Skip to content

World's first open-source enterprise world model.

Extending the ontology is a setting, not something inferred from behaviour (#45)

WaylandYang694610ea9943
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index 6d110299..0fec4f3e 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -337,6 +337,9 @@ pub struct SurfacePredicate {
pub form: String,
/// 有多少条 live 的 related_to 事实由这个说法而来
pub fact_count: i64,
+ /// 出现在多少篇文档里。只在一篇里出现过的是那篇文档的用词,不是这个
+ /// 组织的词汇——自动扩展据此设门槛,人工提案只作参考不拦
+ pub doc_count: i64,
/// 一条样例("Dino Crisis (Steam) → GeForce NOW"),让人一眼判断这是什么关系
pub example: Option<String>,
}
@@ -581,6 +584,10 @@ pub struct KnowledgeBase {
pub visibility: String,
/// 部署的公共默认空间(第一个建的库):永远 open、不可删除
pub is_default: bool,
+ /// 抽取遇到本体外的说法时,是否允许系统自动把它补进本体并改写等它的事实。
+ /// 缺省开——新库的十个默认关系不是任何人选的,等人手工补齐之前图基本没法用。
+ /// 关掉不影响"留意":未匹配统计照常累积、照常可见,只是变成你点一下的提案。
+ pub auto_extend_ontology: bool,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
diff --git a/crates/utopia-server/src/api/kbs.rs b/crates/utopia-server/src/api/kbs.rs
index 081147b6..e9ffab9b 100644
--- a/crates/utopia-server/src/api/kbs.rs
+++ b/crates/utopia-server/src/api/kbs.rs
@@ -26,6 +26,9 @@ pub struct UpdateKbReq {
pub name: Option<String>,
pub description: Option<String>,
pub visibility: Option<String>,
+ /// 自动扩本体开关(缺省开;关掉不影响"留意",只是变成你点一下的提案)
+ #[serde(default)]
+ pub auto_extend_ontology: Option<bool>,
}
/// 用户可见的 KB 列表(restricted 库仅矩阵成员与系统管理员可见)。
@@ -73,7 +76,7 @@ pub async fn create(
)
.await?;
if let Some(v) = req.visibility.as_deref() {
- utopia_store::kbs::update(&state.pool, kb.id, None, None, Some(v)).await?;
+ utopia_store::kbs::update(&state.pool, kb.id, None, None, Some(v), None).await?;
}
utopia_store::access::set_kb_member(&state.pool, kb.id, user.id, "admin", Some(user.id))
.await?;
@@ -146,6 +149,7 @@ pub async fn update(
req.name.as_deref().map(str::trim),
req.description.as_deref(),
req.visibility.as_deref(),
+ req.auto_extend_ontology,
)
.await?;
// 审计只记不阻断
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index 50f63282..688c9da4 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -150,6 +150,10 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
"/kbs/{id}/ontology/surface-predicates",
get(ontology_routes::surface_predicates),
)
+ .route(
+ "/kbs/{id}/ontology/auto-extension",
+ get(ontology_routes::last_auto_extension),
+ )
.route(
"/kbs/{id}/ontology/adopt-predicate",
post(ontology_routes::adopt_predicate),
diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rs
index 7fa8f292..869fff6f 100644
--- a/crates/utopia-server/src/api/ontology_routes.rs
+++ b/crates/utopia-server/src/api/ontology_routes.rs
@@ -314,7 +314,7 @@ pub async fn dismiss_miss(
Json(req): Json<DismissMissReq>,
) -> ApiResult<Json<serde_json::Value>> {
require_kb(&state, &user, kb_id, Role::Editor).await?;
- utopia_store::ontology::clear_miss(&state.pool, kb_id, &req.kind, &req.key).await?;
+ utopia_store::ontology::dismiss_miss(&state.pool, kb_id, &req.kind, &req.key).await?;
Ok(Json(json!({ "ok": true })))
}
@@ -534,3 +534,56 @@ pub async fn surface_predicates(
let forms = utopia_store::graph::surface_predicates(&state.pool, kb_id).await?;
Ok(Json(json!({ "forms": forms })))
}
+
+/// 最近一次自动扩本体做了什么,以及还能不能撤销。
+///
+/// 默认开启的前提是它的动作**可见且可退**。只记在审计台账里不算可见——
+/// 那是查证用的,不是通知用的。这里给 Ontology 页一条明确的横幅。
+pub async fn last_auto_extension(
+ 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 row: Option<(serde_json::Value, chrono::DateTime<chrono::Utc>)> = sqlx::query_as(
+ "SELECT detail, created_at FROM audit_events
+ WHERE kb_id = $1 AND action = 'ontology.bootstrapped'
+ ORDER BY id DESC LIMIT 1",
+ )
+ .bind(kb_id)
+ .fetch_optional(&state.pool)
+ .await
+ .map_err(AppError::Db)?;
+ let Some((detail, at)) = row else {
+ return Ok(Json(json!({ "run": null })));
+ };
+ // 已经被撤销干净的就不再提示——那一轮已经没有任何痕迹留在图上了
+ let batches: Vec<Uuid> = detail
+ .get("batches")
+ .and_then(|v| v.as_array())
+ .map(|a| {
+ a.iter()
+ .filter_map(|s| s.as_str().and_then(|x| x.parse().ok()))
+ .collect()
+ })
+ .unwrap_or_default();
+ let (live,): (i64,) = sqlx::query_as(
+ "SELECT count(*) FROM fact_adoptions
+ WHERE kb_id = $1 AND batch_id = ANY($2) AND reverted_at IS NULL",
+ )
+ .bind(kb_id)
+ .bind(&batches)
+ .fetch_one(&state.pool)
+ .await
+ .map_err(AppError::Db)?;
+ if live == 0 {
+ return Ok(Json(json!({ "run": null })));
+ }
+ Ok(Json(json!({ "run": {
+ "at": at,
+ "relations": detail.get("relations"),
+ "classes": detail.get("classes"),
+ "facts_remapped": detail.get("facts_remapped"),
+ "batches": batches,
+ }})))
+}
diff --git a/crates/utopia-server/src/bootstrap_ontology.rs b/crates/utopia-server/src/bootstrap_ontology.rs
index 1947fe81..f7505032 100644
--- a/crates/utopia-server/src/bootstrap_ontology.rs
+++ b/crates/utopia-server/src/bootstrap_ontology.rs
@@ -1,34 +1,48 @@
-//! 冷启动自动扩本体:本体从没被人碰过时,第一批文档抽完后自己把词表建起来。
+//! 自动扩本体:抽取遇到本体外的说法时,把它补进本体并改写等它的那些事实。
//!
//! 新建的库只有 10 个默认关系——那不是任何人选的,是种子数据。传进第一批
//! 文档,里面的关系大半不在这 10 个里,于是大量事实降级成 related_to,
//! 图基本没法用,直到有人坐下来点 Suggest、看提案、逐条 Add。
-//! **没有精心建立的词表要保护时,坚持人工审批保护的是个还不存在的东西。**
//!
//! 敢这么做的前提是采纳可撤销(见 graph::unadopt):错了点一下就回去,
//! 旧事实从来没被销毁过。所以判断轴不是"有多确信"而是"错了有多贵"。
//!
-//! 唯独 `functional` 永不自动:它驱动时态引擎自动闭合事实、生成冲突,
-//! 等发现时那些闭合本身已是一串 supersede 链——不属于"错了很便宜"那类。
+//! **要不要替人做,由人在知识库设置里声明**(`auto_extend_ontology`,缺省开)。
+//! 曾试过从行为推断——"本体有没有被碰过"——那是猜,而且猜错的后果荒唐:在提案上
+//! 点一次 Add 就会永久关掉建议功能。开关一来,猜测没有了,冻结也没有了。
+//!
+//! 关掉它不影响"留意":未匹配统计照常累积、照常在 Unmatched 面板可见,
+//! 只是变成你点一下的提案,信息一条不少。
+//!
+//! 唯独 `functional` 永不自动,开关开着也不行:它驱动时态引擎自动闭合事实、
+//! 生成冲突,等发现时那些闭合本身已是一串 supersede 链——不属于"错了很便宜"那类。
use uuid::Uuid;
use crate::api::ontology_routes;
use crate::state::AppState;
-/// 少于这么多个待认领的说法就不折腾——凑不出像样的提案,白烧一次 LLM 调用。
+/// 少于这么多个够格的说法就不折腾——凑不出像样的提案,白烧一次 LLM 调用。
const MIN_FORMS: usize = 3;
+/// 只采纳出现在这么多篇文档里的说法。**只在一篇里出现过的是那篇文档的用词,
+/// 不是这个组织的词汇**——而本体会反馈进抽取提示词,一次偶然会变成长期指令。
+/// 副作用正好:只有一篇文档时什么都够不着门槛,于是什么也不做,下一篇再试。
+const MIN_DOCS: i64 = 2;
pub async fn bootstrap_ontology(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {
- // 并发的两个抽取任务可能都看到"空闲"而各入队一次;这里重查一遍,
- // 先跑的那个建出关系后,后跑的这个就是 no-op
- if !utopia_store::graph::ontology_untouched(&state.pool, kb_id).await? {
- tracing::debug!(%kb_id, "本体已被扩展过,跳过冷启动");
+ // 并发的两个抽取任务可能都看到"空闲"而各入队一次;开关也可能刚被关掉
+ let kb = utopia_store::kbs::get(&state.pool, kb_id).await?;
+ if !kb.auto_extend_ontology {
+ tracing::debug!(%kb_id, "自动扩本体已关闭,跳过");
return Ok(());
}
- let forms = utopia_store::graph::surface_predicates(&state.pool, kb_id).await?;
+ let forms: Vec<_> = utopia_store::graph::surface_predicates(&state.pool, kb_id)
+ .await?
+ .into_iter()
+ .filter(|f| f.doc_count >= MIN_DOCS)
+ .collect();
if forms.len() < MIN_FORMS {
- tracing::debug!(%kb_id, n = forms.len(), "待认领的说法太少,跳过冷启动");
+ tracing::debug!(%kb_id, n = forms.len(), "够格的说法太少,跳过自动扩本体");
return Ok(());
}
diff --git a/crates/utopia-server/src/extraction.rs b/crates/utopia-server/src/extraction.rs
index 992e1ab7..2e1dde59 100644
--- a/crates/utopia-server/src/extraction.rs
+++ b/crates/utopia-server/src/extraction.rs
@@ -590,10 +590,12 @@ async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
if needs_adjudication || conflicts_found {
state.emit_review(doc.kb_id);
}
- // 冷启动自动扩本体:本体没被人碰过、且这一批都抽完了,由最后一篇触发。
- // 逐篇触发是错的——先到的那篇的词汇会独占本体。并发下可能入队两次,
- // 任务自己会重查一遍,先跑的建出关系后另一个就是 no-op
- if utopia_store::graph::ontology_untouched(&state.pool, doc.kb_id).await?
+ // 自动扩本体:开关开着、且这一批都抽完了,由最后一篇触发。
+ // 判据是显式开关而不是"本体有没有被碰过"——后者是从行为推断意图,
+ // 推错的后果很荒唐(在提案上点一次 Add 就永久关掉建议),而且一旦为假
+ // 就永不再真,本体会冻结在第一批文档碰巧包含的词汇上。
+ // 并发下可能入队两次,任务自己会重查开关与状态
+ if kb.auto_extend_ontology
&& utopia_store::documents::extraction_idle(&state.pool, doc.kb_id).await?
{
utopia_store::jobs::enqueue(
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index c68c3416..f00fec93 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -937,6 +937,7 @@ pub async fn surface_predicates(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Sur
Ok(sqlx::query_as(
"SELECT fe.surface_predicate AS form,
count(DISTINCT f.id) AS fact_count,
+ count(DISTINCT fe.document_id) AS doc_count,
(SELECT s.canonical_name || ' → ' || o.canonical_name
FROM fact_evidence e2
JOIN facts f2 ON f2.id = e2.fact_id
@@ -950,6 +951,10 @@ pub async fn surface_predicates(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Sur
JOIN relation_types rt ON rt.id = f.predicate_id
WHERE f.kb_id = $1 AND rt.kb_id = $1 AND rt.key = $2
AND f.invalidated_at IS NULL AND fe.surface_predicate IS NOT NULL
+ -- 用户拒绝过的说法不再出现在候选里(人工与自动两条路都据此绕开)
+ AND NOT EXISTS (SELECT 1 FROM ontology_misses m
+ WHERE m.kb_id = $1 AND m.kind = 'relation_type'
+ AND m.key = fe.surface_predicate AND m.dismissed_at IS NOT NULL)
GROUP BY fe.surface_predicate, rt.id
ORDER BY fact_count DESC, form",
)
@@ -1128,19 +1133,3 @@ pub async fn unadopt(pool: &PgPool, kb_id: Uuid, batch_id: Uuid) -> AppResult<u3
tx.commit().await?;
Ok(reverted)
}
-
-/// 本体是否从没被人碰过:只有内置类型、没有任何自建或导入的。
-///
-/// 冷启动自动扩本体的判定依据。**没有精心建立的词表时,坚持人工审批保护的
-/// 是个还不存在的东西**——而默认那 10 个关系不是任何人选的,是种子数据。
-/// 一旦有人加过或导入过,这里就为 false,自动扩本体从此不再触发。
-pub async fn ontology_untouched(pool: &PgPool, kb_id: Uuid) -> AppResult<bool> {
- let (custom,): (i64,) = sqlx::query_as(
- "SELECT (SELECT count(*) FROM entity_types WHERE kb_id = $1 AND NOT builtin)
- + (SELECT count(*) FROM relation_types WHERE kb_id = $1 AND NOT builtin)",
- )
- .bind(kb_id)
- .fetch_one(pool)
- .await?;
- Ok(custom == 0)
-}
diff --git a/crates/utopia-store/src/kbs.rs b/crates/utopia-store/src/kbs.rs
index 156cf7d5..d59de982 100644
--- a/crates/utopia-store/src/kbs.rs
+++ b/crates/utopia-store/src/kbs.rs
@@ -74,6 +74,7 @@ pub async fn update(
name: Option<&str>,
description: Option<&str>,
visibility: Option<&str>,
+ auto_extend_ontology: Option<bool>,
) -> AppResult<KnowledgeBase> {
if let Some(v) = visibility {
if !matches!(v, "open" | "restricted") {
@@ -96,6 +97,7 @@ pub async fn update(
SET name = COALESCE($2, name),
description = COALESCE($3, description),
visibility = COALESCE($4, visibility),
+ auto_extend_ontology = COALESCE($5, auto_extend_ontology),
updated_at = now()
WHERE id = $1 RETURNING *",
)
@@ -103,6 +105,7 @@ pub async fn update(
.bind(name)
.bind(description)
.bind(visibility)
+ .bind(auto_extend_ontology)
.fetch_optional(pool)
.await?
.ok_or(AppError::NotFound)
diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rs
index ff9e2be9..48ce4d74 100644
--- a/crates/utopia-store/src/ontology.rs
+++ b/crates/utopia-store/src/ontology.rs
@@ -346,12 +346,14 @@ pub async fn record_miss(
example: Option<&str>,
) -> AppResult<()> {
sqlx::query(
+ // 已被用户拒绝的不再累加:否则计数会把"不要"重新顶成一个待处理信号
"INSERT INTO ontology_misses (kb_id, kind, key, example)
VALUES ($1, $2, left($3, 80), left($4, 200))
ON CONFLICT (kb_id, kind, key)
DO UPDATE SET count = ontology_misses.count + 1,
example = COALESCE(EXCLUDED.example, ontology_misses.example),
- updated_at = now()",
+ updated_at = now()
+ WHERE ontology_misses.dismissed_at IS NULL",
)
.bind(kb_id)
.bind(kind)
@@ -365,13 +367,31 @@ pub async fn record_miss(
pub async fn list_misses(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<OntologyMiss>> {
Ok(sqlx::query_as(
"SELECT kind, key, example, count FROM ontology_misses
- WHERE kb_id = $1 ORDER BY count DESC, updated_at DESC LIMIT 50",
+ WHERE kb_id = $1 AND dismissed_at IS NULL
+ ORDER BY count DESC, updated_at DESC LIMIT 50",
)
.bind(kb_id)
.fetch_all(pool)
.await?)
}
+/// 用户说"不要这个"。**标记而非删除**——删掉的话下一次抽取遇到同一个词
+/// 原样插回来,用户的拒绝活不过一轮抽取。自动扩展路径也据此绕开。
+pub async fn dismiss_miss(pool: &PgPool, kb_id: Uuid, kind: &str, key: &str) -> AppResult<()> {
+ sqlx::query(
+ "UPDATE ontology_misses SET dismissed_at = now()
+ WHERE kb_id = $1 AND kind = $2 AND key = $3 AND dismissed_at IS NULL",
+ )
+ .bind(kb_id)
+ .bind(kind)
+ .bind(key)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 本体已经覆盖了这个说法(采纳时调用):与"用户拒绝"不同,这条真的可以清掉,
+/// 下次抽取它会命中本体,不再是未匹配。
pub async fn clear_miss(pool: &PgPool, kb_id: Uuid, kind: &str, key: &str) -> AppResult<()> {
sqlx::query("DELETE FROM ontology_misses WHERE kb_id = $1 AND kind = $2 AND key = $3")
.bind(kb_id)
diff --git a/docs/decisions/0001-ontology-import-and-governance.md b/docs/decisions/0001-ontology-import-and-governance.md
index 232b4a53..24dd190d 100644
--- a/docs/decisions/0001-ontology-import-and-governance.md
+++ b/docs/decisions/0001-ontology-import-and-governance.md
@@ -1,6 +1,6 @@
# 0001 · 本体导入与治理路线
-- **状态**:进行中 · P0–P5 均未开工
+- **状态**:进行中 · P0(实体可编辑)与 P1(停止静默丢弃)已建成;P3b 部分建成,见 [0003](0003-ontology-growth-loop.md)
- **成文**:2026-08-27 / 28,随调研持续修订(约定见 [README](README.md))
> 理由比清单重要——清单会过期,理由决定以后遇到新情况怎么判。所以本文把「贯穿性判据」放在分阶段之前,且推翻过的判断就地留痕(见 P1、P3 的修订记录)。
@@ -191,6 +191,11 @@ v2: http://acme.com/hr#Employee rdfs:label "Staff Member" → key = staff_membe
#### P3b · 关系清单同样会膨胀(原先漏掉的)
+> **本节的抽取侧已建成**(撤逃生舱、提示词规则 8、表层谓词落在证据上);
+> **映射回本体那一半也建成了,但形态与这里写的不同**——不是全自动的检索裁决,
+> 而是「聚类 → 带影响面的提案 → 一键采纳并改写 → 可撤销」,加一个默认开启的开关。
+> 见 [0003](0003-ontology-growth-loop.md),含三次判断变化的留痕。
+
上面只解决了实体类型。但提示词里紧挨着类清单的是**关系清单**,同样由本体全量展开、同样每个分块重发。实测(Industry Corpus):9 个类 197 字符,10 个关系 **250 字符**——关系已经是更大的那一半。且**代码库无任何 prompt caching**(`cache_control` 零命中),O(分块 × 本体) 没有缓存兜底。部门级本体(300 类 / 400 属性)约每分块 4200 token,181 分块 76 万输入 token——而这才 28 篇文档。
**当初漏掉的原因是一个不对称**:`(NVIDIA, acquired, Mellanox)` 不知道 NVIDIA 是 Organization 也是完整事实——**类型是挂在节点上的注解,可延后**;而 `(NVIDIA, ?, Mellanox)` 不是事实,**谓词就是事实本身**,"先空着后补"不通。
@@ -249,6 +254,11 @@ related_to 事实 359 条
### P4 · 治理即经验
+> **这一节列的三件事都还没做**,但实际长出来的治理闭环是另一个形状——
+> 采纳即改写、可撤销、开关控制自动。见 [0003](0003-ontology-growth-loop.md)。
+> 这里的"决策不可被遗忘"(`type_source`)仍然成立且未做:**实体类型那半边
+> 至今只有一个 PATCH 端点,没有任何对应机制。**
+
**顺序不能反**:先有 P0 的编辑能力,才有"人工决策"可保护、可学习。
1. **决策不可被遗忘(正确性,不是功能)**——`entities` 加 `type_source`(extracted / human / inferred)。抽取不覆盖 `human`;推理机也不覆盖。没有这一层,重抽会静默吃掉全部治理成果。
diff --git a/docs/decisions/0003-ontology-growth-loop.md b/docs/decisions/0003-ontology-growth-loop.md
new file mode 100644
index 00000000..3c61ef41
--- /dev/null
+++ b/docs/decisions/0003-ontology-growth-loop.md
@@ -0,0 +1,134 @@
+# 0003 · 本体从语料里长出来,人站在哪一环
+
+- **状态**:已建成(#44 + `feat/ontology-auto-extend-switch`);末节列出已知缺口
+- **成文**:2026-08-28
+- **相关**:[0001](0001-ontology-import-and-governance.md) 的 P3b 与 P4——那两节是计划,本文是实际长出来的东西,两者不一样
+
+> 本文最有价值的部分是**三次判断变化**那一节。结论本身从代码里读得出来,理由读不出来,而三次变化的理由各不相同——按 [README](README.md) 的约定就地留痕。
+
+---
+
+## 问题
+
+抽取器读到"《星球大战:零号连队》可在 GeForce NOW 上玩",而本体里没有"可在…上玩",只能降级成 `related_to`——**等于什么都没说**。真实语料上这类边曾占 40.5%。
+
+而新建的知识库只有 10 个默认关系,那不是任何人选的,是种子数据。所以每一个新库开局都是这个状态:**图里近一半的边没有语义,直到有人坐下来一条条补本体。**
+
+抽取侧的修法(撤掉逃生舱、加提示词规则 8、把原词存进 `fact_evidence.surface_predicate`)见 0001 的 P3b。本文接着往下——**原词留住之后,怎么把它变回本体里的关系。**
+
+---
+
+## 建成的东西
+
+### 采纳的收益在后半句
+
+Suggest 面板此前就能提案并一键 Add,但**只建关系、不动事实**——本体长大了,图没变好,那 49 条继续写着"有关联"。
+
+现在采纳做两件事:建关系类型 + **把等着它的事实改写过去**。提案上直接写"将重新归类 21 条",并列出归并了哪些写法。
+
+改写走追加:插入带 `supersedes` 的新行、作废旧行,与人工纠正、时态闭合同一条路。实体历史里因此读得到「先记成 related to,后精化成 available on,某某某改的」。
+
+**只改写说法全部落在采纳集合内的事实。** 一条事实可能跨分块积累多种说法,只认领其中一种就改写等于替另一种做了决定。实测这类占比不到 1%。
+
+### 可以撤销
+
+`fact_adoptions` 记每一条的去向:批次、谓词、旧事实、新事实、以及**是"新建取代"还是"并入已存在"**。撤销按批次回滚:新行作废、旧行复活。
+
+**关系类型不删**——有事实指向过它(`delete_relation_type` 也会拒绝),而按 append-only 的规矩"它存在过"本身是历史,一个没人用的关系是惰性的。撤销标记账本行而不是删除,因为采纳发生过、撤销也发生过,两件都是真的。
+
+撤销要二次确认(轻确认,不是打字解锁——它本身可逆)。
+
+### 三档动作
+
+| | 谁决定 | 何时用 |
+|---|---|---|
+| 逐条 Add | 人 | 挑着采纳 |
+| Add all | 人 | 常见情形是"这些都对",一次决定 |
+| 自动 | 开关 | 见下 |
+
+### 开关
+
+`knowledge_bases.auto_extend_ontology`,KB 设置页,**默认开启**。
+
+它只管**自动采纳**,永远不管**留意**:关掉之后未匹配的说法照常累积、照常在 Unmatched 面板可见,只是变成你点一下的提案。文案里必须明说这一点——"停止扩展"太容易被读成"停止留意"。
+
+默认开启的前提是它的动作**可见且可退**:Ontology 页有横幅说明加了什么、改了多少条、附撤销。**审计台账是事后查证用的,不是通知用的。**
+
+### 永不自动的那一样
+
+`functional` 无论建议方说什么、开关开着也一样,永远是 `false`。
+
+它驱动时态引擎**自动闭合事实、生成冲突**,等发现时那些闭合本身已是一串 supersede 链,撤销要反向拆解。`part_of` 曾被误标为 functional,28 篇新闻稿积压 59 条假冲突。
+
+**判据一句话:可逆的可以自动,触发级联写入的不行。**
+
+### 拒绝有记忆
+
+`dismiss` 此前是 `DELETE FROM ontology_misses`,下一次抽取遇到同一个词原样插回——**用户的"不要"活不过一轮抽取**。开关关着时这只是恼人;开着时它变成系统覆盖人的明确决定。
+
+改成标记(`dismissed_at`):`record_miss` 不再累加已标记的,人工与自动两条路都跳过。顺带修好了"dismiss 是暂时的"这个现存 bug。
+
+### 自动采纳的门槛
+
+只采纳出现在 **≥2 篇文档**里的说法。理由不是安全(有撤销),是质量:**本体会反馈进抽取提示词,一次偶然用词会变成长期指令。** 副作用正好——单篇文档什么都够不着门槛,于是什么也不做,下一篇再议。
+
+---
+
+## 三次判断变化
+
+### 一、我反对自动化,理由是错的
+
+**原判断**:不该自动写本体。同义词会爆炸(四种 "available" 变四个关系)、通用动词会混进来(`is`/`has`/`includes`)、频次不等于语义、`functional` 猜错会成批制造假冲突。
+
+**这些论据本身没错**,错的是结论所依赖的隐含前提:**"错了代价高"**。
+
+代价并不高。采纳走的是 supersede,旧事实从来没被销毁过。**可逆性是我自己设计的,然后论证时没把它算进去**——拿一个已经设计掉的不可逆去反对自动化。
+
+**判断轴不是"有多确信",是"错了有多贵"。**
+
+(同义词与通用动词那两条论据仍然成立,只是它们要的不是"人来点头",是**聚类**——自动化的是审批,不是归并。)
+
+### 二、接受自动化后,我用了一个猜测当判据
+
+**原判断**:本体"有没有被碰过"(存在非内置类型)可以判断该不该自动跑。
+
+**那是从行为推断意图,两个方向都错。**
+
+在提案上点一次 Add 会记一条带操作人的本体动作——**参与治理闭环,导致治理闭环停止工作**。改个描述里的错别字也一样。
+
+而且它一旦为假就永不再真:自动跑完第一轮,本体"被碰过了",于是**词汇永久冻结在第一批文档碰巧包含的那些上**,而 RSS 与文件夹来源是每天持续进文档的。
+
+### 三、开关(用户指出)
+
+**声明取代猜测。** 开关不只是加了个控制,它**删掉了一个坏机制**——没有猜测就没有荒唐的开关,没有自动关闭就没有冻结,迭代变成"开着就一直跑",不需要任何聪明劲。
+
+默认开启则解掉了开关本身的老问题:新用户找不到它,只能忍受一个近半边没有语义的图。
+
+---
+
+## 两个在已上线代码里发现的缺陷
+
+**并入分支让历史说了谎。** 采纳时若目标断言已存在,旧行被作废且**没有任何后继指向它**。实体历史把"已作废且无后继"判为 `rejected`,于是界面上写着「关于 GeForce NOW 的这条记录被撤回了」——它其实一字未少地并进了另一条断言。这跟 [#37](https://github.com/deeplethe/utopia/pull/37) 修的是同一类:**界面自信地陈述一件没发生的事。** `fact_adoptions` 是它的直接由来。
+
+**单篇文档能定下整个本体。** 触发条件"没有别的文档在处理中",在批次只有一篇时立刻为真——而代码里我自己的注释写着"逐篇触发是错的"。≥2 篇文档那条门槛修的是它。
+
+---
+
+## 实测
+
+| | |
+|---|---|
+| 采纳 `available_on`(归并 4 种写法) | 改写 **49** 条(48 新建 + 1 并入) |
+| 采纳 `supports` 后撤销 | `related_to` 精确回到采纳前的数,24 行标记已撤销,关系类型留着 |
+| 冷启动(一次性库,3 篇文档) | 自动建 5 个关系(全 `functional=false`),改写 19 条,**剩余 `related_to` 为 0** |
+| 拒绝 `runs_on` 后模拟下一轮抽取 | 计数停在 41 不涨(此前会删掉再插回) |
+
+一个**负面结果,而它证明了设计**:建议把 `optimized_for` 并进了 `runs_on`——"为 RTX 优化"不等于"跑在 RTX 上"。归并的写法在 tooltip 里可见,过并能被人抓出来。**这就是我不建议全自动归并的最直接证据。**
+
+---
+
+## 已知缺口
+
+- **实体类型这半边完全没有对应机制。** 谓词有聚类→提案→一键采纳并改写,实体类型只有一个 PATCH 端点。而实体那边问题有实测数据:`General` 库里 "rust" 分在 5 个类;`Industry Corpus` 里 `product` 占 37.1%。详见 0001 P3 的三层拆解(描述为空是根因、`entities` 缺"表层类型"列是第二层)。
+- **关掉开关后没有"自上次以来有 88 个新说法"的提醒**,信号在 Unmatched 面板里但没人主动看。
+- **提案不持久化**:Suggest 的结果只在前端内存里,刷新就没了。
diff --git a/docs/decisions/README.md b/docs/decisions/README.md
index bea0f6d9..e2467164 100644
--- a/docs/decisions/README.md
+++ b/docs/decisions/README.md
@@ -22,8 +22,9 @@
| | 文档 | 状态 |
|---|---|---|
-| 0001 | [本体导入与治理路线](0001-ontology-import-and-governance.md) | 进行中 · P0–P5 未开工 |
+| 0001 | [本体导入与治理路线](0001-ontology-import-and-governance.md) | 进行中 · P0/P1 已建成,P2–P5 未开工 |
| 0002 | [推理机](0002-reasoning-engine.md) | 规划中 · 取代 0001 P5 的排期 |
+| 0003 | [本体从语料里长出来,人站在哪一环](0003-ontology-growth-loop.md) | 已建成 · 含三次判断变化的留痕 |
## 不放这里的东西
diff --git a/migrations/0024_auto_extend_ontology.sql b/migrations/0024_auto_extend_ontology.sql
new file mode 100644
index 00000000..bd8e9766
--- /dev/null
+++ b/migrations/0024_auto_extend_ontology.sql
@@ -0,0 +1,15 @@
+-- 本体自动扩展的开关,以及"人说过不要"的记忆。
+--
+-- 开关:冷启动自动扩本体此前靠"本体有没有被碰过"来判断该不该跑。那个判据
+-- 是从行为里推断意图,推错了会很荒唐——在提案上点一次 Add 就会永久关掉
+-- 建议功能,因为那记了一条带操作人的本体动作。而且它一旦为假就永不再真,
+-- 本体被冻结在第一批文档碰巧包含的词汇上,可来源是每天持续进文档的。
+-- 换成显式开关:猜测没有了,冻结也没有了,"要不要替我做"由人声明。
+ALTER TABLE knowledge_bases
+ ADD COLUMN auto_extend_ontology BOOLEAN NOT NULL DEFAULT TRUE;
+
+-- 记忆:dismiss 此前是 DELETE,下一次抽取遇到同一个词原样插回来——用户的
+-- "不要"活不过一轮抽取。开关关着时这只是恼人;开着时它变成系统覆盖人的
+-- 明确决定。标记而非删除,累加与自动采纳都绕开已标记的。
+ALTER TABLE ontology_misses
+ ADD COLUMN dismissed_at TIMESTAMPTZ;
diff --git a/web/src/api.ts b/web/src/api.ts
index 31ef8e49..6cba8686 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -50,6 +50,9 @@ export interface Kb {
visibility: "open" | "restricted";
/** 部署的公共默认空间(第一个建的库):永远 open、不可删除 */
is_default: boolean;
+ /** 抽取遇到本体外的说法时,是否允许系统自动补进本体并改写等它的事实。
+ 关掉不影响"留意":未匹配统计照常累积可见,只是变成你点一下的提案 */
+ auto_extend_ontology: boolean;
/** 调用者在本库的角色(仅详情接口返回):前端据此门控破坏性入口 */
my_role?: "viewer" | "editor" | "admin" | "owner" | null;
}
@@ -677,6 +680,17 @@ export const api = {
surfacePredicates: (kbId: string) =>
request<{ forms: SurfacePredicate[] }>(`/api/v1/kbs/${kbId}/ontology/surface-predicates`),
+ /** 最近一次自动扩本体做了什么,以及还能不能撤销(撤干净了返回 null) */
+ lastAutoExtension: (kbId: string) =>
+ request<{
+ run: {
+ at: string;
+ relations: string[] | null;
+ classes: string[] | null;
+ facts_remapped: number | null;
+ batches: string[];
+ } | null;
+ }>(`/api/v1/kbs/${kbId}/ontology/auto-extension`),
/** 建关系 **并**把等着它的 related_to 事实改写过去——后半句才是收益 */
adoptPredicate: (
kbId: string,
diff --git a/web/src/i18n.ts b/web/src/i18n.ts
index a5969f95..79dab9bd 100644
--- a/web/src/i18n.ts
+++ b/web/src/i18n.ts
@@ -629,6 +629,19 @@ export const S = {
reverted: (n: number) =>
n === 1 ? "Reverted — 1 fact restored" : `Reverted — ${n} facts restored`,
undoKeepsRelation: "The relation stays; only the facts move back.",
+ /* 撤销要二次确认:它一次改回成批事实 */
+ undoTitle: "Undo this ontology change?",
+ undoHint: (n: number) =>
+ `${n} fact${n === 1 ? "" : "s"} will go back to “related to”. The relation itself stays — ` +
+ `nothing is deleted, and you can adopt it again later.`,
+ undoConfirm: "Undo",
+ undoCancel: "Keep",
+ /* 自动扩本体的通知:默认开启的前提是它的动作可见且可退。
+ 只记在审计台账里不算可见——那是查证用的,不是通知用的 */
+ autoRanTitle: "Utopia extended this ontology from your documents",
+ autoRanBody: (rels: string[], facts: number) =>
+ `Added ${rels.join(", ")} · ${facts} fact${facts === 1 ? "" : "s"} reclassified`,
+ autoRanOff: "Turn this off in knowledge base settings.",
/* 批量:常见情形是"这些都对",一条条点是把一个决定拆成八个 */
addAll: (n: number) => `Add all ${n}`,
addingAll: "Adding…",
@@ -726,6 +739,14 @@ export const S = {
title: "Knowledge base settings",
general: "General",
members: "Members",
+ /* 自动扩本体开关。说明必须讲清关掉之后失去的**只是**代劳,不是留意——
+ 否则用户会以为关掉它就看不到未匹配的信号了 */
+ autoExtend: "Extend the ontology automatically",
+ autoExtendNote:
+ "When extraction meets a relation this ontology does not have, add it and reclassify the " +
+ "facts that were waiting for it. Every change is listed and can be undone. Turning this " +
+ "off does not stop Utopia from noticing — the phrases still collect under Unmatched, they " +
+ "just wait for you to approve them.",
defaultOpenLabel: "Open to everyone",
defaultOpenNote:
"This is the deployment's default knowledge base, so visibility is locked: every member " +
diff --git a/web/src/pages/KbSettings.tsx b/web/src/pages/KbSettings.tsx
index f6c217e2..1f2d9d53 100644
--- a/web/src/pages/KbSettings.tsx
+++ b/web/src/pages/KbSettings.tsx
@@ -44,6 +44,7 @@ export function KbSettings() {
const [name, setName] = useState("");
const [desc, setDesc] = useState("");
const [visibility, setVisibility] = useState<"open" | "restricted">("open");
+ const [autoExtend, setAutoExtend] = useState(true);
const [confirmingDelete, setConfirmingDelete] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -52,6 +53,7 @@ export function KbSettings() {
setName(kb.data.name);
setDesc(kb.data.description ?? "");
setVisibility(kb.data.visibility);
+ setAutoExtend(kb.data.auto_extend_ontology);
}
}, [kb.data]);
@@ -62,7 +64,12 @@ export function KbSettings() {
const save = useMutation({
mutationFn: () =>
- api.updateKb(kbId!, { name: name.trim(), description: desc.trim() || null, visibility }),
+ api.updateKb(kbId!, {
+ name: name.trim(),
+ description: desc.trim() || null,
+ visibility,
+ auto_extend_ontology: autoExtend,
+ }),
onSuccess: () => {
setError(null);
invalidate();
@@ -183,6 +190,22 @@ export function KbSettings() {
onChange={(e) => setDesc(e.target.value)}
/>
</div>
+ {/* 自动扩本体:默认开,因为新库的十个默认关系不是任何人选的。
+ 说明里要讲清关掉之后失去的**只是**代劳,不是留意 */}
+ <label className="flex items-start gap-2.5 pt-1 cursor-pointer">
+ <input
+ type="checkbox"
+ className="mt-0.5 accent-[var(--u-accent)]"
+ checked={autoExtend}
+ onChange={(e) => setAutoExtend(e.target.checked)}
+ />
+ <span className="min-w-0">
+ <span className="block text-sm text-neutral-200">{S.kbset.autoExtend}</span>
+ <span className="block text-xs leading-relaxed text-neutral-500">
+ {S.kbset.autoExtendNote}
+ </span>
+ </span>
+ </label>
<div className="flex items-center gap-3">
<button
className="u-btn u-btn-primary px-3.5 py-1.5 text-xs"
diff --git a/web/src/pages/Ontology.tsx b/web/src/pages/Ontology.tsx
index 968a751e..6c4e3c68 100644
--- a/web/src/pages/Ontology.tsx
+++ b/web/src/pages/Ontology.tsx
@@ -19,6 +19,7 @@ import {
Button,
Chip,
ColorPicker,
+ DangerConfirm,
Dropdown,
Input,
Loading,
@@ -1098,6 +1099,15 @@ function MissesPanel({
} | null>(
null,
);
+ // 撤销要二次确认:一次改回成批事实
+ const [confirmUndo, setConfirmUndo] = useState<{ batches: string[]; moved: number } | null>(
+ null,
+ );
+ // 系统自动扩过本体没有——横幅要据此显示,撤干净了后端返回 null
+ const autoRun = useQuery({
+ queryKey: ["auto-extension", kbId],
+ queryFn: () => api.lastAutoExtension(kbId),
+ });
// 待认领的表层谓词:提案的影响面("将改写 57 条")从这里算
const surface = useQuery({
queryKey: ["surface-predicates", kbId],
@@ -1217,7 +1227,8 @@ function MissesPanel({
onSuccess: (r) => {
if (r.failed.length) toast.error(S.ontology.addAllPartial(r.failed));
else toast.success(S.ontology.adopted(r.moved));
- if (r.batches.length) setLastAdopt({ batches: r.batches, key: S.ontology.addAllLabel, moved: r.moved });
+ if (r.batches.length)
+ setLastAdopt({ batches: r.batches, key: S.ontology.addAllLabel, moved: r.moved });
setProposals(null);
onChanged();
},
@@ -1233,6 +1244,8 @@ function MissesPanel({
onSuccess: (r) => {
toast.success(S.ontology.reverted(r.reverted));
setLastAdopt(null);
+ setConfirmUndo(null);
+ autoRun.refetch();
onChanged();
},
onError,
@@ -1275,6 +1288,38 @@ function MissesPanel({
))}
</div>
)}
+ {/* 系统自己动了本体,必须让人看见——只记在审计台账里不算可见。
+ 默认开启的前提是它的动作可见且可退,这条横幅是"可见"那一半 */}
+ {autoRun.data?.run && !lastAdopt && (
+ <div className="mt-3 rounded-lg border border-[var(--u-accent)]/25 bg-[var(--u-accent)]/[0.06] px-3 py-2.5">
+ <div className="flex items-start gap-2">
+ <div className="min-w-0 flex-1">
+ <p className="text-xs text-neutral-200">{S.ontology.autoRanTitle}</p>
+ <p className="mt-0.5 text-[11px] text-neutral-400">
+ {S.ontology.autoRanBody(
+ autoRun.data.run.relations ?? [],
+ autoRun.data.run.facts_remapped ?? 0,
+ )}
+ </p>
+ <p className="mt-0.5 text-[11px] text-neutral-600">{S.ontology.autoRanOff}</p>
+ </div>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={unadopt.isPending}
+ onClick={() =>
+ setConfirmUndo({
+ batches: autoRun.data!.run!.batches,
+ moved: autoRun.data!.run!.facts_remapped ?? 0,
+ })
+ }
+ >
+ {S.ontology.undoAdoptBtn}
+ </Button>
+ </div>
+ </div>
+ )}
+
{/* 采纳改写了成批事实——没有回头路的话没人敢点第一下 */}
{lastAdopt && (
@@ -1288,13 +1333,27 @@ function MissesPanel({
variant="ghost"
className="ml-auto"
disabled={unadopt.isPending}
- onClick={() => unadopt.mutate(lastAdopt.batches)}
+ onClick={() =>
+ setConfirmUndo({ batches: lastAdopt.batches, moved: lastAdopt.moved })
+ }
>
{S.ontology.undoAdoptBtn}
</Button>
</div>
)}
+ {/* 撤销一次改回成批事实:轻确认——它本身也是可逆的,不必打字解锁 */}
+ {confirmUndo && (
+ <DangerConfirm
+ title={S.ontology.undoTitle}
+ hint={S.ontology.undoHint(confirmUndo.moved)}
+ confirmLabel={S.ontology.undoConfirm}
+ cancelLabel={S.ontology.undoCancel}
+ busy={unadopt.isPending}
+ onConfirm={() => unadopt.mutate(confirmUndo.batches)}
+ onCancel={() => setConfirmUndo(null)}
+ />
+ )}
{proposals && (
<div className="mt-4 border-t border-white/10 pt-3">
<div className="mb-2 flex items-center gap-2">