diff --git a/crates/utopia-cli/src/main.rs b/crates/utopia-cli/src/main.rs index 913dcf3e0..617df6e55 100644 --- a/crates/utopia-cli/src/main.rs +++ b/crates/utopia-cli/src/main.rs @@ -82,7 +82,7 @@ struct ManifestDataDir { /// not a side effect of a code change. // 是迁移文件的**个数**,不是最大的编号(守卫 `schema_version_policy_compares_against_current` // 按个数比):编号有空缺时两者不同——0071 由一个开放 PR 占着,0072 先落,个数是 71 -const CURRENT_SCHEMA_VERSION: u32 = 110; +const CURRENT_SCHEMA_VERSION: u32 = 111; #[tokio::main] async fn main() -> anyhow::Result<()> { diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs index a5036d33d..8f5ea3a1b 100644 --- a/crates/utopia-core/src/models.rs +++ b/crates/utopia-core/src/models.rs @@ -1196,6 +1196,9 @@ pub struct KnowledgeBase { /// 治理开关(0025,**缺省开**,见 0050):开着,govern 任务按先进先出过等人的 /// 重复对,先读台账里人的先例再裁;关掉,任务在两簇之间看到就停 pub governance: bool, + /// 探索提的口径够不够格自动生效(0011,#504,缺省关)。它只管往后的写入: + /// 关掉不撤销已生效的,要撤一条用撤回 + pub auto_confirm_mappings: bool, /// 这次打开治理的时刻;保险丝只数它之后的撤回(0025 决定 9)。 /// 新库生下来就开着治理,这一格于是等于建库的时刻(0050) pub governance_since: Option>, @@ -1264,7 +1267,7 @@ pub struct MappingRevision { pub id: Uuid, pub before: serde_json::Value, /// 改的人。**裸外键 + 用户软删除**,所以归因不会因为人离职而丢; - /// 真被硬删过才会是 NULL + /// 真被硬删过,或这一版是自动确认换掉的(#504),才会是 NULL pub changed_by_name: Option, pub changed_at: DateTime, } @@ -1327,6 +1330,16 @@ pub struct ConceptMapping { /// 人从零写的口径记写的人;探索提的为空(#562)。`decided_by` 分不出这件事—— /// 探索提的经人确认之后同样有 decided_by pub written_by: Option, + /// 表态或改过这一条的人。为空不等于机器确认:评测脚本直接写的真值同样为空, + /// 机器确认看 `auto_confirmed_at` + pub decided_by: Option, + /// 模型对当前这版定义的置信度(0–1);人一改就清空,它说的是上一版 + pub confidence: Option, + /// 模型给当前这版定义的理由,随 `confidence` 一起清空 + pub rationale: Option, + /// 机器确认这一版的时刻;人表态、修改或撤回后清空。只有这一格非空的才能被探索 + /// 刷新、被撤回(#504) + pub auto_confirmed_at: Option>, } /// 一处公理违规,配好展示所需的三元组文本(见 `axiom_violations`)。 diff --git a/crates/utopia-server/src/api/kbs.rs b/crates/utopia-server/src/api/kbs.rs index ab1dccdd4..6bc940476 100644 --- a/crates/utopia-server/src/api/kbs.rs +++ b/crates/utopia-server/src/api/kbs.rs @@ -55,6 +55,10 @@ pub struct UpdateKbReq { /// 打开那一刻就排一轮,关掉后任务在两簇之间看到就停。见 docs/decisions/0025 #[serde(default)] pub governance: Option, + /// 口径自动确认开关(缺省关):Editor 就能改,因为确认一条口径本来就是 Editor 的权限。 + /// 见 docs/decisions/0011 的 #504 修订 + #[serde(default)] + pub auto_confirm_mappings: Option, /// 人写的数据约定(「测试单不算数」这类 schema 里没有的规则),问数与探索的 /// 提示词都读它。探索生成的描述在另一个字段,PATCH 不了。见 #570 #[serde(default)] @@ -129,6 +133,7 @@ pub async fn create( None, None, None, + None, ) .await?; } @@ -210,7 +215,44 @@ pub async fn update( Path(id): Path, Json(req): Json, ) -> ApiResult> { - kb_with_role(&state, &user, id, Role::Admin).await?; + // 只改口径开关的请求 Editor 就够,夹带别的字段照旧要 Admin。**这里故意解构、不写 `..`**: + // 往 `UpdateKbReq` 加字段时这里编译不过,加字段的人得想清楚它归谁改; + // 从前是一串 `is_none()`,漏列一个,新字段就成了 Editor 能改的 + let UpdateKbReq { + name, + description, + visibility, + auto_extend_ontology, + ontology_lang, + materialize_inferences, + inference_interval_minutes, + auto_type_resolution, + governance, + auto_confirm_mappings, + data_conventions, + } = &req; + let setting_only = auto_confirm_mappings.is_some() + && name.is_none() + && description.is_none() + && visibility.is_none() + && auto_extend_ontology.is_none() + && ontology_lang.is_none() + && materialize_inferences.is_none() + && inference_interval_minutes.is_none() + && auto_type_resolution.is_none() + && governance.is_none() + && data_conventions.is_none(); + kb_with_role( + &state, + &user, + id, + if setting_only { + Role::Editor + } else { + Role::Admin + }, + ) + .await?; let kb = utopia_store::kbs::update( &state.pool, id, @@ -224,6 +266,7 @@ pub async fn update( req.auto_type_resolution, req.governance, req.data_conventions.as_deref().map(str::trim), + req.auto_confirm_mappings, ) .await?; // 打开开关就自动开始处理:排一轮,同库已排着的不重复 @@ -244,6 +287,7 @@ pub async fn update( "name": req.name, "visibility": req.visibility, "governance": req.governance, + "auto_confirm_mappings": req.auto_confirm_mappings, "data_conventions": req.data_conventions.is_some(), }), ) @@ -496,3 +540,303 @@ pub async fn list_packs(AuthUser(_): AuthUser) -> ApiResult anyhow::Result> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(None); + }; + let pool = sqlx::PgPool::connect(&url).await?; + utopia_store::db::migrate(&pool).await?; + let [org, ws, kb, other, admin, editor, viewer] = + std::array::from_fn(|_| Uuid::now_v7()); + sqlx::raw_sql(&format!( + "INSERT INTO organizations(id,name) VALUES ('{org}','auto-mapping-route'); + INSERT INTO workspaces(id,org_id,name) VALUES ('{ws}','{org}','auto-mapping-route'); + INSERT INTO knowledge_bases(id,workspace_id,name,visibility) VALUES + ('{kb}','{ws}','mappings','restricted'), ('{other}','{ws}','other','restricted'); + INSERT INTO users(id,org_id,email,display_name,password_hash) VALUES + ('{admin}','{org}','{admin}@map.test','Admin','unused'), + ('{editor}','{org}','{editor}@map.test','Editor','unused'), + ('{viewer}','{org}','{viewer}@map.test','Viewer','unused'); + INSERT INTO kb_members(kb_id,user_id,role) VALUES + ('{kb}','{admin}','admin'), ('{kb}','{editor}','editor'), ('{kb}','{viewer}','viewer');" + )) + .execute(&pool) + .await?; + let dir = tempfile::tempdir()?; + let cfg = utopia_core::config::AppConfig { + data_dir: dir.path().to_string_lossy().into_owned(), + ..Default::default() + }; + let state = crate::state::AppState::new( + pool.clone(), + &cfg, + Arc::new(utopia_search::SearchIndex::open( + &dir.path().join("search"), + )?), + "test-only".into(), + ); + Ok(Some(Self { + pool, + state, + cfg, + _dir: dir, + kb, + other, + admin, + editor, + viewer, + })) + } + + async fn send( + &self, + user: Uuid, + method: &str, + path: String, + body: Value, + ) -> anyhow::Result<(StatusCode, Value)> { + let token = crate::auth::issue_token(&self.state, user)?; + let response = crate::api::router(self.state.clone(), &self.cfg) + .oneshot( + Request::builder() + .method(method) + .uri(path) + .header("authorization", format!("Bearer {token}")) + .header("content-type", "application/json") + .body(Body::from(body.to_string()))?, + ) + .await?; + let status = response.status(); + let bytes = to_bytes(response.into_body(), 1024 * 1024).await?; + Ok(( + status, + serde_json::from_slice(&bytes).unwrap_or(Value::Null), + )) + } + + async fn patch( + &self, + user: Uuid, + base: Uuid, + body: Value, + ) -> anyhow::Result<(StatusCode, Value)> { + self.send(user, "PATCH", format!("/api/v1/kbs/{base}"), body) + .await + } + + async fn switch_is_on(&self) -> anyhow::Result { + Ok(utopia_store::kbs::get(&self.pool, self.kb) + .await? + .auto_confirm_mappings) + } + + /// 库里放一条机器确认的口径,返回它的 id。 + async fn automatic_mapping(&self) -> anyhow::Result { + let entity = Uuid::now_v7(); + sqlx::query( + "INSERT INTO entities (id, kb_id, canonical_name) VALUES ($1, $2, 'Revenue')", + ) + .bind(entity) + .bind(self.kb) + .execute(&self.pool) + .await?; + sqlx::query("UPDATE knowledge_bases SET auto_confirm_mappings = true WHERE id = $1") + .bind(self.kb) + .execute(&self.pool) + .await?; + let (id, written) = utopia_store::mappings::propose_with_evidence( + &self.pool, + self.kb, + entity, + "warehouse", + None, + Some("SUM(amount)"), + None, + None, + None, + false, + Some(0.9), + Some("The schema states revenue"), + ) + .await?; + assert!(written); + Ok(id) + } + + async fn cleanup(self) -> anyhow::Result<()> { + sqlx::query("DELETE FROM knowledge_bases WHERE id = ANY($1)") + .bind(&[self.kb, self.other][..]) + .execute(&self.pool) + .await?; + Ok(()) + } + } + + #[tokio::test] + async fn an_editor_can_turn_the_switch_on_and_off() -> anyhow::Result<()> { + let Some(f) = Fixture::new().await? else { + return Ok(()); + }; + assert!(!f.switch_is_on().await?); + let (status, body) = f + .patch(f.editor, f.kb, json!({"auto_confirm_mappings": true})) + .await?; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["auto_confirm_mappings"], true); + let (status, body) = f + .patch(f.editor, f.kb, json!({"auto_confirm_mappings": false})) + .await?; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["auto_confirm_mappings"], false); + f.cleanup().await + } + + #[tokio::test] + async fn each_change_of_the_switch_is_audited_with_its_actor() -> anyhow::Result<()> { + let Some(f) = Fixture::new().await? else { + return Ok(()); + }; + f.patch(f.editor, f.kb, json!({"auto_confirm_mappings": true})) + .await?; + f.patch(f.editor, f.kb, json!({"auto_confirm_mappings": false})) + .await?; + let events: Vec = sqlx::query_scalar( + "SELECT detail FROM audit_events + WHERE kb_id = $1 AND actor_id = $2 AND action = 'kb.updated' ORDER BY created_at", + ) + .bind(f.kb) + .bind(f.editor) + .fetch_all(&f.pool) + .await?; + assert_eq!(events.len(), 2); + assert_eq!(events[0]["auto_confirm_mappings"], true); + assert_eq!(events[1]["auto_confirm_mappings"], false); + f.cleanup().await + } + + #[tokio::test] + async fn a_viewer_cannot_change_the_switch() -> anyhow::Result<()> { + let Some(f) = Fixture::new().await? else { + return Ok(()); + }; + let (status, _) = f + .patch(f.viewer, f.kb, json!({"auto_confirm_mappings": true})) + .await?; + assert_eq!(status, StatusCode::FORBIDDEN); + assert!(!f.switch_is_on().await?); + f.cleanup().await + } + + #[tokio::test] + async fn an_editor_of_another_base_does_not_see_this_one() -> anyhow::Result<()> { + let Some(f) = Fixture::new().await? else { + return Ok(()); + }; + let (status, _) = f + .patch(f.editor, f.other, json!({"auto_confirm_mappings": true})) + .await?; + assert_eq!(status, StatusCode::NOT_FOUND); + f.cleanup().await + } + + #[tokio::test] + async fn a_request_that_changes_anything_else_still_needs_an_admin() -> anyhow::Result<()> { + let Some(f) = Fixture::new().await? else { + return Ok(()); + }; + let (status, _) = f + .patch( + f.editor, + f.kb, + json!({"auto_confirm_mappings": true, "name": "Changed"}), + ) + .await?; + assert_eq!(status, StatusCode::FORBIDDEN); + assert!(!f.switch_is_on().await?); + f.cleanup().await + } + + #[tokio::test] + async fn a_request_without_the_switch_leaves_it_as_it_is() -> anyhow::Result<()> { + let Some(f) = Fixture::new().await? else { + return Ok(()); + }; + f.patch(f.admin, f.kb, json!({"auto_confirm_mappings": true})) + .await?; + let (status, _) = f + .patch(f.admin, f.kb, json!({"description": "Changed"})) + .await?; + assert_eq!(status, StatusCode::OK); + assert!(f.switch_is_on().await?); + f.cleanup().await + } + + #[tokio::test] + async fn an_editor_can_revert_an_automatic_confirmation() -> anyhow::Result<()> { + let Some(f) = Fixture::new().await? else { + return Ok(()); + }; + let id = f.automatic_mapping().await?; + let (status, _) = f + .send( + f.editor, + "POST", + format!("/api/v1/kbs/{}/mappings/{id}/revert", f.kb), + json!({}), + ) + .await?; + assert_eq!(status, StatusCode::OK); + assert!(utopia_store::mappings::confirmed(&f.pool, f.kb, 10) + .await? + .is_empty()); + f.cleanup().await + } + + #[tokio::test] + async fn a_viewer_cannot_revert_an_automatic_confirmation() -> anyhow::Result<()> { + let Some(f) = Fixture::new().await? else { + return Ok(()); + }; + let id = f.automatic_mapping().await?; + let (status, _) = f + .send( + f.viewer, + "POST", + format!("/api/v1/kbs/{}/mappings/{id}/revert", f.kb), + json!({}), + ) + .await?; + assert_eq!(status, StatusCode::FORBIDDEN); + assert_eq!( + utopia_store::mappings::confirmed(&f.pool, f.kb, 10) + .await? + .len(), + 1 + ); + f.cleanup().await + } +} diff --git a/crates/utopia-server/src/api/mapping_routes.rs b/crates/utopia-server/src/api/mapping_routes.rs index 8b8757ad5..2c8de08a6 100644 --- a/crates/utopia-server/src/api/mapping_routes.rs +++ b/crates/utopia-server/src/api/mapping_routes.rs @@ -142,6 +142,19 @@ pub async fn revise( Ok(Json(json!({ "ok": true }))) } +/// 撤回一条自动确认(0011 的 #504 修订)。审计与撤回同一个事务,在 store 里写。 +pub async fn revert( + State(state): State, + AuthUser(user): AuthUser, + Path((kb_id, mapping_id)): Path<(Uuid, Uuid)>, +) -> ApiResult> { + require_kb(&state, &user, kb_id, Role::Editor).await?; + utopia_store::mappings::revert_automatic(&state.pool, kb_id, mapping_id, user.id).await?; + // 它回到了待看,审阅页的计数跟着变 + state.emit_review(kb_id); + Ok(Json(json!({ "ok": true }))) +} + /// 一条口径的改版历史。0006 说留痕是为了答得出「上季度这个数是怎么算的」, /// 这是那句话的兑现处。 pub async fn revisions( diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs index 2b01f5426..d5dbf4ed4 100644 --- a/crates/utopia-server/src/api/mod.rs +++ b/crates/utopia-server/src/api/mod.rs @@ -256,6 +256,10 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router { "/kbs/{id}/mappings/{mapping_id}", axum::routing::patch(mapping_routes::revise), ) + .route( + "/kbs/{id}/mappings/{mapping_id}/revert", + post(mapping_routes::revert), + ) .route( "/kbs/{id}/mappings/{mapping_id}/revisions", get(mapping_routes::revisions), diff --git a/crates/utopia-server/src/mappings.rs b/crates/utopia-server/src/mappings.rs index c10c5814e..e9c816d89 100644 --- a/crates/utopia-server/src/mappings.rs +++ b/crates/utopia-server/src/mappings.rs @@ -1,13 +1,13 @@ //! 问数语义映射的 Agentic 探索:读挂载源的 schema + KB 既有概念,让 LLM 提议 //! "业务概念(Metric/Dimension 实体)→ 数据资产定义" 的映射。 //! -//! 提议写进 `concept_mappings`(status = proposed)→ Review 页自成一档, -//! Confirm / Reject 之后 status 变 confirmed,问数只读确认过的那些。 +//! 提议写进 `concept_mappings`,数据映射页确认或拒绝;问数只读已确认的定义。 +//! 库可选择自动确认有置信度与理由支撑的定义(0011,#504,默认关)。 //! //! **从前它是一条 0.6 置信的 `mapped_to` 事实**,借「低置信事实」那一档露面。 //! 搬出来的理由见 0011:它不是关于世界的断言,是配置——而「确认」这个动作 //! 当时是 `UPDATE facts SET confidence = 1.0`,原地改一张不许原地改的表。 -//! agent 只提议,口径生效权在人——与消解"宁分勿合"同一哲学。 +//! 人的决定与修改不会被后续探索覆盖;自动确认保留模型的理由与审计。 use crate::llm_util; use crate::state::AppState; @@ -311,9 +311,11 @@ async fn explore(state: &AppState, kb_id: Uuid, run: Uuid) -> anyhow::Result<()> \"definition\": {{\"table\": \"schema.table\", \"expr\": \"SQL expression\", \ \"sql\": \"full SELECT if joins are needed (optional)\", \"unit\": \"optional\"}}, \ \"summary\": \"one line: source + expression, shown to reviewers\", \ - \"rationale\": \"why this mapping, citing column comments\"}}\n\ + \"confidence\": 0.0, \"rationale\": \"why this mapping, citing column comments\"}}\n\ Metrics are aggregatable quantities (use sum/count/avg in expr); dimensions are \ - group-by columns. Propose at most {cap}, only well-grounded ones.", + group-by columns. Confidence is a number from 0 to 1 measuring whether the exact \ + definition follows the schema and stated conventions; reduce it when business meaning \ + is uncertain. Propose at most {cap}, only well-grounded ones.", if existing_names.is_empty() { "(none)".into() } else { @@ -428,7 +430,7 @@ async fn explore(state: &AppState, kb_id: Uuid, run: Uuid) -> anyhow::Result<()> if let Some(t) = s("table") { covered.insert(t); } - let (_, written) = utopia_store::mappings::propose( + let (_, written) = utopia_store::mappings::propose_with_evidence( &state.pool, kb_id, resolved.entity_id, @@ -440,6 +442,8 @@ async fn explore(state: &AppState, kb_id: Uuid, run: Uuid) -> anyhow::Result<()> // summary 是给人看的那句:Review 列表与问数 prompt 都靠它 p["summary"].as_str().or(def["summary"].as_str()), def["derived"].as_bool().unwrap_or(false), + p["confidence"].as_f64(), + p["rationale"].as_str(), ) .await?; if written { @@ -619,4 +623,120 @@ mod tests { // **0 条上限会把「连不上」变成「模型什么都没提」**,两件事又混在一起了 assert_eq!(proposal_cap(0), 12); } + #[tokio::test] + async fn exploration_keeps_the_models_evidence_and_confirms_only_after_opt_in( + ) -> anyhow::Result<()> { + use serde_json::json; + use std::sync::Arc; + use uuid::Uuid; + use wiremock::{ + matchers::{body_string_contains, method, path}, + Mock, MockServer, ResponseTemplate, + }; + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = sqlx::PgPool::connect(&url).await?; + utopia_store::db::migrate(&pool).await?; + let [org, ws, kb, user] = std::array::from_fn(|_| Uuid::now_v7()); + sqlx::raw_sql(&format!( + "INSERT INTO organizations(id,name) VALUES ('{org}','mapping-exploration'); + INSERT INTO workspaces(id,org_id,name) VALUES ('{ws}','{org}','mapping-exploration'); + INSERT INTO knowledge_bases(id,workspace_id,name) VALUES ('{kb}','{ws}','mapping-exploration'); + INSERT INTO users(id,org_id,email,display_name,password_hash) + VALUES ('{user}','{org}','{user}@mapping.test','Editor','unused');" + )).execute(&pool).await?; + let model = MockServer::start().await; + let proposals = json!([{"name":"Source rows", "kind":"metric", "source":"test", + "definition":{"table":"public.entities", "expr":"COUNT(*)"}, + "confidence":0.8, "rationale":"Count each entity row"}]) + .to_string(); + Mock::given(method("POST")) + .and(path("/chat/completions")) + .and(body_string_contains("ONLY a JSON array")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "choices":[{"message":{"role":"assistant","content":proposals}}] + }))) + .mount(&model) + .await; + Mock::given(method("POST")) + .and(path("/chat/completions")) + .and(body_string_contains("ONLY a JSON object")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "choices":[{"message":{"role":"assistant","content":"{}"}}] + }))) + .mount(&model) + .await; + let source = utopia_store::datasources::create( + &pool, + &format!("mapping-{}", kb.simple()), + "postgres", + &url, + user, + ) + .await?; + let result = async { + sqlx::query("INSERT INTO kb_data_sources(kb_id,data_source_id) VALUES ($1,$2)") + .bind(kb) + .bind(source) + .execute(&pool) + .await?; + utopia_store::settings::upsert( + &pool, + ws, + Some(&model.uri()), + None, + Some("scripted"), + None, + None, + None, + None, + ) + .await?; + let dir = tempfile::tempdir()?; + let cfg = utopia_core::config::AppConfig { + data_dir: dir.path().to_string_lossy().into_owned(), + ..Default::default() + }; + let state = crate::state::AppState::new( + pool.clone(), + &cfg, + Arc::new(utopia_search::SearchIndex::open( + &dir.path().join("search"), + )?), + "test-only".into(), + ); + super::explore_mappings(&state, kb).await?; + let pending = utopia_store::mappings::proposed(&pool, kb, 10, 0) + .await? + .remove(0); + assert_eq!(pending.confidence, Some(0.8)); + assert_eq!(pending.rationale.as_deref(), Some("Count each entity row")); + sqlx::query("UPDATE knowledge_bases SET auto_confirm_mappings = true WHERE id = $1") + .bind(kb) + .execute(&pool) + .await?; + super::explore_mappings(&state, kb).await?; + let effective = utopia_store::mappings::confirmed(&pool, kb, 10) + .await? + .remove(0); + assert_eq!(effective.id, pending.id); + assert_eq!(effective.decided_by, None); + let requests = model.received_requests().await.unwrap(); + let prompt = requests + .iter() + .find(|r| String::from_utf8_lossy(&r.body).contains("ONLY a JSON array")) + .unwrap(); + assert!(String::from_utf8_lossy(&prompt.body).contains("confidence")); + assert_eq!(requests.len(), 4); + anyhow::Ok(()) + } + .await; + sqlx::query("DELETE FROM knowledge_bases WHERE id = $1") + .bind(kb) + .execute(&pool) + .await?; + utopia_store::datasources::delete(&pool, source).await?; + result + } } diff --git a/crates/utopia-store/src/kbs.rs b/crates/utopia-store/src/kbs.rs index af2baec83..bb43ab98c 100644 --- a/crates/utopia-store/src/kbs.rs +++ b/crates/utopia-store/src/kbs.rs @@ -110,6 +110,7 @@ pub async fn update( auto_type_resolution: Option, governance: Option, data_conventions: Option<&str>, + auto_confirm_mappings: Option, ) -> AppResult { // 改语言不回头重写已有的类——它们已经是这个库的数据,可能有人手工调过。 // 这一列往后管的是**新**描述(自动扩本体、AI 建议)写成什么语言 @@ -151,6 +152,7 @@ pub async fn update( ELSE governance_since END, -- 人写的约定;清空要送空串,送 null 等于不改(与 description 同一约定) data_conventions = COALESCE($11, data_conventions), + auto_confirm_mappings = COALESCE($12, auto_confirm_mappings), updated_at = now() WHERE id = $1 RETURNING *", ) @@ -165,6 +167,7 @@ pub async fn update( .bind(auto_type_resolution) .bind(governance) .bind(data_conventions) + .bind(auto_confirm_mappings) .fetch_optional(pool) .await? .ok_or(AppError::NotFound) diff --git a/crates/utopia-store/src/mappings.rs b/crates/utopia-store/src/mappings.rs index 1f5f5e207..a096e5faa 100644 --- a/crates/utopia-store/src/mappings.rs +++ b/crates/utopia-store/src/mappings.rs @@ -12,6 +12,9 @@ use utopia_core::models::{ConceptMapping, MappingRevision}; use utopia_core::{AppError, AppResult}; use uuid::Uuid; +/// 自动确认的门槛。这是库主动打开的一道策略,不是量出来的准确率保证(0011) +const AUTO_CONFIRM_AT: f64 = 0.8; + /// 探索任务提议一条映射。 /// /// **同一个 (概念, 源) 只有一条**,由主键管——从前这条唯一性藏在 `object_value` @@ -33,35 +36,102 @@ pub async fn propose( summary: Option<&str>, derived: bool, ) -> AppResult<(Uuid, bool)> { - // **`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", + propose_with_evidence( + pool, kb_id, concept_id, source, table_name, expr, sql, unit, summary, derived, None, None, + ) + .await +} + +/// `propose` 带上模型的置信度与理由。每次写入都重新判一次开关与门槛(0011,#504): +/// 机器确认的定义可以被更好的一版刷新,人表过态或改过的探索永远盖不掉。 +#[allow(clippy::too_many_arguments)] +pub async fn propose_with_evidence( + 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, + confidence: Option, + rationale: Option<&str>, +) -> AppResult<(Uuid, bool)> { + let confidence = confidence.filter(|c| c.is_finite() && (0.0..=1.0).contains(c)); + let rationale = rationale.map(str::trim).filter(|s| !s.is_empty()); + let mut tx = pool.begin().await?; + // 模型调用可能很久,开关以落库这一刻为准。FOR SHARE 让这次写入与同时发生的关闭 + // 排上先后,又不至于让同库的几轮探索互相排队 + let enabled: bool = sqlx::query_scalar( + "SELECT auto_confirm_mappings FROM knowledge_bases WHERE id = $1 FOR SHARE", ) .bind(kb_id) - .bind(concept_id) - .bind(source) - .fetch_optional(pool) + .fetch_one(&mut *tx) .await?; - let id = existing.map(|(i,)| i).unwrap_or_else(Uuid::now_v7); - let written = sqlx::query( + let automatic = enabled + && confidence.is_some_and(|c| c >= AUTO_CONFIRM_AT) + && rationale.is_some() + && [expr, sql] + .into_iter() + .flatten() + .any(|s| !s.trim().is_empty()); + let status = if automatic { "confirmed" } else { "proposed" }; + // 自动写入要换掉一版已生效的定义:换之前那一版先进 revisions,与 `revise` 同一个理由。 + // 拿着行锁读,下面的 upsert 才不会与人的修改撞出一条多余的快照;定义没变就不留 + let replaced: Option<(Uuid, serde_json::Value)> = if automatic { + sqlx::query_as( + "SELECT m.id, to_jsonb(m) - 'id' - 'kb_id' FROM concept_mappings m + WHERE m.kb_id = $1 AND m.concept_id = $2 AND m.source = $3 + AND m.status = 'confirmed' AND m.auto_confirmed_at IS NOT NULL + AND m.decided_by IS NULL + AND (m.table_name, m.expr, m.sql, m.unit, m.summary, m.derived) + IS DISTINCT FROM ($4::text, $5::text, $6::text, $7::text, $8::text, $9::boolean) + FOR UPDATE", + ) + .bind(kb_id) + .bind(concept_id) + .bind(source) + .bind(table_name) + .bind(expr) + .bind(sql) + .bind(unit) + .bind(summary) + .bind(derived) + .fetch_optional(&mut *tx) + .await? + } else { + None + }; + // WHERE 只放行两种行,其余一律不动: + // - 还等着人、人也没碰过的提议; + // - 机器自己确认的那一版,而且这一次**仍然过得了门槛**。证据变弱或开关关了,已生效的 + // 定义原样留着,不能悄悄退回待看,让问数不再用它又没有一条事件说明为什么。 + // 人确认的、拒绝的、改过的,以及不是机器确认却没有 decided_by 的(评测脚本直接写的 + // 真值)都挡在外面,所以判断「机器确认」看 auto_confirmed_at,不看 decided_by + let written: Option = sqlx::query_scalar( "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) + (id, kb_id, concept_id, source, table_name, expr, sql, unit, summary, derived, + confidence, rationale, status, decided_at, auto_confirmed_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, + CASE WHEN $13 = 'confirmed' THEN now() END, + CASE WHEN $13 = 'confirmed' THEN now() END) 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'", + confidence = EXCLUDED.confidence, rationale = EXCLUDED.rationale, + status = EXCLUDED.status, decided_at = EXCLUDED.decided_at, + auto_confirmed_at = EXCLUDED.auto_confirmed_at, updated_at = now() + WHERE concept_mappings.decided_by IS NULL + AND (concept_mappings.status = 'proposed' + OR (concept_mappings.status = 'confirmed' + AND concept_mappings.auto_confirmed_at IS NOT NULL + AND EXCLUDED.status = 'confirmed')) + RETURNING id", ) - .bind(id) + .bind(Uuid::now_v7()) .bind(kb_id) .bind(concept_id) .bind(source) @@ -71,12 +141,133 @@ pub async fn propose( .bind(unit) .bind(summary) .bind(derived) - .execute(pool) - .await? - .rows_affected(); - // 插入或刷新了算写入;撞上已确认 / 已拒绝的那一行,WHERE 挡下更新,写入数为零—— - // 调用方靠这一位区分「进了待看」与「决定还在」 - Ok((id, written > 0)) + .bind(confidence) + .bind(rationale) + .bind(status) + .fetch_optional(&mut *tx) + .await?; + // **`DO UPDATE ... WHERE` 不满足时 `RETURNING` 一行都不返回。** + // + // 这是 Postgres 的实情而不是直觉:条件挡住更新,那一行就不算被这条语句 + // 动过,于是也不出现在 RETURNING 里。测试当场撞上——第二次提议一条已被 + // 拒绝的映射,`fetch_one` 报「no rows returned」。 + // + // 所以挡下来时把 id 单独查出来:更新与否是一回事,「这条映射是哪一行」是另一回事。 + // 写入了就用 RETURNING 的 id,它才是并发插入之后真正落下的那一行 + let id = match written { + Some(id) => id, + None => { + sqlx::query_scalar( + "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_one(&mut *tx) + .await? + } + }; + if let Some((mapping_id, before)) = replaced { + // changed_by 为空:这一版是机器换掉的,没有人可记 + sqlx::query( + "INSERT INTO concept_mapping_revisions (id, mapping_id, before, changed_by) + VALUES ($1, $2, $3, NULL)", + ) + .bind(Uuid::now_v7()) + .bind(mapping_id) + .bind(before) + .execute(&mut *tx) + .await?; + } + if written.is_some() && automatic { + // 自动写入改的是生效的定义:这条事件写不进去就连定义一起回滚, + // 不留一条谁也说不清来历的生效口径 + sqlx::query( + "INSERT INTO audit_events (id, kb_id, actor_id, action, target_kind, target_id, detail) + VALUES ($1, $2, NULL, 'mapping.auto_confirmed', 'concept_mapping', $3, $4)", + ) + .bind(Uuid::now_v7()) + .bind(kb_id) + .bind(id) + .bind(serde_json::json!({ + "concept_id": concept_id, "source": source, "confidence": confidence, + "rationale": rationale, "threshold": AUTO_CONFIRM_AT, + "definition": { "table": table_name, "expr": expr, "sql": sql, + "unit": unit, "summary": summary, "derived": derived } + })) + .execute(&mut *tx) + .await?; + } + tx.commit().await?; + // 插入或刷新了算写入;撞上被挡下的那一行,写入数为零—— + // 调用方靠这一位区分「进了待看或已生效」与「决定还在」 + Ok((id, written.is_some())) +} + +/// 人撤回一条自动确认:它立刻不再生效,回到待看,等人来定。 +/// +/// **撤回之后 `decided_by` 记这个人**,`propose` 据此不再碰它——否则下一轮探索 +/// 分数还是够,撤回当场被刷回去,等于没撤。定义本身不动:换掉过的旧版在 revisions 里, +/// 要用旧版,人照常编辑;要它永远别回来,那是拒绝。 +pub async fn revert_automatic( + pool: &PgPool, + kb_id: Uuid, + mapping_id: Uuid, + actor: Uuid, +) -> AppResult<()> { + let mut tx = pool.begin().await?; + let row: Option<(serde_json::Value, bool)> = sqlx::query_as( + "SELECT to_jsonb(m) - 'id' - 'kb_id', + m.status = 'confirmed' AND m.auto_confirmed_at IS NOT NULL + FROM concept_mappings m + WHERE m.id = $2 AND m.kb_id = $1 FOR UPDATE", + ) + .bind(kb_id) + .bind(mapping_id) + .fetch_optional(&mut *tx) + .await?; + let (before, automatic) = row.ok_or(AppError::NotFound)?; + if !automatic { + return Err(AppError::Conflict( + "This definition was not confirmed automatically, so there is nothing to revert".into(), + )); + } + 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 status = 'proposed', decided_by = $3, decided_at = now(), + auto_confirmed_at = NULL, updated_at = now() + WHERE id = $2 AND kb_id = $1", + ) + .bind(kb_id) + .bind(mapping_id) + .bind(actor) + .execute(&mut *tx) + .await?; + // 与撤回同一个事务:撤回发生过就一定查得到是谁撤的 + sqlx::query( + "INSERT INTO audit_events (id, kb_id, actor_id, action, target_kind, target_id, detail) + VALUES ($1, $2, $3, 'mapping.auto_confirm_reverted', 'concept_mapping', $4, $5)", + ) + .bind(Uuid::now_v7()) + .bind(kb_id) + .bind(actor) + .bind(mapping_id) + .bind(serde_json::json!({ "before": before })) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(()) } /// 人从零写一条口径(#562)。**落下来就是确认的**:写的人就是表态的人, @@ -87,7 +278,7 @@ pub async fn propose( /// /// 同一个 (概念, 源) 已经有一条时报冲突,而不是悄悄覆盖:那一条可能是探索提的、 /// 人已经确认过的,覆盖等于抹掉一次表态。要改用 `revise`。 -/// 探索反过来也盖不掉这条:`propose` 只刷新 `proposed` 的行。 +/// 探索反过来也盖不掉这条:`propose` 只刷新人没碰过的提议和机器自己确认的那一版。 #[allow(clippy::too_many_arguments)] pub async fn create( pool: &PgPool, @@ -140,7 +331,8 @@ pub async fn proposed( ) -> AppResult> { 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, m.written_by + m.table_name, m.expr, m.sql, m.unit, m.summary, m.derived, m.status, m.written_by, + m.decided_by, m.confidence, m.rationale, m.auto_confirmed_at FROM concept_mappings m JOIN entities e ON e.id = m.concept_id WHERE m.kb_id = $1 AND m.status = 'proposed' @@ -154,12 +346,13 @@ pub async fn proposed( .await?) } -/// 人确认过的。问数把它们注进 system prompt——**只用确认过的口径**, +/// 已生效的(人工或自动确认)。问数把它们注进 system prompt——**只用确认过的口径**, /// 而不是每次从 schema 猜。 pub async fn confirmed(pool: &PgPool, kb_id: Uuid, limit: i64) -> AppResult> { 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, m.written_by + m.table_name, m.expr, m.sql, m.unit, m.summary, m.derived, m.status, m.written_by, + m.decided_by, m.confidence, m.rationale, m.auto_confirmed_at FROM concept_mappings m JOIN entities e ON e.id = m.concept_id WHERE m.kb_id = $1 AND m.status = 'confirmed' @@ -175,7 +368,8 @@ pub async fn confirmed(pool: &PgPool, kb_id: Uuid, limit: i64) -> AppResult AppResult<()> { let res = sqlx::query( "UPDATE concept_mappings - SET status = $3, decided_by = $4, decided_at = now(), updated_at = now() + SET status = $3, decided_by = $4, decided_at = now(), + auto_confirmed_at = NULL, updated_at = now() WHERE id = $2 AND kb_id = $1", ) .bind(kb_id) @@ -221,7 +416,7 @@ pub async fn revise( 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", + WHERE m.id = $2 AND m.kb_id = $1 FOR UPDATE", ) .bind(kb_id) .bind(mapping_id) @@ -244,7 +439,8 @@ pub async fn revise( sqlx::query( "UPDATE concept_mappings SET table_name = $3, expr = $4, sql = $5, unit = $6, summary = $7, - derived = $8, updated_at = now() + derived = $8, decided_by = $9, decided_at = now(), + confidence = NULL, rationale = NULL, auto_confirmed_at = NULL, updated_at = now() WHERE id = $2 AND kb_id = $1", ) .bind(kb_id) @@ -255,6 +451,7 @@ pub async fn revise( .bind(unit) .bind(summary) .bind(derived) + .bind(actor) .execute(&mut *tx) .await?; tx.commit().await?; @@ -284,7 +481,8 @@ pub async fn page( OR m.table_name ILIKE '%' || $3 || '%')"; let rows: Vec = 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, m.written_by + m.table_name, m.expr, m.sql, m.unit, m.summary, m.derived, m.status, m.written_by, + m.decided_by, m.confidence, m.rationale, m.auto_confirmed_at FROM concept_mappings m JOIN entities e ON e.id = m.concept_id {WHERE} @@ -497,7 +695,8 @@ pub async fn confirmed_texts(pool: &PgPool, kb_id: Uuid) -> AppResult AppResult> { let rows: Vec = 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, m.written_by + m.table_name, m.expr, m.sql, m.unit, m.summary, m.derived, m.status, m.written_by, + m.decided_by, m.confidence, m.rationale, m.auto_confirmed_at FROM concept_mappings m JOIN entities e ON e.id = m.concept_id WHERE m.kb_id = $1 AND m.id = ANY($2)", ) diff --git a/crates/utopia-store/tests/store/a_mapping_is_not_a_fact.rs b/crates/utopia-store/tests/store/a_mapping_is_not_a_fact.rs index 7f65fde4f..42d601398 100644 --- a/crates/utopia-store/tests/store/a_mapping_is_not_a_fact.rs +++ b/crates/utopia-store/tests/store/a_mapping_is_not_a_fact.rs @@ -187,3 +187,456 @@ async fn a_rejected_mapping_does_not_come_back() -> anyhow::Result<()> { .await?; run } + +/// 一个打开了自动确认的库,给下面每条自动确认的性质各用一份。 +struct Auto { + pool: PgPool, + org: Uuid, + kb: Uuid, + ent: Uuid, +} + +impl Auto { + async fn new() -> anyhow::Result> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(None); + }; + let pool = PgPool::connect(&url).await?; + utopia_store::db::migrate(&pool).await?; + let (org, kb, ent) = fixture(&pool).await?; + let auto = Self { pool, org, kb, ent }; + auto.switch(true).await?; + Ok(Some(auto)) + } + + async fn switch(&self, on: bool) -> anyhow::Result<()> { + sqlx::query("UPDATE knowledge_bases SET auto_confirm_mappings = $2 WHERE id = $1") + .bind(self.kb) + .bind(on) + .execute(&self.pool) + .await?; + Ok(()) + } + + async fn person(&self) -> anyhow::Result { + let user = Uuid::now_v7(); + sqlx::query( + "INSERT INTO users (id, org_id, email, display_name, password_hash) + VALUES ($1, $2, $1 || '@auto-map.test', 'Editor', 'unused')", + ) + .bind(user) + .bind(self.org) + .execute(&self.pool) + .await?; + Ok(user) + } + + async fn propose( + &self, + confidence: Option, + rationale: Option<&str>, + expr: Option<&str>, + ) -> utopia_core::AppResult<(Uuid, bool)> { + utopia_store::mappings::propose_with_evidence( + &self.pool, + self.kb, + self.ent, + "warehouse", + Some("orders"), + expr, + None, + None, + Some("Revenue"), + false, + confidence, + rationale, + ) + .await + } + + /// 一条过得了门槛的提议:开关开着它就直接生效。 + async fn grounded(&self, expr: &str) -> anyhow::Result<(Uuid, bool)> { + Ok(self + .propose(Some(0.9), Some("Grounded"), Some(expr)) + .await?) + } + + async fn effective(&self) -> anyhow::Result> { + Ok(utopia_store::mappings::confirmed(&self.pool, self.kb, 10).await?) + } + + async fn pending(&self) -> anyhow::Result> { + Ok(utopia_store::mappings::proposed(&self.pool, self.kb, 10, 0).await?) + } + + async fn events(&self, action: &str) -> anyhow::Result, serde_json::Value)>> { + Ok(sqlx::query_as( + "SELECT actor_id, detail FROM audit_events WHERE kb_id = $1 AND action = $2", + ) + .bind(self.kb) + .bind(action) + .fetch_all(&self.pool) + .await?) + } + + async fn cleanup(self) -> anyhow::Result<()> { + sqlx::query("DELETE FROM knowledge_bases WHERE id = $1") + .bind(self.kb) + .execute(&self.pool) + .await?; + Ok(()) + } +} + +#[tokio::test] +async fn a_base_that_has_not_opted_in_only_collects_proposals() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + a.switch(false).await?; + a.propose( + Some(1.0), + Some("The schema states revenue"), + Some("SUM(amount)"), + ) + .await?; + assert!(a.effective().await?.is_empty()); + assert_eq!(a.pending().await?.len(), 1); + a.cleanup().await +} + +#[tokio::test] +async fn missing_or_invalid_evidence_leaves_a_proposal_waiting() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + for (confidence, rationale, expr) in [ + (None, Some("Grounded"), Some("SUM(amount)")), + (Some(0.79), Some("Grounded"), Some("SUM(amount)")), + (Some(f64::NAN), Some("Grounded"), Some("SUM(amount)")), + (Some(1.1), Some("Grounded"), Some("SUM(amount)")), + (Some(0.9), Some(" "), Some("SUM(amount)")), + (Some(0.9), Some("Grounded"), None), + ] { + a.propose(confidence, rationale, expr).await?; + assert!(a.effective().await?.is_empty()); + } + a.cleanup().await +} + +#[tokio::test] +async fn the_threshold_itself_confirms_and_the_readers_show_its_evidence() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + let (id, written) = a + .propose( + Some(0.8), + Some(" The schema states revenue "), + Some("SUM(amount)"), + ) + .await?; + assert!(written); + let auto = a.effective().await?.remove(0); + assert_eq!(auto.confidence, Some(0.8)); + assert_eq!(auto.rationale.as_deref(), Some("The schema states revenue")); + assert_eq!(auto.decided_by, None); + assert!(auto.auto_confirmed_at.is_some()); + let page = utopia_store::mappings::page(&a.pool, a.kb, None, None, 10, 0) + .await? + .0; + assert_eq!(page[0].rationale, auto.rationale); + let by_id = utopia_store::mappings::by_ids(&a.pool, a.kb, &[id]).await?; + assert_eq!(by_id[0].confidence, Some(0.8)); + a.cleanup().await +} + +#[tokio::test] +async fn an_automatic_write_is_audited_with_no_actor_and_its_definition() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + a.grounded("SUM(amount)").await?; + let events = a.events("mapping.auto_confirmed").await?; + assert_eq!(events.len(), 1); + assert_eq!(events[0].0, None); + assert_eq!(events[0].1["definition"]["expr"], "SUM(amount)"); + assert_eq!(events[0].1["rationale"], "Grounded"); + a.cleanup().await +} + +#[tokio::test] +async fn a_failed_audit_undoes_the_automatic_write() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + a.propose(None, None, None).await?; + // 触发器只认这个库,别的测试可以同时跑 + let (kb, fault) = (a.kb, format!("auto_mapping_fault_{}", a.kb.simple())); + sqlx::raw_sql(&format!( + "CREATE FUNCTION {fault}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN + IF NEW.kb_id = '{kb}' AND NEW.action = 'mapping.auto_confirmed' THEN + RAISE EXCEPTION 'injected mapping audit failure'; END IF; RETURN NEW; END $$; + CREATE TRIGGER {fault} BEFORE INSERT ON audit_events + FOR EACH ROW EXECUTE FUNCTION {fault}();" + )) + .execute(&a.pool) + .await?; + let failed = a.grounded("SUM(amount)").await; + sqlx::raw_sql(&format!( + "DROP TRIGGER {fault} ON audit_events; DROP FUNCTION {fault}();" + )) + .execute(&a.pool) + .await?; + assert!(failed.is_err()); + assert!(a.effective().await?.is_empty()); + assert_eq!(a.pending().await?[0].expr, None); + a.cleanup().await +} + +#[tokio::test] +async fn a_better_definition_refreshes_an_automatic_one_and_keeps_the_old() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + let (id, _) = a.grounded("SUM(amount)").await?; + assert_eq!(a.grounded("SUM(net_amount)").await?, (id, true)); + assert_eq!( + a.effective().await?[0].expr.as_deref(), + Some("SUM(net_amount)") + ); + let revisions = utopia_store::mappings::revisions(&a.pool, a.kb, id).await?; + assert_eq!(revisions.len(), 1); + assert_eq!(revisions[0].before["expr"], "SUM(amount)"); + assert_eq!(revisions[0].changed_by_name, None); + a.cleanup().await +} + +#[tokio::test] +async fn the_same_definition_again_adds_no_version() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + let (id, _) = a.grounded("SUM(amount)").await?; + a.grounded("SUM(amount)").await?; + assert!(utopia_store::mappings::revisions(&a.pool, a.kb, id) + .await? + .is_empty()); + a.cleanup().await +} + +#[tokio::test] +async fn weaker_evidence_does_not_demote_an_automatic_definition() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + let (id, _) = a.grounded("SUM(amount)").await?; + let result = a + .propose(Some(0.7), Some("Uncertain"), Some("SUM(other)")) + .await?; + assert_eq!(result, (id, false)); + let kept = a.effective().await?.remove(0); + assert_eq!(kept.expr.as_deref(), Some("SUM(amount)")); + assert_eq!(kept.confidence, Some(0.9)); + a.cleanup().await +} + +#[tokio::test] +async fn turning_the_switch_off_neither_revokes_nor_refreshes() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + let (id, _) = a.grounded("SUM(amount)").await?; + a.switch(false).await?; + assert_eq!( + a.effective().await?.len(), + 1, + "the switch alone revokes nothing" + ); + assert_eq!(a.grounded("SUM(other)").await?, (id, false)); + assert_eq!(a.effective().await?[0].expr.as_deref(), Some("SUM(amount)")); + a.cleanup().await +} + +/// `scripts/bench/ask.mjs` 就是这样写真值的:已确认、没有 decided_by。开关开不开都不能动它。 +#[tokio::test] +async fn exploration_leaves_a_confirmed_row_it_did_not_confirm() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + let (id, _) = a.propose(None, None, Some("SUM(truth)")).await?; + sqlx::query("UPDATE concept_mappings SET status = 'confirmed' WHERE id = $1") + .bind(id) + .execute(&a.pool) + .await?; + assert_eq!(a.grounded("SUM(amount)").await?, (id, false)); + a.switch(false).await?; + assert_eq!(a.grounded("SUM(amount)").await?, (id, false)); + assert_eq!(a.effective().await?[0].expr.as_deref(), Some("SUM(truth)")); + a.cleanup().await +} + +#[tokio::test] +async fn editing_a_pending_proposal_keeps_it_from_exploration() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + let user = a.person().await?; + let (id, _) = a + .propose(Some(0.5), Some("Unsure"), Some("SUM(amount)")) + .await?; + utopia_store::mappings::revise( + &a.pool, + a.kb, + id, + Some("orders"), + Some("SUM(human_amount)"), + None, + None, + None, + false, + user, + ) + .await?; + assert_eq!(a.grounded("SUM(amount)").await?, (id, false)); + let human = a.pending().await?.remove(0); + assert_eq!(human.expr.as_deref(), Some("SUM(human_amount)")); + assert_eq!(human.decided_by, Some(user)); + a.cleanup().await +} + +#[tokio::test] +async fn editing_clears_the_evidence_of_the_preceding_definition() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + let user = a.person().await?; + let (id, _) = a.grounded("SUM(amount)").await?; + utopia_store::mappings::revise( + &a.pool, + a.kb, + id, + Some("orders"), + Some("SUM(human_amount)"), + None, + None, + None, + false, + user, + ) + .await?; + let edited = a.effective().await?.remove(0); + assert_eq!(edited.confidence, None); + assert_eq!(edited.rationale, None); + assert_eq!(edited.auto_confirmed_at, None); + let revisions = utopia_store::mappings::revisions(&a.pool, a.kb, id).await?; + assert_eq!(revisions[0].before["confidence"], 0.9); + a.cleanup().await +} + +#[tokio::test] +async fn a_persons_decision_ends_the_automation_on_that_row() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + let user = a.person().await?; + let (id, _) = a.grounded("SUM(amount)").await?; + for status in ["confirmed", "rejected"] { + utopia_store::mappings::decide(&a.pool, a.kb, id, status, user).await?; + assert_eq!(a.grounded("SUM(other)").await?, (id, false)); + let row = utopia_store::mappings::by_ids(&a.pool, a.kb, &[id]) + .await? + .remove(0); + assert_eq!(row.status, status); + assert_eq!(row.expr.as_deref(), Some("SUM(amount)")); + assert_eq!(row.auto_confirmed_at, None); + } + a.cleanup().await +} + +#[tokio::test] +async fn a_revert_takes_the_definition_out_of_effect_and_records_who() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + let user = a.person().await?; + let (id, _) = a.grounded("SUM(amount)").await?; + utopia_store::mappings::revert_automatic(&a.pool, a.kb, id, user).await?; + assert!(a.effective().await?.is_empty()); + let back = a.pending().await?.remove(0); + assert_eq!(back.expr.as_deref(), Some("SUM(amount)")); + assert_eq!(back.decided_by, Some(user)); + assert_eq!(back.auto_confirmed_at, None); + let events = a.events("mapping.auto_confirm_reverted").await?; + assert_eq!(events.len(), 1); + assert_eq!(events[0].0, Some(user)); + assert_eq!(events[0].1["before"]["expr"], "SUM(amount)"); + assert_eq!( + utopia_store::mappings::revisions(&a.pool, a.kb, id) + .await? + .len(), + 1 + ); + a.cleanup().await +} + +#[tokio::test] +async fn exploration_does_not_confirm_a_reverted_definition_again() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + let user = a.person().await?; + let (id, _) = a.grounded("SUM(amount)").await?; + utopia_store::mappings::revert_automatic(&a.pool, a.kb, id, user).await?; + assert_eq!(a.grounded("SUM(amount)").await?, (id, false)); + assert!(a.effective().await?.is_empty()); + a.cleanup().await +} + +#[tokio::test] +async fn a_person_can_still_confirm_a_reverted_definition() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + let user = a.person().await?; + let (id, _) = a.grounded("SUM(amount)").await?; + utopia_store::mappings::revert_automatic(&a.pool, a.kb, id, user).await?; + utopia_store::mappings::decide(&a.pool, a.kb, id, "confirmed", user).await?; + assert_eq!(a.effective().await?.len(), 1); + a.cleanup().await +} + +#[tokio::test] +async fn only_an_automatic_confirmation_can_be_reverted() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + let user = a.person().await?; + let (id, _) = a.grounded("SUM(amount)").await?; + utopia_store::mappings::decide(&a.pool, a.kb, id, "confirmed", user).await?; + let refused = utopia_store::mappings::revert_automatic(&a.pool, a.kb, id, user).await; + assert!(matches!(refused, Err(utopia_core::AppError::Conflict(_)))); + assert_eq!(a.effective().await?[0].decided_by, Some(user)); + let missing = + utopia_store::mappings::revert_automatic(&a.pool, a.kb, Uuid::now_v7(), user).await; + assert!(matches!(missing, Err(utopia_core::AppError::NotFound))); + a.cleanup().await +} + +#[tokio::test] +async fn concurrent_automatic_proposals_return_the_stored_id() -> anyhow::Result<()> { + let Some(a) = Auto::new().await? else { + return Ok(()); + }; + let (x, y) = tokio::join!(a.grounded("COUNT(*)"), a.grounded("COUNT(*)")); + let (x, y) = (x?, y?); + assert_eq!(x, y); + let ids: Vec = sqlx::query_scalar( + "SELECT target_id FROM audit_events WHERE kb_id = $1 AND action = 'mapping.auto_confirmed'", + ) + .bind(a.kb) + .fetch_all(&a.pool) + .await?; + assert_eq!(ids, vec![x.0, x.0]); + a.cleanup().await +} diff --git a/crates/utopia-store/tests/store/exploration_describes_the_data.rs b/crates/utopia-store/tests/store/exploration_describes_the_data.rs index 20d564eac..fdf1dcc30 100644 --- a/crates/utopia-store/tests/store/exploration_describes_the_data.rs +++ b/crates/utopia-store/tests/store/exploration_describes_the_data.rs @@ -51,6 +51,7 @@ async fn the_description_and_the_conventions_do_not_overwrite_each_other() -> an None, None, Some("Amounts are in cents.\nis_test = 1 is excluded."), + None, ) .await?; // 探索写描述与问题 @@ -101,6 +102,7 @@ async fn the_description_and_the_conventions_do_not_overwrite_each_other() -> an None, None, Some("cents only"), + None, ) .await?; let got = utopia_store::kbs::get(&pool, kb).await?; @@ -119,6 +121,7 @@ async fn the_description_and_the_conventions_do_not_overwrite_each_other() -> an None, None, no, + None, ) .await?; assert_eq!( diff --git a/docs/decisions/0011-a-mapping-is-not-a-fact.md b/docs/decisions/0011-a-mapping-is-not-a-fact.md index ab1d03134..a9db13c94 100644 --- a/docs/decisions/0011-a-mapping-is-not-a-fact.md +++ b/docs/decisions/0011-a-mapping-is-not-a-fact.md @@ -1,6 +1,6 @@ # 0011 · A mapping is configuration -- **Status**: Implemented (#126, #140, #148) · open: the evidence chain +- **Status**: Implemented (#126, #140, #148, #1332) · open: the evidence chain - **Written**: 2026-08-31 · condensed into English 2026-09-03 - **Related**: [0009](0009-no-type-is-a-type.md) removes the builtin entity classes, [0010](0010-no-relation-is-no-relation.md) the fallback relation, #125 the other eight @@ -70,6 +70,45 @@ rebuilding all three. ## Revisions +- 2026-10-30 (#504, #1332): a base may opt into automatic confirmation of exploration's + definitions with `auto_confirm_mappings`, default off. This stays outside the governor: + a mapping is configuration and not a queue over the graph, so it has its own switch, as + `auto_type_resolution` does, and no `agent_decisions` row or fuse; 0043 and + `design/governance.md` carry the matching note. What it keeps from the governor's rules + is that every automatic decision is recorded and can be taken back. + - **The gate.** Exploration keeps `confidence` (0–1) and `rationale` apart from status. A + score of at least 0.8, a nonempty rationale and an expression or SQL are required; + anything less leaves the proposal waiting for a person. The threshold is an opt-in gate, + not a measured guarantee of correctness or a reason to turn it on by default. No + live-model accuracy improvement is claimed. An Editor may change the switch, because an + Editor may already confirm a definition; other base settings keep their Admin gate. + - **What marks it.** `auto_confirmed_at` is set while the current definition stands on an + automatic confirmation. `decided_by IS NULL` is not enough: `scripts/bench/ask.mjs` + seeds confirmed truth that way, and that truth must not be rewritten. + - **What exploration may change.** A definition no person has touched while it waits, and + a machine-confirmed definition when the new one passes the gate with the switch on. The + replaced definition goes to `concept_mapping_revisions` with no actor. Weaker evidence or + a switch turned off changes nothing: an effective definition is never silently demoted, + and turning the switch off revokes nothing. Anything a person confirmed, rejected or + edited, including an edit of a still-pending proposal, is out of reach. An edit clears + the model's evidence; the history snapshot keeps it for the preceding definition. + - **The revert.** `POST /kbs/{id}/mappings/{mapping_id}/revert` (Editor) takes a + machine-confirmed definition out of effect at once and returns it to pending under the + person's name, so the next exploration does not confirm it again. The definition stays + as it is, since the row holds one version: an older one is in the history, and a person + restores it by editing. Rejecting says the definition is wrong and must not return; a + revert says the machine should not have decided. + - **The record.** Each automatic write commits with `mapping.auto_confirmed` (the + definition and its evidence) and each revert with `mapping.auto_confirm_reverted`, so + a failed audit writes nothing. The upsert judges protection holding the row lock, and a + person's revision locks the row before taking its snapshot. Readers expose the evidence + and the decision's actor, and the mappings page marks automatic definitions. + - The gate does not answer 0036's dead end. A definition such as `sum(amt_pay)` runs, looks + right and can carry a high score while being off by a hundred, and a score cannot tell. + What bounds that here is the default-off switch, the record and the revert, not the + threshold. + - This applies to the existing concept definitions. Table-alignment adoption in 0036 and + the retirement of this table's role in #556 remain their own decisions. - 2026-09-02: the status line said "planned" while the record arrived in the same commit as its implementation. The status line is the implementing PR's responsibility; now a README rule. diff --git a/docs/decisions/0043-every-review-queue-is-governed.md b/docs/decisions/0043-every-review-queue-is-governed.md index 657c649da..cafe410ab 100644 --- a/docs/decisions/0043-every-review-queue-is-governed.md +++ b/docs/decisions/0043-every-review-queue-is-governed.md @@ -65,10 +65,14 @@ Agent rows for facts and conflicts carry their summary in place of two names. A ## Open questions -- **Cut 2: violations, ontology defects, concept mappings.** A violation's `fact_retracted` and `fact_closed` fit this shape. `axiom_relaxed` changes the ontology, and `fixed` for a defect means a person changed it; both need a gate before an agent applies them. +- **Cut 2: violations, ontology defects.** Concept mappings left this cut; see Revisions. A violation's `fact_retracted` and `fact_closed` fit this shape. `axiom_relaxed` changes the ontology, and `fixed` for a defect means a person changed it; both need a gate before an agent applies them. - **The second look.** The fact and conflict queues have no tool loop yet (0025 decision 5); the batch sees the evidence directly. Add one when proposals keep asking for something the batch could not see. - **The interface.** The Agent queue shows these rows with minimal changes; the queue cards themselves don't yet show the agent's proposal inline, as duplicate cards do. +## Revisions + +- 2026-10-30 (#504, #1332): concept mappings are exempt from decision 1 and leave cut 2. A mapping is configuration outside the graph ([0011](0011-a-mapping-is-not-a-fact.md)), and #725 already moves it off the review queues. Its automatic confirmation therefore has its own switch, like `auto_type_resolution`, and no `agent_decisions` row, precedent read or fuse. It keeps an audit event for each write and a revert. The other queues are unchanged. + ## Status history The status line as it stood on 2026-09-27, before status lines were cut to one line: diff --git a/docs/design/governance.md b/docs/design/governance.md index dc1af298f..d6488fa89 100644 --- a/docs/design/governance.md +++ b/docs/design/governance.md @@ -18,6 +18,12 @@ on their own page [0011, 0015, 0017, 0025]. Every human decision is a ledger eve (`review.merge`, `review.keep`, `merge.revert`, `fact.*`, `conflict.*`) and may carry a `rationale`, asked as "What told you?", optional, written as `why` on the event [0026]. +**Mappings are outside the governor.** A concept mapping is configuration, not a claim in the +graph [0011], so automatic confirmation has its own switch (`auto_confirm_mappings`, default off) +and neither an `agent_decisions` row nor a fuse. It keeps the record and the way back: each write +commits with `mapping.auto_confirmed`, and an Editor can revert one, which returns it to pending +and out of exploration's reach [0011, #504]. + **The governor.** `knowledge_bases.governance`, on by default; the `govern` job is enqueued when the switch turns on, after an extraction that leaves pairs, after a person's decision, and hourly for backlog, at most one waiting per base; it re-reads the switch before every cluster [0025 d2]. A @@ -106,8 +112,8 @@ for 589 pairs [0025 d10]. `reject_new`); a date must be in the evidence and a stale fact is confirmed only by a quote in the current version; every action records its undo in `detail`; reverts of any kind count for the fuse. #725 splits the PR: the temporal fixes merge first, the conflict actions become the - conflicts queue, the low-confidence handling is dropped. Cut 2 (violations, defects, mappings) - is open. + conflicts queue, the low-confidence handling is dropped. Cut 2 (violations, defects) is open; + mappings left it [0011, #504]. - **Queues organised by what a decision changes** [#725]: ontology proposals; alignment (a signature or rule the aligner cannot settle; the signature half is built, #754); time anchors (a missing or conflicting document date, an unanchored mention); identity (pairs evidence cannot settle, merges the gate held); diff --git a/docs/design/lakehouse-and-actions.md b/docs/design/lakehouse-and-actions.md index 368d8cbce..ca6e33fc0 100644 --- a/docs/design/lakehouse-and-actions.md +++ b/docs/design/lakehouse-and-actions.md @@ -22,7 +22,12 @@ against a real cluster; Databricks and Snowflake are covered by protocol replays **The semantic layer.** `concept_mappings` (concept, source, table, expr, sql, unit, summary, status, revisions) is configuration outside the ledger with its own page, proposed by exploration and confirmed by a person; rerunning exploration does not erase a rejection; a Viewer reads, an -Editor revises; chat reads confirmed mappings into its prompt, capped at 30 [0011]. A definition +Editor revises. A base may opt into automatic confirmation at confidence ≥ 0.8 with a +rationale and an expression or SQL (default off, #504); exploration may refresh a definition it +confirmed but never demotes it, and human decisions and edits remain protected. An Editor can +revert an automatic confirmation, which returns it to pending. The mappings page shows the +decision origin and evidence; automatic writes and reverts commit with their audit events. Chat reads confirmed mappings +into its prompt, capped at 30 [0011]. A definition can be written by hand (#563), and a one-page conventions document in the schema folder moved a bench from 2 to 14 of 18 with no code [0036]. The concept exploration used to create (`Metric` and `Dimension` entities with a SQL expression in a side table) is the wrong kind of thing and is to diff --git a/migrations/0124_a_base_can_opt_into_mapping_confirmation.sql b/migrations/0124_a_base_can_opt_into_mapping_confirmation.sql new file mode 100644 index 000000000..5e80e69fa --- /dev/null +++ b/migrations/0124_a_base_can_opt_into_mapping_confirmation.sql @@ -0,0 +1,9 @@ +-- Confidence is evidence for a decision, not an encoding of mapping status (0011). +ALTER TABLE knowledge_bases + ADD COLUMN auto_confirm_mappings boolean NOT NULL DEFAULT false; +ALTER TABLE concept_mappings + ADD COLUMN confidence double precision CHECK (confidence >= 0 AND confidence <= 1), + ADD COLUMN rationale text, + -- Set while the current definition stands on an automatic confirmation. A confirmed row + -- with no decided_by is not enough to tell: scripts/bench/ask.mjs seeds truth that way. + ADD COLUMN auto_confirmed_at timestamptz; diff --git a/web/src/api.ts b/web/src/api.ts index 65c5d15c0..9f1c15e76 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -139,6 +139,7 @@ export interface Kb { /** 治理开关(0025,缺省关):agent 按先进先出过等人的重复对,先读台账里人的 * 先例再裁;打开就开始,关掉就停 */ governance: boolean; + auto_confirm_mappings: boolean; /** 这次打开治理的时刻;保险丝只数它之后的撤回 */ governance_since: string | null; /** 多久重推一次(分钟)。事实持续在变,只靠手点会让派生一直是缺的 */ @@ -744,6 +745,11 @@ export interface ConceptMapping { /** 派生指标:算出来的,不是表里的列 */ derived: boolean; status: "proposed" | "confirmed" | "rejected"; + decided_by: string | null; + confidence: number | null; + rationale: string | null; + /** 机器确认这一版的时刻。有它才算自动确认:`decided_by` 为空的不一定是机器确认的 */ + auto_confirmed_at: string | null; } /** 一条口径改动之前的样子。**整版快照而不是差异**(0006): * 读的时候要回答的是「当时是什么」,差异得从头重放才答得出来 */ @@ -2640,6 +2646,12 @@ export const api = { body: JSON.stringify({ status }), }, ), + /** 撤回一条自动确认:不再生效,回到待看,探索也不再自动确认它 */ + revertMapping: (kbId: string, mappingId: string) => + request<{ ok: boolean }>( + `/api/v1/kbs/${kbId}/mappings/${mappingId}/revert`, + { method: "POST" }, + ), /** 跑一遍一致性检查。同步返回——纯计算,没有模型调用也没有网络 */ runConsistencyCheck: (kbId: string) => request<{ diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts index 92838d88e..9ac09aa3d 100644 --- a/web/src/i18n/en.ts +++ b/web/src/i18n/en.ts @@ -2009,6 +2009,10 @@ export const en = { colSource: "Source", colDefinition: "How it is computed", colStatus: "Status", + autoConfirmed: "Automatically confirmed", + revertAutomatic: "Revert", + confidence: (score: number) => `Confidence: ${Math.round(score * 100)}%`, + rationale: (text: string) => `Rationale: ${text}`, derivedBadge: "Derived", noDefinition: "(empty)", approve: "Confirm", @@ -2466,6 +2470,8 @@ export const en = { autoResolveTypes: "Resolve entity types after extraction", autoResolveTypesNote: "After each document is extracted, run a round of type resolution on entities the engine has not looked at yet. Only refinements within the current class are applied on their own — a re-classification across the tree still waits for you on the Ontology page. Every batch is listed there and can be undone.", + autoConfirmMappings: "Automatically confirm mapping proposals", + autoConfirmMappingsNote: "Off by default. On exploration, definitions with confidence of at least 80%, a rationale and an expression or SQL become effective immediately. A wrong definition can produce a plausible wrong answer. Human decisions and edits are kept. Turning this off leaves existing definitions in place; refreshed automatic definitions return to review.", governance: "Let the agent work the duplicates queue", governanceNote: "First in, first out. Before deciding a pair the agent reads what people in this base decided on the same names and the same kinds of pairs. It merges only where that history supports it, keeps apart on confidence, and leaves a proposal for everything else. Every decision is listed under Agent on the Review page and can be reverted. Turning this off stops the queue.", diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts index 8390c719d..ed32d1d92 100644 --- a/web/src/i18n/zh.ts +++ b/web/src/i18n/zh.ts @@ -1750,6 +1750,10 @@ export const zh: Strings = { colSource: "数据源", colDefinition: "怎么算", colStatus: "状态", + autoConfirmed: "自动确认", + revertAutomatic: "撤回", + confidence: (score: number) => `置信度:${Math.round(score * 100)}%`, + rationale: (text: string) => `理由:${text}`, derivedBadge: "派生", noDefinition: "(未填)", approve: "确认", @@ -2157,6 +2161,8 @@ export const zh: Strings = { autoResolveTypes: "抽取后自动消解实体类型", autoResolveTypesNote: "每篇文档抽完,对引擎还没看过的实体跑一轮类型消解。只有在现类子树里精化的才自动落地,跨轴的改判仍留在本体页等你。每一批都列在本体页,随时可以撤回。", + autoConfirmMappings: "自动确认映射提议", + autoConfirmMappingsNote: "默认关闭。探索时,置信度至少为 80%、有理由且有表达式或 SQL 的定义立即生效。错误定义可能产生看似合理的错误答案。人工决定和修改会保留。关闭后已有定义继续生效;重新探索刷新自动定义时会将其送回审核。", governance: "让 agent 处理重复项队列", governanceNote: "先进先出。裁一对之前,agent 先读这个库里的人对同样的名字、同样的类型对做过什么决定:有先例撑着才合并,有把握就分开,其余的写成建议留给你。每一笔都列在审核页的 Agent 里,可以撤回。关掉,队列就停。", diff --git a/web/src/pages/KbSettings.test.ts b/web/src/pages/KbSettings.test.ts index 14acde6a1..d67c70a92 100644 --- a/web/src/pages/KbSettings.test.ts +++ b/web/src/pages/KbSettings.test.ts @@ -73,7 +73,8 @@ const initial: Kb = { id: "kb-a", workspace_id: "workspace", name: "Research", kind: "general", description: "Original description", visibility: "open", is_default: false, auto_extend_ontology: false, materialize_inferences: false, - auto_type_resolution: false, governance: false, governance_since: null, + auto_type_resolution: false, + auto_confirm_mappings: false, governance: false, governance_since: null, inference_interval_minutes: 60, last_inference_at: null, ontology_lang: "en", }; let server: Kb; diff --git a/web/src/pages/KbSettings.tsx b/web/src/pages/KbSettings.tsx index 8a30f5aad..34b0e9487 100644 --- a/web/src/pages/KbSettings.tsx +++ b/web/src/pages/KbSettings.tsx @@ -120,6 +120,7 @@ export function KbSettings() { const [autoResolve, setAutoResolve] = useState(false); // 治理(0025):**缺省关**——它会合并实体,还没在哪个库上量过;打开就开始,关掉就停 const [governance, setGovernance] = useState(false); + const [autoMappings, setAutoMappings] = useState(false); const [inferMins, setInferMins] = useState(60); const [ontoLang, setOntoLang] = useState<"en" | "zh">("en"); const [confirmingDelete, setConfirmingDelete] = useState(false); @@ -144,6 +145,7 @@ export function KbSettings() { setMaterialize(kb.data.materialize_inferences); setAutoResolve(kb.data.auto_type_resolution); setGovernance(kb.data.governance); + setAutoMappings(kb.data.auto_confirm_mappings); setInferMins(kb.data.inference_interval_minutes); } }, [ @@ -164,6 +166,7 @@ export function KbSettings() { const saveIdentity = useKbPatch(kbId!, setError); const saveVisibility = useKbPatch(kbId!, setError); const saveAutomation = useKbPatch(kbId!, setError); + const saveMappings = useKbPatch(kbId!, setError); const saveLang = useKbPatch(kbId!, setError); const removeKb = useMutation({ @@ -410,6 +413,25 @@ export function KbSettings() { + saveMappings.mutate({ auto_confirm_mappings: autoMappings })} + > + {S.kbset.save} + + } + > + + + {/* 语料语言。**不是界面语言**——类描述逐字进抽取提示词, 读者是正在读这些文档的模型,所以它跟文档走不跟读者走 */} onDecisionPending(false), }); + const revert = useMutation({ + mutationFn: () => api.revertMapping(kbId, m.id), + onSuccess: onChanged, + onError: (e: unknown) => toast.error((e as Error).message), + }); + + const automatic = m.auto_confirmed_at !== null; const how = howComputed(m); return (
@@ -393,6 +400,9 @@ function MappingRow({ {S.mapping.derivedBadge} )} + {automatic && ( + {S.mapping.autoConfirmed} + )} {statusLabel(m.status)} @@ -411,6 +421,13 @@ function MappingRow({

{m.summary}

)} + {m.confidence !== null && ( +

{S.mapping.confidence(m.confidence)}

+ )} + {m.rationale && ( +

{S.mapping.rationale(m.rationale)}

+ )} + {editing ? ( - {m.status === "proposed" && ( + {(m.status === "proposed" || automatic) && ( <> + )} diff --git a/web/src/pages/accountRecordDates.test.ts b/web/src/pages/accountRecordDates.test.ts index aacca2c57..eeda95856 100644 --- a/web/src/pages/accountRecordDates.test.ts +++ b/web/src/pages/accountRecordDates.test.ts @@ -54,7 +54,7 @@ describe("record moments on the account pages", () => { const kb: Kb = { id: "kb1", workspace_id: "ws", name: "Research", kind: "knowledge", description: null, visibility: "restricted", is_default: false, auto_extend_ontology: true, - materialize_inferences: false, auto_type_resolution: false, governance: false, + materialize_inferences: false, auto_type_resolution: false, governance: false, auto_confirm_mappings: false, governance_since: null, inference_interval_minutes: 60, last_inference_at: null, ontology_lang: "en", }; diff --git a/web/src/pages/mappingAutomation.test.ts b/web/src/pages/mappingAutomation.test.ts new file mode 100644 index 000000000..9b7619608 --- /dev/null +++ b/web/src/pages/mappingAutomation.test.ts @@ -0,0 +1,70 @@ +import { createElement } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { describe, expect, it, vi } from "vitest"; +import type { ConceptMapping } from "../api"; + +import { S } from "../i18n"; +import { en } from "../i18n/en"; +import { zh } from "../i18n/zh"; + +vi.mock("../kb", () => ({ useKb: () => ({ kb: { id: "kb1" } }) })); +import { Mappings } from "./Mappings"; + +function render(mapping: ConceptMapping) { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + client.setQueryData(["mappings", "kb1", "all", "", 0], { + items: [mapping], total: 1, counts: { proposed: 0, confirmed: 1, rejected: 0 }, + }); + return renderToStaticMarkup(createElement(QueryClientProvider, { + client, children: createElement(Mappings), + })); +} + +const automatic: ConceptMapping = { + id: "m1", concept_id: "e1", concept_name: "Revenue", source: "Warehouse", + table_name: "orders", expr: "SUM(amount)", sql: null, unit: null, + summary: null, derived: false, status: "confirmed", decided_by: null, + confidence: 0.9, rationale: "The schema defines the amount column", + auto_confirmed_at: "2026-10-30T00:00:00Z", +}; + +describe("mapping decision origin and evidence", () => { + it("marks an automatic definition and offers every way to answer it", () => { + const html = render(automatic); + expect(html).toContain(S.mapping.autoConfirmed); + expect(html).toContain(S.mapping.approve); + expect(html).toContain(S.mapping.reject); + expect(html).toContain(S.mapping.revertAutomatic); + }); + + it("shows the model's evidence", () => { + const html = render(automatic); + expect(html).toContain(S.mapping.confidence(0.9)); + expect(html).toContain(S.mapping.rationale(automatic.rationale!)); + }); + + it("drops the mark and the revert once a person has decided", () => { + const html = render({ ...automatic, decided_by: "editor", auto_confirmed_at: null }); + expect(html).not.toContain(S.mapping.autoConfirmed); + expect(html).not.toContain(S.mapping.revertAutomatic); + }); + + it("does not call a confirmed row automatic only because nobody is recorded on it", () => { + const html = render({ ...automatic, auto_confirmed_at: null }); + expect(html).not.toContain(S.mapping.autoConfirmed); + expect(html).not.toContain(S.mapping.revertAutomatic); + }); + + it("shows no score when the model gave none", () => { + const html = render({ + ...automatic, status: "proposed", confidence: null, rationale: null, auto_confirmed_at: null, + }); + expect(html).not.toContain("90%"); + }); + + it("words the score in both languages", () => { + expect(en.mapping.confidence(0.8)).toBe("Confidence: 80%"); + expect(zh.mapping.confidence(0.8)).toBe("置信度:80%"); + }); +});