World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Report an entity id that is not in the base instead of saying paths_between found no path (#948)
Maya Kid5764903122f5
diff --git a/crates/utopia-server/src/api/mcp_tests.rs b/crates/utopia-server/src/api/mcp_tests.rsindex 40d9578f..46777cc9 100644--- a/crates/utopia-server/src/api/mcp_tests.rs+++ b/crates/utopia-server/src/api/mcp_tests.rs@@ -1276,6 +1276,61 @@ async fn opposite_directions_reach_authenticated_path_output() -> anyhow::Resultresult.and(cleanup)}+/// 以 id 给出的一端要真在这个库里。从前一个不存在的 id(抄错的、别的库的)得到的是+/// 「两者之间没有路径」,读起来像一个关于图的事实;结果里的名字也只是那串 id+#[tokio::test]+async fn a_path_to_an_unknown_id_says_so() -> anyhow::Result<()> {+ let Some(f) = Fixture::new().await? else {+ return Ok(());+ };+ let (missing, foreign, loner) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ sqlx::query(+ "INSERT INTO entities(id,kb_id,canonical_name) VALUES ($1,$2,'Elsewhere'), ($3,$4,'Loner')",+ )+ .bind(foreign)+ .bind(f.other_kb)+ .bind(loner)+ .bind(f.kb)+ .execute(&f.state.pool)+ .await?;+ for (args, text) in [+ (+ json!({"from":missing,"to":f.object}),+ format!("Unknown `from`: no entity with id {missing} in this base."),+ ),+ (+ json!({"from":f.subject,"to":foreign}),+ format!("Unknown `to`: no entity with id {foreign} in this base."),+ ),+ ] {+ let result = f.call("paths_between", args).await?;+ assert_eq!(result["isError"], false, "{result}");+ assert_eq!(result["content"][0]["text"], text.as_str());+ }+ // 在库里的 id:没有路径时照常说没有,而且说的是名字+ let none = f+ .call("paths_between", json!({"from":f.subject,"to":loner}))+ .await?;+ assert_eq!(none["isError"], false);+ let text = none["content"][0]["text"].as_str().unwrap();+ assert!(+ text.starts_with("No path of up to 3 hops between Alice and Loner."),+ "{text}"+ );+ // 找到路径时,开头那一行也写名字+ let found = f+ .call("paths_between", json!({"from":f.subject,"to":f.object}))+ .await?;+ let header = found["content"][0]["text"]+ .as_str()+ .unwrap()+ .lines()+ .next()+ .unwrap();+ assert!(header.contains(" between Alice and Acme "), "{header}");+ f.clean().await+}+#[tokio::test]async fn missing_entities_and_empty_graph_reads_keep_their_results() -> anyhow::Result<()> {let Some(f) = Fixture::new().await? else {diff --git a/crates/utopia-server/src/api/tools_graph.rs b/crates/utopia-server/src/api/tools_graph.rsindex 3de81450..0d02380d 100644--- a/crates/utopia-server/src/api/tools_graph.rs+++ b/crates/utopia-server/src/api/tools_graph.rs@@ -97,6 +97,8 @@ struct Resolved {id: Uuid,name: String,note: Option<String>,+ /// 参数本来就是一个 id:没在库里查过,`name` 也只是那串 id+ by_id: bool,}enum ResolveError {@@ -120,6 +122,7 @@ async fn resolve(id,name: raw.to_string(),note: None,+ by_id: true,});}let (hits, _) = lookup(ctx, raw).await.map_err(|e| {@@ -166,6 +169,7 @@ async fn resolve(id: first.id,name: first.name.clone(),note: Some(note),+ by_id: false,})}@@ -1057,6 +1061,19 @@ pub(super) fn path_text(p: &Path) -> String {parts.join("; ")}+/// 一个端点在这条路径上的名字:路径两头的边写着它+fn name_on_path(p: &Path, id: Uuid) -> Option<&str> {+ p.edges.iter().find_map(|e| {+ if e.subject_id == id {+ Some(e.subject_name.as_str())+ } else if e.object_id == id {+ Some(e.object_name.as_str())+ } else {+ None+ }+ })+}+pub async fn paths_between(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value) -> ToolResult {let mut notes = Vec::new();let mut ends = Vec::new();@@ -1083,7 +1100,6 @@ pub async fn paths_between(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value)}}}- let (from, to) = (&ends[0], &ends[1]);let m = moments(args);let max_hops = args["max_hops"].as_u64()@@ -1097,8 +1113,8 @@ pub async fn paths_between(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value)let paths = match utopia_store::paths::paths_between(&ctx.state.pool,ctx.kb_id,- from.id,- to.id,+ ends[0].id,+ ends[1].id,m.at,m.as_of,limits,@@ -1115,6 +1131,41 @@ pub async fn paths_between(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value).error();}};+ // 以 id 给出的一端没在库里查过。找到了路径,它就在路上,名字写在边上;没找到,+ // 可能只是这个 id 不在这个库(抄错的、别的库的)——那时「两者之间没有路径」+ // 读起来像一个关于图的事实,所以先认一遍,认不出就照实说+ for (key, end) in ["from", "to"].into_iter().zip(ends.iter_mut()) {+ if !end.by_id {+ continue;+ }+ if let Some(p) = paths.first() {+ if let Some(name) = name_on_path(p, end.id) {+ end.name = name.to_string();+ }+ continue;+ }+ match utopia_store::graph::entity_node(&ctx.state.pool, ctx.kb_id, end.id, m.as_of).await {+ Ok(Some(node)) => end.name = node.name,+ Ok(None) => {+ return ToolResult::new(+ format!(+ "Unknown `{key}`: no entity with id {} in this base.",+ end.id+ ),+ json!({ "kind": "path", "label": "?", "detail": "unknown entity" }),+ )+ }+ Err(e) => {+ tracing::warn!(error = %e, "Entity lookup failed");+ return ToolResult::new(+ "Could not look up entities.".into(),+ json!({ "kind": "path", "label": "?", "detail": "failed" }),+ )+ .error();+ }+ }+ }+ let (from, to) = (&ends[0], &ends[1]);let label = format!("{} ↔ {}", from.name, to.name);let when = match (m.at, m.before, m.as_of) {(Some(t), _, _) => format!(" at {}", crate::time_text::world(t, Some("day"))),diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rsindex fb3293e1..50d4c439 100644--- a/crates/utopia-store/src/graph.rs+++ b/crates/utopia-store/src/graph.rs@@ -1513,15 +1513,15 @@ pub async fn search_entities(Ok((nodes, total))}-/// 实体详情:节点信息 + 事实时间线。-pub async fn entity_detail(+/// 一个实体节点本身,不带事实:只想知道它在不在这个库、叫什么的时候用。+/// `entity_detail` 会把全部事实一起读出来,一个枢纽实体就是几百行+pub async fn entity_node(pool: &PgPool,kb_id: Uuid,entity_id: Uuid,- at: Option<chrono::DateTime<chrono::Utc>>,as_of: Option<chrono::DateTime<chrono::Utc>>,-) -> AppResult<(GraphNode, Vec<EntityFact>)> {- let node: GraphNode = sqlx::query_as(&format!(+) -> AppResult<Option<GraphNode>> {+ Ok(sqlx::query_as(&format!("{} WHERE e.kb_id = $1 AND e.id = $2",node_sql(as_of.map(|_| 3), as_of.map(|_| 3))))@@ -1529,8 +1529,20 @@ pub async fn entity_detail(.bind(entity_id).bind(as_of).fetch_optional(pool)- .await?- .ok_or(AppError::NotFound)?;+ .await?)+}++/// 实体详情:节点信息 + 事实时间线。+pub async fn entity_detail(+ pool: &PgPool,+ kb_id: Uuid,+ entity_id: Uuid,+ at: Option<chrono::DateTime<chrono::Utc>>,+ as_of: Option<chrono::DateTime<chrono::Utc>>,+) -> AppResult<(GraphNode, Vec<EntityFact>)> {+ let node = entity_node(pool, kb_id, entity_id, as_of)+ .await?+ .ok_or(AppError::NotFound)?;let mut facts: Vec<EntityFact> = sqlx::query_as(&format!("SELECT f.id, {said_as} AS said_as, f.recorded_at, f.invalidated_at, f.supersedes,