Skip to content

World's first open-source enterprise world model.

A new knowledge base can start from a real vocabulary instead of ten seeds

WaylandYang92db693c3e47
diff --git a/Cargo.lock b/Cargo.lock
index 400792f0..ab52085e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4806,6 +4806,7 @@ dependencies = [
"chrono",
"dotenvy",
"feed-rs",
+ "flate2",
"futures-util",
"jsonwebtoken",
"reqwest",
diff --git a/Cargo.toml b/Cargo.toml
index fd01450c..82d78b86 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -43,6 +43,7 @@ figment = { version = "0.10", features = ["env"] }
dotenvy = "0.15"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
+flate2 = "1"
# Phase 1: 摄入/检索/LLM
utopia-ingest = { path = "crates/utopia-ingest" }
diff --git a/crates/utopia-ingest/src/ontology_rdf.rs b/crates/utopia-ingest/src/ontology_rdf.rs
index e589aca2..41faaa11 100644
--- a/crates/utopia-ingest/src/ontology_rdf.rs
+++ b/crates/utopia-ingest/src/ontology_rdf.rs
@@ -167,14 +167,26 @@ fn read_triples(bytes: &[u8], format: RdfFormat) -> anyhow::Result<Vec<Triple>>
object_lit,
});
};
+ // **相对 IRI 需要 base 才能解析。** 从字节读没有文档 URL,而 Turtle 规范说
+ // base 默认取文档自身的地址。给一个占位符:本体文件里的相对 IRI 几乎都是
+ // 文档级元数据(PROV-O 的 `<#> a owl:Ontology`),我们不消费 owl:Ontology 节点,
+ // 解析得过去就行。不给的话整个文件在第一个 `<#>` 上报
+ // "No scheme found in an absolute IRI" 而全军覆没
+ const BASE: &str = "urn:utopia:import";
match format {
RdfFormat::Turtle => {
- for r in oxttl::TurtleParser::new().for_reader(bytes) {
+ let p = oxttl::TurtleParser::new()
+ .with_base_iri(BASE)
+ .map_err(|e| anyhow::anyhow!("base IRI 无效:{e}"))?;
+ for r in p.for_reader(bytes) {
push(r?);
}
}
RdfFormat::RdfXml => {
- for r in oxrdfxml::RdfXmlParser::new().for_reader(bytes) {
+ let p = oxrdfxml::RdfXmlParser::new()
+ .with_base_iri(BASE)
+ .map_err(|e| anyhow::anyhow!("base IRI 无效:{e}"))?;
+ for r in p.for_reader(bytes) {
push(r?);
}
}
diff --git a/crates/utopia-server/Cargo.toml b/crates/utopia-server/Cargo.toml
index e6374eb8..f4acec6d 100644
--- a/crates/utopia-server/Cargo.toml
+++ b/crates/utopia-server/Cargo.toml
@@ -33,6 +33,7 @@ jsonwebtoken.workspace = true
dotenvy.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
+flate2.workspace = true
reqwest.workspace = true
feed-rs.workspace = true
diff --git a/crates/utopia-server/packs/README.md b/crates/utopia-server/packs/README.md
new file mode 100644
index 00000000..69dbb302
--- /dev/null
+++ b/crates/utopia-server/packs/README.md
@@ -0,0 +1,22 @@
+# 预制本体包
+
+来源文件按原样保存(gzip 压缩),由 `src/ontology_packs.rs` 用 `include_bytes!` 内嵌进二进制。
+
+**为什么内嵌而不是运行时下载**:README 承诺整套系统可以运行在完全离线的内网环境。
+运行时抓取会让这句话失效,也让构建不可复现(上游随时会发新版)。
+
+**为什么压缩**:未压缩合计 1.7 MB,压缩后 316 KB。这是个公开仓库,clone 体积是真实成本。
+`flate2` 本来就在依赖树里,解压是三行。
+
+| 文件 | 来源 | 许可 | 抓取日 |
+|---|---|---|---|
+| `schema-org.ttl.gz` | https://schema.org/version/latest/schemaorg-current-https.ttl | CC BY-SA 3.0 | 2026-08-30 |
+| `w3c-org.ttl.gz` | https://www.w3.org/ns/org.ttl | W3C Document License | 2026-08-30 |
+| `prov-o.ttl.gz` | https://www.w3.org/ns/prov.ttl | W3C Document License | 2026-08-30 |
+| `foaf.rdf.gz` | http://xmlns.com/foaf/spec/index.rdf | CC BY 1.0 | 2026-08-30 |
+| `iof-core.rdf.gz` | https://spec.industrialontologies.org/ontology/core/Core/ | MIT | 2026-08-30 |
+
+## 更新一个包
+
+重新抓取、`gzip -9c` 覆盖、更新 `ontology_packs.rs` 里的计数与本文件的抓取日。
+**不要改动原文内容**——投影只覆盖当下能消费的部分,原文保真是 [0001](../../../docs/decisions/0001-ontology-import-and-governance.md) 判据 1。
diff --git a/crates/utopia-server/packs/foaf.rdf.gz b/crates/utopia-server/packs/foaf.rdf.gz
new file mode 100644
index 00000000..b1ac0058
Binary files /dev/null and b/crates/utopia-server/packs/foaf.rdf.gz differ
diff --git a/crates/utopia-server/packs/iof-core.rdf.gz b/crates/utopia-server/packs/iof-core.rdf.gz
new file mode 100644
index 00000000..209fcf60
Binary files /dev/null and b/crates/utopia-server/packs/iof-core.rdf.gz differ
diff --git a/crates/utopia-server/packs/prov-o.ttl.gz b/crates/utopia-server/packs/prov-o.ttl.gz
new file mode 100644
index 00000000..0799cf53
Binary files /dev/null and b/crates/utopia-server/packs/prov-o.ttl.gz differ
diff --git a/crates/utopia-server/packs/schema-org.ttl.gz b/crates/utopia-server/packs/schema-org.ttl.gz
new file mode 100644
index 00000000..d0a1907e
Binary files /dev/null and b/crates/utopia-server/packs/schema-org.ttl.gz differ
diff --git a/crates/utopia-server/packs/w3c-org.ttl.gz b/crates/utopia-server/packs/w3c-org.ttl.gz
new file mode 100644
index 00000000..1d5a58b3
Binary files /dev/null and b/crates/utopia-server/packs/w3c-org.ttl.gz differ
diff --git a/crates/utopia-server/src/api/kbs.rs b/crates/utopia-server/src/api/kbs.rs
index d953eb74..374ba218 100644
--- a/crates/utopia-server/src/api/kbs.rs
+++ b/crates/utopia-server/src/api/kbs.rs
@@ -19,6 +19,12 @@ pub struct CreateKbReq {
pub description: Option<String>,
#[serde(default)]
pub visibility: Option<String>,
+ /// 起点本体包的 id,按给定顺序装。空 = 只有十个种子。
+ ///
+ /// **顺序有意义**:第一个包的类会认领同名的种子类(它们没有 IRI),
+ /// 后面的包撞名时查对齐表。schema.org 放第一个,别的包才对得上。
+ #[serde(default)]
+ pub ontology_packs: Vec<String>,
}
#[derive(Deserialize)]
@@ -83,6 +89,14 @@ pub async fn create(
}
utopia_store::access::set_kb_member(&state.pool, kb.id, user.id, "admin", Some(user.id))
.await?;
+ install_packs(
+ &state,
+ kb.id,
+ user.id,
+ &kb.ontology_lang,
+ &req.ontology_packs,
+ )
+ .await?;
let kb = utopia_store::kbs::get(&state.pool, kb.id).await?;
Ok(Json(kb))
}
@@ -262,3 +276,52 @@ pub async fn audit_log(
let events = utopia_store::audit::list_for_kb(&state.pool, id, 100).await?;
Ok(Json(json!({ "events": events })))
}
+
+/// 建库时装选中的本体包。
+///
+/// **种子本体先落地**:包里的类要认领同名的种子类(`schema:Organization` 接管
+/// `organization`),而认领的前提是那一行已经存在。`ensure_default_ontology`
+/// 平时是懒调的(首次读本体或首次抽取时),这里必须显式先跑一次。
+///
+/// **一个包失败不回滚已装的**:本体是加法,装了一半的库仍然可用,
+/// 而回滚要撤已经建好的类——那正是 0008 决定不做导入撤销的理由。
+/// 失败信息里带上是哪个包,让人知道从哪补。
+async fn install_packs(
+ state: &AppState,
+ kb_id: Uuid,
+ actor: Uuid,
+ lang: &str,
+ pack_ids: &[String],
+) -> ApiResult<()> {
+ if pack_ids.is_empty() {
+ return Ok(());
+ }
+ utopia_store::graph::ensure_default_ontology(&state.pool, kb_id, lang).await?;
+ for id in pack_ids {
+ let pack = crate::ontology_packs::get(id)
+ .ok_or_else(|| AppError::invalid("unknown_pack", format!("未知的本体包:{id}")))?;
+ let bytes = crate::ontology_packs::bytes(pack)?;
+ crate::owl_import::apply(state, kb_id, actor, pack.filename, &bytes)
+ .await
+ .map_err(|e| AppError::Other(anyhow::anyhow!("装本体包 {} 失败:{e}", pack.id)))?;
+ }
+ Ok(())
+}
+
+/// 可选的本体包清单,给建库界面。不需要登录之外的权限——它是静态数据。
+pub async fn list_packs(AuthUser(_): AuthUser) -> ApiResult<Json<serde_json::Value>> {
+ let packs: Vec<_> = crate::ontology_packs::PACKS
+ .iter()
+ .map(|p| {
+ json!({
+ "id": p.id,
+ "name": p.name,
+ "summary": p.summary,
+ "classes": p.classes,
+ "properties": p.properties,
+ "overlaps": p.overlaps,
+ })
+ })
+ .collect();
+ Ok(Json(json!({ "packs": packs })))
+}
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index 374d36b8..2dfa377e 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -57,6 +57,8 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
.delete(workspaces::delete),
)
.route("/workspaces/{id}/kbs", get(kbs::list).post(kbs::create))
+ // 建库界面用的静态清单,与具体工作区无关
+ .route("/ontology-packs", get(kbs::list_packs))
.route("/workspaces/{id}/my-kbs", get(kbs::my_kbs))
.route(
"/workspaces/{id}/settings",
diff --git a/crates/utopia-server/src/main.rs b/crates/utopia-server/src/main.rs
index 228ed389..5f00d156 100644
--- a/crates/utopia-server/src/main.rs
+++ b/crates/utopia-server/src/main.rs
@@ -12,7 +12,9 @@ mod ingest_sources;
mod llm_util;
mod mappings;
mod ontology_index;
+mod ontology_packs;
mod owl_import;
+mod pack_alignment;
mod pipeline;
mod predicate_match;
mod query_engine;
diff --git a/crates/utopia-server/src/ontology_packs.rs b/crates/utopia-server/src/ontology_packs.rs
new file mode 100644
index 00000000..7a0a51d4
--- /dev/null
+++ b/crates/utopia-server/src/ontology_packs.rs
@@ -0,0 +1,134 @@
+//! 预制本体包:建库时可选的起点。
+//!
+//! 十个种子关系一个类型签名都没有(`graph.rs` 的 `DEFAULT_RELATION_TYPES`),
+//! 而抽取提示词是支持签名的——`- buys_from (employee|team → *)`。没有签名,方向
+//! 就只能靠散文描述,而散文约束不了方向。schema.org 的 1521 个属性里 1488 个带
+//! domain + range,方向是**声明的**不是描述的。见 `docs/decisions/0008`。
+//!
+//! **文件内嵌进二进制**,不在运行时下载:README 承诺整套系统可以跑在完全离线的
+//! 内网环境,运行时抓取会让这句话失效。原文按 gzip 存放(1.7 MB → 316 KB),
+//! 解压在 [`bytes`]。
+
+use utopia_core::{AppError, AppResult};
+
+/// 一个可选的起点本体。
+///
+/// `classes` / `properties` 是**抓取当天数过的展示数字**,给建库界面用;
+/// 真正建了多少以导入返回的 plan 为准——投影只覆盖当下能消费的构造。
+pub struct Pack {
+ pub id: &'static str,
+ pub name: &'static str,
+ pub summary: &'static str,
+ /// 传给 `owl_import` 的文件名。**格式靠扩展名判定**(`RdfFormat::detect`),
+ /// 所以这里必须保留真实后缀。
+ pub filename: &'static str,
+ pub classes: u32,
+ pub properties: u32,
+ /// 与已选包重叠时给用户的提示;`None` = 与其他包基本不重叠
+ pub overlaps: Option<&'static str>,
+ gz: &'static [u8],
+}
+
+pub const PACKS: &[Pack] = &[
+ Pack {
+ id: "schema-org",
+ name: "schema.org",
+ summary: "通用词表:人、组织、产品、事件、创作。97.8% 的属性带类型签名。",
+ filename: "schema-org.ttl",
+ classes: 1010,
+ properties: 1676,
+ overlaps: None,
+ gz: include_bytes!("../packs/schema-org.ttl.gz"),
+ },
+ Pack {
+ id: "w3c-org",
+ name: "W3C Org",
+ summary: "组织架构:部门、职位、任期、汇报关系。补 schema.org 最弱的一块。",
+ filename: "w3c-org.ttl",
+ classes: 13,
+ properties: 34,
+ overlaps: Some("与 schema.org 撞名 6 处,已预先对齐"),
+ gz: include_bytes!("../packs/w3c-org.ttl.gz"),
+ },
+ Pack {
+ id: "prov-o",
+ name: "PROV-O",
+ summary: "溯源:某个结论由谁、在何时、依据什么产出。W3C 标准词汇。",
+ filename: "prov-o.ttl",
+ classes: 49,
+ properties: 69,
+ overlaps: Some("与 schema.org 撞名 4 处,已预先对齐"),
+ gz: include_bytes!("../packs/prov-o.ttl.gz"),
+ },
+ Pack {
+ id: "foaf",
+ name: "FOAF",
+ summary: "人与社交关系。核心概念 schema.org 已覆盖,按需选用。",
+ filename: "foaf.rdf",
+ classes: 12,
+ properties: 62,
+ overlaps: Some("与 schema.org 重叠 21%,是候选里最高的"),
+ gz: include_bytes!("../packs/foaf.rdf.gz"),
+ },
+ Pack {
+ id: "iof-core",
+ name: "IOF Core",
+ summary: "工业制造:Industry Ontology Foundry 的核心层。",
+ filename: "iof-core.rdf",
+ classes: 294,
+ properties: 75,
+ overlaps: None,
+ gz: include_bytes!("../packs/iof-core.rdf.gz"),
+ },
+];
+
+pub fn get(id: &str) -> Option<&'static Pack> {
+ PACKS.iter().find(|p| p.id == id)
+}
+
+/// 解压出原文。**每次调用都解一遍**——建库是低频动作,不值得为它常驻 1.7 MB。
+pub fn bytes(pack: &Pack) -> AppResult<Vec<u8>> {
+ use std::io::Read;
+ let mut out = Vec::new();
+ flate2::read::GzDecoder::new(pack.gz)
+ .read_to_end(&mut out)
+ .map_err(|e| AppError::Other(anyhow::anyhow!("本体包 {} 解压失败:{e}", pack.id)))?;
+ Ok(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// 每个包都能解压,且解出来的不是空文件。
+ /// `include_bytes!` 保证文件存在,但保证不了它是有效的 gzip。
+ #[test]
+ fn every_pack_decompresses() {
+ for p in PACKS {
+ let b = bytes(p).unwrap_or_else(|e| panic!("{}: {e}", p.id));
+ assert!(b.len() > 10_000, "{} 解出来只有 {} 字节", p.id, b.len());
+ }
+ }
+
+ /// 文件名后缀决定格式判定,写错了整个包会被当成另一种语法送进解析器。
+ #[test]
+ fn filenames_carry_a_format_suffix() {
+ for p in PACKS {
+ assert!(
+ p.filename.ends_with(".ttl") || p.filename.ends_with(".rdf"),
+ "{} 的文件名没有可判定的后缀:{}",
+ p.id,
+ p.filename
+ );
+ }
+ }
+
+ #[test]
+ fn ids_are_unique() {
+ let mut ids: Vec<_> = PACKS.iter().map(|p| p.id).collect();
+ ids.sort_unstable();
+ let n = ids.len();
+ ids.dedup();
+ assert_eq!(ids.len(), n, "包 id 有重复");
+ }
+}
diff --git a/crates/utopia-server/src/owl_import.rs b/crates/utopia-server/src/owl_import.rs
index e8efecda..54aff542 100644
--- a/crates/utopia-server/src/owl_import.rs
+++ b/crates/utopia-server/src/owl_import.rs
@@ -24,6 +24,9 @@ pub enum Disposition {
Update,
/// key 被另一个 IRI 占着 → 跳过并报告,不悄悄改名也不覆盖
KeyTaken,
+ /// key 被另一个 IRI 占着,但对齐表说那两个是**同一个东西** → 跳过且不算冲突。
+ /// 与 KeyTaken 分开,是因为它不需要人裁:少建一个重复的类正是想要的结果
+ Aligned,
}
/// 一个属性在这次导入里会不会被建出来,以及为什么。
@@ -203,6 +206,8 @@ pub async fn plan(
let mut classes = Vec::new();
for c in &proj.classes {
+ // 对齐表判为"同名不同义"时,用它声明的 key 顶替派生出来的那个
+ let mut renamed_key: Option<&'static str> = None;
let (disposition, conflict_with) = if let Some(prev) = claimed_class.get(c.key.as_str()) {
(Disposition::KeyTaken, Some((*prev).to_string()))
} else if e_by_iri.contains_key(c.iri.as_str()) {
@@ -218,19 +223,35 @@ pub async fn plan(
// 一个没建出来的东西——内置那几个基类一个子类都挂不上,
// 类型精化无从谈起。
None => (Disposition::Update, None),
- // 已经有一个**不同的** IRI:两个词汇表争同一个短标签,
- // 这是真冲突。不自动加后缀——那会让重导入认不出自己上次建的是哪个
- Some(_) => (Disposition::KeyTaken, existing.iri.clone()),
+ // 已经有一个**不同的** IRI:两个词汇表争同一个短标签。
+ // 先查预制包的对齐表——那是**声明**的处置,重导入结果一样,
+ // 所以下面那条"不自动加后缀"的理由对它不适用
+ Some(other) => match crate::pack_alignment::lookup(&c.iri, other) {
+ // 同义:已有的那个就是它,少建一个重复的类正是想要的
+ Some(crate::pack_alignment::Alignment::SameAs) => {
+ (Disposition::Aligned, existing.iri.clone())
+ }
+ // 同名不同义:换一个声明好的 key 建出来
+ Some(crate::pack_alignment::Alignment::Rename(k)) => {
+ renamed_key = Some(k);
+ (Disposition::Create, None)
+ }
+ // 表里没有:这是真冲突。不自动加后缀——那会让重导入
+ // 认不出自己上次建的是哪个
+ None => (Disposition::KeyTaken, existing.iri.clone()),
+ },
}
} else {
(Disposition::Create, None)
};
- if disposition != Disposition::KeyTaken {
- claimed_class.insert(c.key.as_str(), c.iri.as_str());
+ // 改名与原名都是借用(前者 'static,后者借自 proj),统一成一个引用用完再落地
+ let key: &str = renamed_key.unwrap_or(c.key.as_str());
+ if !matches!(disposition, Disposition::KeyTaken | Disposition::Aligned) {
+ claimed_class.insert(key, c.iri.as_str());
}
classes.push(PlannedItem {
iri: c.iri.clone(),
- key: c.key.clone(),
+ key: key.to_string(),
label: c.label.clone(),
has_description: !c.description.trim().is_empty(),
disposition,
@@ -323,6 +344,13 @@ pub async fn apply(
.map_err(utopia_core::AppError::Other)?;
let by_iri: HashMap<&str, &_> = proj.classes.iter().map(|c| (c.iri.as_str(), c)).collect();
+ // 已在库里的类:IRI → id。Aligned 要靠它把"同义的那个"接上父类引用
+ let existing_by_iri: HashMap<String, Uuid> =
+ utopia_store::graph::entity_types(&state.pool, kb_id)
+ .await?
+ .into_iter()
+ .filter_map(|t| t.iri.clone().map(|i| (i, t.id)))
+ .collect();
let mut created_classes = 0usize;
let mut updated_classes = 0usize;
// IRI → 本体里的 id,父类解析要用
@@ -337,7 +365,8 @@ pub async fn apply(
let id = utopia_store::ontology::create_entity_type_with_iri(
&state.pool,
kb_id,
- &c.key,
+ // **不是 `c.key`**:对齐表判为同名不同义时用的是改过的那个
+ &item.key,
&c.label,
&c.description,
&c.iri,
@@ -375,6 +404,15 @@ pub async fn apply(
}
}
// key 被占:报告过了,不动
+ // 同义:不建。但要把 IRI 指向已有那个类的 id,否则以它为父类的
+ // 子类会解析不到,整棵树在这里断掉
+ Disposition::Aligned => {
+ if let Some(target) = item.conflict_with.as_deref() {
+ if let Some(id) = existing_by_iri.get(target) {
+ id_of.insert(c.iri.clone(), *id);
+ }
+ }
+ }
Disposition::KeyTaken => {}
}
}
diff --git a/crates/utopia-server/src/pack_alignment.rs b/crates/utopia-server/src/pack_alignment.rs
new file mode 100644
index 00000000..89ec68f8
--- /dev/null
+++ b/crates/utopia-server/src/pack_alignment.rs
@@ -0,0 +1,280 @@
+//! 包与包之间的同名词处置。
+//!
+//! 导入撞 key 时,`owl_import` 的默认判断是 [`Disposition::KeyTaken`]——跳过并报告,
+//! 不自动加后缀。那条理由("重导入认不出自己上次建的是哪个")针对的是**猜**出来的
+//! 后缀;本模块给的是**声明**的处置,重导入结果一样,所以不受那条约束。
+//!
+//! 为什么需要它:预制包两两撞名约 20 处,而且分两类——
+//!
+//! - `org:Organization` 与 `schema:Organization` 是**同一个东西**,跳过是对的,
+//! 但不该报成"冲突"让用户去裁一件没得裁的事
+//! - `org:role`(组织里的职位)与 `schema:role`(演员饰演的角色)**只是同名**,
+//! 跳过等于丢掉 W3C Org 存在的理由
+//!
+//! 只覆盖预制包。用户手动导入的词汇表不在这里——那是明确的意图,撞名该报给他看。
+
+/// 同名词的处置。
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum Alignment {
+ /// 同义:已有的那个就是它,不必再建。跳过,但记作"已对齐"而非"冲突"
+ SameAs,
+ /// 同名不同义:改用这个 key 建出来
+ Rename(&'static str),
+}
+
+/// (进来的 IRI, 已占位的 IRI) → 处置。
+///
+/// 上游自己声明过的对齐优先抄:W3C Org 的文档声明了与 FOAF 的对应,
+/// PROV-O 声明了与 FOAF、Dublin Core 的对应。这里只记我们的包之间实际会撞的那些。
+const TABLE: &[(&str, &str, Alignment)] = &[
+ // ── W3C Org × schema.org ──────────────────────────────────────────
+ (
+ "http://www.w3.org/ns/org#Organization",
+ "https://schema.org/Organization",
+ Alignment::SameAs,
+ ),
+ (
+ "http://www.w3.org/ns/org#identifier",
+ "https://schema.org/identifier",
+ Alignment::SameAs,
+ ),
+ (
+ "http://www.w3.org/ns/org#location",
+ "https://schema.org/location",
+ Alignment::SameAs,
+ ),
+ // org:Role 是"职位所承载的角色"(与 Post、Membership 配套),
+ // schema:role 是创作作品里的饰演关系。同名,无关
+ (
+ "http://www.w3.org/ns/org#Role",
+ "https://schema.org/Role",
+ Alignment::Rename("org_role"),
+ ),
+ // org:member 是带任期的成员关系(经由 Membership 具体化),
+ // schema:member 是泛指的从属。粒度不同,两个都要
+ (
+ "http://www.w3.org/ns/org#member",
+ "https://schema.org/member",
+ Alignment::Rename("org_member"),
+ ),
+ (
+ "http://www.w3.org/ns/org#memberOf",
+ "https://schema.org/memberOf",
+ Alignment::Rename("org_member_of"),
+ ),
+ // ── PROV-O × schema.org ───────────────────────────────────────────
+ // prov:Agent 是 Person 与 Organization 的**超类**,不是同义词。
+ // 判成 SameAs 会把"施事者"这个抽象层整个抹掉
+ (
+ "http://www.w3.org/ns/prov#Agent",
+ "https://schema.org/agent",
+ Alignment::Rename("prov_agent"),
+ ),
+ // ── FOAF × schema.org ─────────────────────────────────────────────
+ (
+ "http://xmlns.com/foaf/0.1/Person",
+ "https://schema.org/Person",
+ Alignment::SameAs,
+ ),
+ (
+ "http://xmlns.com/foaf/0.1/Organization",
+ "https://schema.org/Organization",
+ Alignment::SameAs,
+ ),
+ (
+ "http://xmlns.com/foaf/0.1/Project",
+ "https://schema.org/Project",
+ Alignment::SameAs,
+ ),
+ (
+ "http://xmlns.com/foaf/0.1/name",
+ "https://schema.org/name",
+ Alignment::SameAs,
+ ),
+ (
+ "http://xmlns.com/foaf/0.1/knows",
+ "https://schema.org/knows",
+ Alignment::SameAs,
+ ),
+ (
+ "http://xmlns.com/foaf/0.1/givenName",
+ "https://schema.org/givenName",
+ Alignment::SameAs,
+ ),
+ (
+ "http://xmlns.com/foaf/0.1/familyName",
+ "https://schema.org/familyName",
+ Alignment::SameAs,
+ ),
+ (
+ "http://xmlns.com/foaf/0.1/gender",
+ "https://schema.org/gender",
+ Alignment::SameAs,
+ ),
+ (
+ "http://xmlns.com/foaf/0.1/logo",
+ "https://schema.org/logo",
+ Alignment::SameAs,
+ ),
+ (
+ "http://xmlns.com/foaf/0.1/thumbnail",
+ "https://schema.org/thumbnail",
+ Alignment::SameAs,
+ ),
+ (
+ "http://xmlns.com/foaf/0.1/title",
+ "https://schema.org/title",
+ Alignment::SameAs,
+ ),
+ (
+ "http://xmlns.com/foaf/0.1/member",
+ "https://schema.org/member",
+ Alignment::SameAs,
+ ),
+ // foaf:Agent 与 prov:Agent 同义(PROV-O 官方就是这么对齐的),
+ // 但都不等于 schema:agent
+ (
+ "http://xmlns.com/foaf/0.1/Agent",
+ "https://schema.org/agent",
+ Alignment::Rename("foaf_agent"),
+ ),
+ // foaf:status 是即时通讯时代的在线状态,schema:status 是订单/动作状态
+ (
+ "http://xmlns.com/foaf/0.1/status",
+ "https://schema.org/status",
+ Alignment::Rename("foaf_status"),
+ ),
+];
+
+/// 撞名时查这张表。两个 IRI 都不在预制包里就返回 `None`,走原来的 `KeyTaken`。
+pub fn lookup(incoming_iri: &str, existing_iri: &str) -> Option<Alignment> {
+ TABLE
+ .iter()
+ .find(|(a, b, _)| *a == incoming_iri && *b == existing_iri)
+ .map(|(_, _, al)| *al)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // 命名空间前缀只在测试里拼 IRI 用;表里写的是完整 IRI,
+ // 因为那是要跟投影结果逐字符比对的东西,拼接会掩盖笔误
+ const SCHEMA: &str = "https://schema.org/";
+ const ORG: &str = "http://www.w3.org/ns/org#";
+ const PROV: &str = "http://www.w3.org/ns/prov#";
+ const FOAF: &str = "http://xmlns.com/foaf/0.1/";
+
+ #[test]
+ fn same_as_and_rename_are_both_reachable() {
+ assert_eq!(
+ lookup(
+ &format!("{ORG}Organization"),
+ &format!("{SCHEMA}Organization")
+ ),
+ Some(Alignment::SameAs)
+ );
+ assert_eq!(
+ lookup(&format!("{ORG}Role"), &format!("{SCHEMA}Role")),
+ Some(Alignment::Rename("org_role"))
+ );
+ }
+
+ /// 不在表里的组合必须落回 `KeyTaken`——**默认是报告冲突,不是猜**
+ #[test]
+ fn unknown_pairs_fall_through() {
+ assert_eq!(
+ lookup("http://example.com/a#Foo", &format!("{SCHEMA}Foo")),
+ None
+ );
+ assert_eq!(
+ lookup(&format!("{PROV}Entity"), "http://example.com/b#Entity"),
+ None
+ );
+ }
+
+ /// 方向敏感:表是 (进来的, 已占的),反过来查不到。
+ /// 装包顺序不同时命中的是不同的条目,不该靠对称性蒙混
+ #[test]
+ fn lookup_is_directional() {
+ assert!(lookup(
+ &format!("{SCHEMA}Organization"),
+ &format!("{ORG}Organization")
+ )
+ .is_none());
+ }
+
+ /// Rename 出来的 key 必须过 `validate_key` 那套约束:小写字母数字下划线、不超 40
+ #[test]
+ fn renamed_keys_are_valid() {
+ for (_, _, al) in TABLE {
+ if let Alignment::Rename(k) = al {
+ assert!(k.len() <= 40, "{k} 超过 40 字符");
+ assert!(
+ k.chars()
+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'),
+ "{k} 含非法字符"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn no_duplicate_pairs() {
+ let mut seen: Vec<(&str, &str)> = TABLE.iter().map(|(a, b, _)| (*a, *b)).collect();
+ let n = seen.len();
+ seen.sort_unstable();
+ seen.dedup();
+ assert_eq!(seen.len(), n, "对齐表里有重复的 (进来, 已占) 组合");
+ }
+
+ /// FOAF 常量在测试外没被引用,这里确认它拼对了
+ #[test]
+ fn foaf_namespace_is_used() {
+ assert!(lookup(&format!("{FOAF}Person"), &format!("{SCHEMA}Person")).is_some());
+ }
+}
+
+/// 对齐表里的 IRI 必须真的出现在包里。
+///
+/// 表是手写的字符串,写错一个字符它就静默失效——撞名照样走 `KeyTaken`,
+/// 只是再也不会命中。上游改前缀(schema.org 从 `http://` 迁到 `https://` 就发生过)
+/// 也是同一种失效。所以拿真包跑一遍投影,逐条核对。
+#[cfg(test)]
+mod against_real_packs {
+ use super::*;
+ use std::collections::HashSet;
+ use utopia_ingest::ontology_rdf::{project, RdfFormat};
+
+ /// 把所有预制包投影一遍,收集出现过的 IRI
+ fn all_iris() -> HashSet<String> {
+ let mut out = HashSet::new();
+ for p in crate::ontology_packs::PACKS {
+ let bytes = crate::ontology_packs::bytes(p).expect(p.id);
+ let fmt = RdfFormat::detect(p.filename, &bytes);
+ let proj = project(&bytes, fmt).unwrap_or_else(|e| panic!("{} 投影失败:{e}", p.id));
+ out.extend(proj.classes.iter().map(|c| c.iri.clone()));
+ out.extend(proj.properties.iter().map(|p| p.iri.clone()));
+ }
+ out
+ }
+
+ #[test]
+ fn every_alignment_iri_exists_in_some_pack() {
+ let iris = all_iris();
+ let mut missing = Vec::new();
+ for (incoming, existing, _) in TABLE {
+ if !iris.contains(*incoming) {
+ missing.push(*incoming);
+ }
+ if !iris.contains(*existing) {
+ missing.push(*existing);
+ }
+ }
+ assert!(
+ missing.is_empty(),
+ "对齐表里这些 IRI 在任何预制包里都找不到,表已失效:\n {}",
+ missing.join("\n ")
+ );
+ }
+}