Skip to content

World's first open-source enterprise world model.

How a number is computed is not a claim about the world (#126)

WaylandYang97da5ea9eba2
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index e9202a44..8702aa07 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -777,3 +777,31 @@ pub struct ProposedAttribute {
/// 事实已经在那儿了,它们的主语是什么类是事实,不是判断
pub domain_keys: Vec<String>,
}
+
+/// 语义层的一条映射:业务概念 → 数据资产定义(见 `docs/decisions/0011`)。
+///
+/// **字段是列,不是 JSON 里的键。** 从前它是一条 `mapped_to` 事实,
+/// 这几样全塞在 `object_value` 里——于是「哪些概念映射到了 orders 这张表」
+/// 要扒 JSON,而「同一个概念同一个源只该有一条」这条约束数据库管不到。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct ConceptMapping {
+ pub id: Uuid,
+ pub concept_id: Uuid,
+ /// 概念的名字。读的一侧总要它(问数 prompt、Review 列表),
+ /// 每次再查一遍实体表是白跑
+ pub concept_name: String,
+ /// 挂载的数据源。同一个概念在不同源上可以有不同定义,这是有意支持的
+ pub source: String,
+ pub table_name: Option<String>,
+ pub expr: Option<String>,
+ pub sql: Option<String>,
+ pub unit: Option<String>,
+ pub summary: Option<String>,
+ /// 派生指标(「转化率 = 成交数 / 访问数」):算出来的,不是表里的列
+ pub derived: bool,
+ /// proposed | confirmed | rejected
+ ///
+ /// **状态而不是置信度。** 从前借事实的 confidence 表达「提议 0.6 / 确认 1.0」,
+ /// 那是把二值状态编码成浮点数,还顺带让它落进「低置信事实」那一档
+ pub status: String,
+}
diff --git a/crates/utopia-server/src/api/chat.rs b/crates/utopia-server/src/api/chat.rs
index 82c967db..2116e141 100644
--- a/crates/utopia-server/src/api/chat.rs
+++ b/crates/utopia-server/src/api/chat.rs
@@ -273,12 +273,15 @@ pub async fn chat(
// 写工具跟人走:editor 及以上的对话才带 remember,viewer 纯只读
// 挂载的数据源决定 query_data 是否入列(问数是读,viewer 亦可用)
let mounted_sources = utopia_store::datasources::mounted(&state.pool, kb_id).await?;
- // 语义层:人确认过的 指标/维度 → 数据资产 映射(置信 ≥0.75,与 Review 阈值互补),
- // 直接进 system prompt——问数优先用确认口径,而不是每次从 schema 猜
+ // 语义层:人确认过的 指标/维度 → 数据资产 映射,直接进 system prompt——
+ // 问数优先用确认口径,而不是每次从 schema 猜。
+ //
+ // 从前这里按 `confidence >= 0.75` 捞事实,而那个阈值是拿浮点数编码一个
+ // 二值状态(提议 0.6 / 确认 1.0)。现在读 `status = confirmed`(0011)
let mappings = if mounted_sources.is_empty() {
Vec::new()
} else {
- utopia_store::graph::confirmed_mappings(&state.pool, kb_id, 0.75, 30).await?
+ utopia_store::mappings::confirmed(&state.pool, kb_id, 30).await?
};
let can_write = utopia_store::access::kb_role(&state.pool, &user, &kb)
.await?
@@ -342,8 +345,30 @@ pub async fn chat(
system_prompt.push_str(
"\nSemantic layer (confirmed definitions — use these instead of guessing from schema):",
);
- for (name, def) in &mappings {
- system_prompt.push_str(&format!("\n- {name}: {def}"));
+ // 从前这里直接把整份 JSON 打进去。现在字段是列,只挑问数用得上的
+ // 那几样铺开——`sql` 与 `expr` 是「怎么算」,`unit` 是答里必须带的
+ // 量纲,`summary` 是给模型的一句人话
+ for m in &mappings {
+ let how = m
+ .sql
+ .as_deref()
+ .or(m.expr.as_deref())
+ .or(m.table_name.as_deref())
+ .unwrap_or("-");
+ let unit = m
+ .unit
+ .as_deref()
+ .map(|u| format!(" [{u}]"))
+ .unwrap_or_default();
+ let note = m
+ .summary
+ .as_deref()
+ .map(|s| format!(" — {s}"))
+ .unwrap_or_default();
+ system_prompt.push_str(&format!(
+ "\n- {} ({}){unit}: {how}{note}",
+ m.concept_name, m.source
+ ));
}
}
}
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index a485ef6b..16c3784e 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -283,6 +283,11 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
.route("/kbs/{id}/review", get(review_routes::list))
.route("/kbs/{id}/review/history", get(review_routes::history))
.route("/kbs/{id}/review/{review_id}", post(review_routes::decide))
+ // 语义层映射的表态(0011)。跟消解审核并排——都是「引擎提议、人裁决」
+ .route(
+ "/kbs/{id}/review/mappings/{mapping_id}",
+ post(review_routes::decide_mapping),
+ )
.route(
"/kbs/{id}/facts/{fact_id}/confirm",
post(review_routes::confirm_fact),
diff --git a/crates/utopia-server/src/api/review_routes.rs b/crates/utopia-server/src/api/review_routes.rs
index b4dfe630..ce058f5f 100644
--- a/crates/utopia-server/src/api/review_routes.rs
+++ b/crates/utopia-server/src/api/review_routes.rs
@@ -53,9 +53,14 @@ pub async fn list(
let merges = utopia_store::resolution::list_merges(&state.pool, kb_id, 30).await?;
let conflicts = utopia_store::temporal::list_conflicts(&state.pool, kb_id).await?;
let unconfirmed = utopia_store::graph::stale_facts(&state.pool, kb_id, 100).await?;
+ // 语义层的待表态映射(0011)。从前它借「低置信事实」那一档露面——
+ // 靠 confidence 0.6 混进去,而它根本不是一条关于世界的断言。
+ // 现在自成一档,前端也据此分组显示
+ let mappings = utopia_store::mappings::proposed(&state.pool, kb_id, 100).await?;
Ok(Json(json!({
"reviews": reviews, "facts": facts, "merges": merges,
- "conflicts": conflicts, "unconfirmed": unconfirmed
+ "conflicts": conflicts, "unconfirmed": unconfirmed,
+ "mappings": mappings
})))
}
@@ -385,3 +390,43 @@ pub async fn history(
utopia_store::audit::review_history(&state.pool, kb_id, per, page * per).await?;
Ok(Json(json!({ "events": events, "total": total })))
}
+
+#[derive(Deserialize)]
+pub struct DecideMappingReq {
+ /// confirmed | rejected
+ pub status: String,
+}
+
+/// 对一条语义层映射表态(0011)。
+///
+/// **改状态不删行**:确认发生过、拒绝也发生过。而拒绝留痕当下就有用——
+/// 下一轮探索会再次算出被拒绝过的那条,`propose` 的 `WHERE status = 'proposed'`
+/// 据此不把它刷回待看。
+pub async fn decide_mapping(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, mapping_id)): Path<(Uuid, Uuid)>,
+ Json(req): Json<DecideMappingReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ if !matches!(req.status.as_str(), "confirmed" | "rejected") {
+ return Err(utopia_core::AppError::invalid(
+ "bad_status",
+ "status 只能是 confirmed 或 rejected",
+ )
+ .into());
+ }
+ utopia_store::mappings::decide(&state.pool, kb_id, mapping_id, &req.status, user.id).await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "mapping.decided",
+ "concept_mapping",
+ Some(mapping_id),
+ json!({ "status": req.status }),
+ )
+ .await;
+ state.emit_review(kb_id);
+ Ok(Json(json!({ "ok": true })))
+}
diff --git a/crates/utopia-server/src/mappings.rs b/crates/utopia-server/src/mappings.rs
index 89c993d1..209be09e 100644
--- a/crates/utopia-server/src/mappings.rs
+++ b/crates/utopia-server/src/mappings.rs
@@ -1,15 +1,18 @@
//! 问数语义映射的 Agentic 探索:读挂载源的 schema + KB 既有概念,让 LLM 提议
//! "业务概念(Metric/Dimension 实体)→ 数据资产定义" 的映射。
//!
-//! 提议以低置信(0.6)mapped_to 事实落库 → 自动流入 Review 的低置信区,
-//! Confirm/Reject 零新 UI;确认(置信提满)后的映射注入问数 prompt。
+//! 提议写进 `concept_mappings`(status = proposed)→ Review 页自成一档,
+//! Confirm / Reject 之后 status 变 confirmed,问数只读确认过的那些。
+//!
+//! **从前它是一条 0.6 置信的 `mapped_to` 事实**,借「低置信事实」那一档露面。
+//! 搬出来的理由见 0011:它不是关于世界的断言,是配置——而「确认」这个动作
+//! 当时是 `UPDATE facts SET confidence = 1.0`,原地改一张不许原地改的表。
//! agent 只提议,口径生效权在人——与消解"宁分勿合"同一哲学。
use crate::llm_util;
use crate::state::AppState;
use uuid::Uuid;
-const PROPOSAL_CONFIDENCE: f32 = 0.6;
const MAX_SCHEMA_CHARS: usize = 12_000;
pub async fn explore_mappings(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {
@@ -133,61 +136,35 @@ pub async fn explore_mappings(state: &AppState, kb_id: Uuid) -> anyhow::Result<(
)
.await?;
- // 定义带 source + summary(Review 与 prompt 展示都靠 summary)
- let mut definition = p["definition"].clone();
- if !definition.is_object() {
+ // 定义拆成列写进 concept_mappings(0011)。从前它是一份塞进
+ // `object_value` 的 JSON,宾语挂在一条叫 mapped_to 的关系上——
+ // 而那条关系是本体里的一行,跟 works_at 并列。**它不是关于世界的
+ // 断言,是配置**,所以搬去自己的表
+ let def = &p["definition"];
+ if !def.is_object() {
continue;
}
- definition["source"] = serde_json::json!(source);
- if let Some(s) = p["summary"].as_str() {
- definition["summary"] = serde_json::json!(s);
- }
-
- let mapped_to: Option<(Uuid,)> =
- sqlx::query_as("SELECT id FROM relation_types WHERE kb_id = $1 AND key = 'mapped_to'")
- .bind(kb_id)
- .fetch_optional(&state.pool)
- .await?;
- let Some((mapped_to,)) = mapped_to else {
- continue;
+ let s = |k: &str| {
+ def[k]
+ .as_str()
+ .filter(|x| !x.is_empty())
+ .map(str::to_string)
};
-
- let (fact_id, created) = utopia_store::graph::insert_value_fact(
+ utopia_store::mappings::propose(
&state.pool,
kb_id,
resolved.entity_id,
- Some(mapped_to),
- &definition,
- // 问数映射不带时间:两端都空
- utopia_store::graph::Validity::default(),
- PROPOSAL_CONFIDENCE,
+ source,
+ s("table").as_deref(),
+ s("expr").as_deref(),
+ s("sql").as_deref(),
+ s("unit").as_deref(),
+ // summary 是给人看的那句:Review 列表与问数 prompt 都靠它
+ p["summary"].as_str().or(def["summary"].as_str()),
+ def["derived"].as_bool().unwrap_or(false),
)
.await?;
- if created {
- accepted += 1;
- // 证据挂 schema 文档的首个 live chunk(rationale 作 quote)
- if let Some((chunk_id,)) = sqlx::query_as::<_, (Uuid,)>(
- "SELECT c.id FROM chunks c JOIN documents d ON d.id = c.document_id
- WHERE d.kb_id = $1 AND d.external_key LIKE 'datasource:%:schema'
- AND c.superseded_at IS NULL
- ORDER BY c.seq LIMIT 1",
- )
- .bind(kb_id)
- .fetch_optional(&state.pool)
- .await?
- {
- let rationale = p["rationale"].as_str().unwrap_or("");
- // 谓词是代码写死的 mapped_to,不是模型给的说法,没有表层形式可留
- utopia_store::graph::add_evidence(
- &state.pool,
- fact_id,
- chunk_id,
- (!rationale.is_empty()).then_some(rationale),
- None,
- )
- .await?;
- }
- }
+ accepted += 1;
}
tracing::info!(%kb_id, proposals = accepted, "映射探索完成,提议已入审核队列");
diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rs
index 0bef16ba..48717df0 100644
--- a/crates/utopia-store/src/lib.rs
+++ b/crates/utopia-store/src/lib.rs
@@ -13,6 +13,7 @@ pub mod extraction_drops;
pub mod graph;
pub mod jobs;
pub mod kbs;
+pub mod mappings;
pub mod members;
pub mod memory;
pub mod model_limits;
diff --git a/crates/utopia-store/src/mappings.rs b/crates/utopia-store/src/mappings.rs
new file mode 100644
index 00000000..52378a93
--- /dev/null
+++ b/crates/utopia-store/src/mappings.rs
@@ -0,0 +1,201 @@
+//! 语义层的「业务概念 → 数据资产」映射(见 `docs/decisions/0011`)。
+//!
+//! 它从前是一条 `mapped_to` 事实,宾语是塞在 `object_value` 里的一份 JSON。
+//! 搬出来的理由写在迁移 0055 里,一句话:**它不是关于世界的断言,是配置**。
+//!
+//! 与账本的区别在这里就能看见:这张表**允许原地改**。`confirm` 改的是
+//! 「这条配置生效了没有」,不是「我们对世界的认知变了」——所以它不需要
+//! append-only,改之前的那一版进 `concept_mapping_revisions` 留痕即可。
+
+use sqlx::PgPool;
+use utopia_core::models::ConceptMapping;
+use utopia_core::{AppError, AppResult};
+use uuid::Uuid;
+
+/// 探索任务提议一条映射。
+///
+/// **同一个 (概念, 源) 只有一条**,由主键管——从前这条唯一性藏在 `object_value`
+/// 内部,数据库看不见,只能靠确认流程显式闭合。
+///
+/// 已经有人表过态的不覆盖:重跑探索会再次算出被拒绝过的那条,不加这一句
+/// 它就被刷回待看,等于每跑一次都把人的否决抹掉一次(`ontology_proposals`
+/// 那边踩过同一个坑,见 0049)。
+#[allow(clippy::too_many_arguments)]
+pub async fn propose(
+ pool: &PgPool,
+ kb_id: Uuid,
+ concept_id: Uuid,
+ source: &str,
+ table_name: Option<&str>,
+ expr: Option<&str>,
+ sql: Option<&str>,
+ unit: Option<&str>,
+ summary: Option<&str>,
+ derived: bool,
+) -> AppResult<Uuid> {
+ // **`DO UPDATE ... WHERE` 不满足时 `RETURNING` 一行都不返回。**
+ //
+ // 这是 Postgres 的实情而不是直觉:条件挡住更新,那一行就不算被这条语句
+ // 动过,于是也不出现在 RETURNING 里。测试当场撞上——第二次提议一条已被
+ // 拒绝的映射,`fetch_one` 报「no rows returned」。
+ //
+ // 所以把 id 单独查出来:更新与否是一回事,「这条映射是哪一行」是另一回事。
+ let existing: Option<(Uuid,)> = sqlx::query_as(
+ "SELECT id FROM concept_mappings
+ WHERE kb_id = $1 AND concept_id = $2 AND source = $3",
+ )
+ .bind(kb_id)
+ .bind(concept_id)
+ .bind(source)
+ .fetch_optional(pool)
+ .await?;
+ let id = existing.map(|(i,)| i).unwrap_or_else(Uuid::now_v7);
+ sqlx::query(
+ "INSERT INTO concept_mappings
+ (id, kb_id, concept_id, source, table_name, expr, sql, unit, summary, derived)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
+ ON CONFLICT (kb_id, concept_id, source) DO UPDATE
+ SET table_name = EXCLUDED.table_name, expr = EXCLUDED.expr,
+ sql = EXCLUDED.sql, unit = EXCLUDED.unit,
+ summary = EXCLUDED.summary, derived = EXCLUDED.derived,
+ updated_at = now()
+ WHERE concept_mappings.status = 'proposed'",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .bind(concept_id)
+ .bind(source)
+ .bind(table_name)
+ .bind(expr)
+ .bind(sql)
+ .bind(unit)
+ .bind(summary)
+ .bind(derived)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+/// 还等着人表态的。Review 页读它。
+pub async fn proposed(pool: &PgPool, kb_id: Uuid, limit: i64) -> AppResult<Vec<ConceptMapping>> {
+ Ok(sqlx::query_as(
+ "SELECT m.id, m.concept_id, e.canonical_name AS concept_name, m.source,
+ m.table_name, m.expr, m.sql, m.unit, m.summary, m.derived, m.status
+ FROM concept_mappings m
+ JOIN entities e ON e.id = m.concept_id
+ WHERE m.kb_id = $1 AND m.status = 'proposed'
+ ORDER BY e.canonical_name, m.source
+ LIMIT $2",
+ )
+ .bind(kb_id)
+ .bind(limit)
+ .fetch_all(pool)
+ .await?)
+}
+
+/// 人确认过的。问数把它们注进 system prompt——**只用确认过的口径**,
+/// 而不是每次从 schema 猜。
+pub async fn confirmed(pool: &PgPool, kb_id: Uuid, limit: i64) -> AppResult<Vec<ConceptMapping>> {
+ Ok(sqlx::query_as(
+ "SELECT m.id, m.concept_id, e.canonical_name AS concept_name, m.source,
+ m.table_name, m.expr, m.sql, m.unit, m.summary, m.derived, m.status
+ FROM concept_mappings m
+ JOIN entities e ON e.id = m.concept_id
+ WHERE m.kb_id = $1 AND m.status = 'confirmed'
+ ORDER BY e.canonical_name, m.source
+ LIMIT $2",
+ )
+ .bind(kb_id)
+ .bind(limit)
+ .fetch_all(pool)
+ .await?)
+}
+
+/// 有人表态了。
+///
+/// **改状态不删行**:确认发生过、拒绝也发生过。而拒绝留痕还有当下就用得着的
+/// 作用——`propose` 的 `WHERE status = 'proposed'` 据此不把它刷回待看。
+pub async fn decide(
+ pool: &PgPool,
+ kb_id: Uuid,
+ mapping_id: Uuid,
+ status: &str,
+ actor: Uuid,
+) -> AppResult<()> {
+ let res = sqlx::query(
+ "UPDATE concept_mappings
+ SET status = $3, decided_by = $4, decided_at = now(), updated_at = now()
+ WHERE id = $2 AND kb_id = $1",
+ )
+ .bind(kb_id)
+ .bind(mapping_id)
+ .bind(status)
+ .bind(actor)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
+
+/// 改一条确认过的口径。**改之前那一版先进 revisions**——问数回溯历史报表时
+/// 要答得出「上季度这个数是怎么算的」。
+///
+/// 存整版快照而不是差异:读的时候要的就是「当时是什么」,而差异得从头重放
+/// 才能回答这个问题。
+#[allow(clippy::too_many_arguments)]
+pub async fn revise(
+ pool: &PgPool,
+ kb_id: Uuid,
+ mapping_id: Uuid,
+ table_name: Option<&str>,
+ expr: Option<&str>,
+ sql: Option<&str>,
+ unit: Option<&str>,
+ summary: Option<&str>,
+ derived: bool,
+ actor: Uuid,
+) -> AppResult<()> {
+ let mut tx = pool.begin().await?;
+ let before: Option<(serde_json::Value,)> = sqlx::query_as(
+ "SELECT to_jsonb(m) - 'id' - 'kb_id' FROM concept_mappings m
+ WHERE m.id = $2 AND m.kb_id = $1",
+ )
+ .bind(kb_id)
+ .bind(mapping_id)
+ .fetch_optional(&mut *tx)
+ .await?;
+ let Some((before,)) = before else {
+ tx.rollback().await?;
+ return Err(AppError::NotFound);
+ };
+ sqlx::query(
+ "INSERT INTO concept_mapping_revisions (id, mapping_id, before, changed_by)
+ VALUES ($1, $2, $3, $4)",
+ )
+ .bind(Uuid::now_v7())
+ .bind(mapping_id)
+ .bind(before)
+ .bind(actor)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query(
+ "UPDATE concept_mappings
+ SET table_name = $3, expr = $4, sql = $5, unit = $6, summary = $7,
+ derived = $8, updated_at = now()
+ WHERE id = $2 AND kb_id = $1",
+ )
+ .bind(kb_id)
+ .bind(mapping_id)
+ .bind(table_name)
+ .bind(expr)
+ .bind(sql)
+ .bind(unit)
+ .bind(summary)
+ .bind(derived)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(())
+}
diff --git a/crates/utopia-store/tests/a_mapping_is_not_a_fact.rs b/crates/utopia-store/tests/a_mapping_is_not_a_fact.rs
new file mode 100644
index 00000000..c8e18dbb
--- /dev/null
+++ b/crates/utopia-store/tests/a_mapping_is_not_a_fact.rs
@@ -0,0 +1,191 @@
+//! 语义层映射的两条硬性质——打在真库上(见 `docs/decisions/0011`)。
+//!
+//! 这两条都是搬出账本换来的东西,也正是从前做不到的:
+//!
+//! 1. **同一个 (概念, 源) 只有一条。** 从前这条唯一性藏在 `object_value`
+//! 这个 JSONB 内部,数据库看不见,只能靠确认流程显式闭合——也就是靠流程
+//! 而不是约束。现在它是主键。
+//! 2. **表过态的不被下一轮探索刷回待看。** `ontology_proposals` 那边踩过同一个
+//! 坑(0049):重跑必然再次算出被拒绝过的那条,不挡住就等于每跑一次都把
+//! 人的否决抹掉一次。
+
+use sqlx::PgPool;
+use uuid::Uuid;
+
+async fn fixture(pool: &PgPool) -> anyhow::Result<(Uuid, Uuid, Uuid)> {
+ let (org, ws, kb, ent) = (
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ );
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'map-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'map-test')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'map-test')")
+ .bind(kb)
+ .bind(ws)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, canonical_name, aliases) VALUES ($1, $2, '营收', '{}')",
+ )
+ .bind(ent)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ Ok((org, kb, ent))
+}
+
+#[tokio::test]
+async fn one_concept_one_source_one_mapping() -> anyhow::Result<()> {
+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let (_org, kb, ent) = fixture(&pool).await?;
+
+ let run = async {
+ let p = |t: &'static str| {
+ utopia_store::mappings::propose(
+ &pool,
+ kb,
+ ent,
+ "warehouse",
+ Some(t),
+ None,
+ None,
+ None,
+ None,
+ false,
+ )
+ };
+ let a = p("orders").await?;
+ let b = p("orders_v2").await?;
+ assert_eq!(a, b, "同一个 (概念, 源) 该是同一行,不是两行");
+
+ let got = utopia_store::mappings::proposed(&pool, kb, 100).await?;
+ assert_eq!(got.len(), 1, "只该有一条");
+ assert_eq!(
+ got[0].table_name.as_deref(),
+ Some("orders_v2"),
+ "重跑探索该刷新定义"
+ );
+
+ // 换一个源就是另一条:同一概念在不同源上有不同定义是有意支持的
+ utopia_store::mappings::propose(
+ &pool,
+ kb,
+ ent,
+ "lakehouse",
+ Some("f_orders"),
+ None,
+ None,
+ None,
+ None,
+ false,
+ )
+ .await?;
+ assert_eq!(
+ utopia_store::mappings::proposed(&pool, kb, 100)
+ .await?
+ .len(),
+ 2,
+ "不同源该各有一条"
+ );
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ // **只删知识库,不删 org/user。** 用户是软删除的,生产代码里没有
+ // `DELETE FROM users`——测试也不该造一个产品里不存在的动作,否则
+ // 撞上的外键约束是夹具自己的问题,会被误当成产品缺陷(实测发生过)
+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
+ .bind(kb)
+ .execute(&pool)
+ .await?;
+ run
+}
+
+#[tokio::test]
+async fn a_rejected_mapping_does_not_come_back() -> anyhow::Result<()> {
+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let (org, kb, ent) = fixture(&pool).await?;
+
+ let run = async {
+ let user = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO users (id, org_id, email, display_name, password_hash)
+ VALUES ($1, $2, $1 || '@m.test', 'm', 'x')",
+ )
+ .bind(user)
+ .bind(org)
+ .execute(&pool)
+ .await?;
+
+ let id = utopia_store::mappings::propose(
+ &pool,
+ kb,
+ ent,
+ "warehouse",
+ Some("orders"),
+ None,
+ None,
+ None,
+ None,
+ false,
+ )
+ .await?;
+ utopia_store::mappings::decide(&pool, kb, id, "rejected", user).await?;
+
+ // 下一轮探索会再次算出同一条——它不该被刷回待看
+ utopia_store::mappings::propose(
+ &pool,
+ kb,
+ ent,
+ "warehouse",
+ Some("orders"),
+ None,
+ None,
+ None,
+ None,
+ false,
+ )
+ .await?;
+ assert!(
+ utopia_store::mappings::proposed(&pool, kb, 100)
+ .await?
+ .is_empty(),
+ "拒绝过的不该重新排队"
+ );
+ // 确认过的同理不该被探索覆盖
+ assert!(
+ utopia_store::mappings::confirmed(&pool, kb, 100)
+ .await?
+ .is_empty(),
+ "拒绝的也不该出现在确认列表里"
+ );
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ // **只删知识库,不删 org/user。** 用户是软删除的,生产代码里没有
+ // `DELETE FROM users`——测试也不该造一个产品里不存在的动作,否则
+ // 撞上的外键约束是夹具自己的问题,会被误当成产品缺陷(实测发生过)
+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
+ .bind(kb)
+ .execute(&pool)
+ .await?;
+ run
+}
diff --git a/docs/decisions/0011-a-mapping-is-not-a-fact.md b/docs/decisions/0011-a-mapping-is-not-a-fact.md
new file mode 100644
index 00000000..765e7546
--- /dev/null
+++ b/docs/decisions/0011-a-mapping-is-not-a-fact.md
@@ -0,0 +1,125 @@
+# 0011 · 「怎么算」不是「有什么」
+
+- **状态**:规划中
+- **成文**:2026-08-31(约定见 [README](README.md))
+- **相关**:[0009](0009-no-type-is-a-type.md) 删掉内置实体类、[0010](0010-no-relation-is-no-relation.md)
+ 删掉兜底关系、`#125` 删掉其余八条种子关系——本文是同一条线的最后一段:
+ **本体里只该剩下词表**
+
+> 本篇是拆一个当初有意为之的复用。原设计不是疏忽,它买到了三样具体的东西,
+> 所以这里先把买到的列清楚,再说为什么仍然要拆。
+
+## 现状
+
+问数语义层把「业务概念 → 数据资产定义」存成一条事实:
+
+```
+主语 = 概念实体(Metric / Dimension)
+谓词 = mapped_to ← relation_types 里的一行,与 works_at 并列
+宾语 = object_value JSON { source, table?, expr?, sql?, unit?, summary? }
+置信 = 0.6 提议 / 1.0 已确认
+```
+
+整条路:
+
+```
+探索任务读挂载源 schema → LLM 提议 → 0.6 置信的 mapped_to 事实
+ ↓ review_routes 的 low_confidence_facts 按 <0.75 捞起来
+人在 Review 页 Confirm → confirm_fact 把 confidence 改成 1.0
+ ↓ chat.rs 读 confirmed_mappings(≥0.75)
+注入问数 system prompt
+```
+
+## 复用买到了什么
+
+**一、Review 流零新 UI。** 提议以低置信落库,自动流进「低置信事实」那一档,
+Confirm / Reject 用的是现成的按钮。`mappings.rs` 的模块注释把这一点写成了设计
+意图,不是事后总结。
+
+**二、双时态历史。** 口径改过没有、什么时候改的、改之前是什么——账本本来就答得出来。
+
+**三、证据链。** 与其它事实同构,实体历史页面直接就能展示。
+
+这三样都是真的,拆开就要重做。
+
+## 为什么仍然要拆
+
+### 1. 它不是关于世界的断言
+
+本体回答「世界上有什么、它们之间是什么关系」。`mapped_to` 回答的是
+「**这个数在我们的数据库里怎么算出来**」——它是实现细节,跟 `works_at`
+不是一类东西。
+
+这一条与 0009 删掉内置实体类、0010 删掉 `related_to` 是同一句话的三次应用:
+**代码层面的机制不该混进词表**。0009 说的是「`concept` 是控制流不是词表」,
+这里是「`mapped_to` 是配置不是词表」。
+
+### 2. 它出现在不该出现的地方
+
+`relation_types` 里的一行意味着:本体页把它列成一条关系、抽取提示词把它端给
+模型、本体规模统计把它算进去、`#125` 之后它还是**唯一一条种子关系**——
+一个新库开局本体里只有它,而它跟用户要建的知识图谱毫无关系。
+
+### 3. 「确认」这个动作已经在违反账本的地基
+
+```rust
+// graph.rs — confirm_fact
+UPDATE facts SET confidence = 1.0 WHERE id = $1
+```
+
+账本是 append-only 的:纠正一条事实要插新行 + `supersedes` 旧行,因为
+**认知变更本身是信息**(0001 P0 的立论)。而确认口径是**原地 UPDATE**——
+它改的不是「我们对世界的认知」,是「这条配置生效了没有」。
+
+一个需要原地改状态的东西住在一张不许原地改的表里,这本身就是它不合身的证据。
+今天没出事,是因为口径确认的语义恰好简单到用一个浮点数就能表达。
+
+### 4. 形状对不上
+
+一条映射真正的字段是 `source / table / expr / sql / unit / summary`,
+现在全塞在 `object_value` 这个 JSONB 里。于是:
+
+- 查不动。「哪些概念映射到了 orders 这张表」要扒 JSON
+- 约束不了。同一个概念同一个源应该只有一条,而唯一性粒度
+ `(概念, 源)` 藏在 `object_value` 内部,数据库管不到——今天靠确认流程
+ 显式闭合,靠的是流程不是约束
+- 说不清。`mapped_to` 的 range 是什么?没有答案,因为宾语不是实体也不是
+ 某个数据类型,是一份配置
+
+## 决定
+
+**单独一张 `concept_mappings` 表。** 概念(entity id)→ 数据资产定义,
+字段展开成列,唯一性 `(kb_id, concept_id, source)` 由主键管。
+
+`mapped_to` 从 `relation_types` 退场,`DEFAULT_RELATION_TYPES` 随之清空——
+建库不再播种任何关系,本体从第一天起就只有用户自己导入的词表。
+
+## 要重做的三样,逐条
+
+**Review 流**:不再借低置信事实那一档。语义层的待确认项是另一种东西
+(配置提议,不是知识断言),Review 页给它一个自己的分组。这与 0002 R0
+的一致性检查落在同一处——那一档也是「引擎提议、人裁决」。
+
+**历史**:表上自带 `created_at / confirmed_at / confirmed_by`,加一张
+`concept_mapping_revisions` 记口径演变。**不做双时态**——口径没有「有效时间」
+与「记录时间」两条轴,它只有「什么时候生效的」一条。硬套账本那套是把复杂度
+搬过来而不是解决它。
+
+**证据链**:映射的证据是「LLM 读了哪张表的 schema 提议的」,与事实的
+「哪一句原文」不是一回事,本来就该分开记。
+
+## 代价,写在前面
+
+- **一次数据迁移**:现有的 `mapped_to` 事实要搬进新表。库里是 mock 数据,
+ 所以这一刀不写迁移,直接换(与 `#125` 同)。真发布之后就没有这个便利了。
+- **三处接线要改**:`mappings.rs` 写入、`review_routes` 读取、`chat.rs` 注入。
+- **短期内多一段 UI**:Review 页要多一个分组。0002 R0 也需要它,两者合并做
+ 一次,别做两遍。
+
+## 开放问题
+
+- **确认过的口径改了怎么办?** 双时态那套答得出「上季度的口径是什么」,
+ 换成 revisions 表之后要显式设计。问数回溯历史报表时会撞上它。
+- **多源同概念**:`(kb_id, concept_id, source)` 允许同一个概念在不同源上有
+ 不同定义,这是有意的(0010 之前的注释就这么写)。但问数该用哪一条?
+ 今天靠 prompt 里全给、让模型挑。这条不因本篇改变,但搬表之后更容易加规则。
diff --git a/docs/decisions/README.md b/docs/decisions/README.md
index 78e40e41..29d1d528 100644
--- a/docs/decisions/README.md
+++ b/docs/decisions/README.md
@@ -32,6 +32,7 @@
| 0008 | [预制本体包作为冷启动](0008-ontology-packs-as-cold-start.md) | 规划中 · 建库仍只发种子关系 |
| 0009 | [「还没判出来」不该是一个类](0009-no-type-is-a-type.md) | 已实施 · `entities.type_id` 改为可空 |
| 0010 | [「说不出是什么关系」不该是一个关系](0010-no-relation-is-no-relation.md) | 已实施 · `facts.predicate_id` 改为可空 · 0009 在关系侧的孪生 · **含一次七分钟后长回来的修订** |
+| 0011 | [「怎么算」不是「有什么」](0011-a-mapping-is-not-a-fact.md) | 规划中 · 语义层映射搬出本体 · 0009/0010 那条线的最后一段 |
## 不是决策记录的那些
diff --git a/migrations/0055_a_mapping_is_not_a_fact.sql b/migrations/0055_a_mapping_is_not_a_fact.sql
new file mode 100644
index 00000000..b3efc044
--- /dev/null
+++ b/migrations/0055_a_mapping_is_not_a_fact.sql
@@ -0,0 +1,83 @@
+-- 语义层的「概念 → 数据资产」映射搬出本体,见 docs/decisions/0011。
+--
+-- 从前它是一条 `mapped_to` 事实:主语是概念实体,宾语是塞在 `object_value`
+-- 里的一份 JSON 配置,而 `mapped_to` 本身是 `relation_types` 里的一行,
+-- 与 `works_at` 并列。
+--
+-- 拆开的理由,三条都不是洁癖:
+--
+-- 1. **它不是关于世界的断言。** 本体回答「世界上有什么」,这个回答的是
+-- 「这个数在我们的数据库里怎么算」。与 0009 说「concept 是控制流不是词表」、
+-- 0010 说「related_to 是兜底不是关系」是同一句话的第三次应用。
+--
+-- 2. **「确认」这个动作已经在违反账本的地基。** `confirm_fact` 是
+-- `UPDATE facts SET confidence = 1.0`——原地改。而账本是 append-only 的,
+-- 纠正事实要插新行 + supersedes,因为认知变更本身是信息(0001 P0)。
+-- 确认口径改的不是认知,是「这条配置生效了没有」。一个需要原地改状态的
+-- 东西住在一张不许原地改的表里,本身就是它不合身的证据。
+--
+-- 3. **形状对不上。** 真正的字段是 source / table / expr / sql / unit /
+-- summary,全塞在一个 JSONB 里:查不动(「哪些概念映射到了 orders」要扒
+-- JSON)、约束不了(唯一性粒度 (概念,源) 藏在 object_value 内部,
+-- 数据库管不到,今天靠流程而不是约束)。
+
+CREATE TABLE concept_mappings (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ -- 被映射的业务概念(Metric / Dimension 那类实体)
+ concept_id UUID NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
+ -- 挂载的数据源。**它进主键**:同一个概念在不同源上有不同定义是有意支持的,
+ -- 而同一个概念在同一个源上只该有一条——这条从前靠确认流程显式闭合,
+ -- 现在由数据库管
+ source TEXT NOT NULL,
+ -- 怎么算。字段展开成列而不是继续塞 JSON——它们是这张表存在的理由
+ table_name TEXT,
+ expr TEXT,
+ sql TEXT,
+ unit TEXT,
+ summary TEXT,
+ -- 派生指标(比如「转化率 = 成交数 / 访问数」):算出来的,不是表里的列
+ derived BOOLEAN NOT NULL DEFAULT FALSE,
+
+ -- **状态而不是置信度。** 从前借事实的 confidence 表达「提议 0.6 / 确认 1.0」,
+ -- 那是把一个二值状态编码成浮点数,还顺带让它落进「低置信事实」那一档。
+ -- 这里说清楚它是什么
+ status TEXT NOT NULL DEFAULT 'proposed'
+ CHECK (status IN ('proposed', 'confirmed', 'rejected')),
+ -- NULL = 还没人表态。确认与拒绝都留痕:拒绝过的不该被下一轮探索刷回待看。
+ --
+ -- 裸外键,与 `entity_merges.merged_by`、`ontology_proposals.decided_by`
+ -- 那几处一致——**用户是软删除的,生产代码里没有 `DELETE FROM users`**,
+ -- 所以这条外键的删除规则永远不会被触发,而归因保住了。
+ decided_by UUID REFERENCES users(id),
+ decided_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+
+ UNIQUE (kb_id, concept_id, source)
+);
+
+-- 问数只读确认过的(chat.rs 注入 system prompt),而 Review 只捞待表态的。
+-- 两条查询都按 kb + status 走
+CREATE INDEX concept_mappings_status_idx ON concept_mappings (kb_id, status);
+
+-- 口径演变留痕。**不做双时态**:口径没有「有效时间」与「记录时间」两条轴,
+-- 它只有「什么时候生效的」一条。硬套账本那套是把复杂度搬过来,不是解决它。
+CREATE TABLE concept_mapping_revisions (
+ id UUID PRIMARY KEY,
+ mapping_id UUID NOT NULL REFERENCES concept_mappings(id) ON DELETE CASCADE,
+ -- 改之前那一版的全文。存快照而不是差异:读的时候要的是「当时是什么」,
+ -- 而差异要从头重放才能回答这个问题
+ before JSONB NOT NULL,
+ changed_by UUID REFERENCES users(id),
+ changed_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE INDEX concept_mapping_revisions_idx
+ ON concept_mapping_revisions (mapping_id, changed_at DESC);
+
+-- 旧的 mapped_to 事实不迁移:仓库尚未发布,库里都是 mock 知识(与 #125 同)。
+-- 它们留在账本里不碍事——`confirmed_mappings` 那条查询会随代码一起改掉,
+-- 于是再没有人读它们。
+--
+-- **真发布之后就没有这个便利了**,写在这里免得下次照抄。
diff --git a/web/src/api.ts b/web/src/api.ts
index 2314e991..e4a4391e 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -270,6 +270,26 @@ export interface ReviewItem {
right: ReviewSide;
}
+
+/** 语义层的一条映射:业务概念 → 数据资产定义(见 docs/decisions/0011)。
+ *
+ * 字段是列而不是 JSON 里的键——从前它是一条 `mapped_to` 事实,
+ * 这几样全塞在 `object_value` 里。 */
+export interface ConceptMapping {
+ id: string;
+ concept_id: string;
+ concept_name: string;
+ /** 挂载的数据源。同一概念在不同源上可以有不同定义 */
+ source: string;
+ table_name: string | null;
+ expr: string | null;
+ sql: string | null;
+ unit: string | null;
+ summary: string | null;
+ /** 派生指标:算出来的,不是表里的列 */
+ derived: boolean;
+ status: "proposed" | "confirmed" | "rejected";
+}
export interface FactReviewItem {
id: string;
subject_name: string;
@@ -1130,6 +1150,7 @@ export const api = {
merges: MergeLog[];
conflicts: ConflictItem[];
unconfirmed: FactReviewItem[];
+ mappings: ConceptMapping[];
}>(`/api/v1/kbs/${kbId}/review`),
closeFact: (kbId: string, factId: string, validTo: string) =>
request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/close`, {
@@ -1150,6 +1171,12 @@ export const api = {
method: "POST",
body: JSON.stringify({ action }),
}),
+ /** 对一条语义层映射表态(0011)。改状态不删行——拒绝留痕,下一轮探索不再提议它 */
+ decideMapping: (kbId: string, mappingId: string, status: "confirmed" | "rejected") =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/mappings/${mappingId}`, {
+ method: "POST",
+ body: JSON.stringify({ status }),
+ }),
confirmFact: (kbId: string, factId: string) =>
request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/confirm`, {
method: "POST",
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index dfe10539..4d0fcf89 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -887,6 +887,7 @@ export const en = {
railConflicts: "Conflicts",
railUnconfirmed: "Unconfirmed",
railLowConfidence: "Low confidence",
+ railMappings: "Semantic layer",
railDecisions: "Decisions",
railMerges: "Merges",
categoryEmpty: "This queue is clear.",
@@ -932,6 +933,10 @@ export const en = {
merge: "Merge",
keep: "Keep separate",
lowConfidence: "Low-confidence facts",
+ mappings: "Semantic layer",
+ mappingsHint:
+ "Proposed mappings from a business concept to how it is computed. Confirm one and Ask uses it instead of guessing from the schema.",
+ mappingDerived: "derived",
lowConfidenceHint:
"Extracted with confidence below 75%. Confirm to trust, reject to remove from the graph (the ledger keeps the record).",
confirm: "Confirm",
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 0c9a6790..244dcfc8 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -790,6 +790,7 @@ export const zh: Strings = {
railConflicts: "冲突",
railUnconfirmed: "未确认",
railLowConfidence: "低置信度",
+ railMappings: "语义层",
railDecisions: "决定",
railMerges: "合并",
categoryEmpty: "这个队列是空的。",
@@ -832,6 +833,10 @@ export const zh: Strings = {
merge: "合并",
keep: "保持分开",
lowConfidence: "低置信度事实",
+ mappings: "语义层",
+ mappingsHint:
+ "从业务概念到「这个数怎么算」的提议。确认之后问数直接用这个口径,而不是每次从 schema 猜。",
+ mappingDerived: "派生",
lowConfidenceHint:
"抽取时置信度低于 75%。确认表示采信,驳回表示从图谱移除(台账仍留有记录)。",
confirm: "确认",
diff --git a/web/src/pages/Review.tsx b/web/src/pages/Review.tsx
index 78f9457d..1fe5738b 100644
--- a/web/src/pages/Review.tsx
+++ b/web/src/pages/Review.tsx
@@ -2,6 +2,7 @@ import { useEffect, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
api,
+ type ConceptMapping,
type ConflictItem,
type FactReviewItem,
type MergeLog,
@@ -437,6 +438,58 @@ function DecisionRow({ e }: { e: ReviewHistoryEvent }) {
);
}
+
+/** 一条待表态的语义层映射(0011)。
+ *
+ * 展示的重点是**「这个数怎么算」**——SQL / 表达式 / 表名按这个优先级取一个,
+ * 因为人要判断的正是它对不对。概念名与源是身份,unit 是答里必须带的量纲。 */
+function MappingRow({
+ mapping: m,
+ busy,
+ onDecide,
+}: {
+ mapping: ConceptMapping;
+ busy: boolean;
+ onDecide: (status: "confirmed" | "rejected") => void;
+}) {
+ const how = m.sql ?? m.expr ?? m.table_name ?? "—";
+ return (
+ <div className="glass rounded-xl p-3">
+ <div className="flex items-baseline gap-2 flex-wrap">
+ <span className="text-sm text-neutral-200">{m.concept_name}</span>
+ <span className="text-[11px] text-neutral-500">{m.source}</span>
+ {m.unit && (
+ <span className="text-[11px] text-neutral-500">[{m.unit}]</span>
+ )}
+ {m.derived && (
+ <span className="text-[11px] text-[var(--u-warn)]">
+ {S.review.mappingDerived}
+ </span>
+ )}
+ </div>
+ <div className="mt-1 u-num text-xs text-neutral-400 break-all">{how}</div>
+ {m.summary && (
+ <p className="mt-1 text-xs text-neutral-500">{m.summary}</p>
+ )}
+ <div className="mt-2 flex gap-1.5">
+ <button
+ className="u-btn text-xs"
+ disabled={busy}
+ onClick={() => onDecide("rejected")}
+ >
+ {S.review.reject}
+ </button>
+ <button
+ className="u-btn u-btn-primary text-xs"
+ disabled={busy}
+ onClick={() => onDecide("confirmed")}
+ >
+ {S.review.confirm}
+ </button>
+ </div>
+ </div>
+ );
+}
/* ---------- 页面:左栏分类 + 单类内容区 ---------- */
type Sel =
@@ -444,6 +497,9 @@ type Sel =
| "conflicts"
| "unconfirmed"
| "lowconf"
+ // 语义层的待表态映射(0011)。从前它借「低置信事实」那一档露面——
+ // 靠 0.6 的置信度混进去,而它根本不是一条关于世界的断言
+ | "mappings"
| "decisions"
| "merges";
@@ -452,12 +508,14 @@ const QUEUE_ORDER: Sel[] = [
"conflicts",
"unconfirmed",
"lowconf",
+ "mappings",
];
const PAGE_SIZE: Record<Sel, number> = {
duplicates: DUP_PAGE,
conflicts: CONFLICT_PAGE,
unconfirmed: FACT_PAGE,
lowconf: FACT_PAGE,
+ mappings: FACT_PAGE,
merges: MERGE_PAGE,
decisions: 20,
};
@@ -549,6 +607,16 @@ export function Review() {
: api.rejectFact(kb!.id, id),
onSettled: invalidate,
});
+ const mappingAction = useMutation({
+ mutationFn: ({
+ id,
+ status,
+ }: {
+ id: string;
+ status: "confirmed" | "rejected";
+ }) => api.decideMapping(kb!.id, id, status),
+ onSettled: invalidate,
+ });
const revert = useMutation({
mutationFn: (mergeId: string) => api.revertMerge(kb!.id, mergeId),
onSettled: invalidate,
@@ -578,6 +646,7 @@ export function Review() {
conflicts: data?.conflicts?.length ?? 0,
unconfirmed: data?.unconfirmed?.length ?? 0,
lowconf: data?.facts.length ?? 0,
+ mappings: data?.mappings?.length ?? 0,
merges: data?.merges.length ?? 0,
decisions: history.data?.total ?? 0,
};
@@ -609,6 +678,7 @@ export function Review() {
title: S.review.lowConfidence,
hint: S.review.lowConfidenceHint,
},
+ mappings: { title: S.review.mappings, hint: S.review.mappingsHint },
decisions: { title: S.review.decisionsTitle, hint: S.review.decisionsHint },
merges: { title: S.review.mergeHistory, hint: null },
};
@@ -643,6 +713,12 @@ export function Review() {
count={counts.lowconf}
onClick={() => select("lowconf")}
/>
+ <RailItem
+ active={active === "mappings"}
+ label={S.review.railMappings}
+ count={counts.mappings}
+ onClick={() => select("mappings")}
+ />
</div>
<RailHeader label={S.review.tabHistory} />
<div className="px-2 space-y-0.5">
@@ -773,6 +849,26 @@ export function Review() {
</div>
)}
+ {active === "mappings" && counts.mappings > 0 && (
+ <div className="space-y-3">
+ {pageSlice(data.mappings ?? [], page, FACT_PAGE).rows.map(
+ (m) => (
+ <MappingRow
+ key={m.id}
+ mapping={m}
+ busy={
+ mappingAction.isPending &&
+ mappingAction.variables?.id === m.id
+ }
+ onDecide={(status) =>
+ mappingAction.mutate({ id: m.id, status })
+ }
+ />
+ ),
+ )}
+ </div>
+ )}
+
{active === "merges" &&
(counts.merges === 0 ? (
<div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">