Skip to content

World's first open-source enterprise world model.

The reasoning engine: R0 in full, and R1 behind a switch (#132)

WaylandYanga46de5d6c099
diff --git a/Cargo.lock b/Cargo.lock
index 927b8640..72700bd8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4877,6 +4877,7 @@ dependencies = [
"url",
"utopia-core",
"utopia-ingest",
+ "utopia-reason",
"uuid",
]
diff --git a/Cargo.toml b/Cargo.toml
index c68e3974..59e8fc65 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -47,6 +47,7 @@ flate2 = "1"
# Phase 1: 摄入/检索/LLM
utopia-ingest = { path = "crates/utopia-ingest" }
+utopia-reason = { path = "crates/utopia-reason" }
utopia-search = { path = "crates/utopia-search" }
utopia-llm = { path = "crates/utopia-llm" }
tantivy = "0.26"
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index f7cab99e..34fde075 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -307,6 +307,9 @@ pub struct EntityTypeView {
pub parents: Vec<Uuid>,
/// 左栏画树时挂在哪一支下。不参与语义,只管展示
pub primary_parent: Option<Uuid>,
+ /// 与这个类互斥的类:**声明「不可能同时是」**。一致性检查据此报出
+ /// 不可满足的类——一个类继承了两个互斥的祖先,就永远不可能有实例(0002)
+ pub disjoint: Vec<Uuid>,
pub description: String,
pub usage: i64,
}
@@ -319,6 +322,12 @@ pub struct RelationTypeView {
pub temporal: String,
pub functional: bool,
pub inverse_functional: bool,
+ /// 其余四条 OWL 公理。**推理机的判据全在这里**(0002)——它们从前只能
+ /// 靠导入 OWL 带进来,在界面上建本体的人永远开不了那台机器
+ pub is_transitive: bool,
+ pub is_symmetric: bool,
+ pub is_asymmetric: bool,
+ pub is_irreflexive: bool,
pub builtin: bool,
pub description: String,
/// relation(宾语是实体)| attribute(宾语是字面值)
@@ -476,6 +485,11 @@ pub struct GraphEdge {
pub label: Option<String>,
/// true = 这条边的名字来自原文,不是本体认下的关系。界面要显示得看得出区别
pub inferred: bool,
+ /// true = 这条边是**推出来的**,不是任何人断言的(R1,住在 `derived_facts`)。
+ ///
+ /// **与 `inferred` 不是一回事**,尽管两个词很近:那一位说的是「名字来自原文
+ /// 而不是本体」,这一位说的是「这条边根本不是谁说的,是引擎推的」
+ pub derived: bool,
pub valid_from: Option<DateTime<Utc>>,
pub valid_to: Option<DateTime<Utc>>,
pub confidence: f32,
@@ -714,6 +728,14 @@ pub struct KnowledgeBase {
/// 内置本体按哪种语言播种,以及新的类/关系描述写成哪种语言(`en` | `zh`)。
/// **跟语料走,不跟界面走**——description 的读者是正在读这些文档的模型。
/// 见 docs/decisions/0004。
+ /// 是否把推出来的事实写进账本(R1)。**缺省关**——这一步往图里加东西,
+ /// 而 0001 判据 2 说「本体是引导不是执法」:声明可能是错的,不该在用户
+ /// 没表态时就按它改图
+ pub materialize_inferences: bool,
+ /// 多久重推一次(分钟)。见 `knowledge_bases.inference_interval_minutes`
+ pub inference_interval_minutes: i32,
+ /// 上次推完的时间。**答的是「上次看过没有」,不是「上次改过没有」**
+ pub last_inference_at: Option<DateTime<Utc>>,
pub ontology_lang: String,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
@@ -805,3 +827,116 @@ pub struct ConceptMapping {
/// 那是把二值状态编码成浮点数,还顺带让它落进「低置信事实」那一档
pub status: String,
}
+
+/// 一处公理违规,配好展示所需的三元组文本(见 `axiom_violations`)。
+///
+/// **两条事实都展开成 主-谓-宾 文本**:Review 页要让人一眼看出矛盾在哪,
+/// 而两个 UUID 看不出任何东西。自反那一类两条相同——它就是一条事实。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct AxiomViolation {
+ pub id: Uuid,
+ /// self_loop | asymmetry | cycle | functional
+ pub kind: String,
+ /// 判据来自哪条关系。人若判「公理写错了」,从这里进本体去改
+ pub predicate: Option<String>,
+ pub left_fact: Uuid,
+ pub left_text: String,
+ pub right_fact: Uuid,
+ pub right_text: String,
+ /// 环的长度(含首尾)。其余三类为 0——前端据此决定要不要显示「查看路径」
+ pub path_len: i32,
+ pub detected_at: chrono::DateTime<chrono::Utc>,
+}
+
+/// 本体自己的一处自相矛盾(见 `ontology_defects`)。
+///
+/// **与 [`AxiomViolation`] 不是一回事**:那个说「事实与定义抵触」,这个说
+/// 「定义自己站不住」。后者更根本——一个自相矛盾的本体会让前者的结论全部可疑。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct OntologyDefect {
+ pub id: Uuid,
+ /// symmetric_and_asymmetric | transitive_and_functional | subclass_cycle
+ /// | disjoint_with_ancestor | inherits_disjoint
+ pub kind: String,
+ /// 出问题那个对象的标签(类或谓词)。查不到就是它已经被删了
+ pub subject_label: Option<String>,
+ /// 另一方:互斥的那个类
+ pub other_label: Option<String>,
+ /// 环上类的标签,按顺序
+ pub path_labels: Vec<String>,
+ pub detected_at: chrono::DateTime<chrono::Utc>,
+}
+
+/// 一条推出来的事实,连同它的证明(实体面板的「推出来的」那一档)。
+///
+/// **`premises` 是这一档存在的理由**:不给出前提的话,一条派生边跟一条普通的边
+/// 在界面上看不出区别,而那正是「推理污染知识」的样子。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct DerivedFactView {
+ pub id: Uuid,
+ pub subject_id: Uuid,
+ pub subject: String,
+ pub object_id: Uuid,
+ pub object: String,
+ pub predicate: String,
+ /// transitive | symmetric——靠哪条规则推的
+ pub rule: String,
+ pub valid_from: Option<DateTime<Utc>>,
+ pub valid_to: Option<DateTime<Utc>>,
+ pub confidence: f32,
+ pub derived_at: DateTime<Utc>,
+ /// 直接前提,按推导顺序展开成三元组文本
+ pub premises: Vec<String>,
+}
+
+/// 审核队列各档的**真实条数**。
+///
+/// 与列表分开取是有意的:列表有上限(一页十条),数数没有。从前左栏读的是
+/// 数组长度,而接口固定只回 100 条——一个有 164 条待办的库,界面写着 100,
+/// 清完还会再冒出来。
+#[derive(Debug, Clone, Copy, Default, Serialize, sqlx::FromRow)]
+pub struct ReviewCounts {
+ pub duplicates: i64,
+ pub conflicts: i64,
+ pub unconfirmed: i64,
+ pub lowconf: i64,
+ pub mappings: i64,
+ pub violations: i64,
+ pub defects: i64,
+ pub merges: i64,
+}
+
+/// 一个关系声明了哪些 OWL 公理。
+///
+/// **六位打包成一个东西传,不是六个参数。** 它们本来就是同一族——推理机
+/// (0002)拿它们当判据,界面上也该并排出现;散成参数表里的六个 bool,
+/// 调用点迟早传错顺序,而 `bool` 之间编译器帮不上忙。
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct RelationAxioms {
+ /// 主语侧唯一(一个人一个出生地)
+ pub functional: bool,
+ /// 宾语侧唯一(一个项目一个 leader)
+ pub inverse_functional: bool,
+ /// A→B ∧ B→C ⟹ A→C
+ pub transitive: bool,
+ /// A→B ⟹ B→A
+ pub symmetric: bool,
+ /// A→B ⟹ 不存在 B→A
+ pub asymmetric: bool,
+ /// 不存在 A→A
+ pub irreflexive: bool,
+}
+
+/// 文库的一页,连同这一页之外的统计。
+///
+/// **统计不受名字/状态筛选影响**:`ready` / `extracting` / `failed` 说的是这个
+/// 来源里有多少,那是批量按钮的作用范围,跟你此刻在搜什么无关。
+#[derive(Debug, Clone, Serialize)]
+pub struct DocumentPage {
+ pub docs: Vec<Document>,
+ /// 命中筛选的总数(分页器用它)
+ pub total: i64,
+ pub ready: i64,
+ pub extracting: i64,
+ pub failed: i64,
+}
diff --git a/crates/utopia-reason/src/derive.rs b/crates/utopia-reason/src/derive.rs
new file mode 100644
index 00000000..00c70374
--- /dev/null
+++ b/crates/utopia-reason/src/derive.rs
@@ -0,0 +1,504 @@
+//! R1:物化推导。**这一层会往图里加东西**,所以它的每一条约束都是必要的。
+//!
+//! 与 R0 的分水岭:R0 只指出问题,风险面为零;R1 写事实。ADR 0002 把这一步
+//! 单列一档,并且给了三条硬性规矩,下面逐条落在代码里。
+//!
+//! **一、规则只从本体公理编译。** 没有用户自定义 DSL——那是另一个产品。
+//! 今天能编译的只有 `TransitiveProperty` 与 `SymmetricProperty`:`inverseOf`
+//! 与 `subPropertyOf` 投影侧还没落库,所以这里也就没有。**少一条规则不是
+//! 缺陷,是「没声明就不推」的同一条**。
+//!
+//! **二、断言优先于派生,硬性。** 已经断言过的三元组不再派生一遍——不是为了
+//! 省行数,是为了让「这条是谁说的」有唯一答案。
+//!
+//! **三、深度上限 + 环检测,实测必需。** ADR 在真实语料上量过:`part_of` 的
+//! 传递闭包从 185 条膨胀到 828 条且**不收敛**,深度分布第 5 层起振荡而不是
+//! 衰减——那是有环的形状。所以这里既不推自环(`A → A` 是矛盾不是知识,交给
+//! R0 报),也在轮数上封顶。
+//!
+//! 还有一条 ADR 列在开放问题里、这里必须给出答案的:**有效时间取交集**。
+//! 前提 A `[2020,2023)`、前提 B `[2022,∞)` → 派生 `[2022,2023)`。交集为空
+//! 就不推——两段没有重叠的时候,链本身在任何时刻都不成立。
+
+use crate::{Axioms, Edge, MAX_DEPTH};
+use std::collections::{HashMap, HashSet};
+use uuid::Uuid;
+
+/// 单个谓词上派生的条数上限。
+///
+/// **不是防御性编程,是拿数量过的**:4.5 倍膨胀出现在一个 185 条边的谓词上,
+/// 而膨胀是超线性的。封顶之后被截掉多少条要**说出来**(见 [`Derivation::capped`])
+/// ——悄悄截断会让「推完了」和「推了一部分」长得一模一样。
+pub const MAX_DERIVED_PER_PREDICATE: usize = 20_000;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Rule {
+ /// `A p B` ∧ `B p C` ⟹ `A p C`
+ Transitive,
+ /// `A p B` ⟹ `B p A`
+ Symmetric,
+}
+
+impl Rule {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Rule::Transitive => "transitive",
+ Rule::Symmetric => "symmetric",
+ }
+ }
+}
+
+/// 一条要落地的派生事实,连同它的证明。
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Derived {
+ pub predicate: Uuid,
+ pub subject: Uuid,
+ pub object: Uuid,
+ pub rule: Rule,
+ /// 用到的前提,按推导顺序。**这是证明树的一层**——R2 展开解释时顺着它走,
+ /// 而前提失效时也靠它知道该让哪些派生跟着失效
+ pub premises: Vec<Uuid>,
+}
+
+/// 一次推导的产出。
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct Derivation {
+ pub facts: Vec<Derived>,
+ /// 撞上上限、没推完的谓词。**必须回给调用方**:界面上要说得出
+ /// 「这个谓词太密,只推了两万条」,而不是让人以为推完了
+ pub capped: Vec<Uuid>,
+}
+
+/// 一条参与推导的边,比 [`Edge`] 多带有效期。
+///
+/// 单独一个类型而不是给 `Edge` 加字段:R0 完全用不上时间——公理是否被违反
+/// 与它什么时候成立无关,而 R1 每一步都要算交集。
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct TimedEdge {
+ pub edge: Edge,
+ /// 半开区间 `[from, to)`。两端都可为空 = 不知道/一直
+ pub from: Option<i64>,
+ pub to: Option<i64>,
+}
+
+/// 交集。`None` 表示无界那一侧。
+fn overlap(
+ a: (Option<i64>, Option<i64>),
+ b: (Option<i64>, Option<i64>),
+) -> Option<(Option<i64>, Option<i64>)> {
+ let from = match (a.0, b.0) {
+ (Some(x), Some(y)) => Some(x.max(y)),
+ (Some(x), None) | (None, Some(x)) => Some(x),
+ (None, None) => None,
+ };
+ let to = match (a.1, b.1) {
+ (Some(x), Some(y)) => Some(x.min(y)),
+ (Some(x), None) | (None, Some(x)) => Some(x),
+ (None, None) => None,
+ };
+ // 空交集不推。两段没有重叠时,这条链在任何时刻都不成立——推出来的是一条
+ // 从不为真的事实,比不推更糟
+ if let (Some(f), Some(t)) = (from, to) {
+ if f >= t {
+ return None;
+ }
+ }
+ Some((from, to))
+}
+
+/// 从某个主语出发的一条边:(宾语, 起, 止, 事实 id)。
+type Hop = (Uuid, Option<i64>, Option<i64>, Uuid);
+
+/// 派生的中间态:一个 (主语, 宾语) 对是怎么来的。
+#[derive(Clone)]
+struct Reached {
+ from: Option<i64>,
+ to: Option<i64>,
+ premises: Vec<Uuid>,
+}
+
+/// 拿公理推一遍这批边。
+pub fn derive(edges: &[TimedEdge], axioms: &HashMap<Uuid, Axioms>) -> Derivation {
+ let mut out = Derivation::default();
+ let mut by_pred: HashMap<Uuid, Vec<TimedEdge>> = HashMap::new();
+ for e in edges {
+ let Some(ax) = axioms.get(&e.edge.predicate) else {
+ continue;
+ };
+ if !ax.transitive && !ax.symmetric {
+ continue;
+ }
+ by_pred.entry(e.edge.predicate).or_default().push(*e);
+ }
+ // 谓词按 id 排序:同一个库两次推导该给出同一份结果
+ let mut preds: Vec<Uuid> = by_pred.keys().copied().collect();
+ preds.sort();
+ for pred in preds {
+ let group = &by_pred[&pred];
+ let ax = axioms[&pred];
+ one_predicate(pred, group, ax, &mut out);
+ }
+ out
+}
+
+fn one_predicate(pred: Uuid, group: &[TimedEdge], ax: Axioms, out: &mut Derivation) {
+ // 断言过的三元组。**派生撞上它就让路**——asserted > derived 是硬性的
+ let asserted: HashSet<(Uuid, Uuid)> = group
+ .iter()
+ .map(|e| (e.edge.subject, e.edge.object))
+ .collect();
+
+ // 已经推出来的 (主, 宾) → 怎么来的。同一对只留第一条证明:
+ // 多条路径都能推出同一件事时,展示哪一条对用户没有区别,而全存下来
+ // 会让证明树的规模跟着路径数走
+ let mut reached: HashMap<(Uuid, Uuid), Reached> = HashMap::new();
+ let mut emitted: Vec<Derived> = Vec::new();
+ let mut capped = false;
+
+ // ---- 对称:一跳就够,不进迭代
+ if ax.symmetric {
+ for e in group {
+ let pair = (e.edge.object, e.edge.subject);
+ if pair.0 == pair.1 || asserted.contains(&pair) || reached.contains_key(&pair) {
+ continue;
+ }
+ reached.insert(
+ pair,
+ Reached {
+ from: e.from,
+ to: e.to,
+ premises: vec![e.edge.fact],
+ },
+ );
+ emitted.push(Derived {
+ predicate: pred,
+ subject: pair.0,
+ object: pair.1,
+ rule: Rule::Symmetric,
+ premises: vec![e.edge.fact],
+ });
+ }
+ }
+
+ // ---- 传递:半朴素求值。frontier 是上一轮新产生的,只有它需要再往下接
+ if ax.transitive {
+ // 从主语出发能走的边。对称推出来的那些也算基础事实——它们已经是我们
+ // 的断言了,链上不该因为「来路不同」断掉
+ let mut base: HashMap<Uuid, Vec<Hop>> = HashMap::new();
+ for e in group {
+ base.entry(e.edge.subject).or_default().push((
+ e.edge.object,
+ e.from,
+ e.to,
+ e.edge.fact,
+ ));
+ }
+ for ((s, o), r) in reached.iter() {
+ if let Some(&p) = r.premises.first() {
+ base.entry(*s).or_default().push((*o, r.from, r.to, p));
+ }
+ }
+
+ let mut frontier: Vec<((Uuid, Uuid), Reached)> = group
+ .iter()
+ .map(|e| {
+ (
+ (e.edge.subject, e.edge.object),
+ Reached {
+ from: e.from,
+ to: e.to,
+ premises: vec![e.edge.fact],
+ },
+ )
+ })
+ .collect();
+
+ // **`MAX_DEPTH - 1` 轮,不是 MAX_DEPTH 轮。** 起始 frontier 里每条已经
+ // 带着一条前提,此后每轮加一条——跑满 MAX_DEPTH 轮会得到 13 条前提的
+ // 证明,而那个常量在 R0 那边的含义是「路径最长 12」。两处得是同一个意思
+ for _ in 0..MAX_DEPTH.saturating_sub(1) {
+ if frontier.is_empty() {
+ break;
+ }
+ let mut next: Vec<((Uuid, Uuid), Reached)> = Vec::new();
+ for ((a, b), acc) in frontier.drain(..) {
+ let Some(outs) = base.get(&b) else {
+ continue;
+ };
+ for &(c, from, to, fact) in outs {
+ // **不推自环。** `A p A` 在一个传递+反对称的谓词上是矛盾
+ // 而不是知识,R0 那边会把这个环连路径一起报出来
+ if a == c {
+ continue;
+ }
+ if asserted.contains(&(a, c)) || reached.contains_key(&(a, c)) {
+ continue;
+ }
+ let Some((nf, nt)) = overlap((acc.from, acc.to), (from, to)) else {
+ continue;
+ };
+ if emitted.len() >= MAX_DERIVED_PER_PREDICATE {
+ capped = true;
+ break;
+ }
+ let mut premises = acc.premises.clone();
+ premises.push(fact);
+ reached.insert(
+ (a, c),
+ Reached {
+ from: nf,
+ to: nt,
+ premises: premises.clone(),
+ },
+ );
+ emitted.push(Derived {
+ predicate: pred,
+ subject: a,
+ object: c,
+ rule: Rule::Transitive,
+ premises: premises.clone(),
+ });
+ next.push((
+ (a, c),
+ Reached {
+ from: nf,
+ to: nt,
+ premises,
+ },
+ ));
+ }
+ if capped {
+ break;
+ }
+ }
+ if capped {
+ break;
+ }
+ frontier = next;
+ }
+ }
+
+ out.facts.extend(emitted);
+ if capped {
+ out.capped.push(pred);
+ }
+}
+
+/// 派生事实的有效期,给落库那一侧用。
+///
+/// 与 [`derive`] 分开是因为交集已经在推导过程里算过了,而调用方拿到的
+/// [`Derived`] 只带前提——重算一次比把区间塞进结果里更省事,也更难错:
+/// 前提就是那几条事实,交集是它们的函数。
+pub fn validity(
+ premises: &[Uuid],
+ by_fact: &HashMap<Uuid, (Option<i64>, Option<i64>)>,
+) -> Option<(Option<i64>, Option<i64>)> {
+ let mut acc = (None, None);
+ for p in premises {
+ let span = *by_fact.get(p)?;
+ acc = overlap(acc, span)?;
+ }
+ Some(acc)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn n(i: u8) -> Uuid {
+ Uuid::from_bytes([i; 16])
+ }
+ fn f(i: u8) -> Uuid {
+ Uuid::from_bytes([i; 16].map(|b| b ^ 0xF0))
+ }
+ /// 一条无时间的边
+ fn e(fact: u8, s: u8, o: u8) -> TimedEdge {
+ TimedEdge {
+ edge: Edge {
+ fact: f(fact),
+ predicate: n(99),
+ subject: n(s),
+ object: n(o),
+ },
+ from: None,
+ to: None,
+ }
+ }
+ /// 一条带区间的边
+ fn te(fact: u8, s: u8, o: u8, from: Option<i64>, to: Option<i64>) -> TimedEdge {
+ TimedEdge {
+ from,
+ to,
+ ..e(fact, s, o)
+ }
+ }
+ fn with(ax: Axioms) -> HashMap<Uuid, Axioms> {
+ HashMap::from([(n(99), ax)])
+ }
+ fn transitive() -> HashMap<Uuid, Axioms> {
+ with(Axioms {
+ transitive: true,
+ ..Default::default()
+ })
+ }
+ fn pairs(d: &Derivation) -> Vec<(u8, u8)> {
+ let mut p: Vec<(u8, u8)> = d
+ .facts
+ .iter()
+ .map(|x| (x.subject.as_bytes()[0], x.object.as_bytes()[0]))
+ .collect();
+ p.sort();
+ p
+ }
+
+ #[test]
+ fn nothing_declared_derives_nothing() {
+ let edges = [e(1, 1, 2), e(2, 2, 3)];
+ assert!(derive(&edges, &HashMap::new()).facts.is_empty());
+ // 声明了别的公理也一样——只有 transitive / symmetric 编得出规则
+ let irr = with(Axioms {
+ irreflexive: true,
+ ..Default::default()
+ });
+ assert!(derive(&edges, &irr).facts.is_empty());
+ }
+
+ #[test]
+ fn a_chain_closes() {
+ // 1→2→3→4,传递应推出 1→3、1→4、2→4
+ let edges = [e(1, 1, 2), e(2, 2, 3), e(3, 3, 4)];
+ let d = derive(&edges, &transitive());
+ assert_eq!(pairs(&d), vec![(1, 3), (1, 4), (2, 4)]);
+ assert!(d.capped.is_empty());
+ }
+
+ #[test]
+ fn the_proof_is_the_premises_in_order() {
+ let edges = [e(1, 1, 2), e(2, 2, 3), e(3, 3, 4)];
+ let d = derive(&edges, &transitive());
+ let long = d
+ .facts
+ .iter()
+ .find(|x| x.subject == n(1) && x.object == n(4))
+ .unwrap();
+ assert_eq!(
+ long.premises,
+ vec![f(1), f(2), f(3)],
+ "证明要按推导顺序带上三条前提"
+ );
+ assert_eq!(long.rule, Rule::Transitive);
+ }
+
+ #[test]
+ fn asserted_beats_derived() {
+ // 1→2、2→3 已经推得出 1→3,而 1→3 也被断言过 → 不重复派生
+ let edges = [e(1, 1, 2), e(2, 2, 3), e(3, 1, 3)];
+ let d = derive(&edges, &transitive());
+ assert!(d.facts.is_empty(), "断言过的三元组不该再派生一份");
+ }
+
+ #[test]
+ fn a_ring_does_not_derive_self_loops_and_does_not_hang() {
+ // 1→2→3→1:环。传递闭包里会推出 1→1,而那是矛盾不是知识
+ let edges = [e(1, 1, 2), e(2, 2, 3), e(3, 3, 1)];
+ let d = derive(&edges, &transitive());
+ assert!(
+ d.facts.iter().all(|x| x.subject != x.object),
+ "自环不该被推出来——R0 会把这个环连路径一起报"
+ );
+ // 但环上其余的推导是成立的:1→3、2→1、3→2
+ assert_eq!(pairs(&d), vec![(1, 3), (2, 1), (3, 2)]);
+ }
+
+ #[test]
+ fn symmetric_derives_the_other_direction_once() {
+ let sym = with(Axioms {
+ symmetric: true,
+ ..Default::default()
+ });
+ let edges = [e(1, 1, 2)];
+ let d = derive(&edges, &sym);
+ assert_eq!(pairs(&d), vec![(2, 1)]);
+ assert_eq!(d.facts[0].rule, Rule::Symmetric);
+ assert_eq!(d.facts[0].premises, vec![f(1)]);
+ // 两个方向都断言过 → 无可派生
+ let both = [e(1, 1, 2), e(2, 2, 1)];
+ assert!(derive(&both, &sym).facts.is_empty());
+ }
+
+ #[test]
+ fn validity_is_the_intersection() {
+ // 1→2 在 [10,30),2→3 在 [20,∞) ⟹ 1→3 在 [20,30)
+ let edges = [te(1, 1, 2, Some(10), Some(30)), te(2, 2, 3, Some(20), None)];
+ let d = derive(&edges, &transitive());
+ assert_eq!(pairs(&d), vec![(1, 3)]);
+ let by_fact = HashMap::from([(f(1), (Some(10), Some(30))), (f(2), (Some(20), None))]);
+ assert_eq!(
+ validity(&d.facts[0].premises, &by_fact),
+ Some((Some(20), Some(30)))
+ );
+ }
+
+ #[test]
+ fn no_overlap_derives_nothing() {
+ // 1→2 只在 [10,20),2→3 只在 [30,40) —— 这条链在任何时刻都不成立
+ let edges = [
+ te(1, 1, 2, Some(10), Some(20)),
+ te(2, 2, 3, Some(30), Some(40)),
+ ];
+ let d = derive(&edges, &transitive());
+ assert!(
+ d.facts.is_empty(),
+ "两段不重叠时推出来的是一条从不为真的事实"
+ );
+ }
+
+ #[test]
+ fn a_touching_boundary_is_not_an_overlap() {
+ // [10,20) 与 [20,30):半开区间,端点相接不算重叠
+ let edges = [
+ te(1, 1, 2, Some(10), Some(20)),
+ te(2, 2, 3, Some(20), Some(30)),
+ ];
+ assert!(derive(&edges, &transitive()).facts.is_empty());
+ }
+
+ #[test]
+ fn depth_is_bounded() {
+ // 一条 40 跳的链,深度上限是 12
+ let edges: Vec<TimedEdge> = (1..=40).map(|i| e(i, i, i + 1)).collect();
+ let d = derive(&edges, &transitive());
+ let longest = d.facts.iter().map(|x| x.premises.len()).max().unwrap();
+ assert!(
+ longest <= MAX_DEPTH,
+ "证明长度不该超过深度上限,实际 {longest}"
+ );
+ assert!(!d.facts.is_empty(), "有上限不等于什么都不推");
+ }
+
+ #[test]
+ fn symmetric_feeds_the_transitive_chain() {
+ // 同时声明对称与传递:1→2 与 3→2 断言过,对称推出 2→3,
+ // 于是传递能接上 1→3
+ let both = with(Axioms {
+ symmetric: true,
+ transitive: true,
+ ..Default::default()
+ });
+ let edges = [e(1, 1, 2), e(2, 3, 2)];
+ let d = derive(&edges, &both);
+ let got = pairs(&d);
+ assert!(got.contains(&(2, 1)) && got.contains(&(2, 3)), "两条对称边");
+ assert!(got.contains(&(1, 3)), "对称推出来的边要能继续参与传递");
+ }
+
+ #[test]
+ fn each_predicate_is_closed_on_its_own() {
+ // 99 传递、98 不是:跨谓词不该接成链
+ let mut other = e(2, 2, 3);
+ other.edge.predicate = n(98);
+ let edges = [e(1, 1, 2), other];
+ let d = derive(&edges, &transitive());
+ assert!(d.facts.is_empty(), "1 →(99) 2 →(98) 3 推不出任何东西");
+ }
+}
diff --git a/crates/utopia-reason/src/lib.rs b/crates/utopia-reason/src/lib.rs
index 1fb8dc7c..e360b031 100644
--- a/crates/utopia-reason/src/lib.rs
+++ b/crates/utopia-reason/src/lib.rs
@@ -12,6 +12,9 @@
//! 没声明就不查——不报矛盾比猜一个公理出来安全。所以一个没装本体包的库跑出来
//! 是零,那是实情不是故障。
+pub mod derive;
+pub mod ontology;
+
use std::collections::{HashMap, HashSet};
use uuid::Uuid;
@@ -43,7 +46,9 @@ impl Axioms {
}
}
-/// 查出来的一处矛盾。`reason` 直接进 `fact_conflicts.reason`。
+/// 查出来的一处矛盾。落库在 `axiom_violations`——**不进 `fact_conflicts`**:
+/// 那张表问的是「哪条对」,而公理违规问的是「错在数据还是错在定义」,
+/// 后者的出路可能是去改本体。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Violation {
pub kind: Kind,
diff --git a/crates/utopia-reason/src/ontology.rs b/crates/utopia-reason/src/ontology.rs
new file mode 100644
index 00000000..c3c52a4d
--- /dev/null
+++ b/crates/utopia-reason/src/ontology.rs
@@ -0,0 +1,392 @@
+//! 本体自己的自洽性:**不碰事实,只看定义**。
+//!
+//! 与 [`crate::check`] 是两件事。那一层问「事实与定义抵触吗」,这一层问
+//! 「定义自己站得住吗」。分开不是分类癖:一个自相矛盾的本体会让事实层的
+//! 结论全部可疑——若某个谓词同时声明了 symmetric 与 asymmetric,那么据它
+//! 报出来的每一条反对称违规都建立在一个本来就不成立的前提上。所以这一层
+//! 的结论要**排在前面**给人看。
+//!
+//! 便宜也是理由:输入只有几千行本体,不用扫账本。
+//!
+//! **同样是「没声明就不查」。** 这里查的每一条都对应本体里写下来的东西,
+//! 没有一条是我们替用户假设的。
+
+use crate::Axioms;
+use std::collections::{HashMap, HashSet};
+use uuid::Uuid;
+
+/// 类层级上溯的深度上限。与 [`crate::MAX_DEPTH`] 同一个理由:本体里可以有环
+/// (建表时只挡得住自环,`A → B → A` 拦不住),没有上限就不终止。
+pub const MAX_ANCESTRY: usize = 32;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub enum Defect {
+ /// 同一个谓词既声明 symmetric 又声明 asymmetric。
+ ///
+ /// OWL 里这两者只能同时对**空**属性成立——一旦有一条边 `A p B`,对称说
+ /// `B p A` 必须成立,反对称说它必须不成立。所以但凡这个谓词上有事实,
+ /// 声明就一定错了一个。
+ SymmetricAndAsymmetric,
+ /// 传递 + 函数性。OWL 2 DL 明文禁止(函数性属性不得声明为传递),
+ /// 因为两者一起会让推理跳出可判定的片段。
+ ///
+ /// 直觉上也讲得通:函数性说「主语侧只有一个值」,传递说「顺着链一直推」,
+ /// 而链上第二跳就给同一个主语推出了第二个值。
+ TransitiveAndFunctional,
+ /// subClassOf 绕成了环。建表时的 CHECK 只挡得住 `A → A`。
+ ///
+ /// 环意味着环上所有类互为子类,即它们其实是同一个类——而它们有各自的
+ /// 标签、描述、属性,界面上也各画一行。
+ SubclassCycle,
+ /// 一个类跟自己的祖先声明了互斥 → 这个类**永远不可能有实例**。
+ /// 它继承了祖先的身份,又声明与之互斥。
+ DisjointWithAncestor,
+ /// 一个类的两个祖先互相互斥 → 同上,不可满足。
+ /// 多父继承下这个形状不罕见:两支各自合理,合起来就矛盾了。
+ InheritsDisjoint,
+}
+
+impl Defect {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Defect::SymmetricAndAsymmetric => "symmetric_and_asymmetric",
+ Defect::TransitiveAndFunctional => "transitive_and_functional",
+ Defect::SubclassCycle => "subclass_cycle",
+ Defect::DisjointWithAncestor => "disjoint_with_ancestor",
+ Defect::InheritsDisjoint => "inherits_disjoint",
+ }
+ }
+}
+
+/// 本体里的一处自相矛盾。
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct OntologyDefect {
+ pub kind: Defect,
+ /// 出问题的那个对象:谓词(前两类)或类(后三类)
+ pub subject: Uuid,
+ /// 另一方:互斥的那个类。前两类与环没有第二方
+ pub other: Option<Uuid>,
+ /// 环的路径(按类排列),或从类到那个祖先的路径。其余为空
+ pub path: Vec<Uuid>,
+}
+
+/// 量一遍本体自己。
+///
+/// `parents` 是 `(子, 父)` 对,`disjoint` 是互斥对——**导入侧已经把对称性
+/// 展开成两行**,所以这里两个方向都会看到,去重靠有序键。
+pub fn check_ontology(
+ axioms: &HashMap<Uuid, Axioms>,
+ parents: &[(Uuid, Uuid)],
+ disjoint: &[(Uuid, Uuid)],
+) -> Vec<OntologyDefect> {
+ let mut out = Vec::new();
+
+ // ---- 谓词上的两处自相矛盾。**排序后再报**:HashMap 的遍历顺序每次不同,
+ // 而同一个本体两次检查出来的结果该是同一份
+ let mut preds: Vec<(&Uuid, &Axioms)> = axioms.iter().collect();
+ preds.sort_by_key(|(id, _)| **id);
+ for (&pred, ax) in preds {
+ if ax.symmetric && ax.asymmetric {
+ out.push(OntologyDefect {
+ kind: Defect::SymmetricAndAsymmetric,
+ subject: pred,
+ other: None,
+ path: Vec::new(),
+ });
+ }
+ if ax.transitive && (ax.functional || ax.inverse_functional) {
+ out.push(OntologyDefect {
+ kind: Defect::TransitiveAndFunctional,
+ subject: pred,
+ other: None,
+ path: Vec::new(),
+ });
+ }
+ }
+
+ let up = adjacency(parents);
+ out.extend(subclass_cycles(&up));
+ out.extend(unsatisfiable(&up, disjoint));
+ out
+}
+
+/// 子 → 父的邻接表。同一对重复声明只留一次。
+fn adjacency(parents: &[(Uuid, Uuid)]) -> HashMap<Uuid, Vec<Uuid>> {
+ let mut up: HashMap<Uuid, Vec<Uuid>> = HashMap::new();
+ for &(child, parent) in parents {
+ let slot = up.entry(child).or_default();
+ if !slot.contains(&parent) {
+ slot.push(parent);
+ }
+ }
+ // 排序保证同一份本体每次算出同一条路径
+ for v in up.values_mut() {
+ v.sort();
+ }
+ up
+}
+
+/// subClassOf 的环。每个环只报一次,键取环上类的有序集合。
+fn subclass_cycles(up: &HashMap<Uuid, Vec<Uuid>>) -> Vec<OntologyDefect> {
+ let mut reported: HashSet<Vec<Uuid>> = HashSet::new();
+ let mut out = Vec::new();
+ let mut starts: Vec<Uuid> = up.keys().copied().collect();
+ starts.sort();
+ for start in starts {
+ let mut path = Vec::new();
+ let mut on_path = HashSet::new();
+ climb(
+ start,
+ start,
+ up,
+ &mut path,
+ &mut on_path,
+ &mut reported,
+ &mut out,
+ );
+ }
+ out
+}
+
+fn climb(
+ start: Uuid,
+ at: Uuid,
+ up: &HashMap<Uuid, Vec<Uuid>>,
+ path: &mut Vec<Uuid>,
+ on_path: &mut HashSet<Uuid>,
+ reported: &mut HashSet<Vec<Uuid>>,
+ out: &mut Vec<OntologyDefect>,
+) {
+ if path.len() >= MAX_ANCESTRY {
+ return;
+ }
+ let Some(ups) = up.get(&at) else {
+ return;
+ };
+ for &parent in ups {
+ if parent == start && !path.is_empty() {
+ // 回到起点:这是一个环。`path` 此刻是 start 之后的那几个类
+ let mut ring = vec![start];
+ ring.extend(path.iter().copied());
+ let mut key = ring.clone();
+ key.sort();
+ key.dedup();
+ if reported.insert(key) {
+ out.push(OntologyDefect {
+ kind: Defect::SubclassCycle,
+ subject: start,
+ other: None,
+ path: ring,
+ });
+ }
+ continue;
+ }
+ if on_path.contains(&parent) || parent == start {
+ // 别处的环,等它自己那一轮报;这里只是别走进去
+ continue;
+ }
+ path.push(parent);
+ on_path.insert(parent);
+ climb(start, parent, up, path, on_path, reported, out);
+ on_path.remove(&parent);
+ path.pop();
+ }
+}
+
+/// 不可满足的类:它的祖先集合里出现了一对互斥。
+///
+/// 两种形状分开报,因为**给人的话不一样**:跟自己的祖先互斥是「这条 disjoint
+/// 声明写反了」,而两个祖先互斥是「这个类不该同时挂在这两支下」。
+fn unsatisfiable(up: &HashMap<Uuid, Vec<Uuid>>, disjoint: &[(Uuid, Uuid)]) -> Vec<OntologyDefect> {
+ let pairs: HashSet<(Uuid, Uuid)> = disjoint.iter().copied().collect();
+ if pairs.is_empty() {
+ return Vec::new();
+ }
+ let mut out = Vec::new();
+ let mut classes: Vec<Uuid> = up.keys().copied().collect();
+ classes.sort();
+ for class in classes {
+ let anc = ancestors(class, up);
+ // 一、跟自己的祖先互斥
+ for &a in &anc {
+ if pairs.contains(&(class, a)) {
+ out.push(OntologyDefect {
+ kind: Defect::DisjointWithAncestor,
+ subject: class,
+ other: Some(a),
+ path: Vec::new(),
+ });
+ }
+ }
+ // 二、两个祖先互相互斥。有序对去重,否则展开成两行的 disjoint 会报两遍
+ let mut sorted: Vec<Uuid> = anc.iter().copied().collect();
+ sorted.sort();
+ for (i, &a) in sorted.iter().enumerate() {
+ for &b in &sorted[i + 1..] {
+ if pairs.contains(&(a, b)) {
+ out.push(OntologyDefect {
+ kind: Defect::InheritsDisjoint,
+ subject: class,
+ other: Some(b),
+ path: vec![a],
+ });
+ }
+ }
+ }
+ }
+ out
+}
+
+/// 一个类的全部祖先(不含自己)。有环也不会转不出来——`seen` 挡住。
+fn ancestors(class: Uuid, up: &HashMap<Uuid, Vec<Uuid>>) -> HashSet<Uuid> {
+ let mut seen = HashSet::new();
+ let mut queue = vec![(class, 0usize)];
+ while let Some((at, depth)) = queue.pop() {
+ if depth >= MAX_ANCESTRY {
+ continue;
+ }
+ let Some(ups) = up.get(&at) else {
+ continue;
+ };
+ for &parent in ups {
+ if parent != class && seen.insert(parent) {
+ queue.push((parent, depth + 1));
+ }
+ }
+ }
+ seen
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn c(i: u8) -> Uuid {
+ Uuid::from_bytes([i; 16])
+ }
+ fn kinds(v: &[OntologyDefect]) -> Vec<Defect> {
+ let mut k: Vec<Defect> = v.iter().map(|d| d.kind).collect();
+ k.sort();
+ k
+ }
+ fn ax(f: impl Fn(&mut Axioms)) -> HashMap<Uuid, Axioms> {
+ let mut a = Axioms::default();
+ f(&mut a);
+ HashMap::from([(c(99), a)])
+ }
+
+ #[test]
+ fn a_property_cannot_be_both_symmetric_and_asymmetric() {
+ let a = ax(|a| {
+ a.symmetric = true;
+ a.asymmetric = true;
+ });
+ let d = check_ontology(&a, &[], &[]);
+ assert_eq!(kinds(&d), vec![Defect::SymmetricAndAsymmetric]);
+ assert_eq!(d[0].subject, c(99));
+ }
+
+ #[test]
+ fn either_one_alone_is_fine() {
+ assert!(check_ontology(&ax(|a| a.symmetric = true), &[], &[]).is_empty());
+ assert!(check_ontology(&ax(|a| a.asymmetric = true), &[], &[]).is_empty());
+ // 传递 + 反对称是**正常的**——它正是环检测有意义的前提
+ let both = ax(|a| {
+ a.transitive = true;
+ a.asymmetric = true;
+ });
+ assert!(check_ontology(&both, &[], &[]).is_empty());
+ }
+
+ #[test]
+ fn transitive_and_functional_is_forbidden_by_owl2() {
+ let a = ax(|a| {
+ a.transitive = true;
+ a.functional = true;
+ });
+ assert_eq!(
+ kinds(&check_ontology(&a, &[], &[])),
+ vec![Defect::TransitiveAndFunctional]
+ );
+ // 反函数性同理
+ let b = ax(|a| {
+ a.transitive = true;
+ a.inverse_functional = true;
+ });
+ assert_eq!(
+ kinds(&check_ontology(&b, &[], &[])),
+ vec![Defect::TransitiveAndFunctional]
+ );
+ }
+
+ #[test]
+ fn subclass_of_can_form_a_ring() {
+ let none = HashMap::new();
+ // 1 → 2 → 3 → 1
+ let ring = [(c(1), c(2)), (c(2), c(3)), (c(3), c(1))];
+ let d = check_ontology(&none, &ring, &[]);
+ assert_eq!(kinds(&d), vec![Defect::SubclassCycle], "三个类绕成一圈");
+ assert_eq!(d.len(), 1, "同一个环只报一次,不是每个类各报一次");
+ assert_eq!(d[0].path.len(), 3, "路径要带上环上全部三个类");
+ }
+
+ #[test]
+ fn a_tree_is_not_a_ring() {
+ let none = HashMap::new();
+ // 多父也不是环:4 同时挂在 2 与 3 下
+ let tree = [(c(1), c(2)), (c(1), c(3)), (c(4), c(2)), (c(4), c(3))];
+ assert!(check_ontology(&none, &tree, &[]).is_empty());
+ }
+
+ #[test]
+ fn a_class_disjoint_with_its_own_ancestor_can_never_exist() {
+ let none = HashMap::new();
+ let parents = [(c(1), c(2)), (c(2), c(3))];
+ // 导入侧把 disjoint 的对称性展开成两行,这里照样给两行
+ let dis = [(c(1), c(3)), (c(3), c(1))];
+ let d = check_ontology(&none, &parents, &dis);
+ assert_eq!(kinds(&d), vec![Defect::DisjointWithAncestor]);
+ assert_eq!(d[0].subject, c(1));
+ assert_eq!(d[0].other, Some(c(3)), "指出跟哪个祖先互斥——人要去改那一条");
+ }
+
+ #[test]
+ fn two_disjoint_ancestors_make_a_class_unsatisfiable() {
+ let none = HashMap::new();
+ // 1 同时是 2 与 3 的子类,而 2 与 3 互斥
+ let parents = [(c(1), c(2)), (c(1), c(3))];
+ let dis = [(c(2), c(3)), (c(3), c(2))];
+ let d = check_ontology(&none, &parents, &dis);
+ assert_eq!(kinds(&d), vec![Defect::InheritsDisjoint]);
+ assert_eq!(d.len(), 1, "展开成两行的 disjoint 不该报两遍");
+ assert_eq!(d[0].subject, c(1));
+ }
+
+ #[test]
+ fn disjoint_between_unrelated_branches_is_the_point_of_disjoint() {
+ let none = HashMap::new();
+ // 2 与 3 互斥,而 1 只挂在 2 下、4 只挂在 3 下——这正是 disjoint 的正常用法
+ let parents = [(c(1), c(2)), (c(4), c(3))];
+ let dis = [(c(2), c(3)), (c(3), c(2))];
+ assert!(check_ontology(&none, &parents, &dis).is_empty());
+ }
+
+ #[test]
+ fn a_ring_does_not_hang_the_ancestor_walk() {
+ let none = HashMap::new();
+ let ring = [(c(1), c(2)), (c(2), c(1))];
+ let dis = [(c(1), c(2)), (c(2), c(1))];
+ // 环 + 互斥同时存在:既要报环,也不能在上溯时转不出来
+ let d = check_ontology(&none, &ring, &dis);
+ assert!(d.iter().any(|x| x.kind == Defect::SubclassCycle));
+ assert!(d.iter().any(|x| x.kind == Defect::DisjointWithAncestor));
+ }
+
+ #[test]
+ fn nothing_declared_means_nothing_reported() {
+ assert!(check_ontology(&HashMap::new(), &[], &[]).is_empty());
+ // 类层级齐全但一条 disjoint 都没有 → 没有判据
+ let parents = [(c(1), c(2)), (c(2), c(3))];
+ assert!(check_ontology(&HashMap::new(), &parents, &[]).is_empty());
+ }
+}
diff --git a/crates/utopia-search/src/lib.rs b/crates/utopia-search/src/lib.rs
index 5fa69c6d..9a30bf0a 100644
--- a/crates/utopia-search/src/lib.rs
+++ b/crates/utopia-search/src/lib.rs
@@ -110,6 +110,17 @@ impl SearchIndex {
Ok(())
}
+ /// 索引里有多少条分块。**启动时拿它跟库里的数对账**——索引目录是独立于
+ /// 数据库的一份文件(换机器、卷没挂上、损坏都可能让它落空),而落空之后
+ /// 检索只会静默回零,界面上看不出任何异样。
+ pub fn len(&self) -> usize {
+ self.reader.searcher().num_docs() as usize
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+
/// BM25 检索(限定 kb)。
/// 查询用与索引完全一致的 jieba analyzer 切词后按 OR 组合——
/// 不能走 QueryParser:CJK 整句会被当成短语查询(要求词连续出现),召回归零。
diff --git a/crates/utopia-server/src/api/chat.rs b/crates/utopia-server/src/api/chat.rs
index 95b8dd9f..2d7f159a 100644
--- a/crates/utopia-server/src/api/chat.rs
+++ b/crates/utopia-server/src/api/chat.rs
@@ -2,7 +2,7 @@
//! 事件序列:step*(行动轨迹)| sources(引用清单,随检索增量更新)| delta*(增量文本)→ done | error。
//! 模型不支持 tool-calling 时自动降级为一次性 RAG 注入。
-use axum::extract::{Path, State};
+use axum::extract::{Path, Query, State};
use axum::response::sse::{Event, KeepAlive, Sse};
use axum::Json;
use futures_util::{Stream, StreamExt};
@@ -612,7 +612,8 @@ pub async fn chat(
}
"find_entities" => {
let name = args["name"].as_str().unwrap_or("").to_string();
- let hits = utopia_store::graph::search_entities(&state.pool, kb_id, &name, 8)
+ let (hits, _) =
+ utopia_store::graph::search_entities(&state.pool, kb_id, &name, 8, 0)
.await
.unwrap_or_default();
let text = if hits.is_empty() {
@@ -1045,14 +1046,57 @@ fn truncate(text: &str, max_chars: usize) -> String {
// 会话管理(列表 / 回放 / 删除)
// ---------------------------------------------------------------------------
+#[derive(serde::Deserialize)]
+pub struct ConversationsQuery {
+ /// 搜标题与消息正文两处:人记得住的往往是问过的那句话,不是标题
+ #[serde(default)]
+ pub q: Option<String>,
+ #[serde(default)]
+ pub limit: Option<i64>,
+ #[serde(default)]
+ pub offset: Option<i64>,
+}
+
pub async fn list_conversations(
State(state): State<AppState>,
AuthUser(user): AuthUser,
Path(kb_id): Path<Uuid>,
+ Query(q): Query<ConversationsQuery>,
+) -> ApiResult<Json<serde_json::Value>> {
+ utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
+ let (conversations, total) = utopia_store::conversations::list(
+ &state.pool,
+ kb_id,
+ user.id,
+ q.q.as_deref().map(str::trim).filter(|s| !s.is_empty()),
+ q.limit.unwrap_or(30).clamp(1, 100),
+ q.offset.unwrap_or(0).max(0),
+ )
+ .await?;
+ Ok(Json(
+ json!({ "conversations": conversations, "total": total }),
+ ))
+}
+
+#[derive(serde::Deserialize)]
+pub struct RenameConversationReq {
+ pub title: String,
+}
+
+/// 改会话标题。
+///
+/// **标题本来是从第一句话自动取的**,而一段对话跑偏是常态——改名让人能按
+/// 自己记得的方式找回它。
+pub async fn rename_conversation(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>,
+ Json(req): Json<RenameConversationReq>,
) -> ApiResult<Json<serde_json::Value>> {
utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
- let conversations = utopia_store::conversations::list(&state.pool, kb_id, user.id).await?;
- Ok(Json(json!({ "conversations": conversations })))
+ utopia_store::conversations::rename(&state.pool, kb_id, user.id, conversation_id, &req.title)
+ .await?;
+ Ok(Json(json!({ "ok": true })))
}
/// 历史回放:消息含落库的行动轨迹(steps)与引用(sources)。
diff --git a/crates/utopia-server/src/api/documents_routes.rs b/crates/utopia-server/src/api/documents_routes.rs
index f3eaa282..425292e5 100644
--- a/crates/utopia-server/src/api/documents_routes.rs
+++ b/crates/utopia-server/src/api/documents_routes.rs
@@ -107,14 +107,88 @@ pub async fn upload(
Ok(Json(json!({ "created": created, "skipped": skipped })))
}
+#[derive(serde::Deserialize)]
+pub struct DocsQuery {
+ /// 来源作用域:缺省 = 全部;`none` = 没有来源的;否则一个来源 id
+ #[serde(default)]
+ pub source: Option<String>,
+ /// 文件名包含
+ #[serde(default)]
+ pub q: Option<String>,
+ /// 抽取状态:none | queued | extracting | done | failed
+ #[serde(default)]
+ pub graph: Option<String>,
+ #[serde(default)]
+ pub limit: Option<i64>,
+ #[serde(default)]
+ pub offset: Option<i64>,
+}
+
+/// 文库一页。
+///
+/// **改成服务端筛选与分页**:从前一次取回整库、前端切片。27 篇没事,两万篇会把
+/// 整张表打进浏览器;而客户端筛选还有个更隐蔽的毛病——它只筛得到已经拿下来的那些。
pub async fn list(
State(state): State<AppState>,
AuthUser(user): AuthUser,
Path(kb_id): Path<Uuid>,
-) -> ApiResult<Json<Vec<Document>>> {
+ Query(q): Query<DocsQuery>,
+) -> ApiResult<Json<utopia_core::models::DocumentPage>> {
utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
- let docs = utopia_store::documents::list(&state.pool, kb_id).await?;
- Ok(Json(docs))
+ let page = utopia_store::documents::page(
+ &state.pool,
+ kb_id,
+ parse_scope(q.source.as_deref()),
+ q.q.as_deref().map(str::trim).filter(|s| !s.is_empty()),
+ q.graph.as_deref().filter(|s| !s.is_empty()),
+ q.limit.unwrap_or(15).clamp(1, 200),
+ q.offset.unwrap_or(0).max(0),
+ )
+ .await?;
+ Ok(Json(page))
+}
+
+/// `None` = 全部,`Some(None)` = 没有来源的,`Some(Some(id))` = 某个来源。
+///
+/// 认不出的字符串当成「全部」而不是报错:这个参数来自界面上的一次点击,
+/// 而一次点击不该把整页变成一条错误。
+fn parse_scope(raw: Option<&str>) -> Option<Option<Uuid>> {
+ match raw {
+ None | Some("") => None,
+ Some("none") => Some(None),
+ Some(s) => s.parse().ok().map(Some),
+ }
+}
+
+/// 一键重试这个作用域里全部抽取失败的文档。
+///
+/// **存在的理由是一条条点太慢**:一个来源里五篇失败就是点五次,而失败往往是
+/// 成批的(模型端点断了一阵,那段时间进来的全挂)。
+pub async fn retry_failed(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Query(q): Query<DocsQuery>,
+) -> ApiResult<Json<serde_json::Value>> {
+ utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Editor).await?;
+ let ids =
+ utopia_store::documents::failed_ids(&state.pool, kb_id, parse_scope(q.source.as_deref()))
+ .await?;
+ // 逐个入队而不是一条 SQL 批量改状态:排队本身有别的动作(解雇在跑的任务、
+ // 清增量标记),那些在 `queue_extraction_one` 里,绕过它会留下半截状态
+ let mut queued = 0usize;
+ for id in &ids {
+ if utopia_store::documents::queue_extraction_one(&state.pool, *id)
+ .await
+ .is_ok()
+ {
+ queued += 1;
+ }
+ }
+ if queued > 0 {
+ state.emit_document(kb_id, ids[0]);
+ }
+ Ok(Json(json!({ "queued": queued, "found": ids.len() })))
}
/// 文档详情 + 全部分块(文档查看器用)。
diff --git a/crates/utopia-server/src/api/graph_routes.rs b/crates/utopia-server/src/api/graph_routes.rs
index ab67dd4f..c28a8648 100644
--- a/crates/utopia-server/src/api/graph_routes.rs
+++ b/crates/utopia-server/src/api/graph_routes.rs
@@ -32,6 +32,10 @@ fn parse_at(raw: Option<&str>) -> Result<Option<chrono::DateTime<chrono::Utc>>,
.map_err(|_| AppError::Validation("Invalid `at` (expected YYYY-MM-DD or RFC3339)".into()))
}
+/// 总览一次画多少个节点。**上限本身是合理的**——画一万个点没人看得懂;
+/// 骗人的是把它当成规模显示,所以接口同时回总数
+const GRAPH_NODE_CAP: i64 = 150;
+
#[derive(Deserialize)]
pub struct OverviewQuery {
#[serde(default)]
@@ -46,8 +50,14 @@ pub async fn overview(
) -> ApiResult<Json<serde_json::Value>> {
require_kb(&state, &user, kb_id, Role::Viewer).await?;
let at = parse_at(q.at.as_deref())?;
- let (nodes, edges) = utopia_store::graph::overview(&state.pool, kb_id, 150, at).await?;
- Ok(Json(json!({ "nodes": nodes, "edges": edges })))
+ // 画多少个是渲染的事,库里有多少是知识库的事——两个数都回,界面才说得出
+ // 「画了 150 个,共 325 个」而不是把上限说成规模
+ let (nodes, edges, total_nodes, total_edges) =
+ utopia_store::graph::overview(&state.pool, kb_id, GRAPH_NODE_CAP, at).await?;
+ Ok(Json(json!({
+ "nodes": nodes, "edges": edges,
+ "total_nodes": total_nodes, "total_edges": total_edges,
+ })))
}
#[derive(Deserialize)]
@@ -76,6 +86,10 @@ pub async fn neighborhood(
#[derive(Deserialize)]
pub struct EntitySearchQuery {
pub q: String,
+ #[serde(default)]
+ pub limit: Option<i64>,
+ #[serde(default)]
+ pub offset: Option<i64>,
}
pub async fn search_entities(
@@ -86,10 +100,19 @@ pub async fn search_entities(
) -> ApiResult<Json<serde_json::Value>> {
require_kb(&state, &user, kb_id, Role::Viewer).await?;
if query.q.trim().is_empty() {
- return Ok(Json(json!({ "entities": [] })));
+ return Ok(Json(json!({ "entities": [], "total": 0 })));
}
- let entities = utopia_store::graph::search_entities(&state.pool, kb_id, &query.q, 10).await?;
- Ok(Json(json!({ "entities": entities })))
+ // 一并回总数:「宁分勿合」本来就会造出一堆同名,固定十条时想找的那个
+ // 可能根本不在这十条里,而界面上看不出来
+ let (entities, total) = utopia_store::graph::search_entities(
+ &state.pool,
+ kb_id,
+ &query.q,
+ query.limit.unwrap_or(10).clamp(1, 100),
+ query.offset.unwrap_or(0).max(0),
+ )
+ .await?;
+ Ok(Json(json!({ "entities": entities, "total": total })))
}
pub async fn entity_detail(
@@ -99,7 +122,21 @@ pub async fn entity_detail(
) -> ApiResult<Json<serde_json::Value>> {
require_kb(&state, &user, kb_id, Role::Viewer).await?;
let (entity, facts) = utopia_store::graph::entity_detail(&state.pool, kb_id, entity_id).await?;
- Ok(Json(json!({ "entity": entity, "facts": facts })))
+ // 推出来的那些**单独回一个键**,不掺进 `facts`。前端据此给它们自己的一档:
+ // 一条派生边跟一条断言边混在同一个列表里,用户看不出「这条是文档里写的」
+ // 和「这条是引擎推的」的区别,而那正是推理会污染知识的样子
+ let derived =
+ utopia_store::reasoning::derived_for_entity(&state.pool, kb_id, entity_id).await?;
+ // 同名的那些**打开面板时就给**,不是等改名之后才回。
+ //
+ // 从前它只随 `update_entity` 的响应回来,于是「把同名的合并进来」这个动作
+ // 只有先改一次名才够得着——而两个张伟并存是「宁分勿合」的正当产物,不是
+ // 改名改出来的。合并入口该长在能看见同名的地方。
+ let same_name = utopia_store::graph::same_name_peers(&state.pool, kb_id, entity_id).await?;
+ Ok(Json(json!({
+ "entity": entity, "facts": facts,
+ "derived": derived, "same_name": same_name,
+ })))
}
#[derive(Deserialize)]
diff --git a/crates/utopia-server/src/api/kbs.rs b/crates/utopia-server/src/api/kbs.rs
index 9cd9bd1a..06a38163 100644
--- a/crates/utopia-server/src/api/kbs.rs
+++ b/crates/utopia-server/src/api/kbs.rs
@@ -1,4 +1,4 @@
-use axum::extract::{Path, State};
+use axum::extract::{Path, Query, State};
use axum::Json;
use serde::Deserialize;
use serde_json::json;
@@ -38,6 +38,12 @@ pub struct UpdateKbReq {
/// 本体语言(`en` | `zh`):跟语料走,不跟界面走。见 docs/decisions/0004
#[serde(default)]
pub ontology_lang: Option<String>,
+ /// 物化推理开关(缺省关)。见 docs/decisions/0002 R1
+ #[serde(default)]
+ pub materialize_inferences: Option<bool>,
+ /// 多久重推一次(分钟)。事实持续在变,只靠手点会让派生一直是缺的
+ #[serde(default)]
+ pub inference_interval_minutes: Option<i32>,
}
/// 用户可见的 KB 列表(restricted 库仅矩阵成员与系统管理员可见)。
@@ -85,7 +91,18 @@ pub async fn create(
)
.await?;
if let Some(v) = req.visibility.as_deref() {
- utopia_store::kbs::update(&state.pool, kb.id, None, None, Some(v), None, None).await?;
+ utopia_store::kbs::update(
+ &state.pool,
+ kb.id,
+ None,
+ None,
+ Some(v),
+ None,
+ None,
+ None,
+ None,
+ )
+ .await?;
}
utopia_store::access::set_kb_member(&state.pool, kb.id, user.id, "admin", Some(user.id))
.await?;
@@ -161,6 +178,8 @@ pub async fn update(
req.visibility.as_deref(),
req.auto_extend_ontology,
req.ontology_lang.as_deref(),
+ req.materialize_inferences,
+ req.inference_interval_minutes,
)
.await?;
// 审计只记不阻断
@@ -260,14 +279,66 @@ pub async fn remove_member(
}
/// 库级审计日志(Admin 起步;纯审计展示)。
+#[derive(Deserialize)]
+pub struct AuditQuery {
+ /// 动作前缀。`entity.` 捞出 entity.retyped / entity.renamed 一族
+ #[serde(default)]
+ pub action: Option<String>,
+ #[serde(default)]
+ pub actor: Option<Uuid>,
+ /// 含起点、不含终点,与半开区间的惯例一致
+ #[serde(default)]
+ pub since: Option<String>,
+ #[serde(default)]
+ pub until: Option<String>,
+ #[serde(default)]
+ pub limit: Option<i64>,
+ #[serde(default)]
+ pub offset: Option<i64>,
+}
+
+/// 日期参数:按天给(`2026-08-30`)或 RFC3339 都收。
+fn parse_day(raw: Option<&str>) -> Result<Option<chrono::DateTime<chrono::Utc>>, AppError> {
+ let Some(s) = raw.map(str::trim).filter(|s| !s.is_empty()) else {
+ return Ok(None);
+ };
+ if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
+ return Ok(Some(d.and_hms_opt(0, 0, 0).unwrap().and_utc()));
+ }
+ chrono::DateTime::parse_from_rfc3339(s)
+ .map(|t| Some(t.with_timezone(&chrono::Utc)))
+ .map_err(|_| AppError::invalid("bad_date", "expected YYYY-MM-DD or RFC3339"))
+}
+
+/// 审计台账。**分页 + 筛选**——从前是固定最近 100 条,而台账是合规材料,
+/// 「只看得到最近一百条」等于查不了历史。
pub async fn audit_log(
State(state): State<AppState>,
AuthUser(user): AuthUser,
Path(id): Path<Uuid>,
+ Query(q): Query<AuditQuery>,
) -> ApiResult<Json<serde_json::Value>> {
kb_with_role(&state, &user, id, Role::Admin).await?;
- let events = utopia_store::audit::list_for_kb(&state.pool, id, 100).await?;
- Ok(Json(json!({ "events": events })))
+ let limit = q.limit.unwrap_or(50).clamp(1, 200);
+ let offset = q.offset.unwrap_or(0).max(0);
+ let action = q.action.as_deref().map(str::trim).filter(|s| !s.is_empty());
+ let (events, total) = utopia_store::audit::list_for_kb(
+ &state.pool,
+ id,
+ action,
+ q.actor,
+ parse_day(q.since.as_deref())?,
+ parse_day(q.until.as_deref())?,
+ limit,
+ offset,
+ )
+ .await?;
+ // 下拉按这个库实际发生过的动作填,而不是一份硬编码清单——
+ // 后者会列出一堆这个库从来没有过的选项
+ let actions = utopia_store::audit::actions_for_kb(&state.pool, id).await?;
+ Ok(Json(
+ json!({ "events": events, "total": total, "actions": actions }),
+ ))
}
/// 建库时装选中的本体包。
///
diff --git a/crates/utopia-server/src/api/members_routes.rs b/crates/utopia-server/src/api/members_routes.rs
index ecbeff32..48e421aa 100644
--- a/crates/utopia-server/src/api/members_routes.rs
+++ b/crates/utopia-server/src/api/members_routes.rs
@@ -36,6 +36,23 @@ pub async fn org_users(
))
}
+/// 已停用的账号。**仅管理员**——它是一份「谁被停了」的名单,
+/// 而恢复本来就是管理员动作。
+///
+/// 没有这个接口的时候,恢复是一条死路:停用的人从每一个列表里消失,
+/// 管理员拿不到 id,而 `POST /admin/users/{id}` 要的正是那个 id。
+pub async fn deactivated_users(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+) -> ApiResult<Json<Vec<OrgUser>>> {
+ if !user.is_admin {
+ return Err(utopia_core::AppError::Forbidden.into());
+ }
+ Ok(Json(
+ utopia_store::members::deactivated_users(&state.pool, user.org_id).await?,
+ ))
+}
+
#[derive(Deserialize)]
pub struct SetRoleReq {
pub role: String,
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index 8ca47825..6446319e 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -74,6 +74,8 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
axum::routing::put(members_routes::set_role).delete(members_routes::remove),
)
.route("/users", get(members_routes::org_users))
+ // 已停用的账号:没有这一条,恢复就够不着(那个人从所有列表里消失)
+ .route("/users/deactivated", get(members_routes::deactivated_users))
.route(
"/kbs/{id}",
patch(kbs::update).get(kbs::get_one).delete(kbs::delete),
@@ -131,6 +133,11 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
.post(documents_routes::upload)
.layer(DefaultBodyLimit::max(MAX_UPLOAD_BYTES)),
)
+ // 一键重试:抽取失败往往是成批的(模型端点断了一阵,那段时间进来的全挂)
+ .route(
+ "/kbs/{id}/documents/retry-failed",
+ post(documents_routes::retry_failed),
+ )
.route(
"/kbs/{id}/extraction-drops",
get(documents_routes::extraction_drops),
@@ -221,7 +228,9 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
.route("/kbs/{id}/conversations", get(chat::list_conversations))
.route(
"/kbs/{id}/conversations/{conversation_id}",
- get(chat::conversation_detail).delete(chat::delete_conversation),
+ get(chat::conversation_detail)
+ .patch(chat::rename_conversation)
+ .delete(chat::delete_conversation),
)
.route(
"/documents/{id}",
@@ -295,6 +304,25 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
"/kbs/{id}/review/mappings/{mapping_id}",
post(review_routes::decide_mapping),
)
+ // 一致性检查(0002 R0):跑一遍,与裁决一处违规。
+ // 检查本身是纯计算,同步跑
+ .route(
+ "/kbs/{id}/consistency/check",
+ post(review_routes::run_consistency_check),
+ )
+ .route(
+ "/kbs/{id}/review/violations/{violation_id}",
+ post(review_routes::decide_violation),
+ )
+ .route(
+ "/kbs/{id}/review/defects/{defect_id}",
+ post(review_routes::decide_defect),
+ )
+ // R1 物化推导。受 KB 上的 materialize_inferences 开关约束
+ .route(
+ "/kbs/{id}/inference/run",
+ post(review_routes::run_inference),
+ )
.route(
"/kbs/{id}/facts/{fact_id}/confirm",
post(review_routes::confirm_fact),
diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rs
index db5c2933..f8e125b6 100644
--- a/crates/utopia-server/src/api/ontology_routes.rs
+++ b/crates/utopia-server/src/api/ontology_routes.rs
@@ -86,6 +86,10 @@ pub struct EntityTypeReq {
/// 界面上写明了这条,所以不额外给一个"选主父"的控件
#[serde(default)]
pub parents: Vec<Uuid>,
+ /// 与它互斥的类。**缺省 = 不动**——不管互斥的调用方(提案采纳、冷启动)
+ /// 不该因为一次建类就把已有的声明清空
+ #[serde(default)]
+ pub disjoint: Option<Vec<Uuid>>,
/// 语义指引,注入抽取 prompt
#[serde(default)]
pub description: Option<String>,
@@ -115,6 +119,11 @@ pub async fn create_entity_type(
req.description.as_deref().unwrap_or("").trim(),
)
.await?;
+ // 互斥缺省 = 不动:不管它的调用方(提案采纳、冷启动)不该因为建一个类
+ // 就把已有的声明清空
+ if let Some(d) = req.disjoint.as_deref() {
+ utopia_store::ontology::set_disjoint_for(&state.pool, kb_id, id, d).await?;
+ }
// 审计只记不阻断
let _ = utopia_store::audit::record(
&state.pool,
@@ -147,6 +156,9 @@ pub async fn update_entity_type(
req.description.as_deref().unwrap_or("").trim(),
)
.await?;
+ if let Some(d) = req.disjoint.as_deref() {
+ utopia_store::ontology::set_disjoint_for(&state.pool, kb_id, id, d).await?;
+ }
let _ = utopia_store::audit::record(
&state.pool,
Some(kb_id),
@@ -191,6 +203,20 @@ pub struct RelationTypeReq {
pub functional: bool,
#[serde(default)]
pub inverse_functional: bool,
+ /// 其余四条 OWL 公理。**必须能在界面上编**——推理机(0002)的判据全部
+ /// 来自这几位,而它们从前只能靠导入 OWL 文件带进来:一个在界面上手工建
+ /// 本体的用户,永远开不了那台机器。
+ ///
+ /// 与 `functional` / `inverse_functional` 并排,因为它们本来就是同一族,
+ /// 只是那两个先落库了
+ #[serde(default)]
+ pub is_transitive: bool,
+ #[serde(default)]
+ pub is_symmetric: bool,
+ #[serde(default)]
+ pub is_asymmetric: bool,
+ #[serde(default)]
+ pub is_irreflexive: bool,
#[serde(default)]
pub description: Option<String>,
/// relation | attribute(创建时定死,更新时忽略)
@@ -211,6 +237,20 @@ pub struct RelationTypeReq {
pub unit: Option<String>,
}
+impl RelationTypeReq {
+ /// 六位公理打包。**散着传迟早传错顺序**——它们都是 bool,编译器帮不上忙。
+ fn axioms(&self) -> utopia_core::models::RelationAxioms {
+ utopia_core::models::RelationAxioms {
+ functional: self.functional,
+ inverse_functional: self.inverse_functional,
+ transitive: self.is_transitive,
+ symmetric: self.is_symmetric,
+ asymmetric: self.is_asymmetric,
+ irreflexive: self.is_irreflexive,
+ }
+ }
+}
+
fn default_temporal() -> String {
"state".into()
}
@@ -235,8 +275,7 @@ pub async fn create_relation_type(
key,
req.label.trim(),
&req.temporal,
- req.functional,
- req.inverse_functional,
+ req.axioms(),
req.description.as_deref().unwrap_or("").trim(),
kind,
req.domains.as_deref().unwrap_or(&[]),
@@ -271,8 +310,7 @@ pub async fn update_relation_type(
id,
req.label.trim(),
&req.temporal,
- req.functional,
- req.inverse_functional,
+ req.axioms(),
req.description.as_deref().unwrap_or("").trim(),
req.datatype.as_deref(),
req.unit.as_deref().map(str::trim).filter(|s| !s.is_empty()),
@@ -925,8 +963,14 @@ pub async fn adopt_predicate(
key,
req.label.trim(),
&req.temporal,
- req.functional,
- req.inverse_functional,
+ // 采纳一个提案不替人声明公理。**functional 是唯一的例外**,
+ // 因为它是这个表单本来就问过的一项;其余四条要人去关系页显式勾——
+ // 推理机的判据必须是人写下来的,不是采纳时顺手带上的
+ utopia_core::models::RelationAxioms {
+ functional: req.functional,
+ inverse_functional: req.inverse_functional,
+ ..Default::default()
+ },
req.description.as_deref().unwrap_or("").trim(),
"relation",
// 提案与冷启动只建关系,不声明 domain/range —— 留空 = 不限主宾类型
@@ -1113,7 +1157,20 @@ pub async fn apply_import(
let (filename, bytes) = read_upload(multipart).await?;
let (import_id, plan) =
crate::owl_import::apply(&state, kb_id, user.id, &filename, &bytes).await?;
- Ok(Json(json!({ "import_id": import_id, "plan": plan })))
+ // 公理刚变,这是最该重算一致性的时刻——用户导进来的正是判据本身。
+ // 失败不影响导入本身:本体已经落库了,检查跑不动是另一件事,
+ // Review 页那个按钮还能再跑一次
+ let violations = match utopia_store::reasoning::run(&state.pool, kb_id).await {
+ Ok(r) => r.found,
+ Err(e) => {
+ tracing::warn!(?e, "导入后的一致性检查没跑成");
+ 0
+ }
+ };
+ state.emit_review(kb_id);
+ Ok(Json(
+ json!({ "import_id": import_id, "plan": plan, "violations": violations }),
+ ))
}
pub async fn list_imports(
@@ -1266,9 +1323,9 @@ pub(crate) async fn adopt_attribute_core(
spec.key,
spec.label,
"state",
- // 建议方不替时态引擎做决定:functional 会驱动它自动闭合旧值
- false,
- false,
+ // 建议方不替时态引擎做决定:functional 会驱动它自动闭合旧值,
+ // 而其余公理会驱动推理机——两者都该由人显式声明
+ Default::default(),
spec.description,
"attribute",
&domains,
diff --git a/crates/utopia-server/src/api/review_routes.rs b/crates/utopia-server/src/api/review_routes.rs
index ce058f5f..63c59406 100644
--- a/crates/utopia-server/src/api/review_routes.rs
+++ b/crates/utopia-server/src/api/review_routes.rs
@@ -12,7 +12,8 @@ use crate::auth::AuthUser;
use crate::error::ApiResult;
use crate::state::AppState;
-const LOW_CONFIDENCE_BELOW: f32 = 0.75;
+/// 一页多少条。**服务端的默认,不是上限**——前端可以要更少,多则被 clamp 挡住
+const REVIEW_PAGE: i64 = 10;
/// 冲突双方的三元组快照:(旧主语, 旧宾语, 新主语, 新宾语, 谓词标签)。
type ConflictSnapshot = (String, Option<String>, String, Option<String>, String);
@@ -40,27 +41,88 @@ async fn fact_snapshot(state: &AppState, kb_id: Uuid, fact_id: Uuid) -> Option<s
row.map(|(s, p, o, c)| json!({ "subject": s, "predicate": p, "object": o, "confidence": c }))
}
+#[derive(Deserialize)]
+pub struct ReviewQuery {
+ /// 要看哪一档。缺省 duplicates
+ #[serde(default)]
+ pub queue: Option<String>,
+ #[serde(default)]
+ pub limit: Option<i64>,
+ #[serde(default)]
+ pub offset: Option<i64>,
+}
+
+/// 审核队列:**计数与内容分开取**。
+///
+/// 从前一次把八个队列全端回来,每个固定 100 条,前端再客户端分页——于是左栏
+/// 的徽标是截断后的数字(库里 164 条低置信事实,界面写 100),而第十一页之后
+/// 的东西界面上不存在。
+///
+/// 现在:计数每次都回(八个 COUNT 一条查询,走的是与列表同一套 WHERE),
+/// 内容只回当前那一档的一页。切换分档或翻页各发一次请求,代价是多几次往返,
+/// 换来的是**数字不再骗人**,而且一个有十万条待办的库也翻得到底。
pub async fn list(
State(state): State<AppState>,
AuthUser(user): AuthUser,
Path(kb_id): Path<Uuid>,
+ Query(q): Query<ReviewQuery>,
) -> ApiResult<Json<serde_json::Value>> {
require_kb(&state, &user, kb_id, Role::Viewer).await?;
- let reviews = utopia_store::resolution::list_reviews(&state.pool, kb_id).await?;
- let facts =
- utopia_store::graph::low_confidence_facts(&state.pool, kb_id, LOW_CONFIDENCE_BELOW, 100)
- .await?;
- let merges = utopia_store::resolution::list_merges(&state.pool, kb_id, 30).await?;
- let conflicts = utopia_store::temporal::list_conflicts(&state.pool, kb_id).await?;
- let unconfirmed = utopia_store::graph::stale_facts(&state.pool, kb_id, 100).await?;
- // 语义层的待表态映射(0011)。从前它借「低置信事实」那一档露面——
- // 靠 confidence 0.6 混进去,而它根本不是一条关于世界的断言。
- // 现在自成一档,前端也据此分组显示
- let mappings = utopia_store::mappings::proposed(&state.pool, kb_id, 100).await?;
+ let counts = utopia_store::review::counts(&state.pool, kb_id).await?;
+ let queue = q.queue.as_deref().unwrap_or("duplicates");
+ // 上限挡住「limit=1000000 把库拖垮」,同时留出足够一页的余量
+ let limit = q.limit.unwrap_or(REVIEW_PAGE).clamp(1, 200);
+ let offset = q.offset.unwrap_or(0).max(0);
+
+ let items = match queue {
+ "duplicates" => {
+ json!(utopia_store::resolution::list_reviews(&state.pool, kb_id, limit, offset).await?)
+ }
+ "conflicts" => {
+ json!(utopia_store::temporal::list_conflicts(&state.pool, kb_id, limit, offset).await?)
+ }
+ "unconfirmed" => {
+ json!(utopia_store::graph::stale_facts(&state.pool, kb_id, limit, offset).await?)
+ }
+ "lowconf" => json!(
+ utopia_store::graph::low_confidence_facts(
+ &state.pool,
+ kb_id,
+ utopia_store::review::LOW_CONFIDENCE_BELOW,
+ limit,
+ offset,
+ )
+ .await?
+ ),
+ "mappings" => {
+ json!(utopia_store::mappings::proposed(&state.pool, kb_id, limit, offset).await?)
+ }
+ "violations" => {
+ json!(
+ utopia_store::reasoning::open_violations(&state.pool, kb_id, limit, offset).await?
+ )
+ }
+ "defects" => {
+ json!(utopia_store::reasoning::open_defects(&state.pool, kb_id, limit, offset).await?)
+ }
+ "merges" => {
+ json!(utopia_store::resolution::list_merges(&state.pool, kb_id, limit, offset).await?)
+ }
+ // 认不出的档名当成契约错误报出来,而不是悄悄回空——悄悄回空会让前端
+ // 拼错一个字母之后看到「这一档清空了」
+ other => {
+ return Err(utopia_core::AppError::invalid(
+ "unknown_queue",
+ format!("no review queue named {other}"),
+ )
+ .into())
+ }
+ };
+
Ok(Json(json!({
- "reviews": reviews, "facts": facts, "merges": merges,
- "conflicts": conflicts, "unconfirmed": unconfirmed,
- "mappings": mappings
+ "counts": counts,
+ "queue": queue,
+ "items": items,
})))
}
@@ -430,3 +492,194 @@ pub async fn decide_mapping(
state.emit_review(kb_id);
Ok(Json(json!({ "ok": true })))
}
+
+#[derive(Deserialize)]
+pub struct DecideViolationReq {
+ /// fact_retracted | axiom_relaxed | accepted
+ pub resolution: String,
+}
+
+/// 人裁决一处公理违规。
+///
+/// **三个出路而不是两个。** `axiom_relaxed` 是这一档独有的:矛盾可能出在定义
+/// 而不是数据——用户导的本体把某个属性声明成反对称,而他自己的语料里那关系
+/// 其实双向。这时该改的是本体,不是二十条事实。
+///
+/// 端点只记决定,不替人执行。撤事实走 `reject_fact`,改公理走本体页——
+/// 那两个动作各有自己的权限与台账,塞进这里会变成一个什么都能干的端点。
+pub async fn decide_violation(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, violation_id)): Path<(Uuid, Uuid)>,
+ Json(req): Json<DecideViolationReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ if !matches!(
+ req.resolution.as_str(),
+ "fact_retracted" | "axiom_relaxed" | "accepted"
+ ) {
+ return Err(utopia_core::AppError::invalid(
+ "bad_resolution",
+ "resolution 只能是 fact_retracted、axiom_relaxed 或 accepted",
+ )
+ .into());
+ }
+ utopia_store::reasoning::decide(&state.pool, kb_id, violation_id, &req.resolution, user.id)
+ .await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "violation.decided",
+ "axiom_violation",
+ Some(violation_id),
+ json!({ "resolution": req.resolution }),
+ )
+ .await;
+ state.emit_review(kb_id);
+ Ok(Json(json!({ "ok": true })))
+}
+
+/// 手动跑一遍一致性检查。
+///
+/// **同步跑而不是排任务**:这是纯计算,没有模型调用也没有网络——一个几万条
+/// 事实的库跑下来是毫秒级。排进任务队列只会让人点完按钮盯着一个"排队中",
+/// 而队列真正要解决的是"这活儿要跑几分钟"。
+///
+/// `predicates_with_axioms` 一并回给前端:**零和零的含义不同**。没有公理时
+/// 结论是"没有判据",界面该说"先导一份带公理的本体",而不是"未发现矛盾"。
+pub async fn run_consistency_check(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let report = utopia_store::reasoning::run(&state.pool, kb_id).await?;
+ // 本体自洽性一并算。两者判据同源(都是本体声明的公理),分两个按钮
+ // 只会让人点两次
+ let onto = utopia_store::reasoning::check_ontology(&state.pool, kb_id).await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "consistency.checked",
+ "knowledge_base",
+ Some(kb_id),
+ json!({
+ "edges": report.edges,
+ "predicates_with_axioms": report.predicates_with_axioms,
+ "found": report.found,
+ "inserted": report.inserted,
+ "cleared": report.cleared,
+ "defects_found": onto.found,
+ }),
+ )
+ .await;
+ state.emit_review(kb_id);
+ Ok(Json(json!({
+ "edges": report.edges,
+ "predicates_with_axioms": report.predicates_with_axioms,
+ "found": report.found,
+ "inserted": report.inserted,
+ "cleared": report.cleared,
+ // 本体自己那一档单独回。**不加进 found**:两个数不是一类东西,
+ // 加起来之后「3 处矛盾」既可能是三条事实抵触,也可能是本体自己写反了三处
+ "classes": onto.classes,
+ "defects_found": onto.found,
+ "defects_new": onto.inserted,
+ })))
+}
+
+#[derive(Deserialize)]
+pub struct DecideDefectReq {
+ /// fixed | accepted
+ pub resolution: String,
+}
+
+/// 人对一处本体缺陷表态。
+///
+/// **两个出路而不是三个**:本体缺陷压根没看数据,所以没有「数据错了」这一条。
+pub async fn decide_defect(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, defect_id)): Path<(Uuid, Uuid)>,
+ Json(req): Json<DecideDefectReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ if !matches!(req.resolution.as_str(), "fixed" | "accepted") {
+ return Err(utopia_core::AppError::invalid(
+ "bad_resolution",
+ "resolution 只能是 fixed 或 accepted",
+ )
+ .into());
+ }
+ utopia_store::reasoning::decide_defect(&state.pool, kb_id, defect_id, &req.resolution, user.id)
+ .await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "defect.decided",
+ "ontology_defect",
+ Some(defect_id),
+ json!({ "resolution": req.resolution }),
+ )
+ .await;
+ state.emit_review(kb_id);
+ Ok(Json(json!({ "ok": true })))
+}
+
+/// 跑一遍推理(R1)。
+///
+/// **受 `materialize_inferences` 开关约束。** 默认关,因为这一步往图里加东西,
+/// 而 0001 判据 2 说「本体是引导不是执法」——声明可能是错的,不该在用户没表态时
+/// 就按它改图。开关关着时不静默跳过:回一个明确的错,界面才说得出为什么没动。
+///
+/// 同步跑,与一致性检查同一个理由:纯计算,没有模型调用也没有网络。
+pub async fn run_inference(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let on: bool =
+ sqlx::query_scalar("SELECT materialize_inferences FROM knowledge_bases WHERE id = $1")
+ .bind(kb_id)
+ .fetch_one(&state.pool)
+ .await
+ .map_err(utopia_core::AppError::Db)?;
+ if !on {
+ return Err(utopia_core::AppError::invalid(
+ "inference_off",
+ "materialized inference is off for this knowledge base",
+ )
+ .into());
+ }
+ let report = utopia_store::reasoning::materialize(&state.pool, kb_id).await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "inference.materialized",
+ "knowledge_base",
+ Some(kb_id),
+ json!({
+ "rules": report.rules,
+ "edges": report.edges,
+ "derived": report.derived,
+ "inserted": report.inserted,
+ "invalidated": report.invalidated,
+ "capped": report.capped,
+ }),
+ )
+ .await;
+ state.emit_graph(kb_id);
+ Ok(Json(json!({
+ "rules": report.rules,
+ "edges": report.edges,
+ "derived": report.derived,
+ "inserted": report.inserted,
+ "invalidated": report.invalidated,
+ "capped": report.capped,
+ })))
+}
diff --git a/crates/utopia-server/src/bootstrap_ontology.rs b/crates/utopia-server/src/bootstrap_ontology.rs
index 08a36461..49b42e5d 100644
--- a/crates/utopia-server/src/bootstrap_ontology.rs
+++ b/crates/utopia-server/src/bootstrap_ontology.rs
@@ -245,8 +245,8 @@ pub async fn bootstrap_ontology(state: &AppState, kb_id: Uuid) -> anyhow::Result
&g.key,
&label,
"state",
- false,
- false,
+ // 冷启动不替人声明任何公理:推理机的判据必须是人写下来的
+ Default::default(),
"",
"relation",
&[],
diff --git a/crates/utopia-server/src/main.rs b/crates/utopia-server/src/main.rs
index eede2648..9a1c8a71 100644
--- a/crates/utopia-server/src/main.rs
+++ b/crates/utopia-server/src/main.rs
@@ -72,6 +72,16 @@ async fn main() -> anyhow::Result<()> {
let search = Arc::new(SearchIndex::open(&index_dir)?);
tracing::info!("全文索引就绪: {}", index_dir.display());
+ // **索引落空就自己重建,不给按钮。**
+ //
+ // 索引是独立于数据库的一份文件:换机器、卷没挂上、目录损坏,任何一样都会让它
+ // 落空。而落空之后检索只会静默回零——界面上看不出任何异样,用户会以为是
+ // 「确实没有匹配」。这种失败不该靠人先意识到再去点一个按钮。
+ //
+ // 判据是「库里有分块而索引空着」,不是「数目对不对得上」:后者在正常运行中
+ // 也会短暂不等(一篇文档正在索引),拿它当判据会让每次启动都重建一遍。
+ reindex_if_empty(&pool, &search).await;
+
// JWT 密钥:环境变量优先(轮换、多实例显式对齐走这条),否则用库里那条;
// 库里也没有就现生成一条存进去。生成放在这里而不是 store 里,是因为
// OsRng 已经随 argon2 在 server 的依赖里,store 不必为此多一个依赖。
@@ -152,6 +162,39 @@ async fn main() -> anyhow::Result<()> {
}
});
+ // 定时推理调度器(0002 R1)。
+ //
+ // **必须定时,不能只靠手点**:事实是持续变的——每篇文档抽取都在加边——而
+ // 派生只在跑的那一刻算。不定时的话,下一篇文档进来之后图上的派生就是缺的,
+ // 而这种缺失界面上看不出来(不是错,是新链没推)。
+ //
+ // 与来源同步共用一个节拍:每分钟扫一遍,到期的入队。真正的推导在任务里跑,
+ // 不在这个循环里——一个大库全量重推可能要几秒,卡在调度循环里会拖住别的库
+ let infer_state = state.clone();
+ tokio::spawn(async move {
+ let mut tick = tokio::time::interval(std::time::Duration::from_secs(60));
+ tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
+ loop {
+ tick.tick().await;
+ match utopia_store::reasoning::due_for_inference(&infer_state.pool).await {
+ Ok(due) => {
+ for kb_id in due {
+ if let Err(e) = utopia_store::jobs::enqueue(
+ &infer_state.pool,
+ "materialize_inferences",
+ serde_json::json!({ "kb_id": kb_id }),
+ )
+ .await
+ {
+ tracing::warn!(kb_id = %kb_id, error = %e, "推理任务入队失败");
+ }
+ }
+ }
+ Err(e) => tracing::warn!(error = %e, "扫描到期推理失败"),
+ }
+ }
+ });
+
let app = api::router(state, &cfg);
let listener = tokio::net::TcpListener::bind(&cfg.bind_addr).await?;
tracing::info!("Utopia 服务启动于 http://{}", cfg.bind_addr);
@@ -182,6 +225,58 @@ async fn main() -> anyhow::Result<()> {
Ok(())
}
+/// 索引空着而库里有东西 → 从库里重建一遍。
+///
+/// 失败只告警不阻断启动:检索退化成「暂时搜不到」,而整个服务起不来是更坏的
+/// 结果。日志里那一行说清了发生什么,下次重启还会再试。
+async fn reindex_if_empty(pool: &sqlx::PgPool, search: &SearchIndex) {
+ if !search.is_empty() {
+ return;
+ }
+ let total = match utopia_store::documents::live_chunk_count(pool).await {
+ Ok(n) => n,
+ Err(e) => {
+ tracing::warn!(error = %e, "数不出分块数,跳过索引重建");
+ return;
+ }
+ };
+ if total == 0 {
+ return;
+ }
+ tracing::info!(chunks = total, "全文索引是空的,从库里重建");
+ let rows = match utopia_store::documents::all_chunks_for_index(pool).await {
+ Ok(r) => r,
+ Err(e) => {
+ tracing::warn!(error = %e, "读分块失败,索引未重建");
+ return;
+ }
+ };
+ // 按文档攒批再写:`reindex_document` 一次替换一篇文档的全部分块,
+ // 逐条调会把前一条刚写的删掉
+ let mut current: Option<(uuid::Uuid, uuid::Uuid)> = None;
+ let mut batch: Vec<(String, String)> = Vec::new();
+ let mut done = 0usize;
+ let flush = |key: Option<(uuid::Uuid, uuid::Uuid)>, batch: &mut Vec<(String, String)>| {
+ if let Some((kb, doc)) = key {
+ if let Err(e) = search.reindex_document(&kb.to_string(), &doc.to_string(), batch) {
+ tracing::warn!(error = %e, document = %doc, "重建索引时有一篇没写进去");
+ }
+ }
+ batch.clear();
+ };
+ for (kb_id, doc_id, chunk_id, text) in rows {
+ if current != Some((kb_id, doc_id)) {
+ flush(current, &mut batch);
+ current = Some((kb_id, doc_id));
+ }
+ batch.push((chunk_id.to_string(), text));
+ done += 1;
+ }
+ // `reindex_document` 自己 commit,所以这里不必再提交一次
+ flush(current, &mut batch);
+ tracing::info!(chunks = done, "全文索引重建完成");
+}
+///
/// 任务分发:新任务类型在这里注册。
///
/// 单拎成函数而不是内联在闭包里,是为了让失败**有一个统一的出口**——
@@ -209,6 +304,40 @@ async fn dispatch(st: &state::AppState, job: &utopia_store::jobs::Job) -> anyhow
.ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;
mappings::explore_mappings(st, kb_id).await
}
+ // 定时重推(0002 R1)。**先记时间再推**——推导抛错时也不该让这个库
+ // 在下一分钟被重新扫起来,那会变成一个每分钟失败一次的循环
+ "materialize_inferences" => {
+ let kb_id: Uuid = job
+ .payload
+ .get("kb_id")
+ .and_then(|v| v.as_str())
+ .and_then(|s| s.parse().ok())
+ .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;
+ utopia_store::reasoning::mark_inference_ran(&st.pool, kb_id).await?;
+ let report = utopia_store::reasoning::materialize(&st.pool, kb_id).await?;
+ // **到点对比**:`materialize` 本来就在拿这一轮算出来的对上库里现有的,
+ // 所以「对比」不是新机制。这里只把那次对比的结果留下来给人看——
+ // 没有变化时不写,免得台账被每小时一条「什么都没变」淹掉
+ if report.inserted > 0 || report.invalidated > 0 {
+ let _ = utopia_store::audit::record(
+ &st.pool,
+ Some(kb_id),
+ Uuid::nil(),
+ "inference.materialized",
+ "knowledge_base",
+ Some(kb_id),
+ serde_json::json!({
+ "scheduled": true,
+ "inserted": report.inserted,
+ "invalidated": report.invalidated,
+ "rules": report.rules,
+ }),
+ )
+ .await;
+ st.emit_graph(kb_id);
+ }
+ Ok(())
+ }
"extract_document" => {
let id = payload_document_id(&job.payload)?;
extraction::extract_document(st, id).await
diff --git a/crates/utopia-server/src/state.rs b/crates/utopia-server/src/state.rs
index 5908c6f0..e26d9bd1 100644
--- a/crates/utopia-server/src/state.rs
+++ b/crates/utopia-server/src/state.rs
@@ -79,6 +79,16 @@ impl AppState {
});
}
+ /// 图变了。推理往图里加过边之后要发一次——它不经过文档管道,
+ /// 而 `document` 那条事件是文档管道专用的
+ pub fn emit_graph(&self, kb_id: Uuid) {
+ let _ = self.events.send(AppEvent {
+ kb_id: Some(kb_id),
+ kind: "graph",
+ document_id: None,
+ });
+ }
+
pub fn emit_source(&self, kb_id: Uuid) {
let _ = self.events.send(AppEvent {
kb_id: Some(kb_id),
diff --git a/crates/utopia-store/Cargo.toml b/crates/utopia-store/Cargo.toml
index ad670f89..5ea3e1f9 100644
--- a/crates/utopia-store/Cargo.toml
+++ b/crates/utopia-store/Cargo.toml
@@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
utopia-core.workspace = true
utopia-ingest.workspace = true
+utopia-reason.workspace = true
pgvector.workspace = true
cron.workspace = true
sqlx.workspace = true
diff --git a/crates/utopia-store/src/audit.rs b/crates/utopia-store/src/audit.rs
index 4417a6c5..c2c48000 100644
--- a/crates/utopia-store/src/audit.rs
+++ b/crates/utopia-store/src/audit.rs
@@ -118,16 +118,73 @@ pub async fn review_history(
Ok((rows, total))
}
-pub async fn list_for_kb(pool: &PgPool, kb_id: Uuid, limit: i64) -> AppResult<Vec<AuditEventView>> {
- let rows: Vec<AuditEventView> = sqlx::query_as(
+/// 一个知识库的审计台账,**带分页与筛选**。
+///
+/// 从前是固定最近 100 条、无分页无筛选——而台账是合规材料,「只看得到最近
+/// 一百条」等于查不了历史。三个筛选是按真实的查法挑的:
+///
+/// - `action`:查一类动作(「谁改过类型」「有哪些拒绝」)。前缀匹配而不是
+/// 全等,因为动作名本身分层(`entity.retyped` / `entity.renamed`),
+/// 传 `entity.` 就能把一族捞出来
+/// - `actor`:查一个人做过什么。合规审计最常见的问题
+/// - `since` / `until`:查一段时间。事故复盘要的就是这个
+///
+/// 一并回总数,否则分页器不知道有几页——而「不知道有几页」正是这一档
+/// 从前那个 100 的翻版。
+#[allow(clippy::too_many_arguments)]
+pub async fn list_for_kb(
+ pool: &PgPool,
+ kb_id: Uuid,
+ action: Option<&str>,
+ actor: Option<Uuid>,
+ since: Option<chrono::DateTime<chrono::Utc>>,
+ until: Option<chrono::DateTime<chrono::Utc>>,
+ limit: i64,
+ offset: i64,
+) -> AppResult<(Vec<AuditEventView>, i64)> {
+ // 四个筛选都写成「参数为空就不生效」,这样一条 SQL 覆盖全部组合——
+ // 拼字符串会在这里长出十六个分支,而每个分支都是一次注入面
+ const WHERE: &str = "WHERE e.kb_id = $1
+ AND ($2::text IS NULL OR e.action LIKE $2 || '%')
+ AND ($3::uuid IS NULL OR e.actor_id = $3)
+ AND ($4::timestamptz IS NULL OR e.created_at >= $4)
+ AND ($5::timestamptz IS NULL OR e.created_at < $5)";
+
+ let rows: Vec<AuditEventView> = sqlx::query_as(&format!(
"SELECT e.id, e.action, e.target_kind, e.target_id, e.detail,
u.display_name AS actor_name, e.created_at
FROM audit_events e LEFT JOIN users u ON u.id = e.actor_id
- WHERE e.kb_id = $1 ORDER BY e.created_at DESC LIMIT $2",
- )
+ {WHERE}
+ ORDER BY e.created_at DESC LIMIT $6 OFFSET $7"
+ ))
.bind(kb_id)
+ .bind(action)
+ .bind(actor)
+ .bind(since)
+ .bind(until)
.bind(limit)
+ .bind(offset)
.fetch_all(pool)
.await?;
- Ok(rows)
+
+ let (total,): (i64,) = sqlx::query_as(&format!("SELECT count(*) FROM audit_events e {WHERE}"))
+ .bind(kb_id)
+ .bind(action)
+ .bind(actor)
+ .bind(since)
+ .bind(until)
+ .fetch_one(pool)
+ .await?;
+ Ok((rows, total))
+}
+
+/// 这个库的台账里出现过哪些动作。**筛选下拉要按实际有的填**——列一个
+/// 全部动作的硬编码清单,用户会看到一堆这个库从来没发生过的选项。
+pub async fn actions_for_kb(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<String>> {
+ Ok(
+ sqlx::query_scalar("SELECT DISTINCT action FROM audit_events WHERE kb_id = $1 ORDER BY 1")
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?,
+ )
}
diff --git a/crates/utopia-store/src/conversations.rs b/crates/utopia-store/src/conversations.rs
index 6168129e..6a420fef 100644
--- a/crates/utopia-store/src/conversations.rs
+++ b/crates/utopia-store/src/conversations.rs
@@ -19,22 +19,82 @@ pub async fn create(pool: &PgPool, kb_id: Uuid, user_id: Uuid, title: &str) -> A
Ok(id)
}
-/// 本人在本 KB 的会话列表(新→旧)。
-pub async fn list(pool: &PgPool, kb_id: Uuid, user_id: Uuid) -> AppResult<Vec<ConversationView>> {
- let rows: Vec<ConversationView> = sqlx::query_as(
- "SELECT id, title, created_at, updated_at,
+/// 我在这个库里的会话。**可搜、可翻页**——标题会重(同一个问题问两次就重了),
+/// 而固定一百条之后的会话界面上根本不存在。
+///
+/// 搜的是标题与消息正文两处:人记得住的往往是「我问过那个关于 Q3 的」,
+/// 而那句话在正文里,标题可能被截成了别的样子。
+pub async fn list(
+ pool: &PgPool,
+ kb_id: Uuid,
+ user_id: Uuid,
+ q: Option<&str>,
+ limit: i64,
+ offset: i64,
+) -> AppResult<(Vec<ConversationView>, i64)> {
+ const WHERE: &str = "WHERE c.kb_id = $1 AND c.user_id = $2
+ AND ($3::text IS NULL
+ OR c.title ILIKE '%' || $3 || '%'
+ OR EXISTS (SELECT 1 FROM conversation_messages m
+ WHERE m.conversation_id = c.id
+ AND m.content ILIKE '%' || $3 || '%'))";
+ let rows: Vec<ConversationView> = sqlx::query_as(&format!(
+ "SELECT c.id, c.title, c.created_at, c.updated_at,
(SELECT count(*) FROM conversation_messages m
WHERE m.conversation_id = c.id) AS message_count
FROM conversations c
- WHERE kb_id = $1 AND user_id = $2
- ORDER BY updated_at DESC
- LIMIT 100",
- )
+ {WHERE}
+ ORDER BY c.updated_at DESC
+ LIMIT $4 OFFSET $5"
+ ))
.bind(kb_id)
.bind(user_id)
+ .bind(q)
+ .bind(limit)
+ .bind(offset)
.fetch_all(pool)
.await?;
- Ok(rows)
+ let (total,): (i64,) = sqlx::query_as(&format!("SELECT count(*) FROM conversations c {WHERE}"))
+ .bind(kb_id)
+ .bind(user_id)
+ .bind(q)
+ .fetch_one(pool)
+ .await?;
+ Ok((rows, total))
+}
+
+/// 改一个会话的标题。
+///
+/// **标题本来是从第一句话自动取的**,而那句话往往不是它后来变成的样子——
+/// 一段对话跑偏是常态,改名让人能按自己记得的方式找回它。
+pub async fn rename(
+ pool: &PgPool,
+ kb_id: Uuid,
+ user_id: Uuid,
+ conversation_id: Uuid,
+ title: &str,
+) -> AppResult<()> {
+ let title = title.trim();
+ if title.is_empty() || title.chars().count() > 120 {
+ return Err(AppError::invalid(
+ "bad_title",
+ "Title must be 1-120 characters",
+ ));
+ }
+ let res = sqlx::query(
+ "UPDATE conversations SET title = $4
+ WHERE id = $3 AND kb_id = $1 AND user_id = $2",
+ )
+ .bind(kb_id)
+ .bind(user_id)
+ .bind(conversation_id)
+ .bind(title)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
}
/// 归属校验:会话必须属于本 KB 本人。
diff --git a/crates/utopia-store/src/documents.rs b/crates/utopia-store/src/documents.rs
index e0d2f3e9..d55dcfbe 100644
--- a/crates/utopia-store/src/documents.rs
+++ b/crates/utopia-store/src/documents.rs
@@ -1,6 +1,6 @@
use pgvector::Vector;
use sqlx::PgPool;
-use utopia_core::models::{ChunkView, Document};
+use utopia_core::models::{ChunkView, Document, DocumentPage};
use utopia_core::{AppError, AppResult};
use utopia_ingest::ChunkPiece;
use uuid::Uuid;
@@ -54,6 +54,111 @@ pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Document>> {
Ok(rows)
}
+/// 文库一页,**带筛选与统计**。
+///
+/// 从前是 `SELECT * FROM documents WHERE kb_id = $1` 不带上限、前端客户端分页。
+/// 27 篇没事,两万篇会把整张表打进浏览器;而客户端筛选还有个更隐蔽的毛病——
+/// 它只筛得到已经拿下来的那些。
+///
+/// 统计单独算,而且**只按来源作用域算,不受名字/状态筛选影响**:
+/// 「这个来源里有几篇可抽」是那两个批量按钮的作用范围,跟你此刻在搜什么无关。
+#[allow(clippy::too_many_arguments)]
+pub async fn page(
+ pool: &PgPool,
+ kb_id: Uuid,
+ // None = 全部;Some(None) = 只看没有来源的;Some(Some(id)) = 某个来源
+ source: Option<Option<Uuid>>,
+ q: Option<&str>,
+ graph_status: Option<&str>,
+ limit: i64,
+ offset: i64,
+) -> AppResult<DocumentPage> {
+ // 三个筛选都写成「参数为空就不生效」,一条 SQL 覆盖全部组合。
+ // `$2 = 'any'` 那一支是「不按来源筛」,`'none'` 是「只看没有来源的」——
+ // 用两个哨兵字符串而不是两个可空参数,因为 NULL 在这里有歧义:
+ // 它既可能是「不筛」,也可能是「筛出 source_id IS NULL 的」
+ const WHERE: &str = "WHERE kb_id = $1
+ AND ($2 = 'any'
+ OR ($2 = 'none' AND source_id IS NULL)
+ OR source_id::text = $2)
+ AND ($3::text IS NULL OR filename ILIKE '%' || $3 || '%')
+ AND ($4::text IS NULL OR graph_status = $4)";
+ let scope = match source {
+ None => "any".to_string(),
+ Some(None) => "none".to_string(),
+ Some(Some(id)) => id.to_string(),
+ };
+
+ let docs: Vec<Document> = sqlx::query_as(&format!(
+ "SELECT * FROM documents {WHERE} ORDER BY created_at DESC LIMIT $5 OFFSET $6"
+ ))
+ .bind(kb_id)
+ .bind(&scope)
+ .bind(q)
+ .bind(graph_status)
+ .bind(limit)
+ .bind(offset)
+ .fetch_all(pool)
+ .await?;
+
+ let (total,): (i64,) = sqlx::query_as(&format!("SELECT count(*) FROM documents {WHERE}"))
+ .bind(kb_id)
+ .bind(&scope)
+ .bind(q)
+ .bind(graph_status)
+ .fetch_one(pool)
+ .await?;
+
+ // 统计只按来源作用域算:那两个批量按钮作用于整个来源,不是你搜出来的那几条
+ let stats: (i64, i64, i64) = sqlx::query_as(
+ "SELECT
+ count(*) FILTER (WHERE status = 'ready'),
+ count(*) FILTER (WHERE graph_status IN ('queued', 'extracting')),
+ count(*) FILTER (WHERE graph_status = 'failed')
+ FROM documents
+ WHERE kb_id = $1
+ AND ($2 = 'any'
+ OR ($2 = 'none' AND source_id IS NULL)
+ OR source_id::text = $2)",
+ )
+ .bind(kb_id)
+ .bind(&scope)
+ .fetch_one(pool)
+ .await?;
+
+ Ok(DocumentPage {
+ docs,
+ total,
+ ready: stats.0,
+ extracting: stats.1,
+ failed: stats.2,
+ })
+}
+
+/// 这个来源(或整库)里抽取失败的文档 id。**一键重试要的就是这份名单**。
+pub async fn failed_ids(
+ pool: &PgPool,
+ kb_id: Uuid,
+ source: Option<Option<Uuid>>,
+) -> AppResult<Vec<Uuid>> {
+ let scope = match source {
+ None => "any".to_string(),
+ Some(None) => "none".to_string(),
+ Some(Some(id)) => id.to_string(),
+ };
+ Ok(sqlx::query_scalar(
+ "SELECT id FROM documents
+ WHERE kb_id = $1 AND graph_status = 'failed'
+ AND ($2 = 'any'
+ OR ($2 = 'none' AND source_id IS NULL)
+ OR source_id::text = $2)",
+ )
+ .bind(kb_id)
+ .bind(&scope)
+ .fetch_all(pool)
+ .await?)
+}
+
pub async fn get(pool: &PgPool, id: Uuid) -> AppResult<Document> {
sqlx::query_as("SELECT * FROM documents WHERE id = $1")
.bind(id)
@@ -660,3 +765,26 @@ pub async fn extraction_idle(pool: &PgPool, kb_id: Uuid) -> AppResult<bool> {
.await?;
Ok(pending == 0)
}
+
+/// 全库分块,按文档分组,供检索索引重建用。
+///
+/// **一次全取**:这条只在启动发现索引落空时跑,那时候要的正是全部;
+/// 而它跑完之后就再也不跑了。
+pub async fn all_chunks_for_index(pool: &PgPool) -> AppResult<Vec<(Uuid, Uuid, Uuid, String)>> {
+ Ok(sqlx::query_as(
+ "SELECT kb_id, document_id, id, text FROM chunks
+ WHERE superseded_at IS NULL
+ ORDER BY document_id, seq",
+ )
+ .fetch_all(pool)
+ .await?)
+}
+
+/// 库里一共有多少条在用的分块。启动时拿它跟索引对账。
+pub async fn live_chunk_count(pool: &PgPool) -> AppResult<i64> {
+ Ok(
+ sqlx::query_scalar("SELECT count(*) FROM chunks WHERE superseded_at IS NULL")
+ .fetch_one(pool)
+ .await?,
+ )
+}
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index b2bb421e..8cd1f096 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -384,12 +384,18 @@ const NODE_SQL: &str = "SELECT e.id, e.canonical_name AS name, t.key AS type_key
/// 全图概览:按度数取 top N 实体及其间的边。
/// `at`:服务端 as-of——只返回 T 时刻有效的边(起点不晚于 T 或未知,终点晚于 T 或开放)。
/// 前端时间滑杆走本地过滤不传此参数;这是给 API/MCP 消费者的时间旅行入口。
+/// 图谱总览:度数最高的 `limit` 个节点,以及它们之间的边。
+///
+/// **一并回总数。** 画多少个是渲染的事,库里有多少是知识库的事,两者从前
+/// 在界面上被同一个数字表示——一个上万实体的库,右上角永远写着 150,而那
+/// 是上限不是规模。渲染上限本身是合理的(画一万个点没人看得懂),骗人的是
+/// 把它说成总数。
pub async fn overview(
pool: &PgPool,
kb_id: Uuid,
limit: i64,
at: Option<chrono::DateTime<chrono::Utc>>,
-) -> AppResult<(Vec<GraphNode>, Vec<GraphEdge>)> {
+) -> AppResult<(Vec<GraphNode>, Vec<GraphEdge>, i64, i64)> {
let nodes: Vec<GraphNode> = sqlx::query_as(&format!(
"{NODE_SQL} WHERE e.kb_id = $1 AND e.merged_into IS NULL ORDER BY degree DESC, e.created_at LIMIT $2"
))
@@ -400,7 +406,26 @@ pub async fn overview(
let ids: Vec<Uuid> = nodes.iter().map(|n| n.id).collect();
let edges = edges_among(pool, kb_id, &ids, at).await?;
- Ok((nodes, edges))
+
+ // 总数按与画布同一套口径数:合并掉的实体不算,作废的事实不算,
+ // 属性事实(宾语是字面值)画不出边所以也不算。口径不同的话,
+ // 「150 / 325」里那个 325 会跟用户在别处看到的数对不上
+ let total_nodes: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM entities WHERE kb_id = $1 AND merged_into IS NULL",
+ )
+ .bind(kb_id)
+ .fetch_one(pool)
+ .await?;
+ let total_edges: i64 = sqlx::query_scalar(
+ "SELECT (SELECT count(*) FROM facts
+ WHERE kb_id = $1 AND invalidated_at IS NULL AND object_id IS NOT NULL)
+ + (SELECT count(*) FROM derived_facts
+ WHERE kb_id = $1 AND invalidated_at IS NULL)",
+ )
+ .bind(kb_id)
+ .fetch_one(pool)
+ .await?;
+ Ok((nodes, edges, total_nodes, total_edges))
}
async fn edges_among(
@@ -412,18 +437,35 @@ async fn edges_among(
if ids.is_empty() {
return Ok(Vec::new());
}
+ // **派生边显式 UNION 进来。** 它们住在 `derived_facts`,不在 `facts` 里——
+ // 所以每一个想看到推理结果的读路径都得像这里一样写出来。忘了写的后果是
+ // 看不见派生,而不是把它们当成谁的断言(那正是分表买到的东西)。
+ //
+ // 图要它们,因为「这条边是推出来的」正是用户该看见的信息之一;`derived`
+ // 那一位让界面画得出区别,也让人整体过滤掉。
let edges: Vec<GraphEdge> = sqlx::query_as(
"SELECT f.id, f.subject_id AS source, f.object_id AS target,
COALESCE(r.key, fact_surface_predicate(f.id)) AS predicate,
COALESCE(r.label, fact_surface_predicate(f.id)) AS label,
- r.id IS NULL AS inferred,
+ r.id IS NULL AS inferred, FALSE AS derived,
f.valid_from, f.valid_to, f.confidence
FROM facts f LEFT JOIN relation_types r ON r.id = f.predicate_id
WHERE f.kb_id = $1 AND f.invalidated_at IS NULL AND f.object_id IS NOT NULL
AND f.subject_id = ANY($2) AND f.object_id = ANY($2)
AND ($3::timestamptz IS NULL
OR ((f.valid_from IS NULL OR f.valid_from <= $3)
- AND (f.valid_to IS NULL OR f.valid_to > $3)))",
+ AND (f.valid_to IS NULL OR f.valid_to > $3)))
+ UNION ALL
+ SELECT d.id, d.subject_id AS source, d.object_id AS target,
+ r.key AS predicate, r.label AS label,
+ FALSE AS inferred, TRUE AS derived,
+ d.valid_from, d.valid_to, d.confidence
+ FROM derived_facts d JOIN relation_types r ON r.id = d.predicate_id
+ WHERE d.kb_id = $1 AND d.invalidated_at IS NULL
+ AND d.subject_id = ANY($2) AND d.object_id = ANY($2)
+ AND ($3::timestamptz IS NULL
+ OR ((d.valid_from IS NULL OR d.valid_from <= $3)
+ AND (d.valid_to IS NULL OR d.valid_to > $3)))",
)
.bind(kb_id)
.bind(ids)
@@ -484,23 +526,36 @@ pub async fn neighborhood(
Ok((nodes, edges))
}
+/// 按名字找实体。**一并回总数**——「宁分勿合」本来就会造出一堆同名,
+/// 固定十条的时候,想找的那个可能根本不在这十条里而界面上看不出来。
pub async fn search_entities(
pool: &PgPool,
kb_id: Uuid,
q: &str,
limit: i64,
-) -> AppResult<Vec<GraphNode>> {
+ offset: i64,
+) -> AppResult<(Vec<GraphNode>, i64)> {
let pattern = format!("%{}%", q.trim());
let nodes: Vec<GraphNode> = sqlx::query_as(&format!(
"{NODE_SQL} WHERE e.kb_id = $1 AND e.merged_into IS NULL
- AND e.canonical_name ILIKE $2 ORDER BY degree DESC LIMIT $3"
+ AND e.canonical_name ILIKE $2
+ ORDER BY degree DESC, e.canonical_name LIMIT $3 OFFSET $4"
))
.bind(kb_id)
- .bind(pattern)
+ .bind(&pattern)
.bind(limit)
+ .bind(offset)
.fetch_all(pool)
.await?;
- Ok(nodes)
+ let (total,): (i64,) = sqlx::query_as(
+ "SELECT count(*) FROM entities e
+ WHERE e.kb_id = $1 AND e.merged_into IS NULL AND e.canonical_name ILIKE $2",
+ )
+ .bind(kb_id)
+ .bind(&pattern)
+ .fetch_one(pool)
+ .await?;
+ Ok((nodes, total))
}
/// 实体详情:节点信息 + 事实时间线。
@@ -673,6 +728,7 @@ pub async fn low_confidence_facts(
kb_id: Uuid,
below: f32,
limit: i64,
+ offset: i64,
) -> AppResult<Vec<FactReviewItem>> {
let rows: Vec<FactReviewItem> = sqlx::query_as(
"SELECT f.id, s.canonical_name AS subject_name, COALESCE(r.label, fact_surface_predicate(f.id)) AS predicate_label,
@@ -687,11 +743,12 @@ pub async fn low_confidence_facts(
LEFT JOIN entities o ON o.id = f.object_id
WHERE f.kb_id = $1 AND f.invalidated_at IS NULL AND f.confidence < $2
ORDER BY f.confidence, f.recorded_at DESC
- LIMIT $3",
+ LIMIT $3 OFFSET $4",
)
.bind(kb_id)
.bind(below)
.bind(limit)
+ .bind(offset)
.fetch_all(pool)
.await?;
Ok(rows)
@@ -700,7 +757,12 @@ pub async fn low_confidence_facts(
/// "证据全部停留在旧版"的现行事实(S3 第三刀:文档新版没再确认的知识)。
/// 判定纯派生自 chunk 存活性——认领机制保证未变段落的证据不被误伤;
/// 绝不自动删除(没再提 ≠ 不成立),删除/闭合权在 Review 的人手里。
-pub async fn stale_facts(pool: &PgPool, kb_id: Uuid, limit: i64) -> AppResult<Vec<FactReviewItem>> {
+pub async fn stale_facts(
+ pool: &PgPool,
+ kb_id: Uuid,
+ limit: i64,
+ offset: i64,
+) -> AppResult<Vec<FactReviewItem>> {
let rows: Vec<FactReviewItem> = sqlx::query_as(
"SELECT f.id, s.canonical_name AS subject_name, COALESCE(r.label, fact_surface_predicate(f.id)) AS predicate_label,
COALESCE(o.canonical_name, f.object_value->>'summary') AS object_name,
@@ -718,10 +780,11 @@ pub async fn stale_facts(pool: &PgPool, kb_id: Uuid, limit: i64) -> AppResult<Ve
JOIN chunks c ON c.id = fe.chunk_id
WHERE fe.fact_id = f.id AND c.superseded_at IS NULL)
ORDER BY f.recorded_at DESC
- LIMIT $2",
+ LIMIT $2 OFFSET $3",
)
.bind(kb_id)
.bind(limit)
+ .bind(offset)
.fetch_all(pool)
.await?;
Ok(rows)
diff --git a/crates/utopia-store/src/kbs.rs b/crates/utopia-store/src/kbs.rs
index 98eafb1f..ee5dc7eb 100644
--- a/crates/utopia-store/src/kbs.rs
+++ b/crates/utopia-store/src/kbs.rs
@@ -73,6 +73,7 @@ pub async fn get(pool: &PgPool, id: Uuid) -> AppResult<KnowledgeBase> {
.ok_or(AppError::NotFound)
}
+#[allow(clippy::too_many_arguments)]
pub async fn update(
pool: &PgPool,
id: Uuid,
@@ -81,6 +82,8 @@ pub async fn update(
visibility: Option<&str>,
auto_extend_ontology: Option<bool>,
ontology_lang: Option<&str>,
+ materialize_inferences: Option<bool>,
+ inference_interval_minutes: Option<i32>,
) -> AppResult<KnowledgeBase> {
// 改语言不回头重写已有的类——它们已经是这个库的数据,可能有人手工调过。
// 这一列往后管的是**新**描述(自动扩本体、AI 建议)写成什么语言
@@ -113,6 +116,8 @@ pub async fn update(
visibility = COALESCE($4, visibility),
auto_extend_ontology = COALESCE($5, auto_extend_ontology),
ontology_lang = COALESCE($6, ontology_lang),
+ materialize_inferences = COALESCE($7, materialize_inferences),
+ inference_interval_minutes = COALESCE($8, inference_interval_minutes),
updated_at = now()
WHERE id = $1 RETURNING *",
)
@@ -122,6 +127,8 @@ pub async fn update(
.bind(visibility)
.bind(auto_extend_ontology)
.bind(ontology_lang)
+ .bind(materialize_inferences)
+ .bind(inference_interval_minutes)
.fetch_optional(pool)
.await?
.ok_or(AppError::NotFound)
diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rs
index 48717df0..20259c3e 100644
--- a/crates/utopia-store/src/lib.rs
+++ b/crates/utopia-store/src/lib.rs
@@ -18,7 +18,9 @@ pub mod members;
pub mod memory;
pub mod model_limits;
pub mod ontology;
+pub mod reasoning;
pub mod resolution;
+pub mod review;
pub mod settings;
pub mod sources;
pub mod temporal;
diff --git a/crates/utopia-store/src/mappings.rs b/crates/utopia-store/src/mappings.rs
index d2e3611d..c1165e96 100644
--- a/crates/utopia-store/src/mappings.rs
+++ b/crates/utopia-store/src/mappings.rs
@@ -77,7 +77,12 @@ pub async fn propose(
}
/// 还等着人表态的。Review 页读它。
-pub async fn proposed(pool: &PgPool, kb_id: Uuid, limit: i64) -> AppResult<Vec<ConceptMapping>> {
+pub async fn proposed(
+ pool: &PgPool,
+ kb_id: Uuid,
+ limit: i64,
+ offset: i64,
+) -> AppResult<Vec<ConceptMapping>> {
Ok(sqlx::query_as(
"SELECT m.id, m.concept_id, e.canonical_name AS concept_name, m.source,
m.table_name, m.expr, m.sql, m.unit, m.summary, m.derived, m.status
@@ -85,10 +90,11 @@ pub async fn proposed(pool: &PgPool, kb_id: Uuid, limit: i64) -> AppResult<Vec<C
JOIN entities e ON e.id = m.concept_id
WHERE m.kb_id = $1 AND m.status = 'proposed'
ORDER BY e.canonical_name, m.source
- LIMIT $2",
+ LIMIT $2 OFFSET $3",
)
.bind(kb_id)
.bind(limit)
+ .bind(offset)
.fetch_all(pool)
.await?)
}
diff --git a/crates/utopia-store/src/members.rs b/crates/utopia-store/src/members.rs
index ff909c68..3c261c79 100644
--- a/crates/utopia-store/src/members.rs
+++ b/crates/utopia-store/src/members.rs
@@ -89,3 +89,20 @@ pub async fn remove(pool: &PgPool, workspace_id: Uuid, user_id: Uuid) -> AppResu
}
Ok(())
}
+
+/// 已停用的账号。**没有这一条,恢复就够不着**——停用的人从所有列表里消失,
+/// 管理员拿不到他的 id,而恢复接口要的正是那个 id。
+///
+/// 与 [`org_users`] 分成两个查询而不是加一个「含停用」的开关:读的人不一样
+/// (那个喂选人器,这个喂管理页的一小块),而一个布尔参数会让两处的调用点
+/// 都得先想一下自己要哪一种。
+pub async fn deactivated_users(pool: &PgPool, org_id: Uuid) -> AppResult<Vec<OrgUser>> {
+ Ok(sqlx::query_as(
+ "SELECT id, email, display_name, is_admin FROM users
+ WHERE org_id = $1 AND deactivated_at IS NOT NULL
+ ORDER BY deactivated_at DESC",
+ )
+ .bind(org_id)
+ .fetch_all(pool)
+ .await?)
+}
diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rs
index cf1f6489..2a601343 100644
--- a/crates/utopia-store/src/ontology.rs
+++ b/crates/utopia-store/src/ontology.rs
@@ -3,8 +3,8 @@
use pgvector::Vector;
use sqlx::PgPool;
use utopia_core::models::{
- EntityInstance, EntityTypeView, OntologyImportView, OntologyMiss, RelationTypeView,
- TypeCandidate,
+ EntityInstance, EntityTypeView, OntologyImportView, OntologyMiss, RelationAxioms,
+ RelationTypeView, TypeCandidate,
};
use utopia_core::{AppError, AppResult};
use uuid::Uuid;
@@ -16,6 +16,8 @@ pub async fn entity_type_views(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Enti
WHERE p.child_id = t.id) AS parents,
(SELECT p.parent_id FROM entity_type_parents p
WHERE p.child_id = t.id AND p.is_primary) AS primary_parent,
+ ARRAY(SELECT d.b_id FROM entity_type_disjoint d
+ WHERE d.kb_id = t.kb_id AND d.a_id = t.id) AS disjoint,
(SELECT count(*) FROM entities e
WHERE e.type_id = t.id AND e.merged_into IS NULL) AS usage
FROM entity_types t WHERE t.kb_id = $1 ORDER BY lower(t.label)",
@@ -71,7 +73,9 @@ fn validate_shape(shape: &str) -> AppResult<()> {
pub async fn relation_type_views(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<RelationTypeView>> {
Ok(sqlx::query_as(
- "SELECT r.id, r.key, r.label, r.temporal, r.functional, r.inverse_functional, r.builtin, r.description,
+ "SELECT r.id, r.key, r.label, r.temporal, r.functional, r.inverse_functional,
+ r.is_transitive, r.is_symmetric, r.is_asymmetric, r.is_irreflexive,
+ r.builtin, r.description,
r.kind, r.datatype, r.unit,
ARRAY(SELECT d.entity_type_id FROM relation_type_domains d
WHERE d.relation_type_id = r.id) AS domains,
@@ -301,8 +305,7 @@ pub async fn create_relation_type(
key: &str,
label: &str,
temporal: &str,
- functional: bool,
- inverse_functional: bool,
+ ax: RelationAxioms,
description: &str,
kind: &str,
domains: &[Uuid],
@@ -320,21 +323,28 @@ pub async fn create_relation_type(
let is_attr = kind == "attribute";
let id = Uuid::now_v7();
sqlx::query(
- "INSERT INTO relation_types (id, kb_id, key, label, temporal, functional, inverse_functional, description,
- kind, datatype, unit)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)",
+ "INSERT INTO relation_types (id, kb_id, key, label, temporal,
+ functional, inverse_functional, description,
+ kind, datatype, unit,
+ is_transitive, is_symmetric,
+ is_asymmetric, is_irreflexive)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)",
)
.bind(id)
.bind(kb_id)
.bind(key)
.bind(label)
.bind(temporal)
- .bind(functional)
- .bind(inverse_functional)
+ .bind(ax.functional)
+ .bind(ax.inverse_functional)
.bind(description)
.bind(kind)
.bind(is_attr.then_some(datatype).flatten())
.bind(is_attr.then_some(unit).flatten())
+ .bind(ax.transitive)
+ .bind(ax.symmetric)
+ .bind(ax.asymmetric)
+ .bind(ax.irreflexive)
.execute(pool)
.await
.map_err(|e| match &e {
@@ -388,8 +398,7 @@ pub async fn update_relation_type(
id: Uuid,
label: &str,
temporal: &str,
- functional: bool,
- inverse_functional: bool,
+ ax: RelationAxioms,
description: &str,
datatype: Option<&str>,
unit: Option<&str>,
@@ -412,20 +421,28 @@ pub async fn update_relation_type(
// 它们是签名不是身份,"这个属性也适用于承包商" 是个正当的编辑。
// datatype/unit 只对 attribute 行生效,datatype 缺省保持原值
let res = sqlx::query(
- "UPDATE relation_types SET label = $3, temporal = $4, functional = $5, inverse_functional = $6, description = $7,
+ "UPDATE relation_types
+ SET label = $3, temporal = $4,
+ functional = $5, inverse_functional = $6, description = $7,
datatype = CASE WHEN kind = 'attribute' AND $8 IS NOT NULL THEN $8 ELSE datatype END,
- unit = CASE WHEN kind = 'attribute' THEN $9 ELSE unit END
+ unit = CASE WHEN kind = 'attribute' THEN $9 ELSE unit END,
+ is_transitive = $10, is_symmetric = $11,
+ is_asymmetric = $12, is_irreflexive = $13
WHERE id = $2 AND kb_id = $1",
)
.bind(kb_id)
.bind(id)
.bind(label)
.bind(temporal)
- .bind(functional)
- .bind(inverse_functional)
+ .bind(ax.functional)
+ .bind(ax.inverse_functional)
.bind(description)
.bind(datatype)
.bind(unit)
+ .bind(ax.transitive)
+ .bind(ax.symmetric)
+ .bind(ax.asymmetric)
+ .bind(ax.irreflexive)
.execute(pool)
.await?;
if res.rows_affected() == 0 {
@@ -1411,6 +1428,48 @@ pub async fn set_disjoint_bulk(
Ok(())
}
+/// 把 `others` 设成这个类的**全部**互斥对象(不在其中的解除)。
+///
+/// 与 [`set_disjoint_bulk`] 的分工:那个是导入用的「只增不减」,这个是编辑用的
+/// 「这就是全部」。编辑必须能取消——否则界面上取消勾选没有任何效果,
+/// 而用户会以为自己改了。
+///
+/// 两个方向各写一行,与导入侧一致:查「A 与 B 互斥吗」因此不必关心从哪头问。
+pub async fn set_disjoint_for(
+ pool: &PgPool,
+ kb_id: Uuid,
+ class: Uuid,
+ others: &[Uuid],
+) -> AppResult<()> {
+ let mut tx = pool.begin().await?;
+ // 先清掉这个类参与的全部互斥边——两个方向都要清,因为它两边都可能出现
+ sqlx::query(
+ "DELETE FROM entity_type_disjoint
+ WHERE kb_id = $1 AND (a_id = $2 OR b_id = $2)",
+ )
+ .bind(kb_id)
+ .bind(class)
+ .execute(&mut *tx)
+ .await?;
+ for other in others {
+ if *other == class {
+ continue;
+ }
+ sqlx::query(
+ "INSERT INTO entity_type_disjoint (kb_id, a_id, b_id)
+ VALUES ($1, $2, $3), ($1, $3, $2)
+ ON CONFLICT DO NOTHING",
+ )
+ .bind(kb_id)
+ .bind(class)
+ .bind(other)
+ .execute(&mut *tx)
+ .await?;
+ }
+ tx.commit().await?;
+ Ok(())
+}
+
// ---------------------------------------------------------------------------
// 本体提案(见 `ontology_proposals`)
// ---------------------------------------------------------------------------
diff --git a/crates/utopia-store/src/reasoning.rs b/crates/utopia-store/src/reasoning.rs
new file mode 100644
index 00000000..4ed59933
--- /dev/null
+++ b/crates/utopia-store/src/reasoning.rs
@@ -0,0 +1,755 @@
+//! 一致性检查的取数与落库。判断本身在 `utopia-reason`——那一层不碰数据库。
+//!
+//! 三步:把活事实取成边、把 `relation_types` 的公理列取成 `Axioms`、把
+//! `check()` 吐出来的违规写进 `axiom_violations`。
+//!
+//! **重跑是幂等的,而且以「重算」为准。** 每次跑完,这个库里没被重新算出来的
+//! `open` 行会被删掉——它们是派生状态,事实撤了、公理放宽了,那条违规就不该
+//! 还挂在 Review 页上。已经有人表态的(`resolved`)一行不动:那是人的决定,
+//! 不是算出来的东西。
+//!
+//! 这条规矩踩过一次坑的反面(见 `ontology_proposals`):那边重跑会把被拒绝过的
+//! 提案刷回待看,等于每跑一次就把人的否决抹掉一次。所以这里 `ON CONFLICT`
+//! 什么都不做——已经在库里的那一行,无论 open 还是 resolved,都按原样留着。
+
+use sqlx::PgPool;
+use std::collections::HashMap;
+use utopia_core::models::{AxiomViolation, DerivedFactView, OntologyDefect};
+/// 规则种类的字面量。用 &'static str 而不是枚举:它直接进 SQL 也直接做键
+type RuleKind = &'static str;
+use utopia_core::AppResult;
+use utopia_reason::derive::TimedEdge;
+use utopia_reason::{check, Axioms, Edge, Violation};
+use uuid::Uuid;
+
+/// 一次检查的产出,给调用方写审计与告诉用户。
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct Report {
+ /// 参与检查的边数
+ pub edges: usize,
+ /// 声明了至少一条公理的谓词数。**为零时结论是「没有判据」而不是「没有矛盾」**
+ pub predicates_with_axioms: usize,
+ /// 这次算出来的违规总数
+ pub found: usize,
+ /// 其中是新的(此前没在库里)
+ pub inserted: usize,
+ /// 清掉的陈旧 open 行
+ pub cleared: usize,
+}
+
+/// 取这个库里所有能参与检查的边。
+///
+/// 三个过滤条件都是必要的:
+///
+/// - `invalidated_at IS NULL`——被推翻的事实不该再报矛盾,它已经不是我们的断言了
+/// - `predicate_id IS NOT NULL`——没有谓词就没有公理可依(见 `facts.predicate_id`)
+/// - `object_id IS NOT NULL`——属性事实的宾语是字面值,公理谈的是实体之间的关系
+async fn edges(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Edge>> {
+ let rows: Vec<(Uuid, Uuid, Uuid, Uuid)> = sqlx::query_as(
+ "SELECT id, predicate_id, subject_id, object_id
+ FROM facts
+ WHERE kb_id = $1
+ AND invalidated_at IS NULL
+ AND predicate_id IS NOT NULL
+ AND object_id IS NOT NULL",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows
+ .into_iter()
+ .map(|(fact, predicate, subject, object)| Edge {
+ fact,
+ predicate,
+ subject,
+ object,
+ })
+ .collect())
+}
+
+/// 取这个库的谓词公理。
+///
+/// **只取声明了至少一位的**:一位都没声明的谓词进了表也不会被检查(`says_nothing`
+/// 会跳过),白白占内存。而且这个条数本身有意义——它是「有没有判据」的度量,
+/// 报告里要用。
+async fn axioms(pool: &PgPool, kb_id: Uuid) -> AppResult<HashMap<Uuid, Axioms>> {
+ let rows: Vec<(Uuid, bool, bool, bool, bool, bool, bool)> = sqlx::query_as(
+ "SELECT id, is_transitive, is_symmetric, is_asymmetric, is_irreflexive,
+ functional, inverse_functional
+ FROM relation_types
+ WHERE kb_id = $1
+ AND (is_transitive OR is_symmetric OR is_asymmetric OR is_irreflexive
+ OR functional OR inverse_functional)",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows
+ .into_iter()
+ .map(
+ |(
+ id,
+ transitive,
+ symmetric,
+ asymmetric,
+ irreflexive,
+ functional,
+ inverse_functional,
+ )| {
+ (
+ id,
+ Axioms {
+ transitive,
+ symmetric,
+ asymmetric,
+ irreflexive,
+ functional,
+ inverse_functional,
+ },
+ )
+ },
+ )
+ .collect())
+}
+
+/// 跑一遍检查,把结果落库。
+pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
+ let edges = edges(pool, kb_id).await?;
+ let axioms = axioms(pool, kb_id).await?;
+ let violations = check(&edges, &axioms);
+
+ let mut report = Report {
+ edges: edges.len(),
+ predicates_with_axioms: axioms.len(),
+ found: violations.len(),
+ ..Default::default()
+ };
+
+ // 事务里做,否则「插新的」与「清陈旧的」之间有个窗口,那一瞬间 Review 页
+ // 会短暂地少东西
+ let mut tx = pool.begin().await?;
+ let mut fresh: Vec<Uuid> = Vec::with_capacity(violations.len());
+ for v in &violations {
+ let Violation {
+ kind,
+ left,
+ right,
+ path,
+ } = v;
+ let id: Option<(Uuid,)> = sqlx::query_as(
+ "INSERT INTO axiom_violations (id, kb_id, kind, left_fact, right_fact, path)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ ON CONFLICT (kb_id, kind, left_fact, right_fact) DO NOTHING
+ RETURNING id",
+ )
+ .bind(Uuid::now_v7())
+ .bind(kb_id)
+ .bind(kind.as_str())
+ .bind(left)
+ .bind(right)
+ .bind(path)
+ .fetch_optional(&mut *tx)
+ .await?;
+ if id.is_some() {
+ report.inserted += 1;
+ }
+ // 无论新插的还是本来就在的,都算「这一轮仍然成立」
+ let keep: (Uuid,) = sqlx::query_as(
+ "SELECT id FROM axiom_violations
+ WHERE kb_id = $1 AND kind = $2 AND left_fact = $3 AND right_fact = $4",
+ )
+ .bind(kb_id)
+ .bind(kind.as_str())
+ .bind(left)
+ .bind(right)
+ .fetch_one(&mut *tx)
+ .await?;
+ fresh.push(keep.0);
+ }
+
+ // 这一轮没算出来的 open 行是陈的:事实被撤了,或者公理放宽了。
+ // resolved 的不动——那是人的决定,不是派生状态
+ let cleared = sqlx::query(
+ "DELETE FROM axiom_violations
+ WHERE kb_id = $1 AND status = 'open' AND NOT (id = ANY($2))",
+ )
+ .bind(kb_id)
+ .bind(&fresh)
+ .execute(&mut *tx)
+ .await?;
+ report.cleared = cleared.rows_affected() as usize;
+ tx.commit().await?;
+ Ok(report)
+}
+
+/// Review 页要看的:还没人表态的违规,连同两条事实的三元组文本。
+///
+/// 展开成文本在 SQL 里做而不是回来再查一遍:一页几十条,每条两个三元组,
+/// 分开查就是上百次往返。谓词用 `fact_surface_predicate` 兜底——本体里没有
+/// 对应关系的事实拿原文说法显示(见 `facts.predicate_id`)。
+pub async fn open_violations(
+ pool: &PgPool,
+ kb_id: Uuid,
+ limit: i64,
+ offset: i64,
+) -> AppResult<Vec<AxiomViolation>> {
+ Ok(sqlx::query_as(
+ "WITH triple AS (
+ SELECT f.id,
+ s.canonical_name || ' · '
+ || COALESCE(r.label, fact_surface_predicate(f.id), '?') || ' · '
+ || COALESCE(o.canonical_name, f.object_value ->> 'summary',
+ f.object_value #>> '{}', '?') AS text,
+ r.label AS predicate
+ FROM facts f
+ JOIN entities s ON s.id = f.subject_id
+ LEFT JOIN relation_types r ON r.id = f.predicate_id
+ LEFT JOIN entities o ON o.id = f.object_id
+ WHERE f.kb_id = $1
+ )
+ SELECT v.id, v.kind, l.predicate,
+ v.left_fact, l.text AS left_text,
+ v.right_fact, rt.text AS right_text,
+ coalesce(array_length(v.path, 1), 0) AS path_len,
+ v.detected_at
+ FROM axiom_violations v
+ JOIN triple l ON l.id = v.left_fact
+ JOIN triple rt ON rt.id = v.right_fact
+ WHERE v.kb_id = $1 AND v.status = 'open'
+ ORDER BY v.detected_at DESC
+ LIMIT $2 OFFSET $3",
+ )
+ .bind(kb_id)
+ .bind(limit)
+ .bind(offset)
+ .fetch_all(pool)
+ .await?)
+}
+
+/// 人裁决一处违规。
+///
+/// **三个出路,不是两个。** 时态冲突问「哪条对」,而这里可能是定义错了——
+/// 用户导的本体把某个属性声明成反对称,而他自己的语料里那关系其实双向。
+/// `axiom_relaxed` 记的就是这种:该改的是本体,不是二十条事实。
+///
+/// 改状态不删行,与账本同一个规矩:表过态这件事本身要留痕,而且 `run` 靠
+/// `status = 'open'` 判断哪些是派生的、可以重算掉——人的决定必须活过重跑。
+pub async fn decide(
+ pool: &PgPool,
+ kb_id: Uuid,
+ violation_id: Uuid,
+ resolution: &str,
+ actor: Uuid,
+) -> AppResult<()> {
+ let res = sqlx::query(
+ "UPDATE axiom_violations
+ SET status = 'resolved', resolution = $3, decided_by = $4, decided_at = now()
+ WHERE id = $2 AND kb_id = $1 AND status = 'open'",
+ )
+ .bind(kb_id)
+ .bind(violation_id)
+ .bind(resolution)
+ .bind(actor)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(utopia_core::AppError::NotFound);
+ }
+ Ok(())
+}
+
+// ===================== R0 的另一半:本体自己 =====================
+
+/// 本体自洽性检查的产出。
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct OntologyReport {
+ pub classes: usize,
+ pub found: usize,
+ pub inserted: usize,
+ pub cleared: usize,
+}
+
+/// 量一遍本体自己:谓词的公理组合、subClassOf 的环、不可满足的类。
+///
+/// 与 [`run`] 同一套重跑规矩:`open` 是派生状态、可以被重算掉,`resolved`
+/// 是人的决定、一行不动。
+pub async fn check_ontology(pool: &PgPool, kb_id: Uuid) -> AppResult<OntologyReport> {
+ let ax = axioms(pool, kb_id).await?;
+ let parents: Vec<(Uuid, Uuid)> = sqlx::query_as(
+ "SELECT child_id, parent_id FROM entity_type_parents p
+ JOIN entity_types t ON t.id = p.child_id
+ WHERE t.kb_id = $1",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?;
+ let disjoint: Vec<(Uuid, Uuid)> =
+ sqlx::query_as("SELECT a_id, b_id FROM entity_type_disjoint WHERE kb_id = $1")
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?;
+ let classes: i64 = sqlx::query_scalar("SELECT count(*) FROM entity_types WHERE kb_id = $1")
+ .bind(kb_id)
+ .fetch_one(pool)
+ .await?;
+
+ let defects = utopia_reason::ontology::check_ontology(&ax, &parents, &disjoint);
+ let mut report = OntologyReport {
+ classes: classes as usize,
+ found: defects.len(),
+ ..Default::default()
+ };
+
+ let mut tx = pool.begin().await?;
+ let mut fresh: Vec<Uuid> = Vec::with_capacity(defects.len());
+ for d in &defects {
+ let existing: Option<(Uuid,)> = sqlx::query_as(
+ "SELECT id FROM ontology_defects
+ WHERE kb_id = $1 AND kind = $2 AND subject = $3
+ AND other IS NOT DISTINCT FROM $4",
+ )
+ .bind(kb_id)
+ .bind(d.kind.as_str())
+ .bind(d.subject)
+ .bind(d.other)
+ .fetch_optional(&mut *tx)
+ .await?;
+ let id = match existing {
+ Some((id,)) => id,
+ None => {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO ontology_defects (id, kb_id, kind, subject, other, path)
+ VALUES ($1, $2, $3, $4, $5, $6)",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .bind(d.kind.as_str())
+ .bind(d.subject)
+ .bind(d.other)
+ .bind(&d.path)
+ .execute(&mut *tx)
+ .await?;
+ report.inserted += 1;
+ id
+ }
+ };
+ fresh.push(id);
+ }
+ let cleared = sqlx::query(
+ "DELETE FROM ontology_defects
+ WHERE kb_id = $1 AND status = 'open' AND NOT (id = ANY($2))",
+ )
+ .bind(kb_id)
+ .bind(&fresh)
+ .execute(&mut *tx)
+ .await?;
+ report.cleared = cleared.rows_affected() as usize;
+ tx.commit().await?;
+ Ok(report)
+}
+
+// ===================== R1:物化推导 =====================
+
+/// 一次推导的产出。
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct DeriveReport {
+ /// 编译出来的规则条数。**为零时结论是「没有规则」而不是「推不出东西」**
+ pub rules: usize,
+ pub edges: usize,
+ /// 这一轮算出来的派生总数
+ pub derived: usize,
+ /// 新落库的
+ pub inserted: usize,
+ /// 前提没了、跟着作废的
+ pub invalidated: usize,
+ /// 撞上单谓词上限、没推完的谓词个数
+ pub capped: usize,
+}
+
+/// 派生事实的身份:三元组 + 区间。
+///
+/// **区间进键**是有意的:区间变了就是另一条断言,老的作废、新的落地,
+/// 因为账本不许原地改。
+type DerivedKey = (Uuid, Uuid, Uuid, Option<i64>, Option<i64>);
+
+/// 精度按「最粗的那个」取。
+///
+/// 派生区间的两端各来自某一条前提,严格说该各随各的精度。取最粗是**故意保守**:
+/// 一条链只和它最不确定的那一环一样可信,而把 year 级的前提推出来的结论标成
+/// day,正是 `facts.valid_from_precision` 那条注释里说的「在无知的地方填一个
+/// 确定的值」。
+fn coarsest(a: Option<&str>, b: Option<&str>) -> Option<String> {
+ let rank = |p: &str| match p {
+ "year" => 0,
+ "month" => 1,
+ _ => 2,
+ };
+ match (a, b) {
+ (Some(x), Some(y)) => Some(if rank(x) <= rank(y) { x } else { y }.to_string()),
+ (Some(x), None) | (None, Some(x)) => Some(x.to_string()),
+ (None, None) => None,
+ }
+}
+
+/// 按本体公理重编译规则,返回 `(谓词, 种类) → 规则 id`。
+///
+/// **幂等**:身份取 `(kb, 谓词, 种类)`,重编译认得出「还是那条规则」——否则每跑
+/// 一次 `derived_facts.rule_id` 就指向一个新 id,历史全断。
+///
+/// **公理撤了的规则不删。** 已失效的派生行仍指着它,解释「当时是靠哪条规则推的」
+/// 需要它还在;而它不再出现在返回值里,据它推出来的事实由下面的对账作废。
+/// 规则一个库也就几条,留着不占地方。
+async fn compile_rules(
+ pool: &PgPool,
+ kb_id: Uuid,
+ ax: &HashMap<Uuid, Axioms>,
+) -> AppResult<HashMap<(Uuid, RuleKind), Uuid>> {
+ let mut want: Vec<(Uuid, RuleKind)> = Vec::new();
+ for (&pred, a) in ax {
+ if a.transitive {
+ want.push((pred, "transitive"));
+ }
+ if a.symmetric {
+ want.push((pred, "symmetric"));
+ }
+ }
+ want.sort();
+ let mut out = HashMap::new();
+ for (pred, kind) in want {
+ sqlx::query(
+ "INSERT INTO rules (id, kb_id, predicate_id, kind) VALUES ($1, $2, $3, $4)
+ ON CONFLICT (kb_id, predicate_id, kind) DO NOTHING",
+ )
+ .bind(Uuid::now_v7())
+ .bind(kb_id)
+ .bind(pred)
+ .bind(kind)
+ .execute(pool)
+ .await?;
+ let (id,): (Uuid,) = sqlx::query_as(
+ "SELECT id FROM rules WHERE kb_id = $1 AND predicate_id = $2 AND kind = $3",
+ )
+ .bind(kb_id)
+ .bind(pred)
+ .bind(kind)
+ .fetch_one(pool)
+ .await?;
+ out.insert((pred, kind), id);
+ }
+ Ok(out)
+}
+
+/// 取边时一并拿回来的随行信息(精度与置信度,落库要用)。
+type EdgeRow = (
+ Uuid,
+ Uuid,
+ Uuid,
+ Uuid,
+ Option<chrono::DateTime<chrono::Utc>>,
+ Option<chrono::DateTime<chrono::Utc>>,
+ Option<String>,
+ Option<String>,
+ f32,
+);
+
+type LiveRow = (
+ Uuid,
+ Uuid,
+ Uuid,
+ Uuid,
+ Option<chrono::DateTime<chrono::Utc>>,
+ Option<chrono::DateTime<chrono::Utc>>,
+);
+
+/// 推一遍,把派生事实落进账本。
+///
+/// **调用方负责检查 `materialize_inferences` 开关。** 这一层不判——它也被
+/// 「预览一下会推出什么」那条路用,而预览不该受开关约束。
+pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport> {
+ let ax = axioms(pool, kb_id).await?;
+ let rules = compile_rules(pool, kb_id, &ax).await?;
+
+ // 输入**只有断言**。派生住在另一张表,所以这里连过滤都不必写——那正是
+ // 分表买到的东西:忘了排除的后果是推不出东西,不是把自己的输出喂回自己
+ let rows: Vec<EdgeRow> = sqlx::query_as(
+ "SELECT id, predicate_id, subject_id, object_id,
+ valid_from, valid_to, valid_from_precision, valid_to_precision, confidence
+ FROM facts
+ WHERE kb_id = $1
+ AND invalidated_at IS NULL
+ AND predicate_id IS NOT NULL
+ AND object_id IS NOT NULL",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?;
+
+ let mut edges = Vec::with_capacity(rows.len());
+ let mut meta: HashMap<Uuid, (Option<String>, Option<String>, f32)> = HashMap::new();
+ let mut spans: HashMap<Uuid, (Option<i64>, Option<i64>)> = HashMap::new();
+ for (id, pred, subj, obj, from, to, fp, tp, conf) in rows {
+ let (f, t) = (from.map(|x| x.timestamp()), to.map(|x| x.timestamp()));
+ edges.push(TimedEdge {
+ edge: Edge {
+ fact: id,
+ predicate: pred,
+ subject: subj,
+ object: obj,
+ },
+ from: f,
+ to: t,
+ });
+ spans.insert(id, (f, t));
+ meta.insert(id, (fp, tp, conf));
+ }
+
+ let derivation = utopia_reason::derive::derive(&edges, &ax);
+ let mut report = DeriveReport {
+ rules: rules.len(),
+ edges: edges.len(),
+ derived: derivation.facts.len(),
+ capped: derivation.capped.len(),
+ ..Default::default()
+ };
+
+ let mut wanted: HashMap<DerivedKey, &utopia_reason::derive::Derived> = HashMap::new();
+ for d in &derivation.facts {
+ let Some((from, to)) = utopia_reason::derive::validity(&d.premises, &spans) else {
+ continue;
+ };
+ wanted.insert((d.subject, d.predicate, d.object, from, to), d);
+ }
+
+ let mut tx = pool.begin().await?;
+ let live: Vec<LiveRow> = sqlx::query_as(
+ "SELECT id, subject_id, predicate_id, object_id, valid_from, valid_to
+ FROM derived_facts
+ WHERE kb_id = $1 AND invalidated_at IS NULL",
+ )
+ .bind(kb_id)
+ .fetch_all(&mut *tx)
+ .await?;
+
+ let mut stale: Vec<Uuid> = Vec::new();
+ for (id, s, p, o, from, to) in &live {
+ let key = (
+ *s,
+ *p,
+ *o,
+ from.map(|x| x.timestamp()),
+ to.map(|x| x.timestamp()),
+ );
+ if wanted.remove(&key).is_none() {
+ stale.push(*id);
+ }
+ }
+
+ // 前提没了 → 派生跟着失效。**置 invalidated_at 而不是删**:与拒绝一条事实
+ // 完全同构,记录轴上留下「我们曾据此推出,后来前提没了」,实体历史页面
+ // 直接就能展示(0002 第 3 节)
+ if !stale.is_empty() {
+ sqlx::query("UPDATE derived_facts SET invalidated_at = now() WHERE id = ANY($1)")
+ .bind(&stale)
+ .execute(&mut *tx)
+ .await?;
+ report.invalidated = stale.len();
+ }
+
+ for ((subject, predicate, object, from, to), d) in wanted {
+ let Some(&rule_id) = rules.get(&(predicate, d.rule.as_str())) else {
+ continue;
+ };
+ // 精度与置信度都取前提里最保守的那一个
+ let mut fp: Option<String> = None;
+ let mut tp: Option<String> = None;
+ let mut conf = 1.0f32;
+ for p in &d.premises {
+ if let Some((pf, pt, pc)) = meta.get(p) {
+ fp = coarsest(fp.as_deref(), pf.as_deref());
+ tp = coarsest(tp.as_deref(), pt.as_deref());
+ conf = conf.min(*pc);
+ }
+ }
+ // 约束是「有日期才有精度」——交集把某一端算成无界时,那一端的精度也得清掉
+ let fp = from.and(fp);
+ let tp = to.and(tp);
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO derived_facts (id, kb_id, subject_id, predicate_id, object_id,
+ valid_from, valid_to,
+ valid_from_precision, valid_to_precision,
+ confidence, rule_id)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .bind(subject)
+ .bind(predicate)
+ .bind(object)
+ .bind(from.map(stamp))
+ .bind(to.map(stamp))
+ .bind(&fp)
+ .bind(&tp)
+ .bind(conf)
+ .bind(rule_id)
+ .execute(&mut *tx)
+ .await?;
+ for (seq, premise) in d.premises.iter().enumerate() {
+ sqlx::query(
+ "INSERT INTO fact_derivations (derived_fact_id, premise_fact_id, seq)
+ VALUES ($1, $2, $3)",
+ )
+ .bind(id)
+ .bind(premise)
+ .bind(seq as i32)
+ .execute(&mut *tx)
+ .await?;
+ }
+ report.inserted += 1;
+ }
+ tx.commit().await?;
+ Ok(report)
+}
+
+fn stamp(secs: i64) -> chrono::DateTime<chrono::Utc> {
+ chrono::DateTime::from_timestamp(secs, 0).unwrap_or_default()
+}
+
+/// Review 页要看的本体缺陷,连同标签。
+///
+/// 标签在 SQL 里取而不是回来再查:`subject` 那一列同一列指两张表(谓词或类),
+/// 分开查就要先按 kind 分组、再发两批查询,而一次 LEFT JOIN 两张表就够——
+/// 一个 id 只可能命中其中一张。
+pub async fn open_defects(
+ pool: &PgPool,
+ kb_id: Uuid,
+ limit: i64,
+ offset: i64,
+) -> AppResult<Vec<OntologyDefect>> {
+ Ok(sqlx::query_as(
+ "SELECT d.id, d.kind,
+ COALESCE(st.label, sr.label) AS subject_label,
+ ot.label AS other_label,
+ COALESCE(
+ (SELECT array_agg(t.label ORDER BY x.ord)
+ FROM unnest(d.path) WITH ORDINALITY AS x(id, ord)
+ JOIN entity_types t ON t.id = x.id),
+ ARRAY[]::text[]
+ ) AS path_labels,
+ d.detected_at
+ FROM ontology_defects d
+ LEFT JOIN entity_types st ON st.id = d.subject
+ LEFT JOIN relation_types sr ON sr.id = d.subject
+ LEFT JOIN entity_types ot ON ot.id = d.other
+ WHERE d.kb_id = $1 AND d.status = 'open'
+ ORDER BY d.detected_at DESC
+ LIMIT $2 OFFSET $3",
+ )
+ .bind(kb_id)
+ .bind(limit)
+ .bind(offset)
+ .fetch_all(pool)
+ .await?)
+}
+
+/// 人对一处本体缺陷表态。
+///
+/// 两个出路而不是三个:本体缺陷没有「数据错了」这一条——它压根没看数据。
+/// `fixed` 是「我去改了本体」,`accepted` 是「看过,不必改」。
+pub async fn decide_defect(
+ pool: &PgPool,
+ kb_id: Uuid,
+ defect_id: Uuid,
+ resolution: &str,
+ actor: Uuid,
+) -> AppResult<()> {
+ let res = sqlx::query(
+ "UPDATE ontology_defects
+ SET status = 'resolved', resolution = $3, decided_by = $4, decided_at = now()
+ WHERE id = $2 AND kb_id = $1 AND status = 'open'",
+ )
+ .bind(kb_id)
+ .bind(defect_id)
+ .bind(resolution)
+ .bind(actor)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(utopia_core::AppError::NotFound);
+ }
+ Ok(())
+}
+
+/// 到点该重推的库。
+///
+/// 与来源同步同一个形状:一个间隔 + 一个上次时间。**从没推过的算到期**——
+/// 刚打开开关的库不该等一个周期才第一次推。
+pub async fn due_for_inference(pool: &PgPool) -> AppResult<Vec<Uuid>> {
+ Ok(sqlx::query_scalar(
+ "SELECT id FROM knowledge_bases
+ WHERE materialize_inferences
+ AND (last_inference_at IS NULL
+ OR last_inference_at < now()
+ - make_interval(mins => inference_interval_minutes))",
+ )
+ .fetch_all(pool)
+ .await?)
+}
+
+/// 记下这一轮推完的时间。
+///
+/// **推完就记,哪怕什么都没变**:这一列答的是「上次看过没有」,不是「上次改过
+/// 没有」。不记的话没变化的库会每分钟被扫起来重算一遍。
+pub async fn mark_inference_ran(pool: &PgPool, kb_id: Uuid) -> AppResult<()> {
+ sqlx::query("UPDATE knowledge_bases SET last_inference_at = now() WHERE id = $1")
+ .bind(kb_id)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 一条派生事实,配好展示与证明所需的文本(实体面板的「推出来的」那一档)。
+///
+/// **证明一起取回来**:这一档存在的理由就是「这条边不是谁说的,是这么推出来的」,
+/// 而不给出前提的话它跟一条普通的边看不出区别——那正是用户担心的污染。
+pub async fn derived_for_entity(
+ pool: &PgPool,
+ kb_id: Uuid,
+ entity_id: Uuid,
+) -> AppResult<Vec<DerivedFactView>> {
+ Ok(sqlx::query_as(
+ "SELECT d.id,
+ d.subject_id, s.canonical_name AS subject,
+ d.object_id, o.canonical_name AS object,
+ r.label AS predicate,
+ ru.kind AS rule,
+ d.valid_from, d.valid_to, d.confidence, d.derived_at,
+ COALESCE(
+ (SELECT array_agg(
+ ps.canonical_name || ' · '
+ || COALESCE(pr.label, '?') || ' · '
+ || COALESCE(po.canonical_name, '?')
+ ORDER BY fd.seq)
+ FROM fact_derivations fd
+ JOIN facts pf ON pf.id = fd.premise_fact_id
+ JOIN entities ps ON ps.id = pf.subject_id
+ LEFT JOIN relation_types pr ON pr.id = pf.predicate_id
+ LEFT JOIN entities po ON po.id = pf.object_id
+ WHERE fd.derived_fact_id = d.id),
+ ARRAY[]::text[]
+ ) AS premises
+ FROM derived_facts d
+ JOIN entities s ON s.id = d.subject_id
+ JOIN entities o ON o.id = d.object_id
+ JOIN relation_types r ON r.id = d.predicate_id
+ JOIN rules ru ON ru.id = d.rule_id
+ WHERE d.kb_id = $1 AND d.invalidated_at IS NULL
+ AND (d.subject_id = $2 OR d.object_id = $2)
+ ORDER BY d.derived_at DESC",
+ )
+ .bind(kb_id)
+ .bind(entity_id)
+ .fetch_all(pool)
+ .await?)
+}
diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs
index 01b87320..8376ba68 100644
--- a/crates/utopia-store/src/resolution.rs
+++ b/crates/utopia-store/src/resolution.rs
@@ -892,14 +892,21 @@ async fn assemble_reviews(
}
/// 全部待处理审核项(LLM 裁决中 + 等人工的都展示,人工可随时抢先定夺)。
-pub async fn list_reviews(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<ReviewItem>> {
+pub async fn list_reviews(
+ pool: &PgPool,
+ kb_id: Uuid,
+ limit: i64,
+ offset: i64,
+) -> AppResult<Vec<ReviewItem>> {
let rows: Vec<ReviewRow> = sqlx::query_as(
"SELECT id, left_id, right_id, score, reason, stage, created_at
FROM resolution_reviews
WHERE kb_id = $1 AND status = 'pending'
- ORDER BY created_at DESC LIMIT 100",
+ ORDER BY created_at DESC LIMIT $2 OFFSET $3",
)
.bind(kb_id)
+ .bind(limit)
+ .bind(offset)
.fetch_all(pool)
.await?;
assemble_reviews(pool, kb_id, rows).await
@@ -1420,7 +1427,12 @@ pub async fn revert_merge(pool: &PgPool, kb_id: Uuid, merge_id: Uuid) -> AppResu
}
/// 合并日志(审核页历史区)。
-pub async fn list_merges(pool: &PgPool, kb_id: Uuid, limit: i64) -> AppResult<Vec<MergeLogView>> {
+pub async fn list_merges(
+ pool: &PgPool,
+ kb_id: Uuid,
+ limit: i64,
+ offset: i64,
+) -> AppResult<Vec<MergeLogView>> {
let rows: Vec<MergeLogView> = sqlx::query_as(
"SELECT m.id, s.canonical_name AS source_name, t.canonical_name AS target_name,
u.display_name AS merged_by_name, m.reason, m.created_at, m.reverted_at
@@ -1429,10 +1441,11 @@ pub async fn list_merges(pool: &PgPool, kb_id: Uuid, limit: i64) -> AppResult<Ve
JOIN entities t ON t.id = m.target_id
LEFT JOIN users u ON u.id = m.merged_by
WHERE m.kb_id = $1
- ORDER BY m.created_at DESC LIMIT $2",
+ ORDER BY m.created_at DESC LIMIT $2 OFFSET $3",
)
.bind(kb_id)
.bind(limit)
+ .bind(offset)
.fetch_all(pool)
.await?;
Ok(rows)
diff --git a/crates/utopia-store/src/review.rs b/crates/utopia-store/src/review.rs
new file mode 100644
index 00000000..dd87081f
--- /dev/null
+++ b/crates/utopia-store/src/review.rs
@@ -0,0 +1,52 @@
+//! 审核队列的**真实条数**。
+//!
+//! 从前左栏的徽标读的是接口返回的数组长度,而接口固定只回 100 条——于是一个
+//! 有 164 条低置信事实的库,界面写着 100。清完那 100 条,剩下的 64 条会再冒
+//! 出来,看起来像凭空长的。
+//!
+//! **数数和取数是两件事,得分开做。** 取数有上限(一页十条,翻页拿下一页),
+//! 数数没有:`count(*)` 走的是与列表同一套 WHERE,索引也是同一条。
+//!
+//! 八个 COUNT 合成一条查询而不是发八次:它们都在同一个 kb 上,一次往返把
+//! 左栏一次性填满,而分开发会让切换知识库时左栏一档一档地跳出来。
+
+use sqlx::PgPool;
+use utopia_core::models::ReviewCounts;
+use utopia_core::AppResult;
+use uuid::Uuid;
+
+/// 低置信的阈值。**与 `review_routes` 共用一个常量**——两处各写一个数,
+/// 迟早分叉成「徽标说 12 条,点进去 9 条」。
+pub const LOW_CONFIDENCE_BELOW: f32 = 0.75;
+
+pub async fn counts(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewCounts> {
+ Ok(sqlx::query_as(
+ "SELECT
+ (SELECT count(*) FROM resolution_reviews
+ WHERE kb_id = $1 AND status = 'pending') AS duplicates,
+ (SELECT count(*) FROM fact_conflicts
+ WHERE kb_id = $1 AND status = 'open') AS conflicts,
+ -- 待确认 = 有证据、但证据所在的分块全被新版本取代了
+ (SELECT count(*) FROM facts f
+ WHERE f.kb_id = $1 AND f.invalidated_at IS NULL
+ AND EXISTS (SELECT 1 FROM fact_evidence fe WHERE fe.fact_id = f.id)
+ AND NOT EXISTS (SELECT 1 FROM fact_evidence fe
+ JOIN chunks c ON c.id = fe.chunk_id
+ WHERE fe.fact_id = f.id
+ AND c.superseded_at IS NULL)) AS unconfirmed,
+ (SELECT count(*) FROM facts
+ WHERE kb_id = $1 AND invalidated_at IS NULL
+ AND confidence < $2 AND derived_by_rule IS NULL) AS lowconf,
+ (SELECT count(*) FROM concept_mappings
+ WHERE kb_id = $1 AND status = 'proposed') AS mappings,
+ (SELECT count(*) FROM axiom_violations
+ WHERE kb_id = $1 AND status = 'open') AS violations,
+ (SELECT count(*) FROM ontology_defects
+ WHERE kb_id = $1 AND status = 'open') AS defects,
+ (SELECT count(*) FROM entity_merges WHERE kb_id = $1) AS merges",
+ )
+ .bind(kb_id)
+ .bind(LOW_CONFIDENCE_BELOW)
+ .fetch_one(pool)
+ .await?)
+}
diff --git a/crates/utopia-store/src/sources.rs b/crates/utopia-store/src/sources.rs
index bcee23b0..f0ca22f7 100644
--- a/crates/utopia-store/src/sources.rs
+++ b/crates/utopia-store/src/sources.rs
@@ -293,6 +293,12 @@ pub async fn finish_sync(
}
/// 文档打标签(整组替换)。
+///
+/// **零调用,故意留着**:没有路由,界面上也没有入口。标签会是文档上唯一
+/// 「人自己贴的」维度——来源是它从哪来的,名字与状态是系统给的,三者都表达
+/// 不了「这批要脱敏」这种横跨来源、只有人知道的分组。要不要有这个维度,
+/// 悬而未决——完整的两面之辞写在 `migrations/0002_ingest.sql` 的 `tags` 列上,
+/// 别当死代码删掉。
pub async fn set_document_tags(
pool: &PgPool,
kb_id: Uuid,
diff --git a/crates/utopia-store/src/temporal.rs b/crates/utopia-store/src/temporal.rs
index 41f2d2aa..4c6d5f68 100644
--- a/crates/utopia-store/src/temporal.rs
+++ b/crates/utopia-store/src/temporal.rs
@@ -315,7 +315,12 @@ async fn record_conflict(
/// Review 页的冲突列表(双方事实带名字与区间)。
/// 惰性清理:任一方已被作废(被驳回/被别的闭合改写)的冲突已无意义,
/// 自动出队标 stale——防止在僵尸冲突上误裁(如把 Eve 闭合在已驳回的 Ivan 上)。
-pub async fn list_conflicts(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<ConflictView>> {
+pub async fn list_conflicts(
+ pool: &PgPool,
+ kb_id: Uuid,
+ limit: i64,
+ offset: i64,
+) -> AppResult<Vec<ConflictView>> {
sqlx::query(
"UPDATE fact_conflicts c
SET status = 'resolved', resolution = 'stale', resolved_at = now()
@@ -344,9 +349,11 @@ pub async fn list_conflicts(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Conflic
LEFT JOIN entities no_ ON no_.id = fn_.object_id
WHERE c.kb_id = $1 AND c.status = 'open'
ORDER BY c.created_at DESC
- LIMIT 200",
+ LIMIT $2 OFFSET $3",
)
.bind(kb_id)
+ .bind(limit)
+ .bind(offset)
.fetch_all(pool)
.await?;
Ok(rows)
diff --git a/crates/utopia-store/tests/a_mapping_is_not_a_fact.rs b/crates/utopia-store/tests/a_mapping_is_not_a_fact.rs
index cb656b0d..88d81812 100644
--- a/crates/utopia-store/tests/a_mapping_is_not_a_fact.rs
+++ b/crates/utopia-store/tests/a_mapping_is_not_a_fact.rs
@@ -71,7 +71,7 @@ async fn one_concept_one_source_one_mapping() -> anyhow::Result<()> {
let b = p("orders_v2").await?;
assert_eq!(a, b, "同一个 (概念, 源) 该是同一行,不是两行");
- let got = utopia_store::mappings::proposed(&pool, kb, 100).await?;
+ let got = utopia_store::mappings::proposed(&pool, kb, 100, 0).await?;
assert_eq!(got.len(), 1, "只该有一条");
assert_eq!(
got[0].table_name.as_deref(),
@@ -94,7 +94,7 @@ async fn one_concept_one_source_one_mapping() -> anyhow::Result<()> {
)
.await?;
assert_eq!(
- utopia_store::mappings::proposed(&pool, kb, 100)
+ utopia_store::mappings::proposed(&pool, kb, 100, 0)
.await?
.len(),
2,
@@ -164,7 +164,7 @@ async fn a_rejected_mapping_does_not_come_back() -> anyhow::Result<()> {
)
.await?;
assert!(
- utopia_store::mappings::proposed(&pool, kb, 100)
+ utopia_store::mappings::proposed(&pool, kb, 100, 0)
.await?
.is_empty(),
"拒绝过的不该重新排队"
diff --git a/crates/utopia-store/tests/axioms_judge_the_ledger.rs b/crates/utopia-store/tests/axioms_judge_the_ledger.rs
new file mode 100644
index 00000000..ef351fc2
--- /dev/null
+++ b/crates/utopia-store/tests/axioms_judge_the_ledger.rs
@@ -0,0 +1,241 @@
+//! 一致性检查打在真库上:取数、判断、落库、重跑。
+//!
+//! 纯逻辑那部分在 `utopia-reason` 里已经有 12 个用例,不起库就能跑。这里钉的是
+//! 那一层看不见的四样,每一样都活在 SQL 或表约束里:
+//!
+//! - **取数的三个过滤**。被推翻的事实、没有谓词的事实、宾语是字面值的属性事实,
+//! 都不该参与——公理谈的是实体之间的关系
+//! - **没有公理就没有判据**。一个没导本体包的库跑出来是零,那是实情不是故障
+//! - **重跑幂等**。同一处矛盾不重复入库,而人表过态的那一行重跑不会被抹掉
+//! (`ontology_proposals` 在这里踩过坑:重跑把被拒绝的提案刷回待看)
+//! - **陈旧的会被清掉**。事实撤了,那条违规就不该还挂在 Review 页上
+//!
+//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆。
+
+use sqlx::PgPool;
+use utopia_store::reasoning;
+use uuid::Uuid;
+
+struct Fixture {
+ org: Uuid,
+ kb: Uuid,
+ /// 声明了 asymmetric + irreflexive
+ owns: Uuid,
+ /// 一位公理都没声明
+ mentions: Uuid,
+ a: Uuid,
+ b: Uuid,
+}
+
+async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let etype = Uuid::now_v7();
+ let (owns, mentions) = (Uuid::now_v7(), Uuid::now_v7());
+ let (a, b) = (Uuid::now_v7(), Uuid::now_v7());
+
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'axioms-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'axioms-test')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'axioms-test')",
+ )
+ .bind(kb)
+ .bind(ws)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'thing', 'Thing')",
+ )
+ .bind(etype)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label, is_asymmetric, is_irreflexive)
+ VALUES ($1, $2, 'owns', 'owns', TRUE, TRUE)",
+ )
+ .bind(owns)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ // 一位公理都没有——它的边永远不该被判成矛盾
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label) VALUES ($1, $2, 'mentions', 'mentions')",
+ )
+ .bind(mentions)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ for (id, name) in [(a, "Acme"), (b, "Beta")] {
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
+ )
+ .bind(id)
+ .bind(kb)
+ .bind(etype)
+ .bind(name)
+ .execute(pool)
+ .await?;
+ }
+ Ok(Fixture {
+ org,
+ kb,
+ owns,
+ mentions,
+ a,
+ b,
+ })
+}
+
+/// 落一条关系事实,返回它的 id。
+async fn fact(pool: &PgPool, kb: Uuid, s: Uuid, p: Uuid, o: Uuid) -> anyhow::Result<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id)
+ VALUES ($1, $2, $3, $4, $5)",
+ )
+ .bind(id)
+ .bind(kb)
+ .bind(s)
+ .bind(p)
+ .bind(o)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+async fn open_kinds(pool: &PgPool, kb: Uuid) -> anyhow::Result<Vec<String>> {
+ Ok(sqlx::query_scalar(
+ "SELECT kind FROM axiom_violations WHERE kb_id = $1 AND status = 'open' ORDER BY kind",
+ )
+ .bind(kb)
+ .fetch_all(pool)
+ .await?)
+}
+
+#[tokio::test]
+async fn the_ontology_is_the_only_judge() -> anyhow::Result<()> {
+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ // ---- 一、没有矛盾的库跑出来是零
+ let quiet = fact(&pool, f.kb, f.a, f.owns, f.b).await?;
+ let r = reasoning::run(&pool, f.kb).await?;
+ assert_eq!(r.edges, 1);
+ assert_eq!(r.predicates_with_axioms, 1, "mentions 一位都没声明,不该进来");
+ assert_eq!(r.found, 0, "一条单向的 owns 不构成任何矛盾");
+
+ // ---- 二、公理说了才算数
+ // B owns A —— 与上面那条构成反对称违规
+ let back = fact(&pool, f.kb, f.b, f.owns, f.a).await?;
+ // A mentions B / B mentions A —— 双向,但 mentions 没有公理,不该报
+ fact(&pool, f.kb, f.a, f.mentions, f.b).await?;
+ fact(&pool, f.kb, f.b, f.mentions, f.a).await?;
+ // A owns A —— 自反违规
+ let loop_fact = fact(&pool, f.kb, f.a, f.owns, f.a).await?;
+
+ let r = reasoning::run(&pool, f.kb).await?;
+ assert_eq!(r.edges, 5);
+ assert_eq!(
+ open_kinds(&pool, f.kb).await?,
+ vec!["asymmetry", "self_loop"],
+ "双向的 mentions 不该被报——它的谓词没有任何公理"
+ );
+ assert_eq!(r.inserted, 2);
+
+ // 自反那一条:两列指的是同一条事实
+ let (l, rr): (Uuid, Uuid) = sqlx::query_as(
+ "SELECT left_fact, right_fact FROM axiom_violations
+ WHERE kb_id = $1 AND kind = 'self_loop'",
+ )
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(l, loop_fact);
+ assert_eq!(l, rr, "一条事实跟自己矛盾,不需要第二条");
+
+ // ---- 三、重跑不重复入库
+ let again = reasoning::run(&pool, f.kb).await?;
+ assert_eq!(again.found, 2);
+ assert_eq!(again.inserted, 0, "同一处矛盾第二次跑不该再插一行");
+ assert_eq!(again.cleared, 0, "也不该把上一轮的清掉");
+
+ // ---- 四、人表过态的,重跑不抹
+ sqlx::query(
+ "UPDATE axiom_violations SET status = 'resolved', resolution = 'accepted'
+ WHERE kb_id = $1 AND kind = 'asymmetry'",
+ )
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ let after = reasoning::run(&pool, f.kb).await?;
+ assert_eq!(after.inserted, 0, "已经有人表态的那一行不该被重新插一条");
+ let resolved: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM axiom_violations WHERE kb_id = $1 AND status = 'resolved'",
+ )
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(resolved, 1, "人的决定必须活过重跑");
+
+ // ---- 五、事实撤了,陈旧的 open 行要清掉
+ sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = $1")
+ .bind(loop_fact)
+ .execute(&pool)
+ .await?;
+ let swept = reasoning::run(&pool, f.kb).await?;
+ assert_eq!(swept.cleared, 1, "被推翻的事实不该还挂着一条违规");
+ assert!(
+ !open_kinds(&pool, f.kb).await?.contains(&"self_loop".to_string()),
+ "撤掉那条事实之后自反违规就不成立了"
+ );
+
+ // ---- 六、属性事实不参与:宾语是字面值,公理谈的是实体之间的关系
+ sqlx::query(
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_value)
+ VALUES ($1, $2, $3, $4, '\"2015\"'::jsonb)",
+ )
+ .bind(Uuid::now_v7())
+ .bind(f.kb)
+ .bind(f.a)
+ .bind(f.owns)
+ .execute(&pool)
+ .await?;
+ let attrs = reasoning::run(&pool, f.kb).await?;
+ assert_eq!(attrs.edges, 4, "字面值宾语的那条不该被取成边");
+
+ // ---- 七、没有本体包的库:结论是「没有判据」,不是「没有矛盾」
+ sqlx::query("UPDATE relation_types SET is_asymmetric = FALSE, is_irreflexive = FALSE WHERE kb_id = $1")
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ let blind = reasoning::run(&pool, f.kb).await?;
+ assert_eq!(blind.predicates_with_axioms, 0);
+ assert_eq!(blind.found, 0);
+ assert!(
+ open_kinds(&pool, f.kb).await?.is_empty(),
+ "公理撤了,据它报出来的违规也该跟着走"
+ );
+ let _ = (quiet, back);
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ // 连 org 一起删——只删 kb 会把 organizations / workspaces 留在开发库里
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ run
+}
diff --git a/crates/utopia-store/tests/derived_facts_are_second_class.rs b/crates/utopia-store/tests/derived_facts_are_second_class.rs
new file mode 100644
index 00000000..866d291b
--- /dev/null
+++ b/crates/utopia-store/tests/derived_facts_are_second_class.rs
@@ -0,0 +1,304 @@
+//! R1 打在真库上。纯逻辑那部分(`utopia-reason::derive`)已有 12 个用例,
+//! 这里钉的是它看不见的四样:
+//!
+//! - **断言优先于派生**。已经断言过的三元组不再派生一份
+//! - **前提撤了,派生跟着失效**——而且是置 `invalidated_at` 不是删行,
+//! 记录轴上要留下「我们曾据此推出,后来前提没了」(0002 第 3 节)
+//! - **证明存得下来**。`fact_derivations` 按 seq 记直接前提,R2 顺着它展开
+//! - **规则身份跨重跑稳定**。否则每跑一次 `rule_id` 指向新 id,历史全断
+//!
+//! 还有一条只有连库才验得出:派生事实要过 `facts` 的两条精度 CHECK。
+//! 交集把某一端算成无界时,那一端的精度必须跟着清掉,否则整条 INSERT 被拒。
+
+use sqlx::PgPool;
+use utopia_store::reasoning;
+use uuid::Uuid;
+
+struct Fixture {
+ org: Uuid,
+ kb: Uuid,
+ part_of: Uuid,
+ a: Uuid,
+ b: Uuid,
+ c: Uuid,
+}
+
+async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let etype = Uuid::now_v7();
+ let part_of = Uuid::now_v7();
+ let (a, b, c) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'derive-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'derive-test')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'derive-test')",
+ )
+ .bind(kb)
+ .bind(ws)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'thing', 'Thing')",
+ )
+ .bind(etype)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label, is_transitive)
+ VALUES ($1, $2, 'part_of', 'part of', TRUE)",
+ )
+ .bind(part_of)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ for (id, name) in [(a, "Acme"), (b, "Beta"), (c, "Cyrus")] {
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
+ )
+ .bind(id)
+ .bind(kb)
+ .bind(etype)
+ .bind(name)
+ .execute(pool)
+ .await?;
+ }
+ Ok(Fixture {
+ org,
+ kb,
+ part_of,
+ a,
+ b,
+ c,
+ })
+}
+
+/// 落一条断言事实,可带区间与精度。
+async fn assert_fact(
+ pool: &PgPool,
+ f: &Fixture,
+ s: Uuid,
+ o: Uuid,
+ span: Option<(&str, &str)>,
+) -> anyhow::Result<Uuid> {
+ let id = Uuid::now_v7();
+ match span {
+ Some((from, prec)) => {
+ sqlx::query(
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id,
+ valid_from, valid_from_precision)
+ VALUES ($1, $2, $3, $4, $5, $6::timestamptz, $7)",
+ )
+ .bind(id)
+ .bind(f.kb)
+ .bind(s)
+ .bind(f.part_of)
+ .bind(o)
+ .bind(from)
+ .bind(prec)
+ .execute(pool)
+ .await?;
+ }
+ None => {
+ sqlx::query(
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id)
+ VALUES ($1, $2, $3, $4, $5)",
+ )
+ .bind(id)
+ .bind(f.kb)
+ .bind(s)
+ .bind(f.part_of)
+ .bind(o)
+ .execute(pool)
+ .await?;
+ }
+ }
+ Ok(id)
+}
+
+/// 活着的派生事实:(主, 宾)
+async fn live_derived(pool: &PgPool, kb: Uuid) -> anyhow::Result<Vec<(Uuid, Uuid)>> {
+ Ok(sqlx::query_as(
+ "SELECT subject_id, object_id FROM derived_facts
+ WHERE kb_id = $1 AND invalidated_at IS NULL
+ ORDER BY subject_id, object_id",
+ )
+ .bind(kb)
+ .fetch_all(pool)
+ .await?)
+}
+
+#[tokio::test]
+async fn what_the_engine_adds_it_can_also_take_back() -> anyhow::Result<()> {
+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ // ---- 一、A ⊂ B ⊂ C ⟹ A ⊂ C
+ let ab = assert_fact(&pool, &f, f.a, f.b, None).await?;
+ let bc = assert_fact(&pool, &f, f.b, f.c, None).await?;
+ let r = reasoning::materialize(&pool, f.kb).await?;
+ assert_eq!(r.rules, 1, "一条 transitive 规则");
+ assert_eq!(r.edges, 2);
+ assert_eq!(r.inserted, 1);
+ assert_eq!(live_derived(&pool, f.kb).await?, vec![(f.a, f.c)]);
+
+ // 证明:两条前提,按顺序
+ let derived: Uuid = sqlx::query_scalar("SELECT id FROM derived_facts WHERE kb_id = $1")
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+ let premises: Vec<Uuid> = sqlx::query_scalar(
+ "SELECT premise_fact_id FROM fact_derivations
+ WHERE derived_fact_id = $1 ORDER BY seq",
+ )
+ .bind(derived)
+ .fetch_all(&pool)
+ .await?;
+ assert_eq!(premises, vec![ab, bc], "证明要按推导顺序记直接前提");
+
+ // ---- 二、重跑幂等,规则 id 不变
+ let rule_before: Uuid = sqlx::query_scalar("SELECT id FROM rules WHERE kb_id = $1")
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+ let again = reasoning::materialize(&pool, f.kb).await?;
+ assert_eq!(again.inserted, 0, "同一条派生第二次跑不该再插一份");
+ assert_eq!(again.invalidated, 0);
+ let rule_after: Uuid = sqlx::query_scalar("SELECT id FROM rules WHERE kb_id = $1")
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(rule_before, rule_after, "重编译要认得出还是那条规则");
+
+ // ---- 三、断言优先:把 A ⊂ C 也断言出来,派生的那条就该让路
+ assert_fact(&pool, &f, f.a, f.c, None).await?;
+ let asserted = reasoning::materialize(&pool, f.kb).await?;
+ assert_eq!(asserted.derived, 0, "断言过的三元组不该再派生");
+ assert_eq!(asserted.invalidated, 1, "此前派生的那条要作废");
+ assert!(live_derived(&pool, f.kb).await?.is_empty());
+ // 作废不是删——记录轴上留着
+ let ghost: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM derived_facts
+ WHERE kb_id = $1 AND invalidated_at IS NOT NULL",
+ )
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(ghost, 1, "派生失效要留痕,与拒绝一条事实同构");
+
+ // ---- 四、前提撤了,派生跟着走
+ sqlx::query(
+ "UPDATE facts SET invalidated_at = now() WHERE subject_id = $1 AND object_id = $2",
+ )
+ .bind(f.a)
+ .bind(f.c)
+ .execute(&pool)
+ .await?;
+ let back = reasoning::materialize(&pool, f.kb).await?;
+ assert_eq!(back.inserted, 1, "断言撤了,派生该回来");
+ sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = $1")
+ .bind(bc)
+ .execute(&pool)
+ .await?;
+ let gone = reasoning::materialize(&pool, f.kb).await?;
+ assert_eq!(gone.invalidated, 1, "前提没了,派生必须跟着失效");
+ assert!(live_derived(&pool, f.kb).await?.is_empty());
+
+ // ---- 五、精度:交集把结束端算成无界,那一端的精度必须跟着清掉,
+ // 否则撞上 facts_to_precision_matches_date
+ sqlx::query("UPDATE facts SET invalidated_at = NULL WHERE id = $1")
+ .bind(bc)
+ .execute(&pool)
+ .await?;
+ sqlx::query(
+ "UPDATE facts SET valid_from = '2020-01-01'::timestamptz,
+ valid_from_precision = 'year' WHERE id = $1",
+ )
+ .bind(ab)
+ .execute(&pool)
+ .await?;
+ sqlx::query(
+ "UPDATE facts SET valid_from = '2022-06-01'::timestamptz,
+ valid_from_precision = 'day' WHERE id = $1",
+ )
+ .bind(bc)
+ .execute(&pool)
+ .await?;
+ let dated = reasoning::materialize(&pool, f.kb).await?;
+ assert_eq!(dated.inserted, 1);
+ let (from, fp, tp): (
+ Option<chrono::DateTime<chrono::Utc>>,
+ Option<String>,
+ Option<String>,
+ ) = sqlx::query_as(
+ "SELECT valid_from, valid_from_precision, valid_to_precision FROM derived_facts
+ WHERE kb_id = $1 AND invalidated_at IS NULL",
+ )
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(
+ from.map(|x| x.format("%Y-%m-%d").to_string()).as_deref(),
+ Some("2022-06-01"),
+ "交集取两个起点里晚的那个"
+ );
+ assert_eq!(
+ fp.as_deref(),
+ Some("year"),
+ "精度取最粗的——链只和最弱的一环一样可信"
+ );
+ assert_eq!(tp, None, "结束端无界,精度必须是空");
+
+ // ---- 六、公理撤了:据它推出的事实作废,而规则行**留着**
+ sqlx::query("UPDATE relation_types SET is_transitive = FALSE WHERE id = $1")
+ .bind(f.part_of)
+ .execute(&pool)
+ .await?;
+ let blind = reasoning::materialize(&pool, f.kb).await?;
+ assert_eq!(blind.rules, 0, "没有公理就编不出规则");
+ assert_eq!(blind.invalidated, 1, "据它推出来的事实要作废");
+ assert!(live_derived(&pool, f.kb).await?.is_empty());
+ let rules_left: i64 = sqlx::query_scalar("SELECT count(*) FROM rules WHERE kb_id = $1")
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(
+ rules_left, 1,
+ "规则行留着——刚作废的那些派生仍指着它,解释「当时靠哪条规则推的」需要它还在"
+ );
+ // 公理加回来,派生也要回来(规则 id 还是原来那个)
+ sqlx::query("UPDATE relation_types SET is_transitive = TRUE WHERE id = $1")
+ .bind(f.part_of)
+ .execute(&pool)
+ .await?;
+ let revived = reasoning::materialize(&pool, f.kb).await?;
+ assert_eq!(revived.rules, 1);
+ assert_eq!(revived.inserted, 1, "公理回来,推导也回来");
+ let rule_now: Uuid = sqlx::query_scalar("SELECT id FROM rules WHERE kb_id = $1")
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(rule_now, rule_before, "撤了又加回来,还是同一条规则");
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ run
+}
diff --git a/migrations/0002_ingest.sql b/migrations/0002_ingest.sql
index c131ff25..1a49d983 100644
--- a/migrations/0002_ingest.sql
+++ b/migrations/0002_ingest.sql
@@ -53,7 +53,22 @@ CREATE TABLE documents (
-- 抽取慢慢跑
graph_status TEXT NOT NULL DEFAULT 'none'
CHECK (graph_status IN ('none', 'queued', 'extracting', 'done', 'failed')),
- -- 文档标签(过滤与批量组织;不做实体文件夹)
+ -- 文档标签(过滤与批量组织;不做实体文件夹)。
+ --
+ -- **今天四层皆空,而且是故意留着的。** 没有任何地方写它、读它、露出它——
+ -- `set_document_tags` 零调用,前端连字段名都没提过。它穿过了 53 → 19 → 10
+ -- 三轮迁移折叠,没有一轮有人想起它。
+ --
+ -- 留着不是忘了删:**标签会是这张表上唯一「人自己贴的」维度**。来源是文档
+ -- 从哪来的,名字与状态是系统给的,三者都不表达「这批要脱敏」「Q3 那一包」
+ -- 这种横跨来源的、只有人知道的分组。
+ --
+ -- 反对的一面同样成立:Utopia 的立论是**图才是组织结构**,而 0009 / 0010 /
+ -- 0011 删掉的正是「与本体重复的机制」。加了它就是在图旁边另建一套组织系统。
+ -- 还有更锋利的一问:标签背后最常见的真实需求是「这篇我还没核对」,而那不是
+ -- 标签,是**审阅状态**——那东西该有一等公民的表示。
+ --
+ -- 悬而未决,等外部意见。下一个想清理死代码的人:这一段就是结论,别直接删。
tags TEXT[] NOT NULL DEFAULT '{}',
-- 来源内的逻辑身份(watch_folder 相对路径 / url / rss guid / api external_id)。
-- 摄入据此做三路判定:新增 / 变更 / 未变——内容变了原地替换文档而不是堆积
diff --git a/migrations/0012_axiom_violations.sql b/migrations/0012_axiom_violations.sql
new file mode 100644
index 00000000..bd9c1e50
--- /dev/null
+++ b/migrations/0012_axiom_violations.sql
@@ -0,0 +1,56 @@
+-- 公理违规:一致性检查(0002 R0)查出来的矛盾。
+--
+-- **不复用 `fact_conflicts`**,尽管两者都是「两条事实打架,等人裁决」。理由是
+-- 裁决动作根本不同:
+--
+-- fact_conflicts 时态冲突,问的是「哪条对」
+-- → closed / kept_both / rejected_new,三个答案都在改事实
+-- axiom_violations 公理违规,问的是「错在数据还是错在定义」
+-- → 撤事实,或者去改本体那条公理
+--
+-- 后者那条出路是本质的。用户导一份 FOAF 进来,里面某个属性声明成反对称,而他
+-- 自己的语料里那关系其实双向——这时该改的是本体,不是二十条事实。硬塞进一张表,
+-- `resolution` 那一列就要同时表达两套语义,而读它的代码得先看 `reason` 才知道
+-- 该怎么解释 `resolution`。
+--
+-- 形状也对不上:`fact_conflicts` 假设冲突总是「新的顶掉旧的」(old/new 两列),
+-- 而自反违规只有**一条**事实(它自己跟自己矛盾),环是**一串**。
+
+CREATE TABLE axiom_violations (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ -- self_loop 自反:一条事实的主宾相同,而谓词声明了 Irreflexive
+ -- asymmetry 反对称:A→B 与 B→A 并存
+ -- cycle 传递环:A→B→C→A,谓词同时是 Transitive 与 Asymmetric
+ -- functional 基数:该唯一的主语侧(或宾语侧)出现了两个值
+ kind TEXT NOT NULL
+ CHECK (kind IN ('self_loop', 'asymmetry', 'cycle', 'functional')),
+ -- 涉及的两条事实。**自反那类两列相同**——一条事实跟自己矛盾,不需要第二条;
+ -- 环取首尾,中间的在 path 里
+ left_fact UUID NOT NULL REFERENCES facts(id) ON DELETE CASCADE,
+ right_fact UUID NOT NULL REFERENCES facts(id) ON DELETE CASCADE,
+ -- 环的完整路径,按事实排列;其余三类为空。
+ -- 留着是因为「A→B→C→A」比「A 与 C 矛盾」有用得多——人要顺着看一遍才知道
+ -- 该撤哪一条。
+ --
+ -- 裸 UUID 数组而不是关联表:它是一条**证据**(当时那个环长这样),不是一组
+ -- 需要被查询的关系。没有「哪些环经过这条事实」这种查法
+ path UUID[] NOT NULL DEFAULT '{}',
+ status TEXT NOT NULL DEFAULT 'open'
+ CHECK (status IN ('open', 'resolved')),
+ -- fact_retracted 判数据错,撤了事实
+ -- axiom_relaxed 判定义错,去本体里改了那条公理
+ -- accepted 两边都对,人认可这种并存(下一轮不再报)
+ resolution TEXT CHECK (resolution IN ('fact_retracted', 'axiom_relaxed', 'accepted')),
+ decided_by UUID REFERENCES users(id),
+ decided_at TIMESTAMPTZ,
+ detected_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+
+ -- 同一处矛盾重跑不重复入库。检查是确定性的(环按事实 id 排序去重),
+ -- 所以同一个环每次算出来的首尾都是同一对
+ UNIQUE (kb_id, kind, left_fact, right_fact)
+);
+
+-- Review 页只捞待表态的
+CREATE INDEX axiom_violations_open_idx ON axiom_violations (kb_id, detected_at DESC)
+ WHERE status = 'open';
diff --git a/migrations/0013_reasoning.sql b/migrations/0013_reasoning.sql
new file mode 100644
index 00000000..5eba5169
--- /dev/null
+++ b/migrations/0013_reasoning.sql
@@ -0,0 +1,162 @@
+-- 推理机 R0 补完 + R1 物化推导(见 docs/decisions/0002)。
+
+-- ============ R0 的另一半:本体自己的自洽性 ============
+--
+-- `axiom_violations` 说的是「事实与定义抵触」,这张说的是「定义自己站不住」。
+-- 分开不是分类癖:一个自相矛盾的本体会让事实层的结论**全部可疑**——若某个谓词
+-- 同时声明了 symmetric 与 asymmetric,那么据它报出来的每一条反对称违规都建立在
+-- 一个本来就不成立的前提上。所以界面上这一档排在前面。
+--
+-- 形状也不同:那张表的两列是 `facts` 的外键,而这里指的是类与谓词。
+CREATE TABLE ontology_defects (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ -- symmetric_and_asymmetric 一个谓词同时声明了两者(只对空属性成立)
+ -- transitive_and_functional OWL 2 DL 明文禁止的组合
+ -- subclass_cycle A ⊂ B ⊂ A,建表的 CHECK 只挡得住自环
+ -- disjoint_with_ancestor 类与自己的祖先互斥 → 永远不可能有实例
+ -- inherits_disjoint 两个祖先互斥 → 同上
+ kind TEXT NOT NULL CHECK (kind IN (
+ 'symmetric_and_asymmetric', 'transitive_and_functional',
+ 'subclass_cycle', 'disjoint_with_ancestor', 'inherits_disjoint')),
+ -- **两列都是裸 UUID,没有外键。** 前两类指 relation_types,后三类指
+ -- entity_types——同一列指两张表,外键表达不了。而这是派生状态:本体一改
+ -- 就整批重算,指向已删对象的行在下一轮自然消失,不必靠级联兜底
+ subject UUID NOT NULL,
+ other UUID,
+ -- 环的路径(按类排列)。其余为空
+ path UUID[] NOT NULL DEFAULT '{}',
+ status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'resolved')),
+ -- fixed 去本体里改了(改声明、断开继承、撤掉 disjoint)
+ -- accepted 人看过,认为不必改
+ resolution TEXT CHECK (resolution IN ('fixed', 'accepted')),
+ decided_by UUID REFERENCES users(id),
+ decided_at TIMESTAMPTZ,
+ detected_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (kb_id, kind, subject, other)
+);
+
+CREATE INDEX ontology_defects_open_idx ON ontology_defects (kb_id, detected_at DESC)
+ WHERE status = 'open';
+
+-- ============ R1:规则与派生 ============
+
+-- 规则**只从本体公理编译**,没有用户自定义 DSL——那是另一个产品(0002)。
+--
+-- 为什么要一张表而不是把规则种类塞进派生行:`facts.derived_by_rule` 需要一个
+-- 指得着的东西,而「这条是靠哪条规则来的」在解释(R2)与「撤掉这条公理,
+-- 哪些派生要跟着走」两处都要按规则聚合。
+--
+-- 它是派生状态:每次推导前按本体重编译一遍。所以身份取 `(kb, 谓词, 种类)`
+-- 而不是自增——重编译要能认出「还是那条规则」,否则每跑一次
+-- `derived_facts.rule_id` 就指向一个新 id,历史全断。
+--
+-- **公理撤了的规则不删。** `derived_facts` 上已失效的行仍指着它,解释
+-- 「当时是靠哪条规则推的」需要它还在。规则一个库也就几条,留着不占地方。
+CREATE TABLE rules (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ predicate_id UUID NOT NULL REFERENCES relation_types(id) ON DELETE CASCADE,
+ -- transitive | symmetric。`inverseOf` 与 `subPropertyOf` 投影侧还没落库,
+ -- 所以也就编不出来——少一条规则不是缺陷,是「没声明就不推」的同一条
+ kind TEXT NOT NULL CHECK (kind IN ('transitive', 'symmetric')),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (kb_id, predicate_id, kind)
+);
+
+-- 推出来的事实。**自己一张表,不进 `facts`。**
+--
+-- 试过塞进 `facts` 加一位 `derived_by_rule` 标记,那一版的问题是**失败方向反了**:
+-- 仓库里有四十多处读 `facts` 的查询,其中只有一处认识那个标记,于是新写一条
+-- 查询默认就是把派生当断言看,得记得加过滤。写这个功能的人(我)当场就漏了
+-- 两处——低置信审核队列会把派生事实端给人 Confirm/Reject(确认一条推导没有
+-- 意义,而拒绝它下一轮会原样推回来,因为前提还在),时态对账会拿一条推导去
+-- 闭合一条断言(引擎拿自己的结论改人的数据,0001 判据 2 正好禁止这个)。
+--
+-- 分开之后忘了 UNION 的后果是**看不见**派生,而不是**混进去**。
+--
+-- 另外两条:
+--
+-- 一、**列本来就不一样**。派生没有 `supersedes`(它没有「纠正」语义)、没有
+-- `fact_evidence`(它的证据是前提,在 `fact_derivations` 里)、`confidence`
+-- 的含义也不同(算出来的,不是模型自报的)。塞一张表里这些列对它全是借用的。
+--
+-- 二、**数量级差一档**。0002 在真实语料上量过 185 → 828,派生可能是断言的四倍多。
+-- 让每一条 `facts` 查询都去过滤掉大半行,是白付的代价。
+CREATE TABLE derived_facts (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ subject_id UUID NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
+ -- **非空**,与 `facts.predicate_id` 不同:规则是挂在谓词上的,没有谓词
+ -- 就没有规则,也就推不出这一行
+ predicate_id UUID NOT NULL REFERENCES relation_types(id) ON DELETE CASCADE,
+ -- 同样非空:公理谈的是实体之间的关系,字面值宾语的属性事实不参与推导
+ object_id UUID NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
+ rule_id UUID NOT NULL REFERENCES rules(id),
+ -- 有效期取前提的交集(0002 开放问题里给的语义)。精度与 `facts` 同一套
+ -- 不变量:有日期才有精度
+ valid_from TIMESTAMPTZ,
+ valid_to TIMESTAMPTZ,
+ valid_from_precision TEXT,
+ valid_to_precision TEXT,
+ -- 前提里最小的那个。一条链只和它最弱的一环一样可信
+ confidence REAL NOT NULL DEFAULT 1.0,
+ derived_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ -- 前提没了就置这个,**不删行**:与拒绝一条事实完全同构,记录轴上留下
+ -- 「我们曾据此推出,后来前提没了」,实体历史页面直接就能展示(0002 第 3 节)
+ invalidated_at TIMESTAMPTZ,
+ CONSTRAINT derived_from_precision_matches_date
+ CHECK ((valid_from IS NULL) = (valid_from_precision IS NULL)),
+ CONSTRAINT derived_to_precision_matches_date
+ CHECK ((valid_to IS NULL) = (valid_to_precision IS NULL))
+);
+
+-- 图要按 (主, 宾) 取边;对账要按三元组 + 区间认出「还是那一条」
+CREATE INDEX derived_facts_live_idx
+ ON derived_facts (kb_id, subject_id, object_id) WHERE invalidated_at IS NULL;
+CREATE UNIQUE INDEX derived_facts_identity_idx
+ ON derived_facts (kb_id, subject_id, predicate_id, object_id, valid_from, valid_to)
+ WHERE invalidated_at IS NULL;
+
+-- 证明树的一层:这条派生用了哪几条前提。
+--
+-- **不存整棵树,只存直接前提。** 顺着这张表递归展开就是完整的证明(R2 要的
+-- 东西)。存整棵树是同一份信息记 N 遍,而 N 是路径数。
+--
+-- 前提一律是断言(`facts`):推导的输入里排除了派生,否则同一次调用的输出会
+-- 变成下一次的输入,重跑结果依赖上一轮的残留。
+--
+-- `seq` 保证顺序:`A→B→C→D` 的证明读起来要是这个顺序,人才看得懂链是怎么走的。
+CREATE TABLE fact_derivations (
+ derived_fact_id UUID NOT NULL REFERENCES derived_facts(id) ON DELETE CASCADE,
+ premise_fact_id UUID NOT NULL REFERENCES facts(id) ON DELETE CASCADE,
+ seq INT NOT NULL,
+ PRIMARY KEY (derived_fact_id, seq)
+);
+
+-- 「这条前提被撤了,哪些派生要跟着失效」——反向查,主键覆盖不了
+CREATE INDEX fact_derivations_premise_idx ON fact_derivations (premise_fact_id);
+
+-- 推理开关。**默认关**:R1 会往图里加东西,而 0001 判据 2 说「本体是引导不是
+-- 执法」——声明可能是错的,所以不该在用户没表态时就按它改图。
+--
+-- 放在 KB 上而不是部署上:一个库的本体带公理、另一个库全是自由文本抽出来的,
+-- 该不该推是按库不同的。
+ALTER TABLE knowledge_bases
+ ADD COLUMN materialize_inferences BOOLEAN NOT NULL DEFAULT FALSE;
+
+-- 多久重推一次。**必须定时,不能只靠手点**:事实是持续变的(每篇文档抽取都在
+-- 加边),而派生只在跑的那一刻算。不定时的话,下一篇文档进来之后图上的派生就
+-- 是**缺的**——不是错的(前提还在),是新链没推出来,而这种缺失界面上看不出来。
+--
+-- 跟来源同步同一个形状:一个间隔 + 一个上次时间,调度器每分钟扫一遍到期的。
+-- 60 分钟是拍的:推导是纯计算不花钱,但在增量维护(0002 R3)做出来之前每次都是
+-- 全库重算,所以也不该太密。
+ALTER TABLE knowledge_bases
+ ADD COLUMN inference_interval_minutes INT NOT NULL DEFAULT 60
+ CHECK (inference_interval_minutes BETWEEN 5 AND 10080);
+
+-- 上次推完的时间。**到点对比就是拿这一次的结果跟库里现有的比**——
+-- `materialize` 本来就在做这件事(算出来的对上现有的,多的插、少的作废),
+-- 所以「对比」不是新机制,是把那次对比的结果记下来给人看
+ALTER TABLE knowledge_bases ADD COLUMN last_inference_at TIMESTAMPTZ;
diff --git a/web/src/api.ts b/web/src/api.ts
index eca32ba1..3f18538b 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -85,6 +85,13 @@ export interface Kb {
/** 抽取遇到本体外的说法时,是否允许系统自动补进本体并改写等它的事实。
关掉不影响"留意":未匹配统计照常累积可见,只是变成你点一下的提案 */
auto_extend_ontology: boolean;
+ /** 把推出来的事实写进账本(R1)。**缺省关**——推理往图里加东西,
+ * 而声明可能是错的,不该在用户没表态时就按它改图 */
+ materialize_inferences: boolean;
+ /** 多久重推一次(分钟)。事实持续在变,只靠手点会让派生一直是缺的 */
+ inference_interval_minutes: number;
+ /** 上次推完的时间 */
+ last_inference_at: string | null;
/** 内置本体按哪种语言播种、新描述写哪种语言。**跟语料走,不跟界面走**
(界面语言在客户端,见 docs/decisions/0004) */
ontology_lang: "en" | "zh";
@@ -134,6 +141,8 @@ export interface Doc {
/** 图谱抽取管道的失败原因(与 error 分列:两条管道各存各的) */
graph_error: string | null;
chunk_count: number;
+ /** 文档标签。**今天没有任何界面用它**——故意留着,理由写在
+ * `migrations/0002_ingest.sql` 的 `tags` 列上 */
tags: string[];
missing_since: string | null;
created_at: string;
@@ -270,6 +279,100 @@ export interface ChunkFact {
confidence: number;
}
+/** 一条推出来的事实,连同它的证明(实体面板的「推出来的」那一档)。
+ *
+ * `premises` 是这一档存在的理由:不给出前提的话,一条派生边跟一条普通的边
+ * 在界面上看不出区别,而那正是「推理污染知识」的样子。 */
+export interface DerivedFact {
+ id: string;
+ subject_id: string;
+ subject: string;
+ object_id: string;
+ object: string;
+ predicate: string;
+ /** 靠哪条规则推的 */
+ rule: "transitive" | "symmetric";
+ valid_from: string | null;
+ valid_to: string | null;
+ confidence: number;
+ derived_at: string;
+ /** 直接前提,按推导顺序 */
+ premises: string[];
+}
+
+/** 审核页的分档。**与服务端的 queue 参数是同一组字面量**——拼错会拿到
+ * 一个明确的 unknown_queue 错误,而不是悄悄的空列表。 */
+export type ReviewQueue =
+ | "duplicates"
+ | "conflicts"
+ | "unconfirmed"
+ | "lowconf"
+ | "mappings"
+ | "violations"
+ | "defects"
+ | "merges";
+
+/** 各档的真实条数。左栏的徽标读它,不读列表长度 */
+export interface ReviewCounts {
+ duplicates: number;
+ conflicts: number;
+ unconfirmed: number;
+ lowconf: number;
+ mappings: number;
+ violations: number;
+ defects: number;
+ merges: number;
+}
+
+/** 类型消解的一条建议:一个待精化的实体、送去检索的画像、以及候选类。
+ *
+ * `profile` 回给调用方是有意的——检索找不着的时候,第一个要看的就是
+ * 「我们拿什么去找的」,而不是猜是画像不对还是类的描述不对。 */
+export interface TypeSuggestion {
+ entity_id: string;
+ name: string;
+ /** 现在挂着的类,可能没有(0009) */
+ coarse: string | null;
+ coarse_description: string | null;
+ proposed_type: string | null;
+ specific_type: string | null;
+ fact_count: number;
+ profile: string;
+ candidates: {
+ id: string;
+ key: string;
+ label: string;
+ description: string;
+ distance: number;
+ }[];
+}
+
+/** 跑完一轮的结果。**三档分开报**:自动改了的、留给人的、裁决说「都不是」的。
+ * 最后那一档带着理由——这一步押在「选择都不是是个体面答案」上,
+ * 不记理由,最大的那一档就是不透明的。 */
+export interface ResolutionOutcome {
+ batch: string | null;
+ retyped: number;
+ for_review: {
+ entity_id: string;
+ name: string;
+ coarse: string | null;
+ from_type_id: string | null;
+ to_type_id: string;
+ choice: string;
+ confidence: number;
+ reason: string | null;
+ /** 选中的类不在粗类的子树里——换的是分类轴,不是往下走一格 */
+ crosses_axis: boolean;
+ }[];
+ left_alone: {
+ name: string;
+ coarse: string | null;
+ specific_type: string | null;
+ reason: string | null;
+ top_candidate: string | null;
+ }[];
+}
export interface ReviewSide {
id: string;
name: string;
@@ -311,6 +414,36 @@ export interface ConceptMapping {
derived: boolean;
status: "proposed" | "confirmed" | "rejected";
}
+/** 一处公理违规(0002 R0)。判据来自本体自己声明的公理,没声明就不报 */
+export interface AxiomViolation {
+ id: string;
+ kind: "self_loop" | "asymmetry" | "cycle" | "functional";
+ /** 判据来自哪条关系。判「公理写错了」时从这里进本体去改 */
+ predicate: string | null;
+ left_fact: string;
+ left_text: string;
+ /** 自反那一类与 left 相同——一条事实跟自己矛盾 */
+ right_fact: string;
+ right_text: string;
+ /** 环的长度;其余三类为 0 */
+ path_len: number;
+ detected_at: string;
+}
+/** 本体自己的一处自相矛盾。**与 AxiomViolation 不是一回事**:那个说
+ * 「事实与定义抵触」,这个说「定义自己站不住」,后者更根本 */
+export interface OntologyDefect {
+ id: string;
+ kind:
+ | "symmetric_and_asymmetric"
+ | "transitive_and_functional"
+ | "subclass_cycle"
+ | "disjoint_with_ancestor"
+ | "inherits_disjoint";
+ subject_label: string | null;
+ other_label: string | null;
+ path_labels: string[];
+ detected_at: string;
+}
export interface FactReviewItem {
id: string;
subject_name: string;
@@ -371,6 +504,9 @@ export interface GraphEdge {
label: string | null;
/** true = 这条边的名字来自原文,不是本体认下的关系 */
inferred: boolean;
+ /** true = 这条边是**推出来的**,不是任何人断言的(R1)。
+ * 与 `inferred` 不是一回事:那个说「名字来自原文」,这个说「不是谁说的」 */
+ derived: boolean;
valid_from: string | null;
valid_to: string | null;
confidence: number;
@@ -471,6 +607,8 @@ export interface EntityTypeView {
builtin: boolean;
/** 全部父类(subClassOf 可以有多个) */
parents: string[];
+ /** 与它互斥的类:**声明「不可能同时是」** */
+ disjoint: string[];
/** 左栏画树时挂在哪一支下。不参与语义,只管展示 */
primary_parent: string | null;
description: string;
@@ -484,6 +622,11 @@ export interface RelationTypeView {
temporal: string;
functional: boolean;
inverse_functional: boolean;
+ /** 其余四条 OWL 公理。**推理机的判据全在这里** */
+ is_transitive: boolean;
+ is_symmetric: boolean;
+ is_asymmetric: boolean;
+ is_irreflexive: boolean;
builtin: boolean;
description: string;
/** relation(宾语是实体)| attribute(宾语是字面值) */
@@ -715,8 +858,34 @@ export const api = {
kbs: (workspaceId: string) =>
request<Kb[]>(`/api/v1/workspaces/${workspaceId}/kbs`),
- kbAudit: (kbId: string) =>
- request<{ events: AuditEvent[] }>(`/api/v1/kbs/${kbId}/audit`),
+ /** 审计台账。**分页 + 筛选**——台账是合规材料,只看最近 100 条等于查不了历史。
+ * `action` 是前缀:`entity.` 捞出 entity.retyped / entity.renamed 一族。 */
+ kbAudit: (
+ kbId: string,
+ opts: {
+ action?: string;
+ actor?: string;
+ since?: string;
+ until?: string;
+ limit: number;
+ offset: number;
+ },
+ ) => {
+ const p = new URLSearchParams({
+ limit: String(opts.limit),
+ offset: String(opts.offset),
+ });
+ if (opts.action) p.set("action", opts.action);
+ if (opts.actor) p.set("actor", opts.actor);
+ if (opts.since) p.set("since", opts.since);
+ if (opts.until) p.set("until", opts.until);
+ return request<{
+ events: AuditEvent[];
+ total: number;
+ /** 这个库实际发生过的动作,筛选下拉按它填 */
+ actions: string[];
+ }>(`/api/v1/kbs/${kbId}/audit?${p}`);
+ },
myKbs: (workspaceId: string) =>
request<{ kbs: MyKb[] }>(`/api/v1/workspaces/${workspaceId}/my-kbs`),
createKb: (
@@ -810,6 +979,15 @@ export const api = {
body: JSON.stringify(body),
}),
+ /** 已停用的账号。**没有它恢复就够不着**——那个人从所有列表里消失,
+ * 而恢复接口要的正是他的 id */
+ deactivatedUsers: () =>
+ request<OrgUser[]>("/api/v1/users/deactivated"),
+ /** 恢复一个停用的账号 */
+ adminReactivateUser: (userId: string) =>
+ request<{ ok: boolean }>(`/api/v1/admin/users/${userId}`, {
+ method: "POST",
+ }),
/** 停用一个账号(软删除)。归因照旧查得到——审计、合并日志、改类账本都靠它 */
adminDeactivateUser: (userId: string) =>
request<{ ok: boolean }>(`/api/v1/admin/users/${userId}`, {
@@ -859,7 +1037,41 @@ export const api = {
{ method: "POST" },
),
- documents: (kbId: string) => request<Doc[]>(`/api/v1/kbs/${kbId}/documents`),
+ /** 文库一页。**服务端筛选与分页**——从前一次取回整库、前端切片,
+ * 而客户端筛选只筛得到已经拿下来的那些 */
+ documents: (
+ kbId: string,
+ opts: {
+ source?: string;
+ q?: string;
+ graph?: string;
+ limit: number;
+ offset: number;
+ },
+ ) => {
+ const p = new URLSearchParams({
+ limit: String(opts.limit),
+ offset: String(opts.offset),
+ });
+ if (opts.source) p.set("source", opts.source);
+ if (opts.q) p.set("q", opts.q);
+ if (opts.graph) p.set("graph", opts.graph);
+ return request<{
+ docs: Doc[];
+ total: number;
+ /** 下面三个**只按来源作用域算**,不受名字/状态筛选影响——
+ * 它们是批量按钮的作用范围 */
+ ready: number;
+ extracting: number;
+ failed: number;
+ }>(`/api/v1/kbs/${kbId}/documents?${p}`);
+ },
+ /** 一键重试这个作用域里全部抽取失败的文档 */
+ retryFailedDocs: (kbId: string, source?: string) =>
+ request<{ queued: number; found: number }>(
+ `/api/v1/kbs/${kbId}/documents/retry-failed${source ? `?source=${source}` : ""}`,
+ { method: "POST" },
+ ),
/** 整库一次取回:行数按 (文档 × 原因 × 对象) 聚合后很小,避免逐行发请求 */
extractionDrops: (kbId: string) =>
request<{ drops: ExtractionDrop[] }>(
@@ -891,21 +1103,40 @@ export const api = {
body: JSON.stringify(body),
}),
graphOverview: (kbId: string) =>
- request<{ nodes: GraphNode[]; edges: GraphEdge[] }>(
- `/api/v1/kbs/${kbId}/graph/overview`,
- ),
+ request<{
+ nodes: GraphNode[];
+ edges: GraphEdge[];
+ /** 库里一共有多少。**与 nodes.length 不是一回事**——画布只画度数最高的
+ * 那一批,把上限当成规模显示是这个接口从前最误导人的地方 */
+ total_nodes?: number;
+ total_edges?: number;
+ }>(`/api/v1/kbs/${kbId}/graph/overview`),
+ /** 邻域视图**没有总数**:它本来就只是一小片,说「共 325 个」没有意义。
+ * 两个字段声明成可选,好让调用方与总览共用一个类型 */
graphNeighborhood: (kbId: string, entityId: string) =>
- request<{ nodes: GraphNode[]; edges: GraphEdge[] }>(
- `/api/v1/kbs/${kbId}/graph/neighborhood?entity=${entityId}&hops=2`,
- ),
- searchEntities: (kbId: string, q: string) =>
- request<{ entities: GraphNode[] }>(
- `/api/v1/kbs/${kbId}/entities?q=${encodeURIComponent(q)}`,
+ request<{
+ nodes: GraphNode[];
+ edges: GraphEdge[];
+ total_nodes?: number;
+ total_edges?: number;
+ }>(`/api/v1/kbs/${kbId}/graph/neighborhood?entity=${entityId}&hops=2`),
+ /** 按名字找实体。**一并回总数**——「宁分勿合」会造出一堆同名,
+ * 固定十条时想找的那个可能根本不在这十条里 */
+ searchEntities: (kbId: string, q: string, limit = 10) =>
+ request<{ entities: GraphNode[]; total: number }>(
+ `/api/v1/kbs/${kbId}/entities?q=${encodeURIComponent(q)}&limit=${limit}`,
),
entityDetail: (kbId: string, entityId: string) =>
- request<{ entity: GraphNode; facts: EntityFact[] }>(
- `/api/v1/kbs/${kbId}/entities/${entityId}`,
- ),
+ request<{
+ entity: GraphNode;
+ facts: EntityFact[];
+ /** 推出来的那些**单独一个键**,不掺进 facts:混在同一个列表里,
+ * 用户看不出「文档里写的」和「引擎推的」的区别 */
+ derived: DerivedFact[];
+ /** 同名的其他实体。**打开面板就给**——合并入口要长在能看见同名的地方,
+ * 而不是藏在「改一次名」之后 */
+ same_name: GraphNode[];
+ }>(`/api/v1/kbs/${kbId}/entities/${entityId}`),
/** 认知变更历史(记录时间轴):服务端分页 */
/** 人工修正实体的类型或名字。同名不拦——返回的 same_name 供界面提示是否合并。 */
updateEntity: (
@@ -1169,15 +1400,22 @@ export const api = {
documentExtractions: (docId: string) =>
request<{ facts: ChunkFact[] }>(`/api/v1/documents/${docId}/extractions`),
- review: (kbId: string) =>
+ /** 审核队列的各档**真实条数**。与列表分开取——列表有一页的上限,数数没有。
+ * 从前徽标读的是数组长度,而接口固定只回 100 条,于是 164 条写成 100。 */
+ review: (
+ kbId: string,
+ queue: ReviewQueue,
+ limit: number,
+ offset: number,
+ ) =>
request<{
- reviews: ReviewItem[];
- facts: FactReviewItem[];
- merges: MergeLog[];
- conflicts: ConflictItem[];
- unconfirmed: FactReviewItem[];
- mappings: ConceptMapping[];
- }>(`/api/v1/kbs/${kbId}/review`),
+ counts: ReviewCounts;
+ queue: ReviewQueue;
+ /** 只有当前这一档的一页。类型按档不同,调用处按 queue 收窄 */
+ items: unknown[];
+ }>(
+ `/api/v1/kbs/${kbId}/review?queue=${queue}&limit=${limit}&offset=${offset}`,
+ ),
closeFact: (kbId: string, factId: string, validTo: string) =>
request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/close`, {
method: "POST",
@@ -1203,6 +1441,88 @@ export const api = {
method: "POST",
body: JSON.stringify({ status }),
}),
+ /** 跑一遍一致性检查。同步返回——纯计算,没有模型调用也没有网络 */
+ runConsistencyCheck: (kbId: string) =>
+ request<{
+ edges: number;
+ /** **零和零不一样**:没有公理时结论是「没有判据」,不是「未发现矛盾」 */
+ predicates_with_axioms: number;
+ found: number;
+ inserted: number;
+ cleared: number;
+ classes: number;
+ /** 本体自己的矛盾**单独回**,不加进 found:两个数不是一类东西 */
+ defects_found: number;
+ defects_new: number;
+ }>(`/api/v1/kbs/${kbId}/consistency/check`, { method: "POST" }),
+ /** 对一处本体缺陷表态。**两个出路**——它压根没看数据,没有「数据错了」这条 */
+ decideDefect: (
+ kbId: string,
+ defectId: string,
+ resolution: "fixed" | "accepted",
+ ) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/defects/${defectId}`, {
+ method: "POST",
+ body: JSON.stringify({ resolution }),
+ }),
+ /** 跑一遍推理(R1)。开关关着时后端回 inference_off */
+ /** 类型消解:**只算不写**。回执里带着送去检索的画像——检索找不着时,
+ * 第一个要看的就是「我们拿什么去找的」 */
+ /** 手动合并:把 source 并进 target。**方向要紧**——source 消失,
+ * 它的事实搬到 target 上;合并可整体回滚(entity_merges 记着快照) */
+ mergeEntities: (kbId: string, source: string, target: string) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/entities/merge`, {
+ method: "POST",
+ body: JSON.stringify({ source, target }),
+ }),
+ typeResolutionPreview: (kbId: string) =>
+ request<{ items: TypeSuggestion[] }>(
+ `/api/v1/kbs/${kbId}/ontology/type-resolution/preview`,
+ { method: "POST" },
+ ),
+ /** 跑一遍并落库。三档分开回:自动改的、留给人的、说「都不是」的 */
+ typeResolutionApply: (kbId: string) =>
+ request<ResolutionOutcome>(`/api/v1/kbs/${kbId}/ontology/type-resolution`, {
+ method: "POST",
+ }),
+ /** 认可一个「粗类 → 细类」的配对,并把带上的实体改过去。
+ * **认可的是类对,改的是实体**——认可一次,之后同一对不再进人工 */
+ approveRefinement: (
+ kbId: string,
+ body: { from_type_id: string; to_type_id: string; entity_ids: string[] },
+ ) =>
+ request<{ retyped: number }>(
+ `/api/v1/kbs/${kbId}/ontology/type-resolution/approve`,
+ { method: "POST", body: JSON.stringify(body) },
+ ),
+ /** 撤销一整批:把那批实体放回原来的类 */
+ typeResolutionUndo: (kbId: string, batchId: string) =>
+ request<{ reverted: number }>(
+ `/api/v1/kbs/${kbId}/ontology/type-resolution/${batchId}`,
+ { method: "DELETE" },
+ ),
+ runInference: (kbId: string) =>
+ request<{
+ /** 编译出来的规则条数。为零时是「没有规则」而不是「推不出东西」 */
+ rules: number;
+ edges: number;
+ derived: number;
+ inserted: number;
+ /** 前提没了、跟着作废的 */
+ invalidated: number;
+ /** 撞上单谓词上限、没推完的谓词个数 */
+ capped: number;
+ }>(`/api/v1/kbs/${kbId}/inference/run`, { method: "POST" }),
+ /** 对一处公理违规表态。三个出路——第三个是这一档独有的:可能是定义错了 */
+ decideViolation: (
+ kbId: string,
+ violationId: string,
+ resolution: "fact_retracted" | "axiom_relaxed" | "accepted",
+ ) =>
+ request<{ ok: boolean }>(
+ `/api/v1/kbs/${kbId}/review/violations/${violationId}`,
+ { method: "POST", body: JSON.stringify({ resolution }) },
+ ),
confirmFact: (kbId: string, factId: string) =>
request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/confirm`, {
method: "POST",
@@ -1248,10 +1568,25 @@ export const api = {
/** RAG 对话:SSE 流式。返回中止函数。 */
export const conversationsApi = {
- list: (kbId: string) =>
- request<{ conversations: ConversationRow[] }>(
- `/api/v1/kbs/${kbId}/conversations`,
- ),
+ /** **可搜可翻页**:标题会重(同一个问题问两次就重了),而固定一百条之后的
+ * 会话界面上根本不存在。搜的是标题与消息正文两处——人记得住的往往是
+ * 问过的那句话,不是标题 */
+ list: (kbId: string, q = "", limit = 30, offset = 0) => {
+ const p = new URLSearchParams({
+ limit: String(limit),
+ offset: String(offset),
+ });
+ if (q.trim()) p.set("q", q.trim());
+ return request<{ conversations: ConversationRow[]; total: number }>(
+ `/api/v1/kbs/${kbId}/conversations?${p}`,
+ );
+ },
+ /** 改标题。标题本来是从第一句话自动取的,而一段对话跑偏是常态 */
+ rename: (kbId: string, id: string, title: string) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conversations/${id}`, {
+ method: "PATCH",
+ body: JSON.stringify({ title }),
+ }),
detail: (kbId: string, id: string) =>
request<{ messages: ConversationMessage[] }>(
`/api/v1/kbs/${kbId}/conversations/${id}`,
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index a549d039..436a5c2a 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -66,6 +66,9 @@ export const en = {
only_postgres: "Only PostgreSQL is supported for now.",
bad_conn_string: "A connection string starts with postgres://",
concurrency_range: "Pick a number between 1 and 256.",
+ inference_off:
+ "Materialized inference is off for this knowledge base. Turn it on in Settings.",
+ bad_resolution: "That is not a valid decision.",
},
/** 机器给的补充(cron 解析器的原话之类)缀在措辞后面 */
errDetail: (msg: string, detail: string) => `${msg} (${detail})`,
@@ -291,6 +294,14 @@ export const en = {
emptyPull: "No documents yet — they arrive when this source syncs.",
filterPlaceholder: "Filter by name",
filterNoMatch: "No documents match your filter.",
+ anyStatus: "Any extraction state",
+ statusFailed: "Failed",
+ statusDone: "Extracted",
+ statusQueued: "Queued",
+ statusExtracting: "Extracting",
+ statusNone: "Not extracted",
+ retryFailed: (n: number) => `Retry ${n} failed`,
+ retryQueued: (n: number) => `${n} queued for extraction`,
colFile: "File",
colStatus: "Status",
colGraph: "Graph",
@@ -513,6 +524,10 @@ export const en = {
untitled: "Untitled",
noConversations: "No conversations yet.",
deleteConversation: "Delete conversation",
+ searchConversations: "Search chats",
+ moreActions: "More",
+ rename: "Rename",
+ copyTitle: "Copy title",
deleteTitle: "Delete conversation?",
deleteHint: (name: string) =>
`“${name}” and its messages will be permanently removed.`,
@@ -522,6 +537,7 @@ export const en = {
graph: {
// 还没判出类型的实体(0009)。不是一个类,是"这一格还空着"
untyped: "Untyped",
+ searchMore: (n: number) => `${n} more — load 20`,
zoomIn: "Zoom in",
zoomOut: "Zoom out",
fitView: "Fit view",
@@ -573,10 +589,38 @@ export const en = {
? "One other entity shares this name."
: `${n} other entities share this name.`,
sameNameHint: "If they are the same thing, merge them under Review.",
+ mergeInto: "Merge in",
+ mergeIntoHint:
+ "Fold that entity into this one. Its facts move here; merges can be reverted.",
+ mergeConfirm: (from: string, into: string) =>
+ `Merge “${from}” into “${into}”? Its facts move here. You can revert this from Review.`,
viewRelations: "Relations",
viewTimeline: "Timeline",
/* 第三视图:记录时间轴——不是"事情何时发生",而是"我们何时这么认为" */
viewHistory: "History",
+ viewDerived: "Derived",
+ derivedEdges: (n: number) => `${n} derived`,
+ derivedHint:
+ "Edges no one asserted — the engine worked them out from axioms your ontology declares. Each one shows the premises it came from.",
+ derivedNoProof: "The premises are gone.",
+ derivedPanel: "Inference",
+ derivedCountLabel: "Edges derived",
+ derivedStateLabel: "Schedule",
+ derivedLastLabel: "Last run",
+ derivedOn: (mins: number) => `every ${mins} min`,
+ derivedOff: "off",
+ derivedNever: "never",
+ derivedAgo: (mins: number) =>
+ mins < 1 ? "just now" : mins < 60 ? `${mins} min ago` : `${Math.round(mins / 60)} h ago`,
+ derivedRun: "Run now",
+ derivedRunning: "Running…",
+ derivedNoChange: "Nothing changed.",
+ derivedChanged: (added: number, gone: number) =>
+ `${added} added · ${gone} retracted`,
+ derivedCapped: (n: number) => `${n} predicate(s) not closed fully`,
+ close: "Close",
+ ruleTransitive: "transitive",
+ ruleSymmetric: "symmetric",
historyHint: "How this entity's record changed — and who changed it.",
historyEmpty: "Nothing recorded for this entity yet.",
historyKind: {
@@ -608,6 +652,12 @@ export const en = {
endedUnknown: "ended, date unknown",
stats: (n: number, e: number, active: number) =>
`${n} entities · ${e} facts · ${active} active`,
+ /** 画布只画度数最高的一批。**说清楚画了多少、共多少**——从前这里写的是
+ * 上限,一个上万实体的库右上角永远是 150 */
+ statsCapped: (shown: number, total: number, e: number, active: number) =>
+ `showing ${shown} of ${total} entities · ${e} facts · ${active} active`,
+ cappedHint: (shown: number, total: number) =>
+ `The canvas draws the ${shown} best-connected entities of ${total}. Search to reach the rest.`,
stabilizing: "Stabilizing layout",
allTime: "All time",
nowBtn: "Now",
@@ -725,6 +775,26 @@ export const en = {
newProperty: "New property",
filter: "Filter…",
missesShort: "Unmatched",
+ refineShort: "Refine types",
+ refineTitle: "Refine types",
+ refineHint:
+ "Entities whose class is roughly right but not the most specific one available. Look first, then apply — retyping does not appear on any timeline, so this is the only place you get to see it before it happens.",
+ refinePreview: "Look first",
+ refineLooking: "Looking…",
+ refineRun: "Run and apply",
+ refineRunning: "Running…",
+ refineNothing: "Nothing to refine.",
+ refineCandidates: (n: number) => `${n} entities would be considered`,
+ refineNoCandidates: "Retrieval found no class for this one.",
+ refineModelSays: (t: string) => `the model called it “${t}”`,
+ refineRetyped: (n: number) => `${n} retyped automatically`,
+ refineUndo: "Undo this batch",
+ refineUndone: (n: number) => `${n} put back`,
+ refineForReview: (n: number) => `${n} need your call`,
+ refineCrossesAxis: "different axis",
+ refineApprovePair: "Approve this class pair",
+ refineLeftAlone: (n: number) => `${n} left alone`,
+ refineTopCandidate: (c: string) => `closest class was ${c}`,
instances: "Instances",
instanceFacts: (n: number) => `${n} facts`,
description: "Description",
@@ -754,6 +824,12 @@ export const en = {
shapeColor: "Shape & color",
parent: "Parent class",
noParent: "(top level)",
+ disjoint: "Cannot also be",
+ disjointHint:
+ "Classes nothing can belong to at the same time. A Person is not an Organisation. The consistency check uses this to find classes that can never have an instance.",
+ noDisjoint: "No class excluded",
+ disjointWithParent:
+ "This class inherits from a class it says it cannot be — nothing could ever satisfy it.",
/* 多父时左栏只能画一处,说明画在哪一支下 */
primaryParentHint: "Shown in the tree under the first one.",
/* 类型签名。措辞要说清它是引导不是闸门——本体写错时模型仍可覆盖 */
@@ -772,6 +848,21 @@ export const en = {
temporalEternal: "Eternal (timeless)",
functional: "Functional (single value at a time)",
inverseFunctional: "Inverse functional (one subject per object at a time)",
+ axioms: "Axioms",
+ axiomsHint:
+ "What this relation guarantees. These are not descriptions — they change what the system does: the temporal engine closes old values, and the reasoning engine adds edges to the graph.",
+ functionalHint: "One subject, one value at a time. A new value closes the old one.",
+ inverseFunctionalHint: "One object, one subject. A project has one lead.",
+ transitive: "Transitive",
+ transitiveHint: "A→B and B→C means A→C. The engine will add those edges.",
+ symmetric: "Symmetric",
+ symmetricHint: "A→B means B→A. The engine will add the other direction.",
+ asymmetric: "Asymmetric",
+ asymmetricHint: "A→B rules out B→A. Both directions get reported as a contradiction.",
+ irreflexive: "Irreflexive",
+ irreflexiveHint: "Nothing can point at itself through this relation.",
+ axiomConflict:
+ "Symmetric and asymmetric together hold only for a relation with no facts at all — one of the two is wrong.",
usage: (n: number) => `${n} in use`,
builtin: "built-in",
save: "Save",
@@ -904,6 +995,8 @@ export const en = {
railUnconfirmed: "Unconfirmed",
railLowConfidence: "Low confidence",
railMappings: "Semantic layer",
+ railViolations: "Axioms",
+ railDefects: "Ontology",
railDecisions: "Decisions",
railMerges: "Merges",
categoryEmpty: "This queue is clear.",
@@ -949,6 +1042,49 @@ export const en = {
merge: "Merge",
keep: "Keep separate",
lowConfidence: "Low-confidence facts",
+ defects: "Ontology contradicts itself",
+ defectsHint:
+ "Problems in the definitions themselves — no facts involved. These come first: while a definition contradicts itself, every fact-level finding that rests on it is suspect.",
+ defectSymAsym: "Declared both symmetric and asymmetric",
+ defectTransFunc: "Transitive and functional at once",
+ defectCycle: "subClassOf runs in a circle",
+ defectDisjointAncestor: "Disjoint with its own ancestor",
+ defectInheritsDisjoint: "Inherits from two disjoint classes",
+ defectNeverInstantiable: "no instance can ever satisfy it",
+ defectFixed: "I fixed the ontology",
+ defectAccepted: "Leave it",
+ runInference: "Run inference",
+ inferring: "Inferring…",
+ inferenceNoRules:
+ "No transitive or symmetric property is declared, so there is no rule to run.",
+ inferenceAdded: (n: number) => `${n} facts derived`,
+ inferenceRetracted: (n: number) => `${n} retracted`,
+ inferenceNothing: "Nothing new to derive",
+ inferenceCapped: (n: number) =>
+ `${n} predicate(s) hit the per-predicate limit and were not closed fully`,
+ violations: "Axiom violations",
+ violationsHint:
+ "Facts that contradict axioms your ontology declares. Nothing here is a guess — a predicate that declares no axioms is never checked.",
+ violationSelfLoop: "Points at itself",
+ violationAsymmetry: "Both directions asserted",
+ violationCycle: "Cycle through the transitive chain",
+ violationFunctional: "Should hold one value, holds two",
+ violationVia: (p: string) => `via ${p}`,
+ violationPath: (n: number) => `${n} facts in the cycle`,
+ retractFact: "Data is wrong",
+ relaxAxiom: "Axiom is wrong",
+ acceptBoth: "Both are right",
+ runCheck: "Run check",
+ checkNeverRun:
+ "Not checked yet. Contradictions are found by asking your ontology, so a run here only reports what its axioms actually say.",
+ checking: "Checking…",
+ checkNoAxioms:
+ "No axioms declared, so nothing could be checked. Import an ontology that declares them.",
+ checkFound: (n: number) => `${n} new`,
+ /** 算出来了,但都是已经在队列里或已被裁决过的——说「3 处矛盾」而列表只有
+ * 一条会让人以为界面漏了东西 */
+ checkNothingNew: "Nothing new",
+ checkClean: (n: number) => `${n} facts checked, no contradictions`,
mappings: "Semantic layer",
mappingsHint:
"Proposed mappings from a business concept to how it is computed. Confirm one and Ask uses it instead of guessing from the schema.",
@@ -1005,6 +1141,12 @@ export const en = {
"facts that were waiting for it. Every change is listed and can be undone. Turning this " +
"off does not stop Utopia from noticing — the phrases still collect under Unmatched, they " +
"just wait for you to approve them.",
+ materialize: "Materialize inferences",
+ materializeNote:
+ "Write facts the ontology entails into the ledger — transitive chains and symmetric pairs. Off by default: a declaration can be wrong, and this one changes the graph. Derived facts are marked and can be taken back.",
+ inferEvery: "Re-derive every",
+ minutes: "minutes",
+ lastInference: (when: string) => `last run ${when}`,
/* 语料语言。措辞要把"这不是界面语言"讲清楚,否则一定有人当成界面开关 */
ontologyLang: "Language of this ontology",
ontologyLangNote:
@@ -1039,6 +1181,11 @@ export const en = {
activity: "Activity",
activityHint:
"Who changed what in this knowledge base. Pure audit — records are append-only.",
+ auditAllActions: "All actions",
+ auditSince: "From this date",
+ auditUntil: "Up to this date",
+ auditClear: "Clear filters",
+ auditTotal: (n: number) => `${n} events`,
activityEmpty: "Nothing recorded yet.",
deletedUser: "a removed user",
auditActions: {
@@ -1087,6 +1234,10 @@ export const en = {
deactivate: "Deactivate",
deactivateHint:
"Cuts off access everywhere — sign-in and any token already issued. What they did stays attributed to them.",
+ deactivatedTitle: "Deactivated accounts",
+ deactivatedHint:
+ "They cannot sign in and do not appear in any member list. What they did is still attributed to them — that is why the account is kept rather than deleted.",
+ reactivate: "Restore",
deactivateConfirm: (name: string) =>
`Deactivate ${name}? They lose access everywhere. Their past decisions stay on record.`,
pickUser: "Select a user to add…",
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 74b0c672..d66f9cb4 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -60,6 +60,8 @@ export const zh: Strings = {
only_postgres: "目前只支持 PostgreSQL。",
bad_conn_string: "连接串要以 postgres:// 开头",
concurrency_range: "填一个 1 到 256 之间的数。",
+ inference_off: "这个库没有打开物化推理。到设置里开。",
+ bad_resolution: "这不是一个有效的裁决。",
},
errDetail: (msg: string, detail: string) => `${msg}(${detail})`,
toast: {
@@ -270,6 +272,14 @@ export const zh: Strings = {
emptyPull: "还没有文档——这个来源同步时它们会出现。",
filterPlaceholder: "按名称筛选",
filterNoMatch: "没有文档匹配当前筛选。",
+ anyStatus: "全部抽取状态",
+ statusFailed: "失败",
+ statusDone: "已抽取",
+ statusQueued: "排队中",
+ statusExtracting: "抽取中",
+ statusNone: "未抽取",
+ retryFailed: (n: number) => `重试 ${n} 篇失败`,
+ retryQueued: (n: number) => `${n} 篇已排队`,
colFile: "文件",
colStatus: "状态",
colGraph: "图谱",
@@ -481,6 +491,10 @@ export const zh: Strings = {
untitled: "未命名",
noConversations: "还没有对话。",
deleteConversation: "删除对话",
+ searchConversations: "搜索会话",
+ moreActions: "更多",
+ rename: "重命名",
+ copyTitle: "复制标题",
deleteTitle: "删除这个对话?",
deleteHint: (name: string) => `「${name}」及其消息将被永久移除。`,
deleteBtn: "删除",
@@ -488,6 +502,7 @@ export const zh: Strings = {
},
graph: {
untyped: "未分类",
+ searchMore: (n: number) => `还有 ${n} 个——再加载 20`,
zoomIn: "放大",
zoomOut: "缩小",
fitView: "适应视图",
@@ -528,9 +543,36 @@ export const zh: Strings = {
editEmptyName: "名称不能为空",
sameNameNote: (n: number) => `另有 ${n} 个实体同名。`,
sameNameHint: "如果它们是同一个东西,去「审阅」里合并。",
+ mergeInto: "并入",
+ mergeIntoHint: "把那个实体并进这一个。它的事实搬过来;合并可以撤销。",
+ mergeConfirm: (from: string, into: string) =>
+ `把「${from}」并进「${into}」?它的事实会搬过来。可以在审阅页撤销。`,
viewRelations: "关系",
viewTimeline: "时间线",
viewHistory: "记录历史",
+ viewDerived: "推出来的",
+ derivedEdges: (n: number) => `推出来的 ${n}`,
+ derivedHint:
+ "没有人断言过的边——引擎按本体声明的公理推出来的。每一条都附着它用到的前提。",
+ derivedNoProof: "前提已经不在了。",
+ derivedPanel: "推理",
+ derivedCountLabel: "推出来的边",
+ derivedStateLabel: "定时",
+ derivedLastLabel: "上次推理",
+ derivedOn: (mins: number) => `每 ${mins} 分钟`,
+ derivedOff: "已关闭",
+ derivedNever: "从未",
+ derivedAgo: (mins: number) =>
+ mins < 1 ? "刚刚" : mins < 60 ? `${mins} 分钟前` : `${Math.round(mins / 60)} 小时前`,
+ derivedRun: "现在跑一遍",
+ derivedRunning: "推理中…",
+ derivedNoChange: "没有变化。",
+ derivedChanged: (added: number, gone: number) =>
+ `新增 ${added} · 作废 ${gone}`,
+ derivedCapped: (n: number) => `${n} 个谓词没推完`,
+ close: "关闭",
+ ruleTransitive: "传递",
+ ruleSymmetric: "对称",
historyHint: "这个实体的记录如何变化——以及是谁改的。",
historyEmpty: "这个实体还没有记录。",
historyKind: {
@@ -556,6 +598,10 @@ export const zh: Strings = {
endedUnknown: "已结束(时间不详)",
stats: (n: number, e: number, active: number) =>
`${n} 个实体 · ${e} 条事实 · ${active} 条现行`,
+ statsCapped: (shown: number, total: number, e: number, active: number) =>
+ `已画 ${shown} / 共 ${total} 个实体 · ${e} 条事实 · ${active} 条现行`,
+ cappedHint: (shown: number, total: number) =>
+ `画布只画连接最密的 ${shown} 个,库里共 ${total} 个。其余的用搜索找。`,
stabilizing: "布局收敛中",
allTime: "全部时间",
nowBtn: "现在",
@@ -665,6 +711,26 @@ export const zh: Strings = {
newProperty: "新建属性",
filter: "筛选…",
missesShort: "未匹配",
+ refineShort: "类型消解",
+ refineTitle: "类型消解",
+ refineHint:
+ "类挂得大致对、但本体里有更具体的那一个。先看一遍再落库——改类不进任何时间轴,这是唯一能在它发生之前看见它的地方。",
+ refinePreview: "先看一遍",
+ refineLooking: "计算中…",
+ refineRun: "跑一遍并落库",
+ refineRunning: "运行中…",
+ refineNothing: "没有可精化的。",
+ refineCandidates: (n: number) => `会考虑 ${n} 个实体`,
+ refineNoCandidates: "检索没给它找到任何类。",
+ refineModelSays: (t: string) => `模型说它是「${t}」`,
+ refineRetyped: (n: number) => `自动改了 ${n} 个`,
+ refineUndo: "撤销这一批",
+ refineUndone: (n: number) => `已放回 ${n} 个`,
+ refineForReview: (n: number) => `${n} 个要你拍板`,
+ refineCrossesAxis: "换了分类轴",
+ refineApprovePair: "认可这一对类",
+ refineLeftAlone: (n: number) => `${n} 个原样不动`,
+ refineTopCandidate: (c: string) => `最近的候选是 ${c}`,
instances: "实例",
instanceFacts: (n: number) => `${n} 条事实`,
description: "描述",
@@ -693,6 +759,12 @@ export const zh: Strings = {
shapeColor: "形状与颜色",
parent: "父类",
noParent: "(顶层)",
+ disjoint: "不可能同时是",
+ disjointHint:
+ "任何东西不可能同时属于的类。人不是组织。一致性检查据此找出永远不可能有实例的类。",
+ noDisjoint: "没有排除任何类",
+ disjointWithParent:
+ "这个类继承自一个它声明不可能是的类——没有任何东西能满足它。",
primaryParentHint: "左栏的树里挂在第一个下面。",
signature: "类型签名",
signatureHint:
@@ -708,6 +780,21 @@ export const zh: Strings = {
temporalEternal: "恒常(无时间)",
functional: "函数性(同一时刻只有一个值)",
inverseFunctional: "反函数性(同一时刻一个宾语只对一个主语)",
+ axioms: "公理",
+ axiomsHint:
+ "这条关系保证什么。**它们不是描述,是会改变系统行为的声明**:时态引擎据此闭合旧值,推理机据此往图里加边。",
+ functionalHint: "同一主语同一时刻只有一个值。新值会闭合旧值。",
+ inverseFunctionalHint: "同一宾语只有一个主语。一个项目一个负责人。",
+ transitive: "传递",
+ transitiveHint: "A→B 且 B→C 就有 A→C。引擎会把那些边推出来。",
+ symmetric: "对称",
+ symmetricHint: "A→B 就有 B→A。引擎会把反方向补上。",
+ asymmetric: "反对称",
+ asymmetricHint: "有 A→B 就不该有 B→A。两个方向并存会被报成矛盾。",
+ irreflexive: "自反禁止",
+ irreflexiveHint: "任何东西不能通过这条关系指向自己。",
+ axiomConflict:
+ "对称与反对称同时成立,只对一条事实都没有的关系为真——两者必有一个写错了。",
usage: (n: number) => `${n} 处在用`,
builtin: "内置",
save: "保存",
@@ -806,6 +893,8 @@ export const zh: Strings = {
railUnconfirmed: "未确认",
railLowConfidence: "低置信度",
railMappings: "语义层",
+ railViolations: "公理",
+ railDefects: "本体",
railDecisions: "决定",
railMerges: "合并",
categoryEmpty: "这个队列是空的。",
@@ -848,6 +937,46 @@ export const zh: Strings = {
merge: "合并",
keep: "保持分开",
lowConfidence: "低置信度事实",
+ defects: "本体自相矛盾",
+ defectsHint:
+ "定义本身的问题,没有牵涉任何事实。这一档排在前面:定义站不住的时候,据它报出来的每一条事实级结论都可疑。",
+ defectSymAsym: "同时声明了对称与反对称",
+ defectTransFunc: "传递与函数性并存",
+ defectCycle: "subClassOf 绕成了环",
+ defectDisjointAncestor: "与自己的祖先互斥",
+ defectInheritsDisjoint: "继承了两个互斥的类",
+ defectNeverInstantiable: "这个类永远不可能有实例",
+ defectFixed: "已去本体里改了",
+ defectAccepted: "先放着",
+ runInference: "跑一遍推理",
+ inferring: "推理中…",
+ inferenceNoRules: "本体没有声明传递或对称属性,编不出规则。",
+ inferenceAdded: (n: number) => `推出 ${n} 条`,
+ inferenceRetracted: (n: number) => `作废 ${n} 条`,
+ inferenceNothing: "没有新的可推",
+ inferenceCapped: (n: number) => `${n} 个谓词撞上单谓词上限,没有推完`,
+ violations: "公理违规",
+ violationsHint:
+ "与本体自己声明的公理相抵触的事实。这里没有猜测——谓词没声明公理就不查。",
+ violationSelfLoop: "指向了自己",
+ violationAsymmetry: "两个方向都断言了",
+ violationCycle: "传递链绕成了环",
+ violationFunctional: "该只有一个值,却有两个",
+ violationVia: (p: string) => `依据 ${p}`,
+ violationPath: (n: number) => `环上 ${n} 条事实`,
+ retractFact: "数据错了",
+ relaxAxiom: "公理错了",
+ acceptBoth: "两边都对",
+ runCheck: "跑一遍检查",
+ checkNeverRun:
+ "还没查过。矛盾是拿本体自己声明的公理量出来的——跑一遍只会报公理确实说了的那些。",
+ checking: "检查中…",
+ checkNoAxioms: "本体没有声明任何公理,无从判起。先导一份带公理的本体。",
+ checkFound: (n: number) => `新增 ${n} 处`,
+ /** 算出来了,但都是已经在队列里或已被裁决过的——说「3 处矛盾」而列表只有
+ * 一条会让人以为界面漏了东西 */
+ checkNothingNew: "没有新的",
+ checkClean: (n: number) => `查了 ${n} 条事实,没有矛盾`,
mappings: "语义层",
mappingsHint:
"从业务概念到「这个数怎么算」的提议。确认之后问数直接用这个口径,而不是每次从 schema 猜。",
@@ -900,6 +1029,12 @@ export const zh: Strings = {
"当抽取遇到这个本体里没有的关系时,把它加进来,并把一直等着它的那些事实重新归类。" +
"每一次变更都会列出,并且可以撤销。关掉它并不会让 Utopia 不再留意——" +
"那些说法仍然会汇集到「未匹配」下,只是要等你点头。",
+ materialize: "物化推理",
+ materializeNote:
+ "把本体蕴含的事实写进账本——传递链与对称对。默认关:声明可能是错的,而这一步会改图。派生事实带标记,也随时可以撤回。",
+ inferEvery: "每隔",
+ minutes: "分钟重推",
+ lastInference: (when: string) => `上次 ${when}`,
ontologyLang: "本体的语言",
ontologyLangNote:
"类与关系的描述用哪种语言写。它们会被原样送进抽取提示词," +
@@ -928,6 +1063,11 @@ export const zh: Strings = {
dataNewConn: "登记新连接",
activity: "活动",
activityHint: "谁在这个知识库里改了什么。纯审计——记录只追加。",
+ auditAllActions: "全部动作",
+ auditSince: "起始日期",
+ auditUntil: "截止日期",
+ auditClear: "清除筛选",
+ auditTotal: (n: number) => `共 ${n} 条`,
activityEmpty: "还没有记录。",
deletedUser: "一位已移除的用户",
auditActions: {
@@ -975,6 +1115,10 @@ export const zh: Strings = {
deactivate: "停用账号",
deactivateHint:
"断掉整个系统的访问——登录与已签发的 token 都失效。他做过的事仍然记在他名下。",
+ deactivatedTitle: "已停用的账号",
+ deactivatedHint:
+ "他们登不进来,也不出现在任何成员列表里。做过的事仍然算在他们名下——账号被保留而不是删除,正是为了这个。",
+ reactivate: "恢复",
deactivateConfirm: (name: string) =>
`停用 ${name}?他将无法再登录任何地方,但过往的决定仍然留痕。`,
pickUser: "选择要添加的用户…",
diff --git a/web/src/pages/Chat.tsx b/web/src/pages/Chat.tsx
index ef02c54c..27c15749 100644
--- a/web/src/pages/Chat.tsx
+++ b/web/src/pages/Chat.tsx
@@ -2,7 +2,7 @@
会话持久化:左栏会话列表;上下文由服务端拼,前端只发 conversation_id + 新消息;
行动轨迹(steps)与引用(sources)随消息落库,历史回放与实时流共用渲染。 */
import { useEffect, useRef, useState } from "react";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Link, useNavigate, useParams } from "@tanstack/react-router";
import Markdown from "react-markdown";
import remarkGfm from "remark-gfm";
@@ -19,7 +19,7 @@ import {
Search as SearchIcon,
Square,
SquarePen,
- Trash2,
+ MoreHorizontal,
Waypoints,
Wrench,
} from "lucide-react";
@@ -32,6 +32,7 @@ import {
type Source,
} from "../api";
import { S } from "../i18n";
+import { toast } from "../toast";
import { useKb } from "../kb";
import { DangerConfirm, RAIL_CLS } from "../ui";
@@ -64,6 +65,10 @@ export function Chat() {
const [streaming, setStreaming] = useState(false);
const [scopeOpen, setScopeOpen] = useState(false);
const [pendingDelete, setPendingDelete] = useState<ConversationRow | null>(null);
+ // 会话搜索。**搜标题也搜正文**——人记得住的往往是问过的那句话
+ const [convSearch, setConvSearch] = useState("");
+ // 三点菜单展开的是哪一条。同时只开一个
+ const [menuFor, setMenuFor] = useState<string | null>(null);
const abortRef = useRef<(() => void) | null>(null);
const scopeRef = useRef<HTMLDivElement>(null);
const bottomRef = useRef<HTMLDivElement>(null);
@@ -87,9 +92,22 @@ export function Chat() {
}, [scopeOpen]);
const convs = useQuery({
- queryKey: ["conversations", kb?.id],
- queryFn: () => conversationsApi.list(kb!.id),
+ queryKey: ["conversations", kb?.id, convSearch],
+ queryFn: () => conversationsApi.list(kb!.id, convSearch),
enabled: !!kb,
+ placeholderData: (prev) => prev,
+ });
+ // 改标题:**就地编辑**,不弹对话框——改一个名字不值得打断整页
+ const [renamingId, setRenamingId] = useState<string | null>(null);
+ const [renameDraft, setRenameDraft] = useState("");
+ const rename = useMutation({
+ mutationFn: (v: { id: string; title: string }) =>
+ conversationsApi.rename(kb!.id, v.id, v.title),
+ onSuccess: () => {
+ setRenamingId(null);
+ queryClient.invalidateQueries({ queryKey: ["conversations", kb?.id] });
+ },
+ onError: (e: Error) => toast.error(e.message),
});
// 直落底部(instant):平滑滚动在流式追加下会一路慢爬
@@ -368,6 +386,17 @@ export function Chat() {
{S.ask.newChat}
</button>
</div>
+ {/* 搜索。**标题重是常态**(同一个问题问两次就重了),而正文里那句话
+ 才是人记得住的——所以服务端两处都搜 */}
+ <div className="px-2 pb-2">
+ <input
+ className="input-dark w-full px-2.5 py-1.5 text-[12.5px]"
+ placeholder={S.ask.searchConversations}
+ value={convSearch}
+ onChange={(e) => setConvSearch(e.target.value)}
+ onKeyDown={(e) => e.key === "Escape" && setConvSearch("")}
+ />
+ </div>
<div className="u-scroll flex-1 overflow-y-auto px-2 pb-3 space-y-0.5">
{(convs.data?.conversations ?? []).map((c: ConversationRow) => (
<div
@@ -377,25 +406,85 @@ export function Chat() {
}`}
>
{/* 单行标题;删除键悬停浮现(弹确认,不直接删) */}
- <button
- onClick={() => openConversation(c.id)}
- className="w-full text-left px-2.5 py-2"
- >
- <span
- className={`block truncate pr-5 text-[13px] ${
- c.id === activeId ? "text-white" : "text-neutral-300"
- }`}
+ {renamingId === c.id ? (
+ /* 就地编辑:Enter 保存、Esc 取消。改一个名字不值得弹对话框 */
+ <input
+ autoFocus
+ className="input-dark w-full px-2 py-1.5 text-[13px]"
+ value={renameDraft}
+ onChange={(e) => setRenameDraft(e.target.value)}
+ onBlur={() => setRenamingId(null)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && renameDraft.trim())
+ rename.mutate({ id: c.id, title: renameDraft });
+ if (e.key === "Escape") setRenamingId(null);
+ }}
+ />
+ ) : (
+ <button
+ onClick={() => openConversation(c.id)}
+ className="w-full text-left px-2.5 py-2"
>
- {c.title || S.ask.untitled}
- </span>
- </button>
- <button
- onClick={() => setPendingDelete(c)}
- title={S.ask.deleteConversation}
- className="absolute right-2 top-1/2 -translate-y-1/2 hidden group-hover:block text-neutral-600 hover:text-[var(--u-danger)]"
- >
- <Trash2 size={13} />
- </button>
+ <span
+ className={`block truncate pr-5 text-[13px] ${
+ c.id === activeId ? "text-white" : "text-neutral-300"
+ }`}
+ >
+ {c.title || S.ask.untitled}
+ </span>
+ </button>
+ )}
+ {/* 三点菜单:**一个入口装下所有动作**。从前右边直接是删除,
+ 而删除是这里最不该一步到位的那个 */}
+ {renamingId !== c.id && (
+ <button
+ onClick={() => setMenuFor(menuFor === c.id ? null : c.id)}
+ title={S.ask.moreActions}
+ className="absolute right-2 top-1/2 -translate-y-1/2 hidden group-hover:block text-neutral-600 hover:text-neutral-200"
+ >
+ <MoreHorizontal size={14} />
+ </button>
+ )}
+ {menuFor === c.id && (
+ <>
+ {/* 点别处就关。铺满全屏而不是监听 document:不必在卸载时
+ 记得摘监听器 */}
+ <div
+ className="fixed inset-0 z-10"
+ onClick={() => setMenuFor(null)}
+ />
+ <div className="glass-strong absolute right-2 top-8 z-20 w-32 rounded-lg py-1 shadow-xl">
+ <button
+ className="w-full px-3 py-1.5 text-left text-xs text-neutral-300 hover:bg-white/5"
+ onClick={() => {
+ setRenameDraft(c.title || "");
+ setRenamingId(c.id);
+ setMenuFor(null);
+ }}
+ >
+ {S.ask.rename}
+ </button>
+ <button
+ className="w-full px-3 py-1.5 text-left text-xs text-neutral-300 hover:bg-white/5"
+ onClick={() => {
+ navigator.clipboard?.writeText(c.title || "");
+ setMenuFor(null);
+ }}
+ >
+ {S.ask.copyTitle}
+ </button>
+ <button
+ className="w-full px-3 py-1.5 text-left text-xs text-[var(--u-danger)] hover:bg-white/5"
+ onClick={() => {
+ setPendingDelete(c);
+ setMenuFor(null);
+ }}
+ >
+ {S.ask.deleteConversation}
+ </button>
+ </div>
+ </>
+ )}
</div>
))}
{convs.data?.conversations.length === 0 && (
diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsx
index 08667877..d28c3be0 100644
--- a/web/src/pages/Graph.tsx
+++ b/web/src/pages/Graph.tsx
@@ -24,7 +24,14 @@ import {
ZoomIn,
ZoomOut,
} from "lucide-react";
-import { api, type EntityFact, type Evidence, type GraphEdge, type GraphNode } from "../api";
+import {
+ api,
+ type DerivedFact,
+ type EntityFact,
+ type Evidence,
+ type GraphEdge,
+ type GraphNode,
+} from "../api";
import { S } from "../i18n";
import { useKb } from "../kb";
import { toast } from "../toast";
@@ -42,6 +49,16 @@ const RING_HOVERED = "#8FE7FF"; // 悬停冰青环
const EDGE_COLOR = "rgba(163,163,163,0.2)"; // 纯灰(应用户要求,不用钢蓝)
// 本体没认下的关系:同色更淡。名字来自原文,不该跟词表里的关系看着一样重
const EDGE_COLOR_INFERRED = "rgba(163,163,163,0.1)";
+// 推出来的边(R1)。**跟上面两者说的不是一件事**:那两个说「这条边的名字从哪来」,
+// 这个说「这条边根本不是谁说的,是引擎推的」。所以给它自己的色相而不是再淡一档灰——
+// 用户要在余光里就分得出「文档里写的」和「推出来的」
+const EDGE_COLOR_DERIVED = "rgba(231,197,124,0.42)";
+const EDGE_COLOR_DERIVED_DIM = "rgba(231,197,124,0.14)";
+// 呼吸周期。动画不是为了好看,是因为静态的一个色差在几百条边里根本注意不到
+const DERIVED_PULSE_MS = 2200;
+// 超过这个数就只上色不动画。**写出来而不是悄悄降级**:每帧重算几千条边的颜色,
+// 换来的是拖不动图,而那时候用户要的是能拖得动
+const DERIVED_ANIMATE_MAX = 400;
// 注意:sigma 边着色器在预乘混合(ONE, ONE_MINUS_SRC_ALPHA)下不预乘 RGB,
// alpha 无法压暗边——暗度必须编码进 RGB(不透明近背景色)
const EDGE_DIM = "#141414";
@@ -241,6 +258,10 @@ export function Graph() {
const [searchInput, setSearchInput] = useState("");
const [searchQ, setSearchQ] = useState("");
const [hiddenTypes, setHiddenTypes] = useState<Set<string>>(new Set());
+ // 推出来的边显不显示。默认显示——推理默认关着,有派生就意味着用户开过开关
+ const [showDerived, setShowDerived] = useState(true);
+ // 信息窗默认收起:它答的是「什么时候推的」,那是偶尔才问的问题
+ const [derivedPanel, setDerivedPanel] = useState(false);
/** null = 全时段;数值 = as-of 时刻(ms)。
默认 as-of 今天:时态平台的图谱默认呈现"现在的世界",
已闭合的事实不该与现行事实无差别并列(All time 是显式选择) */
@@ -264,10 +285,15 @@ export function Graph() {
// 全图模式走全库实体搜索;子图模式只在已加载的子图内客户端过滤
const inSubgraph = !!focusEntity;
+ // 搜到的条数上限。**「加载更多」而不是翻页**:这是个下拉建议框,
+ // 用户在找一个具体的实体,翻页会让他丢掉刚才扫过的那几条
+ const [searchLimit, setSearchLimit] = useState(10);
+ useEffect(() => setSearchLimit(10), [searchQ]);
const candidates = useQuery({
- queryKey: ["entitySearch", kb?.id, searchQ],
- queryFn: () => api.searchEntities(kb!.id, searchQ),
+ queryKey: ["entitySearch", kb?.id, searchQ, searchLimit],
+ queryFn: () => api.searchEntities(kb!.id, searchQ, searchLimit),
enabled: !!kb && searchQ.length > 0 && !inSubgraph,
+ placeholderData: (prev) => prev,
});
const subgraphHits = useMemo(() => {
if (!inSubgraph || !searchQ || !data.data) return [];
@@ -292,7 +318,15 @@ export function Graph() {
hiddenTypes: Set<string>;
activeNodes: Set<string> | null;
activeEdges: Set<string> | null;
- }>({ hiddenTypes: new Set(), activeNodes: null, activeEdges: null });
+ /** 推出来的边显不显示。**默认显示**——推理默认是关的,所以有派生边就意味着
+ * 用户主动开过开关;但要能一键藏起来,看「只有人说过的那张图」长什么样 */
+ showDerived: boolean;
+ }>({
+ hiddenTypes: new Set(),
+ activeNodes: null,
+ activeEdges: null,
+ showDerived: true,
+ });
const playingRef = useRef(false);
/* 播放淡入表:本轮新激活的节点/边 id → 激活时刻(rAF 循环驱动至到位) */
const fadeRef = useRef<Map<string, number>>(new Map());
@@ -337,6 +371,13 @@ export function Graph() {
return [...map.entries()];
}, [data.data]);
+ // 有几条推出来的边。**为零时那个开关整个不出现**——一个没开推理的库不该
+ // 看到一个永远切换不出任何变化的按钮
+ const derivedCount = useMemo(
+ () => (data.data?.edges ?? []).filter((e) => e.derived).length,
+ [data.data],
+ );
+
/* 时间过滤:计算 T 时刻的活跃边/节点集合 */
const recomputeActive = useCallback(
(t: number | null) => {
@@ -384,8 +425,19 @@ export function Graph() {
useEffect(() => {
filterRef.current.hiddenTypes = hiddenTypes;
+ filterRef.current.showDerived = showDerived;
sigmaRef.current?.refresh();
- }, [hiddenTypes]);
+ }, [hiddenTypes, showDerived]);
+
+ // 派生边的呼吸。**只在有派生边、且开着显示、且数量不多时才转**——
+ // 一个没开推理的库不该为这件事每两秒重画一次
+ useEffect(() => {
+ const n = derivedCount;
+ if (!showDerived || n === 0 || n > DERIVED_ANIMATE_MAX) return;
+ // 与 sigma 的重绘同频即可,不必每帧:呼吸是慢动作,30 fps 看不出差别
+ const timer = setInterval(() => sigmaRef.current?.refresh(), 1000 / 30);
+ return () => clearInterval(timer);
+ }, [showDerived, derivedCount]);
useEffect(() => {
selectedRef.current = selected;
@@ -421,8 +473,14 @@ export function Graph() {
g.addEdgeWithKey(e.id, e.source, e.target, {
label: e.label?.toUpperCase() ?? "",
size: 1,
- color: e.inferred ? EDGE_COLOR_INFERRED : EDGE_COLOR,
+ color: e.derived
+ ? EDGE_COLOR_DERIVED
+ : e.inferred
+ ? EDGE_COLOR_INFERRED
+ : EDGE_COLOR,
type: "line",
+ // reducer 每帧读它:决定要不要藏、要不要呼吸
+ derived: e.derived,
});
}
}
@@ -617,6 +675,21 @@ export function Graph() {
res.hidden = true;
return res;
}
+ // 推出来的边:先看藏不藏,再决定呼吸到哪一档。
+ // **放在最前面**——藏起来的边不必再算后面那些提亮/压暗
+ const isDerived = attrs.derived === true;
+ if (isDerived) {
+ if (!f.showDerived) {
+ res.hidden = true;
+ return res;
+ }
+ res.color = lerpColor(
+ EDGE_COLOR_DERIVED_DIM,
+ EDGE_COLOR_DERIVED,
+ // 三角波而不是正弦:两端各停一瞬,看起来是「呼吸」不是「闪」
+ Math.abs(((performance.now() % DERIVED_PULSE_MS) / DERIVED_PULSE_MS) * 2 - 1),
+ );
+ }
// hover: 只提亮关联边;selected: 提亮关联边 + 压暗其余
const hov = hoverRef.current;
const sel =
@@ -746,6 +819,11 @@ export function Graph() {
const empty = data.isSuccess && data.data.nodes.length === 0;
const nodeCount = data.data?.nodes.length ?? 0;
const edgeCount = data.data?.edges.length ?? 0;
+ // 库里一共有多少。**与画上去的不是一回事**——邻域视图没有总数(它本来就只
+ // 是一小片),所以缺省回落到画上去的那个数,不会显示成「共 0 个」
+ const totalNodes = data.data?.total_nodes ?? nodeCount;
+ const totalEdges = data.data?.total_edges ?? edgeCount;
+ const capped = totalNodes > nodeCount;
return (
<div className="h-full relative">
@@ -786,6 +864,20 @@ export function Graph() {
<span className="ml-auto text-xs text-neutral-500">{c.type_label}</span>
</button>
))}
+ {/* 还有更多没显示。**说清剩多少**——从前固定十条,想找的那个
+ 不在这十条里的时候,界面上一点线索都没有。子图内搜索是客户端
+ 过滤,没有「更多」这回事 */}
+ {!inSubgraph &&
+ (candidates.data?.total ?? 0) > searchHits.length && (
+ <button
+ onClick={() => setSearchLimit((n) => n + 20)}
+ className="w-full border-t border-white/10 px-3 py-1.5 text-left text-xs text-neutral-400 hover:bg-white/5 hover:text-neutral-200"
+ >
+ {S.graph.searchMore(
+ candidates.data!.total - searchHits.length,
+ )}
+ </button>
+ )}
</div>
)}
</div>
@@ -822,11 +914,65 @@ export function Graph() {
<span className="text-neutral-300">{t.label}</span>
</button>
))}
+ {/* 推出来的边:与类型图例同一条,因为它们是同一种动作——决定图上
+ 显示什么。为零时不出现 */}
+ {derivedCount > 0 && (
+ <div className="relative flex items-center gap-1">
+ <button
+ onClick={() => setShowDerived((v) => !v)}
+ title={S.graph.derivedHint}
+ className={`glass rounded-full px-2.5 py-1 text-[11px] flex items-center gap-1.5 transition-opacity ${
+ showDerived ? "" : "opacity-35"
+ }`}
+ >
+ <span
+ className="h-2 w-2 rounded-full"
+ style={{ background: "rgba(231,197,124,0.9)" }}
+ />
+ <span className="text-neutral-300">
+ {S.graph.derivedEdges(derivedCount)}
+ </span>
+ </button>
+ {/* 展开成一个小窗:这批边是什么时候推的、现在还推不推、手动再跑一次。
+ **与开关分成两个按钮**——「藏起来」是每天要点的,「什么时候推的」
+ 是偶尔才问的,合成一个会让常用动作多一步 */}
+ <button
+ onClick={() => setDerivedPanel((v) => !v)}
+ title={S.graph.derivedPanel}
+ aria-expanded={derivedPanel}
+ className={`glass rounded-full h-[22px] w-[22px] text-[11px] leading-none text-neutral-400 hover:text-neutral-100 transition-colors ${
+ derivedPanel ? "text-neutral-100" : ""
+ }`}
+ >
+ ⋯
+ </button>
+ {derivedPanel && kb && (
+ <DerivedPanel
+ kbId={kb.id}
+ count={derivedCount}
+ onClose={() => setDerivedPanel(false)}
+ />
+ )}
+ </div>
+ )}
</div>
<div className="ml-auto pointer-events-none pt-0.5 u-num text-[11px] text-neutral-500">
{stabilizing && <span className="text-neutral-400">{S.graph.stabilizing} · </span>}
- {S.graph.stats(nodeCount, edgeCount, timeT === null ? edgeCount : activeCount)}
+ {/* 画满上限时说清「画了多少 / 共多少」。**这个数从前是上限冒充规模**——
+ 一个上万实体的库右上角永远写着 150 */}
+ {capped ? (
+ <span title={S.graph.cappedHint(nodeCount, totalNodes)}>
+ {S.graph.statsCapped(
+ nodeCount,
+ totalNodes,
+ totalEdges,
+ timeT === null ? edgeCount : activeCount,
+ )}
+ </span>
+ ) : (
+ S.graph.stats(nodeCount, edgeCount, timeT === null ? edgeCount : activeCount)
+ )}
</div>
</div>
@@ -1174,6 +1320,147 @@ function fmtInterval(f: EntityFact): string {
return from ? `${from} ~ ${end}` : `~ ${end}`;
}
+/** 一条推出来的事实,**证明摊开在下面**。
+ *
+ * 不做折叠:这一档存在的全部理由就是「这条边不是谁说的,是这么来的」,
+ * 把前提藏在一次点击后面等于把理由藏起来。链最长十二条,摊开也不长。 */
+/** 派生开关旁边那个小窗:**这批边是什么时候、按什么推出来的,以及现在还准不准**。
+ *
+ * 存在的理由是「新鲜度看不见」。派生每小时重推一次,而事实每篇文档进来都在变——
+ * 一条派生边看上去和它刚推出来的时候一模一样,可它依据的前提可能三分钟前刚被撤掉。
+ * 光有开关答不了「我现在看到的是什么时候的结论」。
+ *
+ * 手动按钮留在这里而不是别处:想重推的人正是刚看完这三行、觉得数字太旧的那个人。
+ */
+function DerivedPanel({
+ kbId,
+ count,
+ onClose,
+}: {
+ kbId: string;
+ count: number;
+ onClose: () => void;
+}) {
+ const qc = useQueryClient();
+ const kb = useQuery({
+ queryKey: ["kbOne", kbId],
+ queryFn: () => api.kbDetail(kbId),
+ });
+ const run = useMutation({
+ mutationFn: () => api.runInference(kbId),
+ onSuccess: () => {
+ qc.invalidateQueries({ queryKey: ["graph"] });
+ qc.invalidateQueries({ queryKey: ["kbOne", kbId] });
+ },
+ onError: (e: Error) => toast.error(e.message),
+ });
+
+ const on = kb.data?.materialize_inferences ?? false;
+ const last = kb.data?.last_inference_at;
+ // 「多久以前」比一个时间戳好读——问题是「新不新」,不是「几点」
+ const age = last ? Math.round((Date.now() - new Date(last).getTime()) / 60000) : null;
+
+ return (
+ <div className="glass-strong pointer-events-auto absolute left-0 top-8 z-20 w-72 rounded-xl p-3 shadow-xl">
+ <div className="flex items-baseline gap-2">
+ <span className="text-[13px] text-neutral-100">{S.graph.derivedPanel}</span>
+ <button
+ className="ml-auto text-neutral-500 hover:text-neutral-200"
+ onClick={onClose}
+ aria-label={S.graph.close}
+ >
+ ×
+ </button>
+ </div>
+
+ <dl className="mt-2 space-y-1 text-[11px]">
+ <div className="flex justify-between gap-3">
+ <dt className="text-neutral-500">{S.graph.derivedCountLabel}</dt>
+ <dd className="u-num text-neutral-200">{count}</dd>
+ </div>
+ <div className="flex justify-between gap-3">
+ <dt className="text-neutral-500">{S.graph.derivedStateLabel}</dt>
+ <dd className={on ? "text-neutral-200" : "text-[var(--u-warn)]"}>
+ {on ? S.graph.derivedOn(kb.data!.inference_interval_minutes) : S.graph.derivedOff}
+ </dd>
+ </div>
+ <div className="flex justify-between gap-3">
+ <dt className="text-neutral-500">{S.graph.derivedLastLabel}</dt>
+ <dd className="u-num text-neutral-200">
+ {age === null ? S.graph.derivedNever : S.graph.derivedAgo(age)}
+ </dd>
+ </div>
+ </dl>
+
+ {/* 上一次手动跑的结果留在这儿。**推出多少、作废多少要分开说**——
+ 「什么都没变」和「换掉了三十条」是两件很不一样的事 */}
+ {run.data && (
+ <p className="mt-2 text-[11px] text-neutral-400">
+ {run.data.inserted === 0 && run.data.invalidated === 0
+ ? S.graph.derivedNoChange
+ : S.graph.derivedChanged(run.data.inserted, run.data.invalidated)}
+ {run.data.capped > 0 && ` · ${S.graph.derivedCapped(run.data.capped)}`}
+ </p>
+ )}
+
+ <button
+ className="u-btn u-btn-primary mt-2.5 w-full py-1 text-[11px]"
+ disabled={!on || run.isPending}
+ title={on ? undefined : S.err.inference_off}
+ onClick={() => run.mutate()}
+ >
+ {run.isPending ? S.graph.derivedRunning : S.graph.derivedRun}
+ </button>
+ </div>
+ );
+}
+
+function DerivedRow({
+ d,
+ onNavigate,
+}: {
+ d: DerivedFact;
+ onNavigate: (entityId: string) => void;
+}) {
+ return (
+ <div className="glass rounded-xl p-3">
+ <div className="flex items-baseline gap-1.5 flex-wrap text-sm">
+ <button
+ className="text-neutral-100 hover:text-white underline-offset-2 hover:underline"
+ onClick={() => onNavigate(d.subject_id)}
+ >
+ {d.subject}
+ </button>
+ <span className="text-xs text-neutral-500">{d.predicate}</span>
+ <button
+ className="text-neutral-100 hover:text-white underline-offset-2 hover:underline"
+ onClick={() => onNavigate(d.object_id)}
+ >
+ {d.object}
+ </button>
+ <span className="ml-auto text-[10px] text-[var(--u-warn)]">
+ {d.rule === "transitive"
+ ? S.graph.ruleTransitive
+ : S.graph.ruleSymmetric}
+ </span>
+ </div>
+ {/* 证明:前提按推导顺序,缩进一格。看得出链是怎么走的 */}
+ <ol className="mt-2 space-y-0.5 border-l border-[var(--u-line)] pl-2.5">
+ {d.premises.map((p, i) => (
+ <li key={i} className="text-[11px] text-neutral-400">
+ {p}
+ </li>
+ ))}
+ </ol>
+ {d.premises.length === 0 && (
+ <p className="mt-1 text-[11px] text-neutral-600">
+ {S.graph.derivedNoProof}
+ </p>
+ )}
+ </div>
+ );
+}
+
function EntityPanel({
kbId,
entityId,
@@ -1190,9 +1477,14 @@ function EntityPanel({
queryFn: () => api.entityDetail(kbId, entityId),
});
const [openFact, setOpenFact] = useState<string | null>(null);
+ // 推出来的那些。**单独一个键,不掺进 facts**——混在一个列表里,用户看不出
+ // 「文档里写的」和「引擎推的」的区别
+ const derived = detail.data?.derived ?? [];
// Relations = 按关系分组(查关系);Timeline = 有效时间轴(事情何时成立);
// History = 记录时间轴(我们何时这么认为、又何时改了主意)
- const [view, setView] = useState<"relations" | "timeline" | "history">("relations");
+ const [view, setView] = useState<
+ "relations" | "timeline" | "history" | "derived"
+ >("relations");
const e: GraphNode | undefined = detail.data?.entity;
@@ -1201,7 +1493,27 @@ function EntityPanel({
const [editing, setEditing] = useState(false);
const [draftName, setDraftName] = useState("");
const [draftType, setDraftType] = useState("");
- const [sameName, setSameName] = useState<GraphNode[]>([]);
+ // 同名的其他实体:详情接口打开就给。改名之后再用响应里的那份覆盖——
+ // 改完名可能撞上一批新的同名,那时候的答案比打开时的新
+ const [renamedPeers, setRenamedPeers] = useState<GraphNode[] | null>(null);
+ const sameName = renamedPeers ?? detail.data?.same_name ?? [];
+ const setSameName = setRenamedPeers;
+ // 手动合并:把同名的那个并进**当前这个**。方向写死是有意的——
+ // 用户正在看的就是他判断为「主」的那一个
+ const merge = useMutation({
+ mutationFn: (source: string) => api.mergeEntities(kbId, source, entityId),
+ onSuccess: () => {
+ toast.success(S.toast.saved);
+ // 本地把并掉的那个摘掉,别等重取——它已经不存在了,留着会让人再点一次
+ setSameName((prev) =>
+ (prev ?? sameName).filter((p) => p.id !== merge.variables),
+ );
+ qc.invalidateQueries({ queryKey: ["entity", kbId, entityId] });
+ qc.invalidateQueries({ queryKey: ["graph"] });
+ qc.invalidateQueries({ queryKey: ["review", kbId] });
+ },
+ onError: (err: Error) => toast.error(err.message),
+ });
// 类型下拉要的是全量本体,不是当前视图里出现过的那几个
const ontology = useQuery({
queryKey: ["ontology", kbId],
@@ -1396,18 +1708,33 @@ function EntityPanel({
<X size={11} />
</button>
</div>
- <div className="mt-1.5 flex flex-wrap gap-1">
+ {/* 每个同名的给两个动作:去看它,或者把它并进来。
+ **方向写死成「并进当前这个」**——合并有方向(源消失、事实搬到目标上),
+ 而当前打开的这个就是用户正在看、正在判断的那一个 */}
+ <div className="mt-1.5 space-y-1">
{sameName.map((p) => (
- <button
- key={p.id}
- onClick={() => onNavigate(p.id)}
- className="text-[11px] px-1.5 py-0.5 rounded bg-white/[0.06] text-neutral-300 hover:bg-white/10"
- >
- {p.type_label ?? S.graph.untyped}
- {p.disambiguator && p.disambiguator !== p.type_label
- ? ` · ${p.disambiguator}`
- : ""}
- </button>
+ <div key={p.id} className="flex items-center gap-1">
+ <button
+ onClick={() => onNavigate(p.id)}
+ className="min-w-0 flex-1 truncate text-left text-[11px] px-1.5 py-0.5 rounded bg-white/[0.06] text-neutral-300 hover:bg-white/10"
+ >
+ {p.type_label ?? S.graph.untyped}
+ {p.disambiguator && p.disambiguator !== p.type_label
+ ? ` · ${p.disambiguator}`
+ : ""}
+ </button>
+ <button
+ className="shrink-0 text-[11px] px-1.5 py-0.5 rounded text-neutral-400 hover:bg-white/10 hover:text-neutral-100"
+ disabled={merge.isPending}
+ title={S.graph.mergeIntoHint}
+ onClick={() => {
+ if (confirm(S.graph.mergeConfirm(p.name, e?.name ?? "")))
+ merge.mutate(p.id);
+ }}
+ >
+ {S.graph.mergeInto}
+ </button>
+ </div>
))}
</div>
</div>
@@ -1416,7 +1743,13 @@ function EntityPanel({
{/* 视图切换:Relations(分组)| Timeline(年表) */}
<div className="px-4 pt-2.5">
<div className="flex rounded-lg overflow-hidden border border-white/10 w-fit">
- {(["relations", "timeline", "history"] as const).map((v) => (
+ {(
+ ["relations", "timeline", "history", "derived"] as const
+ )
+ // 推出来的那一档:**没有派生就不出现**。一个没开推理的库不该看到
+ // 一个永远是空的标签页
+ .filter((v) => v !== "derived" || derived.length > 0)
+ .map((v) => (
<button
key={v}
onClick={() => setView(v)}
@@ -1430,7 +1763,9 @@ function EntityPanel({
? S.graph.viewRelations
: v === "timeline"
? S.graph.viewTimeline
- : S.graph.viewHistory}
+ : v === "history"
+ ? S.graph.viewHistory
+ : S.graph.viewDerived}
</button>
))}
</div>
@@ -1482,9 +1817,21 @@ function EntityPanel({
/>
)}
{view === "history" && <EntityHistory kbId={kbId} entityId={entityId} />}
- {view !== "history" && detail.data?.facts.length === 0 && (
- <p className="text-sm text-neutral-500 p-2">{S.graph.noFacts}</p>
+ {view === "derived" && (
+ <div className="space-y-2">
+ <p className="px-2 pb-1 text-[11px] leading-relaxed text-neutral-500">
+ {S.graph.derivedHint}
+ </p>
+ {derived.map((d) => (
+ <DerivedRow key={d.id} d={d} onNavigate={onNavigate} />
+ ))}
+ </div>
)}
+ {view !== "history" &&
+ view !== "derived" &&
+ detail.data?.facts.length === 0 && (
+ <p className="text-sm text-neutral-500 p-2">{S.graph.noFacts}</p>
+ )}
</div>
</div>
);
diff --git a/web/src/pages/KbSettings.tsx b/web/src/pages/KbSettings.tsx
index 63ca3603..77891d26 100644
--- a/web/src/pages/KbSettings.tsx
+++ b/web/src/pages/KbSettings.tsx
@@ -21,6 +21,7 @@ import {
DangerConfirm,
Dropdown,
Loading,
+ Pager,
RAIL_CLS,
SearchSelect,
} from "../ui";
@@ -65,6 +66,9 @@ export function KbSettings() {
const [desc, setDesc] = useState("");
const [visibility, setVisibility] = useState<"open" | "restricted">("open");
const [autoExtend, setAutoExtend] = useState(true);
+ // **默认关**,与上面那个相反:推理往账本里写事实,而声明可能是错的
+ const [materialize, setMaterialize] = useState(false);
+ const [inferMins, setInferMins] = useState(60);
const [ontoLang, setOntoLang] = useState<"en" | "zh">("en");
const [confirmingDelete, setConfirmingDelete] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -75,6 +79,8 @@ export function KbSettings() {
setDesc(kb.data.description ?? "");
setVisibility(kb.data.visibility);
setAutoExtend(kb.data.auto_extend_ontology);
+ setMaterialize(kb.data.materialize_inferences);
+ setInferMins(kb.data.inference_interval_minutes);
setOntoLang(kb.data.ontology_lang);
}
}, [kb.data]);
@@ -91,6 +97,8 @@ export function KbSettings() {
description: desc.trim() || null,
visibility,
auto_extend_ontology: autoExtend,
+ materialize_inferences: materialize,
+ inference_interval_minutes: inferMins,
ontology_lang: ontoLang,
}),
onSuccess: () => {
@@ -247,6 +255,51 @@ export function KbSettings() {
</span>
</span>
</label>
+ {/* 物化推理:**默认关**,与上面那个相反。自动扩本体动的是词表,
+ 这个动的是账本——它按公理往图里写事实,而声明可能是错的 */}
+ <label className="flex items-start gap-2.5 pt-1 cursor-pointer">
+ <input
+ type="checkbox"
+ className="mt-0.5 accent-[var(--u-accent)]"
+ checked={materialize}
+ onChange={(e) => setMaterialize(e.target.checked)}
+ />
+ <span className="min-w-0">
+ <span className="block text-sm text-neutral-200">
+ {S.kbset.materialize}
+ </span>
+ <span className="block text-xs leading-relaxed text-neutral-500">
+ {S.kbset.materializeNote}
+ </span>
+ </span>
+ </label>
+ {/* 重推间隔。**只在开着的时候露出来**——关着时它不影响任何事,
+ 摆在那里只会让人以为设了就会推 */}
+ {materialize && (
+ <div className="pl-6 flex items-center gap-2">
+ <label className="text-xs text-neutral-500">
+ {S.kbset.inferEvery}
+ </label>
+ <input
+ type="number"
+ min={5}
+ max={10080}
+ className="input-dark w-24 px-2 py-1 text-xs u-num"
+ value={inferMins}
+ onChange={(e) => setInferMins(Number(e.target.value))}
+ />
+ <span className="text-xs text-neutral-500">
+ {S.kbset.minutes}
+ </span>
+ {kb.data.last_inference_at && (
+ <span className="text-[11px] text-neutral-600">
+ {S.kbset.lastInference(
+ new Date(kb.data.last_inference_at).toLocaleString(),
+ )}
+ </span>
+ )}
+ </div>
+ )}
{/* 语料语言。**不是界面语言**——类描述逐字进抽取提示词,
读者是正在读这些文档的模型,所以它跟文档走不跟读者走 */}
<div className="pt-1">
@@ -347,16 +400,87 @@ function auditDetailName(e: AuditEvent): string {
return typeof hit === "string" ? hit : "";
}
+const AUDIT_PAGE = 50;
+
function KbActivity({ kbId }: { kbId: string }) {
+ // 筛选按真实查法来:查一类动作、查一个人、查一段时间。
+ // 动作前缀匹配——`entity.` 就能把 retyped / renamed 一族一起捞出来
+ const [action, setAction] = useState("");
+ const [since, setSince] = useState("");
+ const [until, setUntil] = useState("");
+ const [page, setPage] = useState(0);
const audit = useQuery({
- queryKey: ["kbAudit", kbId],
- queryFn: () => api.kbAudit(kbId),
+ queryKey: ["kbAudit", kbId, action, since, until, page],
+ queryFn: () =>
+ api.kbAudit(kbId, {
+ action: action || undefined,
+ since: since || undefined,
+ until: until || undefined,
+ limit: AUDIT_PAGE,
+ offset: page * AUDIT_PAGE,
+ }),
+ placeholderData: (prev) => prev,
});
const events = audit.data?.events ?? [];
+ const total = audit.data?.total ?? 0;
+ // 下拉按这个库实际发生过的动作填,不是硬编码清单
+ const actions = audit.data?.actions ?? [];
+ const filtered = !!(action || since || until);
+
+ const reset = (fn: () => void) => {
+ fn();
+ setPage(0);
+ };
return (
<div className="glass rounded-xl p-4">
<p className="text-xs text-neutral-500 mb-3">{S.kbset.activityHint}</p>
+ <div className="mb-3 flex flex-wrap items-center gap-2">
+ <select
+ className="input-dark px-2 py-1 text-xs"
+ value={action}
+ onChange={(e) => reset(() => setAction(e.target.value))}
+ >
+ <option value="">{S.kbset.auditAllActions}</option>
+ {actions.map((a) => (
+ <option key={a} value={a}>
+ {a}
+ </option>
+ ))}
+ </select>
+ <input
+ type="date"
+ className="input-dark px-2 py-1 text-xs u-num"
+ value={since}
+ title={S.kbset.auditSince}
+ onChange={(e) => reset(() => setSince(e.target.value))}
+ />
+ <span className="text-xs text-neutral-600">→</span>
+ <input
+ type="date"
+ className="input-dark px-2 py-1 text-xs u-num"
+ value={until}
+ title={S.kbset.auditUntil}
+ onChange={(e) => reset(() => setUntil(e.target.value))}
+ />
+ {filtered && (
+ <button
+ className="u-btn u-btn-ghost px-2 py-1 text-xs"
+ onClick={() =>
+ reset(() => {
+ setAction("");
+ setSince("");
+ setUntil("");
+ })
+ }
+ >
+ {S.kbset.auditClear}
+ </button>
+ )}
+ <span className="ml-auto u-num text-[11px] text-neutral-500">
+ {S.kbset.auditTotal(total)}
+ </span>
+ </div>
{audit.isPending ? (
<p className="text-xs text-neutral-600">{S.nav.loading}</p>
) : events.length === 0 ? (
@@ -389,6 +513,12 @@ function KbActivity({ kbId }: { kbId: string }) {
))}
</div>
)}
+ <Pager
+ total={total}
+ pageSize={AUDIT_PAGE}
+ page={page}
+ onPage={setPage}
+ />
</div>
);
}
diff --git a/web/src/pages/Library.tsx b/web/src/pages/Library.tsx
index 7ac5b249..3a472c14 100644
--- a/web/src/pages/Library.tsx
+++ b/web/src/pages/Library.tsx
@@ -16,7 +16,7 @@ import { api, type Doc, type ExtractionDrop, type SourceView } from "../api";
import { S } from "../i18n";
import { useKb } from "../kb";
import { toast } from "../toast";
-import { Chip, type ChipTone, DangerConfirm, Loading, Pager, pageSlice } from "../ui";
+import { Chip, type ChipTone, DangerConfirm, Loading, Pager } from "../ui";
import {
KIND_ICON,
SOURCE_ICONS,
@@ -326,6 +326,9 @@ export function Library() {
const [showHistory, setShowHistory] = useState(false);
const [page, setPage] = useState(0);
const [filter, setFilter] = useState("");
+ // 按抽取状态筛。**空 = 不筛**——五篇失败混在二十七篇里,从前只能一页页看
+ const [graphFilter, setGraphFilter] = useState("");
+
// 切换文件夹回到第一页、清空过滤、退出历史视图
useEffect(() => {
@@ -338,9 +341,19 @@ export function Library() {
// 状态变化经 SSE 事件流推送(useKbEvents 挂在 Shell),无需轮询
const docs = useQuery({
- queryKey: ["documents", kb?.id],
- queryFn: () => api.documents(kb!.id),
+ // **服务端筛选与分页**:作用域、名字、抽取状态、页码都进 queryKey,
+ // 换任何一个都重新取一页。从前是一次取回整库、客户端切片
+ queryKey: ["documents", kb?.id, selection, filter, graphFilter, page],
+ queryFn: () =>
+ api.documents(kb!.id, {
+ source: selection === "all" ? undefined : selection === "uploads" ? "none" : selection,
+ q: filter.trim() || undefined,
+ graph: graphFilter || undefined,
+ limit: PAGE_SIZE,
+ offset: page * PAGE_SIZE,
+ }),
enabled: !!kb,
+ placeholderData: (prev) => prev,
});
const sources = useQuery({
queryKey: ["sources", kb?.id],
@@ -365,11 +378,31 @@ export function Library() {
const invalidate = () => {
queryClient.invalidateQueries({ queryKey: ["documents", kb?.id] });
+ queryClient.invalidateQueries({ queryKey: ["docCount", kb?.id] });
queryClient.invalidateQueries({ queryKey: ["sources", kb?.id] });
// 重抽会重写这篇文档的丢弃信号,跟着文档一起失效
queryClient.invalidateQueries({ queryKey: ["extraction-drops", kb?.id] });
};
+ // 一键重试这个作用域里全部失败的。**逐篇入队在服务端做**——排队还带着
+ // 别的动作(解雇在跑的任务、清增量标记),绕过去会留下半截状态
+ const retryFailed = useMutation({
+ mutationFn: () =>
+ api.retryFailedDocs(
+ kb!.id,
+ selection === "all"
+ ? undefined
+ : selection === "uploads"
+ ? "none"
+ : selection,
+ ),
+ onSuccess: (r) => {
+ toast.success(S.library.retryQueued(r.queued));
+ invalidate();
+ },
+ onError: (e: Error) => toast.error(e.message),
+ });
+
const upload = useMutation({
// 选中 folder 来源时,上传直接归入该文件夹
mutationFn: (files: FileList | File[]) => {
@@ -452,22 +485,20 @@ export function Library() {
if (!kb) return <Loading>{S.nav.loading}</Loading>;
- const allDocs = docs.data ?? [];
+ // 服务端已经切好了这一页:筛选、作用域、页码都在请求里
+ const pagedDocs = docs.data?.docs ?? [];
+ const totalDocs = docs.data?.total ?? 0;
+ // 整库可抽的篇数。**重建是库级动作**,不该显示当前来源的数字
+ const kbStats = useQuery({
+ queryKey: ["docCount", kb?.id],
+ queryFn: () => api.documents(kb!.id, { limit: 1, offset: 0 }),
+ enabled: !!kb,
+ });
+ const kbReady = kbStats.data?.ready ?? 0;
const sourceList = sources.data?.sources ?? [];
- const visibleDocs =
- selection === "all"
- ? allDocs
- : selection === "uploads"
- ? allDocs.filter((d) => !d.source_id)
- : allDocs.filter((d) => d.source_id === selection);
const selectedSource = sourceList.find((s) => s.id === selection);
-
+ const safePage = page;
const query = filter.trim().toLowerCase();
- const filteredDocs = query
- ? visibleDocs.filter((d) => d.filename.toLowerCase().includes(query))
- : visibleDocs;
-
- const { rows: pagedDocs, safe: safePage } = pageSlice(filteredDocs, page, PAGE_SIZE);
return (
<div className="h-full flex">
@@ -518,6 +549,36 @@ export function Library() {
</button>
)}
</div>
+ {/* 按抽取状态筛。**选项写死成那五个**,不按库里实际有的填——
+ 它是一组固定的管道状态,而「这个库现在没有失败的」正是用户
+ 想通过筛一下确认的事 */}
+ <select
+ className="input-dark px-2 py-1.5 text-[13px] shrink-0"
+ value={graphFilter}
+ onChange={(e) => {
+ setGraphFilter(e.target.value);
+ setPage(0);
+ }}
+ >
+ <option value="">{S.library.anyStatus}</option>
+ <option value="failed">{S.library.statusFailed}</option>
+ <option value="done">{S.library.statusDone}</option>
+ <option value="queued">{S.library.statusQueued}</option>
+ <option value="extracting">{S.library.statusExtracting}</option>
+ <option value="none">{S.library.statusNone}</option>
+ </select>
+ {/* 一键重试。**只在真有失败时出现**——没有失败的库不该看到一个
+ 点了什么都不会发生的按钮。数字写在按钮上,点之前就知道会动几篇 */}
+ {(docs.data?.failed ?? 0) > 0 && canUpload && (
+ <button
+ onClick={() => retryFailed.mutate()}
+ disabled={retryFailed.isPending}
+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs flex items-center gap-1.5 shrink-0"
+ >
+ <RefreshCw size={12} />
+ {S.library.retryFailed(docs.data!.failed)}
+ </button>
+ )}
{/* 全库重建:清算语义,仅 KB admin;放在 All documents 视图 */}
{selection === "all" && canRebuild && (
<button
@@ -563,13 +624,12 @@ export function Library() {
/>
)}
- {/* 抽取进度:当前视图内聚合 graph_status,SSE 推动实时走条 */}
+ {/* 抽取进度。**数来自服务端**,按来源作用域算——从前是数当前页里的,
+ 翻一页进度条就跳 */}
{(() => {
- const pending = visibleDocs.filter((d) =>
- ["queued", "extracting"].includes(d.graph_status),
- ).length;
+ const pending = docs.data?.extracting ?? 0;
if (pending === 0) return null;
- const total = visibleDocs.filter((d) => d.graph_status !== "none").length;
+ const total = (docs.data?.ready ?? 0) + pending;
const done = total - pending;
return (
<div className="mb-3 glass rounded-xl px-4 py-2.5">
@@ -603,7 +663,7 @@ export function Library() {
) : (
<>
<div className={`glass rounded-2xl glass-hover ${dragging ? "u-highlight" : ""}`}>
- {filteredDocs.length ? (
+ {pagedDocs.length ? (
<table className="w-full text-sm">
<thead>
<tr className="text-left text-xs text-neutral-500 border-b border-white/10">
@@ -640,7 +700,7 @@ export function Library() {
))}
</tbody>
</table>
- ) : query && visibleDocs.length ? (
+ ) : query || graphFilter ? (
<div className="py-20 text-center text-sm text-neutral-500">
{S.library.filterNoMatch}
</div>
@@ -659,7 +719,7 @@ export function Library() {
</div>
<Pager
- total={filteredDocs.length}
+ total={totalDocs}
pageSize={PAGE_SIZE}
page={safePage}
onPage={setPage}
@@ -718,7 +778,7 @@ export function Library() {
<DangerConfirm
title={S.library.reExtractTitle}
hint={S.library.reExtractHint(
- allDocs.filter((d) => d.source_id === selectedSource.id && d.status === "ready").length,
+ docs.data?.ready ?? 0,
selectedSource.name,
)}
confirmLabel={S.library.reExtractConfirm}
@@ -748,7 +808,7 @@ export function Library() {
<DangerConfirm
title={S.library.rebuildTitle}
hint={S.library.rebuildHint(
- allDocs.filter((d) => d.status === "ready").length,
+ kbReady,
kb.name,
)}
requireText={kb.name}
diff --git a/web/src/pages/Members.tsx b/web/src/pages/Members.tsx
index 42b3a88c..ad6209d4 100644
--- a/web/src/pages/Members.tsx
+++ b/web/src/pages/Members.tsx
@@ -2,6 +2,7 @@ import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "../api";
import { S } from "../i18n";
+import { toast } from "../toast";
import { Dropdown, Pager, pageSlice, SearchSelect } from "../ui";
const ROLES = ["owner", "admin", "editor", "viewer"] as const;
@@ -162,10 +163,68 @@ export function Members({ workspaceId }: { workspaceId: string }) {
</div>
{me.data?.is_admin && <CreateUser onCreated={refresh} />}
+ {me.data?.is_admin && <DeactivatedUsers onChanged={refresh} />}
</div>
);
}
+
+/** 已停用的账号,以及恢复它们。
+ *
+ * **这一块存在的理由是「否则恢复够不着」**:停用之后那个人从成员表、选人器、
+ * 每一个列表里消失,管理员拿不到他的 id,而恢复接口要的正是那个 id。
+ *
+ * 一个都没有时整块不出现——没有停用过的部署不该看到一个永远空的区块。
+ */
+function DeactivatedUsers({ onChanged }: { onChanged: () => void }) {
+ const list = useQuery({
+ queryKey: ["deactivatedUsers"],
+ queryFn: api.deactivatedUsers,
+ });
+ const queryClient = useQueryClient();
+ const revive = useMutation({
+ mutationFn: (userId: string) => api.adminReactivateUser(userId),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ["deactivatedUsers"] });
+ onChanged();
+ },
+ onError: (e: Error) => toast.error(e.message),
+ });
+
+ const users = list.data ?? [];
+ if (users.length === 0) return null;
+
+ return (
+ <div className="mt-6">
+ <h4 className="text-[13px] text-neutral-300">
+ {S.members.deactivatedTitle}
+ </h4>
+ <p className="mt-0.5 text-[11px] leading-relaxed text-neutral-500">
+ {S.members.deactivatedHint}
+ </p>
+ <div className="mt-2 space-y-1">
+ {users.map((u) => (
+ <div
+ key={u.id}
+ className="flex items-center gap-2 rounded border border-white/10 px-2.5 py-1.5"
+ >
+ <span className="text-[13px] text-neutral-300">
+ {u.display_name}
+ </span>
+ <span className="text-[11px] text-neutral-600">{u.email}</span>
+ <button
+ className="ml-auto u-btn u-btn-ghost px-2 py-0.5 text-xs"
+ disabled={revive.isPending}
+ onClick={() => revive.mutate(u.id)}
+ >
+ {S.members.reactivate}
+ </button>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
/** 管理员代开账号(注册关闭后的唯一入口)。 */
function CreateUser({ onCreated }: { onCreated: () => void }) {
const queryClient = useQueryClient();
diff --git a/web/src/pages/Ontology.tsx b/web/src/pages/Ontology.tsx
index 70bf3001..cfd123d9 100644
--- a/web/src/pages/Ontology.tsx
+++ b/web/src/pages/Ontology.tsx
@@ -4,7 +4,14 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";
-import { ChevronRight, Inbox, Plus, Search, Upload } from "lucide-react";
+import {
+ ChevronRight,
+ Inbox,
+ Plus,
+ Search,
+ Upload,
+ Wand2,
+} from "lucide-react";
import {
api,
type EntityTypeView,
@@ -12,6 +19,8 @@ import {
type OntologyMiss,
type PlannedItem,
type OntologyProposals,
+ type ResolutionOutcome,
+ type TypeSuggestion,
type RelationTypeView,
} from "../api";
import { S } from "../i18n";
@@ -48,6 +57,8 @@ type Sel =
| { kind: "new-class"; parentId: string | null }
| { kind: "new-relation" }
| { kind: "misses" }
+ // 类型消解:把「大致对」的类换成更具体的那个
+ | { kind: "refine" }
| { kind: "import" }
| null;
@@ -224,6 +235,21 @@ export function Ontology() {
<Upload size={14} className="text-neutral-500" />
<span>{S.ontology.importShort}</span>
</button>
+ {/* 类型消解:把「大致对」的类换成更具体的那个。**紧挨着未匹配**——
+ 两者都是「本体与数据对不齐」的处置,只是方向相反:那个是本体缺东西,
+ 这个是本体有更好的选项没被用上 */}
+ <button
+ onClick={() => setSel({ kind: "refine" })}
+ className={cn(
+ "shrink-0 border-t border-white/10 px-4 py-2.5 flex items-center gap-2 text-[13px] transition-colors",
+ sel?.kind === "refine"
+ ? "u-nav-active"
+ : "text-neutral-400 hover:bg-white/[0.05] hover:text-neutral-200",
+ )}
+ >
+ <Wand2 size={14} className="text-neutral-500" />
+ <span>{S.ontology.refineShort}</span>
+ </button>
{/* 底部常驻:抽取未匹配信号(有存量时带数量徽标) */}
<button
onClick={() => setSel({ kind: "misses" })}
@@ -252,6 +278,10 @@ export function Ontology() {
<div className="max-w-xl">
<ImportPanel kbId={kb.id} onChanged={refresh} onError={onError} />
</div>
+ ) : sel?.kind === "refine" ? (
+ <div className="max-w-2xl">
+ <RefinePanel kbId={kb.id} onChanged={refresh} onError={onError} />
+ </div>
) : sel?.kind === "misses" ? (
<div className="max-w-xl">
<MissesPanel
@@ -904,6 +934,9 @@ function ClassForm({
existing?.parents ?? (parentId ? [parentId] : []),
);
const [description, setDescription] = useState(existing?.description ?? "");
+ // 互斥:声明「不可能同时是」。一致性检查据此报不可满足的类(0002)——
+ // 一个类继承了两个互斥的祖先,就永远不可能有实例,而它不报错,只是永远空着
+ const [disjoint, setDisjoint] = useState<string[]>(existing?.disjoint ?? []);
// 从左栏点"+ 子类"进来时预填那个父。多父下它是第一个,也就是主父
useEffect(() => setParents(parentId ? [parentId] : []), [parentId]);
@@ -916,6 +949,7 @@ function ClassForm({
color,
shape,
parents,
+ disjoint,
description,
})
: api.createEntityType(kbId, {
@@ -924,6 +958,7 @@ function ClassForm({
color,
shape,
parents,
+ disjoint,
description,
}),
onSuccess: (res) => {
@@ -1030,6 +1065,33 @@ function ClassForm({
</p>
)}
</div>
+ {/* 互斥:**声明「不可能同时是」**。紧挨着父类,因为两者是同一件事的
+ 两面——父类说「也是」,互斥说「不可能同时是」,而一致性检查正是
+ 在这两者打架时报出「这个类永远不可能有实例」 */}
+ <div>
+ <label className={lbl}>{S.ontology.disjoint}</label>
+ <p className="text-[11px] leading-relaxed text-neutral-600 mb-1.5">
+ {S.ontology.disjointHint}
+ </p>
+ <MultiSearchSelect
+ values={disjoint}
+ options={parentOptions(allTypes, existing?.id)}
+ onToggle={(id) =>
+ setDisjoint((v) =>
+ v.includes(id) ? v.filter((x) => x !== id) : [...v, id],
+ )
+ }
+ placeholder={S.ontology.searchTypes}
+ emptyHint={S.ontology.noDisjoint}
+ />
+ {/* 跟自己的父类互斥 = 这个类永远不可能有实例。当场说,
+ 比让人跑一遍一致性检查再发现要快 */}
+ {disjoint.some((d) => parents.includes(d)) && (
+ <p className="mt-1.5 text-[11px] text-[var(--u-danger)]">
+ {S.ontology.disjointWithParent}
+ </p>
+ )}
+ </div>
<div>
<label className={lbl}>{S.ontology.description}</label>
{/* 语义指引:整段注入抽取 prompt,直接影响抽取归类质量 */}
@@ -1093,6 +1155,14 @@ function PropertyForm({
const [inverseFunctional, setInverseFunctional] = useState(
existing?.inverse_functional ?? false,
);
+ // 其余四条 OWL 公理。**推理机的判据全在这里**——从前只能靠导入 OWL 带进来,
+ // 在界面上手工建本体的人永远开不了那台机器(0002)
+ const [transitive, setTransitive] = useState(existing?.is_transitive ?? false);
+ const [symmetric, setSymmetric] = useState(existing?.is_symmetric ?? false);
+ const [asymmetric, setAsymmetric] = useState(existing?.is_asymmetric ?? false);
+ const [irreflexive, setIrreflexive] = useState(
+ existing?.is_irreflexive ?? false,
+ );
const [description, setDescription] = useState(existing?.description ?? "");
const [domains, setDomains] = useState<string[]>(existing?.domains ?? []);
const [ranges, setRanges] = useState<string[]>(existing?.ranges ?? []);
@@ -1116,6 +1186,10 @@ function PropertyForm({
temporal,
functional,
inverse_functional: inverseFunctional,
+ is_transitive: transitive,
+ is_symmetric: symmetric,
+ is_asymmetric: asymmetric,
+ is_irreflexive: irreflexive,
description,
domains,
ranges,
@@ -1126,6 +1200,10 @@ function PropertyForm({
temporal,
functional,
inverse_functional: inverseFunctional,
+ is_transitive: transitive,
+ is_symmetric: symmetric,
+ is_asymmetric: asymmetric,
+ is_irreflexive: irreflexive,
description,
domains,
ranges,
@@ -1228,22 +1306,61 @@ function PropertyForm({
]}
/>
</div>
- <label className="flex items-center gap-2 text-sm text-neutral-300">
- <input
- type="checkbox"
- checked={functional}
- onChange={(e) => setFunctional(e.target.checked)}
- />
- {S.ontology.functional}
- </label>
- <label className="flex items-center gap-2 text-sm text-neutral-300">
- <input
- type="checkbox"
- checked={inverseFunctional}
- onChange={(e) => setInverseFunctional(e.target.checked)}
- />
- {S.ontology.inverseFunctional}
- </label>
+ {/* 六条公理并成一组。**它们本来就是同一族**——推理机(0002)拿它们当
+ 判据,散在表单各处会让人以为前两条和后四条是两回事。
+ 每一条底下写清「勾了会发生什么」:这些开关不是描述,是会改变系统行为的
+ 声明——`functional` 让时态引擎自动闭合旧值,`transitive` 让推理机往图里
+ 加边。看不出后果的开关,人只会照着直觉乱勾。 */}
+ <div>
+ <label className={lbl}>{S.ontology.axioms}</label>
+ <p className="text-[11px] leading-relaxed text-neutral-600 mb-1.5">
+ {S.ontology.axiomsHint}
+ </p>
+ <div className="space-y-1.5">
+ {(
+ [
+ [functional, setFunctional, S.ontology.functional, S.ontology.functionalHint],
+ [
+ inverseFunctional,
+ setInverseFunctional,
+ S.ontology.inverseFunctional,
+ S.ontology.inverseFunctionalHint,
+ ],
+ [transitive, setTransitive, S.ontology.transitive, S.ontology.transitiveHint],
+ [symmetric, setSymmetric, S.ontology.symmetric, S.ontology.symmetricHint],
+ [asymmetric, setAsymmetric, S.ontology.asymmetric, S.ontology.asymmetricHint],
+ [
+ irreflexive,
+ setIrreflexive,
+ S.ontology.irreflexive,
+ S.ontology.irreflexiveHint,
+ ],
+ ] as const
+ ).map(([on, set, title, hint], i) => (
+ <label key={i} className="flex items-start gap-2 cursor-pointer">
+ <input
+ type="checkbox"
+ className="mt-0.5 accent-[var(--u-accent)]"
+ checked={on}
+ onChange={(e) => set(e.target.checked)}
+ />
+ <span className="min-w-0">
+ <span className="block text-[13px] text-neutral-200">{title}</span>
+ <span className="block text-[11px] leading-relaxed text-neutral-500">
+ {hint}
+ </span>
+ </span>
+ </label>
+ ))}
+ </div>
+ {/* 对称与反对称同时勾是自相矛盾的(只对空关系成立)。本体自洽性检查
+ 会报出来,但在这里当场说一句比让人跑一遍检查再发现要快 */}
+ {symmetric && asymmetric && (
+ <p className="mt-1.5 text-[11px] text-[var(--u-danger)]">
+ {S.ontology.axiomConflict}
+ </p>
+ )}
+ </div>
<div>
<label className={lbl}>{S.ontology.description}</label>
<textarea
@@ -1281,6 +1398,248 @@ function PropertyForm({
/* ---------- 未匹配信号 + AI 建议 ---------- */
+
+/** 类型消解:把「大致对」的类换成更具体的那个。
+ *
+ * **两步走,跟本体导入同一个形状**:先看一遍会发生什么,再决定落不落。这里还多
+ * 一层理由——改类不进时间轴,不像事实改写那样在实体历史里自己显形,所以
+ * 「先看一眼」是唯一能看见它的时机。
+ *
+ * 跑完分三档,各有各的处置:自动改掉的(可整批撤销)、跨了分类轴留给人的、
+ * 裁决说「都不是」的。**最后那一档带着理由**——这一步押在「选择都不是是个
+ * 体面答案」上,不记理由,最大的那一档就是不透明的。
+ */
+function RefinePanel({
+ kbId,
+ onChanged,
+ onError,
+}: {
+ kbId: string;
+ onChanged: () => void;
+ onError: (e: Error) => void;
+}) {
+ const [preview, setPreview] = useState<TypeSuggestion[] | null>(null);
+ const [outcome, setOutcome] = useState<ResolutionOutcome | null>(null);
+
+ const look = useMutation({
+ mutationFn: () => api.typeResolutionPreview(kbId),
+ onSuccess: (d) => {
+ setPreview(d.items);
+ setOutcome(null);
+ },
+ onError,
+ });
+ const run = useMutation({
+ mutationFn: () => api.typeResolutionApply(kbId),
+ onSuccess: (d) => {
+ setOutcome(d);
+ setPreview(null);
+ onChanged();
+ },
+ onError,
+ });
+ const approve = useMutation({
+ mutationFn: (v: {
+ from_type_id: string;
+ to_type_id: string;
+ entity_ids: string[];
+ }) => api.approveRefinement(kbId, v),
+ onSuccess: () => {
+ toast.success(S.toast.saved);
+ onChanged();
+ },
+ onError,
+ });
+ const undo = useMutation({
+ mutationFn: (batch: string) => api.typeResolutionUndo(kbId, batch),
+ onSuccess: (d) => {
+ toast.success(S.ontology.refineUndone(d.reverted));
+ setOutcome(null);
+ onChanged();
+ },
+ onError,
+ });
+
+ const busy = look.isPending || run.isPending;
+
+ return (
+ <div className="space-y-4">
+ <div>
+ <h3 className="u-title text-lg mb-1">{S.ontology.refineTitle}</h3>
+ <p className="text-xs leading-relaxed text-neutral-500 max-w-xl">
+ {S.ontology.refineHint}
+ </p>
+ </div>
+
+ <div className="flex gap-2">
+ <button
+ className="u-btn text-xs"
+ disabled={busy}
+ onClick={() => look.mutate()}
+ >
+ {look.isPending ? S.ontology.refineLooking : S.ontology.refinePreview}
+ </button>
+ <button
+ className="u-btn u-btn-primary text-xs"
+ disabled={busy}
+ onClick={() => run.mutate()}
+ >
+ {run.isPending ? S.ontology.refineRunning : S.ontology.refineRun}
+ </button>
+ </div>
+
+ {/* ---- 只算不写的那一步 */}
+ {preview && (
+ <div className="space-y-2">
+ <p className="text-xs text-neutral-500">
+ {preview.length === 0
+ ? S.ontology.refineNothing
+ : S.ontology.refineCandidates(preview.length)}
+ </p>
+ {preview.map((s) => (
+ <div key={s.entity_id} className="glass rounded-xl p-3">
+ <div className="flex items-baseline gap-2 flex-wrap">
+ <span className="text-sm text-neutral-100">{s.name}</span>
+ <span className="text-[11px] text-neutral-500">
+ {s.coarse ?? S.graph.untyped}
+ </span>
+ {s.specific_type && (
+ <span className="text-[11px] text-[var(--u-warn)]">
+ {S.ontology.refineModelSays(s.specific_type)}
+ </span>
+ )}
+ <span className="ml-auto u-num text-[10.5px] text-neutral-600">
+ {S.review.factsCount(s.fact_count)}
+ </span>
+ </div>
+ {/* **把送去检索的那段字显示出来**:找不着的时候,第一个要看的
+ 就是我们拿什么去找的,而不是猜画像还是类描述的问题 */}
+ <p className="mt-1 text-[11px] text-neutral-500 line-clamp-2">
+ {s.profile}
+ </p>
+ <div className="mt-1.5 flex flex-wrap gap-1">
+ {s.candidates.slice(0, 6).map((c) => (
+ <span
+ key={c.id}
+ title={c.description}
+ className="u-chip u-chip-neutral u-num text-[10.5px]"
+ >
+ {c.label} {c.distance.toFixed(2)}
+ </span>
+ ))}
+ {s.candidates.length === 0 && (
+ <span className="text-[11px] text-neutral-600">
+ {S.ontology.refineNoCandidates}
+ </span>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* ---- 落库之后的三档 */}
+ {outcome && (
+ <div className="space-y-3">
+ <div className="flex items-center gap-3 flex-wrap">
+ <span className="text-xs text-neutral-300">
+ {S.ontology.refineRetyped(outcome.retyped)}
+ </span>
+ {outcome.batch && outcome.retyped > 0 && (
+ <button
+ className="u-btn u-btn-ghost text-xs"
+ disabled={undo.isPending}
+ onClick={() => undo.mutate(outcome.batch!)}
+ >
+ {S.ontology.refineUndo}
+ </button>
+ )}
+ </div>
+
+ {outcome.for_review.length > 0 && (
+ <div className="space-y-2">
+ <p className="text-xs text-neutral-500">
+ {S.ontology.refineForReview(outcome.for_review.length)}
+ </p>
+ {outcome.for_review.map((r) => (
+ <div key={r.entity_id} className="glass rounded-xl p-3">
+ <div className="flex items-baseline gap-2 flex-wrap">
+ <span className="text-sm text-neutral-100">{r.name}</span>
+ <span className="text-[11px] text-neutral-500">
+ {r.coarse ?? S.graph.untyped} → {r.choice}
+ </span>
+ {r.crosses_axis && (
+ <span className="u-chip u-chip-warn text-[10.5px]">
+ {S.ontology.refineCrossesAxis}
+ </span>
+ )}
+ <span className="ml-auto u-num text-[10.5px] text-neutral-600">
+ {Math.round(r.confidence * 100)}%
+ </span>
+ </div>
+ {r.reason && (
+ <p className="mt-1 text-[11px] text-neutral-500">
+ {r.reason}
+ </p>
+ )}
+ {/* **认可的是这一对类,不是这一个实体。** 认可一次,
+ 之后同一对不再进人工——那正是这一档大部分条目的成因 */}
+ {r.from_type_id && (
+ <button
+ className="u-btn u-btn-primary mt-2 text-xs"
+ disabled={approve.isPending}
+ onClick={() =>
+ approve.mutate({
+ from_type_id: r.from_type_id!,
+ to_type_id: r.to_type_id,
+ entity_ids: [r.entity_id],
+ })
+ }
+ >
+ {S.ontology.refineApprovePair}
+ </button>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+
+ {outcome.left_alone.length > 0 && (
+ <div className="space-y-1.5">
+ <p className="text-xs text-neutral-500">
+ {S.ontology.refineLeftAlone(outcome.left_alone.length)}
+ </p>
+ {outcome.left_alone.map((d, i) => (
+ <div key={i} className="glass rounded-xl px-3 py-2">
+ <div className="flex items-baseline gap-2 flex-wrap">
+ <span className="text-[13px] text-neutral-200">
+ {d.name}
+ </span>
+ <span className="text-[11px] text-neutral-500">
+ {d.coarse ?? S.graph.untyped}
+ </span>
+ </div>
+ {/* 理由与头一个候选一起给:理由说不通时,看候选就知道是
+ 检索没找着还是裁决没看上 */}
+ {d.reason && (
+ <p className="mt-0.5 text-[11px] text-neutral-500">
+ {d.reason}
+ </p>
+ )}
+ {d.top_candidate && (
+ <p className="mt-0.5 text-[11px] text-neutral-600">
+ {S.ontology.refineTopCandidate(d.top_candidate)}
+ </p>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
function MissesPanel({
kbId,
misses,
diff --git a/web/src/pages/Review.tsx b/web/src/pages/Review.tsx
index 1fe5738b..15907e4d 100644
--- a/web/src/pages/Review.tsx
+++ b/web/src/pages/Review.tsx
@@ -2,6 +2,9 @@ import { useEffect, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
api,
+ type AxiomViolation,
+ type ReviewQueue,
+ type OntologyDefect,
type ConceptMapping,
type ConflictItem,
type FactReviewItem,
@@ -12,7 +15,7 @@ import {
} from "../api";
import { S } from "../i18n";
import { useKb } from "../kb";
-import { Chip, type ChipTone, Pager, RAIL_CLS, pageSlice, cn } from "../ui";
+import { Chip, type ChipTone, Pager, RAIL_CLS, cn } from "../ui";
const DUP_PAGE = 6;
const FACT_PAGE = 10;
@@ -443,6 +446,138 @@ function DecisionRow({ e }: { e: ReviewHistoryEvent }) {
*
* 展示的重点是**「这个数怎么算」**——SQL / 表达式 / 表名按这个优先级取一个,
* 因为人要判断的正是它对不对。概念名与源是身份,unit 是答里必须带的量纲。 */
+/** 本体自己的一处自相矛盾。**两个按钮而不是三个**——这一档压根没看数据,
+ * 所以没有「数据错了」这条出路,只能是「我去改了本体」或「先放着」。 */
+function DefectRow({
+ defect: d,
+ busy,
+ onDecide,
+}: {
+ defect: OntologyDefect;
+ busy: boolean;
+ onDecide: (resolution: "fixed" | "accepted") => void;
+}) {
+ const what = {
+ symmetric_and_asymmetric: S.review.defectSymAsym,
+ transitive_and_functional: S.review.defectTransFunc,
+ subclass_cycle: S.review.defectCycle,
+ disjoint_with_ancestor: S.review.defectDisjointAncestor,
+ inherits_disjoint: S.review.defectInheritsDisjoint,
+ }[d.kind];
+ // 后两类的后果值得写出来:不可满足的类不会报错,它只是永远空着
+ const unsatisfiable =
+ d.kind === "disjoint_with_ancestor" || d.kind === "inherits_disjoint";
+ return (
+ <div className="glass rounded-xl p-3">
+ <div className="flex items-baseline gap-2 flex-wrap">
+ <span className="text-sm text-[var(--u-danger)]">{what}</span>
+ {d.subject_label && (
+ <span className="text-xs text-neutral-300">{d.subject_label}</span>
+ )}
+ {d.other_label && (
+ <span className="text-xs text-neutral-500">↔ {d.other_label}</span>
+ )}
+ </div>
+ {d.path_labels.length > 0 && (
+ <div className="mt-1 text-xs text-neutral-400">
+ {d.path_labels.join(" → ")} → {d.path_labels[0]}
+ </div>
+ )}
+ {unsatisfiable && (
+ <p className="mt-1 text-xs text-neutral-500">
+ {S.review.defectNeverInstantiable}
+ </p>
+ )}
+ <div className="mt-2 flex gap-1.5">
+ <button
+ className="u-btn text-xs"
+ disabled={busy}
+ onClick={() => onDecide("accepted")}
+ >
+ {S.review.defectAccepted}
+ </button>
+ <button
+ className="u-btn u-btn-primary text-xs"
+ disabled={busy}
+ onClick={() => onDecide("fixed")}
+ >
+ {S.review.defectFixed}
+ </button>
+ </div>
+ </div>
+ );
+}
+
+/** 一处公理违规。**三个按钮而不是两个**——第三个是这一档独有的出路:
+ * 矛盾可能出在定义上(用户导的本体把某个属性声明成反对称,而他的语料里
+ * 那关系其实双向),这时该改的是本体,不是二十条事实。 */
+function ViolationRow({
+ violation: v,
+ busy,
+ onDecide,
+}: {
+ violation: AxiomViolation;
+ busy: boolean;
+ onDecide: (
+ resolution: "fact_retracted" | "axiom_relaxed" | "accepted",
+ ) => void;
+}) {
+ const what = {
+ self_loop: S.review.violationSelfLoop,
+ asymmetry: S.review.violationAsymmetry,
+ cycle: S.review.violationCycle,
+ functional: S.review.violationFunctional,
+ }[v.kind];
+ // 自反那一类两条事实是同一条——显示一遍就够,显示两遍像个 bug
+ const single = v.left_fact === v.right_fact;
+ return (
+ <div className="glass rounded-xl p-3">
+ <div className="flex items-baseline gap-2 flex-wrap">
+ <span className="text-sm text-[var(--u-warn)]">{what}</span>
+ {v.predicate && (
+ <span className="text-[11px] text-neutral-500">
+ {S.review.violationVia(v.predicate)}
+ </span>
+ )}
+ {v.path_len > 0 && (
+ <span className="text-[11px] text-neutral-500">
+ {S.review.violationPath(v.path_len)}
+ </span>
+ )}
+ </div>
+ <div className="mt-1.5 space-y-1">
+ <div className="text-xs text-neutral-300">{v.left_text}</div>
+ {!single && (
+ <div className="text-xs text-neutral-300">{v.right_text}</div>
+ )}
+ </div>
+ <div className="mt-2 flex gap-1.5 flex-wrap">
+ <button
+ className="u-btn text-xs"
+ disabled={busy}
+ onClick={() => onDecide("accepted")}
+ >
+ {S.review.acceptBoth}
+ </button>
+ <button
+ className="u-btn text-xs"
+ disabled={busy}
+ onClick={() => onDecide("axiom_relaxed")}
+ >
+ {S.review.relaxAxiom}
+ </button>
+ <button
+ className="u-btn u-btn-primary text-xs"
+ disabled={busy}
+ onClick={() => onDecide("fact_retracted")}
+ >
+ {S.review.retractFact}
+ </button>
+ </div>
+ </div>
+ );
+}
+
function MappingRow({
mapping: m,
busy,
@@ -500,15 +635,34 @@ type Sel =
// 语义层的待表态映射(0011)。从前它借「低置信事实」那一档露面——
// 靠 0.6 的置信度混进去,而它根本不是一条关于世界的断言
| "mappings"
+ // 公理违规(0002 R0)。**与 conflicts 分开**:那一档问「哪条对」,
+ // 这一档还可能答「公理写错了」——出路不同
+ | "violations"
+ // 本体自己的自相矛盾。**与 violations 分开**:那一档看事实,这一档只看定义
+ | "defects"
| "decisions"
| "merges";
+/** 走服务端分页的那几档(决策台账另有自己的接口) */
+const QUEUE_FETCHED: ReviewQueue[] = [
+ "duplicates",
+ "conflicts",
+ "unconfirmed",
+ "lowconf",
+ "mappings",
+ "violations",
+ "defects",
+ "merges",
+];
+
const QUEUE_ORDER: Sel[] = [
"duplicates",
"conflicts",
"unconfirmed",
"lowconf",
"mappings",
+ "violations",
+ "defects",
];
const PAGE_SIZE: Record<Sel, number> = {
duplicates: DUP_PAGE,
@@ -516,6 +670,8 @@ const PAGE_SIZE: Record<Sel, number> = {
unconfirmed: FACT_PAGE,
lowconf: FACT_PAGE,
mappings: FACT_PAGE,
+ violations: FACT_PAGE,
+ defects: FACT_PAGE,
merges: MERGE_PAGE,
decisions: 20,
};
@@ -570,11 +726,22 @@ export function Review() {
const [sel, setSel] = useState<Sel | null>(null);
const [page, setPage] = useState(0);
- // 队列变化经 SSE 事件流推送(useKbEvents 挂在 Shell),无需轮询
+ // 队列变化经 SSE 事件流推送(useKbEvents 挂在 Shell),无需轮询。
+ //
+ // **按分档 + 页码取**:从前一次把八个队列全端回来、每档 100 条、客户端分页,
+ // 于是左栏的徽标是截断后的数字,第十一页之后的东西界面上不存在。现在计数
+ // 每次都回(服务端 COUNT,不受一页多少条影响),内容只回当前这一档的一页。
+ const queueSel: ReviewQueue = QUEUE_FETCHED.includes(
+ (sel ?? "duplicates") as ReviewQueue,
+ )
+ ? ((sel ?? "duplicates") as ReviewQueue)
+ : "duplicates";
const review = useQuery({
- queryKey: ["review", kb?.id],
- queryFn: () => api.review(kb!.id),
+ queryKey: ["review", kb?.id, queueSel, page],
+ queryFn: () => api.review(kb!.id, queueSel, PAGE_SIZE[queueSel], page * PAGE_SIZE[queueSel]),
enabled: !!kb,
+ // 翻页时别把上一页闪成空白——计数与骨架都还在,只有条目在换
+ placeholderData: (prev) => prev,
});
// 决策台账:服务端分页,仅选中时拉取
const history = useQuery({
@@ -617,6 +784,32 @@ export function Review() {
}) => api.decideMapping(kb!.id, id, status),
onSettled: invalidate,
});
+ const defectAction = useMutation({
+ mutationFn: ({
+ id,
+ resolution,
+ }: {
+ id: string;
+ resolution: "fixed" | "accepted";
+ }) => api.decideDefect(kb!.id, id, resolution),
+ onSettled: invalidate,
+ });
+ const violationAction = useMutation({
+ mutationFn: ({
+ id,
+ resolution,
+ }: {
+ id: string;
+ resolution: "fact_retracted" | "axiom_relaxed" | "accepted";
+ }) => api.decideViolation(kb!.id, id, resolution),
+ onSettled: invalidate,
+ });
+ // 检查是同步的纯计算,所以直接 mutate 不排队。跑完把报告留在按钮旁边——
+ // **零和零不一样**:没有公理时要说「无从判起」,不能说「未发现矛盾」
+ const runCheck = useMutation({
+ mutationFn: () => api.runConsistencyCheck(kb!.id),
+ onSettled: invalidate,
+ });
const revert = useMutation({
mutationFn: (mergeId: string) => api.revertMerge(kb!.id, mergeId),
onSettled: invalidate,
@@ -640,24 +833,38 @@ export function Review() {
onSettled: invalidate,
});
- const data = review.data;
+ // **徽标读服务端的 COUNT,不读列表长度。** 这是从前那个「库里 164、界面写
+ // 100」的根源:数组长度反映的是一页多少条,不是库里有多少条。
+ const c = review.data?.counts;
const counts: Record<Sel, number> = {
- duplicates: data?.reviews.length ?? 0,
- conflicts: data?.conflicts?.length ?? 0,
- unconfirmed: data?.unconfirmed?.length ?? 0,
- lowconf: data?.facts.length ?? 0,
- mappings: data?.mappings?.length ?? 0,
- merges: data?.merges.length ?? 0,
+ duplicates: c?.duplicates ?? 0,
+ conflicts: c?.conflicts ?? 0,
+ unconfirmed: c?.unconfirmed ?? 0,
+ lowconf: c?.lowconf ?? 0,
+ mappings: c?.mappings ?? 0,
+ violations: c?.violations ?? 0,
+ defects: c?.defects ?? 0,
+ merges: c?.merges ?? 0,
decisions: history.data?.total ?? 0,
};
+ // 当前这一档的一页。**服务端已经切好了**,这里只按档收窄类型——
+ // 收窄错了会在渲染时露馅,而不是悄悄显示空列表
+ const rows = review.data?.queue === queueSel ? (review.data.items ?? []) : [];
+ const asDuplicates = () => rows as ReviewItem[];
+ const asFacts = () => rows as FactReviewItem[];
+ const asConflicts = () => rows as ConflictItem[];
+ const asMappings = () => rows as ConceptMapping[];
+ const asViolations = () => rows as AxiomViolation[];
+ const asDefects = () => rows as OntologyDefect[];
+ const asMerges = () => rows as MergeLog[];
const queueEmpty = QUEUE_ORDER.every((k) => counts[k] === 0);
// 首批数据到达:定位到第一个非空队列(全空落在 duplicates 显示"干净"文案)
useEffect(() => {
- if (sel === null && data)
+ if (sel === null && c)
setSel(QUEUE_ORDER.find((k) => counts[k] > 0) ?? "duplicates");
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [data]);
+ }, [c]);
const select = (s: Sel) => {
setSel(s);
@@ -679,6 +886,11 @@ export function Review() {
hint: S.review.lowConfidenceHint,
},
mappings: { title: S.review.mappings, hint: S.review.mappingsHint },
+ violations: {
+ title: S.review.violations,
+ hint: S.review.violationsHint,
+ },
+ defects: { title: S.review.defects, hint: S.review.defectsHint },
decisions: { title: S.review.decisionsTitle, hint: S.review.decisionsHint },
merges: { title: S.review.mergeHistory, hint: null },
};
@@ -719,6 +931,18 @@ export function Review() {
count={counts.mappings}
onClick={() => select("mappings")}
/>
+ <RailItem
+ active={active === "violations"}
+ label={S.review.railViolations}
+ count={counts.violations}
+ onClick={() => select("violations")}
+ />
+ <RailItem
+ active={active === "defects"}
+ label={S.review.railDefects}
+ count={counts.defects}
+ onClick={() => select("defects")}
+ />
</div>
<RailHeader label={S.review.tabHistory} />
<div className="px-2 space-y-0.5">
@@ -749,7 +973,7 @@ export function Review() {
</p>
)}
- {data && (
+ {review.data && (
<section>
{/* 页级标题:与 Library/KB Settings 同级(text-lg),不是卡片头 */}
<h2 className="u-title text-lg mb-1">{SECTION[active].title}</h2>
@@ -759,8 +983,12 @@ export function Review() {
</p>
)}
- {/* 空态:整个待办全清 vs 单类清空 */}
- {isQueueSel && counts[active] === 0 && (
+ {/* 空态:整个待办全清 vs 单类清空。**公理这一档除外**——它自己那句要
+ 分清「查过、没矛盾」和「还没查过」,通用空态说不出这个差别 */}
+ {isQueueSel &&
+ active !== "violations" &&
+ active !== "defects" &&
+ counts[active] === 0 && (
<div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">
{queueEmpty ? S.review.empty : S.review.categoryEmpty}
</div>
@@ -768,7 +996,7 @@ export function Review() {
{active === "duplicates" && counts.duplicates > 0 && (
<div className="space-y-3">
- {pageSlice(data.reviews, page, DUP_PAGE).rows.map((item) => (
+ {asDuplicates().map((item) => (
<DuplicateCard
key={item.id}
item={item}
@@ -785,7 +1013,7 @@ export function Review() {
{active === "conflicts" && counts.conflicts > 0 && (
<div className="space-y-3">
- {pageSlice(data.conflicts, page, CONFLICT_PAGE).rows.map(
+ {asConflicts().map(
(c) => (
<ConflictRow
key={c.id}
@@ -805,7 +1033,7 @@ export function Review() {
{active === "unconfirmed" && counts.unconfirmed > 0 && (
<div className="space-y-3">
- {pageSlice(data.unconfirmed, page, FACT_PAGE).rows.map(
+ {asFacts().map(
(fact) => (
<UnconfirmedRow
key={fact.id}
@@ -830,7 +1058,7 @@ export function Review() {
{active === "lowconf" && counts.lowconf > 0 && (
<div className="space-y-3">
- {pageSlice(data.facts, page, FACT_PAGE).rows.map((fact) => (
+ {asFacts().map((fact) => (
<FactRow
key={fact.id}
fact={fact}
@@ -851,7 +1079,7 @@ export function Review() {
{active === "mappings" && counts.mappings > 0 && (
<div className="space-y-3">
- {pageSlice(data.mappings ?? [], page, FACT_PAGE).rows.map(
+ {asMappings().map(
(m) => (
<MappingRow
key={m.id}
@@ -869,6 +1097,83 @@ export function Review() {
</div>
)}
+ {active === "defects" && (
+ <div className="space-y-3">
+ {counts.defects === 0 && (
+ <div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">
+ {S.review.categoryEmpty}
+ </div>
+ )}
+ {asDefects().map(
+ (d) => (
+ <DefectRow
+ key={d.id}
+ defect={d}
+ busy={
+ defectAction.isPending &&
+ defectAction.variables?.id === d.id
+ }
+ onDecide={(resolution) =>
+ defectAction.mutate({ id: d.id, resolution })
+ }
+ />
+ ),
+ )}
+ </div>
+ )}
+
+ {active === "violations" && (
+ <div className="space-y-3">
+ {/* 按钮在这一档里,不在页头:只有看这一档的人才想重跑。
+ 报告留在按钮旁边——空结果要说清是「没矛盾」还是「没判据」 */}
+ <div className="flex items-center gap-3">
+ <button
+ className="u-btn u-btn-primary text-xs"
+ disabled={runCheck.isPending}
+ onClick={() => runCheck.mutate()}
+ >
+ {runCheck.isPending
+ ? S.review.checking
+ : S.review.runCheck}
+ </button>
+ {runCheck.data && (
+ <span className="text-xs text-neutral-500">
+ {/* 三种结果说三句话。**`found` 不是要报的数**:
+ 重跑会把已裁决的那些重新算出来,说「3 处矛盾」而
+ 列表只剩一条,看起来像界面漏了东西 */}
+ {runCheck.data.predicates_with_axioms === 0
+ ? S.review.checkNoAxioms
+ : runCheck.data.inserted > 0
+ ? S.review.checkFound(runCheck.data.inserted)
+ : runCheck.data.found > 0
+ ? S.review.checkNothingNew
+ : S.review.checkClean(runCheck.data.edges)}
+ </span>
+ )}
+ </div>
+ {counts.violations === 0 && !runCheck.data && (
+ <div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">
+ {S.review.checkNeverRun}
+ </div>
+ )}
+ {asViolations().map(
+ (v) => (
+ <ViolationRow
+ key={v.id}
+ violation={v}
+ busy={
+ violationAction.isPending &&
+ violationAction.variables?.id === v.id
+ }
+ onDecide={(resolution) =>
+ violationAction.mutate({ id: v.id, resolution })
+ }
+ />
+ ),
+ )}
+ </div>
+ )}
+
{active === "merges" &&
(counts.merges === 0 ? (
<div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">
@@ -876,7 +1181,7 @@ export function Review() {
</div>
) : (
<div className="space-y-2">
- {pageSlice(data.merges, page, MERGE_PAGE).rows.map((m) => (
+ {asMerges().map((m) => (
<MergeRow
key={m.id}
merge={m}
diff --git a/web/src/pages/Shell.tsx b/web/src/pages/Shell.tsx
index 51bb07a3..6020c409 100644
--- a/web/src/pages/Shell.tsx
+++ b/web/src/pages/Shell.tsx
@@ -1,3 +1,4 @@
+import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { Link, Outlet, useNavigate, useRouterState } from "@tanstack/react-router";
import {
@@ -50,6 +51,13 @@ export function Shell() {
// 告警流是全局的:角标跨库,而系统级告警根本没有库
useAlertEvents();
+ // 未登录就去登录页。**副作用要在 effect 里**,理由见下面 401 那一支
+ const unauthorized =
+ me.isError && me.error instanceof ApiError && me.error.status === 401;
+ useEffect(() => {
+ if (unauthorized) navigate({ to: "/login" });
+ }, [unauthorized, navigate]);
+
if (me.isPending) {
return (
<div className="min-h-screen flex items-center justify-center text-neutral-500 text-sm">
@@ -59,8 +67,11 @@ export function Shell() {
}
if (me.isError) {
+ // **跳转在 effect 里做,不在渲染里。** 渲染期间调 `navigate` 是在别人渲染
+ // 的过程中改路由器的状态,React 会常驻一条「Cannot update a component
+ // while rendering a different component」的警告。今天不出错,但它是
+ // 「渲染顺序依赖」的味道——改布局时最容易在这种地方变成真 bug
if (me.error instanceof ApiError && me.error.status === 401) {
- navigate({ to: "/login" });
return null;
}
return <ServerDown />;
diff --git a/web/src/pages/SourcesRail.tsx b/web/src/pages/SourcesRail.tsx
index 09962645..8ddaaacd 100644
--- a/web/src/pages/SourcesRail.tsx
+++ b/web/src/pages/SourcesRail.tsx
@@ -136,18 +136,23 @@ export function SourcesRail({
/** 缺省时隐藏 "+"(如文档查看页) */
onAdd?: () => void;
}) {
+ // 左栏只要两个数:整库多少篇、没有来源的多少篇。**各取一页零条**——
+ // 统计随响应回来,不必把文档拉下来数
const docs = useQuery({
- queryKey: ["documents", kbId],
- queryFn: () => api.documents(kbId),
+ queryKey: ["docCount", kbId],
+ queryFn: () => api.documents(kbId, { limit: 1, offset: 0 }),
+ });
+ const uploads = useQuery({
+ queryKey: ["docCount", kbId, "uploads"],
+ queryFn: () => api.documents(kbId, { source: "none", limit: 1, offset: 0 }),
});
const sources = useQuery({
queryKey: ["sources", kbId],
queryFn: () => api.sources(kbId),
});
- const allDocs = docs.data ?? [];
const sourceList = sources.data?.sources ?? [];
- const uploadsCount = allDocs.filter((d) => !d.source_id).length;
+ const uploadsCount = uploads.data?.total ?? 0;
return (
<aside className={`${RAIL_CLS} flex flex-col`}>
@@ -158,7 +163,7 @@ export function SourcesRail({
onClick={() => onSelect("all")}
icon={<LibraryIcon size={14} />}
label={S.library.allDocs}
- count={allDocs.length}
+ count={docs.data?.total ?? 0}
/>
</div>
<div className="flex items-center justify-between px-4 pt-3 pb-1.5">
diff --git a/web/src/useKbEvents.ts b/web/src/useKbEvents.ts
index 17a006ae..f7d8bbe6 100644
--- a/web/src/useKbEvents.ts
+++ b/web/src/useKbEvents.ts
@@ -13,6 +13,9 @@ export function useKbEvents(kbId: string | undefined) {
queryClient.invalidateQueries({ queryKey: ["documents", kbId] });
queryClient.invalidateQueries({ queryKey: ["graph"] });
});
+ es.addEventListener("graph", () => {
+ queryClient.invalidateQueries({ queryKey: ["graph"] });
+ });
es.addEventListener("review", () => {
queryClient.invalidateQueries({ queryKey: ["review", kbId] });
});