World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Two values clash only while both hold (#635)
WaylandYang6b624554ec34
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rsindex 44c8784b..4b007cda 100644--- a/crates/utopia-core/src/models.rs+++ b/crates/utopia-core/src/models.rs@@ -1187,7 +1187,7 @@ pub struct ConceptMapping {#[derive(Debug, Clone, Serialize)]pub struct AxiomViolation {pub id: Uuid,- /// self_loop | asymmetry | cycle | functional | signature | derived_contradiction+ /// self_loop | asymmetry | cycle | functional | inverse_functional | signature | derived_contradictionpub kind: String,/// 判据来自哪条关系。人若判「公理写错了」,从这里进本体去改pub predicate: Option<String>,@@ -1195,7 +1195,7 @@ pub struct AxiomViolation {pub left_text: String,pub right_fact: Uuid,pub right_text: String,- /// 环的长度(含首尾)。其余三类为 0——前端据此决定要不要显示「查看路径」+ /// `path` 的长度:环上的事实(含首尾)、互斥组里的事实、派生的前提。自环与签名为 0pub path_len: i32,pub detected_at: chrono::DateTime<chrono::Utc>,/// `derived_contradiction` 独有(0017):推出来的那条三元组——它没有落库,diff --git a/crates/utopia-reason/src/derive.rs b/crates/utopia-reason/src/derive.rsindex aa6c473d..e7d28cd8 100644--- a/crates/utopia-reason/src/derive.rs+++ b/crates/utopia-reason/src/derive.rs@@ -88,8 +88,8 @@ pub struct Derivation {/// 一条参与推导的边,比 [`Edge`] 多带有效期。///-/// 单独一个类型而不是给 `Edge` 加字段:R0 完全用不上时间——公理是否被违反-/// 与它什么时候成立无关,而 R1 每一步都要算交集。+/// 单独一个类型而不是给 `Edge` 加字段:环与自环用不上时间,R0 的互斥三类要看+/// 两条是否同时成立(#634),R1 每一步都要算交集。#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct TimedEdge {pub edge: Edge,@@ -386,7 +386,7 @@ pub fn validity(pub struct Clash {/// `Derivation::facts` 里的下标pub derived: usize,- /// 撞在哪条公理上:`Functional`(含 inverse_functional)、`Asymmetry`、`SelfLoop`+ /// 撞在哪条公理上:`Functional`、`InverseFunctional`、`Asymmetry`、`SelfLoop`pub axiom: Kind,/// 被撞的断言。自环没有对方,取派生的最后一条前提pub against: Uuid,@@ -528,7 +528,7 @@ pub fn contradictions(if *subj != d.subject && overlap(span, *sp).is_some() {out.with_assertions.push(Clash {derived: i,- axiom: Kind::Functional,+ axiom: Kind::InverseFunctional,against: *fact,});}@@ -594,7 +594,7 @@ pub fn contradictions(if let Some(v) = d_po.get(&(d.predicate, d.object)) {for &j in v {if j > i && derivation.facts[j].subject != d.subject && overlapping(j) {- note(i, j, Kind::Functional);+ note(i, j, Kind::InverseFunctional);}}}diff --git a/crates/utopia-reason/src/lib.rs b/crates/utopia-reason/src/lib.rsindex 5f11d082..d0df22b3 100644--- a/crates/utopia-reason/src/lib.rs+++ b/crates/utopia-reason/src/lib.rs@@ -16,6 +16,7 @@ pub mod derive;pub mod ontology;pub mod rules;+use derive::TimedEdge;use std::collections::{HashMap, HashSet};use uuid::Uuid;@@ -59,10 +60,11 @@ impl Axioms {pub struct Violation {pub kind: Kind,/// 涉及的事实。**自反违反只有一条**——它跟自己矛盾,不需要第二条。- /// 环取首尾两条(中间那些在 `path` 里)。+ /// 环取首尾两条(中间那些在 `path` 里);互斥的三类(asymmetry、functional、+ /// inverse_functional)取整组里 id 最小与最大的两条。pub left: Uuid,pub right: Uuid,- /// 环的完整路径,按事实排列;其余三类为空。+ /// 环的完整路径,按事实排列;互斥的三类是整组事实,按 id 排序;自环为空。/// 留着是因为「A→B→C→A」比「A 与 C 矛盾」有用得多——人要顺着看一遍才知道/// 该撤哪一条pub path: Vec<Uuid>,@@ -76,9 +78,13 @@ pub enum Kind {Asymmetry,/// `A p B p … p A`,而 p 声明了 transitive——闭包里推出 `A p A`Cycle,- /// 同一主语与谓词同时指向两个宾语,而 p 声明了 functional- /// (inverse_functional 则是同一宾语被两个主语指)+ /// 同一主语与谓词在同一段时间里指向两个宾语,而 p 声明了 functionalFunctional,+ /// 同一宾语在同一段时间里被两个主语指,而 p 声明了 inverse_functional。+ ///+ /// 与 `Functional` 分开记(#634):从前两个方向共用一个种类,一个项目同时有两位+ /// 负责人被写成「该只有一个值,却有两个」,人照着去主语那一侧找,找的是错的一端+ InverseFunctional,/// `A p B`,而 A 不在 p 声明的 domain 里、或 B 不在 range 里(#190 / #196)。////// **这一类不由本 crate 算出**:它要看实体的类型与 domain / range 的闭包,那是@@ -100,6 +106,7 @@ impl Kind {Kind::Asymmetry => "asymmetry",Kind::Cycle => "cycle",Kind::Functional => "functional",+ Kind::InverseFunctional => "inverse_functional",Kind::Signature => "signature",Kind::DerivedContradiction => "derived_contradiction",}@@ -118,34 +125,54 @@ pub const MAX_DEPTH: usize = 12;////// 每个谓词各查各的:公理是挂在谓词上的,跨谓词的边之间没有可比性/// (`A part_of B` 与 `B produces A` 同时成立不是矛盾)。-pub fn check(edges: &[Edge], axioms: &HashMap<Uuid, Axioms>) -> Vec<Violation> {+///+/// **互斥的三类要求两条事实同时成立**(#634)。functional、inverse_functional、+/// asymmetric 说的都是「同一时刻」:Lin Zhao 的薪水在 2024-02-20 从 28000 变成+/// 32000,两段首尾相接,那是一次调薪。从前这里只收 `Edge`,区间在调用方就丢了,+/// 于是每一次接任都进了 Review。判据与 `derive::contradictions` 同一个——派生那一侧+/// 一直是按区间重叠判的,断言这一侧跟它对齐。+///+/// 区间照 `TimedEdge` 的读法:半开 `[from, to)`,`None` 是那一侧无界(恒常谓词两端+/// 都是 `None`,于是退回到只看形状)。自环与环不看时间。+pub fn check(edges: &[TimedEdge], axioms: &HashMap<Uuid, Axioms>) -> Vec<Violation> {let mut out = Vec::new();- let mut by_pred: HashMap<Uuid, Vec<Edge>> = HashMap::new();- for e in edges {- let Some(ax) = axioms.get(&e.predicate) else {+ let mut by_pred: HashMap<Uuid, Vec<TimedEdge>> = HashMap::new();+ for t in edges {+ let Some(ax) = axioms.get(&t.edge.predicate) else {continue;};if ax.says_nothing() {continue;}- by_pred.entry(e.predicate).or_default().push(*e);+ by_pred.entry(t.edge.predicate).or_default().push(*t);}for (pred, group) in by_pred {let ax = axioms[&pred];+ let shapes: Vec<Edge> = group.iter().map(|t| t.edge).collect();if ax.irreflexive {- out.extend(self_loops(&group));+ out.extend(self_loops(&shapes));}if ax.asymmetric {out.extend(asymmetries(&group));}if ax.transitive {- out.extend(cycles(&group));+ out.extend(cycles(&shapes));}if ax.functional {- out.extend(too_many(&group, |e| e.subject, |e| e.object));+ out.extend(clashes(+ &group,+ Kind::Functional,+ |e| (e.subject, Uuid::nil()),+ |a, b| a.object != b.object,+ ));}if ax.inverse_functional {- out.extend(too_many(&group, |e| e.object, |e| e.subject));+ out.extend(clashes(+ &group,+ Kind::InverseFunctional,+ |e| (e.object, Uuid::nil()),+ |a, b| a.subject != b.subject,+ ));}}out@@ -165,25 +192,23 @@ fn self_loops(edges: &[Edge]) -> Vec<Violation> {.collect()}-fn asymmetries(edges: &[Edge]) -> Vec<Violation> {- let mut seen: HashMap<(Uuid, Uuid), Uuid> = HashMap::new();- let mut out = Vec::new();- for e in edges {- if e.subject == e.object {- // 自环由 irreflexive 那一档负责;反对称在这里报一遍是重复- continue;- }- if let Some(&other) = seen.get(&(e.object, e.subject)) {- out.push(Violation {- kind: Kind::Asymmetry,- left: other,- right: e.fact,- path: Vec::new(),- });- }- seen.insert((e.subject, e.object), e.fact);- }- out+/// 反对称:同一对节点在同一段时间里两个方向都断言了。+///+/// 键是无序的那一对节点,「不同」是方向相反——与 functional 同一个形状,所以走+/// 同一个函数。+fn asymmetries(edges: &[TimedEdge]) -> Vec<Violation> {+ // 自环由 irreflexive 那一档负责;反对称在这里报一遍是重复+ let two_way: Vec<TimedEdge> = edges+ .iter()+ .filter(|t| t.edge.subject != t.edge.object)+ .copied()+ .collect();+ clashes(+ &two_way,+ Kind::Asymmetry,+ |e| (e.subject.min(e.object), e.subject.max(e.object)),+ |a, b| a.subject != b.subject,+ )}/// 找环。**每个环只报一次,而且只以一种形状报**:去重按环上事实的集合,报出来的@@ -279,37 +304,89 @@ fn walk<'a>(}}-/// 函数性违反:同一个「一端」指向了两个不同的「另一端」。+/// 互斥:同一个键下,两条「不同」的事实同时成立。///-/// `functional` 与 `inverse_functional` 是同一个判断的两个方向,所以共用这一个-/// 函数,由调用方决定哪一端是键。-fn too_many(edges: &[Edge], key: fn(&Edge) -> Uuid, val: fn(&Edge) -> Uuid) -> Vec<Violation> {- let mut by_key: HashMap<Uuid, Vec<&Edge>> = HashMap::new();- for e in edges {- by_key.entry(key(e)).or_default().push(e);+/// functional(键是主语,不同是宾语不同)、inverse_functional(键是宾语,不同是+/// 主语不同)、asymmetric(键是无序的一对节点,不同是方向相反)都是这个形状,+/// 调用方给键和「不同」。+///+/// **一组报一处。** 同一个主语同一段时间里指了五个宾语,是一件事;两两组合报十处+/// 只是把它说十遍。组是冲突关系的连通块:a 与 b 同时成立、b 与 c 同时成立,三条+/// 就是一组,哪怕 a 与 c 首尾相接。先后出现、互不重叠的两场冲突是两组。+///+/// **身份只由组里有哪些事实决定**(#624)。`axiom_violations` 按+/// `(kind, left_fact, right_fact)` 唯一;从前 left/right 取遇到的头两条,而遇到的+/// 顺序来自 HashMap 与取数顺序——同一处冲突换个顺序就是另一行,人裁过的那行被绕开,+/// 与 #618 的环是同一个病。现在 `path` 是排过序的整组,left/right 是它的首尾。+fn clashes(+ edges: &[TimedEdge],+ kind: Kind,+ key: fn(&Edge) -> (Uuid, Uuid),+ differ: fn(&Edge, &Edge) -> bool,+) -> Vec<Violation> {+ let mut by_key: HashMap<(Uuid, Uuid), Vec<&TimedEdge>> = HashMap::new();+ for t in edges {+ // 空区间(没有日期的事件,0031)哪一刻都不成立,跟谁都不同时+ if matches!((t.from, t.to), (Some(f), Some(to)) if f >= to) {+ continue;+ }+ by_key.entry(key(&t.edge)).or_default().push(t);}let mut out = Vec::new();- for (_, group) in by_key {- // 只报第一对。同一个主语指了五个宾语时报十对(两两组合)只是把同一件事- // 说十遍——人要处理的是「这里有冲突」,看一对就够去查了- let mut distinct: Vec<&Edge> = Vec::new();- for e in group {- if !distinct.iter().any(|d| val(d) == val(e)) {- distinct.push(e);+ for mut group in by_key.into_values() {+ if group.len() < 2 {+ continue;+ }+ // 按起点扫一遍,手里留着还没结束的:它们正是与这一条同时成立的。一长串前后+ // 相接的历史值(逐月的薪水)手里始终只有一两条,不会两两比一遍+ group.sort_by_key(|t| (t.from.unwrap_or(i64::MIN), t.edge.fact));+ let mut parent: Vec<usize> = (0..group.len()).collect();+ let mut clashed = vec![false; group.len()];+ let mut open: Vec<usize> = Vec::new();+ for i in 0..group.len() {+ let start = group[i].from.unwrap_or(i64::MIN);+ // 半开区间:终点正好是这一条起点的,已经结束了——首尾相接是接任+ open.retain(|&j| group[j].to.is_none_or(|to| to > start));+ for &j in &open {+ if differ(&group[i].edge, &group[j].edge) {+ clashed[i] = true;+ clashed[j] = true;+ let (a, b) = (root(&mut parent, i), root(&mut parent, j));+ parent[a] = b;+ }+ }+ open.push(i);+ }+ let mut blocks: HashMap<usize, Vec<Uuid>> = HashMap::new();+ for i in 0..group.len() {+ if clashed[i] {+ let r = root(&mut parent, i);+ blocks.entry(r).or_default().push(group[i].edge.fact);}}- if distinct.len() > 1 {+ for mut facts in blocks.into_values() {+ facts.sort_unstable();+ facts.dedup();out.push(Violation {- kind: Kind::Functional,- left: distinct[0].fact,- right: distinct[1].fact,- path: Vec::new(),+ kind,+ left: facts[0],+ right: facts[facts.len() - 1],+ path: facts,});}}out}+/// 并查集找根,顺手压缩路径+fn root(parent: &mut [usize], mut i: usize) -> usize {+ while parent[i] != i {+ parent[i] = parent[parent[i]];+ i = parent[i];+ }+ i+}+#[cfg(test)]mod tests {use super::*;@@ -334,6 +411,52 @@ mod tests {fn with(ax: Axioms) -> HashMap<Uuid, Axioms> {HashMap::from([(n(99), ax)])}+ /// 不带时间地查:两端都无界,任意两条都同时成立,检查只剩形状。大部分用例问的+ /// 就是形状;问时间的用例用 `at` 造边,直接调 `super::check`+ fn check(edges: &[Edge], axioms: &HashMap<Uuid, Axioms>) -> Vec<Violation> {+ let timed: Vec<TimedEdge> = edges+ .iter()+ .map(|&edge| TimedEdge {+ edge,+ from: None,+ to: None,+ })+ .collect();+ super::check(&timed, axioms)+ }+ /// 带区间的边,`[from, to)`+ fn at(fact: u8, s: u8, o: u8, from: Option<i64>, to: Option<i64>) -> TimedEdge {+ TimedEdge {+ edge: e(fact, s, o),+ from,+ to,+ }+ }+ /// 输入的全排列。顺序是这一类 bug 的全部来源,所以每种顺序都要跑到+ fn permutations<T: Copy>(items: &[T]) -> Vec<Vec<T>> {+ if items.len() <= 1 {+ return vec![items.to_vec()];+ }+ let mut out = Vec::new();+ for i in 0..items.len() {+ let mut rest = items.to_vec();+ let head = rest.remove(i);+ for mut tail in permutations(&rest) {+ tail.insert(0, head);+ out.push(tail);+ }+ }+ out+ }+ /// 一次检查的结果,排成与顺序无关的形状,好拿来比+ fn shape(v: Vec<Violation>) -> Vec<(&'static str, Uuid, Uuid, Vec<Uuid>)> {+ let mut out: Vec<_> = v+ .into_iter()+ .map(|x| (x.kind.as_str(), x.left, x.right, x.path))+ .collect();+ out.sort();+ out+ }fn kinds(v: &[Violation]) -> Vec<Kind> {let mut k: Vec<Kind> = v.iter().map(|x| x.kind).collect();k.sort_by_key(|x| x.as_str());@@ -532,7 +655,7 @@ mod tests {).is_empty());- // 同一个宾语被两个主语指+ // 同一个宾语被两个主语指:记成它自己的种类,不冒充 functional(#634)let inn = [e(1, 2, 1), e(2, 3, 1)];assert_eq!(kinds(&check(@@ -542,7 +665,7 @@ mod tests {..Default::default()}))),- vec![Kind::Functional]+ vec![Kind::InverseFunctional]);assert!(check(&inn,@@ -554,8 +677,8 @@ mod tests {.is_empty());}- /// 同一个主语指五个宾语只报一对。报十对(两两组合)是把同一件事说十遍——- /// 人要处理的是「这里有冲突」,看一对就够去查了。+ /// 同一个主语指五个宾语只报一处。报十处(两两组合)是把同一件事说十遍;+ /// 那一处带着全部五条,人撤哪条都有按钮。#[test]fn one_finding_per_conflicting_key_not_one_per_pair() {let edges = [e(1, 1, 2), e(2, 1, 3), e(3, 1, 4), e(4, 1, 5), e(5, 1, 6)];@@ -567,6 +690,147 @@ mod tests {}),);assert_eq!(v.len(), 1);+ assert_eq!(v[0].path, vec![f(1), f(2), f(3), f(4), f(5)]);+ assert_eq!((v[0].left, v[0].right), (f(1), f(5)));+ }++ /// **一处冲突,不管以什么顺序读进来,都是同一行**(#624)。从前 left/right 取+ /// 遇到的头两条:三个值的六种顺序给出六种键,反对称两种顺序给出两种键——而+ /// `axiom_violations` 按键唯一,换个顺序,人裁过的那行就被绕开了。+ ///+ /// 跑全排列而不是跑一百次:顺序是这里唯一的变量,每一种都要到。+ #[test]+ fn the_same_clash_is_the_same_row_whatever_the_order() {+ let functional = with(Axioms {+ functional: true,+ ..Default::default()+ });+ let inverse = with(Axioms {+ inverse_functional: true,+ ..Default::default()+ });+ let asymmetric = with(Axioms {+ asymmetric: true,+ ..Default::default()+ });+ let cases: [(&[Edge], &HashMap<Uuid, Axioms>); 3] = [+ (&[e(1, 1, 2), e(2, 1, 3), e(3, 1, 4)], &functional),+ (&[e(1, 2, 1), e(2, 3, 1), e(3, 4, 1)], &inverse),+ (&[e(1, 1, 2), e(2, 2, 1), e(3, 1, 2)], &asymmetric),+ ];+ for (edges, ax) in cases {+ let shapes: HashSet<_> = permutations(edges)+ .iter()+ .map(|p| shape(check(p, ax)))+ .collect();+ assert_eq!(shapes.len(), 1, "顺序换出了不同的行: {shapes:?}");+ let only = shapes.into_iter().next().unwrap();+ assert_eq!(only.len(), 1);+ let (_, left, right, path) = &only[0];+ assert_eq!(path, &vec![f(1), f(2), f(3)], "整组,按 id 排序");+ assert_eq!((*left, *right), (f(1), f(3)), "首尾是最小与最大");+ }+ }++ /// **前后相接是接任,不是矛盾**(#634)。Lin Zhao 的薪水 `[2023-06, 2024-02)`+ /// 是 28000、`[2024-02, 现在)` 是 32000:一个人任何一刻都只有一份薪水。从前+ /// 检查不看时间,每次调薪都进 Review。重叠哪怕一秒,才是同时有两个值。+ #[test]+ fn a_succession_is_not_a_contradiction() {+ let functional = with(Axioms {+ functional: true,+ ..Default::default()+ });+ let (jun23, feb24) = (1_685_577_600, 1_708_387_200);++ let raise = [+ at(1, 1, 2, Some(jun23), Some(feb24)),+ at(2, 1, 3, Some(feb24), None),+ ];+ assert!(super::check(&raise, &functional).is_empty(), "首尾相接");++ let overlap = [+ at(1, 1, 2, Some(jun23), Some(feb24 + 1)),+ at(2, 1, 3, Some(feb24), None),+ ];+ assert_eq!(+ kinds(&super::check(&overlap, &functional)),+ vec![Kind::Functional]+ );++ // 宾语侧同理:一个项目换了负责人,中间还空了一年+ let handover = [+ at(1, 2, 9, Some(jun23), Some(feb24)),+ at(2, 3, 9, Some(feb24 + 31_536_000), None),+ ];+ let inverse = with(Axioms {+ inverse_functional: true,+ ..Default::default()+ });+ assert!(super::check(&handover, &inverse).is_empty());++ // 反对称同理:先是 A 管 B,后来 B 管 A+ let reversal = [+ at(1, 1, 2, Some(jun23), Some(feb24)),+ at(2, 2, 1, Some(feb24), None),+ ];+ let asymmetric = with(Axioms {+ asymmetric: true,+ ..Default::default()+ });+ assert!(super::check(&reversal, &asymmetric).is_empty());+ }++ /// 无界的那一侧跟谁都重叠:一条不知道从何时起、一直成立的事实,与任何一段+ /// 都同时成立。没有日期的事件区间为空(0031),哪一刻都不成立,跟谁都不冲突。+ #[test]+ fn an_unbounded_span_meets_everything_and_an_empty_one_meets_nothing() {+ let functional = with(Axioms {+ functional: true,+ ..Default::default()+ });+ let always = [at(1, 1, 2, None, None), at(2, 1, 3, Some(100), Some(200))];+ assert_eq!(+ kinds(&super::check(&always, &functional)),+ vec![Kind::Functional]+ );++ let undated_event = [+ at(1, 1, 2, Some(150), Some(150)),+ at(2, 1, 3, Some(100), Some(200)),+ ];+ assert!(super::check(&undated_event, &functional).is_empty());+ }++ /// **组是冲突的连通块。** a 与 b 重叠、b 与 c 重叠,a 与 c 首尾相接:三条是一组+ /// ——撤掉 b 两场冲突一起消失,分开报会让人以为是两件事。两场彼此隔开的冲突是两组。+ #[test]+ fn a_clash_is_a_connected_group_and_separate_clashes_stay_separate() {+ let functional = with(Axioms {+ functional: true,+ ..Default::default()+ });+ let chained = [+ at(1, 1, 2, Some(0), Some(100)),+ at(2, 1, 3, Some(50), Some(150)),+ at(3, 1, 4, Some(100), Some(200)),+ ];+ let v = super::check(&chained, &functional);+ assert_eq!(v.len(), 1);+ assert_eq!(v[0].path, vec![f(1), f(2), f(3)]);++ let apart = [+ at(1, 1, 2, Some(0), Some(100)),+ at(2, 1, 3, Some(50), Some(100)),+ at(3, 1, 4, Some(500), Some(600)),+ at(4, 1, 5, Some(550), Some(600)),+ // 与谁都不重叠的一条不进任何一组+ at(5, 1, 6, Some(300), Some(400)),+ ];+ let v = shape(super::check(&apart, &functional));+ assert_eq!(v.len(), 2);+ assert_eq!(v[0].3, vec![f(1), f(2)]);+ assert_eq!(v[1].3, vec![f(3), f(4)]);}/// 同一个主语两次指向**同一个**宾语不是冲突——重复断言而已。diff --git a/crates/utopia-store/src/reasoning.rs b/crates/utopia-store/src/reasoning.rsindex 986a4433..40d18822 100644--- a/crates/utopia-store/src/reasoning.rs+++ b/crates/utopia-store/src/reasoning.rs@@ -214,9 +214,10 @@ pub async fn record_signature_breaks(/// 跑一遍检查,把结果落库。pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {let (timed, spans, _) = timed_edges(pool, kb_id).await?;- let edges: Vec<Edge> = timed.iter().map(|t| t.edge).collect();let axioms = axioms(pool, kb_id).await?;- let mut violations = check(&edges, &axioms);+ // 带着区间查:互斥的三类只在同时成立时才算(#634)。从前这里把区间剥掉再查,+ // 每一次调薪、每一次换负责人都进了 Review+ let mut violations = check(&timed, &axioms);// 第五类不在纯逻辑引擎里:它要看实体的类型与谓词的 domain / range,那是库里的// 东西。算出来后与其它四类走同一条落库与清陈规矩for fact in signature_breaks(pool, kb_id, None).await? {@@ -279,7 +280,7 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {}let mut report = Report {- edges: edges.len(),+ edges: timed.len(),predicates_with_axioms: axioms.len(),found: violations.len(),contradictions: details.len(),@@ -288,6 +289,8 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {..Default::default()};+ let accepted = accepted_groups(pool, kb_id).await?;+// 事务里做,否则「插新的」与「清陈旧的」之间有个窗口,那一瞬间 Review 页// 会短暂地少东西let mut tx = pool.begin().await?;@@ -299,6 +302,17 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {right,path,} = v;+ let grouped = is_grouped(*kind);+ // 人认可过「这几条可以并存」,这一轮的组又全在那几条里——比如其中一条后来+ // 撤了,剩下的组首尾变了、键也变了——仍然是那句认可管着,不再端上来。+ // 组里有一条认可时没见过的,就不在这里拦:那是新情况+ if grouped+ && accepted+ .iter()+ .any(|(k, facts)| k == kind.as_str() && path.iter().all(|f| facts.contains(f)))+ {+ continue;+ }let detail = details.get(&(*left, *right)).cloned()@@ -317,7 +331,8 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {// 本来就在而且 resolved 的要再看一眼:`fact_retracted` / `fact_closed` /// `axiom_relaxed` 都是「世界会变」的承诺——事实没了、区间闭了、公理放宽了,// 违规就不该再算出来。又算出来了,承诺就是没兑现,那行回到 open,人再看一次。- // `accepted` 是有意并存,重算多少次都沉默(#202)+ // `accepted` 是有意并存,重算多少次都沉默(#202)——只要还是认可时那几条。+ // 互斥的组走到这里说明上面没拦住:同一个键下多了一条,那行也回到 openlet (keep, status, resolution, is_new): (Uuid, String, Option<String>, bool) =sqlx::query_as("INSERT INTO axiom_violations@@ -339,12 +354,12 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {if is_new {report.inserted += 1;}- if status == "resolved"- && matches!(- resolution.as_deref(),- Some("fact_retracted" | "fact_closed" | "axiom_relaxed")- )- {+ let broken = match resolution.as_deref() {+ Some("fact_retracted" | "fact_closed" | "axiom_relaxed") => true,+ Some("accepted") => grouped,+ _ => false,+ };+ if status == "resolved" && broken {sqlx::query("UPDATE axiom_violationsSET status = 'open', resolution = NULL, decided_by = NULL,@@ -442,6 +457,39 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {Ok(report)}+/// 互斥的三类:一处违规是一组同时成立、彼此冲突的事实(`path` 是整组)。+fn is_grouped(kind: Kind) -> bool {+ matches!(+ kind,+ Kind::Asymmetry | Kind::Functional | Kind::InverseFunctional+ )+}++/// 人认可过并存的互斥组:(种类, 组里的事实)。+///+/// 认可说的是「这几条可以同时成立」,所以按事实集合比,不按键比——组里撤掉一条,+/// 剩下的首尾换了、键也换了,那句认可照样管着它们(#624)。+async fn accepted_groups(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<(String, HashSet<Uuid>)>> {+ let rows: Vec<(String, Uuid, Uuid, Vec<Uuid>)> = sqlx::query_as(+ "SELECT kind, left_fact, right_fact, path FROM axiom_violations+ WHERE kb_id = $1 AND status = 'resolved' AND resolution = 'accepted'+ AND kind IN ('asymmetry', 'functional', 'inverse_functional')",+ )+ .bind(kb_id)+ .fetch_all(pool)+ .await?;+ Ok(rows+ .into_iter()+ .map(|(kind, left, right, path)| {+ let mut facts: HashSet<Uuid> = path.into_iter().collect();+ // 首尾本来就在 path 里;0053 之前记下的一对 path 是空的,靠这两列+ facts.insert(left);+ facts.insert(right);+ (kind, facts)+ })+ .collect())+}+/// 矛盾要写成人能读的话,而派生没有落库、没有文本可查——名字在这里补。struct Names {entities: HashMap<Uuid, String>,diff --git a/crates/utopia-store/tests/a_clash_needs_both_at_once.rs b/crates/utopia-store/tests/a_clash_needs_both_at_once.rsnew file mode 100644index 00000000..bc57fc04--- /dev/null+++ b/crates/utopia-store/tests/a_clash_needs_both_at_once.rs@@ -0,0 +1,367 @@+//! 互斥违规(asymmetry、functional、inverse_functional)打在真库上(#624、#634)。+//!+//! 纯逻辑那部分——全排列下同一个键、首尾相接不算、连通块成组——在 `utopia-reason`+//! 里跑。这里钉的是只有过一遍取数与落库才看得见的四样:+//!+//! 1. **接任不进 Review。** 从前 `run` 把区间剥掉再查:一次调薪、一次换负责人、一次+//! 上下级对调,各进一行。区间是 `timed_edges` 从库里读出来的,这一段纯逻辑测不到+//! 2. **宾语侧记成自己的种类。** 从前落库是 `functional`,人照着去主语那一侧找+//! 3. **换一个取数顺序,裁决照样接得上。** 这是 #624 报的那个序列:裁成+//! `axiom_relaxed`,公理与事实都没变,只是堆里的顺序变了,重跑——从前插了一行新的+//! open、原来那行不重开+//! 4. **认可管的是它见过的那几条。** 组里多一条,要人再看;那条撤了,认可照样管着+//! 剩下的,哪怕组的首尾(也就是键)已经变了+//!+//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。++use sqlx::PgPool;+use utopia_store::reasoning;+use uuid::Uuid;++struct Fixture {+ org: Uuid,+ kb: Uuid,+ etype: Uuid,+ /// state + functional+ salary: Uuid,+ /// state + inverse_functional+ leads: Uuid,+ /// state + asymmetric+ reports_to: Uuid,+}++async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {+ let (org, ws, kb, etype) = (+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ );+ let (salary, leads, reports_to) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'clash-test')")+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'clash-test')")+ .bind(ws)+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'clash-test')",+ )+ .bind(kb)+ .bind(ws)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'thing', 'Thing')",+ )+ .bind(etype)+ .bind(kb)+ .execute(pool)+ .await?;+ for (id, key, functional, inverse, asymmetric) in [+ (salary, "salary", true, false, false),+ (leads, "leads", false, true, false),+ (reports_to, "reports_to", false, false, true),+ ] {+ sqlx::query(+ "INSERT INTO relation_types+ (id, kb_id, key, label, temporal, functional, inverse_functional, is_asymmetric)+ VALUES ($1, $2, $3, $3, 'state', $4, $5, $6)",+ )+ .bind(id)+ .bind(kb)+ .bind(key)+ .bind(functional)+ .bind(inverse)+ .bind(asymmetric)+ .execute(pool)+ .await?;+ }+ Ok(Fixture {+ org,+ kb,+ etype,+ salary,+ leads,+ reports_to,+ })+}++async fn entity(pool: &PgPool, f: &Fixture, name: &str) -> anyhow::Result<Uuid> {+ let id = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",+ )+ .bind(id)+ .bind(f.kb)+ .bind(f.etype)+ .bind(name)+ .execute(pool)+ .await?;+ Ok(id)+}++/// 一条关系事实,区间 `[from, to)`,按天。两端都不给就是「从证据那天起一直成立」+async fn fact(+ pool: &PgPool,+ f: &Fixture,+ (s, p, o): (Uuid, Uuid, Uuid),+ from: Option<&str>,+ to: Option<&str>,+) -> anyhow::Result<Uuid> {+ let day = |d: Option<&str>| {+ d.map(|d| {+ format!("{d}T00:00:00Z")+ .parse::<chrono::DateTime<chrono::Utc>>()+ .unwrap()+ })+ };+ let id = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id,+ valid_from, valid_from_precision, valid_to, valid_to_precision)+ VALUES ($1, $2, $3, $4, $5,+ $6, CASE WHEN $6 IS NULL THEN NULL ELSE 'day' END,+ $7, CASE WHEN $7 IS NULL THEN NULL ELSE 'day' END)",+ )+ .bind(id)+ .bind(f.kb)+ .bind(s)+ .bind(p)+ .bind(o)+ .bind(day(from))+ .bind(day(to))+ .execute(pool)+ .await?;+ Ok(id)+}++/// open 的违规:(kind, left, right, path)+async fn open(pool: &PgPool, f: &Fixture) -> anyhow::Result<Vec<(String, Uuid, Uuid, Vec<Uuid>)>> {+ Ok(sqlx::query_as(+ "SELECT kind, left_fact, right_fact, path FROM axiom_violations+ WHERE kb_id = $1 AND status = 'open' ORDER BY kind, left_fact",+ )+ .bind(f.kb)+ .fetch_all(pool)+ .await?)+}++fn sorted(mut ids: Vec<Uuid>) -> Vec<Uuid> {+ ids.sort();+ ids+}++async fn cleanup(pool: &PgPool, f: &Fixture) -> anyhow::Result<()> {+ sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(f.org)+ .execute(pool)+ .await?;+ Ok(())+}++#[tokio::test]+async fn a_succession_stays_out_of_review_and_an_overlap_comes_in() -> 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 result = async {+ let lin = entity(&pool, &f, "Lin Zhao").await?;+ let (k28, k32, k40) = (+ entity(&pool, &f, "28000").await?,+ entity(&pool, &f, "32000").await?,+ entity(&pool, &f, "40000").await?,+ );+ let aurora = entity(&pool, &f, "Project Aurora").await?;+ let (zhang, zhou, kim) = (+ entity(&pool, &f, "Zhang San").await?,+ entity(&pool, &f, "Zhou Qi").await?,+ entity(&pool, &f, "Kim").await?,+ );+ let (a, b) = (entity(&pool, &f, "A").await?, entity(&pool, &f, "B").await?);++ // ---- 一、三种接任:调薪首尾相接,换负责人中间空了一年,上下级前后对调+ fact(+ &pool,+ &f,+ (lin, f.salary, k28),+ Some("2023-06-01"),+ Some("2024-02-20"),+ )+ .await?;+ let raised = fact(&pool, &f, (lin, f.salary, k32), Some("2024-02-20"), None).await?;+ fact(+ &pool,+ &f,+ (zhang, f.leads, aurora),+ Some("2023-02-01"),+ Some("2024-07-05"),+ )+ .await?;+ let took_over = fact(&pool, &f, (zhou, f.leads, aurora), Some("2025-09-01"), None).await?;+ fact(+ &pool,+ &f,+ (a, f.reports_to, b),+ Some("2020-01-01"),+ Some("2022-01-01"),+ )+ .await?;+ fact(&pool, &f, (b, f.reports_to, a), Some("2023-01-01"), None).await?;++ let r = reasoning::run(&pool, f.kb).await?;+ assert_eq!(r.edges, 6);+ assert_eq!(r.found, 0, "三次接任,没有一处矛盾");+ assert!(open(&pool, &f).await?.is_empty());++ // ---- 二、重叠才是矛盾。宾语侧记成 inverse_functional+ let doubled = fact(&pool, &f, (lin, f.salary, k40), Some("2024-06-01"), None).await?;+ let second_lead = fact(&pool, &f, (kim, f.leads, aurora), Some("2025-10-01"), None).await?;+ reasoning::run(&pool, f.kb).await?;+ let rows = open(&pool, &f).await?;+ assert_eq!(rows.len(), 2, "{rows:?}");++ let func = rows+ .iter()+ .find(|r| r.0 == "functional")+ .expect("functional row");+ let pair = sorted(vec![raised, doubled]);+ assert_eq!(+ (func.1, func.2),+ (pair[0], pair[1]),+ "首尾是组里最小与最大的 id"+ );+ assert_eq!(func.3, pair, "path 是整组,按 id 排序");++ let inv = rows+ .iter()+ .find(|r| r.0 == "inverse_functional")+ .expect("宾语侧违规记成 inverse_functional,不冒充 functional");+ assert_eq!(inv.3, sorted(vec![took_over, second_lead]));+ Ok::<_, anyhow::Error>(())+ }+ .await;+ cleanup(&pool, &f).await?;+ result+}++#[tokio::test]+async fn a_decision_follows_the_clash_not_the_scan_order() -> 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 result = async {+ let (a, b) = (entity(&pool, &f, "A").await?, entity(&pool, &f, "B").await?);+ let ab = fact(&pool, &f, (a, f.reports_to, b), None, None).await?;+ let ba = fact(&pool, &f, (b, f.reports_to, a), None, None).await?;++ let r = reasoning::run(&pool, f.kb).await?;+ assert_eq!(r.inserted, 1);+ sqlx::query(+ "UPDATE axiom_violations SET status = 'resolved', resolution = 'axiom_relaxed'+ WHERE kb_id = $1 AND kind = 'asymmetry'",+ )+ .bind(f.kb)+ .execute(&pool)+ .await?;++ // 公理没放宽、事实没动,只把先读到的那条挪到堆的后面:一次什么都不改的+ // UPDATE 会写一个新的行版本,顺序扫描于是先读到另一条。从前这就换了键——+ // 插一行新的 open,裁过的那行不重开(#624 的复现序列)+ sqlx::query("UPDATE facts SET confidence = confidence WHERE id = $1")+ .bind(ab)+ .execute(&pool)+ .await?;++ let again = reasoning::run(&pool, f.kb).await?;+ assert_eq!(+ again.inserted, 0,+ "同一处冲突不因为读的顺序变了就成了另一行"+ );+ assert_eq!(again.reopened, 1, "放宽公理的承诺没兑现,那一行回到 open");+ let rows = open(&pool, &f).await?;+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].3, sorted(vec![ab, ba]));+ Ok::<_, anyhow::Error>(())+ }+ .await;+ cleanup(&pool, &f).await?;+ result+}++#[tokio::test]+async fn an_acceptance_covers_the_facts_it_saw() -> 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 result = async {+ let lin = entity(&pool, &f, "Lin Zhao").await?;+ let (x, y, z) = (+ entity(&pool, &f, "base").await?,+ entity(&pool, &f, "bonus").await?,+ entity(&pool, &f, "stock").await?,+ );+ let p = fact(&pool, &f, (lin, f.salary, x), Some("2024-01-01"), None).await?;+ let q = fact(&pool, &f, (lin, f.salary, y), Some("2024-01-01"), None).await?;+ reasoning::run(&pool, f.kb).await?;+ sqlx::query(+ "UPDATE axiom_violations SET status = 'resolved', resolution = 'accepted'+ WHERE kb_id = $1 AND kind = 'functional'",+ )+ .bind(f.kb)+ .execute(&pool)+ .await?;++ let quiet = reasoning::run(&pool, f.kb).await?;+ assert_eq!(+ (quiet.inserted, quiet.reopened),+ (0, 0),+ "认可过的并存重跑沉默"+ );+ assert!(open(&pool, &f).await?.is_empty());++ // ---- 组里多了一条认可时没见过的:那是新情况,要人再看+ let r = fact(&pool, &f, (lin, f.salary, z), Some("2024-03-01"), None).await?;+ reasoning::run(&pool, f.kb).await?;+ let rows = open(&pool, &f).await?;+ assert_eq!(rows.len(), 1, "{rows:?}");+ assert_eq!(rows[0].3, sorted(vec![p, q, r]));++ // ---- 那条撤了:剩下的仍是认可过的那两条。组的首尾可能已经换了,键跟着换,+ // 认可照样管着——按事实比,不按键比+ sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = $1")+ .bind(r)+ .execute(&pool)+ .await?;+ let settled = reasoning::run(&pool, f.kb).await?;+ assert!(+ open(&pool, &f).await?.is_empty(),+ "撤掉新来的那条,回到认可过的状态"+ );+ assert_eq!(settled.inserted, 0);+ let accepted: i64 = sqlx::query_scalar(+ "SELECT count(*) FROM axiom_violations+ WHERE kb_id = $1 AND status = 'resolved' AND resolution = 'accepted'",+ )+ .bind(f.kb)+ .fetch_one(&pool)+ .await?;+ assert_eq!(accepted, 1, "人的认可活过这一整串重跑");+ Ok::<_, anyhow::Error>(())+ }+ .await;+ cleanup(&pool, &f).await?;+ result+}diff --git a/migrations/0053_a_clash_is_keyed_by_its_facts.sql b/migrations/0053_a_clash_is_keyed_by_its_facts.sqlnew file mode 100644index 00000000..a446fa84--- /dev/null+++ b/migrations/0053_a_clash_is_keyed_by_its_facts.sql@@ -0,0 +1,55 @@+-- 互斥违规按组里的事实定键,并且只有同时成立才算(#624、#634)。+--+-- asymmetry、functional 从前以扫描时遇到的头两条做 `(left_fact, right_fact)`:同一处+-- 冲突换个取数顺序就是另一个键,而 `axiom_violations` 按 `(kb_id, kind, left_fact,+-- right_fact)` 唯一——人裁过的那一行被绕开,与 #618 的环同一个病(0052)。代码那边+-- 改成:一处违规是一组同时成立、彼此冲突的事实,`path` 是整组按 id 排序,left/right+-- 是它的首尾。+--+-- 同一刀里还有两件:检查开始看有效期(前后相接的两个值是接任),inverse_functional+-- 有了自己的种类(从前与 functional 共用一个)。这里修既有的行。++ALTER TABLE axiom_violations+ DROP CONSTRAINT axiom_violations_kind_check,+ ADD CONSTRAINT axiom_violations_kind_check CHECK (kind IN (+ 'self_loop', 'asymmetry', 'cycle', 'functional', 'inverse_functional',+ 'signature', 'derived_contradiction'+ ));++-- open 的删掉:下一轮推理以新形状算回来。其中那些接任被报成的矛盾不会再回来。+DELETE FROM axiom_violations+ WHERE kind IN ('asymmetry', 'functional') AND status = 'open';++-- 裁过的不能删——那是人的决定。先把记成 functional 的宾语侧违规改回它的种类:+-- 两条事实宾语相同、主语不同,那是 inverse_functional 算出来的。+UPDATE axiom_violations v+ SET kind = 'inverse_functional'+ FROM facts l, facts r+ WHERE v.kind = 'functional'+ AND l.id = v.left_fact AND r.id = v.right_fact+ AND l.object_id = r.object_id AND l.subject_id <> r.subject_id;++-- 再规范成新形状。从前记的都是一对,所以组就是这两条。+CREATE TEMP TABLE clash_canon ON COMMIT DROP AS+SELECT id, kb_id, kind, detected_at,+ LEAST(left_fact, right_fact) AS lo,+ GREATEST(left_fact, right_fact) AS hi+ FROM axiom_violations+ WHERE kind IN ('asymmetry', 'functional', 'inverse_functional') AND status <> 'open';++-- 规范完可能两行撞在一起:同一对被两种顺序各裁过一次。留最早发现的那一行。+DELETE FROM axiom_violations WHERE id IN (+ SELECT id FROM (+ SELECT id,+ row_number() OVER (+ PARTITION BY kb_id, kind, lo, hi+ ORDER BY detected_at, id) AS rn+ FROM clash_canon) t+ WHERE t.rn > 1);++UPDATE axiom_violations v+ SET left_fact = c.lo,+ right_fact = c.hi,+ path = ARRAY[c.lo, c.hi]+ FROM clash_canon c+ WHERE v.id = c.id;diff --git a/web/src/api.ts b/web/src/api.tsindex e81babe5..5719d07e 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -634,7 +634,7 @@ export interface MappingRevision {/** derived_contradiction 独有(0017):推出来的那条三元组——它没有落库,* 只能在这里写出来。其它种类是 `{}` */export interface ViolationDetail {- axiom?: "functional" | "asymmetry" | "self_loop";+ axiom?: "functional" | "inverse_functional" | "asymmetry" | "self_loop";rule?: "transitive" | "symmetric" | "inverse" | "sub_property";via_label?: string;subject?: string;@@ -656,6 +656,7 @@ export interface AxiomViolation {| "asymmetry"| "cycle"| "functional"+ | "inverse_functional"| "signature"| "derived_contradiction";/** 判据来自哪条关系。判「公理写错了」时从这里进本体去改 */@@ -665,14 +666,15 @@ export interface AxiomViolation {/** 自反那一类与 left 相同——一条事实跟自己矛盾 */right_fact: string;right_text: string;- /** 环的长度;其余三类为 0 */+ /** `path` 的长度:环上的、互斥组里的事实,派生的前提;自环与签名为 0 */path_len: number;detected_at: string;detail: ViolationDetail;/** 审核线索(0017 §2),一次只给一条:旧断言没写结束日期、有同名实体、* 抽取置信度低。没有就空 */hint: "stale" | "duplicate" | "unsure" | null;- /** 环上的每一条事实,按顺序;其余种类为空。撤事实要指名撤哪条(#202) */+ /** 环上的每一条事实(按顺序),或互斥组里的每一条(按 id);自环与签名为空。+ * 撤事实要指名撤哪条(#202) */path: { id: string; text: string }[];}/** 本体自己的一处自相矛盾。**与 AxiomViolation 不是一回事**:那个说diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex 6a62abf5..80a77b20 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -1814,9 +1814,12 @@ export const en = {violationsHint:"Facts that contradict axioms your ontology declares. Nothing here is a guess — a predicate that declares no axioms is never checked.",violationSelfLoop: "Points at itself",- violationAsymmetry: "Both directions asserted",+ violationAsymmetry: "Both directions hold at once",violationCycle: "Cycle through the transitive chain",- violationFunctional: "Should hold one value, holds two",+ /** 互斥的三类只在同时成立时才报(#634),所以文案说「同一时间」 */+ violationFunctional: "More than one value at once",+ /** 宾语侧(#634):同一个对象同一时间被不止一个主语指着 */+ violationInverseFunctional: "More than one holder at once",/** 签名违规(#190 / #196):一条事实的主语或宾语落在谓词声明的类型之外——* 抽取时会掰正,采纳与合并这两条路从前绕过了检查 */violationSignature: "Subject or object outside the declared types",@@ -1843,9 +1846,10 @@ export const en = {retractFact: "Data is wrong",/** 双事实与环上的违规:撤具体哪一条(#202) */retractThis: "Retract",- retractThisHint: "Withdraw this fact from the graph; the other one stays.",+ retractThisHint: "Withdraw this fact from the graph; the rest stay.",relaxAxiom: "Axiom is wrong",- acceptBoth: "Both are right",+ /** 互斥组可以不止两条 */+ acceptBoth: (n: number): string => (n > 2 ? "All are right" : "Both are right"),runCheck: "Run check",checkNeverRun:"Not checked yet. Contradictions are found by asking your ontology, so a run here only reports what its axioms actually say.",diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex 727ba0e5..5bb8d910 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -1581,9 +1581,10 @@ export const zh: Strings = {violationsHint:"与本体自己声明的公理相抵触的事实。这里没有猜测——谓词没声明公理就不查。",violationSelfLoop: "指向了自己",- violationAsymmetry: "两个方向都断言了",+ violationAsymmetry: "两个方向同时成立",violationCycle: "传递链绕成了环",- violationFunctional: "该只有一个值,却有两个",+ violationFunctional: "同一时间有不止一个值",+ violationInverseFunctional: "同一时间有不止一个持有者",violationSignature: "主语或宾语不在关系声明的类型里",violationDerived: "推出来的与断言相抵触",derivedLine: (s: string, p: string, o: string) =>@@ -1603,9 +1604,9 @@ export const zh: Strings = {violationPath: (n: number) => `环上 ${n} 条事实`,retractFact: "数据错了",retractThis: "撤这条",- retractThisHint: "把这条事实撤出图谱,另一条不动。",+ retractThisHint: "把这条事实撤出图谱,其余的不动。",relaxAxiom: "公理错了",- acceptBoth: "两边都对",+ acceptBoth: (n: number) => (n > 2 ? "都对" : "两边都对"),runCheck: "跑一遍检查",checkNeverRun:"还没查过。矛盾是拿本体自己声明的公理量出来的——跑一遍只会报公理确实说了的那些。",diff --git a/web/src/pages/Review.tsx b/web/src/pages/Review.tsxindex 28fd4739..26bcd6ac 100644--- a/web/src/pages/Review.tsx+++ b/web/src/pages/Review.tsx@@ -799,6 +799,7 @@ function ViolationRow({asymmetry: S.review.violationAsymmetry,cycle: S.review.violationCycle,functional: S.review.violationFunctional,+ inverse_functional: S.review.violationInverseFunctional,signature: S.review.violationSignature,derived_contradiction: S.review.violationDerived,}[v.kind];@@ -826,7 +827,7 @@ function ViolationRow({{S.review.violationVia(v.predicate)}</span>)}- {v.path_len > 0 && (+ {v.kind === "cycle" && v.path_len > 0 && (<span className="text-fine text-ink-2">{S.review.violationPath(v.path_len)}</span>@@ -853,7 +854,7 @@ function ViolationRow({disabled={busy}onClick={() => onDecide("accepted")}>- {S.review.acceptBoth}+ {S.review.acceptBoth(facts.length)}</Button><Button variant="secondary" size="sm"disabled={busy}