World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Three leftovers that only tests called are removed: the document-dating prompt, the write-time direction judge, and adoption by proposed class name (#1132)
WaylandYang95338a7bf6bc
diff --git a/crates/utopia-extract/src/time.rs b/crates/utopia-extract/src/time.rsindex dd723960..fae9d3c9 100644--- a/crates/utopia-extract/src/time.rs+++ b/crates/utopia-extract/src/time.rs@@ -1,14 +1,13 @@//! 时间提法的解读(0045 决定 2、3、8):**模型读,代码算**。//!-//! 两次调用,都只返回结构化的字段,模型从不写一个算出来的日期:+//! 只返回结构化的字段,模型从不写一个算出来的日期://!-//! 1. **给文档定日期**([`build_dating_messages`] / [`parse_dating_response`]):读文件开头,-//! 抄下文档自己的日期(电头、申报日、公报的报告年份)、它命名的期间及其边界、财年-//! 的截止日。上传时间永远不进来——那是记录时间轴(决定 3)。-//! 2. **解读提法**([`build_interpretation_messages`] / [`parse_interpretation_response`]):-//! 每条提法给形状、引用、粒度。绝对值按原文的字抄成数字部件;相对的说锚点(另一条-//! 提法、文档本身、文档命名的期间)与偏移(数、单位、方向);期间报名字。日历算术、-//! 财年到区间、按粒度截断、形状蕴含的区间,全在服务端算。+//! **解读提法**([`build_interpretation_messages`] / [`parse_interpretation_response`]):+//! 每条提法给形状、引用、粒度。绝对值按原文的字抄成数字部件;相对的说锚点(另一条+//! 提法、文档本身、文档命名的期间)与偏移(数、单位、方向);期间报名字。日历算术、+//! 财年到区间、按粒度截断、形状蕴含的区间,全在服务端算。+//!+//! 文档自己的日期不再单独问一次模型:每块在抽取时报它那段文字写明的日期(0064)。//!//! 代码里**没有时间词**(决定 8):不认月份名、不认「去年」「上年末」,只解 JSON、验//! 部件范围、拼提示词。提示词是常量英文;例子是中性的(镇议会、桥、面包房),不出自@@ -329,48 +328,6 @@ pub struct TimeContext<'a> {pub fiscal_year_end: Option<(u32, u32)>,}-/// 定日期的系统消息。只抄开头说了的;文档自己的日期,从不是今天;部件是抄写的数字-const DATING_SYSTEM: &str = "\-You read the opening of a document and write down what it states about the document's own \-time: its date, the periods it names with their bounds, and the day its fiscal year ends. You \-transcribe what the words state; you never compute a date. Output one JSON object and nothing \-else, shaped like this:\n\-\n\-{\"date\": {\"y\": 2011, \"m\": 3, \"d\": 4}, \"date_words\": \"March 4, 2011\", \"periods\": [[\"name as written\", {\"y\": 2010, \"m\": 10, \"d\": 1}, {\"y\": 2011, \"m\": 9, \"d\": 30}]], \"fiscal_year_end\": [9, 30]}\n\-\n\-1. date is the document's own date: the day it was written, issued, filed, published or signed \-(a dateline, a filing date, a date under the title), or, for a report or bulletin that covers a \-period, the period it reports on. It is never today's date, and never a date the opening \-mentions for something else — an event it reports, an agreement it refers to, a deadline it \-sets. null when the opening states none.\n\-2. A date is written as parts, each a number transcribed from the words: y the year, m the \-month (a month name becomes its number), d the day, and h, min, s for a clock time when one is \-written. Write only the parts the words state: a bulletin for the year 2024 has {\"y\": 2024}; \-a report for March 2024 has {\"y\": 2024, \"m\": 3}; a dateline \"4 March 2011\" has \-{\"y\": 2011, \"m\": 3, \"d\": 4}.\n\-3. date_words is the words that state the date, copied verbatim from the opening; null when \-date is null.\n\-4. periods lists the periods the opening names and bounds, one entry each, [name, from, to]: \-a fiscal year or quarter, a reporting period, a term. name is the period as the opening writes \-it (\"fiscal 2019\", \"the second quarter\", \"2024年\"); from and to are its first and last \-day, month or year as parts, at the precision the words give. A reporting year \"2024\" runs \-from {\"y\": 2024} to {\"y\": 2024}. A fiscal year or quarter the opening states by its end \-date (\"the year ended September 30, 2019\") runs from the day after the previous one ended to \-that end date. Leave out a period whose bounds the opening does not fix.\n\-5. fiscal_year_end is [month, day] on which the document's fiscal year ends, when the opening \-states it or a stated fiscal year end makes it plain; null otherwise.\n\-6. Never compute a date from today, never resolve a relative expression, never fill in a part \-the words do not state. When the opening states nothing about the document's date or periods, \-output {\"date\": null, \"date_words\": null, \"periods\": [], \"fiscal_year_end\": null}.\n\-\n\-Example. The opening \"Westbrook Town Council — Minutes of the meeting held on March 4, 2011. \-Present: the mayor and six councillors.\" gives {\"date\": {\"y\": 2011, \"m\": 3, \"d\": 4}, \-\"date_words\": \"March 4, 2011\", \"periods\": [], \"fiscal_year_end\": null}. The opening \-\"Harbor Bakery — Annual report for fiscal 2019, the year ended September 30, 2019. Issued \-November 12, 2019.\" gives {\"date\": {\"y\": 2019, \"m\": 11, \"d\": 12}, \"date_words\": \-\"November 12, 2019\", \"periods\": [[\"fiscal 2019\", {\"y\": 2018, \"m\": 10, \"d\": 1}, \-{\"y\": 2019, \"m\": 9, \"d\": 30}]], \"fiscal_year_end\": [9, 30]}";-/// 解读提法的系统消息。形状各一行;引用是字面说的,不是它蕴含的;从不计算const INTERPRETATION_SYSTEM: &str = "\You interpret the time expressions of a document. Each mention is given with its id, its words \@@ -440,22 +397,6 @@ a second shop.\"]:\n\[4, \"point\", {\"kind\": \"anchored\", \"anchor\": {\"kind\": \"mention\", \"id\": 3}, \"offset\": {\"count\": 2, \"unit\": \"year\", \"direction\": \"after\"}}, \"year\"],\n\[5, \"point\", {\"kind\": \"anchored\", \"anchor\": {\"kind\": \"document\"}, \"offset\": {\"count\": 1, \"unit\": \"year\", \"direction\": \"before\"}}, \"year\"]]}";-/// 定日期的两条消息:常量系统消息 + 文件名与开头。开头不在这里截——它就是这次-/// 调用的正文,预算由调用方定-pub fn build_dating_messages(filename: &str, opening: &str) -> Vec<ChatMessage> {- let user = format!("Document: {filename}\n\nOpening:\n\"\"\"\n{opening}\n\"\"\"");- vec![- ChatMessage {- role: "system".into(),- content: DATING_SYSTEM.to_string(),- },- ChatMessage {- role: "user".into(),- content: user,- },- ]-}-/// 解读提法的两条消息:常量系统消息 + 语境块 + 提法清单(编号、原文的字、句子)pub fn build_interpretation_messages(context: &TimeContext<'_>,@@ -609,53 +550,6 @@ fn word<T: DeserializeOwned>(v: &Value) -> Option<T> {serde_json::from_value(Value::String(s)).ok()}-/// 期间条目 `[name, from, to]`-fn named_period(v: &Value) -> Option<NamedPeriod> {- let arr = v.as_array()?;- Some(NamedPeriod {- name: text(arr.first()?)?,- from: parts(arr.get(1)?)?,- to: parts(arr.get(2)?)?,- })-}--/// 解定日期的回复。日期、财年截止日坏了就留空并计数;期间逐条计数-pub fn parse_dating_response(raw: &str) -> anyhow::Result<DocumentDating> {- let value = reply_value(raw, "document dating")?;- let mut out = DocumentDating::default();- match value.get("date") {- None | Some(Value::Null) => {}- Some(v) => match parts(v) {- Some(d) => out.date = Some(d),- None => out.skipped += 1,- },- }- out.date_words = value.get("date_words").and_then(text);- if let Some(items) = value.get("periods").and_then(Value::as_array) {- for item in items {- match named_period(item) {- Some(p) => out.periods.push(p),- None => out.skipped += 1,- }- }- }- match value.get("fiscal_year_end") {- None | Some(Value::Null) => {}- Some(v) => {- let pair = v.as_array().and_then(|a| {- let m = int(a.first()?)?;- let d = int(a.get(1)?)?;- ((1..=12).contains(&m) && (1..=31).contains(&d)).then_some((m as u32, d as u32))- });- match pair {- Some(p) => out.fiscal_year_end = Some(p),- None => out.skipped += 1,- }- }- }- Ok(out)-}-/// 锚点:`{"kind": "mention", "id": N}` / `{"kind": "document"}` / `{"kind": "period", "name"}`;/// 光秃秃的 "document" 也认——只有它不带别的字段fn anchor(v: &Value) -> Option<Anchor> {@@ -899,65 +793,11 @@ mod tests {}}- /// 一份完整的定日期回复:带部件的日期、原话、两个期间、财年截止日- const DATING: &str = r#"{"date": {"y": 2019, "m": 11, "d": 12}, "date_words": "November 12, 2019",- "periods": [["fiscal 2019", {"y": 2018, "m": 10, "d": 1}, {"y": 2019, "m": 9, "d": 30}],- ["2024年", {"y": 2024}, {"y": 2024}]],- "fiscal_year_end": [9, 30]}"#;-- #[test]- fn a_dating_reply_parses_into_the_context() {- let d = parse_dating_response(DATING).unwrap();- assert_eq!(d.skipped, 0);- assert_eq!(d.date, Some(ymd(2019, 11, 12)));- assert_eq!(d.date_words.as_deref(), Some("November 12, 2019"));- assert_eq!(d.periods.len(), 2);- assert_eq!(d.periods[0].name, "fiscal 2019");- assert_eq!(d.periods[0].from, ymd(2018, 10, 1));- assert_eq!(d.periods[0].to, ymd(2019, 9, 30));- assert_eq!(d.periods[1].name, "2024年");- assert_eq!(d.periods[1].from, year(2024));- assert_eq!(d.periods[1].to, year(2024));- assert_eq!(d.fiscal_year_end, Some((9, 30)));- }-- #[test]- fn a_dating_reply_with_no_date_leaves_everything_empty() {- let d = parse_dating_response(- r#"{"date": null, "date_words": null, "periods": [], "fiscal_year_end": null}"#,- )- .unwrap();- assert_eq!(d.date, None);- assert_eq!(d.date_words, None);- assert!(d.periods.is_empty());- assert_eq!(d.fiscal_year_end, None);- assert_eq!(d.skipped, 0);- }-- /// 坏的日期、坏的期间、坏的财年截止日各计一次;好的期间照收- #[test]- fn a_dating_reply_counts_its_malformed_items() {- let d = parse_dating_response(- r#"{"date": {"y": 2019, "m": 13}, "date_words": "Undecimber 2019",- "periods": [["fiscal 2019", {"y": 2018, "m": 10, "d": 1}, {"y": 2019, "m": 9, "d": 30}],- ["broken", {"y": 2018}],- ["day without month", {"y": 2018, "d": 5}, {"y": 2019}]],- "fiscal_year_end": [13, 1]}"#,- )- .unwrap();- assert_eq!(d.date, None);- assert_eq!(d.periods.len(), 1);- assert_eq!(d.fiscal_year_end, None);- assert_eq!(d.skipped, 4);- }-#[test]fn a_clock_time_parses_and_prints_on_the_ladder() {- let d = parse_dating_response(- r#"{"date": {"y": 2011, "m": 3, "d": 4, "h": 14, "min": 30, "s": 5}, "date_words": "14:30:05 on March 4, 2011"}"#,- )- .unwrap();- let date = d.date.unwrap();+ let date =+ parts(&serde_json::json!({"y": 2011, "m": 3, "d": 4, "h": 14, "min": 30, "s": 5}))+ .unwrap();assert_eq!(date.granularity(), Granularity::Second);assert_eq!(date.to_string(), "2011-03-04 14:30:05");assert_eq!(year(2024).to_string(), "2024");@@ -1137,19 +977,8 @@ mod tests {assert_eq!(items[1].id, 2);}- #[test]- fn a_cut_off_dating_reply_keeps_the_complete_periods() {- let marker = r#"["2024年", {"y": 20"#;- let cut = DATING.find(marker).unwrap() + marker.len();- let d = parse_dating_response(&DATING[..cut]).unwrap();- assert_eq!(d.date, Some(ymd(2019, 11, 12)));- assert_eq!(d.periods.len(), 1);- assert_eq!(d.periods[0].name, "fiscal 2019");- }-#[test]fn a_reply_without_json_is_an_error() {- assert!(parse_dating_response("I could not find a date.").is_err());assert!(parse_interpretation_response("no", &[1]).is_err());}@@ -1168,25 +997,6 @@ mod tests {"10-K",];- #[test]- fn the_dating_prompt_carries_the_document_and_the_rules() {- let msgs = build_dating_messages(- "minutes.pdf",- "Westbrook Town Council — Minutes of the meeting held on March 4, 2011.",- );- assert_eq!(msgs.len(), 2);- assert_eq!(msgs[0].role, "system");- assert!(msgs[0].content.contains("Never compute"));- assert!(msgs[0].content.contains("never today's date"));- assert!(msgs[0].content.contains("fiscal_year_end"));- for mark in CORPUS_MARKS {- assert!(!msgs[0].content.contains(mark), "prompt carries {mark}");- }- assert_eq!(msgs[1].role, "user");- assert!(msgs[1].content.contains("Document: minutes.pdf"));- assert!(msgs[1].content.contains("held on March 4, 2011"));- }-#[test]fn the_interpretation_prompt_carries_the_context_and_every_mention() {let date = ymd(2019, 11, 12);@@ -1268,7 +1078,7 @@ mod tests {/// 存成 JSONB 再读回来,一字不差#[test]- fn interpretations_and_datings_round_trip_through_serde() {+ fn interpretations_round_trip_through_serde() {let ids: Vec<i64> = (1..=11).collect();let (items, _) = parse_interpretation_response(INTERPRETED, &ids).unwrap();for item in &items {@@ -1282,20 +1092,5 @@ mod tests {assert_eq!(json["reference"]["anchor"]["kind"], "document");assert_eq!(json["reference"]["offset"]["unit"], "year");assert_eq!(json["granularity"], "year");-- let dating = parse_dating_response(DATING).unwrap();- let json = serde_json::to_string(&dating).unwrap();- let back: DocumentDating = serde_json::from_str(&json).unwrap();- assert_eq!(back.date, dating.date);- assert_eq!(back.date_words, dating.date_words);- assert_eq!(back.periods, dating.periods);- assert_eq!(back.fiscal_year_end, dating.fiscal_year_end);- assert_eq!(back.skipped, dating.skipped);- let stored = serde_json::to_value(&dating).unwrap();- assert_eq!(stored["date"]["year"], 2019, "stored parts use full names");- assert_eq!(stored["fiscal_year_end"], serde_json::json!([9, 30]));-- let old: DocumentDating = serde_json::from_str("{}").unwrap();- assert_eq!(old.date, None, "a row stored without fields reads as empty");}}diff --git a/crates/utopia-server/src/owl_import.rs b/crates/utopia-server/src/owl_import.rsindex 1734ecbb..09d69dc3 100644--- a/crates/utopia-server/src/owl_import.rs+++ b/crates/utopia-server/src/owl_import.rs@@ -345,7 +345,7 @@ pub async fn plan(////// 单次导入认本文件里的类和库里已有的类(见 [`apply`] 里的 resolve),但包是挨个/// 装的:装 W3C Org 时 FOAF 还没来,`headOf` 的 `rdfs:domain foaf:Agent` 就落了空;-/// 等 FOAF 装好,没人回头补。没有 domain 的谓词 `judge_direction` 不判方向,+/// 等 FOAF 装好,没人回头补。没有 domain 的谓词判不出方向,/// 反向的 `Project Aurora head_of Li Ting` 就原样进图(#222)。////// 只补不删,关联表 ON CONFLICT DO NOTHING,重复跑无害。属性不在这里:属性的@@ -584,7 +584,7 @@ pub async fn apply(//// **库里已有的类也算数。** 从前只认本文件里的类,于是 W3C Org 的// `headOf rdfs:domain foaf:Agent` 在 FOAF 已经装好的库里照样丢 domain,- // 而没有 domain 的谓词 `judge_direction` 根本不判方向(#222)+ // 而没有 domain 的谓词根本判不出方向(#222)let resolve = |iris: &[String]| -> Vec<Uuid> {iris.iter().filter_map(|i| {diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rsindex c37d6b14..7c12bb23 100644--- a/crates/utopia-store/src/ontology.rs+++ b/crates/utopia-store/src/ontology.rs@@ -1899,43 +1899,6 @@ pub async fn decide_proposal(Ok(())}-/// 主语的类型合不合这个关系声明的 domain。沿继承链往上找。-///-/// **只回答,不动数据。** 0001 已经判过:签名是提示不是闸门,-/// 「用可能错的声明驱动自动动作风险高」。而实体类型本身也是模型判出来的-/// (实测里 Elon Musk 被判成 `researcher`),拿它去翻转事实方向,-/// 是两层不确定叠在一起还静默改写。所以这里的结果只用来落一条信号。-///-/// 三种回答,别混成两种:-/// - `Some(true)` 合-/// - `Some(false)` 不合——**这才是信号**-/// - `None` 没得判(关系没声明 domain,或实体还没有类型)-pub async fn subject_fits_domain(- pool: &PgPool,- relation_type_id: Uuid,- subject_type_id: Option<Uuid>,-) -> AppResult<Option<bool>> {- let Some(subject_type_id) = subject_type_id else {- return Ok(None);- };- let (declared, ok): (i64, i64) = sqlx::query_as(- "WITH RECURSIVE up(id) AS (- SELECT $2::uuid- UNION- SELECT p.parent_id FROM entity_type_parents p JOIN up ON p.child_id = up.id- )- SELECT (SELECT count(*) FROM relation_type_domains WHERE relation_type_id = $1),- (SELECT count(*) FROM relation_type_domains d- JOIN up ON up.id = d.entity_type_id- WHERE d.relation_type_id = $1)",- )- .bind(relation_type_id)- .bind(subject_type_id)- .fetch_one(pool)- .await?;- Ok((declared > 0).then_some(ok > 0))-}-/// 这些类的全部祖先(不含自己)。沿 `subClassOf` 上溯,多继承与菱形都走得通。////// 给按块检索的候选补地板用:向量检索偏爱字面出现在正文里的叶子类,@@ -1961,109 +1924,6 @@ pub async fn ancestors_of(pool: &PgPool, ids: &[Uuid]) -> AppResult<Vec<Uuid>> {Ok(rows.into_iter().map(|(id,)| id).collect())}-/// 同 [`subject_fits_domain`],但类型**从库里的实体读**,不靠调用方手上那份。-///-/// 抽取器手上的 `entity_type_of` 只覆盖模型在这一块里声明过的实体;宾语常常-/// 是别处已经存在的实体,这一块没重新声明它的类型,于是查不到、判不了。-/// 而消解已经把它连到了库里那一行——那里有类型,用它才判得全。-pub async fn entity_fits_domain(- pool: &PgPool,- relation_type_id: Uuid,- entity_id: Uuid,-) -> AppResult<Option<bool>> {- let (declared, ok): (i64, i64) = sqlx::query_as(- "WITH RECURSIVE up(id) AS (- SELECT type_id FROM entities WHERE id = $2- UNION- SELECT p.parent_id FROM entity_type_parents p JOIN up ON p.child_id = up.id- )- SELECT (SELECT count(*) FROM relation_type_domains WHERE relation_type_id = $1),- (SELECT count(*) FROM relation_type_domains d- JOIN up ON up.id = d.entity_type_id- WHERE d.relation_type_id = $1)",- )- .bind(relation_type_id)- .bind(entity_id)- .fetch_one(pool)- .await?;- Ok((declared > 0).then_some(ok > 0))-}--/// 一条 (主语, 谓词, 宾语) 对着谓词的 domain 签名该怎么落。-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum Fit {- /// 谓词没声明 domain——没有判据,照原样落- Unchecked,- /// 主语符合- Keep,- /// 主语不符合、宾语符合:按签名对调主宾- Swap,- /// 两边都不符合:这个关系不适用于这对实体,谓词该留空- Neither,-}--/// **三条写谓词的路共用的那一道判断**(#190 / #196):抽取落新事实、采纳把谓词-/// 挂回旧事实、合并换掉主语——从前只有抽取查,另外两条各自绕了过去。-///-/// 判据刻意窄(0012):只看签名,只在**正向违反而反向成立**时对调,两个方向都-/// 对不上就留空谓词。参数顺序不是关于世界的断言,是这个 key 的编码约定,所以本体-/// 在这一处是执法的;哪些类型能参与仍是引导,不在这里裁。-///-/// **range 也算进来**(#222)。从前只看 domain:`headOf` 的 domain 是 Agent,-/// schema.org 里 Project 也是 Organization 也是 Agent,于是 `Project Aurora head_of-/// Li Ting` 主语过关就 Keep,宾语是个人、range 要 Organization 这件事没人看。-/// 现在两端各看各的:正向两端都不违反才 Keep;否则反过来两端都不违反才 Swap。-/// 没判出类型的实体在 range 这一端不算违反("不知道"不是"不符合",与-/// `signature_breaks` 同一条纪律);domain 那一端沿用旧规矩,那是 0012 定下的-pub async fn judge_direction(- pool: &PgPool,- relation_type_id: Uuid,- subject_id: Uuid,- object_id: Uuid,-) -> AppResult<Fit> {- let subject_in_domain = entity_fits_domain(pool, relation_type_id, subject_id).await?;- let object_in_range = entity_fits_range(pool, relation_type_id, object_id).await?;- if subject_in_domain.is_none() && object_in_range.is_none() {- return Ok(Fit::Unchecked);- }- if subject_in_domain != Some(false) && object_in_range != Some(false) {- return Ok(Fit::Keep);- }- let object_in_domain = entity_fits_domain(pool, relation_type_id, object_id).await?;- let subject_in_range = entity_fits_range(pool, relation_type_id, subject_id).await?;- if object_in_domain != Some(false) && subject_in_range != Some(false) {- return Ok(Fit::Swap);- }- Ok(Fit::Neither)-}--/// [`entity_fits_domain`] 的 range 版。多一条规矩:实体还没判出类型 → None,-/// 不当违反——range 这一端是新加的判据(#222),不该让未分类实体的事实因此-/// 丢掉谓词-pub async fn entity_fits_range(- pool: &PgPool,- relation_type_id: Uuid,- entity_id: Uuid,-) -> AppResult<Option<bool>> {- let (declared, typed, ok): (i64, bool, i64) = sqlx::query_as(- "WITH RECURSIVE up(id) AS (- SELECT type_id FROM entities WHERE id = $2- UNION- SELECT p.parent_id FROM entity_type_parents p JOIN up ON p.child_id = up.id- )- SELECT (SELECT count(*) FROM relation_type_ranges WHERE relation_type_id = $1),- (SELECT type_id IS NOT NULL FROM entities WHERE id = $2),- (SELECT count(*) FROM relation_type_ranges g- JOIN up ON up.id = g.entity_type_id- WHERE g.relation_type_id = $1)",- )- .bind(relation_type_id)- .bind(entity_id)- .fetch_one(pool)- .await?;- Ok((declared > 0 && typed).then_some(ok > 0))-}-/// 把 `owl:inverseOf` / `rdfs:subPropertyOf` 从 IRI 解析成 id。////// **必须是第二遍。** 这两条指的是另一个关系类型,而 id 要等全部插完才有——diff --git a/crates/utopia-store/src/reasoning.rs b/crates/utopia-store/src/reasoning.rsindex d127e2c0..6ec9b141 100644--- a/crates/utopia-store/src/reasoning.rs+++ b/crates/utopia-store/src/reasoning.rs@@ -137,9 +137,9 @@ async fn axioms(conn: &mut PgConnection, kb_id: Uuid) -> AppResult<HashMap<Uuid,/// 主语不在谓词声明的 domain 里、或宾语不在 range 里的活事实(#190 / #196)。///-/// 这是签名检查在**账本层**的那一半:抽取与采纳在写入时按 `ontology::judge_direction`-/// 掰正或留空,但合并会换掉主语、本体会事后改 domain,写入时的守卫挡不住写入之后-/// 的改动。所以这里对着库量一遍,任何一条路写反了都在 Review 里看得见。+/// 签名检查在**账本层**:对齐只给结构对得上的候选(0053),但合并会换掉主语、本体会+/// 事后改 domain,写入时的把关挡不住写入之后的改动。所以这里对着库量一遍,任何一条路+/// 写反了都在 Review 里看得见。////// **没有类型的实体不算**:它没有类型可比,「不知道」不是「不符合」——按 0009,/// 未分类是一种诚实的状态,不该因此被报成矛盾。声明了 domain / range 的谓词才查,diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rsindex a38143f6..660ba2ef 100644--- a/crates/utopia-store/src/resolution.rs+++ b/crates/utopia-store/src/resolution.rs@@ -2415,85 +2415,6 @@ pub async fn put_verdict(Ok(())}-/// 把提议过 `forms` 里那些类型的实体改到 `type_id` 上。返回 (批次 id, 改动数)。-///-/// 与谓词那边的 `graph::adopt_proposed_predicates` 对称:**只建类型不动实体,-/// 本体长大了、图没变好**——提议过 model 的实体会继续挂在 concept 下。-///-/// 实体是可变行(P0 的 PATCH 就直接改),所以这里就是 UPDATE,撤销靠账本-/// 记下改之前的类型,而不是靠 supersedes 链。-pub async fn adopt_proposed_types(- pool: &PgPool,- kb_id: Uuid,- type_id: Uuid,- forms: &[String],- // None = 引擎自动(本体长出新类之后的收尾认领没有人在按)- actor: Option<Uuid>,-) -> AppResult<(Uuid, u32)> {- let batch_id = Uuid::now_v7();- if forms.is_empty() {- return Ok((batch_id, 0));- }- // 已经在目标类上的不算改动,也不进账本——撤销时不该把它们推回去。- //- // **`IS DISTINCT FROM` 而不是 `<>`**:0009 之后 type_id 可能是 NULL,而- // `NULL <> uuid` 求值为 NULL 不是 true,那一行会被悄悄滤掉——偏偏带着- // proposed_type 的几乎全是还没判出类型的实体,整个认领功能会一声不响地空转- let targets: Vec<(Uuid, Option<Uuid>, String)> = sqlx::query_as(- "SELECT id, type_id, canonical_name FROM entities- WHERE kb_id = $1 AND merged_into IS NULL- -- 人拍过板的不认领。**这一行顺带让 unadopt 天然正确**:human 行- -- 永远不进采纳批次,撤销时也就不会遇到它们,不必额外还原 type_source- AND type_source <> 'human'- AND proposed_type = ANY($2) AND type_id IS DISTINCT FROM $3",- )- .bind(kb_id)- .bind(forms)- .bind(type_id)- .fetch_all(pool)- .await?;-- let mut names: HashSet<String> = HashSet::new();- let mut moved = 0u32;- for (entity_id, from_type, name) in targets {- let mut tx = pool.begin().await?;- sqlx::query(- // actor 有值 = 人在界面上点的批准,他背书了这个类型 → 受保护。- // 无值 = 本体长出新类之后的收尾认领,没人在按- "UPDATE entities- SET type_id = $2, proposed_type = NULL, updated_at = now(),- type_source = CASE WHEN $3::uuid IS NULL THEN 'inferred' ELSE 'human' END- WHERE id = $1",- )- .bind(entity_id)- .bind(type_id)- .bind(actor)- .execute(&mut *tx)- .await?;- sqlx::query(- "INSERT INTO entity_retypes- (batch_id, kb_id, entity_id, from_type_id, to_type_id, actor_id)- VALUES ($1, $2, $3, $4, $5, $6)",- )- .bind(batch_id)- .bind(kb_id)- .bind(entity_id)- .bind(from_type)- .bind(type_id)- .bind(actor)- .execute(&mut *tx)- .await?;- tx.commit().await?;- names.insert(name);- moved += 1;- }- // 消歧后缀的兜底值就是类型标签,改了类就得重算(同 P0 的实体改类)- for n in &names {- refresh_disambiguators(pool, kb_id, n).await?;- }- Ok((batch_id, moved))-}-/// 撤销一次实体改类:把它们放回原来的类型。////// 类型本身不删——与谓词那边同一条理由:有实体指向过它,而"它存在过"是历史。@@ -2969,9 +2890,7 @@ pub async fn nearest_typed_for_each_with(/// 按实体逐个改类,写进同一本账。返回 (批次 id, 改动数)。///-/// 与 [`adopt_proposed_types`] 的区别只在挑选方式:那个按 `proposed_type` 这个-/// **说法**认领一批,这个由调用方点名——类型消解裁决出来的是"这个实体是那个类",-/// 不是"叫这个说法的都是那个类"。+/// 由调用方点名:类型消解裁决出来的是"这个实体是那个类",不是"叫这个说法的都是那个类"。////// 账本格式一字不差,所以 [`unadopt_types`] 原样能撤。pub async fn retype_entities(diff --git a/crates/utopia-store/src/type_bindings.rs b/crates/utopia-store/src/type_bindings.rsindex e83fe701..86f119f9 100644--- a/crates/utopia-store/src/type_bindings.rs+++ b/crates/utopia-store/src/type_bindings.rs@@ -587,9 +587,9 @@ pub async fn bound_map(pool: &PgPool, kb_id: Uuid) -> AppResult<HashMap<String,Ok(rows.into_iter().collect())}-/// 没有类对得上的类别词:按老流程提到本体页(`proposed_type` → `adopt_proposed_types`)。+/// 没有类对得上的类别词:把模型提的类名记在实体的 `proposed_type` 上,类型消解读它。///-/// 守 `set_proposed_type` 的约:只写第一次、最长 60 字;只提活着的、还没类的、人没+/// 只写第一次、最长 60 字;只提活着的、还没类的、人没/// 定过的实体——采纳时人定过的不会被认领,数进「将重新归类 N 个」里就是虚的。/// 返回写上的行数。pub async fn propose(diff --git a/crates/utopia-store/tests/store/a_direction_is_judged_by_range_too.rs b/crates/utopia-store/tests/store/a_direction_is_judged_by_range_too.rsdeleted file mode 100644index 5cb6a4cf..00000000--- a/crates/utopia-store/tests/store/a_direction_is_judged_by_range_too.rs+++ /dev/null@@ -1,139 +0,0 @@-//! `judge_direction` 看 range,不只看 domain(#222)。-//!-//! 从前只要主语过了 domain 就 Keep,宾语违反 range 没人看:`headOf` 的 domain 是-//! Agent,schema.org 里 Project 也是 Agent,于是 `Project Aurora head_of Li Ting`-//! 原样进图。这里用最小的本体复现那一形:一个两端都允许的 domain,一个只认-//! 公司的 range,反过来读才成立的事实必须被对调。--use sqlx::PgPool;-use utopia_store::ontology::{judge_direction, Fit};-use uuid::Uuid;--struct Fixture {- /// domain = person | company,range = company- leads: Uuid,- alice: Uuid,- acme: Uuid,- globex: Uuid,- /// 还没判出类型的实体- mystery: Uuid,-}--async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {- let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());- let (person, company, leads) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());- let (alice, acme, globex, mystery) = (- Uuid::now_v7(),- Uuid::now_v7(),- Uuid::now_v7(),- Uuid::now_v7(),- );-- sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'direction-test')")- .bind(org)- .execute(pool)- .await?;- sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'direction-test')")- .bind(ws)- .bind(org)- .execute(pool)- .await?;- sqlx::query(- "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'direction-test')",- )- .bind(kb)- .bind(ws)- .execute(pool)- .await?;- for (id, key, label) in [- (person, "person", "Person"),- (company, "company", "Company"),- ] {- 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) VALUES ($1, $2, 'leads', 'leads')",- )- .bind(leads)- .bind(kb)- .execute(pool)- .await?;- for ty in [person, company] {- sqlx::query(- "INSERT INTO relation_type_domains (relation_type_id, entity_type_id) VALUES ($1, $2)",- )- .bind(leads)- .bind(ty)- .execute(pool)- .await?;- }- sqlx::query(- "INSERT INTO relation_type_ranges (relation_type_id, entity_type_id) VALUES ($1, $2)",- )- .bind(leads)- .bind(company)- .execute(pool)- .await?;- for (id, ty, name) in [- (alice, Some(person), "Alice"),- (acme, Some(company), "Acme"),- (globex, Some(company), "Globex"),- (mystery, None, "Mystery"),- ] {- sqlx::query(- "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",- )- .bind(id)- .bind(kb)- .bind(ty)- .bind(name)- .execute(pool)- .await?;- }- Ok(Fixture {- leads,- alice,- acme,- globex,- mystery,- })-}--#[tokio::test]-async fn direction_is_judged_by_range_too() -> anyhow::Result<()> {- let Some(url) = utopia_store::test_db::url() else {- return Ok(());- };- let pool = PgPool::connect(&url).await?;- let f = seed(&pool).await?;-- // 正向两端都符合:照旧- assert_eq!(- judge_direction(&pool, f.leads, f.alice, f.acme).await?,- Fit::Keep- );- // 主语过了 domain(公司也允许当主语),宾语却是个人、range 只认公司。- // 从前这里是 Keep——正是 Project Aurora head_of Li Ting 那一形;- // 反过来读两端都成立,所以对调- assert_eq!(- judge_direction(&pool, f.leads, f.acme, f.alice).await?,- Fit::Swap- );- // 宾语还没判出类型:range 这一端"不知道"不算违反,不能因此丢谓词- assert_eq!(- judge_direction(&pool, f.leads, f.alice, f.mystery).await?,- Fit::Keep- );- // 两个公司:正向宾语 range 符合、主语 domain 也符合 → Keep- assert_eq!(- judge_direction(&pool, f.leads, f.acme, f.globex).await?,- Fit::Keep- );- Ok(())-}diff --git a/crates/utopia-store/tests/store/human_type_decisions.rs b/crates/utopia-store/tests/store/human_type_decisions.rsindex 4a3c99d0..d4cbe0aa 100644--- a/crates/utopia-store/tests/store/human_type_decisions.rs+++ b/crates/utopia-store/tests/store/human_type_decisions.rs@@ -5,10 +5,9 @@//! 而 0009 刚在同一片区域踩过 `NULL <> uuid` 的坑——类型系统数得清 Rust,//! 数不到 SQL 里去。//!-//! 四条断言对应四条路径:+//! 三条断言对应三条路径://!//! - 类型消解取材(`entities_for_type_resolution`)不该捞人拍过板的-//! - 本体长出新类后的认领(`adopt_proposed_types`)不该盖掉人拍过板的//! - 抽取升格不该给「人说过就是没有类型」的实体安一个类型 ← 0009 × P4 的交叉//! - `retype_entities` 用现成的 `actor` 参数区分 human / inferred//!@@ -132,56 +131,6 @@ async fn type_resolution_leaves_human_decisions_alone() -> anyhow::Result<()> {run}-/// 本体长出新类之后的认领,同样不该盖掉人的决定。-///-/// 这一条顺带保证了 `unadopt_types` 的正确性:human 行永远不进采纳批次,-/// 撤销时也就不会遇到它们,不必额外还原 `type_source`。-#[tokio::test]-async fn adopting_a_new_class_does_not_claim_human_typed_entities() -> 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 {- // 两个实体都被模型提议过 startup,但一个的类型是人定的- for (name, source) in [("Acme", "human"), ("Globex", "extracted")] {- let id = entity(&pool, &f, name, Some(f.org_type), source).await?;- sqlx::query("UPDATE entities SET proposed_type = 'startup' WHERE id = $1")- .bind(id)- .execute(&pool)- .await?;- }-- let (_, moved) = utopia_store::resolution::adopt_proposed_types(- &pool,- f.kb,- f.sub_type,- &["startup".to_string()],- None,- )- .await?;- assert_eq!(moved, 1, "只该认领那个不是人定的");-- let human: Option<Uuid> = sqlx::query_scalar(- "SELECT type_id FROM entities WHERE kb_id = $1 AND canonical_name = 'Acme'",- )- .bind(f.kb)- .fetch_one(&pool)- .await?;- assert_eq!(human, Some(f.org_type), "人定的类型原样未动");- Ok::<_, anyhow::Error>(())- }- .await;-- sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")- .bind(f.kb)- .execute(&pool)- .await?;- run-}-/// **0009 × P4 的交叉,最容易漏的一条。**////// 0009 之后「没有类型」可能是人的决定——他看过这个实体,认为本体里没有合适的类。diff --git a/crates/utopia-store/tests/store/main.rs b/crates/utopia-store/tests/store/main.rsindex ab28ed4c..1f28c5c9 100644--- a/crates/utopia-store/tests/store/main.rs+++ b/crates/utopia-store/tests/store/main.rs@@ -43,7 +43,6 @@ mod a_deleted_document_no_longer_attests;mod a_deletion_is_an_event;mod a_derivation_follows_the_second_clock;mod a_described_thing_is_an_entity_without_a_name;-mod a_direction_is_judged_by_range_too;mod a_dirty_ledger_stops_the_migration;mod a_disambiguator_follows_the_ontology;mod a_document_opening_is_its_first_live_chunk;