World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
A rule reads attributes and concludes a type (0021 / #277) (#359)
WaylandYang0b18c7cbb701
diff --git a/Cargo.lock b/Cargo.lockindex 11d6d7c0..97c12a3b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -5118,6 +5118,7 @@ dependencies = [name = "utopia-reason"version = "0.1.0"dependencies = [+ "serde_json","uuid",]@@ -5184,6 +5185,7 @@ dependencies = ["chrono","cron","pgvector",+ "serde","serde_json","sha2 0.11.0","sqlx",diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rsindex b61817fa..a8447948 100644--- a/crates/utopia-core/src/models.rs+++ b/crates/utopia-core/src/models.rs@@ -1063,11 +1063,14 @@ pub struct DerivedFactView {pub id: Uuid,pub subject_id: Uuid,pub subject: String,- pub object_id: Uuid,+ /// 字面值结论(业务规则的归类与属性)没有实体宾语(0021)+ pub object_id: Option<Uuid>,pub object: String,pub predicate: String,- /// transitive | symmetric——靠哪条规则推的+ /// transitive | symmetric | inverse | sub_property,或 `business`(业务规则)pub rule: String,+ /// 业务规则的名字。公理推的为 None——公理没有名字,`rule` 那一列就是它的全部身份+ pub rule_name: Option<String>,pub valid_from: Option<DateTime<Utc>>,pub valid_to: Option<DateTime<Utc>>,pub confidence: f32,diff --git a/crates/utopia-reason/Cargo.toml b/crates/utopia-reason/Cargo.tomlindex 0e477a68..c5aa43fe 100644--- a/crates/utopia-reason/Cargo.toml+++ b/crates/utopia-reason/Cargo.toml@@ -6,3 +6,5 @@ license.workspace = true[dependencies]uuid.workspace = true+# 属性值是字面值(`facts.object_value`),比较要认它的形状+serde_json.workspace = truediff --git a/crates/utopia-reason/src/lib.rs b/crates/utopia-reason/src/lib.rsindex b6c3ca5c..c7207e83 100644--- a/crates/utopia-reason/src/lib.rs+++ b/crates/utopia-reason/src/lib.rs@@ -14,6 +14,7 @@pub mod derive;pub mod ontology;+pub mod rules;use std::collections::{HashMap, HashSet};use uuid::Uuid;diff --git a/crates/utopia-reason/src/rules.rs b/crates/utopia-reason/src/rules.rsnew file mode 100644index 00000000..f815ec03--- /dev/null+++ b/crates/utopia-reason/src/rules.rs@@ -0,0 +1,503 @@+//! 业务规则:读一个实体自己的属性事实,得出一个结论(见 `docs/decisions/0021`)。+//!+//! **与 `derive()` 分开的一趟。** 那一趟走的是实体—实体的边,在公理下做闭包;+//! 这一趟做的是「拿字面值跟阈值比」。两件事的输入、判据、终止条件都不一样,+//! 塞进一个函数只会让两边都难读。+//!+//! 与那一趟共享的是**区间语义**(`derive::validity`)和「结论是派生的」这条+//! 身份:命中产出的东西照样进 `derived_facts`、照样挂前提、照样在前提消失时失效。+//!+//! 这一层同样不碰数据库。取规则、取属性事实、落库都在 `utopia-store`。++use crate::derive::validity;+use std::collections::HashMap;+use uuid::Uuid;++/// 一个实体、一条属性、一个时段上的字面值。求值器的全部输入。+#[derive(Debug, Clone, PartialEq)]+pub struct AttrFact {+ pub id: Uuid,+ pub subject: Uuid,+ /// `relation_types` 里 kind='attribute' 的那个谓词+ pub predicate: Uuid,+ /// `facts.object_value -> 'value'`,已经从外壳里取出来+ pub value: serde_json::Value,+}++/// 条件的比较方式。与 `attribute_rule_conditions.op` 的 CHECK 一一对应。+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Op {+ Gt,+ Gte,+ Lt,+ Lte,+ Between,+ In,+ Present,+}++impl Op {+ pub fn as_str(self) -> &'static str {+ match self {+ Op::Gt => "gt",+ Op::Gte => "gte",+ Op::Lt => "lt",+ Op::Lte => "lte",+ Op::Between => "between",+ Op::In => "in",+ Op::Present => "present",+ }+ }++ pub fn parse(s: &str) -> Option<Self> {+ Some(match s {+ "gt" => Op::Gt,+ "gte" => Op::Gte,+ "lt" => Op::Lt,+ "lte" => Op::Lte,+ "between" => Op::Between,+ "in" => Op::In,+ "present" => Op::Present,+ _ => return None,+ })+ }+}++/// 操作数。形状由 op 决定,读的时候一次解析好,求值热路径上不再碰 JSON。+#[derive(Debug, Clone, PartialEq)]+pub enum Operand {+ Num(f64),+ /// 闭区间 [lo, hi]+ Range(f64, f64),+ /// 类别集合。**逐字匹配**——同一类别换个语言就不算命中,这是 0021 记下的+ /// 未决问题,不在这里偷偷做模糊+ Set(Vec<String>),+ None,+}++#[derive(Debug, Clone, PartialEq)]+pub struct Condition {+ pub predicate: Uuid,+ pub op: Op,+ pub operand: Operand,+}++/// 结论。两种形状对应 `attribute_rules.conclusion` 的两支。+#[derive(Debug, Clone, PartialEq)]+pub enum Conclusion {+ /// 派生归类:结论是一个类,落成 `is_a` 上的字面值+ Typing { class: String },+ /// 派生属性:某个属性谓词上的一个字面值+ Attribute {+ predicate: Uuid,+ value: serde_json::Value,+ },+}++#[derive(Debug, Clone, PartialEq)]+pub struct BusinessRule {+ pub id: Uuid,+ pub conclusion: Conclusion,+ /// 合取:全部满足才算命中。空条件集永不命中——一条没有判据的规则应当+ /// 什么都不推,而不是把整个类都归进去+ pub conditions: Vec<Condition>,+}++/// 一次命中。前提是**真正让它成立的那几条事实**,不是这个实体的全部属性。+#[derive(Debug, Clone, PartialEq)]+pub struct RuleHit {+ pub rule: Uuid,+ pub subject: Uuid,+ pub premises: Vec<Uuid>,+ pub from: Option<i64>,+ pub to: Option<i64>,+}++#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct RuleReport {+ /// 参与求值的规则数+ pub rules: usize,+ /// 命中数(去重后)+ pub hits: usize,+ /// 因组合数超上限而没有展开完的 (规则, 实体) 对数。**必须报出来**:+ /// 少推几条与「这个实体不满足」在结果里长得一模一样+ pub capped: usize,+}++/// 一个 (规则, 实体) 对最多展开多少种前提组合。+///+/// 组合数是各条件命中集大小的乘积:一口井的同一项读数报过三次、三个条件,+/// 就是 27 种。真实数据里每项通常只有一两条,这个上限只在「同一属性被反复+/// 覆盖几十次」时才够得着,而那种时候多算出来的区间也早就没有阅读价值了。+const MAX_COMBOS: usize = 64;++/// 求值。+///+/// `facts` 是**已经限定在这条规则的主类之内**的属性事实——挑哪些实体参与是+/// 取数那一侧的事(子类展开要查本体),这一层只管判断。+///+/// 语义:每个条件各自挑出满足它的事实集合,再在「每个条件取一条」的组合上+/// 求区间交集,交集非空即一次命中。**所以同一条规则可以在同一个实体上产出+/// 多段区间**——2023 那次读数命中、2025 那次不命中,得到的是两段各自成立的+/// 结论,而不是一行翻来覆去改(0021 决策 4)。+pub fn evaluate(+ rules: &[BusinessRule],+ facts: &[AttrFact],+ spans: &HashMap<Uuid, (Option<i64>, Option<i64>)>,+) -> (Vec<RuleHit>, RuleReport) {+ let mut report = RuleReport {+ rules: rules.len(),+ ..Default::default()+ };+ let mut hits: Vec<RuleHit> = Vec::new();++ // 按实体分组:规则谈的是「一个实体自己的属性」,跨实体不参与+ let mut by_subject: HashMap<Uuid, Vec<&AttrFact>> = HashMap::new();+ for f in facts {+ by_subject.entry(f.subject).or_default().push(f);+ }++ for rule in rules {+ if rule.conditions.is_empty() {+ continue;+ }+ for (subject, own) in &by_subject {+ // 每个条件的命中集。任何一个为空,这条规则在这个实体上就不成立+ let mut per_condition: Vec<Vec<Uuid>> = Vec::with_capacity(rule.conditions.len());+ let mut satisfiable = true;+ for c in &rule.conditions {+ let matched: Vec<Uuid> = own+ .iter()+ .filter(|f| f.predicate == c.predicate && satisfies(c, &f.value))+ .map(|f| f.id)+ .collect();+ if matched.is_empty() {+ satisfiable = false;+ break;+ }+ per_condition.push(matched);+ }+ if !satisfiable {+ continue;+ }++ let combos: usize = per_condition.iter().map(|v| v.len()).product();+ if combos > MAX_COMBOS {+ report.capped += 1;+ continue;+ }++ // 笛卡尔积。同一区间可能由多个组合得出(同一读数报了两遍),+ // 按区间去重——它们本来就会落成同一行+ let mut seen: Vec<(Option<i64>, Option<i64>)> = Vec::new();+ for combo in cartesian(&per_condition) {+ let Some((from, to)) = validity(&combo, spans) else {+ continue;+ };+ if seen.contains(&(from, to)) {+ continue;+ }+ seen.push((from, to));+ hits.push(RuleHit {+ rule: rule.id,+ subject: *subject,+ premises: combo,+ from,+ to,+ });+ }+ }+ }+ report.hits = hits.len();+ (hits, report)+}++/// 每个条件取一条,穷举组合。调用方已经把上限挡在外面。+fn cartesian(sets: &[Vec<Uuid>]) -> Vec<Vec<Uuid>> {+ let mut out: Vec<Vec<Uuid>> = vec![Vec::new()];+ for set in sets {+ let mut next = Vec::with_capacity(out.len() * set.len());+ for prefix in &out {+ for id in set {+ let mut row = prefix.clone();+ row.push(*id);+ next.push(row);+ }+ }+ out = next;+ }+ out+}++/// 一条属性值满不满足一个条件。+///+/// **类型不对就是不满足,不是报错。** 一个本该是数字的属性被抽成了+/// "十二点三",这条规则在这个实体上不成立——而不是让整轮物化失败。+fn satisfies(c: &Condition, value: &serde_json::Value) -> bool {+ match (&c.op, &c.operand) {+ (Op::Present, _) => !value.is_null(),+ (Op::Gt, Operand::Num(n)) => num(value).is_some_and(|v| v > *n),+ (Op::Gte, Operand::Num(n)) => num(value).is_some_and(|v| v >= *n),+ (Op::Lt, Operand::Num(n)) => num(value).is_some_and(|v| v < *n),+ (Op::Lte, Operand::Num(n)) => num(value).is_some_and(|v| v <= *n),+ (Op::Between, Operand::Range(lo, hi)) => num(value).is_some_and(|v| v >= *lo && v <= *hi),+ (Op::In, Operand::Set(set)) => text(value).is_some_and(|s| set.iter().any(|x| x == &s)),+ // op 与操作数形状对不上:库里的 CHECK 挡了大部分,剩下的当不满足+ _ => false,+ }+}++/// 数字。**字符串里的数字也认**——抽取把「12.3」存成字符串是常有的事,+/// 而一个阈值规则因为引号而静默失效,是最难被发现的那种失效。+fn num(v: &serde_json::Value) -> Option<f64> {+ match v {+ serde_json::Value::Number(n) => n.as_f64(),+ serde_json::Value::String(s) => s.trim().parse::<f64>().ok(),+ serde_json::Value::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),+ _ => None,+ }+}++/// 类别。数字与布尔也转成字面形态参与集合比较,理由同上。+fn text(v: &serde_json::Value) -> Option<String> {+ match v {+ serde_json::Value::String(s) => Some(s.trim().to_string()),+ serde_json::Value::Number(n) => Some(n.to_string()),+ serde_json::Value::Bool(b) => Some(b.to_string()),+ _ => None,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn id(n: u8) -> Uuid {+ Uuid::from_bytes([n; 16])+ }++ fn fact(fid: u8, subject: u8, pred: u8, value: serde_json::Value) -> AttrFact {+ AttrFact {+ id: id(fid),+ subject: id(subject),+ predicate: id(pred),+ value,+ }+ }++ /// 全烃 12.3 且解释为气测异常 → 命中,前提正是那两条读数+ #[test]+ fn a_conjunction_fires_and_names_the_two_readings() {+ let rule = BusinessRule {+ id: id(90),+ conclusion: Conclusion::Typing {+ class: "GasBearingWell".into(),+ },+ conditions: vec![+ Condition {+ predicate: id(10),+ op: Op::Gt,+ operand: Operand::Num(8.0),+ },+ Condition {+ predicate: id(11),+ op: Op::In,+ operand: Operand::Set(vec!["气测异常".into(), "气测异常后效".into()]),+ },+ ],+ };+ let facts = vec![+ fact(1, 50, 10, json!(12.3)),+ fact(2, 50, 11, json!("气测异常")),+ ];+ let spans = HashMap::from([(id(1), (Some(100), None)), (id(2), (Some(100), None))]);+ let (hits, report) = evaluate(&[rule], &facts, &spans);+ assert_eq!(hits.len(), 1);+ assert_eq!(hits[0].subject, id(50));+ assert_eq!(hits[0].premises, vec![id(1), id(2)]);+ assert_eq!(hits[0].from, Some(100));+ assert_eq!(report.hits, 1);+ }++ /// 合取里少一条就不成立。**这是最容易写反的地方**:任一条件没有命中的+ /// 事实,整条规则在这个实体上就不成立,而不是「按剩下的条件算」+ #[test]+ fn a_missing_condition_fires_nothing() {+ let rule = BusinessRule {+ id: id(90),+ conclusion: Conclusion::Typing {+ class: "GasBearingWell".into(),+ },+ conditions: vec![+ Condition {+ predicate: id(10),+ op: Op::Gt,+ operand: Operand::Num(8.0),+ },+ Condition {+ predicate: id(11),+ op: Op::Present,+ operand: Operand::None,+ },+ ],+ };+ let facts = vec![fact(1, 50, 10, json!(12.3))];+ let spans = HashMap::from([(id(1), (Some(100), None))]);+ let (hits, _) = evaluate(&[rule], &facts, &spans);+ assert!(hits.is_empty(), "第二个条件没有任何事实,不该命中");+ }++ /// 同一属性的两次读数各自成立 → 两段区间,而不是一行翻转(0021 决策 4)+ #[test]+ fn two_readings_give_two_intervals() {+ let rule = BusinessRule {+ id: id(90),+ conclusion: Conclusion::Typing {+ class: "GasBearingWell".into(),+ },+ conditions: vec![Condition {+ predicate: id(10),+ op: Op::Gt,+ operand: Operand::Num(8.0),+ }],+ };+ // 2023 与 2025 两次读数都过阈值,区间不相交+ let facts = vec![fact(1, 50, 10, json!(12.3)), fact(2, 50, 10, json!(9.9))];+ let spans = HashMap::from([+ (id(1), (Some(100), Some(200))),+ (id(2), (Some(300), Some(400))),+ ]);+ let (hits, _) = evaluate(&[rule], &facts, &spans);+ assert_eq!(hits.len(), 2, "两次读数各自成立");+ let mut spans_out: Vec<_> = hits.iter().map(|h| (h.from, h.to)).collect();+ spans_out.sort();+ assert_eq!(+ spans_out,+ vec![(Some(100), Some(200)), (Some(300), Some(400))]+ );+ }++ /// 区间不相交的两条前提凑不成一次命中:全烃是 2023 的,解释是 2025 的,+ /// 这两条从来没有同时成立过+ #[test]+ fn premises_that_never_overlapped_fire_nothing() {+ let rule = BusinessRule {+ id: id(90),+ conclusion: Conclusion::Typing {+ class: "GasBearingWell".into(),+ },+ conditions: vec![+ Condition {+ predicate: id(10),+ op: Op::Gt,+ operand: Operand::Num(8.0),+ },+ Condition {+ predicate: id(11),+ op: Op::In,+ operand: Operand::Set(vec!["气测异常".into()]),+ },+ ],+ };+ let facts = vec![+ fact(1, 50, 10, json!(12.3)),+ fact(2, 50, 11, json!("气测异常")),+ ];+ let spans = HashMap::from([+ (id(1), (Some(100), Some(200))),+ (id(2), (Some(300), Some(400))),+ ]);+ let (hits, _) = evaluate(&[rule], &facts, &spans);+ assert!(hits.is_empty(), "两条前提没有同时成立的时段");+ }++ /// 数字被抽成字符串照样比得动。**这一条挡的是最难发现的失效**:+ /// 规则从不报错,只是永远不命中+ #[test]+ fn a_number_in_quotes_still_compares() {+ let rule = BusinessRule {+ id: id(90),+ conclusion: Conclusion::Attribute {+ predicate: id(20),+ value: json!("good"),+ },+ conditions: vec![Condition {+ predicate: id(10),+ op: Op::Gte,+ operand: Operand::Num(12.0),+ }],+ };+ let facts = vec![fact(1, 50, 10, json!(" 12.3 "))];+ let spans = HashMap::from([(id(1), (None, None))]);+ let (hits, _) = evaluate(&[rule], &facts, &spans);+ assert_eq!(hits.len(), 1);+ }++ /// 阈值抬高到读数之上,同一份数据就不再命中——降/升阈值重跑是 0021 的验收项+ #[test]+ fn raising_the_threshold_clears_the_hit() {+ let facts = vec![fact(1, 50, 10, json!(12.3))];+ let spans = HashMap::from([(id(1), (None, None))]);+ let mk = |threshold: f64| BusinessRule {+ id: id(90),+ conclusion: Conclusion::Typing {+ class: "GasBearingWell".into(),+ },+ conditions: vec![Condition {+ predicate: id(10),+ op: Op::Gt,+ operand: Operand::Num(threshold),+ }],+ };+ assert_eq!(evaluate(&[mk(8.0)], &facts, &spans).0.len(), 1);+ assert!(evaluate(&[mk(20.0)], &facts, &spans).0.is_empty());+ }++ /// 没有条件的规则什么都不推。空合取在逻辑上恒真,会把整个类归进去——+ /// 那是「规则还没写完」最坏的失败方式+ #[test]+ fn a_rule_without_conditions_concludes_nothing() {+ let rule = BusinessRule {+ id: id(90),+ conclusion: Conclusion::Typing { class: "X".into() },+ conditions: vec![],+ };+ let facts = vec![fact(1, 50, 10, json!(12.3))];+ let spans = HashMap::from([(id(1), (None, None))]);+ let (hits, _) = evaluate(&[rule], &facts, &spans);+ assert!(hits.is_empty());+ }++ /// 组合数超上限时**报出来**,不是静默少推+ #[test]+ fn too_many_combinations_are_reported() {+ let rule = BusinessRule {+ id: id(90),+ conclusion: Conclusion::Typing { class: "X".into() },+ conditions: vec![+ Condition {+ predicate: id(10),+ op: Op::Present,+ operand: Operand::None,+ },+ Condition {+ predicate: id(11),+ op: Op::Present,+ operand: Operand::None,+ },+ ],+ };+ let mut facts = Vec::new();+ let mut spans = HashMap::new();+ for i in 0..10u8 {+ facts.push(fact(i, 50, 10, json!(1)));+ facts.push(fact(i + 100, 50, 11, json!(1)));+ spans.insert(id(i), (None, None));+ spans.insert(id(i + 100), (None, None));+ }+ let (hits, report) = evaluate(&[rule], &facts, &spans);+ assert_eq!(report.capped, 1, "100 种组合超过上限,要计数");+ assert!(hits.is_empty());+ }+}diff --git a/crates/utopia-server/src/api/chat.rs b/crates/utopia-server/src/api/chat.rsindex bb734267..827a730d 100644--- a/crates/utopia-server/src/api/chat.rs+++ b/crates/utopia-server/src/api/chat.rs@@ -303,7 +303,10 @@ pub(super) fn base_tools() -> serde_json::Value {relations with validity ranges (from → to; 'now' = still ongoing). \The best tool for who/when/history questions. Use after find_entities. \Pass `at` to see the world as of that date (server-side filter) — \- always do this for \"who was X in <year/month>\" questions.",+ always do this for \"who was X in <year/month>\" questions. \+ Conclusions a business rule reached about this entity come back too, \+ marked `[rule: <name>]` with the readings that made them true — take \+ those as given rather than re-deriving them from the readings yourself.","parameters": {"type": "object","properties": {@@ -322,6 +325,29 @@ pub(super) fn base_tools() -> serde_json::Value {}}},+ {+ "type": "function",+ "function": {+ "name": "list_rules",+ "description": "The business rules this base runs: what each one concludes and the exact conditions it tests, thresholds included. A rule is written by a person, and its conclusions are already in the graph — read the rule to explain WHY something was concluded, or to answer \"what counts as X here\". Do not re-implement a rule's comparison yourself; ask entity_facts or rule_matches for what it actually concluded.",+ "parameters": { "type": "object", "properties": {} }+ }+ },+ {+ "type": "function",+ "function": {+ "name": "rule_matches",+ "description": "Which entities a business rule currently marks, with the readings that made each one true. Use it for \"which wells are gas-bearing\" style questions — one call instead of checking every entity. Get the rule id from list_rules.",+ "parameters": {+ "type": "object",+ "properties": {+ "rule_id": { "type": "string", "description": "Rule id (uuid) from list_rules." },+ "limit": { "type": "integer", "description": "How many to return (default 50, max 200)." }+ },+ "required": ["rule_id"]+ }+ }+ },{"type": "function","function": {diff --git a/crates/utopia-server/src/api/mcp.rs b/crates/utopia-server/src/api/mcp.rsindex 4d0a276a..56038e7f 100644--- a/crates/utopia-server/src/api/mcp.rs+++ b/crates/utopia-server/src/api/mcp.rs@@ -36,11 +36,17 @@ const PROTOCOL_VERSION: &str = "2025-06-18";////// `query_data` 仍旧不放:它对**部署之外的生产库**跑 SQL,审计怎么记、/// 一个被投喂了脏文档的 agent 拿它做什么,都还没答完(0014 的混淆代理那一节)。-const EXPOSED: [&str; 6] = [+/// 业务规则的两个只读工具也在这里(0021):判据要看得见——一个 agent 解释+/// 「凭什么算含气井」时,该读到那条规则和它的阈值,而不是自己猜一个。+/// **写规则不放**:推理的判据由人写下,而一次工具调用分不出「人口述、agent+/// 代打」与「模型自己编了一条」+const EXPOSED: [&str; 8] = ["search_chunks","get_document","search_docs","find_entities",+ "list_rules",+ "rule_matches","changes","entity_facts",];diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rsindex 76b4454b..3e7e7a05 100644--- a/crates/utopia-server/src/api/mod.rs+++ b/crates/utopia-server/src/api/mod.rs@@ -14,6 +14,7 @@ mod mcp;mod members_routes;pub(crate) mod ontology_routes;mod review_routes;+pub(crate) mod rule_routes;mod search_routes;mod settings_routes;mod sources_routes;@@ -184,6 +185,16 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {get(documents_routes::extraction_drops),).route("/kbs/{id}/ontology", get(ontology_routes::get))+ // 业务规则(0021):读规则要 Viewer,写要 Editor+ .route(+ "/kbs/{id}/rules",+ get(rule_routes::list).post(rule_routes::create),+ )+ .route("/kbs/{id}/rules/run", post(rule_routes::run_now))+ .route(+ "/kbs/{id}/rules/{rule_id}",+ patch(rule_routes::update).delete(rule_routes::delete),+ ).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.rsnew file mode 100644index 00000000..f382677a--- /dev/null+++ b/crates/utopia-server/src/api/rule_routes.rs@@ -0,0 +1,161 @@+//! 业务规则的增删改查(0021 / #277)。+//!+//! **写规则要 Editor**:它是本体的一部分——一条规则改一次,全库的结论跟着变,+//! 与改一条公理同一个量级。++use axum::extract::{Path, State};+use axum::Json;+use serde::Deserialize;+use serde_json::json;+use utopia_core::models::Role;+use utopia_store::business_rules::ConditionInput;+use uuid::Uuid;++use super::graph_routes::require_kb;+use crate::auth::AuthUser;+use crate::error::ApiResult;+use crate::state::AppState;++#[derive(Deserialize)]+pub struct RuleReq {+ pub name: String,+ #[serde(default)]+ pub description: String,+ pub subject_type_id: Uuid,+ /// typing | attribute+ pub conclusion: 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 conditions: Vec<ConditionInput>,+}++#[derive(Deserialize)]+pub struct RulePatch {+ #[serde(default)]+ pub name: Option<String>,+ #[serde(default)]+ pub description: Option<String>,+ #[serde(default)]+ pub enabled: Option<bool>,+ /// 给了就整组替换;不给就不动条件+ #[serde(default)]+ pub conditions: Option<Vec<ConditionInput>>,+}++pub async fn list(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path(kb_id): Path<Uuid>,+) -> ApiResult<Json<serde_json::Value>> {+ require_kb(&state, &user, kb_id, Role::Viewer).await?;+ let rules = utopia_store::business_rules::list(&state.pool, kb_id).await?;+ Ok(Json(json!({ "rules": rules })))+}++pub async fn create(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path(kb_id): Path<Uuid>,+ Json(req): Json<RuleReq>,+) -> ApiResult<Json<serde_json::Value>> {+ require_kb(&state, &user, kb_id, Role::Editor).await?;+ let id = utopia_store::business_rules::create(+ &state.pool,+ kb_id,+ &req.name,+ &req.description,+ req.subject_type_id,+ &req.conclusion,+ req.conclude_type_id,+ req.conclude_predicate_id,+ req.conclude_value.clone(),+ &req.conditions,+ )+ .await?;+ let _ = utopia_store::audit::record(+ &state.pool,+ Some(kb_id),+ user.id,+ "rule.created",+ "attribute_rule",+ Some(id),+ json!({ "name": req.name, "conclusion": req.conclusion }),+ )+ .await;+ Ok(Json(json!({ "id": id })))+}++pub async fn update(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path((kb_id, rule_id)): Path<(Uuid, Uuid)>,+ Json(req): Json<RulePatch>,+) -> ApiResult<Json<serde_json::Value>> {+ require_kb(&state, &user, kb_id, Role::Editor).await?;+ utopia_store::business_rules::update(+ &state.pool,+ kb_id,+ rule_id,+ req.name.as_deref(),+ req.description.as_deref(),+ req.enabled,+ req.conditions.as_deref(),+ )+ .await?;+ let _ = utopia_store::audit::record(+ &state.pool,+ Some(kb_id),+ user.id,+ "rule.updated",+ "attribute_rule",+ Some(rule_id),+ json!({ "enabled": req.enabled, "conditions_replaced": req.conditions.is_some() }),+ )+ .await;+ Ok(Json(json!({ "ok": true })))+}++pub async fn delete(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path((kb_id, rule_id)): Path<(Uuid, Uuid)>,+) -> ApiResult<Json<serde_json::Value>> {+ require_kb(&state, &user, kb_id, Role::Editor).await?;+ utopia_store::business_rules::delete(&state.pool, kb_id, rule_id).await?;+ let _ = utopia_store::audit::record(+ &state.pool,+ Some(kb_id),+ user.id,+ "rule.deleted",+ "attribute_rule",+ Some(rule_id),+ json!({}),+ )+ .await;+ Ok(Json(json!({ "ok": true })))+}++/// 现在就跑一遍,把这条规则的结论算出来。+///+/// **不等下一个物化周期**:写规则的人想立刻看见它推出了什么,而周期默认一小时。+/// 走的是同一个 `materialize`——预览与正式是同一条路,不另写一份会漂移的逻辑。+pub async fn run_now(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path(kb_id): Path<Uuid>,+) -> ApiResult<Json<serde_json::Value>> {+ require_kb(&state, &user, kb_id, Role::Editor).await?;+ let report = utopia_store::reasoning::materialize(&state.pool, kb_id).await?;+ state.emit_graph(kb_id);+ Ok(Json(json!({+ "rules": report.attribute_rules,+ "hits": report.rule_hits,+ "capped": report.rule_capped,+ "inserted": report.inserted,+ "invalidated": report.invalidated,+ })))+}diff --git a/crates/utopia-server/src/api/tools.rs b/crates/utopia-server/src/api/tools.rsindex 16be2021..c5cf1bbc 100644--- a/crates/utopia-server/src/api/tools.rs+++ b/crates/utopia-server/src/api/tools.rs@@ -76,6 +76,11 @@ pub async fn dispatch("find_entities" => find_entities(ctx, sink, args).await,"entity_facts" => entity_facts(ctx, args).await,"changes" => changes(ctx, args).await,+ // 业务规则只读(0021):判据要看得见,但**写规则不开给模型**——+ // 「推理的判据由人写」是 0002 与 0021 共同的那条线,而一个工具调用+ // 分不出「人口述、agent 代打」与「模型自己编了一条」+ "list_rules" => list_rules(ctx).await,+ "rule_matches" => rule_matches(ctx, args).await,"query_data" if !ctx.mounted_sources.is_empty() => query_data(ctx, args).await,"remember" if ctx.can_write => remember(ctx, args).await,other => (@@ -321,7 +326,33 @@ pub async fn entity_facts(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolRef.valid_from.is_none_or(|from| from <= t) && f.valid_to.is_none_or(|to| to > t)});}- let text = if facts.is_empty() {+ // 规则的结论也是这个实体的一部分(0021)。**不给的话模型会拿那些+ // 读数自己再判一遍**——而阈值写在规则里,它看不见,于是两处判断+ // 迟早不一致,agent 那次还没有前提链、没有区间、也不进账本+ let derived =+ utopia_store::reasoning::derived_for_entity(&ctx.state.pool, ctx.kb_id, id)+ .await+ .unwrap_or_default();+ let mut derived: Vec<String> = derived+ .iter()+ .filter(|d| {+ at.is_none_or(|t| {+ d.valid_from.is_none_or(|from| from <= t)+ && d.valid_to.is_none_or(|to| to > t)+ })+ })+ .map(|d| {+ format!(+ "{} · {} · {} [rule: {}]",+ d.subject,+ d.predicate,+ d.object,+ d.rule_name.as_deref().unwrap_or(&d.rule),+ )+ })+ .collect();++ let text = if facts.is_empty() && derived.is_empty() {match at {Some(t) => format!("{}: no facts valid as of {}.",@@ -331,7 +362,9 @@ pub async fn entity_facts(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolReNone => format!("{}: no recorded facts.", node.name),}} else {- facts.iter().map(fact_line).collect::<Vec<_>>().join("\n")+ let mut lines: Vec<String> = facts.iter().map(fact_line).collect();+ lines.append(&mut derived);+ lines.join("\n")};let detail = match (at, as_of) {(Some(t), Some(r)) => format!(@@ -362,6 +395,135 @@ pub async fn entity_facts(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolRe}}+/// 这个库的判据。**把阈值原样给出来**——模型要能解释「凭什么算含气井」,+/// 而不是猜一个听起来合理的门槛。+pub async fn list_rules(ctx: &ToolCtx<'_>) -> ToolResult {+ let Ok(rules) = utopia_store::business_rules::list(&ctx.state.pool, ctx.kb_id).await else {+ return (+ "Could not read the rules.".to_string(),+ json!({ "kind": "tool", "label": "list_rules", "detail": "failed" }),+ );+ };+ if rules.is_empty() {+ return (+ "This base has no business rules.".to_string(),+ json!({ "kind": "tool", "label": "list_rules", "detail": "none" }),+ );+ }+ let text = rules+ .iter()+ .map(|r| {+ let conditions = r["conditions"]+ .as_array()+ .map(|cs| {+ cs.iter()+ .map(|c| {+ format!(+ "{} {} {}",+ c["predicate_label"].as_str().unwrap_or("?"),+ c["op"].as_str().unwrap_or("?"),+ c["operand"]+ .as_str()+ .map(str::to_string)+ .unwrap_or_else(|| c["operand"].to_string()),+ )+ })+ .collect::<Vec<_>>()+ .join(" AND ")+ })+ .unwrap_or_default();+ let concludes = if r["conclusion"] == "typing" {+ r["conclude_type_label"].as_str().unwrap_or("?").to_string()+ } else {+ format!(+ "{} = {}",+ r["conclude_predicate_label"].as_str().unwrap_or("?"),+ r["conclude_value"]+ )+ };+ format!(+ "{} [{}] — applies to {} where {} ⇒ {} · marks {} now · id {}",+ r["name"].as_str().unwrap_or("?"),+ if r["enabled"] == true { "on" } else { "off" },+ r["subject_label"].as_str().unwrap_or("?"),+ conditions,+ concludes,+ r["derived_count"],+ r["id"].as_str().unwrap_or("?"),+ )+ })+ .collect::<Vec<_>>()+ .join("\n");+ let n = rules.len();+ (+ text,+ json!({ "kind": "tool", "label": "list_rules", "detail": format!("{n} rules") }),+ )+}++/// 一条规则此刻标了谁。**前提一起给**:结论没有前提就跟一条凭空的断言没区别。+pub async fn rule_matches(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult {+ let Some(rule_id) = args["rule_id"]+ .as_str()+ .and_then(|s| s.parse::<Uuid>().ok())+ else {+ return (+ "Invalid rule_id (expected the uuid returned by list_rules).".to_string(),+ json!({ "kind": "tool", "label": "rule_matches", "detail": "invalid id" }),+ );+ };+ let limit = args["limit"].as_i64().unwrap_or(50).clamp(1, 200);+ let Ok((rows, total)) =+ utopia_store::business_rules::matches(&ctx.state.pool, ctx.kb_id, rule_id, limit, 0).await+ else {+ return (+ "Could not read what that rule marks.".to_string(),+ json!({ "kind": "tool", "label": "rule_matches", "detail": "failed" }),+ );+ };+ if rows.is_empty() {+ return (+ "That rule marks nothing right now.".to_string(),+ json!({ "kind": "tool", "label": "rule_matches", "detail": "0" }),+ );+ }+ let text = rows+ .iter()+ .map(|m| {+ let premises = m["premises"]+ .as_array()+ .map(|p| {+ p.iter()+ .filter_map(|x| x.as_str())+ .collect::<Vec<_>>()+ .join(", ")+ })+ .unwrap_or_default();+ format!(+ "{} ⇒ {} (because {}) [{}]",+ m["entity"].as_str().unwrap_or("?"),+ m["concluded"]+ .as_str()+ .map(str::to_string)+ .unwrap_or_else(|| m["concluded"].to_string()),+ premises,+ m["entity_id"].as_str().unwrap_or("?"),+ )+ })+ .collect::<Vec<_>>()+ .join("\n");+ // 截断要说出来:模型看到 50 条会当成全部,而库里可能有两百+ let text = if total > rows.len() as i64 {+ format!("{text}\n(showing {} of {total})", rows.len())+ } else {+ text+ };+ (+ text,+ json!({ "kind": "tool", "label": "rule_matches", "detail": format!("{total} entities") }),+ )+}+pub async fn changes(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult {let day = |k: &str| {args[k]diff --git a/crates/utopia-server/src/rdf.rs b/crates/utopia-server/src/rdf.rsindex ff433354..e119a907 100644--- a/crates/utopia-server/src/rdf.rs+++ b/crates/utopia-server/src/rdf.rs@@ -503,7 +503,14 @@ pub fn emit_derived(d: &ExportDerived,) -> std::io::Result<()> {let stmt = names.derived(d.id);- let rule = names.rule(d.rule_id);+ // 推理活动的身份:公理规则有自己的 id,业务规则用它的。两者都要有一个+ // 稳定的 IRI,否则审计读到一条结论却指不出「凭什么」+ let rule = match (d.rule_id, d.attribute_rule_id) {+ (Some(r), _) => names.rule(r),+ (None, Some(r)) => names.rule(r),+ // 库里的 CHECK 保证不会两个都空;真到了这一步宁可跳过整条+ (None, None) => return Ok(()),+ };sink.r(&stmt, &nn(rdf::TYPE.as_str()), &nn(rdf::STATEMENT.as_str()))?;sink.r(&stmt,@@ -513,7 +520,19 @@ pub fn emit_derived(if let Some(p) = vocab.relation(d.predicate_id).cloned() {sink.r(&stmt, &nn(rdf::PREDICATE.as_str()), &p)?;}- sink.r(&stmt, &nn(rdf::OBJECT.as_str()), &names.entity(d.object_id))?;+ // 宾语两条通道,与断言事实同一套:实体走 IRI,字面值结论走字面量(0021)+ match (d.object_id, &d.object_value) {+ (Some(o), _) => sink.r(&stmt, &nn(rdf::OBJECT.as_str()), &names.entity(o))?,+ (None, Some(v)) => {+ let (datatype, _) = vocab.literal_shape(d.predicate_id);+ sink.l(+ &stmt,+ &nn(rdf::OBJECT.as_str()),+ &literal_value(v, datatype),+ )?;+ }+ (None, None) => {}+ }sink.l(&stmt, &utopia("derived"), &flag(true))?;emit_validity(sink,@@ -530,7 +549,13 @@ pub fn emit_derived(sink.l(&stmt, &utopia("confidence"), &confidence(d.confidence))?;sink.r(&stmt, &prov("wasGeneratedBy"), &rule)?;sink.r(&rule, &nn(rdf::TYPE.as_str()), &prov("Activity"))?;- sink.l(&rule, &nn(rdfs::LABEL.as_str()), &text(d.rule.clone()))?;+ // 标签用规则自己的名字(业务规则),公理退回它的种类名——审计读到的是+ // 「Gas-bearing well」而不是「business」+ sink.l(+ &rule,+ &nn(rdfs::LABEL.as_str()),+ &text(d.rule_name.clone().unwrap_or_else(|| d.rule.clone())),+ )?;// 前提。审计顺着 prov:used 往下走一步就到断言,再走一步就到句子for premise in &d.premises {let p = names.fact(*premise);@@ -876,14 +901,85 @@ mod tests {);}+ /// 业务规则的结论也要出现在导出里,而且宾语是**字面值**。+ ///+ /// 这一条挡的是一次静默丢失:取数那边原本 `JOIN rules`,而业务规则的+ /// `rule_id` 是 NULL——整条结论会被内连接挡在文件之外,而 0020 承诺的正是+ /// 「审计员不靠我们也能读全」。活动的标签也要是规则自己的名字,+ /// 「business」对读的人没有意义+ #[test]+ fn a_rule_conclusion_reaches_the_export_as_a_literal() {+ let derived = ExportDerived {+ id: id(7),+ subject_id: id(10),+ predicate_id: id(2),+ object_id: None,+ object_value: Some(serde_json::json!({ "class": "gas_well" })),+ rule_id: None,+ attribute_rule_id: Some(id(9)),+ valid_from: None,+ valid_from_precision: None,+ valid_to: None,+ valid_to_precision: None,+ derived_at: at("2026-02-01T00:00:00Z"),+ invalidated_at: None,+ confidence: 0.9,+ rule: "business".into(),+ rule_name: Some("Gas-bearing well".into()),+ premises: vec![id(5)],+ };+ let quads = export(Format::Turtle, |sink, names, vocab| {+ emit_derived(sink, names, vocab, &derived).unwrap();+ });+ let stmt = "<urn:utopia:kb:01a06dc4-f40a-7013-b09f-1b499e2e7441:derived:07070707-0707-0707-0707-070707070707>";+ // 派生标记还在——它仍旧是推出来的,不是谁断言的+ assert!(has(+ &quads,+ stmt,+ "urn:utopia:ns:derived",+ "\"true\"^^<http://www.w3.org/2001/XMLSchema#boolean>"+ ));+ // 宾语是字面值而不是一个实体 IRI+ let obj = objects(+ &quads,+ stmt,+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#object",+ );+ assert_eq!(obj.len(), 1, "结论要有宾语");+ assert!(+ obj[0].starts_with('"'),+ "字面值结论的宾语该是字面量,拿到的是 {}",+ obj[0]+ );+ // 前提照常挂着:审计顺着 prov:used 走得到那两条读数+ assert_eq!(+ objects(&quads, stmt, "http://www.w3.org/ns/prov#used").len(),+ 1+ );+ // 活动的标签是规则的名字+ let rule_iri =+ "<urn:utopia:kb:01a06dc4-f40a-7013-b09f-1b499e2e7441:rule:09090909-0909-0909-0909-090909090909>";+ assert_eq!(+ objects(+ &quads,+ rule_iri,+ "http://www.w3.org/2000/01/rdf-schema#label"+ ),+ vec!["\"Gas-bearing well\""],+ "推理活动要以规则名示人"+ );+ }+#[test]fn a_derivation_says_it_is_one_and_names_its_premises() {let derived = ExportDerived {id: id(7),subject_id: id(10),predicate_id: id(2),- object_id: id(11),- rule_id: id(8),+ object_id: Some(id(11)),+ object_value: None,+ rule_id: Some(id(8)),+ attribute_rule_id: None,valid_from: None,valid_from_precision: None,valid_to: None,@@ -892,6 +988,7 @@ mod tests {invalidated_at: None,confidence: 0.8,rule: "transitive".into(),+ rule_name: None,premises: vec![id(5)],};let quads = export(Format::Turtle, |sink, names, vocab| {diff --git a/crates/utopia-store/Cargo.toml b/crates/utopia-store/Cargo.tomlindex d02c65f5..fd10e4e9 100644--- a/crates/utopia-store/Cargo.toml+++ b/crates/utopia-store/Cargo.toml@@ -8,6 +8,7 @@ license.workspace = trueutopia-core.workspace = trueutopia-ingest.workspace = trueutopia-reason.workspace = true+serde.workspace = truepgvector.workspace = truecron.workspace = truesqlx.workspace = truediff --git a/crates/utopia-store/src/business_rules.rs b/crates/utopia-store/src/business_rules.rsnew file mode 100644index 00000000..2440d054--- /dev/null+++ b/crates/utopia-store/src/business_rules.rs@@ -0,0 +1,529 @@+//! 业务规则的存取(0021 / #277)。求值在 `utopia-reason::rules`,接进物化在+//! `reasoning::materialize`;这里只管「人写下来的那几条规则怎么进库、怎么取回」。+//!+//! **判据是人写的。** 这个模块没有任何一处由模型生成规则的入口——与 0002 对+//! 公理的态度同一条线。++use serde_json::json;+use sqlx::PgPool;+use utopia_core::{AppError, AppResult};+use uuid::Uuid;++/// 内建 `is_a` 谓词:派生归类的结论落在它上面(0021 决策 2)。+///+/// **按需建,不在建库时铺。** 一个从不写规则的库不该多出一个它看不懂的谓词+/// ——与 #231 给 `metric` / `dimension` 做的选择一致。+pub async fn ensure_is_a(pool: &PgPool, kb_id: Uuid) -> AppResult<Uuid> {+ if let Some((id,)) =+ sqlx::query_as::<_, (Uuid,)>("SELECT id FROM relation_types WHERE kb_id = $1 AND key = $2")+ .bind(kb_id)+ .bind(IS_A)+ .fetch_optional(pool)+ .await?+ {+ return Ok(id);+ }+ let id = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO relation_types (id, kb_id, key, label, kind, datatype, builtin, description)+ VALUES ($1, $2, $3, 'is a', 'attribute', 'text', TRUE, $4)+ ON CONFLICT (kb_id, key) DO NOTHING",+ )+ .bind(id)+ .bind(kb_id)+ .bind(IS_A)+ .bind("A class a rule concluded for this entity. Derived, and it never replaces the asserted type.")+ .execute(pool)+ .await?;+ // ON CONFLICT 命中说明并发建过了,取回那一条+ let (id,): (Uuid,) =+ sqlx::query_as("SELECT id FROM relation_types WHERE kb_id = $1 AND key = $2")+ .bind(kb_id)+ .bind(IS_A)+ .fetch_one(pool)+ .await?;+ Ok(id)+}++pub const IS_A: &str = "is_a";++/// 列表查询回来的一行规则:id、名字、说明、主类及其标签、结论那几列、+/// 开关,以及「此刻凭它成立的结论条数」。+///+/// 起个名字而不是让它当匿名元组:这一行有十三格,读的人对不上位置+type RuleRow = (+ Uuid,+ String,+ String,+ Uuid,+ Option<String>,+ String,+ Option<Uuid>,+ Option<String>,+ Option<Uuid>,+ Option<String>,+ Option<serde_json::Value>,+ bool,+ i64,+);++/// 条件查询回来的一行:规则、属性谓词及其标签、比较方式、操作数+type ConditionRow = (+ Uuid,+ Uuid,+ Option<String>,+ String,+ Option<serde_json::Value>,+);++/// 一条条件,界面与 API 共用的形状。+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+pub struct ConditionInput {+ pub predicate_id: Uuid,+ pub op: String,+ #[serde(default)]+ pub operand: Option<serde_json::Value>,+}++/// 建一条规则。**校验在这里做完**:条件的 op 与操作数形状、谓词必须是属性、+/// 结论的两种形状各自完整——库里的 CHECK 是最后一道,报错信息却是给人看的。+#[allow(clippy::too_many_arguments)]+pub async fn create(+ pool: &PgPool,+ kb_id: Uuid,+ name: &str,+ description: &str,+ subject_type_id: Uuid,+ conclusion: &str,+ conclude_type_id: Option<Uuid>,+ conclude_predicate_id: Option<Uuid>,+ conclude_value: Option<serde_json::Value>,+ conditions: &[ConditionInput],+) -> AppResult<Uuid> {+ let name = name.trim();+ if name.is_empty() || name.chars().count() > 80 {+ return Err(AppError::invalid(+ "bad_rule_name",+ "A rule needs a name of 1-80 characters.",+ ));+ }+ if conditions.is_empty() {+ // 空合取恒真,会把整个类归进去——挡在入口比在求值器里默默不推更早+ return Err(AppError::invalid(+ "no_conditions",+ "A rule needs at least one condition; without one it would conclude for every entity of the class.",+ ));+ }+ 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.",+ ))+ }+ }+ exists(+ pool,+ kb_id,+ "entity_types",+ subject_type_id,+ "unknown_class",+ "That class is not in this base.",+ )+ .await?;++ let id = Uuid::now_v7();+ let mut tx = pool.begin().await?;+ sqlx::query(+ "INSERT INTO attribute_rules+ (id, kb_id, name, description, subject_type_id, conclusion,+ conclude_type_id, conclude_predicate_id, conclude_value)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)",+ )+ .bind(id)+ .bind(kb_id)+ .bind(name)+ .bind(description.trim())+ .bind(subject_type_id)+ .bind(conclusion)+ .bind(conclude_type_id)+ .bind(conclude_predicate_id)+ .bind(&conclude_value)+ .execute(&mut *tx)+ .await+ .map_err(|e| match e {+ sqlx::Error::Database(ref d) if d.is_unique_violation() => AppError::invalid(+ "duplicate_rule",+ "A rule with that name already exists here.",+ ),+ other => AppError::Db(other),+ })?;+ insert_conditions(&mut tx, id, conditions).await?;+ tx.commit().await?;+ Ok(id)+}++/// 改一条规则:条件整组替换。+///+/// **不做逐条的增删改**——条件是一个合取整体,替换比对着 seq 打补丁好读,+/// 也没有「改到一半」的中间状态。+pub async fn update(+ pool: &PgPool,+ kb_id: Uuid,+ rule_id: Uuid,+ name: Option<&str>,+ description: Option<&str>,+ enabled: Option<bool>,+ conditions: Option<&[ConditionInput]>,+) -> AppResult<()> {+ if let Some(cs) = conditions {+ if cs.is_empty() {+ return Err(AppError::invalid(+ "no_conditions",+ "A rule needs at least one condition.",+ ));+ }+ validate_conditions(pool, kb_id, cs).await?;+ }+ let mut tx = pool.begin().await?;+ let res = sqlx::query(+ "UPDATE attribute_rules+ SET name = COALESCE($3, name),+ description = COALESCE($4, description),+ enabled = COALESCE($5, enabled),+ updated_at = now()+ WHERE id = $2 AND kb_id = $1",+ )+ .bind(kb_id)+ .bind(rule_id)+ .bind(name.map(str::trim))+ .bind(description.map(str::trim))+ .bind(enabled)+ .execute(&mut *tx)+ .await?;+ if res.rows_affected() == 0 {+ return Err(AppError::NotFound);+ }+ if let Some(cs) = conditions {+ sqlx::query("DELETE FROM attribute_rule_conditions WHERE rule_id = $1")+ .bind(rule_id)+ .execute(&mut *tx)+ .await?;+ insert_conditions(&mut tx, rule_id, cs).await?;+ }+ tx.commit().await?;+ Ok(())+}++/// 删一条规则。它推出来的派生行随 `ON DELETE CASCADE` 一起走——**规则没了,+/// 凭它得出的结论就没有依据了**,留着无从解释。+pub async fn delete(pool: &PgPool, kb_id: Uuid, rule_id: Uuid) -> AppResult<()> {+ let res = sqlx::query("DELETE FROM attribute_rules WHERE id = $2 AND kb_id = $1")+ .bind(kb_id)+ .bind(rule_id)+ .execute(pool)+ .await?;+ if res.rows_affected() == 0 {+ return Err(AppError::NotFound);+ }+ Ok(())+}++/// 列出规则,连同条件与「现在推出了多少条」。+pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<serde_json::Value>> {+ let rules: Vec<RuleRow> = sqlx::query_as(+ "SELECT r.id, r.name, r.description, r.subject_type_id, st.label,+ r.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)+ FROM attribute_rules r+ JOIN entity_types st ON st.id = r.subject_type_id+ LEFT JOIN entity_types ct ON ct.id = r.conclude_type_id+ LEFT JOIN relation_types cp ON cp.id = r.conclude_predicate_id+ WHERE r.kb_id = $1+ ORDER BY r.created_at",+ )+ .bind(kb_id)+ .fetch_all(pool)+ .await?;+ if rules.is_empty() {+ return Ok(Vec::new());+ }+ let ids: Vec<Uuid> = rules.iter().map(|r| r.0).collect();+ let conds: Vec<ConditionRow> = sqlx::query_as(+ "SELECT c.rule_id, c.predicate_id, p.label, c.op, c.operand+ FROM attribute_rule_conditions c+ JOIN relation_types p ON p.id = c.predicate_id+ WHERE c.rule_id = ANY($1)+ ORDER BY c.rule_id, c.seq",+ )+ .bind(&ids)+ .fetch_all(pool)+ .await?;++ Ok(rules+ .into_iter()+ .map(+ |(+ id,+ name,+ description,+ subject_type_id,+ subject_label,+ conclusion,+ ct,+ ct_label,+ cp,+ cp_label,+ cv,+ enabled,+ derived,+ )| {+ let conditions: Vec<serde_json::Value> = conds+ .iter()+ .filter(|c| c.0 == id)+ .map(|(_, pid, plabel, op, operand)| {+ json!({+ "predicate_id": pid,+ "predicate_label": plabel,+ "op": op,+ "operand": operand,+ })+ })+ .collect();+ json!({+ "id": id,+ "name": name,+ "description": description,+ "subject_type_id": subject_type_id,+ "subject_label": subject_label,+ "conclusion": conclusion,+ "conclude_type_id": ct,+ "conclude_type_label": ct_label,+ "conclude_predicate_id": cp,+ "conclude_predicate_label": cp_label,+ "conclude_value": cv,+ "enabled": enabled,+ "derived_count": derived,+ "conditions": conditions,+ })+ },+ )+ .collect())+}++/// 命中查询回来的一行:派生 id、实体 id 与名字、结论、区间两端、前提的可读形态+type MatchRow = (+ Uuid,+ Uuid,+ String,+ Option<serde_json::Value>,+ Option<chrono::DateTime<chrono::Utc>>,+ Option<chrono::DateTime<chrono::Utc>>,+ Vec<String>,+);++/// 一条规则此刻标了哪些实体。+///+/// **规则卡片上那个数字要点得动**:二十个实体还能一个个点开看,两百个就只能+/// 靠这份列表。前提也带回来——「凭哪几条读数」与结论本身同样是答案的一半。+pub async fn matches(+ pool: &PgPool,+ kb_id: Uuid,+ rule_id: Uuid,+ limit: i64,+ offset: i64,+) -> AppResult<(Vec<serde_json::Value>, i64)> {+ let total: (i64,) = sqlx::query_as(+ "SELECT count(*) FROM derived_facts d+ WHERE d.kb_id = $1 AND d.attribute_rule_id = $2 AND d.invalidated_at IS NULL",+ )+ .bind(kb_id)+ .bind(rule_id)+ .fetch_one(pool)+ .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,+ COALESCE(+ (SELECT array_agg(+ COALESCE(pr.label, '?') || ' = '+ || COALESCE(pf.object_value #>> '{value}', '?')+ ORDER BY fd.seq)+ FROM fact_derivations fd+ JOIN facts pf ON pf.id = fd.premise_fact_id+ LEFT JOIN relation_types pr ON pr.id = pf.predicate_id+ WHERE fd.derived_fact_id = d.id),+ ARRAY[]::text[]+ )+ FROM derived_facts d+ JOIN entities e ON e.id = d.subject_id+ WHERE d.kb_id = $1 AND d.attribute_rule_id = $2 AND d.invalidated_at IS NULL+ ORDER BY e.canonical_name+ LIMIT $3 OFFSET $4",+ )+ .bind(kb_id)+ .bind(rule_id)+ .bind(limit)+ .bind(offset)+ .fetch_all(pool)+ .await?;++ Ok((+ rows.into_iter()+ .map(|(id, entity_id, name, value, 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(),+ "valid_from": from,+ "valid_to": to,+ "premises": premises,+ })+ })+ .collect(),+ total.0,+ ))+}++async fn insert_conditions(+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,+ rule_id: Uuid,+ conditions: &[ConditionInput],+) -> AppResult<()> {+ for (seq, c) in conditions.iter().enumerate() {+ sqlx::query(+ "INSERT INTO attribute_rule_conditions (id, rule_id, seq, predicate_id, op, operand)+ VALUES ($1, $2, $3, $4, $5, $6)",+ )+ .bind(Uuid::now_v7())+ .bind(rule_id)+ .bind(seq as i32)+ .bind(c.predicate_id)+ .bind(&c.op)+ .bind(&c.operand)+ .execute(&mut **tx)+ .await?;+ }+ Ok(())+}++/// 条件的校验。**报错要说人话**:库里的 CHECK 只会回一个约束名。+async fn validate_conditions(+ pool: &PgPool,+ kb_id: Uuid,+ conditions: &[ConditionInput],+) -> AppResult<()> {+ for c in conditions {+ let op = utopia_reason::rules::Op::parse(&c.op).ok_or_else(|| {+ AppError::invalid(+ "bad_op",+ "A condition compares with >, >=, <, <=, a range, a set, or presence.",+ )+ })?;+ attribute_predicate(pool, kb_id, c.predicate_id).await?;+ let shaped = match op {+ utopia_reason::rules::Op::Present => c.operand.is_none(),+ utopia_reason::rules::Op::Between => c+ .operand+ .as_ref()+ .and_then(|v| v.as_array())+ .is_some_and(|a| a.len() == 2 && a.iter().all(|x| x.as_f64().is_some())),+ utopia_reason::rules::Op::In => c+ .operand+ .as_ref()+ .and_then(|v| v.as_array())+ .is_some_and(|a| !a.is_empty()),+ _ => c.operand.as_ref().is_some_and(|v| {+ v.as_f64().is_some()+ || v.as_str()+ .and_then(|s| s.trim().parse::<f64>().ok())+ .is_some()+ }),+ };+ if !shaped {+ return Err(AppError::invalid(+ "bad_operand",+ "That comparison does not match the value it was given: a threshold needs a number, a range needs two, a set needs at least one entry, and presence takes none.",+ ));+ }+ }+ Ok(())+}++/// 条件与属性结论只能落在 kind='attribute' 的谓词上——规则读的是这个实体+/// 自己的字面值,关系(实体到实体)不参与(0021 决策 3)。+async fn attribute_predicate(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<()> {+ let row: Option<(String,)> =+ sqlx::query_as("SELECT kind FROM relation_types WHERE id = $2 AND kb_id = $1")+ .bind(kb_id)+ .bind(id)+ .fetch_optional(pool)+ .await?;+ match row.as_ref().map(|(k,)| k.as_str()) {+ Some("attribute") => Ok(()),+ Some(_) => Err(AppError::invalid(+ "not_an_attribute",+ "A rule reads this entity's own attributes; a relation to another entity cannot be a condition.",+ )),+ None => Err(AppError::invalid(+ "unknown_predicate",+ "That attribute is not in this base.",+ )),+ }+}++async fn exists(+ pool: &PgPool,+ kb_id: Uuid,+ table: &str,+ id: Uuid,+ code: &'static str,+ message: &'static str,+) -> AppResult<()> {+ let sql = format!("SELECT 1 FROM {table} WHERE id = $2 AND kb_id = $1");+ let row: Option<(i32,)> = sqlx::query_as(&sql)+ .bind(kb_id)+ .bind(id)+ .fetch_optional(pool)+ .await?;+ row.map(|_| ())+ .ok_or_else(|| AppError::invalid(code, message))+}diff --git a/crates/utopia-store/src/export.rs b/crates/utopia-store/src/export.rsindex 70bc1fdb..ab12690e 100644--- a/crates/utopia-store/src/export.rs+++ b/crates/utopia-store/src/export.rs@@ -84,8 +84,12 @@ pub struct ExportDerived {pub id: Uuid,pub subject_id: Uuid,pub predicate_id: Uuid,- pub object_id: Uuid,- pub rule_id: Uuid,+ /// 字面值结论(业务规则的归类与属性)没有实体宾语(0021)+ pub object_id: Option<Uuid>,+ pub object_value: Option<serde_json::Value>,+ /// 公理规则。业务规则推的为 None——它的身份在 attribute_rule_id 上+ pub rule_id: Option<Uuid>,+ pub attribute_rule_id: Option<Uuid>,pub valid_from: Option<DateTime<Utc>>,pub valid_from_precision: Option<String>,pub valid_to: Option<DateTime<Utc>>,@@ -93,8 +97,10 @@ pub struct ExportDerived {pub derived_at: DateTime<Utc>,pub invalidated_at: Option<DateTime<Utc>>,pub confidence: f32,- /// transitive | symmetric+ /// transitive | symmetric | inverse | sub_property,或 businesspub rule: String,+ /// 业务规则的名字,进 RDF 当这条推理活动的标签+ pub rule_name: Option<String>,/// 前提事实。审计要顺着它往下走到句子pub premises: Vec<Uuid>,}@@ -196,13 +202,19 @@ pub async fn derived_page(after: Option<Uuid>,) -> AppResult<Vec<ExportDerived>> {Ok(sqlx::query_as(- "SELECT d.id, d.subject_id, d.predicate_id, d.object_id, d.rule_id,+ // **两个 LEFT JOIN。** 表拓宽之后(0021)派生可能没有实体宾语、+ // 也可能来自业务规则而不是公理——内连接会把这类结论整条挡在导出之外,+ // 而 0020 承诺的正是「审计员不靠我们也能读全」+ "SELECT d.id, d.subject_id, d.predicate_id, d.object_id, d.object_value,+ d.rule_id, d.attribute_rule_id,d.valid_from, d.valid_from_precision, d.valid_to, d.valid_to_precision,d.derived_at, d.invalidated_at, d.confidence,- ru.kind AS rule,+ COALESCE(ru.kind, 'business') AS rule, ar.name AS rule_name,COALESCE(ARRAY(SELECT fd.premise_fact_id FROM fact_derivations fdWHERE fd.derived_fact_id = d.id ORDER BY fd.seq), '{}') AS premises- FROM derived_facts d JOIN rules ru ON ru.id = d.rule_id+ FROM derived_facts d+ LEFT JOIN rules ru ON ru.id = d.rule_id+ LEFT JOIN attribute_rules ar ON ar.id = d.attribute_rule_idWHERE d.kb_id = $1 AND d.id > COALESCE($2, '00000000-0000-0000-0000-000000000000'::uuid)ORDER BY d.id LIMIT $3",)diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rsindex bb628c76..c2a15fd7 100644--- a/crates/utopia-store/src/graph.rs+++ b/crates/utopia-store/src/graph.rs@@ -421,10 +421,13 @@ pub async fn overview(.fetch_one(pool).await?;let total_edges: i64 = sqlx::query_scalar(&format!(+ // 两边都要 `object_id IS NOT NULL`:数的是**画得出来的边**。派生表拓宽+ // 之后(0021)字面值结论也住在这张表里,把它们数进来,状态栏报的边数+ // 就比画布上多——而多出来的那些永远找不到"SELECT (SELECT count(*) FROM facts fWHERE f.kb_id = $1 AND {facts_held} AND f.object_id IS NOT NULL)+ (SELECT count(*) FROM derived_facts d- WHERE d.kb_id = $1 AND {derived_held})",+ WHERE d.kb_id = $1 AND {derived_held} AND d.object_id IS NOT NULL)",facts_held = crate::record_axis::facts_held_at("f", 2),derived_held = crate::record_axis::derived_held_at("d", 2),))diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rsindex 6713cee2..04918587 100644--- a/crates/utopia-store/src/lib.rs+++ b/crates/utopia-store/src/lib.rs@@ -5,6 +5,7 @@ pub mod access;pub mod accounts;pub mod alerts;pub mod audit;+pub mod business_rules;pub mod conversations;pub mod datasources;pub mod db;diff --git a/crates/utopia-store/src/reasoning.rs b/crates/utopia-store/src/reasoning.rsindex 755a3bff..966fa9fd 100644--- a/crates/utopia-store/src/reasoning.rs+++ b/crates/utopia-store/src/reasoning.rs@@ -824,6 +824,12 @@ pub struct DeriveReport {/// 推出来了却撞上断言或别的派生、这一轮拦下没落的(0017)。**拦下的每一条/// 都在 Review 里有对应的一行**——`run` 与这里用同一个函数算pub blocked: usize,+ /// 参与求值的业务规则条数(0021)+ pub attribute_rules: usize,+ /// 业务规则命中数+ pub rule_hits: usize,+ /// 前提组合太多、没展开完的 (规则, 实体) 对数。**与「不满足」区分开报**+ pub rule_capped: usize,}/// 一次取数,三样东西:带区间的边、每条事实的区间、精度与置信度。@@ -901,11 +907,47 @@ async fn accepted_clashes(.collect())}-/// 派生事实的身份:三元组 + 区间。+/// 派生事实的身份:主 + 谓 + 宾 + 区间。////// **区间进键**是有意的:区间变了就是另一条断言,老的作废、新的落地,/// 因为账本不许原地改。-type DerivedKey = (Uuid, Uuid, Uuid, Option<i64>, Option<i64>);+///+/// 宾语两格,与 `derived_facts` 拓宽后的两条通道一一对应(0021 决策 1):实体宾语+/// 走 `Option<Uuid>`,字面值结论走那串规范化过的 JSON。两格都参与比较——否则+/// 同一个类上的两条不同结论会被认成同一条。+type DerivedKey = (+ Uuid,+ Uuid,+ Option<Uuid>,+ Option<String>,+ Option<i64>,+ Option<i64>,+);++/// 这一轮要落库的一条派生。公理推出来的与规则推出来的在这里合流——+/// **合流是必须的**:陈旧行的对账扫的是整张表,两趟各做各的 diff 会把对方的+/// 行每轮都判成陈旧作废掉。+struct Wanted {+ subject: Uuid,+ predicate: Uuid,+ object_id: Option<Uuid>,+ object_value: Option<serde_json::Value>,+ from: Option<i64>,+ to: Option<i64>,+ premises: Vec<Uuid>,+ /// 公理规则(`rules.id`)或业务规则(`attribute_rules.id`),恰好一个+ rule_id: Option<Uuid>,+ attribute_rule_id: Option<Uuid>,+}++/// JSON 值的规范化文本形态,只用来做键。+///+/// `serde_json::Value` 自己不是 `Hash`,而键里必须带上字面值宾语;序列化成+/// 字符串是最省事且稳定的做法——`Map` 在 serde_json 默认是 `BTreeMap`,+/// 同样的内容序列化出来逐字节相同。+fn value_key(v: Option<&serde_json::Value>) -> Option<String> {+ v.map(|v| v.to_string())+}/// 精度按「最粗的那个」取。///@@ -998,13 +1040,255 @@ type EdgeRow = (type LiveRow = (Uuid,+ Uuid,+ Uuid,+ Option<Uuid>,+ Option<serde_json::Value>,+ Option<chrono::DateTime<chrono::Utc>>,+ Option<chrono::DateTime<chrono::Utc>>,+);++/// 一条业务规则连同它的条件,已经解析成求值器的形状。+struct LoadedRule {+ rule: utopia_reason::rules::BusinessRule,+ /// 规则只看这个类**及其子类**的实体+ subject_types: Vec<Uuid>,+ /// 结论落在哪个谓词上:归类落 `is_a`,属性落它自己那个+ conclude_predicate: Uuid,+}++/// 求值要用的一行规则:id、主类、结论种类、结论那三格,外加结论类的 IRI 与 key+/// (归类结论按 IRI 记,没有才退回 key)+type RuleDefRow = (+ Uuid,+ Uuid,+ String,+ Option<Uuid>,+ Option<Uuid>,+ Option<serde_json::Value>,+ Option<String>,+ Option<String>,+);++/// 取业务规则。条件形状不合法的规则**整条跳过而不是报错退出**——一条写坏的+/// 规则不该让整轮物化停摆,而它不产出这件事在报告的条数里看得见。+async fn attribute_rules(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<LoadedRule>> {+ use utopia_reason::rules::{BusinessRule, Conclusion, Condition, Op};++ let rows: Vec<RuleDefRow> = sqlx::query_as(+ "SELECT r.id, r.subject_type_id, r.conclusion,+ r.conclude_type_id, r.conclude_predicate_id, r.conclude_value,+ ct.iri, ct.key+ FROM attribute_rules r+ LEFT JOIN entity_types ct ON ct.id = r.conclude_type_id+ WHERE r.kb_id = $1 AND r.enabled",+ )+ .bind(kb_id)+ .fetch_all(pool)+ .await?;+ if rows.is_empty() {+ return Ok(Vec::new());+ }++ // 归类结论要落在内建 `is_a` 上。规则存在就意味着它已经被建出来了+ // (建规则那一步负责),这里取不到就说明库被手改过——跳过而不是造一个+ let is_a: Option<(Uuid,)> =+ sqlx::query_as("SELECT id FROM relation_types WHERE kb_id = $1 AND key = 'is_a'")+ .bind(kb_id)+ .fetch_optional(pool)+ .await?;++ let ids: Vec<Uuid> = rows.iter().map(|r| r.0).collect();+ let conds: Vec<(Uuid, Uuid, String, Option<serde_json::Value>)> = sqlx::query_as(+ "SELECT rule_id, predicate_id, op, operand+ FROM attribute_rule_conditions+ WHERE rule_id = ANY($1)+ ORDER BY rule_id, seq",+ )+ .bind(&ids)+ .fetch_all(pool)+ .await?;+ let mut by_rule: HashMap<Uuid, Vec<Condition>> = HashMap::new();+ let mut broken: HashSet<Uuid> = HashSet::new();+ for (rule_id, predicate, op, operand) in conds {+ let Some(op) = Op::parse(&op) else {+ broken.insert(rule_id);+ continue;+ };+ let Some(operand) = parse_operand(op, operand.as_ref()) else {+ broken.insert(rule_id);+ continue;+ };+ by_rule.entry(rule_id).or_default().push(Condition {+ predicate,+ op,+ operand,+ });+ }++ let mut out = Vec::new();+ for (id, subject_type, conclusion, conclude_type, conclude_pred, conclude_value, iri, key) in+ rows+ {+ if broken.contains(&id) {+ continue;+ }+ let Some(conditions) = by_rule.remove(&id) else {+ // 一条没有条件的规则什么都不推(求值器也这么判),不必往下走+ continue;+ };+ let (conclusion, predicate) = match conclusion.as_str() {+ "typing" => {+ let (Some(_), Some((is_a,))) = (conclude_type, is_a) else {+ continue;+ };+ // **按 IRI 记,没有 IRI 才退回 key**:改标签不该让已推出的结论+ // 变成另一条(0021 决策 2)+ let Some(class) = iri.or(key) else { continue };+ (Conclusion::Typing { class }, is_a)+ }+ "attribute" => {+ let (Some(p), Some(v)) = (conclude_pred, conclude_value) else {+ continue;+ };+ (+ Conclusion::Attribute {+ predicate: p,+ value: v,+ },+ p,+ )+ }+ _ => continue,+ };+ let subject_types = descendants_of(pool, kb_id, subject_type).await?;+ out.push(LoadedRule {+ rule: BusinessRule {+ id,+ conclusion,+ conditions,+ },+ subject_types,+ conclude_predicate: predicate,+ });+ }+ Ok(out)+}++/// 操作数按 op 解析。形状不对返回 None,调用方整条规则跳过。+fn parse_operand(+ op: utopia_reason::rules::Op,+ raw: Option<&serde_json::Value>,+) -> Option<utopia_reason::rules::Operand> {+ use utopia_reason::rules::{Op, Operand};+ match op {+ Op::Present => Some(Operand::None),+ Op::Between => {+ let arr = raw?.as_array()?;+ let (lo, hi) = (arr.first()?.as_f64()?, arr.get(1)?.as_f64()?);+ Some(Operand::Range(lo.min(hi), lo.max(hi)))+ }+ Op::In => {+ let arr = raw?.as_array()?;+ let set: Vec<String> = arr+ .iter()+ .map(|v| match v {+ serde_json::Value::String(s) => s.trim().to_string(),+ other => other.to_string(),+ })+ .collect();+ (!set.is_empty()).then_some(Operand::Set(set))+ }+ _ => Some(Operand::Num(raw?.as_f64().or_else(|| {+ raw.and_then(|v| v.as_str())+ .and_then(|s| s.trim().parse().ok())+ })?)),+ }+}++/// 一个类连同它的全部子类。规则写在 `Well` 上,`HorizontalWell` 的实体也该被看。+async fn descendants_of(pool: &PgPool, kb_id: Uuid, root: Uuid) -> AppResult<Vec<Uuid>> {+ let rows: Vec<(Uuid,)> = sqlx::query_as(+ "WITH RECURSIVE sub AS (+ SELECT id FROM entity_types WHERE id = $2 AND kb_id = $1+ UNION+ SELECT p.child_id FROM entity_type_parents p JOIN sub ON p.parent_id = sub.id+ )+ SELECT id FROM sub",+ )+ .bind(kb_id)+ .bind(root)+ .fetch_all(pool)+ .await?;+ Ok(rows.into_iter().map(|(id,)| id).collect())+}++/// 属性事实查询回来的一行:事实、主语、谓词、字面值、区间两端与精度、置信度,+/// 以及主语当下的断言类型(规则要按主类过滤)+type AttrFactRow = (Uuid,Uuid,Uuid,+ serde_json::Value,Option<chrono::DateTime<chrono::Utc>>,Option<chrono::DateTime<chrono::Utc>>,+ Option<String>,+ Option<String>,+ f32,+ Option<Uuid>,);+/// 属性事实:字面值通道上的活事实,连同区间与精度。+///+/// 与 `timed_edges` 是对偶的一份——那边取 `object_id IS NOT NULL` 的边,+/// 这边取 `object_value IS NOT NULL` 的字面值。两边都只看断言。+async fn attribute_facts(+ pool: &PgPool,+ kb_id: Uuid,+) -> AppResult<(+ Vec<utopia_reason::rules::AttrFact>,+ HashMap<Uuid, (Option<i64>, Option<i64>)>,+ HashMap<Uuid, (Option<String>, Option<String>, f32)>,+ HashMap<Uuid, Option<Uuid>>,+)> {+ let rows: Vec<AttrFactRow> = sqlx::query_as(+ "SELECT f.id, f.subject_id, f.predicate_id, f.object_value,+ f.valid_from, f.valid_to, f.valid_from_precision, f.valid_to_precision,+ f.confidence, e.type_id+ FROM facts f+ JOIN entities e ON e.id = f.subject_id+ WHERE f.kb_id = $1+ AND f.invalidated_at IS NULL+ AND f.predicate_id IS NOT NULL+ AND f.object_value IS NOT NULL+ AND e.merged_into IS NULL",+ )+ .bind(kb_id)+ .fetch_all(pool)+ .await?;++ let mut facts = Vec::with_capacity(rows.len());+ let mut spans = HashMap::new();+ let mut meta = HashMap::new();+ let mut type_of = HashMap::new();+ for (id, subject, predicate, value, from, to, fp, tp, conf, type_id) in rows {+ let (f, t) = (from.map(|x| x.timestamp()), to.map(|x| x.timestamp()));+ // 属性事实的字面值是 `{"value": …, "unit": …}`;比较的是里面那个 value。+ // 取不到就把整个对象交给求值器——它对认不出的形状一律判不满足+ let inner = value.get("value").cloned().unwrap_or_else(|| value.clone());+ facts.push(utopia_reason::rules::AttrFact {+ id,+ subject,+ predicate,+ value: inner,+ });+ spans.insert(id, (f, t));+ meta.insert(id, (fp, tp, conf));+ type_of.insert(subject, type_id);+ }+ Ok((facts, spans, meta, type_of))+}+/// 推一遍,把派生事实落进账本。////// **调用方负责检查 `materialize_inferences` 开关。** 这一层不判——它也被@@ -1012,7 +1296,7 @@ type LiveRow = (pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport> {let ax = axioms(pool, kb_id).await?;let rules = compile_rules(pool, kb_id, &ax).await?;- let (edges, spans, meta) = timed_edges(pool, kb_id).await?;+ let (edges, spans, mut meta) = timed_edges(pool, kb_id).await?;let derivation = utopia_reason::derive::derive(&edges, &ax);// asserted > derived 是硬性的(0002):撞上断言的派生不落地。人认可过并存的@@ -1032,6 +1316,7 @@ pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport>blocked.insert(*j);}}+let mut report = DeriveReport {rules: rules.len(),edges: edges.len(),@@ -1041,7 +1326,7 @@ pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport>..Default::default()};- let mut wanted: HashMap<DerivedKey, &utopia_reason::derive::Derived> = HashMap::new();+ let mut wanted: HashMap<DerivedKey, Wanted> = HashMap::new();for (i, d) in derivation.facts.iter().enumerate() {if blocked.contains(&i) {continue;@@ -1049,12 +1334,97 @@ pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport>let Some((from, to)) = utopia_reason::derive::validity(&d.premises, &spans) else {continue;};- wanted.insert((d.subject, d.predicate, d.object, from, to), d);+ // **按 `via` 查,不是 `predicate`。** 规则行是给「声明了公理的那个+ // 谓词」编的;跨谓词的两条规则里,派生出来的谓词是另一个+ let Some(&rule_id) = rules.get(&(d.via, d.rule.as_str())) else {+ // 查不到规则是**编译与推导不一致**,不是正常情况。数出来,+ // 别再让它静默消失一次+ report.unruled += 1;+ continue;+ };+ wanted.insert(+ (d.subject, d.predicate, Some(d.object), None, from, to),+ Wanted {+ subject: d.subject,+ predicate: d.predicate,+ object_id: Some(d.object),+ object_value: None,+ from,+ to,+ premises: d.premises.clone(),+ rule_id: Some(rule_id),+ attribute_rule_id: None,+ },+ );+ }++ // 第二趟:属性事实上的业务规则(0021)。**并进同一个 `wanted`**——+ // 下面的陈旧对账扫的是整张 `derived_facts`,两趟各做各的 diff 会把对方+ // 落的行每一轮都判成陈旧+ let loaded = attribute_rules(pool, kb_id).await?;+ report.attribute_rules = loaded.len();+ if !loaded.is_empty() {+ let (attr_facts, attr_spans, attr_meta, type_of) = attribute_facts(pool, kb_id).await?;+ for lr in &loaded {+ // 规则只看自己主类(含子类)的实体+ let scoped: Vec<utopia_reason::rules::AttrFact> = attr_facts+ .iter()+ .filter(|f| {+ type_of+ .get(&f.subject)+ .and_then(|t| *t)+ .is_some_and(|t| lr.subject_types.contains(&t))+ })+ .cloned()+ .collect();+ let (hits, rr) = utopia_reason::rules::evaluate(+ std::slice::from_ref(&lr.rule),+ &scoped,+ &attr_spans,+ );+ report.rule_hits += rr.hits;+ // 是「这一轮算出来的派生总数」,公理与规则都算在内。+ // **别改写它的原义**:被拦下的那些也算「算出来了」,队列里那一行+ // 正是凭它对上的+ report.derived += rr.hits;+ report.rule_capped += rr.capped;+ for h in hits {+ let value = match &lr.rule.conclusion {+ utopia_reason::rules::Conclusion::Typing { class } => {+ serde_json::json!({ "class": class })+ }+ utopia_reason::rules::Conclusion::Attribute { value, .. } => {+ serde_json::json!({ "value": value })+ }+ };+ let key = (+ h.subject,+ lr.conclude_predicate,+ None,+ value_key(Some(&value)),+ h.from,+ h.to,+ );+ wanted.entry(key).or_insert(Wanted {+ subject: h.subject,+ predicate: lr.conclude_predicate,+ object_id: None,+ object_value: Some(value),+ from: h.from,+ to: h.to,+ premises: h.premises,+ rule_id: None,+ attribute_rule_id: Some(lr.rule.id),+ });+ }+ }+ // 前提的精度与置信度:两趟共用下面那段,所以两份 meta 也要合起来+ meta.extend(attr_meta);}let mut tx = pool.begin().await?;let live: Vec<LiveRow> = sqlx::query_as(- "SELECT id, subject_id, predicate_id, object_id, valid_from, valid_to+ "SELECT id, subject_id, predicate_id, object_id, object_value, valid_from, valid_toFROM derived_factsWHERE kb_id = $1 AND invalidated_at IS NULL",)@@ -1063,11 +1433,12 @@ pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport>.await?;let mut stale: Vec<Uuid> = Vec::new();- for (id, s, p, o, from, to) in &live {+ for (id, s, p, o, ov, from, to) in &live {let key = (*s,*p,*o,+ value_key(ov.as_ref()),from.map(|x| x.timestamp()),to.map(|x| x.timestamp()),);@@ -1087,17 +1458,7 @@ pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport>report.invalidated = stale.len();}- for ((subject, predicate, object, from, to), d) in wanted {- // **按 `via` 查,不是 `predicate`。** 规则行是给「声明了公理的那个- // 谓词」编的;跨谓词的两条规则里,派生出来的谓词是另一个。- // 原先按 predicate 查,前两条规则一直对(两者相同),加了 inverse /- // sub_property 之后查不到规则就 `continue`——推出来了却不落库- let Some(&rule_id) = rules.get(&(d.via, d.rule.as_str())) else {- // 查不到规则是**编译与推导不一致**,不是正常情况。数出来,- // 别再让它静默消失一次- report.unruled += 1;- continue;- };+ for (_, d) in wanted {// 精度与置信度都取前提里最保守的那一个let mut fp: Option<String> = None;let mut tp: Option<String> = None;@@ -1110,27 +1471,29 @@ pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport>}}// 约束是「有日期才有精度」——交集把某一端算成无界时,那一端的精度也得清掉- let fp = from.and(fp);- let tp = to.and(tp);+ let fp = d.from.and(fp);+ let tp = d.to.and(tp);let id = Uuid::now_v7();sqlx::query("INSERT INTO derived_facts (id, kb_id, subject_id, predicate_id, object_id,- valid_from, valid_to,+ object_value, valid_from, valid_to,valid_from_precision, valid_to_precision,- confidence, rule_id)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)",+ confidence, rule_id, attribute_rule_id)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)",).bind(id).bind(kb_id)- .bind(subject)- .bind(predicate)- .bind(object)- .bind(from.map(stamp))- .bind(to.map(stamp))+ .bind(d.subject)+ .bind(d.predicate)+ .bind(d.object_id)+ .bind(&d.object_value)+ .bind(d.from.map(stamp))+ .bind(d.to.map(stamp)).bind(&fp).bind(&tp).bind(conf)- .bind(rule_id)+ .bind(d.rule_id)+ .bind(d.attribute_rule_id).execute(&mut *tx).await?;for (seq, premise) in d.premises.iter().enumerate() {@@ -1415,15 +1778,22 @@ async fn derived_one(Ok(sqlx::query_as("SELECT d.id,d.subject_id, s.canonical_name AS subject,- d.object_id, o.canonical_name AS object,+ d.object_id,+ COALESCE(o.canonical_name, ct.label,+ d.object_value ->> 'class',+ d.object_value #>> '{value}',+ d.object_value #>> '{}') AS object,r.label AS predicate,- ru.kind AS rule,+ COALESCE(ru.kind, 'business') AS rule,+ ar.name AS rule_name,d.valid_from, d.valid_to, d.confidence, d.derived_at,COALESCE((SELECT array_agg(ps.canonical_name || ' · '|| COALESCE(pr.label, '?') || ' · '- || COALESCE(po.canonical_name, '?')+ || COALESCE(po.canonical_name,+ pf.object_value #>> '{value}',+ '?')ORDER BY fd.seq)FROM fact_derivations fdJOIN facts pf ON pf.id = fd.premise_fact_id@@ -1435,9 +1805,11 @@ async fn derived_one() AS premisesFROM derived_facts dJOIN entities s ON s.id = d.subject_id- JOIN entities o ON o.id = d.object_id+ LEFT JOIN entities o ON o.id = d.object_idJOIN relation_types r ON r.id = d.predicate_id- JOIN rules ru ON ru.id = d.rule_id+ LEFT JOIN rules ru ON ru.id = d.rule_id+ LEFT 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.id = $2",).bind(kb_id)@@ -1455,18 +1827,31 @@ pub async fn derived_for_entity(kb_id: Uuid,entity_id: Uuid,) -> AppResult<Vec<DerivedFactView>> {+ // **宾语与规则两侧都是 LEFT JOIN。** 表拓宽之后(0021)一条派生的宾语可能+ // 是字面值而不是实体,规则可能是业务规则而不是公理——内连接会把这两种+ // 结论**静默地**从面板上抹掉,而它们恰恰是最需要解释的那种。+ //+ // 宾语的显示文本因此有三个来源:实体名、归类结论里的类标签、属性结论的值。Ok(sqlx::query_as("SELECT d.id,d.subject_id, s.canonical_name AS subject,- d.object_id, o.canonical_name AS object,+ d.object_id,+ COALESCE(o.canonical_name,+ ct.label,+ d.object_value ->> 'class',+ d.object_value #>> '{value}',+ d.object_value #>> '{}') AS object,r.label AS predicate,- ru.kind AS rule,+ COALESCE(ru.kind, 'business') AS rule,+ ar.name AS rule_name,d.valid_from, d.valid_to, d.confidence, d.derived_at,COALESCE((SELECT array_agg(ps.canonical_name || ' · '|| COALESCE(pr.label, '?') || ' · '- || COALESCE(po.canonical_name, '?')+ || COALESCE(po.canonical_name,+ pf.object_value #>> '{value}',+ '?')ORDER BY fd.seq)FROM fact_derivations fdJOIN facts pf ON pf.id = fd.premise_fact_id@@ -1478,9 +1863,11 @@ pub async fn derived_for_entity() AS premisesFROM derived_facts dJOIN entities s ON s.id = d.subject_id- JOIN entities o ON o.id = d.object_id+ LEFT JOIN entities o ON o.id = d.object_idJOIN relation_types r ON r.id = d.predicate_id- JOIN rules ru ON ru.id = d.rule_id+ LEFT JOIN rules ru ON ru.id = d.rule_id+ LEFT 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.invalidated_at IS NULLAND (d.subject_id = $2 OR d.object_id = $2)ORDER BY d.derived_at DESC",diff --git a/crates/utopia-store/tests/a_proof_reaches_the_sentence.rs b/crates/utopia-store/tests/a_proof_reaches_the_sentence.rsindex 231c0350..ddb46080 100644--- a/crates/utopia-store/tests/a_proof_reaches_the_sentence.rs+++ b/crates/utopia-store/tests/a_proof_reaches_the_sentence.rs@@ -189,7 +189,7 @@ async fn a_proof_reaches_the_sentence() -> anyhow::Result<()> {reasoning::derived_for_entity(&pool, f.kb, f.a).await?;let ac = derived.iter()- .find(|d| d.subject_id == f.a && d.object_id == f.c)+ .find(|d| d.subject_id == f.a && d.object_id == Some(f.c)).expect("A part_of C should be derived");// 1. 顺序对,2. 叶子是原句diff --git a/crates/utopia-store/tests/a_rule_concludes_a_type.rs b/crates/utopia-store/tests/a_rule_concludes_a_type.rsnew file mode 100644index 00000000..a1f73373--- /dev/null+++ b/crates/utopia-store/tests/a_rule_concludes_a_type.rs@@ -0,0 +1,459 @@+//! 业务规则打在真库上(0021 / #277)。+//!+//! 求值本身的用例在 `utopia-reason::rules`,纯逻辑、不起库。这里钉的是那一层+//! 看不见的四样:+//!+//! - 命中真的落进 `derived_facts` 的**字面值通道**,并挂着 `attribute_rule_id`+//! - 前提链进 `fact_derivations`——「这口井凭哪两条读数」+//! - **重跑不产生第二行**:同一性索引把 NULL 宾语认成同一条(这是拓宽表时+//! 最容易漏的一处,漏了就是每轮多一行)+//! - 阈值抬高后重跑,旧结论**作废而不是删除**,记录轴上留着「曾据此推出」+//!+//! 还钉一条与公理那一趟的相处:两趟合流进同一次对账,谁也不该把对方的行+//! 判成陈旧。++use sqlx::PgPool;+use uuid::Uuid;++struct Fixture {+ org: Uuid,+ kb: Uuid,+ well: Uuid,+ gas_bearing: Uuid,+ thc: Uuid,+ category: Uuid,+ is_a: Uuid,+ w1: Uuid,+}++async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ let (well, gas_bearing) = (Uuid::now_v7(), Uuid::now_v7());+ let (thc, category, is_a) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ let w1 = Uuid::now_v7();++ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'rule-test')")+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'rule-test')")+ .bind(ws)+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'rule-test')",+ )+ .bind(kb)+ .bind(ws)+ .execute(pool)+ .await?;+ for (id, key, label) in [+ (well, "well", "Well"),+ (gas_bearing, "gas_well", "GasBearingWell"),+ ] {+ sqlx::query("INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, $3, $4)")+ .bind(id)+ .bind(kb)+ .bind(key)+ .bind(label)+ .execute(pool)+ .await?;+ }+ // 两个属性谓词 + 内建 is_a+ for (id, key, label, datatype) in [+ (thc, "total_hydrocarbon", "全烃", "number"),+ (category, "interpretation_category", "解释结论", "text"),+ (is_a, "is_a", "is a", "text"),+ ] {+ sqlx::query(+ "INSERT INTO relation_types (id, kb_id, key, label, kind, datatype, builtin)+ VALUES ($1, $2, $3, $4, 'attribute', $5, $6)",+ )+ .bind(id)+ .bind(kb)+ .bind(key)+ .bind(label)+ .bind(datatype)+ .bind(key == "is_a")+ .execute(pool)+ .await?;+ }+ sqlx::query(+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, 'W-1')",+ )+ .bind(w1)+ .bind(kb)+ .bind(well)+ .execute(pool)+ .await?;+ Ok(Fixture {+ org,+ kb,+ well,+ gas_bearing,+ thc,+ category,+ is_a,+ w1,+ })+}++/// 一条属性事实。+async fn attr(+ pool: &PgPool,+ f: &Fixture,+ predicate: Uuid,+ value: serde_json::Value,+ from: &str,+) -> anyhow::Result<Uuid> {+ let id = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_value,+ valid_from, valid_from_precision, confidence)+ VALUES ($1, $2, $3, $4, $5, $6, 'day', 0.9)",+ )+ .bind(id)+ .bind(f.kb)+ .bind(f.w1)+ .bind(predicate)+ .bind(serde_json::json!({ "value": value }))+ .bind(from.parse::<chrono::DateTime<chrono::Utc>>()?)+ .execute(pool)+ .await?;+ Ok(id)+}++/// 一条规则:全烃 > 阈值 且 解释结论 ∈ {气测异常, 气测异常后效} → GasBearingWell+async fn rule(pool: &PgPool, f: &Fixture, threshold: f64) -> anyhow::Result<Uuid> {+ let id = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO attribute_rules (id, kb_id, name, subject_type_id, conclusion, conclude_type_id)+ VALUES ($1, $2, 'gas-bearing', $3, 'typing', $4)",+ )+ .bind(id)+ .bind(f.kb)+ .bind(f.well)+ .bind(f.gas_bearing)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO attribute_rule_conditions (id, rule_id, seq, predicate_id, op, operand)+ VALUES ($1, $2, 0, $3, 'gt', $4), ($5, $2, 1, $6, 'in', $7)",+ )+ .bind(Uuid::now_v7())+ .bind(id)+ .bind(f.thc)+ .bind(serde_json::json!(threshold))+ .bind(Uuid::now_v7())+ .bind(f.category)+ .bind(serde_json::json!(["气测异常", "气测异常后效"]))+ .execute(pool)+ .await?;+ Ok(id)+}++#[derive(sqlx::FromRow)]+struct Derived {+ id: Uuid,+ object_value: Option<serde_json::Value>,+ object_id: Option<Uuid>,+ attribute_rule_id: Option<Uuid>,+ valid_from: Option<chrono::DateTime<chrono::Utc>>,+ invalidated_at: Option<chrono::DateTime<chrono::Utc>>,+}++async fn derived(pool: &PgPool, f: &Fixture) -> anyhow::Result<Vec<Derived>> {+ Ok(sqlx::query_as(+ "SELECT id, object_value, object_id, attribute_rule_id, valid_from, invalidated_at+ FROM derived_facts WHERE kb_id = $1 ORDER BY derived_at",+ )+ .bind(f.kb)+ .fetch_all(pool)+ .await?)+}++#[tokio::test]+async fn a_rule_types_a_well_and_says_which_readings_did_it() -> 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 a = attr(+ &pool,+ &f,+ f.thc,+ serde_json::json!(12.3),+ "2023-06-01T00:00:00Z",+ )+ .await?;+ let b = attr(+ &pool,+ &f,+ f.category,+ serde_json::json!("气测异常"),+ "2023-06-01T00:00:00Z",+ )+ .await?;+ let r = rule(&pool, &f, 8.0).await?;++ let report = utopia_store::reasoning::materialize(&pool, f.kb).await?;+ assert_eq!(report.attribute_rules, 1, "规则要被读进来");+ assert_eq!(report.rule_hits, 1, "两条读数满足合取");++ let rows = derived(&pool, &f).await?;+ assert_eq!(rows.len(), 1, "一条派生归类");+ let d = &rows[0];+ assert!(d.object_id.is_none(), "归类走字面值通道,没有实体宾语");+ assert_eq!(+ d.object_value+ .as_ref()+ .and_then(|v| v.get("class"))+ .and_then(|v| v.as_str()),+ Some("gas_well"),+ "没有 IRI 时退回 key,记的是类而不是标签"+ );+ assert_eq!(d.attribute_rule_id, Some(r), "结论指回它的规则");+ assert_eq!(+ d.valid_from.map(|t| t.to_rfc3339()),+ Some("2023-06-01T00:00:00+00:00".into()),+ "区间取两条前提的交集"+ );++ // 前提链:凭哪两条读数+ let premises: Vec<(Uuid,)> = sqlx::query_as(+ "SELECT premise_fact_id FROM fact_derivations WHERE derived_fact_id = $1 ORDER BY seq",+ )+ .bind(d.id)+ .fetch_all(&pool)+ .await?;+ let got: Vec<Uuid> = premises.into_iter().map(|(x,)| x).collect();+ assert_eq!(got.len(), 2, "两条前提都要记下来");+ assert!(got.contains(&a) && got.contains(&b));++ // **重跑不该多一行。** 字面值结论的 object_id 是 NULL,而 Postgres 默认+ // 把 NULL 当互不相同——同一性索引写错的话这里每跑一轮多一条+ let again = utopia_store::reasoning::materialize(&pool, f.kb).await?;+ assert_eq!(again.inserted, 0, "同一条结论重跑不再插");+ assert_eq!(again.invalidated, 0, "也不该把自己判成陈旧");+ assert_eq!(derived(&pool, &f).await?.len(), 1, "库里还是一行");+ Ok::<_, anyhow::Error>(())+ }+ .await;++ sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(f.org)+ .execute(&pool)+ .await?;+ run+}++/// 阈值抬到读数之上再跑:结论**作废而不是删除**——记录轴上留着「我们曾据此推出」+#[tokio::test]+async fn raising_the_threshold_invalidates_without_deleting() -> 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?;+ assert_eq!(derived(&pool, &f).await?.len(), 1);++ // 阈值抬到 20:同一份数据不再满足+ sqlx::query(+ "UPDATE attribute_rule_conditions SET operand = '20' WHERE rule_id = $1 AND seq = 0",+ )+ .bind(r)+ .execute(&pool)+ .await?;+ let report = utopia_store::reasoning::materialize(&pool, f.kb).await?;+ assert_eq!(report.rule_hits, 0, "抬高之后不再命中");+ assert_eq!(report.invalidated, 1);++ let rows = derived(&pool, &f).await?;+ assert_eq!(rows.len(), 1, "行还在——作废不是删除");+ assert!(rows[0].invalidated_at.is_some(), "标了作废时刻");+ Ok::<_, anyhow::Error>(())+ }+ .await;++ sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(f.org)+ .execute(&pool)+ .await?;+ run+}++/// 关掉规则等同于前提消失:结论下一轮失效,而规则行还在+#[tokio::test]+async fn disabling_a_rule_retires_what_it_concluded() -> 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?;++ sqlx::query("UPDATE attribute_rules SET enabled = FALSE WHERE id = $1")+ .bind(r)+ .execute(&pool)+ .await?;+ let report = utopia_store::reasoning::materialize(&pool, f.kb).await?;+ assert_eq!(report.attribute_rules, 0, "关掉的规则不参与求值");+ assert_eq!(report.invalidated, 1, "它推出来的东西跟着退场");+ let rows = derived(&pool, &f).await?;+ assert!(rows[0].invalidated_at.is_some());+ Ok::<_, anyhow::Error>(())+ }+ .await;++ sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(f.org)+ .execute(&pool)+ .await?;+ run+}++/// 撤掉一条前提事实,结论跟着失效——与公理那一趟同一条路+#[tokio::test]+async fn retracting_a_reading_retires_the_conclusion() -> 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 a = 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?;+ rule(&pool, &f, 8.0).await?;+ utopia_store::reasoning::materialize(&pool, f.kb).await?;+ assert_eq!(derived(&pool, &f).await?[0].invalidated_at, None);++ sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = $1")+ .bind(a)+ .execute(&pool)+ .await?;+ let report = utopia_store::reasoning::materialize(&pool, f.kb).await?;+ assert_eq!(report.rule_hits, 0, "少了全烃这条前提就不成立");+ assert_eq!(report.invalidated, 1);+ Ok::<_, anyhow::Error>(())+ }+ .await;++ sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(f.org)+ .execute(&pool)+ .await?;+ run+}++/// 派生的结论**不写 `entities.type_id`**(0021 决策 2):断言类型是人的,+/// 规则的结论是叠在上面的一层+#[tokio::test]+async fn the_asserted_type_is_left_alone() -> 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?;+ rule(&pool, &f, 8.0).await?;+ utopia_store::reasoning::materialize(&pool, f.kb).await?;++ let (t,): (Option<Uuid>,) = sqlx::query_as("SELECT type_id FROM entities WHERE id = $1")+ .bind(f.w1)+ .fetch_one(&pool)+ .await?;+ assert_eq!(t, Some(f.well), "实体的断言类型仍然是 Well");+ let rows = derived(&pool, &f).await?;+ assert_eq!(rows.len(), 1, "GasBearingWell 只作为派生存在");+ assert_eq!(rows[0].object_id, None);+ // 结论落在内建 is_a 上+ let (p,): (Uuid,) = sqlx::query_as("SELECT predicate_id FROM derived_facts WHERE id = $1")+ .bind(rows[0].id)+ .fetch_one(&pool)+ .await?;+ assert_eq!(p, f.is_a);+ Ok::<_, anyhow::Error>(())+ }+ .await;++ sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(f.org)+ .execute(&pool)+ .await?;+ run+}diff --git a/docs/decisions/0021-a-rule-reads-attributes-and-concludes-a-type.md b/docs/decisions/0021-a-rule-reads-attributes-and-concludes-a-type.mdindex bfb2e83d..75bab16b 100644--- a/docs/decisions/0021-a-rule-reads-attributes-and-concludes-a-type.md+++ b/docs/decisions/0021-a-rule-reads-attributes-and-concludes-a-type.md@@ -1,6 +1,6 @@# 0021 · A rule reads attributes and concludes a type-- **Status**: planned · nothing built; the derivation machinery it stacks on is live+- **Status**: implemented · all four decisions built and the five phases done (#359) · `derived_facts` widened, `attribute_rules` authored through the ontology page, the evaluator running in the materialisation job, conclusions explained in the entity panel with their premises, and two read-only MCP tools (`list_rules`, `rule_matches`) · writing a rule stays out of MCP, see the open question · a conclusion's own text cannot be edited yet (delete and rewrite), the rule card's entity count is not clickable, and a rule-classified entity carries no canvas marker- **Written**: 2026-09-05 (conventions in the [README](README.md))- **Related**: [0002](0002-reasoning-engine.md) built the derivation runner and ruled out a user-defined rule language for ontology axioms; this record adds one narrow rule kind that lives beside the axioms, not inside them. [0009](0009-no-type-is-a-type.md) made `type_id` nullable and a type a considered claim; a rule concludes a *second* type without touching the asserted one. [0015](0015-recording-a-sentence-is-not-asserting-a-fact.md) draws the asserted / derived line this conclusion sits below. From #277.@@ -61,4 +61,20 @@ A well with a 2023 reading that fires the rule and a 2025 reading that does not- **Does a derived typing feed the extraction prompt or the mapping probe?** Those read the ontology's classes; a well that is derived-`GasBearingWell` is not asserted to be one. Leaning no — a derivation is a read-time overlay, not a fact the ontology teaches back into extraction — but a rule that concludes a class the corpus then reinforces is a loop worth watching.- **Category conditions and language.** `interpretation_category ∈ {"气测异常", "气测异常后效"}` is text matched literally. If the same category arrives in English from a different source, the set misses it. Out of scope here; the mapping layer (0011) is where a category vocabulary would belong.- **One conclusion per rule, or several.** #277 says one. A report that sets both a typing and a `gas_potential` grade from the same two readings would want two rules over the same premises today; whether that is a nuisance is a question the sample will answer.+- **Should an agent ever write a rule?** Reading is settled and built: `list_rules` and+ `rule_matches` are exposed over MCP, and `entity_facts` returns conclusions marked with the+ rule that reached them, so an agent explains a classification from the criteria instead of+ re-deriving it from the readings with a threshold it guessed. Writing is deliberately not+ exposed. The line 0002 drew is against the model *inventing* criteria, and a person+ dictating a rule to their agent is not that — but a tool call cannot tell the two apart,+ and the audit would read as the person's own token either way. A rule is also heavier than+ a fact: one wrong rule re-decides the whole base on every materialisation pass, quietly.+ If this opens later, it wants a pending queue of the shape `pending_facts` has, so a person+ nods before a rule takes effect.+- **A canvas marker for a rule-classified entity.** A conclusion is a judgement about one+ entity rather than a connection, so it draws no edge, and today it is visible only in the+ panel. Asserted attributes have no marker either, so adding one just for derived ones would+ invert the ground. The real gap the marker was standing in for — "which entities did this+ rule mark" — is answered by `rule_matches`. Revisit when someone reports losing track of a+ marked entity on the canvas, which is also when it will be clear what the marker should say.- **Where authored rules live for export.** If a deployment's rules are part of its ontology, RDF export (#308) has to say how — a rule is not an OWL axiom. Deferred to whenever export lands.diff --git a/docs/decisions/README.md b/docs/decisions/README.mdindex 4bcd7a5c..c8867305 100644--- a/docs/decisions/README.md+++ b/docs/decisions/README.md@@ -44,7 +44,7 @@ The test for writing one: if someone (including us) looks at a piece of code in| 0018 | [The lakehouse is one protocol away](0018-the-lakehouse-is-one-protocol-away.md) | Implemented: Trino (Iceberg / Delta / Hive), Databricks and Snowflake behind the same trait, scheme picks the engine (#239) · Trino verified against a real cluster (#327); Databricks and Snowflake still want one (#241, #242) · MaxCompute waits || 0019 | [The second clock can be rewound](0019-the-second-clock-can-be-rewound.md) | Implemented in three cuts · `held_at` and `as_of` on every graph read (#317), entities' own clock by unwinding `entity_merges` (#337), retrieval as of a moment · the control on the graph page is still open (#307), full-text recall is still "now" only || 0020 | [An auditor reads it without us](0020-an-auditor-reads-it-without-us.md) | Implemented · `GET /kbs/{id}/export?format=turtle\|jsonld` streams the base as RDF, `rdf.rs` holds the mapping · SPARQL waits, and the record says why (#308) |-| 0021 | [A rule reads attributes and concludes a type](0021-a-rule-reads-attributes-and-concludes-a-type.md) | Planned · nothing built · `derived_facts` widens to match `facts`, a derived typing rides the builtin `is_a`, rules authored in `attribute_rules` by a person, validity is the premise intersection (#277) |+| 0021 | [A rule reads attributes and concludes a type](0021-a-rule-reads-attributes-and-concludes-a-type.md) | Implemented (#359) · `derived_facts` widened to match `facts`, rules authored in `attribute_rules` from the ontology page, evaluated in the materialisation job, explained in the entity panel with their premises · read-only over MCP, writing a rule stays out · no canvas marker, and a conclusion is rewritten rather than edited |## Not a decision recorddiff --git a/migrations/0028_a_rule_reads_attributes.sql b/migrations/0028_a_rule_reads_attributes.sqlnew file mode 100644index 00000000..f2105c9d--- /dev/null+++ b/migrations/0028_a_rule_reads_attributes.sql@@ -0,0 +1,108 @@+-- 0021:属性事实上的业务规则。人写规则,引擎按物化的节奏跑,结论是派生的。++-- ---------------------------------------------------------------------------+-- 一、`derived_facts` 拓宽到与 `facts` 同宽(0021 决策 1)+-- ---------------------------------------------------------------------------+--+-- 从前派生只能是「实体—实体」边:`object_id NOT NULL`。而业务规则的两种结论+-- 都不是边——派生归类是一个类,派生属性是一个字面值。+--+-- **拓宽机制,而不是在旁边另开一张表。** 下游那些路径(证明链、失效、物化+-- 对账、图上画成派生、asserted > derived 的优先级)认的是「这一行在+-- derived_facts 里」,不是「它的宾语是实体」,所以拓宽之后它们一行都不用改。+-- `facts` 早就是这个形状了,派生表比断言表还窄本身就是那条缝。+ALTER TABLE derived_facts ALTER COLUMN object_id DROP NOT NULL;+ALTER TABLE derived_facts ADD COLUMN object_value JSONB;+ALTER TABLE derived_facts ADD CONSTRAINT derived_object_or_value+ CHECK (object_id IS NOT NULL OR object_value IS NOT NULL);++-- ---------------------------------------------------------------------------+-- 二、规则本身+-- ---------------------------------------------------------------------------+--+-- 与 `rules`(公理编译出来的那张)分开:那张是 `(谓词, 公理种类)`,一个谓词+-- 一行,没有条件可放。业务规则是「某个类的实体,其自身属性满足一组条件,+-- 就得出一个结论」——主类、条件集、结论,三样都无处可去。+--+-- **人写,模型永不提议**(与 0002 对公理的判断同一条线:推理的判据是写下来的)。+CREATE TABLE attribute_rules (+ id UUID PRIMARY KEY,+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,+ name TEXT NOT NULL,+ description TEXT NOT NULL DEFAULT '',+ -- 规则只看这个类(及其子类)的实体+ subject_type_id UUID NOT NULL REFERENCES entity_types(id) ON DELETE CASCADE,+ -- typing → 派生归类,结论在 conclude_type_id+ -- attribute → 派生属性,结论在 conclude_predicate_id + conclude_value+ conclusion TEXT NOT NULL CHECK (conclusion IN ('typing', 'attribute')),+ conclude_type_id UUID REFERENCES entity_types(id) ON DELETE CASCADE,+ conclude_predicate_id UUID REFERENCES relation_types(id) ON DELETE CASCADE,+ conclude_value JSONB,+ -- 关掉不等于删掉:关掉的规则下一轮不产出,已产出的按前提消失的老路失效+ enabled BOOLEAN NOT NULL DEFAULT TRUE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ -- 两种结论各填各的那几列,填串了直接挡住+ CONSTRAINT attribute_rule_conclusion_shape CHECK (+ (conclusion = 'typing'+ AND conclude_type_id IS NOT NULL+ AND conclude_predicate_id IS NULL+ AND conclude_value IS NULL)+ OR+ (conclusion = 'attribute'+ AND conclude_type_id IS NULL+ AND conclude_predicate_id IS NOT NULL+ AND conclude_value IS NOT NULL)+ ),+ UNIQUE (kb_id, name)+);+CREATE INDEX attribute_rules_kb_idx ON attribute_rules (kb_id) WHERE enabled;++-- 条件是**结构化的,不是一段文本**。存成表达式字符串就等于发明了一门小语言,+-- 而 0021 明确把通用规则语言排除在外:写下来的判据要能被读、被校验、被界面+-- 原样画出来。+--+-- operand 按 op 取不同形状(number / [lo,hi] / 字符串数组 / null),一列 JSONB+-- 装下:拆成四列会有三列永远是空的。+CREATE TABLE attribute_rule_conditions (+ id UUID PRIMARY KEY,+ rule_id UUID NOT NULL REFERENCES attribute_rules(id) ON DELETE CASCADE,+ seq INT NOT NULL,+ -- 只能是 kind='attribute' 的谓词;跨实体的关系不参与(0021 决策 3)+ predicate_id UUID NOT NULL REFERENCES relation_types(id) ON DELETE CASCADE,+ op TEXT NOT NULL CHECK (op IN ('gt', 'gte', 'lt', 'lte', 'between', 'in', 'present')),+ operand JSONB,+ -- present 不带操作数,其余都必须带+ CONSTRAINT attribute_rule_condition_operand CHECK (+ (op = 'present' AND operand IS NULL) OR (op <> 'present' AND operand IS NOT NULL)+ ),+ UNIQUE (rule_id, seq)+);+CREATE INDEX attribute_rule_conditions_rule_idx ON attribute_rule_conditions (rule_id);++-- ---------------------------------------------------------------------------+-- 三、一行派生来自公理规则或业务规则,恰好一个+-- ---------------------------------------------------------------------------+ALTER TABLE derived_facts ALTER COLUMN rule_id DROP NOT NULL;+ALTER TABLE derived_facts+ ADD COLUMN attribute_rule_id UUID REFERENCES attribute_rules(id) ON DELETE CASCADE;+ALTER TABLE derived_facts ADD CONSTRAINT derived_one_rule+ CHECK ((rule_id IS NOT NULL) <> (attribute_rule_id IS NOT NULL));++-- ---------------------------------------------------------------------------+-- 四、同一性索引要认得字面值结论+-- ---------------------------------------------------------------------------+--+-- 旧索引按 `(kb, 主, 谓, 宾, 起, 止)` 认「还是那一条」,而字面值结论的+-- `object_id` 是 NULL。**Postgres 默认把 NULL 视作互不相同**,于是同一条结论+-- 每跑一轮都能再插一行,物化对账那一步永远认不出它已经在库里——重复行会随+-- 轮次线性增长,而且每一轮都报成 inserted。+--+-- 重建成 NULLS NOT DISTINCT 并把 object_value 一起纳入:两端各有一个可空列,+-- 靠它们区分的正是「归类」与「属性值」两种结论。+DROP INDEX derived_facts_identity_idx;+CREATE UNIQUE INDEX derived_facts_identity_idx+ ON derived_facts (kb_id, subject_id, predicate_id, object_id, object_value,+ valid_from, valid_to)+ NULLS NOT DISTINCT+ WHERE invalidated_at IS NULL;diff --git a/web/src/api.ts b/web/src/api.tsindex 5347c985..ede67710 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -308,16 +308,51 @@ export interface ChunkFact {** `premises` 是这一档存在的理由:不给出前提的话,一条派生边跟一条普通的边* 在界面上看不出区别,而那正是「推理污染知识」的样子。 */+/** 一条条件:这个属性、这样比、跟这个值比 */+export interface RuleCondition {+ predicate_id: string;+ /** gt | gte | lt | lte | between | in | present */+ op: string;+ /** 数字 / [lo,hi] / 字符串数组;present 不带 */+ operand?: unknown;+ predicate_label?: string;+}++export interface RuleInput {+ name: string;+ description?: string;+ subject_type_id: string;+ /** typing = 推出一个类;attribute = 推出一个属性值 */+ conclusion: "typing" | "attribute";+ conclude_type_id?: string;+ conclude_predicate_id?: string;+ conclude_value?: unknown;+ conditions: RuleCondition[];+}++export interface BusinessRule extends RuleInput {+ id: string;+ enabled: boolean;+ subject_label: string;+ conclude_type_label: string | null;+ conclude_predicate_label: string | null;+ /** 此刻凭它成立的结论条数 */+ derived_count: number;+}+export interface DerivedFact {id: string;subject_id: string;subject: string;- object_id: string;+ /** 字面值结论(规则推出的归类与属性)没有实体宾语 */+ object_id: string | null;object: string;predicate: string;/** 靠哪条规则推的 *//** 靠哪条规则推的。后两种是 0017 补上的跨谓词规则 */- rule: "transitive" | "symmetric" | "inverse" | "sub_property";+ rule: "transitive" | "symmetric" | "inverse" | "sub_property" | "business";+ /** 业务规则的名字。公理推的为 null——公理没有名字 */+ rule_name?: string | null;valid_from: string | null;valid_to: string | null;confidence: number;@@ -1508,6 +1543,42 @@ export const api = {readiness: (kbId: string) =>request<Readiness>(`/api/v1/kbs/${kbId}/readiness`),+ /* ---- 业务规则(0021 / #277):人写下的判据,引擎按物化的节奏跑 ---- */+ rules: (kbId: string) =>+ request<{ rules: BusinessRule[] }>(`/api/v1/kbs/${kbId}/rules`),+ createRule: (kbId: string, body: RuleInput) =>+ request<{ id: string }>(`/api/v1/kbs/${kbId}/rules`, {+ method: "POST",+ body: JSON.stringify(body),+ }),+ updateRule: (+ kbId: string,+ ruleId: string,+ body: {+ name?: string;+ description?: string;+ enabled?: boolean;+ conditions?: RuleCondition[];+ },+ ) =>+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/rules/${ruleId}`, {+ method: "PATCH",+ body: JSON.stringify(body),+ }),+ deleteRule: (kbId: string, ruleId: string) =>+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/rules/${ruleId}`, {+ method: "DELETE",+ }),+ /** 立刻跑一遍。物化默认一小时一轮,而写规则的人想马上看见它推出了什么 */+ runRules: (kbId: string) =>+ request<{+ rules: number;+ hits: number;+ capped: number;+ inserted: number;+ invalidated: number;+ }>(`/api/v1/kbs/${kbId}/rules/run`, { method: "POST" }),+entityHistory: (kbId: string, entityId: string, page: number, per = 30) =>request<{ events: EntityHistoryEvent[]; total: number }>(`/api/v1/kbs/${kbId}/entities/${entityId}/history?page=${page}&per=${per}`,diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex d44a126d..5ad3630d 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -781,7 +781,7 @@ export const en = {viewDerived: "Derived",derivedEdges: (n: number) => `${n} derived`,derivedHint:- "Edges no one asserted — the engine worked them out from axioms your ontology declares. Each one shows the premises it came from.",+ "Nothing here was asserted — the engine worked it out, from an axiom your ontology declares or from a rule someone wrote. Each one shows the premises it came from.",derivedNoProof: "The premises are gone.",/* 争议(0017 §3) */contestedChip: "disputed",@@ -1044,6 +1044,55 @@ export const en = {missesShort: "Unmatched",uniquenessShort: "Overlaps",refineShort: "Refine types",+ /* ---- 业务规则(0021 / #277)---- */+ rulesShort: "Business rules",+ rulesTitle: "Business rules",+ /* 说清三件事:谁写的、结论是什么身份、什么时候重算。第三件最容易被误解成+ 「保存就生效」,而它其实等下一轮物化 */+ rulesHint:+ "A rule reads one entity's own attributes and concludes a class or a value. " ++ "You write the criteria — the model never proposes one. " ++ "What a rule concludes is derived: it never replaces an asserted fact, it carries the readings that made it true, and it retires by itself when they change.",+ rulesEmpty: "No rules yet.",+ ruleNew: "New rule",+ ruleName: "Name",+ ruleNamePlaceholder: "Gas-bearing well",+ ruleDescription: "What it means (optional)",+ ruleSubject: "Applies to",+ ruleSubjectHint: "and its subclasses",+ ruleConcludes: "Concludes",+ ruleConcludesTyping: "the class",+ ruleConcludesAttribute: "the attribute",+ ruleConditions: "When all of",+ ruleAddCondition: "Add a condition",+ ruleOpGt: "is above",+ ruleOpGte: "is at least",+ ruleOpLt: "is below",+ ruleOpLte: "is at most",+ ruleOpBetween: "is between",+ ruleOpIn: "is one of",+ ruleOpPresent: "is recorded",+ ruleOperandNumber: "12.0",+ ruleOperandSet: "gas anomaly, post-effect gas anomaly",+ ruleOperandSetHint: "comma separated",+ ruleSave: "Save rule",+ ruleSaved: "Rule saved",+ ruleDeleted: "Rule deleted",+ ruleDelete: "Delete",+ ruleDeleteConfirm: (n: string) => `Delete “${n}”? What it concluded goes with it.`,+ ruleEnabled: "On",+ ruleDisabled: "Off",+ /* 数字是「此刻凭它成立的结论条数」,不是历史总数 */+ ruleDerivedCount: (n: number) =>+ n === 1 ? "1 entity" : `${n} entities`,+ ruleRun: "Run now",+ ruleRunning: "Running…",+ /* 跑完要说清三件事,因为图会自己变:命中多少、新落多少、退了多少 */+ ruleRunDone: (hits: number, inserted: number, invalidated: number) =>+ `${hits} matched · ${inserted} new · ${invalidated} retired`,+ 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.",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 59923094..2b150a06 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -704,7 +704,7 @@ export const zh: Strings = {viewDerived: "推出来的",derivedEdges: (n: number) => `推出来的 ${n}`,derivedHint:- "没有人断言过的边——引擎按本体声明的公理推出来的。每一条都附着它用到的前提。",+ "这里没有一条是谁断言的——都是引擎推出来的:或按本体声明的公理,或按有人写下的规则。每一条都附着它用到的前提。",derivedNoProof: "前提已经不在了。",contestedChip: "有争议",contestedHint: (kind: string, derived: string | null) =>@@ -934,6 +934,48 @@ export const zh: Strings = {missesShort: "未匹配",uniquenessShort: "并存",refineShort: "类型消解",+ rulesShort: "业务规则",+ rulesTitle: "业务规则",+ rulesHint:+ "一条规则读一个实体自己的属性,得出一个类或一个值。判据由你写下——模型不会提议。" ++ "规则得出的结论是派生的:它不会盖掉断言,它带着让它成立的那几条读数,读数变了它自己退场。",+ rulesEmpty: "还没有规则。",+ ruleNew: "新建规则",+ ruleName: "名称",+ ruleNamePlaceholder: "含气井",+ ruleDescription: "它是什么意思(选填)",+ ruleSubject: "适用于",+ ruleSubjectHint: "及其子类",+ ruleConcludes: "得出",+ ruleConcludesTyping: "这个类",+ ruleConcludesAttribute: "这个属性",+ ruleConditions: "当以下全部成立",+ ruleAddCondition: "加一个条件",+ ruleOpGt: "大于",+ ruleOpGte: "不小于",+ ruleOpLt: "小于",+ ruleOpLte: "不大于",+ ruleOpBetween: "介于",+ ruleOpIn: "属于",+ ruleOpPresent: "有记录",+ ruleOperandNumber: "12.0",+ ruleOperandSet: "气测异常, 气测异常后效",+ ruleOperandSetHint: "逗号分隔",+ ruleSave: "保存规则",+ ruleSaved: "规则已保存",+ ruleDeleted: "规则已删除",+ ruleDelete: "删除",+ ruleDeleteConfirm: (n: string) => `删除「${n}」?凭它得出的结论一并消失。`,+ ruleEnabled: "启用",+ ruleDisabled: "停用",+ ruleDerivedCount: (n: number) => `${n} 个实体`,+ ruleRun: "立刻跑一遍",+ ruleRunning: "正在跑…",+ ruleRunDone: (hits: number, inserted: number, invalidated: number) =>+ `命中 ${hits} · 新增 ${inserted} · 退场 ${invalidated}`,+ ruleRunCapped: (n: number) =>+ `${n} 对(规则,实体)的读数组合太多没有展开完,它们的结论不完整`,+ ruleNeedsCondition: "一条规则至少要有一个条件。",refineTitle: "类型消解",refineHint:"类挂得大致对、但本体里有更具体的那一个。先看一遍再落库——改类不进任何时间轴,这是唯一能在它发生之前看见它的地方。",diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsxindex 390a90dc..df95b1d6 100644--- a/web/src/pages/Graph.tsx+++ b/web/src/pages/Graph.tsx@@ -2316,7 +2316,8 @@ function DerivedRow({}: {kbId: string;d: DerivedFact;- otherId: string;+ /** 字面值结论没有另一端实体(0021)*/+ otherId: string | null;otherName: string;open: boolean;onToggle: () => void;@@ -2333,23 +2334,31 @@ function DerivedRow({size={11}className={`shrink-0 text-ink-3 u-turn ${open ? "rotate-90" : ""}`}/>- <span- role="link"- tabIndex={0}- onClick={(ev) => {- ev.stopPropagation();- onNavigate(otherId);- }}- onKeyDown={(ev) => {- if (ev.key === "Enter") {+ {/* 业务规则的结论是字面值(一个类、一个值),另一端没有实体可跳——+ 这时候画成普通文字,而不是一个点了没反应的链接(0021) */}+ {/* 业务规则的结论是字面值(一个类、一个值),另一端没有实体可跳——+ 这时候画成普通文字,而不是一个点了没反应的链接(0021) */}+ {otherId ? (+ <span+ role="link"+ tabIndex={0}+ onClick={(ev) => {ev.stopPropagation();onNavigate(otherId);- }- }}- className="u-inline-link truncate text-body text-ink"- >- {otherName}- </span>+ }}+ onKeyDown={(ev) => {+ if (ev.key === "Enter") {+ ev.stopPropagation();+ onNavigate(otherId);+ }+ }}+ className="u-inline-link truncate text-body text-ink"+ >+ {otherName}+ </span>+ ) : (+ <span className="truncate text-body text-ink">{otherName}</span>+ )}<span className="ml-auto shrink-0 pl-2 text-fine text-ink-3">{d.premises.length}</span>@@ -2638,10 +2647,12 @@ function EntityPanel({>();for (const d of derived) {const direction = d.subject_id === entityId ? "out" : "in";- // 四条规则各有名字。**查不到就退回原始 kind 串**——那对读的人没有- // 意义,但比显示成另一条规则的名字诚实- const rule = S.graph.ruleNames[d.rule] ?? d.rule;- const key = `${direction}|${d.predicate}|${d.rule}`;+ // 四条公理各有名字;业务规则用它自己的名字(0021)——「Gas-bearing well」+ // 比「business」有意义得多,而那个名字正是人写规则时起的。+ // **查不到就退回原始 kind 串**:对读的人没有意义,但比显示成另一条规则诚实+ const rule = d.rule_name ?? S.graph.ruleNames[d.rule] ?? d.rule;+ // 分组键用规则名而不是 kind:同一个谓词上两条业务规则各归各的+ const key = `${direction}|${d.predicate}|${d.rule_name ?? d.rule}`;const cur = map.get(key);if (cur) cur.rows.push(d);else map.set(key, { key, direction, predicate: d.predicate, rule, rows: [d] });diff --git a/web/src/pages/Ontology.tsx b/web/src/pages/Ontology.tsxindex 758a955b..672442af 100644--- a/web/src/pages/Ontology.tsx+++ b/web/src/pages/Ontology.tsx@@ -9,6 +9,7 @@ import {ArrowRight,ChevronRight,Inbox,+ Scale,Network,Plus,Search,@@ -33,6 +34,7 @@ import { S } from "../i18n";import { useKb } from "../kb";import { toast } from "../toast";import { OntologySchemaGraph, type SchemaSelection } from "./OntologySchemaGraph";+import { RulesPanel } from "./RulesPanel";import {Button,Checkbox,@@ -84,6 +86,7 @@ type Sel =| { kind: "misses" }| { kind: "uniqueness" }// 类型消解:把「大致对」的类换成更具体的那个+ | { kind: "rules" }| { kind: "refine" }| { kind: "import" }// 模式图无选中:看整张图,不停靠表单@@ -335,6 +338,15 @@ export function Ontology() {>{S.ontology.importShort}</RailItem>+ {/* 业务规则(0021):本体说「有这么个类」,规则说「什么样的实体算它」。+ 所以它归在本体这一页,而不是另开一处——判据与词汇是同一份契约 */}+ <RailItem+ active={sel?.kind === "rules"}+ icon={<Scale size={14} />}+ onClick={() => setSel({ kind: "rules" })}+ >+ {S.ontology.rulesShort}+ </RailItem>{/* 类型消解:把「大致对」的类换成更具体的那个。**紧挨着未匹配**——两者都是「本体与数据对不齐」的处置,只是方向相反:那个是本体缺东西,这个是本体有更好的选项没被用上 */}@@ -377,7 +389,8 @@ export function Ontology() {{sel?.kind === "import" ||sel?.kind === "refine" ||sel?.kind === "misses" ||- sel?.kind === "uniqueness" ? (+ sel?.kind === "uniqueness" ||+ sel?.kind === "rules" ? (<div className="flex-1 min-w-0 overflow-y-auto u-scroll px-8 py-6"><div className="max-w-6xl">{sel.kind === "import" ? (@@ -402,6 +415,15 @@ export function Ontology() {onError={onError}/></div>+ ) : sel.kind === "rules" ? (+ <div className="max-w-2xl">+ <RulesPanel+ kbId={kb.id}+ classes={entity_types}+ attributes={relation_types.filter((r) => r.kind === "attribute")}+ onError={onError}+ />+ </div>) : (<div className="max-w-xl"><MissesPaneldiff --git a/web/src/pages/RulesPanel.tsx b/web/src/pages/RulesPanel.tsxnew file mode 100644index 00000000..d4698ab6--- /dev/null+++ b/web/src/pages/RulesPanel.tsx@@ -0,0 +1,473 @@+/** 业务规则的编写台(0021 / #277)。+ *+ * **规则读起来要像一句话**:「Well 及其子类,当 全烃 大于 8 且 解释 属于 {…},+ * 得出 GasBearingWell」。所以这里不做表达式输入框——结构化的下拉与数字框既是+ * 录入方式,也是它唯一的显示方式,两者不会漂移。+ *+ * 条件整组提交而不是逐条打补丁:一个合取是一个整体,没有「改到一半」的状态。+ *+ * 样式按 web/DESIGN.md 那五条:字号五档、间距六档、颜色只用 token、控件与状态+ * 一律从 ui/ 来。 */+import { useState } from "react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { Play, Plus, Trash2 } from "lucide-react";+import {+ api,+ type BusinessRule,+ type EntityTypeView,+ type RelationTypeView,+ type RuleCondition,+} from "../api";+import { S } from "../i18n";+import {+ Button,+ DangerConfirm,+ Dropdown,+ IconButton,+ Input,+ Panel,+} from "../ui";+import { toast } from "../toast";++/** op → 那句话里的动词。**数字与集合两类分开**,因为它们的操作数长得不一样 */+const OPS: {+ value: string;+ label: () => string;+ operand: "num" | "range" | "set" | "none";+}[] = [+ { value: "gt", label: () => S.ontology.ruleOpGt, operand: "num" },+ { value: "gte", label: () => S.ontology.ruleOpGte, operand: "num" },+ { value: "lt", label: () => S.ontology.ruleOpLt, operand: "num" },+ { value: "lte", label: () => S.ontology.ruleOpLte, operand: "num" },+ { value: "between", label: () => S.ontology.ruleOpBetween, operand: "range" },+ { value: "in", label: () => S.ontology.ruleOpIn, operand: "set" },+ { value: "present", label: () => S.ontology.ruleOpPresent, operand: "none" },+];++const operandKind = (op: string) =>+ OPS.find((o) => o.value === op)?.operand ?? "num";++/** 条件的操作数 → 输入框里的文本。回读要与写入是同一套,否则编辑一次就变形 */+function operandText(op: string, operand: unknown): string {+ const kind = operandKind(op);+ if (kind === "none") return "";+ if (kind === "set") return Array.isArray(operand) ? operand.join(", ") : "";+ if (kind === "range") return Array.isArray(operand) ? operand.join(" - ") : "";+ return operand === null || operand === undefined ? "" : String(operand);+}++/** 输入框文本 → 操作数。**解析不出来就返回 undefined**,由调用方拦在保存之前 */+function parseOperand(op: string, text: string): unknown | undefined {+ const kind = operandKind(op);+ if (kind === "none") return undefined;+ const t = text.trim();+ if (kind === "set") {+ const set = t+ .split(",")+ .map((s) => s.trim())+ .filter(Boolean);+ return set.length ? set : undefined;+ }+ if (kind === "range") {+ const parts = t.split(/[-~]/).map((s) => Number(s.trim()));+ return parts.length === 2 && parts.every((n) => Number.isFinite(n))+ ? parts+ : undefined;+ }+ const n = Number(t);+ return Number.isFinite(n) ? n : undefined;+}++type Draft = {+ name: string;+ description: string;+ subject_type_id: string;+ conclusion: "typing" | "attribute";+ conclude_type_id: string;+ conclude_predicate_id: string;+ conclude_value: string;+ conditions: { predicate_id: string; op: string; text: string }[];+};++const emptyDraft = (+ classes: EntityTypeView[],+ attrs: RelationTypeView[],+): Draft => ({+ name: "",+ description: "",+ subject_type_id: classes[0]?.id ?? "",+ conclusion: "typing",+ conclude_type_id: classes[0]?.id ?? "",+ conclude_predicate_id: attrs[0]?.id ?? "",+ conclude_value: "",+ conditions: attrs[0]+ ? [{ predicate_id: attrs[0].id, op: "gt", text: "" }]+ : [],+});++export function RulesPanel({+ kbId,+ classes,+ attributes,+ onError,+}: {+ kbId: string;+ classes: EntityTypeView[];+ /** kind='attribute' 的谓词——规则只读实体自己的字面值 */+ attributes: RelationTypeView[];+ onError: (e: unknown) => void;+}) {+ const qc = useQueryClient();+ const rules = useQuery({+ queryKey: ["rules", kbId],+ queryFn: () => api.rules(kbId),+ });+ const [draft, setDraft] = useState<Draft | null>(null);+ /** 待确认删除的那一条。删规则会带走它推出的全部结论,值得停一下 */+ const [doomed, setDoomed] = useState<BusinessRule | null>(null);++ const invalidate = () => {+ qc.invalidateQueries({ queryKey: ["rules", kbId] });+ qc.invalidateQueries({ queryKey: ["graph"] });+ qc.invalidateQueries({ queryKey: ["entity", kbId] });+ };++ const save = useMutation({+ mutationFn: () => {+ const d = draft!;+ if (!d.conditions.length) throw new Error(S.ontology.ruleNeedsCondition);+ const conditions: RuleCondition[] = d.conditions.map((c) => {+ const operand = parseOperand(c.op, c.text);+ if (operandKind(c.op) !== "none" && operand === undefined) {+ throw new Error(S.ontology.ruleNeedsCondition);+ }+ 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,+ conclusion: d.conclusion,+ conclude_type_id:+ d.conclusion === "typing" ? d.conclude_type_id : undefined,+ conclude_predicate_id:+ d.conclusion === "attribute" ? d.conclude_predicate_id : undefined,+ conclude_value:+ d.conclusion === "attribute" ? d.conclude_value : undefined,+ conditions,+ });+ },+ onSuccess: () => {+ toast.success(S.ontology.ruleSaved);+ setDraft(null);+ invalidate();+ },+ onError: (e: Error) => toast.error(e.message),+ });++ const run = useMutation({+ mutationFn: () => api.runRules(kbId),+ onSuccess: (r) => {+ toast.success(S.ontology.ruleRunDone(r.hits, r.inserted, r.invalidated));+ // 展开不全要单独说:少推几条与「不满足」在结果里长得一样+ if (r.capped) toast.error(S.ontology.ruleRunCapped(r.capped));+ invalidate();+ },+ onError,+ });++ const toggle = useMutation({+ mutationFn: (r: BusinessRule) =>+ api.updateRule(kbId, r.id, { enabled: !r.enabled }),+ onSuccess: invalidate,+ onError,+ });++ const remove = useMutation({+ mutationFn: (id: string) => api.deleteRule(kbId, id),+ onSuccess: () => {+ toast.success(S.ontology.ruleDeleted);+ invalidate();+ },+ onError,+ });++ const list = rules.data?.rules ?? [];++ return (+ <div className="space-y-6">+ {doomed && (+ <DangerConfirm+ title={S.ontology.ruleDelete}+ hint={S.ontology.ruleDeleteConfirm(doomed.name)}+ confirmLabel={S.ontology.ruleDelete}+ cancelLabel={S.graph.editCancel}+ busy={remove.isPending}+ onConfirm={() => {+ remove.mutate(doomed.id);+ setDoomed(null);+ }}+ onCancel={() => setDoomed(null)}+ />+ )}++ <div className="space-y-2">+ <div className="flex flex-wrap items-center gap-2">+ <h2 className="text-title font-medium text-ink">+ {S.ontology.rulesTitle}+ </h2>+ {list.length > 0 && (+ <span className="u-num text-small text-ink-3">{list.length}</span>+ )}+ <Button+ size="sm"+ variant="ghost"+ className="ml-auto"+ onClick={() => run.mutate()}+ disabled={run.isPending || !list.length}+ >+ <Play size={12} />+ {run.isPending ? S.ontology.ruleRunning : S.ontology.ruleRun}+ </Button>+ </div>+ <p className="text-fine leading-relaxed text-ink-3">+ {S.ontology.rulesHint}+ </p>+ </div>++ {list.map((r) => (+ <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">+ {S.ontology.ruleDerivedCount(r.derived_count)}+ </span>+ )}+ <div className="ml-auto flex items-center gap-2">+ {/* 开关是个动作,所以是 Button;启用与否用 variant 区分,+ 而不是拿 Chip 当按钮——Chip 是状态标签,不接受点击 */}+ <Button+ size="sm"+ variant={r.enabled ? "secondary" : "ghost"}+ onClick={() => toggle.mutate(r)}+ aria-pressed={r.enabled}+ >+ {r.enabled ? S.ontology.ruleEnabled : S.ontology.ruleDisabled}+ </Button>+ <IconButton+ label={S.ontology.ruleDelete}+ size="sm"+ onClick={() => setDoomed(r)}+ >+ <Trash2 size={12} />+ </IconButton>+ </div>+ </div>+ {r.description && (+ <p className="text-small leading-relaxed text-ink-3">+ {r.description}+ </p>+ )}+ {/* 规则读成一句话。这一段就是它的全部语义,没有别处再藏着条件 */}+ <p className="text-small leading-relaxed text-ink-2">+ <span className="text-ink-3">{S.ontology.ruleSubject} </span>+ {r.subject_label}+ <span className="text-ink-3"> ({S.ontology.ruleSubjectHint})</span>+ <span className="text-ink-3">, {S.ontology.ruleConditions} </span>+ {r.conditions.map((c, i) => (+ <span key={i}>+ {i > 0 && <span className="text-ink-3"> · </span>}+ <span className="text-ink">{c.predicate_label}</span>{" "}+ <span className="text-ink-3">+ {OPS.find((o) => o.value === c.op)?.label() ?? c.op}+ </span>{" "}+ <span className="u-num text-ink">+ {operandText(c.op, c.operand)}+ </span>+ </span>+ ))}+ <span className="text-ink-3"> → {S.ontology.ruleConcludes} </span>+ <span className="text-ink">+ {r.conclusion === "typing"+ ? r.conclude_type_label+ : `${r.conclude_predicate_label} = ${JSON.stringify(r.conclude_value)}`}+ </span>+ </p>+ </Panel>+ ))}++ {!list.length && !draft && (+ <p className="text-small text-ink-3">{S.ontology.rulesEmpty}</p>+ )}++ {draft ? (+ <Panel className="space-y-3 p-4">+ <Input+ value={draft.name}+ onChange={(e) => setDraft({ ...draft, name: e.target.value })}+ placeholder={S.ontology.ruleNamePlaceholder}+ className="w-full"+ />+ <Input+ value={draft.description}+ onChange={(e) => setDraft({ ...draft, description: e.target.value })}+ placeholder={S.ontology.ruleDescription}+ className="w-full"+ />+ <div className="flex items-center gap-2">+ <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 }))}+ />+ </div>++ <div className="space-y-2">+ <div className="text-fine text-ink-3">+ {S.ontology.ruleConditions}+ </div>+ {draft.conditions.map((c, i) => (+ <div key={i} className="flex items-center gap-2">+ <Dropdown+ value={c.predicate_id}+ onChange={(v) => {+ const next = [...draft.conditions];+ next[i] = { ...c, predicate_id: v };+ setDraft({ ...draft, conditions: next });+ }}+ options={attributes.map((a) => ({+ value: a.id,+ label: a.label,+ }))}+ />+ <Dropdown+ value={c.op}+ onChange={(v) => {+ const next = [...draft.conditions];+ next[i] = { ...c, op: v, text: "" };+ setDraft({ ...draft, conditions: next });+ }}+ options={OPS.map((o) => ({+ value: o.value,+ label: o.label(),+ }))}+ />+ {operandKind(c.op) !== "none" && (+ <Input+ value={c.text}+ onChange={(e) => {+ const next = [...draft.conditions];+ next[i] = { ...c, text: e.target.value };+ setDraft({ ...draft, conditions: next });+ }}+ placeholder={+ operandKind(c.op) === "set"+ ? S.ontology.ruleOperandSet+ : S.ontology.ruleOperandNumber+ }+ className="u-num flex-1"+ />+ )}+ <IconButton+ label={S.ontology.ruleDelete}+ size="sm"+ onClick={() =>+ setDraft({+ ...draft,+ conditions: draft.conditions.filter((_, j) => j !== i),+ })+ }+ >+ <Trash2 size={11} />+ </IconButton>+ </div>+ ))}+ <Button+ size="sm"+ variant="ghost"+ onClick={() =>+ setDraft({+ ...draft,+ conditions: [+ ...draft.conditions,+ { predicate_id: attributes[0]?.id ?? "", op: "gt", text: "" },+ ],+ })+ }+ >+ <Plus size={11} />+ {S.ontology.ruleAddCondition}+ </Button>+ </div>++ <div className="flex flex-wrap items-center gap-2">+ <span className="shrink-0 text-fine text-ink-3">+ {S.ontology.ruleConcludes}+ </span>+ <Dropdown+ value={draft.conclusion}+ onChange={(v) =>+ setDraft({ ...draft, conclusion: v as "typing" | "attribute" })+ }+ options={[+ { value: "typing", label: S.ontology.ruleConcludesTyping },+ { value: "attribute", label: S.ontology.ruleConcludesAttribute },+ ]}+ />+ {draft.conclusion === "typing" ? (+ <Dropdown+ value={draft.conclude_type_id}+ onChange={(v) => setDraft({ ...draft, conclude_type_id: v })}+ options={classes.map((c) => ({ value: c.id, label: c.label }))}+ />+ ) : (+ <>+ <Dropdown+ value={draft.conclude_predicate_id}+ onChange={(v) =>+ setDraft({ ...draft, conclude_predicate_id: v })+ }+ options={attributes.map((a) => ({+ value: a.id,+ label: a.label,+ }))}+ />+ <Input+ value={draft.conclude_value}+ onChange={(e) =>+ setDraft({ ...draft, conclude_value: e.target.value })+ }+ className="flex-1"+ />+ </>+ )}+ </div>++ <div className="flex justify-end gap-2">+ <Button size="sm" variant="ghost" onClick={() => setDraft(null)}>+ {S.graph.editCancel}+ </Button>+ <Button size="sm" onClick={() => save.mutate()} disabled={save.isPending}>+ {S.ontology.ruleSave}+ </Button>+ </div>+ </Panel>+ ) : (+ <Button+ size="sm"+ variant="ghost"+ onClick={() => setDraft(emptyDraft(classes, attributes))}+ disabled={!classes.length || !attributes.length}+ >+ <Plus size={12} />+ {S.ontology.ruleNew}+ </Button>+ )}+ </div>+ );+}