Skip to content

World's first open-source enterprise world model.

Facts corroborate an identity when the profile cannot (#342)

WaylandYang5e51d3cb2e5f
diff --git a/crates/utopia-server/src/extraction.rs b/crates/utopia-server/src/extraction.rs
index 63697f6d..41be9fd1 100644
--- a/crates/utopia-server/src/extraction.rs
+++ b/crates/utopia-server/src/extraction.rs
@@ -313,6 +313,7 @@ pub async fn extract_document(
/// mention → 实体 id。同一文档内同名同类型直接复用(单文档语境里罕有同名不同人,
/// 也把消解调用摊薄到每个名字一次);跨文档歧义由 resolve_mention 的画像比对处理。
+#[allow(clippy::too_many_arguments)]
async fn resolve(
pool: &PgPool,
kb_id: Uuid,
@@ -320,6 +321,8 @@ async fn resolve(
type_id: Option<Uuid>,
name: &str,
ctx: Option<&[f32]>,
+ // 本次提及所在分块的原文:画像分不开同名候选时的事实旁证(#331)
+ text: Option<&str>,
doc_cache: &mut HashMap<(Option<Uuid>, String), Uuid>,
needs_adjudication: &mut bool,
) -> anyhow::Result<Uuid> {
@@ -330,24 +333,37 @@ async fn resolve(
if let Some(id) = doc_cache.get(&key) {
return Ok(*id);
}
- let id = resolve_uncached(pool, kb_id, type_id, name, ctx, &[], needs_adjudication).await?;
+ let id = resolve_uncached(
+ pool,
+ kb_id,
+ type_id,
+ name,
+ ctx,
+ text,
+ &[],
+ needs_adjudication,
+ )
+ .await?;
doc_cache.insert(key, id);
Ok(id)
}
/// Resolve without the document's name cache. Handles use this path so two identities claimed
/// separately in one response cannot collapse before their fact refs are bound.
+#[allow(clippy::too_many_arguments)]
async fn resolve_uncached(
pool: &PgPool,
kb_id: Uuid,
type_id: Option<Uuid>,
name: &str,
ctx: Option<&[f32]>,
+ text: Option<&str>,
exclude: &[Uuid],
needs_adjudication: &mut bool,
) -> anyhow::Result<Uuid> {
let r =
- utopia_store::resolution::resolve_mention(pool, kb_id, type_id, name, ctx, exclude).await?;
+ utopia_store::resolution::resolve_mention(pool, kb_id, type_id, name, ctx, text, exclude)
+ .await?;
// 疑似重复对(画像灰区 / 类型漂移 / 同名并列)入审核队列。多数走批量裁决器,
// 同名并列(`ReviewStage::Human`)分不出谁是谁,只能等人裁——它自己带着 stage。
for review in &r.reviews {
@@ -439,6 +455,7 @@ async fn resolve_handle(
type_id: Option<Uuid>,
name: &str,
ctx: Option<&[f32]>,
+ text: Option<&str>,
response_claims: &mut HashMap<String, Vec<Uuid>>,
handled_by_name: &mut HashMap<String, Vec<Uuid>>,
ambiguous_bare_cache: &mut HashMap<String, Uuid>,
@@ -477,6 +494,7 @@ async fn resolve_handle(
type_id,
name,
ctx,
+ text,
&excluded,
needs_adjudication,
)
@@ -508,6 +526,7 @@ async fn resolve_bare(
type_id: Option<Uuid>,
name: &str,
ctx: Option<&[f32]>,
+ text: Option<&str>,
doc_cache: &mut HashMap<(Option<Uuid>, String), Uuid>,
handled_by_name: &HashMap<String, Vec<Uuid>>,
ambiguous_bare_cache: &mut HashMap<String, Uuid>,
@@ -526,6 +545,7 @@ async fn resolve_bare(
type_id,
name,
ctx,
+ text,
doc_cache,
needs_adjudication,
)
@@ -538,7 +558,17 @@ async fn resolve_bare(
// The text supplies no evidence for choosing among the handled namesakes. Preserve the
// fact on one document-scoped provisional entity and expose every possible identity link
// to a person. Subsequent bare mentions in this document reuse this provisional entity.
- let id = resolve_uncached(pool, kb_id, type_id, name, ctx, &claims, needs_adjudication).await?;
+ let id = resolve_uncached(
+ pool,
+ kb_id,
+ type_id,
+ name,
+ ctx,
+ text,
+ &claims,
+ needs_adjudication,
+ )
+ .await?;
if create_namesake_reviews(pool, kb_id, id, &claims).await? {
*human_reviews_found = true;
}
@@ -890,6 +920,7 @@ async fn run(state: &AppState, document_id: Uuid, proposer: Proposer) -> anyhow:
type_id,
name,
ctx,
+ Some(&chunk.text),
&mut response_claims,
&mut handled_by_name,
&mut ambiguous_bare_cache,
@@ -906,6 +937,7 @@ async fn run(state: &AppState, document_id: Uuid, proposer: Proposer) -> anyhow:
type_id,
name,
ctx,
+ Some(&chunk.text),
&mut doc_cache,
&handled_by_name,
&mut ambiguous_bare_cache,
@@ -1020,6 +1052,7 @@ async fn run(state: &AppState, document_id: Uuid, proposer: Proposer) -> anyhow:
type_id,
subject_name,
ctx,
+ Some(&chunk.text),
&mut doc_cache,
&handled_by_name,
&mut ambiguous_bare_cache,
@@ -1379,6 +1412,7 @@ async fn run(state: &AppState, document_id: Uuid, proposer: Proposer) -> anyhow:
None,
f.subject.trim(),
ctx,
+ Some(&chunk.text),
&mut doc_cache,
&handled_by_name,
&mut ambiguous_bare_cache,
@@ -1418,6 +1452,7 @@ async fn run(state: &AppState, document_id: Uuid, proposer: Proposer) -> anyhow:
None,
object_name,
ctx,
+ Some(&chunk.text),
&mut doc_cache,
&handled_by_name,
&mut ambiguous_bare_cache,
@@ -2219,6 +2254,7 @@ mod tests {
Some(person),
"Alice",
None,
+ None,
&mut legacy_cache,
&mut legacy_needs_adjudication,
)
@@ -2229,6 +2265,7 @@ mod tests {
Some(person),
"Alice",
None,
+ None,
&mut legacy_cache,
&mut legacy_needs_adjudication,
)
@@ -2245,6 +2282,7 @@ mod tests {
Some(person),
"Zhang Wei",
None,
+ None,
&mut response_claims,
&mut document_claims,
&mut bare_cache,
@@ -2258,6 +2296,7 @@ mod tests {
Some(person),
"Zhang Wei",
None,
+ None,
&mut response_claims,
&mut document_claims,
&mut bare_cache,
@@ -2356,6 +2395,7 @@ mod tests {
Some(person),
"Zhang Wei",
None,
+ None,
&mut doc_cache,
&document_claims,
&mut bare_cache,
@@ -2379,6 +2419,7 @@ mod tests {
None,
"Zhang Wei",
None,
+ None,
&mut doc_cache,
&document_claims,
&mut bare_cache,
@@ -2419,6 +2460,7 @@ mod tests {
Some(person),
"Zhang Wei",
None,
+ None,
&mut later_response_claims,
&mut document_claims,
&mut bare_cache,
@@ -2516,6 +2558,7 @@ mod tests {
Some(person),
"Zhang Wei",
Some(&ctx),
+ None,
&mut doc_cache,
&mut needs_adjudication,
)
diff --git a/crates/utopia-server/src/mappings.rs b/crates/utopia-server/src/mappings.rs
index 755f8912..8b6e2f1b 100644
--- a/crates/utopia-server/src/mappings.rs
+++ b/crates/utopia-server/src/mappings.rs
@@ -160,13 +160,15 @@ pub async fn explore_mappings(state: &AppState, kb_id: Uuid) -> anyhow::Result<(
.await?;
let Some((type_id,)) = type_id else { continue };
- // 概念实体:走消解(同名归并;无向量上下文按 v1 兼容归并)
+ // 概念实体:走消解(同名归并;无向量上下文按 v1 兼容归并)。
+ // 没有块原文可给——这些名字来自数据源的 schema 探索,不是从文档句子里抽的
let resolved = utopia_store::resolution::resolve_mention(
&state.pool,
kb_id,
Some(type_id),
name,
None,
+ None,
&[],
)
.await?;
diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs
index 2ae4972c..e549f4cc 100644
--- a/crates/utopia-store/src/resolution.rs
+++ b/crates/utopia-store/src/resolution.rs
@@ -27,6 +27,15 @@ pub const SIM_NEW: f32 = 0.35;
/// chunk、不同事实积累)分差远大于此,只有质心几乎重合(如同一 chunk 播种)才触发。
pub const SIM_TIE_MARGIN: f32 = 0.02;
+/// 旁证宾语的最短长度。低于它的("IT"、"A 组")在任何一篇文档里都可能出现,
+/// 命中不含信息量。**宁可漏掉一条旁证**:漏了就是今天的行为,错了会并错人。
+const MIN_CORROBORATION_CHARS: usize = 2;
+
+/// 每个候选取几个消歧宾语参与旁证。取多个是因为文档提到的未必是排序最靠前的
+/// 那一个(他的部门写在这句、职位写在下一句),但也不能全取——候选的事实越多,
+/// 撞上一个泛泛的宾语的机会越大。
+const CORROBORATION_OBJECTS: i64 = 3;
+
/// 名称规范化:全角 ASCII → 半角、全角空格 → 半角、空白折叠。
/// 返回展示形态(保留大小写);匹配一律再套 SQL lower()。
pub fn normalize_name(raw: &str) -> String {
@@ -233,6 +242,9 @@ pub async fn resolve_mention(
type_id: Option<Uuid>,
raw_name: &str,
context: Option<&[f32]>,
+ // 这次提及所在的**块原文**。画像分不出谁是谁时拿它做事实旁证(#331)——
+ // 传整篇文档会让每个部门都命中,所以这里要的是句子或块,不是文档。
+ text: Option<&str>,
// Candidates already claimed by a different response-local handle. They remain stored
// and recallable on later calls, but this mention cannot attach to them.
exclude: &[Uuid],
@@ -321,6 +333,20 @@ pub async fn resolve_mention(
})
.reduce(|acc, cur| if cur.1 > acc.1 { cur } else { acc })
{
+ // 画像掷硬币之前,先问事实(#331):这句话里提到了其中一个人的
+ // 部门或职位吗?提到了就不是硬币,是线索
+ if let Some(t) = text {
+ if let Some(c) =
+ corroborating_candidate(pool, kb_id, &[best, runner], t).await?
+ {
+ update_profile(pool, c.id, c.profile_n, ctx).await?;
+ return Ok(Resolution {
+ entity_id: c.id,
+ created: false,
+ reviews: Vec::new(),
+ });
+ }
+ }
let id = create_entity(pool, kb_id, type_id, &name, context).await?;
refresh_disambiguators(pool, kb_id, &name).await?;
let reviews = [(best, sim), (runner, r_sim)]
@@ -356,7 +382,27 @@ pub async fn resolve_mention(
});
}
- // 走到这里:所有候选都有画像且最高分 < ATTACH → 新建实体(同名不同人)
+ // 走到这里:所有候选都有画像且最高分 < ATTACH → 新建实体(同名不同人)。
+ //
+ // 但先问一次事实(#331)。灰区的意思是"向量说不好",不是"一定是新人"——
+ // 这句话里若正好写着某一个候选的部门或职位,那比余弦值可靠。
+ // **只认灰区**(≥ SIM_NEW):分数低于它的候选连审核对都不配入队,
+ // 拿一条旁证把它拉成同一人,等于绕过阈值而不是补充它。
+ if let Some(t) = text {
+ let in_grey: Vec<&Candidate> = scored
+ .iter()
+ .filter(|(_, s)| *s >= SIM_NEW)
+ .map(|(c, _)| *c)
+ .collect();
+ if let Some(c) = corroborating_candidate(pool, kb_id, &in_grey, t).await? {
+ update_profile(pool, c.id, c.profile_n, ctx).await?;
+ return Ok(Resolution {
+ entity_id: c.id,
+ created: false,
+ reviews: Vec::new(),
+ });
+ }
+ }
let id = create_entity(pool, kb_id, type_id, &name, context).await?;
refresh_disambiguators(pool, kb_id, &name).await?;
let mut reviews = best_scored
@@ -380,6 +426,85 @@ pub async fn resolve_mention(
})
}
+/// **事实旁证**:这次提及的原文里,出现了某个候选的消歧宾语吗(#331)。
+///
+/// 画像向量分不出谁是谁时,能分开的线索往往就在事实里——一个张伟 `works_for`
+/// 平台工程部,另一个 `works_for` 财务部,而这句话里写着"财务"。人在审核卡上
+/// 看的正是这些事实(`top_facts`),这一步是把人做的事交回给代码。
+///
+/// **证据只往一个方向走。** 一致是"同一人"的弱证据;不一致**什么都不是**——
+/// 在 Acme 上班又在 Zenith 兼职的人有两个 `works_for` 值,他仍是一个人。所以
+/// 这个函数只回答"哪个候选被原文提到了",永远不回答"哪个候选被排除了"。
+///
+/// **恰好一个候选命中才算数。** 两个都命中说明这条线索在他们之间也分不开,
+/// 与其挑一个不如维持原样。
+///
+/// 宾语的挑法与 `refresh_disambiguators` 同源(#299 之后从本体的 range 声明选,
+/// 不是词表),并且**排除同名同伴也指着的那些**:两个张伟都在同一家公司时,
+/// 公司名对分辨他们毫无帮助,却最容易在文档里撞上。
+async fn corroborating_candidate<'a>(
+ pool: &PgPool,
+ kb_id: Uuid,
+ candidates: &[&'a Candidate],
+ text: &str,
+) -> AppResult<Option<&'a Candidate>> {
+ // 单个候选也算数:「其他候选都没命中」在只有一个候选时天然成立
+ if candidates.is_empty() || text.trim().is_empty() {
+ return Ok(None);
+ }
+ let ids: Vec<Uuid> = candidates.iter().map(|c| c.id).collect();
+ // 一次查完所有候选:每个候选取若干个「同伴不指向」的宾语名字
+ let rows: Vec<(Uuid, String)> = sqlx::query_as(
+ "SELECT s.subject_id, s.name FROM (
+ SELECT f.subject_id, o.canonical_name AS name,
+ row_number() OVER (
+ PARTITION BY f.subject_id
+ ORDER BY EXISTS (SELECT 1 FROM relation_type_ranges rr
+ WHERE rr.relation_type_id = r.id) DESC,
+ (r.temporal = 'state') DESC,
+ r.functional DESC,
+ f.confidence DESC, f.recorded_at DESC
+ ) AS rn
+ FROM facts f
+ JOIN relation_types r ON r.id = f.predicate_id
+ JOIN entities o ON o.id = f.object_id
+ WHERE f.kb_id = $1 AND f.subject_id = ANY($2)
+ AND f.invalidated_at IS NULL AND f.object_id IS NOT NULL
+ -- 同名同伴也指着的宾语没有分辨力,排除
+ AND NOT EXISTS (SELECT 1 FROM facts g
+ WHERE g.kb_id = $1 AND g.subject_id = ANY($2)
+ AND g.subject_id <> f.subject_id
+ AND g.object_id = f.object_id
+ AND g.invalidated_at IS NULL)
+ ) s WHERE s.rn <= $3",
+ )
+ .bind(kb_id)
+ .bind(&ids)
+ .bind(CORROBORATION_OBJECTS)
+ .fetch_all(pool)
+ .await?;
+
+ let haystack = text.to_lowercase();
+ let mut hit: Option<&'a Candidate> = None;
+ for (subject_id, object_name) in &rows {
+ let needle = object_name.trim().to_lowercase();
+ if needle.chars().count() < MIN_CORROBORATION_CHARS || !haystack.contains(&needle) {
+ continue;
+ }
+ let Some(c) = candidates.iter().find(|c| c.id == *subject_id) else {
+ continue;
+ };
+ match hit {
+ // 同一个候选的第二条宾语也命中:仍是同一个候选,不算分歧
+ Some(prev) if prev.id == c.id => {}
+ // 命中了第二个候选:这条线索分不开他们
+ Some(_) => return Ok(None),
+ None => hit = Some(c),
+ }
+ }
+ Ok(hit)
+}
+
/// 包含关系候选的最短边:两个名字里**较短的那个**至少这么长才算数。
/// 低于它的多是「研究院」「中心」这类通名,配对没有信息量,只会刷爆队列。
const MIN_CONTAIN_CHARS: i32 = 4;
diff --git a/crates/utopia-store/tests/a_declared_disjointness_keeps_names_apart.rs b/crates/utopia-store/tests/a_declared_disjointness_keeps_names_apart.rs
index e93b65ee..788af8ba 100644
--- a/crates/utopia-store/tests/a_declared_disjointness_keeps_names_apart.rs
+++ b/crates/utopia-store/tests/a_declared_disjointness_keeps_names_apart.rs
@@ -113,7 +113,7 @@ async fn drift_reviews(
name: &str,
type_id: Uuid,
) -> anyhow::Result<Vec<Uuid>> {
- let r = resolution::resolve_mention(pool, f.kb, Some(type_id), name, None, &[]).await?;
+ let r = resolution::resolve_mention(pool, f.kb, Some(type_id), name, None, None, &[]).await?;
assert!(
r.created,
"a cross-type same name is a new entity: keep apart, never merge"
diff --git a/crates/utopia-store/tests/a_namesake_tie_goes_to_review_not_a_coin_flip.rs b/crates/utopia-store/tests/a_namesake_tie_goes_to_review_not_a_coin_flip.rs
index e39d3771..0d956a0b 100644
--- a/crates/utopia-store/tests/a_namesake_tie_goes_to_review_not_a_coin_flip.rs
+++ b/crates/utopia-store/tests/a_namesake_tie_goes_to_review_not_a_coin_flip.rs
@@ -132,6 +132,7 @@ async fn a_namesake_tie_creates_an_entity_and_two_reviews() -> anyhow::Result<()
Some(f.person),
"Zhang Wei",
Some(&ctx),
+ None,
&[],
)
.await?;
diff --git a/crates/utopia-store/tests/facts_corroborate_an_identity.rs b/crates/utopia-store/tests/facts_corroborate_an_identity.rs
new file mode 100644
index 00000000..7a63afce
--- /dev/null
+++ b/crates/utopia-store/tests/facts_corroborate_an_identity.rs
@@ -0,0 +1,305 @@
+//! 画像分不开同名的人时,事实能分开(#331,续 #270/#329)。
+//!
+//! 一个库里有两个「张伟」:一个在平台工程部,一个在财务部。画像向量分不出谁是谁
+//! ——#329 之后这种并列会新建实体、入两条人工审核对,而人在审核卡上看的正是那两条
+//! `works_for` 事实。**代码本可以自己看。** 这个文件钉的就是那一步。
+//!
+//! 证据只往一个方向走:一致是「同一人」的弱证据,不一致**什么都不是**。在 Acme
+//! 上班又在 Zenith 兼职的人有两个 `works_for`,他仍是一个人;两个不同的人也可能
+//! 同属一家公司。所以这里既钉「命中就定案」,也钉「命中不了就一切照旧」——
+//! 后者才是不把弱证据当强证据的那道闸。
+//!
+//! 连库才测得到:命中与否取决于一条带窗口函数、带 NOT EXISTS 的 SQL 挑出了哪些
+//! 宾语,`cargo check` 一个字看不见。没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。
+
+use sqlx::PgPool;
+use uuid::Uuid;
+
+struct Fx {
+ kb: Uuid,
+ person: Uuid,
+ zhang_a: Uuid,
+ zhang_b: Uuid,
+}
+
+/// 两个同名的张伟。`shared` 为真时再给他们一个**共同**的雇主——
+/// 那条事实对分辨他们毫无帮助,却最容易在文档里撞上。
+async fn seed(pool: &PgPool, shared: bool) -> anyhow::Result<Fx> {
+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (person, organization) = (Uuid::now_v7(), Uuid::now_v7());
+ let works_for = Uuid::now_v7();
+ let (platform, finance, both) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (zhang_a, zhang_b) = (Uuid::now_v7(), Uuid::now_v7());
+
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'corroboration-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'corroboration-test')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO knowledge_bases (id, workspace_id, name)
+ VALUES ($1, $2, 'corroboration-test')",
+ )
+ .bind(kb)
+ .bind(ws)
+ .execute(pool)
+ .await?;
+ for (id, key, label) in [
+ (person, "person", "Person"),
+ (organization, "organization", "Organization"),
+ ] {
+ 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?;
+ }
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label, temporal)
+ VALUES ($1, $2, 'works_for', 'works for', 'state')",
+ )
+ .bind(works_for)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ for (id, type_id, name) in [
+ (platform, organization, "Platform Engineering"),
+ (finance, organization, "Finance"),
+ (both, organization, "Nebula Holdings"),
+ (zhang_a, person, "Zhang Wei"),
+ (zhang_b, person, "Zhang Wei"),
+ ] {
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
+ )
+ .bind(id)
+ .bind(kb)
+ .bind(type_id)
+ .bind(name)
+ .execute(pool)
+ .await?;
+ }
+ // 两人的画像**完全相同**:同一个 chunk 播的种(#221 之后是常态)。
+ // 向量在这个场景里注定分不开他们
+ for (id, v) in [(zhang_a, "[1,0,0]"), (zhang_b, "[1,0,0]")] {
+ sqlx::query(
+ "UPDATE entities SET profile_embedding = $2::vector, profile_n = 1 WHERE id = $1",
+ )
+ .bind(id)
+ .bind(v)
+ .execute(pool)
+ .await?;
+ }
+ let mut pairs = vec![(zhang_a, platform), (zhang_b, finance)];
+ if shared {
+ pairs.push((zhang_a, both));
+ pairs.push((zhang_b, both));
+ }
+ for (subject, object) in pairs {
+ sqlx::query(
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, confidence)
+ VALUES ($1, $2, $3, $4, $5, 0.9)",
+ )
+ .bind(Uuid::now_v7())
+ .bind(kb)
+ .bind(subject)
+ .bind(works_for)
+ .bind(object)
+ .execute(pool)
+ .await?;
+ }
+ Ok(Fx {
+ kb,
+ person,
+ zhang_a,
+ zhang_b,
+ })
+}
+
+async fn drop_kb(pool: &PgPool, kb: Uuid) -> anyhow::Result<()> {
+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 并列 + 原文点了其中一个人的部门 → 定案,不再掷硬币也不再劳烦人。
+#[tokio::test]
+async fn a_fact_in_the_text_settles_a_namesake_tie() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool, false).await?;
+
+ let run = async {
+ let ctx: Vec<f32> = vec![1.0, 0.0, 0.0];
+ let r = utopia_store::resolution::resolve_mention(
+ &pool,
+ f.kb,
+ Some(f.person),
+ "Zhang Wei",
+ Some(&ctx),
+ Some("Zhang Wei of Finance signed off on the quarterly report."),
+ &[],
+ )
+ .await?;
+ assert!(!r.created, "原文点名了财务,不该再新建第三个张伟");
+ assert_eq!(r.entity_id, f.zhang_b, "该归到财务部那个张伟");
+ assert!(
+ r.reviews.is_empty(),
+ "事实已经把人分开了,不该再入人工审核对"
+ );
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ drop_kb(&pool, f.kb).await?;
+ run
+}
+
+/// 原文把两个部门都提了 → 这条线索在他们之间也分不开,维持 #329 的行为。
+#[tokio::test]
+async fn a_clue_that_points_at_both_settles_nothing() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool, false).await?;
+
+ let run = async {
+ let ctx: Vec<f32> = vec![1.0, 0.0, 0.0];
+ let r = utopia_store::resolution::resolve_mention(
+ &pool,
+ f.kb,
+ Some(f.person),
+ "Zhang Wei",
+ Some(&ctx),
+ Some("Platform Engineering and Finance both sent a Zhang Wei to the review."),
+ &[],
+ )
+ .await?;
+ assert!(r.created, "两边都命中就等于没命中,仍该新建实体");
+ assert_eq!(r.reviews.len(), 2, "仍该对两个候选各入一条人工审核对");
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ drop_kb(&pool, f.kb).await?;
+ run
+}
+
+/// **共同的雇主不是线索。** 两个张伟都在星云控股,文档提到星云控股什么也没说明——
+/// 这条事实在 SQL 里就该被排除,否则它是最容易撞上的那种误判。
+#[tokio::test]
+async fn an_employer_they_share_is_not_a_clue() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool, true).await?;
+
+ let run = async {
+ let ctx: Vec<f32> = vec![1.0, 0.0, 0.0];
+ let r = utopia_store::resolution::resolve_mention(
+ &pool,
+ f.kb,
+ Some(f.person),
+ "Zhang Wei",
+ Some(&ctx),
+ Some("Zhang Wei has worked at Nebula Holdings for six years."),
+ &[],
+ )
+ .await?;
+ assert!(
+ r.created,
+ "两人共有的雇主没有分辨力,不该拿它把 mention 判给其中一个"
+ );
+ assert_eq!(r.reviews.len(), 2, "仍是分不开,照旧入两条人工审核对");
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ drop_kb(&pool, f.kb).await?;
+ run
+}
+
+/// 谁都没提到 → 一切照旧。**这一条是那道闸**:不一致(或没提)绝不能被当成
+/// 「不是同一人」的证据,否则兼职的人会被拆成两个。
+#[tokio::test]
+async fn text_that_names_neither_changes_nothing() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool, false).await?;
+
+ let run = async {
+ let ctx: Vec<f32> = vec![1.0, 0.0, 0.0];
+ let with_text = utopia_store::resolution::resolve_mention(
+ &pool,
+ f.kb,
+ Some(f.person),
+ "Zhang Wei",
+ Some(&ctx),
+ // 提到的是第三家公司:一致的证据没有,"不一致"也不算证据
+ Some("Zhang Wei moonlights at Zenith Robotics on weekends."),
+ &[],
+ )
+ .await?;
+ assert!(with_text.created, "没有命中就该保持 #329 的行为");
+ assert_eq!(with_text.reviews.len(), 2, "两条人工审核对照旧");
+ assert_ne!(with_text.entity_id, f.zhang_a);
+ assert_ne!(with_text.entity_id, f.zhang_b);
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ drop_kb(&pool, f.kb).await?;
+ run
+}
+
+/// 灰区(分数在 `SIM_NEW..SIM_ATTACH`)同样受旁证左右:向量说「不够像」,
+/// 而原文点了名。阈值一个都没动,动的是在阈值之外多问了一句。
+#[tokio::test]
+async fn the_grey_zone_listens_to_the_facts_too() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool, false).await?;
+
+ let run = async {
+ // 让两个候选分开且都落在灰区:与 A 约 0.45,与 B 约 0.40,
+ // 差 0.05 > SIM_TIE_MARGIN,所以走的是灰区那条路而不是并列那条
+ sqlx::query("UPDATE entities SET profile_embedding = '[0,1,0]'::vector WHERE id = $1")
+ .bind(f.zhang_b)
+ .execute(&pool)
+ .await?;
+ let ctx: Vec<f32> = vec![0.45, 0.40, 0.80];
+ let r = utopia_store::resolution::resolve_mention(
+ &pool,
+ f.kb,
+ Some(f.person),
+ "Zhang Wei",
+ Some(&ctx),
+ Some("The Finance lead, Zhang Wei, approved it."),
+ &[],
+ )
+ .await?;
+ assert!(!r.created, "灰区里原文点了名,就不该再新建一个同名实体");
+ assert_eq!(r.entity_id, f.zhang_b, "该归到财务部那个");
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ drop_kb(&pool, f.kb).await?;
+ run
+}
diff --git a/crates/utopia-store/tests/human_type_decisions.rs b/crates/utopia-store/tests/human_type_decisions.rs
index f51adf9c..4b3401f9 100644
--- a/crates/utopia-store/tests/human_type_decisions.rs
+++ b/crates/utopia-store/tests/human_type_decisions.rs
@@ -227,6 +227,7 @@ async fn extraction_does_not_fill_in_a_type_a_human_left_empty() -> anyhow::Resu
Some(f.org_type),
&name,
Some(&ctx),
+ None,
&[],
)
.await?;
diff --git a/crates/utopia-store/tests/review_stages.rs b/crates/utopia-store/tests/review_stages.rs
index c396c670..f6439f9e 100644
--- a/crates/utopia-store/tests/review_stages.rs
+++ b/crates/utopia-store/tests/review_stages.rs
@@ -59,16 +59,19 @@ async fn human_review_is_visible_but_never_pending_adjudication() -> anyhow::Res
}
let run = async {
- let ordinary = resolution::resolve_mention(&pool, kb, Some(ty), "Acme", None, &[]).await?;
+ let ordinary =
+ resolution::resolve_mention(&pool, kb, Some(ty), "Acme", None, None, &[]).await?;
assert_eq!(ordinary.entity_id, existing);
assert!(!ordinary.created, "exclude=[] must retain ordinary recall");
let split =
- resolution::resolve_mention(&pool, kb, Some(ty), "Acme", None, &[existing]).await?;
+ resolution::resolve_mention(&pool, kb, Some(ty), "Acme", None, None, &[existing])
+ .await?;
assert_ne!(split.entity_id, existing);
assert!(split.created, "the excluded candidate cannot be attached");
let recalled_split =
- resolution::resolve_mention(&pool, kb, Some(ty), "Acme", None, &[existing]).await?;
+ resolution::resolve_mention(&pool, kb, Some(ty), "Acme", None, None, &[existing])
+ .await?;
assert_eq!(recalled_split.entity_id, split.entity_id);
assert!(
!recalled_split.created,