Changesets · Branches · Tags · Compare
| Changeset | 2bae07dc9dff7147566b393ef430d87884608ff2e40168acc496ff9c67b9c2e9 |
|---|---|
| Author | WaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-09-03 11:14 +08:00 |
| Committer | GitHub <noreply@github.com> · 2026-09-03 11:14 +08:00 |
| Parents | 762a87286d3d |
16 files changed
modified crates/utopia-core/src/models.rs +12 −3
| @@ -867,10 +867,10 @@ | ||
| 867 | 867 | /// |
| 868 | 868 | /// **两条事实都展开成 主-谓-宾 文本**:Review 页要让人一眼看出矛盾在哪, |
| 869 | 869 | /// 而两个 UUID 看不出任何东西。自反那一类两条相同——它就是一条事实。 |
| 870 | -#[derive(Debug, Clone, Serialize, sqlx::FromRow)] | |
| 870 | +#[derive(Debug, Clone, Serialize)] | |
| 871 | 871 | pub struct AxiomViolation { |
| 872 | 872 | pub id: Uuid, |
| 873 | - /// self_loop | asymmetry | cycle | functional | |
| 873 | + /// self_loop | asymmetry | cycle | functional | signature | derived_contradiction | |
| 874 | 874 | pub kind: String, |
| 875 | 875 | /// 判据来自哪条关系。人若判「公理写错了」,从这里进本体去改 |
| 876 | 876 | pub predicate: Option<String>, |
| @@ -881,6 +881,12 @@ | ||
| 881 | 881 | /// 环的长度(含首尾)。其余三类为 0——前端据此决定要不要显示「查看路径」 |
| 882 | 882 | pub path_len: i32, |
| 883 | 883 | pub detected_at: chrono::DateTime<chrono::Utc>, |
| 884 | + /// `derived_contradiction` 独有(0017):推出来的那条三元组——它没有落库, | |
| 885 | + /// 只能在这里写出来。字段见 `reasoning::run`。其余种类是 `{}` | |
| 886 | + pub detail: serde_json::Value, | |
| 887 | + /// 审核线索(0017 §2):`stale`(旧断言没写结束日期)、`duplicate`(有同名 | |
| 888 | + /// 实体)、`unsure`(抽取置信度低)。只给一条,没有就空 | |
| 889 | + pub hint: Option<String>, | |
| 884 | 890 | } |
| 885 | 891 | |
| 886 | 892 | /// 本体自己的一处自相矛盾(见 `ontology_defects`)。 |
| @@ -891,8 +897,11 @@ | ||
| 891 | 897 | pub struct OntologyDefect { |
| 892 | 898 | pub id: Uuid, |
| 893 | 899 | /// symmetric_and_asymmetric | transitive_and_functional | subclass_cycle |
| 894 | - /// | disjoint_with_ancestor | inherits_disjoint | |
| 900 | + /// | disjoint_with_ancestor | inherits_disjoint | inverse_of_itself | |
| 901 | + /// | inverse_not_mutual | sub_property_cycle | rules_disagree | |
| 895 | 902 | pub kind: String, |
| 903 | + /// `rules_disagree` 独有(0017):哪两条规则、撞在哪条公理上、几对、几个例子 | |
| 904 | + pub detail: serde_json::Value, | |
| 896 | 905 | /// 出问题那个对象的标签(类或谓词)。查不到就是它已经被删了 |
| 897 | 906 | pub subject_label: Option<String>, |
| 898 | 907 | /// 另一方:互斥的那个类 |
modified crates/utopia-reason/src/derive.rs +403 −2
| @@ -20,7 +20,7 @@ | ||
| 20 | 20 | //! 前提 A `[2020,2023)`、前提 B `[2022,∞)` → 派生 `[2022,2023)`。交集为空 |
| 21 | 21 | //! 就不推——两段没有重叠的时候,链本身在任何时刻都不成立。 |
| 22 | 22 | |
| 23 | -use crate::{Axioms, Edge, MAX_DEPTH}; | |
| 23 | +use crate::{Axioms, Edge, Kind, MAX_DEPTH}; | |
| 24 | 24 | use std::collections::{HashMap, HashSet}; |
| 25 | 25 | use uuid::Uuid; |
| 26 | 26 | |
| @@ -31,7 +31,7 @@ | ||
| 31 | 31 | /// ——悄悄截断会让「推完了」和「推了一部分」长得一模一样。 |
| 32 | 32 | pub const MAX_DERIVED_PER_PREDICATE: usize = 20_000; |
| 33 | 33 | |
| 34 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 34 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | |
| 35 | 35 | pub enum Rule { |
| 36 | 36 | /// `A p B` ∧ `B p C` ⟹ `A p C` |
| 37 | 37 | Transitive, |
| @@ -379,6 +379,248 @@ | ||
| 379 | 379 | Some(acc) |
| 380 | 380 | } |
| 381 | 381 | |
| 382 | +// ===================== 矛盾:派生撞上了什么(0017) ===================== | |
| 383 | + | |
| 384 | +/// 一条派生撞上了一条断言。 | |
| 385 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 386 | +pub struct Clash { | |
| 387 | + /// `Derivation::facts` 里的下标 | |
| 388 | + pub derived: usize, | |
| 389 | + /// 撞在哪条公理上:`Functional`(含 inverse_functional)、`Asymmetry`、`SelfLoop` | |
| 390 | + pub axiom: Kind, | |
| 391 | + /// 被撞的断言。自环没有对方,取派生的最后一条前提 | |
| 392 | + pub against: Uuid, | |
| 393 | +} | |
| 394 | + | |
| 395 | +/// 两条规则加在一起产出了互相矛盾的派生。 | |
| 396 | +/// | |
| 397 | +/// **按规则对聚合,不逐对报**:`ceo_of ⊑ works_at` 加 `works_at` functional,每个有 | |
| 398 | +/// 两个 ceo 的组织就撞一对——根子是那两条声明,逐对进队列只会淹掉 Review。 | |
| 399 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 400 | +pub struct RuleClash { | |
| 401 | + /// (声明所在的谓词, 规则种类),两条按 (谓词, 种类) 排过序,a ≤ b | |
| 402 | + pub a: (Uuid, Rule), | |
| 403 | + pub b: (Uuid, Rule), | |
| 404 | + pub axiom: Kind, | |
| 405 | + /// 互撞的派生对,按 `Derivation::facts` 的下标 | |
| 406 | + pub pairs: Vec<(usize, usize)>, | |
| 407 | +} | |
| 408 | + | |
| 409 | +/// 半开区间 `[from, to)`,两端可空 | |
| 410 | +type Span = (Option<i64>, Option<i64>); | |
| 411 | +/// (谓词, 一端) → 另一端的边:(另一端, 事实, 区间)。functional 两个方向各一份 | |
| 412 | +type ByEnd = HashMap<(Uuid, Uuid), Vec<(Uuid, Uuid, Span)>>; | |
| 413 | +/// 一条规则的身份:声明所在的谓词 + 规则种类 | |
| 414 | +type RuleSide = (Uuid, Rule); | |
| 415 | +/// 互撞的派生对,按 (规则 a, 规则 b, 撞在哪条公理上) 分组 | |
| 416 | +type Grouped = HashMap<(RuleSide, RuleSide, Kind), Vec<(usize, usize)>>; | |
| 417 | + | |
| 418 | +#[derive(Debug, Clone, Default, PartialEq, Eq)] | |
| 419 | +pub struct Contradictions { | |
| 420 | + pub with_assertions: Vec<Clash>, | |
| 421 | + pub between_derivations: Vec<RuleClash>, | |
| 422 | +} | |
| 423 | + | |
| 424 | +impl Contradictions { | |
| 425 | + /// 不该落地的派生下标:撞过断言的,和撞过别的派生的。**写图宁少勿错**(0002) | |
| 426 | + pub fn blocked(&self) -> HashSet<usize> { | |
| 427 | + let mut out: HashSet<usize> = self.with_assertions.iter().map(|c| c.derived).collect(); | |
| 428 | + for rc in &self.between_derivations { | |
| 429 | + for (i, j) in &rc.pairs { | |
| 430 | + out.insert(*i); | |
| 431 | + out.insert(*j); | |
| 432 | + } | |
| 433 | + } | |
| 434 | + out | |
| 435 | + } | |
| 436 | +} | |
| 437 | + | |
| 438 | +/// 拿公理量一遍派生:与断言撞的逐条列出,派生之间撞的按规则对聚合。 | |
| 439 | +/// | |
| 440 | +/// 只查四类——`functional`(含 inverse)、`asymmetric`、`irreflexive`——因为只有它们 | |
| 441 | +/// 能由**两条边**判出矛盾;传递环那类要走闭包,派生本身就是闭包的一部分,R0 对断言 | |
| 442 | +/// 查过就够了。functional 与 asymmetric 都要求**有效区间重叠**:Mira 走了 Devin | |
| 443 | +/// 接任,两条 `ceo_of` 区间不交,那是接任,不是矛盾。 | |
| 444 | +/// | |
| 445 | +/// 撞上断言的派生一律**不落地**(asserted > derived,硬性);这一步把「让路」这件事 | |
| 446 | +/// 从静默变成可见——0002 那张表里写了没做的那一行。 | |
| 447 | +pub fn contradictions( | |
| 448 | + derivation: &Derivation, | |
| 449 | + edges: &[TimedEdge], | |
| 450 | + axioms: &HashMap<Uuid, Axioms>, | |
| 451 | + spans: &HashMap<Uuid, (Option<i64>, Option<i64>)>, | |
| 452 | +) -> Contradictions { | |
| 453 | + // 断言的三份索引:(谓词, 主) → 宾;(谓词, 宾) → 主;(谓词, 主, 宾) → 边 | |
| 454 | + let mut by_ps: ByEnd = HashMap::new(); | |
| 455 | + let mut by_po: ByEnd = HashMap::new(); | |
| 456 | + let mut by_spo: HashMap<(Uuid, Uuid, Uuid), Vec<(Uuid, Span)>> = HashMap::new(); | |
| 457 | + for e in edges { | |
| 458 | + let span = (e.from, e.to); | |
| 459 | + let x = e.edge; | |
| 460 | + by_ps | |
| 461 | + .entry((x.predicate, x.subject)) | |
| 462 | + .or_default() | |
| 463 | + .push((x.object, x.fact, span)); | |
| 464 | + by_po | |
| 465 | + .entry((x.predicate, x.object)) | |
| 466 | + .or_default() | |
| 467 | + .push((x.subject, x.fact, span)); | |
| 468 | + by_spo | |
| 469 | + .entry((x.predicate, x.subject, x.object)) | |
| 470 | + .or_default() | |
| 471 | + .push((x.fact, span)); | |
| 472 | + } | |
| 473 | + | |
| 474 | + let mut out = Contradictions::default(); | |
| 475 | + // 派生的区间:与落库那一侧同一个函数算,算不出的(前提区间不交)本来就不会落 | |
| 476 | + let derived_spans: Vec<Option<Span>> = derivation | |
| 477 | + .facts | |
| 478 | + .iter() | |
| 479 | + .map(|d| validity(&d.premises, spans)) | |
| 480 | + .collect(); | |
| 481 | + | |
| 482 | + for (i, d) in derivation.facts.iter().enumerate() { | |
| 483 | + let Some(span) = derived_spans[i] else { | |
| 484 | + continue; | |
| 485 | + }; | |
| 486 | + let Some(ax) = axioms.get(&d.predicate) else { | |
| 487 | + continue; | |
| 488 | + }; | |
| 489 | + let Some(&last) = d.premises.last() else { | |
| 490 | + continue; | |
| 491 | + }; | |
| 492 | + if ax.irreflexive && d.subject == d.object { | |
| 493 | + out.with_assertions.push(Clash { | |
| 494 | + derived: i, | |
| 495 | + axiom: Kind::SelfLoop, | |
| 496 | + against: last, | |
| 497 | + }); | |
| 498 | + } | |
| 499 | + if ax.asymmetric { | |
| 500 | + if let Some(v) = by_spo.get(&(d.predicate, d.object, d.subject)) { | |
| 501 | + for (fact, sp) in v { | |
| 502 | + if overlap(span, *sp).is_some() { | |
| 503 | + out.with_assertions.push(Clash { | |
| 504 | + derived: i, | |
| 505 | + axiom: Kind::Asymmetry, | |
| 506 | + against: *fact, | |
| 507 | + }); | |
| 508 | + } | |
| 509 | + } | |
| 510 | + } | |
| 511 | + } | |
| 512 | + if ax.functional { | |
| 513 | + if let Some(v) = by_ps.get(&(d.predicate, d.subject)) { | |
| 514 | + for (obj, fact, sp) in v { | |
| 515 | + if *obj != d.object && overlap(span, *sp).is_some() { | |
| 516 | + out.with_assertions.push(Clash { | |
| 517 | + derived: i, | |
| 518 | + axiom: Kind::Functional, | |
| 519 | + against: *fact, | |
| 520 | + }); | |
| 521 | + } | |
| 522 | + } | |
| 523 | + } | |
| 524 | + } | |
| 525 | + if ax.inverse_functional { | |
| 526 | + if let Some(v) = by_po.get(&(d.predicate, d.object)) { | |
| 527 | + for (subj, fact, sp) in v { | |
| 528 | + if *subj != d.subject && overlap(span, *sp).is_some() { | |
| 529 | + out.with_assertions.push(Clash { | |
| 530 | + derived: i, | |
| 531 | + axiom: Kind::Functional, | |
| 532 | + against: *fact, | |
| 533 | + }); | |
| 534 | + } | |
| 535 | + } | |
| 536 | + } | |
| 537 | + } | |
| 538 | + } | |
| 539 | + | |
| 540 | + // 派生之间:同样三份索引,只不过键的是下标 | |
| 541 | + let mut d_ps: HashMap<(Uuid, Uuid), Vec<usize>> = HashMap::new(); | |
| 542 | + let mut d_po: HashMap<(Uuid, Uuid), Vec<usize>> = HashMap::new(); | |
| 543 | + let mut d_spo: HashMap<(Uuid, Uuid, Uuid), Vec<usize>> = HashMap::new(); | |
| 544 | + for (i, d) in derivation.facts.iter().enumerate() { | |
| 545 | + if derived_spans[i].is_none() { | |
| 546 | + continue; | |
| 547 | + } | |
| 548 | + d_ps.entry((d.predicate, d.subject)).or_default().push(i); | |
| 549 | + d_po.entry((d.predicate, d.object)).or_default().push(i); | |
| 550 | + d_spo | |
| 551 | + .entry((d.predicate, d.subject, d.object)) | |
| 552 | + .or_default() | |
| 553 | + .push(i); | |
| 554 | + } | |
| 555 | + let mut grouped: Grouped = HashMap::new(); | |
| 556 | + let mut note = |i: usize, j: usize, axiom: Kind| { | |
| 557 | + let (i, j) = if i < j { (i, j) } else { (j, i) }; | |
| 558 | + let ri = (derivation.facts[i].via, derivation.facts[i].rule); | |
| 559 | + let rj = (derivation.facts[j].via, derivation.facts[j].rule); | |
| 560 | + let (a, b) = if (ri.0, ri.1.as_str()) <= (rj.0, rj.1.as_str()) { | |
| 561 | + (ri, rj) | |
| 562 | + } else { | |
| 563 | + (rj, ri) | |
| 564 | + }; | |
| 565 | + grouped.entry((a, b, axiom)).or_default().push((i, j)); | |
| 566 | + }; | |
| 567 | + for (i, d) in derivation.facts.iter().enumerate() { | |
| 568 | + let Some(span) = derived_spans[i] else { | |
| 569 | + continue; | |
| 570 | + }; | |
| 571 | + let Some(ax) = axioms.get(&d.predicate) else { | |
| 572 | + continue; | |
| 573 | + }; | |
| 574 | + let overlapping = |j: usize| derived_spans[j].is_some_and(|s| overlap(span, s).is_some()); | |
| 575 | + if ax.asymmetric { | |
| 576 | + if let Some(v) = d_spo.get(&(d.predicate, d.object, d.subject)) { | |
| 577 | + for &j in v { | |
| 578 | + if j > i && overlapping(j) { | |
| 579 | + note(i, j, Kind::Asymmetry); | |
| 580 | + } | |
| 581 | + } | |
| 582 | + } | |
| 583 | + } | |
| 584 | + if ax.functional { | |
| 585 | + if let Some(v) = d_ps.get(&(d.predicate, d.subject)) { | |
| 586 | + for &j in v { | |
| 587 | + if j > i && derivation.facts[j].object != d.object && overlapping(j) { | |
| 588 | + note(i, j, Kind::Functional); | |
| 589 | + } | |
| 590 | + } | |
| 591 | + } | |
| 592 | + } | |
| 593 | + if ax.inverse_functional { | |
| 594 | + if let Some(v) = d_po.get(&(d.predicate, d.object)) { | |
| 595 | + for &j in v { | |
| 596 | + if j > i && derivation.facts[j].subject != d.subject && overlapping(j) { | |
| 597 | + note(i, j, Kind::Functional); | |
| 598 | + } | |
| 599 | + } | |
| 600 | + } | |
| 601 | + } | |
| 602 | + } | |
| 603 | + let mut rule_clashes: Vec<RuleClash> = grouped | |
| 604 | + .into_iter() | |
| 605 | + .map(|((a, b, axiom), mut pairs)| { | |
| 606 | + pairs.sort_unstable(); | |
| 607 | + pairs.dedup(); | |
| 608 | + RuleClash { a, b, axiom, pairs } | |
| 609 | + }) | |
| 610 | + .collect(); | |
| 611 | + // 输出排过序——这条路的价值有一半在确定性 | |
| 612 | + rule_clashes.sort_by(|x, y| { | |
| 613 | + (x.a.0, x.a.1.as_str(), x.b.0, x.b.1.as_str()).cmp(&( | |
| 614 | + y.a.0, | |
| 615 | + y.a.1.as_str(), | |
| 616 | + y.b.0, | |
| 617 | + y.b.1.as_str(), | |
| 618 | + )) | |
| 619 | + }); | |
| 620 | + out.between_derivations = rule_clashes; | |
| 621 | + out | |
| 622 | +} | |
| 623 | + | |
| 382 | 624 | #[cfg(test)] |
| 383 | 625 | mod tests { |
| 384 | 626 | use super::*; |
| @@ -796,4 +1038,163 @@ | ||
| 796 | 1038 | let d = derive(&[ep(P, 1, 1, 1)], &ax); |
| 797 | 1039 | assert!(d.facts.is_empty(), "`A p A` 的逆还是 `A p A`——自环不推"); |
| 798 | 1040 | } |
| 1041 | + | |
| 1042 | + // ---------- 矛盾(0017) ---------- | |
| 1043 | + | |
| 1044 | + /// 指定谓词的一条带区间的边 | |
| 1045 | + fn et(pred: Uuid, fact: u8, s: u8, o: u8, from: Option<i64>, to: Option<i64>) -> TimedEdge { | |
| 1046 | + TimedEdge { | |
| 1047 | + edge: Edge { | |
| 1048 | + fact: f(fact), | |
| 1049 | + predicate: pred, | |
| 1050 | + subject: n(s), | |
| 1051 | + object: n(o), | |
| 1052 | + }, | |
| 1053 | + from, | |
| 1054 | + to, | |
| 1055 | + } | |
| 1056 | + } | |
| 1057 | + | |
| 1058 | + fn spans_of(edges: &[TimedEdge]) -> HashMap<Uuid, (Option<i64>, Option<i64>)> { | |
| 1059 | + edges | |
| 1060 | + .iter() | |
| 1061 | + .map(|e| (e.edge.fact, (e.from, e.to))) | |
| 1062 | + .collect() | |
| 1063 | + } | |
| 1064 | + | |
| 1065 | + /// `ceo_of ⊑ works_at`,works_at functional:Mira 的 ceo_of 推出 works_at Acme, | |
| 1066 | + /// 而账本里说她 works_at Globex——派生撞上断言,指名道姓 | |
| 1067 | + #[test] | |
| 1068 | + fn a_derivation_that_breaks_functional_names_the_assertion_it_hit() { | |
| 1069 | + let ax = HashMap::from([ | |
| 1070 | + ( | |
| 1071 | + P, | |
| 1072 | + Axioms { | |
| 1073 | + sub_property_of: Some(Q), | |
| 1074 | + ..Default::default() | |
| 1075 | + }, | |
| 1076 | + ), | |
| 1077 | + ( | |
| 1078 | + Q, | |
| 1079 | + Axioms { | |
| 1080 | + functional: true, | |
| 1081 | + ..Default::default() | |
| 1082 | + }, | |
| 1083 | + ), | |
| 1084 | + ]); | |
| 1085 | + let edges = [ep(P, 1, 1, 2), ep(Q, 2, 1, 3)]; | |
| 1086 | + let d = derive(&edges, &ax); | |
| 1087 | + assert_eq!(d.facts.len(), 1); | |
| 1088 | + let c = contradictions(&d, &edges, &ax, &spans_of(&edges)); | |
| 1089 | + assert_eq!( | |
| 1090 | + c.with_assertions, | |
| 1091 | + vec![Clash { | |
| 1092 | + derived: 0, | |
| 1093 | + axiom: Kind::Functional, | |
| 1094 | + against: f(2) | |
| 1095 | + }] | |
| 1096 | + ); | |
| 1097 | + assert!(c.between_derivations.is_empty()); | |
| 1098 | + assert_eq!(c.blocked(), HashSet::from([0])); | |
| 1099 | + } | |
| 1100 | + | |
| 1101 | + /// 区间不交就不是矛盾:前任与继任 | |
| 1102 | + #[test] | |
| 1103 | + fn disjoint_intervals_are_succession_and_stay_silent() { | |
| 1104 | + let ax = HashMap::from([ | |
| 1105 | + ( | |
| 1106 | + P, | |
| 1107 | + Axioms { | |
| 1108 | + sub_property_of: Some(Q), | |
| 1109 | + ..Default::default() | |
| 1110 | + }, | |
| 1111 | + ), | |
| 1112 | + ( | |
| 1113 | + Q, | |
| 1114 | + Axioms { | |
| 1115 | + functional: true, | |
| 1116 | + ..Default::default() | |
| 1117 | + }, | |
| 1118 | + ), | |
| 1119 | + ]); | |
| 1120 | + let edges = [ | |
| 1121 | + et(P, 1, 1, 2, Some(10), Some(20)), | |
| 1122 | + et(Q, 2, 1, 3, Some(30), None), | |
| 1123 | + ]; | |
| 1124 | + let d = derive(&edges, &ax); | |
| 1125 | + let c = contradictions(&d, &edges, &ax, &spans_of(&edges)); | |
| 1126 | + assert!(c.with_assertions.is_empty(), "{c:?}"); | |
| 1127 | + } | |
| 1128 | + | |
| 1129 | + /// 对称与非对称:`A p B` 对称推出 `B p A`,而 p 又声明 asymmetric—— | |
| 1130 | + /// 每条断言都撞上自己的镜像 | |
| 1131 | + #[test] | |
| 1132 | + fn a_symmetric_derivation_hits_the_asymmetric_assertion() { | |
| 1133 | + let ax = HashMap::from([( | |
| 1134 | + P, | |
| 1135 | + Axioms { | |
| 1136 | + symmetric: true, | |
| 1137 | + asymmetric: true, | |
| 1138 | + ..Default::default() | |
| 1139 | + }, | |
| 1140 | + )]); | |
| 1141 | + let edges = [ep(P, 1, 1, 2)]; | |
| 1142 | + let d = derive(&edges, &ax); | |
| 1143 | + let c = contradictions(&d, &edges, &ax, &spans_of(&edges)); | |
| 1144 | + assert_eq!(c.with_assertions.len(), 1); | |
| 1145 | + assert_eq!(c.with_assertions[0].axiom, Kind::Asymmetry); | |
| 1146 | + assert_eq!(c.with_assertions[0].against, f(1)); | |
| 1147 | + } | |
| 1148 | + | |
| 1149 | + /// 两条派生互撞时按规则对聚合,而且都不落地 | |
| 1150 | + #[test] | |
| 1151 | + fn derivations_that_disagree_are_grouped_by_the_rules_that_made_them() { | |
| 1152 | + let ax = HashMap::from([ | |
| 1153 | + ( | |
| 1154 | + P, | |
| 1155 | + Axioms { | |
| 1156 | + sub_property_of: Some(Q), | |
| 1157 | + ..Default::default() | |
| 1158 | + }, | |
| 1159 | + ), | |
| 1160 | + ( | |
| 1161 | + Q, | |
| 1162 | + Axioms { | |
| 1163 | + functional: true, | |
| 1164 | + ..Default::default() | |
| 1165 | + }, | |
| 1166 | + ), | |
| 1167 | + ]); | |
| 1168 | + // 1 ceo_of 2 与 1 ceo_of 3:两条 works_at 由同一条规则推出,互相排斥 | |
| 1169 | + let edges = [ep(P, 1, 1, 2), ep(P, 2, 1, 3), ep(P, 3, 4, 5)]; | |
| 1170 | + let d = derive(&edges, &ax); | |
| 1171 | + assert_eq!(d.facts.len(), 3); | |
| 1172 | + let c = contradictions(&d, &edges, &ax, &spans_of(&edges)); | |
| 1173 | + assert!(c.with_assertions.is_empty()); | |
| 1174 | + assert_eq!(c.between_derivations.len(), 1); | |
| 1175 | + let rc = &c.between_derivations[0]; | |
| 1176 | + assert_eq!(rc.a, (P, Rule::SubProperty)); | |
| 1177 | + assert_eq!(rc.b, (P, Rule::SubProperty)); | |
| 1178 | + assert_eq!(rc.axiom, Kind::Functional); | |
| 1179 | + assert_eq!(rc.pairs.len(), 1); | |
| 1180 | + // 第三条(4 works_at 5)没跟谁撞,照常落地 | |
| 1181 | + assert_eq!(c.blocked().len(), 2); | |
| 1182 | + assert!(!c.blocked().contains(&2)); | |
| 1183 | + } | |
| 1184 | + | |
| 1185 | + /// 谓词上没有公理就没有矛盾可言 | |
| 1186 | + #[test] | |
| 1187 | + fn a_predicate_without_axioms_cannot_contradict() { | |
| 1188 | + let ax = HashMap::from([( | |
| 1189 | + P, | |
| 1190 | + Axioms { | |
| 1191 | + sub_property_of: Some(Q), | |
| 1192 | + ..Default::default() | |
| 1193 | + }, | |
| 1194 | + )]); | |
| 1195 | + let edges = [ep(P, 1, 1, 2), ep(Q, 2, 1, 3)]; | |
| 1196 | + let d = derive(&edges, &ax); | |
| 1197 | + let c = contradictions(&d, &edges, &ax, &spans_of(&edges)); | |
| 1198 | + assert_eq!(c, Contradictions::default()); | |
| 1199 | + } | |
| 799 | 1200 | } |
modified crates/utopia-reason/src/lib.rs +7 −1
| @@ -67,7 +67,7 @@ | ||
| 67 | 67 | pub path: Vec<Uuid>, |
| 68 | 68 | } |
| 69 | 69 | |
| 70 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 70 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | |
| 71 | 71 | pub enum Kind { |
| 72 | 72 | /// `A p A`,而 p 声明了 irreflexive |
| 73 | 73 | SelfLoop, |
| @@ -85,6 +85,11 @@ | ||
| 85 | 85 | /// 是为了与其它四类走同一条落库、清陈、裁决的路——left 与 right 同一条事实, |
| 86 | 86 | /// 与自反那类同款 |
| 87 | 87 | Signature, |
| 88 | + /// 一条派生撞上了一条断言(0017):推出来的 `A p B` 与账本里的某条断言在 p 的 | |
| 89 | + /// 公理上不能并存。派生不落地,这一行把它摆到人面前。`left` 是被撞的断言, | |
| 90 | + /// `right` 是派生的最后一条前提,`path` 是全部前提;推出来的三元组本身在 | |
| 91 | + /// `axiom_violations.detail` 里——它没有落库,没有 id 可指 | |
| 92 | + DerivedContradiction, | |
| 88 | 93 | } |
| 89 | 94 | |
| 90 | 95 | impl Kind { |
| @@ -95,6 +100,7 @@ | ||
| 95 | 100 | Kind::Cycle => "cycle", |
| 96 | 101 | Kind::Functional => "functional", |
| 97 | 102 | Kind::Signature => "signature", |
| 103 | + Kind::DerivedContradiction => "derived_contradiction", | |
| 98 | 104 | } |
| 99 | 105 | } |
| 100 | 106 | } |
modified crates/utopia-server/src/api/review_routes.rs +91 −3
| @@ -497,8 +497,11 @@ | ||
| 497 | 497 | |
| 498 | 498 | #[derive(Deserialize)] |
| 499 | 499 | pub struct DecideViolationReq { |
| 500 | - /// fact_retracted | axiom_relaxed | accepted | |
| 500 | + /// fact_retracted | fact_closed | axiom_relaxed | accepted | |
| 501 | 501 | pub resolution: String, |
| 502 | + /// `fact_closed` 必填:旧断言在哪一天结束 | |
| 503 | + #[serde(default)] | |
| 504 | + pub close_at: Option<chrono::DateTime<chrono::Utc>>, | |
| 502 | 505 | } |
| 503 | 506 | |
| 504 | 507 | /// 人裁决一处公理违规。 |
| @@ -518,16 +521,101 @@ | ||
| 518 | 521 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 519 | 522 | if !matches!( |
| 520 | 523 | req.resolution.as_str(), |
| 521 | - "fact_retracted" | "axiom_relaxed" | "accepted" | |
| 524 | + "fact_retracted" | "fact_closed" | "axiom_relaxed" | "accepted" | |
| 522 | 525 | ) { |
| 523 | 526 | return Err(utopia_core::AppError::invalid( |
| 524 | 527 | "bad_resolution", |
| 525 | - "resolution 只能是 fact_retracted、axiom_relaxed 或 accepted", | |
| 528 | + "resolution 只能是 fact_retracted、fact_closed、axiom_relaxed 或 accepted", | |
| 526 | 529 | ) |
| 527 | 530 | .into()); |
| 528 | 531 | } |
| 532 | + let row: Option<(String, Uuid)> = sqlx::query_as( | |
| 533 | + "SELECT kind, left_fact FROM axiom_violations | |
| 534 | + WHERE id = $1 AND kb_id = $2 AND status = 'open'", | |
| 535 | + ) | |
| 536 | + .bind(violation_id) | |
| 537 | + .bind(kb_id) | |
| 538 | + .fetch_optional(&state.pool) | |
| 539 | + .await | |
| 540 | + .map_err(utopia_core::AppError::Db)?; | |
| 541 | + let Some((kind, left)) = row else { | |
| 542 | + return Err(utopia_core::AppError::NotFound.into()); | |
| 543 | + }; | |
| 544 | + // 派生撞断言那一类(0017)的修法就在卡片上,端点替人执行:撤旧断言、或给它一个 | |
| 545 | + // 结束日期。其它几类仍只记决定——那些卡片上两条都是断言,撤哪条端点判不了 | |
| 546 | + let repaired = kind == "derived_contradiction"; | |
| 547 | + match (repaired, req.resolution.as_str()) { | |
| 548 | + (true, "fact_retracted") => { | |
| 549 | + let snap = fact_snapshot(&state, kb_id, left).await; | |
| 550 | + utopia_store::graph::reject_fact(&state.pool, kb_id, left).await?; | |
| 551 | + if let Some(d) = snap { | |
| 552 | + let _ = utopia_store::audit::record( | |
| 553 | + &state.pool, | |
| 554 | + Some(kb_id), | |
| 555 | + user.id, | |
| 556 | + "fact.reject", | |
| 557 | + "fact", | |
| 558 | + Some(left), | |
| 559 | + d, | |
| 560 | + ) | |
| 561 | + .await; | |
| 562 | + } | |
| 563 | + } | |
| 564 | + (true, "fact_closed") => { | |
| 565 | + let Some(at) = req.close_at else { | |
| 566 | + return Err(utopia_core::AppError::invalid( | |
| 567 | + "close_at_required", | |
| 568 | + "fact_closed 要给出结束日期", | |
| 569 | + ) | |
| 570 | + .into()); | |
| 571 | + }; | |
| 572 | + let open: Option<(Uuid,)> = sqlx::query_as( | |
| 573 | + "SELECT id FROM facts | |
| 574 | + WHERE id = $1 AND invalidated_at IS NULL AND valid_to IS NULL", | |
| 575 | + ) | |
| 576 | + .bind(left) | |
| 577 | + .fetch_optional(&state.pool) | |
| 578 | + .await | |
| 579 | + .map_err(utopia_core::AppError::Db)?; | |
| 580 | + if open.is_none() { | |
| 581 | + return Err(utopia_core::AppError::invalid( | |
| 582 | + "not_open", | |
| 583 | + "这条断言已有结束日期,或已被撤", | |
| 584 | + ) | |
| 585 | + .into()); | |
| 586 | + } | |
| 587 | + let snap = fact_snapshot(&state, kb_id, left).await; | |
| 588 | + utopia_store::temporal::close_superseded(&state.pool, left, at, "day").await?; | |
| 589 | + if let Some(mut d) = snap { | |
| 590 | + d["valid_to"] = json!(at.to_rfc3339()); | |
| 591 | + let _ = utopia_store::audit::record( | |
| 592 | + &state.pool, | |
| 593 | + Some(kb_id), | |
| 594 | + user.id, | |
| 595 | + "fact.close", | |
| 596 | + "fact", | |
| 597 | + Some(left), | |
| 598 | + d, | |
| 599 | + ) | |
| 600 | + .await; | |
| 601 | + } | |
| 602 | + } | |
| 603 | + (false, "fact_closed") => { | |
| 604 | + return Err(utopia_core::AppError::invalid( | |
| 605 | + "bad_resolution", | |
| 606 | + "fact_closed 只用于 derived_contradiction", | |
| 607 | + ) | |
| 608 | + .into()); | |
| 609 | + } | |
| 610 | + _ => {} | |
| 611 | + } | |
| 529 | 612 | utopia_store::reasoning::decide(&state.pool, kb_id, violation_id, &req.resolution, user.id) |
| 530 | 613 | .await?; |
| 614 | + // 路清了就让派生落地,人不必再去点一次「推一遍」。撤与闭合把断言挪开了, | |
| 615 | + // 认可则在 materialize 里放行 | |
| 616 | + if repaired { | |
| 617 | + utopia_store::reasoning::materialize(&state.pool, kb_id).await?; | |
| 618 | + } | |
| 531 | 619 | let _ = utopia_store::audit::record( |
| 532 | 620 | &state.pool, |
| 533 | 621 | Some(kb_id), |
modified crates/utopia-store/src/reasoning.rs +379 −74
| @@ -12,13 +12,14 @@ | ||
| 12 | 12 | //! 提案刷回待看,等于每跑一次就把人的否决抹掉一次。所以这里 `ON CONFLICT` |
| 13 | 13 | //! 什么都不做——已经在库里的那一行,无论 open 还是 resolved,都按原样留着。 |
| 14 | 14 | |
| 15 | +use serde_json::json; | |
| 15 | 16 | use sqlx::PgPool; |
| 16 | -use std::collections::HashMap; | |
| 17 | +use std::collections::{HashMap, HashSet}; | |
| 17 | 18 | use utopia_core::models::{AxiomViolation, DerivedFactView, OntologyDefect}; |
| 18 | 19 | /// 规则种类的字面量。用 &'static str 而不是枚举:它直接进 SQL 也直接做键 |
| 19 | 20 | type RuleKind = &'static str; |
| 20 | 21 | use utopia_core::AppResult; |
| 21 | -use utopia_reason::derive::TimedEdge; | |
| 22 | +use utopia_reason::derive::{Contradictions, Derivation, TimedEdge}; | |
| 22 | 23 | use utopia_reason::{check, Axioms, Edge, Kind, Violation}; |
| 23 | 24 | use uuid::Uuid; |
| 24 | 25 | |
| @@ -35,37 +36,17 @@ | ||
| 35 | 36 | pub inserted: usize, |
| 36 | 37 | /// 清掉的陈旧 open 行 |
| 37 | 38 | pub cleared: usize, |
| 39 | + /// 派生撞上断言的条数(0017),已含在 `found` 里 | |
| 40 | + pub contradictions: usize, | |
| 41 | + /// 撞上单谓词上限、没进队列的矛盾条数。**不为零时说明根子在规则**: | |
| 42 | + /// 一条谓词上上百条派生都撞了,逐条看是没有意义的 | |
| 43 | + pub contradictions_capped: usize, | |
| 44 | + /// 互撞的规则对数——进 `ontology_defects`,不进这张表 | |
| 45 | + pub rules_disagree: usize, | |
| 38 | 46 | } |
| 39 | 47 | |
| 40 | -/// 取这个库里所有能参与检查的边。 | |
| 41 | -/// | |
| 42 | -/// 三个过滤条件都是必要的: | |
| 43 | -/// | |
| 44 | -/// - `invalidated_at IS NULL`——被推翻的事实不该再报矛盾,它已经不是我们的断言了 | |
| 45 | -/// - `predicate_id IS NOT NULL`——没有谓词就没有公理可依(见 `facts.predicate_id`) | |
| 46 | -/// - `object_id IS NOT NULL`——属性事实的宾语是字面值,公理谈的是实体之间的关系 | |
| 47 | -async fn edges(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Edge>> { | |
| 48 | - let rows: Vec<(Uuid, Uuid, Uuid, Uuid)> = sqlx::query_as( | |
| 49 | - "SELECT id, predicate_id, subject_id, object_id | |
| 50 | - FROM facts | |
| 51 | - WHERE kb_id = $1 | |
| 52 | - AND invalidated_at IS NULL | |
| 53 | - AND predicate_id IS NOT NULL | |
| 54 | - AND object_id IS NOT NULL", | |
| 55 | - ) | |
| 56 | - .bind(kb_id) | |
| 57 | - .fetch_all(pool) | |
| 58 | - .await?; | |
| 59 | - Ok(rows | |
| 60 | - .into_iter() | |
| 61 | - .map(|(fact, predicate, subject, object)| Edge { | |
| 62 | - fact, | |
| 63 | - predicate, | |
| 64 | - subject, | |
| 65 | - object, | |
| 66 | - }) | |
| 67 | - .collect()) | |
| 68 | -} | |
| 48 | +/// 单个谓词上进队列的矛盾上限(0017 §1)。超出的部分只计数。 | |
| 49 | +const MAX_CLASHES_PER_PREDICATE: usize = 50; | |
| 69 | 50 | |
| 70 | 51 | /// 取这个库的谓词公理。 |
| 71 | 52 | /// |
| @@ -229,7 +210,8 @@ | ||
| 229 | 210 | |
| 230 | 211 | /// 跑一遍检查,把结果落库。 |
| 231 | 212 | pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> { |
| 232 | - let edges = edges(pool, kb_id).await?; | |
| 213 | + let (timed, spans, _) = timed_edges(pool, kb_id).await?; | |
| 214 | + let edges: Vec<Edge> = timed.iter().map(|t| t.edge).collect(); | |
| 233 | 215 | let axioms = axioms(pool, kb_id).await?; |
| 234 | 216 | let mut violations = check(&edges, &axioms); |
| 235 | 217 | // 第五类不在纯逻辑引擎里:它要看实体的类型与谓词的 domain / range,那是库里的 |
| @@ -243,10 +225,63 @@ | ||
| 243 | 225 | }); |
| 244 | 226 | } |
| 245 | 227 | |
| 228 | + // 第六类(0017):推出来却落不了地的派生。与 `materialize` 用同一个函数算, | |
| 229 | + // 所以这里报的正是那边拦下的——两边各算一套的话,队列会跟图对不上 | |
| 230 | + let derivation = utopia_reason::derive::derive(&timed, &axioms); | |
| 231 | + let clashes = utopia_reason::derive::contradictions(&derivation, &timed, &axioms, &spans); | |
| 232 | + let names = names_for(pool, &derivation, &clashes).await?; | |
| 233 | + let mut details: HashMap<(Uuid, Uuid), serde_json::Value> = HashMap::new(); | |
| 234 | + let mut per_pred: HashMap<Uuid, usize> = HashMap::new(); | |
| 235 | + let mut contradictions_capped = 0usize; | |
| 236 | + for c in &clashes.with_assertions { | |
| 237 | + let d = &derivation.facts[c.derived]; | |
| 238 | + let Some(&last) = d.premises.last() else { | |
| 239 | + continue; | |
| 240 | + }; | |
| 241 | + let key = (c.against, last); | |
| 242 | + if details.contains_key(&key) { | |
| 243 | + continue; | |
| 244 | + } | |
| 245 | + let n = per_pred.entry(d.predicate).or_default(); | |
| 246 | + if *n >= MAX_CLASHES_PER_PREDICATE { | |
| 247 | + contradictions_capped += 1; | |
| 248 | + continue; | |
| 249 | + } | |
| 250 | + *n += 1; | |
| 251 | + let span = utopia_reason::derive::validity(&d.premises, &spans); | |
| 252 | + details.insert( | |
| 253 | + key, | |
| 254 | + json!({ | |
| 255 | + "axiom": c.axiom.as_str(), | |
| 256 | + "rule": d.rule.as_str(), | |
| 257 | + "via": d.via, | |
| 258 | + "via_label": names.predicate(d.via), | |
| 259 | + "subject_id": d.subject, | |
| 260 | + "subject": names.entity(d.subject), | |
| 261 | + "predicate_id": d.predicate, | |
| 262 | + "predicate": names.predicate(d.predicate), | |
| 263 | + "object_id": d.object, | |
| 264 | + "object": names.entity(d.object), | |
| 265 | + "valid_from": span.and_then(|s| s.0).map(|t| stamp(t).to_rfc3339()), | |
| 266 | + "valid_to": span.and_then(|s| s.1).map(|t| stamp(t).to_rfc3339()), | |
| 267 | + "premises": d.premises, | |
| 268 | + }), | |
| 269 | + ); | |
| 270 | + violations.push(Violation { | |
| 271 | + kind: Kind::DerivedContradiction, | |
| 272 | + left: c.against, | |
| 273 | + right: last, | |
| 274 | + path: d.premises.clone(), | |
| 275 | + }); | |
| 276 | + } | |
| 277 | + | |
| 246 | 278 | let mut report = Report { |
| 247 | 279 | edges: edges.len(), |
| 248 | 280 | predicates_with_axioms: axioms.len(), |
| 249 | 281 | found: violations.len(), |
| 282 | + contradictions: details.len(), | |
| 283 | + contradictions_capped, | |
| 284 | + rules_disagree: clashes.between_derivations.len(), | |
| 250 | 285 | ..Default::default() |
| 251 | 286 | }; |
| 252 | 287 | |
| @@ -261,9 +296,13 @@ | ||
| 261 | 296 | right, |
| 262 | 297 | path, |
| 263 | 298 | } = v; |
| 299 | + let detail = details | |
| 300 | + .get(&(*left, *right)) | |
| 301 | + .cloned() | |
| 302 | + .unwrap_or_else(|| json!({})); | |
| 264 | 303 | let id: Option<(Uuid,)> = sqlx::query_as( |
| 265 | - "INSERT INTO axiom_violations (id, kb_id, kind, left_fact, right_fact, path) | |
| 266 | - VALUES ($1, $2, $3, $4, $5, $6) | |
| 304 | + "INSERT INTO axiom_violations (id, kb_id, kind, left_fact, right_fact, path, detail) | |
| 305 | + VALUES ($1, $2, $3, $4, $5, $6, $7) | |
| 267 | 306 | ON CONFLICT (kb_id, kind, left_fact, right_fact) DO NOTHING |
| 268 | 307 | RETURNING id", |
| 269 | 308 | ) |
| @@ -273,6 +312,7 @@ | ||
| 273 | 312 | .bind(left) |
| 274 | 313 | .bind(right) |
| 275 | 314 | .bind(path) |
| 315 | + .bind(&detail) | |
| 276 | 316 | .fetch_optional(&mut *tx) |
| 277 | 317 | .await?; |
| 278 | 318 | if id.is_some() { |
| @@ -303,10 +343,144 @@ | ||
| 303 | 343 | .execute(&mut *tx) |
| 304 | 344 | .await?; |
| 305 | 345 | report.cleared = cleared.rows_affected() as usize; |
| 346 | + | |
| 347 | + // 派生之间互撞的按规则对进 `ontology_defects`——根子是那两条声明,不是哪条事实。 | |
| 348 | + // 同一对谓词上可能有几种撞法(functional 与 asymmetric 各撞各的),唯一键只到 | |
| 349 | + // 谓词对,所以合成一行,几种撞法都写进 detail | |
| 350 | + let mut by_pair: HashMap<(Uuid, Uuid), Vec<serde_json::Value>> = HashMap::new(); | |
| 351 | + let mut order: Vec<(Uuid, Uuid)> = Vec::new(); | |
| 352 | + for rc in &clashes.between_derivations { | |
| 353 | + let triple = |i: usize| { | |
| 354 | + let d = &derivation.facts[i]; | |
| 355 | + format!( | |
| 356 | + "{} · {} · {}", | |
| 357 | + names.entity(d.subject), | |
| 358 | + names.predicate(d.predicate), | |
| 359 | + names.entity(d.object) | |
| 360 | + ) | |
| 361 | + }; | |
| 362 | + let examples: Vec<serde_json::Value> = rc | |
| 363 | + .pairs | |
| 364 | + .iter() | |
| 365 | + .take(3) | |
| 366 | + .map(|(i, j)| json!([triple(*i), triple(*j)])) | |
| 367 | + .collect(); | |
| 368 | + let key = (rc.a.0, rc.b.0); | |
| 369 | + if !by_pair.contains_key(&key) { | |
| 370 | + order.push(key); | |
| 371 | + } | |
| 372 | + by_pair.entry(key).or_default().push(json!({ | |
| 373 | + "rule_a": rc.a.1.as_str(), | |
| 374 | + "via_a": names.predicate(rc.a.0), | |
| 375 | + "rule_b": rc.b.1.as_str(), | |
| 376 | + "via_b": names.predicate(rc.b.0), | |
| 377 | + "axiom": rc.axiom.as_str(), | |
| 378 | + "count": rc.pairs.len(), | |
| 379 | + "examples": examples, | |
| 380 | + })); | |
| 381 | + } | |
| 382 | + let mut fresh_defects: Vec<Uuid> = Vec::with_capacity(order.len()); | |
| 383 | + for key in order { | |
| 384 | + let rules = by_pair.remove(&key).unwrap_or_default(); | |
| 385 | + let count: usize = rules | |
| 386 | + .iter() | |
| 387 | + .map(|r| r["count"].as_u64().unwrap_or(0) as usize) | |
| 388 | + .sum(); | |
| 389 | + // 已经有人认可过的那一行保持 resolved,只刷 detail:0017 说认可之后不再报 | |
| 390 | + let (id,): (Uuid,) = sqlx::query_as( | |
| 391 | + "INSERT INTO ontology_defects (id, kb_id, kind, subject, other, path, detail) | |
| 392 | + VALUES ($1, $2, 'rules_disagree', $3, $4, '{}', $5) | |
| 393 | + ON CONFLICT (kb_id, kind, subject, other) DO UPDATE SET detail = EXCLUDED.detail | |
| 394 | + RETURNING id", | |
| 395 | + ) | |
| 396 | + .bind(Uuid::now_v7()) | |
| 397 | + .bind(kb_id) | |
| 398 | + .bind(key.0) | |
| 399 | + .bind(key.1) | |
| 400 | + .bind(json!({ "count": count, "rules": rules })) | |
| 401 | + .fetch_one(&mut *tx) | |
| 402 | + .await?; | |
| 403 | + fresh_defects.push(id); | |
| 404 | + } | |
| 405 | + sqlx::query( | |
| 406 | + "DELETE FROM ontology_defects | |
| 407 | + WHERE kb_id = $1 AND kind = 'rules_disagree' AND status = 'open' | |
| 408 | + AND NOT (id = ANY($2))", | |
| 409 | + ) | |
| 410 | + .bind(kb_id) | |
| 411 | + .bind(&fresh_defects) | |
| 412 | + .execute(&mut *tx) | |
| 413 | + .await?; | |
| 306 | 414 | tx.commit().await?; |
| 307 | 415 | Ok(report) |
| 308 | 416 | } |
| 309 | 417 | |
| 418 | +/// 矛盾要写成人能读的话,而派生没有落库、没有文本可查——名字在这里补。 | |
| 419 | +struct Names { | |
| 420 | + entities: HashMap<Uuid, String>, | |
| 421 | + predicates: HashMap<Uuid, String>, | |
| 422 | +} | |
| 423 | + | |
| 424 | +impl Names { | |
| 425 | + fn entity(&self, id: Uuid) -> String { | |
| 426 | + self.entities | |
| 427 | + .get(&id) | |
| 428 | + .cloned() | |
| 429 | + .unwrap_or_else(|| "?".into()) | |
| 430 | + } | |
| 431 | + fn predicate(&self, id: Uuid) -> String { | |
| 432 | + self.predicates | |
| 433 | + .get(&id) | |
| 434 | + .cloned() | |
| 435 | + .unwrap_or_else(|| "?".into()) | |
| 436 | + } | |
| 437 | +} | |
| 438 | + | |
| 439 | +async fn names_for( | |
| 440 | + pool: &PgPool, | |
| 441 | + derivation: &Derivation, | |
| 442 | + clashes: &Contradictions, | |
| 443 | +) -> AppResult<Names> { | |
| 444 | + let mut ents: HashSet<Uuid> = HashSet::new(); | |
| 445 | + let mut preds: HashSet<Uuid> = HashSet::new(); | |
| 446 | + let mut want = |i: usize| { | |
| 447 | + let d = &derivation.facts[i]; | |
| 448 | + ents.insert(d.subject); | |
| 449 | + ents.insert(d.object); | |
| 450 | + preds.insert(d.predicate); | |
| 451 | + preds.insert(d.via); | |
| 452 | + }; | |
| 453 | + for c in &clashes.with_assertions { | |
| 454 | + want(c.derived); | |
| 455 | + } | |
| 456 | + for rc in &clashes.between_derivations { | |
| 457 | + for (i, j) in rc.pairs.iter().take(3) { | |
| 458 | + want(*i); | |
| 459 | + want(*j); | |
| 460 | + } | |
| 461 | + } | |
| 462 | + for rc in &clashes.between_derivations { | |
| 463 | + preds.insert(rc.a.0); | |
| 464 | + preds.insert(rc.b.0); | |
| 465 | + } | |
| 466 | + let ents: Vec<Uuid> = ents.into_iter().collect(); | |
| 467 | + let preds: Vec<Uuid> = preds.into_iter().collect(); | |
| 468 | + let entities: Vec<(Uuid, String)> = | |
| 469 | + sqlx::query_as("SELECT id, canonical_name FROM entities WHERE id = ANY($1)") | |
| 470 | + .bind(&ents) | |
| 471 | + .fetch_all(pool) | |
| 472 | + .await?; | |
| 473 | + let predicates: Vec<(Uuid, String)> = | |
| 474 | + sqlx::query_as("SELECT id, label FROM relation_types WHERE id = ANY($1)") | |
| 475 | + .bind(&preds) | |
| 476 | + .fetch_all(pool) | |
| 477 | + .await?; | |
| 478 | + Ok(Names { | |
| 479 | + entities: entities.into_iter().collect(), | |
| 480 | + predicates: predicates.into_iter().collect(), | |
| 481 | + }) | |
| 482 | +} | |
| 483 | + | |
| 310 | 484 | /// Review 页要看的:还没人表态的违规,连同两条事实的三元组文本。 |
| 311 | 485 | /// |
| 312 | 486 | /// 展开成文本在 SQL 里做而不是回来再查一遍:一页几十条,每条两个三元组, |
| @@ -336,10 +510,20 @@ | ||
| 336 | 510 | v.left_fact, l.text AS left_text, |
| 337 | 511 | v.right_fact, rt.text AS right_text, |
| 338 | 512 | coalesce(array_length(v.path, 1), 0) AS path_len, |
| 339 | - v.detected_at | |
| 513 | + v.detected_at, v.detail, | |
| 514 | + lf.valid_to IS NULL AS left_open, | |
| 515 | + lf.confidence AS left_confidence, | |
| 516 | + EXISTS ( | |
| 517 | + SELECT 1 FROM entities e | |
| 518 | + JOIN entities x ON x.kb_id = e.kb_id AND x.id <> e.id | |
| 519 | + AND x.merged_into IS NULL | |
| 520 | + AND lower(x.canonical_name) = lower(e.canonical_name) | |
| 521 | + WHERE e.id IN (lf.subject_id, lf.object_id) | |
| 522 | + ) AS same_name_peers | |
| 340 | 523 | FROM axiom_violations v |
| 341 | 524 | JOIN triple l ON l.id = v.left_fact |
| 342 | 525 | JOIN triple rt ON rt.id = v.right_fact |
| 526 | + JOIN facts lf ON lf.id = v.left_fact | |
| 343 | 527 | WHERE v.kb_id = $1 AND v.status = 'open' |
| 344 | 528 | ORDER BY v.detected_at DESC |
| 345 | 529 | LIMIT $2 OFFSET $3", |
| @@ -348,7 +532,60 @@ | ||
| 348 | 532 | .bind(limit) |
| 349 | 533 | .bind(offset) |
| 350 | 534 | .fetch_all(pool) |
| 351 | - .await?) | |
| 535 | + .await? | |
| 536 | + .into_iter() | |
| 537 | + .map(|r: ViolationRow| { | |
| 538 | + let hint = if r.kind == "derived_contradiction" { | |
| 539 | + hint_for(&r).map(String::from) | |
| 540 | + } else { | |
| 541 | + None | |
| 542 | + }; | |
| 543 | + AxiomViolation { | |
| 544 | + id: r.id, | |
| 545 | + kind: r.kind, | |
| 546 | + predicate: r.predicate, | |
| 547 | + left_fact: r.left_fact, | |
| 548 | + left_text: r.left_text, | |
| 549 | + right_fact: r.right_fact, | |
| 550 | + right_text: r.right_text, | |
| 551 | + path_len: r.path_len, | |
| 552 | + detected_at: r.detected_at, | |
| 553 | + detail: r.detail, | |
| 554 | + hint, | |
| 555 | + } | |
| 556 | + }) | |
| 557 | + .collect()) | |
| 558 | +} | |
| 559 | + | |
| 560 | +#[derive(sqlx::FromRow)] | |
| 561 | +struct ViolationRow { | |
| 562 | + id: Uuid, | |
| 563 | + kind: String, | |
| 564 | + predicate: Option<String>, | |
| 565 | + left_fact: Uuid, | |
| 566 | + left_text: String, | |
| 567 | + right_fact: Uuid, | |
| 568 | + right_text: String, | |
| 569 | + path_len: i32, | |
| 570 | + detected_at: chrono::DateTime<chrono::Utc>, | |
| 571 | + detail: serde_json::Value, | |
| 572 | + left_open: bool, | |
| 573 | + left_confidence: f32, | |
| 574 | + same_name_peers: bool, | |
| 575 | +} | |
| 576 | + | |
| 577 | +/// 线索按最常见的错法排(0017 §2):旧断言没写结束日期、两个同名实体、抽取本来就 | |
| 578 | +/// 没把握。一次只给一条——三条并列等于没给 | |
| 579 | +fn hint_for(r: &ViolationRow) -> Option<&'static str> { | |
| 580 | + if r.left_open && r.detail.get("valid_from").is_some_and(|v| !v.is_null()) { | |
| 581 | + Some("stale") | |
| 582 | + } else if r.same_name_peers { | |
| 583 | + Some("duplicate") | |
| 584 | + } else if r.left_confidence < 0.75 { | |
| 585 | + Some("unsure") | |
| 586 | + } else { | |
| 587 | + None | |
| 588 | + } | |
| 352 | 589 | } |
| 353 | 590 | |
| 354 | 591 | /// 人裁决一处违规。 |
| @@ -463,7 +700,8 @@ | ||
| 463 | 700 | } |
| 464 | 701 | let cleared = sqlx::query( |
| 465 | 702 | "DELETE FROM ontology_defects |
| 466 | - WHERE kb_id = $1 AND status = 'open' AND NOT (id = ANY($2))", | |
| 703 | + WHERE kb_id = $1 AND status = 'open' AND kind <> 'rules_disagree' | |
| 704 | + AND NOT (id = ANY($2))", | |
| 467 | 705 | ) |
| 468 | 706 | .bind(kb_id) |
| 469 | 707 | .bind(&fresh) |
| @@ -497,6 +735,84 @@ | ||
| 497 | 735 | /// 而下游靠它推出的 `employs` 反倒进了库——一条派生的前提凭空消失。 |
| 498 | 736 | /// 数出来,别再让它静默一次 |
| 499 | 737 | pub unruled: usize, |
| 738 | + /// 推出来了却撞上断言或别的派生、这一轮拦下没落的(0017)。**拦下的每一条 | |
| 739 | + /// 都在 Review 里有对应的一行**——`run` 与这里用同一个函数算 | |
| 740 | + pub blocked: usize, | |
| 741 | +} | |
| 742 | + | |
| 743 | +/// 一次取数,三样东西:带区间的边、每条事实的区间、精度与置信度。 | |
| 744 | +/// `run` 与 `materialize` 共用——两边看到的边必须是同一批 | |
| 745 | +type TimedEdges = ( | |
| 746 | + Vec<TimedEdge>, | |
| 747 | + HashMap<Uuid, (Option<i64>, Option<i64>)>, | |
| 748 | + HashMap<Uuid, (Option<String>, Option<String>, f32)>, | |
| 749 | +); | |
| 750 | + | |
| 751 | +async fn timed_edges(pool: &PgPool, kb_id: Uuid) -> AppResult<TimedEdges> { | |
| 752 | + // 输入**只有断言**。派生住在另一张表,所以这里连过滤都不必写——那正是 | |
| 753 | + // 分表买到的东西:忘了排除的后果是推不出东西,不是把自己的输出喂回自己 | |
| 754 | + let rows: Vec<EdgeRow> = sqlx::query_as( | |
| 755 | + "SELECT id, predicate_id, subject_id, object_id, | |
| 756 | + valid_from, valid_to, valid_from_precision, valid_to_precision, confidence | |
| 757 | + FROM facts | |
| 758 | + WHERE kb_id = $1 | |
| 759 | + AND invalidated_at IS NULL | |
| 760 | + AND predicate_id IS NOT NULL | |
| 761 | + AND object_id IS NOT NULL", | |
| 762 | + ) | |
| 763 | + .bind(kb_id) | |
| 764 | + .fetch_all(pool) | |
| 765 | + .await?; | |
| 766 | + | |
| 767 | + let mut edges = Vec::with_capacity(rows.len()); | |
| 768 | + let mut meta: HashMap<Uuid, (Option<String>, Option<String>, f32)> = HashMap::new(); | |
| 769 | + let mut spans: HashMap<Uuid, (Option<i64>, Option<i64>)> = HashMap::new(); | |
| 770 | + for (id, pred, subj, obj, from, to, fp, tp, conf) in rows { | |
| 771 | + let (f, t) = (from.map(|x| x.timestamp()), to.map(|x| x.timestamp())); | |
| 772 | + edges.push(TimedEdge { | |
| 773 | + edge: Edge { | |
| 774 | + fact: id, | |
| 775 | + predicate: pred, | |
| 776 | + subject: subj, | |
| 777 | + object: obj, | |
| 778 | + }, | |
| 779 | + from: f, | |
| 780 | + to: t, | |
| 781 | + }); | |
| 782 | + spans.insert(id, (f, t)); | |
| 783 | + meta.insert(id, (fp, tp, conf)); | |
| 784 | + } | |
| 785 | + Ok((edges, spans, meta)) | |
| 786 | +} | |
| 787 | + | |
| 788 | +/// 人认可过并存的(派生三元组, 断言)对:这些派生下一轮照常落地(0017 §2)。 | |
| 789 | +async fn accepted_clashes( | |
| 790 | + pool: &PgPool, | |
| 791 | + kb_id: Uuid, | |
| 792 | +) -> AppResult<HashSet<(Uuid, Uuid, Uuid, Uuid)>> { | |
| 793 | + let rows: Vec<(Uuid, serde_json::Value)> = sqlx::query_as( | |
| 794 | + "SELECT left_fact, detail FROM axiom_violations | |
| 795 | + WHERE kb_id = $1 AND kind = 'derived_contradiction' AND resolution = 'accepted'", | |
| 796 | + ) | |
| 797 | + .bind(kb_id) | |
| 798 | + .fetch_all(pool) | |
| 799 | + .await?; | |
| 800 | + let id = |v: &serde_json::Value, k: &str| { | |
| 801 | + v.get(k) | |
| 802 | + .and_then(|x| x.as_str()) | |
| 803 | + .and_then(|s| s.parse::<Uuid>().ok()) | |
| 804 | + }; | |
| 805 | + Ok(rows | |
| 806 | + .into_iter() | |
| 807 | + .filter_map(|(against, d)| { | |
| 808 | + Some(( | |
| 809 | + id(&d, "subject_id")?, | |
| 810 | + id(&d, "predicate_id")?, | |
| 811 | + id(&d, "object_id")?, | |
| 812 | + against, | |
| 813 | + )) | |
| 814 | + }) | |
| 815 | + .collect()) | |
| 500 | 816 | } |
| 501 | 817 | |
| 502 | 818 | /// 派生事实的身份:三元组 + 区间。 |
| @@ -610,52 +926,40 @@ | ||
| 610 | 926 | pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport> { |
| 611 | 927 | let ax = axioms(pool, kb_id).await?; |
| 612 | 928 | let rules = compile_rules(pool, kb_id, &ax).await?; |
| 613 | - | |
| 614 | - // 输入**只有断言**。派生住在另一张表,所以这里连过滤都不必写——那正是 | |
| 615 | - // 分表买到的东西:忘了排除的后果是推不出东西,不是把自己的输出喂回自己 | |
| 616 | - let rows: Vec<EdgeRow> = sqlx::query_as( | |
| 617 | - "SELECT id, predicate_id, subject_id, object_id, | |
| 618 | - valid_from, valid_to, valid_from_precision, valid_to_precision, confidence | |
| 619 | - FROM facts | |
| 620 | - WHERE kb_id = $1 | |
| 621 | - AND invalidated_at IS NULL | |
| 622 | - AND predicate_id IS NOT NULL | |
| 623 | - AND object_id IS NOT NULL", | |
| 624 | - ) | |
| 625 | - .bind(kb_id) | |
| 626 | - .fetch_all(pool) | |
| 627 | - .await?; | |
| 628 | - | |
| 629 | - let mut edges = Vec::with_capacity(rows.len()); | |
| 630 | - let mut meta: HashMap<Uuid, (Option<String>, Option<String>, f32)> = HashMap::new(); | |
| 631 | - let mut spans: HashMap<Uuid, (Option<i64>, Option<i64>)> = HashMap::new(); | |
| 632 | - for (id, pred, subj, obj, from, to, fp, tp, conf) in rows { | |
| 633 | - let (f, t) = (from.map(|x| x.timestamp()), to.map(|x| x.timestamp())); | |
| 634 | - edges.push(TimedEdge { | |
| 635 | - edge: Edge { | |
| 636 | - fact: id, | |
| 637 | - predicate: pred, | |
| 638 | - subject: subj, | |
| 639 | - object: obj, | |
| 640 | - }, | |
| 641 | - from: f, | |
| 642 | - to: t, | |
| 643 | - }); | |
| 644 | - spans.insert(id, (f, t)); | |
| 645 | - meta.insert(id, (fp, tp, conf)); | |
| 646 | - } | |
| 929 | + let (edges, spans, meta) = timed_edges(pool, kb_id).await?; | |
| 647 | 930 | |
| 648 | 931 | let derivation = utopia_reason::derive::derive(&edges, &ax); |
| 932 | + // asserted > derived 是硬性的(0002):撞上断言的派生不落地。人认可过并存的 | |
| 933 | + // 除外;派生之间互撞的两边都不落,认可与否只影响报不报(0017) | |
| 934 | + let clashes = utopia_reason::derive::contradictions(&derivation, &edges, &ax, &spans); | |
| 935 | + let accepted = accepted_clashes(pool, kb_id).await?; | |
| 936 | + let mut blocked: HashSet<usize> = HashSet::new(); | |
| 937 | + for c in &clashes.with_assertions { | |
| 938 | + let d = &derivation.facts[c.derived]; | |
| 939 | + if !accepted.contains(&(d.subject, d.predicate, d.object, c.against)) { | |
| 940 | + blocked.insert(c.derived); | |
| 941 | + } | |
| 942 | + } | |
| 943 | + for rc in &clashes.between_derivations { | |
| 944 | + for (i, j) in &rc.pairs { | |
| 945 | + blocked.insert(*i); | |
| 946 | + blocked.insert(*j); | |
| 947 | + } | |
| 948 | + } | |
| 649 | 949 | let mut report = DeriveReport { |
| 650 | 950 | rules: rules.len(), |
| 651 | 951 | edges: edges.len(), |
| 652 | 952 | derived: derivation.facts.len(), |
| 653 | 953 | capped: derivation.capped.len(), |
| 954 | + blocked: blocked.len(), | |
| 654 | 955 | ..Default::default() |
| 655 | 956 | }; |
| 656 | 957 | |
| 657 | 958 | let mut wanted: HashMap<DerivedKey, &utopia_reason::derive::Derived> = HashMap::new(); |
| 658 | - for d in &derivation.facts { | |
| 959 | + for (i, d) in derivation.facts.iter().enumerate() { | |
| 960 | + if blocked.contains(&i) { | |
| 961 | + continue; | |
| 962 | + } | |
| 659 | 963 | let Some((from, to)) = utopia_reason::derive::validity(&d.premises, &spans) else { |
| 660 | 964 | continue; |
| 661 | 965 | }; |
| @@ -776,9 +1080,9 @@ | ||
| 776 | 1080 | offset: i64, |
| 777 | 1081 | ) -> AppResult<Vec<OntologyDefect>> { |
| 778 | 1082 | Ok(sqlx::query_as( |
| 779 | - "SELECT d.id, d.kind, | |
| 1083 | + "SELECT d.id, d.kind, d.detail, | |
| 780 | 1084 | COALESCE(st.label, sr.label) AS subject_label, |
| 781 | - ot.label AS other_label, | |
| 1085 | + COALESCE(ot.label, orr.label) AS other_label, | |
| 782 | 1086 | COALESCE( |
| 783 | 1087 | (SELECT array_agg(t.label ORDER BY x.ord) |
| 784 | 1088 | FROM unnest(d.path) WITH ORDINALITY AS x(id, ord) |
| @@ -790,6 +1094,7 @@ | ||
| 790 | 1094 | LEFT JOIN entity_types st ON st.id = d.subject |
| 791 | 1095 | LEFT JOIN relation_types sr ON sr.id = d.subject |
| 792 | 1096 | LEFT JOIN entity_types ot ON ot.id = d.other |
| 1097 | + LEFT JOIN relation_types orr ON orr.id = d.other | |
| 793 | 1098 | WHERE d.kb_id = $1 AND d.status = 'open' |
| 794 | 1099 | ORDER BY d.detected_at DESC |
| 795 | 1100 | LIMIT $2 OFFSET $3", |
added crates/utopia-store/tests/a_contradiction_points_upstream.rs +341 −0
| @@ -0,0 +1,341 @@ | ||
| 1 | +//! 0017:派生撞上断言时,让路这件事从静默变成可见。 | |
| 2 | +//! | |
| 3 | +//! `ceo_of ⊑ works_at`,`works_at` functional。Mira `ceo_of` Acme 推出 Mira `works_at` | |
| 4 | +//! Acme,而账本里说她 `works_at` Globex。这里守四件事: | |
| 5 | +//! | |
| 6 | +//! 1. **派生不落地,而队列里有一行。** `run` 记一条 `derived_contradiction`,left 是被撞 | |
| 7 | +//! 的断言,right 是最后一条前提,detail 写着推出来的三元组;`materialize` 拦下它。 | |
| 8 | +//! 2. **修了就落。** 给旧断言一个结束日期,派生的区间与它不再重叠,下一轮落地, | |
| 9 | +//! 队列里那一行随之清掉。 | |
| 10 | +//! 3. **认可就落。** 人说两边都对,`accepted` 之后派生照常落地,那一行留着不再报。 | |
| 11 | +//! 4. **派生之间互撞按规则对聚合。** 两个 ceo 推出两条互斥的 works_at,进 | |
| 12 | +//! `ontology_defects` 一行 `rules_disagree`,两条派生都不落。 | |
| 13 | +//! | |
| 14 | +//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。 | |
| 15 | + | |
| 16 | +use sqlx::PgPool; | |
| 17 | +use utopia_store::reasoning; | |
| 18 | +use uuid::Uuid; | |
| 19 | + | |
| 20 | +struct Fixture { | |
| 21 | + org: Uuid, | |
| 22 | + user: Uuid, | |
| 23 | + kb: Uuid, | |
| 24 | + ceo_of: Uuid, | |
| 25 | + works_at: Uuid, | |
| 26 | + mira: Uuid, | |
| 27 | + acme: Uuid, | |
| 28 | + globex: Uuid, | |
| 29 | + initech: Uuid, | |
| 30 | +} | |
| 31 | + | |
| 32 | +async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> { | |
| 33 | + let (org, ws, kb, user) = ( | |
| 34 | + Uuid::now_v7(), | |
| 35 | + Uuid::now_v7(), | |
| 36 | + Uuid::now_v7(), | |
| 37 | + Uuid::now_v7(), | |
| 38 | + ); | |
| 39 | + let etype = Uuid::now_v7(); | |
| 40 | + let (ceo_of, works_at) = (Uuid::now_v7(), Uuid::now_v7()); | |
| 41 | + let (mira, acme, globex, initech) = ( | |
| 42 | + Uuid::now_v7(), | |
| 43 | + Uuid::now_v7(), | |
| 44 | + Uuid::now_v7(), | |
| 45 | + Uuid::now_v7(), | |
| 46 | + ); | |
| 47 | + | |
| 48 | + sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'contradiction-test')") | |
| 49 | + .bind(org) | |
| 50 | + .execute(pool) | |
| 51 | + .await?; | |
| 52 | + sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'contradiction-test')") | |
| 53 | + .bind(ws) | |
| 54 | + .bind(org) | |
| 55 | + .execute(pool) | |
| 56 | + .await?; | |
| 57 | + sqlx::query( | |
| 58 | + "INSERT INTO users (id, org_id, email, display_name, password_hash) | |
| 59 | + VALUES ($1, $2, $1 || '@contradiction.test', 'c', 'x')", | |
| 60 | + ) | |
| 61 | + .bind(user) | |
| 62 | + .bind(org) | |
| 63 | + .execute(pool) | |
| 64 | + .await?; | |
| 65 | + sqlx::query( | |
| 66 | + "INSERT INTO knowledge_bases (id, workspace_id, name, materialize_inferences) | |
| 67 | + VALUES ($1, $2, 'contradiction-test', TRUE)", | |
| 68 | + ) | |
| 69 | + .bind(kb) | |
| 70 | + .bind(ws) | |
| 71 | + .execute(pool) | |
| 72 | + .await?; | |
| 73 | + sqlx::query( | |
| 74 | + "INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'thing', 'Thing')", | |
| 75 | + ) | |
| 76 | + .bind(etype) | |
| 77 | + .bind(kb) | |
| 78 | + .execute(pool) | |
| 79 | + .await?; | |
| 80 | + sqlx::query( | |
| 81 | + "INSERT INTO relation_types (id, kb_id, key, label, functional) | |
| 82 | + VALUES ($1, $2, 'works_at', 'works at', TRUE)", | |
| 83 | + ) | |
| 84 | + .bind(works_at) | |
| 85 | + .bind(kb) | |
| 86 | + .execute(pool) | |
| 87 | + .await?; | |
| 88 | + sqlx::query( | |
| 89 | + "INSERT INTO relation_types (id, kb_id, key, label, sub_property_of) | |
| 90 | + VALUES ($1, $2, 'ceo_of', 'CEO of', $3)", | |
| 91 | + ) | |
| 92 | + .bind(ceo_of) | |
| 93 | + .bind(kb) | |
| 94 | + .bind(works_at) | |
| 95 | + .execute(pool) | |
| 96 | + .await?; | |
| 97 | + for (id, name) in [ | |
| 98 | + (mira, "Mira"), | |
| 99 | + (acme, "Acme"), | |
| 100 | + (globex, "Globex"), | |
| 101 | + (initech, "Initech"), | |
| 102 | + ] { | |
| 103 | + sqlx::query( | |
| 104 | + "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)", | |
| 105 | + ) | |
| 106 | + .bind(id) | |
| 107 | + .bind(kb) | |
| 108 | + .bind(etype) | |
| 109 | + .bind(name) | |
| 110 | + .execute(pool) | |
| 111 | + .await?; | |
| 112 | + } | |
| 113 | + Ok(Fixture { | |
| 114 | + org, | |
| 115 | + user, | |
| 116 | + kb, | |
| 117 | + ceo_of, | |
| 118 | + works_at, | |
| 119 | + mira, | |
| 120 | + acme, | |
| 121 | + globex, | |
| 122 | + initech, | |
| 123 | + }) | |
| 124 | +} | |
| 125 | + | |
| 126 | +async fn asserted( | |
| 127 | + pool: &PgPool, | |
| 128 | + f: &Fixture, | |
| 129 | + subject: Uuid, | |
| 130 | + predicate: Uuid, | |
| 131 | + object: Uuid, | |
| 132 | + from: Option<&str>, | |
| 133 | +) -> anyhow::Result<Uuid> { | |
| 134 | + let id = Uuid::now_v7(); | |
| 135 | + sqlx::query( | |
| 136 | + "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, confidence, | |
| 137 | + valid_from, valid_from_precision) | |
| 138 | + VALUES ($1, $2, $3, $4, $5, 0.9, $6::timestamptz, CASE WHEN $6 IS NULL THEN NULL ELSE 'day' END)", | |
| 139 | + ) | |
| 140 | + .bind(id) | |
| 141 | + .bind(f.kb) | |
| 142 | + .bind(subject) | |
| 143 | + .bind(predicate) | |
| 144 | + .bind(object) | |
| 145 | + .bind(from) | |
| 146 | + .execute(pool) | |
| 147 | + .await?; | |
| 148 | + Ok(id) | |
| 149 | +} | |
| 150 | + | |
| 151 | +async fn live_derived(pool: &PgPool, f: &Fixture) -> anyhow::Result<Vec<(Uuid, Uuid)>> { | |
| 152 | + Ok(sqlx::query_as( | |
| 153 | + "SELECT subject_id, object_id FROM derived_facts | |
| 154 | + WHERE kb_id = $1 AND invalidated_at IS NULL ORDER BY subject_id, object_id", | |
| 155 | + ) | |
| 156 | + .bind(f.kb) | |
| 157 | + .fetch_all(pool) | |
| 158 | + .await?) | |
| 159 | +} | |
| 160 | + | |
| 161 | +async fn open_contradictions( | |
| 162 | + pool: &PgPool, | |
| 163 | + f: &Fixture, | |
| 164 | +) -> anyhow::Result<Vec<(Uuid, Uuid, serde_json::Value)>> { | |
| 165 | + Ok(sqlx::query_as( | |
| 166 | + "SELECT id, left_fact, detail FROM axiom_violations | |
| 167 | + WHERE kb_id = $1 AND kind = 'derived_contradiction' AND status = 'open'", | |
| 168 | + ) | |
| 169 | + .bind(f.kb) | |
| 170 | + .fetch_all(pool) | |
| 171 | + .await?) | |
| 172 | +} | |
| 173 | + | |
| 174 | +#[tokio::test] | |
| 175 | +async fn a_contradiction_points_upstream() -> anyhow::Result<()> { | |
| 176 | + let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else { | |
| 177 | + eprintln!("跳过:未设 UTOPIA_DATABASE_URL"); | |
| 178 | + return Ok(()); | |
| 179 | + }; | |
| 180 | + let pool = PgPool::connect(&url).await?; | |
| 181 | + let f = seed(&pool).await?; | |
| 182 | + | |
| 183 | + let run = async { | |
| 184 | + // Mira works_at Globex(没写结束日期);Mira ceo_of Acme 自 2024 起 | |
| 185 | + let old = asserted(&pool, &f, f.mira, f.works_at, f.globex, Some("2020-01-01")).await?; | |
| 186 | + let ceo = asserted(&pool, &f, f.mira, f.ceo_of, f.acme, Some("2024-01-01")).await?; | |
| 187 | + | |
| 188 | + // 1. 派生不落地,队列里有一行 | |
| 189 | + let m = reasoning::materialize(&pool, f.kb).await?; | |
| 190 | + assert_eq!(m.derived, 1); | |
| 191 | + assert_eq!( | |
| 192 | + m.blocked, 1, | |
| 193 | + "the derivation that hits an assertion stays out" | |
| 194 | + ); | |
| 195 | + assert_eq!(m.inserted, 0); | |
| 196 | + assert!(live_derived(&pool, &f).await?.is_empty()); | |
| 197 | + | |
| 198 | + let r = reasoning::run(&pool, f.kb).await?; | |
| 199 | + assert_eq!(r.contradictions, 1); | |
| 200 | + assert_eq!(r.rules_disagree, 0); | |
| 201 | + let rows = open_contradictions(&pool, &f).await?; | |
| 202 | + assert_eq!(rows.len(), 1); | |
| 203 | + let (vid, left, detail) = &rows[0]; | |
| 204 | + assert_eq!(*left, old, "left is the assertion that was hit"); | |
| 205 | + assert_eq!(detail["axiom"], "functional"); | |
| 206 | + assert_eq!(detail["rule"], "sub_property"); | |
| 207 | + assert_eq!(detail["subject"], "Mira"); | |
| 208 | + assert_eq!(detail["predicate"], "works at"); | |
| 209 | + assert_eq!(detail["object"], "Acme"); | |
| 210 | + assert_eq!(detail["via_label"], "CEO of"); | |
| 211 | + assert_eq!(detail["premises"][0], serde_json::json!(ceo)); | |
| 212 | + let (right,): (Uuid,) = | |
| 213 | + sqlx::query_as("SELECT right_fact FROM axiom_violations WHERE id = $1") | |
| 214 | + .bind(vid) | |
| 215 | + .fetch_one(&pool) | |
| 216 | + .await?; | |
| 217 | + assert_eq!(right, ceo, "right is the last premise"); | |
| 218 | + | |
| 219 | + // Review 给的线索:旧断言没写结束日期、派生起得更晚 → stale | |
| 220 | + let page = reasoning::open_violations(&pool, f.kb, 50, 0).await?; | |
| 221 | + let card = page | |
| 222 | + .iter() | |
| 223 | + .find(|v| v.id == *vid) | |
| 224 | + .expect("card on the page"); | |
| 225 | + assert_eq!(card.hint.as_deref(), Some("stale")); | |
| 226 | + assert_eq!(card.detail["subject"], "Mira"); | |
| 227 | + | |
| 228 | + // 重跑幂等:还是那一行 | |
| 229 | + reasoning::run(&pool, f.kb).await?; | |
| 230 | + assert_eq!(open_contradictions(&pool, &f).await?.len(), 1); | |
| 231 | + | |
| 232 | + // 2. 修了就落:给旧断言一个结束日期,区间不再重叠 | |
| 233 | + sqlx::query( | |
| 234 | + "UPDATE facts SET valid_to = '2023-06-30'::timestamptz, valid_to_precision = 'day' | |
| 235 | + WHERE id = $1", | |
| 236 | + ) | |
| 237 | + .bind(old) | |
| 238 | + .execute(&pool) | |
| 239 | + .await?; | |
| 240 | + let m = reasoning::materialize(&pool, f.kb).await?; | |
| 241 | + assert_eq!(m.blocked, 0); | |
| 242 | + assert_eq!( | |
| 243 | + m.inserted, 1, | |
| 244 | + "once the assertion ends, the derivation lands" | |
| 245 | + ); | |
| 246 | + assert_eq!(live_derived(&pool, &f).await?, vec![(f.mira, f.acme)]); | |
| 247 | + reasoning::run(&pool, f.kb).await?; | |
| 248 | + assert!( | |
| 249 | + open_contradictions(&pool, &f).await?.is_empty(), | |
| 250 | + "the queue row clears with the contradiction" | |
| 251 | + ); | |
| 252 | + | |
| 253 | + // 3. 认可就落:把结束日期拿掉,矛盾回来;人说两边都对,派生照常落地 | |
| 254 | + sqlx::query("UPDATE facts SET valid_to = NULL, valid_to_precision = NULL WHERE id = $1") | |
| 255 | + .bind(old) | |
| 256 | + .execute(&pool) | |
| 257 | + .await?; | |
| 258 | + let m = reasoning::materialize(&pool, f.kb).await?; | |
| 259 | + assert_eq!(m.blocked, 1); | |
| 260 | + assert_eq!(m.invalidated, 1, "the landed derivation is withdrawn again"); | |
| 261 | + reasoning::run(&pool, f.kb).await?; | |
| 262 | + let rows = open_contradictions(&pool, &f).await?; | |
| 263 | + assert_eq!(rows.len(), 1); | |
| 264 | + reasoning::decide(&pool, f.kb, rows[0].0, "accepted", f.user).await?; | |
| 265 | + let m = reasoning::materialize(&pool, f.kb).await?; | |
| 266 | + assert_eq!(m.blocked, 0, "an accepted pair lands"); | |
| 267 | + assert_eq!(live_derived(&pool, &f).await?, vec![(f.mira, f.acme)]); | |
| 268 | + let r = reasoning::run(&pool, f.kb).await?; | |
| 269 | + assert_eq!(r.contradictions, 1, "still counted"); | |
| 270 | + assert!( | |
| 271 | + open_contradictions(&pool, &f).await?.is_empty(), | |
| 272 | + "but the accepted row stays resolved and nothing new is opened" | |
| 273 | + ); | |
| 274 | + | |
| 275 | + // 4. 派生之间互撞:先把旧断言闭合掉,让断言不再参与;再来一个 ceo_of Initech, | |
| 276 | + // 两条 works_at 由同一条规则推出、互斥——按规则对报一次,两条都不落 | |
| 277 | + sqlx::query( | |
| 278 | + "UPDATE facts SET valid_to = '2023-06-30'::timestamptz, valid_to_precision = 'day' | |
| 279 | + WHERE id = $1", | |
| 280 | + ) | |
| 281 | + .bind(old) | |
| 282 | + .execute(&pool) | |
| 283 | + .await?; | |
| 284 | + let ceo2 = asserted(&pool, &f, f.mira, f.ceo_of, f.initech, Some("2024-01-01")).await?; | |
| 285 | + let m = reasoning::materialize(&pool, f.kb).await?; | |
| 286 | + assert_eq!(m.derived, 2); | |
| 287 | + assert_eq!(m.blocked, 2, "both sides of a rule clash stay out"); | |
| 288 | + assert_eq!(m.invalidated, 1, "the one that had landed is withdrawn"); | |
| 289 | + assert!(live_derived(&pool, &f).await?.is_empty()); | |
| 290 | + let r = reasoning::run(&pool, f.kb).await?; | |
| 291 | + assert_eq!(r.contradictions, 0); | |
| 292 | + assert_eq!(r.rules_disagree, 1); | |
| 293 | + let defects: Vec<(Uuid, Option<Uuid>, serde_json::Value)> = sqlx::query_as( | |
| 294 | + "SELECT subject, other, detail FROM ontology_defects | |
| 295 | + WHERE kb_id = $1 AND kind = 'rules_disagree' AND status = 'open'", | |
| 296 | + ) | |
| 297 | + .bind(f.kb) | |
| 298 | + .fetch_all(&pool) | |
| 299 | + .await?; | |
| 300 | + assert_eq!(defects.len(), 1); | |
| 301 | + assert_eq!(defects[0].0, f.ceo_of); | |
| 302 | + assert_eq!(defects[0].1, Some(f.ceo_of)); | |
| 303 | + assert_eq!(defects[0].2["count"], 1); | |
| 304 | + assert_eq!(defects[0].2["rules"][0]["axiom"], "functional"); | |
| 305 | + assert_eq!(defects[0].2["rules"][0]["rule_a"], "sub_property"); | |
| 306 | + assert_eq!(defects[0].2["rules"][0]["via_a"], "CEO of"); | |
| 307 | + let page = reasoning::open_defects(&pool, f.kb, 50, 0).await?; | |
| 308 | + let card = page | |
| 309 | + .iter() | |
| 310 | + .find(|d| d.kind == "rules_disagree") | |
| 311 | + .expect("the rule clash is on the page"); | |
| 312 | + assert_eq!(card.subject_label.as_deref(), Some("CEO of")); | |
| 313 | + assert_eq!(card.other_label.as_deref(), Some("CEO of")); | |
| 314 | + | |
| 315 | + // 撤掉第二个 ceo:规则对的那一行清掉,第一条派生重新落地 | |
| 316 | + sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = $1") | |
| 317 | + .bind(ceo2) | |
| 318 | + .execute(&pool) | |
| 319 | + .await?; | |
| 320 | + reasoning::run(&pool, f.kb).await?; | |
| 321 | + let (n,): (i64,) = sqlx::query_as( | |
| 322 | + "SELECT count(*) FROM ontology_defects | |
| 323 | + WHERE kb_id = $1 AND kind = 'rules_disagree' AND status = 'open'", | |
| 324 | + ) | |
| 325 | + .bind(f.kb) | |
| 326 | + .fetch_one(&pool) | |
| 327 | + .await?; | |
| 328 | + assert_eq!(n, 0, "a rule clash clears when its derivations go"); | |
| 329 | + let m = reasoning::materialize(&pool, f.kb).await?; | |
| 330 | + assert_eq!(m.blocked, 0); | |
| 331 | + assert_eq!(live_derived(&pool, &f).await?, vec![(f.mira, f.acme)]); | |
| 332 | + anyhow::Ok(()) | |
| 333 | + } | |
| 334 | + .await; | |
| 335 | + | |
| 336 | + let _ = sqlx::query("DELETE FROM organizations WHERE id = $1") | |
| 337 | + .bind(f.org) | |
| 338 | + .execute(&pool) | |
| 339 | + .await; | |
| 340 | + run | |
| 341 | +} |
modified docs/decisions/0002-reasoning-engine.md +2 −0
| @@ -75,6 +75,8 @@ | ||
| 75 | 75 | |
| 76 | 76 | > **修订记录(2026-09-02)**:表格三行里只有第一行的前半兑现了——`asserted` 硬性优先,已断言的三元组不再派生(`derive.rs`)。 |
| 77 | 77 | > 「记一条规则与事实矛盾的信号」**没有**,「派生 vs 派生进 Review」**没有**(同一三元组的多条推导只留第一条证明)。两者都还是待做。 |
| 78 | +> | |
| 79 | +> **修订记录(2026-09-03)**:两行都兑现了,方案见 [0017](0017-a-contradiction-points-upstream.md)。派生撞断言:`derive::contradictions` 逐条算出,`run` 记成 `axiom_violations` 一种 `derived_contradiction`(单谓词封顶 50),`materialize` 用同一个函数拦下不落地;卡片给线索(旧断言没结束日期、同名实体、置信度低)与修法(闭合、撤回、认可)。派生撞派生:按规则对聚合进 `ontology_defects` 一种 `rules_disagree`,两边都不落——根子是那两条声明,不是哪条事实。 | |
| 78 | 80 | |
| 79 | 81 | ### 3. 前提撤回时——双时态是最优解,不是负担 |
| 80 | 82 |
modified docs/decisions/0016-close-the-open-seams-before-cutting-new-ones.md +1 −1
| @@ -67,7 +67,7 @@ | ||
| 67 | 67 | ### B · 推理机补完——A 之后,与 C 并行 |
| 68 | 68 | |
| 69 | 69 | **B1 · R2 证明树。**〔已做,`feat/proof-tree`;实际是链不是树,理由见 0002 R2 的修订〕递归展开到叶子 chunk 的 API + 实体面板里可展开的树。数据结构(`fact_derivations`)已够。 |
| 70 | -**B2 · 派生 vs 断言矛盾要有信号。** `axiom_violations` 加一种 kind(`derived_contradiction`),进 Review 同一档——0002 写了没做的那一行。 | |
| 70 | +**B2 · 派生 vs 断言矛盾要有信号。** `axiom_violations` 加一种 kind(`derived_contradiction`),进 Review 同一档——0002 写了没做的那一行。(完整方案见 [0017](0017-a-contradiction-points-upstream.md);B2a 引擎与队列已做,B2b 图与面板上的可见性待做。) | |
| 71 | 71 | **B3 · `disjointWith` 进消解,合并路径复核签名。** `classify_type_drift` 改从 `entity_type_disjoint` 读(没声明就退回今天的行为,不硬编码); |
| 72 | 72 | `merge_entities` 搬事实前跑一遍与写入时相同的 domain / range 检查,违反的进 `axiom_violations` 而不是静默搬过去。这是 0009 与 0012 各自待做的同一件事。 |
| 73 | 73 | 〔**签名那一半已提前做了**(#190 / #196 逼出来的,A 线里插队):`ontology::judge_direction` 一处判断,抽取与采纳共用;合并后对搬动过的事实报 `signature` 违规;R0 多一类。剩下 `disjointWith` 进消解那一半仍在这里。〕 |
added docs/decisions/0017-a-contradiction-points-upstream.md +205 −0
| @@ -0,0 +1,205 @@ | ||
| 1 | +# 0017 · A contradiction points at an error upstream | |
| 2 | + | |
| 3 | +- **Status**: B2a implemented (engine and queue: `derive::contradictions`, migration 0020, the Review card with clues and repairs) · B2b (visibility in the graph and the entity panel) still planned · B2 of 0016, wider than the one line written there: contradictions become visible everywhere, not only as a new kind in the queue | |
| 4 | +- **Written**: 2026-09-03 (conventions in [README](README.md)) | |
| 5 | +- **Related**: the two unbuilt rows of the "derived vs asserted" table in [0002](0002-reasoning-engine.md) §2; [0016](0016-close-the-open-seams-before-cutting-new-ones.md) B2; the proof chain (B1, #227) supplies the "premises expand to the sentence" half of the card below | |
| 6 | + | |
| 7 | +> This record changes one phrase in 0002. There, a contradiction "goes to Review for a ruling". | |
| 8 | +> In discussion (2026-09-03) it became clear what a person actually does when two edges | |
| 9 | +> disagree: follow the signal to **where something went wrong upstream** — a fact went | |
| 10 | +> stale, extraction misread, resolution merged the wrong pair, the ontology is too strict. | |
| 11 | +> So this queue is built as an audit, and every button is a repair. | |
| 12 | + | |
| 13 | +## The problem | |
| 14 | + | |
| 15 | +R1 derivation only yields to "this exact triple is already asserted". It does not consult | |
| 16 | +axioms: `part_of` transitivity derives `A part_of C` while the ledger asserts `C part_of A` | |
| 17 | +(asymmetric); `ceo_of` is functional and `Acme ceo_of Zhang San` is asserted, yet the | |
| 18 | +engine still lands `Acme ceo_of Li Si`. R0 scans `facts` only, derivations live in their | |
| 19 | +own table, so this class of contradiction is **invisible on both sides**: absent from | |
| 20 | +Review, absent from the graph. | |
| 21 | + | |
| 22 | +It is not the only invisible class. Temporal conflicts and axiom violations are known to | |
| 23 | +the Review page alone; on the graph and in the entity panel a contested edge looks exactly | |
| 24 | +like any other. | |
| 25 | + | |
| 26 | +## Criteria | |
| 27 | + | |
| 28 | +1. **A contradiction points at an error upstream.** The error is in one of four places: | |
| 29 | + stale knowledge (most common), a misread extraction, a wrong merge, an over-strict | |
| 30 | + ontology. The interface's job is to lay out the clues and offer the repairs. | |
| 31 | +2. **Write less to the graph rather than write wrong** (0002). A derivation that hits a | |
| 32 | + contradiction does not land; when two derivations collide, neither lands. | |
| 33 | +3. **Anything reported item by item needs an upper bound.** Only "one assertion against one | |
| 34 | + concrete edge" — a volume that can be predicted — goes into the queue individually, and | |
| 35 | + with a per-predicate cap; whatever is produced in batches is aggregated by its cause. | |
| 36 | +4. **A disputed fact is visible where it sits.** The assertion stays live, but someone | |
| 37 | + passing it on the graph or in the panel should see that it is questioned, and reach the | |
| 38 | + place to fix it in one step. | |
| 39 | + | |
| 40 | +## Decisions | |
| 41 | + | |
| 42 | +### 1. Detection: two tiers, pure logic in `utopia-reason` | |
| 43 | + | |
| 44 | +`derive::contradictions(derived, edges, axioms)` checks every derivation against the axioms | |
| 45 | +of its predicate, once against assertions and once against other derivations: | |
| 46 | + | |
| 47 | +| Axiom | What counts as a contradiction | | |
| 48 | +|---|---| | |
| 49 | +| functional | same subject and predicate, different object, **validity intervals overlap** (Mira leaving and Devin taking over is a succession; the half-open interval semantics of `validity` are reused) | | |
| 50 | +| inverse_functional | the dual | | |
| 51 | +| asymmetric | the reverse edge exists with overlapping validity | | |
| 52 | +| irreflexive | the derivation is a self-loop | | |
| 53 | + | |
| 54 | +**Derived vs asserted**: per item. The derivation does not land; one `axiom_violations` | |
| 55 | +row of kind `derived_contradiction`. Capped per predicate (same shape as R1's | |
| 56 | +`MAX_DERIVED_PER_PREDICATE`; 50 suggested); the overflow stays out of the queue and is | |
| 57 | +counted in the report. | |
| 58 | + | |
| 59 | +**Derived vs derived**: aggregated. The cause is a rule set that contradicts itself — | |
| 60 | +`ceo_of ⊑ works_at` together with `works_at` functional necessarily produces contradictions | |
| 61 | +in batches. Queuing every pair would flood Review, and a person facing a hundred identical | |
| 62 | +"two derivations disagree" cards cannot decide anything from them. So one row per **pair of | |
| 63 | +rules** goes into `ontology_defects`, kind `rules_disagree`, recording both rules, the | |
| 64 | +count, and two or three examples. It is the dynamic form of the existing static defects | |
| 65 | +`transitive_and_functional` and `symmetric_and_asymmetric`: invisible in the declarations, | |
| 66 | +surfacing once data arrives. Neither derivation lands. | |
| 67 | + | |
| 68 | +`run()` (R0) and `materialize` (R1) share the one function: R0 already holds the edges and | |
| 69 | +axioms and adds a `derive` + `contradictions` pass to report; R1 uses the same result to | |
| 70 | +decide what stays unlanded. **Both must compute it** — otherwise R0's "clear open rows not | |
| 71 | +recomputed this round" would sweep away what R1 wrote. | |
| 72 | + | |
| 73 | +### 2. The Review card: lay out the clues, lay out the repairs | |
| 74 | + | |
| 75 | +**The derived-vs-asserted card**, three parts: | |
| 76 | + | |
| 77 | +1. **The contradiction itself**: the derived edge (rule, premise chain expandable to the | |
| 78 | + sentence — from B1) beside the asserted edge (evidence quote, interval, confidence). | |
| 79 | + Most errors are visible at a glance. | |
| 80 | +2. **A diagnostic hint**, one line when a clue can be computed, none when it cannot: | |
| 81 | + - the assertion has no end date and the derivation starts after it → "looks stale: did | |
| 82 | + Zhang San's tenure end in 2024-07?" | |
| 83 | + - an entity on either side has same-name neighbours (the existing `same_name` machinery) | |
| 84 | + → "looks like a wrong merge: are these two Acmes one company?" | |
| 85 | + - the assertion's confidence is below 0.75 → "the extraction was unsure to begin with" | |
| 86 | + - none of the above → "read both sentences" | |
| 87 | +3. **Actions that are repairs**, all on existing endpoints; once a repair is made the | |
| 88 | + violation clears on the next recomputation, with no separate resolve step: | |
| 89 | + | |
| 90 | +| Action | What it repairs | Where it lands | | |
| 91 | +|---|---|---| | |
| 92 | +| Close the assertion at a date | stale knowledge | `POST /facts/{id}/close` (same as the temporal-conflict queue, with a date input) | | |
| 93 | +| Retract the assertion | misread extraction / wrong merge | `reject_fact`, append-only | | |
| 94 | +| Go to possible duplicates | wrong merge | the Duplicates queue in Review | | |
| 95 | +| The ontology is too strict | wrong definition | the relation on the Ontology page | | |
| 96 | +| Both hold; let the derivation through | the world is like that | `resolution = accepted`; the next `materialize` lets that pair land | | |
| 97 | + | |
| 98 | +**The derived-vs-derived card** (in the ontology-defects queue): "these two declarations | |
| 99 | +together produced N contradicting pairs; examples below — usually a sub-property attached | |
| 100 | +in the wrong place, or a functional declaration that is too strict". Two actions: go to the | |
| 101 | +Ontology page and change a declaration; or "accept" (contradicting derivations from this | |
| 102 | +pair of rules never land and are not reported again). Both sides are derived and the | |
| 103 | +assertions beneath may each be right, so there is no "the data is wrong" here; "both hold" | |
| 104 | +would mean giving up the meaning of functional, which belongs on the Ontology page, so | |
| 105 | +there is no such button either. | |
| 106 | + | |
| 107 | +### 3. Disputed facts are visible where they sit | |
| 108 | + | |
| 109 | +"Disputed" becomes one status with three sources: open temporal conflicts | |
| 110 | +(`fact_conflicts`), open axiom violations (`axiom_violations`, including the new kind), and | |
| 111 | +blocked derivations (the `detail` of `derived_contradiction` rows). B2 makes it a first-class | |
| 112 | +state of the browse pages and wires up the first two sources along the way — they are | |
| 113 | +equally invisible today. | |
| 114 | + | |
| 115 | +**Rows in the entity panel**: `EntityFact` already carries `stale` and `corrected`; a third | |
| 116 | +flag `contested: Option<Contest { kind, ref_id }>` is computed with one EXISTS. The chip | |
| 117 | +reads "disputed"; hover gives one sentence ("derived works_at Li Si contradicts this"); | |
| 118 | +click goes to the matching Review item. The row is not dimmed: the assertion is still live. | |
| 119 | + | |
| 120 | +**The Derived tab of the panel**: a new section, "derivations that did not land", read from | |
| 121 | +`axiom_violations.detail`, each row naming what blocked it and expanding to its premise | |
| 122 | +chain. Here a person sees "the engine could have drawn this edge, and what stopped it". | |
| 123 | + | |
| 124 | +**Edges on the graph**: | |
| 125 | + | |
| 126 | +- A contested assertion switches to the **alert colour**, edge and all, with no reliance on | |
| 127 | + a node ring. The request was explicit: a ring sits on the node while the edge stays grey, | |
| 128 | + and peripheral vision cannot tell them apart. | |
| 129 | +- A blocked derivation is drawn as a **ghost edge**: the same hue mixed toward `EDGE_DIM` | |
| 130 | + (under premultiplied blending alpha cannot darken an edge; only the RGB can be mixed — see | |
| 131 | + the note at `EDGE_DIM`), thinner. It follows the Derived toggle; clicking it opens the | |
| 132 | + entity panel at that row. sigma's default edge program does not draw dashes, and no custom | |
| 133 | + program is introduced for this. | |
| 134 | +- The hover label chip gets a "⚠" prefix, and the tooltip states the dispute. | |
| 135 | + | |
| 136 | +**Colour**: one new token, `--u-contest`, set to **#ff6a3d** (hot coral orange). It has to | |
| 137 | +stand apart from three colours already in use: derived edges are gold | |
| 138 | +(`rgb(231,197,124)`), warning chips are amber (`--u-warn` #f2b66d, too close to gold to | |
| 139 | +double as an edge colour), and danger is pink (`--u-danger` #ff9daf, reserved for | |
| 140 | +destructive actions). Coral orange is bright enough on the dark ground, its hue is far from | |
| 141 | +all three, and it is no common type colour (the type palette leans blue, green and violet). | |
| 142 | +Edge colour `rgba(255,106,61,0.55)`; ghost edge `lerp(#ff6a3d, EDGE_DIM, 0.55)`. This is | |
| 143 | +the only new colour; chips on the Ontology and Review pages use the same token. | |
| 144 | + | |
| 145 | +### 4. Data | |
| 146 | + | |
| 147 | +Migration `0020` (0019 was taken by #199 / #233): | |
| 148 | + | |
| 149 | +- `axiom_violations.kind` CHECK gains `derived_contradiction` | |
| 150 | +- `axiom_violations` gains `detail JSONB NOT NULL DEFAULT '{}'`: the derived triple (three | |
| 151 | + ids and three names), the rule kind, the premise ids — without it the interface cannot | |
| 152 | + say what was derived; `path` holds the premises for the proof chain but cannot draw the | |
| 153 | + ghost edge | |
| 154 | +- `axiom_violations.resolution` CHECK gains `fact_closed` (closing an assertion is a repair | |
| 155 | + that leaves its own trace, kept apart from `fact_retracted`) | |
| 156 | +- `ontology_defects.kind` CHECK gains `rules_disagree`, plus `detail JSONB` (both rules, the | |
| 157 | + count, the examples) | |
| 158 | + | |
| 159 | +`left_fact` / `right_fact` stay non-null and keep pointing at `facts`: for derived vs | |
| 160 | +asserted, `left` is the contradicted assertion and `right` the derivation's last premise; | |
| 161 | +`rules_disagree` does not live in this table. | |
| 162 | + | |
| 163 | +### 5. Interfaces | |
| 164 | + | |
| 165 | +- `GET /kbs/{id}/graph`: edges gain `contested: bool`; a new class of edge with | |
| 166 | + `blocked: true` (the ghosts) | |
| 167 | +- `GET /kbs/{id}/entities/{id}`: `facts[].contested`; `blocked: [...]` next to `derived` | |
| 168 | +- Review `violations` queue: rows gain `detail` and `hint` (the diagnostic as a code; wording | |
| 169 | + belongs to the frontend) | |
| 170 | +- `POST /kbs/{id}/review/violations/{id}`: `resolution` gains `fact_closed` (with | |
| 171 | + `close_at`); the server calls `close_fact` and then marks the row resolved | |
| 172 | + | |
| 173 | +### 6. Tests | |
| 174 | + | |
| 175 | +- `utopia-reason` unit tests: one per axiom, non-overlapping intervals are no contradiction, | |
| 176 | + derived-vs-derived aggregates by rule pair, the cap is counted | |
| 177 | +- Store integration: a functional assertion stands and a derivation collides → the | |
| 178 | + derivation stays out and one violation carries `detail`; retract the assertion and rerun → | |
| 179 | + the derivation lands and the violation clears; `accepted` → both coexist; `fact_closed` | |
| 180 | + runs the close path; R0 and R1 agree | |
| 181 | +- Browser: an edge turns coral, ghost edges follow the toggle, the panel chip jumps to the | |
| 182 | + Review item, the Review card shows three parts and five actions | |
| 183 | + | |
| 184 | +## Two cuts | |
| 185 | + | |
| 186 | +**B2a · engine and queue**: §1, §2, §4, and the Review parts of §5, with the integration | |
| 187 | +tests. Two days. | |
| 188 | +**B2b · visibility**: §3 plus the graph and panel interfaces, wiring existing temporal | |
| 189 | +conflicts and axiom violations along the way. A day and a half. | |
| 190 | + | |
| 191 | +B1 (#227) merges first after a rebase; B2a branches from it. | |
| 192 | + | |
| 193 | +## Open questions | |
| 194 | + | |
| 195 | +- **The per-predicate cap of 50 is a guess**, awaiting a bench number like R1's twenty | |
| 196 | + thousand. | |
| 197 | +- **Granularity of `accepted`**: per pair (one derivation against one assertion). An | |
| 198 | + assertion hit by several derivations needs several clicks; aggregating the exemption per | |
| 199 | + assertion would generalise "this axiom does not apply to this assertion" too far. Per | |
| 200 | + pair first, measure later. | |
| 201 | +- **Could ghost edges be too many?** Their number is bounded by the (capped) violation | |
| 202 | + count, so it should stay manageable; failing that, draw them only when a related node is | |
| 203 | + selected. | |
| 204 | +- **Does the disputed status need its own SSE event?** The `review` event is already sent; | |
| 205 | + graph and panel can refetch on it. No new event. |
modified docs/decisions/README.md +2 −1
| @@ -20,7 +20,7 @@ | ||
| 20 | 20 | |
| 21 | 21 | **行号会漂,文件名会换。** 正文里的 `file.rs:123` 是成文时的坐标,不保证仍然准确;迁移在 #130 / #131 从 53 份折成 10 份、一个域一份,所以 2026-08-31 之前写的迁移文件名都要按域重找。引用时优先写函数名、表名、常量名。 |
| 22 | 22 | |
| 23 | -**语言**:中文,与代码注释一致(UI 与 README 保持英文)。目前的读者是维护者,不是外部贡献者;将来需要时再译。 | |
| 23 | +**语言**:2026-09-03 起新记录用英文(0017 起),读者已经包括外部贡献者;此前的十六篇仍是中文,与代码注释一致,是否回译等有人需要时再定。 | |
| 24 | 24 | |
| 25 | 25 | ## 索引 |
| 26 | 26 | |
| @@ -42,6 +42,7 @@ | ||
| 42 | 42 | | 0014 | [身份跟着人,范围跟着令牌](0014-identity-from-the-person-scope-from-the-token.md) | 已实施(#180)· MCP 只读五工具 · 令牌页在账户层(A2)· 误导性的占位 crate 已删 | |
| 43 | 43 | | 0015 | [记下一句话,不等于断言一个事实](0015-recording-a-sentence-is-not-asserting-a-fact.md) | 已实施 · 记忆抽出的事实进 `pending_facts`,Review 新档 + 跟在 remember 步骤后的确认卡 · `remember` 重新打开 · MCP 放开写是下一刀 | |
| 44 | 44 | | 0016 | [先把开着的口子收上,再开新的](0016-close-the-open-seams-before-cutting-new-ones.md) | 规划中 · v0.1.0 之后的排期:A 收口 → B 推理机 ∥ C 尺子与本体 → D 语义层 → E 企业交付;模拟引擎后置 | |
| 45 | +| 0017 | [A contradiction points at an error upstream](0017-a-contradiction-points-upstream.md) | B2a 已实现(引擎与队列:逐条封顶、按规则对聚合、卡片给线索与修法)· B2b 待做:争议在图和面板上原地可见(新警戒色)| | |
| 45 | 46 | |
| 46 | 47 | ## 不是决策记录的那些 |
| 47 | 48 |
added migrations/0020_a_contradiction_points_upstream.sql +34 −0
| @@ -0,0 +1,34 @@ | ||
| 1 | +-- 派生撞上断言时,让路这件事从静默变成可见(docs/decisions/0017)。 | |
| 2 | +-- | |
| 3 | +-- 0002 定了 asserted > derived:推出来的事实撞上账本里的断言就不落地。此前那一步 | |
| 4 | +-- 什么都不留——`ceo_of ⊑ works_at` 推出的 works_at 没了,人不知道有过这回事,也就 | |
| 5 | +-- 不知道该去看看是抽取错了、旧断言该闭合、还是两个「Mira」其实是一个人。 | |
| 6 | +-- | |
| 7 | +-- 一致性检查多一种 `derived_contradiction`:left 是被撞的断言,right 是派生的最后一条 | |
| 8 | +-- 前提,path 是全部前提;推出来的三元组本身没有落库、没有 id 可指,放进 `detail`。 | |
| 9 | +-- 出路多一条 `fact_closed`——最常见的修法是给旧断言一个结束日期。 | |
| 10 | +-- | |
| 11 | +-- 派生之间互撞(两条规则加在一起产出互斥的结论)按规则对聚合进 `ontology_defects`, | |
| 12 | +-- 一种 `rules_disagree`,`detail` 记规则对与几个例子。逐对进 Review 只会淹掉队列。 | |
| 13 | + | |
| 14 | +ALTER TABLE axiom_violations | |
| 15 | + DROP CONSTRAINT axiom_violations_kind_check, | |
| 16 | + ADD CONSTRAINT axiom_violations_kind_check CHECK (kind IN ( | |
| 17 | + 'self_loop', 'asymmetry', 'cycle', 'functional', 'signature', | |
| 18 | + 'derived_contradiction' | |
| 19 | + )), | |
| 20 | + DROP CONSTRAINT axiom_violations_resolution_check, | |
| 21 | + ADD CONSTRAINT axiom_violations_resolution_check CHECK (resolution IN ( | |
| 22 | + 'fact_retracted', 'fact_closed', 'axiom_relaxed', 'accepted' | |
| 23 | + )), | |
| 24 | + ADD COLUMN detail JSONB NOT NULL DEFAULT '{}'::jsonb; | |
| 25 | + | |
| 26 | +ALTER TABLE ontology_defects | |
| 27 | + DROP CONSTRAINT ontology_defects_kind_check, | |
| 28 | + ADD CONSTRAINT ontology_defects_kind_check CHECK (kind IN ( | |
| 29 | + 'symmetric_and_asymmetric', 'transitive_and_functional', 'subclass_cycle', | |
| 30 | + 'disjoint_with_ancestor', 'inherits_disjoint', | |
| 31 | + 'inverse_of_itself', 'inverse_not_mutual', 'sub_property_cycle', | |
| 32 | + 'rules_disagree' | |
| 33 | + )), | |
| 34 | + ADD COLUMN detail JSONB NOT NULL DEFAULT '{}'::jsonb; |
modified web/src/api.ts +52 −4
| @@ -473,9 +473,33 @@ | ||
| 473 | 473 | changed_at: string; |
| 474 | 474 | } |
| 475 | 475 | /** 一处公理违规(0002 R0)。判据来自本体自己声明的公理,没声明就不报 */ |
| 476 | +/** derived_contradiction 独有(0017):推出来的那条三元组——它没有落库, | |
| 477 | + * 只能在这里写出来。其它种类是 `{}` */ | |
| 478 | +export interface ViolationDetail { | |
| 479 | + axiom?: "functional" | "asymmetry" | "self_loop"; | |
| 480 | + rule?: "transitive" | "symmetric" | "inverse" | "sub_property"; | |
| 481 | + via_label?: string; | |
| 482 | + subject?: string; | |
| 483 | + predicate?: string; | |
| 484 | + object?: string; | |
| 485 | + valid_from?: string | null; | |
| 486 | + valid_to?: string | null; | |
| 487 | + premises?: string[]; | |
| 488 | +} | |
| 489 | +export type ViolationResolution = | |
| 490 | + | "fact_retracted" | |
| 491 | + | "fact_closed" | |
| 492 | + | "axiom_relaxed" | |
| 493 | + | "accepted"; | |
| 476 | 494 | export interface AxiomViolation { |
| 477 | 495 | id: string; |
| 478 | - kind: "self_loop" | "asymmetry" | "cycle" | "functional"; | |
| 496 | + kind: | |
| 497 | + | "self_loop" | |
| 498 | + | "asymmetry" | |
| 499 | + | "cycle" | |
| 500 | + | "functional" | |
| 501 | + | "signature" | |
| 502 | + | "derived_contradiction"; | |
| 479 | 503 | /** 判据来自哪条关系。判「公理写错了」时从这里进本体去改 */ |
| 480 | 504 | predicate: string | null; |
| 481 | 505 | left_fact: string; |
| @@ -486,6 +510,10 @@ | ||
| 486 | 510 | /** 环的长度;其余三类为 0 */ |
| 487 | 511 | path_len: number; |
| 488 | 512 | detected_at: string; |
| 513 | + detail: ViolationDetail; | |
| 514 | + /** 审核线索(0017 §2),一次只给一条:旧断言没写结束日期、有同名实体、 | |
| 515 | + * 抽取置信度低。没有就空 */ | |
| 516 | + hint: "stale" | "duplicate" | "unsure" | null; | |
| 489 | 517 | } |
| 490 | 518 | /** 本体自己的一处自相矛盾。**与 AxiomViolation 不是一回事**:那个说 |
| 491 | 519 | * 「事实与定义抵触」,这个说「定义自己站不住」,后者更根本 */ |
| @@ -500,11 +528,27 @@ | ||
| 500 | 528 | // 0017 加的三类:都在谓词上,前两类关于逆,第三类是子属性成环 |
| 501 | 529 | | "inverse_of_itself" |
| 502 | 530 | | "inverse_not_mutual" |
| 503 | - | "sub_property_cycle"; | |
| 531 | + | "sub_property_cycle" | |
| 532 | + // 0017:两条规则加在一起产出互斥的派生,按规则对聚合报一次 | |
| 533 | + | "rules_disagree"; | |
| 504 | 534 | subject_label: string | null; |
| 505 | 535 | other_label: string | null; |
| 506 | 536 | path_labels: string[]; |
| 507 | 537 | detected_at: string; |
| 538 | + detail: DefectDetail; | |
| 539 | +} | |
| 540 | +/** rules_disagree 独有:哪两条规则、撞在哪条公理上、几对、几个例子 */ | |
| 541 | +export interface DefectDetail { | |
| 542 | + count?: number; | |
| 543 | + rules?: { | |
| 544 | + rule_a: string; | |
| 545 | + via_a: string; | |
| 546 | + rule_b: string; | |
| 547 | + via_b: string; | |
| 548 | + axiom: string; | |
| 549 | + count: number; | |
| 550 | + examples: [string, string][]; | |
| 551 | + }[]; | |
| 508 | 552 | } |
| 509 | 553 | export interface FactReviewItem { |
| 510 | 554 | id: string; |
| @@ -1720,11 +1764,15 @@ | ||
| 1720 | 1764 | decideViolation: ( |
| 1721 | 1765 | kbId: string, |
| 1722 | 1766 | violationId: string, |
| 1723 | - resolution: "fact_retracted" | "axiom_relaxed" | "accepted", | |
| 1767 | + resolution: ViolationResolution, | |
| 1768 | + closeAt?: string, | |
| 1724 | 1769 | ) => |
| 1725 | 1770 | request<{ ok: boolean }>( |
| 1726 | 1771 | `/api/v1/kbs/${kbId}/review/violations/${violationId}`, |
| 1727 | - { method: "POST", body: JSON.stringify({ resolution }) }, | |
| 1772 | + { | |
| 1773 | + method: "POST", | |
| 1774 | + body: JSON.stringify({ resolution, close_at: closeAt ?? null }), | |
| 1775 | + }, | |
| 1728 | 1776 | ), |
| 1729 | 1777 | confirmFact: (kbId: string, factId: string) => |
| 1730 | 1778 | request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/confirm`, { |
modified web/src/i18n/en.ts +28 −0
| @@ -1303,6 +1303,16 @@ | ||
| 1303 | 1303 | defectInverseSelf: "Its own inverse — say symmetric instead", |
| 1304 | 1304 | defectInverseNotMutual: "The inverse does not point back", |
| 1305 | 1305 | defectSubPropertyCycle: "subPropertyOf runs in a circle", |
| 1306 | + defectRulesDisagree: "Two rules produce contradicting derivations", | |
| 1307 | + rulesDisagreeCount: (n: number) => | |
| 1308 | + `${n} pair(s) of derivations held back until this is settled`, | |
| 1309 | + rulesDisagreeRule: ( | |
| 1310 | + a: string, | |
| 1311 | + va: string, | |
| 1312 | + b: string, | |
| 1313 | + vb: string, | |
| 1314 | + axiom: string, | |
| 1315 | + ) => `${a} on ${va} with ${b} on ${vb}, against ${axiom}`, | |
| 1306 | 1316 | defectNeverInstantiable: "no instance can ever satisfy it", |
| 1307 | 1317 | defectFixed: "I fixed the ontology", |
| 1308 | 1318 | defectAccepted: "Leave it", |
| @@ -1325,6 +1335,24 @@ | ||
| 1325 | 1335 | /** 签名违规(#190 / #196):一条事实的主语或宾语落在谓词声明的类型之外—— |
| 1326 | 1336 | * 抽取时会掰正,采纳与合并这两条路从前绕过了检查 */ |
| 1327 | 1337 | violationSignature: "Subject or object outside the declared types", |
| 1338 | + /** 0017:派生撞上断言。卡片是一次审核,线索指向上游的错 */ | |
| 1339 | + violationDerived: "A derivation contradicts an assertion", | |
| 1340 | + derivedLine: (s: string, p: string, o: string) => | |
| 1341 | + `Derived: ${s} · ${p} · ${o}`, | |
| 1342 | + derivedBy: (rule: string, via: string) => `by ${rule} on ${via}`, | |
| 1343 | + assertedLine: (t: string) => `Asserted: ${t}`, | |
| 1344 | + hintStale: | |
| 1345 | + "The assertion has no end date and the derivation starts later. It may simply have ended.", | |
| 1346 | + hintDuplicate: | |
| 1347 | + "Two entities share this name. They may be the same one.", | |
| 1348 | + hintUnsure: | |
| 1349 | + "The assertion was extracted with low confidence. Read its sentence.", | |
| 1350 | + hintReadBoth: "Read both sentences and decide which one is wrong.", | |
| 1351 | + closeAssertion: "Give the assertion an end date", | |
| 1352 | + retractAssertion: "Retract the assertion", | |
| 1353 | + seeDuplicates: "See duplicates", | |
| 1354 | + openOntology: "Open the ontology", | |
| 1355 | + letBothStand: "Let both stand", | |
| 1328 | 1356 | violationVia: (p: string) => `via ${p}`, |
| 1329 | 1357 | violationPath: (n: number) => `${n} facts in the cycle`, |
| 1330 | 1358 | retractFact: "Data is wrong", |
modified web/src/i18n/zh.ts +23 −0
| @@ -1177,6 +1177,15 @@ | ||
| 1177 | 1177 | defectInverseSelf: "自己是自己的逆——写成「对称」更直白", |
| 1178 | 1178 | defectInverseNotMutual: "逆关系没有指回来", |
| 1179 | 1179 | defectSubPropertyCycle: "子属性绕成了环", |
| 1180 | + defectRulesDisagree: "两条规则推出互相抵触的结论", | |
| 1181 | + rulesDisagreeCount: (n: number) => `${n} 对派生等这里定了再落地`, | |
| 1182 | + rulesDisagreeRule: ( | |
| 1183 | + a: string, | |
| 1184 | + va: string, | |
| 1185 | + b: string, | |
| 1186 | + vb: string, | |
| 1187 | + axiom: string, | |
| 1188 | + ) => `${va} 上的 ${a} 与 ${vb} 上的 ${b},撞在 ${axiom} 上`, | |
| 1180 | 1189 | defectNeverInstantiable: "这个类永远不可能有实例", |
| 1181 | 1190 | defectFixed: "已去本体里改了", |
| 1182 | 1191 | defectAccepted: "先放着", |
| @@ -1195,6 +1204,20 @@ | ||
| 1195 | 1204 | violationCycle: "传递链绕成了环", |
| 1196 | 1205 | violationFunctional: "该只有一个值,却有两个", |
| 1197 | 1206 | violationSignature: "主语或宾语不在关系声明的类型里", |
| 1207 | + violationDerived: "推出来的与断言相抵触", | |
| 1208 | + derivedLine: (s: string, p: string, o: string) => | |
| 1209 | + `推出:${s} · ${p} · ${o}`, | |
| 1210 | + derivedBy: (rule: string, via: string) => `由 ${via} 上的 ${rule}`, | |
| 1211 | + assertedLine: (t: string) => `断言:${t}`, | |
| 1212 | + hintStale: "这条断言没写结束日期,而推出来的那条起得更晚——它可能只是结束了。", | |
| 1213 | + hintDuplicate: "有两个同名实体,它们可能是同一个。", | |
| 1214 | + hintUnsure: "这条断言抽取时把握不大,去读一下原句。", | |
| 1215 | + hintReadBoth: "读一下两边的原句,判断哪条错了。", | |
| 1216 | + closeAssertion: "给断言一个结束日期", | |
| 1217 | + retractAssertion: "撤掉断言", | |
| 1218 | + seeDuplicates: "去看重复实体", | |
| 1219 | + openOntology: "去本体页", | |
| 1220 | + letBothStand: "两边都成立", | |
| 1198 | 1221 | violationVia: (p: string) => `依据 ${p}`, |
| 1199 | 1222 | violationPath: (n: number) => `环上 ${n} 条事实`, |
| 1200 | 1223 | retractFact: "数据错了", |
modified web/src/pages/Review.tsx +140 −7
| @@ -14,6 +14,7 @@ | ||
| 14 | 14 | type ReviewHistoryEvent, |
| 15 | 15 | type ReviewItem, |
| 16 | 16 | type ReviewSide, |
| 17 | + type ViolationResolution, | |
| 17 | 18 | } from "../api"; |
| 18 | 19 | import { PendingFactRow, useCanDecide } from "./PendingFacts"; |
| 19 | 20 | import { S } from "../i18n"; |
| @@ -481,7 +482,9 @@ | ||
| 481 | 482 | inverse_of_itself: S.review.defectInverseSelf, |
| 482 | 483 | inverse_not_mutual: S.review.defectInverseNotMutual, |
| 483 | 484 | sub_property_cycle: S.review.defectSubPropertyCycle, |
| 485 | + rules_disagree: S.review.defectRulesDisagree, | |
| 484 | 486 | }[d.kind]; |
| 487 | + const rules = d.kind === "rules_disagree" ? (d.detail.rules ?? []) : []; | |
| 485 | 488 | // 后两类的后果值得写出来:不可满足的类不会报错,它只是永远空着 |
| 486 | 489 | const unsatisfiable = |
| 487 | 490 | d.kind === "disjoint_with_ancestor" || d.kind === "inherits_disjoint"; |
| @@ -506,6 +509,23 @@ | ||
| 506 | 509 | {S.review.defectNeverInstantiable} |
| 507 | 510 | </p> |
| 508 | 511 | )} |
| 512 | + {rules.length > 0 && ( | |
| 513 | + <div className="mt-1 space-y-1 text-xs text-neutral-400"> | |
| 514 | + <div>{S.review.rulesDisagreeCount(d.detail.count ?? 0)}</div> | |
| 515 | + {rules.map((r, i) => ( | |
| 516 | + <div key={i}> | |
| 517 | + <div className="text-neutral-500"> | |
| 518 | + {S.review.rulesDisagreeRule(r.rule_a, r.via_a, r.rule_b, r.via_b, r.axiom)} | |
| 519 | + </div> | |
| 520 | + {r.examples.map(([x, y], j) => ( | |
| 521 | + <div key={j} className="pl-3 text-neutral-400"> | |
| 522 | + {x} <span className="text-neutral-600">·</span> {y} | |
| 523 | + </div> | |
| 524 | + ))} | |
| 525 | + </div> | |
| 526 | + ))} | |
| 527 | + </div> | |
| 528 | + )} | |
| 509 | 529 | <div className="mt-2 flex gap-1.5"> |
| 510 | 530 | <button |
| 511 | 531 | className="u-btn u-btn-ghost px-3 py-1.5 text-xs" |
| @@ -533,12 +553,14 @@ | ||
| 533 | 553 | violation: v, |
| 534 | 554 | busy, |
| 535 | 555 | onDecide, |
| 556 | + onDuplicates, | |
| 557 | + onOntology, | |
| 536 | 558 | }: { |
| 537 | 559 | violation: AxiomViolation; |
| 538 | 560 | busy: boolean; |
| 539 | - onDecide: ( | |
| 540 | - resolution: "fact_retracted" | "axiom_relaxed" | "accepted", | |
| 541 | - ) => void; | |
| 561 | + onDecide: (resolution: ViolationResolution, closeAt?: string) => void; | |
| 562 | + onDuplicates: () => void; | |
| 563 | + onOntology: () => void; | |
| 542 | 564 | }) { |
| 543 | 565 | const what = { |
| 544 | 566 | self_loop: S.review.violationSelfLoop, |
| @@ -546,7 +568,11 @@ | ||
| 546 | 568 | cycle: S.review.violationCycle, |
| 547 | 569 | functional: S.review.violationFunctional, |
| 548 | 570 | signature: S.review.violationSignature, |
| 571 | + derived_contradiction: S.review.violationDerived, | |
| 549 | 572 | }[v.kind]; |
| 573 | + if (v.kind === "derived_contradiction") { | |
| 574 | + return <ContradictionRow {...{ v, what, busy, onDecide, onDuplicates, onOntology }} />; | |
| 575 | + } | |
| 550 | 576 | // 自反那一类两条事实是同一条——显示一遍就够,显示两遍像个 bug |
| 551 | 577 | const single = v.left_fact === v.right_fact; |
| 552 | 578 | return ( |
| @@ -597,6 +623,109 @@ | ||
| 597 | 623 | ); |
| 598 | 624 | } |
| 599 | 625 | |
| 626 | +/** | |
| 627 | + * 派生撞上断言(0017):卡片是一次审核,线索指向上游的错——旧断言该闭合、 | |
| 628 | + * 两个同名实体其实是一个、抽取本来就没把握。修法就在卡片上,端点替人执行。 | |
| 629 | + */ | |
| 630 | +function ContradictionRow({ | |
| 631 | + v, | |
| 632 | + what, | |
| 633 | + busy, | |
| 634 | + onDecide, | |
| 635 | + onDuplicates, | |
| 636 | + onOntology, | |
| 637 | +}: { | |
| 638 | + v: AxiomViolation; | |
| 639 | + what: string; | |
| 640 | + busy: boolean; | |
| 641 | + onDecide: (resolution: ViolationResolution, closeAt?: string) => void; | |
| 642 | + onDuplicates: () => void; | |
| 643 | + onOntology: () => void; | |
| 644 | +}) { | |
| 645 | + const [closeAt, setCloseAt] = useState(""); | |
| 646 | + const d = v.detail; | |
| 647 | + const hint = | |
| 648 | + v.hint === "stale" | |
| 649 | + ? S.review.hintStale | |
| 650 | + : v.hint === "duplicate" | |
| 651 | + ? S.review.hintDuplicate | |
| 652 | + : v.hint === "unsure" | |
| 653 | + ? S.review.hintUnsure | |
| 654 | + : S.review.hintReadBoth; | |
| 655 | + return ( | |
| 656 | + <div className="glass rounded-xl p-3 border border-[color-mix(in_srgb,var(--u-contest)_35%,transparent)]"> | |
| 657 | + <div className="flex items-baseline gap-2 flex-wrap"> | |
| 658 | + <span className="text-sm text-[var(--u-contest)]">{what}</span> | |
| 659 | + {v.predicate && ( | |
| 660 | + <span className="text-[11px] text-neutral-500"> | |
| 661 | + {S.review.violationVia(v.predicate)} | |
| 662 | + </span> | |
| 663 | + )} | |
| 664 | + </div> | |
| 665 | + <div className="mt-1.5 space-y-1"> | |
| 666 | + <div className="text-xs text-neutral-300"> | |
| 667 | + {S.review.derivedLine(d.subject ?? "?", d.predicate ?? "?", d.object ?? "?")} | |
| 668 | + {d.rule && d.via_label && ( | |
| 669 | + <span className="ml-1.5 text-neutral-500"> | |
| 670 | + {S.review.derivedBy(d.rule, d.via_label)} | |
| 671 | + </span> | |
| 672 | + )} | |
| 673 | + </div> | |
| 674 | + <div className="text-xs text-neutral-300"> | |
| 675 | + {S.review.assertedLine(v.left_text)} | |
| 676 | + </div> | |
| 677 | + </div> | |
| 678 | + <p className="mt-1.5 text-xs text-neutral-500">{hint}</p> | |
| 679 | + <div className="mt-2 flex gap-1.5 flex-wrap items-center"> | |
| 680 | + <input | |
| 681 | + type="date" | |
| 682 | + className="input-dark px-2 py-1 text-xs u-num" | |
| 683 | + value={closeAt} | |
| 684 | + title={S.review.closeAssertion} | |
| 685 | + onChange={(e) => setCloseAt(e.target.value)} | |
| 686 | + /> | |
| 687 | + <button | |
| 688 | + className="u-btn u-btn-primary px-3 py-1.5 text-xs" | |
| 689 | + disabled={busy || !closeAt} | |
| 690 | + onClick={() => | |
| 691 | + onDecide("fact_closed", new Date(closeAt).toISOString()) | |
| 692 | + } | |
| 693 | + > | |
| 694 | + {S.review.closeAssertion} | |
| 695 | + </button> | |
| 696 | + <button | |
| 697 | + className="u-btn u-btn-ghost px-3 py-1.5 text-xs" | |
| 698 | + disabled={busy} | |
| 699 | + onClick={() => onDecide("fact_retracted")} | |
| 700 | + > | |
| 701 | + {S.review.retractAssertion} | |
| 702 | + </button> | |
| 703 | + <button | |
| 704 | + className="u-btn u-btn-ghost px-3 py-1.5 text-xs" | |
| 705 | + disabled={busy} | |
| 706 | + onClick={onDuplicates} | |
| 707 | + > | |
| 708 | + {S.review.seeDuplicates} | |
| 709 | + </button> | |
| 710 | + <button | |
| 711 | + className="u-btn u-btn-ghost px-3 py-1.5 text-xs" | |
| 712 | + disabled={busy} | |
| 713 | + onClick={onOntology} | |
| 714 | + > | |
| 715 | + {S.review.openOntology} | |
| 716 | + </button> | |
| 717 | + <button | |
| 718 | + className="u-btn u-btn-ghost px-3 py-1.5 text-xs" | |
| 719 | + disabled={busy} | |
| 720 | + onClick={() => onDecide("accepted")} | |
| 721 | + > | |
| 722 | + {S.review.letBothStand} | |
| 723 | + </button> | |
| 724 | + </div> | |
| 725 | + </div> | |
| 726 | + ); | |
| 727 | +} | |
| 728 | + | |
| 600 | 729 | /* ---------- 页面:左栏分类 + 单类内容区 ---------- */ |
| 601 | 730 | |
| 602 | 731 | type Sel = |
| @@ -788,10 +917,12 @@ | ||
| 788 | 917 | mutationFn: ({ |
| 789 | 918 | id, |
| 790 | 919 | resolution, |
| 920 | + closeAt, | |
| 791 | 921 | }: { |
| 792 | 922 | id: string; |
| 793 | - resolution: "fact_retracted" | "axiom_relaxed" | "accepted"; | |
| 794 | - }) => api.decideViolation(kb!.id, id, resolution), | |
| 923 | + resolution: ViolationResolution; | |
| 924 | + closeAt?: string; | |
| 925 | + }) => api.decideViolation(kb!.id, id, resolution, closeAt), | |
| 795 | 926 | onSettled: invalidate, |
| 796 | 927 | }); |
| 797 | 928 | // 检查是同步的纯计算,所以直接 mutate 不排队。跑完把报告留在按钮旁边—— |
| @@ -1177,9 +1308,11 @@ | ||
| 1177 | 1308 | violationAction.isPending && |
| 1178 | 1309 | violationAction.variables?.id === v.id |
| 1179 | 1310 | } |
| 1180 | - onDecide={(resolution) => | |
| 1181 | - violationAction.mutate({ id: v.id, resolution }) | |
| 1311 | + onDecide={(resolution, closeAt) => | |
| 1312 | + violationAction.mutate({ id: v.id, resolution, closeAt }) | |
| 1182 | 1313 | } |
| 1314 | + onDuplicates={() => select("duplicates")} | |
| 1315 | + onOntology={() => navigate({ to: "/ontology" })} | |
| 1183 | 1316 | /> |
| 1184 | 1317 | ))} |
| 1185 | 1318 | </div> |
modified web/src/styles.css +2 −0
| @@ -31,6 +31,8 @@ | ||
| 31 | 31 | --u-warn: #f2b66d; |
| 32 | 32 | /* 浅玫瑰:深底上的危险"文字/描边/点"专用(够亮才可读) */ |
| 33 | 33 | --u-danger: #ff9daf; |
| 34 | + /* 0017:争议色。派生撞上断言、被挡下的派生——警告与危险之外的第三种 */ | |
| 35 | + --u-contest: #ff6a3d; | |
| 34 | 36 | /* 深红:危险"实底按钮"专用(浅玫瑰做底会发粉;亮红在单色 chrome 上嗓门过大),配白字 */ |
| 35 | 37 | --u-danger-solid: #c9353a; |
| 36 | 38 | --u-violet: #c4a5ff; |