World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
A name is a fact, and the extractor reports the other names it reads (#670)
WaylandYangf680576d58ab
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rsindex 4b007cda..8dd446f5 100644--- a/crates/utopia-core/src/models.rs+++ b/crates/utopia-core/src/models.rs@@ -655,7 +655,6 @@ pub struct Entity {/// 是「抽取器抽到了东西,但本体里没有对应的类」这个状态pub type_id: Option<Uuid>,pub canonical_name: String,- pub aliases: Vec<String>,pub merged_into: Option<Uuid>,pub created_at: DateTime<Utc>,pub updated_at: DateTime<Utc>,@@ -728,6 +727,23 @@ pub struct GraphEdge {pub blocked: bool,}+/// 一个实体的一个名字(0041):`known_as` 上的一条值事实,单独成一栏,不混进事实行。+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]+pub struct NameView {+ pub fact_id: Uuid,+ pub name: String,+ /// 界面上显示的那个名字(`entities.canonical_name`)+ pub canonical: bool,+ pub recorded_at: DateTime<Utc>,+ /// 世界轴:曾用名在这里有一个结束+ 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 document_ids: Vec<Uuid>,+ pub evidence_count: i64,+}+/// 实体详情页的事实行(时间线)。#[derive(Debug, Clone, Serialize, sqlx::FromRow)]pub struct EntityFact {diff --git a/crates/utopia-extract/src/lib.rs b/crates/utopia-extract/src/lib.rsindex aba970ec..f21707a4 100644--- a/crates/utopia-extract/src/lib.rs+++ b/crates/utopia-extract/src/lib.rs@@ -16,6 +16,10 @@ pub struct Extraction {pub entities: Vec<ExtractedEntity>,#[serde(default)]pub facts: Vec<ExtractedFact>,+ /// 实体在这段文字里的**别的名字**(0041 决定 2):简称、曾用名、另一种文字的写法。+ /// 模型报,服务端只核对名字与引文确实在原文里——认不认「简称」「又名」这些词是模型的事+ #[serde(default)]+ pub names: Vec<ExtractedName>,/// 逐项解析时被跳过的条目数。**必须报给调用方**——不报就是一次静默丢弃,/// 与 #108「部分抽取报告成完成」同一类错#[serde(skip)]@@ -46,6 +50,17 @@ pub struct ExtractedEntity {pub specific_type: Option<String>,}+/// 一个实体的一个别的名字。`ref` 是这次回复里的 local_id,或者提示词给的 k 句柄+#[derive(Debug, Deserialize)]+pub struct ExtractedName {+ #[serde(rename = "ref")]+ pub entity_ref: String,+ pub name: String,+ /// 名字出现在里面的那段原文,逐字抄+ #[serde(default)]+ pub quote: Option<String>,+}+#[derive(Debug, Deserialize)]pub struct ExtractedFact {pub subject: String,@@ -265,7 +280,8 @@ pub fn build_messages(Output format:\n\{{\"entities\":[{{\"local_id\":\"e1\",\"name\":\"entity name\",\"type\":\"type key\",\"specific_type\":\"what you would call it\"}}],\n\\"facts\":[{{\"subject\":\"subject entity name\",\"subject_ref\":\"e1\",\"subject_span\":\"the words in quote that name the subject\",\"predicate\":\"relation key\",\"object\":\"object entity name\",\"object_ref\":\"e2\",\"object_span\":\"the words in quote that name the object\",\n\- \"valid_from\":\"2023-01\",\"valid_to\":null,\"confidence\":0.9,\"quote\":\"verbatim supporting quote\"}}]}}\n\+ \"valid_from\":\"2023-01\",\"valid_to\":null,\"confidence\":0.9,\"quote\":\"verbatim supporting quote\"}}],\n\+ \"names\":[{{\"ref\":\"e1\",\"name\":\"another name the text uses for it\",\"quote\":\"verbatim text containing that name\"}}]}}\n\\n\Rules:\n\1. Give every newly listed entity a local_id unique within this response (e1, e2, ...). \@@ -281,6 +297,14 @@ pub fn build_messages(\"星云科技上海研究院\" becomes \"上海研究院\", \"Nebula Technologies Inc.\" becomes \\"Nebula\" — and both forms mean one entity, listed once under the fuller form. \Two names are two entities only when the text is talking about two things.\n\+ 1b. Every other name the text gives an entity goes into \"names\", once per name: the \+ shortened form it introduces or uses (\"上海研究院\" for \"星云科技上海研究院\"), a \+ former name, the name in another language. \"ref\" is the entity's local_id or its \+ known handle, and \"quote\" is a verbatim excerpt that contains the name. Only \+ names belong there — never a pronoun or a description (\"该公司\", \"the company\", \+ \"former employees\") — and never the name already written in entities. A name \+ must name the entity itself, not something that belongs to it: \"星云科技研发团队\" \+ names a team, not 星云科技.\n\2. Every fact keeps its name fields and uses subject_ref; relation facts also use \object_ref. Each ref must be either a local_id defined exactly once in \entities or a known handle supplied with this text. An entity referenced by a known \@@ -554,6 +578,8 @@ pub fn parse_response(raw: &str) -> anyhow::Result<Extraction> {let (mut entities, mut skipped_entities) = take::<ExtractedEntity>(&value, "entities");let (facts, skipped_facts) = take::<ExtractedFact>(&value, "facts");+ // 名字条目坏了不算实体或事实被跳过:丢一个名字只是少一座桥,不丢断言+ let (names, _) = take::<ExtractedName>(&value, "names");// A handle identifies exactly one entity definition within one response. Reject every// definition participating in a duplicate (including identical duplicates): keeping the@@ -579,6 +605,7 @@ pub fn parse_response(raw: &str) -> anyhow::Result<Extraction> {Ok(Extraction {entities,facts,+ names,skipped_entities,skipped_facts,truncated,@@ -1583,6 +1610,27 @@ mod tests {assert!(without.facts[0].object_span.is_none());}+ #[test]+ fn names_are_parsed_and_a_malformed_one_is_skipped() {+ let raw = r#"{"entities":[{"local_id":"e1","name":"海洋探测器1号","type":"equipment"}],+ "facts":[],+ "names":[{"ref":"e1","name":"海探1","quote":"海洋探测器1号(简称“海探1”)"},+ {"name":"no ref"}]}"#;+ let x = parse_response(raw).unwrap();+ assert_eq!(x.names.len(), 1);+ assert_eq!(x.names[0].entity_ref, "e1");+ assert_eq!(x.names[0].name, "海探1");+ assert_eq!(x.skipped_entities, 0, "a bad name is not a skipped entity");+ }++ #[test]+ fn the_contract_asks_for_other_names_and_forbids_descriptions() {+ let msgs = build_messages(&[], &[], &[], None, "f.txt", &[], "text");+ let system = &msgs[0].content;+ assert!(system.contains("\"names\":[{\"ref\""));+ assert!(system.contains("1b. Every other name the text gives an entity"));+ }+#[test]fn parse_response_with_fence() {let raw = "好的,结果如下:\n```json\n{\"entities\":[{\"name\":\"张三\",\"type\":\"person\"}],\"facts\":[]}\n```";diff --git a/crates/utopia-extract/src/normalize.rs b/crates/utopia-extract/src/normalize.rsindex 427545d2..f0a7aa11 100644--- a/crates/utopia-extract/src/normalize.rs+++ b/crates/utopia-extract/src/normalize.rs@@ -423,7 +423,14 @@ pub fn normalize_facts(x: &mut Extraction) -> Vec<Normalization> {// ---- 被上面几条弄成孤点的声明 ----// 只去掉「原来有事实引用、现在没有了」的:模型一开始就只声明不连边的,不归这里管- let after = referenced(&x.facts);+ let mut after = referenced(&x.facts);+ // 模型给它报了别的名字的声明也不算孤点:那些名字要绑在它身上(0041)+ after.extend(+ x.names+ .iter()+ .filter_map(|n| handle_name(Some(&n.entity_ref)))+ .map(|n| n.to_lowercase()),+ );let mut orphans = Vec::new();let mut kept_entities = entities;kept_entities.retain(|e| {@@ -494,6 +501,7 @@ mod tests {skipped_entities: 0,skipped_facts: 0,truncated: false,+ names: Vec::new(),};let n = normalize_facts(&mut x);(x, n)diff --git a/crates/utopia-server/src/api/graph_routes.rs b/crates/utopia-server/src/api/graph_routes.rsindex 7a390f7f..eab2af2a 100644--- a/crates/utopia-server/src/api/graph_routes.rs+++ b/crates/utopia-server/src/api/graph_routes.rs@@ -186,8 +186,10 @@ pub async fn entity_detail(// 没落地的派生(0017 §3)也单独一个键:它们连 `derived_facts` 都不在let blocked =utopia_store::reasoning::blocked_for_entity(&state.pool, kb_id, entity_id).await?;+ // 名字也单独一个键(0041):本名、简称、曾用名,各带出处与有效期+ let names = utopia_store::names::for_entity(&state.pool, kb_id, entity_id, as_of).await?;Ok(Json(json!({- "entity": entity, "facts": facts,+ "entity": entity, "facts": facts, "names": names,"derived": derived, "blocked": blocked, "same_name": same_name,})))}diff --git a/crates/utopia-server/src/api/tools_graph.rs b/crates/utopia-server/src/api/tools_graph.rsindex 732a6be9..993da040 100644--- a/crates/utopia-server/src/api/tools_graph.rs+++ b/crates/utopia-server/src/api/tools_graph.rs@@ -630,12 +630,27 @@ pub async fn entity_facts(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value)}).collect();+ // 名字单独一行(0041):「海探1」和「海洋探测器1号」是同一个,模型答题时要知道+ let names = utopia_store::names::for_entity(&ctx.state.pool, ctx.kb_id, who.id, m.as_of)+ .await+ .unwrap_or_else(|e| {+ tracing::warn!(error = %e, "Entity names lookup failed");+ Vec::new()+ });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());}+ let other_names: Vec<&str> = names+ .iter()+ .filter(|n| !n.canonical)+ .map(|n| n.name.as_str())+ .collect();+ if !other_names.is_empty() {+ lines.push(format!("Also known as: {}", other_names.join(", ")));+ }if let Some(a) = &aligned {lines.push(a.clone());}@@ -692,6 +707,11 @@ pub async fn entity_facts(ctx: &ToolCtx<'_>, sink: &mut ToolSink, args: &Value)"kb_id": ctx.kb_id,"entity": {"id": node.id, "name": node.name,"type_key": node.type_key, "type_label": node.type_label},+ "names": names.iter().map(|n| json!({+ "fact_id": n.fact_id, "name": n.name, "canonical": n.canonical,+ "recorded_at": n.recorded_at, "valid_from": n.valid_from, "valid_to": n.valid_to,+ "document_ids": n.document_ids,+ })).collect::<Vec<_>>(),"at": m.at, "as_of": m.as_of, "before": m.before,"total_facts": facts.len(), "matched_facts": kept.len(),"limit": limit, "truncated": shown.len() < kept.len(),diff --git a/crates/utopia-server/src/bootstrap_ontology.rs b/crates/utopia-server/src/bootstrap_ontology.rsindex b6b9ff92..c380ae7c 100644--- a/crates/utopia-server/src/bootstrap_ontology.rs+++ b/crates/utopia-server/src/bootstrap_ontology.rs@@ -70,7 +70,8 @@ async fn counted_relation_groups(// 而 `produces` 有 265 条、`produced_by` 只有 15 条——票多的先进本体,// 票少的那个本该被 `predicate_match` 的 `_by` 规则接住,却因为**采纳路径压根// 没走匹配器**而长成了独立关系。匹配器只在抽取时用过,这里是它缺席的第二处。- let rtypes = utopia_store::graph::relation_types(&state.pool, kb_id).await?;+ let mut rtypes = utopia_store::graph::relation_types(&state.pool, kb_id).await?;+ rtypes.retain(|r| !utopia_store::names::is_name_attribute(r));let index = PredicateIndex::build(&rtypes);let mut docs_of: HashMap<String, HashSet<Uuid>> = HashMap::new();diff --git a/crates/utopia-server/src/extraction.rs b/crates/utopia-server/src/extraction.rsindex 1df4d1a5..fc52b6d4 100644--- a/crates/utopia-server/src/extraction.rs+++ b/crates/utopia-server/src/extraction.rs@@ -156,6 +156,15 @@ enum SpanVerdict {Misplaced(String),}+/// 模型报给 `bound` 的别名,是不是已经声明成了另一个实体的名字(0041)。+///+/// 结构判据,不认词:同一个名字不会同时是两样东西的名字。模型把「海探1项目」列成+/// 一个机构,又把它报成探测器的别名——两个答案打架,别名那个不要+fn name_claimed_elsewhere(name: &str, bound: Uuid, declared: &HashMap<String, Uuid>) -> bool {+ let key = utopia_store::resolution::normalize_name(name).to_lowercase();+ declared.get(&key).is_some_and(|id| *id != bound)+}+/// 片段在不在引文里:大小写、空白都不论fn span_in_quote(span: &str, quote: &str) -> bool {let norm = |s: &str| {@@ -909,7 +918,9 @@ async fn run(state: &AppState, document_id: Uuid, proposer: Proposer) -> anyhow:let etypes = utopia_store::graph::entity_types(&state.pool, doc.kb_id).await?;// 这一轮落过的事实(新建或重复观察):结尾对它们跑一遍签名检查let mut touched_facts: Vec<Uuid> = Vec::new();- let rtypes = utopia_store::graph::relation_types(&state.pool, doc.kb_id).await?;+ let mut rtypes = utopia_store::graph::relation_types(&state.pool, doc.kb_id).await?;+ // 名字属性不进给模型的清单(0041):名字走回复里的 `names`,服务端核对它在原文里+ rtypes.retain(|r| !utopia_store::names::is_name_attribute(r));// 关系与属性分道:属性走字面值通道,不进关系清单。//// **本体里没有对应关系时就没有谓词**(见 `facts.predicate_id`)。原词落进@@ -1355,6 +1366,24 @@ async fn run(state: &AppState, document_id: Uuid, proposer: Proposer) -> anyhow:if let Some(p) = proposed {let _ = utopia_store::resolution::set_proposed_type(&state.pool, id, p).await;}+ // 模型写下的这个名字就在这一块原文里时,给这条名字事实补出处(0041)。+ // 给已知句柄时它照提示词写的是清单上的全称,这一块里未必有——那就不补,+ // 这一块用的别的写法走下面的 `names`。+ // 记忆日志里的不补:那一句算不算出处,要等人点头(0018)+ if !await_nod && span_in_quote(name, &chunk.text) {+ let _ = utopia_store::names::record(+ &state.pool,+ doc.kb_id,+ id,+ name,+ Some(utopia_store::names::NameSource {+ chunk_id: chunk.id,+ quote: name,+ }),+ doc.doc_time,+ )+ .await;+ }// 模型自己的说法。**跟 proposed_type 分开存**:那一列的含义是// "本体里没有",增长回路靠它的稀有性设门槛;这一列每个实体都有。// 与粗类同名的不记——那不是更具体的说法,只是把清单抄了一遍@@ -1387,6 +1416,125 @@ async fn run(state: &AppState, document_id: Uuid, proposer: Proposer) -> anyhow:entity_type_of.insert(name.to_string(), type_id);}+ // 实体的别的名字(0041 决定 2)。**名字与引文都要在这一块原文里**:名字是召回的桥,+ // 一座凭空造的桥会把两个不相干的实体接到一起。认不认「简称」「又名」是模型的事,+ // 服务端不认词,只核对它抄的字是不是真在原文里+ // 这次回复声明的名字,加上本文档前面几块认下的:别名撞上它们之一就不收+ let declared_names: HashMap<String, Uuid> = entity_ids+ .iter()+ .map(|(name, id)| (name.as_str(), *id))+ .chain(+ doc_entities+ .iter()+ .map(|(id, _, name)| (name.as_str(), *id)),+ )+ .map(|(name, id)| {+ (+ utopia_store::resolution::normalize_name(name).to_lowercase(),+ id,+ )+ })+ .collect();+ for n in &extraction.names {+ let name = n.name.trim();+ let Some(bound) = ref_entities.get(n.entity_ref.trim()) else {+ drop_signal(+ state,+ doc.kb_id,+ document_id,+ utopia_store::extraction_drops::reason::MALFORMED_ITEM,+ "name ref is not a declared handle",+ Some(name),+ )+ .await;+ continue;+ };+ let quote = n+ .quote+ .as_deref()+ .map(str::trim)+ .filter(|q| !q.is_empty())+ .unwrap_or(name);+ if name_claimed_elsewhere(name, bound.id, &declared_names) {+ drop_signal(+ state,+ doc.kb_id,+ document_id,+ utopia_store::extraction_drops::reason::NAME_CLAIMED_BY_ANOTHER,+ &n.entity_ref,+ Some(name),+ )+ .await;+ continue;+ }+ if !is_entity_name(name)+ || !span_in_quote(name, quote)+ || !span_in_quote(quote, &chunk.text)+ {+ drop_signal(+ state,+ doc.kb_id,+ document_id,+ utopia_store::extraction_drops::reason::NAME_NOT_IN_TEXT,+ &n.entity_ref,+ Some(name),+ )+ .await;+ continue;+ }+ // 记忆日志读到的名字与它的其它事实一样等人点头(0018):名字是召回的桥,+ // 一句没确认过的话不该先把桥搭上。点头之后是一条普通的名字事实;+ // 这一步不配对,同名的配对等下一次在文档里读到它+ if await_nod {+ let known_as = utopia_store::names::ensure_known_as(&state.pool, doc.kb_id).await?;+ let value = serde_json::json!({+ "value": utopia_store::resolution::normalize_name(name)+ });+ if let utopia_store::pending::Outcome::Proposed(_) = utopia_store::pending::propose(+ &state.pool,+ utopia_store::pending::Proposal {+ kb_id: doc.kb_id,+ subject_id: bound.id,+ predicate_id: Some(known_as),+ object_id: None,+ object_value: Some(&value),+ proposed_predicate: Some(utopia_store::names::KNOWN_AS),+ validity: utopia_store::graph::Validity {+ attested_at: doc.doc_time,+ ..Default::default()+ },+ confidence: 1.0,+ chunk_id: chunk.id,+ proposed_by: proposer.user_id,+ proposed_token: proposer.token_id,+ },+ )+ .await?+ {+ pending_count += 1;+ }+ continue;+ }+ utopia_store::names::record(+ &state.pool,+ doc.kb_id,+ bound.id,+ name,+ Some(utopia_store::names::NameSource {+ chunk_id: chunk.id,+ quote,+ }),+ doc.doc_time,+ )+ .await?;+ // 别的实体已经叫这个名字:送去裁决,不合并+ if utopia_store::names::pair_shared_name(&state.pool, doc.kb_id, bound.id, name).await?+ > 0+ {+ needs_adjudication = true;+ }+ }+// 改绑的候选:这次回复声明的实体,加上提示词里给过的库内实体(#582)let span_declared: HashMap<String, Uuid> = {let mut m = entity_ids.clone();@@ -3305,7 +3453,29 @@ mod name_tests {#[cfg(test)]mod tests {- use super::{slot_matches, span_in_quote, verify_span, SpanVerdict};++ #[test]+ fn a_name_declared_for_another_entity_is_not_an_alias() {+ let (probe, project) = (Uuid::now_v7(), Uuid::now_v7());+ let declared = HashMap::from([+ ("海洋探测器1号".to_string(), probe),+ ("海探1项目".to_string(), project),+ ]);+ assert!(name_claimed_elsewhere("海探1项目", probe, &declared));+ assert!(+ name_claimed_elsewhere(" 海探1项目 ", probe, &declared),+ "空白不论"+ );+ assert!(+ !name_claimed_elsewhere("海探1", probe, &declared),+ "没人声明过的名字照收"+ );+ assert!(+ !name_claimed_elsewhere("海洋探测器1号", probe, &declared),+ "自己的名字不算撞"+ );+ }+ use super::{name_claimed_elsewhere, slot_matches, span_in_quote, verify_span, SpanVerdict};fn declared(names: &[&str]) -> HashMap<String, Uuid> {names.iter()@@ -3955,7 +4125,9 @@ mod tests {.await?;}let pairs: Vec<(Uuid, Uuid)> = sqlx::query_as(- "SELECT subject_id, object_id FROM facts WHERE kb_id = $1 ORDER BY subject_id",+ // 只看边:实体身上还有名字事实(0041),那些没有宾语实体+ "SELECT subject_id, object_id FROM facts+ WHERE kb_id = $1 AND object_id IS NOT NULL ORDER BY subject_id",).bind(kb).fetch_all(&pool)@@ -4038,7 +4210,8 @@ mod tests {"later bare mentions must reuse document-local C");let c_objects: Vec<Uuid> = sqlx::query_scalar(- "SELECT object_id FROM facts WHERE kb_id = $1 AND subject_id = $2 ORDER BY object_id",+ "SELECT object_id FROM facts+ WHERE kb_id = $1 AND subject_id = $2 AND object_id IS NOT NULL ORDER BY object_id",).bind(kb).bind(c)diff --git a/crates/utopia-server/src/ontology_index.rs b/crates/utopia-server/src/ontology_index.rsindex 0c92c882..b3e05bce 100644--- a/crates/utopia-server/src/ontology_index.rs+++ b/crates/utopia-server/src/ontology_index.rs@@ -76,7 +76,9 @@ pub async fn refresh(state: &AppState, kb_id: Uuid) -> anyhow::Result<usize> {/// 挂回 `queued` 等 30s。worker 槽立刻空出来,下一轮再试。pub async fn gate_required(state: &AppState, kb_id: Uuid) -> anyhow::Result<bool> {let etypes = utopia_store::graph::entity_types(&state.pool, kb_id).await?;- let rtypes = utopia_store::graph::relation_types(&state.pool, kb_id).await?;+ let mut rtypes = utopia_store::graph::relation_types(&state.pool, kb_id).await?;+ // 名字属性不进本体向量索引:检索出来就会被当成一条可抽的属性递给模型+ rtypes.retain(|r| !utopia_store::names::is_name_attribute(r));let budget = utopia_store::access::ontology_prompt_budget(&state.pool).await?;let chars = crate::extraction::full_ontology_chars(&etypes, &rtypes);if chars <= budget {diff --git a/crates/utopia-server/src/type_resolution.rs b/crates/utopia-server/src/type_resolution.rsindex cb90a6f1..5b6666cd 100644--- a/crates/utopia-server/src/type_resolution.rs+++ b/crates/utopia-server/src/type_resolution.rs@@ -316,8 +316,8 @@ fn profile_of(s: &utopia_store::resolution::TypeCandidateSubject) -> String {}}parts.push(s.canonical_name.clone());- if !s.aliases.is_empty() {- parts.push(s.aliases.join(", "));+ if !s.other_names.is_empty() {+ parts.push(s.other_names.join(", "));}if !s.roles.is_empty() {parts.push(s.roles.join(" "));diff --git a/crates/utopia-store/src/documents.rs b/crates/utopia-store/src/documents.rsindex c45bf405..c8ab0647 100644--- a/crates/utopia-store/src/documents.rs+++ b/crates/utopia-store/src/documents.rs@@ -834,6 +834,12 @@ pub async fn delete(JOIN chunks c ON c.id = fe.chunk_idJOIN documents d ON d.id = c.document_idWHERE fe.fact_id = f.id AND d.deleted_at IS NULL)+ -- 实体的本名不随文档走(0041):建实体时就记下了这条名字事实,这篇文档只是+ -- 给它补过出处。删掉出处,实体还叫这个名字,名字栏里不能少了它+ AND NOT EXISTS (SELECT 1 FROM relation_types nr+ JOIN entities ne ON ne.id = f.subject_id+ WHERE nr.id = f.predicate_id AND nr.builtin AND nr.key = 'known_as'+ AND lower(f.object_value->>'value') = lower(ne.canonical_name))RETURNING f.id",).bind(kb_id)diff --git a/crates/utopia-store/src/extraction_drops.rs b/crates/utopia-store/src/extraction_drops.rsindex 239d1c3b..5ea10c53 100644--- a/crates/utopia-store/src/extraction_drops.rs+++ b/crates/utopia-store/src/extraction_drops.rs@@ -54,6 +54,12 @@ pub mod reason {pub const SUBJECT_SHORTENED: &str = "subject_shortened";/// 主宾片段不在引文里(#582):模型没照抄。事实照旧处理,只记下来pub const SPAN_NOT_IN_QUOTE: &str = "span_not_in_quote";+ /// 模型报的别名(或它的引文)不在这一块原文里(0041 决定 2):不记这个名字。+ /// 名字是召回的桥,一座凭空的桥会把两个不相干的实体接到一起+ pub const NAME_NOT_IN_TEXT: &str = "name_not_in_text";+ /// 模型报的别名,这次回复(或本文档前面几块)里已经是另一个实体的名字(0041 决定 2):+ /// 一个名字不会同时是两样东西的名字。「海探1项目」声明成了一个机构,就不是探测器的别名+ pub const NAME_CLAIMED_BY_ANOTHER: &str = "name_claimed_by_another";/// 主语片段是个描述,不是任何声明过的实体的名字:事实不落(#582,取代 #578 的词表)pub const SUBJECT_DESCRIBED: &str = "subject_described";/// 宾语片段是个描述:事实照落,宾语落成字面值(#582)diff --git a/crates/utopia-store/src/governance.rs b/crates/utopia-store/src/governance.rsindex c8e60e37..6476316c 100644--- a/crates/utopia-store/src/governance.rs+++ b/crates/utopia-store/src/governance.rs@@ -722,7 +722,12 @@ pub async fn loop_calls_today(pool: &PgPool, kb_id: Uuid) -> AppResult<i64> {}/// 工具:提到这个实体的原文片段——它的事实是从哪句话里抽出来的,出自哪份文档。-/// 证据上有 quote 就用 quote,没有就截分块开头+/// 证据上有 quote 就用 quote,没有就截分块开头。+///+/// **名字事实排在后面,引文就是名字本身的不要**(0041)。名字事实置信度 1.0,+/// 按置信度排它每块都赢,而「这一块写了它的名字」的引文往往只是那个名字——+/// 给裁决的 agent 一串光秃秃的名字,等于没给原文。带整句引文的别名(「简称海探1」)+/// 照样留着,那正是判断是不是一个东西要看的pub async fn quotes_of(pool: &PgPool,kb_id: Uuid,@@ -730,15 +735,21 @@ pub async fn quotes_of(limit: i64,) -> AppResult<Vec<(String, String)>> {let rows: Vec<(String, String)> = sqlx::query_as(- "SELECT DISTINCT ON (fe.chunk_id) d.filename,- COALESCE(NULLIF(fe.quote, ''), left(c.text, 240))- FROM facts f- JOIN fact_evidence fe ON fe.fact_id = f.id- JOIN chunks c ON c.id = fe.chunk_id- JOIN documents d ON d.id = c.document_id- WHERE f.kb_id = $1 AND f.invalidated_at IS NULL- AND (f.subject_id = $2 OR f.object_id = $2)- ORDER BY fe.chunk_id, f.confidence DESC+ "SELECT filename, quote FROM (+ SELECT DISTINCT ON (fe.chunk_id) d.filename,+ COALESCE(NULLIF(fe.quote, ''), left(c.text, 240)) AS quote+ FROM facts f+ -- 谓词可以为空(0010),LEFT JOIN 才不丢那些事实+ LEFT JOIN relation_types r ON r.id = f.predicate_id+ JOIN fact_evidence fe ON fe.fact_id = f.id+ JOIN chunks c ON c.id = fe.chunk_id+ JOIN documents d ON d.id = c.document_id+ WHERE f.kb_id = $1 AND f.invalidated_at IS NULL+ AND (f.subject_id = $2 OR f.object_id = $2)+ AND NOT (coalesce(r.builtin AND r.key = 'known_as', false)+ AND lower(trim(coalesce(fe.quote, ''))) = lower(f.object_value->>'value'))+ ORDER BY fe.chunk_id, coalesce(r.builtin AND r.key = 'known_as', false), f.confidence DESC+ ) qLIMIT $3",).bind(kb_id)diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rsindex 0c075bcd..dfff67ed 100644--- a/crates/utopia-store/src/graph.rs+++ b/crates/utopia-store/src/graph.rs@@ -789,6 +789,8 @@ fn node_sql(as_of: Option<usize>, owner: Option<usize>) -> String {// 主宾也跟着倒:三月被合并掉的实体,在二月身上还挂着它自己的那些事实(#336)let subject = crate::record_axis::owner_at("f", "subject_id", owner, false);let object = crate::record_axis::owner_at("f", "object_id", owner, true);+ // 名字事实不算度数(0041):每个实体至少有一个名字,数进去所有节点一起变大一号+ let not_name = crate::names::not_a_name("f");format!("SELECT e.id, e.canonical_name AS name, t.key AS type_key,t.label AS type_label,@@ -796,7 +798,7 @@ fn node_sql(as_of: Option<usize>, owner: Option<usize>) -> String {coalesce(t.shape, 'circle') AS shape,e.disambiguator,(SELECT count(*) FROM facts f- WHERE ({subject} = e.id OR {object} = e.id) AND {held}) AS degree+ WHERE ({subject} = e.id OR {object} = e.id) AND {held} AND {not_name}) AS degreeFROM entities e LEFT JOIN entity_types t ON t.id = e.type_id")}@@ -1080,10 +1082,10 @@ 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- OR EXISTS (SELECT 1 FROM unnest(e.aliases) AS a WHERE a ILIKE $2))+ AND (e.canonical_name ILIKE $2 OR {named})ORDER BY degree DESC, e.canonical_name, e.id LIMIT $3 OFFSET $4",- node_sql(None, None)+ node_sql(None, None),+ named = crate::names::has_name_like("e", 2),)).bind(kb_id).bind(&pattern)@@ -1091,12 +1093,12 @@ pub async fn search_entities(.bind(offset).fetch_all(pool).await?;- let (total,): (i64,) = sqlx::query_as(+ let (total,): (i64,) = sqlx::query_as(&format!("SELECT count(*) FROM entities eWHERE 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))",- )+ AND (e.canonical_name ILIKE $2 OR {named})",+ named = crate::names::has_name_like("e", 2),+ )).bind(kb_id).bind(&pattern).fetch_one(pool)@@ -1171,7 +1173,9 @@ pub async fn entity_detail(LEFT JOIN entity_types ot ON ot.id = o.type_idWHERE f.kb_id = $1 AND {facts_held} AND {facts_hold}AND ({subject} = $2 OR {object} = $2)+ AND {not_name}ORDER BY f.valid_from NULLS LAST, f.recorded_at",+ not_name = crate::names::not_a_name("f"),facts_held = crate::record_axis::facts_held_at("f", 3),facts_hold = crate::world_axis::facts_hold_at("f", 4),holds_from = crate::world_axis::facts_holds_from("f"),@@ -1283,6 +1287,12 @@ pub async fn update_entity(.execute(pool).await?;+ // 人改的名字也是一条名字事实(0041)。旧名字不作废:之前的文档还管它叫旧名字,+ // 召回靠它认出来;它只是不再是界面上显示的那一个+ if let Some(n) = new_name {+ crate::names::record(pool, kb_id, entity_id, n, None, None).await?;+ }+// 消歧后缀依赖名字分组与类型标签(类型标签是它的兜底值),两者都刚被改过。// 改名要刷两组:旧名那组可能掉到 1 个(后缀该清掉),新名那组可能涨到 2 个。if let Some(n) = new_name.filter(|n| !n.eq_ignore_ascii_case(&before.name)) {@@ -1763,7 +1773,11 @@ pub async fn graph_changes(WHERE fe.fact_id = ev.idORDER BY fe.doc_version DESC NULLS LAST LIMIT 1) src ON true- WHERE $5::text[] IS NULL OR ev.kind = ANY($5)+ WHERE ($5::text[] IS NULL OR ev.kind = ANY($5))+ -- 实体的本名那条名字事实不算一次变化(0041):每建一个实体就多一行「X known as X」,+ -- 限量的变更清单会被它挤满。新读到的别名、改名照样列出来+ AND NOT (coalesce(r.builtin AND r.key = 'known_as', false)+ AND lower(ev.object_value->>'value') = lower(s.canonical_name))ORDER BY ev.at DESC, ev.idLIMIT $6"))diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rsindex ec1471e2..e25e3203 100644--- a/crates/utopia-store/src/lib.rs+++ b/crates/utopia-store/src/lib.rs@@ -22,6 +22,7 @@ pub mod mappings;pub mod members;pub mod memory;pub mod model_limits;+pub mod names;pub mod ontology;pub mod palette;pub mod paths;diff --git a/crates/utopia-store/src/names.rs b/crates/utopia-store/src/names.rsnew file mode 100644index 00000000..eac70aba--- /dev/null+++ b/crates/utopia-store/src/names.rs@@ -0,0 +1,257 @@+//! 名字是关于实体的一条事实(0041 决定 1)。+//!+//! 一个实体的每个名字——本名、简称、曾用名、另一种文字的写法——都是内建属性+//! `known_as` 上的一条值事实:`object_value = {"value": 名字}`,`object_id` 为空。+//! 它有出处(证据引文)、两个时钟、可以有有效期(更名),能被撤回,合并时跟着+//! 其它事实一起搬、撤回合并时一起搬回去。**它是值,不是节点**:画布只画带+//! `object_id` 的边。+//!+//! 读的时候要分清两件事,这个模块给两种 SQL 片段:+//! - 召回:`has_name_in` —— 这个实体有没有叫这些名字之一的(含曾用名:世界轴上+//! 结束了的名字仍然认得出旧文档里的它,所以只看记录轴 `invalidated_at`);+//! - 列事实:`not_a_name` —— 实体面板、审阅卡、度数、规则这些地方,名字不算+//! 一条「事实」,不能冒充证据,也不能把计数撑大。++use crate::graph::{add_evidence, insert_value_fact, Validity};+use crate::resolution::normalize_name;+use sqlx::PgPool;+use utopia_core::models::{NameView, RelationType};+use utopia_core::AppResult;+use uuid::Uuid;++/// 内建属性的 key。与 `is_a` 同一个做法:`builtin = TRUE`,建库时不铺,第一次要时建+pub const KNOWN_AS: &str = "known_as";++/// 这条关系类型是不是名字属性。给模型看的清单、本体引导、本体向量索引都要把它拿掉:+/// 名字走自己的通道(抽取回复里的 `names`,服务端核对它在原文里),不能当一条普通属性+/// 被模型直接写进来——那样就绕过了核对+pub fn is_name_attribute(r: &RelationType) -> bool {+ r.builtin && r.key == KNOWN_AS+}++/// 取(没有就建)这个库的 `known_as` 属性。+pub async fn ensure_known_as(pool: &PgPool, kb_id: Uuid) -> AppResult<Uuid> {+ if let Some((id,)) =+ sqlx::query_as::<_, (Uuid,)>("SELECT id FROM relation_types WHERE kb_id = $1 AND key = $2")+ .bind(kb_id)+ .bind(KNOWN_AS)+ .fetch_optional(pool)+ .await?+ {+ return Ok(id);+ }+ sqlx::query(+ "INSERT INTO relation_types (id, kb_id, key, label, kind, datatype, temporal, builtin, description)+ VALUES ($1, $2, $3, 'known as', 'attribute', 'text', 'state', TRUE, $4)+ ON CONFLICT (kb_id, key) DO NOTHING",+ )+ .bind(Uuid::now_v7())+ .bind(kb_id)+ .bind(KNOWN_AS)+ .bind(+ "A name a text uses for this entity. Each name is a fact with its source and both clocks; \+ a name is a value and never becomes a node.",+ )+ .execute(pool)+ .await?;+ // ON CONFLICT 命中说明并发建过了,取回那一条+ let (id,): (Uuid,) =+ sqlx::query_as("SELECT id FROM relation_types WHERE kb_id = $1 AND key = $2")+ .bind(kb_id)+ .bind(KNOWN_AS)+ .fetch_one(pool)+ .await?;+ Ok(id)+}++/// 一个名字的出处:哪一块、引文。没有出处的名字(人在界面上写的、迁移补的)传 None+#[derive(Debug, Clone, Copy)]+pub struct NameSource<'a> {+ pub chunk_id: Uuid,+ pub quote: &'a str,+}++/// 记下「这段文字管这个实体叫这个名字」。返回名字事实的 id;名字是空的返回 None。+///+/// 同一个实体同一个名字只有一行(`insert_value_fact` 按主语、谓词、值去重),+/// 再被提到只是多一条证据、证据日期往早挪。+pub async fn record(+ pool: &PgPool,+ kb_id: Uuid,+ entity_id: Uuid,+ name: &str,+ source: Option<NameSource<'_>>,+ attested_at: Option<chrono::DateTime<chrono::Utc>>,+) -> AppResult<Option<Uuid>> {+ let name = normalize_name(name);+ if name.is_empty() {+ return Ok(None);+ }+ let attr = ensure_known_as(pool, kb_id).await?;+ let (fact_id, _) = insert_value_fact(+ pool,+ kb_id,+ entity_id,+ Some(attr),+ &serde_json::json!({ "value": name }),+ Validity {+ attested_at,+ ..Default::default()+ },+ 1.0,+ )+ .await?;+ if let Some(s) = source {+ add_evidence(pool, fact_id, s.chunk_id, Some(s.quote), Some(KNOWN_AS)).await?;+ }+ Ok(Some(fact_id))+}++/// 召回用:实体 `{entity}` 有一条现行的名字事实,库 id 在第 `${kb}` 个参数,+/// 小写值在第 `${names}` 个参数(text[])里。+///+/// 只看记录轴:世界轴上结束了的名字(曾用名)照样召回——更名之前的文档还在用它。+///+/// **写成不相关子查询,按库过滤,并带上索引的谓词**(`facts_value_text_idx` 是+/// `(kb_id, lower(value)) WHERE invalidated_at IS NULL AND object_value IS NOT NULL`)。+/// 相关子查询 `nf.subject_id = e.id` 不带库,规划器用不上这个索引,每次召回都要+/// 扫全表的 facts——所有库的+pub fn has_name_in(entity: &str, kb: usize, names: usize) -> String {+ format!(+ "{entity}.id IN (SELECT nf.subject_id FROM facts nf+ JOIN relation_types nr ON nr.id = nf.predicate_id+ WHERE nf.kb_id = ${kb} AND nr.kb_id = ${kb} AND nr.builtin AND nr.key = '{KNOWN_AS}'+ AND nf.invalidated_at IS NULL AND nf.object_value IS NOT NULL+ AND lower(nf.object_value->>'value') = ANY(${names}))"+ )+}++/// 查找用:实体 `{entity}` 有一条现行的名字事实 ILIKE 第 `${param}` 个参数。+pub fn has_name_like(entity: &str, param: usize) -> String {+ format!(+ "EXISTS (SELECT 1 FROM facts nf+ JOIN relation_types nr ON nr.id = nf.predicate_id+ WHERE nf.subject_id = {entity}.id AND nf.kb_id = {entity}.kb_id+ AND nr.builtin AND nr.key = '{KNOWN_AS}'+ AND nf.invalidated_at IS NULL+ AND nf.object_value->>'value' ILIKE ${param})"+ )+}++/// 列事实用:事实 `{fact}` 不是名字事实。+pub fn not_a_name(fact: &str) -> String {+ format!(+ "NOT EXISTS (SELECT 1 FROM relation_types nr+ WHERE nr.id = {fact}.predicate_id AND nr.builtin AND nr.key = '{KNOWN_AS}')"+ )+}++/// 一个实体的名字栏:本名在前,其余按首次记下的先后。`as_of` 回放到当时库里记着的名字。+pub async fn for_entity(+ pool: &PgPool,+ kb_id: Uuid,+ entity_id: Uuid,+ as_of: Option<chrono::DateTime<chrono::Utc>>,+) -> AppResult<Vec<NameView>> {+ Ok(sqlx::query_as(&format!(+ "SELECT f.id AS fact_id, f.object_value->>'value' AS name,+ lower(f.object_value->>'value') = lower(e.canonical_name) AS canonical,+ f.recorded_at, f.valid_from, f.valid_from_precision, f.valid_to, f.valid_to_precision,+ ARRAY(SELECT DISTINCT fe.document_id FROM fact_evidence fe+ WHERE fe.fact_id = f.id AND fe.document_id IS NOT NULL+ ORDER BY fe.document_id) AS document_ids,+ (SELECT count(*) FROM fact_evidence fe WHERE fe.fact_id = f.id) AS evidence_count+ FROM facts f+ JOIN relation_types r ON r.id = f.predicate_id+ JOIN entities e ON e.id = $2+ WHERE f.kb_id = $1 AND r.builtin AND r.key = '{KNOWN_AS}'+ AND {owner} = $2 AND {held}+ ORDER BY canonical DESC, f.recorded_at",+ owner = crate::record_axis::owner_at("f", "subject_id", as_of.map(|_| 3), false),+ held = crate::record_axis::facts_held_at("f", 3),+ ))+ .bind(kb_id)+ .bind(entity_id)+ .bind(as_of)+ .fetch_all(pool)+ .await?)+}++/// 一个刚从原文里读到的别名,别的实体已经在用:把这一对送去裁决(0041 决定 5 的第一步)。+///+/// **只排队,不合并。** 两个实体叫同一个名字,可能是一个东西被拆开了(「海探1」先到、+/// 写着「简称海探1」的那篇后到),也可能就是两个东西。判断归裁决器与治理闸门。+/// 不排的话,后到的那篇把名字记在新实体上,两个实体都叫「海探1」,却没有任何东西+/// 把它们配成一对——入库顺序又一次决定了结果。+///+/// 类型一方为空或两边相同才配:声明了不同类型的同名,是重名那条路的事。+///+/// **已经判过「不是一个」的对不再排。** 同一个简称每出现在一块里就会走到这里一次;+/// 人(或裁决器)分开过的一对要是每次都重新进队列,分开这个决定就等于没有记住。+/// 返回排进去的对数+pub async fn pair_shared_name(+ pool: &PgPool,+ kb_id: Uuid,+ entity_id: Uuid,+ name: &str,+) -> AppResult<usize> {+ let name = normalize_name(name);+ let others: Vec<(Uuid,)> = sqlx::query_as(+ "SELECT DISTINCT e.id+ FROM entities e+ JOIN entities me ON me.id = $2+ JOIN facts nf ON nf.subject_id = e.id AND nf.kb_id = $1+ AND nf.invalidated_at IS NULL AND nf.object_value IS NOT NULL+ JOIN relation_types nr ON nr.id = nf.predicate_id AND nr.builtin AND nr.key = $4+ WHERE e.kb_id = $1 AND e.merged_into IS NULL AND e.id <> $2+ AND lower(nf.object_value->>'value') = lower($3)+ AND (e.type_id IS NULL OR me.type_id IS NULL OR e.type_id = me.type_id)+ AND NOT EXISTS (+ SELECT 1 FROM resolution_reviews rr+ WHERE rr.kb_id = $1 AND rr.status = 'kept'+ AND least(rr.left_id, rr.right_id) = least(e.id, $2)+ AND greatest(rr.left_id, rr.right_id) = greatest(e.id, $2))+ LIMIT 4",+ )+ .bind(kb_id)+ .bind(entity_id)+ .bind(&name)+ .bind(KNOWN_AS)+ .fetch_all(pool)+ .await?;+ for (other,) in &others {+ crate::resolution::create_review(+ pool,+ kb_id,+ entity_id,+ *other,+ 0.0,+ &format!("shared_name|{name}"),+ crate::resolution::ReviewStage::Adjudicating,+ )+ .await?;+ }+ Ok(others.len())+}++/// 本名以外的现行名字,按首次记下的先后。给裁决器与审阅卡的「又名」那一行+pub async fn other_names(pool: &PgPool, entity_id: Uuid) -> AppResult<Vec<String>> {+ let rows: Vec<(String,)> = sqlx::query_as(+ "SELECT v FROM (+ SELECT DISTINCT ON (lower(f.object_value->>'value'))+ f.object_value->>'value' AS v, f.recorded_at+ FROM facts f+ JOIN relation_types r ON r.id = f.predicate_id+ JOIN entities e ON e.id = f.subject_id+ WHERE f.subject_id = $1 AND r.builtin AND r.key = $2+ AND f.invalidated_at IS NULL+ AND lower(f.object_value->>'value') <> lower(e.canonical_name)+ ORDER BY lower(f.object_value->>'value'), f.recorded_at+ ) n ORDER BY n.recorded_at",+ )+ .bind(entity_id)+ .bind(KNOWN_AS)+ .fetch_all(pool)+ .await?;+ Ok(rows.into_iter().map(|(v,)| v).collect())+}diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rsindex d96de7c2..90ef42c9 100644--- a/crates/utopia-store/src/ontology.rs+++ b/crates/utopia-store/src/ontology.rs@@ -607,6 +607,21 @@ pub async fn update_relation_type(domains: Option<&[Uuid]>,ranges: Option<&[Uuid]>,) -> AppResult<()> {+ // 名字属性是内建的(0041):标成 functional 会让每个第二个名字都成一条冲突、+ // 甚至把本名关掉;改名、改时态也一样没有正当用途+ let name_attribute: Option<(bool,)> = sqlx::query_as(+ "SELECT builtin AND key = 'known_as' FROM relation_types WHERE id = $1 AND kb_id = $2",+ )+ .bind(id)+ .bind(kb_id)+ .fetch_optional(pool)+ .await?;+ if name_attribute == Some((true,)) {+ return Err(AppError::invalid(+ "builtin_name_attribute",+ "The name attribute is built in and cannot be edited",+ ));+ }// 改名也归一:不然界面上改一次就能把小驼峰改回 "access to"let label = &lower_camel(label);if !matches!(temporal, "state" | "event" | "eternal") {@@ -1186,14 +1201,17 @@ async fn relations_needing_embedding(model: &str,) -> AppResult<Vec<TypeToEmbed>> {// 判据同上(#672):在 Rust 里用 `embed_text` 比,不在 SQL 里重拼。关系只有整段- // 那一份向量,label 那三列补空+ // 那一份向量,label 那三列补空。+ //+ // 名字属性不嵌(0041):没有向量就不会被最近邻检索出来,本体提议、属性归并、+ // 抽取时的候选清单都碰不到它——名字只走抽取回复里的 `names` 那一条路let rows: Vec<StoredEmbedding> = sqlx::query_as("SELECT id, label, coalesce(description, '') AS description,embedding IS NOT NULL AS embedded, embedded_model, embedded_text,false AS label_embedded, NULL::text AS label_embedded_model,NULL::text AS label_embedded_textFROM relation_types- WHERE kb_id = $1",+ WHERE kb_id = $1 AND NOT (builtin AND key = 'known_as')",).bind(kb_id).fetch_all(pool)@@ -1383,17 +1401,22 @@ pub async fn nearest_relation_types(////// 不区分 kind:属性与关系同住一张表且共用 key 命名空间,调用方拿到 id 之后/// 该怎么用它自己清楚(改写事实时谓词就是谓词)。+///+/// 名字属性找不到(0041):把一批「简称」「former_name」的值事实归并到 `known_as`+/// 上,等于绕开了名字的核对与配对,所以这条路不给它pub async fn relation_type_id_by_key(pool: &PgPool,kb_id: Uuid,key: &str,) -> AppResult<Option<Uuid>> {- let row: Option<(Uuid,)> =- sqlx::query_as("SELECT id FROM relation_types WHERE kb_id = $1 AND key = $2")- .bind(kb_id)- .bind(key)- .fetch_optional(pool)- .await?;+ let row: Option<(Uuid,)> = sqlx::query_as(+ "SELECT id FROM relation_types+ WHERE kb_id = $1 AND key = $2 AND NOT (builtin AND key = 'known_as')",+ )+ .bind(kb_id)+ .bind(key)+ .fetch_optional(pool)+ .await?;Ok(row.map(|(id,)| id))}diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rsindex d68c1c2d..52393878 100644--- a/crates/utopia-store/src/resolution.rs+++ b/crates/utopia-store/src/resolution.rs@@ -253,16 +253,19 @@ pub async fn resolve_mention(// 召回键 = 本名 + 泛用后缀词干及其增广("星尘"↔"星尘项目"互为候选)。// 只扩召回,归并与否仍由下方画像相似度分层定夺。let keys = recall_keys(&name);- let candidates: Vec<Candidate> = sqlx::query_as(+ // 名字召回读名字事实(0041 决定 1):本名、简称、曾用名都是 `known_as` 上的一条。+ // 度数不数名字事实——名字不是一条「关于它的事」,数进去每个实体都凭空多一+ let candidates: Vec<Candidate> = sqlx::query_as(&format!("SELECT e.id, e.canonical_name, e.profile_embedding, e.profile_n,(SELECT count(*) FROM facts fWHERE (f.subject_id = e.id OR f.object_id = e.id)- AND f.invalidated_at IS NULL) AS degree+ AND f.invalidated_at IS NULL AND {not_name}) AS degreeFROM entities eWHERE e.kb_id = $1 AND e.type_id = $2 AND e.merged_into IS NULL- AND (lower(e.canonical_name) = ANY($3)- OR EXISTS (SELECT 1 FROM unnest(e.aliases) a WHERE lower(a) = ANY($3)))",- )+ AND (lower(e.canonical_name) = ANY($3) OR {named})",+ not_name = crate::names::not_a_name("f"),+ named = crate::names::has_name_in("e", 1, 3),+ )).bind(kb_id).bind(type_id).bind(&keys)@@ -559,7 +562,7 @@ const CONTAIN_SCAN_LIMIT: i64 = 16;/// 包含关系绝不能走它:`华瑞集团技术中心` 与 `星云科技技术中心` 都含「技术中心」,/// 同一篇文档里上下文相似度很容易过线,而它们是两个部门。宁分勿合。///-/// **别名一并参与**:合并会把名字搬进 `aliases`,只查 `canonical_name` 的话,+/// **别的名字一并参与**:合并会把名字事实搬到存活者身上,只查 `canonical_name` 的话,/// 每成功合并一次就少一条召回的桥——`Holmes` 并入 `Sherlock Holmes` 之后,/// 后来的 `Mr. Holmes` 就再也搭不上了(它跟 `Sherlock Holmes` 谁也不含谁)。/// 合并越成功、漏得越多,是个会自我加剧的洞。@@ -616,9 +619,9 @@ async fn containment_reviews((char_length(e.canonical_name) >= $4AND (lower(e.canonical_name) LIKE '%' || $3 || '%'OR $3 LIKE '%' || lower(e.canonical_name) || '%'))- -- **别名也要参与召回,否则每合并一次就少一条桥。**+ -- **别的名字也要参与召回,否则每合并一次就少一条桥。**--- -- 合并把名字搬进 aliases:Holmes 并入 Sherlock Holmes 之后,+ -- 合并把名字事实搬到存活者身上:Holmes 并入 Sherlock Holmes 之后,-- Holmes 那一行 merged_into 非空、被上面第一个条件滤掉了。可十分钟后-- 出现的 Mr. Holmes 跟 Sherlock Holmes 谁也不含谁——本来正是靠-- Holmes 才桥得上。实测就是这么漏的:同类型那个 bug 修好、Holmes@@ -626,10 +629,14 @@ async fn containment_reviews(---- 合并越成功,桥拆得越多。这个洞会自我加剧。OR EXISTS (- SELECT 1 FROM unnest(e.aliases) AS alias- WHERE char_length(alias) >= $4- AND (lower(alias) LIKE '%' || $3 || '%'- OR $3 LIKE '%' || lower(alias) || '%'))+ SELECT 1 FROM facts nf+ JOIN relation_types nr ON nr.id = nf.predicate_id+ WHERE nf.subject_id = e.id AND nf.kb_id = $1+ AND nr.builtin AND nr.key = 'known_as'+ AND nf.invalidated_at IS NULL+ AND char_length(nf.object_value->>'value') >= $4+ AND (lower(nf.object_value->>'value') LIKE '%' || $3 || '%'+ OR $3 LIKE '%' || lower(nf.object_value->>'value') || '%')))ORDER BY char_length(e.canonical_name)LIMIT $5",@@ -814,16 +821,16 @@ async fn resolve_type_drift(.map(|(k,)| k),None => None,};- let cross: Vec<CrossCandidate> = sqlx::query_as(+ let cross: Vec<CrossCandidate> = sqlx::query_as(&format!("SELECT e.id, e.canonical_name, t.key AS type_key, e.type_id, e.type_source,e.profile_embedding, e.profile_nFROM entities e LEFT JOIN entity_types t ON t.id = e.type_id-- IS DISTINCT FROM 而不是 <>:后者遇 NULL 返回 NULL,被 WHERE 当假,-- 未分类实体会被整个漏掉(0009)WHERE e.kb_id = $1 AND e.type_id IS DISTINCT FROM $2 AND e.merged_into IS NULL- AND (lower(e.canonical_name) = ANY($3)- OR EXISTS (SELECT 1 FROM unnest(e.aliases) a WHERE lower(a) = ANY($3)))",- )+ AND (lower(e.canonical_name) = ANY($3) OR {named})",+ named = crate::names::has_name_in("e", 1, 3),+ )).bind(kb_id).bind(type_id).bind(keys)@@ -974,6 +981,8 @@ async fn create_entity(// 分不开就别硬分,谁也不归,两个都送审。weighed: &[Uuid],) -> AppResult<(Uuid, bool)> {+ // 名字属性在锁外取:它自己有一次插入,放进锁里会让所有建实体的人排同一把队+ let known_as = crate::names::ensure_known_as(pool, kb_id).await?;let mut tx = pool.begin().await?;sqlx::query("SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))").bind(kb_id.to_string())@@ -1009,6 +1018,19 @@ async fn create_entity(.bind(i32::from(context.is_some())).execute(&mut *tx).await?;+ // 与实体同一个事务:召回按名字事实找它,建出来却查不到名字的那一瞬间不能有。+ // 出处(哪一块、哪句话)由抽取随后给这条事实补证据+ sqlx::query(+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_value)+ VALUES ($1, $2, $3, $4, jsonb_build_object('value', $5::text))",+ )+ .bind(Uuid::now_v7())+ .bind(kb_id)+ .bind(id)+ .bind(known_as)+ .bind(name)+ .execute(&mut *tx)+ .await?;tx.commit().await?;Ok((id, true))}@@ -1092,15 +1114,17 @@ pub async fn existing_by_name() -> AppResult<Option<Uuid>> {let name = normalize_name(raw_name);let keys = recall_keys(&name);- let id: Option<Uuid> = sqlx::query_scalar(+ let id: Option<Uuid> = sqlx::query_scalar(&format!("SELECT e.id FROM entities eWHERE e.kb_id = $1 AND e.merged_into IS NULL- AND (lower(e.canonical_name) = ANY($2)- OR EXISTS (SELECT 1 FROM unnest(e.aliases) a WHERE lower(a) = ANY($2)))+ AND (lower(e.canonical_name) = ANY($2) OR {named})ORDER BY (SELECT count(*) FROM facts f- WHERE f.subject_id = e.id OR f.object_id = e.id) DESC, e.created_at+ WHERE (f.subject_id = e.id OR f.object_id = e.id) AND {not_name}) DESC,+ e.created_atLIMIT 1",- )+ named = crate::names::has_name_in("e", 1, 2),+ not_name = crate::names::not_a_name("f"),+ )).bind(kb_id).bind(&keys).fetch_optional(pool)@@ -1232,17 +1256,18 @@ async fn review_side(pool: &PgPool, kb_id: Uuid, entity_id: Uuid) -> AppResult<Rdisambiguator: Option<String>,degree: i64,}- let row: SideRow = sqlx::query_as(+ let row: SideRow = sqlx::query_as(&format!("SELECT e.id, e.canonical_name AS name, t.label AS type_label,coalesce(t.color, '#94a3b8') AS color, e.disambiguator,(SELECT count(*) FROM facts fWHERE (f.subject_id = e.id OR f.object_id = e.id)- AND f.invalidated_at IS NULL) AS degree+ AND f.invalidated_at IS NULL AND {not_name}) AS degree-- LEFT JOIN:没判出类型的实体照样要能进审核(0009)。-- 内连接会让它整条审核项取不出来,而漂移审核恰恰最常发生在它们身上FROM entities e LEFT JOIN entity_types t ON t.id = e.type_idWHERE e.kb_id = $1 AND e.id = $2",- )+ not_name = crate::names::not_a_name("f"),+ )).bind(kb_id).bind(entity_id).fetch_optional(pool)@@ -1275,7 +1300,9 @@ pub async fn entity_fact_lines(valid_from: Option<DateTime<Utc>>,valid_to: Option<DateTime<Utc>>,}- let rows: Vec<Line> = sqlx::query_as(+ // 名字不算审阅卡上的一条事实(0041):两个同名实体各有一条「known as 张伟」,+ // 摆出来像是一条共同证据,其实它什么也分不出来+ let rows: Vec<Line> = sqlx::query_as(&format!("SELECT CASE WHEN f.subject_id = $2 THEN 'out' ELSE 'in' END AS direction,COALESCE(r.label, fact_surface_predicate(f.id)) AS predicate_label,o.canonical_name AS other_name,@@ -1287,18 +1314,27 @@ pub async fn entity_fact_lines(WHERE f.kb_id = $1 AND f.invalidated_at IS NULLAND (f.subject_id = $2 OR f.object_id = $2)AND COALESCE(r.label, fact_surface_predicate(f.id)) IS NOT NULL+ AND {not_name}ORDER BY f.confidence DESC, f.recorded_at DESCLIMIT $3",- )+ not_name = crate::names::not_a_name("f"),+ )).bind(kb_id).bind(entity_id).bind(limit).fetch_all(pool).await?;- Ok(rows+ // 本名以外的名字单独打头一行(0041):「海洋探测器1号」对「海探1」,裁决器要看得见+ // 前者也叫海探1,否则两边的事实各说各的,它只会判「不是同一个」。本名不列——+ // 两个张伟各有一条「known as 张伟」,摆出来像共同证据,其实什么也分不出+ let also_known_as = crate::names::other_names(pool, entity_id).await?;+ let head =+ (!also_known_as.is_empty()).then(|| format!("also known as: {}", also_known_as.join(", ")));++ Ok(head.into_iter()- .map(|l| {+ .chain(rows.into_iter().map(|l| {let other = l.other_name.unwrap_or_else(|| "?".into());let core = if l.direction == "out" {format!("{} → {}", l.predicate_label, other)@@ -1312,7 +1348,7 @@ pub async fn entity_fact_lines((Some(f), None) => format!("{core} ({} → now)", f.format("%Y-%m")),_ => core,}- })+ })).collect())}@@ -1636,7 +1672,6 @@ struct EntityFull {// None = 还没判出来(0009)type_id: Option<Uuid>,canonical_name: String,- aliases: Vec<String>,profile_embedding: Option<Vector>,profile_n: i32,merged_into: Option<Uuid>,@@ -1644,7 +1679,7 @@ struct EntityFull {async fn entity_full(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<EntityFull> {sqlx::query_as(- "SELECT type_id, canonical_name, aliases, profile_embedding, profile_n, merged_into+ "SELECT type_id, canonical_name, profile_embedding, profile_n, merged_intoFROM entities WHERE kb_id = $1 AND id = $2",).bind(kb_id)@@ -1655,7 +1690,10 @@ async fn entity_full(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<EntityFu}/// 合并 source → target:事实改挂 target、互指事实与合并后的重复事实作废、-/// source 名并入 target 别名、画像加权合并、source 标记 merged_into。全程记日志可回滚。+/// 画像加权合并、source 标记 merged_into。全程记日志可回滚。+///+/// **名字不用特判**(0041):source 的名字是它身上的 `known_as` 事实,跟别的事实一起+/// 搬到 target、记进 `moved_subject_facts`;同名的那条按重复事实作废。撤回合并时一起搬回去pub async fn merge_entities(pool: &PgPool,kb_id: Uuid,@@ -1741,19 +1779,6 @@ pub async fn merge_entities(invalidated.extend(dup_ids);}- // source 名与别名并入 target 别名(去重、排除 target 本名)- let mut aliases = target.aliases.clone();- let taken: std::collections::HashSet<String> = std::iter::once(&target.canonical_name)- .chain(aliases.iter())- .map(|s| s.to_lowercase())- .collect();- for a in std::iter::once(&source.canonical_name).chain(source.aliases.iter()) {- if !taken.contains(&a.to_lowercase()) && !aliases.iter().any(|x| x.eq_ignore_ascii_case(a))- {- aliases.push(a.clone());- }- }-// 画像加权合并let (profile, profile_n) = match (&target.profile_embedding, &source.profile_embedding) {(Some(t), Some(s)) if t.as_slice().len() == s.as_slice().len() => {@@ -1785,11 +1810,10 @@ pub async fn merge_entities(let new_type_id = target.type_id.or(source.type_id);sqlx::query(- "UPDATE entities SET aliases = $2, profile_embedding = $3, profile_n = $4,- type_id = $5, updated_at = now() WHERE id = $1",+ "UPDATE entities SET profile_embedding = $2, profile_n = $3,+ type_id = $4, updated_at = now() WHERE id = $1",).bind(target_id)- .bind(&aliases).bind(&profile).bind(profile_n).bind(new_type_id)@@ -1990,22 +2014,14 @@ pub async fn revert_merge(pool: &PgPool, kb_id: Uuid, merge_id: Uuid) -> AppResu.await?;let source = entity_full(pool, kb_id, m.source_id).await?;- // target 别名回退:剔除来自 source 的名字+ // source 的名字是它的名字事实,已经跟着 moved_subject_facts 搬回去了sqlx::query("UPDATE entities SET- aliases = (SELECT coalesce(array_agg(a), '{}') FROM unnest(aliases) a- WHERE lower(a) <> ALL($2)),- profile_embedding = $3, profile_n = $4,- type_id = coalesce($5, type_id), updated_at = now()+ profile_embedding = $2, profile_n = $3,+ type_id = coalesce($4, type_id), updated_at = now()WHERE id = $1",).bind(m.target_id)- .bind(- std::iter::once(&source.canonical_name)- .chain(source.aliases.iter())- .map(|s| s.to_lowercase())- .collect::<Vec<_>>(),- ).bind(&m.target_profile_before).bind(m.target_profile_n_before).bind(m.target_type_before)@@ -2422,7 +2438,9 @@ mod tests {pub struct TypeCandidateSubject {pub id: Uuid,pub canonical_name: String,- pub aliases: Vec<String>,+ /// 本名以外的名字(名字事实,0041)。给模型看:「海探1」一个人判不出是什么,+ /// 连着「海洋探测器1号」就判得出+ pub other_names: Vec<String>,/// 现在挂着的类,**可能没有**(0009:没判出来就是 NULL)。名字里的"粗"/// 是历史——抽取现在也可能直接给一个细类,而且可能给错(实测/// `绍兴 → address`),所以这里也可能是要被**纠正**的那个@@ -2466,7 +2484,13 @@ pub async fn entities_for_type_resolution(unattended: bool,) -> AppResult<Vec<TypeCandidateSubject>> {Ok(sqlx::query_as(- "SELECT e.id, e.canonical_name, e.aliases, t.key AS coarse_key, t.id AS coarse_id,+ "SELECT e.id, e.canonical_name,+ ARRAY(SELECT DISTINCT nf.object_value->>'value' FROM facts nf+ JOIN relation_types nr ON nr.id = nf.predicate_id+ WHERE nf.subject_id = e.id AND nr.builtin AND nr.key = 'known_as'+ AND nf.invalidated_at IS NULL+ AND lower(nf.object_value->>'value') <> lower(e.canonical_name)) AS other_names,+ t.key AS coarse_key, t.id AS coarse_id,t.description AS coarse_description,e.proposed_type, e.specific_type,-- 对方写**名字**,不写它的类型 key。@@ -2486,19 +2510,25 @@ pub async fn entities_for_type_resolution(WHERE f.kb_id = $1 AND f.invalidated_at IS NULLAND (f.subject_id = e.id OR f.object_id = e.id)AND COALESCE(rt.key, fact_surface_predicate(f.id)) IS NOT NULL+ -- 名字不是它扮演的角色,每个实体都有,判不出类型(0041)+ AND NOT coalesce(rt.builtin AND rt.key = 'known_as', false)LIMIT 12) AS roles,ARRAY(SELECT DISTINCT ev.quote FROM fact_evidence evJOIN facts f2 ON f2.id = ev.fact_id+ LEFT JOIN relation_types rt2 ON rt2.id = f2.predicate_idWHERE f2.kb_id = $1 AND f2.invalidated_at IS NULLAND f2.subject_id = e.idAND ev.quote IS NOT NULL+ AND NOT coalesce(rt2.builtin AND rt2.key = 'known_as', false)LIMIT 3) AS quotes,(SELECT count(*) FROM facts f3+ LEFT JOIN relation_types rt3 ON rt3.id = f3.predicate_idWHERE f3.kb_id = $1 AND f3.invalidated_at IS NULL- AND (f3.subject_id = e.id OR f3.object_id = e.id)) AS fact_count+ AND (f3.subject_id = e.id OR f3.object_id = e.id)+ AND NOT coalesce(rt3.builtin AND rt3.key = 'known_as', false)) AS fact_countFROM entities eLEFT JOIN entity_types t ON t.id = e.type_idWHERE e.kb_id = $1 AND e.merged_into IS NULLdiff --git a/crates/utopia-store/src/temporal.rs b/crates/utopia-store/src/temporal.rsindex 05ee9087..a3e6f94f 100644--- a/crates/utopia-store/src/temporal.rs+++ b/crates/utopia-store/src/temporal.rs@@ -718,6 +718,8 @@ pub async fn uniqueness_candidates(WHERE f.kb_id = $1 AND f.invalidated_at IS NULLAND f.valid_to IS NULL AND f.valid_to_precision IS NULLAND r.temporal = 'state'+ -- 名字不算:一个实体有两个名字是常态,不是「这个属性该唯一」的证据(0041)+ AND NOT (r.builtin AND r.key = 'known_as')AND (f.object_id IS NOT NULL OR f.object_value IS NOT NULL)),crowded AS (diff --git a/crates/utopia-store/tests/a_definition_can_be_written_by_hand.rs b/crates/utopia-store/tests/a_definition_can_be_written_by_hand.rsindex 254ddbdb..bcc686eb 100644--- a/crates/utopia-store/tests/a_definition_can_be_written_by_hand.rs+++ b/crates/utopia-store/tests/a_definition_can_be_written_by_hand.rs@@ -33,13 +33,11 @@ async fn fixture(pool: &PgPool) -> anyhow::Result<(Uuid, Uuid, Uuid)> {.bind(ws).execute(pool).await?;- sqlx::query(- "INSERT INTO entities (id, kb_id, canonical_name, aliases) VALUES ($1, $2, 'GMV', '{}')",- )- .bind(ent)- .bind(kb)- .execute(pool)- .await?;+ sqlx::query("INSERT INTO entities (id, kb_id, canonical_name) VALUES ($1, $2, 'GMV')")+ .bind(ent)+ .bind(kb)+ .execute(pool)+ .await?;sqlx::query("INSERT INTO users (id, org_id, email, display_name, password_hash)VALUES ($1, $2, $1 || '@w.test', 'w', 'x')",@@ -81,14 +79,25 @@ async fn a_written_definition_is_confirmed_and_signed() -> anyhow::Result<()> {assert_eq!(confirmed[0].id, id);assert_eq!(confirmed[0].written_by, Some(user), "人写的记谁写的");assert!(- utopia_store::mappings::proposed(&pool, kb, 100, 0).await?.is_empty(),+ utopia_store::mappings::proposed(&pool, kb, 100, 0)+ .await?+ .is_empty(),"不该出现在待审队列里");// 同一个 (概念, 源) 再写一条:冲突,而不是悄悄盖掉已有的那条let again = utopia_store::mappings::create(- &pool, kb, ent, "warehouse", Some("dw.dwd_ord_dtl"), Some("sum(amt_total)"),- None, None, None, false, user,+ &pool,+ kb,+ ent,+ "warehouse",+ Some("dw.dwd_ord_dtl"),+ Some("sum(amt_total)"),+ None,+ None,+ None,+ false,+ user,).await;assert!(@@ -98,8 +107,16 @@ async fn a_written_definition_is_confirmed_and_signed() -> anyhow::Result<()> {// 探索盖不掉人写的:propose 同键 → 行原样不动、仍是 confirmedutopia_store::mappings::propose(- &pool, kb, ent, "warehouse", Some("orders_v2"), Some("sum(amt_total)"),- None, None, None, false,+ &pool,+ kb,+ ent,+ "warehouse",+ Some("orders_v2"),+ Some("sum(amt_total)"),+ None,+ None,+ None,+ false,).await?;let confirmed = utopia_store::mappings::confirmed(&pool, kb, 100).await?;@@ -108,14 +125,22 @@ async fn a_written_definition_is_confirmed_and_signed() -> anyhow::Result<()> {assert_eq!(confirmed[0].written_by, Some(user));// 探索自己提的那些 written_by 为空——页面靠这个分「人写」与「探索提的」let ent2 = Uuid::now_v7();- sqlx::query("INSERT INTO entities (id, kb_id, canonical_name, aliases) VALUES ($1, $2, 'Orders', '{}')")+ sqlx::query("INSERT INTO entities (id, kb_id, canonical_name) VALUES ($1, $2, 'Orders')").bind(ent2).bind(kb).execute(&pool).await?;utopia_store::mappings::propose(- &pool, kb, ent2, "warehouse", Some("dw.dwd_ord_dtl"), Some("count(distinct ord_id)"),- None, None, None, false,+ &pool,+ kb,+ ent2,+ "warehouse",+ Some("dw.dwd_ord_dtl"),+ Some("count(distinct ord_id)"),+ None,+ None,+ None,+ false,).await?;let proposed = utopia_store::mappings::proposed(&pool, kb, 100, 0).await?;diff --git a/crates/utopia-store/tests/a_mapping_is_not_a_fact.rs b/crates/utopia-store/tests/a_mapping_is_not_a_fact.rsindex 741ebbe4..7f65fde4 100644--- a/crates/utopia-store/tests/a_mapping_is_not_a_fact.rs+++ b/crates/utopia-store/tests/a_mapping_is_not_a_fact.rs@@ -33,13 +33,11 @@ async fn fixture(pool: &PgPool) -> anyhow::Result<(Uuid, Uuid, Uuid)> {.bind(ws).execute(pool).await?;- sqlx::query(- "INSERT INTO entities (id, kb_id, canonical_name, aliases) VALUES ($1, $2, '营收', '{}')",- )- .bind(ent)- .bind(kb)- .execute(pool)- .await?;+ sqlx::query("INSERT INTO entities (id, kb_id, canonical_name) VALUES ($1, $2, '营收')")+ .bind(ent)+ .bind(kb)+ .execute(pool)+ .await?;Ok((org, kb, ent))}diff --git a/crates/utopia-store/tests/a_name_is_a_fact.rs b/crates/utopia-store/tests/a_name_is_a_fact.rsnew file mode 100644index 00000000..bd6d86d0--- /dev/null+++ b/crates/utopia-store/tests/a_name_is_a_fact.rs@@ -0,0 +1,438 @@+//! 名字是关于实体的一条事实(0041 决定 1)。+//!+//! 建实体时本名就是一条名字事实;记下的别名让后来的提及找得到它;名字不进事实列表、+//! 不算度数;合并把名字当普通事实搬走,撤回合并再搬回来。++use sqlx::PgPool;+use utopia_store::{graph, names, resolution};+use uuid::Uuid;++struct Fixture {+ org: Uuid,+ kb: Uuid,+ equipment: Uuid,+}++async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {+ let (org, ws, kb, equipment) = (+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ );+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'names-test')")+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'names-test')")+ .bind(ws)+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'names-test')",+ )+ .bind(kb)+ .bind(ws)+ .execute(pool)+ .await?;+ sqlx::query("INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'equipment', 'Equipment')")+ .bind(equipment)+ .bind(kb)+ .execute(pool)+ .await?;+ Ok(Fixture { org, kb, equipment })+}++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(())+}++async fn mention(pool: &PgPool, f: &Fixture, name: &str) -> anyhow::Result<resolution::Resolution> {+ // 不给向量:召回到候选就走「并到事实最多的那个」,量的正是召回找不找得到+ Ok(resolution::resolve_mention(pool, f.kb, Some(f.equipment), name, None, None, &[]).await?)+}++fn values(v: &[utopia_core::models::NameView]) -> Vec<String> {+ let mut out: Vec<String> = v.iter().map(|n| n.name.clone()).collect();+ out.sort();+ out+}++#[tokio::test]+async fn a_new_entity_carries_its_name_and_an_alias_brings_a_later_mention_home(+) -> 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 probe = mention(&pool, &f, "海洋探测器1号").await?;+ assert!(probe.created);+ let n = names::for_entity(&pool, f.kb, probe.entity_id, None).await?;+ assert_eq!(values(&n), vec!["海洋探测器1号"], "本名是一条名字事实");+ assert!(n[0].canonical);++ // 没有桥的简称:另起一个实体(这正是 0041 要修的,这一刀靠记下名字修)+ let before = mention(&pool, &f, "海探2").await?;+ assert!(before.created && before.entity_id != probe.entity_id);++ names::record(&pool, f.kb, probe.entity_id, "海探1", None, None).await?;+ let later = mention(&pool, &f, "海探1").await?;+ assert!(!later.created, "记下的别名让后来的提及找得到它");+ assert_eq!(later.entity_id, probe.entity_id);+ assert_eq!(+ resolution::existing_by_name(&pool, f.kb, "海探1").await?,+ Some(probe.entity_id)+ );++ // 同一个名字再记一次只有一行+ names::record(&pool, f.kb, probe.entity_id, " 海探1 ", None, None).await?;+ let n = names::for_entity(&pool, f.kb, probe.entity_id, None).await?;+ assert_eq!(values(&n), vec!["海探1", "海洋探测器1号"]);+ assert_eq!(+ names::record(&pool, f.kb, probe.entity_id, " ", None, None).await?,+ None+ );+ anyhow::Ok(())+ }+ .await;+ teardown(&pool, &f).await?;+ run+}++#[tokio::test]+async fn a_name_is_neither_a_listed_fact_nor_a_degree() -> 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 probe = mention(&pool, &f, "海洋探测器1号").await?;+ names::record(&pool, f.kb, probe.entity_id, "海探1", None, None).await?;+ let (node, facts) = graph::entity_detail(&pool, f.kb, probe.entity_id, None, None).await?;+ assert!(facts.is_empty(), "名字不进事实列表:{facts:?}");+ assert_eq!(node.degree, 0, "名字不算度数");+ anyhow::Ok(())+ }+ .await;+ teardown(&pool, &f).await?;+ run+}++#[tokio::test]+async fn merging_moves_names_and_reverting_brings_them_back() -> 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 full = mention(&pool, &f, "海洋探测器1号").await?.entity_id;+ let short = mention(&pool, &f, "海探1").await?.entity_id;+ assert_ne!(full, short);++ let merge = resolution::merge_entities(&pool, f.kb, short, full, None, "test").await?;+ assert_eq!(+ values(&names::for_entity(&pool, f.kb, full, None).await?),+ vec!["海探1", "海洋探测器1号"],+ "被并方的名字随它的事实搬过来"+ );+ assert_eq!(+ resolution::existing_by_name(&pool, f.kb, "海探1").await?,+ Some(full),+ "合并之后按简称找到的是存活者"+ );++ resolution::revert_merge(&pool, f.kb, merge).await?;+ assert_eq!(+ values(&names::for_entity(&pool, f.kb, short, None).await?),+ vec!["海探1"]+ );+ assert_eq!(+ values(&names::for_entity(&pool, f.kb, full, None).await?),+ vec!["海洋探测器1号"],+ "撤回合并,名字搬回去"+ );+ anyhow::Ok(())+ }+ .await;+ teardown(&pool, &f).await?;+ run+}++#[tokio::test]+async fn a_name_another_entity_already_has_queues_the_pair_without_merging() -> 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 {+ // 倒序到达:只写简称的那篇先建出「海探1」,写着全称的那篇后到+ let short = mention(&pool, &f, "海探1").await?.entity_id;+ let full = mention(&pool, &f, "海洋探测器1号").await?.entity_id;+ names::record(&pool, f.kb, full, "海探1", None, None).await?;+ assert_eq!(+ names::pair_shared_name(&pool, f.kb, full, "海探1").await?,+ 1+ );+ let (reason, stage, status): (String, String, String) = sqlx::query_as(+ "SELECT reason, stage, status FROM resolution_reviews+ WHERE kb_id = $1 AND least(left_id, right_id) = least($2, $3)+ AND greatest(left_id, right_id) = greatest($2, $3)",+ )+ .bind(f.kb)+ .bind(short)+ .bind(full)+ .fetch_one(&pool)+ .await?;+ assert_eq!(reason, "shared_name|海探1");+ assert_eq!(+ (stage.as_str(), status.as_str()),+ ("adjudicating", "pending")+ );+ let merged: Option<Uuid> =+ sqlx::query_scalar("SELECT merged_into FROM entities WHERE id = $1")+ .bind(short)+ .fetch_one(&pool)+ .await?;+ assert_eq!(merged, None, "只排队,不合并");+ // 再报一次同一个名字不重复排+ assert_eq!(+ names::pair_shared_name(&pool, f.kb, full, "海探1").await?,+ 1+ );+ let n: i64 = sqlx::query_scalar("SELECT count(*) FROM resolution_reviews WHERE kb_id = $1")+ .bind(f.kb)+ .fetch_one(&pool)+ .await?;+ assert_eq!(n, 1);+ anyhow::Ok(())+ }+ .await;+ teardown(&pool, &f).await?;+ run+}++#[tokio::test]+async fn the_adjudicator_sees_the_other_names_and_never_the_shared_one() -> 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 full = mention(&pool, &f, "海洋探测器1号").await?.entity_id;+ names::record(&pool, f.kb, full, "海探1", None, None).await?;+ let lines = resolution::entity_fact_lines(&pool, f.kb, full, 4).await?;+ assert_eq!(lines, vec!["also known as: 海探1".to_string()]);+ let bare = mention(&pool, &f, "海探2").await?.entity_id;+ assert!(+ resolution::entity_fact_lines(&pool, f.kb, bare, 4)+ .await?+ .is_empty(),+ "只有本名的实体没有「又名」这一行"+ );+ anyhow::Ok(())+ }+ .await;+ teardown(&pool, &f).await?;+ run+}++/// 分开过的一对,同一个简称再被读到也不再排队:分开这个决定要记得住+#[tokio::test]+async fn a_pair_kept_apart_is_not_queued_again() -> 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 {+ mention(&pool, &f, "海探1").await?;+ let full = mention(&pool, &f, "海洋探测器1号").await?.entity_id;+ names::record(&pool, f.kb, full, "海探1", None, None).await?;+ assert_eq!(+ names::pair_shared_name(&pool, f.kb, full, "海探1").await?,+ 1+ );+ sqlx::query(+ "UPDATE resolution_reviews SET status = 'kept', decided_at = now() WHERE kb_id = $1",+ )+ .bind(f.kb)+ .execute(&pool)+ .await?;+ assert_eq!(+ names::pair_shared_name(&pool, f.kb, full, "海探1").await?,+ 0,+ "判过不是一个的,不再配"+ );+ let pending: i64 = sqlx::query_scalar(+ "SELECT count(*) FROM resolution_reviews WHERE kb_id = $1 AND status = 'pending'",+ )+ .bind(f.kb)+ .fetch_one(&pool)+ .await?;+ assert_eq!(pending, 0);+ anyhow::Ok(())+ }+ .await;+ teardown(&pool, &f).await?;+ run+}++/// 名字属性不是一条普通属性:按 key 找不到,改不了,也不进本体向量索引。+/// 否则本体提议能把「简称」一类的值归并到它上面、唯一性面板能把它标成 functional,+/// 名字的核对与配对就都绕过去了+#[tokio::test]+async fn the_name_attribute_is_not_an_ordinary_attribute() -> 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 known_as = names::ensure_known_as(&pool, f.kb).await?;+ assert_eq!(+ utopia_store::ontology::relation_type_id_by_key(&pool, f.kb, names::KNOWN_AS).await?,+ None+ );+ let edited = utopia_store::ontology::update_relation_type(+ &pool,+ f.kb,+ known_as,+ "known as",+ "state",+ utopia_core::models::RelationAxioms {+ functional: true,+ ..Default::default()+ },+ "",+ None,+ None,+ None,+ None,+ )+ .await;+ assert!(edited.is_err(), "内建的名字属性不能改成 functional");+ let functional: bool =+ sqlx::query_scalar("SELECT functional FROM relation_types WHERE id = $1")+ .bind(known_as)+ .fetch_one(&pool)+ .await?;+ assert!(!functional);+ let stale = utopia_store::ontology::types_needing_embedding(+ &pool,+ f.kb,+ "test-model",+ Some(utopia_store::ontology::TypeKind::Relation),+ )+ .await?;+ assert!(stale.iter().all(|t| t.id != known_as), "名字属性不嵌");+ anyhow::Ok(())+ }+ .await;+ teardown(&pool, &f).await?;+ run+}++/// 一段只写了名字的引文不是原文:给治理 agent 的片段里没有它,带整句的别名照样有。+/// 删掉文档,实体的本名还在,只凭这篇文档读到的别名跟着作废+#[tokio::test]+async fn a_bare_name_is_not_a_quote_and_a_deleted_document_keeps_the_name() -> 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 full = mention(&pool, &f, "海洋探测器1号").await?.entity_id;+ let (doc, chunk) = (Uuid::now_v7(), Uuid::now_v7());+ sqlx::query("INSERT INTO documents (id, kb_id, filename, sha256) VALUES ($1, $2, 'probe.txt', $3)")+ .bind(doc)+ .bind(f.kb)+ .bind(doc.to_string())+ .execute(&pool)+ .await?;+ sqlx::query(+ "INSERT INTO chunks (id, kb_id, document_id, seq, text)+ VALUES ($1, $2, $3, 0, '海洋探测器1号(简称海探1)于2026年下水。')",+ )+ .bind(chunk)+ .bind(f.kb)+ .bind(doc)+ .execute(&pool)+ .await?;+ let source = |quote| {+ Some(names::NameSource {+ chunk_id: chunk,+ quote,+ })+ };+ let canonical = names::record(&pool, f.kb, full, "海洋探测器1号", source("海洋探测器1号"), None)+ .await?+ .expect("canonical name fact");+ let alias = names::record(&pool, f.kb, full, "海探1", source("简称海探1"), None)+ .await?+ .expect("alias fact");+ let launched: Uuid = sqlx::query_scalar(+ "INSERT INTO relation_types (id, kb_id, key, label, kind, datatype, temporal)+ VALUES ($1, $2, 'launch_year', 'launch year', 'attribute', 'text', 'event') RETURNING id",+ )+ .bind(Uuid::now_v7())+ .bind(f.kb)+ .fetch_one(&pool)+ .await?;+ let (fact, _) = graph::insert_value_fact(+ &pool,+ f.kb,+ full,+ Some(launched),+ &serde_json::json!({ "value": "2026" }),+ graph::Validity::default(),+ 0.9,+ )+ .await?;+ graph::add_evidence(&pool, fact, chunk, Some("于2026年下水"), Some("launch_year")).await?;++ let quotes: Vec<String> = utopia_store::governance::quotes_of(&pool, f.kb, full, 10)+ .await?+ .into_iter()+ .map(|(_, q)| q)+ .collect();+ assert!(quotes.iter().all(|q| q != "海洋探测器1号"), "{quotes:?}");+ assert_eq!(quotes.len(), 1, "一块一段:{quotes:?}");+ assert_eq!(quotes[0], "于2026年下水", "同一块里真正的句子优先");++ utopia_store::documents::delete(&pool, f.kb, doc, None).await?;+ let invalidated = |id: Uuid| {+ let pool = pool.clone();+ async move {+ sqlx::query_scalar::<_, bool>(+ "SELECT invalidated_at IS NOT NULL FROM facts WHERE id = $1",+ )+ .bind(id)+ .fetch_one(&pool)+ .await+ }+ };+ assert!(!invalidated(canonical).await?, "本名不随文档走");+ assert!(invalidated(alias).await?, "只凭这篇读到的别名作废");+ assert!(invalidated(fact).await?);+ anyhow::Ok(())+ }+ .await;+ teardown(&pool, &f).await?;+ run+}diff --git a/crates/utopia-store/tests/a_question_picks_its_definitions.rs b/crates/utopia-store/tests/a_question_picks_its_definitions.rsindex 198fbe71..bc13ba71 100644--- a/crates/utopia-store/tests/a_question_picks_its_definitions.rs+++ b/crates/utopia-store/tests/a_question_picks_its_definitions.rs@@ -32,14 +32,12 @@ async fn base(pool: &PgPool) -> anyhow::Result<Uuid> {async fn definition(pool: &PgPool, kb: Uuid, name: &str, summary: &str) -> anyhow::Result<Uuid> {let ent = Uuid::now_v7();- sqlx::query(- "INSERT INTO entities (id, kb_id, canonical_name, aliases) VALUES ($1, $2, $3, '{}')",- )- .bind(ent)- .bind(kb)- .bind(name)- .execute(pool)- .await?;+ sqlx::query("INSERT INTO entities (id, kb_id, canonical_name) VALUES ($1, $2, $3)")+ .bind(ent)+ .bind(kb)+ .bind(name)+ .execute(pool)+ .await?;let (id, _) = m::propose(pool,kb,diff --git a/crates/utopia-store/tests/an_undeclared_name_is_looked_up.rs b/crates/utopia-store/tests/an_undeclared_name_is_looked_up.rsindex 21d0f864..d58949ca 100644--- a/crates/utopia-store/tests/an_undeclared_name_is_looked_up.rs+++ b/crates/utopia-store/tests/an_undeclared_name_is_looked_up.rs@@ -35,16 +35,19 @@ async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {.bind(kb).execute(pool).await?;- // 有类型的、带别名的一个;并掉的一个(同名,不该被找到)+ // 有类型的、带别名的一个;并掉的一个(同名,不该被找到)。+ // 别名是一条名字事实(0041),不再是 entities 上的一列sqlx::query(- "INSERT INTO entities (id, kb_id, type_id, canonical_name, aliases)- VALUES ($1, $2, $3, 'Acme Corporation', ARRAY['ACME'])",+ "INSERT INTO entities (id, kb_id, type_id, canonical_name)+ VALUES ($1, $2, $3, 'Acme Corporation')",).bind(acme).bind(kb).bind(organization).execute(pool).await?;+ utopia_store::names::record(pool, kb, acme, "Acme Corporation", None, None).await?;+ utopia_store::names::record(pool, kb, acme, "ACME", None, None).await?;sqlx::query("INSERT INTO entities (id, kb_id, canonical_name, merged_into) VALUES ($1, $2, 'Nova Labs', $3)",)diff --git a/docs/decisions/0041-a-name-is-a-claim-about-an-entity.md b/docs/decisions/0041-a-name-is-a-claim-about-an-entity.mdindex 23b7ee6e..b685c9ce 100644--- a/docs/decisions/0041-a-name-is-a-claim-about-an-entity.md+++ b/docs/decisions/0041-a-name-is-a-claim-about-an-entity.md@@ -1,6 +1,6 @@# 0041 · A name is a claim about an entity-- **Status**: decision 1 settled 2026-09-13 (names are facts) · cut 0 built: `scripts/bench/identity.mjs`, baseline on `dev` forward F1 0.43, reverse 0.54 · cut 1 implemented (#670): migration 0055 and `names` in the store, the extractor's `names`, shared-name pairs to the adjudicator; forward 0.68, reverse 0.68, the two orders agree on all 210 pairs (one run each; two cut-1 runs differed by 0.07 forward) · decisions 2 and 5 revised by cut 1 · cuts 2–4 not started+- **Status**: decision 1 settled 2026-09-13 (names are facts) · cut 0 built: `scripts/bench/identity.mjs`, baseline on `dev` forward F1 0.43, reverse 0.54 · cut 1 implemented (#670): migration 0055 and `names` in the store, the extractor's `names`, shared-name pairs to the adjudicator; forward 0.68, reverse 0.68, the two orders agree on all 210 pairs (one run each; two cut-1 runs differed by 0.07 forward) · re-measured on DeepSeek-V3 after the review fixes: dev 0.46 / 0.40 (2 of 21 anchors unresolved), cut 1 0.61 / 0.44–0.53 over three runs; on V3 the adjudicator keeps 海洋探测器1号 and 海探1 apart in reverse order even with the shared name listed, which is cut 3's question · decisions 2 and 5 revised by cut 1 · cuts 2–4 not started- **Written**: 2026-09-13 (conventions in the [README](README.md))- **Related**: [0009](0009-no-type-is-a-type.md) made an undecided type an honest state, and [0016](0016-close-the-open-seams-before-cutting-new-ones.md) B3 let a declared `disjointWith` keep names apart; #270 stopped a namesake tie from being settled by candidate order and #331 let facts break it; #428 and [0025](0025-governance-reads-the-ledger-before-it-decides.md) moved duplicates through a queue an agent works; #582 and #583 made the extractor copy the words that name each side of a fact; [0037](0037-a-relation-carries-its-own-attributes.md) put attributes on edges.diff --git a/migrations/0055_a_name_is_a_fact.sql b/migrations/0055_a_name_is_a_fact.sqlnew file mode 100644index 00000000..5e32eb91--- /dev/null+++ b/migrations/0055_a_name_is_a_fact.sql@@ -0,0 +1,123 @@+-- 名字是关于实体的一条事实(0041 决定 1)。+--+-- 从前一个实体的名字分两处放:`entities.canonical_name` 一个,`entities.aliases` 一串。+-- 别名只有合并会写,没有出处、没有时间、撤不回单个,抽取读到的「简称海探1」进不来。+-- 现在每个名字都是 `known_as` 这条内建属性上的一条值事实:`object_value = {"value": 名字}`,+-- `object_id` 为空——**不成节点**,画布只画带 object_id 的边,和数量值走同一个通道(#586)。+-- 时态引擎只对声明了 functional / inverse_functional 的状态关系收口、记冲突,`known_as`+-- 两者都不是(重名本来就有),第二个名字不会关掉第一个。+--+-- `canonical_name` 留着,是界面上显示的那一个,同时它也是一条名字事实。+--+-- **已经合并掉的实体要小心。** 它的名字现在躺在存活者的 `aliases` 里,合并日志+-- `entity_merges` 靠 `moved_subject_facts` 记「搬过哪些事实」、撤回时按它搬回去。+-- 名字变成事实之后,新的合并会把名字事实当普通事实搬、撤回时搬回来,不用任何特判。+-- 迁移时已经在合并状态的那些,要补成「当初就是这么搬的」:+-- 它的名字事实挂到合并链末端的存活者身上,并把这条事实的 id 追加进链上每一条+-- 未撤回合并的 `moved_subject_facts`——撤回链上任何一环,名字都跟着那一环回去;+-- 存活者已经有同一个名字(重名合并最常见:「Apple」并进「Apple」),就把它作废,+-- 并同样追加进链上每一条的 `invalidated_facts`——合并本来就会这样去重,撤回时一并复活。++-- 0. 用户自己建过一条 key 叫 known_as 的关系:让出 key,它的事实原样留着(只是 key 变了,+-- 标签不动)。不让的话下面第 1 步什么也不插,名字全写到那条非内建的关系上,+-- 而所有读名字的地方只认内建的那条+UPDATE relation_types SET key = 'known_as_' || left(id::text, 8)+ WHERE key = 'known_as' AND NOT builtin;++-- 1. 每个库一条内建属性。按需也会建(`names::ensure_known_as`),这里给存量库补上+INSERT INTO relation_types (id, kb_id, key, label, kind, datatype, temporal, builtin, description)+SELECT gen_random_uuid(), k.id, 'known_as', 'known as', 'attribute', 'text', 'state', TRUE,+ 'A name a text uses for this entity. Each name is a fact with its source and both clocks; a name is a value and never becomes a node.'+ FROM knowledge_bases k+ON CONFLICT (kb_id, key) DO NOTHING;++-- 2. 存活实体的本名+INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_value, recorded_at, attested_from, confidence)+SELECT gen_random_uuid(), e.kb_id, e.id, r.id, jsonb_build_object('value', e.canonical_name),+ e.created_at, e.created_at, 1.0+ FROM entities e+ JOIN relation_types r ON r.kb_id = e.kb_id AND r.key = 'known_as'+ WHERE e.merged_into IS NULL;++-- 3. 已合并实体:沿 merged_into 走到存活者,记下经过的每个节点。+--+-- **下面每一步都是一次扫描加连接,不是逐行子查询。** 临时表没有索引、每行一个相关+-- 子查询的写法,在 20 万实体、4.5 万合并的库上要八分钟以上(三段各两分钟到四分钟);+-- 迁移跑在一个事务里,那段时间整库写不进去+CREATE TEMP TABLE name_walk ON COMMIT DROP AS+WITH RECURSIVE walk(origin, node, depth) AS (+ SELECT e.id, e.id, 0 FROM entities e WHERE e.merged_into IS NOT NULL+ UNION ALL+ SELECT w.origin, e.merged_into, w.depth + 1+ FROM walk w JOIN entities e ON e.id = w.node+ WHERE e.merged_into IS NOT NULL AND w.depth < 64+)+SELECT origin, node, depth FROM walk;+CREATE INDEX ON name_walk (origin);+ANALYZE name_walk;++-- 链末端就是深度最大的那个节点+CREATE TEMP TABLE merged_names ON COMMIT DROP AS+SELECT gen_random_uuid() AS fact_id, x.id AS origin, x.kb_id, x.canonical_name, x.created_at,+ s.survivor+ FROM entities x+ JOIN (SELECT DISTINCT ON (origin) origin, node AS survivor+ FROM name_walk ORDER BY origin, depth DESC) s ON s.origin = x.id+ WHERE x.merged_into IS NOT NULL;+CREATE INDEX ON merged_names (origin);+ANALYZE merged_names;++INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_value, recorded_at, attested_from, confidence)+SELECT m.fact_id, m.kb_id, m.survivor, r.id, jsonb_build_object('value', m.canonical_name),+ m.created_at, m.created_at, 1.0+ FROM merged_names m+ JOIN relation_types r ON r.kb_id = m.kb_id AND r.key = 'known_as';++-- 链上经过节点 N 的每个名字,都记进 source 为 N 的那条未撤回合并+UPDATE entity_merges em+ SET moved_subject_facts = em.moved_subject_facts || moved.fact_ids+ FROM (SELECT w.node AS source_id, array_agg(m.fact_id ORDER BY m.fact_id) AS fact_ids+ FROM merged_names m JOIN name_walk w ON w.origin = m.origin+ GROUP BY w.node) moved+ WHERE em.source_id = moved.source_id AND em.reverted_at IS NULL;++-- 同一个存活者身上重复的名字:存活者自己的本名留着,合并来的里面留最早记下的,其余作废+CREATE TEMP TABLE merged_name_dups ON COMMIT DROP AS+SELECT fact_id, origin FROM (+ SELECT m.fact_id, m.origin,+ lower(s.canonical_name) = lower(m.canonical_name) AS same_as_survivor,+ row_number() OVER (PARTITION BY m.survivor, lower(m.canonical_name)+ ORDER BY m.created_at, m.fact_id) AS nth+ FROM merged_names m+ JOIN entities s ON s.id = m.survivor+) d+ WHERE same_as_survivor OR nth > 1;++UPDATE facts f SET invalidated_at = now()+ FROM merged_name_dups d+ WHERE f.id = d.fact_id;++UPDATE entity_merges em+ SET invalidated_facts = em.invalidated_facts || dup.fact_ids+ FROM (SELECT w.node AS source_id, array_agg(d.fact_id ORDER BY d.fact_id) AS fact_ids+ FROM merged_name_dups d JOIN name_walk w ON w.origin = d.origin+ GROUP BY w.node) dup+ WHERE em.source_id = dup.source_id AND em.reverted_at IS NULL;++-- 4. 存活者别名里剩下的(不对应任何已合并实体本名的,理论上不该有,有就照记)+INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_value, recorded_at, attested_from, confidence)+SELECT gen_random_uuid(), e.kb_id, e.id, r.id, jsonb_build_object('value', a.alias),+ e.updated_at, e.updated_at, 1.0+ FROM entities e+ JOIN relation_types r ON r.kb_id = e.kb_id AND r.key = 'known_as'+ CROSS JOIN LATERAL (SELECT DISTINCT ON (lower(x)) x AS alias FROM unnest(e.aliases) x) a+ WHERE e.merged_into IS NULL+ AND NOT EXISTS (SELECT 1 FROM facts f+ WHERE f.subject_id = e.id AND f.predicate_id = r.id+ AND lower(f.object_value->>'value') = lower(a.alias));++ALTER TABLE entities DROP COLUMN aliases;++-- 召回按名字等值查:值事实的小写值上建索引(数量值也在里面,不妨碍)+CREATE INDEX facts_value_text_idx ON facts (kb_id, lower(object_value->>'value'))+ WHERE invalidated_at IS NULL AND object_value IS NOT NULL;diff --git a/scripts/bench/ask.mjs b/scripts/bench/ask.mjsindex 70701de0..d5b83540 100644--- a/scripts/bench/ask.mjs+++ b/scripts/bench/ask.mjs@@ -154,8 +154,8 @@ function seedTruth(kb) {WITH found AS (SELECT id FROM entitiesWHERE kb_id = '${kb}' AND lower(canonical_name) = lower('${label}')AND merged_into IS NULL LIMIT 1),- made AS (INSERT INTO entities (id, kb_id, type_id, canonical_name, aliases)- SELECT gen_random_uuid(), '${kb}', '${typeId}', '${label}', '{}'+ made AS (INSERT INTO entities (id, kb_id, type_id, canonical_name)+ SELECT gen_random_uuid(), '${kb}', '${typeId}', '${label}'WHERE NOT EXISTS (SELECT 1 FROM found) RETURNING id)SELECT id FROM found UNION ALL SELECT id FROM made`);psql(`diff --git a/scripts/bench/govern.mjs b/scripts/bench/govern.mjsindex fade061e..c8ffdefc 100644--- a/scripts/bench/govern.mjs+++ b/scripts/bench/govern.mjs@@ -96,7 +96,7 @@ async function fresh() {// ---------- 撤掉 agent(与模拟的人)的决定 ----------function reset(kb) {psql(`DO $$-DECLARE m RECORD; src RECORD;+DECLARE m RECORD;BEGINFOR m IN SELECT * FROM entity_merges WHERE kb_id = '${kb}' AND reverted_at IS NULL ORDER BY created_at DESC LOOPUPDATE facts SET subject_id = m.source_id WHERE id = ANY(m.moved_subject_facts);@@ -105,10 +105,8 @@ BEGINUPDATE facts SET invalidated_at = NULL WHERE id IN (SELECT supersedes FROM facts WHERE id = ANY(m.temporal_corrections) AND invalidated_at IS NULL AND supersedes IS NOT NULL);UPDATE facts SET invalidated_at = now() WHERE id = ANY(m.temporal_corrections) AND invalidated_at IS NULL;- SELECT canonical_name, aliases INTO src FROM entities WHERE id = m.source_id;+ -- 名字是 known_as 上的事实(0041),跟着 moved_subject_facts 搬回去了,不用另外还UPDATE entities SET- aliases = (SELECT coalesce(array_agg(a), '{}') FROM unnest(aliases) a- WHERE lower(a) <> ALL (SELECT lower(x) FROM unnest(array_prepend(src.canonical_name, src.aliases)) x)),profile_embedding = m.target_profile_before, profile_n = m.target_profile_n_before,type_id = coalesce(m.target_type_before, type_id), updated_at = now()WHERE id = m.target_id;diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex 92f951a3..8b25a8a9 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -47,6 +47,7 @@ export const en = {"That class is already below this one — the hierarchy would loop.",bad_lang: "Pick a supported language.",attr_needs_class: "An attribute has to belong to a class.",+ builtin_name_attribute: "The name attribute is built in and cannot be edited.",attr_has_no_link:"An attribute has no inverse and no super-property — its value is a literal, not something to point back from.",link_target_is_attr:@@ -1754,6 +1755,7 @@ export const en = {namesake: "Two entities with this name in one document",/* 画像分不开时的并列:分数是真的,所以百分比照常显示(与 namesake 的哨兵值不同) */namesake_tie: "Same name, and the profiles cannot tell them apart",+ shared_name: "Another entity already has this name",/* 名字互相包含:等值召回看不见,简称会静默变成第二个实体 */contains: "One name contains the other",ambiguous_name: "Same name, context did not settle it",diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex 117a2ea1..5d595d7b 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -44,6 +44,7 @@ export const zh: Strings = {parent_cycle: "那个类已经在这个类下面了——层级会成环。",bad_lang: "选一个支持的语言。",attr_needs_class: "属性必须挂在某个类上。",+ builtin_name_attribute: "名字属性是内建的,不能修改。",attr_has_no_link:"属性没有逆,也没有父属性——它的宾语是字面值,谈不上反过来指回来。",link_target_is_attr: "要选一条关系,不是属性——属性的值是字面量。",@@ -1532,6 +1533,7 @@ export const zh: Strings = {governed: "agent 按先例裁的",namesake: "同一篇文档里有两个同名实体",namesake_tie: "同名,画像分不出谁是谁",+ shared_name: "另一个实体已经叫这个名字",contains: "一个名字包含另一个",ambiguous_name: "同名,但上下文没能定夺",type_drift: "同名,但类型不同",