Skip to content

World's first open-source enterprise world model.

The aligner's open questions have a queue (#754)

WaylandYang2c8dba4eff5b
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index 0b0f19b7..624bfce3 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -1472,6 +1472,8 @@ pub struct ReviewCounts {
pub lowconf: i64,
pub mappings: i64,
pub violations: i64,
+ /// 对齐器两票不一致的签名与类别词(#725 对齐队列)
+ pub alignment: i64,
pub defects: i64,
pub merges: i64,
/// agent 写下、等人回答的建议(0025)
@@ -1575,6 +1577,7 @@ pub struct ReviewWaiting {
pub lowconf: QueueWait,
pub violations: QueueWait,
pub defects: QueueWait,
+ pub alignment: QueueWait,
}
/// 办过的:近 7 天与近 30 天两个窗口,加近 14 天每天一根柱
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index 4d4cd0ba..38fe98d5 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -497,6 +497,15 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
post(review_routes::decide_pending),
)
.route("/kbs/{id}/review/{review_id}", post(review_routes::decide))
+ // 对齐队列(#725):人定签名的属性与方向、类别词的类
+ .route(
+ "/kbs/{id}/review/alignment/phrases/{binding_id}",
+ post(review_routes::decide_alignment_phrase),
+ )
+ .route(
+ "/kbs/{id}/review/alignment/kind-words/{kind_word}",
+ post(review_routes::decide_alignment_kind_word),
+ )
// 语义层映射的表态(0011)。跟消解审核并排——都是「引擎提议、人裁决」
.route(
"/kbs/{id}/review/mappings/{mapping_id}",
diff --git a/crates/utopia-server/src/api/review_routes.rs b/crates/utopia-server/src/api/review_routes.rs
index 3273833b..d660f973 100644
--- a/crates/utopia-server/src/api/review_routes.rs
+++ b/crates/utopia-server/src/api/review_routes.rs
@@ -113,6 +113,10 @@ pub async fn list(
"mappings" => {
json!(utopia_store::mappings::proposed(&state.pool, kb_id, limit, offset).await?)
}
+ // 对齐器两票不一致的签名与类别词(#725 对齐队列,0044 决定 3)
+ "alignment" => {
+ json!(utopia_store::alignment_queue::list(&state.pool, kb_id, limit, offset).await?)
+ }
"violations" => {
json!(
utopia_store::reasoning::open_violations(&state.pool, kb_id, limit, offset).await?
@@ -1206,3 +1210,166 @@ pub async fn run_inference(
"capped": report.capped,
})))
}
+
+#[derive(Deserialize)]
+pub struct DecideAlignmentPhraseReq {
+ /// 属性的键;空 = 没有属性对得上,陈述留在开放图谱
+ #[serde(default)]
+ pub property: Option<String>,
+ /// forward | reverse;给了属性就得给
+ #[serde(default)]
+ pub direction: Option<String>,
+}
+
+/// 人定一条短语签名绑到哪个属性(#725 对齐队列)。写成人的判定,代理此后不再改它;
+/// 类型化图谱立刻按新绑定重算。
+pub async fn decide_alignment_phrase(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, binding_id)): Path<(Uuid, Uuid)>,
+ Json(req): Json<DecideAlignmentPhraseReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let sig = utopia_store::phrase_bindings::signature_of(&state.pool, kb_id, binding_id)
+ .await?
+ .ok_or(utopia_core::AppError::NotFound)?;
+ let property = match req
+ .property
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ {
+ None => None,
+ Some(key) => {
+ let id = utopia_store::ontology::relation_type_views(&state.pool, kb_id)
+ .await?
+ .into_iter()
+ .find(|p| p.key == key)
+ .map(|p| p.id)
+ .ok_or_else(|| {
+ utopia_core::AppError::invalid("unknown_property", "no property with that key")
+ })?;
+ Some(id)
+ }
+ };
+ let direction = match (property, req.direction.as_deref()) {
+ (None, _) => None,
+ (Some(_), Some(d @ ("forward" | "reverse"))) => Some(d),
+ (Some(_), _) => {
+ return Err(utopia_core::AppError::invalid(
+ "direction_required",
+ "a bound signature needs a direction: forward or reverse",
+ )
+ .into())
+ }
+ };
+ let votes = json!({ "person": { "property": req.property, "direction": direction } });
+ utopia_store::phrase_bindings::decide(
+ &state.pool,
+ kb_id,
+ &sig,
+ utopia_store::phrase_bindings::Decision {
+ relation_type_id: property,
+ direction,
+ status: if property.is_some() { "bound" } else { "none" },
+ votes: &votes,
+ decided_by: "person",
+ },
+ )
+ .await?;
+ let typed = utopia_store::materialize::materialize(&state.pool, kb_id).await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "alignment.phrase_decided",
+ "phrase_binding",
+ Some(binding_id),
+ json!({ "phrase": sig.phrase, "property": req.property, "direction": direction,
+ "typed_added": typed.added, "typed_retired": typed.retired }),
+ )
+ .await;
+ state.emit_review(kb_id);
+ state.emit_graph(kb_id);
+ Ok(Json(
+ json!({ "ok": true, "typed": { "added": typed.added, "merged": typed.merged, "retired": typed.retired } }),
+ ))
+}
+
+#[derive(Deserialize)]
+pub struct DecideAlignmentKindWordReq {
+ /// 类的键;空 = 没有类对得上
+ #[serde(default)]
+ pub class: Option<String>,
+}
+
+/// 人定一个类别词绑到哪个类(#725 对齐队列)。绑上的类写到它名下的实体上;两端的类变了,
+/// 短语签名跟着变,所以再排一次短语对齐。
+pub async fn decide_alignment_kind_word(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, kind_word)): Path<(Uuid, String)>,
+ Json(req): Json<DecideAlignmentKindWordReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let class = match req
+ .class
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ {
+ None => None,
+ Some(key) => Some(
+ utopia_store::graph::entity_types(&state.pool, kb_id)
+ .await?
+ .into_iter()
+ .find(|c| c.key == key)
+ .map(|c| c.id)
+ .ok_or_else(|| {
+ utopia_core::AppError::invalid("unknown_class", "no class with that key")
+ })?,
+ ),
+ };
+ let votes = json!({ "person": req.class });
+ let written = utopia_store::type_bindings::decide(
+ &state.pool,
+ kb_id,
+ &kind_word,
+ &[],
+ class,
+ if class.is_some() { "bound" } else { "none" },
+ &votes,
+ "person",
+ )
+ .await?;
+ if !written {
+ return Err(utopia_core::AppError::NotFound.into());
+ }
+ match class {
+ Some(id) => {
+ utopia_store::type_bindings::apply(&state.pool, kb_id, &kind_word, id).await?;
+ }
+ None => {
+ utopia_store::type_bindings::unapply(&state.pool, kb_id, &kind_word).await?;
+ }
+ }
+ utopia_store::jobs::enqueue_unless_queued(
+ &state.pool,
+ "align_phrases",
+ json!({ "kb_id": kb_id }),
+ )
+ .await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "alignment.kind_word_decided",
+ "type_binding",
+ None,
+ json!({ "kind_word": kind_word, "class": req.class }),
+ )
+ .await;
+ state.emit_review(kb_id);
+ state.emit_graph(kb_id);
+ Ok(Json(json!({ "ok": true })))
+}
diff --git a/crates/utopia-store/src/alignment_queue.rs b/crates/utopia-store/src/alignment_queue.rs
new file mode 100644
index 00000000..2bbbad1a
--- /dev/null
+++ b/crates/utopia-store/src/alignment_queue.rs
@@ -0,0 +1,151 @@
+//! 对齐队列(#725 的「Alignment」一档):对齐器两票不一致、拿不定的签名与类别词,等人来定。
+//!
+//! 两种条目走同一档:一条短语签名(短语 × 两端的类,几条例句,两票各选了什么)要人定
+//! 属性和方向或「没有」;一个类别词(词、写法、例名、两票)要人定类或「没有」。人定了写回
+//! `phrase_bindings` / `type_bindings`,`decided_by = 'person'`,代理此后不再改它;短语定了
+//! 类型化图谱按新绑定重算,类别词定了它名下的实体换类、短语签名跟着变。
+//!
+//! 卡片由账本拼:这里只读两张绑定表和类别词签名,不调模型。
+
+use chrono::{DateTime, Utc};
+use serde::Serialize;
+use sqlx::PgPool;
+use utopia_core::AppResult;
+use uuid::Uuid;
+
+/// 队列里的一条:短语签名或类别词。
+#[derive(Debug, Clone, Serialize)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum AlignmentItem {
+ Phrase {
+ id: Uuid,
+ phrase: String,
+ subject_class: Option<String>,
+ object_class: Option<String>,
+ object_is_value: bool,
+ statement_count: i32,
+ /// 判定时记下的例句(「主语 —短语→ 宾语」)
+ examples: Vec<String>,
+ /// 两票各选了什么:`{"first": {...} | null, "second": {...} | null}`
+ votes: Option<serde_json::Value>,
+ decided_at: DateTime<Utc>,
+ },
+ KindWord {
+ kind_word: String,
+ words: Vec<String>,
+ examples: Vec<String>,
+ phrases: Vec<String>,
+ entity_count: i64,
+ votes: Option<serde_json::Value>,
+ decided_at: DateTime<Utc>,
+ },
+}
+
+#[derive(sqlx::FromRow)]
+struct PhraseRow {
+ id: Uuid,
+ phrase: String,
+ subject_class: Option<String>,
+ object_class: Option<String>,
+ object_is_value: bool,
+ statement_count: i32,
+ examples: Vec<String>,
+ votes: Option<serde_json::Value>,
+ decided_at: DateTime<Utc>,
+}
+
+#[derive(sqlx::FromRow)]
+struct KindWordRow {
+ kind_word: String,
+ words: Vec<String>,
+ votes: Option<serde_json::Value>,
+ decided_at: DateTime<Utc>,
+}
+
+/// 等人定的条目,先来的在前,两种混排。
+pub async fn list(
+ pool: &PgPool,
+ kb_id: Uuid,
+ limit: i64,
+ offset: i64,
+) -> AppResult<Vec<AlignmentItem>> {
+ let phrases: Vec<PhraseRow> = sqlx::query_as(
+ "SELECT b.id, b.phrase, st.key AS subject_class, ot.key AS object_class,
+ b.object_is_value, b.statement_count, b.examples, b.votes, b.decided_at
+ FROM phrase_bindings b
+ LEFT JOIN entity_types st ON st.id = b.subject_type_id
+ LEFT JOIN entity_types ot ON ot.id = b.object_type_id
+ WHERE b.kb_id = $1 AND b.status = 'undecided'",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?;
+ let words: Vec<KindWordRow> = sqlx::query_as(
+ "SELECT kind_word, words, votes, decided_at
+ FROM type_bindings WHERE kb_id = $1 AND status = 'undecided'",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?;
+ // 类别词的例名和短语来自签名(活着的实体数出来的),按词对上
+ let sigs = if words.is_empty() {
+ Vec::new()
+ } else {
+ crate::type_bindings::signatures(pool, kb_id).await?
+ };
+ let mut items: Vec<(DateTime<Utc>, AlignmentItem)> = phrases
+ .into_iter()
+ .map(|r| {
+ (
+ r.decided_at,
+ AlignmentItem::Phrase {
+ id: r.id,
+ phrase: r.phrase,
+ subject_class: r.subject_class,
+ object_class: r.object_class,
+ object_is_value: r.object_is_value,
+ statement_count: r.statement_count,
+ examples: r.examples,
+ votes: r.votes,
+ decided_at: r.decided_at,
+ },
+ )
+ })
+ .collect();
+ for w in words {
+ let sig = sigs.iter().find(|s| s.kind_word == w.kind_word);
+ items.push((
+ w.decided_at,
+ AlignmentItem::KindWord {
+ kind_word: w.kind_word,
+ words: w.words,
+ examples: sig.map(|s| s.examples.clone()).unwrap_or_default(),
+ phrases: sig.map(|s| s.phrases.clone()).unwrap_or_default(),
+ entity_count: sig.map(|s| s.count).unwrap_or(0),
+ votes: w.votes,
+ decided_at: w.decided_at,
+ },
+ ));
+ }
+ items.sort_by_key(|(at, _)| *at);
+ Ok(items
+ .into_iter()
+ .map(|(_, item)| item)
+ .skip(usize::try_from(offset).unwrap_or(0))
+ .take(usize::try_from(limit).unwrap_or(usize::MAX))
+ .collect())
+}
+
+/// 等人定的条目数,以及最老的一条从什么时候起在等。
+pub async fn waiting(pool: &PgPool, kb_id: Uuid) -> AppResult<(i64, Option<DateTime<Utc>>)> {
+ Ok(sqlx::query_as(
+ "SELECT count(*), min(decided_at) FROM (
+ SELECT decided_at FROM phrase_bindings WHERE kb_id = $1 AND status = 'undecided'
+ UNION ALL
+ SELECT decided_at FROM type_bindings WHERE kb_id = $1 AND status = 'undecided'
+ ) q",
+ )
+ .bind(kb_id)
+ .fetch_one(pool)
+ .await?)
+}
diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rs
index c29f5b19..25d23a13 100644
--- a/crates/utopia-store/src/lib.rs
+++ b/crates/utopia-store/src/lib.rs
@@ -4,6 +4,7 @@
pub mod access;
pub mod accounts;
pub mod alerts;
+pub mod alignment_queue;
pub mod audit;
pub mod business_rules;
pub mod conversations;
diff --git a/crates/utopia-store/src/phrase_bindings.rs b/crates/utopia-store/src/phrase_bindings.rs
index 09fb2227..82c5e857 100644
--- a/crates/utopia-store/src/phrase_bindings.rs
+++ b/crates/utopia-store/src/phrase_bindings.rs
@@ -101,6 +101,28 @@ pub async fn signatures(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<PhraseSigna
Ok(sqlx::query_as(&sql).bind(kb_id).fetch_all(pool).await?)
}
+/// 按 id 取一条绑定的签名(人在队列里定它时用):短语、两端的类、宾语是不是字面值,
+/// 例句照判定时记下的,陈述数同。
+pub async fn signature_of(
+ pool: &PgPool,
+ kb_id: Uuid,
+ id: Uuid,
+) -> AppResult<Option<PhraseSignature>> {
+ Ok(sqlx::query_as(
+ "SELECT b.phrase, b.subject_type_id, st.key AS subject_type_key,
+ b.object_type_id, ot.key AS object_type_key, b.object_is_value,
+ b.statement_count::bigint AS count, b.examples, '{}'::text[] AS quotes
+ FROM phrase_bindings b
+ LEFT JOIN entity_types st ON st.id = b.subject_type_id
+ LEFT JOIN entity_types ot ON ot.id = b.object_type_id
+ WHERE b.kb_id = $1 AND b.id = $2",
+ )
+ .bind(kb_id)
+ .bind(id)
+ .fetch_optional(pool)
+ .await?)
+}
+
/// 一条签名判成了什么。
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct Binding {
diff --git a/crates/utopia-store/src/review.rs b/crates/utopia-store/src/review.rs
index 4ccdf3ef..12323ce7 100644
--- a/crates/utopia-store/src/review.rs
+++ b/crates/utopia-store/src/review.rs
@@ -67,7 +67,9 @@ pub async fn counts(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewCounts> {
WHERE rr.kb_id = $1 AND rr.status = 'pending'
AND NOT EXISTS (SELECT 1 FROM agent_decisions d
WHERE d.target_kind = 'review' AND d.target_id = rr.id
- AND d.status = 'proposed')) AS agent_queue",
+ AND d.status = 'proposed')) AS agent_queue,
+ (SELECT count(*) FROM (SELECT 1 FROM phrase_bindings WHERE kb_id = $1 AND status = 'undecided'
+ UNION ALL SELECT 1 FROM type_bindings WHERE kb_id = $1 AND status = 'undecided') a) AS alignment",
unconfirmed = UNCONFIRMED_FACT,
same = crate::resolution::TypeFilter::Same.clause(),
conflict = crate::resolution::TypeFilter::Conflict.clause(),
diff --git a/crates/utopia-store/src/review_summary.rs b/crates/utopia-store/src/review_summary.rs
index ba92f12c..0c31aa8f 100644
--- a/crates/utopia-store/src/review_summary.rs
+++ b/crates/utopia-store/src/review_summary.rs
@@ -61,6 +61,8 @@ struct WaitingRow {
violations_oldest: Option<DateTime<Utc>>,
defects: i64,
defects_oldest: Option<DateTime<Utc>>,
+ alignment: i64,
+ alignment_oldest: Option<DateTime<Utc>>,
}
async fn waiting(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewWaiting> {
@@ -96,7 +98,11 @@ async fn waiting(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewWaiting> {
(SELECT count(*) FROM ontology_defects
WHERE kb_id = $1 AND status = 'open') AS defects,
(SELECT min(detected_at) FROM ontology_defects
- WHERE kb_id = $1 AND status = 'open') AS defects_oldest",
+ WHERE kb_id = $1 AND status = 'open') AS defects_oldest,
+ (SELECT count(*) FROM (SELECT 1 FROM phrase_bindings WHERE kb_id = $1 AND status = 'undecided'
+ UNION ALL SELECT 1 FROM type_bindings WHERE kb_id = $1 AND status = 'undecided') a) AS alignment,
+ (SELECT min(decided_at) FROM (SELECT decided_at FROM phrase_bindings WHERE kb_id = $1 AND status = 'undecided'
+ UNION ALL SELECT decided_at FROM type_bindings WHERE kb_id = $1 AND status = 'undecided') a) AS alignment_oldest",
unconfirmed = UNCONFIRMED_FACT,
);
let r: WaitingRow = sqlx::query_as(&sql)
@@ -113,6 +119,7 @@ async fn waiting(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewWaiting> {
lowconf: wait(r.lowconf, r.lowconf_oldest),
violations: wait(r.violations, r.violations_oldest),
defects: wait(r.defects, r.defects_oldest),
+ alignment: wait(r.alignment, r.alignment_oldest),
})
}
diff --git a/docs/design/governance.md b/docs/design/governance.md
index adcac1a8..f058bf3d 100644
--- a/docs/design/governance.md
+++ b/docs/design/governance.md
@@ -9,8 +9,11 @@ Records: [0025] (the governor), [0026] (why), [0027] (the impact gate), [0028] (
**Queues, grouped by where an item came from.** Review holds nods (`pending_facts`, placed first),
duplicates (`resolution_reviews`), conflicts (`fact_conflicts`), unconfirmed (every evidence chunk
-superseded), low-confidence (`confidence < 0.75`), violations (`axiom_violations`) and defects
-(`ontology_defects`), plus the Agent queue; ontology proposals sit on the ontology page and mappings
+superseded), low-confidence (`confidence < 0.75`), violations (`axiom_violations`), defects
+(`ontology_defects`) and alignment (a phrase signature or a kind word the aligner's two votes
+split on, `phrase_bindings` and `type_bindings` in `undecided`; a person binds it to a property
+with a direction or to a class, or says none fits, and the typed graph recomputes at once; the
+aligner never overrides a person, #754), plus the Agent queue; ontology proposals sit on the ontology page and mappings
on their own page [0011, 0015, 0017, 0025]. Every human decision is a ledger event with an actor
(`review.merge`, `review.keep`, `merge.revert`, `fact.*`, `conflict.*`) and may carry a `rationale`,
asked as "What told you?", optional, written as `why` on the event [0026].
@@ -106,7 +109,7 @@ for 589 pairs [0025 d10].
conflicts queue, the low-confidence handling is dropped. Cut 2 (violations, defects, mappings)
is open.
- **Queues organised by what a decision changes** [#725]: ontology proposals; alignment (a
- signature or rule the aligner cannot settle); time anchors (a missing or conflicting document
+ signature or rule the aligner cannot settle; the signature half is built, #754); time anchors (a missing or conflicting document
date, an unanchored mention); identity (pairs evidence cannot settle, merges the gate held);
typed-fact errata; cross-document conflicts; nods. Agents handle every item; people see what an
agent could not settle or what one decision resolves at once. Cards are one template per queue,
diff --git a/web/src/api.ts b/web/src/api.ts
index 9f4a110a..bd3ff9bd 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -467,6 +467,8 @@ export type ReviewQueue =
| "mappings"
| "violations"
| "defects"
+ // 对齐器两票不一致的签名与类别词(#725,0044 决定 3)
+ | "alignment"
| "merges"
// agent 的每一笔(0025):建议、自动裁决与人的回答
| "agent";
@@ -488,6 +490,8 @@ export interface ReviewCounts {
mappings: number;
violations: number;
defects: number;
+ /** 对齐器拿不定的签名与类别词(#725) */
+ alignment: number;
merges: number;
/** agent 写下、等人回答的建议(0025) */
agent: number;
@@ -694,6 +698,35 @@ export interface AxiomViolation {
}
/** 本体自己的一处自相矛盾。**与 AxiomViolation 不是一回事**:那个说
* 「事实与定义抵触」,这个说「定义自己站不住」,后者更根本 */
+/** 对齐队列里的一条(#725):一条短语签名,或一个类别词,都是对齐器两票不一致、等人定的 */
+export type AlignmentItem =
+ | {
+ kind: "phrase";
+ id: string;
+ phrase: string;
+ subject_class: string | null;
+ object_class: string | null;
+ object_is_value: boolean;
+ statement_count: number;
+ examples: string[];
+ votes: { first?: AlignmentVote | null; second?: AlignmentVote | null } | null;
+ decided_at: string;
+ }
+ | {
+ kind: "kind_word";
+ kind_word: string;
+ words: string[];
+ examples: string[];
+ phrases: string[];
+ entity_count: number;
+ votes: { first?: string | null; second?: string | null } | null;
+ decided_at: string;
+ };
+export interface AlignmentVote {
+ property: string;
+ direction: "forward" | "reverse";
+}
+
export interface OntologyDefect {
id: string;
kind:
@@ -829,7 +862,14 @@ export interface ReviewSummary {
/** agent 在这个库里做过什么(0025) */
agent: { running: boolean; queue: number; open: number; last_7d: AgentWindow; last_30d: AgentWindow };
waiting: Record<
- "pending" | "duplicates" | "conflicts" | "unconfirmed" | "lowconf" | "violations" | "defects",
+ | "pending"
+ | "duplicates"
+ | "conflicts"
+ | "unconfirmed"
+ | "lowconf"
+ | "violations"
+ | "defects"
+ | "alignment",
QueueWait
>;
decided: {
@@ -2252,6 +2292,23 @@ export const api = {
defects_found: number;
defects_new: number;
}>(`/api/v1/kbs/${kbId}/consistency/check`, { method: "POST" }),
+ /** 人定一条短语签名:属性与方向,或没有(陈述留在开放图谱)。类型化图谱立刻重算 */
+ decideAlignmentPhrase: (
+ kbId: string,
+ bindingId: string,
+ property: string | null,
+ direction: "forward" | "reverse",
+ ) =>
+ request<{ ok: boolean; typed: { added: number; merged: number; retired: number } }>(
+ `/api/v1/kbs/${kbId}/review/alignment/phrases/${bindingId}`,
+ { method: "POST", body: JSON.stringify({ property, direction }) },
+ ),
+ /** 人定一个类别词:类,或没有。它名下的实体换类,短语签名跟着重判 */
+ decideAlignmentKindWord: (kbId: string, kindWord: string, cls: string | null) =>
+ request<{ ok: boolean }>(
+ `/api/v1/kbs/${kbId}/review/alignment/kind-words/${encodeURIComponent(kindWord)}`,
+ { method: "POST", body: JSON.stringify({ class: cls }) },
+ ),
/** 对一处本体缺陷表态。**两个出路**——它压根没看数据,没有「数据错了」这条 */
decideDefect: (
kbId: string,
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 673ca27f..ac8d81a3 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -1746,6 +1746,7 @@ export const en = {
railMappings: "Data mapping",
railViolations: "Axioms",
railDefects: "Ontology",
+ railAlignment: "Alignment",
railDecisions: "Decisions",
railMerges: "Merges",
railAgent: "Agent",
@@ -1892,6 +1893,21 @@ export const en = {
: `${ok} pairs decided`
: `${ok} decided, ${failed} could not be — they stay in the queue`,
lowConfidence: "Low-confidence facts",
+ // 对齐队列(#725)
+ alignment: "The aligner could not settle these",
+ alignmentHint:
+ "A phrase between two kinds of thing, or a kind word, where the aligner's two votes disagreed. Pick the property or class the documents' words mean, or say none fits: the statements then stay in the open graph. Your decision stands; the aligner never overrides a person.",
+ alignmentValue: "a value",
+ alignmentNone: "none fits",
+ alignmentForward: "as written",
+ alignmentReverse: "reversed",
+ alignmentBind: "Bind",
+ alignmentLeaveOpen: "Leave open",
+ alignmentStatements: (n: number) => (n === 1 ? "1 statement" : `${n} statements`),
+ alignmentEntities: (n: number) => (n === 1 ? "1 thing" : `${n} things`),
+ alignmentVotes: (first: string, second: string) => `Votes: ${first} · ${second}`,
+ alignmentTyped: (kept: number, retired: number) =>
+ `Typed graph recomputed: ${kept} statements typed, ${retired} rows retired`,
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.",
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index ca6cb820..77548acc 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -1529,6 +1529,7 @@ export const zh: Strings = {
railMappings: "数据映射",
railViolations: "公理",
railDefects: "本体",
+ railAlignment: "对齐",
railDecisions: "决定",
railMerges: "合并",
railAgent: "Agent",
@@ -1653,6 +1654,20 @@ export const zh: Strings = {
batchDone: (ok, failed) =>
failed === 0 ? `已裁 ${ok} 对` : `已裁 ${ok} 对,${failed} 对没成,留在队列里`,
lowConfidence: "低置信度事实",
+ // 对齐队列(#725)
+ alignment: "对齐器拿不定的",
+ alignmentHint:
+ "两类东西之间的一个说法,或一个类别词,对齐器的两票不一致。选出文档这个说法对应本体的哪个属性或类,或者说没有对得上的:那些陈述就留在开放图谱里。你定了就算数,对齐器不会改人的判定。",
+ alignmentValue: "一个值",
+ alignmentNone: "没有对得上的",
+ alignmentForward: "照原文方向",
+ alignmentReverse: "反过来",
+ alignmentBind: "绑定",
+ alignmentLeaveOpen: "留在开放图谱",
+ alignmentStatements: (n: number) => `${n} 条陈述`,
+ alignmentEntities: (n: number) => `${n} 样东西`,
+ alignmentVotes: (first: string, second: string) => `两票:${first} · ${second}`,
+ alignmentTyped: (kept: number, retired: number) => `类型化图谱已重算:${kept} 条成了类型化事实,${retired} 行作废`,
defects: "本体自相矛盾",
defectsHint:
"定义本身的问题,没有牵涉任何事实。这一档排在前面:定义站不住的时候,据它报出来的每一条事实级结论都可疑。",
diff --git a/web/src/pages/Review.tsx b/web/src/pages/Review.tsx
index 26bcd6ac..6bb0b4d3 100644
--- a/web/src/pages/Review.tsx
+++ b/web/src/pages/Review.tsx
@@ -10,6 +10,9 @@ import {
type ReviewQueue,
type ReviewTypeFilter,
type OntologyDefect,
+ type AlignmentItem,
+ type EntityTypeView,
+ type RelationTypeView,
type ConflictItem,
type FactReviewItem,
type MergeLog,
@@ -38,6 +41,7 @@ import {
RAIL_CLS,
RailItem,
Segmented,
+ SearchSelect,
Status,
cn,
type ChipTone,
@@ -695,6 +699,135 @@ function DecisionRow({ e }: { e: ReviewHistoryEvent }) {
* 因为人要判断的正是它对不对。概念名与源是身份,unit 是答里必须带的量纲。 */
/** 本体自己的一处自相矛盾。**两个按钮而不是三个**——这一档压根没看数据,
* 所以没有「数据错了」这条出路,只能是「我去改了本体」或「先放着」。 */
+function voteText(v: { property: string; direction: string } | string | null | undefined): string {
+ if (v === undefined || v === null) return S.review.alignmentNone;
+ if (typeof v === "string") return v;
+ return `${v.property} · ${v.direction === "reverse" ? S.review.alignmentReverse : S.review.alignmentForward}`;
+}
+
+/** 一条短语签名:短语、两端的类、例句、两票;人选属性与方向,或「没有」 */
+function AlignmentPhraseRow({
+ item,
+ properties,
+ busy,
+ onDecide,
+}: {
+ item: Extract<AlignmentItem, { kind: "phrase" }>;
+ properties: RelationTypeView[];
+ busy: boolean;
+ onDecide: (property: string | null, direction: "forward" | "reverse") => void;
+}) {
+ const first = item.votes?.first ?? null;
+ const second = item.votes?.second ?? null;
+ const [property, setProperty] = useState<string>(first?.property ?? second?.property ?? "");
+ const [direction, setDirection] = useState<"forward" | "reverse">(
+ first?.direction ?? second?.direction ?? "forward",
+ );
+ // 字面值当宾语的签名只配属性(attribute),两样东西之间的只配关系(relation)
+ const fitting = properties.filter((p) =>
+ item.object_is_value ? p.kind === "attribute" : p.kind === "relation",
+ );
+ return (
+ <div className="glass rounded-panel p-3">
+ <div className="flex items-baseline gap-2 flex-wrap">
+ <span className="text-body text-ink">“{item.phrase}”</span>
+ <span className="text-small text-ink-2">
+ {item.subject_class ?? "?"} → {item.object_is_value ? S.review.alignmentValue : (item.object_class ?? "?")}
+ </span>
+ <span className="text-small text-ink-2">{S.review.alignmentStatements(item.statement_count)}</span>
+ </div>
+ {item.examples.length > 0 && (
+ <div className="mt-1 space-y-1 text-small text-ink-2">
+ {item.examples.map((e, i) => (
+ <div key={i}>{e}</div>
+ ))}
+ </div>
+ )}
+ <div className="mt-1 text-small text-ink-2">
+ {S.review.alignmentVotes(voteText(first), voteText(second))}
+ </div>
+ <div className={CARD_ACTIONS}>
+ <SearchSelect
+ size="sm"
+ className="w-56"
+ value={property}
+ onChange={setProperty}
+ options={[
+ { value: "", label: S.review.alignmentNone },
+ ...fitting.map((p) => ({ value: p.key, label: p.label })),
+ ]}
+ />
+ {property && !item.object_is_value && (
+ <Segmented
+ size="sm"
+ value={direction}
+ onChange={setDirection}
+ options={[
+ { value: "forward", label: S.review.alignmentForward },
+ { value: "reverse", label: S.review.alignmentReverse },
+ ]}
+ />
+ )}
+ <Button size="sm" disabled={busy} onClick={() => onDecide(property || null, direction)}>
+ {property ? S.review.alignmentBind : S.review.alignmentLeaveOpen}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+/** 一个类别词:词、写法、例名、它们参与的短语、两票;人选类,或「没有」 */
+function AlignmentKindWordRow({
+ item,
+ classes,
+ busy,
+ onDecide,
+}: {
+ item: Extract<AlignmentItem, { kind: "kind_word" }>;
+ classes: EntityTypeView[];
+ busy: boolean;
+ onDecide: (cls: string | null) => void;
+}) {
+ const first = item.votes?.first ?? null;
+ const second = item.votes?.second ?? null;
+ const [cls, setCls] = useState<string>(first ?? second ?? "");
+ return (
+ <div className="glass rounded-panel p-3">
+ <div className="flex items-baseline gap-2 flex-wrap">
+ <span className="text-body text-ink">{item.kind_word}</span>
+ {item.words.length > 0 && (
+ <span className="text-small text-ink-2">{item.words.join(" · ")}</span>
+ )}
+ <span className="text-small text-ink-2">{S.review.alignmentEntities(item.entity_count)}</span>
+ </div>
+ {item.examples.length > 0 && (
+ <div className="mt-1 text-small text-ink-2">{item.examples.join(" · ")}</div>
+ )}
+ {item.phrases.length > 0 && (
+ <div className="mt-1 text-small text-ink-2">{item.phrases.map((p) => `—${p}→`).join(" ")}</div>
+ )}
+ <div className="mt-1 text-small text-ink-2">
+ {S.review.alignmentVotes(voteText(first), voteText(second))}
+ </div>
+ <div className={CARD_ACTIONS}>
+ <SearchSelect
+ size="sm"
+ className="w-56"
+ value={cls}
+ onChange={setCls}
+ options={[
+ { value: "", label: S.review.alignmentNone },
+ ...classes.map((c) => ({ value: c.key, label: c.label })),
+ ]}
+ />
+ <Button size="sm" disabled={busy} onClick={() => onDecide(cls || null)}>
+ {cls ? S.review.alignmentBind : S.review.alignmentLeaveOpen}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
function DefectRow({
defect: d,
busy,
@@ -998,6 +1131,8 @@ type Sel =
| "violations"
// 本体自己的自相矛盾。**与 violations 分开**:那一档看事实,这一档只看定义
| "defects"
+ // 对齐器两票不一致的签名与类别词(#725,0044 决定 3):问的是「这个说法是本体的哪个属性」
+ | "alignment"
// agent 的每一笔(0025):建议等人答,自动裁的可撤。它不是七档之一——
// 七档问「这条知识对不对」,这一档问「机器替你办的对不对」
| "agent"
@@ -1013,6 +1148,7 @@ const QUEUE_FETCHED: ReviewQueue[] = [
"lowconf",
"violations",
"defects",
+ "alignment",
"merges",
"agent",
];
@@ -1025,6 +1161,7 @@ const QUEUE_ORDER: Sel[] = [
"lowconf",
"violations",
"defects",
+ "alignment",
];
/** 有内容区、要翻页的那些档——总览不翻页 */
type Paged = Exclude<Sel, "overview">;
@@ -1037,6 +1174,7 @@ const PAGE_SIZE: Record<Paged, number> = {
lowconf: FACT_PAGE,
violations: FACT_PAGE,
defects: FACT_PAGE,
+ alignment: FACT_PAGE,
merges: MERGE_PAGE,
decisions: 20,
agent: 20,
@@ -1205,6 +1343,28 @@ export function Review() {
}) => api.decideDefect(kb!.id, id, resolution),
onSettled: invalidate,
});
+ const alignmentPhraseAction = useMutation({
+ mutationFn: ({
+ id,
+ property,
+ direction,
+ }: {
+ id: string;
+ property: string | null;
+ direction: "forward" | "reverse";
+ }) => api.decideAlignmentPhrase(kb!.id, id, property, direction),
+ onSuccess: (r) => {
+ if (r.typed.added + r.typed.merged + r.typed.retired > 0) {
+ toast.success(S.review.alignmentTyped(r.typed.added + r.typed.merged, r.typed.retired));
+ }
+ },
+ onSettled: invalidate,
+ });
+ const alignmentKindWordAction = useMutation({
+ mutationFn: ({ kindWord, cls }: { kindWord: string; cls: string | null }) =>
+ api.decideAlignmentKindWord(kb!.id, kindWord, cls),
+ onSettled: invalidate,
+ });
const violationAction = useMutation({
mutationFn: ({
id,
@@ -1275,6 +1435,7 @@ export function Review() {
mappings: c?.mappings ?? 0,
violations: c?.violations ?? 0,
defects: c?.defects ?? 0,
+ alignment: c?.alignment ?? 0,
merges: c?.merges ?? 0,
decisions: history.data?.total ?? 0,
agent: c?.agent ?? 0,
@@ -1288,6 +1449,13 @@ export function Review() {
const asConflicts = () => rows as ConflictItem[];
const asViolations = () => rows as AxiomViolation[];
const asDefects = () => rows as OntologyDefect[];
+ const asAlignment = () => rows as AlignmentItem[];
+ // 对齐卡片要列本体的类与属性给人选;只在这一档拉
+ const ontology = useQuery({
+ queryKey: ["ontology", kb?.id],
+ queryFn: () => api.ontology(kb!.id),
+ enabled: !!kb && queueSel === "alignment",
+ });
const asMerges = () => rows as MergeLog[];
const asAgent = () => rows as AgentDecision[];
// agent 正在裁的一对(0025):任务在跑、这一对标着 adjudicating。批量选页时跳过它们
@@ -1324,6 +1492,7 @@ export function Review() {
hint: S.review.violationsHint,
},
defects: { title: S.review.defects, hint: S.review.defectsHint },
+ alignment: { title: S.review.alignment, hint: S.review.alignmentHint },
decisions: { title: S.review.decisionsTitle, hint: S.review.decisionsHint },
merges: { title: S.review.mergeHistory, hint: null },
agent: { title: S.review.agentTitle, hint: S.review.agentHint },
@@ -1397,6 +1566,13 @@ export function Review() {
>
{S.review.railDefects}
</RailItem>
+ <RailItem
+ active={active === "alignment"}
+ count={counts.alignment}
+ onClick={() => select("alignment")}
+ >
+ {S.review.railAlignment}
+ </RailItem>
{/* agent 的队列(0025):徽标是等人回答的建议数 */}
<RailItem
active={active === "agent"}
@@ -1719,6 +1895,45 @@ export function Review() {
</div>
)}
+ {active === "alignment" && (
+ <div className="space-y-3">
+ {counts.alignment === 0 && (
+ <div className="glass rounded-panel p-8 text-center text-body text-ink-2">
+ {S.review.categoryEmpty}
+ </div>
+ )}
+ {asAlignment().map((item) =>
+ item.kind === "phrase" ? (
+ <AlignmentPhraseRow
+ key={item.id}
+ item={item}
+ properties={ontology.data?.relation_types ?? []}
+ busy={
+ alignmentPhraseAction.isPending &&
+ alignmentPhraseAction.variables?.id === item.id
+ }
+ onDecide={(property, direction) =>
+ alignmentPhraseAction.mutate({ id: item.id, property, direction })
+ }
+ />
+ ) : (
+ <AlignmentKindWordRow
+ key={item.kind_word}
+ item={item}
+ classes={ontology.data?.entity_types ?? []}
+ busy={
+ alignmentKindWordAction.isPending &&
+ alignmentKindWordAction.variables?.kindWord === item.kind_word
+ }
+ onDecide={(cls) =>
+ alignmentKindWordAction.mutate({ kindWord: item.kind_word, cls })
+ }
+ />
+ ),
+ )}
+ </div>
+ )}
+
{active === "violations" && (
<div className="space-y-3">
{/* 按钮在这一档里,不在页头:只有看这一档的人才想重跑。
diff --git a/web/src/pages/ReviewOverview.tsx b/web/src/pages/ReviewOverview.tsx
index c7c661cd..9e2237fd 100644
--- a/web/src/pages/ReviewOverview.tsx
+++ b/web/src/pages/ReviewOverview.tsx
@@ -17,6 +17,7 @@ const WAITING: { key: WaitingQueue; label: string }[] = [
{ key: "lowconf", label: S.review.railLowConfidence },
{ key: "violations", label: S.review.railViolations },
{ key: "defects", label: S.review.railDefects },
+ { key: "alignment", label: S.review.railAlignment },
];
/** 从某个时刻到现在整几天;不满一天算 0 */