Skip to content

World's first open-source enterprise world model.

The graph answers with paths, neighbours and a timeline (#565)

WaylandYangf7712c9c09a6
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index e7400ec4..26594845 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -645,6 +645,8 @@ pub struct EntityFact {
pub temporal: Option<String>,
pub other_id: Option<Uuid>,
pub other_name: Option<String>,
+ /// 对端实体的类型标签;属性事实没有对端时为 None
+ pub other_type: Option<String>,
/// 字面值宾语(属性事实/问数映射):{"value":…,"unit":…} 或 {"summary":…}
pub object_value: Option<serde_json::Value>,
pub valid_from: Option<DateTime<Utc>>,
diff --git a/crates/utopia-server/src/api/chat.rs b/crates/utopia-server/src/api/chat.rs
index d982d999..a12121a0 100644
--- a/crates/utopia-server/src/api/chat.rs
+++ b/crates/utopia-server/src/api/chat.rs
@@ -366,11 +366,18 @@ pub(super) fn base_tools() -> serde_json::Value {
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.",
+ those as given rather than re-deriving them from the readings yourself. \
+ Output is grouped by predicate and cut at `limit`; narrow with predicate, \
+ object_type, since / until, or use timeline / neighbors / paths_between.",
"parameters": {
"type": "object",
"properties": {
- "entity_id": { "type": "string", "description": "Entity id (uuid) from find_entities." },
+ "entity_id": { "type": "string", "description": "Entity id (uuid) from find_entities, or an entity name (the server picks the best match and says which)." },
+ "predicate": { "type": "string", "description": "Optional: only facts whose relation name contains this (e.g. 'founder')." },
+ "object_type": { "type": "string", "description": "Optional: only facts whose other end is of this type (e.g. 'Person')." },
+ "since": { "type": "string", "description": "Optional WORLD-time window start: facts still holding after it." },
+ "until": { "type": "string", "description": "Optional WORLD-time window end: facts that had started by it." },
+ "limit": { "type": "integer", "description": "How many facts to return (default 80, max 300); the reply says when it is cut." },
"at": {
"type": "string",
"description": "Optional as-of moment on the WORLD axis (YYYY, YYYY-MM, \
@@ -390,6 +397,62 @@ pub(super) fn base_tools() -> serde_json::Value {
}
}
},
+ {
+ "type": "function",
+ "function": {
+ "name": "paths_between",
+ "description": "How two entities are connected in the knowledge graph: the chains of facts that join them, up to 3 hops, shortest first. THE tool for 'what is the relation between A and B', 'how is X linked to Y', 'who connects A and B'. Both ends take an entity name or an id; with a name the server picks the best match and says which. Pass `at` to require every edge to hold at that moment (world time), `as_of` to read the base as recorded then. Each edge comes with its validity range.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "from": { "type": "string", "description": "One end: entity name, or an id from find_entities." },
+ "to": { "type": "string", "description": "The other end: entity name, or an id." },
+ "max_hops": { "type": "integer", "description": "Longest chain to consider, 1-3 (default 3)." },
+ "at": { "type": "string", "description": "Optional WORLD-time moment (YYYY, YYYY-MM, YYYY-MM-DD): every edge on a path must hold then." },
+ "as_of": { "type": "string", "description": "Optional RECORD-time moment: the paths as the base held them then." }
+ },
+ "required": ["from", "to"]
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "neighbors",
+ "description": "The entities linked to one entity, grouped by predicate, one hop. Use it to see what surrounds an entity before deciding where to look next (each further hop is another call); narrow with `predicate` (e.g. 'founder', 'employee') or `object_type` (e.g. 'Person'). Attribute values are not neighbors; entity_facts has them.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "entity": { "type": "string", "description": "Entity name, or an id from find_entities." },
+ "predicate": { "type": "string", "description": "Optional: only relations whose name contains this." },
+ "object_type": { "type": "string", "description": "Optional: only neighbors of this type (name contains)." },
+ "at": { "type": "string", "description": "Optional WORLD-time moment: only links valid then." },
+ "as_of": { "type": "string", "description": "Optional RECORD-time moment." },
+ "limit": { "type": "integer", "description": "How many to return (default 40, max 300)." }
+ },
+ "required": ["entity"]
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "timeline",
+ "description": "One entity's dated facts in world-time order: THE tool for 'the timeline of X', 'the history of X', 'what happened to X between <year> and <year>'. Only facts with a stated date appear; narrow with `since` / `until` (world time) or `predicate`.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "entity": { "type": "string", "description": "Entity name, or an id from find_entities." },
+ "since": { "type": "string", "description": "Optional start of the window (YYYY, YYYY-MM, YYYY-MM-DD)." },
+ "until": { "type": "string", "description": "Optional end of the window." },
+ "predicate": { "type": "string", "description": "Optional: only relations whose name contains this." },
+ "as_of": { "type": "string", "description": "Optional RECORD-time moment: the timeline as the base held it then." },
+ "limit": { "type": "integer", "description": "How many to return (default 60, max 300)." }
+ },
+ "required": ["entity"]
+ }
+ }
+ },
{
"type": "function",
"function": {
@@ -451,8 +514,9 @@ pub(super) fn base_tools() -> serde_json::Value {
const SYSTEM_PROMPT: &str = "You are the assistant of Utopia, a temporal knowledge platform. \
You have tools: search_chunks (document search) and get_document (the full text of one \
- document found by search), find_entities, entity_facts and changes (a bi-temporal \
- knowledge graph), and search_docs (Utopia's own manual, the Charter).\n\
+ document found by search), find_entities, entity_facts, neighbors, timeline, \
+ paths_between and changes (a bi-temporal knowledge graph), and search_docs (Utopia's \
+ own manual, the Charter).\n\
search_chunks returns short excerpts of the best-matching sections only. When a hit is \
clearly the right document but the excerpt does not carry the answer, read the whole \
document with get_document before saying the knowledge base does not have it.\n\
@@ -475,16 +539,17 @@ const SYSTEM_PROMPT: &str = "You are the assistant of Utopia, a temporal knowled
preamble about what you are or are not looking up. Everything below is for messages about \
the user's data.\n\
1. For factual questions — questions about the user's data, never one about this \
- conversation — ALWAYS gather evidence with tools before answering. Prefer the \
- graph tools for questions about people/organizations/projects and time (\"who was X \
- when\", \"what changed\"), search_chunks for content and detail questions. Combine both \
- when useful.\n\
+ conversation — ALWAYS gather evidence with tools before answering. For how two \
+ things are related, call paths_between (names are fine); for the history of one \
+ thing, timeline; to see what is linked to it, neighbors; for its facts, entity_facts, \
+ narrowed with predicate / object_type / since / until. search_chunks answers content \
+ and detail questions. Combine both when useful.\n\
2. Facts carry validity ranges (from → to). For \"as of <date>\" questions pass `at` to \
entity_facts and the server filters to that moment; for history questions omit `at` \
to see the full timeline. For 'what did we know / have on record / believe as of <date>' or 'before <memo> arrived' pass `as_of` — that is the record axis and the ONLY way to answer such a question; do not narrate a plan, call the tool. The two combine: `at` for the date asked about, `as_of` for when. State dates in the answer. Dates in tool output carry their own precision: \
`2023` means the year and `2023-06` the month — never turn them into a specific day; \
- `attested <time>` marks a fact with no stated start, known only from that evidence on; \
- `ended by <time>` marks one the text says is over, date not given.\n\
+ `undated` marks a fact with no stated start; \
+ `ended, date unknown` marks one the text says is over, date not given.\n\
2a. For 'before a correction or memo arrived', call changes to find its exact record timestamp, \
then call entity_facts with `before` set to that timestamp, copied exactly as printed — the \
server reads the base as it stood strictly before that change. Never compute an earlier \
@@ -882,6 +947,7 @@ pub async fn chat(
actor: Some(user.id),
// 网页端对话不经令牌:说话的就是这个人本人
via_token: None,
+ question: Some(&query),
};
let (result, step) = tools::dispatch(&ctx, &mut sink, &call.name, &args).await;
// **这一步发生在正文的哪个位置。**
diff --git a/crates/utopia-server/src/api/mcp.rs b/crates/utopia-server/src/api/mcp.rs
index 56038e7f..6c15e76f 100644
--- a/crates/utopia-server/src/api/mcp.rs
+++ b/crates/utopia-server/src/api/mcp.rs
@@ -40,7 +40,7 @@ const PROTOCOL_VERSION: &str = "2025-06-18";
/// 「凭什么算含气井」时,该读到那条规则和它的阈值,而不是自己猜一个。
/// **写规则不放**:推理的判据由人写下,而一次工具调用分不出「人口述、agent
/// 代打」与「模型自己编了一条」
-const EXPOSED: [&str; 8] = [
+const EXPOSED: [&str; 11] = [
"search_chunks",
"get_document",
"search_docs",
@@ -49,6 +49,9 @@ const EXPOSED: [&str; 8] = [
"rule_matches",
"changes",
"entity_facts",
+ "neighbors",
+ "timeline",
+ "paths_between",
];
/// 会往账本里写的那些。
@@ -215,6 +218,8 @@ pub async fn handle(
actor: Some(user.id),
// 「谁说的」要答到 agent 这一层:一个人可以同时挂三个客户端
via_token: Some(auth.token_id),
+ // agent 的意图不在请求里;同名按事实数排
+ question: None,
};
let mut sink = ToolSink::default();
let (text, _step) = tools::dispatch(&ctx, &mut sink, name, &args).await;
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index fd762c37..9c3d0365 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -20,6 +20,7 @@ mod settings_routes;
mod sources_routes;
mod token_routes;
mod tools;
+mod tools_graph;
mod workspaces;
use axum::extract::DefaultBodyLimit;
diff --git a/crates/utopia-server/src/api/tools.rs b/crates/utopia-server/src/api/tools.rs
index 4aa2ea40..06b74bf0 100644
--- a/crates/utopia-server/src/api/tools.rs
+++ b/crates/utopia-server/src/api/tools.rs
@@ -42,6 +42,29 @@ pub struct ToolCtx<'a> {
/// 经 MCP 时,是哪一枚令牌在说话。**人之外还要记它**:一个人可以同时挂
/// 三个 agent,审核卡上只写人名分不出是哪一个记的(0026)。对话里为 None
pub via_token: Option<Uuid>,
+ /// 用户这一轮的原话。图谱工具拿它消歧:同名候选按「谁的上下文画像离这个问题近」排。
+ /// MCP 没有它(agent 的意图不在请求里),那边按事实数排
+ pub question: Option<&'a str>,
+}
+
+impl ToolCtx<'_> {
+ /// 一段文字的向量,用这个工作区配的嵌入模型。没配、或调用失败时 None:
+ /// 图谱工具照常按子串走,向量只是第二阶段
+ pub async fn embed(&self, text: &str) -> Option<Vec<f32>> {
+ let settings = utopia_store::settings::get(&self.state.pool, self.workspace_id)
+ .await
+ .ok()
+ .flatten()?;
+ let client = crate::llm_util::embed_client(&settings)?;
+ match client.embed(&[text.to_string()]).await {
+ Ok(mut v) if !v.is_empty() => Some(v.remove(0)),
+ Ok(_) => None,
+ Err(e) => {
+ tracing::warn!(error = %e, "嵌入失败,图谱工具按子串匹配");
+ None
+ }
+ }
+ }
}
/// 工具执行过程中往外攒的东西。
@@ -73,8 +96,11 @@ pub async fn dispatch(
"search_chunks" => search_chunks(ctx, sink, args).await,
"get_document" => get_document(ctx, sink, args).await,
"search_docs" => search_docs(ctx, sink, args).await,
- "find_entities" => find_entities(ctx, sink, args).await,
- "entity_facts" => entity_facts(ctx, args).await,
+ "find_entities" => super::tools_graph::find_entities(ctx, sink, args).await,
+ "entity_facts" => super::tools_graph::entity_facts(ctx, sink, args).await,
+ "neighbors" => super::tools_graph::neighbors(ctx, sink, args).await,
+ "timeline" => super::tools_graph::timeline(ctx, sink, args).await,
+ "paths_between" => super::tools_graph::paths_between(ctx, sink, args).await,
"changes" => changes(ctx, args).await,
// 业务规则只读(0021):判据要看得见,但**写规则不开给模型**——
// 「推理的判据由人写」是 0002 与 0021 共同的那条线,而一个工具调用
@@ -270,129 +296,6 @@ pub async fn search_docs(
)
}
-pub async fn find_entities(
- ctx: &ToolCtx<'_>,
- sink: &mut ToolSink,
- args: &serde_json::Value,
-) -> ToolResult {
- let name = args["name"].as_str().unwrap_or("").to_string();
- let (hits, _) = utopia_store::graph::search_entities(&ctx.state.pool, ctx.kb_id, &name, 8, 0)
- .await
- .unwrap_or_default();
- let text = if hits.is_empty() {
- "No matching entities.".to_string()
- } else {
- hits.iter()
- .map(|n| {
- let dis = n
- .disambiguator
- .as_deref()
- .map(|d| format!(" ({d})"))
- .unwrap_or_default();
- format!(
- "{} | {}{} | {} | {} facts",
- n.id,
- n.name,
- dis,
- // 没判出类型的实体照样能被搜到、被引用(0009)
- n.type_label.as_deref().unwrap_or("untyped"),
- n.degree
- )
- })
- .collect::<Vec<_>>()
- .join("\n")
- };
- for n in &hits {
- sink.resolved.push(json!({
- "id": n.id.to_string(), "name": n.name, "type": n.type_label
- }));
- }
- (
- text,
- json!({ "kind": "entity", "label": name, "detail": format!("{} matches", hits.len()) }),
- )
-}
-
-pub async fn entity_facts(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult {
- let id = args["entity_id"]
- .as_str()
- .and_then(|s| s.parse::<Uuid>().ok());
- // 世界轴过滤在 SQL 里(world_axis,0022):没起点的事实从最早的证据起,结束了
- // 不知哪天的到说出它的那份文档为止。这里只把 T 传下去,不自己解释 NULL
- let at = args["at"].as_str().and_then(parse_when);
- // 记录轴(0019 / #347):那一刻**我们持有**的事实。两根轴两个参数,绝不合成
- // 一个——合起来就会拿「三月的世界,以今天的认知」去答「三月的世界,以三月的认知」
- // 「更正到来之前」(#416):`before` 是 changes 里印出来的那个时刻,原样抄过来。
- // 账本的钟是微秒,「严格早于 T」就是「不晚于 T 减一微秒」——这一步在这里做,
- // 不让模型对着 ISO 字符串算小数秒的借位:算错一位,答的就是更正**之后**的状态,
- // 而且看不出来(#351 那种错)。给了 before 就以它为准
- let before = args["before"].as_str().and_then(parse_when);
- let as_of = match before {
- Some(t) => Some(just_before(t)),
- None => args["as_of"].as_str().and_then(parse_when),
- };
- let Some(id) = id else {
- return (
- "Invalid entity_id (expected the uuid returned by find_entities).".to_string(),
- json!({ "kind": "facts", "label": "?", "detail": "invalid id" }),
- );
- };
- match utopia_store::graph::entity_detail(&ctx.state.pool, ctx.kb_id, id, at, as_of).await {
- Ok((node, facts)) => {
- // 规则的结论也是这个实体的一部分(0021)。**不给的话模型会拿那些
- // 读数自己再判一遍**——而阈值写在规则里,它看不见,于是两处判断
- // 迟早不一致,agent 那次还没有前提链、没有区间、也不进账本
- // 两根轴一起传(#549):as_of 回到三月,派生也回到三月,不然模型
- // 拿到的是「三月的断言 + 今天的结论」,一条前提都不在,结论却在
- let derived = utopia_store::reasoning::derived_for_entity(
- &ctx.state.pool,
- ctx.kb_id,
- id,
- at,
- as_of,
- )
- .await
- .unwrap_or_default();
- let mut derived: Vec<String> = derived
- .iter()
- .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 {}.",
- node.name,
- crate::time_text::instant(t)
- ),
- None => format!("{}: no recorded facts.", node.name),
- }
- } else {
- let mut lines: Vec<String> = facts.iter().map(fact_line).collect();
- lines.append(&mut derived);
- lines.join("\n")
- };
- let detail = entity_facts_detail(facts.len(), at, as_of, before);
- (
- text,
- json!({ "kind": "facts", "label": node.name, "detail": detail }),
- )
- }
- Err(_) => (
- "Entity not found.".to_string(),
- json!({ "kind": "facts", "label": "?", "detail": "not found" }),
- ),
- }
-}
-
/// 这个库的判据。**把阈值原样给出来**——模型要能解释「凭什么算含气井」,
/// 而不是猜一个听起来合理的门槛。
pub async fn list_rules(ctx: &ToolCtx<'_>) -> ToolResult {
@@ -733,7 +636,7 @@ async fn run_query(state: &AppState, ds_id: Uuid, sql: &str) -> anyhow::Result<S
}
/// 事实行:"works at → 星云科技 (2023-08 → now) [90%]",in 方向用 ←。
-fn fact_line(f: &EntityFact) -> String {
+pub(super) fn fact_line(f: &EntityFact) -> String {
// 属性事实没有对端实体,值在 `object_value` 里(0004)。从前这里只看 `other_name`,
// 于是薪资、职位到了模型眼前是 `salary → ?`——区间和置信度都在,唯独值没到,
// 模型只能说"没有薪资信息"(#348)。渲染规则与客户端 `fmtObjectValue` 一致
@@ -781,11 +684,11 @@ fn record_stamp(time: chrono::DateTime<chrono::Utc>) -> String {
/// 严格早于 T,按账本的分辨率(timestamptz 是微秒):不晚于 T − 1µs。
/// `recorded_at <= T−1µs` 恰好是 `recorded_at < T`,`invalidated_at > T−1µs` 恰好是
/// `invalidated_at >= T`——0019 的 held_at 一个字不用改
-fn just_before(t: chrono::DateTime<chrono::Utc>) -> chrono::DateTime<chrono::Utc> {
+pub(super) fn just_before(t: chrono::DateTime<chrono::Utc>) -> chrono::DateTime<chrono::Utc> {
t - chrono::Duration::microseconds(1)
}
-fn entity_facts_detail(
+pub(super) fn entity_facts_detail(
count: usize,
at: Option<chrono::DateTime<chrono::Utc>>,
as_of: Option<chrono::DateTime<chrono::Utc>>,
@@ -807,7 +710,7 @@ fn entity_facts_detail(
/// 时刻参数:`YYYY-MM-DD` 或 RFC3339。`at` 与 `as_of` 共用一个解析——记录轴上的
/// 时刻常常是一个带时间的戳("第一波灌完那一刻"),日期粒度装不下它
-fn parse_when(raw: &str) -> Option<chrono::DateTime<chrono::Utc>> {
+pub(super) fn parse_when(raw: &str) -> Option<chrono::DateTime<chrono::Utc>> {
let s = raw.trim();
// 完整的 RFC3339 时刻原样收下,小数秒也留着——记录轴上同一秒内可以先录入再更正
// (#351),这里截掉一位就把两次认知叠回一起。日期形式(YYYY / YYYY-MM / YYYY-MM-DD,
@@ -821,7 +724,7 @@ fn parse_when(raw: &str) -> Option<chrono::DateTime<chrono::Utc>> {
/// 字面值宾语给模型看的样子:`{value, unit}` → "28000 CNY",布尔 → ✓/✗,
/// 映射那类 `{summary}` → 摘要本身。与 `web/src/pages/Graph.tsx::fmtObjectValue` 同一条规则,
/// 两边分叉的话,人看到的和模型看到的就不是同一个值
-fn literal_text(v: &serde_json::Value) -> Option<String> {
+pub(super) fn literal_text(v: &serde_json::Value) -> Option<String> {
// 裸标量(`changes` 那头的旧数据长这样):字符串读成它自己,不带引号
match v {
serde_json::Value::Null => return None,
@@ -1142,6 +1045,7 @@ mod tests {
temporal: Some("state".into()),
other_id: None,
other_name: None,
+ other_type: None,
object_value: Some(value),
valid_from: Some(t("2023-06-01T00:00:00Z")),
valid_to: Some(t("2024-02-20T00:00:00Z")),
diff --git a/crates/utopia-server/src/api/tools_graph.rs b/crates/utopia-server/src/api/tools_graph.rs
new file mode 100644
index 00000000..242df3d7
--- /dev/null
+++ b/crates/utopia-server/src/api/tools_graph.rs
@@ -0,0 +1,1202 @@
+//! 图谱查询工具(#558):`paths_between`、`neighbors`、`timeline`,以及
+//! `find_entities` 的排序和 `entity_facts` 的过滤与分组。
+//!
+//! 从前模型手里的图谱只有两个动作:按名找实体、倒出一个实体的全部事实。
+//! 「OpenAI 和 Anthropic 的关系」要它自己把两边几百条事实在上下文里连线,
+//! 十六次里三次连上;「OpenAI 的时间线」是一份 433 行的倾倒,它自己排序。
+//! 这里把查询的活收回服务端:路径是服务端搜的,邻居按谓词分好组,时间线按
+//! 世界时间排好,事实可以按谓词、对象类型、时段筛。
+//!
+//! **实体参数收 uuid 也收名字。** 收名字是为了省掉一轮 find_entities,以及那一轮
+//! 之后常见的「你说的是哪个 OpenAI」——排序规则挑一个,把挑了谁、还有谁一并
+//! 写在结果最上面,模型不同意就拿 id 再来一次。
+
+use super::tools::{
+ entity_facts_detail, fact_line, just_before, literal_text, parse_when, ToolCtx, ToolResult,
+ ToolSink,
+};
+use serde_json::{json, Value};
+use std::collections::{BTreeMap, HashMap, HashSet};
+use utopia_core::models::{EntityFact, GraphNode};
+use utopia_store::paths::{Limits, Path, PathEdge};
+use uuid::Uuid;
+
+const NEIGHBORS_DEFAULT: usize = 40;
+const TIMELINE_DEFAULT: usize = 60;
+const FACTS_DEFAULT: usize = 80;
+const LIST_MAX: usize = 300;
+
+// ---- 实体参数 -------------------------------------------------------------------
+
+/// 名字匹配的排序:**类型判出来的在前,同名精确命中在前,事实多的在前**。
+///
+/// 没类型的短语("lawsuit against OpenAI",#559)在有别的候选时不列:它们几乎全是
+/// 抽取漏进来的描述,列出来只会把问题变成一次消歧。全是 untyped 时照列——一个
+/// 类型都没判出来的库也得能用。**叫这个名字的照列,有没有类型都一样**:问的就是
+/// "Acme",而 Acme 本身还没判出类型时,只剩一个 "Acme lawsuit" 是把人引到错的实体上,
+/// 没类型的实体也得找得到(0009)。
+pub(super) fn rank(mut hits: Vec<GraphNode>, query: &str) -> Vec<GraphNode> {
+ let q = query.trim().to_lowercase();
+ let exact = |n: &GraphNode| n.name.trim().to_lowercase() == q;
+ if hits.iter().any(|n| n.type_label.is_some()) {
+ hits.retain(|n| n.type_label.is_some() || exact(n));
+ }
+ hits.sort_by(|a, b| {
+ exact(b)
+ .cmp(&exact(a))
+ .then(b.degree.cmp(&a.degree))
+ .then_with(|| a.name.cmp(&b.name))
+ });
+ hits
+}
+
+/// 第一名是不是明显的那一个:只有它,或只有它精确命中,或它的事实数是第二名的三倍
+pub(super) fn dominant(ranked: &[GraphNode], query: &str) -> bool {
+ let q = query.trim().to_lowercase();
+ match ranked {
+ [] => false,
+ [_] => true,
+ [first, second, ..] => {
+ let exact = |n: &GraphNode| n.name.trim().to_lowercase() == q;
+ (exact(first) && !exact(second)) || first.degree >= 3 * second.degree.max(1)
+ }
+ }
+}
+
+fn node_line(n: &GraphNode) -> String {
+ let dis = n
+ .disambiguator
+ .as_deref()
+ .map(|d| format!(" ({d})"))
+ .unwrap_or_default();
+ format!(
+ "{} | {}{} | {} | {} facts",
+ n.id,
+ n.name,
+ dis,
+ // 没判出类型的实体照样能被搜到、被引用(0009)
+ n.type_label.as_deref().unwrap_or("untyped"),
+ n.degree
+ )
+}
+
+fn remember(sink: &mut ToolSink, n: &GraphNode) {
+ sink.resolved.push(json!({
+ "id": n.id.to_string(), "name": n.name, "type": n.type_label
+ }));
+}
+
+/// 一个实体参数解析成 id。名字走 [`rank`],挑了谁写进 `note` 交给结果开头
+struct Resolved {
+ id: Uuid,
+ name: String,
+ note: Option<String>,
+}
+
+async fn resolve(ctx: &ToolCtx<'_>, sink: &mut ToolSink, raw: &str) -> Result<Resolved, String> {
+ let raw = raw.trim();
+ if raw.is_empty() {
+ return Err("an entity name or id is required".to_string());
+ }
+ if let Ok(id) = raw.parse::<Uuid>() {
+ return Ok(Resolved {
+ id,
+ name: raw.to_string(),
+ note: None,
+ });
+ }
+ let hits = lookup(ctx, raw).await;
+ let (ranked, by_question) = rank_by_question(ctx, rank(hits, raw), raw).await;
+ let Some(first) = ranked.first() else {
+ return Err(format!("no entity named \"{raw}\" in this base"));
+ };
+ remember(sink, first);
+ let others: Vec<String> = ranked
+ .iter()
+ .skip(1)
+ .take(4)
+ .map(|n| {
+ format!(
+ "{} ({}, {} facts, {})",
+ n.name,
+ n.type_label.as_deref().unwrap_or("untyped"),
+ n.degree,
+ n.id
+ )
+ })
+ .collect();
+ let mut note = format!(
+ "\"{raw}\" = {} ({}, {} facts)",
+ first.name,
+ first.type_label.as_deref().unwrap_or("untyped"),
+ first.degree
+ );
+ if by_question {
+ note.push_str(", closest to the question");
+ }
+ if !others.is_empty() {
+ note.push_str(&format!(
+ "; other matches: {}. Pass an id to choose another.",
+ others.join("; ")
+ ));
+ }
+ Ok(Resolved {
+ id: first.id,
+ name: first.name.clone(),
+ note: Some(note),
+ })
+}
+
+/// 时刻参数三件套:`at` 世界轴,`as_of` / `before` 记录轴(before 优先,减一微秒)
+struct Moments {
+ at: Option<chrono::DateTime<chrono::Utc>>,
+ as_of: Option<chrono::DateTime<chrono::Utc>>,
+ before: Option<chrono::DateTime<chrono::Utc>>,
+}
+
+fn moments(args: &Value) -> Moments {
+ let at = args["at"].as_str().and_then(parse_when);
+ let before = args["before"].as_str().and_then(parse_when);
+ let as_of = match before {
+ Some(t) => Some(just_before(t)),
+ None => args["as_of"].as_str().and_then(parse_when),
+ };
+ Moments { at, as_of, before }
+}
+
+fn limit_of(args: &Value, default: usize) -> usize {
+ args["limit"]
+ .as_u64()
+ .map(|n| n as usize)
+ .filter(|n| *n > 0)
+ .unwrap_or(default)
+ .min(LIST_MAX)
+}
+
+fn contains_ci(haystack: Option<&str>, needle: &str) -> bool {
+ haystack.is_some_and(|h| h.to_lowercase().contains(&needle.to_lowercase()))
+}
+
+// ---- find_entities ---------------------------------------------------------------
+
+pub async fn find_entities(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value) -> ToolResult {
+ let name = args["name"].as_str().unwrap_or("").to_string();
+ let hits = lookup(ctx, &name).await;
+ let (ranked, by_question) = rank_by_question(ctx, rank(hits, &name), &name).await;
+ let text = if ranked.is_empty() {
+ "No matching entities.".to_string()
+ } else if by_question || dominant(&ranked, &name) {
+ let mut lines = vec![format!("Best match: {}", node_line(&ranked[0]))];
+ if ranked.len() > 1 {
+ lines.push("Other matches:".to_string());
+ lines.extend(ranked[1..].iter().map(node_line));
+ }
+ lines.join("\n")
+ } else {
+ let mut lines = vec![format!(
+ "Several entities match \"{name}\"; pick by type and fact count, or ask the user:"
+ )];
+ lines.extend(ranked.iter().map(node_line));
+ lines.join("\n")
+ };
+ for n in &ranked {
+ remember(sink, n);
+ }
+ (
+ text,
+ json!({ "kind": "entity", "label": name, "detail": format!("{} matches", ranked.len()) }),
+ )
+}
+
+// ---- entity_facts ----------------------------------------------------------------
+
+/// 事实的另一端:对端实体,或属性值
+fn other_text(f: &EntityFact) -> String {
+ let literal = f
+ .object_value
+ .as_ref()
+ .and_then(literal_text)
+ .filter(|_| f.other_name.is_none());
+ f.other_name
+ .as_deref()
+ .or(literal.as_deref())
+ .unwrap_or("?")
+ .to_string()
+}
+
+fn range_text(f: &EntityFact) -> String {
+ let range = crate::time_text::span(crate::time_text::Span {
+ valid_from: f.valid_from,
+ from_precision: f.valid_from_precision.as_deref(),
+ valid_to: f.valid_to,
+ to_precision: f.valid_to_precision.as_deref(),
+ holds_from: f.holds_from,
+ holds_to: f.holds_to,
+ });
+ if range.is_empty() {
+ range
+ } else {
+ format!(" ({range})")
+ }
+}
+
+fn confidence_text(f: &EntityFact) -> String {
+ format!("[{}%]", (f.confidence * 100.0).round() as i32)
+}
+
+/// 谓词组的抬头:出边 `pred →`,入边 `← pred`
+fn group_key(f: &EntityFact) -> String {
+ let pred = f.predicate_label.as_deref().unwrap_or("?");
+ if f.direction == "out" {
+ format!("{pred} →")
+ } else {
+ format!("← {pred}")
+ }
+}
+
+/// 按谓词分组,多的组在前;组内保持传入顺序(时间序)。回 (组名, 该组事实)
+pub(super) fn grouped(facts: &[EntityFact]) -> Vec<(String, Vec<&EntityFact>)> {
+ let mut groups: BTreeMap<String, Vec<&EntityFact>> = BTreeMap::new();
+ for f in facts {
+ groups.entry(group_key(f)).or_default().push(f);
+ }
+ let mut out: Vec<(String, Vec<&EntityFact>)> = groups.into_iter().collect();
+ out.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then_with(|| a.0.cmp(&b.0)));
+ out
+}
+
+/// 过滤没命中时告诉模型这个实体身上有哪些谓词:它猜的词("board member")和
+/// 库里的词(`comprised`、`has_member`)常常对不上(#560),空手而回它只会再猜一次
+pub(super) fn predicates_of(facts: &[EntityFact]) -> String {
+ let mut counts: BTreeMap<String, usize> = BTreeMap::new();
+ for f in facts {
+ *counts.entry(group_key(f)).or_default() += 1;
+ }
+ let mut named: Vec<(String, usize)> = counts.into_iter().collect();
+ named.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
+ named
+ .iter()
+ .take(20)
+ .map(|(k, n)| format!("{k} ({n})"))
+ .collect::<Vec<_>>()
+ .join(", ")
+}
+
+/// 子串找不到时按词找:每个词各去库里捞一把,名字里含的词数达到「全部减一、至少两个」
+/// 的候选算命中("OpenAI board members" → "OpenAI's board of directors")。
+/// 模型给的名字常带一个库里没有的词(members、公司、这个),全词命中会把它们全漏掉
+async fn lookup(ctx: &ToolCtx<'_>, raw: &str) -> Vec<GraphNode> {
+ let (hits, _) = utopia_store::graph::search_entities(&ctx.state.pool, ctx.kb_id, raw, 8, 0)
+ .await
+ .unwrap_or_default();
+ if !hits.is_empty() {
+ return hits;
+ }
+ let words: Vec<&str> = raw.split_whitespace().filter(|w| w.len() >= 2).collect();
+ if words.len() < 2 {
+ return hits;
+ }
+ let mut pool: Vec<GraphNode> = Vec::new();
+ for w in &words {
+ let (found, _) = utopia_store::graph::search_entities(&ctx.state.pool, ctx.kb_id, w, 40, 0)
+ .await
+ .unwrap_or_default();
+ for n in found {
+ if !pool.iter().any(|p| p.id == n.id) {
+ pool.push(n);
+ }
+ }
+ }
+ let need = words.len().saturating_sub(1).max(2);
+ let mut scored: Vec<(usize, GraphNode)> = pool
+ .into_iter()
+ .map(|n| (word_score(&n.name, &words), n))
+ .filter(|(s, _)| *s >= need)
+ .collect();
+ scored.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.degree.cmp(&a.1.degree)));
+ scored.into_iter().map(|(_, n)| n).take(8).collect()
+}
+
+/// 名字里含了几个词(大小写不敏感)
+pub(super) fn word_score(name: &str, words: &[&str]) -> usize {
+ let lower = name.to_lowercase();
+ words
+ .iter()
+ .filter(|w| lower.contains(&w.to_lowercase()))
+ .count()
+}
+
+/// 同名候选按问题排:用户的问题嵌一次,与候选的上下文画像比,近的在前。
+/// 精确命中仍在前(问 OpenAI 就先给叫 OpenAI 的),画像只在同一档里排序。
+/// 没有问题(MCP)、没有嵌入模型、只有一个候选:原样返回,第二个值说明有没有用上
+async fn rank_by_question(
+ ctx: &ToolCtx<'_>,
+ ranked: Vec<GraphNode>,
+ query: &str,
+) -> (Vec<GraphNode>, bool) {
+ if ranked.len() < 2 {
+ return (ranked, false);
+ }
+ let Some(question) = ctx.question else {
+ return (ranked, false);
+ };
+ let Some(vec) = ctx.embed(question).await else {
+ return (ranked, false);
+ };
+ let ids: Vec<Uuid> = ranked.iter().map(|n| n.id).collect();
+ let Ok(dist) =
+ utopia_store::graph::profile_distances(&ctx.state.pool, ctx.kb_id, &ids, &vec).await
+ else {
+ return (ranked, false);
+ };
+ let dist: HashMap<Uuid, f64> = dist.into_iter().collect();
+ (reorder_by_distance(ranked, query, &dist), true)
+}
+
+/// 纯函数:精确命中的一档在前;档内按画像距离升序,没有画像的垫底;再按事实数
+pub(super) fn reorder_by_distance(
+ mut ranked: Vec<GraphNode>,
+ query: &str,
+ dist: &HashMap<Uuid, f64>,
+) -> Vec<GraphNode> {
+ let q = query.trim().to_lowercase();
+ let exact = |n: &GraphNode| n.name.trim().to_lowercase() == q;
+ ranked.sort_by(|a, b| {
+ exact(b)
+ .cmp(&exact(a))
+ .then_with(|| {
+ let da = dist.get(&a.id).copied().unwrap_or(f64::MAX);
+ let db = dist.get(&b.id).copied().unwrap_or(f64::MAX);
+ da.partial_cmp(&db).unwrap_or(std::cmp::Ordering::Equal)
+ })
+ .then(b.degree.cmp(&a.degree))
+ });
+ ranked
+}
+
+/// 谓词参数与库里的词对齐:模型说 "board member",库里叫 `has_member`。子串对不上时
+/// 把它嵌一次,取最近的关系类型(关系向量在 `relation_types.embedding`),距离在
+/// 上限内的算它说的是那几个。自动扩本体造出的关系没有向量(#560),对不到
+const PREDICATE_DISTANCE: f32 = 0.45;
+const PREDICATE_CANDIDATES: i64 = 5;
+
+async fn aligned_predicates(ctx: &ToolCtx<'_>, word: &str) -> Vec<String> {
+ let Some(vec) = ctx.embed(word).await else {
+ return Vec::new();
+ };
+ let near = utopia_store::ontology::nearest_relation_types(
+ &ctx.state.pool,
+ ctx.kb_id,
+ &vec,
+ PREDICATE_CANDIDATES,
+ None,
+ )
+ .await
+ .unwrap_or_default();
+ for c in &near {
+ tracing::debug!(word, key = c.key, distance = c.distance, "谓词对齐候选");
+ }
+ near.into_iter()
+ .filter(|c| c.distance <= PREDICATE_DISTANCE)
+ .map(|c| c.key)
+ .collect()
+}
+
+/// 过滤;谓词按子串对不上时向量对齐一次,回一句说明给结果开头
+async fn filtered<'f>(
+ ctx: &ToolCtx<'_>,
+ facts: &'f [EntityFact],
+ filter: &FactFilter<'_>,
+) -> (Vec<&'f EntityFact>, Option<String>) {
+ let kept: Vec<&EntityFact> = facts.iter().filter(|f| filter.keeps(f)).collect();
+ let Some(word) = filter.predicate else {
+ return (kept, None);
+ };
+ if !kept.is_empty() || facts.is_empty() {
+ return (kept, None);
+ }
+ let keys: HashSet<String> = aligned_predicates(ctx, word).await.into_iter().collect();
+ if keys.is_empty() {
+ return (kept, None);
+ }
+ let widened = FactFilter {
+ predicate: None,
+ ..*filter
+ };
+ let kept: Vec<&EntityFact> = facts
+ .iter()
+ .filter(|f| {
+ widened.keeps(f) && f.predicate_key.as_deref().is_some_and(|k| keys.contains(k))
+ })
+ .collect();
+ let mut names: Vec<&str> = keys.iter().map(String::as_str).collect();
+ names.sort();
+ let note = format!("predicate \"{word}\" read as {}", names.join(", "));
+ (kept, Some(note))
+}
+
+#[derive(Clone, Copy)]
+struct FactFilter<'a> {
+ predicate: Option<&'a str>,
+ object_type: Option<&'a str>,
+ since: Option<chrono::DateTime<chrono::Utc>>,
+ until: Option<chrono::DateTime<chrono::Utc>>,
+}
+
+impl FactFilter<'_> {
+ fn from_args(args: &Value) -> FactFilter<'_> {
+ FactFilter {
+ predicate: args["predicate"].as_str().filter(|s| !s.trim().is_empty()),
+ object_type: args["object_type"]
+ .as_str()
+ .filter(|s| !s.trim().is_empty()),
+ since: args["since"].as_str().and_then(parse_when),
+ until: args["until"].as_str().and_then(parse_when),
+ }
+ }
+
+ fn narrows(&self) -> bool {
+ self.predicate.is_some()
+ || self.object_type.is_some()
+ || self.since.is_some()
+ || self.until.is_some()
+ }
+
+ /// 时段用**说出来的**区间:起点在 until 之前、终点在 since 之后(开放的终点算在后)
+ fn keeps(&self, f: &EntityFact) -> bool {
+ if let Some(p) = self.predicate {
+ if !contains_ci(f.predicate_key.as_deref(), p)
+ && !contains_ci(f.predicate_label.as_deref(), p)
+ {
+ return false;
+ }
+ }
+ if let Some(t) = self.object_type {
+ if !contains_ci(f.other_type.as_deref(), t) {
+ return false;
+ }
+ }
+ if let Some(until) = self.until {
+ if f.valid_from.is_some_and(|from| from > until) {
+ return false;
+ }
+ }
+ if let Some(since) = self.since {
+ if f.valid_to.is_some_and(|to| to < since) {
+ return false;
+ }
+ }
+ true
+ }
+}
+
+pub async fn entity_facts(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value) -> ToolResult {
+ let raw = args["entity_id"]
+ .as_str()
+ .or_else(|| args["entity"].as_str())
+ .unwrap_or("");
+ let who = match resolve(ctx, sink, raw).await {
+ Ok(r) => r,
+ Err(e) => {
+ return (
+ format!(
+ "Invalid entity: {e} (expected a name, or the uuid returned by find_entities)."
+ ),
+ json!({ "kind": "facts", "label": "?", "detail": "invalid id" }),
+ )
+ }
+ };
+ let m = moments(args);
+ let filter = FactFilter::from_args(args);
+ let limit = limit_of(args, FACTS_DEFAULT);
+ let Ok((node, facts)) =
+ utopia_store::graph::entity_detail(&ctx.state.pool, ctx.kb_id, who.id, m.at, m.as_of).await
+ else {
+ return (
+ "Entity not found.".to_string(),
+ json!({ "kind": "facts", "label": "?", "detail": "not found" }),
+ );
+ };
+ // 规则的结论也是这个实体的一部分(0021)。**不给的话模型会拿那些读数自己再判
+ // 一遍**——而阈值写在规则里,它看不见,于是两处判断迟早不一致
+ let derived =
+ // 两根轴一起传(#549):as_of 回到三月,派生也回到三月
+ utopia_store::reasoning::derived_for_entity(
+ &ctx.state.pool,
+ ctx.kb_id,
+ who.id,
+ m.at,
+ m.as_of,
+ )
+ .await
+ .unwrap_or_default();
+ let derived: Vec<String> = derived
+ .iter()
+ .map(|d| {
+ format!(
+ "{} · {} · {} [rule: {}]",
+ d.subject,
+ d.predicate,
+ d.object,
+ d.rule_name.as_deref().unwrap_or(&d.rule),
+ )
+ })
+ .collect();
+
+ let (kept, aligned) = filtered(ctx, &facts, &filter).await;
+ let shown: Vec<&EntityFact> = kept.iter().copied().take(limit).collect();
+ let mut lines: Vec<String> = Vec::new();
+ if let Some(note) = &who.note {
+ lines.push(note.clone());
+ }
+ if let Some(a) = &aligned {
+ lines.push(a.clone());
+ }
+ let type_label = node.type_label.as_deref().unwrap_or("untyped");
+ if facts.is_empty() && derived.is_empty() {
+ lines.push(match m.at {
+ Some(t) => format!(
+ "{}: no facts valid as of {}.",
+ node.name,
+ crate::time_text::instant(t)
+ ),
+ None => format!("{}: no recorded facts.", node.name),
+ });
+ } else {
+ let mut head = format!("{} ({type_label}) · {} facts", node.name, facts.len());
+ if filter.narrows() {
+ head.push_str(&format!(", {} match the filter", kept.len()));
+ if kept.is_empty() {
+ head.push_str(&format!(
+ ". Predicates on this entity: {}",
+ predicates_of(&facts)
+ ));
+ }
+ }
+ if shown.len() < kept.len() {
+ head.push_str(&format!(
+ ", {} shown. Narrow with predicate=, object_type=, since/until; timeline for the \
+ dated ones; neighbors for the related entities",
+ shown.len()
+ ));
+ }
+ lines.push(head);
+ let shown_owned: Vec<EntityFact> = shown.iter().map(|f| (*f).clone()).collect();
+ for (key, group) in grouped(&shown_owned) {
+ lines.push(format!("## {key} ({})", group.len()));
+ for f in group {
+ lines.push(format!(
+ "{}{} {}",
+ other_text(f),
+ range_text(f),
+ confidence_text(f)
+ ));
+ }
+ }
+ lines.extend(derived);
+ }
+ let detail = entity_facts_detail(shown.len(), m.at, m.as_of, m.before);
+ (
+ lines.join("\n"),
+ json!({ "kind": "facts", "label": node.name, "detail": detail }),
+ )
+}
+
+// ---- neighbors -------------------------------------------------------------------
+
+pub async fn neighbors(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value) -> ToolResult {
+ let raw = args["entity"]
+ .as_str()
+ .or_else(|| args["entity_id"].as_str())
+ .unwrap_or("");
+ let who = match resolve(ctx, sink, raw).await {
+ Ok(r) => r,
+ Err(e) => {
+ return (
+ format!("Unknown entity: {e}."),
+ json!({ "kind": "neighbors", "label": "?", "detail": "unknown entity" }),
+ )
+ }
+ };
+ let m = moments(args);
+ let filter = FactFilter::from_args(args);
+ let limit = limit_of(args, NEIGHBORS_DEFAULT);
+ let Ok((node, facts)) =
+ utopia_store::graph::entity_detail(&ctx.state.pool, ctx.kb_id, who.id, m.at, m.as_of).await
+ else {
+ return (
+ "Entity not found.".to_string(),
+ json!({ "kind": "neighbors", "label": "?", "detail": "not found" }),
+ );
+ };
+ // 邻居是对端**实体**;属性值不算邻居,entity_facts 里有
+ let (matched, aligned) = filtered(ctx, &facts, &filter).await;
+ let linked: Vec<&EntityFact> = matched
+ .into_iter()
+ .filter(|f| f.other_id.is_some())
+ .collect();
+ let shown: Vec<EntityFact> = linked.iter().take(limit).map(|f| (*f).clone()).collect();
+ let mut lines: Vec<String> = Vec::new();
+ if let Some(note) = &who.note {
+ lines.push(note.clone());
+ }
+ if let Some(a) = &aligned {
+ lines.push(a.clone());
+ }
+ let type_label = node.type_label.as_deref().unwrap_or("untyped");
+ if shown.is_empty() {
+ let all_linked: Vec<EntityFact> = facts
+ .iter()
+ .filter(|f| f.other_id.is_some())
+ .cloned()
+ .collect();
+ let hint = if filter.narrows() && !all_linked.is_empty() {
+ format!(" Predicates on this entity: {}", predicates_of(&all_linked))
+ } else {
+ String::new()
+ };
+ lines.push(format!(
+ "{} ({type_label}): no linked entities{}.{hint}",
+ node.name,
+ if filter.narrows() {
+ " match the filter"
+ } else {
+ ""
+ }
+ ));
+ } else {
+ let groups = grouped(&shown);
+ // 数的是对端实体,不是事实:同一条边常是两条事实(一条带日期一条不带)
+ let entities: HashSet<Uuid> = linked.iter().filter_map(|f| f.other_id).collect();
+ let mut head = format!(
+ "{} ({type_label}): {} linked entities under {} predicates",
+ node.name,
+ entities.len(),
+ groups.len()
+ );
+ if shown.len() < linked.len() {
+ head.push_str(&format!(
+ " ({} shown; narrow with predicate= or object_type=)",
+ shown.len()
+ ));
+ }
+ lines.push(head);
+ for (key, group) in groups {
+ let items: Vec<String> = group
+ .iter()
+ .map(|f| {
+ let ty = f
+ .other_type
+ .as_deref()
+ .map(|t| format!(" [{t}]"))
+ .unwrap_or_default();
+ format!(
+ "{}{}{} {}",
+ other_text(f),
+ ty,
+ range_text(f),
+ confidence_text(f)
+ )
+ })
+ .collect();
+ lines.push(format!("{key} {}", items.join(" · ")));
+ }
+ }
+ let detail = format!("{} of {} linked", shown.len(), linked.len());
+ (
+ lines.join("\n"),
+ json!({ "kind": "neighbors", "label": node.name, "detail": detail }),
+ )
+}
+
+// ---- timeline --------------------------------------------------------------------
+
+pub async fn timeline(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value) -> ToolResult {
+ let raw = args["entity"]
+ .as_str()
+ .or_else(|| args["entity_id"].as_str())
+ .unwrap_or("");
+ let who = match resolve(ctx, sink, raw).await {
+ Ok(r) => r,
+ Err(e) => {
+ return (
+ format!("Unknown entity: {e}."),
+ json!({ "kind": "timeline", "label": "?", "detail": "unknown entity" }),
+ )
+ }
+ };
+ let m = moments(args);
+ let filter = FactFilter::from_args(args);
+ let limit = limit_of(args, TIMELINE_DEFAULT);
+ let Ok((node, facts)) =
+ utopia_store::graph::entity_detail(&ctx.state.pool, ctx.kb_id, who.id, None, m.as_of).await
+ else {
+ return (
+ "Entity not found.".to_string(),
+ json!({ "kind": "timeline", "label": "?", "detail": "not found" }),
+ );
+ };
+ // 只要**说出了世界时间**的事实。没日期的那些起点是摄取时刻,排进时间线只会
+ // 把一篇文章的日期当成事件的日期
+ let (matched, aligned) = filtered(ctx, &facts, &filter).await;
+ let mut dated: Vec<&EntityFact> = matched
+ .into_iter()
+ .filter(|f| f.valid_from.is_some())
+ .collect();
+ dated.sort_by_key(|f| f.valid_from);
+ let undated = facts.iter().filter(|f| f.valid_from.is_none()).count();
+ let shown: Vec<&EntityFact> = dated.iter().copied().take(limit).collect();
+ let mut lines: Vec<String> = Vec::new();
+ if let Some(note) = &who.note {
+ lines.push(note.clone());
+ }
+ if let Some(a) = &aligned {
+ lines.push(a.clone());
+ }
+ let type_label = node.type_label.as_deref().unwrap_or("untyped");
+ if shown.is_empty() {
+ lines.push(format!(
+ "{} ({type_label}): no dated facts{}; {undated} facts carry no date (entity_facts lists them).",
+ node.name,
+ if filter.narrows() { " in that window" } else { "" }
+ ));
+ } else {
+ let first = shown[0].valid_from.expect("dated");
+ let last = shown[shown.len() - 1].valid_from.expect("dated");
+ let mut head = format!("{} ({type_label}): {} dated facts", node.name, dated.len());
+ if shown.len() < dated.len() {
+ head.push_str(&format!(
+ ", {} shown from {} to {} (pass since/until to see the rest)",
+ shown.len(),
+ crate::time_text::world(first, shown[0].valid_from_precision.as_deref()),
+ crate::time_text::world(
+ last,
+ shown[shown.len() - 1].valid_from_precision.as_deref()
+ )
+ ));
+ }
+ if undated > 0 {
+ head.push_str(&format!(
+ "; {undated} undated facts omitted (entity_facts has them)"
+ ));
+ }
+ lines.push(head);
+ for f in &shown {
+ let stamp = crate::time_text::world(
+ f.valid_from.expect("dated"),
+ f.valid_from_precision.as_deref(),
+ );
+ lines.push(format!("{stamp} {}", fact_line(f)));
+ }
+ }
+ let detail = format!("{} of {} dated", shown.len(), dated.len());
+ (
+ lines.join("\n"),
+ json!({ "kind": "timeline", "label": node.name, "detail": detail }),
+ )
+}
+
+// ---- paths_between ---------------------------------------------------------------
+
+/// 一条边在链上的写法:顺着走 `A —pred→ B`,逆着走 `A ←pred— B`
+pub(super) fn edge_text(prev: Uuid, e: &PathEdge) -> String {
+ let pred = e.predicate.as_deref().unwrap_or("?");
+ let range = crate::time_text::span(crate::time_text::Span {
+ valid_from: e.valid_from,
+ from_precision: e.valid_from_precision.as_deref(),
+ valid_to: e.valid_to,
+ to_precision: e.valid_to_precision.as_deref(),
+ holds_from: e.holds_from,
+ holds_to: e.holds_to,
+ });
+ let range = if range.is_empty() {
+ range
+ } else {
+ format!(" ({range})")
+ };
+ let conf = (e.confidence * 100.0).round() as i32;
+ if e.subject_id == prev {
+ format!(
+ "{} —{pred}→ {}{range} [{conf}%]",
+ e.subject_name, e.object_name
+ )
+ } else {
+ format!(
+ "{} ←{pred}— {}{range} [{conf}%]",
+ e.object_name, e.subject_name
+ )
+ }
+}
+
+pub(super) fn path_text(p: &Path) -> String {
+ let mut parts = Vec::new();
+ for (i, e) in p.edges.iter().enumerate() {
+ parts.push(edge_text(p.nodes[i], e));
+ }
+ parts.join("; ")
+}
+
+pub async fn paths_between(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value) -> ToolResult {
+ let mut notes = Vec::new();
+ let mut ends = Vec::new();
+ for key in ["from", "to"] {
+ match resolve(ctx, sink, args[key].as_str().unwrap_or("")).await {
+ Ok(r) => {
+ if let Some(n) = &r.note {
+ notes.push(n.clone());
+ }
+ ends.push(r);
+ }
+ Err(e) => {
+ return (
+ format!("Unknown `{key}`: {e}."),
+ json!({ "kind": "path", "label": "?", "detail": "unknown entity" }),
+ )
+ }
+ }
+ }
+ let (from, to) = (&ends[0], &ends[1]);
+ let m = moments(args);
+ let max_hops = args["max_hops"]
+ .as_u64()
+ .map(|n| n as usize)
+ .unwrap_or(3)
+ .clamp(1, 3);
+ let limits = Limits {
+ max_hops,
+ ..Limits::default()
+ };
+ let paths = match utopia_store::paths::paths_between(
+ &ctx.state.pool,
+ ctx.kb_id,
+ from.id,
+ to.id,
+ m.at,
+ m.as_of,
+ limits,
+ )
+ .await
+ {
+ Ok(p) => p,
+ Err(e) => {
+ return (
+ format!("Path search failed: {e}"),
+ json!({ "kind": "path", "label": "?", "detail": "failed" }),
+ )
+ }
+ };
+ 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"))),
+ (None, Some(b), _) => format!(" as recorded before {}", crate::time_text::instant(b)),
+ (None, None, Some(r)) => format!(" as recorded by {}", crate::time_text::instant(r)),
+ (None, None, None) => String::new(),
+ };
+ let mut lines = notes;
+ if paths.is_empty() {
+ lines.push(format!(
+ "No path of up to {max_hops} hop{} between {} and {}{when}. They may be unrelated in \
+ this base, or connected only through a hub; try neighbors on each.",
+ if max_hops == 1 { "" } else { "s" },
+ from.name,
+ to.name
+ ));
+ return (
+ lines.join("\n"),
+ json!({ "kind": "path", "label": label, "detail": "no path" }),
+ );
+ }
+ let shortest = paths[0].hops();
+ lines.push(format!(
+ "{} path{} between {} and {}{when} (up to {max_hops} hops, shortest first):",
+ paths.len(),
+ if paths.len() == 1 { "" } else { "s" },
+ from.name,
+ to.name
+ ));
+ for (i, p) in paths.iter().enumerate() {
+ lines.push(format!("{}. {}", i + 1, path_text(p)));
+ }
+ let detail = format!(
+ "{} path{}, shortest {shortest} hop{}",
+ paths.len(),
+ if paths.len() == 1 { "" } else { "s" },
+ if shortest == 1 { "" } else { "s" }
+ );
+ (
+ lines.join("\n"),
+ json!({ "kind": "path", "label": label, "detail": detail }),
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn node(name: &str, ty: Option<&str>, degree: i64) -> GraphNode {
+ GraphNode {
+ id: Uuid::now_v7(),
+ name: name.into(),
+ type_key: ty.map(|t| t.to_lowercase()),
+ type_label: ty.map(String::from),
+ color: "#000".into(),
+ shape: "circle".into(),
+ degree,
+ disambiguator: None,
+ }
+ }
+
+ /// 短语实体(untyped)不列,精确命中在前,事实多的在前
+ #[test]
+ fn a_name_match_is_ranked_by_type_exactness_and_weight() {
+ let hits = vec![
+ node("lawsuit against OpenAI", None, 5),
+ node("OpenAI's board of directors", Some("Organization"), 23),
+ node("OpenAI", Some("ResearchProject"), 555),
+ node("OpenAI LP", Some("Corporation"), 6),
+ ];
+ let ranked = rank(hits, "OpenAI");
+ let names: Vec<&str> = ranked.iter().map(|n| n.name.as_str()).collect();
+ assert_eq!(
+ names,
+ ["OpenAI", "OpenAI's board of directors", "OpenAI LP"],
+ "untyped 短语不列,精确命中第一"
+ );
+ assert!(
+ dominant(&ranked, "OpenAI"),
+ "精确命中且事实数是第二名的三倍"
+ );
+ }
+
+ /// 精确命中的 untyped 实体不被同名的有类型实体挤掉
+ #[test]
+ fn an_exact_untyped_match_is_not_hidden_by_a_typed_namesake() {
+ let ranked = rank(
+ vec![
+ node("Acme lawsuit", Some("Event"), 1),
+ node("Acme", None, 200),
+ node("Acme corporate history", None, 4),
+ ],
+ "Acme",
+ );
+ let names: Vec<&str> = ranked.iter().map(|n| n.name.as_str()).collect();
+ assert_eq!(
+ names,
+ ["Acme", "Acme lawsuit"],
+ "叫这个名字的 untyped 照列且在前;别的 untyped 短语仍不列"
+ );
+ assert!(dominant(&ranked, "Acme"), "只有它精确命中");
+ }
+
+ #[test]
+ fn a_base_with_no_types_still_lists_its_entities() {
+ let ranked = rank(
+ vec![node("Acme", None, 3), node("Acme Corp", None, 9)],
+ "acme",
+ );
+ let names: Vec<&str> = ranked.iter().map(|n| n.name.as_str()).collect();
+ assert_eq!(
+ names,
+ ["Acme", "Acme Corp"],
+ "全 untyped 时照列,精确命中在前"
+ );
+ assert!(dominant(&ranked, "acme"));
+ }
+
+ /// 谁都不明显:两个同名同量级的实体,不替模型挑
+ #[test]
+ fn two_namesakes_of_equal_weight_are_not_dominant() {
+ let ranked = rank(
+ vec![
+ node("Zhang Wei", Some("Person"), 12),
+ node("Zhang Wei", Some("Person"), 10),
+ ],
+ "Zhang Wei",
+ );
+ assert!(!dominant(&ranked, "Zhang Wei"));
+ let ranked = rank(
+ vec![
+ node("Zhang Wei", Some("Person"), 40),
+ node("Zhang Wei", Some("Person"), 10),
+ ],
+ "Zhang Wei",
+ );
+ assert!(dominant(&ranked, "Zhang Wei"), "事实数三倍以上就明显");
+ }
+
+ fn fact(direction: &str, pred: &str, other: &str, other_type: Option<&str>) -> EntityFact {
+ EntityFact {
+ id: Uuid::now_v7(),
+ direction: direction.into(),
+ predicate_key: Some(pred.into()),
+ predicate_label: Some(pred.into()),
+ inferred: false,
+ temporal: Some("state".into()),
+ other_id: Some(Uuid::now_v7()),
+ other_name: Some(other.into()),
+ other_type: other_type.map(String::from),
+ object_value: None,
+ valid_from: Some("2021-01-01T00:00:00Z".parse().unwrap()),
+ valid_to: None,
+ valid_from_precision: Some("year".into()),
+ valid_to_precision: None,
+ holds_from: Some("2021-01-01T00:00:00Z".parse().unwrap()),
+ holds_to: None,
+ confidence: 0.9,
+ evidence_count: 1,
+ stale: false,
+ corrected: false,
+ last_evidence_time: None,
+ contested: None,
+ }
+ }
+
+ /// 问题的向量只在同一档里排序:精确命中的仍在前,档内近的先,没画像的垫底
+ #[test]
+ fn the_question_orders_namesakes_but_not_over_an_exact_match() {
+ let exact_far = node("Sam Altman", Some("Organization"), 66);
+ let exact_near = node("Sam Altman", Some("Person"), 27);
+ let partial_nearest = node("Sam Altman's efforts", Some("Event"), 2);
+ let no_profile = node("Sam Altman Jr", Some("Person"), 1);
+ let mut dist = HashMap::new();
+ dist.insert(exact_far.id, 0.40);
+ dist.insert(exact_near.id, 0.20);
+ dist.insert(partial_nearest.id, 0.05);
+ let ranked = reorder_by_distance(
+ vec![
+ exact_far.clone(),
+ no_profile.clone(),
+ partial_nearest.clone(),
+ exact_near.clone(),
+ ],
+ "Sam Altman",
+ &dist,
+ );
+ let ids: Vec<Uuid> = ranked.iter().map(|n| n.id).collect();
+ assert_eq!(
+ ids,
+ vec![
+ exact_near.id,
+ exact_far.id,
+ partial_nearest.id,
+ no_profile.id
+ ]
+ );
+ }
+
+ #[test]
+ fn a_multi_word_name_is_scored_by_the_words_it_contains() {
+ let words = ["OpenAI", "board", "members"];
+ assert_eq!(word_score("OpenAI's board of directors", &words), 2);
+ assert_eq!(word_score("OpenAI LP", &words), 1);
+ assert_eq!(word_score("openai board members list", &words), 3);
+ }
+
+ /// 空手而回时把实体身上的谓词报出来,多的在前
+ #[test]
+ fn an_empty_filter_names_the_predicates_that_exist() {
+ let facts = vec![
+ fact("out", "comprised", "Ilya Sutskever", Some("Person")),
+ fact("out", "comprised", "Helen Toner", Some("Person")),
+ fact("in", "removed", "Sam Altman", Some("Person")),
+ ];
+ assert_eq!(predicates_of(&facts), "comprised → (2), ← removed (1)");
+ }
+
+ /// 分组:多的组在前,出边 `pred →`,入边 `← pred`
+ #[test]
+ fn facts_group_by_predicate_largest_group_first() {
+ let facts = vec![
+ fact("out", "employee", "Bob", Some("Person")),
+ fact("in", "founder", "Carol", Some("Person")),
+ fact("out", "employee", "Dan", Some("Person")),
+ ];
+ let groups = grouped(&facts);
+ let keys: Vec<&str> = groups.iter().map(|(k, _)| k.as_str()).collect();
+ assert_eq!(keys, ["employee →", "← founder"]);
+ assert_eq!(groups[0].1.len(), 2);
+ }
+
+ /// 过滤:谓词按子串、对象类型按子串、时段按说出来的区间
+ #[test]
+ fn a_filter_reads_predicate_type_and_window() {
+ let mut f = fact("out", "works_for", "Acme", Some("Organization"));
+ f.valid_from = Some("2019-01-01T00:00:00Z".parse().unwrap());
+ f.valid_to = Some("2020-06-01T00:00:00Z".parse().unwrap());
+ fn filter<'a>(
+ p: Option<&'a str>,
+ t: Option<&'a str>,
+ since: Option<&str>,
+ until: Option<&str>,
+ ) -> FactFilter<'a> {
+ FactFilter {
+ predicate: p,
+ object_type: t,
+ since: since.map(|s| s.parse().unwrap()),
+ until: until.map(|s| s.parse().unwrap()),
+ }
+ }
+ assert!(filter(Some("works"), None, None, None).keeps(&f));
+ assert!(!filter(Some("founder"), None, None, None).keeps(&f));
+ assert!(filter(None, Some("organ"), None, None).keeps(&f));
+ assert!(!filter(None, Some("person"), None, None).keeps(&f));
+ assert!(
+ filter(None, None, Some("2020-01-01T00:00:00Z"), None).keeps(&f),
+ "2020 年初它还在"
+ );
+ assert!(
+ !filter(None, None, Some("2021-01-01T00:00:00Z"), None).keeps(&f),
+ "2021 年它已结束"
+ );
+ assert!(
+ !filter(None, None, None, Some("2018-06-01T00:00:00Z")).keeps(&f),
+ "2018 年它还没开始"
+ );
+ assert!(!filter(None, None, None, None).narrows());
+ }
+
+ /// 链的写法:顺着走用 →,逆着走用 ←,每条边带自己的区间
+ #[test]
+ fn a_chain_reads_in_walking_order() {
+ let (a, x, b) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let edge = |s: Uuid, sn: &str, o: Uuid, on: &str, pred: &str| PathEdge {
+ fact_id: Uuid::now_v7(),
+ subject_id: s,
+ subject_name: sn.into(),
+ object_id: o,
+ object_name: on.into(),
+ predicate: Some(pred.into()),
+ valid_from: Some("2021-01-01T00:00:00Z".parse().unwrap()),
+ valid_from_precision: Some("year".into()),
+ valid_to: None,
+ valid_to_precision: None,
+ holds_from: Some("2021-01-01T00:00:00Z".parse().unwrap()),
+ holds_to: None,
+ confidence: 0.9,
+ };
+ let p = Path {
+ nodes: vec![a, x, b],
+ edges: vec![
+ edge(a, "OpenAI", x, "Dario Amodei", "employee"),
+ edge(x, "Dario Amodei", b, "Anthropic", "founder"),
+ ],
+ specificity: 0.0,
+ };
+ assert_eq!(
+ path_text(&p),
+ "OpenAI —employee→ Dario Amodei (2021 → now) [90%]; Dario Amodei —founder→ Anthropic (2021 → now) [90%]"
+ );
+ let back = Path {
+ nodes: vec![b, x, a],
+ edges: vec![
+ edge(x, "Dario Amodei", b, "Anthropic", "founder"),
+ edge(a, "OpenAI", x, "Dario Amodei", "employee"),
+ ],
+ specificity: 0.0,
+ };
+ assert_eq!(
+ path_text(&back),
+ "Anthropic ←founder— Dario Amodei (2021 → now) [90%]; Dario Amodei ←employee— OpenAI (2021 → now) [90%]"
+ );
+ }
+}
diff --git a/crates/utopia-server/src/time_text.rs b/crates/utopia-server/src/time_text.rs
index 07c1c3a9..881e74ce 100644
--- a/crates/utopia-server/src/time_text.rs
+++ b/crates/utopia-server/src/time_text.rs
@@ -51,14 +51,18 @@ pub struct Span<'a> {
pub fn span(s: Span<'_>) -> String {
let from = match (s.valid_from, s.holds_from) {
(Some(t), _) => Some(world(t, s.from_precision)),
- (None, Some(a)) => Some(format!("attested {}", instant(a))),
+ // 没有说出来的起点就说没有。从前写 `attested <文档日期>`,模型把那个日期当成
+ // 事情发生的日子念出来("OpenAI 于 2026 年 9 月 6 日被确认为…");锚点是过滤用的,
+ // 不是给人读的
+ (None, Some(_)) => Some("undated".to_string()),
(None, None) => None,
};
let ended_unknown =
s.valid_to.is_none() && s.to_precision == Some(utopia_store::graph::ENDED_UNKNOWN);
let to = match (s.valid_to, ended_unknown, s.holds_to) {
(Some(t), _, _) => Some(world(t, s.to_precision)),
- (None, true, Some(a)) => Some(format!("ended by {}", instant(a))),
+ // 「结束了,不知哪天」照实说;说出它的那份文档的日期同样不给
+ (None, true, Some(_)) => Some("ended, date unknown".to_string()),
(None, true, None) => Some("ended, date unknown".to_string()),
(None, false, _) => None,
};
@@ -133,7 +137,7 @@ mod tests {
holds_from: day("2024-02-20T00:00:00Z"),
..Span::default()
}),
- "attested 2024-02-20T00:00:00Z → now"
+ "undated → now"
);
// 结束了不知哪天:到说出它的那份文档为止,绝不是 now
assert_eq!(
@@ -145,7 +149,7 @@ mod tests {
holds_from: day("2023-06-01T00:00:00Z"),
holds_to: day("2025-10-15T00:00:00Z"),
}),
- "2023-06-01 → ended by 2025-10-15T00:00:00Z"
+ "2023-06-01 → ended, date unknown"
);
// 记录轴事件里没有锚点可用
assert_eq!(
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index e327e2cb..37234e7e 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -832,6 +832,30 @@ pub async fn neighborhood(
Ok((nodes, edges))
}
+/// 这批实体的上下文画像与一个向量的余弦距离;没有画像的不在结果里。
+/// 图谱工具拿用户的问题来比:同名的几个里,谁的画像离问题近,问的多半是谁
+pub async fn profile_distances(
+ pool: &PgPool,
+ kb_id: Uuid,
+ ids: &[Uuid],
+ embedding: &[f32],
+) -> AppResult<Vec<(Uuid, f64)>> {
+ if ids.is_empty() {
+ return Ok(Vec::new());
+ }
+ let rows: Vec<(Uuid, f64)> = sqlx::query_as(
+ "SELECT e.id, (e.profile_embedding <=> $3)::float8
+ FROM entities e
+ WHERE e.kb_id = $1 AND e.id = ANY($2) AND e.profile_embedding IS NOT NULL",
+ )
+ .bind(kb_id)
+ .bind(ids)
+ .bind(pgvector::Vector::from(embedding.to_vec()))
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
/// 按名字找实体。**一并回总数**——「宁分勿合」本来就会造出一堆同名,
/// 固定十条的时候,想找的那个可能根本不在这十条里而界面上看不出来。
pub async fn search_entities(
@@ -844,7 +868,8 @@ pub async fn search_entities(
let pattern = format!("%{}%", q.trim());
let nodes: Vec<GraphNode> = sqlx::query_as(&format!(
"{} WHERE e.kb_id = $1 AND e.merged_into IS NULL
- AND e.canonical_name ILIKE $2
+ AND (e.canonical_name ILIKE $2
+ OR EXISTS (SELECT 1 FROM unnest(e.aliases) AS a WHERE a ILIKE $2))
ORDER BY degree DESC, e.canonical_name LIMIT $3 OFFSET $4",
node_sql(None, None)
))
@@ -856,7 +881,9 @@ pub async fn search_entities(
.await?;
let (total,): (i64,) = sqlx::query_as(
"SELECT count(*) FROM entities e
- WHERE e.kb_id = $1 AND e.merged_into IS NULL AND e.canonical_name ILIKE $2",
+ WHERE e.kb_id = $1 AND e.merged_into IS NULL
+ AND (e.canonical_name ILIKE $2
+ OR EXISTS (SELECT 1 FROM unnest(e.aliases) AS a WHERE a ILIKE $2))",
)
.bind(kb_id)
.bind(&pattern)
@@ -891,7 +918,7 @@ pub async fn entity_detail(
COALESCE(r.label, fact_surface_predicate(f.id)) AS predicate_label,
r.id IS NULL AS inferred, r.temporal,
CASE WHEN {subject} = $2 THEN {object} ELSE {subject} END AS other_id,
- o.canonical_name AS other_name, f.object_value,
+ o.canonical_name AS other_name, ot.label AS other_type, f.object_value,
f.valid_from, f.valid_from_precision, f.valid_to, f.valid_to_precision,
{holds_from} AS holds_from, {holds_to} AS holds_to, f.confidence,
(SELECT count(*) FROM fact_evidence fe WHERE fe.fact_id = f.id) AS evidence_count,
@@ -926,6 +953,7 @@ pub async fn entity_detail(
LEFT JOIN relation_types r ON r.id = f.predicate_id
LEFT JOIN entities o
ON o.id = CASE WHEN {subject} = $2 THEN {object} ELSE {subject} END
+ LEFT JOIN entity_types ot ON ot.id = o.type_id
WHERE f.kb_id = $1 AND {facts_held} AND {facts_hold}
AND ({subject} = $2 OR {object} = $2)
ORDER BY f.valid_from NULLS LAST, f.recorded_at",
diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rs
index e582fed0..4d51d207 100644
--- a/crates/utopia-store/src/lib.rs
+++ b/crates/utopia-store/src/lib.rs
@@ -23,6 +23,7 @@ pub mod memory;
pub mod model_limits;
pub mod ontology;
pub mod palette;
+pub mod paths;
pub mod pending;
pub mod reasoning;
pub mod record_axis;
diff --git a/crates/utopia-store/src/paths.rs b/crates/utopia-store/src/paths.rs
new file mode 100644
index 00000000..648c1fea
--- /dev/null
+++ b/crates/utopia-store/src/paths.rs
@@ -0,0 +1,402 @@
+//! 两点之间的路径(#558):`paths_between(a, b)`——A 和 B 是怎么连上的。
+//!
+//! 「OpenAI 和 Anthropic 的关系」是一道图谱题,而图谱工具从前只有按名找实体和
+//! 倒出一个实体的全部事实。模型要答它,得把 OpenAI 的 555 条事实和 Anthropic 的
+//! 全倒进上下文自己连线;实测十六次里三次连上,三次查了六七轮后宣布「库里没有」。
+//! 库里有,两跳:OpenAI —employee→ Dario Amodei —founder→ Anthropic。
+//!
+//! **回的是链,不是节点集。** 一跳邻域展开已经有了(`graph::neighborhood`,给画布用),
+//! 拿来答关系题等于把倒事实换成倒邻居。这里每条结果都是从 a 到 b 的一条边序列,
+//! 短的在前,途经节点越冷门越靠前。
+//!
+//! **两根时间轴都要过。** 带 `at` 时,路径上**每一条边**都得在那一刻成立——2019 年
+//! 的 OpenAI 和 Anthropic 之间还没有 Anthropic;带 `as_of` 时按当时的记录走,包括
+//! 当时还没合并的实体归谁(`record_axis::owner_at`)。这是普通图谱路径查询没有的
+//! 一半,也是这个库该露出来的那一半。
+//!
+//! **搜索是两头对中间。** 三跳以内的路径 a–x–y–b,只要知道 a 的两跳邻接和 b 的一跳
+//! 邻居就能拼出来,不必把 a 的第三层也铺开——第三层是 OpenAI 这种点的几万条边。
+//! 枢纽(度数超过 `hub_degree` 的中间节点)不往下展:经过 Sam Altman 的路径两点之间
+//! 到处都是,说明不了什么;两端本身不受此限,起点是谁就从谁走。
+
+use chrono::{DateTime, Utc};
+use sqlx::PgPool;
+use std::collections::{HashMap, HashSet};
+use utopia_core::AppResult;
+use uuid::Uuid;
+
+use crate::{record_axis, world_axis};
+
+/// 搜索的边界。测试把 `hub_degree` 调小来验证枢纽不被穿越;产品用默认值。
+#[derive(Debug, Clone, Copy)]
+pub struct Limits {
+ /// 最多几跳(1..=3;再长的路径两点之间到处都是,说明不了关系)
+ pub max_hops: usize,
+ /// 最多回几条
+ pub max_paths: usize,
+ /// 途经节点的度数上限:超过它的不往下展(两端不受此限)
+ pub hub_degree: i64,
+ /// 第二层展开最多读多少条边——按度数从小到大取途经节点,读满即止
+ pub max_edges: i64,
+ /// 排序之前最多攒多少条候选:同一对节点之间多条边会让组合数爆开
+ pub max_candidates: usize,
+}
+
+impl Default for Limits {
+ fn default() -> Self {
+ Self {
+ max_hops: 3,
+ max_paths: 10,
+ hub_degree: 150,
+ max_edges: 20_000,
+ max_candidates: 400,
+ }
+ }
+}
+
+/// 路径上的一条边,带两端的名字和它自己的区间;方向由调用方按走向判断
+/// (`subject_id` 等于上一个节点就是顺着走的)
+#[derive(Debug, Clone, sqlx::FromRow)]
+pub struct PathEdge {
+ pub fact_id: Uuid,
+ pub subject_id: Uuid,
+ pub subject_name: String,
+ pub object_id: Uuid,
+ pub object_name: String,
+ pub predicate: Option<String>,
+ pub valid_from: Option<DateTime<Utc>>,
+ pub valid_from_precision: Option<String>,
+ pub valid_to: Option<DateTime<Utc>>,
+ pub valid_to_precision: Option<String>,
+ pub holds_from: Option<DateTime<Utc>>,
+ pub holds_to: Option<DateTime<Utc>>,
+ pub confidence: f32,
+}
+
+#[derive(Debug, Clone)]
+pub struct Path {
+ /// 从 a 到 b 的节点序列,含两端
+ pub nodes: Vec<Uuid>,
+ /// `nodes[i]` 与 `nodes[i+1]` 之间的边
+ pub edges: Vec<PathEdge>,
+ /// 途经节点度数的 ln(1+d) 之和,越小越具体;两端不计
+ pub specificity: f64,
+}
+
+impl Path {
+ pub fn hops(&self) -> usize {
+ self.edges.len()
+ }
+}
+
+/// 一条边碰到的两个实体(已经按 `as_of` 折算成当时的归属)
+#[derive(Debug, Clone, Copy, sqlx::FromRow)]
+struct Touch {
+ id: Uuid,
+ subject_id: Uuid,
+ object_id: Uuid,
+}
+
+/// 候选:事实 id 序列与节点序列,排序前先攒起来
+struct Candidate {
+ nodes: Vec<Uuid>,
+ facts: Vec<Uuid>,
+}
+
+pub async fn paths_between(
+ pool: &PgPool,
+ kb_id: Uuid,
+ a: Uuid,
+ b: Uuid,
+ at: Option<DateTime<Utc>>,
+ as_of: Option<DateTime<Utc>>,
+ limits: Limits,
+) -> AppResult<Vec<Path>> {
+ let max_hops = limits.max_hops.clamp(1, 3);
+ if a == b {
+ return Ok(Vec::new());
+ }
+
+ // a 的一跳:邻居 → 连到它的边
+ let mut a_edges: HashMap<Uuid, Vec<Uuid>> = HashMap::new();
+ for t in touching(pool, kb_id, &[a], at, as_of).await? {
+ let other = if t.subject_id == a {
+ t.object_id
+ } else {
+ t.subject_id
+ };
+ a_edges.entry(other).or_default().push(t.id);
+ }
+
+ // b 的一跳(两跳以上才用得上)
+ let mut b_edges: HashMap<Uuid, Vec<Uuid>> = HashMap::new();
+ if max_hops >= 2 {
+ for t in touching(pool, kb_id, &[b], at, as_of).await? {
+ let other = if t.subject_id == b {
+ t.object_id
+ } else {
+ t.subject_id
+ };
+ b_edges.entry(other).or_default().push(t.id);
+ }
+ }
+
+ // a 的第二层:只展非枢纽的一跳邻居,按度数从小到大读到 `max_edges` 为止
+ let mut adj2: HashMap<Uuid, Vec<(Uuid, Uuid)>> = HashMap::new();
+ if max_hops >= 3 {
+ let mids: Vec<Uuid> = a_edges
+ .keys()
+ .copied()
+ .filter(|x| *x != a && *x != b)
+ .collect();
+ let degree = degrees(pool, kb_id, &mids, at, as_of).await?;
+ let mut by_degree: Vec<(Uuid, i64)> = mids
+ .iter()
+ .map(|x| (*x, degree.get(x).copied().unwrap_or(0)))
+ .filter(|(_, d)| *d <= limits.hub_degree)
+ .collect();
+ by_degree.sort_by_key(|(_, d)| *d);
+ let mut budget = limits.max_edges;
+ let mut expand = Vec::new();
+ for (x, d) in by_degree {
+ if budget < d {
+ break;
+ }
+ budget -= d;
+ expand.push(x);
+ }
+ if !expand.is_empty() {
+ let expand_set: HashSet<Uuid> = expand.iter().copied().collect();
+ for t in touching(pool, kb_id, &expand, at, as_of).await? {
+ for (x, y) in [(t.subject_id, t.object_id), (t.object_id, t.subject_id)] {
+ if expand_set.contains(&x) {
+ adj2.entry(x).or_default().push((y, t.id));
+ }
+ }
+ }
+ }
+ }
+
+ // 拼候选:一跳直连,两跳交集,三跳经第二层碰到 b 的邻居
+ let mut candidates: Vec<Candidate> = Vec::new();
+ let cap = limits.max_candidates.max(1);
+ if let Some(direct) = a_edges.get(&b) {
+ for f in direct {
+ candidates.push(Candidate {
+ nodes: vec![a, b],
+ facts: vec![*f],
+ });
+ }
+ }
+ if max_hops >= 2 {
+ let mut mids: Vec<&Uuid> = a_edges
+ .keys()
+ .filter(|x| **x != a && **x != b && b_edges.contains_key(*x))
+ .collect();
+ mids.sort();
+ 'two: for x in mids {
+ for fa in &a_edges[x] {
+ for fb in &b_edges[x] {
+ if candidates.len() >= cap {
+ break 'two;
+ }
+ candidates.push(Candidate {
+ nodes: vec![a, *x, b],
+ facts: vec![*fa, *fb],
+ });
+ }
+ }
+ }
+ }
+ if max_hops >= 3 {
+ let mut xs: Vec<&Uuid> = adj2.keys().collect();
+ xs.sort();
+ 'three: for x in xs {
+ for (y, fxy) in &adj2[x] {
+ if *y == a || *y == b || y == x {
+ continue;
+ }
+ let Some(fbs) = b_edges.get(y) else {
+ continue;
+ };
+ for fa in &a_edges[x] {
+ for fb in fbs {
+ if candidates.len() >= cap {
+ break 'three;
+ }
+ candidates.push(Candidate {
+ nodes: vec![a, *x, *y, b],
+ facts: vec![*fa, *fxy, *fb],
+ });
+ }
+ }
+ }
+ }
+ }
+ if candidates.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ // 排序:短的在前;同长的按途经节点的冷门程度;再按置信度
+ let mut mids: Vec<Uuid> = candidates
+ .iter()
+ .flat_map(|c| c.nodes[1..c.nodes.len() - 1].iter().copied())
+ .collect();
+ mids.sort();
+ mids.dedup();
+ let degree = degrees(pool, kb_id, &mids, at, as_of).await?;
+ let specificity = |c: &Candidate| -> f64 {
+ c.nodes[1..c.nodes.len() - 1]
+ .iter()
+ .map(|n| (1.0 + degree.get(n).copied().unwrap_or(0) as f64).ln())
+ .sum()
+ };
+ let mut all_facts: Vec<Uuid> = candidates.iter().flat_map(|c| c.facts.clone()).collect();
+ all_facts.sort();
+ all_facts.dedup();
+ let detail = details(pool, kb_id, &all_facts, as_of).await?;
+ let confidence = |c: &Candidate| -> f64 {
+ let n = c.facts.len().max(1) as f64;
+ c.facts
+ .iter()
+ .map(|f| detail.get(f).map(|e| e.confidence as f64).unwrap_or(0.0))
+ .sum::<f64>()
+ / n
+ };
+ let mut scored: Vec<(usize, f64, f64, Candidate)> = candidates
+ .into_iter()
+ .map(|c| (c.facts.len(), specificity(&c), confidence(&c), c))
+ .collect();
+ scored.sort_by(|x, y| {
+ x.0.cmp(&y.0)
+ .then(x.1.partial_cmp(&y.1).unwrap_or(std::cmp::Ordering::Equal))
+ .then(y.2.partial_cmp(&x.2).unwrap_or(std::cmp::Ordering::Equal))
+ });
+
+ // 同一串节点、同一串谓词只回一条:同一条边常有两份事实(一份带日期,一份只有
+ // 锚点),不去重的话十个名额里有三个是同一条路
+ let mut seen: HashSet<(Vec<Uuid>, Vec<String>)> = HashSet::new();
+ let mut out = Vec::new();
+ for (_, spec, _, c) in scored {
+ if out.len() >= limits.max_paths {
+ break;
+ }
+ let edges: Option<Vec<PathEdge>> = c.facts.iter().map(|f| detail.get(f).cloned()).collect();
+ // 细节查不到的边(as_of 时刻两端之一不可见)整条路径不要:链断了一环就不是链
+ let Some(edges) = edges else {
+ continue;
+ };
+ let predicates: Vec<String> = edges
+ .iter()
+ .map(|e| e.predicate.clone().unwrap_or_default())
+ .collect();
+ if !seen.insert((c.nodes.clone(), predicates)) {
+ continue;
+ }
+ out.push(Path {
+ nodes: c.nodes,
+ edges,
+ specificity: spec,
+ });
+ }
+ Ok(out)
+}
+
+/// 碰到这批实体的边(两个方向),两根时间轴都过,自环不要
+async fn touching(
+ pool: &PgPool,
+ kb_id: Uuid,
+ ids: &[Uuid],
+ at: Option<DateTime<Utc>>,
+ as_of: Option<DateTime<Utc>>,
+) -> AppResult<Vec<Touch>> {
+ if ids.is_empty() {
+ return Ok(Vec::new());
+ }
+ let subject = record_axis::owner_at("f", "subject_id", as_of.map(|_| 3), false);
+ let object = record_axis::owner_at("f", "object_id", as_of.map(|_| 3), true);
+ let rows: Vec<Touch> = sqlx::query_as(&format!(
+ "SELECT f.id, {subject} AS subject_id, {object} AS object_id
+ FROM facts f
+ WHERE f.kb_id = $1 AND f.object_id IS NOT NULL
+ AND ({subject} = ANY($2) OR {object} = ANY($2))
+ AND {subject} <> {object}
+ AND {held} AND {hold}",
+ held = record_axis::facts_held_at("f", 3),
+ hold = world_axis::facts_hold_at("f", 4),
+ ))
+ .bind(kb_id)
+ .bind(ids)
+ .bind(as_of)
+ .bind(at)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+/// 这批实体各自的度数,同一套时间轴过滤下
+async fn degrees(
+ pool: &PgPool,
+ kb_id: Uuid,
+ ids: &[Uuid],
+ at: Option<DateTime<Utc>>,
+ as_of: Option<DateTime<Utc>>,
+) -> AppResult<HashMap<Uuid, i64>> {
+ if ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+ let subject = record_axis::owner_at("f", "subject_id", as_of.map(|_| 3), false);
+ let object = record_axis::owner_at("f", "object_id", as_of.map(|_| 3), true);
+ let rows: Vec<(Uuid, i64)> = sqlx::query_as(&format!(
+ "SELECT n.id, count(f.id)
+ FROM unnest($2::uuid[]) AS n(id)
+ JOIN facts f ON f.kb_id = $1 AND f.object_id IS NOT NULL
+ AND ({subject} = n.id OR {object} = n.id)
+ AND {held} AND {hold}
+ GROUP BY n.id",
+ held = record_axis::facts_held_at("f", 3),
+ hold = world_axis::facts_hold_at("f", 4),
+ ))
+ .bind(kb_id)
+ .bind(ids)
+ .bind(as_of)
+ .bind(at)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows.into_iter().collect())
+}
+
+/// 这批事实的两端名字、谓词与区间
+async fn details(
+ pool: &PgPool,
+ kb_id: Uuid,
+ fact_ids: &[Uuid],
+ as_of: Option<DateTime<Utc>>,
+) -> AppResult<HashMap<Uuid, PathEdge>> {
+ if fact_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+ let subject = record_axis::owner_at("f", "subject_id", as_of.map(|_| 3), false);
+ let object = record_axis::owner_at("f", "object_id", as_of.map(|_| 3), true);
+ let rows: Vec<PathEdge> = sqlx::query_as(&format!(
+ "SELECT f.id AS fact_id,
+ {subject} AS subject_id, s.canonical_name AS subject_name,
+ {object} AS object_id, o.canonical_name AS object_name,
+ COALESCE(r.label, fact_surface_predicate(f.id)) AS predicate,
+ f.valid_from, f.valid_from_precision, f.valid_to, f.valid_to_precision,
+ {holds_from} AS holds_from, {holds_to} AS holds_to, f.confidence
+ FROM facts f
+ LEFT JOIN relation_types r ON r.id = f.predicate_id
+ JOIN entities s ON s.id = {subject}
+ JOIN entities o ON o.id = {object}
+ WHERE f.kb_id = $1 AND f.id = ANY($2)",
+ holds_from = world_axis::facts_holds_from("f"),
+ holds_to = world_axis::facts_holds_to("f"),
+ ))
+ .bind(kb_id)
+ .bind(fact_ids)
+ .bind(as_of)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows.into_iter().map(|e| (e.fact_id, e)).collect())
+}
diff --git a/crates/utopia-store/tests/a_path_joins_two_entities.rs b/crates/utopia-store/tests/a_path_joins_two_entities.rs
new file mode 100644
index 00000000..cf42b57b
--- /dev/null
+++ b/crates/utopia-store/tests/a_path_joins_two_entities.rs
@@ -0,0 +1,357 @@
+//! `paths_between`(#558):两点之间的链,短的在前,每条边都要在 `at` 成立,
+//! 枢纽不穿越,记录轴照走。
+
+use sqlx::PgPool;
+use utopia_store::graph::Validity;
+use utopia_store::paths::{paths_between, Limits, Path};
+use uuid::Uuid;
+
+fn t(s: &str) -> chrono::DateTime<chrono::Utc> {
+ s.parse().unwrap()
+}
+
+/// Acme 与 Beta 之间四条路:直连(2023 起)、经 Bob(Acme 雇员 2016–2020-12,
+/// 2021 起创办 Beta)、经 Dan(雇员 2016–2019,2021 起创办 Beta)、经 Carol 和
+/// Gamma(Carol 2018 起在 Acme,2019 起为 Gamma 顾问,Gamma 2020 起与 Beta 合作)
+struct Fixture {
+ org: Uuid,
+ kb: Uuid,
+ acme: Uuid,
+ beta: Uuid,
+ gamma: Uuid,
+ bob: Uuid,
+ carol: Uuid,
+ dan: Uuid,
+ employee: Uuid,
+ founder: Uuid,
+ partner: Uuid,
+ advises: Uuid,
+ direct: Uuid,
+}
+
+async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (organization, person) = (Uuid::now_v7(), Uuid::now_v7());
+ let (acme, beta, gamma) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (bob, carol, dan) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (employee, founder, partner, advises) = (
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ );
+
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'path-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'path-test')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'path-test')",
+ )
+ .bind(kb)
+ .bind(ws)
+ .execute(pool)
+ .await?;
+ for (id, key, label) in [
+ (organization, "organization", "Organization"),
+ (person, "person", "Person"),
+ ] {
+ 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?;
+ }
+ for (id, key) in [
+ (employee, "employee"),
+ (founder, "founder"),
+ (partner, "partner"),
+ (advises, "advises"),
+ ] {
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label, temporal) VALUES ($1, $2, $3, $3, 'state')",
+ )
+ .bind(id)
+ .bind(kb)
+ .bind(key)
+ .execute(pool)
+ .await?;
+ }
+ for (id, ty, name) in [
+ (acme, organization, "Acme"),
+ (beta, organization, "Beta"),
+ (gamma, organization, "Gamma"),
+ (bob, person, "Bob"),
+ (carol, person, "Carol"),
+ (dan, person, "Dan"),
+ ] {
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
+ )
+ .bind(id)
+ .bind(kb)
+ .bind(ty)
+ .bind(name)
+ .execute(pool)
+ .await?;
+ }
+ let span = |from: &str, to: Option<&str>| Validity {
+ from: Some(t(from)),
+ from_precision: Some("month"),
+ to: to.map(t),
+ to_precision: to.map(|_| "month"),
+ attested_at: None,
+ };
+ let mut direct = Uuid::nil();
+ for (s, p, o, v) in [
+ (
+ acme,
+ employee,
+ bob,
+ span("2016-01-01T00:00:00Z", Some("2020-12-01T00:00:00Z")),
+ ),
+ (bob, founder, beta, span("2021-01-01T00:00:00Z", None)),
+ (acme, partner, beta, span("2023-01-01T00:00:00Z", None)),
+ (acme, employee, carol, span("2018-01-01T00:00:00Z", None)),
+ (carol, advises, gamma, span("2019-01-01T00:00:00Z", None)),
+ (gamma, partner, beta, span("2020-01-01T00:00:00Z", None)),
+ (
+ acme,
+ employee,
+ dan,
+ span("2016-01-01T00:00:00Z", Some("2019-01-01T00:00:00Z")),
+ ),
+ (dan, founder, beta, span("2021-01-01T00:00:00Z", None)),
+ // 同一条边的第二份事实(只有锚点、没日期的那种):路径不该因此多出一条
+ (
+ bob,
+ founder,
+ beta,
+ Validity::starting(None, None).attested(Some(t("2024-05-01T00:00:00Z"))),
+ ),
+ ] {
+ let (id, _) = utopia_store::graph::insert_fact(pool, kb, s, Some(p), o, v, 0.9).await?;
+ if s == acme && p == partner {
+ direct = id;
+ }
+ }
+ Ok(Fixture {
+ org,
+ kb,
+ acme,
+ beta,
+ gamma,
+ bob,
+ carol,
+ dan,
+ employee,
+ founder,
+ partner,
+ advises,
+ direct,
+ })
+}
+
+async fn teardown(pool: &PgPool, f: &Fixture) -> anyhow::Result<()> {
+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
+ .bind(f.kb)
+ .execute(pool)
+ .await?;
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 路径读成「途经谁」,好断言
+fn via(p: &Path) -> Vec<Uuid> {
+ p.nodes[1..p.nodes.len() - 1].to_vec()
+}
+
+#[tokio::test]
+async fn paths_come_shortest_first_and_stop_at_max_hops() -> 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 all = paths_between(&pool, f.kb, f.acme, f.beta, None, None, Limits::default()).await?;
+ let hops: Vec<usize> = all.iter().map(Path::hops).collect();
+ assert_eq!(
+ hops,
+ vec![1, 2, 2, 3],
+ "短的在前:直连、两条两跳、一条三跳;Bob 那条边有两份事实,仍是一条路"
+ );
+ assert!(via(&all[0]).is_empty());
+ let two: Vec<Vec<Uuid>> = all[1..3].iter().map(via).collect();
+ assert!(two.contains(&vec![f.bob]) && two.contains(&vec![f.dan]));
+ assert_eq!(via(&all[3]), vec![f.carol, f.gamma]);
+ // 边自带两端与谓词,顺着走的边主语就是上一个节点
+ let chain = &all[3];
+ assert_eq!(chain.edges[0].subject_id, f.acme);
+ assert_eq!(chain.edges[0].object_name, "Carol");
+ assert_eq!(chain.edges[1].predicate.as_deref(), Some("advises"));
+ assert_eq!(chain.edges[2].object_id, f.beta);
+
+ let limits = |max_hops| Limits {
+ max_hops,
+ ..Limits::default()
+ };
+ let two = paths_between(&pool, f.kb, f.acme, f.beta, None, None, limits(2)).await?;
+ assert_eq!(two.len(), 3, "两跳以内没有 Carol 那条");
+ let one = paths_between(&pool, f.kb, f.acme, f.beta, None, None, limits(1)).await?;
+ assert_eq!(one.len(), 1);
+ assert_eq!(one[0].edges[0].fact_id, f.direct);
+ // 反向问同样走得通
+ let back =
+ paths_between(&pool, f.kb, f.beta, f.acme, None, None, Limits::default()).await?;
+ assert_eq!(back.len(), 4);
+ assert_eq!(back[0].nodes, vec![f.beta, f.acme]);
+ anyhow::Ok(())
+ }
+ .await;
+ teardown(&pool, &f).await?;
+ run
+}
+
+/// 带 `at` 时每一条边都得在那一刻成立:2021 年中,Acme 到 Beta 只剩 Carol–Gamma 那条
+#[tokio::test]
+async fn a_path_holds_only_when_every_edge_holds() -> 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 mid_2021 = Some(t("2021-06-15T00:00:00Z"));
+ let paths = paths_between(
+ &pool,
+ f.kb,
+ f.acme,
+ f.beta,
+ mid_2021,
+ None,
+ Limits::default(),
+ )
+ .await?;
+ assert_eq!(paths.len(), 1, "Bob 已离开、Dan 已离开、直连还没签");
+ assert_eq!(via(&paths[0]), vec![f.carol, f.gamma]);
+
+ let in_2018 = Some(t("2018-06-15T00:00:00Z"));
+ let none = paths_between(
+ &pool,
+ f.kb,
+ f.acme,
+ f.beta,
+ in_2018,
+ None,
+ Limits::default(),
+ )
+ .await?;
+ assert!(none.is_empty(), "2018 年 Beta 还没被谁创办,什么都连不上");
+ anyhow::Ok(())
+ }
+ .await;
+ teardown(&pool, &f).await?;
+ run
+}
+
+/// 枢纽不往下展:Carol 一多几条边就不再是三跳路径的中转
+#[tokio::test]
+async fn a_hub_is_not_walked_through() -> 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 tight = Limits {
+ hub_degree: 2,
+ ..Limits::default()
+ };
+ let before = paths_between(&pool, f.kb, f.acme, f.beta, None, None, tight).await?;
+ assert_eq!(before.len(), 4, "Carol 两条边,不算枢纽");
+ // Carol 再顾问三家:度数 5,超过上限
+ for _ in 0..3 {
+ let other = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, canonical_name) VALUES ($1, $2, 'Other')",
+ )
+ .bind(other)
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ utopia_store::graph::insert_fact(
+ &pool,
+ f.kb,
+ f.carol,
+ Some(f.advises),
+ other,
+ Validity::starting(Some(t("2020-01-01T00:00:00Z")), Some("year")),
+ 0.9,
+ )
+ .await?;
+ }
+ let after = paths_between(&pool, f.kb, f.acme, f.beta, None, None, tight).await?;
+ assert_eq!(after.len(), 3, "经 Carol 的三跳没了");
+ assert!(after.iter().all(|p| !via(p).contains(&f.carol)));
+ let loose =
+ paths_between(&pool, f.kb, f.acme, f.beta, None, None, Limits::default()).await?;
+ assert_eq!(loose.len(), 4, "默认上限下她还只是个普通节点");
+ // 两跳路径不受枢纽限制:Bob 和 Dan 的度数不进这条判断,两端更不进
+ let _ = (f.employee, f.founder, f.partner, f.bob, f.dan);
+ anyhow::Ok(())
+ }
+ .await;
+ teardown(&pool, &f).await?;
+ run
+}
+
+/// 记录轴:直连那条边今天才录入,其余前天就在;问「昨天的记录」走不到它,
+/// 不带 as_of 是此刻的记录(记录轴上 NULL 即现在,0019),四条都在
+#[tokio::test]
+async fn a_path_reads_the_base_as_it_was() -> 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 two_days_ago = chrono::Utc::now() - chrono::Duration::days(2);
+ sqlx::query("UPDATE facts SET recorded_at = $3 WHERE kb_id = $1 AND id <> $2")
+ .bind(f.kb)
+ .bind(f.direct)
+ .bind(two_days_ago)
+ .execute(&pool)
+ .await?;
+ let yesterday = Some(chrono::Utc::now() - chrono::Duration::days(1));
+ let then = paths_between(
+ &pool,
+ f.kb,
+ f.acme,
+ f.beta,
+ None,
+ yesterday,
+ Limits::default(),
+ )
+ .await?;
+ assert_eq!(then.len(), 3, "直连那条今天才进账本");
+ assert!(then.iter().all(|p| p.hops() >= 2));
+ let today =
+ paths_between(&pool, f.kb, f.acme, f.beta, None, None, Limits::default()).await?;
+ assert_eq!(today.len(), 4, "不带 as_of 是此刻的记录");
+ anyhow::Ok(())
+ }
+ .await;
+ teardown(&pool, &f).await?;
+ run
+}
diff --git a/web/src/api.ts b/web/src/api.ts
index 9bdc760e..ee7f69ca 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -1178,7 +1178,17 @@ export interface Source {
/** Agentic 对话的行动轨迹(工具调用一步一条)。 */
export interface ChatStep {
- kind: "search" | "docs" | "entity" | "facts" | "changes" | "query" | "tool";
+ kind:
+ | "search"
+ | "docs"
+ | "entity"
+ | "facts"
+ | "neighbors"
+ | "timeline"
+ | "path"
+ | "changes"
+ | "query"
+ | "tool";
label: string;
detail: string;
/** `remember` 那一步带着它:那句记忆落成的 chunk。对话里的确认卡按它取
diff --git a/web/src/docs/mcp.md b/web/src/docs/mcp.md
index 7fecd235..2fa0204b 100644
--- a/web/src/docs/mcp.md
+++ b/web/src/docs/mcp.md
@@ -41,6 +41,9 @@ Three methods are served:
| `get_document` | The full text of one document, all sections in order, by `document_id`. Use it when a search hit is the right document but the excerpt does not carry the answer. Capped at 24,000 characters, and says so when it cuts |
| `find_entities` | Entities by (partial) name: id, type, and a disambiguator when several share a name |
| `entity_facts` | One entity's facts with validity ranges. Pass `at` (a date) to see the world as of that day; this is the tool for "who was X in 2024". Pass `as_of` (a date or an RFC3339 moment) to see the facts **as the base held them then**, before later corrections, retractions and merges — "what did we have on record before the memo arrived". The two combine: `at` for the date asked about, `as_of` for when |
+| `neighbors` | The entities linked to one entity, one hop, grouped by predicate; narrow with `predicate` or `object_type`. Takes a name as well as an id |
+| `timeline` | One entity's dated facts in world-time order; `since` / `until` narrow the window |
+| `paths_between` | The chains of facts joining two entities, up to three hops, shortest first. With `at`, every edge must hold at that moment; with `as_of`, the chains as the base held them then |
| `changes` | What the graph learned or revised in a window of **record** time: asserted, corrected, rejected, merged. Needs no entity; use it when the question names a period, not a subject |
| `search_docs` | Utopia's own manual, for questions about how the platform works. Never the user's documents |
| `remember` | Record one sentence into the base's memory. **Needs a `write` token held by an editor**; a token without it does not see this tool in `tools/list`, and calling it anyway says why |
diff --git a/web/src/pages/Chat.tsx b/web/src/pages/Chat.tsx
index 90e34d33..454db552 100644
--- a/web/src/pages/Chat.tsx
+++ b/web/src/pages/Chat.tsx
@@ -711,8 +711,9 @@ function segments(turn: Turn): Segment[] {
function stepIcon(kind: ChatStep["kind"]) {
if (kind === "search") return <SearchIcon size={11} />;
if (kind === "docs") return <BookOpen size={11} />;
- if (kind === "entity") return <Waypoints size={11} />;
- if (kind === "facts") return <History size={11} />;
+ if (kind === "entity" || kind === "neighbors" || kind === "path")
+ return <Waypoints size={11} />;
+ if (kind === "facts" || kind === "timeline") return <History size={11} />;
// facts 读世界轴、changes 读认知轴,两个图谱工具给不同的图标——
// 用户看步骤条时该看得出问的是哪根轴
if (kind === "changes") return <GitCompareArrows size={11} />;
@@ -723,8 +724,10 @@ function stepIcon(kind: ChatStep["kind"]) {
/** 工具步骤 → 球体状态:思考球讲当前动作的语言 */
function orbState(kind?: ChatStep["kind"]): OrbState {
if (kind === "search" || kind === "docs") return "searching";
- if (kind === "entity") return "connecting";
- if (kind === "facts" || kind === "changes") return "solving";
+ if (kind === "entity" || kind === "neighbors" || kind === "path")
+ return "connecting";
+ if (kind === "facts" || kind === "timeline" || kind === "changes")
+ return "solving";
if (kind === "query" || kind === "tool") return "working";
return "listening"; // 尚无步骤:刚接到消息
}