Skip to content

World's first open-source enterprise world model.

An ontology can come from outside, and you see what it will do first (#54)

WaylandYang8f38a4d84b7c
diff --git a/Cargo.lock b/Cargo.lock
index ae02de02..20024adf 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2524,6 +2524,59 @@ dependencies = [
"stable_deref_trait",
]
+[[package]]
+name = "oxilangtag"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d3b4eb570abd4a1dcb062c31fd37b832264d9dc7292c3e69acfe926c87b063f"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "oxiri"
+version = "0.2.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "54b4ed3a7192fa19f5f48f99871f2755047fabefd7f222f12a1df1773796a102"
+
+[[package]]
+name = "oxrdf"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0afd5c28e4a399c57ee2bc3accd40c7b671fdc7b6537499f14e95b265af7d7e0"
+dependencies = [
+ "oxilangtag",
+ "oxiri",
+ "rand 0.8.8",
+ "thiserror 2.0.20",
+]
+
+[[package]]
+name = "oxrdfxml"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd5516ae083d09bc57ec65ed5ee97701481725de6ffaa83d968ab42a96157ba1"
+dependencies = [
+ "oxilangtag",
+ "oxiri",
+ "oxrdf",
+ "quick-xml 0.37.5",
+ "thiserror 2.0.20",
+]
+
+[[package]]
+name = "oxttl"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f03fd471bd54c23d76631c0a2677aa4bb308d905f6e491ee35dcb0732b7c5c6c"
+dependencies = [
+ "memchr",
+ "oxilangtag",
+ "oxiri",
+ "oxrdf",
+ "thiserror 2.0.20",
+]
+
[[package]]
name = "p256"
version = "0.13.2"
@@ -2871,6 +2924,15 @@ dependencies = [
"cc",
]
+[[package]]
+name = "quick-xml"
+version = "0.37.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "quick-xml"
version = "0.41.0"
@@ -4687,6 +4749,9 @@ dependencies = [
"csv",
"encoding_rs",
"infer",
+ "oxrdf",
+ "oxrdfxml",
+ "oxttl",
"pdf-extract",
"quick-xml 0.42.0",
"scraper",
diff --git a/Cargo.toml b/Cargo.toml
index 713e6a19..fd01450c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -67,6 +67,12 @@ encoding_rs = "0.8"
quick-xml = "0.42"
zip = { version = "6", default-features = false, features = ["deflate"] }
csv = "1"
+
+# 本体导入:Oxigraph 拆出来的小而专的解析器,只解析不推理——
+# 我们不需要 horned-owl 那套 OWL 推理机,投影只消费 RDF 三元组
+oxttl = "0.2"
+oxrdfxml = "0.2"
+oxrdf = "0.3"
async-stream = "0.3"
futures-util = "0.3"
tokio-stream = "0.1"
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index af80004b..24b2086b 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -274,6 +274,9 @@ pub struct EntityType {
pub builtin: bool,
/// subClassOf 层级(公理推理 P4 点亮,编辑器先维护数据)
pub parent_id: Option<Uuid>,
+ /// OWL 导入的全局身份。手工建的类为 NULL;重导入按它匹配,不按 key——
+ /// 上游改一次 rdfs:label 派生的 key 就变了,按 key 匹配会把同一个类当新类建
+ pub iri: Option<String>,
/// 语义指引:注入抽取 prompt(什么算这个类,举例)
pub description: String,
}
@@ -344,6 +347,20 @@ pub struct ProposedPredicate {
pub example: Option<String>,
}
+/// 一次 OWL 导入的记录。原文按内容寻址存在 blob 里,这行只是账。
+/// `summary` 记下那次投影做了什么,包括**暂未投影**的公理——将来补上消费者
+/// 时据此知道哪些导入值得重跑。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct OntologyImportView {
+ pub id: Uuid,
+ pub filename: String,
+ pub format: String,
+ pub byte_size: i64,
+ pub summary: serde_json::Value,
+ pub imported_at: DateTime<Utc>,
+ pub imported_by_name: Option<String>,
+}
+
/// 一个模型的并发上限。约束来自供应商的速率限制,那是按 (base_url, model) 算的——
/// 本地 Ollama 与托管 API 用同一个数字本来就不对。
#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
@@ -391,6 +408,9 @@ pub struct RelationType {
pub builtin: bool,
/// 语义指引:注入抽取 prompt
pub description: String,
+ /// OWL 导入的全局身份;手工建的为 NULL。重导入按它匹配,不按 key——
+ /// 上游改一次 rdfs:label 派生的 key 就变了,按 key 匹配会把同一个当成新的
+ pub iri: Option<String>,
/// relation(宾语是实体)| attribute(宾语是字面值,走 facts.object_value)
pub kind: String,
/// attribute 专用:属性挂在哪个类下
diff --git a/crates/utopia-ingest/Cargo.toml b/crates/utopia-ingest/Cargo.toml
index 1077557d..4fa956b1 100644
--- a/crates/utopia-ingest/Cargo.toml
+++ b/crates/utopia-ingest/Cargo.toml
@@ -16,4 +16,7 @@ quick-xml.workspace = true
zip.workspace = true
csv.workspace = true
infer.workspace = true
+oxttl.workspace = true
+oxrdfxml.workspace = true
+oxrdf.workspace = true
tracing.workspace = true
diff --git a/crates/utopia-ingest/examples/owl_probe.rs b/crates/utopia-ingest/examples/owl_probe.rs
new file mode 100644
index 00000000..dc0e8ade
--- /dev/null
+++ b/crates/utopia-ingest/examples/owl_probe.rs
@@ -0,0 +1,51 @@
+//! 拿真实公开本体探一遍投影结果。用法:cargo run -p utopia-ingest --example owl_probe -- <文件>
+fn main() -> anyhow::Result<()> {
+ let path = std::env::args().nth(1).expect("需要文件路径");
+ let bytes = std::fs::read(&path)?;
+ let fmt = utopia_ingest::ontology_rdf::RdfFormat::detect(&path, &bytes);
+ let p = utopia_ingest::ontology_rdf::project(&bytes, fmt)?;
+ println!(
+ "格式 {fmt:?} · 三元组 {} · 类 {} · 属性 {}",
+ p.triples,
+ p.classes.len(),
+ p.properties.len()
+ );
+ println!("\n-- 类(前 6)--");
+ for c in p.classes.iter().take(6) {
+ println!(
+ " {} | {} | 父 {} | 描述 {}",
+ c.key,
+ c.label,
+ c.parents.len(),
+ if c.description.is_empty() {
+ "(无)".into()
+ } else {
+ format!("{}…", c.description.chars().take(50).collect::<String>())
+ }
+ );
+ }
+ println!("\n-- 属性(前 6)--");
+ for r in p.properties.iter().take(6) {
+ println!(
+ " {} | {} | {}{}{} | domain {} range {}",
+ r.key,
+ r.label,
+ if r.is_datatype { "字面值" } else { "对象" },
+ if r.functional { " ·functional" } else { "" },
+ if r.inverse_functional {
+ " ·inv_functional"
+ } else {
+ ""
+ },
+ r.domains.len(),
+ r.ranges.len()
+ );
+ }
+ println!("\n-- 暂未投影(前 8)--");
+ let mut u: Vec<_> = p.unprojected.iter().collect();
+ u.sort_by_key(|(_, n)| std::cmp::Reverse(**n));
+ for (k, n) in u.into_iter().take(8) {
+ println!(" {n:4} × {k}");
+ }
+ Ok(())
+}
diff --git a/crates/utopia-ingest/src/lib.rs b/crates/utopia-ingest/src/lib.rs
index b3380448..06dec40c 100644
--- a/crates/utopia-ingest/src/lib.rs
+++ b/crates/utopia-ingest/src/lib.rs
@@ -2,6 +2,7 @@
//! 原则:文本层 Rust 原生解决(快、零依赖);扫描件/复杂版式后续走 docling sidecar。
mod chunker;
+pub mod ontology_rdf;
mod parsers;
pub use chunker::{chunk_text, ChunkPiece};
diff --git a/crates/utopia-ingest/src/ontology_rdf.rs b/crates/utopia-ingest/src/ontology_rdf.rs
new file mode 100644
index 00000000..383b76d3
--- /dev/null
+++ b/crates/utopia-ingest/src/ontology_rdf.rs
@@ -0,0 +1,405 @@
+//! OWL / RDFS 文件的解析与**投影**。
+//!
+//! 分工按 0001 定的三层:本模块只做第二层(投影),第一层(原文保真进 blob)
+//! 由调用方负责。**这里读不懂的东西不是错误,是"暂未投影"**——原文留着,
+//! 将来补上消费者时重跑即可。
+//!
+//! 只解析,不推理:Oxigraph 那两个小解析器给出三元组,我们按名单挑走能用的。
+//! 不引 horned-owl——推理机是 0002 的事,而且它读的是原文不是投影。
+
+use std::collections::{BTreeMap, BTreeSet};
+
+/// 投影出来的一个类。
+#[derive(Debug, Clone, Default, PartialEq)]
+pub struct OwlClass {
+ pub iri: String,
+ /// 从 IRI 派生的短标签(模型读写的令牌);调用方负责去重加后缀
+ pub key: String,
+ pub label: String,
+ /// `rdfs:comment` —— 承重字段,逐字进抽取提示词
+ pub description: String,
+ /// `rdfs:subClassOf` 的全部父类 IRI(多继承在这里是常态)
+ pub parents: Vec<String>,
+}
+
+/// 投影出来的一个属性(对象属性 → 关系,数据属性 → 属性)。
+#[derive(Debug, Clone, Default, PartialEq)]
+pub struct OwlProperty {
+ pub iri: String,
+ pub key: String,
+ pub label: String,
+ pub description: String,
+ /// true = owl:DatatypeProperty(字面值),false = 对象属性
+ pub is_datatype: bool,
+ pub functional: bool,
+ pub inverse_functional: bool,
+ pub domains: Vec<String>,
+ pub ranges: Vec<String>,
+}
+
+/// 一次解析的结果。`unprojected` 是**报告**不是错误——见模块文档。
+#[derive(Debug, Default)]
+pub struct OwlProjection {
+ pub classes: Vec<OwlClass>,
+ pub properties: Vec<OwlProperty>,
+ /// 出现过但我们今天不消费的谓词 → 次数。给预览页"暂未投影"那一栏
+ pub unprojected: BTreeMap<String, usize>,
+ /// 三元组总数,让人对"这个文件有多大"有个数
+ pub triples: usize,
+}
+
+const RDF_TYPE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
+const RDFS: &str = "http://www.w3.org/2000/01/rdf-schema#";
+const OWL: &str = "http://www.w3.org/2002/07/owl#";
+
+/// 支持的输入格式。v1 只做这两个——Protégé 导出的绝大多数是它们,
+/// OWL/XML 与 Manchester 语法刻意砍掉(见 0001 P2 的 "v1 砍掉")。
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum RdfFormat {
+ Turtle,
+ RdfXml,
+}
+
+impl RdfFormat {
+ /// 扩展名是强信号,内容只在**明确矛盾**时推翻它。
+ ///
+ /// 曾经反过来(`.rdf` 探不到 XML 标志就退回 Turtle),结果 FOAF 的官方文件
+ /// 一开头是几十行 `<!--` 注释、`<rdf:` 在嗅探窗口之外,于是被当成 Turtle
+ /// 送进解析器,第一行就报 "Invalid IRI code point"。
+ pub fn detect(filename: &str, bytes: &[u8]) -> Self {
+ let lower = filename.to_ascii_lowercase();
+ // Turtle 的指纹很硬:只有它以 @prefix / @base / PREFIX 开头
+ let looks_turtle = {
+ let head = &bytes[..bytes.len().min(4096)];
+ let s = String::from_utf8_lossy(head);
+ s.lines()
+ .map(str::trim_start)
+ .find(|l| !l.is_empty() && !l.starts_with('#'))
+ .is_some_and(|l| {
+ l.starts_with("@prefix")
+ || l.starts_with("@base")
+ || l.starts_with("PREFIX")
+ || l.starts_with("BASE")
+ })
+ };
+ if lower.ends_with(".ttl") || lower.ends_with(".turtle") || lower.ends_with(".n3") {
+ return Self::Turtle;
+ }
+ if lower.ends_with(".rdf") || lower.ends_with(".owl") || lower.ends_with(".xml") {
+ // .owl 两种编码都常见,所以内容说了算——但只有"确实像 Turtle"才推翻
+ return if looks_turtle {
+ Self::Turtle
+ } else {
+ Self::RdfXml
+ };
+ }
+ if looks_turtle {
+ Self::Turtle
+ } else {
+ Self::RdfXml
+ }
+ }
+}
+
+/// 三元组的中间形态:只留我们看得懂的部分。
+struct Triple {
+ subject: String,
+ predicate: String,
+ /// 宾语是 IRI 时为 Some
+ object_iri: Option<String>,
+ /// 宾语是字面量时为 Some(值, 语言标记)
+ object_lit: Option<(String, Option<String>)>,
+}
+
+fn read_triples(bytes: &[u8], format: RdfFormat) -> anyhow::Result<Vec<Triple>> {
+ use oxrdf::Term;
+ let mut out = Vec::new();
+ let mut push = |t: oxrdf::Triple| {
+ let subject = match &t.subject {
+ oxrdf::NamedOrBlankNode::NamedNode(n) => n.as_str().to_string(),
+ // 空节点是匿名类表达式(owl:Restriction 之类)——投影不碰它们,
+ // 原文里留着等推理机
+ oxrdf::NamedOrBlankNode::BlankNode(_) => return,
+ };
+ let (object_iri, object_lit) = match &t.object {
+ Term::NamedNode(n) => (Some(n.as_str().to_string()), None),
+ Term::Literal(l) => (
+ None,
+ Some((
+ l.value().to_string(),
+ l.language().map(|s| s.to_ascii_lowercase()),
+ )),
+ ),
+ _ => (None, None),
+ };
+ out.push(Triple {
+ subject,
+ predicate: t.predicate.as_str().to_string(),
+ object_iri,
+ object_lit,
+ });
+ };
+ match format {
+ RdfFormat::Turtle => {
+ for r in oxttl::TurtleParser::new().for_reader(bytes) {
+ push(r?);
+ }
+ }
+ RdfFormat::RdfXml => {
+ for r in oxrdfxml::RdfXmlParser::new().for_reader(bytes) {
+ push(r?);
+ }
+ }
+ }
+ Ok(out)
+}
+
+/// 解析并投影。语言标记优先 `@en`/`@zh`,其次无标记,最后随便一个。
+pub fn project(bytes: &[u8], format: RdfFormat) -> anyhow::Result<OwlProjection> {
+ let triples = read_triples(bytes, format)?;
+ let mut proj = OwlProjection {
+ triples: triples.len(),
+ ..Default::default()
+ };
+
+ // 先分类:谁是类、谁是对象属性、谁是数据属性、谁带函数性标记
+ let mut classes: BTreeSet<String> = BTreeSet::new();
+ let mut obj_props: BTreeSet<String> = BTreeSet::new();
+ let mut data_props: BTreeSet<String> = BTreeSet::new();
+ let mut functional: BTreeSet<String> = BTreeSet::new();
+ let mut inverse_functional: BTreeSet<String> = BTreeSet::new();
+ for t in &triples {
+ if t.predicate != RDF_TYPE {
+ continue;
+ }
+ let Some(o) = t.object_iri.as_deref() else {
+ continue;
+ };
+ match o {
+ x if x == format!("{OWL}Class") || x == format!("{RDFS}Class") => {
+ classes.insert(t.subject.clone());
+ }
+ x if x == format!("{OWL}ObjectProperty") => {
+ obj_props.insert(t.subject.clone());
+ }
+ x if x == format!("{OWL}DatatypeProperty") => {
+ data_props.insert(t.subject.clone());
+ }
+ // rdf:Property 没说是对象还是数据 —— 按对象属性处理,
+ // 因为宾语是 IRI 的三元组远多于字面值,猜错的代价也只是分错通道
+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#Property" => {
+ obj_props.insert(t.subject.clone());
+ }
+ x if x == format!("{OWL}FunctionalProperty") => {
+ functional.insert(t.subject.clone());
+ }
+ x if x == format!("{OWL}InverseFunctionalProperty") => {
+ inverse_functional.insert(t.subject.clone());
+ }
+ _ => {}
+ }
+ }
+
+ // 再收集标签、注释、父类、domain/range
+ let mut labels: BTreeMap<String, Vec<(String, Option<String>)>> = BTreeMap::new();
+ let mut comments: BTreeMap<String, Vec<(String, Option<String>)>> = BTreeMap::new();
+ let mut parents: BTreeMap<String, Vec<String>> = BTreeMap::new();
+ let mut domains: BTreeMap<String, Vec<String>> = BTreeMap::new();
+ let mut ranges: BTreeMap<String, Vec<String>> = BTreeMap::new();
+ let known = |p: &str| {
+ p == RDF_TYPE
+ || p == format!("{RDFS}label")
+ || p == format!("{RDFS}comment")
+ || p == format!("{RDFS}subClassOf")
+ || p == format!("{RDFS}subPropertyOf")
+ || p == format!("{RDFS}domain")
+ || p == format!("{RDFS}range")
+ };
+ for t in &triples {
+ let p = t.predicate.as_str();
+ if p == format!("{RDFS}label") {
+ if let Some(l) = &t.object_lit {
+ labels.entry(t.subject.clone()).or_default().push(l.clone());
+ }
+ } else if p == format!("{RDFS}comment") {
+ if let Some(l) = &t.object_lit {
+ comments
+ .entry(t.subject.clone())
+ .or_default()
+ .push(l.clone());
+ }
+ } else if p == format!("{RDFS}subClassOf") {
+ if let Some(o) = &t.object_iri {
+ parents
+ .entry(t.subject.clone())
+ .or_default()
+ .push(o.clone());
+ }
+ } else if p == format!("{RDFS}domain") {
+ if let Some(o) = &t.object_iri {
+ domains
+ .entry(t.subject.clone())
+ .or_default()
+ .push(o.clone());
+ }
+ } else if p == format!("{RDFS}range") {
+ if let Some(o) = &t.object_iri {
+ ranges.entry(t.subject.clone()).or_default().push(o.clone());
+ }
+ } else if !known(p) {
+ // 报告而不是丢弃:预览页要能说清"这个文件里还有什么我们没消费"
+ *proj.unprojected.entry(p.to_string()).or_insert(0) += 1;
+ }
+ }
+
+ for iri in &classes {
+ proj.classes.push(OwlClass {
+ key: key_from_iri(iri),
+ label: pick_lang(labels.get(iri)).unwrap_or_else(|| local_name(iri).to_string()),
+ description: pick_lang(comments.get(iri)).unwrap_or_default(),
+ parents: parents.get(iri).cloned().unwrap_or_default(),
+ iri: iri.clone(),
+ });
+ }
+ for iri in obj_props.iter().chain(data_props.iter()) {
+ proj.properties.push(OwlProperty {
+ key: key_from_iri(iri),
+ label: pick_lang(labels.get(iri))
+ .unwrap_or_else(|| local_name(iri).replace('_', " ").to_string()),
+ description: pick_lang(comments.get(iri)).unwrap_or_default(),
+ is_datatype: data_props.contains(iri),
+ functional: functional.contains(iri),
+ inverse_functional: inverse_functional.contains(iri),
+ domains: domains.get(iri).cloned().unwrap_or_default(),
+ ranges: ranges.get(iri).cloned().unwrap_or_default(),
+ iri: iri.clone(),
+ });
+ }
+ Ok(proj)
+}
+
+/// 多语言标签里挑一个:优先 en / zh,其次无语言标记,最后第一个。
+fn pick_lang(vals: Option<&Vec<(String, Option<String>)>>) -> Option<String> {
+ let vals = vals?;
+ for want in ["en", "zh"] {
+ if let Some((v, _)) = vals
+ .iter()
+ .find(|(_, l)| l.as_deref().is_some_and(|l| l.starts_with(want)))
+ {
+ return Some(v.clone());
+ }
+ }
+ vals.iter()
+ .find(|(_, l)| l.is_none())
+ .or_else(|| vals.first())
+ .map(|(v, _)| v.clone())
+}
+
+/// IRI 的局部名:最后一个 `#` 或 `/` 之后的部分。
+pub fn local_name(iri: &str) -> &str {
+ iri.rsplit(['#', '/']).next().unwrap_or(iri)
+}
+
+/// 从 IRI 派生 key。**IRI 是身份,key 是给模型读的标签**(见 0001 P2):
+/// 只允许 `[a-z0-9_]`、最长 40,所以 IRI 本身进不去。
+/// 驼峰拆成下划线:`hasEmployee` → `has_employee`。
+pub fn key_from_iri(iri: &str) -> String {
+ let local = local_name(iri);
+ let mut out = String::with_capacity(local.len() + 4);
+ let mut prev_lower = false;
+ for c in local.chars() {
+ if c.is_ascii_uppercase() {
+ if prev_lower && !out.is_empty() {
+ out.push('_');
+ }
+ out.push(c.to_ascii_lowercase());
+ prev_lower = false;
+ } else if c.is_ascii_alphanumeric() {
+ out.push(c);
+ prev_lower = true;
+ } else if !out.ends_with('_') && !out.is_empty() {
+ out.push('_');
+ prev_lower = false;
+ }
+ }
+ while out.ends_with('_') {
+ out.pop();
+ }
+ out.chars().take(40).collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const TTL: &str = r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+ @prefix ex: <http://acme.example/hr#> .
+
+ ex:Employee a owl:Class ;
+ rdfs:label "Employee"@en ;
+ rdfs:label "员工"@zh ;
+ rdfs:comment "A person on the payroll."@en ;
+ rdfs:subClassOf ex:Person .
+ ex:Person a owl:Class ; rdfs:label "Person" .
+ ex:hasManager a owl:ObjectProperty, owl:FunctionalProperty ;
+ rdfs:label "has manager" ;
+ rdfs:domain ex:Employee ;
+ rdfs:range ex:Person .
+ ex:salary a owl:DatatypeProperty ; rdfs:domain ex:Employee .
+ ex:Employee owl:disjointWith ex:Contractor .
+ "#;
+
+ #[test]
+ fn projects_classes_properties_and_reports_the_rest() {
+ let p = project(TTL.as_bytes(), RdfFormat::Turtle).unwrap();
+ let emp = p.classes.iter().find(|c| c.key == "employee").unwrap();
+ // 多语言标签取 en 优先
+ assert_eq!(emp.label, "Employee");
+ assert_eq!(emp.description, "A person on the payroll.");
+ assert_eq!(emp.parents, vec!["http://acme.example/hr#Person"]);
+
+ let mgr = p
+ .properties
+ .iter()
+ .find(|x| x.key == "has_manager")
+ .unwrap();
+ assert!(mgr.functional && !mgr.is_datatype);
+ assert_eq!(mgr.ranges, vec!["http://acme.example/hr#Person"]);
+
+ let sal = p.properties.iter().find(|x| x.key == "salary").unwrap();
+ assert!(sal.is_datatype);
+
+ // 消费不了的公理进报告,不是丢弃也不是报错
+ assert!(p
+ .unprojected
+ .contains_key("http://www.w3.org/2002/07/owl#disjointWith"));
+ }
+
+ #[test]
+ fn detects_rdfxml_that_opens_with_comments() {
+ // FOAF 的官方文件就长这样:几十行 <!-- --> 之后才见 <rdf:RDF>。
+ // 早先版本嗅不到 XML 标志就退回 Turtle,结果第一行就解析失败
+ let head = b"<!-- This is the FOAF vocabulary, expressed using RDFS and OWL. -->\n\
+ <!-- padding padding padding padding padding padding padding -->\n";
+ assert_eq!(RdfFormat::detect("index.rdf", head), RdfFormat::RdfXml);
+ // 反过来:.owl 里放 Turtle 也常见,内容说了算
+ assert_eq!(
+ RdfFormat::detect("x.owl", b"@prefix owl: <http://x#> .\n"),
+ RdfFormat::Turtle
+ );
+ // 注释开头的 Turtle 同样认得出(# 行先跳过)
+ assert_eq!(
+ RdfFormat::detect("x", b"# a note\n\n@base <http://x> .\n"),
+ RdfFormat::Turtle
+ );
+ }
+
+ #[test]
+ fn key_derives_from_the_iri_local_name() {
+ assert_eq!(key_from_iri("http://x/hr#hasEmployee"), "has_employee");
+ assert_eq!(key_from_iri("http://x/ns/Person"), "person");
+ assert_eq!(key_from_iri("http://x#HTTP_Server"), "http_server");
+ }
+}
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index ebdb0059..875fc8af 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -146,6 +146,19 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
post(ontology_routes::dismiss_miss),
)
.route("/kbs/{id}/ontology/suggest", post(ontology_routes::suggest))
+ // OWL 导入:预览与落库分开两个端点,绝不让上传即改本体。
+ // 两者跑同一个 plan——分开的代码路径会分叉,而分叉意味着确认之后
+ // 发生的事与刚看过的不一样
+ .route(
+ "/kbs/{id}/ontology/imports",
+ get(ontology_routes::list_imports)
+ .post(ontology_routes::apply_import)
+ .layer(DefaultBodyLimit::max(16 * 1024 * 1024)),
+ )
+ .route(
+ "/kbs/{id}/ontology/imports/preview",
+ post(ontology_routes::preview_import).layer(DefaultBodyLimit::max(16 * 1024 * 1024)),
+ )
.route(
"/kbs/{id}/ontology/proposed-predicates",
get(ontology_routes::proposed_predicates),
diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rs
index 0b273796..98b99966 100644
--- a/crates/utopia-server/src/api/ontology_routes.rs
+++ b/crates/utopia-server/src/api/ontology_routes.rs
@@ -615,3 +615,74 @@ pub async fn last_auto_extension(
"batches": batches,
}})))
}
+
+/// OWL 导入:先看会发生什么,确认了才落库。
+///
+/// **绝不让上传一个文件就不可逆地改掉本体**——预览与落库走同一个 plan,
+/// 两条独立路径迟早分叉,而分叉的后果是确认之后发生的事与刚看过的不一样。
+pub async fn preview_import(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ multipart: axum::extract::Multipart,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let (filename, bytes) = read_upload(multipart).await?;
+ let (plan, _, _) = crate::owl_import::plan(&state, kb_id, &filename, &bytes).await?;
+ Ok(Json(json!({ "filename": filename, "plan": plan })))
+}
+
+pub async fn apply_import(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ multipart: axum::extract::Multipart,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let (filename, bytes) = read_upload(multipart).await?;
+ let (import_id, plan) =
+ crate::owl_import::apply(&state, kb_id, user.id, &filename, &bytes).await?;
+ Ok(Json(json!({ "import_id": import_id, "plan": plan })))
+}
+
+pub async fn list_imports(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Viewer).await?;
+ let imports = utopia_store::ontology::list_imports(&state.pool, kb_id).await?;
+ Ok(Json(json!({ "imports": imports })))
+}
+
+/// 取 multipart 里的第一个文件。上限 8 MB——FOAF 44 KB、DCTerms 48 KB,
+/// FIBO 那种大部头分模块也在几百 KB 量级;再大多半是传错了东西。
+const MAX_ONTOLOGY_BYTES: usize = 8 * 1024 * 1024;
+
+async fn read_upload(
+ mut multipart: axum::extract::Multipart,
+) -> Result<(String, Vec<u8>), AppError> {
+ while let Some(field) = multipart
+ .next_field()
+ .await
+ .map_err(|e| AppError::Validation(format!("Could not read the upload: {e}")))?
+ {
+ let Some(filename) = field.file_name().map(String::from) else {
+ continue;
+ };
+ let bytes = field
+ .bytes()
+ .await
+ .map_err(|e| AppError::Validation(format!("Could not read the uploaded file: {e}")))?;
+ if bytes.len() > MAX_ONTOLOGY_BYTES {
+ return Err(AppError::Validation(
+ "Ontology file is too large (max 8 MB)".into(),
+ ));
+ }
+ if bytes.is_empty() {
+ return Err(AppError::Validation("Ontology file is empty".into()));
+ }
+ return Ok((filename, bytes.to_vec()));
+ }
+ Err(AppError::Validation("No file in the upload".into()))
+}
diff --git a/crates/utopia-server/src/main.rs b/crates/utopia-server/src/main.rs
index 41324329..e017e0a0 100644
--- a/crates/utopia-server/src/main.rs
+++ b/crates/utopia-server/src/main.rs
@@ -10,6 +10,7 @@ mod extraction;
mod ingest_sources;
mod llm_util;
mod mappings;
+mod owl_import;
mod pipeline;
mod query_engine;
mod retrieval;
diff --git a/crates/utopia-server/src/owl_import.rs b/crates/utopia-server/src/owl_import.rs
new file mode 100644
index 00000000..c87d1825
--- /dev/null
+++ b/crates/utopia-server/src/owl_import.rs
@@ -0,0 +1,273 @@
+//! OWL 导入:原文保真 → 投影 → 预览 → 落库。
+//!
+//! **预览与落库走同一个计划**。两条独立的代码路径迟早分叉,而分叉的后果是
+//! 用户点确认之后发生的事与他刚看过的不一样——那比没有预览更糟。
+//!
+//! 匹配按 **IRI** 不按 key:上游改一次 `rdfs:label`,派生出的 key 就变了,
+//! 按 key 匹配会把同一个类当新类建出来,实体全留在孤儿上(见 0001 P2)。
+
+use std::collections::HashMap;
+
+use utopia_core::AppResult;
+use utopia_ingest::ontology_rdf::{self, OwlProjection, RdfFormat};
+use uuid::Uuid;
+
+use crate::state::AppState;
+
+/// 一个类/属性在这次导入里的去向。
+#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Disposition {
+ /// 本体里没有这个 IRI → 新建
+ Create,
+ /// IRI 已在 → 更新标签与描述(key 不动:它可能已被引用)
+ Update,
+ /// key 被另一个 IRI 占着 → 跳过并报告,不悄悄改名也不覆盖
+ KeyTaken,
+}
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct PlannedItem {
+ pub iri: String,
+ pub key: String,
+ pub label: String,
+ pub has_description: bool,
+ pub disposition: Disposition,
+ /// 关系专用:导入声明它是函数性的 —— 预览必须把这些单独列出来
+ #[serde(skip_serializing_if = "std::ops::Not::not")]
+ pub functional: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub conflict_with: Option<String>,
+}
+
+/// 一次导入的完整计划。预览返回它,落库也执行它。
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct ImportPlan {
+ pub format: String,
+ pub triples: usize,
+ pub classes: Vec<PlannedItem>,
+ pub relations: Vec<PlannedItem>,
+ pub attributes: Vec<PlannedItem>,
+ /// 出现过但今天不消费的公理 → 次数。**不是"已跳过",是"暂未投影"**
+ pub unprojected: Vec<(String, usize)>,
+ /// 没有 `rdfs:comment` 的类数。它们在抽取里质量会明显偏低——
+ /// description 逐字进提示词,是模型判断"什么算这个类"的唯一依据
+ pub classes_without_description: usize,
+ /// 声明为函数性的关系数。**这是 part_of 那个坑的企业版**:本体声明唯一,
+ /// 数据不遵守,导完就是一队假冲突
+ pub functional_relations: usize,
+}
+
+/// 解析文件并对着现有本体算出计划。不写任何东西。
+pub async fn plan(
+ state: &AppState,
+ kb_id: Uuid,
+ filename: &str,
+ bytes: &[u8],
+) -> AppResult<(ImportPlan, OwlProjection, RdfFormat)> {
+ let format = RdfFormat::detect(filename, bytes);
+ let proj = ontology_rdf::project(bytes, format).map_err(|e| {
+ utopia_core::AppError::Validation(format!("Could not parse this ontology file: {e}"))
+ })?;
+
+ // 现有本体:按 IRI 与按 key 各建一份索引,两种冲突分别判
+ let etypes = utopia_store::graph::entity_types(&state.pool, kb_id).await?;
+ let rtypes = utopia_store::graph::relation_types(&state.pool, kb_id).await?;
+ let e_by_iri: HashMap<&str, &_> = etypes
+ .iter()
+ .filter_map(|t| t.iri.as_deref().map(|i| (i, t)))
+ .collect();
+ let e_by_key: HashMap<&str, &_> = etypes.iter().map(|t| (t.key.as_str(), t)).collect();
+ let r_by_iri: HashMap<&str, &_> = rtypes
+ .iter()
+ .filter_map(|t| t.iri.as_deref().map(|i| (i, t)))
+ .collect();
+ let r_by_key: HashMap<&str, &_> = rtypes.iter().map(|t| (t.key.as_str(), t)).collect();
+
+ let mut classes = Vec::new();
+ for c in &proj.classes {
+ let (disposition, conflict_with) = if e_by_iri.contains_key(c.iri.as_str()) {
+ (Disposition::Update, None)
+ } else if let Some(existing) = e_by_key.get(c.key.as_str()) {
+ // key 撞了但 IRI 不同:这是两个不同的东西争一个短标签。
+ // 不自动加后缀——那会让重导入认不出自己上次建的是哪个
+ // 占位者可能是手工建的(没有 IRI)——那就返回 None,
+ // 由界面决定怎么措辞。服务端不产出展示文案
+ (Disposition::KeyTaken, existing.iri.clone())
+ } else {
+ (Disposition::Create, None)
+ };
+ classes.push(PlannedItem {
+ iri: c.iri.clone(),
+ key: c.key.clone(),
+ label: c.label.clone(),
+ has_description: !c.description.trim().is_empty(),
+ disposition,
+ functional: false,
+ conflict_with,
+ });
+ }
+
+ let mut relations = Vec::new();
+ let mut attributes = Vec::new();
+ for p in &proj.properties {
+ let (disposition, conflict_with) = if r_by_iri.contains_key(p.iri.as_str()) {
+ (Disposition::Update, None)
+ } else if let Some(existing) = r_by_key.get(p.key.as_str()) {
+ (Disposition::KeyTaken, existing.iri.clone())
+ } else {
+ (Disposition::Create, None)
+ };
+ let item = PlannedItem {
+ iri: p.iri.clone(),
+ key: p.key.clone(),
+ label: p.label.clone(),
+ has_description: !p.description.trim().is_empty(),
+ disposition,
+ functional: p.functional,
+ conflict_with,
+ };
+ if p.is_datatype {
+ attributes.push(item);
+ } else {
+ relations.push(item);
+ }
+ }
+
+ let mut unprojected: Vec<(String, usize)> = proj
+ .unprojected
+ .iter()
+ .map(|(k, v)| (k.clone(), *v))
+ .collect();
+ unprojected.sort_by_key(|(_, n)| std::cmp::Reverse(*n));
+
+ let plan = ImportPlan {
+ format: format!("{format:?}").to_lowercase(),
+ triples: proj.triples,
+ classes_without_description: classes.iter().filter(|c| !c.has_description).count(),
+ functional_relations: relations.iter().filter(|r| r.functional).count(),
+ classes,
+ relations,
+ attributes,
+ unprojected,
+ };
+ Ok((plan, proj, format))
+}
+
+/// 执行计划。**属性暂不落库**:它们需要 domain 才能存(store 层强制),
+/// 而 domain 要等类先建好并解析 IRI → id,那是下一层的事。
+pub async fn apply(
+ state: &AppState,
+ kb_id: Uuid,
+ actor: Uuid,
+ filename: &str,
+ bytes: &[u8],
+) -> AppResult<(Uuid, ImportPlan)> {
+ let (plan, proj, format) = plan(state, kb_id, filename, bytes).await?;
+
+ // 第一层:原文按内容寻址进 blob。**先存原文再改本体**——投影失败可以重来,
+ // 原文丢了就永远回不去
+ let sha = sha256_hex(bytes);
+ state
+ .blob
+ .put(&sha, bytes)
+ .await
+ .map_err(utopia_core::AppError::Other)?;
+
+ let by_iri: HashMap<&str, &_> = proj.classes.iter().map(|c| (c.iri.as_str(), c)).collect();
+ let mut created_classes = 0usize;
+ let mut updated_classes = 0usize;
+ // IRI → 本体里的 id,父类解析要用
+ let mut id_of: HashMap<String, Uuid> = HashMap::new();
+
+ for item in &plan.classes {
+ let Some(c) = by_iri.get(item.iri.as_str()) else {
+ continue;
+ };
+ match item.disposition {
+ Disposition::Create => {
+ let id = utopia_store::ontology::create_entity_type_with_iri(
+ &state.pool,
+ kb_id,
+ &c.key,
+ &c.label,
+ &c.description,
+ &c.iri,
+ )
+ .await?;
+ id_of.insert(c.iri.clone(), id);
+ created_classes += 1;
+ }
+ Disposition::Update => {
+ if let Some(id) = utopia_store::ontology::update_type_from_import(
+ &state.pool,
+ kb_id,
+ &c.iri,
+ &c.label,
+ &c.description,
+ )
+ .await?
+ {
+ id_of.insert(c.iri.clone(), id);
+ updated_classes += 1;
+ }
+ }
+ // key 被占:报告过了,不动
+ Disposition::KeyTaken => {}
+ }
+ }
+
+ // 父类第二遍解析:第一遍时父类可能还没建出来
+ for c in &proj.classes {
+ let (Some(&child), Some(parent_iri)) = (id_of.get(&c.iri), c.parents.first()) else {
+ continue;
+ };
+ // 多继承暂只投影主父(第一个)——`entity_type_parents` 关联表是下一层。
+ // 少投影一个父分支不会静默出错,只是那分支的属性 domain 判定暂时够不到
+ if let Some(&parent) = id_of.get(parent_iri) {
+ let _ = utopia_store::ontology::set_parent(&state.pool, kb_id, child, parent).await;
+ }
+ }
+
+ let summary = serde_json::json!({
+ "classes_created": created_classes,
+ "classes_updated": updated_classes,
+ "classes_key_taken": plan.classes.iter().filter(|c| c.disposition == Disposition::KeyTaken).count(),
+ "relations_seen": plan.relations.len(),
+ "attributes_seen": plan.attributes.len(),
+ "classes_without_description": plan.classes_without_description,
+ "functional_relations": plan.functional_relations,
+ "unprojected": plan.unprojected.iter().take(30).collect::<Vec<_>>(),
+ "triples": plan.triples,
+ });
+ let import_id = utopia_store::ontology::record_import(
+ &state.pool,
+ kb_id,
+ &sha,
+ filename,
+ &format!("{format:?}").to_lowercase(),
+ bytes.len() as i64,
+ &summary,
+ actor,
+ )
+ .await?;
+
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ actor,
+ "ontology.imported",
+ "kb",
+ Some(kb_id),
+ summary,
+ )
+ .await;
+ Ok((import_id, plan))
+}
+
+fn sha256_hex(bytes: &[u8]) -> String {
+ use sha2::{Digest, Sha256};
+ let mut h = Sha256::new();
+ h.update(bytes);
+ h.finalize().iter().map(|b| format!("{b:02x}")).collect()
+}
diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rs
index 48ce4d74..dc29c94f 100644
--- a/crates/utopia-store/src/ontology.rs
+++ b/crates/utopia-store/src/ontology.rs
@@ -1,7 +1,9 @@
//! 本体编辑器仓储:类型/关系 CRUD(带使用量与删除保护)+ 未匹配统计。
use sqlx::PgPool;
-use utopia_core::models::{EntityInstance, EntityTypeView, OntologyMiss, RelationTypeView};
+use utopia_core::models::{
+ EntityInstance, EntityTypeView, OntologyImportView, OntologyMiss, RelationTypeView,
+};
use utopia_core::{AppError, AppResult};
use uuid::Uuid;
@@ -401,3 +403,123 @@ pub async fn clear_miss(pool: &PgPool, kb_id: Uuid, kind: &str, key: &str) -> Ap
.await?;
Ok(())
}
+
+/* ---- OWL 导入 ---- */
+
+/// 建一个带 IRI 的类。IRI 是全局身份,重导入据它匹配(见 0001 P2)。
+pub async fn create_entity_type_with_iri(
+ pool: &PgPool,
+ kb_id: Uuid,
+ key: &str,
+ label: &str,
+ description: &str,
+ iri: &str,
+) -> AppResult<Uuid> {
+ validate_key(key)?;
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO entity_types (id, kb_id, key, label, color, shape, description, iri)
+ VALUES ($1, $2, $3, $4, '#8ea5bd', 'circle', $5, $6)",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .bind(key)
+ .bind(label)
+ .bind(description)
+ .bind(iri)
+ .execute(pool)
+ .await
+ .map_err(|e| match &e {
+ sqlx::Error::Database(db) if db.is_unique_violation() => {
+ AppError::Conflict(format!("Type key '{key}' already exists"))
+ }
+ _ => AppError::Db(e),
+ })?;
+ Ok(id)
+}
+
+/// 重导入时按 IRI 更新标签与描述。**key 不动**——它可能已经被抽取出的实体
+/// 和提示词引用,改它等于把已有数据的引用打断;上游改 label 是常态,
+/// 而 IRI 才是身份。
+pub async fn update_type_from_import(
+ pool: &PgPool,
+ kb_id: Uuid,
+ iri: &str,
+ label: &str,
+ description: &str,
+) -> AppResult<Option<Uuid>> {
+ let row: Option<(Uuid,)> = sqlx::query_as(
+ "UPDATE entity_types
+ SET label = $3,
+ -- 空描述不覆盖已有的:上游可能没写 rdfs:comment,而本地可能
+ -- 已经被人按自己的语料调过,那份调整比空值有价值
+ description = CASE WHEN $4 = '' THEN description ELSE $4 END
+ WHERE kb_id = $1 AND iri = $2 RETURNING id",
+ )
+ .bind(kb_id)
+ .bind(iri)
+ .bind(label)
+ .bind(description)
+ .fetch_optional(pool)
+ .await?;
+ Ok(row.map(|(id,)| id))
+}
+
+/// 设父类。自环与已是该父类的情形静默跳过。
+pub async fn set_parent(pool: &PgPool, kb_id: Uuid, child: Uuid, parent: Uuid) -> AppResult<()> {
+ if child == parent {
+ return Ok(());
+ }
+ sqlx::query("UPDATE entity_types SET parent_id = $3 WHERE kb_id = $1 AND id = $2")
+ .bind(kb_id)
+ .bind(child)
+ .bind(parent)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 记一次导入。原文已按内容寻址存进 blob,这里只记账。
+#[allow(clippy::too_many_arguments)]
+pub async fn record_import(
+ pool: &PgPool,
+ kb_id: Uuid,
+ sha256: &str,
+ filename: &str,
+ format: &str,
+ byte_size: i64,
+ summary: &serde_json::Value,
+ actor: Uuid,
+) -> AppResult<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO ontology_imports
+ (id, kb_id, sha256, filename, format, byte_size, summary, imported_by)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .bind(sha256)
+ .bind(filename)
+ .bind(format)
+ .bind(byte_size)
+ .bind(summary)
+ .bind(actor)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+/// 一个库的导入历史(带导入人显示名;删号后为 NULL)。
+pub async fn list_imports(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<OntologyImportView>> {
+ Ok(sqlx::query_as(
+ "SELECT i.id, i.filename, i.format, i.byte_size, i.summary, i.imported_at,
+ u.display_name AS imported_by_name
+ FROM ontology_imports i
+ LEFT JOIN users u ON u.id = i.imported_by
+ WHERE i.kb_id = $1 ORDER BY i.imported_at DESC LIMIT 50",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?)
+}
diff --git a/docs/decisions/0001-ontology-import-and-governance.md b/docs/decisions/0001-ontology-import-and-governance.md
index 24dd190d..1f63bc28 100644
--- a/docs/decisions/0001-ontology-import-and-governance.md
+++ b/docs/decisions/0001-ontology-import-and-governance.md
@@ -177,6 +177,39 @@ v2: http://acme.com/hr#Employee rdfs:label "Staff Member" → key = staff_membe
**依赖**:`oxttl` + `oxrdfxml`(Oxigraph 那套小而专的 crate)。不引 `horned-owl`,我们不需要推理。工作区目前无任何 RDF 依赖。
+> **修订记录 · P2a + P2b 已落地**(`feat/owl-import`)
+>
+> 落地的是三层里的前两层与整条预览流程:解析(`utopia-ingest/src/ontology_rdf.rs`)、
+> 计划与执行(`utopia-server/src/owl_import.rs`,预览与落库**共用同一个 `plan()`**)、
+> 界面(本体页左栏底部 Import 入口 → 选文件 → 计划 → 确认)。
+> `ontology_imports` 表与 `entity_types.iri` / `relation_types.iri` 见迁移 0031。
+>
+> **对着真实词汇表验证,不是自己写的样例**。FOAF(RDF/XML,635 三元组):
+> 15 类 + 89 属性,`functional` / `inverse_functional` / domain / range 全部读出;
+> DCTerms(Turtle,700 三元组):22 类 + 55 属性。**自己手写的样例文件全部通过,
+> 而真实的 FOAF 在第一行就死了**——格式判定写反了,而且文件开头的 `<!--` 注释把
+> `<rdf:` 推出了嗅探窗口。现在扩展名是强信号,内容只在明显是 Turtle 时才推翻它。
+>
+> **预览多报一件本文没写的事:key 撞车**。FOAF 的 `Person` 与我们内置的 `person`
+> 同名不同身份。当时想的是自动加后缀,但那会让**下一次重导入认不出自己上次建的是
+> 哪个**——这正是本文论证 IRI 必要性时用的那个例子,只是换了个方向出现。所以:
+> 报告,不解决。想要导入的那份,先给现有的改名。
+>
+> **暂未落地,按依赖顺序**:
+> - **属性(DatatypeProperty)解析了但不建**——store 层要求属性挂在一个类的 domain 上,
+> 而 domain 要等类先建好并解析 IRI → id。FOAF 那 54 个属性在预览里明说了"还没建",
+> 不是静默丢掉。
+> - **domain / range 关联表**与随之而来的**提示词类型签名**——本文说它是最高性价比的
+> 十行,仍然是,但它要先有表。
+> - **多继承 DAG**:现在只投影第一个父类。少一个父分支不会静默出错(那分支的属性
+> domain 判定暂时够不到),但 `type_matches_domain` 的静默失配问题还在,随关联表一起补。
+>
+> **一个自己犯的错值得记**:`OntologyImportView` 的字段叫 `imported_at`,前端类型
+> 写成了 `created_at`。TypeScript 一声不吭——类型是我声明的,它只保证代码内部自洽,
+> 不保证与服务端一致。界面上显示成 `Invalid Date` 才发现。同一次还有服务端往
+> `conflict_with` 里塞了中文兜底文案 `(手工建的)`,直接漏进英文界面。
+> 两件事同一个教训:**服务端不产出展示文案**,措辞归界面;跨语言的边界要用真数据看一眼。
+
---
### P3 · 类型消解 —— 让大本体可用
diff --git a/migrations/0032_ontology_imports.sql b/migrations/0032_ontology_imports.sql
new file mode 100644
index 00000000..cdaa6856
--- /dev/null
+++ b/migrations/0032_ontology_imports.sql
@@ -0,0 +1,33 @@
+-- 本体导入的第一层:原文保真。
+--
+-- 投影只覆盖今天能消费的那部分(类、标签、rdfs:comment、subClassOf、
+-- 对象/数据属性、functional、domain/range)。**读不懂的不是错误,是"暂未投影"**——
+-- 原文按内容寻址存进 blob,将来推理机上线或我们补上新消费者时重跑,
+-- 用户什么都不用做。这样"我们表达不了"从能力缺口降级成"投影暂未覆盖"。
+CREATE TABLE ontology_imports (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ -- blob 的内容指纹;同一份文件重复导入不重复占空间
+ sha256 TEXT NOT NULL,
+ filename TEXT NOT NULL,
+ -- turtle | rdfxml
+ format TEXT NOT NULL,
+ byte_size BIGINT NOT NULL,
+ -- 投影版本:将来投影逻辑变了,据此知道哪些导入该重跑
+ projection_version INT NOT NULL DEFAULT 1,
+ -- 这次投影做了什么(新建/更新/暂未投影的计数与明细),预览与事后审计共用
+ summary JSONB NOT NULL DEFAULT '{}'::jsonb,
+ -- 谁导的。删号后留 NULL,与审计台账同规矩
+ imported_by UUID REFERENCES users(id) ON DELETE SET NULL,
+ imported_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE INDEX ontology_imports_kb_idx ON ontology_imports (kb_id, imported_at DESC);
+
+-- IRI 是全局身份,key 是给模型读的短标签(见 0001 P2 的"IRI 与 key 的分工")。
+-- 重导入按 IRI 匹配已有行——按 key 匹配会因为上游改了 rdfs:label 导致 key 变化
+-- 而把同一个类当成新类建出来,实体全留在孤儿上。
+ALTER TABLE entity_types ADD COLUMN iri TEXT;
+ALTER TABLE relation_types ADD COLUMN iri TEXT;
+CREATE UNIQUE INDEX entity_types_iri_idx ON entity_types (kb_id, iri) WHERE iri IS NOT NULL;
+CREATE UNIQUE INDEX relation_types_iri_idx ON relation_types (kb_id, iri) WHERE iri IS NOT NULL;
diff --git a/web/src/api.ts b/web/src/api.ts
index 97b63d17..d237c88b 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -9,7 +9,10 @@ export class ApiError extends Error {
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(path, {
credentials: "include",
- headers: init?.body instanceof FormData ? {} : { "Content-Type": "application/json" },
+ headers:
+ init?.body instanceof FormData
+ ? {}
+ : { "Content-Type": "application/json" },
...init,
});
if (!res.ok) {
@@ -397,7 +400,12 @@ export interface OntologyMiss {
"什么算这个类"的唯一依据;reason 只是给人看的"为什么该加"。喂错了这个类会成为
下一个倾倒场——实测 technology 就是这么来的。 */
export interface OntologyProposals {
- entity_types: { key: string; label: string; description?: string; reason?: string }[];
+ entity_types: {
+ key: string;
+ label: string;
+ description?: string;
+ reason?: string;
+ }[];
relation_types: {
key: string;
label: string;
@@ -417,6 +425,40 @@ export interface ProposedPredicate {
example: string | null;
}
+/** 一个类/属性在这次导入里的去向。key_taken = key 被另一个 IRI 占着,报告但不动 */
+export interface PlannedItem {
+ iri: string;
+ key: string;
+ label: string;
+ has_description: boolean;
+ disposition: "create" | "update" | "key_taken";
+ functional?: boolean;
+ conflict_with?: string | null;
+}
+
+/** 预览与落库返回同一个计划:点确认之后发生的事就是刚看过的事 */
+export interface ImportPlan {
+ format: string;
+ triples: number;
+ classes: PlannedItem[];
+ relations: PlannedItem[];
+ attributes: PlannedItem[];
+ /** 出现过但今天不消费的公理 → 次数。不是已跳过,是暂未投影 */
+ unprojected: [string, number][];
+ classes_without_description: number;
+ functional_relations: number;
+}
+
+export interface OntologyImportView {
+ id: string;
+ filename: string;
+ format: string;
+ byte_size: number;
+ summary: Record<string, unknown>;
+ imported_by_name: string | null;
+ imported_at: string;
+}
+
export interface Source {
n: number;
/** 缺省 = 文档 chunk 引用;charter = 内置手册(跳 /docs/{slug}#{anchor}) */
@@ -457,7 +499,10 @@ export interface ConversationMessage {
}
export const api = {
- health: () => request<{ status: string; name: string; version: string }>("/api/v1/health"),
+ health: () =>
+ request<{ status: string; name: string; version: string }>(
+ "/api/v1/health",
+ ),
me: () => request<User>("/api/v1/auth/me"),
login: (email: string, password: string) =>
request<{ user: User }>("/api/v1/auth/login", {
@@ -469,7 +514,8 @@ export const api = {
method: "POST",
body: JSON.stringify({ email, password, display_name: displayName }),
}),
- logout: () => request<{ ok: boolean }>("/api/v1/auth/logout", { method: "POST" }),
+ logout: () =>
+ request<{ ok: boolean }>("/api/v1/auth/logout", { method: "POST" }),
updateMe: (displayName: string) =>
request<User>("/api/v1/auth/me", {
method: "PATCH",
@@ -478,11 +524,15 @@ export const api = {
changePassword: (currentPassword: string, newPassword: string) =>
request<{ ok: boolean }>("/api/v1/auth/password", {
method: "POST",
- body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
+ body: JSON.stringify({
+ current_password: currentPassword,
+ new_password: newPassword,
+ }),
}),
workspaces: () => request<Workspace[]>("/api/v1/workspaces"),
- kbs: (workspaceId: string) => request<Kb[]>(`/api/v1/workspaces/${workspaceId}/kbs`),
+ kbs: (workspaceId: string) =>
+ request<Kb[]>(`/api/v1/workspaces/${workspaceId}/kbs`),
kbAudit: (kbId: string) =>
request<{ events: AuditEvent[] }>(`/api/v1/kbs/${kbId}/audit`),
myKbs: (workspaceId: string) =>
@@ -498,17 +548,23 @@ export const api = {
kbDetail: (kbId: string) => request<Kb>(`/api/v1/kbs/${kbId}`),
updateKb: (kbId: string, body: Record<string, unknown>) =>
- request<Kb>(`/api/v1/kbs/${kbId}`, { method: "PATCH", body: JSON.stringify(body) }),
+ request<Kb>(`/api/v1/kbs/${kbId}`, {
+ method: "PATCH",
+ body: JSON.stringify(body),
+ }),
deleteKb: (kbId: string) =>
request<{ ok: boolean }>(`/api/v1/kbs/${kbId}`, { method: "DELETE" }),
- kbMembers: (kbId: string) => request<{ members: KbMember[] }>(`/api/v1/kbs/${kbId}/members`),
+ kbMembers: (kbId: string) =>
+ request<{ members: KbMember[] }>(`/api/v1/kbs/${kbId}/members`),
setKbMember: (kbId: string, userId: string, role: string) =>
request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/members/${userId}`, {
method: "PUT",
body: JSON.stringify({ role }),
}),
removeKbMember: (kbId: string, userId: string) =>
- request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/members/${userId}`, { method: "DELETE" }),
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/members/${userId}`, {
+ method: "DELETE",
+ }),
adminDeployment: () =>
request<{
@@ -516,27 +572,42 @@ export const api = {
/** 外层兜底,防任务无限堆积;真正的节流是按模型的限额 */
worker_concurrency: number;
default_model_concurrency: number;
- model_limits: { base_url: string; model: string; max_concurrent: number }[];
+ model_limits: {
+ base_url: string;
+ model: string;
+ max_concurrent: number;
+ }[];
models_in_use: { base_url: string; model: string; kind: string }[];
}>("/api/v1/admin/deployment"),
saveAdminDeployment: (
openRegistration: boolean,
workerConcurrency?: number,
defaultModelConcurrency?: number,
- modelLimit?: { base_url: string; model: string; max_concurrent: number | null },
+ modelLimit?: {
+ base_url: string;
+ model: string;
+ max_concurrent: number | null;
+ },
) =>
request<{ ok: boolean }>("/api/v1/admin/deployment", {
method: "PUT",
body: JSON.stringify({
open_registration: openRegistration,
- ...(workerConcurrency !== undefined ? { worker_concurrency: workerConcurrency } : {}),
+ ...(workerConcurrency !== undefined
+ ? { worker_concurrency: workerConcurrency }
+ : {}),
...(defaultModelConcurrency !== undefined
? { default_model_concurrency: defaultModelConcurrency }
: {}),
...(modelLimit ? { model_limit: modelLimit } : {}),
}),
}),
- adminCreateUser: (body: { email: string; display_name: string; password: string; role: string }) =>
+ adminCreateUser: (body: {
+ email: string;
+ display_name: string;
+ password: string;
+ role: string;
+ }) =>
request<{ user: User }>("/api/v1/admin/users", {
method: "POST",
body: JSON.stringify(body),
@@ -550,21 +621,36 @@ export const api = {
body: JSON.stringify(body),
}),
adminDeleteDataSource: (id: string) =>
- request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}`, { method: "DELETE" }),
+ request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}`, {
+ method: "DELETE",
+ }),
adminTestDataSource: (id: string) =>
- request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}/test`, { method: "POST" }),
+ request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}/test`, {
+ method: "POST",
+ }),
kbDataSources: (kbId: string) =>
- request<{ data_sources: DataSourceView[] }>(`/api/v1/kbs/${kbId}/data-sources`),
+ request<{ data_sources: DataSourceView[] }>(
+ `/api/v1/kbs/${kbId}/data-sources`,
+ ),
kbDataSourcesAvailable: (kbId: string) =>
- request<{ data_sources: DataSourceView[] }>(`/api/v1/kbs/${kbId}/data-sources/available`),
+ request<{ data_sources: DataSourceView[] }>(
+ `/api/v1/kbs/${kbId}/data-sources/available`,
+ ),
mountDataSource: (kbId: string, dsId: string) =>
- request<{ ok: boolean; schema_tables: number }>(`/api/v1/kbs/${kbId}/data-sources/${dsId}`, {
- method: "PUT",
- }),
+ request<{ ok: boolean; schema_tables: number }>(
+ `/api/v1/kbs/${kbId}/data-sources/${dsId}`,
+ {
+ method: "PUT",
+ },
+ ),
unmountDataSource: (kbId: string, dsId: string) =>
- request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/${dsId}`, { method: "DELETE" }),
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/${dsId}`, {
+ method: "DELETE",
+ }),
exploreMappings: (kbId: string) =>
- request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/explore`, { method: "POST" }),
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/explore`, {
+ method: "POST",
+ }),
syncDataSourceSchema: (kbId: string, dsId: string) =>
request<{ ok: boolean; schema_tables: number }>(
`/api/v1/kbs/${kbId}/data-sources/${dsId}/sync-schema`,
@@ -574,7 +660,9 @@ export const api = {
documents: (kbId: string) => request<Doc[]>(`/api/v1/kbs/${kbId}/documents`),
/** 整库一次取回:行数按 (文档 × 原因 × 对象) 聚合后很小,避免逐行发请求 */
extractionDrops: (kbId: string) =>
- request<{ drops: ExtractionDrop[] }>(`/api/v1/kbs/${kbId}/extraction-drops`),
+ request<{ drops: ExtractionDrop[] }>(
+ `/api/v1/kbs/${kbId}/extraction-drops`,
+ ),
upload: (kbId: string, files: File[], sourceId?: string) => {
const form = new FormData();
for (const f of files) form.append("files", f, f.name);
@@ -601,7 +689,9 @@ export const api = {
body: JSON.stringify(body),
}),
graphOverview: (kbId: string) =>
- request<{ nodes: GraphNode[]; edges: GraphEdge[] }>(`/api/v1/kbs/${kbId}/graph/overview`),
+ request<{ nodes: GraphNode[]; edges: GraphEdge[] }>(
+ `/api/v1/kbs/${kbId}/graph/overview`,
+ ),
graphNeighborhood: (kbId: string, entityId: string) =>
request<{ nodes: GraphNode[]; edges: GraphEdge[] }>(
`/api/v1/kbs/${kbId}/graph/neighborhood?entity=${entityId}&hops=2`,
@@ -631,24 +721,34 @@ export const api = {
`/api/v1/kbs/${kbId}/entities/${entityId}/history?page=${page}&per=${per}`,
),
factEvidence: (kbId: string, factId: string) =>
- request<{ evidence: Evidence[] }>(`/api/v1/kbs/${kbId}/facts/${factId}/evidence`),
+ request<{ evidence: Evidence[] }>(
+ `/api/v1/kbs/${kbId}/facts/${factId}/evidence`,
+ ),
documentDetail: (id: string) =>
request<{ document: Doc; chunks: ChunkFull[] }>(`/api/v1/documents/${id}`),
extractDocument: (id: string) =>
- request<{ job_id: number }>(`/api/v1/documents/${id}/extract`, { method: "POST" }),
+ request<{ job_id: number }>(`/api/v1/documents/${id}/extract`, {
+ method: "POST",
+ }),
reprocessDocument: (id: string) =>
- request<{ job_id: number }>(`/api/v1/documents/${id}/reprocess`, { method: "POST" }),
- /** 来源级全量重抽(增量语义:既有决策保留) */
- reExtractSource: (kbId: string, sourceId: string) =>
- request<{ queued: number }>(`/api/v1/kbs/${kbId}/sources/${sourceId}/re-extract`, {
+ request<{ job_id: number }>(`/api/v1/documents/${id}/reprocess`, {
method: "POST",
}),
+ /** 来源级全量重抽(增量语义:既有决策保留) */
+ reExtractSource: (kbId: string, sourceId: string) =>
+ request<{ queued: number }>(
+ `/api/v1/kbs/${kbId}/sources/${sourceId}/re-extract`,
+ {
+ method: "POST",
+ },
+ ),
/** 图谱重建(清算语义:清空图层后全量重抽;KB admin) */
rebuildGraph: (kbId: string) =>
- request<{ entities_removed: number; facts_removed: number; queued: number }>(
- `/api/v1/kbs/${kbId}/graph/rebuild`,
- { method: "POST" },
- ),
+ request<{
+ entities_removed: number;
+ facts_removed: number;
+ queued: number;
+ }>(`/api/v1/kbs/${kbId}/graph/rebuild`, { method: "POST" }),
ontology: (kbId: string) =>
request<{
@@ -662,16 +762,25 @@ export const api = {
body: JSON.stringify(body),
}),
updateEntityType: (kbId: string, id: string, body: Record<string, unknown>) =>
- request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/entity-types/${id}`, {
- method: "PATCH",
- body: JSON.stringify(body),
- }),
+ request<{ ok: boolean }>(
+ `/api/v1/kbs/${kbId}/ontology/entity-types/${id}`,
+ {
+ method: "PATCH",
+ body: JSON.stringify(body),
+ },
+ ),
deleteEntityType: (kbId: string, id: string) =>
- request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/entity-types/${id}`, {
- method: "DELETE",
- }),
+ request<{ ok: boolean }>(
+ `/api/v1/kbs/${kbId}/ontology/entity-types/${id}`,
+ {
+ method: "DELETE",
+ },
+ ),
typeEntities: (kbId: string, typeId: string, page: number, per = 12) =>
- request<{ entities: { id: string; name: string; fact_count: number }[]; total: number }>(
+ request<{
+ entities: { id: string; name: string; fact_count: number }[];
+ total: number;
+ }>(
`/api/v1/kbs/${kbId}/ontology/entity-types/${typeId}/entities?page=${page}&per=${per}`,
),
createRelationType: (kbId: string, body: Record<string, unknown>) =>
@@ -679,25 +788,62 @@ export const api = {
method: "POST",
body: JSON.stringify(body),
}),
- updateRelationType: (kbId: string, id: string, body: Record<string, unknown>) =>
- request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/relation-types/${id}`, {
- method: "PATCH",
- body: JSON.stringify(body),
- }),
+ updateRelationType: (
+ kbId: string,
+ id: string,
+ body: Record<string, unknown>,
+ ) =>
+ request<{ ok: boolean }>(
+ `/api/v1/kbs/${kbId}/ontology/relation-types/${id}`,
+ {
+ method: "PATCH",
+ body: JSON.stringify(body),
+ },
+ ),
deleteRelationType: (kbId: string, id: string) =>
- request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/relation-types/${id}`, {
- method: "DELETE",
- }),
+ request<{ ok: boolean }>(
+ `/api/v1/kbs/${kbId}/ontology/relation-types/${id}`,
+ {
+ method: "DELETE",
+ },
+ ),
dismissMiss: (kbId: string, kind: string, key: string) =>
request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/misses/dismiss`, {
method: "POST",
body: JSON.stringify({ kind, key }),
}),
suggestOntology: (kbId: string) =>
- request<OntologyProposals>(`/api/v1/kbs/${kbId}/ontology/suggest`, { method: "POST" }),
+ request<OntologyProposals>(`/api/v1/kbs/${kbId}/ontology/suggest`, {
+ method: "POST",
+ }),
+
+ /** 上传本体文件只算出计划,一个字节都不写库 */
+ previewOntologyImport: (kbId: string, file: File) => {
+ const form = new FormData();
+ form.append("file", file, file.name);
+ return request<{ filename: string; plan: ImportPlan }>(
+ `/api/v1/kbs/${kbId}/ontology/imports/preview`,
+ { method: "POST", body: form },
+ );
+ },
+ /** 执行刚看过的那个计划——服务端重新算一遍,两条路径共用同一段代码 */
+ applyOntologyImport: (kbId: string, file: File) => {
+ const form = new FormData();
+ form.append("file", file, file.name);
+ return request<{ import_id: string; plan: ImportPlan }>(
+ `/api/v1/kbs/${kbId}/ontology/imports`,
+ { method: "POST", body: form },
+ );
+ },
+ ontologyImports: (kbId: string) =>
+ request<{ imports: OntologyImportView[] }>(
+ `/api/v1/kbs/${kbId}/ontology/imports`,
+ ),
proposedPredicates: (kbId: string) =>
- request<{ forms: ProposedPredicate[] }>(`/api/v1/kbs/${kbId}/ontology/proposed-predicates`),
+ request<{ forms: ProposedPredicate[] }>(
+ `/api/v1/kbs/${kbId}/ontology/proposed-predicates`,
+ ),
/** 最近一次自动扩本体做了什么,以及还能不能撤销(撤干净了返回 null) */
lastAutoExtension: (kbId: string) =>
request<{
@@ -751,23 +897,37 @@ export const api = {
`/api/v1/kbs/${kbId}/sources/${sourceId}/rotate-token`,
{ method: "POST" },
),
- updateSource: (kbId: string, sourceId: string, body: Record<string, unknown>) =>
+ updateSource: (
+ kbId: string,
+ sourceId: string,
+ body: Record<string, unknown>,
+ ) =>
request<{ source: SourceView }>(`/api/v1/kbs/${kbId}/sources/${sourceId}`, {
method: "PATCH",
body: JSON.stringify(body),
}),
deleteSource: (kbId: string, sourceId: string) =>
- request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/sources/${sourceId}`, { method: "DELETE" }),
- cleanupMissing: (kbId: string, sourceId: string) =>
- request<{ deleted: number }>(`/api/v1/kbs/${kbId}/sources/${sourceId}/missing/cleanup`, {
- method: "POST",
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/sources/${sourceId}`, {
+ method: "DELETE",
}),
+ cleanupMissing: (kbId: string, sourceId: string) =>
+ request<{ deleted: number }>(
+ `/api/v1/kbs/${kbId}/sources/${sourceId}/missing/cleanup`,
+ {
+ method: "POST",
+ },
+ ),
syncSource: (kbId: string, sourceId: string) =>
- request<{ queued: boolean }>(`/api/v1/kbs/${kbId}/sources/${sourceId}/sync`, {
- method: "POST",
- }),
+ request<{ queued: boolean }>(
+ `/api/v1/kbs/${kbId}/sources/${sourceId}/sync`,
+ {
+ method: "POST",
+ },
+ ),
sourceRuns: (kbId: string, sourceId: string) =>
- request<{ runs: SyncRun[] }>(`/api/v1/kbs/${kbId}/sources/${sourceId}/runs`),
+ request<{ runs: SyncRun[] }>(
+ `/api/v1/kbs/${kbId}/sources/${sourceId}/runs`,
+ ),
documentExtractions: (docId: string) =>
request<{ facts: ChunkFact[] }>(`/api/v1/documents/${docId}/extractions`),
@@ -799,27 +959,40 @@ export const api = {
body: JSON.stringify({ action }),
}),
confirmFact: (kbId: string, factId: string) =>
- request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/confirm`, { method: "POST" }),
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/confirm`, {
+ method: "POST",
+ }),
rejectFact: (kbId: string, factId: string) =>
- request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/reject`, { method: "POST" }),
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/reject`, {
+ method: "POST",
+ }),
revertMerge: (kbId: string, mergeId: string) =>
- request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/merges/${mergeId}/revert`, { method: "POST" }),
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/merges/${mergeId}/revert`, {
+ method: "POST",
+ }),
reviewHistory: (kbId: string, page: number, per = 20) =>
request<{ events: ReviewHistoryEvent[]; total: number }>(
`/api/v1/kbs/${kbId}/review/history?page=${page}&per=${per}`,
),
- members: (workspaceId: string) => request<Member[]>(`/api/v1/workspaces/${workspaceId}/members`),
+ members: (workspaceId: string) =>
+ request<Member[]>(`/api/v1/workspaces/${workspaceId}/members`),
orgUsers: () => request<OrgUser[]>("/api/v1/users"),
setMemberRole: (workspaceId: string, userId: string, role: string) =>
- request<{ ok: boolean }>(`/api/v1/workspaces/${workspaceId}/members/${userId}`, {
- method: "PUT",
- body: JSON.stringify({ role }),
- }),
+ request<{ ok: boolean }>(
+ `/api/v1/workspaces/${workspaceId}/members/${userId}`,
+ {
+ method: "PUT",
+ body: JSON.stringify({ role }),
+ },
+ ),
removeMember: (workspaceId: string, userId: string) =>
- request<{ ok: boolean }>(`/api/v1/workspaces/${workspaceId}/members/${userId}`, {
- method: "DELETE",
- }),
+ request<{ ok: boolean }>(
+ `/api/v1/workspaces/${workspaceId}/members/${userId}`,
+ {
+ method: "DELETE",
+ },
+ ),
testSettings: (workspaceId: string) =>
request<{
@@ -831,11 +1004,17 @@ export const api = {
/** RAG 对话:SSE 流式。返回中止函数。 */
export const conversationsApi = {
list: (kbId: string) =>
- request<{ conversations: ConversationRow[] }>(`/api/v1/kbs/${kbId}/conversations`),
+ request<{ conversations: ConversationRow[] }>(
+ `/api/v1/kbs/${kbId}/conversations`,
+ ),
detail: (kbId: string, id: string) =>
- request<{ messages: ConversationMessage[] }>(`/api/v1/kbs/${kbId}/conversations/${id}`),
+ request<{ messages: ConversationMessage[] }>(
+ `/api/v1/kbs/${kbId}/conversations/${id}`,
+ ),
remove: (kbId: string, id: string) =>
- request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conversations/${id}`, { method: "DELETE" }),
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conversations/${id}`, {
+ method: "DELETE",
+ }),
};
export function streamChat(
@@ -890,9 +1069,12 @@ export function streamChat(
}
if (event === "conversation")
handlers.onConversation((JSON.parse(data) as { id: string }).id);
- else if (event === "sources") handlers.onSources(JSON.parse(data || "[]"));
- else if (event === "step") handlers.onStep(JSON.parse(data) as ChatStep);
- else if (event === "delta") handlers.onDelta((JSON.parse(data) as { text: string }).text);
+ else if (event === "sources")
+ handlers.onSources(JSON.parse(data || "[]"));
+ else if (event === "step")
+ handlers.onStep(JSON.parse(data) as ChatStep);
+ else if (event === "delta")
+ handlers.onDelta((JSON.parse(data) as { text: string }).text);
else if (event === "done") handlers.onDone();
else if (event === "error") handlers.onError(data);
}
diff --git a/web/src/i18n.ts b/web/src/i18n.ts
index 5ebb9077..fd772ad8 100644
--- a/web/src/i18n.ts
+++ b/web/src/i18n.ts
@@ -74,7 +74,8 @@ export const S = {
signOut: "Sign out",
docs: "Docs",
loading: "Loading…",
- serverUnreachable: "Punishment 500: Utopia has gone quiet — it isn't answering.",
+ serverUnreachable:
+ "Punishment 500: Utopia has gone quiet — it isn't answering.",
notFound: "Punishment 404: You are lost in Utopia.",
returnHome: "Return home",
reportIssue: "Report an issue",
@@ -190,7 +191,8 @@ export const S = {
uploading: "Uploading…",
uploadFailed: "Upload failed",
dropHint: "Drag files here, or click “Upload files”",
- formats: "PDF · Word · Excel · PowerPoint · Markdown · HTML · TXT · CSV and more",
+ formats:
+ "PDF · Word · Excel · PowerPoint · Markdown · HTML · TXT · CSV and more",
emptyPull: "No documents yet — they arrive when this source syncs.",
filterPlaceholder: "Filter by name",
filterNoMatch: "No documents match your filter.",
@@ -205,7 +207,8 @@ export const S = {
reExtract: "Re-extract",
reprocess: "Reprocess",
// 抽取进度(当前视图内聚合,SSE 推动刷新)
- extractProgress: (done: number, total: number) => `Extracting · ${done} / ${total}`,
+ extractProgress: (done: number, total: number) =>
+ `Extracting · ${done} / ${total}`,
// 失败详情:chip 可点开,不再只有 tooltip
errorTitle: "Failure details",
errorParse: "Ingestion pipeline",
@@ -322,7 +325,8 @@ export const S = {
feedUrl: "Feed URL",
interval: "Sync schedule",
intervalManual: "Manual only",
- intervalEvery: (m: number) => (m < 60 ? `Every ${m} min` : `Every ${m / 60} h`),
+ intervalEvery: (m: number) =>
+ m < 60 ? `Every ${m} min` : `Every ${m / 60} h`,
schedule: {
manual: "Manual",
interval: "Interval",
@@ -345,7 +349,8 @@ export const S = {
deleteSourceHint: "Documents are kept and move to Uploads.",
newSourceTitle: "New source",
iconLabel: "Icon",
- pageOf: (from: number, to: number, total: number) => `${from}–${to} of ${total}`,
+ pageOf: (from: number, to: number, total: number) =>
+ `${from}–${to} of ${total}`,
syncHistory: "History",
runNew: (n: number) => `+${n} new`,
runUpdated: (n: number) => `~${n} updated`,
@@ -398,7 +403,8 @@ export const S = {
noConversations: "No conversations yet.",
deleteConversation: "Delete conversation",
deleteTitle: "Delete conversation?",
- deleteHint: (name: string) => `“${name}” and its messages will be permanently removed.`,
+ deleteHint: (name: string) =>
+ `“${name}” and its messages will be permanently removed.`,
deleteBtn: "Delete",
cancel: "Cancel",
},
@@ -422,7 +428,8 @@ export const S = {
noQuote: "(no quote)",
/* 原文说的谓词。词表外的词会被降级成 related to,原意只在这里活着 */
proposedPredicate: (p: string) => `the text said “${p}”`,
- sectionRef: (filename: string, seq: number) => `${filename} · section ${seq} →`,
+ sectionRef: (filename: string, seq: number) =>
+ `${filename} · section ${seq} →`,
fromVersion: (v: number) => `v${v}`,
staleEvidenceHint:
"This evidence comes from an earlier version of the document. " +
@@ -518,7 +525,8 @@ export const S = {
"never do. Takes effect immediately.",
modelDefault: "Default",
modelReset: "Reset",
- modelResetHint: "Drop this model's own limit and fall back to the default.",
+ modelResetHint:
+ "Drop this model's own limit and fall back to the default.",
},
datasources: {
tab: "Data sources",
@@ -619,6 +627,63 @@ export const S = {
save: "Save",
delete: "Delete",
deleteBlocked: "In use — cannot delete",
+ /* ---- OWL / RDFS 导入 ---- */
+ importShort: "Import",
+ importTitle: "Import an ontology",
+ importHint:
+ "Load an OWL or RDFS file (.owl, .rdf, .ttl). Classes and properties are matched by IRI, so re-importing a newer version of the same vocabulary updates what it already created instead of duplicating it.",
+ importPick: "Choose file",
+ importChange: "Choose another",
+ importReading: "Reading…",
+ importApplying: "Importing…",
+ importApply: "Import",
+ importCancel: "Cancel",
+ importParsed: (fmt: string, triples: number) =>
+ `${fmt === "rdfxml" ? "RDF/XML" : "Turtle"} · ${triples.toLocaleString()} triples`,
+ importNothing:
+ "Nothing to import — no classes or properties found in this file.",
+ /* 计划三列:新建 / 更新 / key 被占 */
+ importWillCreate: (n: number) => `${n} new`,
+ importWillUpdate: (n: number) => `${n} updated`,
+ importKeyTaken: (n: number) => `${n} skipped`,
+ importClasses: "Classes",
+ importRelations: "Relations",
+ importAttributes: "Attributes",
+ /* 属性还落不了库:它们要 domain,而 domain 要等类先建好并解析 IRI */
+ importAttributesLater:
+ "Parsed, but not created yet — attributes need a class to hang from, which lands in the next step.",
+ /* 预览必须警告的第一件事:functional 会让时序引擎自动关掉旧事实。
+ part_of 那次一个错误的唯一性声明造了 59 条假冲突 */
+ warnFunctional: (n: number) =>
+ `${n} ${n === 1 ? "relation declares" : "relations declare"} itself functional`,
+ warnFunctionalBody:
+ "A functional relation may hold one value at a time, so a new fact automatically closes the previous one. When the vocabulary claims uniqueness your data does not keep, that shows up as a queue of conflicts. Review these after importing.",
+ /* 第二件事:description 逐字进抽取提示词,没有它的类抽得明显差 */
+ warnNoDescription: (n: number) =>
+ `${n} ${n === 1 ? "class arrives" : "classes arrive"} with no description`,
+ warnNoDescriptionBody:
+ "A class description goes verbatim into the extraction prompt — it is the only thing telling the model what belongs there. Write one for these, or they will quietly under-extract.",
+ /* key 撞了:报告不解决。自动加后缀会让下次重导入认不出自己上次建的是哪个 */
+ warnKeyTaken: (n: number) =>
+ `${n} ${n === 1 ? "key is" : "keys are"} already taken`,
+ warnKeyTakenBody:
+ "Something else already holds this key under a different identity. These are left alone — rename the existing one first if you want the imported version instead.",
+ /* 占位者没有 IRI = 这库里手工建的或内置的,那句话比一个空 IRI 有用 */
+ importTakenBy: (iri: string | null) =>
+ iri
+ ? `taken by ${iri}`
+ : "taken by an entry defined in this knowledge base",
+ /* 出现过但今天不投影的公理,按名字与次数列出——"暂未投影"不是"已跳过" */
+ importUnprojected: "Not projected yet",
+ importUnprojectedBody:
+ "Axioms this file uses that Utopia does not consume yet. Nothing is lost: the source file is stored as uploaded, so a later version can project them.",
+ importDone: (created: number, updated: number) =>
+ `Imported — ${created} classes created, ${updated} updated.`,
+ importHistory: "Previous imports",
+ importNoHistory: "No imports yet.",
+ importBy: (who: string, when: string) => `${who} · ${when}`,
+ importSize: (bytes: number) =>
+ bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(0)} KB`,
misses: "Unmatched from extraction",
missesHint:
"The extractor produced these outside your ontology (they fell back to concept / related to). They are signals for extending the ontology.",
@@ -632,7 +697,9 @@ export const S = {
willRemap: (n: number) =>
n === 1 ? "reclassifies 1 fact" : `reclassifies ${n} facts`,
adopted: (n: number) =>
- n === 1 ? "Added — 1 fact reclassified" : `Added — ${n} facts reclassified`,
+ n === 1
+ ? "Added — 1 fact reclassified"
+ : `Added — ${n} facts reclassified`,
/* 撤销:采纳改写了成批事实,没有回头路的话没人敢点第一下 */
undoAdopt: (key: string, n: number) =>
`${key} added, ${n} fact${n === 1 ? "" : "s"} reclassified`,
@@ -776,9 +843,11 @@ export const S = {
dataExplore: "Explore mappings",
dataExploreHint:
"An agent reads the schemas and proposes metric/dimension definitions — review them in Review before Chat uses them.",
- dataExploreQueued: "Exploration queued — proposals will appear in Review shortly.",
+ dataExploreQueued:
+ "Exploration queued — proposals will appear in Review shortly.",
dataNone: "No data sources mounted.",
- dataNoneAvailable: "No data sources registered yet — ask a deployment admin to register one.",
+ dataNoneAvailable:
+ "No data sources registered yet — ask a deployment admin to register one.",
dataNewConn: "Register a new connection",
activity: "Activity",
activityHint:
@@ -799,6 +868,7 @@ export const S = {
"source.updated": "updated source",
"source.deleted": "deleted a source",
"document.deleted": "deleted document",
+ "ontology.imported": "imported an ontology",
} as Record<string, string>,
membersHint:
"Everyone in the deployment can read an open KB; write access is granted here " +
@@ -811,7 +881,8 @@ export const S = {
saved: "Saved",
danger: "Danger zone",
deleteKb: "Delete this knowledge base",
- deleteHint: (name: string) => `Type “${name}” to confirm. Documents, graph and sources are permanently removed.`,
+ deleteHint: (name: string) =>
+ `Type “${name}” to confirm. Documents, graph and sources are permanently removed.`,
deleteBtn: "Delete permanently",
deleteRowTitle: "Delete this knowledge base",
deleteRowHint: "Documents, graph and sources are removed permanently.",
@@ -823,7 +894,8 @@ export const S = {
remove: "Remove",
pickUser: "Select a user to add…",
add: "Add",
- allAdded: "Everyone in this deployment is already a member. New signups will appear here.",
+ allAdded:
+ "Everyone in this deployment is already a member. New signups will appear here.",
roles: {
owner: "Owner",
admin: "Admin",
diff --git a/web/src/pages/Ontology.tsx b/web/src/pages/Ontology.tsx
index 04d23746..1ae5adb7 100644
--- a/web/src/pages/Ontology.tsx
+++ b/web/src/pages/Ontology.tsx
@@ -4,11 +4,13 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";
-import { ChevronRight, Inbox, Plus, Search } from "lucide-react";
+import { ChevronRight, Inbox, Plus, Search, Upload } from "lucide-react";
import {
api,
type EntityTypeView,
+ type ImportPlan,
type OntologyMiss,
+ type PlannedItem,
type OntologyProposals,
type RelationTypeView,
} from "../api";
@@ -46,6 +48,7 @@ type Sel =
| { kind: "new-class"; parentId: string | null }
| { kind: "new-relation" }
| { kind: "misses" }
+ | { kind: "import" }
| null;
export function Ontology() {
@@ -62,7 +65,9 @@ export function Ontology() {
const el = listRef.current;
if (!el) return;
const ro = new ResizeObserver(() => {
- setRailRows(Math.max(5, Math.floor((el.clientHeight - RAIL_RESERVED) / RAIL_ROW_H)));
+ setRailRows(
+ Math.max(5, Math.floor((el.clientHeight - RAIL_RESERVED) / RAIL_ROW_H)),
+ );
});
ro.observe(el);
return () => ro.disconnect();
@@ -74,7 +79,8 @@ export function Ontology() {
enabled: !!kb,
});
- const refresh = () => queryClient.invalidateQueries({ queryKey: ["ontology", kb?.id] });
+ const refresh = () =>
+ queryClient.invalidateQueries({ queryKey: ["ontology", kb?.id] });
// 错误统一走全局 toast,不再用页面内嵌错误行
const onError = (e: unknown) => toast.error((e as Error).message);
@@ -86,9 +92,13 @@ export function Ontology() {
// 属性不进 Properties 列表:它们挂在类下,在类详情区编辑
const relations = relation_types.filter((r) => r.kind !== "attribute");
const selectedClass =
- sel?.kind === "class" ? (entity_types.find((t) => t.id === sel.id) ?? null) : null;
+ sel?.kind === "class"
+ ? (entity_types.find((t) => t.id === sel.id) ?? null)
+ : null;
const selectedProp =
- sel?.kind === "relation" ? (relation_types.find((r) => r.id === sel.id) ?? null) : null;
+ sel?.kind === "relation"
+ ? (relation_types.find((r) => r.id === sel.id) ?? null)
+ : null;
return (
<div className="h-full flex">
@@ -131,7 +141,10 @@ export function Ontology() {
</button>
))}
</div>
- <div ref={listRef} className="flex-1 min-h-0 overflow-hidden px-2 pt-1.5 pb-2 flex flex-col">
+ <div
+ ref={listRef}
+ className="flex-1 min-h-0 overflow-hidden px-2 pt-1.5 pb-2 flex flex-col"
+ >
{/* 新建行置顶:随当前段建类/建关系 */}
{!filter.trim() && (
<button
@@ -143,7 +156,9 @@ export function Ontology() {
className="w-full flex items-center gap-1.5 rounded-lg px-2 py-2 mb-0.5 text-[13px] text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-200 transition-colors"
>
<Plus size={13} />
- {railTab === "classes" ? S.ontology.newClass : S.ontology.newProperty}
+ {railTab === "classes"
+ ? S.ontology.newClass
+ : S.ontology.newProperty}
</button>
)}
{filter.trim() ? (
@@ -196,6 +211,19 @@ export function Ontology() {
/>
)}
</div>
+ {/* 底部常驻:两个"关于本体"的入口——从外部拿一份本体,或看抽取顶回来的信号 */}
+ <button
+ onClick={() => setSel({ kind: "import" })}
+ className={cn(
+ "shrink-0 border-t border-white/10 px-4 py-2.5 flex items-center gap-2 text-[13px] transition-colors",
+ sel?.kind === "import"
+ ? "u-nav-active"
+ : "text-neutral-400 hover:bg-white/[0.05] hover:text-neutral-200",
+ )}
+ >
+ <Upload size={14} className="text-neutral-500" />
+ <span>{S.ontology.importShort}</span>
+ </button>
{/* 底部常驻:抽取未匹配信号(有存量时带数量徽标) */}
<button
onClick={() => setSel({ kind: "misses" })}
@@ -220,9 +248,18 @@ export function Ontology() {
<div className="flex-1 min-w-0 overflow-y-auto u-scroll px-8 py-6">
{/* 放宽到 6xl 供三列铺开;misses/关系/概览各自带 max-w-xl 内衬不受影响 */}
<div className="max-w-6xl">
- {sel?.kind === "misses" ? (
+ {sel?.kind === "import" ? (
<div className="max-w-xl">
- <MissesPanel kbId={kb.id} misses={misses} onChanged={refresh} onError={onError} />
+ <ImportPanel kbId={kb.id} onChanged={refresh} onError={onError} />
+ </div>
+ ) : sel?.kind === "misses" ? (
+ <div className="max-w-xl">
+ <MissesPanel
+ kbId={kb.id}
+ misses={misses}
+ onChanged={refresh}
+ onError={onError}
+ />
</div>
) : sel?.kind === "new-class" || selectedClass ? (
/* lg 两列(表单 | 属性+实例堆叠);xl 三列并排(包装器 xl:contents 解散入栅格) */
@@ -230,23 +267,32 @@ export function Ontology() {
<div className="glass rounded-xl p-4">
<ClassForm
key={
- selectedClass?.id ?? `new-${sel?.kind === "new-class" ? sel.parentId : "root"}`
+ selectedClass?.id ??
+ `new-${sel?.kind === "new-class" ? sel.parentId : "root"}`
}
kbId={kb.id}
existing={selectedClass}
parentId={
- sel?.kind === "new-class" ? sel.parentId : (selectedClass?.parent_id ?? null)
+ sel?.kind === "new-class"
+ ? sel.parentId
+ : (selectedClass?.parent_id ?? null)
}
allTypes={entity_types}
onNewSub={
selectedClass
- ? () => setSel({ kind: "new-class", parentId: selectedClass.id })
+ ? () =>
+ setSel({
+ kind: "new-class",
+ parentId: selectedClass.id,
+ })
: undefined
}
onDone={(createdId) => {
// 新建成功即选中它:立刻能看到、能继续编辑
if (sel?.kind === "new-class")
- setSel(createdId ? { kind: "class", id: createdId } : null);
+ setSel(
+ createdId ? { kind: "class", id: createdId } : null,
+ );
refresh();
}}
onError={onError}
@@ -259,7 +305,9 @@ export function Ontology() {
kbId={kb.id}
type={selectedClass}
attributes={relation_types.filter(
- (r) => r.kind === "attribute" && r.domain_type_id === selectedClass.id,
+ (r) =>
+ r.kind === "attribute" &&
+ r.domain_type_id === selectedClass.id,
)}
onChanged={refresh}
onError={onError}
@@ -276,7 +324,9 @@ export function Ontology() {
existing={selectedProp}
onDone={(createdId) => {
if (sel?.kind === "new-relation")
- setSel(createdId ? { kind: "relation", id: createdId } : null);
+ setSel(
+ createdId ? { kind: "relation", id: createdId } : null,
+ );
refresh();
}}
onError={onError}
@@ -287,9 +337,14 @@ export function Ontology() {
<div className="glass rounded-xl p-6 max-w-xl">
<PageTitle className="mb-1">{S.ontology.title}</PageTitle>
<p className="text-xs text-neutral-500 u-num">
- {S.ontology.overviewStats(entity_types.length, relations.length)}
+ {S.ontology.overviewStats(
+ entity_types.length,
+ relations.length,
+ )}
+ </p>
+ <p className="mt-3 text-sm text-neutral-400">
+ {S.ontology.overviewHint}
</p>
- <p className="mt-3 text-sm text-neutral-400">{S.ontology.overviewHint}</p>
</div>
)}
</div>
@@ -315,7 +370,9 @@ function InstancesCard({ kbId, type }: { kbId: string; type: EntityTypeView }) {
return (
<div className="glass rounded-xl p-4">
<div className="mb-1.5 flex items-baseline gap-2">
- <h3 className="text-sm font-bold text-neutral-200">{S.ontology.instances}</h3>
+ <h3 className="text-sm font-bold text-neutral-200">
+ {S.ontology.instances}
+ </h3>
<span className="u-num text-xs text-neutral-500">{total}</span>
</div>
<div className="divide-y divide-white/[0.06]">
@@ -364,12 +421,18 @@ function AttributesCard({
return (
<div className="glass rounded-xl p-4">
<div className="mb-1 flex items-baseline gap-2">
- <h3 className="text-sm font-bold text-neutral-200">{S.ontology.attributes}</h3>
+ <h3 className="text-sm font-bold text-neutral-200">
+ {S.ontology.attributes}
+ </h3>
{attributes.length > 0 && (
- <span className="u-num text-xs text-neutral-500">{attributes.length}</span>
+ <span className="u-num text-xs text-neutral-500">
+ {attributes.length}
+ </span>
)}
</div>
- <p className="text-xs text-neutral-500 mb-2">{S.ontology.attributesHint}</p>
+ <p className="text-xs text-neutral-500 mb-2">
+ {S.ontology.attributesHint}
+ </p>
<div className="divide-y divide-white/[0.06]">
{attributes.map((a) =>
editing === a.id ? (
@@ -392,8 +455,14 @@ function AttributesCard({
className="w-full flex items-center gap-2 py-1.5 text-sm text-left text-neutral-300 hover:text-white"
>
<span className="truncate">{a.label}</span>
- <Chip tone="neutral">{S.ontology.datatypeNames[a.datatype ?? "text"]}</Chip>
- {a.unit && <span className="text-xs text-neutral-500 shrink-0">{a.unit}</span>}
+ <Chip tone="neutral">
+ {S.ontology.datatypeNames[a.datatype ?? "text"]}
+ </Chip>
+ {a.unit && (
+ <span className="text-xs text-neutral-500 shrink-0">
+ {a.unit}
+ </span>
+ )}
{a.functional && <Chip tone="info">1:1</Chip>}
<span className="ml-auto shrink-0 u-num text-[10.5px] text-neutral-600">
{S.ontology.usage(a.usage)}
@@ -507,14 +576,22 @@ function AttributeForm({
</div>
<div className="flex-1">
<label className={lbl}>{S.ontology.label}</label>
- <Input value={label} onChange={(e) => setLabel(e.target.value)} className="w-full" />
+ <Input
+ value={label}
+ onChange={(e) => setLabel(e.target.value)}
+ className="w-full"
+ />
</div>
</div>
)}
{existing && (
<div>
<label className={lbl}>{S.ontology.label}</label>
- <Input value={label} onChange={(e) => setLabel(e.target.value)} className="w-full" />
+ <Input
+ value={label}
+ onChange={(e) => setLabel(e.target.value)}
+ className="w-full"
+ />
</div>
)}
<div className="flex gap-2">
@@ -533,13 +610,23 @@ function AttributeForm({
<div className="flex-1">
<label className={lbl}>
{S.ontology.attrUnit}{" "}
- <span className="text-neutral-600">({S.ontology.attrUnitHint})</span>
+ <span className="text-neutral-600">
+ ({S.ontology.attrUnitHint})
+ </span>
</label>
- <Input value={unit} onChange={(e) => setUnit(e.target.value)} className="w-full" />
+ <Input
+ value={unit}
+ onChange={(e) => setUnit(e.target.value)}
+ className="w-full"
+ />
</div>
</div>
<label className="flex items-center gap-2 text-[13px] text-neutral-300">
- <input type="checkbox" checked={single} onChange={(e) => setSingle(e.target.checked)} />
+ <input
+ type="checkbox"
+ checked={single}
+ onChange={(e) => setSingle(e.target.checked)}
+ />
{S.ontology.attrSingle}
</label>
<div>
@@ -554,7 +641,9 @@ function AttributeForm({
<Button
size="sm"
onClick={() => save.mutate()}
- disabled={save.isPending || !label.trim() || (!existing && !key.trim())}
+ disabled={
+ save.isPending || !label.trim() || (!existing && !key.trim())
+ }
>
{S.ontology.save}
</Button>
@@ -604,7 +693,11 @@ function ClassTree({
if (q) {
// filter 模式:拍平命中项(label/key 都参与匹配)
return types
- .filter((t) => t.label.toLowerCase().includes(q) || t.key.toLowerCase().includes(q))
+ .filter(
+ (t) =>
+ t.label.toLowerCase().includes(q) ||
+ t.key.toLowerCase().includes(q),
+ )
.map((t) => ({ t, depth: 0, hasChildren: false }));
}
const children = new Map<string | null, EntityTypeView[]>();
@@ -613,7 +706,8 @@ function ClassTree({
if (!children.has(p)) children.set(p, []);
children.get(p)!.push(t);
}
- const out: { t: EntityTypeView; depth: number; hasChildren: boolean }[] = [];
+ const out: { t: EntityTypeView; depth: number; hasChildren: boolean }[] =
+ [];
const walk = (parent: string | null, depth: number) => {
for (const t of children.get(parent) ?? []) {
const kids = children.get(t.id) ?? [];
@@ -655,7 +749,10 @@ function ClassTree({
>
<ChevronRight
size={12}
- className={cn("transition-transform", !collapsed.has(t.id) && "rotate-90")}
+ className={cn(
+ "transition-transform",
+ !collapsed.has(t.id) && "rotate-90",
+ )}
/>
</span>
) : (
@@ -670,7 +767,12 @@ function ClassTree({
<span className="truncate">{t.label}</span>
</button>
))}
- <Pager total={rows.length} pageSize={pageSize} page={safe} onPage={setPage} />
+ <Pager
+ total={rows.length}
+ pageSize={pageSize}
+ page={safe}
+ onPage={setPage}
+ />
</div>
);
}
@@ -693,7 +795,8 @@ function PropertyList({
const q = filter.trim().toLowerCase();
const rows = q
? relations.filter(
- (r) => r.label.toLowerCase().includes(q) || r.key.toLowerCase().includes(q),
+ (r) =>
+ r.label.toLowerCase().includes(q) || r.key.toLowerCase().includes(q),
)
: relations;
// 半屏分页:过滤词变化回第一页
@@ -720,7 +823,12 @@ function PropertyList({
{r.functional && <Chip tone="info">1:1</Chip>}
</button>
))}
- <Pager total={rows.length} pageSize={pageSize} page={safe} onPage={setPage} />
+ <Pager
+ total={rows.length}
+ pageSize={pageSize}
+ page={safe}
+ onPage={setPage}
+ />
</div>
);
}
@@ -787,7 +895,9 @@ function ClassForm({
const [key, setKey] = useState(existing?.key ?? "");
const [label, setLabel] = useState(existing?.label ?? "");
const [color, setColor] = useState(existing?.color ?? "#8ea5bd");
- const [shape, setShape] = useState<"circle" | "square">(existing?.shape ?? "circle");
+ const [shape, setShape] = useState<"circle" | "square">(
+ existing?.shape ?? "circle",
+ );
const [parent, setParent] = useState<string>(parentId ?? "");
const [description, setDescription] = useState(existing?.description ?? "");
@@ -834,11 +944,15 @@ function ClassForm({
className={`h-3 w-3 ${shape === "square" ? "" : "rounded-full"}`}
style={{ background: color }}
/>
- <span className="font-bold text-neutral-100">{existing?.label ?? S.ontology.newClass}</span>
+ <span className="font-bold text-neutral-100">
+ {existing?.label ?? S.ontology.newClass}
+ </span>
{/* key 是纯技术标识:已存在时干脆不展示,只在创建时输入 */}
{existing?.builtin && <Chip tone="neutral">{S.ontology.builtin}</Chip>}
{existing && (
- <span className="ml-auto text-xs text-neutral-500">{S.ontology.usage(existing.usage)}</span>
+ <span className="ml-auto text-xs text-neutral-500">
+ {S.ontology.usage(existing.usage)}
+ </span>
)}
</div>
{!existing && (
@@ -857,7 +971,11 @@ function ClassForm({
)}
<div>
<label className={lbl}>{S.ontology.label}</label>
- <Input value={label} onChange={(e) => setLabel(e.target.value)} className="w-full" />
+ <Input
+ value={label}
+ onChange={(e) => setLabel(e.target.value)}
+ className="w-full"
+ />
</div>
<div>
<label className={lbl}>{S.ontology.shapeColor}</label>
@@ -906,10 +1024,16 @@ function ClassForm({
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
- <p className="mt-1 text-[10.5px] text-neutral-600">{S.ontology.descriptionHint}</p>
+ <p className="mt-1 text-[10.5px] text-neutral-600">
+ {S.ontology.descriptionHint}
+ </p>
</div>
<div className="flex gap-2 pt-1">
- <Button size="sm" onClick={() => save.mutate()} disabled={save.isPending || !label.trim()}>
+ <Button
+ size="sm"
+ onClick={() => save.mutate()}
+ disabled={save.isPending || !label.trim()}
+ >
{S.ontology.save}
</Button>
{onNewSub && (
@@ -997,7 +1121,9 @@ function PropertyForm({
</span>
{existing?.builtin && <Chip tone="neutral">{S.ontology.builtin}</Chip>}
{existing && (
- <span className="ml-auto text-xs text-neutral-500">{S.ontology.usage(existing.usage)}</span>
+ <span className="ml-auto text-xs text-neutral-500">
+ {S.ontology.usage(existing.usage)}
+ </span>
)}
</div>
{!existing && (
@@ -1016,7 +1142,11 @@ function PropertyForm({
)}
<div>
<label className={lbl}>{S.ontology.label}</label>
- <Input value={label} onChange={(e) => setLabel(e.target.value)} className="w-full" />
+ <Input
+ value={label}
+ onChange={(e) => setLabel(e.target.value)}
+ className="w-full"
+ />
</div>
<div>
<label className={lbl}>{S.ontology.temporal}</label>
@@ -1054,10 +1184,16 @@ function PropertyForm({
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
- <p className="mt-1 text-[10.5px] text-neutral-600">{S.ontology.descriptionHint}</p>
+ <p className="mt-1 text-[10.5px] text-neutral-600">
+ {S.ontology.descriptionHint}
+ </p>
</div>
<div className="flex gap-2 pt-1">
- <Button size="sm" onClick={() => save.mutate()} disabled={save.isPending || !label.trim()}>
+ <Button
+ size="sm"
+ onClick={() => save.mutate()}
+ disabled={save.isPending || !label.trim()}
+ >
{S.ontology.save}
</Button>
{existing && !existing.builtin && (
@@ -1096,13 +1232,12 @@ function MissesPanel({
batches: string[];
key: string;
moved: number;
- } | null>(
- null,
- );
+ } | null>(null);
// 撤销要二次确认:一次改回成批事实
- const [confirmUndo, setConfirmUndo] = useState<{ batches: string[]; moved: number } | null>(
- null,
- );
+ const [confirmUndo, setConfirmUndo] = useState<{
+ batches: string[];
+ moved: number;
+ } | null>(null);
// 系统自动扩过本体没有——横幅要据此显示,撤干净了后端返回 null
const autoRun = useQuery({
queryKey: ["auto-extension", kbId],
@@ -1114,7 +1249,9 @@ function MissesPanel({
queryFn: () => api.proposedPredicates(kbId),
});
const factsWaiting = (forms: string[]) => {
- const byForm = new Map((surface.data?.forms ?? []).map((f) => [f.form, f.fact_count]));
+ const byForm = new Map(
+ (surface.data?.forms ?? []).map((f) => [f.form, f.fact_count]),
+ );
return forms.reduce((n, f) => n + (byForm.get(f) ?? 0), 0);
};
@@ -1131,13 +1268,20 @@ function MissesPanel({
});
const approveEntity = useMutation({
mutationFn: (p: { key: string; label: string; description?: string }) =>
- api.createEntityType(kbId, { key: p.key, label: p.label, description: p.description }),
+ api.createEntityType(kbId, {
+ key: p.key,
+ label: p.label,
+ description: p.description,
+ }),
onSuccess: (_data, p) => {
// 已采纳:从提案列表移除,并顺带清掉对应的未匹配统计 chip(本体已覆盖)
toast.success(S.toast.added);
setProposals(
(prev) =>
- prev && { ...prev, entity_types: prev.entity_types.filter((x) => x.key !== p.key) },
+ prev && {
+ ...prev,
+ entity_types: prev.entity_types.filter((x) => x.key !== p.key),
+ },
);
api.dismissMiss(kbId, "entity_type", p.key).catch(() => {});
onChanged();
@@ -1176,10 +1320,14 @@ function MissesPanel({
const moved = d.remapped ?? 0;
toast.success(moved > 0 ? S.ontology.adopted(moved) : S.toast.added);
// 撤销的把手:采纳改写了成批事实,没有回头路的话没人敢点第一下
- if (moved > 0 && d.batch) setLastAdopt({ batches: [d.batch], key: p.key, moved });
+ if (moved > 0 && d.batch)
+ setLastAdopt({ batches: [d.batch], key: p.key, moved });
setProposals(
(prev) =>
- prev && { ...prev, relation_types: prev.relation_types.filter((x) => x.key !== p.key) },
+ prev && {
+ ...prev,
+ relation_types: prev.relation_types.filter((x) => x.key !== p.key),
+ },
);
api.dismissMiss(kbId, "relation_type", p.key).catch(() => {});
onChanged();
@@ -1233,7 +1381,11 @@ function MissesPanel({
if (r.failed.length) toast.error(S.ontology.addAllPartial(r.failed));
else toast.success(S.ontology.adopted(r.moved));
if (r.batches.length)
- setLastAdopt({ batches: r.batches, key: S.ontology.addAllLabel, moved: r.moved });
+ setLastAdopt({
+ batches: r.batches,
+ key: S.ontology.addAllLabel,
+ moved: r.moved,
+ });
setProposals(null);
onChanged();
},
@@ -1243,7 +1395,8 @@ function MissesPanel({
const unadopt = useMutation({
mutationFn: async (batches: string[]) => {
let reverted = 0;
- for (const b of batches) reverted += (await api.unadoptPredicate(kbId, b)).reverted;
+ for (const b of batches)
+ reverted += (await api.unadoptPredicate(kbId, b)).reverted;
return { reverted };
},
onSuccess: (r) => {
@@ -1259,9 +1412,16 @@ function MissesPanel({
return (
<div className="glass rounded-xl p-4">
<div className="flex items-center gap-3 mb-1">
- <h3 className="text-sm font-bold text-neutral-200">{S.ontology.misses}</h3>
+ <h3 className="text-sm font-bold text-neutral-200">
+ {S.ontology.misses}
+ </h3>
{misses.length > 0 && (
- <Button size="sm" variant="ghost" onClick={() => suggest.mutate()} disabled={suggest.isPending}>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => suggest.mutate()}
+ disabled={suggest.isPending}
+ >
{suggest.isPending ? S.ontology.suggesting : S.ontology.suggest}
</Button>
)}
@@ -1299,14 +1459,18 @@ function MissesPanel({
<div className="mt-3 rounded-lg border border-[var(--u-accent)]/25 bg-[var(--u-accent)]/[0.06] px-3 py-2.5">
<div className="flex items-start gap-2">
<div className="min-w-0 flex-1">
- <p className="text-xs text-neutral-200">{S.ontology.autoRanTitle}</p>
+ <p className="text-xs text-neutral-200">
+ {S.ontology.autoRanTitle}
+ </p>
<p className="mt-0.5 text-[11px] text-neutral-400">
{S.ontology.autoRanBody(
autoRun.data.run.relations ?? [],
autoRun.data.run.facts_remapped ?? 0,
)}
</p>
- <p className="mt-0.5 text-[11px] text-neutral-600">{S.ontology.autoRanOff}</p>
+ <p className="mt-0.5 text-[11px] text-neutral-600">
+ {S.ontology.autoRanOff}
+ </p>
</div>
<Button
size="sm"
@@ -1325,21 +1489,25 @@ function MissesPanel({
</div>
)}
-
{/* 采纳改写了成批事实——没有回头路的话没人敢点第一下 */}
{lastAdopt && (
<div className="mt-3 flex items-center gap-2 rounded-lg border border-white/10 bg-white/[0.03] px-3 py-2">
<span className="text-xs text-neutral-300">
{S.ontology.undoAdopt(lastAdopt.key, lastAdopt.moved)}
</span>
- <span className="text-[11px] text-neutral-600">{S.ontology.undoKeepsRelation}</span>
+ <span className="text-[11px] text-neutral-600">
+ {S.ontology.undoKeepsRelation}
+ </span>
<Button
size="sm"
variant="ghost"
className="ml-auto"
disabled={unadopt.isPending}
onClick={() =>
- setConfirmUndo({ batches: lastAdopt.batches, moved: lastAdopt.moved })
+ setConfirmUndo({
+ batches: lastAdopt.batches,
+ moved: lastAdopt.moved,
+ })
}
>
{S.ontology.undoAdoptBtn}
@@ -1362,9 +1530,12 @@ function MissesPanel({
{proposals && (
<div className="mt-4 border-t border-white/10 pt-3">
<div className="mb-2 flex items-center gap-2">
- <h4 className="text-xs font-bold text-neutral-400">{S.ontology.proposals}</h4>
+ <h4 className="text-xs font-bold text-neutral-400">
+ {S.ontology.proposals}
+ </h4>
{/* 常见情形是"这些都对"——一条条点是把一个决定拆成八个 */}
- {proposals.relation_types.length + proposals.entity_types.length > 1 && (
+ {proposals.relation_types.length + proposals.entity_types.length >
+ 1 && (
<Button
size="sm"
variant="ghost"
@@ -1375,7 +1546,8 @@ function MissesPanel({
{addAll.isPending
? S.ontology.addingAll
: S.ontology.addAll(
- proposals.relation_types.length + proposals.entity_types.length,
+ proposals.relation_types.length +
+ proposals.entity_types.length,
)}
</Button>
)}
@@ -1386,7 +1558,11 @@ function MissesPanel({
<Chip tone="info">C</Chip>
<span className="font-mono text-neutral-300">{p.key}</span>
<span className="text-neutral-200">{p.label}</span>
- {p.reason && <span className="text-xs text-neutral-500 truncate">{p.reason}</span>}
+ {p.reason && (
+ <span className="text-xs text-neutral-500 truncate">
+ {p.reason}
+ </span>
+ )}
<Button
size="sm"
className="ml-auto"
@@ -1413,7 +1589,11 @@ function MissesPanel({
{S.ontology.willRemap(factsWaiting(p.forms))}
</span>
)}
- {p.reason && <span className="text-xs text-neutral-500 truncate">{p.reason}</span>}
+ {p.reason && (
+ <span className="text-xs text-neutral-500 truncate">
+ {p.reason}
+ </span>
+ )}
<Button
size="sm"
className="ml-auto"
@@ -1424,12 +1604,366 @@ function MissesPanel({
</Button>
</div>
))}
- {proposals.entity_types.length === 0 && proposals.relation_types.length === 0 && (
- <p className="text-sm text-neutral-500">—</p>
- )}
+ {proposals.entity_types.length === 0 &&
+ proposals.relation_types.length === 0 && (
+ <p className="text-sm text-neutral-500">—</p>
+ )}
</div>
</div>
)}
</div>
);
}
+
+/* ---------- 本体导入:上传 → 预览计划 → 确认落库 ---------- */
+/* 预览与落库共用服务端同一个 plan。这个面板的全部工作是把计划里
+ **会咬人的三件事**放到人点确认之前:函数性关系(错误的唯一性声明会造出
+ 成队假冲突)、没有描述的类(description 逐字进抽取提示词,缺了就静默抽差)、
+ key 撞车(报告不解决——自动改名会让下次重导入认不出自己上次建的是哪个)。 */
+
+function ImportPanel({
+ kbId,
+ onChanged,
+ onError,
+}: {
+ kbId: string;
+ onChanged: () => void;
+ onError: (e: unknown) => void;
+}) {
+ const [file, setFile] = useState<File | null>(null);
+ const pick = useRef<HTMLInputElement>(null);
+ const queryClient = useQueryClient();
+
+ const history = useQuery({
+ queryKey: ["ontology-imports", kbId],
+ queryFn: () => api.ontologyImports(kbId),
+ });
+
+ const preview = useMutation({
+ mutationFn: (f: File) => api.previewOntologyImport(kbId, f),
+ onError: (e) => {
+ setFile(null);
+ onError(e);
+ },
+ });
+
+ const apply = useMutation({
+ mutationFn: (f: File) => api.applyOntologyImport(kbId, f),
+ onSuccess: (res) => {
+ const p = res.plan;
+ toast.success(
+ S.ontology.importDone(
+ p.classes.filter((c) => c.disposition === "create").length,
+ p.classes.filter((c) => c.disposition === "update").length,
+ ),
+ );
+ setFile(null);
+ preview.reset();
+ queryClient.invalidateQueries({ queryKey: ["ontology-imports", kbId] });
+ onChanged();
+ },
+ onError,
+ });
+
+ const choose = (f: File | undefined) => {
+ if (!f) return;
+ setFile(f);
+ preview.mutate(f);
+ };
+
+ const plan = preview.data?.plan ?? null;
+ const busy = preview.isPending || apply.isPending;
+ const empty =
+ plan &&
+ plan.classes.length === 0 &&
+ plan.relations.length === 0 &&
+ plan.attributes.length === 0;
+
+ return (
+ <div className="glass rounded-xl p-4">
+ <h3 className="text-sm font-bold text-neutral-200 mb-1">
+ {S.ontology.importTitle}
+ </h3>
+ <p className="text-xs text-neutral-500 mb-3">{S.ontology.importHint}</p>
+
+ <input
+ ref={pick}
+ type="file"
+ accept=".owl,.rdf,.ttl,.xml,.n3"
+ className="hidden"
+ onChange={(e) => {
+ choose(e.target.files?.[0]);
+ e.target.value = "";
+ }}
+ />
+ <div className="flex items-center gap-2">
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={busy}
+ onClick={() => pick.current?.click()}
+ >
+ {file ? S.ontology.importChange : S.ontology.importPick}
+ </Button>
+ {file && (
+ <span className="text-xs text-neutral-400 truncate">
+ <span className="font-mono">{file.name}</span>
+ <span className="text-neutral-600">
+ {" "}
+ · {S.ontology.importSize(file.size)}
+ </span>
+ </span>
+ )}
+ {preview.isPending && (
+ <span className="text-xs text-neutral-500">
+ {S.ontology.importReading}
+ </span>
+ )}
+ </div>
+
+ {plan && (
+ <div className="mt-4">
+ <p className="text-[11px] uppercase tracking-[0.08em] text-neutral-600 u-num">
+ {S.ontology.importParsed(plan.format, plan.triples)}
+ </p>
+
+ {empty ? (
+ <p className="mt-2 text-sm text-neutral-500">
+ {S.ontology.importNothing}
+ </p>
+ ) : (
+ <>
+ {/* 三条警告在计数之前:人只会读第一屏 */}
+ <Warning
+ show={plan.functional_relations > 0}
+ tone="warn"
+ title={S.ontology.warnFunctional(plan.functional_relations)}
+ body={S.ontology.warnFunctionalBody}
+ items={plan.relations
+ .filter((r) => r.functional)
+ .map((r) => r.key)}
+ />
+ <Warning
+ show={plan.classes_without_description > 0}
+ tone="warn"
+ title={S.ontology.warnNoDescription(
+ plan.classes_without_description,
+ )}
+ body={S.ontology.warnNoDescriptionBody}
+ items={plan.classes
+ .filter((c) => !c.has_description)
+ .map((c) => c.key)}
+ />
+ <Warning
+ show={takenCount(plan) > 0}
+ tone="danger"
+ title={S.ontology.warnKeyTaken(takenCount(plan))}
+ body={S.ontology.warnKeyTakenBody}
+ items={[...plan.classes, ...plan.relations, ...plan.attributes]
+ .filter((i) => i.disposition === "key_taken")
+ .map(
+ (i) =>
+ `${i.key} — ${S.ontology.importTakenBy(i.conflict_with ?? null)}`,
+ )}
+ />
+
+ <div className="mt-3 grid gap-2">
+ <PlanRow
+ label={S.ontology.importClasses}
+ items={plan.classes}
+ />
+ <PlanRow
+ label={S.ontology.importRelations}
+ items={plan.relations}
+ />
+ <PlanRow
+ label={S.ontology.importAttributes}
+ items={plan.attributes}
+ note={
+ plan.attributes.length > 0
+ ? S.ontology.importAttributesLater
+ : undefined
+ }
+ />
+ </div>
+
+ {plan.unprojected.length > 0 && (
+ <details className="mt-3">
+ <summary className="cursor-pointer text-xs text-neutral-500 hover:text-neutral-300">
+ {S.ontology.importUnprojected} ({plan.unprojected.length})
+ </summary>
+ <p className="mt-1.5 text-[11px] text-neutral-600">
+ {S.ontology.importUnprojectedBody}
+ </p>
+ <ul className="mt-1.5 space-y-0.5">
+ {plan.unprojected.map(([iri, n]) => (
+ <li key={iri} className="flex gap-2 text-[11px]">
+ <span
+ className="font-mono text-neutral-500 truncate"
+ title={iri}
+ >
+ {shortIri(iri)}
+ </span>
+ <span className="u-num text-neutral-600 shrink-0">
+ ×{n}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </details>
+ )}
+
+ <div className="mt-4 flex items-center gap-2">
+ <Button
+ size="sm"
+ disabled={busy}
+ onClick={() => file && apply.mutate(file)}
+ >
+ {apply.isPending
+ ? S.ontology.importApplying
+ : S.ontology.importApply}
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={busy}
+ onClick={() => {
+ setFile(null);
+ preview.reset();
+ }}
+ >
+ {S.ontology.importCancel}
+ </Button>
+ </div>
+ </>
+ )}
+ </div>
+ )}
+
+ {/* 导入历史:谁在什么时候拿哪个文件动过本体。原文按 sha256 存着 */}
+ <div className="mt-5 border-t border-white/10 pt-3">
+ <h4 className="text-xs font-medium text-neutral-400 mb-2">
+ {S.ontology.importHistory}
+ </h4>
+ {!history.data?.imports.length ? (
+ <p className="text-xs text-neutral-600">
+ {S.ontology.importNoHistory}
+ </p>
+ ) : (
+ <ul className="space-y-1.5">
+ {history.data.imports.map((im) => (
+ <li key={im.id} className="flex items-baseline gap-2 text-xs">
+ <span className="font-mono text-neutral-300 truncate">
+ {im.filename}
+ </span>
+ <span className="u-num text-neutral-600 shrink-0">
+ {S.ontology.importSize(im.byte_size)}
+ </span>
+ <span className="ml-auto text-[11px] text-neutral-600 shrink-0">
+ {S.ontology.importBy(
+ im.imported_by_name ?? "—",
+ new Date(im.imported_at).toLocaleDateString(),
+ )}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function takenCount(p: ImportPlan) {
+ return [...p.classes, ...p.relations, ...p.attributes].filter(
+ (i) => i.disposition === "key_taken",
+ ).length;
+}
+
+/** IRI 尾巴才是人认得出的部分,前缀在列表里只占宽度 */
+function shortIri(iri: string) {
+ const i = Math.max(iri.lastIndexOf("#"), iri.lastIndexOf("/"));
+ return i < 0 ? iri : iri.slice(i + 1);
+}
+
+/** 一条警告:标题给数,正文一句给后果,条目折在 details 里 */
+function Warning({
+ show,
+ tone,
+ title,
+ body,
+ items,
+}: {
+ show: boolean;
+ tone: "warn" | "danger";
+ title: string;
+ body: string;
+ items: string[];
+}) {
+ if (!show) return null;
+ return (
+ <div
+ className={cn(
+ "mt-3 rounded-lg border px-3 py-2.5",
+ tone === "danger"
+ ? "border-rose-500/25 bg-rose-500/[0.06]"
+ : "border-amber-500/25 bg-amber-500/[0.06]",
+ )}
+ >
+ <p className="text-xs text-neutral-200">{title}</p>
+ <p className="mt-0.5 text-[11px] text-neutral-400">{body}</p>
+ {items.length > 0 && (
+ <details className="mt-1.5">
+ <summary className="cursor-pointer text-[11px] text-neutral-500 hover:text-neutral-300">
+ {items.length > 1 ? `${items.length} items` : "1 item"}
+ </summary>
+ <ul className="mt-1 space-y-0.5">
+ {items.map((it) => (
+ <li key={it} className="font-mono text-[11px] text-neutral-400">
+ {it}
+ </li>
+ ))}
+ </ul>
+ </details>
+ )}
+ </div>
+ );
+}
+
+/** 一段的去向计数:新建 / 更新 / 跳过,零的不显示 */
+function PlanRow({
+ label,
+ items,
+ note,
+}: {
+ label: string;
+ items: PlannedItem[];
+ note?: string;
+}) {
+ if (items.length === 0) return null;
+ const n = (d: PlannedItem["disposition"]) =>
+ items.filter((i) => i.disposition === d).length;
+ return (
+ <div className="rounded-lg bg-white/[0.03] px-3 py-2">
+ <div className="flex items-center gap-2">
+ <span className="text-xs text-neutral-300">{label}</span>
+ <span className="ml-auto flex items-center gap-1.5">
+ {n("create") > 0 && (
+ <Chip tone="success">
+ {S.ontology.importWillCreate(n("create"))}
+ </Chip>
+ )}
+ {n("update") > 0 && (
+ <Chip tone="info">{S.ontology.importWillUpdate(n("update"))}</Chip>
+ )}
+ {n("key_taken") > 0 && (
+ <Chip tone="neutral">
+ {S.ontology.importKeyTaken(n("key_taken"))}
+ </Chip>
+ )}
+ </span>
+ </div>
+ {note && <p className="mt-1 text-[11px] text-neutral-600">{note}</p>}
+ </div>
+ );
+}