Skip to content

World's first open-source enterprise world model.

One signature check, wherever a fact gets a predicate or a new subject (#199)

WaylandYangc9699b4de464
diff --git a/crates/utopia-reason/src/lib.rs b/crates/utopia-reason/src/lib.rs
index f4939003..b12b6528 100644
--- a/crates/utopia-reason/src/lib.rs
+++ b/crates/utopia-reason/src/lib.rs
@@ -78,6 +78,13 @@ pub enum Kind {
/// 同一主语与谓词同时指向两个宾语,而 p 声明了 functional
/// (inverse_functional 则是同一宾语被两个主语指)
Functional,
+ /// `A p B`,而 A 不在 p 声明的 domain 里、或 B 不在 range 里(#190 / #196)。
+ ///
+ /// **这一类不由本 crate 算出**:它要看实体的类型与 domain / range 的闭包,那是
+ /// 库里的东西,`utopia-store::reasoning::signature_breaks` 用 SQL 量。列在这里
+ /// 是为了与其它四类走同一条落库、清陈、裁决的路——left 与 right 同一条事实,
+ /// 与自反那类同款
+ Signature,
}
impl Kind {
@@ -87,6 +94,7 @@ impl Kind {
Kind::Asymmetry => "asymmetry",
Kind::Cycle => "cycle",
Kind::Functional => "functional",
+ Kind::Signature => "signature",
}
}
}
diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rs
index c96473ee..a969052d 100644
--- a/crates/utopia-server/src/api/ontology_routes.rs
+++ b/crates/utopia-server/src/api/ontology_routes.rs
@@ -1006,7 +1006,12 @@ pub async fn adopt_predicate(
// 这里的 forms 是人在面板上勾的,完全可能同时勾了 `produced` 和 `produced_by`,
// 而一个 swap 标志伺候不了混合。自动那条路不存在这个问题:同组说法共享屈折基,
// 结尾有没有 `by` 必然一致。真要修得让 adopt 逐条判方向,那是另一件事。
- let (batch_id, remapped) = utopia_store::graph::adopt_proposed_predicates(
+ let utopia_store::graph::Adopted {
+ batch_id,
+ moved: remapped,
+ left_off,
+ corrected,
+ } = utopia_store::graph::adopt_proposed_predicates(
&state.pool,
kb_id,
predicate_id,
@@ -1027,14 +1032,16 @@ pub async fn adopt_predicate(
Some(predicate_id),
json!({
"key": key, "label": req.label, "forms": req.forms,
- "facts_remapped": remapped, "batch": batch_id,
+ "facts_remapped": remapped, "facts_left_off": left_off,
+ "facts_direction_corrected": corrected, "batch": batch_id,
}),
)
.await;
state.emit_review(kb_id);
- Ok(Json(
- json!({ "id": predicate_id, "remapped": remapped, "batch": batch_id }),
- ))
+ Ok(Json(json!({
+ "id": predicate_id, "remapped": remapped, "left_off": left_off,
+ "corrected": corrected, "batch": batch_id,
+ })))
}
/// 撤销一次采纳:新写的行作废、旧行复活。关系类型留着(有事实指向过它,
@@ -1372,8 +1379,12 @@ pub(crate) async fn adopt_attribute_core(
None => unconvertible += 1,
}
}
- let (batch_id, remapped) =
- utopia_store::graph::adopt_value_facts(&state.pool, kb_id, attribute_id, &rewrites).await?;
+ // 属性那一路没有签名可判(宾语是字面值),`left_off` 恒为 0
+ let utopia_store::graph::Adopted {
+ batch_id,
+ moved: remapped,
+ ..
+ } = utopia_store::graph::adopt_value_facts(&state.pool, kb_id, attribute_id, &rewrites).await?;
for form in spec.forms {
let _ =
utopia_store::ontology::clear_miss(&state.pool, kb_id, "attribute_type", form).await;
diff --git a/crates/utopia-server/src/bootstrap_ontology.rs b/crates/utopia-server/src/bootstrap_ontology.rs
index 3b76f7a2..c0240f68 100644
--- a/crates/utopia-server/src/bootstrap_ontology.rs
+++ b/crates/utopia-server/src/bootstrap_ontology.rs
@@ -160,6 +160,7 @@ pub async fn bootstrap_ontology(state: &AppState, kb_id: Uuid) -> anyhow::Result
let mut added_relations = Vec::new();
let mut added_classes = Vec::new();
let mut moved_total = 0u32;
+ let mut left_off_total = 0u32;
let mut batches = Vec::new();
for p in &classes {
@@ -268,7 +269,12 @@ pub async fn bootstrap_ontology(state: &AppState, kb_id: Uuid) -> anyhow::Result
}
}
};
- let (batch, moved) = utopia_store::graph::adopt_proposed_predicates(
+ let utopia_store::graph::Adopted {
+ batch_id: batch,
+ moved,
+ left_off,
+ corrected,
+ } = utopia_store::graph::adopt_proposed_predicates(
&state.pool,
kb_id,
predicate_id,
@@ -277,11 +283,12 @@ pub async fn bootstrap_ontology(state: &AppState, kb_id: Uuid) -> anyhow::Result
)
.await?;
tracing::info!(
- %kb_id, key = %g.key, forms = ?g.forms, docs = g.docs, facts = g.facts, moved,
- reused = g.existing.is_some(), swap,
+ %kb_id, key = %g.key, forms = ?g.forms, docs = g.docs, facts = g.facts, moved, left_off,
+ corrected, reused = g.existing.is_some(), swap,
"按票数采纳关系"
);
moved_total += moved;
+ left_off_total += left_off;
if moved > 0 {
batches.push(batch);
}
@@ -392,7 +399,12 @@ pub async fn bootstrap_ontology(state: &AppState, kb_id: Uuid) -> anyhow::Result
};
// LLM 的 map_to 提案同样可能混着主动与被动,一个 swap 标志伺候不了
//(同人工路径,见 ontology_routes 里那段注释)
- let (batch, moved) = utopia_store::graph::adopt_proposed_predicates(
+ let utopia_store::graph::Adopted {
+ batch_id: batch,
+ moved,
+ left_off,
+ corrected,
+ } = utopia_store::graph::adopt_proposed_predicates(
&state.pool,
kb_id,
predicate_id,
@@ -400,6 +412,11 @@ pub async fn bootstrap_ontology(state: &AppState, kb_id: Uuid) -> anyhow::Result
false,
)
.await?;
+ tracing::info!(
+ %kb_id, key, forms = ?forms, moved, left_off, corrected,
+ "按映射提案采纳关系"
+ );
+ left_off_total += left_off;
moved_total += moved;
if moved > 0 {
batches.push(batch);
@@ -437,6 +454,8 @@ pub async fn bootstrap_ontology(state: &AppState, kb_id: Uuid) -> anyhow::Result
"relations": added_relations,
"classes": added_classes,
"facts_remapped": moved_total,
+ // 签名两边都对不上、没挂上谓词的(#190)。不报这个数,「改写了 N 条」就是报喜不报忧
+ "facts_left_off": left_off_total,
"batches": batches,
}),
)
diff --git a/crates/utopia-server/src/extraction.rs b/crates/utopia-server/src/extraction.rs
index 8aaf40b3..087ff453 100644
--- a/crates/utopia-server/src/extraction.rs
+++ b/crates/utopia-server/src/extraction.rs
@@ -1025,13 +1025,20 @@ async fn run(state: &AppState, document_id: Uuid, proposed_by: Option<Uuid>) ->
// 那份只覆盖模型在这一块里声明过的实体,而宾语常是别处已存在的实体,
// 这一块没重新声明它,于是查不到、判不了、掰不动。实测差别不小——
// 用声明那份时反向只降到 7.0%,剩下的正是宾语类型查不到的那些
- let s_fits =
- utopia_store::ontology::entity_fits_domain(&state.pool, pid, subject_id).await;
- if let Ok(Some(false)) = s_fits {
- let o_fits =
- utopia_store::ontology::entity_fits_domain(&state.pool, pid, object_id)
- .await;
- if let Ok(Some(true)) = o_fits {
+ //
+ // 判断本身在 store(`ontology::judge_direction`),**与采纳共用**(#190):
+ // 写谓词的路不止这一条,守卫只装在一条上就等于没装。查不出来(库错)
+ // 按没有判据处理,照原样落——宁可少掰一条,不能因为一次查询失败丢事实
+ let fit = utopia_store::ontology::judge_direction(
+ &state.pool,
+ pid,
+ subject_id,
+ object_id,
+ )
+ .await
+ .unwrap_or(utopia_store::ontology::Fit::Unchecked);
+ match fit {
+ utopia_store::ontology::Fit::Swap => {
drop_signal(
state,
doc.kb_id,
@@ -1048,7 +1055,8 @@ async fn run(state: &AppState, document_id: Uuid, proposed_by: Option<Uuid>) ->
)
.await;
(Some(pid), object_id, subject_id)
- } else {
+ }
+ utopia_store::ontology::Fit::Neither => {
// **对调也不合法 → 退回没有谓词。**
//
// 这不是方向问题,是这个关系压根不适用:schema.org 的
@@ -1077,8 +1085,9 @@ async fn run(state: &AppState, document_id: Uuid, proposed_by: Option<Uuid>) ->
.await;
(None, subject_id, object_id)
}
- } else {
- (Some(pid), subject_id, object_id)
+ utopia_store::ontology::Fit::Keep | utopia_store::ontology::Fit::Unchecked => {
+ (Some(pid), subject_id, object_id)
+ }
}
} else {
(predicate_id, subject_id, object_id)
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index c080fa49..741e93f9 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -1231,10 +1231,29 @@ pub async fn adopt_proposed_predicates(
predicate_id: Uuid,
forms: &[String],
swap: bool,
-) -> AppResult<(Uuid, u32)> {
+) -> AppResult<Adopted> {
adopt(pool, kb_id, predicate_id, AdoptTargets::ByForm(forms), swap).await
}
+/// 一次采纳的账。`left_off` 必须往上传:改写了 20 条、留下 3 条,只报前半句是报喜不报忧。
+#[derive(Debug, Clone, Copy)]
+pub struct Adopted {
+ pub batch_id: Uuid,
+ /// 改写过去的条数
+ pub moved: u32,
+ /// 签名两边都对不上、**没有**挂上谓词的条数(#190)。它们照旧留在空谓词上,
+ /// 原文说法还在证据里——与抽取遇到同样情形的处置一致
+ pub left_off: u32,
+ /// 按签名对调了主宾的条数。
+ ///
+ /// **掰正不该静默。** 抽取那条路每掰一次就落一条 `direction_corrected`
+ /// 丢弃信号(#138 的原话是「绝不静默」:用可能错的声明驱动的自动动作,
+ /// 留痕才不属于 0001 判据 2 反对的那一类)。采纳走的是同一道判断,
+ /// 也该说出来自己动了几条,否则台账上只剩「改写了 N 条」,看不出其中
+ /// 有几条是被本体掉了个头的
+ pub corrected: u32,
+}
+
/// 要改写哪些事实,以及新行的宾语从哪来。
pub enum AdoptTargets<'a> {
/// 关系那一路:按表层说法去找,宾语原样搬走。
@@ -1254,12 +1273,18 @@ async fn adopt(
predicate_id: Uuid,
targets: AdoptTargets<'_>,
swap: bool,
-) -> AppResult<(Uuid, u32)> {
+) -> AppResult<Adopted> {
let batch_id = Uuid::now_v7();
+ let nothing = Adopted {
+ batch_id,
+ moved: 0,
+ left_off: 0,
+ corrected: 0,
+ };
let targets: Vec<(Uuid, Uuid, Option<Uuid>, Option<serde_json::Value>)> = match targets {
AdoptTargets::ByForm(forms) => {
if forms.is_empty() {
- return Ok((batch_id, 0));
+ return Ok(nothing);
}
sqlx::query_as(
"SELECT f.id, f.subject_id, f.object_id, f.object_value
@@ -1283,7 +1308,7 @@ async fn adopt(
}
AdoptTargets::WithValues(items) => {
if items.is_empty() {
- return Ok((batch_id, 0));
+ return Ok(nothing);
}
// 主语要从库里读回来(调用方给的是 fact_id 与新值),顺带确认这些
// 事实还活着——挑选与采纳之间可能隔着一次重抽
@@ -1307,6 +1332,8 @@ async fn adopt(
};
let mut moved = 0u32;
+ let mut left_off = 0u32;
+ let mut corrected = 0u32;
for (old_id, subject_id, object_id, object_value) in targets {
// 被动形改写:主宾对调。字面值宾语的事实换不了(值不能当主语),
// 而 ByForm 那条查询本来就只取 object_id 非空的,所以这里只可能是实体宾语
@@ -1314,6 +1341,29 @@ async fn adopt(
(true, Some(o)) => (o, Some(subject_id)),
_ => (subject_id, object_id),
};
+ // **挂谓词之前过一遍签名**(#190)。抽取写入时按 domain 掰正方向或留空,
+ // 而采纳是第二条写谓词的路——从前直接把谓词挂回去,实测把违反率从 0 抬到
+ // 12.3%,全在包关系上。同一道判断(`ontology::judge_direction`),同样三种
+ // 结果:合就挂,主语不合宾语合就对调着挂,都不合就**不挂**——那条事实留在
+ // 空谓词上,原文说法还在证据里,与抽取遇到同样情形的处置一致
+ let (subject_id, object_id) = match object_id {
+ Some(o) => {
+ match crate::ontology::judge_direction(pool, predicate_id, subject_id, o).await? {
+ crate::ontology::Fit::Swap => {
+ corrected += 1;
+ (o, Some(subject_id))
+ }
+ crate::ontology::Fit::Neither => {
+ left_off += 1;
+ continue;
+ }
+ crate::ontology::Fit::Keep | crate::ontology::Fit::Unchecked => {
+ (subject_id, Some(o))
+ }
+ }
+ }
+ None => (subject_id, None),
+ };
let mut tx = pool.begin().await?;
// 目标断言可能已存在(同主宾已有一条真关系):那就并进去,别造重复。
//
@@ -1403,7 +1453,12 @@ async fn adopt(
tx.commit().await?;
moved += 1;
}
- Ok((batch_id, moved))
+ Ok(Adopted {
+ batch_id,
+ moved,
+ left_off,
+ corrected,
+ })
}
/// 撤销一次采纳:新写的行作废、旧行复活。
@@ -1551,7 +1606,7 @@ pub async fn adopt_value_facts(
kb_id: Uuid,
attribute_id: Uuid,
rewrites: &[(Uuid, serde_json::Value)],
-) -> AppResult<(Uuid, u32)> {
+) -> AppResult<Adopted> {
// 属性那一路没有对调可言:宾语是字面值,值不能当主语
adopt(
pool,
diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rs
index 4bd721dc..883c9b39 100644
--- a/crates/utopia-store/src/ontology.rs
+++ b/crates/utopia-store/src/ontology.rs
@@ -1768,6 +1768,41 @@ pub async fn entity_fits_domain(
Ok((declared > 0).then_some(ok > 0))
}
+/// 一条 (主语, 谓词, 宾语) 对着谓词的 domain 签名该怎么落。
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Fit {
+ /// 谓词没声明 domain——没有判据,照原样落
+ Unchecked,
+ /// 主语符合
+ Keep,
+ /// 主语不符合、宾语符合:按签名对调主宾
+ Swap,
+ /// 两边都不符合:这个关系不适用于这对实体,谓词该留空
+ Neither,
+}
+
+/// **三条写谓词的路共用的那一道判断**(#190 / #196):抽取落新事实、采纳把谓词
+/// 挂回旧事实、合并换掉主语——从前只有抽取查,另外两条各自绕了过去。
+///
+/// 判据刻意窄(0012):只看 domain,只在**主语违反且宾语符合**时对调,两边都对不上
+/// 就留空谓词。参数顺序不是关于世界的断言,是这个 key 的编码约定,所以本体在这一处
+/// 是执法的;哪些类型能参与仍是引导,不在这里裁。
+pub async fn judge_direction(
+ pool: &PgPool,
+ relation_type_id: Uuid,
+ subject_id: Uuid,
+ object_id: Uuid,
+) -> AppResult<Fit> {
+ match entity_fits_domain(pool, relation_type_id, subject_id).await? {
+ None => Ok(Fit::Unchecked),
+ Some(true) => Ok(Fit::Keep),
+ Some(false) => match entity_fits_domain(pool, relation_type_id, object_id).await? {
+ Some(true) => Ok(Fit::Swap),
+ _ => Ok(Fit::Neither),
+ },
+ }
+}
+
/// 把 `owl:inverseOf` / `rdfs:subPropertyOf` 从 IRI 解析成 id。
///
/// **必须是第二遍。** 这两条指的是另一个关系类型,而 id 要等全部插完才有——
diff --git a/crates/utopia-store/src/reasoning.rs b/crates/utopia-store/src/reasoning.rs
index 56db5af4..a0562078 100644
--- a/crates/utopia-store/src/reasoning.rs
+++ b/crates/utopia-store/src/reasoning.rs
@@ -19,7 +19,7 @@ use utopia_core::models::{AxiomViolation, DerivedFactView, OntologyDefect};
type RuleKind = &'static str;
use utopia_core::AppResult;
use utopia_reason::derive::TimedEdge;
-use utopia_reason::{check, Axioms, Edge, Violation};
+use utopia_reason::{check, Axioms, Edge, Kind, Violation};
use uuid::Uuid;
/// 一次检查的产出,给调用方写审计与告诉用户。
@@ -148,11 +148,100 @@ async fn axioms(pool: &PgPool, kb_id: Uuid) -> AppResult<HashMap<Uuid, Axioms>>
Ok(map)
}
+/// 主语不在谓词声明的 domain 里、或宾语不在 range 里的活事实(#190 / #196)。
+///
+/// 这是签名检查在**账本层**的那一半:抽取与采纳在写入时按 `ontology::judge_direction`
+/// 掰正或留空,但合并会换掉主语、本体会事后改 domain,写入时的守卫挡不住写入之后
+/// 的改动。所以这里对着库量一遍,任何一条路写反了都在 Review 里看得见。
+///
+/// **没有类型的实体不算**:它没有类型可比,「不知道」不是「不符合」——按 0009,
+/// 未分类是一种诚实的状态,不该因此被报成矛盾。声明了 domain / range 的谓词才查,
+/// 与其它四类同一条纪律:没有公理就没有判据。
+///
+/// `only` 给了就只看这些事实(合并之后对搬动过的那几条立刻查);None 是全量。
+pub async fn signature_breaks(
+ pool: &PgPool,
+ kb_id: Uuid,
+ only: Option<&[Uuid]>,
+) -> AppResult<Vec<Uuid>> {
+ let rows: Vec<(Uuid,)> = sqlx::query_as(
+ "WITH RECURSIVE anc(type_id, anc_id) AS (
+ SELECT id, id FROM entity_types WHERE kb_id = $1
+ UNION
+ SELECT a.type_id, p.parent_id
+ FROM anc a JOIN entity_type_parents p ON p.child_id = a.anc_id
+ )
+ SELECT f.id
+ FROM facts f
+ JOIN relation_types r ON r.id = f.predicate_id
+ JOIN entities s ON s.id = f.subject_id
+ JOIN entities o ON o.id = f.object_id
+ WHERE f.kb_id = $1 AND f.invalidated_at IS NULL
+ AND ($2::uuid[] IS NULL OR f.id = ANY($2))
+ AND (
+ (s.type_id IS NOT NULL
+ AND EXISTS (SELECT 1 FROM relation_type_domains d WHERE d.relation_type_id = r.id)
+ AND NOT EXISTS (SELECT 1 FROM relation_type_domains d
+ JOIN anc a ON a.anc_id = d.entity_type_id
+ WHERE d.relation_type_id = r.id AND a.type_id = s.type_id))
+ OR
+ (o.type_id IS NOT NULL
+ AND EXISTS (SELECT 1 FROM relation_type_ranges g WHERE g.relation_type_id = r.id)
+ AND NOT EXISTS (SELECT 1 FROM relation_type_ranges g
+ JOIN anc a ON a.anc_id = g.entity_type_id
+ WHERE g.relation_type_id = r.id AND a.type_id = o.type_id))
+ )
+ ORDER BY f.recorded_at",
+ )
+ .bind(kb_id)
+ .bind(only)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows.into_iter().map(|(id,)| id).collect())
+}
+
+/// 把签名违规落进 `axiom_violations`(kind = `signature`,left 与 right 同一条事实)。
+/// 幂等:同一条事实重复报不重复入库。返回新插入的条数。
+pub async fn record_signature_breaks(
+ pool: &PgPool,
+ kb_id: Uuid,
+ facts: &[Uuid],
+) -> AppResult<usize> {
+ let mut inserted = 0usize;
+ for fact in facts {
+ let id: Option<(Uuid,)> = sqlx::query_as(
+ "INSERT INTO axiom_violations (id, kb_id, kind, left_fact, right_fact)
+ VALUES ($1, $2, 'signature', $3, $3)
+ ON CONFLICT (kb_id, kind, left_fact, right_fact) DO NOTHING
+ RETURNING id",
+ )
+ .bind(Uuid::now_v7())
+ .bind(kb_id)
+ .bind(fact)
+ .fetch_optional(pool)
+ .await?;
+ if id.is_some() {
+ inserted += 1;
+ }
+ }
+ Ok(inserted)
+}
+
/// 跑一遍检查,把结果落库。
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 violations = check(&edges, &axioms);
+ // 第五类不在纯逻辑引擎里:它要看实体的类型与谓词的 domain / range,那是库里的
+ // 东西。算出来后与其它四类走同一条落库与清陈规矩
+ for fact in signature_breaks(pool, kb_id, None).await? {
+ violations.push(Violation {
+ kind: Kind::Signature,
+ left: fact,
+ right: fact,
+ path: Vec::new(),
+ });
+ }
let mut report = Report {
edges: edges.len(),
diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs
index 22375816..730b687e 100644
--- a/crates/utopia-store/src/resolution.rs
+++ b/crates/utopia-store/src/resolution.rs
@@ -1308,6 +1308,21 @@ pub async fn merge_entities(
.chain(moved_object.iter())
.copied()
.collect();
+
+ // **合并是第三条改写事实的路**(#196):换掉主语或宾语,就可能把一条合法事实
+ // 变成签名违规——抽取写入时掰正过的方向,合并一次就能再反回去。这里不掰、不改,
+ // 只报:对搬动过的事实查一遍 domain / range,违反的进 `axiom_violations`
+ //(kind = signature),与其它公理违规同一个队列、同样三个出路。
+ // 放在事务之后:目标实体的类型在事务里刚调和过,提交了才看得见
+ match crate::reasoning::signature_breaks(pool, kb_id, Some(&moved_all)).await {
+ Ok(broken) if !broken.is_empty() => {
+ if let Err(e) = crate::reasoning::record_signature_breaks(pool, kb_id, &broken).await {
+ tracing::warn!(%kb_id, error = %e, "合并后的签名违规没能入库");
+ }
+ }
+ Ok(_) => {}
+ Err(e) => tracing::warn!(%kb_id, error = %e, "合并后的签名检查失败"),
+ }
let report = crate::temporal::reconcile_moved_facts(pool, kb_id, &moved_all).await?;
if !report.corrected.is_empty() {
sqlx::query("UPDATE entity_merges SET temporal_corrections = $2 WHERE id = $1")
diff --git a/crates/utopia-store/tests/a_signature_holds_on_every_path.rs b/crates/utopia-store/tests/a_signature_holds_on_every_path.rs
new file mode 100644
index 00000000..207909b7
--- /dev/null
+++ b/crates/utopia-store/tests/a_signature_holds_on_every_path.rs
@@ -0,0 +1,303 @@
+//! 关系的签名(domain / range)在**三条写路径**上都得算数(#190 / #196)。
+//!
+//! 抽取写入时按 #138 掰正方向或留空谓词,但写谓词的路不止一条:**采纳**把谓词挂回
+//! 旧事实,**合并**换掉主语的类型。守卫只装在抽取上,另外两条各自绕过去——实测采纳
+//! 把违反率从 0 抬到 12.3%。这里守三件事:
+//!
+//! 1. 采纳走同一道判断:主语不合宾语合 → 对调着挂;两边都不合 → 不挂,事实留在空谓词上。
+//! 2. 合并之后,被换了主语的事实若违反签名 → `axiom_violations` 里多一条 `signature`。
+//! 3. 一致性检查(R0)也能量出签名违规,事实撤了它就被清掉。
+//!
+//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。
+
+use sqlx::PgPool;
+use utopia_store::graph::Adopted;
+use uuid::Uuid;
+
+struct Fixture {
+ org: Uuid,
+ kb: Uuid,
+ company: Uuid,
+ person: Uuid,
+ /// schema.org 的 `employee (organization → person)`
+ employee: Uuid,
+ acme: Uuid,
+ alice: Uuid,
+ bob: Uuid,
+ doc: Uuid,
+ chunk: Uuid,
+}
+
+async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (company, person, employee) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (acme, alice, bob) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (src, doc, chunk) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'signature-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'signature-test')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'signature-test')",
+ )
+ .bind(kb)
+ .bind(ws)
+ .execute(pool)
+ .await?;
+ for (id, key, label) in [
+ (company, "company", "Company"),
+ (person, "person", "Person"),
+ ] {
+ sqlx::query("INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, $3, $4)")
+ .bind(id)
+ .bind(kb)
+ .bind(key)
+ .bind(label)
+ .execute(pool)
+ .await?;
+ }
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label) VALUES ($1, $2, 'employee', 'employee')",
+ )
+ .bind(employee)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO relation_type_domains (relation_type_id, entity_type_id) VALUES ($1, $2)",
+ )
+ .bind(employee)
+ .bind(company)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO relation_type_ranges (relation_type_id, entity_type_id) VALUES ($1, $2)",
+ )
+ .bind(employee)
+ .bind(person)
+ .execute(pool)
+ .await?;
+ for (id, ty, name) in [
+ (acme, company, "Acme"),
+ (alice, person, "Alice"),
+ (bob, person, "Bob"),
+ ] {
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
+ )
+ .bind(id)
+ .bind(kb)
+ .bind(ty)
+ .bind(name)
+ .execute(pool)
+ .await?;
+ }
+ sqlx::query("INSERT INTO sources (id, kb_id, name) VALUES ($1, $2, 'signature-test')")
+ .bind(src)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO documents (id, kb_id, source_id, filename, sha256, status)
+ VALUES ($1, $2, $3, 'note.md', 'signature', 'ready')",
+ )
+ .bind(doc)
+ .bind(kb)
+ .bind(src)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO chunks (id, kb_id, document_id, seq, text)
+ VALUES ($1, $2, $3, 0, 'Alice is an employee of Acme. Bob is an employee of Alice.')",
+ )
+ .bind(chunk)
+ .bind(kb)
+ .bind(doc)
+ .execute(pool)
+ .await?;
+ Ok(Fixture {
+ org,
+ kb,
+ company,
+ person,
+ employee,
+ acme,
+ alice,
+ bob,
+ doc,
+ chunk,
+ })
+}
+
+/// 一条没有谓词、证据里留着原文说法 `employee` 的事实——采纳要改写的正是这种
+async fn surfaced_fact(
+ pool: &PgPool,
+ f: &Fixture,
+ subject: Uuid,
+ object: Uuid,
+) -> anyhow::Result<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, confidence)
+ VALUES ($1, $2, $3, NULL, $4, 0.9)",
+ )
+ .bind(id)
+ .bind(f.kb)
+ .bind(subject)
+ .bind(object)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO fact_evidence (fact_id, chunk_id, quote, proposed_predicate, document_id, doc_version)
+ VALUES ($1, $2, 'employee of', 'employee', $3, 1)",
+ )
+ .bind(id)
+ .bind(f.chunk)
+ .bind(f.doc)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+async fn live_employee_edges(pool: &PgPool, f: &Fixture) -> anyhow::Result<Vec<(Uuid, Uuid)>> {
+ Ok(sqlx::query_as(
+ "SELECT subject_id, object_id FROM facts
+ WHERE kb_id = $1 AND predicate_id = $2 AND invalidated_at IS NULL
+ ORDER BY recorded_at",
+ )
+ .bind(f.kb)
+ .bind(f.employee)
+ .fetch_all(pool)
+ .await?)
+}
+
+async fn open_signature_breaks(pool: &PgPool, kb: Uuid) -> anyhow::Result<Vec<Uuid>> {
+ Ok(sqlx::query_as::<_, (Uuid,)>(
+ "SELECT left_fact FROM axiom_violations
+ WHERE kb_id = $1 AND kind = 'signature' AND status = 'open'",
+ )
+ .bind(kb)
+ .fetch_all(pool)
+ .await?
+ .into_iter()
+ .map(|(id,)| id)
+ .collect())
+}
+
+#[tokio::test]
+async fn adoption_and_merge_respect_the_signature() -> 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 {
+ // 模型写的是 "Alice is an employee of Acme" —— 主语 person 违反 domain、宾语 company 符合
+ let reversed = surfaced_fact(&pool, &f, f.alice, f.acme).await?;
+ // "Bob is an employee of Alice" —— 两边都是 person,这个关系压根不适用
+ let hopeless = surfaced_fact(&pool, &f, f.bob, f.alice).await?;
+
+ // 1. 采纳:一条对调着挂上,一条不挂
+ let Adopted {
+ moved, left_off, ..
+ } = utopia_store::graph::adopt_proposed_predicates(
+ &pool,
+ f.kb,
+ f.employee,
+ &["employee".to_string()],
+ false,
+ )
+ .await?;
+ assert_eq!(moved, 1, "the reversed one is adoptable once swapped");
+ assert_eq!(left_off, 1, "the hopeless one must be left without a predicate");
+ assert_eq!(
+ live_employee_edges(&pool, &f).await?,
+ vec![(f.acme, f.alice)],
+ "adoption must write the edge in the ontology's direction: Acme employee Alice"
+ );
+ let (still_bare,): (bool,) =
+ sqlx::query_as("SELECT predicate_id IS NULL AND invalidated_at IS NULL FROM facts WHERE id = $1")
+ .bind(hopeless)
+ .fetch_one(&pool)
+ .await?;
+ assert!(still_bare, "a fact that fits neither way stays live and predicate-less");
+ let (old_gone,): (bool,) =
+ sqlx::query_as("SELECT invalidated_at IS NOT NULL FROM facts WHERE id = $1")
+ .bind(reversed)
+ .fetch_one(&pool)
+ .await?;
+ assert!(old_gone, "the reversed row was superseded, not left beside the corrected one");
+ assert!(open_signature_breaks(&pool, f.kb).await?.is_empty());
+
+ // 2. 合并:把 Acme 并进 Bob(person),Acme employee Alice 的主语变成 person
+ utopia_store::resolution::merge_entities(&pool, f.kb, f.acme, f.bob, None, "test")
+ .await?;
+ let edges = live_employee_edges(&pool, &f).await?;
+ assert_eq!(edges, vec![(f.bob, f.alice)], "the merge moved the subject onto Bob");
+ let (moved_fact,): (Uuid,) = sqlx::query_as(
+ "SELECT id FROM facts WHERE kb_id = $1 AND predicate_id = $2 AND invalidated_at IS NULL",
+ )
+ .bind(f.kb)
+ .bind(f.employee)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(
+ open_signature_breaks(&pool, f.kb).await?,
+ vec![moved_fact],
+ "a merge that breaks the signature must show up as an open violation"
+ );
+
+ // 3. 一致性检查量得出它,撤了事实就清掉
+ let report = utopia_store::reasoning::run(&pool, f.kb).await?;
+ assert_eq!(report.found, 1);
+ assert_eq!(report.inserted, 0, "already recorded by the merge; the check must not duplicate it");
+ sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = $1")
+ .bind(moved_fact)
+ .execute(&pool)
+ .await?;
+ let report = utopia_store::reasoning::run(&pool, f.kb).await?;
+ assert_eq!(report.found, 0);
+ assert_eq!(report.cleared, 1, "a retracted fact takes its violation with it");
+ assert!(open_signature_breaks(&pool, f.kb).await?.is_empty());
+
+ // 未分类的实体不算违反:类型是 NULL 的主语没有东西可比
+ let untyped = Uuid::now_v7();
+ sqlx::query("INSERT INTO entities (id, kb_id, canonical_name) VALUES ($1, $2, 'Nobody')")
+ .bind(untyped)
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, confidence)
+ VALUES ($1, $2, $3, $4, $5, 0.9)",
+ )
+ .bind(Uuid::now_v7())
+ .bind(f.kb)
+ .bind(untyped)
+ .bind(f.employee)
+ .bind(f.alice)
+ .execute(&pool)
+ .await?;
+ assert!(
+ utopia_store::reasoning::signature_breaks(&pool, f.kb, None).await?.is_empty(),
+ "an untyped subject is unknown, not wrong"
+ );
+ let _ = (f.company, f.person);
+ anyhow::Ok(())
+ }
+ .await;
+
+ let _ = sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await;
+ run
+}
diff --git a/crates/utopia-store/tests/adopt_swap.rs b/crates/utopia-store/tests/adopt_swap.rs
index 99e7a9af..2f36f9d4 100644
--- a/crates/utopia-store/tests/adopt_swap.rs
+++ b/crates/utopia-store/tests/adopt_swap.rs
@@ -97,14 +97,15 @@ async fn adopting_a_passive_wording_flips_subject_and_object() -> anyhow::Result
.await?;
let run = async {
- let (_, moved) = utopia_store::graph::adopt_proposed_predicates(
+ let moved = utopia_store::graph::adopt_proposed_predicates(
&pool,
kb,
produces,
&["produced_by".to_string()],
true,
)
- .await?;
+ .await?
+ .moved;
assert_eq!(moved, 1);
// 改写后应该是 OpenAI -[produces]-> ChatGPT,**方向反过来**
let (s, o): (Uuid, Option<Uuid>) = sqlx::query_as(
diff --git a/docs/decisions/0002-reasoning-engine.md b/docs/decisions/0002-reasoning-engine.md
index a953cf70..3dec2e00 100644
--- a/docs/decisions/0002-reasoning-engine.md
+++ b/docs/decisions/0002-reasoning-engine.md
@@ -101,6 +101,7 @@ CREATE TABLE fact_derivations (
> **修订记录(2026-09-02):R0 建成,四处与上面写的不同。**
> 一、**四类不是三类,且不是那三类**:`self_loop` / `asymmetry` / `cycle` / `functional`(兼含 inverse_functional)。**事实层的 disjointWith 违反没有做**——disjoint 只进了本体自检。
+> 〔后来多了第五类 `signature`(#190 / #196):主语不在谓词的 domain、或宾语不在 range。它不由纯逻辑引擎算——要看实体类型与闭包,那是库里的东西——`store::reasoning::signature_breaks` 用 SQL 量,算出来后与其它四类走同一条落库、清陈、裁决的路。合并之后对搬动过的事实立刻查,手动跑检查时全量查。未分类实体不算。〕
> 二、**不进 `fact_conflicts`,另建 `axiom_violations`**:那张表问的是「哪条对」,公理违规问的是「错在数据还是错在定义」,出路是 `fact_retracted` / `axiom_relaxed` / `accepted`。「零新界面」也没守住,Review 页多了 `violations` 与 `defects` 两个页签。
> 三、**多出另一半:本体自身的自洽性**(`ontology_defects`,八类:symmetric 且 asymmetric、transitive 且 functional、子类成环、与祖先 disjoint、继承来的 disjoint、自逆、逆没指回来、子属性成环)。理由是自相矛盾的本体会让事实层的结论全部可疑,所以缺陷优先于违规展示。
> 四、环检测是深度优先不是半朴素——闭包只告诉你 A 推出了 A,人要的是**路径**;半朴素在 R1。
diff --git a/docs/decisions/0012-the-ontology-is-a-contract-not-a-suggestion.md b/docs/decisions/0012-the-ontology-is-a-contract-not-a-suggestion.md
index bc3624f5..382a2661 100644
--- a/docs/decisions/0012-the-ontology-is-a-contract-not-a-suggestion.md
+++ b/docs/decisions/0012-the-ontology-is-a-contract-not-a-suggestion.md
@@ -167,7 +167,7 @@ distrust with Altman`(65 字符)是从句——字符数分不开,**谓语
## 待做
- **写入时的守卫挡不住写入之后的改动**:实体合并会把主语换成另一个类型的实体,
- 于是事实「变成」违反。实测 6 条残留里 4 条如此。要治得把同样的检查放进合并路径。〔仍未做:`merge_entities` 只做互指事实作废、主宾改指、SPO 去重,全程没有 domain / range 复核。〕
+ 于是事实「变成」违反。实测 6 条残留里 4 条如此。要治得把同样的检查放进合并路径。〔**已做**(#190 / #196,`fix/one-domain-check-for-three-paths`):写入时的判断抽成 `ontology::judge_direction`,抽取与**采纳**共用——采纳是第二条写谓词的路,实测把违反率从 0 抬到 12.3%,全在包关系上;两边都不合的采纳**不挂谓词**,条数随 `facts_left_off` 上报。**合并**不掰不改只报:搬动过的事实查一遍 domain / range,违反的进 `axiom_violations`(新 kind `signature`)。一致性检查(0002 R0)也多了这一类,全量量、事实撤了就清,所以本体事后改 domain 也逃不过。未分类实体不算违反——「不知道」不是「不符合」。〕
- 另外 2 条残留(`Stability AI Ltd`、`Colossus 2 data center`)没有合并也没有改类型,
**原因未查明**。
- 导入本体包时过滤掉需要中间节点才能用的关系(domain 全是 `Action`/`Offer`/
diff --git a/docs/decisions/0016-close-the-open-seams-before-cutting-new-ones.md b/docs/decisions/0016-close-the-open-seams-before-cutting-new-ones.md
index 651532f5..eca4adf5 100644
--- a/docs/decisions/0016-close-the-open-seams-before-cutting-new-ones.md
+++ b/docs/decisions/0016-close-the-open-seams-before-cutting-new-ones.md
@@ -26,7 +26,7 @@
| `utopia-mcp` / `utopia-connectors` / `utopia-graph` 三个 crate 是三行占位,其中一个宣称的工具名从未实现 | 0014 | 读源码的人被误导 |
| 证明树只展开一层;增量维护没做;派生 vs 断言矛盾不记信号 | 0002 | README 说 derivation path expands back to the sentence,只对了一层 |
| `disjointWith` 落库了,消解侧仍用硬编码 `CONFUSABLE_TYPE_KEYS` | 0009 / 0001 P5 | 本体声明了不相交,合并候选照样跨过去 |
-| 合并路径没有签名复核 | 0012 待做 | 写入时掰正的方向,合并一次就能再反回去 |
+| 合并路径没有签名复核〔已做,#196;采纳那条路也没有,#190,一并做了〕 | 0012 待做 | 写入时掰正的方向,合并一次就能再反回去 |
| 类型消解只能手动跑 | 0001 P3a | 大本体下新实体的细化靠人记得点一下 |
| 中文库拿到纯英文本体;`zh.ts` 没追平所以界面默认英文 | 0008 / 0004 | 中文用户两头都是英文 |
| `merge_key` 不折 `_by`;叙述动词进本体 | 0007 | 同一关系两个方向并存 |
@@ -70,6 +70,7 @@ Chat memory 与 MCP 两处在 A1 / A2 落地前标 in development。中英两份
**B2 · 派生 vs 断言矛盾要有信号。** `axiom_violations` 加一种 kind(`derived_contradiction`),进 Review 同一档——0002 写了没做的那一行。
**B3 · `disjointWith` 进消解,合并路径复核签名。** `classify_type_drift` 改从 `entity_type_disjoint` 读(没声明就退回今天的行为,不硬编码);
`merge_entities` 搬事实前跑一遍与写入时相同的 domain / range 检查,违反的进 `axiom_violations` 而不是静默搬过去。这是 0009 与 0012 各自待做的同一件事。
+〔**签名那一半已提前做了**(#190 / #196 逼出来的,A 线里插队):`ontology::judge_direction` 一处判断,抽取与采纳共用;合并后对搬动过的事实报 `signature` 违规;R0 多一类。剩下 `disjointWith` 进消解那一半仍在这里。〕
**B4 · R3 增量维护——后置。** 只在测量台上全量重推超过一个明确阈值(建议:`ai-timeline-ends` 语料超过 10 秒)时才做。今天每次全量重推活得下去。
### C · 本体与抽取质量——先造尺子,再调参
diff --git a/docs/decisions/README.md b/docs/decisions/README.md
index bd39a52a..ce399d59 100644
--- a/docs/decisions/README.md
+++ b/docs/decisions/README.md
@@ -27,7 +27,7 @@
| | 文档 | 状态 |
|---|---|---|
| 0001 | [本体导入与治理路线](0001-ontology-import-and-governance.md) | 进行中 · P0–P2c 全建成;P3 按预算落地、P3a 只能手动跑;P3b 建成但形态不同;**P4b/P4c 待做**;P5 已由 0002 落地;判据 2 被 0012 推翻一半 |
-| 0002 | [推理机](0002-reasoning-engine.md) | R0 建成(含本体自检八类)· R1 建成带开关默认关 · **R2 只一层、R3 未做** · 派生 vs 断言矛盾无信号 |
+| 0002 | [推理机](0002-reasoning-engine.md) | R0 建成(事实层五类含签名、本体自检八类)· R1 建成带开关默认关 · **R2 只一层、R3 未做** · 派生 vs 断言矛盾无信号 |
| 0003 | [本体从语料里长出来,人站在哪一环](0003-ontology-growth-loop.md) | 已建成且仍在跑 · 起点已被 0010 与种子退场改写 · 「拒绝有记忆」被 0007 推翻重做 · 新说法提醒待做 |
| 0004 | [语言:哪些字跟着看的人走,哪些跟着语料走](0004-language-and-localization.md) | 已建成 · L0–L3 全落地 · 界面刻意不猜浏览器语言 · 「中文内置本体」随播种退场作废 |
| 0005 | [告警中心](0005-alert-center.md) | 已建成 · 五种告警 · 三个决定推翻两个(就地留痕)· `no_text_layer` 待接 |
@@ -37,7 +37,7 @@
| 0009 | [「还没判出来」不该是一个类](0009-no-type-is-a-type.md) | 已实施 · `disjointWith` 落库但消解侧未消费 · `metric`/`dimension` 去处未答且有可见代价 |
| 0010 | [「说不出是什么关系」不该是一个关系](0010-no-relation-is-no-relation.md) | 已实施 · 待做两条随 0011 完成 · 两处死代码待清 |
| 0011 | [「怎么算」不是「有什么」](0011-a-mapping-is-not-a-fact.md) | 已实施(#126 / #140 / #148)· 证据链未做 · 多源选法未做 |
-| 0012 | [本体是一份契约,不只是一份建议](0012-the-ontology-is-a-contract-not-a-suggestion.md) | 已实施 · 违反率 57%→4%、反向 39→0 · 三条待做全未做 |
+| 0012 | [本体是一份契约,不只是一份建议](0012-the-ontology-is-a-contract-not-a-suggestion.md) | 已实施 · 违反率 57%→4%、反向 39→0 · 守卫已扩到采纳与合并(#190 / #196),另两条待做仍在 |
| 0013 | [一个来源该交出它的历史,不是它的现状](0013-a-source-should-hand-over-its-history.md) | 已实施两个(GitHub / Jira)· 文档协作类未开工 |
| 0014 | [身份跟着人,范围跟着令牌](0014-identity-from-the-person-scope-from-the-token.md) | 已实施(#180)· MCP 只读五工具 · 令牌页在账户层(A2)· 误导性的占位 crate 已删 |
| 0015 | [记下一句话,不等于断言一个事实](0015-recording-a-sentence-is-not-asserting-a-fact.md) | 已实施 · 记忆抽出的事实进 `pending_facts`,Review 新档 + 跟在 remember 步骤后的确认卡 · `remember` 重新打开 · MCP 放开写是下一刀 |
diff --git a/docs/pipeline.md b/docs/pipeline.md
index d9ba1c9d..355e7878 100644
--- a/docs/pipeline.md
+++ b/docs/pipeline.md
@@ -249,7 +249,7 @@ flowchart TB
flowchart TB
ONT[(本体的公理<br/>functional · symmetric · asymmetric<br/>transitive · inverseOf · subPropertyOf · disjoint)] --> SELF[本体自检<br/>八类缺陷]
SELF --> DEF[(ontology_defects)]
- ONT --> R0[事实层检查<br/>自环 · 反对称 · 传递环 · 基数]
+ ONT --> R0[事实层检查<br/>自环 · 反对称 · 传递环 · 基数 · 签名]
G[(图谱)] --> R0
R0 --> VIO[(axiom_violations<br/>带完整路径)]
VIO --> DEC{人裁}
@@ -264,6 +264,8 @@ flowchart TB
style DEC fill:#3a3a5a,color:#fff
```
+**签名在三条写路径上都算数**(#190 / #196):第一节那道「主宾对得上签名吗」的判断住在 store(`ontology::judge_direction`),抽取落新事实、采纳把谓词挂回旧事实都调它——两边都不合的采纳**不挂**,条数随 `facts_left_off` 上报;合并换了主宾之后不掰不改,只对搬动过的事实查一遍,违反的进 `axiom_violations`(`signature`)。检查里的第五类就是它的全量版,本体事后改了 domain 也逃不过。
+
**检查不写库,推导写另一张表。** 一致性检查(R0)只指出问题,风险面为零;物化推导(R1)会往图里加东西,所以它的每条约束都是必要的:
规则**只从本体公理编译**,没有用户 DSL;**断言硬性优先于派生**——已经断言过的三元组不再派生,「这条是谁说的」有唯一答案;
深度上限加环检测,每谓词封顶两万条且被截掉的**要说出来**;有效时间取前提的交集,空交集不推。
diff --git a/migrations/0019_a_signature_holds_on_every_path.sql b/migrations/0019_a_signature_holds_on_every_path.sql
new file mode 100644
index 00000000..95e07130
--- /dev/null
+++ b/migrations/0019_a_signature_holds_on_every_path.sql
@@ -0,0 +1,18 @@
+-- 签名违规成为一致性检查的一种(见 #190 / #196,docs/decisions/0012 待做第一条)。
+--
+-- #138 在抽取写入时按关系的 domain 掰正方向:主语不合、宾语合就对调,都不合就
+-- 留空谓词。但写谓词的路不止抽取一条:**采纳**把谓词挂回旧事实(#190,实测把
+-- 违反率从 0 抬到 12.3%),**合并**换掉主语的类型(#196)。守卫只在一条路上,
+-- 另外两条各自绕过去了。
+--
+-- 修法两层:写入时的判断抽成一处(`ontology::judge_direction`),抽取与采纳共用;
+-- 账本层再加一道兜底——一致性检查(0002 R0)多查一种 `signature`:活事实的主语
+-- 不在谓词声明的 domain 里、或宾语不在 range 里。合并之后对搬动过的事实立刻查一遍,
+-- 手动跑检查时全量查。**任何一条路写反了,人都能在 Review 里看见**,出路与其它
+-- 违规一样:撤事实、放宽公理(去掉那条 domain 声明)、或认可并存。
+--
+-- 只动 CHECK 约束:表的形状够用——签名违规只涉及一条事实,left 与 right 同一条,
+-- 与自反那类同款。
+ALTER TABLE axiom_violations DROP CONSTRAINT axiom_violations_kind_check;
+ALTER TABLE axiom_violations ADD CONSTRAINT axiom_violations_kind_check
+ CHECK (kind IN ('self_loop', 'asymmetry', 'cycle', 'functional', 'signature'));
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 09bc4899..05150fae 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -1313,6 +1313,9 @@ export const en = {
violationAsymmetry: "Both directions asserted",
violationCycle: "Cycle through the transitive chain",
violationFunctional: "Should hold one value, holds two",
+ /** 签名违规(#190 / #196):一条事实的主语或宾语落在谓词声明的类型之外——
+ * 抽取时会掰正,采纳与合并这两条路从前绕过了检查 */
+ violationSignature: "Subject or object outside the declared types",
violationVia: (p: string) => `via ${p}`,
violationPath: (n: number) => `${n} facts in the cycle`,
retractFact: "Data is wrong",
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index ab194530..68d90423 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -1187,6 +1187,7 @@ export const zh: Strings = {
violationAsymmetry: "两个方向都断言了",
violationCycle: "传递链绕成了环",
violationFunctional: "该只有一个值,却有两个",
+ violationSignature: "主语或宾语不在关系声明的类型里",
violationVia: (p: string) => `依据 ${p}`,
violationPath: (n: number) => `环上 ${n} 条事实`,
retractFact: "数据错了",
diff --git a/web/src/pages/Review.tsx b/web/src/pages/Review.tsx
index 2971cc37..5c73892a 100644
--- a/web/src/pages/Review.tsx
+++ b/web/src/pages/Review.tsx
@@ -545,6 +545,7 @@ function ViolationRow({
asymmetry: S.review.violationAsymmetry,
cycle: S.review.violationCycle,
functional: S.review.violationFunctional,
+ signature: S.review.violationSignature,
}[v.kind];
// 自反那一类两条事实是同一条——显示一遍就够,显示两遍像个 bug
const single = v.left_fact === v.right_fact;