World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
A definition you cannot see is one you cannot argue with (#140)
WaylandYangbc8620f43d3e
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rsindex 34fde075..6e1b8bb4 100644--- a/crates/utopia-core/src/models.rs+++ b/crates/utopia-core/src/models.rs@@ -800,6 +800,21 @@ pub struct ProposedAttribute {pub domain_keys: Vec<String>,}+/// 一条口径改动之前的样子。+///+/// **存整版快照而不是差异**(0006):读的时候要回答的是「当时是什么」,+/// 而差异得从头重放才答得出来。`before` 是改动前那一行的 `to_jsonb`,+/// 去掉了 id 与 kb_id。+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]+pub struct MappingRevision {+ pub id: Uuid,+ pub before: serde_json::Value,+ /// 改的人。**裸外键 + 用户软删除**,所以归因不会因为人离职而丢;+ /// 真被硬删过才会是 NULL+ pub changed_by_name: Option<String>,+ pub changed_at: DateTime<Utc>,+}+/// 语义层的一条映射:业务概念 → 数据资产定义(见 `docs/decisions/0011`)。////// **字段是列,不是 JSON 里的键。** 从前它是一条 `mapped_to` 事实,diff --git a/crates/utopia-server/src/api/mapping_routes.rs b/crates/utopia-server/src/api/mapping_routes.rsnew file mode 100644index 00000000..af755b6b--- /dev/null+++ b/crates/utopia-server/src/api/mapping_routes.rs@@ -0,0 +1,148 @@+//! 数据映射 API:口径的列表、改写与改版历史。+//!+//! 审批(`decide`)留在 `review_routes`——那条端点已经在写审计流水+//! (`mapping.decided`),换个界面调它即可,没有理由为了搬页面而搬端点。++use axum::extract::{Path, Query, State};+use axum::Json;+use serde::Deserialize;+use serde_json::json;+use utopia_core::models::Role;+use utopia_core::AppError;+use uuid::Uuid;++use super::graph_routes::require_kb;+use crate::auth::AuthUser;+use crate::error::ApiResult;+use crate::state::AppState;++/// 一页多少条。口径比审阅队列密(一行就是一个定义),一页给得起 25 条+const MAPPING_PAGE: i64 = 25;++#[derive(Deserialize)]+pub struct ListQuery {+ /// proposed | confirmed | rejected;缺省 = 全部+ status: Option<String>,+ q: Option<String>,+ limit: Option<i64>,+ offset: Option<i64>,+}++/// 一页口径 + 三种状态各多少。+///+/// **Viewer 就能看。** 口径是「这个数怎么算」,问数的答案直接由它决定——+/// 看得见答案却看不见口径,等于要人信一个不给看的算法。改(`revise`)+/// 才要 Editor。+pub async fn list(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path(kb_id): Path<Uuid>,+ Query(q): Query<ListQuery>,+) -> ApiResult<Json<serde_json::Value>> {+ require_kb(&state, &user, kb_id, Role::Viewer).await?;+ let status = q.status.as_deref().filter(|s| !s.is_empty());+ if let Some(s) = status {+ if !matches!(s, "proposed" | "confirmed" | "rejected") {+ return Err(AppError::invalid(+ "bad_status",+ "status must be proposed, confirmed or rejected",+ )+ .into());+ }+ }+ let needle = q.q.as_deref().map(str::trim).filter(|s| !s.is_empty());+ let limit = q.limit.unwrap_or(MAPPING_PAGE).clamp(1, 200);+ let offset = q.offset.unwrap_or(0).max(0);++ let (items, total) =+ utopia_store::mappings::page(&state.pool, kb_id, status, needle, limit, offset).await?;+ let (proposed, confirmed, rejected) =+ utopia_store::mappings::status_counts(&state.pool, kb_id).await?;+ Ok(Json(json!({+ "items": items,+ "total": total,+ "counts": { "proposed": proposed, "confirmed": confirmed, "rejected": rejected },+ })))+}++#[derive(Deserialize)]+pub struct ReviseReq {+ table_name: Option<String>,+ expr: Option<String>,+ sql: Option<String>,+ unit: Option<String>,+ summary: Option<String>,+ #[serde(default)]+ derived: bool,+}++/// 改一条口径。+///+/// **在此之前 `mappings::revise` 是零调用的**:函数在、留痕表在、没有路由。+/// 于是口径确认之后就再没人改得动,也没人看得见——问数照着它算,人却够不着。+pub async fn revise(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path((kb_id, mapping_id)): Path<(Uuid, Uuid)>,+ Json(req): Json<ReviseReq>,+) -> ApiResult<Json<serde_json::Value>> {+ require_kb(&state, &user, kb_id, Role::Editor).await?;+ // 空白等于没填:前端清空一个输入框传来的是 "",落库该是 NULL 而不是空串,+ // 否则「有没有配 expr」这个判断要同时问 IS NULL 和 = ''+ let clean = |s: &Option<String>| -> Option<String> {+ s.as_deref()+ .map(str::trim)+ .filter(|x| !x.is_empty())+ .map(str::to_string)+ };+ let (table_name, expr, sql, unit, summary) = (+ clean(&req.table_name),+ clean(&req.expr),+ clean(&req.sql),+ clean(&req.unit),+ clean(&req.summary),+ );+ if table_name.is_none() && expr.is_none() && sql.is_none() {+ return Err(AppError::invalid(+ "empty_mapping",+ "A mapping needs at least one of table, expression or SQL",+ )+ .into());+ }+ utopia_store::mappings::revise(+ &state.pool,+ kb_id,+ mapping_id,+ table_name.as_deref(),+ expr.as_deref(),+ sql.as_deref(),+ unit.as_deref(),+ summary.as_deref(),+ req.derived,+ user.id,+ )+ .await?;+ let _ = utopia_store::audit::record(+ &state.pool,+ Some(kb_id),+ user.id,+ "mapping.revised",+ "concept_mapping",+ Some(mapping_id),+ json!({}),+ )+ .await;+ Ok(Json(json!({ "ok": true })))+}++/// 一条口径的改版历史。0006 说留痕是为了答得出「上季度这个数是怎么算的」,+/// 这是那句话的兑现处。+pub async fn revisions(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path((kb_id, mapping_id)): Path<(Uuid, Uuid)>,+) -> ApiResult<Json<serde_json::Value>> {+ require_kb(&state, &user, kb_id, Role::Viewer).await?;+ let rows = utopia_store::mappings::revisions(&state.pool, kb_id, mapping_id).await?;+ Ok(Json(json!({ "revisions": rows })))+}diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rsindex 6446319e..90bdc090 100644--- a/crates/utopia-server/src/api/mod.rs+++ b/crates/utopia-server/src/api/mod.rs@@ -7,6 +7,7 @@ mod documents_routes;mod events_routes;mod graph_routes;mod kbs;+mod mapping_routes;mod members_routes;pub(crate) mod ontology_routes;mod review_routes;@@ -110,6 +111,15 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {"/admin/data-sources/{id}/test",post(datasource_routes::test),)+ .route("/kbs/{id}/mappings", get(mapping_routes::list))+ .route(+ "/kbs/{id}/mappings/{mapping_id}",+ axum::routing::patch(mapping_routes::revise),+ )+ .route(+ "/kbs/{id}/mappings/{mapping_id}/revisions",+ get(mapping_routes::revisions),+ ).route("/kbs/{id}/data-sources", get(datasource_routes::mounted)).route("/kbs/{id}/data-sources/available",diff --git a/crates/utopia-server/src/api/review_routes.rs b/crates/utopia-server/src/api/review_routes.rsindex 63c59406..71933ea0 100644--- a/crates/utopia-server/src/api/review_routes.rs+++ b/crates/utopia-server/src/api/review_routes.rs@@ -474,7 +474,7 @@ pub async fn decide_mapping(if !matches!(req.status.as_str(), "confirmed" | "rejected") {return Err(utopia_core::AppError::invalid("bad_status",- "status 只能是 confirmed 或 rejected",+ "status must be confirmed or rejected",).into());}diff --git a/crates/utopia-store/src/mappings.rs b/crates/utopia-store/src/mappings.rsindex c1165e96..fb043f1e 100644--- a/crates/utopia-store/src/mappings.rs+++ b/crates/utopia-store/src/mappings.rs@@ -8,7 +8,7 @@//! append-only,改之前的那一版进 `concept_mapping_revisions` 留痕即可。use sqlx::PgPool;-use utopia_core::models::ConceptMapping;+use utopia_core::models::{ConceptMapping, MappingRevision};use utopia_core::{AppError, AppResult};use uuid::Uuid;@@ -205,3 +205,93 @@ pub async fn revise(tx.commit().await?;Ok(())}++/// 数据映射页读的:一页口径,可按状态与关键词筛。+///+/// **`proposed` 与 `confirmed` 那两条查询都不够用**——前者只捞待表态的,+/// 后者是给问数拼 prompt 的(无分页、无筛选、限 30 条)。人要看的是全部,+/// 包括被自己拒绝过的那些:拒绝留了痕,就该看得见,否则「为什么这个概念+/// 没被映射」永远答不上来。+pub async fn page(+ pool: &PgPool,+ kb_id: Uuid,+ status: Option<&str>,+ q: Option<&str>,+ limit: i64,+ offset: i64,+) -> AppResult<(Vec<ConceptMapping>, i64)> {+ // 概念名与数据源名都可搜:人记得住的是「GMV」,也可能是「那个接了 orders 的」+ const WHERE: &str = "WHERE m.kb_id = $1+ AND ($2::text IS NULL OR m.status = $2)+ AND ($3::text IS NULL+ OR e.canonical_name ILIKE '%' || $3 || '%'+ OR m.source ILIKE '%' || $3 || '%'+ OR m.table_name ILIKE '%' || $3 || '%')";+ let rows: Vec<ConceptMapping> = sqlx::query_as(&format!(+ "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}+ ORDER BY e.canonical_name, m.source+ LIMIT $4 OFFSET $5"+ ))+ .bind(kb_id)+ .bind(status)+ .bind(q)+ .bind(limit)+ .bind(offset)+ .fetch_all(pool)+ .await?;+ let (total,): (i64,) = sqlx::query_as(&format!(+ "SELECT count(*) FROM concept_mappings m+ JOIN entities e ON e.id = m.concept_id {WHERE}"+ ))+ .bind(kb_id)+ .bind(status)+ .bind(q)+ .fetch_one(pool)+ .await?;+ Ok((rows, total))+}++/// 每种状态各多少。页面的筛选条要显示计数,分三次查是三次全表扫。+pub async fn status_counts(pool: &PgPool, kb_id: Uuid) -> AppResult<(i64, i64, i64)> {+ let row: (i64, i64, i64) = sqlx::query_as(+ "SELECT count(*) FILTER (WHERE status = 'proposed'),+ count(*) FILTER (WHERE status = 'confirmed'),+ count(*) FILTER (WHERE status = 'rejected')+ FROM concept_mappings WHERE kb_id = $1",+ )+ .bind(kb_id)+ .fetch_one(pool)+ .await?;+ Ok(row)+}++/// 一条口径改过几次、每次改之前是什么样。+///+/// `revise` 从建表起就在写 `concept_mapping_revisions`,而**在此之前没有任何+/// 地方读它**——留痕留了个寂寞。0006 说留痕是为了「问数回溯历史报表时答得出+/// 『上季度这个数是怎么算的』」,那就得有人看得见。+pub async fn revisions(+ pool: &PgPool,+ kb_id: Uuid,+ mapping_id: Uuid,+) -> AppResult<Vec<MappingRevision>> {+ // kb_id 走 JOIN 校验归属:revisions 表自己没有 kb_id,+ // 不校验就能拿别的库的口径历史+ Ok(sqlx::query_as(+ "SELECT r.id, r.before, u.display_name AS changed_by_name, r.changed_at+ FROM concept_mapping_revisions r+ JOIN concept_mappings m ON m.id = r.mapping_id+ LEFT JOIN users u ON u.id = r.changed_by+ WHERE r.mapping_id = $2 AND m.kb_id = $1+ ORDER BY r.changed_at DESC+ LIMIT 50",+ )+ .bind(kb_id)+ .bind(mapping_id)+ .fetch_all(pool)+ .await?)+}diff --git a/web/src/api.ts b/web/src/api.tsindex 3f18538b..5cd2c588 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -394,8 +394,7 @@ export interface ReviewItem {right: ReviewSide;}--/** 语义层的一条映射:业务概念 → 数据资产定义(见 docs/decisions/0011)。+/** 数据映射的一条口径:业务概念 → 数据资产定义(见 docs/decisions/0011)。** 字段是列而不是 JSON 里的键——从前它是一条 `mapped_to` 事实,* 这几样全塞在 `object_value` 里。 */@@ -414,6 +413,15 @@ export interface ConceptMapping {derived: boolean;status: "proposed" | "confirmed" | "rejected";}+/** 一条口径改动之前的样子。**整版快照而不是差异**(0006):+ * 读的时候要回答的是「当时是什么」,差异得从头重放才答得出来 */+export interface MappingRevision {+ id: string;+ before: Record<string, unknown>;+ /** 改的人;用户是软删除的,所以归因不会因为人离职而丢 */+ changed_by_name: string | null;+ changed_at: string;+}/** 一处公理违规(0002 R0)。判据来自本体自己声明的公理,没声明就不报 */export interface AxiomViolation {id: string;@@ -981,8 +989,7 @@ export const api = {/** 已停用的账号。**没有它恢复就够不着**——那个人从所有列表里消失,* 而恢复接口要的正是他的 id */- deactivatedUsers: () =>- request<OrgUser[]>("/api/v1/users/deactivated"),+ deactivatedUsers: () => request<OrgUser[]>("/api/v1/users/deactivated"),/** 恢复一个停用的账号 */adminReactivateUser: (userId: string) =>request<{ ok: boolean }>(`/api/v1/admin/users/${userId}`, {@@ -1008,6 +1015,51 @@ export const api = {request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}/test`, {method: "POST",}),++ /** 一页口径。**Viewer 就能看**——问数的答案直接由口径决定,+ * 看得见答案却看不见口径,等于要人信一个不给看的算法 */+ mappings: (+ kbId: string,+ opts: {+ status?: "proposed" | "confirmed" | "rejected";+ q?: string;+ limit?: number;+ offset?: number;+ } = {},+ ) => {+ const p = new URLSearchParams();+ if (opts.status) p.set("status", opts.status);+ if (opts.q) p.set("q", opts.q);+ if (opts.limit != null) p.set("limit", String(opts.limit));+ if (opts.offset != null) p.set("offset", String(opts.offset));+ const qs = p.toString();+ return request<{+ items: ConceptMapping[];+ total: number;+ counts: { proposed: number; confirmed: number; rejected: number };+ }>(`/api/v1/kbs/${kbId}/mappings${qs ? `?${qs}` : ""}`);+ },+ /** 改一条口径。改之前那一版自动进 revisions */+ reviseMapping: (+ kbId: string,+ mappingId: string,+ body: {+ table_name?: string | null;+ expr?: string | null;+ sql?: string | null;+ unit?: string | null;+ summary?: string | null;+ derived: boolean;+ },+ ) =>+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/mappings/${mappingId}`, {+ method: "PATCH",+ body: JSON.stringify(body),+ }),+ mappingRevisions: (kbId: string, mappingId: string) =>+ request<{ revisions: MappingRevision[] }>(+ `/api/v1/kbs/${kbId}/mappings/${mappingId}/revisions`,+ ),kbDataSources: (kbId: string) =>request<{ data_sources: DataSourceView[] }>(`/api/v1/kbs/${kbId}/data-sources`,@@ -1337,9 +1389,10 @@ export const api = {/** 值换不动那个 datatype、因而没被改写的条数。改写了 3 条丢下 2 条,只报前半句就是报喜不报忧 */unconvertible?: number;- }>(`/api/v1/kbs/${kbId}/ontology/adopt-predicate`,- { method: "POST", body: JSON.stringify(body) },- ),+ }>(`/api/v1/kbs/${kbId}/ontology/adopt-predicate`, {+ method: "POST",+ body: JSON.stringify(body),+ }),/** 撤销一次采纳:新写的行作废、旧行复活。关系类型留着 */unadoptPredicate: (kbId: string, batchId: string) =>request<{ reverted: number }>(@@ -1402,12 +1455,7 @@ export const api = {/** 审核队列的各档**真实条数**。与列表分开取——列表有一页的上限,数数没有。* 从前徽标读的是数组长度,而接口固定只回 100 条,于是 164 条写成 100。 */- review: (- kbId: string,- queue: ReviewQueue,- limit: number,- offset: number,- ) =>+ review: (kbId: string, queue: ReviewQueue, limit: number, offset: number) =>request<{counts: ReviewCounts;queue: ReviewQueue;@@ -1435,12 +1483,19 @@ 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 }),- }),+ /** 对一条数据映射口径表态(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 }),+ },+ ),/** 跑一遍一致性检查。同步返回——纯计算,没有模型调用也没有网络 */runConsistencyCheck: (kbId: string) =>request<{diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex 09e2cf7c..8a711a5d 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -566,7 +566,8 @@ export const en = {「采购了」出来是 purchases——说"原文说的是 purchases"是假的。逐字原句就在旁边的证据引文里,没丢。 */proposedPredicate: (p: string) => `read from the text as “${p}”`,- inferredPredicate: "not a relation in the ontology, this is the source's wording",+ inferredPredicate:+ "not a relation in the ontology, this is the source's wording",unknownPredicate: "no relation stated",sectionRef: (filename: string, seq: number) =>`${filename} · section ${seq} →`,@@ -614,7 +615,11 @@ export const en = {derivedOff: "off",derivedNever: "never",derivedAgo: (mins: number) =>- mins < 1 ? "just now" : mins < 60 ? `${mins} min ago` : `${Math.round(mins / 60)} h ago`,+ mins < 1+ ? "just now"+ : mins < 60+ ? `${mins} min ago`+ : `${Math.round(mins / 60)} h ago`,derivedRun: "Run now",derivedRunning: "Running…",derivedNoChange: "Nothing changed.",@@ -738,7 +743,8 @@ export const en = {defaultChip: "Default",newKb: "New knowledge base",packsLabel: "Bundled ontologies",- packsHint: "Optional. Packs declare direction, so subject and object cannot come out reversed. More can be imported later.",+ packsHint:+ "Optional. Packs declare direction, so subject and object cannot come out reversed. More can be imported later.",packsNone: "None — start from the ten seed relations",packsCount: (c: number, p: number) => `${c} classes · ${p} properties`,name: "Name",@@ -854,14 +860,16 @@ export const en = {axioms: "Axioms",axiomsHint:"What this relation guarantees. These are not descriptions — they change what the system does: the temporal engine closes old values, and the reasoning engine adds edges to the graph.",- functionalHint: "One subject, one value at a time. A new value closes the old one.",+ functionalHint:+ "One subject, one value at a time. A new value closes the old one.",inverseFunctionalHint: "One object, one subject. A project has one lead.",transitive: "Transitive",transitiveHint: "A→B and B→C means A→C. The engine will add those edges.",symmetric: "Symmetric",symmetricHint: "A→B means B→A. The engine will add the other direction.",asymmetric: "Asymmetric",- asymmetricHint: "A→B rules out B→A. Both directions get reported as a contradiction.",+ asymmetricHint:+ "A→B rules out B→A. Both directions get reported as a contradiction.",irreflexive: "Irreflexive",irreflexiveHint: "Nothing can point at itself through this relation.",axiomConflict:@@ -985,6 +993,66 @@ export const en = {proposals: "AI proposals",keyHint: "lowercase_snake_case",},+ mapping: {+ title: "Data mapping",+ hint: "What business concepts point at in the database, and how they are computed. Ask only answers using confirmed definitions.",+ tabDefinitions: "Definitions",+ tabSources: "Data sources",+ filterAll: "All",+ filterProposed: "Pending",+ filterConfirmed: "Confirmed",+ filterRejected: "Rejected",+ searchPlaceholder: "Search concept, source or table…",+ total: (n: number) => `${n} total`,+ range: (from: number, to: number, total: number) =>+ `${from}–${to} of ${total}`,+ prev: "Previous",+ next: "Next",+ empty:+ "No definitions yet. Mount a data source, then run Explore to have an agent propose a first batch.",+ emptyFiltered: "No definitions match.",+ rejectedHint:+ "Rejected ones are listed too — otherwise “why was this concept never mapped?” has no answer.",+ colConcept: "Concept",+ colSource: "Source",+ colDefinition: "How it is computed",+ colStatus: "Status",+ derivedBadge: "Derived",+ noDefinition: "(empty)",+ approve: "Confirm",+ reject: "Reject",+ edit: "Edit",+ editTitle: "Revise definition",+ fieldTable: "Table",+ fieldExpr: "Expression",+ fieldSql: "SQL",+ fieldUnit: "Unit",+ fieldSummary: "Summary",+ fieldDerived: "Derived metric (computed, not a column)",+ save: "Save",+ cancel: "Cancel",+ needOne: "Fill in at least one of table, expression or SQL.",+ history: "Revision history",+ historyHint:+ "A full snapshot of the version before each change. Kept so “how was this number computed last quarter?” has an answer.",+ historyEmpty: "Never revised.",+ historyBy: (who: string) => `Revised by ${who}`,+ historyUnknown: "a removed user",+ sourcesHint:+ "Read-only databases mounted here. Mounting ingests the schema so Ask knows which tables exist before writing SQL.",+ mount: "Mount",+ unmount: "Unmount",+ syncSchema: "Refresh schema",+ schemaSynced: (n: number) => `Schema ingested (${n} tables)`,+ explore: "Explore mappings",+ exploreHint:+ "An agent reads these schemas and proposes metric and dimension definitions. Proposals land in Pending; Ask uses them only once confirmed.",+ exploreQueued: "Exploration queued — proposals will appear under Pending.",+ sourcesEmpty: "No data sources mounted.",+ sourcesNoneAvailable:+ "No data sources registered yet — ask a deployment admin to register one.",+ newConn: "Register a new connection",+ },review: {title: "Review",hint: "Duplicates & low-confidence facts",@@ -997,7 +1065,7 @@ export const en = {railConflicts: "Conflicts",railUnconfirmed: "Unconfirmed",railLowConfidence: "Low confidence",- railMappings: "Semantic layer",+ railMappings: "Data mapping",railViolations: "Axioms",railDefects: "Ontology",railDecisions: "Decisions",@@ -1088,7 +1156,7 @@ export const en = {* 一条会让人以为界面漏了东西 */checkNothingNew: "Nothing new",checkClean: (n: number) => `${n} facts checked, no contradictions`,- mappings: "Semantic layer",+ mappings: "Data mapping",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",diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex 71031293..b32b3558 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -566,7 +566,11 @@ export const zh: Strings = {derivedOff: "已关闭",derivedNever: "从未",derivedAgo: (mins: number) =>- mins < 1 ? "刚刚" : mins < 60 ? `${mins} 分钟前` : `${Math.round(mins / 60)} 小时前`,+ mins < 1+ ? "刚刚"+ : mins < 60+ ? `${mins} 分钟前`+ : `${Math.round(mins / 60)} 小时前`,derivedRun: "现在跑一遍",derivedRunning: "推理中…",derivedNoChange: "没有变化。",@@ -674,7 +678,8 @@ export const zh: Strings = {defaultChip: "默认",newKb: "新建知识库",packsLabel: "预置本体",- packsHint: "可不选。包里的谓语带方向声明,主宾颠倒进不来。之后还能再导入。",+ packsHint:+ "可不选。包里的谓语带方向声明,主宾颠倒进不来。之后还能再导入。",packsNone: "不选 —— 从十个种子关系起步",packsCount: (c: number, p: number) => `${c} 个类 · ${p} 个属性`,name: "名称",@@ -850,7 +855,8 @@ export const zh: Strings = {"抽取器产出了这些,但它们不在你的本体里(于是降级成了 concept / related to)。它们是扩展本体的信号。",dismiss: "忽略",dismissed: (n: number) => `已忽略(${n})`,- dismissedHint: "仍在计数,只是不进建议。如果某一个在你忽略之后涨了,可以撤回。",+ dismissedHint:+ "仍在计数,只是不进建议。如果某一个在你忽略之后涨了,可以撤回。",restore: "撤回忽略",suggest: "用 AI 建议",suggesting: "分析中…",@@ -884,6 +890,64 @@ export const zh: Strings = {proposals: "AI 提案",keyHint: "小写下划线命名",},+ mapping: {+ title: "数据映射",+ hint: "业务概念在数据库里对应什么、怎么算。问数只按确认过的口径回答。",+ tabDefinitions: "口径",+ tabSources: "数据源",+ filterAll: "全部",+ filterProposed: "待审批",+ filterConfirmed: "已确认",+ filterRejected: "已拒绝",+ searchPlaceholder: "搜概念、数据源或表名…",+ total: (n: number) => `共 ${n} 条`,+ range: (from: number, to: number, total: number) =>+ `第 ${from}–${to} 条,共 ${total} 条`,+ prev: "上一页",+ next: "下一页",+ empty: "还没有口径。挂上数据源后点「探查映射」,让智能体先提一批。",+ emptyFiltered: "没有符合条件的口径。",+ rejectedHint:+ "拒绝过的也列在这里——否则「这个概念为什么没被映射」永远答不上来。",+ colConcept: "概念",+ colSource: "数据源",+ colDefinition: "怎么算",+ colStatus: "状态",+ derivedBadge: "派生",+ noDefinition: "(未填)",+ approve: "确认",+ reject: "拒绝",+ edit: "编辑",+ editTitle: "改口径",+ fieldTable: "表",+ fieldExpr: "表达式",+ fieldSql: "SQL",+ fieldUnit: "单位",+ fieldSummary: "说明",+ fieldDerived: "派生指标(算出来的,不是表里的列)",+ save: "保存",+ cancel: "取消",+ needOne: "表、表达式、SQL 至少填一个。",+ history: "改版历史",+ historyHint:+ "改之前那一版的整版快照。留着是为了答得出「上季度这个数是怎么算的」。",+ historyEmpty: "还没有改过。",+ historyBy: (who: string) => `由 ${who} 修改`,+ historyUnknown: "一位已移除的用户",+ sourcesHint:+ "已挂载的只读数据库。挂载会摄入库表结构,问数写 SQL 前才知道有哪些表。",+ mount: "挂载",+ unmount: "卸载",+ syncSchema: "刷新结构",+ schemaSynced: (n: number) => `结构已摄入(${n} 张表)`,+ explore: "探查映射",+ exploreHint:+ "一个智能体读这些库表结构,提出指标/维度的口径。提出来的落在「待审批」,确认之后问数才会用。",+ exploreQueued: "探查已排队——提案稍后出现在「待审批」。",+ sourcesEmpty: "没有挂载任何数据源。",+ sourcesNoneAvailable: "还没有登记数据源——请部署管理员登记一个。",+ newConn: "登记新连接",+ },review: {title: "审阅",hint: "重复项与低置信度事实",@@ -895,7 +959,7 @@ export const zh: Strings = {railConflicts: "冲突",railUnconfirmed: "未确认",railLowConfidence: "低置信度",- railMappings: "语义层",+ railMappings: "数据映射",railViolations: "公理",railDefects: "本体",railDecisions: "决定",@@ -980,7 +1044,7 @@ export const zh: Strings = {* 一条会让人以为界面漏了东西 */checkNothingNew: "没有新的",checkClean: (n: number) => `查了 ${n} 条事实,没有矛盾`,- mappings: "语义层",+ mappings: "数据映射",mappingsHint:"从业务概念到「这个数怎么算」的提议。确认之后问数直接用这个口径,而不是每次从 schema 猜。",mappingDerived: "派生",diff --git a/web/src/pages/KbSettings.tsx b/web/src/pages/KbSettings.tsxindex 77891d26..f60e5add 100644--- a/web/src/pages/KbSettings.tsx+++ b/web/src/pages/KbSettings.tsx@@ -6,10 +6,8 @@ import { useEffect, useState } from "react";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { useNavigate, useSearch } from "@tanstack/react-router";import {- Database,History as HistoryIcon,Lock,- Plus,Settings2,TriangleAlert,Users,@@ -46,7 +44,7 @@ function rolesFor(isOpen: boolean) {return isOpen ? KB_ROLES.filter((r) => r.value !== "viewer") : KB_ROLES;}-type Section = "general" | "members" | "data" | "activity" | "danger";+type Section = "general" | "members" | "activity" | "danger";export function KbSettings() {const navigate = useNavigate();@@ -138,7 +136,6 @@ export function KbSettings() {}[] = [{ key: "general", label: S.kbset.general, Icon: Settings2 },{ key: "members", label: S.kbset.members, Icon: Users },- { key: "data", label: S.kbset.data, Icon: Database },{ key: "activity", label: S.kbset.activity, Icon: HistoryIcon },// 默认库不可删除:danger 节整个不出现...(isDefault@@ -345,7 +342,6 @@ export function KbSettings() {{section === "members" && (<KbMembers kbId={kbId} isOpen={kb.data.visibility === "open"} />)}- {section === "data" && <KbDataSources kbId={kbId} />}{section === "activity" && <KbActivity kbId={kbId} />}@@ -513,161 +509,7 @@ function KbActivity({ kbId }: { kbId: string }) {))}</div>)}- <Pager- total={total}- pageSize={AUDIT_PAGE}- page={page}- onPage={setPage}- />- </div>- );-}--/** 知识库层数据源挂载:从系统已注册的源里挑选;挂载即摄取 schema。- 注册新连接是部署级动作:管理员从这里深链去 Deployment settings 的 Data sources。 */-function KbDataSources({ kbId }: { kbId: string }) {- const queryClient = useQueryClient();- const navigate = useNavigate();- const me = useQuery({ queryKey: ["me"], queryFn: api.me });- const mounted = useQuery({- queryKey: ["kbDataSources", kbId],- queryFn: () => api.kbDataSources(kbId),- });- const available = useQuery({- queryKey: ["kbDataSourcesAvail", kbId],- queryFn: () => api.kbDataSourcesAvailable(kbId),- });- const [picked, setPicked] = useState("");- const [notice, setNotice] = useState<string | null>(null);- const invalidate = () =>- queryClient.invalidateQueries({ queryKey: ["kbDataSources", kbId] });-- const mount = useMutation({- mutationFn: (dsId: string) => api.mountDataSource(kbId, dsId),- onSuccess: (r) => {- setPicked("");- setNotice(S.kbset.dataSchemaSynced(r.schema_tables));- invalidate();- },- });- const unmount = useMutation({- mutationFn: (dsId: string) => api.unmountDataSource(kbId, dsId),- onSettled: invalidate,- });- const sync = useMutation({- mutationFn: (dsId: string) => api.syncDataSourceSchema(kbId, dsId),- onSuccess: (r) => setNotice(S.kbset.dataSchemaSynced(r.schema_tables)),- });- const explore = useMutation({- mutationFn: () => api.exploreMappings(kbId),- onSuccess: () => setNotice(S.kbset.dataExploreQueued),- });-- const mountedIds = new Set(- (mounted.data?.data_sources ?? []).map((d) => d.id),- );- const mountable = (available.data?.data_sources ?? []).filter(- (d) => !mountedIds.has(d.id),- );-- return (- <div className="space-y-4">- <p className="text-xs text-neutral-500">{S.kbset.dataHint}</p>-- <div className="glass rounded-xl divide-y divide-white/5">- {(mounted.data?.data_sources ?? []).map((d) => (- <div key={d.id} className="px-4 py-3 flex items-center gap-3">- <div className="min-w-0 flex-1">- <div className="text-sm text-neutral-200">{d.name}</div>- <div className="text-xs text-neutral-500 font-mono truncate">- {d.summary}- </div>- </div>- <button- className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"- disabled={sync.isPending}- onClick={() => sync.mutate(d.id)}- >- {S.kbset.dataSyncSchema}- </button>- <button- className="text-xs text-neutral-500 hover:text-[var(--u-danger)] shrink-0"- disabled={unmount.isPending}- onClick={() => unmount.mutate(d.id)}- >- {S.kbset.dataUnmount}- </button>- </div>- ))}- {mounted.data?.data_sources.length === 0 && (- <p className="px-4 py-6 text-sm text-neutral-500">- {S.kbset.dataNone}- </p>- )}- </div>-- {mountable.length > 0 && (- <div className="flex items-center gap-2">- <SearchSelect- className="flex-1"- value={picked}- options={mountable.map((d) => ({- value: d.id,- label: d.name,- hint: d.summary,- }))}- onChange={setPicked}- placeholder={S.kbset.dataMount + "…"}- />- <button- className="u-btn u-btn-primary px-3.5 py-1.5 text-xs shrink-0"- disabled={!picked || mount.isPending}- onClick={() => mount.mutate(picked)}- >- {S.kbset.dataMount}- </button>- </div>- )}- {/* 连接注册在部署层:管理员给直达入口,其他人指路找管理员 */}- {me.data?.is_admin ? (- <button- className="flex items-center gap-1.5 text-xs text-neutral-500 hover:text-neutral-300 transition-colors"- onClick={() =>- navigate({ to: "/admin", search: { tab: "datasources" } })- }- >- <Plus size={12} />- {S.kbset.dataNewConn}- </button>- ) : (- mountable.length === 0 &&- available.data &&- (mounted.data?.data_sources.length ?? 0) === 0 && (- <p className="text-xs text-neutral-600">- {S.kbset.dataNoneAvailable}- </p>- )- )}- {(mounted.data?.data_sources.length ?? 0) > 0 && (- <div className="glass rounded-xl px-4 py-3 flex items-center gap-3">- <p className="text-xs text-neutral-500 flex-1">- {S.kbset.dataExploreHint}- </p>- <button- className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"- disabled={explore.isPending}- onClick={() => explore.mutate()}- >- {S.kbset.dataExplore}- </button>- </div>- )}- {notice && <p className="text-xs text-[var(--u-ok)]">{notice}</p>}- {(mount.isError || sync.isError || explore.isError) && (- <p className="text-xs text-rose-400">- {((mount.error ?? sync.error ?? explore.error) as Error).message}- </p>- )}+ <Pager total={total} pageSize={AUDIT_PAGE} page={page} onPage={setPage} /></div>);}@@ -751,32 +593,30 @@ function KbMembers({ kbId, isOpen }: { kbId: string; isOpen: boolean }) {功能坏了,而不是"没人可加"。空列表由 SearchSelect 自己说(它有 noMatches 空态),这里不必再加一句话 */}<div className="mt-3 flex gap-2 items-center border-t border-white/5 pt-3">- <SearchSelect- className="flex-1"- value={addUserId}- onChange={setAddUserId}- placeholder={S.kbset.addMember}- options={addable.map((u) => ({- value: u.id,- label: u.display_name,- hint: u.email,- }))}- />- <Dropdown- className="w-24"- value={addRole}- onChange={setAddRole}- options={rolesFor(isOpen)}- />- <button- className="u-btn u-btn-primary px-3 py-1.5 text-xs"- disabled={!addUserId || setMember.isPending}- onClick={() =>- setMember.mutate({ userId: addUserId, role: addRole })- }- >- {S.members.add}- </button>+ <SearchSelect+ className="flex-1"+ value={addUserId}+ onChange={setAddUserId}+ placeholder={S.kbset.addMember}+ options={addable.map((u) => ({+ value: u.id,+ label: u.display_name,+ hint: u.email,+ }))}+ />+ <Dropdown+ className="w-24"+ value={addRole}+ onChange={setAddRole}+ options={rolesFor(isOpen)}+ />+ <button+ className="u-btn u-btn-primary px-3 py-1.5 text-xs"+ disabled={!addUserId || setMember.isPending}+ onClick={() => setMember.mutate({ userId: addUserId, role: addRole })}+ >+ {S.members.add}+ </button></div></div>);diff --git a/web/src/pages/Mappings.tsx b/web/src/pages/Mappings.tsxnew file mode 100644index 00000000..f5df50a9--- /dev/null+++ b/web/src/pages/Mappings.tsx@@ -0,0 +1,587 @@+// 数据映射:业务概念在数据库里对应什么、怎么算。+//+// **这一页在此之前不存在**,而它管的东西一直都在:口径由探查任务提出、在+// 「审阅」里被确认,然后沉进问数的 system prompt——人再也看不见它,也改不动。+// `mappings::revise` 连同它的留痕表从建表起就是零调用的。+//+// 审批留在同一个端点上(`review/mappings/{id}`,那里已经在写审计流水),+// 搬的是界面不是逻辑:判断一条口径对不对要看得见表结构,而那在这一页。+import { useState } from "react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { Database, History, Pencil, Plus } from "lucide-react";+import { useNavigate } from "@tanstack/react-router";+import { api, type ConceptMapping } from "../api";+import { S } from "../i18n";+import { useKb } from "../kb";+import { toast } from "../toast";+import {+ Chip,+ type ChipTone,+ EmptyState,+ ErrorText,+ Loading,+ Pager,+ PageTitle,+ SearchSelect,+ cn,+} from "../ui";++const PAGE = 25;++type StatusFilter = "all" | "proposed" | "confirmed" | "rejected";++const TONE: Record<string, ChipTone> = {+ proposed: "warn",+ confirmed: "success",+ rejected: "neutral",+};++/** 「这个数怎么算」。SQL / 表达式 / 表名按这个优先级取一个——+ * 三者都在回答同一个问题,而 SQL 最具体、表名最粗 */+const howComputed = (m: ConceptMapping) =>+ m.sql ?? m.expr ?? m.table_name ?? null;++const statusLabel = (s: string) =>+ s === "proposed"+ ? S.mapping.filterProposed+ : s === "confirmed"+ ? S.mapping.filterConfirmed+ : S.mapping.filterRejected;++export function Mappings() {+ const { kb } = useKb();+ const queryClient = useQueryClient();+ const [tab, setTab] = useState<"definitions" | "sources">("definitions");+ const [status, setStatus] = useState<StatusFilter>("all");+ const [q, setQ] = useState("");+ const [page, setPage] = useState(0);++ const data = useQuery({+ queryKey: ["mappings", kb?.id, status, q, page],+ queryFn: () =>+ api.mappings(kb!.id, {+ status: status === "all" ? undefined : status,+ q: q || undefined,+ limit: PAGE,+ offset: page * PAGE,+ }),+ enabled: !!kb,+ });++ const refresh = () =>+ queryClient.invalidateQueries({ queryKey: ["mappings", kb?.id] });++ if (!kb) return <Loading>{S.nav.loading}</Loading>;++ const counts = data.data?.counts;+ const FILTERS: { key: StatusFilter; label: string; n?: number }[] = [+ { key: "all", label: S.mapping.filterAll },+ { key: "proposed", label: S.mapping.filterProposed, n: counts?.proposed },+ {+ key: "confirmed",+ label: S.mapping.filterConfirmed,+ n: counts?.confirmed,+ },+ { key: "rejected", label: S.mapping.filterRejected, n: counts?.rejected },+ ];++ return (+ <div className="p-6 max-w-4xl mx-auto space-y-4">+ <div>+ <PageTitle>{S.mapping.title}</PageTitle>+ <p className="mt-1 text-xs text-neutral-500">{S.mapping.hint}</p>+ </div>++ <div className="flex gap-1.5">+ {(["definitions", "sources"] as const).map((t) => (+ <button+ key={t}+ className={cn(+ "u-btn px-3 py-1 text-xs",+ tab === t && "u-btn-primary",+ )}+ onClick={() => setTab(t)}+ >+ {t === "definitions"+ ? S.mapping.tabDefinitions+ : S.mapping.tabSources}+ </button>+ ))}+ </div>++ {tab === "sources" ? (+ <DataSources kbId={kb.id} onExplored={refresh} />+ ) : (+ <>+ <div className="flex items-center gap-2 flex-wrap">+ {FILTERS.map((f) => (+ <button+ key={f.key}+ className={cn(+ "u-btn px-2.5 py-1 text-xs",+ status === f.key && "u-btn-primary",+ )}+ onClick={() => {+ setStatus(f.key);+ setPage(0);+ }}+ >+ {f.label}+ {f.n != null && <span className="u-num ml-1.5">{f.n}</span>}+ </button>+ ))}+ <input+ className="u-input flex-1 min-w-40 px-3 py-1 text-xs"+ placeholder={S.mapping.searchPlaceholder}+ value={q}+ onChange={(e) => {+ setQ(e.target.value);+ setPage(0);+ }}+ />+ </div>++ {status === "rejected" && (+ <p className="text-xs text-neutral-600">{S.mapping.rejectedHint}</p>+ )}++ {data.isPending ? (+ <Loading>{S.nav.loading}</Loading>+ ) : data.data && data.data.items.length === 0 ? (+ <div className="py-12">+ <EmptyState icon={<Database size={20} />}>+ {q || status !== "all"+ ? S.mapping.emptyFiltered+ : S.mapping.empty}+ </EmptyState>+ </div>+ ) : (+ <div className="space-y-2">+ {data.data?.items.map((m) => (+ <MappingCard+ key={m.id}+ kbId={kb.id}+ mapping={m}+ onChanged={refresh}+ />+ ))}+ </div>+ )}+ <Pager+ total={data.data?.total ?? 0}+ pageSize={PAGE}+ page={page}+ onPage={setPage}+ />+ </>+ )}+ </div>+ );+}++/** 一条口径。**未表态的才给确认/拒绝两个按钮**——已表过态的给「编辑」,+ * 因为改口径和第一次拍板是两件事:前者要留痕(revisions),后者不用。 */+function MappingCard({+ kbId,+ mapping: m,+ onChanged,+}: {+ kbId: string;+ mapping: ConceptMapping;+ onChanged: () => void;+}) {+ const [editing, setEditing] = useState(false);+ const [showHistory, setShowHistory] = useState(false);++ const decide = useMutation({+ mutationFn: (s: "confirmed" | "rejected") =>+ api.decideMapping(kbId, m.id, s),+ onSuccess: onChanged,+ onError: (e: unknown) => toast.error((e as Error).message),+ });++ const how = howComputed(m);+ 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 && (+ <Chip tone="warn" className="text-[11px]">+ {S.mapping.derivedBadge}+ </Chip>+ )}+ <span className="flex-1" />+ <Chip tone={TONE[m.status]} className="text-[11px]">+ {statusLabel(m.status)}+ </Chip>+ </div>++ <div+ className={cn(+ "mt-1 u-num text-xs break-all",+ how ? "text-neutral-400" : "text-neutral-600",+ )}+ >+ {how ?? S.mapping.noDefinition}+ </div>+ {m.summary && (+ <p className="mt-1 text-xs text-neutral-500">{m.summary}</p>+ )}++ {editing ? (+ <EditForm+ kbId={kbId}+ mapping={m}+ onDone={() => {+ setEditing(false);+ onChanged();+ }}+ onCancel={() => setEditing(false)}+ />+ ) : (+ <div className="mt-2 flex items-center gap-1.5 flex-wrap">+ {m.status === "proposed" && (+ <>+ <button+ className="u-btn text-xs"+ disabled={decide.isPending}+ onClick={() => decide.mutate("rejected")}+ >+ {S.mapping.reject}+ </button>+ <button+ className="u-btn u-btn-primary text-xs"+ disabled={decide.isPending}+ onClick={() => decide.mutate("confirmed")}+ >+ {S.mapping.approve}+ </button>+ </>+ )}+ <button+ className="u-btn u-btn-ghost px-2 py-1 text-xs flex items-center gap-1"+ onClick={() => setEditing(true)}+ >+ <Pencil size={11} />+ {S.mapping.edit}+ </button>+ <button+ className="u-btn u-btn-ghost px-2 py-1 text-xs flex items-center gap-1"+ onClick={() => setShowHistory((v) => !v)}+ >+ <History size={11} />+ {S.mapping.history}+ </button>+ </div>+ )}++ {showHistory && <RevisionList kbId={kbId} mappingId={m.id} />}+ </div>+ );+}++function EditForm({+ kbId,+ mapping: m,+ onDone,+ onCancel,+}: {+ kbId: string;+ mapping: ConceptMapping;+ onDone: () => void;+ onCancel: () => void;+}) {+ const [table, setTable] = useState(m.table_name ?? "");+ const [expr, setExpr] = useState(m.expr ?? "");+ const [sql, setSql] = useState(m.sql ?? "");+ const [unit, setUnit] = useState(m.unit ?? "");+ const [summary, setSummary] = useState(m.summary ?? "");+ const [derived, setDerived] = useState(m.derived);++ const save = useMutation({+ mutationFn: () =>+ api.reviseMapping(kbId, m.id, {+ table_name: table,+ expr,+ sql,+ unit,+ summary,+ derived,+ }),+ onSuccess: onDone,+ onError: (e: unknown) => toast.error((e as Error).message),+ });++ const nothing = !table.trim() && !expr.trim() && !sql.trim();+ const field = (+ label: string,+ value: string,+ set: (v: string) => void,+ mono = false,+ ) => (+ <label className="block">+ <span className="text-[11px] text-neutral-500">{label}</span>+ <input+ className={cn(+ "u-input w-full px-2 py-1 text-xs mt-0.5",+ mono && "u-num",+ )}+ value={value}+ onChange={(e) => set(e.target.value)}+ />+ </label>+ );++ return (+ <div className="mt-3 space-y-2 border-t border-white/5 pt-3">+ <p className="text-[11px] text-neutral-500">{S.mapping.editTitle}</p>+ <div className="grid grid-cols-2 gap-2">+ {field(S.mapping.fieldTable, table, setTable, true)}+ {field(S.mapping.fieldUnit, unit, setUnit)}+ </div>+ {field(S.mapping.fieldExpr, expr, setExpr, true)}+ {field(S.mapping.fieldSql, sql, setSql, true)}+ {field(S.mapping.fieldSummary, summary, setSummary)}+ <label className="flex items-center gap-2 text-xs text-neutral-400">+ <input+ type="checkbox"+ checked={derived}+ onChange={(e) => setDerived(e.target.checked)}+ />+ {S.mapping.fieldDerived}+ </label>+ {nothing && (+ <p className="text-xs text-[var(--u-danger)]">{S.mapping.needOne}</p>+ )}+ <div className="flex gap-1.5">+ <button className="u-btn text-xs" onClick={onCancel}>+ {S.mapping.cancel}+ </button>+ <button+ className="u-btn u-btn-primary text-xs"+ disabled={nothing || save.isPending}+ onClick={() => save.mutate()}+ >+ {S.mapping.save}+ </button>+ </div>+ </div>+ );+}++/** 改版历史。**留痕表从建表起就没人读过**——0006 说留它是为了答得出+ * 「上季度这个数是怎么算的」,这里是那句话的兑现处。 */+function RevisionList({+ kbId,+ mappingId,+}: {+ kbId: string;+ mappingId: string;+}) {+ const revs = useQuery({+ queryKey: ["mappingRevisions", kbId, mappingId],+ queryFn: () => api.mappingRevisions(kbId, mappingId),+ });++ if (revs.isPending) return <Loading>{S.nav.loading}</Loading>;+ // **取失败要说取失败。** `?? []` 会把一次 500 画成「还没改过」——+ // 一条改过口径的记录被说成从没改过,比报错难查得多+ if (revs.isError)+ return (+ <div className="mt-3 border-t border-white/5 pt-3">+ <ErrorText>{(revs.error as Error).message}</ErrorText>+ </div>+ );+ const list = revs.data?.revisions ?? [];+ return (+ <div className="mt-3 border-t border-white/5 pt-3 space-y-2">+ <p className="text-[11px] text-neutral-500">{S.mapping.historyHint}</p>+ {list.length === 0 ? (+ <p className="text-xs text-neutral-600">{S.mapping.historyEmpty}</p>+ ) : (+ list.map((r) => {+ const b = r.before;+ const was = (b.sql ?? b.expr ?? b.table_name) as string | null;+ return (+ <div key={r.id} className="text-xs">+ <div className="text-neutral-500">+ {S.mapping.historyBy(+ r.changed_by_name ?? S.mapping.historyUnknown,+ )}+ <span className="u-num ml-2 text-neutral-600">+ {r.changed_at.slice(0, 16).replace("T", " ")}+ </span>+ </div>+ <div className="u-num text-neutral-400 break-all">+ {was ?? S.mapping.noDefinition}+ </div>+ </div>+ );+ })+ )}+ </div>+ );+}++/** 知识库层的数据源挂载。**从 KB 设置搬来的**——挂哪个库和口径怎么定,+ * 是同一件事的两半:不知道有哪些表,就判断不了口径对不对。+ * 注册新连接仍是部署级动作,管理员给直达入口,其他人指路找管理员。 */+function DataSources({+ kbId,+ onExplored,+}: {+ kbId: string;+ onExplored: () => void;+}) {+ const queryClient = useQueryClient();+ const navigate = useNavigate();+ const me = useQuery({ queryKey: ["me"], queryFn: api.me });+ const mounted = useQuery({+ queryKey: ["kbDataSources", kbId],+ queryFn: () => api.kbDataSources(kbId),+ });+ const available = useQuery({+ queryKey: ["kbDataSourcesAvail", kbId],+ queryFn: () => api.kbDataSourcesAvailable(kbId),+ });+ const [picked, setPicked] = useState("");+ const [notice, setNotice] = useState<string | null>(null);+ const invalidate = () =>+ queryClient.invalidateQueries({ queryKey: ["kbDataSources", kbId] });++ const mount = useMutation({+ mutationFn: (dsId: string) => api.mountDataSource(kbId, dsId),+ onSuccess: (r) => {+ setPicked("");+ setNotice(S.mapping.schemaSynced(r.schema_tables));+ invalidate();+ },+ onError: (e: unknown) => toast.error((e as Error).message),+ });+ const unmount = useMutation({+ mutationFn: (dsId: string) => api.unmountDataSource(kbId, dsId),+ onSettled: invalidate,+ });+ const sync = useMutation({+ mutationFn: (dsId: string) => api.syncDataSourceSchema(kbId, dsId),+ onSuccess: (r) => setNotice(S.mapping.schemaSynced(r.schema_tables)),+ onError: (e: unknown) => toast.error((e as Error).message),+ });+ const explore = useMutation({+ mutationFn: () => api.exploreMappings(kbId),+ onSuccess: () => {+ setNotice(S.mapping.exploreQueued);+ onExplored();+ },+ onError: (e: unknown) => toast.error((e as Error).message),+ });++ const mountedIds = new Set(+ (mounted.data?.data_sources ?? []).map((d) => d.id),+ );+ const mountable = (available.data?.data_sources ?? []).filter(+ (d) => !mountedIds.has(d.id),+ );+ const hasMounted = (mounted.data?.data_sources.length ?? 0) > 0;++ return (+ <div className="space-y-4">+ <p className="text-xs text-neutral-500">{S.mapping.sourcesHint}</p>++ <div className="glass rounded-xl divide-y divide-white/5">+ {(mounted.data?.data_sources ?? []).map((d) => (+ <div key={d.id} className="px-4 py-3 flex items-center gap-3">+ <div className="min-w-0 flex-1">+ <div className="text-sm text-neutral-200">{d.name}</div>+ <div className="text-xs text-neutral-500 u-num truncate">+ {d.summary}+ </div>+ </div>+ <button+ className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"+ disabled={sync.isPending}+ onClick={() => sync.mutate(d.id)}+ >+ {S.mapping.syncSchema}+ </button>+ <button+ className="text-xs text-neutral-500 hover:text-[var(--u-danger)] shrink-0"+ disabled={unmount.isPending}+ onClick={() => unmount.mutate(d.id)}+ >+ {S.mapping.unmount}+ </button>+ </div>+ ))}+ {!hasMounted && (+ <p className="px-4 py-6 text-sm text-neutral-500">+ {S.mapping.sourcesEmpty}+ </p>+ )}+ </div>++ {mountable.length > 0 && (+ <div className="flex items-center gap-2">+ <SearchSelect+ className="flex-1"+ value={picked}+ options={mountable.map((d) => ({+ value: d.id,+ label: d.name,+ hint: d.summary,+ }))}+ onChange={setPicked}+ placeholder={S.mapping.mount + "…"}+ />+ <button+ className="u-btn u-btn-primary px-3.5 py-1.5 text-xs shrink-0"+ disabled={!picked || mount.isPending}+ onClick={() => mount.mutate(picked)}+ >+ {S.mapping.mount}+ </button>+ </div>+ )}++ {me.data?.is_admin ? (+ <button+ className="flex items-center gap-1.5 text-xs text-neutral-500 hover:text-neutral-300 transition-colors"+ onClick={() =>+ navigate({ to: "/admin", search: { tab: "datasources" } })+ }+ >+ <Plus size={12} />+ {S.mapping.newConn}+ </button>+ ) : (+ mountable.length === 0 &&+ available.data &&+ !hasMounted && (+ <p className="text-xs text-neutral-600">+ {S.mapping.sourcesNoneAvailable}+ </p>+ )+ )}++ {hasMounted && (+ <div className="glass rounded-xl px-4 py-3 flex items-center gap-3">+ <p className="text-xs text-neutral-500 flex-1">+ {S.mapping.exploreHint}+ </p>+ <button+ className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"+ disabled={explore.isPending}+ onClick={() => explore.mutate()}+ >+ {S.mapping.explore}+ </button>+ </div>+ )}+ {notice && <p className="text-xs text-[var(--u-ok)]">{notice}</p>}+ </div>+ );+}diff --git a/web/src/pages/Review.tsx b/web/src/pages/Review.tsxindex 15907e4d..689e0276 100644--- a/web/src/pages/Review.tsx+++ b/web/src/pages/Review.tsx@@ -1,11 +1,12 @@import { useEffect, useState } from "react";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useNavigate } from "@tanstack/react-router";+import { ArrowUpRight } from "lucide-react";import {api,type AxiomViolation,type ReviewQueue,type OntologyDefect,- type ConceptMapping,type ConflictItem,type FactReviewItem,type MergeLog,@@ -55,7 +56,8 @@ function SideCard({ side }: { side: ReviewSide }) {)}</div><div className="text-xs text-neutral-500 mb-2">- {side.type_label ?? S.graph.untyped} · {S.review.factsCount(side.degree)}+ {side.type_label ?? S.graph.untyped} ·{" "}+ {S.review.factsCount(side.degree)}</div>{side.top_facts.length > 0 ? (<ul className="space-y-1">@@ -145,7 +147,13 @@ function FactRow({</span><span className="text-xs text-neutral-500">—{" "}- <span className={fact.predicate_label === null ? "italic text-neutral-600" : undefined}>+ <span+ className={+ fact.predicate_label === null+ ? "italic text-neutral-600"+ : undefined+ }+ >{fact.predicate_label ?? S.graph.unknownPredicate}</span>{" "}→@@ -299,7 +307,13 @@ function UnconfirmedRow({</span><span className="text-xs text-neutral-500">—{" "}- <span className={fact.predicate_label === null ? "italic text-neutral-600" : undefined}>+ <span+ className={+ fact.predicate_label === null+ ? "italic text-neutral-600"+ : undefined+ }+ >{fact.predicate_label ?? S.graph.unknownPredicate}</span>{" "}→@@ -441,8 +455,7 @@ function DecisionRow({ e }: { e: ReviewHistoryEvent }) {);}--/** 一条待表态的语义层映射(0011)。+/** 一条待表态的数据映射口径(0011)。** 展示的重点是**「这个数怎么算」**——SQL / 表达式 / 表名按这个优先级取一个,* 因为人要判断的正是它对不对。概念名与源是身份,unit 是答里必须带的量纲。 */@@ -578,53 +591,6 @@ function ViolationRow({);}-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 =@@ -632,9 +598,6 @@ type Sel =| "conflicts"| "unconfirmed"| "lowconf"- // 语义层的待表态映射(0011)。从前它借「低置信事实」那一档露面——- // 靠 0.6 的置信度混进去,而它根本不是一条关于世界的断言- | "mappings"// 公理违规(0002 R0)。**与 conflicts 分开**:那一档问「哪条对」,// 这一档还可能答「公理写错了」——出路不同| "violations"@@ -649,7 +612,6 @@ const QUEUE_FETCHED: ReviewQueue[] = ["conflicts","unconfirmed","lowconf",- "mappings","violations","defects","merges",@@ -660,7 +622,6 @@ const QUEUE_ORDER: Sel[] = ["conflicts","unconfirmed","lowconf",- "mappings","violations","defects",];@@ -669,7 +630,6 @@ const PAGE_SIZE: Record<Sel, number> = {conflicts: CONFLICT_PAGE,unconfirmed: FACT_PAGE,lowconf: FACT_PAGE,- mappings: FACT_PAGE,violations: FACT_PAGE,defects: FACT_PAGE,merges: MERGE_PAGE,@@ -689,11 +649,14 @@ function RailItem({label,count,onClick,+ external,}: {active: boolean;label: string;count: number | null;onClick: () => void;+ /** 这一档不在本页办——加个去向记号,免得点下去以为页面没反应 */+ external?: boolean;}) {return (<button@@ -706,6 +669,7 @@ function RailItem({)}><span className="truncate">{label}</span>+ {external && <ArrowUpRight size={11} className="shrink-0 opacity-50" />}{count !== null && (<spanclassName={cn(@@ -723,6 +687,7 @@ function RailItem({export function Review() {const { kb } = useKb();const queryClient = useQueryClient();+ const navigate = useNavigate();const [sel, setSel] = useState<Sel | null>(null);const [page, setPage] = useState(0);@@ -738,7 +703,13 @@ export function Review() {: "duplicates";const review = useQuery({queryKey: ["review", kb?.id, queueSel, page],- queryFn: () => api.review(kb!.id, queueSel, PAGE_SIZE[queueSel], page * PAGE_SIZE[queueSel]),+ queryFn: () =>+ api.review(+ kb!.id,+ queueSel,+ PAGE_SIZE[queueSel as Sel],+ page * PAGE_SIZE[queueSel as Sel],+ ),enabled: !!kb,// 翻页时别把上一页闪成空白——计数与骨架都还在,只有条目在换placeholderData: (prev) => prev,@@ -774,16 +745,6 @@ 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 defectAction = useMutation({mutationFn: ({id,@@ -836,7 +797,9 @@ export function Review() {// **徽标读服务端的 COUNT,不读列表长度。** 这是从前那个「库里 164、界面写// 100」的根源:数组长度反映的是一页多少条,不是库里有多少条。const c = review.data?.counts;- const counts: Record<Sel, number> = {+ // mappings 不是本页的一档(审批在「数据映射」页),但计数照收:+ // 收件箱该说「有几条等你」+ const counts: Record<Sel | "mappings", number> = {duplicates: c?.duplicates ?? 0,conflicts: c?.conflicts ?? 0,unconfirmed: c?.unconfirmed ?? 0,@@ -853,7 +816,6 @@ export function Review() {const asDuplicates = () => rows as ReviewItem[];const asFacts = () => rows as FactReviewItem[];const asConflicts = () => rows as ConflictItem[];- const asMappings = () => rows as ConceptMapping[];const asViolations = () => rows as AxiomViolation[];const asDefects = () => rows as OntologyDefect[];const asMerges = () => rows as MergeLog[];@@ -885,7 +847,6 @@ export function Review() {title: S.review.lowConfidence,hint: S.review.lowConfidenceHint,},- mappings: { title: S.review.mappings, hint: S.review.mappingsHint },violations: {title: S.review.violations,hint: S.review.violationsHint,@@ -925,11 +886,15 @@ export function Review() {count={counts.lowconf}onClick={() => select("lowconf")}/>+ {/* 口径审批搬去了「数据映射」页:判断一条口径对不对要看得见表结构,+ 而那在那一页。**计数留在这里**——收件箱该说「有几条等你」,+ 但活要在有上下文的地方干 */}<RailItem- active={active === "mappings"}+ active={false}label={S.review.railMappings}count={counts.mappings}- onClick={() => select("mappings")}+ onClick={() => navigate({ to: "/mappings" })}+ external/><RailItemactive={active === "violations"}@@ -989,10 +954,10 @@ export function Review() {active !== "violations" &&active !== "defects" &&counts[active] === 0 && (- <div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">- {queueEmpty ? S.review.empty : S.review.categoryEmpty}- </div>- )}+ <div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">+ {queueEmpty ? S.review.empty : S.review.categoryEmpty}+ </div>+ )}{active === "duplicates" && counts.duplicates > 0 && (<div className="space-y-3">@@ -1013,46 +978,42 @@ export function Review() {{active === "conflicts" && counts.conflicts > 0 && (<div className="space-y-3">- {asConflicts().map(- (c) => (- <ConflictRow- key={c.id}- conflict={c}- busy={- conflictAction.isPending &&- conflictAction.variables?.id === c.id- }- onResolve={(action, closeAt) =>- conflictAction.mutate({ id: c.id, action, closeAt })- }- />- ),- )}+ {asConflicts().map((c) => (+ <ConflictRow+ key={c.id}+ conflict={c}+ busy={+ conflictAction.isPending &&+ conflictAction.variables?.id === c.id+ }+ onResolve={(action, closeAt) =>+ conflictAction.mutate({ id: c.id, action, closeAt })+ }+ />+ ))}</div>)}{active === "unconfirmed" && counts.unconfirmed > 0 && (<div className="space-y-3">- {asFacts().map(- (fact) => (- <UnconfirmedRow- key={fact.id}- fact={fact}- busy={- (factAction.isPending &&- factAction.variables?.id === fact.id) ||- (closeFactAction.isPending &&- closeFactAction.variables?.id === fact.id)- }- onReject={() =>- factAction.mutate({ id: fact.id, action: "reject" })- }- onClose={(validTo) =>- closeFactAction.mutate({ id: fact.id, validTo })- }- />- ),- )}+ {asFacts().map((fact) => (+ <UnconfirmedRow+ key={fact.id}+ fact={fact}+ busy={+ (factAction.isPending &&+ factAction.variables?.id === fact.id) ||+ (closeFactAction.isPending &&+ closeFactAction.variables?.id === fact.id)+ }+ onReject={() =>+ factAction.mutate({ id: fact.id, action: "reject" })+ }+ onClose={(validTo) =>+ closeFactAction.mutate({ id: fact.id, validTo })+ }+ />+ ))}</div>)}@@ -1077,26 +1038,6 @@ export function Review() {</div>)}- {active === "mappings" && counts.mappings > 0 && (- <div className="space-y-3">- {asMappings().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 === "defects" && (<div className="space-y-3">{counts.defects === 0 && (@@ -1104,21 +1045,19 @@ export function Review() {{S.review.categoryEmpty}</div>)}- {asDefects().map(- (d) => (- <DefectRow- key={d.id}- defect={d}- busy={- defectAction.isPending &&- defectAction.variables?.id === d.id- }- onDecide={(resolution) =>- defectAction.mutate({ id: d.id, resolution })- }- />- ),- )}+ {asDefects().map((d) => (+ <DefectRow+ key={d.id}+ defect={d}+ busy={+ defectAction.isPending &&+ defectAction.variables?.id === d.id+ }+ onDecide={(resolution) =>+ defectAction.mutate({ id: d.id, resolution })+ }+ />+ ))}</div>)}@@ -1156,21 +1095,19 @@ export function Review() {{S.review.checkNeverRun}</div>)}- {asViolations().map(- (v) => (- <ViolationRow- key={v.id}- violation={v}- busy={- violationAction.isPending &&- violationAction.variables?.id === v.id- }- onDecide={(resolution) =>- violationAction.mutate({ id: v.id, resolution })- }- />- ),- )}+ {asViolations().map((v) => (+ <ViolationRow+ key={v.id}+ violation={v}+ busy={+ violationAction.isPending &&+ violationAction.variables?.id === v.id+ }+ onDecide={(resolution) =>+ violationAction.mutate({ id: v.id, resolution })+ }+ />+ ))}</div>)}diff --git a/web/src/pages/Shell.tsx b/web/src/pages/Shell.tsxindex 6020c409..06c2d06d 100644--- a/web/src/pages/Shell.tsx+++ b/web/src/pages/Shell.tsx@@ -1,8 +1,14 @@import { useEffect } from "react";import { useQuery } from "@tanstack/react-query";-import { Link, Outlet, useNavigate, useRouterState } from "@tanstack/react-router";+import {+ Link,+ Outlet,+ useNavigate,+ useRouterState,+} from "@tanstack/react-router";import {BookMarked,+ Database,Library as LibraryIcon,ListChecks,MessagesSquare,@@ -30,6 +36,8 @@ const TABS = [{ to: "/library", label: S.nav.library, Icon: LibraryIcon },{ to: "/review", label: S.review.title, Icon: ListChecks },{ to: "/ontology", label: S.ontology.title, Icon: Shapes },+ // 本体说「世界上有什么」,数据映射说「这个数在库里怎么算」——挨着放+ { to: "/mappings", label: S.mapping.title, Icon: Database },// 库设置与其它 tab 同为"当前知识库作用域",并列于内容导航{ to: "/kb-settings", label: S.nav.settings, Icon: SettingsIcon },] as const;@@ -38,7 +46,11 @@ export function Shell() {const navigate = useNavigate();const me = useQuery({ queryKey: ["me"], queryFn: api.me });- const health = useQuery({ queryKey: ["health"], queryFn: api.health, staleTime: Infinity });+ const health = useQuery({+ queryKey: ["health"],+ queryFn: api.health,+ staleTime: Infinity,+ });const { kb, kbs, setKb } = useKb();// 标题跟随当前 tab:`Graph · Utopia`;文档查看页归入 Libraryconst pathname = useRouterState({ select: (s) => s.location.pathname });@@ -122,7 +134,9 @@ export function Shell() {><GithubMark size={13} />{health.data && (- <span className="u-num text-[11px]">v{health.data.version}</span>+ <span className="u-num text-[11px]">+ v{health.data.version}+ </span>)}</a></div>@@ -158,4 +172,3 @@ export function Shell() {</div>);}-diff --git a/web/src/router.tsx b/web/src/router.tsxindex ce700380..b595a233 100644--- a/web/src/router.tsx+++ b/web/src/router.tsx@@ -17,6 +17,7 @@ import { KbSettings } from "./pages/KbSettings";import { MyKbs } from "./pages/MyKbs";import { NotFound } from "./pages/ServerDown";import { Ontology } from "./pages/Ontology";+import { Mappings } from "./pages/Mappings";import { Review } from "./pages/Review";import { Search } from "./pages/Search";import { Settings } from "./pages/Settings";@@ -111,6 +112,12 @@ const ontologyRoute = createRoute({component: Ontology,});+const mappingsRoute = createRoute({+ getParentRoute: () => appRoute,+ path: "/mappings",+ component: Mappings,+});+const reviewRoute = createRoute({getParentRoute: () => appRoute,path: "/review",@@ -205,6 +212,7 @@ const routeTree = rootRoute.addChildren([libraryRoute,reviewRoute,ontologyRoute,+ mappingsRoute,kbSettingsRoute,]),]);