Skip to content

World's first open-source enterprise world model.

Wordings that carry a value can become attributes (#77)

WaylandYangd0c1b958a50c
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index ed274de2..0b8ce8b7 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -684,3 +684,24 @@ pub struct TypeCandidate {
pub kind: Option<String>,
pub distance: f32,
}
+
+/// 一个被记下来、但本体里没有对应属性的**字面值**说法。
+///
+/// 跟 [`ProposedPredicate`] 是一对:那个是宾语指向实体的("收购"),
+/// 这个是宾语是字面值的("成立日期 = 2015")。两者不能混——提案要产出的东西
+/// 不一样(关系 vs 属性),而混起来的后果具体:一条 `founding_date` 会变成
+/// 一条指向「2015」这个假实体的边。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct ProposedAttribute {
+ pub form: String,
+ pub fact_count: i64,
+ pub doc_count: i64,
+ /// 一条样例值(`"2015"`、`1200`),让人一眼看出这是什么类型的数
+ pub example: Option<String>,
+ /// 这个说法**实际挂在哪些类上**(主语的类型)。
+ ///
+ /// 属性必须声明 domain,而 domain 猜错的代价是硬的:主语类型对不上
+ /// 就整条丢弃(`attr_domain_mismatch`)。所以不问模型,直接从数据里取——
+ /// 事实已经在那儿了,它们的主语是什么类是事实,不是判断
+ pub domain_keys: Vec<String>,
+}
diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rs
index a8ac107d..302e3c8b 100644
--- a/crates/utopia-server/src/api/ontology_routes.rs
+++ b/crates/utopia-server/src/api/ontology_routes.rs
@@ -373,19 +373,18 @@ pub async fn build_proposals(
let client = llm_util::chat_client(&settings)
.ok_or_else(|| AppError::invalid("no_chat_model", "Chat model not configured"))?;
- // 只取这一遍**产得出提案**的那两类。attribute_type 的信号(未知谓词带字面值)
- // 也在这张表里,但下面的 JSON 骨架只有 entity_types / relation_types——
- // 把属性信号喂进去,模型只会照着建一个关系,而那正是它不该是的东西。
- // 属性提案归本体消解那一遍(0001 P3),不在这里凑合
- let misses: Vec<_> = utopia_store::ontology::list_misses(&state.pool, kb_id)
- .await?
- .into_iter()
- .filter(|m| m.kind != "attribute_type")
- .collect();
- // 表层谓词比 misses 多一样东西:它连着具体事实,所以提案能承诺"改写 N 条"
+ let misses = utopia_store::ontology::list_misses(&state.pool, kb_id).await?;
+ // 表层谓词比 misses 多一样东西:它连着具体事实,所以提案能承诺"改写 N 条"。
+ //
+ // **两条线严格分开**,按宾语是实体还是字面值:`收购` 要的是一条关系,
+ // `founding_date = "2015"` 要的是一个属性。混起来的后果具体——后者会被
+ // 提成关系,于是长出一条指向「2015」这个假实体的边
let forms = utopia_store::graph::proposed_predicates(&state.pool, kb_id).await?;
- if misses.is_empty() && forms.is_empty() {
- return Ok(json!({ "entity_types": [], "relation_types": [] }));
+ let value_forms = utopia_store::graph::proposed_attributes(&state.pool, kb_id).await?;
+ if misses.is_empty() && forms.is_empty() && value_forms.is_empty() {
+ return Ok(json!({
+ "entity_types": [], "relation_types": [], "attribute_types": [], "map_to": []
+ }));
}
// **本体的相关切片,不是它的全文。**
@@ -437,12 +436,44 @@ pub async fn build_proposals(
)
.await
.unwrap_or_default();
+ // 属性那一路:只在属性里找。这里若不限 kind,"成立日期"最近的往往是
+ // 某条关系,模型就会把一个字面值映射到一条边上去
+ let attr_probes: Vec<String> = value_forms
+ .iter()
+ .map(|f| match f.example.as_deref() {
+ Some(ex) if !ex.is_empty() => format!("{} = {ex}", f.form),
+ _ => f.form.clone(),
+ })
+ .chain(
+ misses
+ .iter()
+ .filter(|m| m.kind == "attribute_type")
+ .map(|m| m.key.clone()),
+ )
+ .collect();
+ let per_attr = crate::ontology_index::nearest_for_each(
+ state,
+ kb_id,
+ &attr_probes,
+ CANDIDATES_PER_PROBE,
+ crate::ontology_index::Target::Predicate(Some("attribute")),
+ )
+ .await
+ .unwrap_or_default();
// 并集去重:几个说法常常指向同一个候选,逐个说法各列一遍是白费令牌
let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut candidate_lines: Vec<String> = Vec::new();
// 模型抄回来的 key 要能对回本体:候选表同时按 key、归一化 key、标签建索引
let mut by_name: std::collections::HashMap<String, String> = std::collections::HashMap::new();
- for c in per_pred.iter().chain(per_class.iter()).flatten() {
+ // 每个候选是关系还是属性。映射到已有类型时,采纳走哪条改写路径由它定
+ let mut kind_of_key: std::collections::HashMap<String, String> =
+ std::collections::HashMap::new();
+ for c in per_pred
+ .iter()
+ .chain(per_class.iter())
+ .chain(per_attr.iter())
+ .flatten()
+ {
if !seen.insert(c.key.clone()) {
continue;
}
@@ -450,6 +481,7 @@ pub async fn build_proposals(
by_name.insert(normalize_name(&c.label), c.key.clone());
// 关系行自带 relation / attribute,类行没有 kind
let kind = c.kind.as_deref().unwrap_or("entity type");
+ kind_of_key.insert(c.key.clone(), kind.to_string());
let d = c.description.trim();
// **标签只在它确实多说了点什么的时候才写。**
// 导进来的本体里 label 常常只是 key 的驼峰写法(acquired_from /
@@ -504,6 +536,26 @@ pub async fn build_proposals(
})
.collect();
+ // 字面值那一路多带两样:一条样例值(模型据此判断该是 number 还是 date),
+ // 和这个说法实际挂在哪些类上。后者不是给模型看的,是采纳时直接拿来当
+ // domain 的——属性的 domain 猜错,主语类型对不上就整条丢弃
+ let value_lines: Vec<String> = value_forms
+ .iter()
+ .map(|f| {
+ format!(
+ "- \"{}\" on {} fact(s), value e.g. {}, seen on: {}",
+ f.form,
+ f.fact_count,
+ f.example.as_deref().unwrap_or("-"),
+ if f.domain_keys.is_empty() {
+ "-".to_string()
+ } else {
+ f.domain_keys.join(", ")
+ }
+ )
+ })
+ .collect();
+
let prompt = format!(
"You are an ontology engineer.\n\
\n\
@@ -516,6 +568,14 @@ pub async fn build_proposals(
These predicates were taken from the source text because nothing in the ontology fit. \
Their facts are currently filed under \"related_to\", which says nothing:\n{}\n\
\n\
+ These carried a literal VALUE rather than pointing at another entity, so each one \
+ wants an attribute, never a relation. Turning one into a relation manufactures an \
+ entity out of the value — a node named \"2015\" that stands for nothing:\n{}\n\
+ \n\
+ Each wording gets exactly ONE answer. Do not both map it and propose for it, and do \
+ not propose it as a relation and as an attribute — a wording listed above as carrying \
+ a value is an attribute, full stop.\n\
+ \n\
For each wording, decide one of two things.\n\
\n\
**If one of the candidates above already means it, map to it** — name that \
@@ -533,6 +593,9 @@ pub async fn build_proposals(
because a word was frequent.\n\
- \"functional\" must be false unless the relation truly permits at most one object per \
subject at a time. Getting this wrong makes the temporal engine manufacture conflicts.\n\
+ - An attribute needs a \"datatype\": text, number, date or bool. Read it off the example \
+ value. Choose text when unsure — a value that will not convert to the declared type \
+ is dropped, and a date stored as text is still the value.\n\
\n\
Every proposal needs a \"description\" as well as a \"reason\", and they are not the \
same thing. The reason argues for adding it and is read by a person. **The description \
@@ -544,6 +607,7 @@ pub async fn build_proposals(
Output exactly one JSON object:\n\
{{\"entity_types\":[{{\"key\":\"snake_case\",\"label\":\"Display Name\",\"description\":\"what belongs here, and what does not\",\"reason\":\"why add it\"}}],\n\
\"relation_types\":[{{\"key\":\"snake_case\",\"label\":\"display label\",\"temporal\":\"state|event|eternal\",\"functional\":false,\"forms\":[\"surface spellings this covers\"],\"description\":\"what this relation asserts, and what it does not\",\"reason\":\"why add it\"}}],\n\
+ \"attribute_types\":[{{\"key\":\"snake_case\",\"label\":\"display label\",\"datatype\":\"text|number|date|bool\",\"unit\":\"optional, e.g. CNY\",\"forms\":[\"surface spellings this covers\"],\"description\":\"what this attribute records, and what it does not\",\"reason\":\"why add it\"}}],\n\
\"map_to\":[{{\"key\":\"an existing key, copied from the candidate list above\",\"forms\":[\"surface spellings that mean it\"],\"reason\":\"why these are the same thing\"}}]}}\n\
\n\
Language, and it overrides the skeleton above — that skeleton is written in English \
@@ -554,6 +618,7 @@ pub async fn build_proposals(
candidates_block,
miss_lines.join("\n"),
form_lines.join("\n"),
+ value_lines.join("\n"),
lang_name(&kb.ontology_lang),
lang_name(reason_lang)
);
@@ -568,7 +633,15 @@ pub async fn build_proposals(
let block = utopia_extract::json_block(&reply).map_err(AppError::Other)?;
let mut proposals: serde_json::Value =
serde_json::from_str(&block).map_err(|e| AppError::Other(e.into()))?;
- resolve_map_targets(&mut proposals, &by_name);
+ resolve_map_targets(&mut proposals, &by_name, &kind_of_key);
+ // 说法归哪一档,服务端说了算——它手里有事实。实测模型会把同一个
+ // \"founded_in\" 既提成关系又提成属性,两条都采纳就是同一批事实被抢两次
+ let value_only: std::collections::HashSet<&str> =
+ value_forms.iter().map(|f| f.form.as_str()).collect();
+ let entity_only: std::collections::HashSet<&str> =
+ forms.iter().map(|f| f.form.as_str()).collect();
+ keep_forms(&mut proposals, "relation_types", &entity_only, &value_only);
+ keep_forms(&mut proposals, "attribute_types", &value_only, &entity_only);
Ok(proposals)
}
@@ -578,9 +651,12 @@ pub async fn build_proposals(
/// 而不是 `acquired_from`。**这一步必须在服务端做**:界面上那个"用已有的"
/// 按钮承诺的是把一批事实挂到某个已有谓词上,key 对不上时它只会报错,
/// 而承诺已经说出去了。对不上就不该显示这条。
+/// 顺带标上目标是关系还是属性:采纳时两条路的改写不一样,而模型答的是
+/// 一个 key,看不出这个 key 落在哪张表的哪一档。
fn resolve_map_targets(
proposals: &mut serde_json::Value,
by_name: &std::collections::HashMap<String, String>,
+ kind_of_key: &std::collections::HashMap<String, String>,
) {
let Some(items) = proposals.get_mut("map_to").and_then(|v| v.as_array_mut()) else {
return;
@@ -591,6 +667,10 @@ fn resolve_map_targets(
};
match by_name.get(&normalize_name(raw)) {
Some(real) => {
+ m["kind"] = json!(kind_of_key
+ .get(real)
+ .map(String::as_str)
+ .unwrap_or("relation"));
m["key"] = json!(real);
true
}
@@ -602,6 +682,37 @@ fn resolve_map_targets(
});
}
+/// 只保留说法确实属于这一档的提案,并把不属于的那些说法从 `forms` 里剔掉。
+///
+/// **判据在服务端手里**:一个说法带的是字面值还是实体宾语,事实里写着,
+/// 不必问模型。实测模型会把同一个 `founded_in` 既提成关系又提成属性——
+/// 两条都采纳的话,同一批事实被抢两次,先跑的那条赢,结果取决于循环顺序。
+///
+/// `forms` 全被剔光的提案整条丢掉:它承诺的"改写 N 条"已经是零了。
+fn keep_forms(
+ proposals: &mut serde_json::Value,
+ section: &str,
+ mine: &std::collections::HashSet<&str>,
+ theirs: &std::collections::HashSet<&str>,
+) {
+ let Some(items) = proposals.get_mut(section).and_then(|v| v.as_array_mut()) else {
+ return;
+ };
+ items.retain_mut(|p| {
+ let Some(forms) = p.get_mut("forms").and_then(|v| v.as_array_mut()) else {
+ // 没有 forms 的提案只是"加一个类型",不改写事实,与归档无关
+ return true;
+ };
+ forms.retain(|f| {
+ let Some(s) = f.as_str() else { return false };
+ // 另一档明确认领的才剔掉。两边都不认识的说法(比如来自 misses
+ // 而不是表层谓词)原样留着——剔掉它等于替模型否决了一条提案
+ !theirs.contains(s) || mine.contains(s)
+ });
+ !forms.is_empty()
+ });
+}
+
/// key 与标签的比较形式:小写,只留字母数字。
///
/// **分隔符整个扔掉**,因为要对齐的正是分隔符的差异:`acquiredFrom`、
@@ -640,6 +751,17 @@ pub struct AdoptReq {
pub inverse_functional: bool,
/// 归入这个关系的表层说法("available_on"、"available through"…)
pub forms: Vec<String>,
+ /// `relation`(缺省)或 `attribute`。
+ ///
+ /// 属性走另一条改写路径:宾语是字面值,要按 datatype 换算过才能落到
+ /// 新属性上;domain 也不由请求带,从事实的主语类型里取
+ #[serde(default)]
+ pub kind: Option<String>,
+ /// 属性专用:text | number | date | bool
+ #[serde(default)]
+ pub datatype: Option<String>,
+ #[serde(default)]
+ pub unit: Option<String>,
}
/// 采纳一个表层谓词:建关系类型 **并把等着它的 related_to 事实改写过去**。
@@ -661,6 +783,9 @@ pub async fn adopt_predicate(
if req.forms.is_empty() {
return Err(AppError::invalid("forms_required", "forms cannot be empty").into());
}
+ if req.kind.as_deref() == Some("attribute") {
+ return adopt_attribute(&state, &user, kb_id, &req).await;
+ }
let predicate_id = if req.existing {
// 按 key 找已有的那一条。找不到就报错而不是退回新建——
// 前端说的是"映射到已有的",静默改成新建就是它最不想要的结果
@@ -912,11 +1037,213 @@ fn lang_name(code: &str) -> &'static str {
}
}
+/// 采纳一个**字面值**说法:建(或指向已有的)属性,并把等着它的事实改挂过去。
+///
+/// 跟关系那条路有三处不同,每一处都是属性特有的:
+///
+/// 1. **domain 从数据里取,不由请求带。** 属性必须声明能挂在哪些类下,而猜错
+/// 的代价是硬的——主语类型对不上就整条丢弃(`attr_domain_mismatch`)。
+/// 这些事实的主语现在是什么类是事实不是判断,直接读。
+/// 2. **值要按 datatype 换算。** 库里存的是抽取当时的原样(字符串 "2015"),
+/// 落到一个 date 属性上得先变成日期。
+/// 3. **换不出来的不改写。** 宁可让它继续挂在兜底谓词上等下一次,也不把
+/// 一个换不动的值硬塞进类型化的属性里——那是"宁缺勿脏"的同一条。
+async fn adopt_attribute(
+ state: &AppState,
+ user: &utopia_core::models::User,
+ kb_id: Uuid,
+ req: &AdoptReq,
+) -> ApiResult<Json<serde_json::Value>> {
+ let spec = AttributeAdoption {
+ key: req.key.trim(),
+ label: req.label.trim(),
+ description: req.description.as_deref().unwrap_or("").trim(),
+ datatype: req.datatype.as_deref().unwrap_or("text"),
+ unit: req.unit.as_deref().map(str::trim).filter(|s| !s.is_empty()),
+ forms: &req.forms,
+ existing: req.existing,
+ };
+ let done = adopt_attribute_core(state, kb_id, &spec).await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "ontology.attribute_adopted",
+ "relation_type",
+ Some(done.attribute_id),
+ json!({ "key": spec.key, "forms": req.forms, "existing": req.existing,
+ "remapped": done.remapped, "unconvertible": done.unconvertible }),
+ )
+ .await;
+ // unconvertible 要回给调用方:改写了 3 条、丢下 2 条,界面得说得出后半句
+ Ok(Json(json!({
+ "id": done.attribute_id, "batch": done.batch_id,
+ "remapped": done.remapped, "unconvertible": done.unconvertible
+ })))
+}
+
+/// 一次属性采纳要的全部输入。
+pub(crate) struct AttributeAdoption<'a> {
+ pub key: &'a str,
+ pub label: &'a str,
+ pub description: &'a str,
+ pub datatype: &'a str,
+ pub unit: Option<&'a str>,
+ pub forms: &'a [String],
+ /// true = key 指的是已有属性,只改写、不新建
+ pub existing: bool,
+}
+
+pub(crate) struct AttributeAdopted {
+ pub attribute_id: Uuid,
+ pub batch_id: Uuid,
+ pub remapped: u32,
+ /// 值换不动那个 datatype、因而**没有**被改写的条数。
+ /// 必须往上传:改写了 3 条、丢下 2 条,只报前半句就是报喜不报忧
+ pub unconvertible: usize,
+}
+
+/// 建(或指向已有的)属性,并把等着它的字面值事实改挂过去。人工与自动共用。
+pub(crate) async fn adopt_attribute_core(
+ state: &AppState,
+ kb_id: Uuid,
+ spec: &AttributeAdoption<'_>,
+) -> Result<AttributeAdopted, AppError> {
+ // 先把待改写的事实取出来:它既定 domain,也定值换不换得动
+ let facts = utopia_store::graph::value_facts_for_forms(&state.pool, kb_id, spec.forms).await?;
+ let attribute_id = if spec.existing {
+ utopia_store::ontology::relation_type_id_by_key(&state.pool, kb_id, spec.key)
+ .await?
+ .ok_or_else(|| {
+ AppError::invalid("unknown_relation_key", "no relation type with that key")
+ })?
+ } else {
+ // **domain 从数据里取。** 属性必须声明能挂在哪些类下,猜错的代价是硬的:
+ // 主语类型对不上就整条丢弃。这些事实的主语现在是什么类是事实,不是判断
+ let mut domains: Vec<Uuid> = facts.iter().map(|(_, type_id, _)| *type_id).collect();
+ domains.sort_unstable();
+ domains.dedup();
+ if domains.is_empty() {
+ return Err(AppError::invalid(
+ "no_facts_for_forms",
+ "nothing is waiting on those wordings",
+ ));
+ }
+ utopia_store::ontology::create_relation_type(
+ &state.pool,
+ kb_id,
+ spec.key,
+ spec.label,
+ "state",
+ // 建议方不替时态引擎做决定:functional 会驱动它自动闭合旧值
+ false,
+ false,
+ spec.description,
+ "attribute",
+ &domains,
+ &[],
+ Some(spec.datatype),
+ spec.unit,
+ )
+ .await?
+ };
+
+ // 换算按**库里那一条**的 datatype,不按请求——指向已有属性时请求里根本
+ // 没有 datatype,而即便有,也该听本体的
+ let datatype = utopia_store::ontology::relation_type_datatype(&state.pool, attribute_id)
+ .await?
+ .unwrap_or_else(|| "text".to_string());
+ let mut rewrites: Vec<(Uuid, serde_json::Value)> = Vec::new();
+ let mut unconvertible = 0usize;
+ for (fact_id, _, object_value) in &facts {
+ // 抽取写进去的形状是 {"value": …},取里面那一层来换算
+ let raw = object_value.get("value").unwrap_or(object_value);
+ match utopia_extract::normalize_attr_value(&datatype, raw) {
+ Some(v) => rewrites.push((*fact_id, json!({ "value": v }))),
+ // 换不动的**不改写**:宁可让它继续挂在兜底谓词上等下一次,
+ // 也不把一个换不动的值硬塞进类型化的属性里
+ None => unconvertible += 1,
+ }
+ }
+ let (batch_id, remapped) =
+ utopia_store::graph::adopt_value_facts(&state.pool, kb_id, attribute_id, &rewrites).await?;
+ for form in spec.forms {
+ let _ =
+ utopia_store::ontology::clear_miss(&state.pool, kb_id, "attribute_type", form).await;
+ }
+ Ok(AttributeAdopted {
+ attribute_id,
+ batch_id,
+ remapped,
+ unconvertible,
+ })
+}
+
+/// 映射到**已有属性**:不建东西,只把这些说法的字面值事实挂过去。
+pub(crate) async fn adopt_attribute_existing(
+ state: &AppState,
+ kb_id: Uuid,
+ key: &str,
+ forms: &[String],
+) -> Result<(Uuid, u32), AppError> {
+ let done = adopt_attribute_core(
+ state,
+ kb_id,
+ &AttributeAdoption {
+ key,
+ label: "",
+ description: "",
+ datatype: "text",
+ unit: None,
+ forms,
+ existing: true,
+ },
+ )
+ .await?;
+ Ok((done.batch_id, done.remapped))
+}
+
+/// 自动扩本体那条路的入口。参数摊开而不是传 `AdoptReq`——那个结构是 HTTP
+/// 请求体,自动路径没有请求。
+#[allow(clippy::too_many_arguments)]
+pub(crate) async fn adopt_attribute_auto(
+ state: &AppState,
+ kb_id: Uuid,
+ key: &str,
+ label: &str,
+ description: &str,
+ datatype: &str,
+ unit: Option<&str>,
+ forms: &[String],
+) -> Result<(Uuid, u32), AppError> {
+ let done = adopt_attribute_core(
+ state,
+ kb_id,
+ &AttributeAdoption {
+ key,
+ label,
+ description,
+ datatype,
+ unit,
+ forms,
+ existing: false,
+ },
+ )
+ .await?;
+ if done.unconvertible > 0 {
+ tracing::info!(
+ %kb_id, key, dropped = done.unconvertible,
+ "有值换不动这个 datatype,那些事实留在兜底谓词上"
+ );
+ }
+ Ok((done.batch_id, done.remapped))
+}
+
#[cfg(test)]
mod tests {
use super::{normalize_name, resolve_map_targets};
use serde_json::json;
- use std::collections::HashMap;
+ use std::collections::{HashMap, HashSet};
#[test]
fn names_align_across_spellings() {
@@ -953,7 +1280,7 @@ mod tests {
// 连 key 都没有
{"forms": ["x"]},
]});
- resolve_map_targets(&mut p, &by_name);
+ resolve_map_targets(&mut p, &by_name, &HashMap::new());
let items = p["map_to"].as_array().unwrap();
assert_eq!(items.len(), 2);
assert_eq!(items[0]["key"], "acquired_from");
@@ -963,7 +1290,53 @@ mod tests {
#[test]
fn proposals_without_a_map_to_section_are_left_alone() {
let mut p = json!({"entity_types": [], "relation_types": []});
- resolve_map_targets(&mut p, &HashMap::new());
+ resolve_map_targets(&mut p, &HashMap::new(), &HashMap::new());
assert!(p.get("map_to").is_none());
}
+
+ #[test]
+ fn a_wording_that_carries_a_value_cannot_also_become_a_relation() {
+ // 实测过的形状:模型把同一个 founded_in 既提成关系又提成属性。
+ // 两条都采纳的话同一批事实被抢两次,谁先跑谁赢
+ let value_only: HashSet<&str> = ["founded_in", "registered_capital"].into_iter().collect();
+ let entity_only: HashSet<&str> = ["acquires"].into_iter().collect();
+ let mut p = json!({
+ "relation_types": [
+ {"key": "founded", "forms": ["founded_in", "founding date"]},
+ {"key": "acquires", "forms": ["acquires"]}
+ ],
+ "attribute_types": [
+ {"key": "founding_year", "forms": ["founded_in"]},
+ {"key": "registered_capital", "forms": ["registered_capital"]}
+ ]
+ });
+ super::keep_forms(&mut p, "relation_types", &entity_only, &value_only);
+ super::keep_forms(&mut p, "attribute_types", &value_only, &entity_only);
+
+ let rels = p["relation_types"].as_array().unwrap();
+ // founded 只剩 "founding date"——那个说法两边都不认识,不该替模型否决
+ assert_eq!(rels.len(), 2);
+ assert_eq!(rels[0]["forms"].as_array().unwrap().len(), 1);
+ assert_eq!(rels[0]["forms"][0], "founding date");
+ assert_eq!(rels[1]["key"], "acquires");
+ // 属性那边一条不动
+ assert_eq!(p["attribute_types"].as_array().unwrap().len(), 2);
+ }
+
+ #[test]
+ fn a_proposal_left_with_no_wordings_is_dropped() {
+ // forms 被剔光 = 它承诺的"改写 N 条"已经是零,留着只会让人点一下什么也没发生
+ let value_only: HashSet<&str> = ["founded_in"].into_iter().collect();
+ let mut p = json!({"relation_types": [{"key": "founded", "forms": ["founded_in"]}]});
+ super::keep_forms(&mut p, "relation_types", &HashSet::new(), &value_only);
+ assert!(p["relation_types"].as_array().unwrap().is_empty());
+ }
+
+ #[test]
+ fn a_type_proposal_without_wordings_is_left_alone() {
+ // 没有 forms 的提案只是"加一个类型",不改写任何事实,与归档无关
+ let mut p = json!({"entity_types": [{"key": "platform", "label": "Platform"}]});
+ super::keep_forms(&mut p, "entity_types", &HashSet::new(), &HashSet::new());
+ assert_eq!(p["entity_types"].as_array().unwrap().len(), 1);
+ }
}
diff --git a/crates/utopia-server/src/bootstrap_ontology.rs b/crates/utopia-server/src/bootstrap_ontology.rs
index ff33071e..8bc6d39e 100644
--- a/crates/utopia-server/src/bootstrap_ontology.rs
+++ b/crates/utopia-server/src/bootstrap_ontology.rs
@@ -197,6 +197,56 @@ pub async fn bootstrap_ontology(state: &AppState, kb_id: Uuid) -> anyhow::Result
}
}
+ // 属性那一档:宾语是字面值的说法。
+ //
+ // domain 不从提案里读——它从这些事实的主语类型里取,见 adopt_attribute。
+ // 值换不动的那些不改写,继续挂在兜底谓词上等下一次
+ let attrs = proposals
+ .get("attribute_types")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+ for p in &attrs {
+ let (Some(key), Some(label)) = (str_of(p, "key"), str_of(p, "label")) else {
+ continue;
+ };
+ let forms: Vec<String> = p
+ .get("forms")
+ .and_then(|v| v.as_array())
+ .map(|a| {
+ a.iter()
+ .filter_map(|s| s.as_str().map(String::from))
+ .collect()
+ })
+ .unwrap_or_default();
+ if forms.is_empty() {
+ continue;
+ }
+ match ontology_routes::adopt_attribute_auto(
+ state,
+ kb_id,
+ key,
+ label,
+ str_of(p, "description")
+ .or_else(|| str_of(p, "reason"))
+ .unwrap_or(""),
+ str_of(p, "datatype").unwrap_or("text"),
+ str_of(p, "unit"),
+ &forms,
+ )
+ .await
+ {
+ Ok((batch, moved)) => {
+ added_relations.push(key.to_string());
+ moved_total += moved;
+ if moved > 0 {
+ batches.push(batch);
+ }
+ }
+ Err(e) => tracing::warn!(%kb_id, key, error = %e, "冷启动建属性失败"),
+ }
+ }
+
// **映射到已有类型**:本体里已经有这个意思了,只改写事实、不动本体。
//
// 自动执行是安全的一档:它不让本体长大,只把一批 related_to 挂到一个
@@ -224,6 +274,20 @@ pub async fn bootstrap_ontology(state: &AppState, kb_id: Uuid) -> anyhow::Result
if forms.is_empty() {
continue;
}
+ // 目标是属性时改写走另一条路:值要按它的 datatype 换算。
+ // kind 由服务端在解析提案时标上(模型只答得出一个 key)
+ if str_of(m, "kind") == Some("attribute") {
+ match ontology_routes::adopt_attribute_existing(state, kb_id, key, &forms).await {
+ Ok((batch, moved)) => {
+ moved_total += moved;
+ if moved > 0 {
+ batches.push(batch);
+ }
+ }
+ Err(e) => tracing::warn!(%kb_id, key, error = %e, "映射到已有属性失败"),
+ }
+ continue;
+ }
// 模型偶尔会把候选清单之外的 key 抄进来(或者干脆编一个)。
// 找不到就跳过——**不新建**:这条路的前提就是"它已经存在"
let Some(predicate_id) =
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index cb1db556..699d3238 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -1300,28 +1300,81 @@ pub async fn adopt_proposed_predicates(
kb_id: Uuid,
predicate_id: Uuid,
forms: &[String],
+) -> AppResult<(Uuid, u32)> {
+ adopt(pool, kb_id, predicate_id, AdoptTargets::ByForm(forms)).await
+}
+
+/// 要改写哪些事实,以及新行的宾语从哪来。
+pub enum AdoptTargets<'a> {
+ /// 关系那一路:按表层说法去找,宾语原样搬走。
+ ByForm(&'a [String]),
+ /// 属性那一路:调用方已经挑好事实、并把值按 datatype 归一化过。
+ ///
+ /// **归一化必须在调用方做**:那套规则("2015" → 日期、"1,200" → 数字)
+ /// 住在抽取模块,store 够不着也不该够得着。更要紧的是它会**失败**——
+ /// 一个换算不出来的值不该硬塞进一个日期属性里,那条事实宁可继续挂在
+ /// 兜底谓词上。所以由调用方筛完再交回来。
+ WithValues(&'a [(Uuid, serde_json::Value)]),
+}
+
+async fn adopt(
+ pool: &PgPool,
+ kb_id: Uuid,
+ predicate_id: Uuid,
+ targets: AdoptTargets<'_>,
) -> AppResult<(Uuid, u32)> {
let batch_id = Uuid::now_v7();
- if forms.is_empty() {
- return Ok((batch_id, 0));
- }
- let targets: Vec<(Uuid, Uuid, Option<Uuid>, Option<serde_json::Value>)> = sqlx::query_as(
- "SELECT f.id, f.subject_id, f.object_id, f.object_value
- FROM facts f
- JOIN relation_types rt ON rt.id = f.predicate_id
- WHERE f.kb_id = $1 AND rt.key = $2 AND f.invalidated_at IS NULL
- AND EXISTS (SELECT 1 FROM fact_evidence e
- WHERE e.fact_id = f.id AND e.proposed_predicate = ANY($3))
- AND NOT EXISTS (SELECT 1 FROM fact_evidence e
- WHERE e.fact_id = f.id AND e.proposed_predicate IS NOT NULL
- AND NOT (e.proposed_predicate = ANY($3)))
- ORDER BY f.recorded_at",
- )
- .bind(kb_id)
- .bind(FALLBACK_RELATION_KEY)
- .bind(forms)
- .fetch_all(pool)
- .await?;
+ let targets: Vec<(Uuid, Uuid, Option<Uuid>, Option<serde_json::Value>)> = match targets {
+ AdoptTargets::ByForm(forms) => {
+ if forms.is_empty() {
+ return Ok((batch_id, 0));
+ }
+ sqlx::query_as(
+ "SELECT f.id, f.subject_id, f.object_id, f.object_value
+ FROM facts f
+ JOIN relation_types rt ON rt.id = f.predicate_id
+ WHERE f.kb_id = $1 AND rt.key = $2 AND f.invalidated_at IS NULL
+ -- **只碰宾语是实体的。** 同一个说法可能既有指向实体的事实
+ -- 又有带字面值的(location 两种都用),后者归属性那条路:
+ -- 把它改挂到一条关系上,那个值就再也不是值了
+ AND f.object_id IS NOT NULL
+ AND EXISTS (SELECT 1 FROM fact_evidence e
+ WHERE e.fact_id = f.id AND e.proposed_predicate = ANY($3))
+ AND NOT EXISTS (SELECT 1 FROM fact_evidence e
+ WHERE e.fact_id = f.id AND e.proposed_predicate IS NOT NULL
+ AND NOT (e.proposed_predicate = ANY($3)))
+ ORDER BY f.recorded_at",
+ )
+ .bind(kb_id)
+ .bind(FALLBACK_RELATION_KEY)
+ .bind(forms)
+ .fetch_all(pool)
+ .await?
+ }
+ AdoptTargets::WithValues(items) => {
+ if items.is_empty() {
+ return Ok((batch_id, 0));
+ }
+ // 主语要从库里读回来(调用方给的是 fact_id 与新值),顺带确认这些
+ // 事实还活着——挑选与采纳之间可能隔着一次重抽
+ let ids: Vec<Uuid> = items.iter().map(|(id, _)| *id).collect();
+ let live: Vec<(Uuid, Uuid)> = sqlx::query_as(
+ "SELECT id, subject_id FROM facts
+ WHERE kb_id = $1 AND id = ANY($2) AND invalidated_at IS NULL",
+ )
+ .bind(kb_id)
+ .bind(&ids)
+ .fetch_all(pool)
+ .await?;
+ let subject_of: std::collections::HashMap<Uuid, Uuid> = live.into_iter().collect();
+ items
+ .iter()
+ .filter_map(|(id, value)| {
+ Some((*id, *subject_of.get(id)?, None, Some(value.clone())))
+ })
+ .collect()
+ }
+ };
let mut moved = 0u32;
for (old_id, subject_id, object_id, object_value) in targets {
@@ -1350,10 +1403,13 @@ pub async fn adopt_proposed_predicates(
Some((id,)) => (id, ADOPT_MERGED),
None => {
let id = Uuid::now_v7();
+ // 宾语显式绑定而不是从旧行复制:属性那一路的新值是归一化过的
+ //("2015" → 日期),照抄旧行就等于把没换算的原值塞进去。
+ // 关系那一路绑的就是旧行的值,行为一字不变
let inserted: Option<(Uuid,)> = sqlx::query_as(
"INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, object_value,
valid_from, valid_to, valid_precision, confidence, supersedes)
- SELECT $1, kb_id, subject_id, $3, object_id, object_value,
+ SELECT $1, kb_id, subject_id, $3, $4, $5,
valid_from, valid_to, valid_precision, confidence, id
FROM facts WHERE id = $2 AND invalidated_at IS NULL
RETURNING id",
@@ -1361,6 +1417,8 @@ pub async fn adopt_proposed_predicates(
.bind(id)
.bind(old_id)
.bind(predicate_id)
+ .bind(object_id)
+ .bind(&object_value)
.fetch_optional(&mut *tx)
.await?;
// 已被并发改写:不重复动手
@@ -1456,3 +1514,100 @@ pub async fn unadopt(pool: &PgPool, kb_id: Uuid, batch_id: Uuid) -> AppResult<u3
tx.commit().await?;
Ok(reverted)
}
+
+/// 词表外的**字面值**说法:还挂在兜底谓词上、宾语是值而不是实体的那些。
+///
+/// 跟 [`proposed_predicates`] 互补,两边用 `object_id` 是否为空严格分开。
+/// 混在一起提案就会把 `founding_date` 提成一条关系,而那正是这条路要修掉的。
+pub async fn proposed_attributes(
+ pool: &PgPool,
+ kb_id: Uuid,
+) -> AppResult<Vec<utopia_core::models::ProposedAttribute>> {
+ Ok(sqlx::query_as(
+ "SELECT fe.proposed_predicate AS form,
+ count(DISTINCT f.id) AS fact_count,
+ count(DISTINCT fe.document_id) AS doc_count,
+ (SELECT f2.object_value::text
+ FROM fact_evidence e2
+ JOIN facts f2 ON f2.id = e2.fact_id
+ WHERE e2.proposed_predicate = fe.proposed_predicate
+ AND f2.kb_id = $1 AND f2.predicate_id = rt.id
+ AND f2.object_id IS NULL AND f2.invalidated_at IS NULL
+ LIMIT 1) AS example,
+ -- 主语实际是什么类:属性的 domain 从这里来,不靠猜
+ ARRAY(SELECT DISTINCT t.key
+ FROM fact_evidence e3
+ JOIN facts f3 ON f3.id = e3.fact_id
+ JOIN entities s ON s.id = f3.subject_id
+ JOIN entity_types t ON t.id = s.type_id
+ WHERE e3.proposed_predicate = fe.proposed_predicate
+ AND f3.kb_id = $1 AND f3.predicate_id = rt.id
+ AND f3.object_id IS NULL AND f3.invalidated_at IS NULL) AS domain_keys
+ FROM fact_evidence fe
+ JOIN facts f ON f.id = fe.fact_id
+ JOIN relation_types rt ON rt.id = f.predicate_id
+ WHERE f.kb_id = $1 AND rt.kb_id = $1 AND rt.key = $2
+ AND f.invalidated_at IS NULL AND fe.proposed_predicate IS NOT NULL
+ AND f.object_id IS NULL
+ -- 拒绝过的说法不再出现在候选里
+ AND NOT EXISTS (SELECT 1 FROM ontology_misses m
+ WHERE m.kb_id = $1 AND m.kind = 'attribute_type'
+ AND m.key = fe.proposed_predicate AND m.dismissed_at IS NOT NULL)
+ GROUP BY fe.proposed_predicate, rt.id
+ ORDER BY fact_count DESC, form",
+ )
+ .bind(kb_id)
+ .bind(FALLBACK_RELATION_KEY)
+ .fetch_all(pool)
+ .await?)
+}
+
+/// 某几个字面值说法当前挂着的事实:id、主语的类型、原始值。
+///
+/// 给采纳那一步用。**归一化不在这里做**——它按 datatype 把 "2015" 变成日期、
+/// 把 "1,200" 变成数字,那套规则住在抽取模块,store 够不着也不该够得着。
+/// 调用方归一化完,把结果原样交回来。
+pub async fn value_facts_for_forms(
+ pool: &PgPool,
+ kb_id: Uuid,
+ forms: &[String],
+) -> AppResult<Vec<(Uuid, Uuid, serde_json::Value)>> {
+ if forms.is_empty() {
+ return Ok(Vec::new());
+ }
+ Ok(sqlx::query_as(
+ "SELECT DISTINCT f.id, s.type_id, f.object_value
+ FROM facts f
+ JOIN entities s ON s.id = f.subject_id
+ JOIN relation_types rt ON rt.id = f.predicate_id
+ WHERE f.kb_id = $1 AND rt.key = $2 AND f.invalidated_at IS NULL
+ AND f.object_id IS NULL AND f.object_value IS NOT NULL
+ AND EXISTS (SELECT 1 FROM fact_evidence e
+ WHERE e.fact_id = f.id AND e.proposed_predicate = ANY($3))",
+ )
+ .bind(kb_id)
+ .bind(FALLBACK_RELATION_KEY)
+ .bind(forms)
+ .fetch_all(pool)
+ .await?)
+}
+
+/// 采纳一批**字面值**说法:把它们的事实改挂到某个属性上。
+///
+/// 与 [`adopt_proposed_predicates`] 共用改写、批次与撤销——对图做的事是同一件,
+/// 只有"新宾语从哪来"不同:这里的值由调用方按属性的 datatype 归一化过,
+/// 换算不出来的那些根本不会传进来(它们继续挂在兜底谓词上等下一次)。
+pub async fn adopt_value_facts(
+ pool: &PgPool,
+ kb_id: Uuid,
+ attribute_id: Uuid,
+ rewrites: &[(Uuid, serde_json::Value)],
+) -> AppResult<(Uuid, u32)> {
+ adopt(
+ pool,
+ kb_id,
+ attribute_id,
+ AdoptTargets::WithValues(rewrites),
+ )
+ .await
+}
diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rs
index 84f26cdd..7d54a7aa 100644
--- a/crates/utopia-store/src/ontology.rs
+++ b/crates/utopia-store/src/ontology.rs
@@ -973,3 +973,16 @@ pub async fn relation_type_id_by_key(
.await?;
Ok(row.map(|(id,)| id))
}
+
+/// 一个属性声明的 datatype。改写字面值事实时要按它换算。
+///
+/// 以**库里这一条**为准而不是以请求为准:指向已有属性时请求里根本没有
+/// datatype,而即便有,本体说了算。
+pub async fn relation_type_datatype(pool: &PgPool, id: Uuid) -> AppResult<Option<String>> {
+ let row: Option<(Option<String>,)> =
+ sqlx::query_as("SELECT datatype FROM relation_types WHERE id = $1")
+ .bind(id)
+ .fetch_optional(pool)
+ .await?;
+ Ok(row.and_then(|(d,)| d))
+}
diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs
index 069f515a..04f58f40 100644
--- a/crates/utopia-store/src/resolution.rs
+++ b/crates/utopia-store/src/resolution.rs
@@ -1049,12 +1049,17 @@ pub async fn merge_entities(
.map(|(id,)| id)
.collect();
- // 合并后 SPO+valid_from 重复的 live 事实:留最早 recorded_at 的一条,其余作废
+ // 合并后 SPO+valid_from 重复的 live 事实:留最早 recorded_at 的一条,其余作废。
+ //
+ // **宾语两侧都要分组。** 字面值事实的 object_id 全是 NULL,只按它分组就等于
+ // 把同主同谓下的**所有值**当成同一条断言:一次合并之后,
+ // (公司, 成立年份, 2015) 与 (公司, 注册资本, …) 之外,同谓词的多个值只活得下来
+ // 最早记的那一个,其余无声消失,且没有 supersedes 可查。
let dups: Vec<(Vec<Uuid>,)> = sqlx::query_as(
"SELECT (array_agg(id ORDER BY recorded_at))[2:] FROM facts
WHERE kb_id = $1 AND invalidated_at IS NULL
AND (subject_id = $2 OR object_id = $2)
- GROUP BY subject_id, predicate_id, object_id, valid_from
+ GROUP BY subject_id, predicate_id, object_id, object_value, valid_from
HAVING count(*) > 1",
)
.bind(kb_id)
diff --git a/web/src/api.ts b/web/src/api.ts
index 48b4130b..bad9fbcb 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -445,6 +445,22 @@ export interface OntologyProposals {
/** 这条关系归并了哪些表层说法。有它才谈得上把等待的事实改写过去 */
forms?: string[];
}[];
+ /**
+ * 宾语是字面值的说法("成立日期 = 2015")。
+ *
+ * 跟 relation_types 分开是因为它们要的东西不一样:属性有 datatype,
+ * 而把它当关系建出来,那个值就会变成一个假实体。domain 不在这里——
+ * 服务端从事实的主语类型里取,猜错会让整条被丢弃
+ */
+ attribute_types?: {
+ key: string;
+ label: string;
+ datatype?: string;
+ unit?: string;
+ description?: string;
+ reason?: string;
+ forms?: string[];
+ }[];
/**
* 本体里**已经有**这个意思,只需把说法挂过去。
*
@@ -453,6 +469,9 @@ export interface OntologyProposals {
*/
map_to?: {
key: string;
+ /** 服务端标的:目标落在关系还是属性上。两条改写路径不一样,
+ 而模型只答得出一个 key,看不出它在哪一档 */
+ kind?: string;
forms?: string[];
reason?: string;
}[];
@@ -911,6 +930,10 @@ export const api = {
key: string;
/** true = key 指的是已有的关系/属性,只改写事实,不建新类型 */
existing?: boolean;
+ /** attribute 走另一条改写路径:值要按 datatype 换算 */
+ kind?: "relation" | "attribute";
+ datatype?: string;
+ unit?: string;
label?: string;
temporal?: string;
functional?: boolean;
@@ -918,8 +941,14 @@ export const api = {
forms: string[];
},
) =>
- request<{ id: string; remapped: number; batch: string }>(
- `/api/v1/kbs/${kbId}/ontology/adopt-predicate`,
+ request<{
+ id: string;
+ remapped: number;
+ batch: string;
+ /** 值换不动那个 datatype、因而没被改写的条数。改写了 3 条丢下 2 条,
+ 只报前半句就是报喜不报忧 */
+ unconvertible?: number;
+ }>(`/api/v1/kbs/${kbId}/ontology/adopt-predicate`,
{ method: "POST", body: JSON.stringify(body) },
),
/** 撤销一次采纳:新写的行作废、旧行复活。关系类型留着 */
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 4a2bda22..e0394801 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -789,6 +789,9 @@ export const en = {
n === 1
? "Added — 1 fact reclassified"
: `Added — ${n} facts reclassified`,
+ /* 一部分值换不动这个类型就没被改写。只报改写了多少条是报喜不报忧 */
+ adoptedPartly: (moved: number, left: number) =>
+ `Added — ${moved} reclassified, ${left} left behind (value did not fit the type)`,
/* 撤销:采纳改写了成批事实,没有回头路的话没人敢点第一下 */
undoAdopt: (key: string, n: number) =>
`${key} added, ${n} fact${n === 1 ? "" : "s"} reclassified`,
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 73f7f52c..bba06f94 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -715,6 +715,8 @@ export const zh: Strings = {
mapOver: "用已有的",
willRemap: (n: number) => `将重新归类 ${n} 条事实`,
adopted: (n: number) => `已加入——${n} 条事实已重新归类`,
+ adoptedPartly: (moved: number, left: number) =>
+ `已加入——${moved} 条已重新归类,${left} 条留在原处(值与类型对不上)`,
undoAdopt: (key: string, n: number) =>
`已加入 ${key},${n} 条事实已重新归类`,
undoAdoptBtn: "撤销",
diff --git a/web/src/pages/Ontology.tsx b/web/src/pages/Ontology.tsx
index 8d244709..b02ab947 100644
--- a/web/src/pages/Ontology.tsx
+++ b/web/src/pages/Ontology.tsx
@@ -1403,18 +1403,74 @@ function MissesPanel({
// 逐条串行而不是加个批量端点:每个谓词各有自己的批次和撤销粒度,
// 而且部分失败能如实报告("5 个成功,1 个 key 已存在")而不是整批回滚
+ // 属性提案:宾语是字面值的那些。走同一个采纳入口,但值要按 datatype
+ // 换算,换不动的不改写——所以回执里的 unconvertible 必须说出来
+ const approveAttribute = useMutation({
+ mutationFn: (p: {
+ key: string;
+ label: string;
+ datatype?: string;
+ unit?: string;
+ description?: string;
+ forms?: string[];
+ }) =>
+ api.adoptPredicate(kbId, {
+ key: p.key,
+ kind: "attribute",
+ label: p.label,
+ datatype: p.datatype ?? "text",
+ unit: p.unit,
+ description: p.description,
+ forms: p.forms ?? [],
+ }),
+ onSuccess: (data, p) => {
+ const moved = data.remapped ?? 0;
+ const left = data.unconvertible ?? 0;
+ toast.success(
+ left > 0
+ ? S.ontology.adoptedPartly(moved, left)
+ : moved > 0
+ ? S.ontology.adopted(moved)
+ : S.toast.added,
+ );
+ if (moved > 0 && data.batch)
+ setLastAdopt({ batches: [data.batch], key: p.key, moved });
+ setProposals(
+ (prev) =>
+ prev && {
+ ...prev,
+ attribute_types: (prev.attribute_types ?? []).filter(
+ (x) => x.key !== p.key,
+ ),
+ },
+ );
+ for (const form of p.forms ?? [])
+ api.dismissMiss(kbId, "attribute_type", form).catch(() => {});
+ onChanged();
+ },
+ onError,
+ });
// 映射到已有类型:不建东西,只把这些说法的事实挂过去。
// 跟新建走同一个采纳入口,因为它对图做的事一模一样——也因此同样可撤销
const approveMapping = useMutation({
- mutationFn: (p: { key: string; forms?: string[] }) =>
+ mutationFn: (p: { key: string; kind?: string; forms?: string[] }) =>
api.adoptPredicate(kbId, {
key: p.key,
existing: true,
+ // 目标是属性时值要按它的 datatype 换算,服务端据此分道
+ kind: p.kind === "attribute" ? "attribute" : "relation",
forms: p.forms ?? [],
}),
onSuccess: (data, p) => {
const moved = data.remapped ?? 0;
- toast.success(moved > 0 ? S.ontology.adopted(moved) : S.toast.saved);
+ const left = data.unconvertible ?? 0;
+ toast.success(
+ left > 0
+ ? S.ontology.adoptedPartly(moved, left)
+ : moved > 0
+ ? S.ontology.adopted(moved)
+ : S.toast.saved,
+ );
if (moved > 0 && data.batch)
setLastAdopt({ batches: [data.batch], key: p.key, moved });
setProposals(
@@ -1468,12 +1524,31 @@ function MissesPanel({
failed.push(p.key);
}
}
+ for (const p of all.attribute_types ?? []) {
+ if (!p.forms?.length) continue;
+ try {
+ const r = await api.adoptPredicate(kbId, {
+ key: p.key,
+ kind: "attribute",
+ label: p.label,
+ datatype: p.datatype ?? "text",
+ unit: p.unit,
+ description: p.description,
+ forms: p.forms,
+ });
+ moved += r.remapped;
+ if (r.remapped > 0) batches.push(r.batch);
+ } catch {
+ failed.push(p.key);
+ }
+ }
for (const p of all.map_to ?? []) {
if (!p.forms?.length) continue;
try {
const r = await api.adoptPredicate(kbId, {
key: p.key,
existing: true,
+ kind: p.kind === "attribute" ? "attribute" : "relation",
forms: p.forms,
});
moved += r.remapped;
@@ -1643,6 +1718,7 @@ function MissesPanel({
{/* 常见情形是"这些都对"——一条条点是把一个决定拆成八个 */}
{proposals.relation_types.length +
proposals.entity_types.length +
+ (proposals.attribute_types?.length ?? 0) +
(proposals.map_to?.length ?? 0) >
1 && (
<Button
@@ -1657,6 +1733,7 @@ function MissesPanel({
: S.ontology.addAll(
proposals.relation_types.length +
proposals.entity_types.length +
+ (proposals.attribute_types?.length ?? 0) +
(proposals.map_to?.length ?? 0),
)}
</Button>
@@ -1748,8 +1825,40 @@ function MissesPanel({
</Button>
</div>
))}
+ {(proposals.attribute_types ?? []).map((p) => (
+ <div key={`attr-${p.key}`} className="flex items-center gap-2 text-sm">
+ {/* A 而不是 P:字面值那一档跟关系是两回事,界面上分得清 */}
+ <Chip tone="warn">A</Chip>
+ <span className="font-mono text-neutral-300">{p.key}</span>
+ <span className="text-neutral-200">{p.label}</span>
+ <Chip tone="neutral">{p.datatype ?? "text"}</Chip>
+ {p.unit && <Chip tone="neutral">{p.unit}</Chip>}
+ {!!p.forms?.length && (
+ <span
+ className="text-xs text-[var(--u-accent)]"
+ title={p.forms.join(" · ")}
+ >
+ {S.ontology.willRemap(factsWaiting(p.forms))}
+ </span>
+ )}
+ {p.reason && (
+ <span className="text-xs text-neutral-500 truncate">
+ {p.reason}
+ </span>
+ )}
+ <Button
+ size="sm"
+ className="ml-auto"
+ onClick={() => approveAttribute.mutate(p)}
+ disabled={approveAttribute.isPending}
+ >
+ {S.ontology.approve}
+ </Button>
+ </div>
+ ))}
{proposals.entity_types.length === 0 &&
proposals.relation_types.length === 0 &&
+ !proposals.attribute_types?.length &&
!proposals.map_to?.length && (
<p className="text-sm text-neutral-500">—</p>
)}