Skip to content

World's first open-source enterprise world model.

Adopting a predicate moves the facts that were waiting for it (#44)

WaylandYangdd1f7b975fcd
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index df499fef..6d110299 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -329,6 +329,18 @@ pub struct OntologyMiss {
pub count: i32,
}
+/// 一个待认领的表层谓词:原文这么说过,但本体里没有对应关系,事实降级成了
+/// related_to。与 `OntologyMiss` 的纯计数不同,它连着具体事实——所以采纳时
+/// 能说清"将重新归类 57 条",并真的去改。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct SurfacePredicate {
+ pub form: String,
+ /// 有多少条 live 的 related_to 事实由这个说法而来
+ pub fact_count: i64,
+ /// 一条样例("Dino Crisis (Steam) → GeForce NOW"),让人一眼判断这是什么关系
+ pub example: Option<String>,
+}
+
/// 抽取丢弃信号:事实抽出来了却没能落地,以及为什么。
/// 与 `OntologyMiss` 分开——那个说"你的本体缺这些"(读者是本体维护者),
/// 这个说"这些事实没落地"(读者是上传文档的人)。
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index ff47b723..50f63282 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -7,7 +7,7 @@ mod events_routes;
mod graph_routes;
mod kbs;
mod members_routes;
-mod ontology_routes;
+pub(crate) mod ontology_routes;
mod review_routes;
mod search_routes;
mod settings_routes;
@@ -146,6 +146,18 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
post(ontology_routes::dismiss_miss),
)
.route("/kbs/{id}/ontology/suggest", post(ontology_routes::suggest))
+ .route(
+ "/kbs/{id}/ontology/surface-predicates",
+ get(ontology_routes::surface_predicates),
+ )
+ .route(
+ "/kbs/{id}/ontology/adopt-predicate",
+ post(ontology_routes::adopt_predicate),
+ )
+ .route(
+ "/kbs/{id}/ontology/adopt-predicate/{batch_id}",
+ axum::routing::delete(ontology_routes::unadopt_predicate),
+ )
.route("/kbs/{id}/search", post(search_routes::search))
.route("/kbs/{id}/chat", post(chat::chat))
.route("/kbs/{id}/conversations", get(chat::list_conversations))
diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rs
index 9c1ef898..7fa8f292 100644
--- a/crates/utopia-server/src/api/ontology_routes.rs
+++ b/crates/utopia-server/src/api/ontology_routes.rs
@@ -324,7 +324,14 @@ pub async fn suggest(
AuthUser(user): AuthUser,
Path(kb_id): Path<Uuid>,
) -> ApiResult<Json<serde_json::Value>> {
- let kb = require_kb(&state, &user, kb_id, Role::Editor).await?;
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ Ok(Json(build_proposals(&state, kb_id).await?))
+}
+
+/// 生成本体扩展提案。人工点 Suggest 与冷启动自动扩本体走同一条路——
+/// 自动那条不该是另一套判断,只是少了点头那一步。
+pub async fn build_proposals(state: &AppState, kb_id: Uuid) -> Result<serde_json::Value, AppError> {
+ let kb = utopia_store::kbs::get(&state.pool, kb_id).await?;
let settings = utopia_store::settings::get(&state.pool, kb.workspace_id)
.await?
.ok_or_else(|| AppError::Validation("Chat model not configured".into()))?;
@@ -334,8 +341,10 @@ pub async fn suggest(
let entity_types = utopia_store::ontology::entity_type_views(&state.pool, kb_id).await?;
let relation_types = utopia_store::ontology::relation_type_views(&state.pool, kb_id).await?;
let misses = utopia_store::ontology::list_misses(&state.pool, kb_id).await?;
- if misses.is_empty() {
- return Ok(Json(json!({ "entity_types": [], "relation_types": [] })));
+ // 表层谓词比 misses 多一样东西:它连着具体事实,所以提案能承诺"改写 N 条"
+ let forms = utopia_store::graph::surface_predicates(&state.pool, kb_id).await?;
+ if misses.is_empty() && forms.is_empty() {
+ return Ok(json!({ "entity_types": [], "relation_types": [] }));
}
let current_et: Vec<String> = entity_types.iter().map(|t| t.key.clone()).collect();
@@ -353,6 +362,20 @@ pub async fn suggest(
})
.collect();
+ // 表层谓词行带上事实数与样例:模型据此判断这是不是一个真关系,
+ // 而 forms 字段让采纳时知道该改写哪些事实
+ let form_lines: Vec<String> = forms
+ .iter()
+ .map(|f| {
+ format!(
+ "- \"{}\" on {} fact(s), e.g. {}",
+ f.form,
+ f.fact_count,
+ f.example.as_deref().unwrap_or("-")
+ )
+ })
+ .collect();
+
let prompt = format!(
"You are an ontology engineer. A knowledge graph has this ontology:\n\
Entity type keys: {}\n\
@@ -360,13 +383,25 @@ pub async fn suggest(
\n\
During extraction, the LLM repeatedly produced types/relations OUTSIDE this ontology:\n{}\n\
\n\
- Propose ontology extensions that would cover these misses. Merge near-duplicates. \
- Only propose what is clearly warranted by the misses. Output exactly one JSON object:\n\
+ 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\
+ Propose ontology extensions. Rules:\n\
+ - Merge near-duplicates into ONE relation and list every spelling it covers in \
+ \"forms\" (e.g. available_on / available_from / \"available through\" are one relation).\n\
+ - Skip generic verbs that carry no domain meaning (is, has, includes, provides, brings).\n\
+ - A relation is worth adding when the ontology genuinely lacks that meaning, not merely \
+ 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\
+ \n\
+ Output exactly one JSON object:\n\
{{\"entity_types\":[{{\"key\":\"snake_case\",\"label\":\"Display Name\",\"reason\":\"...\"}}],\n\
- \"relation_types\":[{{\"key\":\"snake_case\",\"label\":\"display label\",\"temporal\":\"state|event|eternal\",\"functional\":false,\"reason\":\"...\"}}]}}",
+ \"relation_types\":[{{\"key\":\"snake_case\",\"label\":\"display label\",\"temporal\":\"state|event|eternal\",\"functional\":false,\"forms\":[\"surface spellings this covers\"],\"reason\":\"...\"}}]}}",
current_et.join(", "),
current_rt.join(", "),
- miss_lines.join("\n")
+ miss_lines.join("\n"),
+ form_lines.join("\n")
);
let reply = client
@@ -379,5 +414,123 @@ pub async fn suggest(
let block = utopia_extract::json_block(&reply).map_err(AppError::Other)?;
let proposals: serde_json::Value =
serde_json::from_str(&block).map_err(|e| AppError::Other(e.into()))?;
- Ok(Json(proposals))
+ Ok(proposals)
+}
+
+#[derive(Deserialize)]
+pub struct AdoptReq {
+ pub key: String,
+ pub label: String,
+ #[serde(default)]
+ pub description: Option<String>,
+ #[serde(default = "default_temporal")]
+ pub temporal: String,
+ /// 缺省 false,且刻意不由建议方决定——本体声明的唯一性会驱动时态引擎自动
+ /// 闭合事实,猜错就是成批的假冲突(part_of 就这么烧过一次)
+ #[serde(default)]
+ pub functional: bool,
+ #[serde(default)]
+ pub inverse_functional: bool,
+ /// 归入这个关系的表层说法("available_on"、"available through"…)
+ pub forms: Vec<String>,
+}
+
+/// 采纳一个表层谓词:建关系类型 **并把等着它的 related_to 事实改写过去**。
+///
+/// 与单纯 create 的区别就在后半句。只建类型的话本体长大了、图没变好——
+/// 那 57 条事实会继续是"有关联"。改写走追加(新行 + supersedes),
+/// 实体历史里读得到"先记成 related to,后精化成 available on"。
+pub async fn adopt_predicate(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Json(req): Json<AdoptReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let key = req.key.trim();
+ if req.forms.is_empty() {
+ return Err(AppError::Validation("forms cannot be empty".into()).into());
+ }
+ let predicate_id = utopia_store::ontology::create_relation_type(
+ &state.pool,
+ kb_id,
+ key,
+ req.label.trim(),
+ &req.temporal,
+ req.functional,
+ req.inverse_functional,
+ req.description.as_deref().unwrap_or("").trim(),
+ "relation",
+ None,
+ None,
+ None,
+ )
+ .await?;
+ let (batch_id, remapped) =
+ utopia_store::graph::adopt_surface_predicates(&state.pool, kb_id, predicate_id, &req.forms)
+ .await?;
+ // 采纳同时清掉对应的未匹配统计——本体已经覆盖它们了
+ for form in &req.forms {
+ let _ = utopia_store::ontology::clear_miss(&state.pool, kb_id, "relation_type", form).await;
+ }
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "ontology.predicate_adopted",
+ "relation_type",
+ Some(predicate_id),
+ json!({
+ "key": key, "label": req.label, "forms": req.forms,
+ "facts_remapped": remapped, "batch": batch_id,
+ }),
+ )
+ .await;
+ state.emit_review(kb_id);
+ Ok(Json(
+ json!({ "id": predicate_id, "remapped": remapped, "batch": batch_id }),
+ ))
+}
+
+/// 撤销一次采纳:新写的行作废、旧行复活。关系类型留着(有事实指向过它,
+/// 而且一个没人用的关系是惰性的)。
+pub async fn unadopt_predicate(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, batch_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ // 归因要按关系类型找回这次撤销,所以先拿到它
+ let predicate_id: Option<(Uuid,)> = sqlx::query_as(
+ "SELECT predicate_id FROM fact_adoptions WHERE batch_id = $1 AND kb_id = $2 LIMIT 1",
+ )
+ .bind(batch_id)
+ .bind(kb_id)
+ .fetch_optional(&state.pool)
+ .await
+ .map_err(utopia_core::AppError::Db)?;
+ let reverted = utopia_store::graph::unadopt(&state.pool, kb_id, batch_id).await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "ontology.adoption_reverted",
+ "relation_type",
+ predicate_id.map(|(id,)| id),
+ json!({ "batch": batch_id, "facts_reverted": reverted }),
+ )
+ .await;
+ state.emit_review(kb_id);
+ Ok(Json(json!({ "reverted": reverted })))
+}
+
+/// 待认领的表层谓词:原文说过、本体没有、事实降级成了 related_to。
+pub async fn surface_predicates(
+ 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 forms = utopia_store::graph::surface_predicates(&state.pool, kb_id).await?;
+ Ok(Json(json!({ "forms": forms })))
}
diff --git a/crates/utopia-server/src/bootstrap_ontology.rs b/crates/utopia-server/src/bootstrap_ontology.rs
new file mode 100644
index 00000000..1947fe81
--- /dev/null
+++ b/crates/utopia-server/src/bootstrap_ontology.rs
@@ -0,0 +1,168 @@
+//! 冷启动自动扩本体:本体从没被人碰过时,第一批文档抽完后自己把词表建起来。
+//!
+//! 新建的库只有 10 个默认关系——那不是任何人选的,是种子数据。传进第一批
+//! 文档,里面的关系大半不在这 10 个里,于是大量事实降级成 related_to,
+//! 图基本没法用,直到有人坐下来点 Suggest、看提案、逐条 Add。
+//! **没有精心建立的词表要保护时,坚持人工审批保护的是个还不存在的东西。**
+//!
+//! 敢这么做的前提是采纳可撤销(见 graph::unadopt):错了点一下就回去,
+//! 旧事实从来没被销毁过。所以判断轴不是"有多确信"而是"错了有多贵"。
+//!
+//! 唯独 `functional` 永不自动:它驱动时态引擎自动闭合事实、生成冲突,
+//! 等发现时那些闭合本身已是一串 supersede 链——不属于"错了很便宜"那类。
+
+use uuid::Uuid;
+
+use crate::api::ontology_routes;
+use crate::state::AppState;
+
+/// 少于这么多个待认领的说法就不折腾——凑不出像样的提案,白烧一次 LLM 调用。
+const MIN_FORMS: usize = 3;
+
+pub async fn bootstrap_ontology(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {
+ // 并发的两个抽取任务可能都看到"空闲"而各入队一次;这里重查一遍,
+ // 先跑的那个建出关系后,后跑的这个就是 no-op
+ if !utopia_store::graph::ontology_untouched(&state.pool, kb_id).await? {
+ tracing::debug!(%kb_id, "本体已被扩展过,跳过冷启动");
+ return Ok(());
+ }
+ let forms = utopia_store::graph::surface_predicates(&state.pool, kb_id).await?;
+ if forms.len() < MIN_FORMS {
+ tracing::debug!(%kb_id, n = forms.len(), "待认领的说法太少,跳过冷启动");
+ return Ok(());
+ }
+
+ let proposals = ontology_routes::build_proposals(state, kb_id).await?;
+ let relations = proposals
+ .get("relation_types")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+ let classes = proposals
+ .get("entity_types")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut added_relations = Vec::new();
+ let mut added_classes = Vec::new();
+ let mut moved_total = 0u32;
+ let mut batches = Vec::new();
+
+ for p in &classes {
+ let (Some(key), Some(label)) = (str_of(p, "key"), str_of(p, "label")) else {
+ continue;
+ };
+ match utopia_store::ontology::create_entity_type(
+ &state.pool,
+ kb_id,
+ key,
+ label,
+ "#8ea5bd",
+ "circle",
+ None,
+ str_of(p, "reason").unwrap_or(""),
+ )
+ .await
+ {
+ Ok(_) => added_classes.push(key.to_string()),
+ // key 撞车之类的:跳过这一条,别带垮整批
+ Err(e) => tracing::warn!(%kb_id, key, error = %e, "冷启动建类失败"),
+ }
+ }
+
+ for p in &relations {
+ 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();
+ let temporal = str_of(p, "temporal").unwrap_or("state");
+ let predicate_id = match utopia_store::ontology::create_relation_type(
+ &state.pool,
+ kb_id,
+ key,
+ label,
+ temporal,
+ // 建议方不替时态引擎做决定,见文件头
+ false,
+ false,
+ str_of(p, "reason").unwrap_or(""),
+ "relation",
+ None,
+ None,
+ None,
+ )
+ .await
+ {
+ Ok(id) => id,
+ Err(e) => {
+ tracing::warn!(%kb_id, key, error = %e, "冷启动建关系失败");
+ continue;
+ }
+ };
+ added_relations.push(key.to_string());
+ if !forms.is_empty() {
+ let (batch, moved) = utopia_store::graph::adopt_surface_predicates(
+ &state.pool,
+ kb_id,
+ predicate_id,
+ &forms,
+ )
+ .await?;
+ moved_total += moved;
+ if moved > 0 {
+ batches.push(batch);
+ }
+ for form in &forms {
+ let _ =
+ utopia_store::ontology::clear_miss(&state.pool, kb_id, "relation_type", form)
+ .await;
+ }
+ }
+ }
+
+ if added_relations.is_empty() && added_classes.is_empty() {
+ return Ok(());
+ }
+ // actor 为 NULL:这是系统的动作,不是谁的决定。台账里查得到做了什么、
+ // 改了多少条、以及撤销要用的批次号
+ let _ = utopia_store::audit::record_opt(
+ &state.pool,
+ Some(kb_id),
+ None,
+ "ontology.bootstrapped",
+ "kb",
+ Some(kb_id),
+ serde_json::json!({
+ "relations": added_relations,
+ "classes": added_classes,
+ "facts_remapped": moved_total,
+ "batches": batches,
+ }),
+ )
+ .await;
+ state.emit_review(kb_id);
+ tracing::info!(
+ %kb_id,
+ relations = added_relations.len(),
+ classes = added_classes.len(),
+ facts = moved_total,
+ "冷启动自动扩本体完成"
+ );
+ Ok(())
+}
+
+fn str_of<'a>(v: &'a serde_json::Value, key: &str) -> Option<&'a str> {
+ v.get(key)
+ .and_then(|x| x.as_str())
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+}
diff --git a/crates/utopia-server/src/extraction.rs b/crates/utopia-server/src/extraction.rs
index 47eb3086..992e1ab7 100644
--- a/crates/utopia-server/src/extraction.rs
+++ b/crates/utopia-server/src/extraction.rs
@@ -5,11 +5,10 @@
use crate::llm_util;
use crate::state::AppState;
use std::collections::HashMap;
+use utopia_store::graph::FALLBACK_RELATION_KEY;
use uuid::Uuid;
const MIN_CONFIDENCE: f32 = 0.6;
-/// 词表外谓词的代码层兜底。刻意不进提示词——理由见 rel_pairs 的注释。
-const FALLBACK_RELATION_KEY: &str = "related_to";
/// 记一条丢弃信号。抽取器有七处 `continue`,每一处都是"事实抽出来了、被挡掉、
/// 什么都不说"。信号写失败绝不能带垮整篇文档的抽取,所以这里吞掉错误。
@@ -591,6 +590,19 @@ async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
if needs_adjudication || conflicts_found {
state.emit_review(doc.kb_id);
}
+ // 冷启动自动扩本体:本体没被人碰过、且这一批都抽完了,由最后一篇触发。
+ // 逐篇触发是错的——先到的那篇的词汇会独占本体。并发下可能入队两次,
+ // 任务自己会重查一遍,先跑的建出关系后另一个就是 no-op
+ if utopia_store::graph::ontology_untouched(&state.pool, doc.kb_id).await?
+ && utopia_store::documents::extraction_idle(&state.pool, doc.kb_id).await?
+ {
+ utopia_store::jobs::enqueue(
+ &state.pool,
+ "bootstrap_ontology",
+ serde_json::json!({ "kb_id": doc.kb_id }),
+ )
+ .await?;
+ }
tracing::info!(%document_id, facts = fact_count, "图谱抽取完成");
Ok(())
diff --git a/crates/utopia-server/src/main.rs b/crates/utopia-server/src/main.rs
index 3d111eb6..f33b534c 100644
--- a/crates/utopia-server/src/main.rs
+++ b/crates/utopia-server/src/main.rs
@@ -2,6 +2,7 @@ mod adjudication;
mod api;
mod auth;
mod blob;
+mod bootstrap_ontology;
mod docs_corpus;
mod error;
mod extraction;
@@ -91,6 +92,15 @@ async fn main() -> anyhow::Result<()> {
let id = payload_document_id(&job.payload)?;
extraction::extract_document(&st, id).await
}
+ "bootstrap_ontology" => {
+ let kb_id: Uuid = job
+ .payload
+ .get("kb_id")
+ .and_then(|v| v.as_str())
+ .and_then(|s| s.parse().ok())
+ .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;
+ bootstrap_ontology::bootstrap_ontology(&st, kb_id).await
+ }
"adjudicate_entities" => {
let kb_id: Uuid = job
.payload
diff --git a/crates/utopia-store/src/documents.rs b/crates/utopia-store/src/documents.rs
index c7b31e4f..e0d2f3e9 100644
--- a/crates/utopia-store/src/documents.rs
+++ b/crates/utopia-store/src/documents.rs
@@ -645,3 +645,18 @@ pub async fn extract_epoch(pool: &PgPool, id: Uuid) -> AppResult<i32> {
.await?;
Ok(epoch)
}
+
+/// 这个库还有没有在排队或正在跑的抽取。
+///
+/// 冷启动自动扩本体要等一批文档都抽完再动手:只看第一篇的话,
+/// 先到的那篇的词汇会独占本体。最后一篇跑完的任务负责触发。
+pub async fn extraction_idle(pool: &PgPool, kb_id: Uuid) -> AppResult<bool> {
+ let (pending,): (i64,) = sqlx::query_as(
+ "SELECT count(*) FROM documents
+ WHERE kb_id = $1 AND graph_status IN ('queued', 'extracting')",
+ )
+ .bind(kb_id)
+ .fetch_one(pool)
+ .await?;
+ Ok(pending == 0)
+}
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index 90f536c2..c68c3416 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -4,7 +4,7 @@ use sqlx::PgPool;
use std::collections::HashSet;
use utopia_core::models::{
ChunkFactView, EntityFact, EntityHistoryEvent, EntityType, EvidenceView, FactReviewItem,
- GraphEdge, GraphNode, RelationType,
+ GraphEdge, GraphNode, RelationType, SurfacePredicate,
};
use utopia_core::{AppError, AppResult};
use uuid::Uuid;
@@ -16,6 +16,16 @@ type FactSpanRow = (
Option<chrono::DateTime<chrono::Utc>>,
);
+/// 词表外谓词的代码层兜底:抽取器降级到它,谓词消解从它改写出去。
+/// 两边必须认同一个 key,所以定义在这里而不是各自的模块。
+pub const FALLBACK_RELATION_KEY: &str = "related_to";
+
+/// 采纳时旧事实的去向(`fact_adoptions.mode`):新写一行取代它。
+const ADOPT_SUPERSEDED: &str = "superseded";
+/// 目标断言已存在 → 并进去。旧行被作废且没有后继,实体历史必须据此把它
+/// 读成"并入"而不是"撤回",否则界面会宣称一件没发生的事。
+const ADOPT_MERGED: &str = "merged";
+
/// 内置本体模板:(key, label, color, shape)
// 低饱和粉彩色系(深色画布上柔和发光,不刺眼);组织/产品用方形区分"机构/制品"
const DEFAULT_ENTITY_TYPES: &[(&str, &str, &str, &str)] = &[
@@ -246,8 +256,9 @@ async fn insert_fact_inner(
.execute(pool)
.await?;
sqlx::query(
- "INSERT INTO fact_evidence (fact_id, chunk_id, quote, document_id, doc_version)
- SELECT $1, chunk_id, quote, document_id, doc_version
+ // 表层谓词随证据一起搬:精化的是时间,不是原文说了什么
+ "INSERT INTO fact_evidence (fact_id, chunk_id, quote, surface_predicate, document_id, doc_version)
+ SELECT $1, chunk_id, quote, surface_predicate, document_id, doc_version
FROM fact_evidence WHERE fact_id = $2
ON CONFLICT DO NOTHING",
)
@@ -836,7 +847,13 @@ pub async fn entity_history(
CASE WHEN ef.supersedes IS NULL THEN 'asserted' ELSE 'corrected' END AS kind
FROM ef
UNION ALL
- SELECT ef.*, ef.invalidated_at AS at, 'rejected' AS kind
+ -- 作废且无后继 = 被推翻……除非它是被并进了另一条断言。那种情形下
+ -- 内容一字未少,说成「撤回」就是界面在陈述一件没发生的事
+ SELECT ef.*, ef.invalidated_at AS at,
+ CASE WHEN EXISTS (SELECT 1 FROM fact_adoptions fa
+ WHERE fa.old_fact_id = ef.id AND fa.mode = 'merged'
+ AND fa.reverted_at IS NULL)
+ THEN 'merged' ELSE 'rejected' END AS kind
FROM ef
WHERE ef.invalidated_at IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM facts s WHERE s.supersedes = ef.id)
@@ -860,12 +877,25 @@ pub async fn entity_history(
-- 否则后发生的人工裁决会被错安到当初那条断言头上
AND ev.kind <> 'asserted'
AND a.action = ANY(CASE ev.kind
- WHEN 'corrected' THEN ARRAY['fact.close', 'conflict.close_old']
- ELSE ARRAY['fact.reject', 'conflict.reject_new'] END)
+ WHEN 'corrected' THEN
+ ARRAY['fact.close', 'conflict.close_old', 'ontology.predicate_adopted']
+ -- 并入只可能由采纳造成,不会是 Review 里的拒绝
+ WHEN 'merged' THEN ARRAY['ontology.predicate_adopted']
+ ELSE ARRAY['fact.reject', 'conflict.reject_new',
+ 'ontology.adoption_reverted'] END)
AND (a.target_id = COALESCE(ev.supersedes, ev.id)
OR a.target_id IN (SELECT c.id FROM fact_conflicts c
WHERE c.old_fact_id = COALESCE(ev.supersedes, ev.id)
- OR c.new_fact_id = ev.id))
+ OR c.new_fact_id = ev.id)
+ -- 采纳与撤销都记在关系类型上、一次动作改一批事实,
+ -- 靠 fact_adoptions 精确关联到具体哪几条(corrected 事件
+ -- 是新行、merged 是旧行,两头都认)
+ OR (a.action IN ('ontology.predicate_adopted',
+ 'ontology.adoption_reverted')
+ AND EXISTS (SELECT 1 FROM fact_adoptions fa
+ WHERE fa.predicate_id = a.target_id
+ AND (fa.new_fact_id = ev.id
+ OR fa.old_fact_id = ev.id))))
ORDER BY a.created_at DESC LIMIT 1
) act ON true
LEFT JOIN LATERAL (
@@ -892,3 +922,225 @@ pub async fn entity_history(
.await?;
Ok((rows, total))
}
+
+// ---------------------------------------------------------------------------
+// 谓词消解:把降级成 related_to 的事实认领回本体
+// ---------------------------------------------------------------------------
+
+// 视图类型 SurfacePredicate 定义在 utopia-core::models(store 不直接依赖 serde)
+
+/// 降级成 related_to 的事实上,原文用过哪些说法。
+///
+/// 这是本体扩展建议的证据基础——比 `ontology_misses` 的纯计数强的地方在于:
+/// 它连着具体事实,所以采纳一个说法时能直接说"将重新归类 57 条"并真的去改。
+pub async fn surface_predicates(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<SurfacePredicate>> {
+ Ok(sqlx::query_as(
+ "SELECT fe.surface_predicate AS form,
+ count(DISTINCT f.id) AS fact_count,
+ (SELECT s.canonical_name || ' → ' || o.canonical_name
+ FROM fact_evidence e2
+ JOIN facts f2 ON f2.id = e2.fact_id
+ JOIN entities s ON s.id = f2.subject_id
+ JOIN entities o ON o.id = f2.object_id
+ WHERE e2.surface_predicate = fe.surface_predicate
+ AND f2.kb_id = $1 AND f2.predicate_id = rt.id AND f2.invalidated_at IS NULL
+ LIMIT 1) AS example
+ 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.surface_predicate IS NOT NULL
+ GROUP BY fe.surface_predicate, rt.id
+ ORDER BY fact_count DESC, form",
+ )
+ .bind(kb_id)
+ .bind(FALLBACK_RELATION_KEY)
+ .fetch_all(pool)
+ .await?)
+}
+
+/// 把由 `forms` 降级而来的 related_to 事实改写到 `predicate_id`。
+/// 返回 (批次 id, 改写条数)——批次 id 是撤销的把手。
+///
+/// **追加而非原地改**:插入带 `supersedes` 的新行并作废旧行,与人工纠正、
+/// 时态闭合走同一条路——认知变更本身是信息,实体历史里读得到
+/// "先记成 related to,后精化成 available on"。
+///
+/// 只改写说法**全部**落在 `forms` 内的事实:一条事实可能积累多种说法
+/// (甲块 "runs on"、乙块 "optimized for"),只认领了其中一种就改写等于替
+/// 另一种也做了决定。实测这类事实占比不到 1%,宁可漏也不猜。
+///
+/// 每条去向都写进 `fact_adoptions`。`supersedes` 一个指针不够用——目标断言
+/// 已存在时走的是"并入",旧行被作废却没有后继,于是既撤不回来、实体历史
+/// 又会把它判成 rejected 而对外宣称"这条被撤回了"(它其实一字未少地并进了
+/// 另一条)。
+pub async fn adopt_surface_predicates(
+ pool: &PgPool,
+ kb_id: Uuid,
+ predicate_id: Uuid,
+ forms: &[String],
+) -> 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>)> = sqlx::query_as(
+ "SELECT f.id, f.subject_id, f.object_id
+ 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.surface_predicate = ANY($3))
+ AND NOT EXISTS (SELECT 1 FROM fact_evidence e
+ WHERE e.fact_id = f.id AND e.surface_predicate IS NOT NULL
+ AND NOT (e.surface_predicate = ANY($3)))
+ ORDER BY f.recorded_at",
+ )
+ .bind(kb_id)
+ .bind(FALLBACK_RELATION_KEY)
+ .bind(forms)
+ .fetch_all(pool)
+ .await?;
+
+ let mut moved = 0u32;
+ for (old_id, subject_id, object_id) in targets {
+ let mut tx = pool.begin().await?;
+ // 目标断言可能已存在(同主宾已有一条真关系):那就并进去,别造重复
+ let existing: Option<(Uuid,)> = sqlx::query_as(
+ "SELECT id FROM facts
+ WHERE kb_id = $1 AND subject_id = $2 AND predicate_id = $3
+ AND object_id IS NOT DISTINCT FROM $4 AND invalidated_at IS NULL",
+ )
+ .bind(kb_id)
+ .bind(subject_id)
+ .bind(predicate_id)
+ .bind(object_id)
+ .fetch_optional(&mut *tx)
+ .await?;
+
+ let (new_id, mode) = match existing {
+ Some((id,)) => (id, ADOPT_MERGED),
+ None => {
+ let id = Uuid::now_v7();
+ 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,
+ valid_from, valid_to, valid_precision, confidence, id
+ FROM facts WHERE id = $2 AND invalidated_at IS NULL
+ RETURNING id",
+ )
+ .bind(id)
+ .bind(old_id)
+ .bind(predicate_id)
+ .fetch_optional(&mut *tx)
+ .await?;
+ // 已被并发改写:不重复动手
+ let Some((id,)) = inserted else {
+ tx.rollback().await?;
+ continue;
+ };
+ (id, ADOPT_SUPERSEDED)
+ }
+ };
+
+ // 证据整体搬过去,表层谓词一并保留——它是这次改写的依据,不该在改写中丢失
+ sqlx::query(
+ "INSERT INTO fact_evidence (fact_id, chunk_id, quote, surface_predicate, document_id, doc_version)
+ SELECT $1, chunk_id, quote, surface_predicate, document_id, doc_version
+ FROM fact_evidence WHERE fact_id = $2
+ ON CONFLICT DO NOTHING",
+ )
+ .bind(new_id)
+ .bind(old_id)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = $1")
+ .bind(old_id)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query(
+ "INSERT INTO fact_adoptions
+ (batch_id, kb_id, predicate_id, old_fact_id, new_fact_id, mode)
+ VALUES ($1, $2, $3, $4, $5, $6)",
+ )
+ .bind(batch_id)
+ .bind(kb_id)
+ .bind(predicate_id)
+ .bind(old_id)
+ .bind(new_id)
+ .bind(mode)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ moved += 1;
+ }
+ Ok((batch_id, moved))
+}
+
+/// 撤销一次采纳:新写的行作废、旧行复活。
+///
+/// 关系类型**不删**——已有事实指向过它(`delete_relation_type` 也会拒绝),
+/// 而按 append-only 的规矩"它存在过"本身是历史;一个没人用的关系是惰性的。
+/// 证据也不清:新行已作废,其证据随之惰性,删掉反而抹掉"我们曾经这么认为"。
+///
+/// 并入那种(mode = merged)只复活旧行,不动被并入的目标——它本来就在,
+/// 复制过去的证据留着无害(`ON CONFLICT DO NOTHING` 本就可能是它自己的)。
+pub async fn unadopt(pool: &PgPool, kb_id: Uuid, batch_id: Uuid) -> AppResult<u32> {
+ let rows: Vec<(Uuid, Uuid, String)> = sqlx::query_as(
+ "SELECT old_fact_id, new_fact_id, mode FROM fact_adoptions
+ WHERE batch_id = $1 AND kb_id = $2 AND reverted_at IS NULL",
+ )
+ .bind(batch_id)
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?;
+ if rows.is_empty() {
+ return Err(AppError::NotFound);
+ }
+
+ let mut tx = pool.begin().await?;
+ let mut reverted = 0u32;
+ for (old_id, new_id, mode) in &rows {
+ if mode == ADOPT_SUPERSEDED {
+ sqlx::query(
+ "UPDATE facts SET invalidated_at = now() WHERE id = $1 AND invalidated_at IS NULL",
+ )
+ .bind(new_id)
+ .execute(&mut *tx)
+ .await?;
+ }
+ sqlx::query("UPDATE facts SET invalidated_at = NULL WHERE id = $1")
+ .bind(old_id)
+ .execute(&mut *tx)
+ .await?;
+ reverted += 1;
+ }
+ // 标记而不是删除:这次采纳发生过,撤销也发生过,两件都是历史
+ sqlx::query(
+ "UPDATE fact_adoptions SET reverted_at = now()
+ WHERE batch_id = $1 AND kb_id = $2 AND reverted_at IS NULL",
+ )
+ .bind(batch_id)
+ .bind(kb_id)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(reverted)
+}
+
+/// 本体是否从没被人碰过:只有内置类型、没有任何自建或导入的。
+///
+/// 冷启动自动扩本体的判定依据。**没有精心建立的词表时,坚持人工审批保护的
+/// 是个还不存在的东西**——而默认那 10 个关系不是任何人选的,是种子数据。
+/// 一旦有人加过或导入过,这里就为 false,自动扩本体从此不再触发。
+pub async fn ontology_untouched(pool: &PgPool, kb_id: Uuid) -> AppResult<bool> {
+ let (custom,): (i64,) = sqlx::query_as(
+ "SELECT (SELECT count(*) FROM entity_types WHERE kb_id = $1 AND NOT builtin)
+ + (SELECT count(*) FROM relation_types WHERE kb_id = $1 AND NOT builtin)",
+ )
+ .bind(kb_id)
+ .fetch_one(pool)
+ .await?;
+ Ok(custom == 0)
+}
diff --git a/crates/utopia-store/src/temporal.rs b/crates/utopia-store/src/temporal.rs
index 17b37854..cec148ea 100644
--- a/crates/utopia-store/src/temporal.rs
+++ b/crates/utopia-store/src/temporal.rs
@@ -257,8 +257,9 @@ pub async fn close_superseded(
.execute(&mut *tx)
.await?;
sqlx::query(
- "INSERT INTO fact_evidence (fact_id, chunk_id, quote, document_id, doc_version)
- SELECT $1, chunk_id, quote, document_id, doc_version
+ // 表层谓词随证据一起搬:纠正的是时间区间,不是原文说了什么
+ "INSERT INTO fact_evidence (fact_id, chunk_id, quote, surface_predicate, document_id, doc_version)
+ SELECT $1, chunk_id, quote, surface_predicate, document_id, doc_version
FROM fact_evidence WHERE fact_id = $2
ON CONFLICT DO NOTHING",
)
diff --git a/migrations/0023_fact_adoptions.sql b/migrations/0023_fact_adoptions.sql
new file mode 100644
index 00000000..ea22235c
--- /dev/null
+++ b/migrations/0023_fact_adoptions.sql
@@ -0,0 +1,29 @@
+-- 采纳表层谓词时,哪条事实被改写成了哪条。
+--
+-- 没有这张表时改写只留下 facts.supersedes 一个指针,而它覆盖不了"并入已存在
+-- 事实"那种情形:旧行被作废、没有任何后继指向它。后果有两个——撤销时找不回
+-- 它去了哪,以及实体历史把"已作废且无后继"判成 rejected,于是界面会说
+-- "这条记录被撤回了",而它其实原封不动地并进了另一条断言。
+--
+-- 顺带补上治理要求的那一半:审计行此前只记了"改写 49 条"这个总数,
+-- 答不出"具体哪 49 条"。
+CREATE TABLE fact_adoptions (
+ -- 一次采纳动作的批次;撤销以它为单位
+ batch_id UUID NOT NULL,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ predicate_id UUID NOT NULL REFERENCES relation_types(id) ON DELETE CASCADE,
+ old_fact_id UUID NOT NULL REFERENCES facts(id) ON DELETE CASCADE,
+ new_fact_id UUID NOT NULL REFERENCES facts(id) ON DELETE CASCADE,
+ -- superseded = 新写一行取代旧行;merged = 并入已存在的行
+ mode TEXT NOT NULL,
+ -- 撤销不删行:抹掉"发生过什么"与账本的规矩相反,而且撤销本身也是
+ -- 一次人的决定,实体历史要据此归因
+ reverted_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (batch_id, old_fact_id)
+);
+
+-- 实体历史逐条问"这条是不是被并走了",走这个索引
+CREATE INDEX fact_adoptions_old_idx ON fact_adoptions (old_fact_id);
+-- 按库列出可撤销的批次
+CREATE INDEX fact_adoptions_kb_idx ON fact_adoptions (kb_id, created_at DESC);
diff --git a/web/src/api.ts b/web/src/api.ts
index b7f17011..31ef8e49 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -398,9 +398,18 @@ export interface OntologyProposals {
temporal?: string;
functional?: boolean;
reason?: string;
+ /** 这条关系归并了哪些表层说法。有它才谈得上把等待的事实改写过去 */
+ forms?: string[];
}[];
}
+/** 原文说过、本体没有、事实降级成了 related_to 的谓词。 */
+export interface SurfacePredicate {
+ form: string;
+ fact_count: number;
+ example: string | null;
+}
+
export interface Source {
n: number;
/** 缺省 = 文档 chunk 引用;charter = 内置手册(跳 /docs/{slug}#{anchor}) */
@@ -666,6 +675,30 @@ export const api = {
suggestOntology: (kbId: string) =>
request<OntologyProposals>(`/api/v1/kbs/${kbId}/ontology/suggest`, { method: "POST" }),
+ surfacePredicates: (kbId: string) =>
+ request<{ forms: SurfacePredicate[] }>(`/api/v1/kbs/${kbId}/ontology/surface-predicates`),
+ /** 建关系 **并**把等着它的 related_to 事实改写过去——后半句才是收益 */
+ adoptPredicate: (
+ kbId: string,
+ body: {
+ key: string;
+ label: string;
+ temporal?: string;
+ functional?: boolean;
+ forms: string[];
+ },
+ ) =>
+ request<{ id: string; remapped: number; batch: string }>(
+ `/api/v1/kbs/${kbId}/ontology/adopt-predicate`,
+ { method: "POST", body: JSON.stringify(body) },
+ ),
+ /** 撤销一次采纳:新写的行作废、旧行复活。关系类型留着 */
+ unadoptPredicate: (kbId: string, batchId: string) =>
+ request<{ reverted: number }>(
+ `/api/v1/kbs/${kbId}/ontology/adopt-predicate/${batchId}`,
+ { method: "DELETE" },
+ ),
+
sources: (kbId: string) =>
request<{ sources: SourceView[] }>(`/api/v1/kbs/${kbId}/sources`),
createSource: (kbId: string, body: Record<string, unknown>) =>
diff --git a/web/src/i18n.ts b/web/src/i18n.ts
index 9acfb90f..a5969f95 100644
--- a/web/src/i18n.ts
+++ b/web/src/i18n.ts
@@ -455,6 +455,8 @@ export const S = {
asserted: "Recorded",
corrected: "Interval corrected",
rejected: "Withdrawn",
+ /* 并入另一条断言:内容一字未少,不是撤回 */
+ merged: "Merged into an existing fact",
} as Record<string, string>,
historyEngine: "engine",
/* 有效区间的变化:修正后区间闭合到某个时点 */
@@ -614,6 +616,25 @@ export const S = {
suggesting: "Analyzing…",
noMisses: "No unmatched types — the ontology covers your corpus.",
approve: "Add",
+ /* 影响面:采纳一个提案会把多少条 related_to 事实改写过去。
+ 没有这一句,"Add" 只是凭空多一个空关系 */
+ willRemap: (n: number) =>
+ n === 1 ? "reclassifies 1 fact" : `reclassifies ${n} facts`,
+ adopted: (n: number) =>
+ n === 1 ? "Added — 1 fact reclassified" : `Added — ${n} facts reclassified`,
+ /* 撤销:采纳改写了成批事实,没有回头路的话没人敢点第一下 */
+ undoAdopt: (key: string, n: number) =>
+ `${key} added, ${n} fact${n === 1 ? "" : "s"} reclassified`,
+ undoAdoptBtn: "Undo",
+ reverted: (n: number) =>
+ n === 1 ? "Reverted — 1 fact restored" : `Reverted — ${n} facts restored`,
+ undoKeepsRelation: "The relation stays; only the facts move back.",
+ /* 批量:常见情形是"这些都对",一条条点是把一个决定拆成八个 */
+ addAll: (n: number) => `Add all ${n}`,
+ addingAll: "Adding…",
+ addAllLabel: "batch",
+ addAllPartial: (keys: string[]) =>
+ `Some could not be added: ${keys.join(", ")} — the rest went through.`,
proposals: "AI proposals",
keyHint: "lowercase_snake_case",
},
diff --git a/web/src/pages/EntityHistory.tsx b/web/src/pages/EntityHistory.tsx
index f180b663..b8667560 100644
--- a/web/src/pages/EntityHistory.tsx
+++ b/web/src/pages/EntityHistory.tsx
@@ -5,7 +5,7 @@
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";
-import { FileText, PencilLine, Undo2 } from "lucide-react";
+import { FileText, Merge, PencilLine, Undo2 } from "lucide-react";
import { api, type EntityHistoryEvent } from "../api";
import { S } from "../i18n";
import { Pager } from "../ui";
@@ -17,12 +17,15 @@ const KIND_ICON = {
asserted: FileText,
corrected: PencilLine,
rejected: Undo2,
+ // 并入不是撤回:内容一字未少地进了另一条断言
+ merged: Merge,
} as const;
const KIND_TONE: Record<string, string> = {
asserted: "text-neutral-500",
corrected: "text-[var(--u-warn)]",
rejected: "text-[var(--u-danger)]",
+ merged: "text-neutral-500",
};
const ymd = (iso: string) => iso.slice(0, 10);
diff --git a/web/src/pages/Ontology.tsx b/web/src/pages/Ontology.tsx
index c6d2c353..968a751e 100644
--- a/web/src/pages/Ontology.tsx
+++ b/web/src/pages/Ontology.tsx
@@ -1089,6 +1089,24 @@ function MissesPanel({
onError: (e: unknown) => void;
}) {
const [proposals, setProposals] = useState<OntologyProposals | null>(null);
+ // 最近一次采纳,供撤销。只留最近一次——旧批次要撤销走审计台账,
+ // 那里本来就记着每次采纳动了哪个关系、多少条
+ const [lastAdopt, setLastAdopt] = useState<{
+ batches: string[];
+ key: string;
+ moved: number;
+ } | null>(
+ null,
+ );
+ // 待认领的表层谓词:提案的影响面("将改写 57 条")从这里算
+ const surface = useQuery({
+ queryKey: ["surface-predicates", kbId],
+ queryFn: () => api.surfacePredicates(kbId),
+ });
+ const factsWaiting = (forms: string[]) => {
+ 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);
+ };
const suggest = useMutation({
mutationFn: () => api.suggestOntology(kbId),
@@ -1117,15 +1135,35 @@ function MissesPanel({
onError,
});
const approveRelation = useMutation({
- mutationFn: (p: { key: string; label: string; temporal?: string; functional?: boolean }) =>
- api.createRelationType(kbId, {
- key: p.key,
- label: p.label,
- temporal: p.temporal ?? "state",
- functional: p.functional ?? false,
- }),
- onSuccess: (_data, p) => {
- toast.success(S.toast.added);
+ // 带 forms 的提案走 adopt:建关系顺带把等着它的 related_to 事实改写过去。
+ // 只建关系的话本体长大了、图没变好——那些事实会继续是"有关联"
+ mutationFn: (p: {
+ key: string;
+ label: string;
+ temporal?: string;
+ functional?: boolean;
+ forms?: string[];
+ }) =>
+ p.forms?.length
+ ? api.adoptPredicate(kbId, {
+ key: p.key,
+ label: p.label,
+ temporal: p.temporal ?? "state",
+ functional: p.functional ?? false,
+ forms: p.forms,
+ })
+ : api.createRelationType(kbId, {
+ key: p.key,
+ label: p.label,
+ temporal: p.temporal ?? "state",
+ functional: p.functional ?? false,
+ }),
+ onSuccess: (data, p) => {
+ const d = data as { remapped?: number; batch?: string };
+ 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 });
setProposals(
(prev) =>
prev && { ...prev, relation_types: prev.relation_types.filter((x) => x.key !== p.key) },
@@ -1136,6 +1174,70 @@ function MissesPanel({
onError,
});
+ // 逐条串行而不是加个批量端点:每个谓词各有自己的批次和撤销粒度,
+ // 而且部分失败能如实报告("5 个成功,1 个 key 已存在")而不是整批回滚
+ const addAll = useMutation({
+ mutationFn: async (all: OntologyProposals) => {
+ const batches: string[] = [];
+ let moved = 0;
+ const failed: string[] = [];
+ for (const p of all.entity_types) {
+ try {
+ await api.createEntityType(kbId, { key: p.key, label: p.label });
+ } catch {
+ failed.push(p.key);
+ }
+ }
+ for (const p of all.relation_types) {
+ try {
+ if (p.forms?.length) {
+ const r = await api.adoptPredicate(kbId, {
+ key: p.key,
+ label: p.label,
+ temporal: p.temporal ?? "state",
+ functional: p.functional ?? false,
+ forms: p.forms,
+ });
+ moved += r.remapped;
+ if (r.remapped > 0) batches.push(r.batch);
+ } else {
+ await api.createRelationType(kbId, {
+ key: p.key,
+ label: p.label,
+ temporal: p.temporal ?? "state",
+ functional: p.functional ?? false,
+ });
+ }
+ } catch {
+ failed.push(p.key);
+ }
+ }
+ return { batches, moved, failed };
+ },
+ onSuccess: (r) => {
+ 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 });
+ setProposals(null);
+ onChanged();
+ },
+ onError,
+ });
+
+ const unadopt = useMutation({
+ mutationFn: async (batches: string[]) => {
+ let reverted = 0;
+ for (const b of batches) reverted += (await api.unadoptPredicate(kbId, b)).reverted;
+ return { reverted };
+ },
+ onSuccess: (r) => {
+ toast.success(S.ontology.reverted(r.reverted));
+ setLastAdopt(null);
+ onChanged();
+ },
+ onError,
+ });
+
return (
<div className="glass rounded-xl p-4">
<div className="flex items-center gap-3 mb-1">
@@ -1174,9 +1276,46 @@ 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>
+ <Button
+ size="sm"
+ variant="ghost"
+ className="ml-auto"
+ disabled={unadopt.isPending}
+ onClick={() => unadopt.mutate(lastAdopt.batches)}
+ >
+ {S.ontology.undoAdoptBtn}
+ </Button>
+ </div>
+ )}
+
{proposals && (
<div className="mt-4 border-t border-white/10 pt-3">
- <h4 className="text-xs font-bold text-neutral-400 mb-2">{S.ontology.proposals}</h4>
+ <div className="mb-2 flex items-center gap-2">
+ <h4 className="text-xs font-bold text-neutral-400">{S.ontology.proposals}</h4>
+ {/* 常见情形是"这些都对"——一条条点是把一个决定拆成八个 */}
+ {proposals.relation_types.length + proposals.entity_types.length > 1 && (
+ <Button
+ size="sm"
+ variant="ghost"
+ className="ml-auto"
+ disabled={addAll.isPending}
+ onClick={() => addAll.mutate(proposals)}
+ >
+ {addAll.isPending
+ ? S.ontology.addingAll
+ : S.ontology.addAll(
+ proposals.relation_types.length + proposals.entity_types.length,
+ )}
+ </Button>
+ )}
+ </div>
<div className="space-y-1.5">
{proposals.entity_types.map((p) => (
<div key={p.key} className="flex items-center gap-2 text-sm">
@@ -1200,6 +1339,16 @@ function MissesPanel({
<span className="font-mono text-neutral-300">{p.key}</span>
<span className="text-neutral-200">{p.label}</span>
{p.temporal && <Chip tone="neutral">{p.temporal}</Chip>}
+ {/* 影响面:采纳后会改写多少条、归并了哪些写法。没有这个,
+ "approve" 就只是凭空多一个空关系 */}
+ {!!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"