World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Render computed rule conclusions from their stored expressions (#815)
Maya Kid2d5762e0c061
diff --git a/crates/utopia-server/src/api/mcp_tests.rs b/crates/utopia-server/src/api/mcp_tests.rsindex e82b8b6b..3eb55a8b 100644--- a/crates/utopia-server/src/api/mcp_tests.rs+++ b/crates/utopia-server/src/api/mcp_tests.rs@@ -939,6 +939,144 @@ fn text_only_results_do_not_acquire_a_structured_payload() {);}+#[tokio::test]+async fn computed_rule_descriptions_keep_the_expression_tree_and_identity() -> anyhow::Result<()> {+ use utopia_store::business_rules::{self, ConditionInput};+ let Some(f) = Fixture::new().await? else {+ return Ok(());+ };+ let ty: Uuid = sqlx::query_scalar("SELECT type_id FROM entities WHERE id=$1")+ .bind(f.subject)+ .fetch_one(&f.state.pool)+ .await?;+ let (revenue, cost, margin) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ for (id, key) in [(revenue, "revenue"), (cost, "cost"), (margin, "margin")] {+ sqlx::query("INSERT INTO relation_types(id,kb_id,key,label,kind,datatype) VALUES ($1,$2,$3,$3,'attribute','number')")+ .bind(id).bind(f.kb).bind(key).execute(&f.state.pool).await?;+ }+ let conditions = [ConditionInput {+ group: 2,+ predicate_id: revenue,+ op: "present".into(),+ operand: None,+ }];+ let sub = json!({"op":"sub","l":{"attr":revenue},"r":{"attr":cost}});+ for (name, expr, expected) in [+ ("difference", sub.clone(), "(revenue - cost)"),+ (+ "ratio",+ json!({"op":"div","l":sub,"r":{"attr":revenue}}),+ "((revenue - cost) / revenue)",+ ),+ (+ "nested",+ json!({"op":"sub","l":{"attr":revenue},"r":{"op":"sub","l":{"attr":cost},"r":{"const":2}}}),+ "(revenue - (cost - 2))",+ ),+ (+ "zero",+ json!({"op":"add","l":{"attr":revenue},"r":{"const":0}}),+ "(revenue + 0)",+ ),+ (+ "negative",+ json!({"op":"mul","l":{"attr":revenue},"r":{"const":"-2.5"}}),+ "(revenue * -2.5)",+ ),+ ] {+ business_rules::create(+ &f.state.pool,+ f.kb,+ name,+ "",+ ty,+ "computed",+ None,+ Some(margin),+ None,+ Some(expr),+ &conditions,+ )+ .await?;+ let before = business_rules::list(&f.state.pool, f.kb).await?;+ let derived_before: Value=sqlx::query_scalar("SELECT coalesce(jsonb_agg(to_jsonb(d) ORDER BY id),'[]') FROM derived_facts d WHERE kb_id=$1")+ .bind(f.kb).fetch_one(&f.state.pool).await?;+ let jobs_before: Value=sqlx::query_scalar("SELECT coalesce(jsonb_agg(to_jsonb(j) ORDER BY id),'[]') FROM jobs j WHERE payload->>'kb_id'=$1 OR payload->>'document_id' IN (SELECT id::text FROM documents WHERE kb_id=$2)")+ .bind(f.kb.to_string()).bind(f.kb).fetch_one(&f.state.pool).await?;+ let result = f.call("list_rules", json!({})).await?;+ assert_eq!(result["isError"], false);+ let text = result["content"][0]["text"].as_str().unwrap();+ let line = text+ .lines()+ .find(|l| l.starts_with(&format!("{name} [")))+ .unwrap();+ assert!(line.contains(&format!("⇒ margin = {expected} ·")), "{line}");+ assert!(text.contains("⇒ weight = {\"unit\":\"kg\",\"value\":8}"));+ assert_eq!(business_rules::list(&f.state.pool, f.kb).await?, before);+ let derived_after: Value=sqlx::query_scalar("SELECT coalesce(jsonb_agg(to_jsonb(d) ORDER BY id),'[]') FROM derived_facts d WHERE kb_id=$1")+ .bind(f.kb).fetch_one(&f.state.pool).await?;+ assert_eq!(derived_before, derived_after);+ let jobs_after: Value=sqlx::query_scalar("SELECT coalesce(jsonb_agg(to_jsonb(j) ORDER BY id),'[]') FROM jobs j WHERE payload->>'kb_id'=$1 OR payload->>'document_id' IN (SELECT id::text FROM documents WHERE kb_id=$2)")+ .bind(f.kb.to_string()).bind(f.kb).fetch_one(&f.state.pool).await?;+ assert_eq!(jobs_before, jobs_after);+ }+ business_rules::create(+ &f.state.pool,+ f.kb,+ "typing control",+ "",+ ty,+ "typing",+ Some(ty),+ None,+ None,+ None,+ &conditions,+ )+ .await?;+ sqlx::query("UPDATE relation_types SET label='收入' WHERE id=ANY($1)")+ .bind(vec![revenue, cost])+ .execute(&f.state.pool)+ .await?;+ let result = f.call("list_rules", json!({})).await?;+ let text = result["content"][0]["text"].as_str().unwrap();+ assert!(text.contains("(收入 [revenue] - 收入 [cost])"), "{text}");+ assert!(text+ .lines()+ .find(|l| l.starts_with("typing control ["))+ .unwrap()+ .contains("⇒ Thing ·"));+ // Corrupt/stale stored references must not expose another base's label or+ // fabricate a formula. Creation itself continues to reject such inputs.+ let foreign = Uuid::now_v7();+ sqlx::query("INSERT INTO relation_types(id,kb_id,key,label,kind,datatype) VALUES ($1,$2,'hidden','Foreign secret','attribute','number')")+ .bind(foreign).bind(f.other_kb).execute(&f.state.pool).await?;+ for expr in [+ json!({"attr":foreign}),+ json!({"op":"unknown"}),+ json!({"const":null}),+ ] {+ sqlx::query(+ "UPDATE attribute_rules SET conclude_expr=$2 WHERE kb_id=$1 AND name='difference'",+ )+ .bind(f.kb)+ .bind(expr)+ .execute(&f.state.pool)+ .await?;+ let result = f.call("list_rules", json!({})).await?;+ let text = result["content"][0]["text"].as_str().unwrap();+ assert!(+ text.lines()+ .find(|l| l.starts_with("difference ["))+ .unwrap()+ .contains("margin = (expression unavailable)"),+ "{text}"+ );+ assert!(!text.contains("Foreign secret"));+ }+ f.clean().await+}+#[tokio::test]async fn rule_reads_preserve_matches_and_empty_results() -> anyhow::Result<()> {let Some(f) = Fixture::new().await? else {diff --git a/crates/utopia-server/src/api/tools.rs b/crates/utopia-server/src/api/tools.rsindex 476cb8ed..6805c5b6 100644--- a/crates/utopia-server/src/api/tools.rs+++ b/crates/utopia-server/src/api/tools.rs@@ -375,6 +375,25 @@ pub async fn list_rules(ctx: &ToolCtx<'_>) -> ToolResult {json!({ "kind": "tool", "label": "list_rules", "detail": "none" }),);}+ let expressions: Vec<_> = rules+ .iter()+ .filter(|r| r["conclusion"] == "computed")+ .map(|r| &r["conclude_expr"])+ .collect();+ let Ok(descriptions) = utopia_store::business_rules::describe_expressions(+ &ctx.state.pool,+ ctx.kb_id,+ &expressions,+ )+ .await+ else {+ return ToolResult::new(+ "Could not read the rules.".to_string(),+ json!({ "kind": "tool", "label": "list_rules", "detail": "failed" }),+ )+ .error();+ };+ let mut descriptions = descriptions.into_iter();let text = rules.iter().map(|r| {@@ -399,6 +418,15 @@ pub async fn list_rules(ctx: &ToolCtx<'_>) -> ToolResult {.unwrap_or_default();let concludes = if r["conclusion"] == "typing" {r["conclude_type_label"].as_str().unwrap_or("?").to_string()+ } else if r["conclusion"] == "computed" {+ format!(+ "{} = {}",+ r["conclude_predicate_label"].as_str().unwrap_or("?"),+ descriptions+ .next()+ .flatten()+ .unwrap_or_else(|| "(expression unavailable)".to_string()),+ )} else {format!("{} = {}",diff --git a/crates/utopia-store/src/business_rules.rs b/crates/utopia-store/src/business_rules.rsindex fae8b26d..1d9bbf65 100644--- a/crates/utopia-store/src/business_rules.rs+++ b/crates/utopia-store/src/business_rules.rs@@ -366,6 +366,77 @@ pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<serde_json::Value.collect())}+/// Read-only descriptions of stored computation trees. Reuse the write-side+/// shape/depth check, then resolve every leaf in one query scoped to this base.+/// Invalid trees or unavailable attributes are reported as unavailable, not null.+pub async fn describe_expressions(+ pool: &PgPool,+ kb_id: Uuid,+ expressions: &[&serde_json::Value],+) -> AppResult<Vec<Option<String>>> {+ let reads: Vec<_> = expressions+ .iter()+ .map(|e| validate_expr(e, 0).ok())+ .collect();+ let mut ids: Vec<Uuid> = reads.iter().flatten().flatten().copied().collect();+ ids.sort();+ ids.dedup();+ let mut names = std::collections::HashMap::new();+ if !ids.is_empty() {+ let rows: Vec<(Uuid, String, String)> = sqlx::query_as(+ "SELECT id, key, label FROM relation_types WHERE kb_id=$1 AND id=ANY($2)",+ )+ .bind(kb_id)+ .bind(&ids)+ .fetch_all(pool)+ .await?;+ for (id, key, label) in rows {+ // Keys keep distinct attributes identifiable even when labels coincide.+ let name = if label.is_empty() || label == key {+ key+ } else {+ format!("{label} [{key}]")+ };+ names.insert(id, name);+ }+ }+ Ok(expressions+ .iter()+ .zip(reads)+ .map(|(e, valid)| valid.and_then(|_| expression_text(e, &names)))+ .collect())+}++// Only called after validate_expr has accepted the tree and bounded its depth.+fn expression_text(+ raw: &serde_json::Value,+ names: &std::collections::HashMap<Uuid, String>,+) -> Option<String> {+ use utopia_reason::rules::Arith;+ if let Some(attr) = raw.get("attr") {+ return names.get(&attr.as_str()?.parse::<Uuid>().ok()?).cloned();+ }+ if let Some(value) = raw.get("const") {+ return Some(+ value+ .as_str()+ .map(|s| s.trim().to_string())+ .unwrap_or_else(|| value.to_string()),+ );+ }+ let op = match Arith::parse(raw.get("op")?.as_str()?)? {+ Arith::Add => "+",+ Arith::Sub => "-",+ Arith::Mul => "*",+ Arith::Div => "/",+ };+ Some(format!(+ "({} {op} {})",+ expression_text(raw.get("l")?, names)?,+ expression_text(raw.get("r")?, names)?+ ))+}+/// 命中查询回来的一行:派生 id、实体 id 与名字、结论、区间两端、前提的可读形态type MatchRow = (Uuid,