World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Two things the system did that nobody could see afterwards (#112)
WaylandYangb1b2bb8d5160
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rsindex 1baaac5f..c9e42b4e 100644--- a/crates/utopia-core/src/models.rs+++ b/crates/utopia-core/src/models.rs@@ -512,15 +512,23 @@ pub struct EntityFact {/// 账本 append-only,所以"我们曾经怎么认为"全部留存:一条事实行最多产出两个/// 事件——写入(asserted / corrected)与作废(rejected,仅当没有后继修正行时;/// 有后继的话这次死亡已由那条 corrected 解释,不重复记)。+///+/// **不是每个事件都来自一条事实。** 改类(`retyped` / `retype_reverted`)来自+/// `entity_retypes`:它没有谓词、没有对方、没有方向,那几个字段因此可空。+/// 从前这里只有事实事件,于是「改了类」在实体历史里完全不显形——0001 P3a 记着+/// 「可撤销不等于会被撤销」,错了不会自己冒出来。#[derive(Debug, Clone, Serialize, sqlx::FromRow)]pub struct EntityHistoryEvent {- pub fact_id: Uuid,- /// 事件发生的记录时刻(写入 = recorded_at,作废 = invalidated_at)+ /// 事实事件才有。改类事件为 None+ pub fact_id: Option<Uuid>,+ /// 事件发生的记录时刻(写入 = recorded_at,作废 = invalidated_at,+ /// 改类 = entity_retypes.created_at / reverted_at)pub at: DateTime<Utc>,/// asserted(首次断言)| corrected(区间被修正)| rejected(认知被推翻)+ /// | merged(并进了另一条断言)| retyped(改了类)| retype_reverted(改类被撤销)pub kind: String,- pub direction: String,- pub predicate_label: String,+ pub direction: Option<String>,+ pub predicate_label: Option<String>,pub other_name: Option<String>,pub object_value: Option<serde_json::Value>,pub valid_from: Option<DateTime<Utc>>,@@ -532,14 +540,17 @@ pub struct EntityHistoryEvent {/// 结束端的粒度,外加一个 `unknown`——**原文说它结束了,但没说哪天**。/// `valid_to` 与它都为 None 才是「仍在持续」(迁移 0046)pub valid_to_precision: Option<String>,- pub confidence: f32,- /// 人工操作者;NULL = 引擎自动(抽取写入 / 时态对账闭合)+ pub confidence: Option<f32>,+ /// 人工操作者;NULL = 引擎自动(抽取写入 / 时态对账闭合 / 高置信改类)pub actor_name: Option<String>,/// 触发本次变更的审计动作(fact.close / conflict.close_old / fact.reject …)pub action: Option<String>,pub document_id: Option<Uuid>,pub filename: Option<String>,pub quote: Option<String>,+ /// 改类事件的两端。起点可空——0009 之后「从没有类到有类」是最常见的一次改类+ pub from_type_label: Option<String>,+ pub to_type_label: Option<String>,}/// 一段**记录时间**窗口里,整个库上发生的认知变更。diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rsindex 2dfa377e..a485ef6b 100644--- a/crates/utopia-server/src/api/mod.rs+++ b/crates/utopia-server/src/api/mod.rs@@ -175,6 +175,11 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {post(ontology_routes::restore_miss),).route("/kbs/{id}/ontology/suggest", post(ontology_routes::suggest))+ // 上次算出来、还没人表态的那些(0049)。刷新页面靠它,不必重跑模型+ .route(+ "/kbs/{id}/ontology/proposals",+ get(ontology_routes::stored_proposals).post(ontology_routes::decide_proposal),+ )// OWL 导入:预览与落库分开两个端点,绝不让上传即改本体。// 两者跑同一个 plan——分开的代码路径会分叉,而分叉意味着确认之后// 发生的事与刚看过的不一样diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rsindex 0c602b47..07c72682 100644--- a/crates/utopia-server/src/api/ontology_routes.rs+++ b/crates/utopia-server/src/api/ontology_routes.rs@@ -368,7 +368,92 @@ pub async fn suggest(.unwrap_or_else(|| "en".into());// 人工那条路 min_docs = 0:面板上「出现在 1 篇」这个数字是显示给人看的,// 他自己判断得了。替他滤掉,只是让他少一条信息- Ok(Json(build_proposals(&state, kb_id, &locale, 0).await?))+ let proposals = build_proposals(&state, kb_id, &locale, 0).await?;+ // 算完就写下来(0049)。从前这批结果只回给前端、存进一个 useState,+ // 刷新一次就没了——而重算要再调一次模型,且未必给出同一批归并+ persist_proposals(&state, kb_id, &proposals).await;+ Ok(Json(proposals))+}++/// 四个小节里的每一条都记一行。**失败不拦住返回**——提案已经算出来了,+/// 存不下只是下次要重算,把整个请求判失败反而把算出来的也丢了。+async fn persist_proposals(state: &AppState, kb_id: Uuid, proposals: &serde_json::Value) {+ const SECTIONS: [&str; 4] = [+ "entity_types",+ "relation_types",+ "attribute_types",+ "map_to",+ ];+ let mut rows: Vec<(String, String, serde_json::Value)> = Vec::new();+ for section in SECTIONS {+ let Some(items) = proposals.get(section).and_then(|v| v.as_array()) else {+ continue;+ };+ for it in items {+ // key 是这一条的身份(迁移里的唯一约束用的就是它)。没有 key 的+ // 存不了,也没法在采纳时对回来——跳过而不是编一个+ let Some(key) = it.get("key").and_then(|k| k.as_str()) else {+ continue;+ };+ rows.push((section.to_string(), key.to_string(), it.clone()));+ }+ }+ if let Err(e) = utopia_store::ontology::save_proposals(&state.pool, kb_id, &rows).await {+ tracing::warn!(%kb_id, error = %e, "本体提案落库失败,这一批只在本次响应里");+ }+}++/// 还等着人看的提案,按接口原来的形状拼回去。+///+/// 前端因此不必区分「刚算出来的」与「上次存下的」——两者同一个类型、同一套渲染。+pub async fn stored_proposals(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path(kb_id): Path<Uuid>,+) -> ApiResult<Json<serde_json::Value>> {+ require_kb(&state, &user, kb_id, Role::Viewer).await?;+ let stored = utopia_store::ontology::open_proposals(&state.pool, kb_id).await?;+ let mut out = json!({+ "entity_types": [], "relation_types": [], "attribute_types": [], "map_to": []+ });+ for p in stored {+ if let Some(arr) = out.get_mut(&p.section).and_then(|v| v.as_array_mut()) {+ arr.push(p.payload);+ }+ }+ Ok(Json(out))+}++#[derive(Deserialize)]+pub struct DecideProposalReq {+ pub section: String,+ pub key: String,+ /// adopted | rejected+ pub status: String,+}++/// 一条提案有人表态了。**改状态不删行**:采纳发生过、拒绝也发生过,+/// 而拒绝留痕正是下一轮 Suggest 不再把它刷回待看的依据。+pub async fn decide_proposal(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path(kb_id): Path<Uuid>,+ Json(req): Json<DecideProposalReq>,+) -> ApiResult<Json<serde_json::Value>> {+ require_kb(&state, &user, kb_id, Role::Editor).await?;+ if !matches!(req.status.as_str(), "adopted" | "rejected") {+ return Err(AppError::invalid("bad_status", "status 只能是 adopted 或 rejected").into());+ }+ utopia_store::ontology::decide_proposal(+ &state.pool,+ kb_id,+ &req.section,+ &req.key,+ &req.status,+ user.id,+ )+ .await?;+ Ok(Json(json!({ "ok": true })))}/// 生成本体扩展提案。人工点 Suggest 与冷启动自动扩本体走同一条路——@@ -1313,7 +1398,7 @@ pub async fn type_resolution_apply(Path(kb_id): Path<Uuid>,) -> ApiResult<Json<serde_json::Value>> {require_kb(&state, &user, kb_id, Role::Editor).await?;- let outcome = crate::type_resolution::resolve(&state, kb_id).await?;+ let outcome = crate::type_resolution::resolve(&state, kb_id, Some(user.id)).await?;let _ = utopia_store::audit::record(&state.pool,Some(kb_id),@@ -1387,7 +1472,9 @@ pub async fn approve_refinement(let (batch, moved) = if picks.is_empty() {(None, 0)} else {- let (b, n) = utopia_store::resolution::retype_entities(&state.pool, kb_id, &picks).await?;+ let (b, n) =+ utopia_store::resolution::retype_entities(&state.pool, kb_id, &picks, Some(user.id))+ .await?;(Some(b), n)};let _ = utopia_store::audit::record(diff --git a/crates/utopia-server/src/bootstrap_ontology.rs b/crates/utopia-server/src/bootstrap_ontology.rsindex e8c80f30..e9394831 100644--- a/crates/utopia-server/src/bootstrap_ontology.rs+++ b/crates/utopia-server/src/bootstrap_ontology.rs@@ -200,6 +200,8 @@ pub async fn bootstrap_ontology(state: &AppState, kb_id: Uuid) -> anyhow::Resultkb_id,type_id,&forms,+ // 系统的动作,不是谁的决定——与本文件下方审计写 NULL 同一条+ None,).await{@@ -408,7 +410,7 @@ pub async fn bootstrap_ontology(state: &AppState, kb_id: Uuid) -> anyhow::Result}// 类先建好、实体后抽出来是常态:把等着已存在类型的那些也收走- match utopia_store::resolution::sweep_proposed_types(&state.pool, kb_id).await {+ match utopia_store::resolution::sweep_proposed_types(&state.pool, kb_id, None).await {Ok(swept) => {for (batch, n) in swept {moved_total += n;diff --git a/crates/utopia-server/src/type_resolution.rs b/crates/utopia-server/src/type_resolution.rsindex c613d830..19ed622c 100644--- a/crates/utopia-server/src/type_resolution.rs+++ b/crates/utopia-server/src/type_resolution.rs@@ -364,7 +364,12 @@ pub struct ReviewItem {}/// 跑一遍类型消解:检索候选 → 裁决 → 三档处置。-pub async fn resolve(state: &AppState, kb_id: Uuid) -> AppResult<ResolutionOutcome> {+pub async fn resolve(+ state: &AppState,+ kb_id: Uuid,+ // 落库那一步记在谁头上。这条路是人在界面上按的,所以有人+ actor: Option<Uuid>,+) -> AppResult<ResolutionOutcome> {let items = preview(state, kb_id).await?;let items: Vec<_> = items.into_iter()@@ -499,7 +504,8 @@ pub async fn resolve(state: &AppState, kb_id: Uuid) -> AppResult<ResolutionOutcolet (batch, retyped) = if picks.is_empty() {(None, 0)} else {- let (b, n) = utopia_store::resolution::retype_entities(&state.pool, kb_id, &picks).await?;+ let (b, n) =+ utopia_store::resolution::retype_entities(&state.pool, kb_id, &picks, actor).await?;(Some(b), n)};Ok(ResolutionOutcome {diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rsindex 84b322f1..a575271f 100644--- a/crates/utopia-store/src/graph.rs+++ b/crates/utopia-store/src/graph.rs@@ -1076,15 +1076,36 @@ pub async fn entity_history(FROM efWHERE ef.invalidated_at IS NOT NULLAND NOT EXISTS (SELECT 1 FROM facts s WHERE s.supersedes = ef.id)+ ),+ -- 改类不是事实:没有谓词、没有对方、没有方向。它来自 entity_retypes,+ -- 一行最多产出两个事件——改动本身,以及撤销。+ --+ -- **撤销过的照样显示。** 读成「改过、又撤了」,不是没发生过。同一类错+ -- 这仓库栽过两次(#37;并入被读成撤回),所以这不是防御性编程+ rt AS (+ SELECT r.created_at AS at, 'retyped' AS kind, r.actor_id,+ tf.label AS from_type_label, tt.label AS to_type_label+ FROM entity_retypes r+ LEFT JOIN entity_types tf ON tf.id = r.from_type_id+ JOIN entity_types tt ON tt.id = r.to_type_id+ WHERE r.kb_id = $1 AND r.entity_id = $2+ UNION ALL+ SELECT r.reverted_at, 'retype_reverted', r.actor_id, tf.label, tt.label+ FROM entity_retypes r+ LEFT JOIN entity_types tf ON tf.id = r.from_type_id+ JOIN entity_types tt ON tt.id = r.to_type_id+ WHERE r.kb_id = $1 AND r.entity_id = $2 AND r.reverted_at IS NOT NULL)";let rows: Vec<EntityHistoryEvent> = sqlx::query_as(&format!("{EVENTS}+ SELECT * FROM (SELECT ev.id AS fact_id, ev.at, ev.kind, ev.direction,r.label AS predicate_label, o.canonical_name AS other_name,ev.object_value, ev.valid_from, ev.valid_from_precision,ev.valid_to, ev.valid_to_precision,ev.confidence, act.actor_name, act.action,- src.document_id, src.filename, src.quote+ src.document_id, src.filename, src.quote,+ NULL::text AS from_type_label, NULL::text AS to_type_labelFROM evJOIN relation_types r ON r.id = ev.predicate_idLEFT JOIN entities o ON o.id = ev.other_id@@ -1126,7 +1147,17 @@ pub async fn entity_history(WHERE fe.fact_id = ev.idORDER BY fe.doc_version DESC NULLS LAST LIMIT 1) src ON true- ORDER BY ev.at DESC, ev.id+ UNION ALL+ SELECT NULL::uuid, rt.at, rt.kind, NULL::text,+ NULL::text, NULL::text,+ NULL::jsonb, NULL::timestamptz, NULL::text,+ NULL::timestamptz, NULL::text,+ NULL::real, u.display_name, NULL::text,+ NULL::uuid, NULL::text, NULL::text,+ rt.from_type_label, rt.to_type_label+ FROM rt LEFT JOIN users u ON u.id = rt.actor_id+ ) x+ ORDER BY x.at DESC, x.fact_idLIMIT $3 OFFSET $4")).bind(kb_id)@@ -1135,11 +1166,14 @@ pub async fn entity_history(.bind(offset).fetch_all(pool).await?;- let (total,): (i64,) = sqlx::query_as(&format!("{EVENTS} SELECT count(*) FROM ev"))- .bind(kb_id)- .bind(entity_id)- .fetch_one(pool)- .await?;+ // 总数把改类那一支也算上,否则分页会少一截+ let (total,): (i64,) = sqlx::query_as(&format!(+ "{EVENTS} SELECT (SELECT count(*) FROM ev) + (SELECT count(*) FROM rt)"+ ))+ .bind(kb_id)+ .bind(entity_id)+ .fetch_one(pool)+ .await?;Ok((rows, total))}diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rsindex 5233b582..57f161bf 100644--- a/crates/utopia-store/src/ontology.rs+++ b/crates/utopia-store/src/ontology.rs@@ -1310,3 +1310,96 @@ pub async fn set_parents_bulk(pool: &PgPool, pairs: &[(Uuid, Uuid)]) -> AppResul.await?;Ok(())}++// ---------------------------------------------------------------------------+// 本体提案(见迁移 0049)+// ---------------------------------------------------------------------------++/// 一条落库的提案。`payload` 是接口原样返回的那一条。+#[derive(Debug, Clone, sqlx::FromRow)]+pub struct StoredProposal {+ pub section: String,+ pub key: String,+ pub payload: serde_json::Value,+}++/// 把一轮 Suggest 的结果写下来。+///+/// **已经有人表过态的不动。** `WHERE status = 'open'` 那一句是这个函数的全部要点:+/// 重跑 Suggest 会再次算出被拒绝过的那条提案(原材料还在 `ontology_misses` 里),+/// 不加这句它就会被刷回 open——等于每跑一次都把人的否决抹掉一次。+pub async fn save_proposals(+ pool: &PgPool,+ kb_id: Uuid,+ items: &[(String, String, serde_json::Value)],+) -> AppResult<()> {+ for (section, key, payload) in items {+ sqlx::query(+ "INSERT INTO ontology_proposals (id, kb_id, section, key, payload)+ VALUES ($1, $2, $3, $4, $5)+ ON CONFLICT (kb_id, section, key) DO UPDATE+ SET payload = EXCLUDED.payload, created_at = now()+ WHERE ontology_proposals.status = 'open'",+ )+ .bind(Uuid::now_v7())+ .bind(kb_id)+ .bind(section)+ .bind(key)+ .bind(payload)+ .execute(pool)+ .await?;+ }+ Ok(())+}++/// 还等着人看的提案。新的排前面——旧的那批已经被看过好几眼了。+pub async fn open_proposals(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<StoredProposal>> {+ Ok(sqlx::query_as(+ "SELECT section, key, payload FROM ontology_proposals+ WHERE kb_id = $1 AND status = 'open'+ ORDER BY created_at DESC, key",+ )+ .bind(kb_id)+ .fetch_all(pool)+ .await?)+}++/// 一条提案被采纳或拒绝了。+///+/// **改状态而不是删行**:采纳发生过、拒绝也发生过。跟 `fact_adoptions`、+/// `entity_retypes` 同一条路。拒绝留痕还有个当下就用得着的作用——下一轮+/// Suggest 不会把它刷回待看。+pub async fn decide_proposal(+ pool: &PgPool,+ kb_id: Uuid,+ section: &str,+ key: &str,+ status: &str,+ actor: Uuid,+) -> AppResult<()> {+ sqlx::query(+ "UPDATE ontology_proposals+ SET status = $4, decided_by = $5, decided_at = now()+ WHERE kb_id = $1 AND section = $2 AND key = $3 AND status = 'open'",+ )+ .bind(kb_id)+ .bind(section)+ .bind(key)+ .bind(status)+ .bind(actor)+ .execute(pool)+ .await?;+ Ok(())+}++/// 还有多少条等着看。0003 的缺口:关掉自动扩展开关之后没有「自上次以来有 N 条」+/// 的提醒,信号在面板里但没人主动看——有了这张表,提醒就是这一句。+pub async fn open_proposal_count(pool: &PgPool, kb_id: Uuid) -> AppResult<i64> {+ let (n,): (i64,) = sqlx::query_as(+ "SELECT count(*) FROM ontology_proposals WHERE kb_id = $1 AND status = 'open'",+ )+ .bind(kb_id)+ .fetch_one(pool)+ .await?;+ Ok(n)+}diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rsindex 9ba553c3..d95f2656 100644--- a/crates/utopia-store/src/resolution.rs+++ b/crates/utopia-store/src/resolution.rs@@ -1525,6 +1525,8 @@ pub async fn adopt_proposed_types(kb_id: Uuid,type_id: Uuid,forms: &[String],+ // None = 引擎自动(本体长出新类之后的收尾认领没有人在按)+ actor: Option<Uuid>,) -> AppResult<(Uuid, u32)> {let batch_id = Uuid::now_v7();if forms.is_empty() {@@ -1559,14 +1561,16 @@ pub async fn adopt_proposed_types(.execute(&mut *tx).await?;sqlx::query(- "INSERT INTO entity_retypes (batch_id, kb_id, entity_id, from_type_id, to_type_id)- VALUES ($1, $2, $3, $4, $5)",+ "INSERT INTO entity_retypes+ (batch_id, kb_id, entity_id, from_type_id, to_type_id, actor_id)+ VALUES ($1, $2, $3, $4, $5, $6)",).bind(batch_id).bind(kb_id).bind(entity_id).bind(from_type).bind(type_id)+ .bind(actor).execute(&mut *tx).await?;tx.commit().await?;@@ -1660,7 +1664,11 @@ fn normalize_type_key(s: &str) -> String {////// 只做**规整后精确同名**的匹配,不做近似——猜错就是把实体放进错的类,/// 而"再等一轮"的代价接近零。-pub async fn sweep_proposed_types(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<(Uuid, u32)>> {+pub async fn sweep_proposed_types(+ pool: &PgPool,+ kb_id: Uuid,+ actor: Option<Uuid>,+) -> AppResult<Vec<(Uuid, u32)>> {let pending = proposed_types(pool, kb_id).await?;let existing: Vec<(Uuid, String)> =sqlx::query_as("SELECT id, key FROM entity_types WHERE kb_id = $1")@@ -1674,7 +1682,8 @@ pub async fn sweep_proposed_types(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<(continue;};let (batch, n) =- adopt_proposed_types(pool, kb_id, *type_id, std::slice::from_ref(&p.form)).await?;+ adopt_proposed_types(pool, kb_id, *type_id, std::slice::from_ref(&p.form), actor)+ .await?;if n > 0 {out.push((batch, n));}@@ -1969,6 +1978,9 @@ pub async fn retype_entities(pool: &PgPool,kb_id: Uuid,picks: &[(Uuid, Uuid)],+ // None = 引擎自动裁决。跟 entity_merges.merged_by 一个约定,+ // 实体历史据此区分"某某某改的"与"高置信自动改的"+ actor: Option<Uuid>,) -> AppResult<(Uuid, u32)> {let batch_id = Uuid::now_v7();let mut moved = 0u32;@@ -2013,14 +2025,16 @@ pub async fn retype_entities(continue;};sqlx::query(- "INSERT INTO entity_retypes (batch_id, kb_id, entity_id, from_type_id, to_type_id)- VALUES ($1, $2, $3, $4, $5)",+ "INSERT INTO entity_retypes+ (batch_id, kb_id, entity_id, from_type_id, to_type_id, actor_id)+ VALUES ($1, $2, $3, $4, $5, $6)",).bind(batch_id).bind(kb_id).bind(entity_id).bind(from_type).bind(type_id)+ .bind(actor).execute(&mut *tx).await?;tx.commit().await?;diff --git a/migrations/0048_retype_actor.sql b/migrations/0048_retype_actor.sqlnew file mode 100644index 00000000..649242f8--- /dev/null+++ b/migrations/0048_retype_actor.sql@@ -0,0 +1,10 @@+-- 改类要能说出是谁改的。+--+-- `entity_retypes` 记了改动本身(何时、从哪个类到哪个类、撤没撤),唯独没记人。+-- 而这张表马上要出现在实体历史里(0001 P3a:「该补的是让改类在实体历史里显形」),+-- 一条写着「Vehicle ← 未分类」却不说谁干的记录,比不显示更容易被误读成引擎所为。+--+-- 可空 = 引擎自动裁决,跟 `entity_merges.merged_by` 已有的约定一字不差+-- (那边的注释写着「NULL = 自动合并(LLM 裁决高置信)」)。不给默认值:+-- 已有的行确实不知道是谁,编一个出来就是伪造归因。+ALTER TABLE entity_retypes ADD COLUMN actor_id UUID REFERENCES users(id);diff --git a/migrations/0049_ontology_proposals.sql b/migrations/0049_ontology_proposals.sqlnew file mode 100644index 00000000..147593d9--- /dev/null+++ b/migrations/0049_ontology_proposals.sql@@ -0,0 +1,40 @@+-- 本体提案落库。+--+-- 从前它只活在浏览器内存里(`Ontology.tsx` 的 `useState<OntologyProposals>`):+-- 刷新一次、切走一次、崩一次,整批提议就没了,想再看只能重跑一次模型。+--+-- **丢的不是原材料。** 未匹配的说法一直存在 `ontology_misses` 里。丢的是**聚类+-- 结果**——哪些说法被归到同一条提议底下、以及"采纳后将重新归类 N 条"那个估算。+-- 而那正是唯一能查证过并的东西:0003 记着模型建议把 `optimized_for` 并进+-- `runs_on`("为 RTX 优化"不等于"跑在 RTX 上"),**它是靠 tooltip 里看得见归并了+-- 哪些说法才被抓出来的**,并且成了"不该全自动归并"的直接证据。能查证的东西不该+-- 只活在一个页面的生命周期里。+CREATE TABLE ontology_proposals (+ id UUID PRIMARY KEY,+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,+ -- 提案分档,与接口返回的四个小节同名:+ -- entity_types | relation_types | attribute_types | map_to+ section TEXT NOT NULL,+ key TEXT NOT NULL,+ -- 那一条提案的原样:label、description、reason、forms、datatype、temporal…+ --+ -- **存 JSONB 而不是拆成列**:四个小节的形状本来就不同(关系有 temporal 与+ -- forms,属性有 datatype,map_to 有目标),拆开要么四张表要么一张稀疏宽表。+ -- 前端消费的也正是这个 JSON,存原样等于不改契约。要查归并了哪些说法仍然+ -- 查得动(`payload->'forms'`)+ payload JSONB NOT NULL,+ -- open = 还等着人看;adopted / rejected = 已经有人表过态+ status TEXT NOT NULL DEFAULT 'open'+ CHECK (status IN ('open', 'adopted', 'rejected')),+ decided_by UUID REFERENCES users(id),+ decided_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ -- 同一个库里同一档下的同一个 key 只有一条。重跑 Suggest 是刷新它,不是再堆一条+ UNIQUE (kb_id, section, key)+);++-- "还有多少条等着看"是这张表最常被问的问题(0003 的另一个缺口:关掉自动扩展+-- 开关之后没有"自上次以来有 N 个新说法"的提醒,信号在面板里但没人主动看)+CREATE INDEX ontology_proposals_open_idx+ ON ontology_proposals (kb_id, created_at DESC)+ WHERE status = 'open';diff --git a/web/src/api.ts b/web/src/api.tsindex 37b4db5f..8d7dbf73 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -354,14 +354,24 @@ export interface EntityFact {last_evidence_time: string | null;}-/** 实体的一次认知变更(记录时间轴上的事件,与 EntityFact 的有效时间轴正交)。 */+/** 实体的一次认知变更(记录时间轴上的事件,与 EntityFact 的有效时间轴正交)。+ *+ * 不是每个事件都来自一条事实:retyped / retype_reverted 来自改类账本,+ * 没有谓词、没有对方、没有方向。 */export interface EntityHistoryEvent {- fact_id: string;- /** 记录时刻:写入 = recorded_at,作废 = invalidated_at */+ /** 事实事件才有;改类事件为 null */+ fact_id: string | null;+ /** 记录时刻:写入 = recorded_at,作废 = invalidated_at,改类 = 改类那一刻 */at: string;- kind: "asserted" | "corrected" | "rejected";- direction: "out" | "in";- predicate_label: string;+ kind:+ | "asserted"+ | "corrected"+ | "rejected"+ | "merged"+ | "retyped"+ | "retype_reverted";+ direction: "out" | "in" | null;+ predicate_label: string | null;other_name: string | null;object_value: Record<string, unknown> | null;valid_from: string | null;@@ -369,13 +379,16 @@ export interface EntityHistoryEvent {valid_from_precision: string | null;/** year | month | day,外加 unknown = 原文说它结束了但没说哪天 */valid_to_precision: string | null;- confidence: number;- /** null = 引擎自动(抽取写入 / 时态对账闭合) */+ confidence: number | null;+ /** null = 引擎自动(抽取写入 / 时态对账闭合 / 高置信自动改类) */actor_name: string | null;action: string | null;document_id: string | null;filename: string | null;quote: string | null;+ /** 改类事件的两端。起点为 null = 从「未分类」改过来(0009 之后最常见的一种) */+ from_type_label: string | null;+ to_type_label: string | null;}export interface Evidence {@@ -942,6 +955,20 @@ export const api = {method: "DELETE",},),+ /** 上次算出来、还没人表态的提案(0049)。刷新页面靠它,不必重跑模型 */+ storedProposals: (kbId: string) =>+ request<OntologyProposals>(`/api/v1/kbs/${kbId}/ontology/proposals`),+ /** 一条提案有人表态了。改状态不删行——拒绝留痕,下一轮 Suggest 不再刷回待看 */+ decideProposal: (+ kbId: string,+ section: string,+ key: string,+ status: "adopted" | "rejected",+ ) =>+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/proposals`, {+ method: "POST",+ body: JSON.stringify({ section, key, status }),+ }),dismissMiss: (kbId: string, kind: string, key: string) =>request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/misses/dismiss`, {method: "POST",diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex cd4199c6..acfe73f3 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -567,6 +567,9 @@ export const en = {rejected: "Withdrawn",/* 并入另一条断言:内容一字未少,不是撤回 */merged: "Merged into an existing fact",+ /* 改的是节点上的类,一条事实都没动 */+ retyped: "Type changed",+ retype_reverted: "Type change undone",} as Record<string, string>,historyEngine: "engine",/* 有效区间的变化:修正后区间闭合到某个时点 */diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex f6bf4e9b..b34fc2c1 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -519,6 +519,8 @@ export const zh: Strings = {corrected: "区间被修正",rejected: "已撤回",merged: "并入了已有事实",+ retyped: "改了类",+ retype_reverted: "改类被撤销",},historyEngine: "引擎",historyClosedAt: (t: string) => `闭合于 ${t}`,diff --git a/web/src/pages/EntityHistory.tsx b/web/src/pages/EntityHistory.tsxindex b8667560..3e8f5457 100644--- a/web/src/pages/EntityHistory.tsx+++ b/web/src/pages/EntityHistory.tsx@@ -5,7 +5,7 @@import { useEffect, useState } from "react";import { useQuery } from "@tanstack/react-query";import { Link } from "@tanstack/react-router";-import { FileText, Merge, PencilLine, Undo2 } from "lucide-react";+import { FileText, Merge, PencilLine, Tag, Undo2 } from "lucide-react";import { api, type EntityHistoryEvent } from "../api";import { S } from "../i18n";import { Pager } from "../ui";@@ -19,6 +19,9 @@ const KIND_ICON = {rejected: Undo2,// 并入不是撤回:内容一字未少地进了另一条断言merged: Merge,+ // 改类不是事实变更:图上的节点换了个类,事实一条没动+ retyped: Tag,+ retype_reverted: Undo2,} as const;const KIND_TONE: Record<string, string> = {@@ -26,6 +29,8 @@ const KIND_TONE: Record<string, string> = {corrected: "text-[var(--u-warn)]",rejected: "text-[var(--u-danger)]",merged: "text-neutral-500",+ retyped: "text-neutral-500",+ retype_reverted: "text-[var(--u-warn)]",};const ymd = (iso: string) => iso.slice(0, 10);@@ -64,14 +69,25 @@ function EventRow({ e }: { e: EntityHistoryEvent }) {</span>{note && <span className="u-num text-[11px] text-neutral-500">{note}</span>}</div>- <div className="mt-0.5 text-[12.5px] text-neutral-400 truncate">- <span className="text-neutral-500">- {e.direction === "in" ? "← " : ""}- {e.predicate_label}- {e.direction === "in" ? "" : " →"}- </span>{" "}- <span className="text-neutral-200">{objectText(e)}</span>- </div>+ {/* 改类事件没有谓词也没有宾语,正文换成类的两端。+ 起点为空 = 从「未分类」改过来,0009 之后最常见的一种 */}+ {e.kind === "retyped" || e.kind === "retype_reverted" ? (+ <div className="mt-0.5 text-[12.5px] text-neutral-400 truncate">+ <span className="text-neutral-500">+ {e.from_type_label ?? S.graph.untyped} →{" "}+ </span>+ <span className="text-neutral-200">{e.to_type_label}</span>+ </div>+ ) : (+ <div className="mt-0.5 text-[12.5px] text-neutral-400 truncate">+ <span className="text-neutral-500">+ {e.direction === "in" ? "← " : ""}+ {e.predicate_label}+ {e.direction === "in" ? "" : " →"}+ </span>{" "}+ <span className="text-neutral-200">{objectText(e)}</span>+ </div>+ )}<div className="mt-0.5 flex items-center gap-1.5 text-[10.5px] text-neutral-600"><span className="u-num">{ymd(e.at)}</span><span>·</span>@@ -115,8 +131,9 @@ export function EntityHistory({ kbId, entityId }: { kbId: string; entityId: stri<div><p className="px-2 pb-1.5 text-[11px] text-neutral-600">{S.graph.historyHint}</p><div className="divide-y divide-white/[0.06]">+ {/* key 里用 fact_id ?? at:改类事件没有 fact_id */}{(q.data?.events ?? []).map((e) => (- <EventRow key={`${e.fact_id}-${e.kind}`} e={e} />+ <EventRow key={`${e.fact_id ?? e.at}-${e.kind}`} e={e} />))}</div><Pager total={total} pageSize={PER} page={page} onPage={setPage} />diff --git a/web/src/pages/Ontology.tsx b/web/src/pages/Ontology.tsxindex 7b6bc92e..e302c76c 100644--- a/web/src/pages/Ontology.tsx+++ b/web/src/pages/Ontology.tsx@@ -1297,6 +1297,26 @@ function MissesPanel({// 默认收起:已忽略的是**背景信息**,不该跟待处理的挤在一起抢注意力const [showDismissed, setShowDismissed] = useState(false);const [proposals, setProposals] = useState<OntologyProposals | null>(null);+ // 上次算出来、还没人表态的那些:刷新页面之后从库里捞回来(0049)。+ //+ // 从前这里只有上面那个 useState——刷新一次、切走一次,整批提议就没了,+ // 想再看只能重跑一次模型,而重跑未必给出同一批归并。归并了哪些说法正是+ // 唯一能查证过并的东西(0003 的 optimized_for → runs_on 就是这么抓出来的)+ const storedProposals = useQuery({+ queryKey: ["storedProposals", kbId],+ queryFn: () => api.storedProposals(kbId),+ });+ useEffect(() => {+ // 只在还没有本地结果时回填。刚点完 Suggest 的那一批更新,不该被覆盖+ if (proposals === null && storedProposals.data) {+ const d = storedProposals.data;+ const empty =+ !d.entity_types?.length &&+ !d.relation_types?.length &&+ !d.attribute_types?.length;+ if (!empty) setProposals(d);+ }+ }, [storedProposals.data, proposals]);// 最近一次采纳,供撤销。只留最近一次——旧批次要撤销走审计台账,// 那里本来就记着每次采纳动了哪个关系、多少条const [lastAdopt, setLastAdopt] = useState<{@@ -1361,6 +1381,8 @@ function MissesPanel({},);api.dismissMiss(kbId, "entity_type", p.key).catch(() => {});+ // 提案表态落库(0049):下一轮 Suggest 不会把它刷回待看+ api.decideProposal(kbId, "entity_types", p.key, "adopted").catch(() => {});onChanged();},onError,@@ -1407,6 +1429,7 @@ function MissesPanel({},);api.dismissMiss(kbId, "relation_type", p.key).catch(() => {});+ api.decideProposal(kbId, "relation_types", p.key, "adopted").catch(() => {});onChanged();},onError,@@ -1457,6 +1480,7 @@ function MissesPanel({);for (const form of p.forms ?? [])api.dismissMiss(kbId, "attribute_type", form).catch(() => {});+ api.decideProposal(kbId, "attribute_types", p.key, "adopted").catch(() => {});onChanged();},onError,