Elffuss BraidHub

kikocis/utopia public

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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Changeset608af2bf35c577af016528e5bb016b4924c3b945e5be1a0a466e2ea8921ff3fe
AuthorWaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-08-31 03:49 +08:00
CommitterGitHub <noreply@github.com> · 2026-08-31 03:49 +08:00
Parentsdee5685cf9f3

Browse the files at this changeset

15 files changed

modified crates/utopia-core/src/models.rs +28 −0
@@ -777,3 +777,31 @@
777777 /// 事实已经在那儿了,它们的主语是什么类是事实,不是判断
778778 pub domain_keys: Vec<String>,
779779 }
780+
781+/// 语义层的一条映射:业务概念 → 数据资产定义(见 `docs/decisions/0011`)。
782+///
783+/// **字段是列,不是 JSON 里的键。** 从前它是一条 `mapped_to` 事实,
784+/// 这几样全塞在 `object_value` 里——于是「哪些概念映射到了 orders 这张表」
785+/// 要扒 JSON,而「同一个概念同一个源只该有一条」这条约束数据库管不到。
786+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
787+pub struct ConceptMapping {
788+ pub id: Uuid,
789+ pub concept_id: Uuid,
790+ /// 概念的名字。读的一侧总要它(问数 prompt、Review 列表),
791+ /// 每次再查一遍实体表是白跑
792+ pub concept_name: String,
793+ /// 挂载的数据源。同一个概念在不同源上可以有不同定义,这是有意支持的
794+ pub source: String,
795+ pub table_name: Option<String>,
796+ pub expr: Option<String>,
797+ pub sql: Option<String>,
798+ pub unit: Option<String>,
799+ pub summary: Option<String>,
800+ /// 派生指标(「转化率 = 成交数 / 访问数」):算出来的,不是表里的列
801+ pub derived: bool,
802+ /// proposed | confirmed | rejected
803+ ///
804+ /// **状态而不是置信度。** 从前借事实的 confidence 表达「提议 0.6 / 确认 1.0」,
805+ /// 那是把二值状态编码成浮点数,还顺带让它落进「低置信事实」那一档
806+ pub status: String,
807+}
modified crates/utopia-server/src/api/chat.rs +30 −5
@@ -273,12 +273,15 @@
273273 // 写工具跟人走:editor 及以上的对话才带 remember,viewer 纯只读
274274 // 挂载的数据源决定 query_data 是否入列(问数是读,viewer 亦可用)
275275 let mounted_sources = utopia_store::datasources::mounted(&state.pool, kb_id).await?;
276- // 语义层:人确认过的 指标/维度 → 数据资产 映射(置信 ≥0.75,与 Review 阈值互补),
277- // 直接进 system prompt——问数优先用确认口径,而不是每次从 schema 猜
276+ // 语义层:人确认过的 指标/维度 → 数据资产 映射,直接进 system prompt——
277+ // 问数优先用确认口径,而不是每次从 schema 猜。
278+ //
279+ // 从前这里按 `confidence >= 0.75` 捞事实,而那个阈值是拿浮点数编码一个
280+ // 二值状态(提议 0.6 / 确认 1.0)。现在读 `status = confirmed`(0011)
278281 let mappings = if mounted_sources.is_empty() {
279282 Vec::new()
280283 } else {
281- utopia_store::graph::confirmed_mappings(&state.pool, kb_id, 0.75, 30).await?
284+ utopia_store::mappings::confirmed(&state.pool, kb_id, 30).await?
282285 };
283286 let can_write = utopia_store::access::kb_role(&state.pool, &user, &kb)
284287 .await?
@@ -342,8 +345,30 @@
342345 system_prompt.push_str(
343346 "\nSemantic layer (confirmed definitions — use these instead of guessing from schema):",
344347 );
345- for (name, def) in &mappings {
346- system_prompt.push_str(&format!("\n- {name}: {def}"));
348+ // 从前这里直接把整份 JSON 打进去。现在字段是列,只挑问数用得上的
349+ // 那几样铺开——`sql` 与 `expr` 是「怎么算」,`unit` 是答里必须带的
350+ // 量纲,`summary` 是给模型的一句人话
351+ for m in &mappings {
352+ let how = m
353+ .sql
354+ .as_deref()
355+ .or(m.expr.as_deref())
356+ .or(m.table_name.as_deref())
357+ .unwrap_or("-");
358+ let unit = m
359+ .unit
360+ .as_deref()
361+ .map(|u| format!(" [{u}]"))
362+ .unwrap_or_default();
363+ let note = m
364+ .summary
365+ .as_deref()
366+ .map(|s| format!(" — {s}"))
367+ .unwrap_or_default();
368+ system_prompt.push_str(&format!(
369+ "\n- {} ({}){unit}: {how}{note}",
370+ m.concept_name, m.source
371+ ));
347372 }
348373 }
349374 }
modified crates/utopia-server/src/api/mod.rs +5 −0
@@ -283,6 +283,11 @@
283283 .route("/kbs/{id}/review", get(review_routes::list))
284284 .route("/kbs/{id}/review/history", get(review_routes::history))
285285 .route("/kbs/{id}/review/{review_id}", post(review_routes::decide))
286+ // 语义层映射的表态(0011)。跟消解审核并排——都是「引擎提议、人裁决」
287+ .route(
288+ "/kbs/{id}/review/mappings/{mapping_id}",
289+ post(review_routes::decide_mapping),
290+ )
286291 .route(
287292 "/kbs/{id}/facts/{fact_id}/confirm",
288293 post(review_routes::confirm_fact),
modified crates/utopia-server/src/api/review_routes.rs +46 −1
@@ -53,9 +53,14 @@
5353 let merges = utopia_store::resolution::list_merges(&state.pool, kb_id, 30).await?;
5454 let conflicts = utopia_store::temporal::list_conflicts(&state.pool, kb_id).await?;
5555 let unconfirmed = utopia_store::graph::stale_facts(&state.pool, kb_id, 100).await?;
56+ // 语义层的待表态映射(0011)。从前它借「低置信事实」那一档露面——
57+ // 靠 confidence 0.6 混进去,而它根本不是一条关于世界的断言。
58+ // 现在自成一档,前端也据此分组显示
59+ let mappings = utopia_store::mappings::proposed(&state.pool, kb_id, 100).await?;
5660 Ok(Json(json!({
5761 "reviews": reviews, "facts": facts, "merges": merges,
58- "conflicts": conflicts, "unconfirmed": unconfirmed
62+ "conflicts": conflicts, "unconfirmed": unconfirmed,
63+ "mappings": mappings
5964 })))
6065 }
6166
@@ -385,3 +390,43 @@
385390 utopia_store::audit::review_history(&state.pool, kb_id, per, page * per).await?;
386391 Ok(Json(json!({ "events": events, "total": total })))
387392 }
393+
394+#[derive(Deserialize)]
395+pub struct DecideMappingReq {
396+ /// confirmed | rejected
397+ pub status: String,
398+}
399+
400+/// 对一条语义层映射表态(0011)。
401+///
402+/// **改状态不删行**:确认发生过、拒绝也发生过。而拒绝留痕当下就有用——
403+/// 下一轮探索会再次算出被拒绝过的那条,`propose` 的 `WHERE status = 'proposed'`
404+/// 据此不把它刷回待看。
405+pub async fn decide_mapping(
406+ State(state): State<AppState>,
407+ AuthUser(user): AuthUser,
408+ Path((kb_id, mapping_id)): Path<(Uuid, Uuid)>,
409+ Json(req): Json<DecideMappingReq>,
410+) -> ApiResult<Json<serde_json::Value>> {
411+ require_kb(&state, &user, kb_id, Role::Editor).await?;
412+ if !matches!(req.status.as_str(), "confirmed" | "rejected") {
413+ return Err(utopia_core::AppError::invalid(
414+ "bad_status",
415+ "status 只能是 confirmed 或 rejected",
416+ )
417+ .into());
418+ }
419+ utopia_store::mappings::decide(&state.pool, kb_id, mapping_id, &req.status, user.id).await?;
420+ let _ = utopia_store::audit::record(
421+ &state.pool,
422+ Some(kb_id),
423+ user.id,
424+ "mapping.decided",
425+ "concept_mapping",
426+ Some(mapping_id),
427+ json!({ "status": req.status }),
428+ )
429+ .await;
430+ state.emit_review(kb_id);
431+ Ok(Json(json!({ "ok": true })))
432+}
modified crates/utopia-server/src/mappings.rs +27 −50
@@ -1,15 +1,18 @@
11 //! 问数语义映射的 Agentic 探索:读挂载源的 schema + KB 既有概念,让 LLM 提议
22 //! "业务概念(Metric/Dimension 实体)→ 数据资产定义" 的映射。
33 //!
4-//! 提议以低置信(0.6)mapped_to 事实落库 → 自动流入 Review 的低置信区,
5-//! Confirm/Reject 零新 UI;确认(置信提满)后的映射注入问数 prompt。
4+//! 提议写进 `concept_mappings`(status = proposed)→ Review 页自成一档,
5+//! Confirm / Reject 之后 status 变 confirmed,问数只读确认过的那些。
6+//!
7+//! **从前它是一条 0.6 置信的 `mapped_to` 事实**,借「低置信事实」那一档露面。
8+//! 搬出来的理由见 0011:它不是关于世界的断言,是配置——而「确认」这个动作
9+//! 当时是 `UPDATE facts SET confidence = 1.0`,原地改一张不许原地改的表。
610 //! agent 只提议,口径生效权在人——与消解"宁分勿合"同一哲学。
711
812 use crate::llm_util;
913 use crate::state::AppState;
1014 use uuid::Uuid;
1115
12-const PROPOSAL_CONFIDENCE: f32 = 0.6;
1316 const MAX_SCHEMA_CHARS: usize = 12_000;
1417
1518 pub async fn explore_mappings(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {
@@ -133,61 +136,35 @@
133136 )
134137 .await?;
135138
136- // 定义带 source + summary(Review 与 prompt 展示都靠 summary)
137- let mut definition = p["definition"].clone();
138- if !definition.is_object() {
139+ // 定义拆成列写进 concept_mappings(0011)。从前它是一份塞进
140+ // `object_value` 的 JSON,宾语挂在一条叫 mapped_to 的关系上——
141+ // 而那条关系是本体里的一行,跟 works_at 并列。**它不是关于世界的
142+ // 断言,是配置**,所以搬去自己的表
143+ let def = &p["definition"];
144+ if !def.is_object() {
139145 continue;
140146 }
141- definition["source"] = serde_json::json!(source);
142- if let Some(s) = p["summary"].as_str() {
143- definition["summary"] = serde_json::json!(s);
144- }
145-
146- let mapped_to: Option<(Uuid,)> =
147- sqlx::query_as("SELECT id FROM relation_types WHERE kb_id = $1 AND key = 'mapped_to'")
148- .bind(kb_id)
149- .fetch_optional(&state.pool)
150- .await?;
151- let Some((mapped_to,)) = mapped_to else {
152- continue;
147+ let s = |k: &str| {
148+ def[k]
149+ .as_str()
150+ .filter(|x| !x.is_empty())
151+ .map(str::to_string)
153152 };
154-
155- let (fact_id, created) = utopia_store::graph::insert_value_fact(
153+ utopia_store::mappings::propose(
156154 &state.pool,
157155 kb_id,
158156 resolved.entity_id,
159- Some(mapped_to),
160- &definition,
161- // 问数映射不带时间:两端都空
162- utopia_store::graph::Validity::default(),
163- PROPOSAL_CONFIDENCE,
157+ source,
158+ s("table").as_deref(),
159+ s("expr").as_deref(),
160+ s("sql").as_deref(),
161+ s("unit").as_deref(),
162+ // summary 是给人看的那句:Review 列表与问数 prompt 都靠它
163+ p["summary"].as_str().or(def["summary"].as_str()),
164+ def["derived"].as_bool().unwrap_or(false),
164165 )
165166 .await?;
166- if created {
167- accepted += 1;
168- // 证据挂 schema 文档的首个 live chunk(rationale 作 quote)
169- if let Some((chunk_id,)) = sqlx::query_as::<_, (Uuid,)>(
170- "SELECT c.id FROM chunks c JOIN documents d ON d.id = c.document_id
171- WHERE d.kb_id = $1 AND d.external_key LIKE 'datasource:%:schema'
172- AND c.superseded_at IS NULL
173- ORDER BY c.seq LIMIT 1",
174- )
175- .bind(kb_id)
176- .fetch_optional(&state.pool)
177- .await?
178- {
179- let rationale = p["rationale"].as_str().unwrap_or("");
180- // 谓词是代码写死的 mapped_to,不是模型给的说法,没有表层形式可留
181- utopia_store::graph::add_evidence(
182- &state.pool,
183- fact_id,
184- chunk_id,
185- (!rationale.is_empty()).then_some(rationale),
186- None,
187- )
188- .await?;
189- }
190- }
167+ accepted += 1;
191168 }
192169
193170 tracing::info!(%kb_id, proposals = accepted, "映射探索完成,提议已入审核队列");
modified crates/utopia-store/src/lib.rs +1 −0
@@ -13,6 +13,7 @@
1313 pub mod graph;
1414 pub mod jobs;
1515 pub mod kbs;
16+pub mod mappings;
1617 pub mod members;
1718 pub mod memory;
1819 pub mod model_limits;
added crates/utopia-store/src/mappings.rs +201 −0
@@ -0,0 +1,201 @@
1+//! 语义层的「业务概念 → 数据资产」映射(见 `docs/decisions/0011`)。
2+//!
3+//! 它从前是一条 `mapped_to` 事实,宾语是塞在 `object_value` 里的一份 JSON。
4+//! 搬出来的理由写在迁移 0055 里,一句话:**它不是关于世界的断言,是配置**。
5+//!
6+//! 与账本的区别在这里就能看见:这张表**允许原地改**。`confirm` 改的是
7+//! 「这条配置生效了没有」,不是「我们对世界的认知变了」——所以它不需要
8+//! append-only,改之前的那一版进 `concept_mapping_revisions` 留痕即可。
9+
10+use sqlx::PgPool;
11+use utopia_core::models::ConceptMapping;
12+use utopia_core::{AppError, AppResult};
13+use uuid::Uuid;
14+
15+/// 探索任务提议一条映射。
16+///
17+/// **同一个 (概念, 源) 只有一条**,由主键管——从前这条唯一性藏在 `object_value`
18+/// 内部,数据库看不见,只能靠确认流程显式闭合。
19+///
20+/// 已经有人表过态的不覆盖:重跑探索会再次算出被拒绝过的那条,不加这一句
21+/// 它就被刷回待看,等于每跑一次都把人的否决抹掉一次(`ontology_proposals`
22+/// 那边踩过同一个坑,见 0049)。
23+#[allow(clippy::too_many_arguments)]
24+pub async fn propose(
25+ pool: &PgPool,
26+ kb_id: Uuid,
27+ concept_id: Uuid,
28+ source: &str,
29+ table_name: Option<&str>,
30+ expr: Option<&str>,
31+ sql: Option<&str>,
32+ unit: Option<&str>,
33+ summary: Option<&str>,
34+ derived: bool,
35+) -> AppResult<Uuid> {
36+ // **`DO UPDATE ... WHERE` 不满足时 `RETURNING` 一行都不返回。**
37+ //
38+ // 这是 Postgres 的实情而不是直觉:条件挡住更新,那一行就不算被这条语句
39+ // 动过,于是也不出现在 RETURNING 里。测试当场撞上——第二次提议一条已被
40+ // 拒绝的映射,`fetch_one` 报「no rows returned」。
41+ //
42+ // 所以把 id 单独查出来:更新与否是一回事,「这条映射是哪一行」是另一回事。
43+ let existing: Option<(Uuid,)> = sqlx::query_as(
44+ "SELECT id FROM concept_mappings
45+ WHERE kb_id = $1 AND concept_id = $2 AND source = $3",
46+ )
47+ .bind(kb_id)
48+ .bind(concept_id)
49+ .bind(source)
50+ .fetch_optional(pool)
51+ .await?;
52+ let id = existing.map(|(i,)| i).unwrap_or_else(Uuid::now_v7);
53+ sqlx::query(
54+ "INSERT INTO concept_mappings
55+ (id, kb_id, concept_id, source, table_name, expr, sql, unit, summary, derived)
56+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
57+ ON CONFLICT (kb_id, concept_id, source) DO UPDATE
58+ SET table_name = EXCLUDED.table_name, expr = EXCLUDED.expr,
59+ sql = EXCLUDED.sql, unit = EXCLUDED.unit,
60+ summary = EXCLUDED.summary, derived = EXCLUDED.derived,
61+ updated_at = now()
62+ WHERE concept_mappings.status = 'proposed'",
63+ )
64+ .bind(id)
65+ .bind(kb_id)
66+ .bind(concept_id)
67+ .bind(source)
68+ .bind(table_name)
69+ .bind(expr)
70+ .bind(sql)
71+ .bind(unit)
72+ .bind(summary)
73+ .bind(derived)
74+ .execute(pool)
75+ .await?;
76+ Ok(id)
77+}
78+
79+/// 还等着人表态的。Review 页读它。
80+pub async fn proposed(pool: &PgPool, kb_id: Uuid, limit: i64) -> AppResult<Vec<ConceptMapping>> {
81+ Ok(sqlx::query_as(
82+ "SELECT m.id, m.concept_id, e.canonical_name AS concept_name, m.source,
83+ m.table_name, m.expr, m.sql, m.unit, m.summary, m.derived, m.status
84+ FROM concept_mappings m
85+ JOIN entities e ON e.id = m.concept_id
86+ WHERE m.kb_id = $1 AND m.status = 'proposed'
87+ ORDER BY e.canonical_name, m.source
88+ LIMIT $2",
89+ )
90+ .bind(kb_id)
91+ .bind(limit)
92+ .fetch_all(pool)
93+ .await?)
94+}
95+
96+/// 人确认过的。问数把它们注进 system prompt——**只用确认过的口径**,
97+/// 而不是每次从 schema 猜。
98+pub async fn confirmed(pool: &PgPool, kb_id: Uuid, limit: i64) -> AppResult<Vec<ConceptMapping>> {
99+ Ok(sqlx::query_as(
100+ "SELECT m.id, m.concept_id, e.canonical_name AS concept_name, m.source,
101+ m.table_name, m.expr, m.sql, m.unit, m.summary, m.derived, m.status
102+ FROM concept_mappings m
103+ JOIN entities e ON e.id = m.concept_id
104+ WHERE m.kb_id = $1 AND m.status = 'confirmed'
105+ ORDER BY e.canonical_name, m.source
106+ LIMIT $2",
107+ )
108+ .bind(kb_id)
109+ .bind(limit)
110+ .fetch_all(pool)
111+ .await?)
112+}
113+
114+/// 有人表态了。
115+///
116+/// **改状态不删行**:确认发生过、拒绝也发生过。而拒绝留痕还有当下就用得着的
117+/// 作用——`propose` 的 `WHERE status = 'proposed'` 据此不把它刷回待看。
118+pub async fn decide(
119+ pool: &PgPool,
120+ kb_id: Uuid,
121+ mapping_id: Uuid,
122+ status: &str,
123+ actor: Uuid,
124+) -> AppResult<()> {
125+ let res = sqlx::query(
126+ "UPDATE concept_mappings
127+ SET status = $3, decided_by = $4, decided_at = now(), updated_at = now()
128+ WHERE id = $2 AND kb_id = $1",
129+ )
130+ .bind(kb_id)
131+ .bind(mapping_id)
132+ .bind(status)
133+ .bind(actor)
134+ .execute(pool)
135+ .await?;
136+ if res.rows_affected() == 0 {
137+ return Err(AppError::NotFound);
138+ }
139+ Ok(())
140+}
141+
142+/// 改一条确认过的口径。**改之前那一版先进 revisions**——问数回溯历史报表时
143+/// 要答得出「上季度这个数是怎么算的」。
144+///
145+/// 存整版快照而不是差异:读的时候要的就是「当时是什么」,而差异得从头重放
146+/// 才能回答这个问题。
147+#[allow(clippy::too_many_arguments)]
148+pub async fn revise(
149+ pool: &PgPool,
150+ kb_id: Uuid,
151+ mapping_id: Uuid,
152+ table_name: Option<&str>,
153+ expr: Option<&str>,
154+ sql: Option<&str>,
155+ unit: Option<&str>,
156+ summary: Option<&str>,
157+ derived: bool,
158+ actor: Uuid,
159+) -> AppResult<()> {
160+ let mut tx = pool.begin().await?;
161+ let before: Option<(serde_json::Value,)> = sqlx::query_as(
162+ "SELECT to_jsonb(m) - 'id' - 'kb_id' FROM concept_mappings m
163+ WHERE m.id = $2 AND m.kb_id = $1",
164+ )
165+ .bind(kb_id)
166+ .bind(mapping_id)
167+ .fetch_optional(&mut *tx)
168+ .await?;
169+ let Some((before,)) = before else {
170+ tx.rollback().await?;
171+ return Err(AppError::NotFound);
172+ };
173+ sqlx::query(
174+ "INSERT INTO concept_mapping_revisions (id, mapping_id, before, changed_by)
175+ VALUES ($1, $2, $3, $4)",
176+ )
177+ .bind(Uuid::now_v7())
178+ .bind(mapping_id)
179+ .bind(before)
180+ .bind(actor)
181+ .execute(&mut *tx)
182+ .await?;
183+ sqlx::query(
184+ "UPDATE concept_mappings
185+ SET table_name = $3, expr = $4, sql = $5, unit = $6, summary = $7,
186+ derived = $8, updated_at = now()
187+ WHERE id = $2 AND kb_id = $1",
188+ )
189+ .bind(kb_id)
190+ .bind(mapping_id)
191+ .bind(table_name)
192+ .bind(expr)
193+ .bind(sql)
194+ .bind(unit)
195+ .bind(summary)
196+ .bind(derived)
197+ .execute(&mut *tx)
198+ .await?;
199+ tx.commit().await?;
200+ Ok(())
201+}
added crates/utopia-store/tests/a_mapping_is_not_a_fact.rs +191 −0
@@ -0,0 +1,191 @@
1+//! 语义层映射的两条硬性质——打在真库上(见 `docs/decisions/0011`)。
2+//!
3+//! 这两条都是搬出账本换来的东西,也正是从前做不到的:
4+//!
5+//! 1. **同一个 (概念, 源) 只有一条。** 从前这条唯一性藏在 `object_value`
6+//! 这个 JSONB 内部,数据库看不见,只能靠确认流程显式闭合——也就是靠流程
7+//! 而不是约束。现在它是主键。
8+//! 2. **表过态的不被下一轮探索刷回待看。** `ontology_proposals` 那边踩过同一个
9+//! 坑(0049):重跑必然再次算出被拒绝过的那条,不挡住就等于每跑一次都把
10+//! 人的否决抹掉一次。
11+
12+use sqlx::PgPool;
13+use uuid::Uuid;
14+
15+async fn fixture(pool: &PgPool) -> anyhow::Result<(Uuid, Uuid, Uuid)> {
16+ let (org, ws, kb, ent) = (
17+ Uuid::now_v7(),
18+ Uuid::now_v7(),
19+ Uuid::now_v7(),
20+ Uuid::now_v7(),
21+ );
22+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'map-test')")
23+ .bind(org)
24+ .execute(pool)
25+ .await?;
26+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'map-test')")
27+ .bind(ws)
28+ .bind(org)
29+ .execute(pool)
30+ .await?;
31+ sqlx::query("INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'map-test')")
32+ .bind(kb)
33+ .bind(ws)
34+ .execute(pool)
35+ .await?;
36+ sqlx::query(
37+ "INSERT INTO entities (id, kb_id, canonical_name, aliases) VALUES ($1, $2, '营收', '{}')",
38+ )
39+ .bind(ent)
40+ .bind(kb)
41+ .execute(pool)
42+ .await?;
43+ Ok((org, kb, ent))
44+}
45+
46+#[tokio::test]
47+async fn one_concept_one_source_one_mapping() -> anyhow::Result<()> {
48+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
49+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
50+ return Ok(());
51+ };
52+ let pool = PgPool::connect(&url).await?;
53+ let (_org, kb, ent) = fixture(&pool).await?;
54+
55+ let run = async {
56+ let p = |t: &'static str| {
57+ utopia_store::mappings::propose(
58+ &pool,
59+ kb,
60+ ent,
61+ "warehouse",
62+ Some(t),
63+ None,
64+ None,
65+ None,
66+ None,
67+ false,
68+ )
69+ };
70+ let a = p("orders").await?;
71+ let b = p("orders_v2").await?;
72+ assert_eq!(a, b, "同一个 (概念, 源) 该是同一行,不是两行");
73+
74+ let got = utopia_store::mappings::proposed(&pool, kb, 100).await?;
75+ assert_eq!(got.len(), 1, "只该有一条");
76+ assert_eq!(
77+ got[0].table_name.as_deref(),
78+ Some("orders_v2"),
79+ "重跑探索该刷新定义"
80+ );
81+
82+ // 换一个源就是另一条:同一概念在不同源上有不同定义是有意支持的
83+ utopia_store::mappings::propose(
84+ &pool,
85+ kb,
86+ ent,
87+ "lakehouse",
88+ Some("f_orders"),
89+ None,
90+ None,
91+ None,
92+ None,
93+ false,
94+ )
95+ .await?;
96+ assert_eq!(
97+ utopia_store::mappings::proposed(&pool, kb, 100)
98+ .await?
99+ .len(),
100+ 2,
101+ "不同源该各有一条"
102+ );
103+ Ok::<_, anyhow::Error>(())
104+ }
105+ .await;
106+
107+ // **只删知识库,不删 org/user。** 用户是软删除的,生产代码里没有
108+ // `DELETE FROM users`——测试也不该造一个产品里不存在的动作,否则
109+ // 撞上的外键约束是夹具自己的问题,会被误当成产品缺陷(实测发生过)
110+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
111+ .bind(kb)
112+ .execute(&pool)
113+ .await?;
114+ run
115+}
116+
117+#[tokio::test]
118+async fn a_rejected_mapping_does_not_come_back() -> anyhow::Result<()> {
119+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
120+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
121+ return Ok(());
122+ };
123+ let pool = PgPool::connect(&url).await?;
124+ let (org, kb, ent) = fixture(&pool).await?;
125+
126+ let run = async {
127+ let user = Uuid::now_v7();
128+ sqlx::query(
129+ "INSERT INTO users (id, org_id, email, display_name, password_hash)
130+ VALUES ($1, $2, $1 || '@m.test', 'm', 'x')",
131+ )
132+ .bind(user)
133+ .bind(org)
134+ .execute(&pool)
135+ .await?;
136+
137+ let id = utopia_store::mappings::propose(
138+ &pool,
139+ kb,
140+ ent,
141+ "warehouse",
142+ Some("orders"),
143+ None,
144+ None,
145+ None,
146+ None,
147+ false,
148+ )
149+ .await?;
150+ utopia_store::mappings::decide(&pool, kb, id, "rejected", user).await?;
151+
152+ // 下一轮探索会再次算出同一条——它不该被刷回待看
153+ utopia_store::mappings::propose(
154+ &pool,
155+ kb,
156+ ent,
157+ "warehouse",
158+ Some("orders"),
159+ None,
160+ None,
161+ None,
162+ None,
163+ false,
164+ )
165+ .await?;
166+ assert!(
167+ utopia_store::mappings::proposed(&pool, kb, 100)
168+ .await?
169+ .is_empty(),
170+ "拒绝过的不该重新排队"
171+ );
172+ // 确认过的同理不该被探索覆盖
173+ assert!(
174+ utopia_store::mappings::confirmed(&pool, kb, 100)
175+ .await?
176+ .is_empty(),
177+ "拒绝的也不该出现在确认列表里"
178+ );
179+ Ok::<_, anyhow::Error>(())
180+ }
181+ .await;
182+
183+ // **只删知识库,不删 org/user。** 用户是软删除的,生产代码里没有
184+ // `DELETE FROM users`——测试也不该造一个产品里不存在的动作,否则
185+ // 撞上的外键约束是夹具自己的问题,会被误当成产品缺陷(实测发生过)
186+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
187+ .bind(kb)
188+ .execute(&pool)
189+ .await?;
190+ run
191+}
added docs/decisions/0011-a-mapping-is-not-a-fact.md +125 −0
@@ -0,0 +1,125 @@
1+# 0011 · 「怎么算」不是「有什么」
2+
3+- **状态**:规划中
4+- **成文**:2026-08-31(约定见 [README](README.md))
5+- **相关**:[0009](0009-no-type-is-a-type.md) 删掉内置实体类、[0010](0010-no-relation-is-no-relation.md)
6+ 删掉兜底关系、`#125` 删掉其余八条种子关系——本文是同一条线的最后一段:
7+ **本体里只该剩下词表**
8+
9+> 本篇是拆一个当初有意为之的复用。原设计不是疏忽,它买到了三样具体的东西,
10+> 所以这里先把买到的列清楚,再说为什么仍然要拆。
11+
12+## 现状
13+
14+问数语义层把「业务概念 → 数据资产定义」存成一条事实:
15+
16+```
17+主语 = 概念实体(Metric / Dimension)
18+谓词 = mapped_to ← relation_types 里的一行,与 works_at 并列
19+宾语 = object_value JSON { source, table?, expr?, sql?, unit?, summary? }
20+置信 = 0.6 提议 / 1.0 已确认
21+```
22+
23+整条路:
24+
25+```
26+探索任务读挂载源 schema → LLM 提议 → 0.6 置信的 mapped_to 事实
27+ ↓ review_routes 的 low_confidence_facts 按 <0.75 捞起来
28+人在 Review 页 Confirm → confirm_fact 把 confidence 改成 1.0
29+ ↓ chat.rs 读 confirmed_mappings(≥0.75)
30+注入问数 system prompt
31+```
32+
33+## 复用买到了什么
34+
35+**一、Review 流零新 UI。** 提议以低置信落库,自动流进「低置信事实」那一档,
36+Confirm / Reject 用的是现成的按钮。`mappings.rs` 的模块注释把这一点写成了设计
37+意图,不是事后总结。
38+
39+**二、双时态历史。** 口径改过没有、什么时候改的、改之前是什么——账本本来就答得出来。
40+
41+**三、证据链。** 与其它事实同构,实体历史页面直接就能展示。
42+
43+这三样都是真的,拆开就要重做。
44+
45+## 为什么仍然要拆
46+
47+### 1. 它不是关于世界的断言
48+
49+本体回答「世界上有什么、它们之间是什么关系」。`mapped_to` 回答的是
50+「**这个数在我们的数据库里怎么算出来**」——它是实现细节,跟 `works_at`
51+不是一类东西。
52+
53+这一条与 0009 删掉内置实体类、0010 删掉 `related_to` 是同一句话的三次应用:
54+**代码层面的机制不该混进词表**。0009 说的是「`concept` 是控制流不是词表」,
55+这里是「`mapped_to` 是配置不是词表」。
56+
57+### 2. 它出现在不该出现的地方
58+
59+`relation_types` 里的一行意味着:本体页把它列成一条关系、抽取提示词把它端给
60+模型、本体规模统计把它算进去、`#125` 之后它还是**唯一一条种子关系**——
61+一个新库开局本体里只有它,而它跟用户要建的知识图谱毫无关系。
62+
63+### 3. 「确认」这个动作已经在违反账本的地基
64+
65+```rust
66+// graph.rs — confirm_fact
67+UPDATE facts SET confidence = 1.0 WHERE id = $1
68+```
69+
70+账本是 append-only 的:纠正一条事实要插新行 + `supersedes` 旧行,因为
71+**认知变更本身是信息**(0001 P0 的立论)。而确认口径是**原地 UPDATE**——
72+它改的不是「我们对世界的认知」,是「这条配置生效了没有」。
73+
74+一个需要原地改状态的东西住在一张不许原地改的表里,这本身就是它不合身的证据。
75+今天没出事,是因为口径确认的语义恰好简单到用一个浮点数就能表达。
76+
77+### 4. 形状对不上
78+
79+一条映射真正的字段是 `source / table / expr / sql / unit / summary`,
80+现在全塞在 `object_value` 这个 JSONB 里。于是:
81+
82+- 查不动。「哪些概念映射到了 orders 这张表」要扒 JSON
83+- 约束不了。同一个概念同一个源应该只有一条,而唯一性粒度
84+ `(概念, 源)` 藏在 `object_value` 内部,数据库管不到——今天靠确认流程
85+ 显式闭合,靠的是流程不是约束
86+- 说不清。`mapped_to` 的 range 是什么?没有答案,因为宾语不是实体也不是
87+ 某个数据类型,是一份配置
88+
89+## 决定
90+
91+**单独一张 `concept_mappings` 表。** 概念(entity id)→ 数据资产定义,
92+字段展开成列,唯一性 `(kb_id, concept_id, source)` 由主键管。
93+
94+`mapped_to` 从 `relation_types` 退场,`DEFAULT_RELATION_TYPES` 随之清空——
95+建库不再播种任何关系,本体从第一天起就只有用户自己导入的词表。
96+
97+## 要重做的三样,逐条
98+
99+**Review 流**:不再借低置信事实那一档。语义层的待确认项是另一种东西
100+(配置提议,不是知识断言),Review 页给它一个自己的分组。这与 0002 R0
101+的一致性检查落在同一处——那一档也是「引擎提议、人裁决」。
102+
103+**历史**:表上自带 `created_at / confirmed_at / confirmed_by`,加一张
104+`concept_mapping_revisions` 记口径演变。**不做双时态**——口径没有「有效时间」
105+与「记录时间」两条轴,它只有「什么时候生效的」一条。硬套账本那套是把复杂度
106+搬过来而不是解决它。
107+
108+**证据链**:映射的证据是「LLM 读了哪张表的 schema 提议的」,与事实的
109+「哪一句原文」不是一回事,本来就该分开记。
110+
111+## 代价,写在前面
112+
113+- **一次数据迁移**:现有的 `mapped_to` 事实要搬进新表。库里是 mock 数据,
114+ 所以这一刀不写迁移,直接换(与 `#125` 同)。真发布之后就没有这个便利了。
115+- **三处接线要改**:`mappings.rs` 写入、`review_routes` 读取、`chat.rs` 注入。
116+- **短期内多一段 UI**:Review 页要多一个分组。0002 R0 也需要它,两者合并做
117+ 一次,别做两遍。
118+
119+## 开放问题
120+
121+- **确认过的口径改了怎么办?** 双时态那套答得出「上季度的口径是什么」,
122+ 换成 revisions 表之后要显式设计。问数回溯历史报表时会撞上它。
123+- **多源同概念**:`(kb_id, concept_id, source)` 允许同一个概念在不同源上有
124+ 不同定义,这是有意的(0010 之前的注释就这么写)。但问数该用哪一条?
125+ 今天靠 prompt 里全给、让模型挑。这条不因本篇改变,但搬表之后更容易加规则。
modified docs/decisions/README.md +1 −0
@@ -32,6 +32,7 @@
3232 | 0008 | [预制本体包作为冷启动](0008-ontology-packs-as-cold-start.md) | 规划中 · 建库仍只发种子关系 |
3333 | 0009 | [「还没判出来」不该是一个类](0009-no-type-is-a-type.md) | 已实施 · `entities.type_id` 改为可空 |
3434 | 0010 | [「说不出是什么关系」不该是一个关系](0010-no-relation-is-no-relation.md) | 已实施 · `facts.predicate_id` 改为可空 · 0009 在关系侧的孪生 · **含一次七分钟后长回来的修订** |
35+| 0011 | [「怎么算」不是「有什么」](0011-a-mapping-is-not-a-fact.md) | 规划中 · 语义层映射搬出本体 · 0009/0010 那条线的最后一段 |
3536
3637 ## 不是决策记录的那些
3738
added migrations/0055_a_mapping_is_not_a_fact.sql +83 −0
@@ -0,0 +1,83 @@
1+-- 语义层的「概念 → 数据资产」映射搬出本体,见 docs/decisions/0011。
2+--
3+-- 从前它是一条 `mapped_to` 事实:主语是概念实体,宾语是塞在 `object_value`
4+-- 里的一份 JSON 配置,而 `mapped_to` 本身是 `relation_types` 里的一行,
5+-- 与 `works_at` 并列。
6+--
7+-- 拆开的理由,三条都不是洁癖:
8+--
9+-- 1. **它不是关于世界的断言。** 本体回答「世界上有什么」,这个回答的是
10+-- 「这个数在我们的数据库里怎么算」。与 0009 说「concept 是控制流不是词表」、
11+-- 0010 说「related_to 是兜底不是关系」是同一句话的第三次应用。
12+--
13+-- 2. **「确认」这个动作已经在违反账本的地基。** `confirm_fact` 是
14+-- `UPDATE facts SET confidence = 1.0`——原地改。而账本是 append-only 的,
15+-- 纠正事实要插新行 + supersedes,因为认知变更本身是信息(0001 P0)。
16+-- 确认口径改的不是认知,是「这条配置生效了没有」。一个需要原地改状态的
17+-- 东西住在一张不许原地改的表里,本身就是它不合身的证据。
18+--
19+-- 3. **形状对不上。** 真正的字段是 source / table / expr / sql / unit /
20+-- summary,全塞在一个 JSONB 里:查不动(「哪些概念映射到了 orders」要扒
21+-- JSON)、约束不了(唯一性粒度 (概念,源) 藏在 object_value 内部,
22+-- 数据库管不到,今天靠流程而不是约束)。
23+
24+CREATE TABLE concept_mappings (
25+ id UUID PRIMARY KEY,
26+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
27+ -- 被映射的业务概念(Metric / Dimension 那类实体)
28+ concept_id UUID NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
29+ -- 挂载的数据源。**它进主键**:同一个概念在不同源上有不同定义是有意支持的,
30+ -- 而同一个概念在同一个源上只该有一条——这条从前靠确认流程显式闭合,
31+ -- 现在由数据库管
32+ source TEXT NOT NULL,
33+ -- 怎么算。字段展开成列而不是继续塞 JSON——它们是这张表存在的理由
34+ table_name TEXT,
35+ expr TEXT,
36+ sql TEXT,
37+ unit TEXT,
38+ summary TEXT,
39+ -- 派生指标(比如「转化率 = 成交数 / 访问数」):算出来的,不是表里的列
40+ derived BOOLEAN NOT NULL DEFAULT FALSE,
41+
42+ -- **状态而不是置信度。** 从前借事实的 confidence 表达「提议 0.6 / 确认 1.0」,
43+ -- 那是把一个二值状态编码成浮点数,还顺带让它落进「低置信事实」那一档。
44+ -- 这里说清楚它是什么
45+ status TEXT NOT NULL DEFAULT 'proposed'
46+ CHECK (status IN ('proposed', 'confirmed', 'rejected')),
47+ -- NULL = 还没人表态。确认与拒绝都留痕:拒绝过的不该被下一轮探索刷回待看。
48+ --
49+ -- 裸外键,与 `entity_merges.merged_by`、`ontology_proposals.decided_by`
50+ -- 那几处一致——**用户是软删除的,生产代码里没有 `DELETE FROM users`**,
51+ -- 所以这条外键的删除规则永远不会被触发,而归因保住了。
52+ decided_by UUID REFERENCES users(id),
53+ decided_at TIMESTAMPTZ,
54+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
55+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
56+
57+ UNIQUE (kb_id, concept_id, source)
58+);
59+
60+-- 问数只读确认过的(chat.rs 注入 system prompt),而 Review 只捞待表态的。
61+-- 两条查询都按 kb + status 走
62+CREATE INDEX concept_mappings_status_idx ON concept_mappings (kb_id, status);
63+
64+-- 口径演变留痕。**不做双时态**:口径没有「有效时间」与「记录时间」两条轴,
65+-- 它只有「什么时候生效的」一条。硬套账本那套是把复杂度搬过来,不是解决它。
66+CREATE TABLE concept_mapping_revisions (
67+ id UUID PRIMARY KEY,
68+ mapping_id UUID NOT NULL REFERENCES concept_mappings(id) ON DELETE CASCADE,
69+ -- 改之前那一版的全文。存快照而不是差异:读的时候要的是「当时是什么」,
70+ -- 而差异要从头重放才能回答这个问题
71+ before JSONB NOT NULL,
72+ changed_by UUID REFERENCES users(id),
73+ changed_at TIMESTAMPTZ NOT NULL DEFAULT now()
74+);
75+
76+CREATE INDEX concept_mapping_revisions_idx
77+ ON concept_mapping_revisions (mapping_id, changed_at DESC);
78+
79+-- 旧的 mapped_to 事实不迁移:仓库尚未发布,库里都是 mock 知识(与 #125 同)。
80+-- 它们留在账本里不碍事——`confirmed_mappings` 那条查询会随代码一起改掉,
81+-- 于是再没有人读它们。
82+--
83+-- **真发布之后就没有这个便利了**,写在这里免得下次照抄。
modified web/src/api.ts +27 −0
@@ -270,6 +270,26 @@
270270 right: ReviewSide;
271271 }
272272
273+
274+/** 语义层的一条映射:业务概念 → 数据资产定义(见 docs/decisions/0011)。
275+ *
276+ * 字段是列而不是 JSON 里的键——从前它是一条 `mapped_to` 事实,
277+ * 这几样全塞在 `object_value` 里。 */
278+export interface ConceptMapping {
279+ id: string;
280+ concept_id: string;
281+ concept_name: string;
282+ /** 挂载的数据源。同一概念在不同源上可以有不同定义 */
283+ source: string;
284+ table_name: string | null;
285+ expr: string | null;
286+ sql: string | null;
287+ unit: string | null;
288+ summary: string | null;
289+ /** 派生指标:算出来的,不是表里的列 */
290+ derived: boolean;
291+ status: "proposed" | "confirmed" | "rejected";
292+}
273293 export interface FactReviewItem {
274294 id: string;
275295 subject_name: string;
@@ -1130,6 +1150,7 @@
11301150 merges: MergeLog[];
11311151 conflicts: ConflictItem[];
11321152 unconfirmed: FactReviewItem[];
1153+ mappings: ConceptMapping[];
11331154 }>(`/api/v1/kbs/${kbId}/review`),
11341155 closeFact: (kbId: string, factId: string, validTo: string) =>
11351156 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/close`, {
@@ -1150,6 +1171,12 @@
11501171 method: "POST",
11511172 body: JSON.stringify({ action }),
11521173 }),
1174+ /** 对一条语义层映射表态(0011)。改状态不删行——拒绝留痕,下一轮探索不再提议它 */
1175+ decideMapping: (kbId: string, mappingId: string, status: "confirmed" | "rejected") =>
1176+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/mappings/${mappingId}`, {
1177+ method: "POST",
1178+ body: JSON.stringify({ status }),
1179+ }),
11531180 confirmFact: (kbId: string, factId: string) =>
11541181 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/confirm`, {
11551182 method: "POST",
modified web/src/i18n/en.ts +5 −0
@@ -887,6 +887,7 @@
887887 railConflicts: "Conflicts",
888888 railUnconfirmed: "Unconfirmed",
889889 railLowConfidence: "Low confidence",
890+ railMappings: "Semantic layer",
890891 railDecisions: "Decisions",
891892 railMerges: "Merges",
892893 categoryEmpty: "This queue is clear.",
@@ -932,6 +933,10 @@
932933 merge: "Merge",
933934 keep: "Keep separate",
934935 lowConfidence: "Low-confidence facts",
936+ mappings: "Semantic layer",
937+ mappingsHint:
938+ "Proposed mappings from a business concept to how it is computed. Confirm one and Ask uses it instead of guessing from the schema.",
939+ mappingDerived: "derived",
935940 lowConfidenceHint:
936941 "Extracted with confidence below 75%. Confirm to trust, reject to remove from the graph (the ledger keeps the record).",
937942 confirm: "Confirm",
modified web/src/i18n/zh.ts +5 −0
@@ -790,6 +790,7 @@
790790 railConflicts: "冲突",
791791 railUnconfirmed: "未确认",
792792 railLowConfidence: "低置信度",
793+ railMappings: "语义层",
793794 railDecisions: "决定",
794795 railMerges: "合并",
795796 categoryEmpty: "这个队列是空的。",
@@ -832,6 +833,10 @@
832833 merge: "合并",
833834 keep: "保持分开",
834835 lowConfidence: "低置信度事实",
836+ mappings: "语义层",
837+ mappingsHint:
838+ "从业务概念到「这个数怎么算」的提议。确认之后问数直接用这个口径,而不是每次从 schema 猜。",
839+ mappingDerived: "派生",
835840 lowConfidenceHint:
836841 "抽取时置信度低于 75%。确认表示采信,驳回表示从图谱移除(台账仍留有记录)。",
837842 confirm: "确认",
modified web/src/pages/Review.tsx +96 −0
@@ -2,6 +2,7 @@
22 import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
33 import {
44 api,
5+ type ConceptMapping,
56 type ConflictItem,
67 type FactReviewItem,
78 type MergeLog,
@@ -437,6 +438,58 @@
437438 );
438439 }
439440
441+
442+/** 一条待表态的语义层映射(0011)。
443+ *
444+ * 展示的重点是**「这个数怎么算」**——SQL / 表达式 / 表名按这个优先级取一个,
445+ * 因为人要判断的正是它对不对。概念名与源是身份,unit 是答里必须带的量纲。 */
446+function MappingRow({
447+ mapping: m,
448+ busy,
449+ onDecide,
450+}: {
451+ mapping: ConceptMapping;
452+ busy: boolean;
453+ onDecide: (status: "confirmed" | "rejected") => void;
454+}) {
455+ const how = m.sql ?? m.expr ?? m.table_name ?? "—";
456+ return (
457+ <div className="glass rounded-xl p-3">
458+ <div className="flex items-baseline gap-2 flex-wrap">
459+ <span className="text-sm text-neutral-200">{m.concept_name}</span>
460+ <span className="text-[11px] text-neutral-500">{m.source}</span>
461+ {m.unit && (
462+ <span className="text-[11px] text-neutral-500">[{m.unit}]</span>
463+ )}
464+ {m.derived && (
465+ <span className="text-[11px] text-[var(--u-warn)]">
466+ {S.review.mappingDerived}
467+ </span>
468+ )}
469+ </div>
470+ <div className="mt-1 u-num text-xs text-neutral-400 break-all">{how}</div>
471+ {m.summary && (
472+ <p className="mt-1 text-xs text-neutral-500">{m.summary}</p>
473+ )}
474+ <div className="mt-2 flex gap-1.5">
475+ <button
476+ className="u-btn text-xs"
477+ disabled={busy}
478+ onClick={() => onDecide("rejected")}
479+ >
480+ {S.review.reject}
481+ </button>
482+ <button
483+ className="u-btn u-btn-primary text-xs"
484+ disabled={busy}
485+ onClick={() => onDecide("confirmed")}
486+ >
487+ {S.review.confirm}
488+ </button>
489+ </div>
490+ </div>
491+ );
492+}
440493 /* ---------- 页面:左栏分类 + 单类内容区 ---------- */
441494
442495 type Sel =
@@ -444,6 +497,9 @@
444497 | "conflicts"
445498 | "unconfirmed"
446499 | "lowconf"
500+ // 语义层的待表态映射(0011)。从前它借「低置信事实」那一档露面——
501+ // 靠 0.6 的置信度混进去,而它根本不是一条关于世界的断言
502+ | "mappings"
447503 | "decisions"
448504 | "merges";
449505
@@ -452,12 +508,14 @@
452508 "conflicts",
453509 "unconfirmed",
454510 "lowconf",
511+ "mappings",
455512 ];
456513 const PAGE_SIZE: Record<Sel, number> = {
457514 duplicates: DUP_PAGE,
458515 conflicts: CONFLICT_PAGE,
459516 unconfirmed: FACT_PAGE,
460517 lowconf: FACT_PAGE,
518+ mappings: FACT_PAGE,
461519 merges: MERGE_PAGE,
462520 decisions: 20,
463521 };
@@ -549,6 +607,16 @@
549607 : api.rejectFact(kb!.id, id),
550608 onSettled: invalidate,
551609 });
610+ const mappingAction = useMutation({
611+ mutationFn: ({
612+ id,
613+ status,
614+ }: {
615+ id: string;
616+ status: "confirmed" | "rejected";
617+ }) => api.decideMapping(kb!.id, id, status),
618+ onSettled: invalidate,
619+ });
552620 const revert = useMutation({
553621 mutationFn: (mergeId: string) => api.revertMerge(kb!.id, mergeId),
554622 onSettled: invalidate,
@@ -578,6 +646,7 @@
578646 conflicts: data?.conflicts?.length ?? 0,
579647 unconfirmed: data?.unconfirmed?.length ?? 0,
580648 lowconf: data?.facts.length ?? 0,
649+ mappings: data?.mappings?.length ?? 0,
581650 merges: data?.merges.length ?? 0,
582651 decisions: history.data?.total ?? 0,
583652 };
@@ -609,6 +678,7 @@
609678 title: S.review.lowConfidence,
610679 hint: S.review.lowConfidenceHint,
611680 },
681+ mappings: { title: S.review.mappings, hint: S.review.mappingsHint },
612682 decisions: { title: S.review.decisionsTitle, hint: S.review.decisionsHint },
613683 merges: { title: S.review.mergeHistory, hint: null },
614684 };
@@ -643,6 +713,12 @@
643713 count={counts.lowconf}
644714 onClick={() => select("lowconf")}
645715 />
716+ <RailItem
717+ active={active === "mappings"}
718+ label={S.review.railMappings}
719+ count={counts.mappings}
720+ onClick={() => select("mappings")}
721+ />
646722 </div>
647723 <RailHeader label={S.review.tabHistory} />
648724 <div className="px-2 space-y-0.5">
@@ -773,6 +849,26 @@
773849 </div>
774850 )}
775851
852+ {active === "mappings" && counts.mappings > 0 && (
853+ <div className="space-y-3">
854+ {pageSlice(data.mappings ?? [], page, FACT_PAGE).rows.map(
855+ (m) => (
856+ <MappingRow
857+ key={m.id}
858+ mapping={m}
859+ busy={
860+ mappingAction.isPending &&
861+ mappingAction.variables?.id === m.id
862+ }
863+ onDecide={(status) =>
864+ mappingAction.mutate({ id: m.id, status })
865+ }
866+ />
867+ ),
868+ )}
869+ </div>
870+ )}
871+
776872 {active === "merges" &&
777873 (counts.merges === 0 ? (
778874 <div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">