World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
A rule says who it marks, what it could not expand, and lets you change its mind (#387)
WaylandYang55f2ddf3d003
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rsindex a6bb0909..470f69c7 100644--- a/crates/utopia-server/src/api/mod.rs+++ b/crates/utopia-server/src/api/mod.rs@@ -195,6 +195,10 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {"/kbs/{id}/rules/{rule_id}",patch(rule_routes::update).delete(rule_routes::delete),)+ .route(+ "/kbs/{id}/rules/{rule_id}/matches",+ get(rule_routes::matches),+ ).route("/kbs/{id}/ontology/type-resolution/preview",post(ontology_routes::type_resolution_preview),diff --git a/crates/utopia-server/src/api/rule_routes.rs b/crates/utopia-server/src/api/rule_routes.rsindex f382677a..0ebfbafa 100644--- a/crates/utopia-server/src/api/rule_routes.rs+++ b/crates/utopia-server/src/api/rule_routes.rs@@ -8,7 +8,7 @@ use axum::Json;use serde::Deserialize;use serde_json::json;use utopia_core::models::Role;-use utopia_store::business_rules::ConditionInput;+use utopia_store::business_rules::{ConclusionInput, ConditionInput};use uuid::Uuid;use super::graph_routes::require_kb;@@ -44,6 +44,15 @@ pub struct RulePatch {/// 给了就整组替换;不给就不动条件#[serde(default)]pub conditions: Option<Vec<ConditionInput>>,+ /// 结论也整组替换:三格互相定义,只改一格会留下半截状态+ #[serde(default)]+ pub conclusion: Option<String>,+ #[serde(default)]+ pub conclude_type_id: Option<Uuid>,+ #[serde(default)]+ pub conclude_predicate_id: Option<Uuid>,+ #[serde(default)]+ pub conclude_value: Option<serde_json::Value>,}pub async fn list(@@ -96,6 +105,12 @@ pub async fn update(Json(req): Json<RulePatch>,) -> ApiResult<Json<serde_json::Value>> {require_kb(&state, &user, kb_id, Role::Editor).await?;+ let conclusion = req.conclusion.as_ref().map(|kind| ConclusionInput {+ kind: kind.clone(),+ type_id: req.conclude_type_id,+ predicate_id: req.conclude_predicate_id,+ value: req.conclude_value.clone(),+ });utopia_store::business_rules::update(&state.pool,kb_id,@@ -104,6 +119,7 @@ pub async fn update(req.description.as_deref(),req.enabled,req.conditions.as_deref(),+ conclusion.as_ref(),).await?;let _ = utopia_store::audit::record(@@ -139,6 +155,29 @@ pub async fn delete(Ok(Json(json!({ "ok": true })))}+/// 一条规则此刻标了谁。界面上那个数字点开就是这份列表。+pub async fn matches(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path((kb_id, rule_id)): Path<(Uuid, Uuid)>,+ axum::extract::Query(q): axum::extract::Query<MatchQuery>,+) -> ApiResult<Json<serde_json::Value>> {+ require_kb(&state, &user, kb_id, Role::Viewer).await?;+ let per = q.per.unwrap_or(20).clamp(1, 100);+ let page = q.page.unwrap_or(0).max(0);+ let (rows, total) =+ utopia_store::business_rules::matches(&state.pool, kb_id, rule_id, per, page * per).await?;+ Ok(Json(json!({ "matches": rows, "total": total })))+}++#[derive(Deserialize)]+pub struct MatchQuery {+ #[serde(default)]+ pub page: Option<i64>,+ #[serde(default)]+ pub per: Option<i64>,+}+/// 现在就跑一遍,把这条规则的结论算出来。////// **不等下一个物化周期**:写规则的人想立刻看见它推出了什么,而周期默认一小时。diff --git a/crates/utopia-store/src/business_rules.rs b/crates/utopia-store/src/business_rules.rsindex 2440d054..dcbf63e0 100644--- a/crates/utopia-store/src/business_rules.rs+++ b/crates/utopia-store/src/business_rules.rs@@ -65,6 +65,7 @@ type RuleRow = (Option<serde_json::Value>,bool,i64,+ i32,);/// 条件查询回来的一行:规则、属性谓词及其标签、比较方式、操作数@@ -116,44 +117,17 @@ pub async fn create(}validate_conditions(pool, kb_id, conditions).await?;- match conclusion {- "typing" => {- let t = conclude_type_id.ok_or_else(|| {- AppError::invalid("no_class", "A typing rule needs the class it concludes.")- })?;- exists(- pool,- kb_id,- "entity_types",- t,- "unknown_class",- "That class is not in this base.",- )- .await?;- ensure_is_a(pool, kb_id).await?;- }- "attribute" => {- let p = conclude_predicate_id.ok_or_else(|| {- AppError::invalid(- "no_predicate",- "An attribute rule needs the attribute it sets.",- )- })?;- if conclude_value.is_none() {- return Err(AppError::invalid(- "no_value",- "An attribute rule needs the value it sets.",- ));- }- attribute_predicate(pool, kb_id, p).await?;- }- _ => {- return Err(AppError::invalid(- "bad_conclusion",- "A conclusion is either a typing or an attribute.",- ))- }- }+ validate_conclusion(+ pool,+ kb_id,+ &ConclusionInput {+ kind: conclusion.to_string(),+ type_id: conclude_type_id,+ predicate_id: conclude_predicate_id,+ value: conclude_value.clone(),+ },+ )+ .await?;exists(pool,kb_id,@@ -199,6 +173,17 @@ pub async fn create(////// **不做逐条的增删改**——条件是一个合取整体,替换比对着 seq 打补丁好读,/// 也没有「改到一半」的中间状态。+/// 结论的一次改写。**两种形状各自完整地给**,不做「只改类、别的不动」——+/// 结论的三格是互相定义的,部分更新会留下 typing 却带着值这种半截状态。+pub struct ConclusionInput {+ /// typing | attribute+ pub kind: String,+ pub type_id: Option<Uuid>,+ pub predicate_id: Option<Uuid>,+ pub value: Option<serde_json::Value>,+}++#[allow(clippy::too_many_arguments)]pub async fn update(pool: &PgPool,kb_id: Uuid,@@ -207,6 +192,7 @@ pub async fn update(description: Option<&str>,enabled: Option<bool>,conditions: Option<&[ConditionInput]>,+ conclusion: Option<&ConclusionInput>,) -> AppResult<()> {if let Some(cs) = conditions {if cs.is_empty() {@@ -217,12 +203,22 @@ pub async fn update(}validate_conditions(pool, kb_id, cs).await?;}+ if let Some(c) = conclusion {+ validate_conclusion(pool, kb_id, c).await?;+ }let mut tx = pool.begin().await?;let res = sqlx::query(+ // 结论给了就整组换(三格一起),没给就一格不动——COALESCE 在这里+ // 不够用:把 typing 改成 attribute 要把 conclude_type_id 置回 NULL,+ // 而 COALESCE 恰恰做不到「显式清空」"UPDATE attribute_rulesSET name = COALESCE($3, name),description = COALESCE($4, description),enabled = COALESCE($5, enabled),+ conclusion = COALESCE($6, conclusion),+ conclude_type_id = CASE WHEN $6 IS NULL THEN conclude_type_id ELSE $7 END,+ conclude_predicate_id = CASE WHEN $6 IS NULL THEN conclude_predicate_id ELSE $8 END,+ conclude_value = CASE WHEN $6 IS NULL THEN conclude_value ELSE $9 END,updated_at = now()WHERE id = $2 AND kb_id = $1",)@@ -231,6 +227,10 @@ pub async fn update(.bind(name.map(str::trim)).bind(description.map(str::trim)).bind(enabled)+ .bind(conclusion.map(|c| c.kind.as_str()))+ .bind(conclusion.and_then(|c| c.type_id))+ .bind(conclusion.and_then(|c| c.predicate_id))+ .bind(conclusion.and_then(|c| c.value.clone())).execute(&mut *tx).await?;if res.rows_affected() == 0 {@@ -268,7 +268,8 @@ pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<serde_json::Valuer.conclusion, r.conclude_type_id, ct.label,r.conclude_predicate_id, cp.label, r.conclude_value, r.enabled,(SELECT count(*) FROM derived_facts d- WHERE d.attribute_rule_id = r.id AND d.invalidated_at IS NULL)+ WHERE d.attribute_rule_id = r.id AND d.invalidated_at IS NULL),+ r.capped_at_last_runFROM attribute_rules rJOIN entity_types st ON st.id = r.subject_type_idLEFT JOIN entity_types ct ON ct.id = r.conclude_type_id@@ -311,6 +312,7 @@ pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<serde_json::Valuecv,enabled,derived,+ capped,)| {let conditions: Vec<serde_json::Value> = conds.iter()@@ -338,6 +340,7 @@ pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<serde_json::Value"conclude_value": cv,"enabled": enabled,"derived_count": derived,+ "capped": capped,"conditions": conditions,})},@@ -350,7 +353,7 @@ type MatchRow = (Uuid,Uuid,String,- Option<serde_json::Value>,+ Option<String>,Option<chrono::DateTime<chrono::Utc>>,Option<chrono::DateTime<chrono::Utc>>,Vec<String>,@@ -377,7 +380,13 @@ pub async fn matches(.await?;let rows: Vec<MatchRow> = sqlx::query_as(- "SELECT d.id, e.id, e.canonical_name, d.object_value, d.valid_from, d.valid_to,+ // 结论读出来要是人看的那个名字。库里存的是类的 key/IRI(归类)或+ // 字面值(属性),两者都不该原样端上来+ "SELECT d.id, e.id, e.canonical_name,+ COALESCE(ct.label,+ d.object_value #>> '{value}',+ d.object_value ->> 'class'),+ d.valid_from, d.valid_to,COALESCE((SELECT array_agg(COALESCE(pr.label, '?') || ' = '@@ -391,8 +400,10 @@ pub async fn matches()FROM derived_facts dJOIN entities e ON e.id = d.subject_id+ JOIN attribute_rules ar ON ar.id = d.attribute_rule_id+ LEFT JOIN entity_types ct ON ct.id = ar.conclude_type_idWHERE d.kb_id = $1 AND d.attribute_rule_id = $2 AND d.invalidated_at IS NULL- ORDER BY e.canonical_name+ ORDER BY e.canonical_name, d.valid_fromLIMIT $3 OFFSET $4",).bind(kb_id)@@ -404,15 +415,12 @@ pub async fn matches(Ok((rows.into_iter()- .map(|(id, entity_id, name, value, from, to, premises)| {+ .map(|(id, entity_id, name, concluded, from, to, premises)| {json!({"derived_id": id,"entity_id": entity_id,"entity": name,- "concluded": value- .as_ref()- .and_then(|v| v.get("class").or_else(|| v.get("value")))- .cloned(),+ "concluded": concluded,"valid_from": from,"valid_to": to,"premises": premises,@@ -445,6 +453,49 @@ async fn insert_conditions(Ok(())}+/// 结论的校验。**建与改共用这一份**——分成两处写,改一次就能绕过建时的判据,+/// 而库里的 CHECK 只会回一个约束名,读的人无从知道错在哪一格。+async fn validate_conclusion(pool: &PgPool, kb_id: Uuid, c: &ConclusionInput) -> AppResult<()> {+ match c.kind.as_str() {+ "typing" => {+ let t = c.type_id.ok_or_else(|| {+ AppError::invalid("no_class", "A typing rule needs the class it concludes.")+ })?;+ exists(+ pool,+ kb_id,+ "entity_types",+ t,+ "unknown_class",+ "That class is not in this base.",+ )+ .await?;+ // 归类结论落在内建 is_a 上,第一次写这种规则时把它建出来+ ensure_is_a(pool, kb_id).await?;+ Ok(())+ }+ "attribute" => {+ let p = c.predicate_id.ok_or_else(|| {+ AppError::invalid(+ "no_predicate",+ "An attribute rule needs the attribute it sets.",+ )+ })?;+ if c.value.is_none() {+ return Err(AppError::invalid(+ "no_value",+ "An attribute rule needs the value it sets.",+ ));+ }+ attribute_predicate(pool, kb_id, p).await+ }+ _ => Err(AppError::invalid(+ "bad_conclusion",+ "A conclusion is either a typing or an attribute.",+ )),+ }+}+/// 条件的校验。**报错要说人话**:库里的 CHECK 只会回一个约束名。async fn validate_conditions(pool: &PgPool,diff --git a/crates/utopia-store/src/reasoning.rs b/crates/utopia-store/src/reasoning.rsindex 966fa9fd..1385fceb 100644--- a/crates/utopia-store/src/reasoning.rs+++ b/crates/utopia-store/src/reasoning.rs@@ -1383,6 +1383,13 @@ pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport>&attr_spans,);report.rule_hits += rr.hits;+ // 展不完的组合数按规则写回:这个数字在卡片上常驻,而不只在+ // 「跑完那一刻」的提示里闪一下(少推几条与「不满足」长得一样)+ sqlx::query("UPDATE attribute_rules SET capped_at_last_run = $2 WHERE id = $1")+ .bind(lr.rule.id)+ .bind(rr.capped as i32)+ .execute(pool)+ .await?;// 是「这一轮算出来的派生总数」,公理与规则都算在内。// **别改写它的原义**:被拦下的那些也算「算出来了」,队列里那一行// 正是凭它对上的diff --git a/crates/utopia-store/tests/a_rule_concludes_a_type.rs b/crates/utopia-store/tests/a_rule_concludes_a_type.rsindex a1f73373..12c60809 100644--- a/crates/utopia-store/tests/a_rule_concludes_a_type.rs+++ b/crates/utopia-store/tests/a_rule_concludes_a_type.rs@@ -457,3 +457,249 @@ async fn the_asserted_type_is_left_alone() -> anyhow::Result<()> {.await?;run}++/// 改结论:从「推一个类」改成「推一个属性值」。+///+/// **旧结论要作废,而不是留在那里跟着新结论一起成立。** 三格是互相定义的,+/// 所以这里也顺带钉住 `conclude_type_id` 被清空了——半截状态(说是 attribute+/// 却还挂着类)在库里看不出错,只会在导出与画布上冒出来。+#[tokio::test]+async fn changing_the_conclusion_retires_the_old_one() -> anyhow::Result<()> {+ let Some(url) = utopia_store::test_db::url() else {+ return Ok(());+ };+ let pool = PgPool::connect(&url).await?;+ let f = seed(&pool).await?;++ let run = async {+ attr(+ &pool,+ &f,+ f.thc,+ serde_json::json!(12.3),+ "2023-06-01T00:00:00Z",+ )+ .await?;+ attr(+ &pool,+ &f,+ f.category,+ serde_json::json!("气测异常"),+ "2023-06-01T00:00:00Z",+ )+ .await?;+ let r = rule(&pool, &f, 8.0).await?;+ utopia_store::reasoning::materialize(&pool, f.kb).await?;+ let rows = derived(&pool, &f).await?;+ assert_eq!(rows.len(), 1);+ assert_eq!(+ rows[0].object_value,+ Some(serde_json::json!({"class": "gas_well"}))+ );++ // 结论换成属性:含气性 = 含气+ let verdict = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO relation_types (id, kb_id, key, label, kind, datatype)+ VALUES ($1, $2, 'gas_verdict', '含气性', 'attribute', 'text')",+ )+ .bind(verdict)+ .bind(f.kb)+ .execute(&pool)+ .await?;+ utopia_store::business_rules::update(+ &pool,+ f.kb,+ r,+ None,+ None,+ None,+ None,+ Some(&utopia_store::business_rules::ConclusionInput {+ kind: "attribute".into(),+ type_id: None,+ predicate_id: Some(verdict),+ value: Some(serde_json::json!("含气")),+ }),+ )+ .await?;++ let (kind, class): (String, Option<Uuid>) = sqlx::query_as(+ "SELECT conclusion, conclude_type_id FROM attribute_rules WHERE id = $1",+ )+ .bind(r)+ .fetch_one(&pool)+ .await?;+ assert_eq!(kind, "attribute");+ assert!(class.is_none(), "换了形状,旧的那一格要清空");++ let report = utopia_store::reasoning::materialize(&pool, f.kb).await?;+ assert_eq!(report.rule_hits, 1, "同一份读数照样命中,只是结论变了");+ assert_eq!(report.invalidated, 1, "旧结论退场");++ let rows = derived(&pool, &f).await?;+ assert_eq!(rows.len(), 2, "两行:作废的旧结论 + 新结论");+ let old = rows.iter().find(|d| d.invalidated_at.is_some()).unwrap();+ let new = rows.iter().find(|d| d.invalidated_at.is_none()).unwrap();+ assert_eq!(+ old.object_value,+ Some(serde_json::json!({"class": "gas_well"}))+ );+ assert_eq!(new.object_value, Some(serde_json::json!({"value": "含气"})));+ Ok::<_, anyhow::Error>(())+ }+ .await;++ sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(f.org)+ .execute(&pool)+ .await?;+ run+}++/// 展不完的组合要**留在规则上**,不是只在跑完那一刻说一句。+///+/// 一口井上两个属性各九条读数就是 81 种组合,超过上限之后这个实体整个被跳过+/// ——而「跳过」与「不满足」在结果里长得一模一样。读数减回来,这个数字要跟着+/// 归零,否则它只会单调地累积成一句吓人的假话。+#[tokio::test]+async fn a_capped_expansion_is_remembered() -> anyhow::Result<()> {+ let Some(url) = utopia_store::test_db::url() else {+ return Ok(());+ };+ let pool = PgPool::connect(&url).await?;+ let f = seed(&pool).await?;++ let run = async {+ let mut thc_facts = Vec::new();+ for i in 0..9 {+ thc_facts.push(+ attr(+ &pool,+ &f,+ f.thc,+ serde_json::json!(10.0 + i as f64),+ &format!("2023-06-{:02}T00:00:00Z", i + 1),+ )+ .await?,+ );+ attr(+ &pool,+ &f,+ f.category,+ serde_json::json!("气测异常"),+ &format!("2023-07-{:02}T00:00:00Z", i + 1),+ )+ .await?;+ }+ let r = rule(&pool, &f, 8.0).await?;++ let report = utopia_store::reasoning::materialize(&pool, f.kb).await?;+ assert_eq!(report.rule_capped, 1);+ assert_eq!(+ report.rule_hits, 0,+ "展不完就整个跳过——这正是要说出来的原因"+ );+ assert_eq!(+ capped_of(&pool, f.kb, r).await?,+ 1,+ "落在规则上,卡片读得到"+ );++ // 读数收回到 1 × 9:能展开了+ for id in thc_facts.iter().skip(1) {+ sqlx::query("DELETE FROM facts WHERE id = $1")+ .bind(id)+ .execute(&pool)+ .await?;+ }+ let report = utopia_store::reasoning::materialize(&pool, f.kb).await?;+ assert_eq!(report.rule_capped, 0);+ assert!(report.rule_hits > 0);+ assert_eq!(capped_of(&pool, f.kb, r).await?, 0, "归零,不累积");+ Ok::<_, anyhow::Error>(())+ }+ .await;++ sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(f.org)+ .execute(&pool)+ .await?;+ run+}++/// 卡片上那个数字点开之后看见的东西:谁被标住了,以及凭哪几条读数。+#[tokio::test]+async fn the_matches_list_says_who_and_why() -> anyhow::Result<()> {+ let Some(url) = utopia_store::test_db::url() else {+ return Ok(());+ };+ let pool = PgPool::connect(&url).await?;+ let f = seed(&pool).await?;++ let run = async {+ attr(+ &pool,+ &f,+ f.thc,+ serde_json::json!(12.3),+ "2023-06-01T00:00:00Z",+ )+ .await?;+ attr(+ &pool,+ &f,+ f.category,+ serde_json::json!("气测异常"),+ "2023-06-01T00:00:00Z",+ )+ .await?;+ let r = rule(&pool, &f, 8.0).await?;+ utopia_store::reasoning::materialize(&pool, f.kb).await?;++ let (rows, total) = utopia_store::business_rules::matches(&pool, f.kb, r, 20, 0).await?;+ assert_eq!(total, 1);+ assert_eq!(rows[0]["entity"], "W-1");+ assert_eq!(+ rows[0]["concluded"], "GasBearingWell",+ "读出来是标签,不是库里的 key"+ );+ let premises: Vec<String> = rows[0]["premises"]+ .as_array()+ .unwrap()+ .iter()+ .map(|v| v.as_str().unwrap().to_string())+ .collect();+ assert_eq!(+ premises,+ vec!["全烃 = 12.3", "解释结论 = 气测异常"],+ "前提按顺序,读得出「凭什么」"+ );++ // 规则关掉之后结论退场,列表也就空了——数字与列表是同一份事实+ utopia_store::business_rules::update(&pool, f.kb, r, None, None, Some(false), None, None)+ .await?;+ utopia_store::reasoning::materialize(&pool, f.kb).await?;+ let (rows, total) = utopia_store::business_rules::matches(&pool, f.kb, r, 20, 0).await?;+ assert_eq!(total, 0);+ assert!(rows.is_empty());+ Ok::<_, anyhow::Error>(())+ }+ .await;++ sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(f.org)+ .execute(&pool)+ .await?;+ run+}++/// 一条规则上次跑的时候,有几个实体没展开完。+async fn capped_of(pool: &PgPool, kb: Uuid, rule_id: Uuid) -> anyhow::Result<i64> {+ let rules = utopia_store::business_rules::list(pool, kb).await?;+ let r = rules+ .iter()+ .find(|r| r["id"].as_str() == Some(&rule_id.to_string()))+ .expect("规则在列表里");+ Ok(r["capped"].as_i64().expect("capped 是个数"))+}diff --git a/migrations/0029_a_rule_remembers_what_it_could_not_expand.sql b/migrations/0029_a_rule_remembers_what_it_could_not_expand.sqlnew file mode 100644index 00000000..166be910--- /dev/null+++ b/migrations/0029_a_rule_remembers_what_it_could_not_expand.sql@@ -0,0 +1,7 @@+-- 0021 打磨:一条规则上次跑的时候,有几个实体的前提组合没展开完。+--+-- **少推几条与「这个实体不满足」在结果里长得一模一样。** 这个数字此前只出现在+-- 「立刻跑一遍」那一刻的提示里,看过就没了——而规则卡片是人回头判断「它到底+-- 靠不靠得住」的地方。落一列,物化每轮写回,卡片上常驻。+ALTER TABLE attribute_rules+ ADD COLUMN capped_at_last_run INT NOT NULL DEFAULT 0;diff --git a/web/src/api.ts b/web/src/api.tsindex 4119b141..958907df 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -330,6 +330,18 @@ export interface RuleInput {conditions: RuleCondition[];}+/** 一条规则标住的一个实体,连同让它成立的那几条读数 */+export interface RuleMatch {+ derived_id: string;+ entity_id: string;+ entity: string;+ concluded: string | null;+ valid_from: string | null;+ valid_to: string | null;+ /** 「全烃 = 12.3」这种可读形态,按前提顺序 */+ premises: string[];+}+export interface BusinessRule extends RuleInput {id: string;enabled: boolean;@@ -338,6 +350,8 @@ export interface BusinessRule extends RuleInput {conclude_predicate_label: string | null;/** 此刻凭它成立的结论条数 */derived_count: number;+ /** 上次跑的时候有几个实体的读数组合没展开完。**大于零就意味着少推了** */+ capped: number;}export interface DerivedFact {@@ -1595,12 +1609,22 @@ export const api = {description?: string;enabled?: boolean;conditions?: RuleCondition[];+ /** 结论整组替换:三格互相定义,只改一格会留下半截状态 */+ conclusion?: "typing" | "attribute";+ conclude_type_id?: string;+ conclude_predicate_id?: string;+ conclude_value?: unknown;},) =>request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/rules/${ruleId}`, {method: "PATCH",body: JSON.stringify(body),}),+ /** 一条规则此刻标了谁。规则卡片上那个数字点开就是它 */+ ruleMatches: (kbId: string, ruleId: string, page = 0, per = 20) =>+ request<{ matches: RuleMatch[]; total: number }>(+ `/api/v1/kbs/${kbId}/rules/${ruleId}/matches?page=${page}&per=${per}`,+ ),deleteRule: (kbId: string, ruleId: string) =>request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/rules/${ruleId}`, {method: "DELETE",diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex 6e8fb965..f9d079e7 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -1092,6 +1092,23 @@ export const en = {ruleRunCapped: (n: number) =>`${n} entity/rule pairs had too many readings to expand; their conclusions are incomplete`,ruleNeedsCondition: "A rule needs at least one condition.",+ /* ---- 打磨:可点的计数、常驻的 capped 提示、改结论 ---- */+ ruleEdit: "Edit",+ ruleEditing: "Editing",+ ruleMatchesTitle: "What it marks",+ ruleMatchesEmpty: "Nothing right now.",+ /* 前提要读成「凭什么」,所以用 because 起头而不是干列 */+ ruleMatchBecause: (premises: string) => `because ${premises}`,+ /* 同一个实体会因为不同时段的读数出现好几次——不写出这一段就像重复了 */+ ruleMatchSpan: (from: string, to: string | null) =>+ to ? `${from} – ${to}` : `since ${from}`,+ ruleMatchesMore: (shown: number, total: number) =>+ `showing ${shown} of ${total}`,+ /* 常驻在卡片上,而不只在跑完那一刻的 toast 里——少推几条与「不满足」+ 在结果里长得一样,读的人得随时看得见 */+ ruleCappedChip: "incomplete",+ ruleCappedHint:+ "Some entities carry too many readings of the same attribute to expand every combination, so this rule's conclusions for them are incomplete.",refineTitle: "Refine types",refineHint:"Entities whose class is roughly right but not the most specific one available. Look first, then apply — retyping does not appear on any timeline, so this is the only place you get to see it before it happens.",diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex cff6e94c..0fc20dc7 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -975,6 +975,18 @@ export const zh: Strings = {ruleRunCapped: (n: number) =>`${n} 对(规则,实体)的读数组合太多没有展开完,它们的结论不完整`,ruleNeedsCondition: "一条规则至少要有一个条件。",+ ruleEdit: "编辑",+ ruleEditing: "正在编辑",+ ruleMatchesTitle: "它标住了谁",+ ruleMatchesEmpty: "此刻一个也没有。",+ ruleMatchBecause: (premises: string) => `凭 ${premises}`,+ ruleMatchSpan: (from: string, to: string | null) =>+ to ? `${from} 至 ${to}` : `${from} 起`,+ ruleMatchesMore: (shown: number, total: number) =>+ `显示 ${shown} / ${total}`,+ ruleCappedChip: "不完整",+ ruleCappedHint:+ "有些实体同一属性的读数太多,组合展不完,这条规则在它们身上的结论是不完整的。",refineTitle: "类型消解",refineHint:"类挂得大致对、但本体里有更具体的那一个。先看一遍再落库——改类不进任何时间轴,这是唯一能在它发生之前看见它的地方。",diff --git a/web/src/pages/RulesPanel.tsx b/web/src/pages/RulesPanel.tsxindex d4698ab6..7adae140 100644--- a/web/src/pages/RulesPanel.tsx+++ b/web/src/pages/RulesPanel.tsx@@ -10,7 +10,7 @@* 一律从 ui/ 来。 */import { useState } from "react";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { Play, Plus, Trash2 } from "lucide-react";+import { Pencil, Play, Plus, Trash2 } from "lucide-react";import {api,type BusinessRule,@@ -21,10 +21,12 @@ import {import { S } from "../i18n";import {Button,+ Chip,DangerConfirm,Dropdown,IconButton,Input,+ LinkButton,Panel,} from "../ui";import { toast } from "../toast";@@ -79,6 +81,8 @@ function parseOperand(op: string, text: string): unknown | undefined {}type Draft = {+ /** 改的是哪一条;新建时为 null。**同一份草稿两种用途**——两套表单会漂移 */+ id: string | null;name: string;description: string;subject_type_id: string;@@ -93,6 +97,7 @@ const emptyDraft = (classes: EntityTypeView[],attrs: RelationTypeView[],): Draft => ({+ id: null,name: "",description: "",subject_type_id: classes[0]?.id ?? "",@@ -105,6 +110,75 @@ const emptyDraft = (: [],});+/** 已有规则 → 草稿。**回读要与写入是同一套形状**,否则编辑一次就变形。 */+function draftOf(r: BusinessRule): Draft {+ return {+ id: r.id,+ name: r.name,+ description: r.description ?? "",+ subject_type_id: r.subject_type_id,+ conclusion: r.conclusion,+ conclude_type_id: r.conclude_type_id ?? "",+ conclude_predicate_id: r.conclude_predicate_id ?? "",+ conclude_value:+ typeof r.conclude_value === "string"+ ? r.conclude_value+ : r.conclude_value === undefined || r.conclude_value === null+ ? ""+ : String(r.conclude_value),+ conditions: r.conditions.map((c) => ({+ predicate_id: c.predicate_id,+ op: c.op,+ text: operandText(c.op, c.operand),+ })),+ };+}++/** 一条规则此刻标住了谁,以及凭什么。计数点开就是它。 */+function Matches({ kbId, ruleId }: { kbId: string; ruleId: string }) {+ const q = useQuery({+ queryKey: ["ruleMatches", kbId, ruleId],+ queryFn: () => api.ruleMatches(kbId, ruleId),+ });+ const rows = q.data?.matches ?? [];+ const total = q.data?.total ?? 0;+ if (!rows.length) {+ return <p className="text-small text-ink-3">{S.ontology.ruleMatchesEmpty}</p>;+ }+ return (+ <div className="space-y-2">+ {rows.map((m) => (+ <div key={m.derived_id} className="space-y-1">+ <div className="flex flex-wrap items-baseline gap-2">+ <span className="text-small text-ink">{m.entity}</span>+ <span className="text-fine text-ink-3">→ {m.concluded}</span>+ {/* 同一个实体会因为不同时段的读数出现好几次,写出这一段才不像重复 */}+ {m.valid_from && (+ <span className="u-num text-fine text-ink-3">+ {S.ontology.ruleMatchSpan(+ m.valid_from.slice(0, 10),+ m.valid_to ? m.valid_to.slice(0, 10) : null,+ )}+ </span>+ )}+ </div>+ {/* 前提就是「凭什么」——列表没有它就跟一串凭空的判断没区别 */}+ {m.premises.length > 0 && (+ <p className="text-fine text-ink-3">+ {S.ontology.ruleMatchBecause(m.premises.join(", "))}+ </p>+ )}+ </div>+ ))}+ {total > rows.length && (+ <p className="u-num text-fine text-ink-3">+ {S.ontology.ruleMatchesMore(rows.length, total)}+ </p>+ )}+ </div>+ );+}+export function RulesPanel({kbId,classes,@@ -125,6 +199,8 @@ export function RulesPanel({const [draft, setDraft] = useState<Draft | null>(null);/** 待确认删除的那一条。删规则会带走它推出的全部结论,值得停一下 */const [doomed, setDoomed] = useState<BusinessRule | null>(null);+ /** 展开了哪条规则的命中列表。一次只展开一条——两份长列表并排读不了 */+ const [opened, setOpened] = useState<string | null>(null);const invalidate = () => {qc.invalidateQueries({ queryKey: ["rules", kbId] });@@ -133,7 +209,7 @@ export function RulesPanel({};const save = useMutation({- mutationFn: () => {+ mutationFn: async () => {const d = draft!;if (!d.conditions.length) throw new Error(S.ontology.ruleNeedsCondition);const conditions: RuleCondition[] = d.conditions.map((c) => {@@ -143,10 +219,7 @@ export function RulesPanel({}return { predicate_id: c.predicate_id, op: c.op, operand };});- return api.createRule(kbId, {- name: d.name,- description: d.description,- subject_type_id: d.subject_type_id,+ const conclusion = {conclusion: d.conclusion,conclude_type_id:d.conclusion === "typing" ? d.conclude_type_id : undefined,@@ -154,8 +227,23 @@ export function RulesPanel({d.conclusion === "attribute" ? d.conclude_predicate_id : undefined,conclude_value:d.conclusion === "attribute" ? d.conclude_value : undefined,- conditions,- });+ };+ // 改一条已有的规则走 PATCH,主类不动——换主类等于换一条规则,+ // 那时候删了重写比原地改诚实+ await (d.id+ ? api.updateRule(kbId, d.id, {+ name: d.name,+ description: d.description,+ conditions,+ ...conclusion,+ })+ : api.createRule(kbId, {+ name: d.name,+ description: d.description,+ subject_type_id: d.subject_type_id,+ conditions,+ ...conclusion,+ }));},onSuccess: () => {toast.success(S.ontology.ruleSaved);@@ -239,11 +327,23 @@ export function RulesPanel({<Panel key={r.id} className="space-y-2 p-4"><div className="flex items-center gap-2"><span className="text-body font-medium text-ink">{r.name}</span>- {/* 此刻凭它成立的结论条数——规则有没有在干活,一眼看得见 */}+ {/* 此刻凭它成立的结论条数。**点得动**——二十个实体还能一个个点开+ 看,两百个就只能靠这份列表 */}{r.derived_count > 0 && (- <span className="u-num text-fine text-ink-3">+ <LinkButton+ className="u-num text-fine"+ onClick={() => setOpened(opened === r.id ? null : r.id)}+ aria-expanded={opened === r.id}+ >{S.ontology.ruleDerivedCount(r.derived_count)}- </span>+ </LinkButton>+ )}+ {/* 展不完的组合:常驻,不只在跑完那一刻的提示里。少推几条与+ 「不满足」在结果里长得一样,读的人得随时看得见 */}+ {r.capped > 0 && (+ <Chip tone="warn" title={S.ontology.ruleCappedHint}>+ {S.ontology.ruleCappedChip}+ </Chip>)}<div className="ml-auto flex items-center gap-2">{/* 开关是个动作,所以是 Button;启用与否用 variant 区分,@@ -256,6 +356,13 @@ export function RulesPanel({>{r.enabled ? S.ontology.ruleEnabled : S.ontology.ruleDisabled}</Button>+ <IconButton+ label={S.ontology.ruleEdit}+ size="sm"+ onClick={() => setDraft(draftOf(r))}+ >+ <Pencil size={12} />+ </IconButton><IconButtonlabel={S.ontology.ruleDelete}size="sm"@@ -295,6 +402,14 @@ export function RulesPanel({: `${r.conclude_predicate_label} = ${JSON.stringify(r.conclude_value)}`}</span></p>+ {opened === r.id && (+ <div className="border-t border-line pt-2">+ <p className="mb-2 text-fine text-ink-3">+ {S.ontology.ruleMatchesTitle}+ </p>+ <Matches kbId={kbId} ruleId={r.id} />+ </div>+ )}</Panel>))}@@ -304,6 +419,9 @@ export function RulesPanel({{draft ? (<Panel className="space-y-3 p-4">+ {draft.id && (+ <p className="text-fine text-ink-3">{S.ontology.ruleEditing}</p>+ )}<Inputvalue={draft.name}onChange={(e) => setDraft({ ...draft, name: e.target.value })}@@ -320,11 +438,19 @@ export function RulesPanel({<span className="shrink-0 text-fine text-ink-3">{S.ontology.ruleSubject}</span>- <Dropdown- value={draft.subject_type_id}- onChange={(v) => setDraft({ ...draft, subject_type_id: v })}- options={classes.map((c) => ({ value: c.id, label: c.label }))}- />+ {draft.id ? (+ // 改一条已有规则时主类固定:换主类等于换一条规则,+ // 而它推出来的结论全挂在旧主类上+ <span className="text-small text-ink-2">+ {classes.find((c) => c.id === draft.subject_type_id)?.label}+ </span>+ ) : (+ <Dropdown+ value={draft.subject_type_id}+ onChange={(v) => setDraft({ ...draft, subject_type_id: v })}+ options={classes.map((c) => ({ value: c.id, label: c.label }))}+ />+ )}</div><div className="space-y-2">