World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
A fact drawn from a memory waits for a nod before it enters the graph (#210)
WaylandYang2fb026818a8c
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rsindex d1bb5728..69cd1673 100644--- a/crates/utopia-core/src/models.rs+++ b/crates/utopia-core/src/models.rs@@ -926,8 +926,36 @@ pub struct DerivedFactView {/// 与列表分开取是有意的:列表有上限(一页十条),数数没有。从前左栏读的是/// 数组长度,而接口固定只回 100 条——一个有 164 条待办的库,界面写着 100,/// 清完还会再冒出来。+/// 等人点头的一条事实(0015)。`quote` 是那句记忆的全文——确认界面要把原句和+/// 三元组并排显示,只列三元组等于要人凭空判断它对不对。+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]+pub struct PendingFactView {+ pub id: Uuid,+ pub subject_id: Uuid,+ pub subject_name: String,+ pub predicate_id: Option<Uuid>,+ /// 本体里的关系名;为空时前端显示 `proposed_predicate`(斜体,标明是原话)+ pub predicate_label: Option<String>,+ pub proposed_predicate: Option<String>,+ pub object_id: Option<Uuid>,+ pub object_name: Option<String>,+ pub object_value: Option<serde_json::Value>,+ pub valid_from: Option<DateTime<Utc>>,+ pub valid_from_precision: Option<String>,+ pub valid_to: Option<DateTime<Utc>>,+ pub valid_to_precision: Option<String>,+ pub confidence: f32,+ pub chunk_id: Uuid,+ pub quote: String,+ pub proposed_by: Option<Uuid>,+ pub proposed_by_name: Option<String>,+ pub created_at: DateTime<Utc>,+}+#[derive(Debug, Clone, Copy, Default, Serialize, sqlx::FromRow)]pub struct ReviewCounts {+ /// 记忆抽出、等人点头的事实(0015)。排第一:它是人自己说的话+ pub pending: i64,pub duplicates: i64,pub conflicts: i64,pub unconfirmed: i64,diff --git a/crates/utopia-server/src/api/chat.rs b/crates/utopia-server/src/api/chat.rsindex aadb6bbb..2c73d269 100644--- a/crates/utopia-server/src/api/chat.rs+++ b/crates/utopia-server/src/api/chat.rs@@ -29,17 +29,14 @@ const KNOWN_ENTITY_LIMIT: usize = 20;const MAX_HISTORY: usize = 20;const MAX_ROUNDS: usize = 6;-/// **`remember` 暂时停用**(见 `docs/decisions/0015`)。+/// `remember` 曾整个停用过一段(见 `docs/decisions/0015`):它那时会把一句话直接+/// 变成图上一条活边,实测里「记住 Acme 把总部搬到了深圳」落成的是一条**空谓词、+/// 0.9 置信**的边,而助手宣称的和图里得到的不是一回事。///-/// 它今天会把一句话直接变成图上一条活边,而中间那一步没人看得见:实测里-/// 「记住 Acme 把总部搬到了深圳」落成的是一条 **空谓词、0.9 置信** 的边——-/// 本体里没有「搬迁到」这类关系,抽取落不上就留空(按 0010 这是对的),-/// 于是助手宣称的和图里得到的不是一回事。-///-/// 0018 建好了 `pending_facts`:抽出来的先等人点头。**抽取侧接上那张表-/// 之后,把这里改回 true。** 在那之前宁可没有这个工具,也不要一个会-/// 悄悄改图的工具。-pub(super) const REMEMBER_ENABLED: bool = false;+/// 现在抽取侧接上了 `pending_facts`:记忆抽出的事实先等人点头,再进账本。+/// 这个开关留着,是为了下次再发现「工具会悄悄改图」时有地方立刻拉闸——+/// 宁可没有这个工具,也不要一个会悄悄改图的工具。+pub(super) const REMEMBER_ENABLED: bool = true;#[derive(Deserialize)]pub struct ChatReq {@@ -95,10 +92,11 @@ fn tools_schema(can_write: bool, data_source_names: &[String]) -> serde_json::Va"name": "remember","description": "Record one memory episode into the knowledge base's temporal \memory. Use ONLY when the user explicitly asks to remember/record \- something, or clearly states a decision or fact to keep. The episode is \- extracted into the knowledge graph; if it contradicts an existing \- single-valued fact, the old fact's validity is closed automatically \- (never deleted). Do not use for casual conversation.",+ something, or clearly states a decision or fact to keep. The sentence \+ is stored immediately; facts extracted from it are PROPOSED and shown \+ to the user for confirmation before they enter the knowledge graph. \+ Never claim a fact was added to the graph. Do not use for casual \+ conversation.","parameters": {"type": "object","properties": {@@ -188,8 +186,10 @@ fn check_call(const MEMORY_PROMPT: &str = "\Memory: you can persist knowledge with the remember tool. Use it when the user says \- \"remember/record this\" or states a decision meant to last. Confirm in your reply what \- was recorded. Never invent memories, and never call it for small talk.";+ \"remember/record this\" or states a decision meant to last. In your reply, say that the \+ sentence was recorded and that the facts extracted from it will be shown for the user's \+ confirmation before entering the graph; never say a fact is already in the graph. \+ Never invent memories, and never call it for small talk.";/// 工具的 JSON schema——**给模型看的那一份**。///@@ -687,6 +687,7 @@ pub async fn chat(workspace_id,mounted_sources: &mounted_sources,can_write,+ actor: Some(user.id),};let (result, step) = tools::dispatch(&ctx, &mut sink, &call.name, &args).await;// **这一步发生在正文的哪个位置。**diff --git a/crates/utopia-server/src/api/mcp.rs b/crates/utopia-server/src/api/mcp.rsindex a133f412..88bfafcc 100644--- a/crates/utopia-server/src/api/mcp.rs+++ b/crates/utopia-server/src/api/mcp.rs@@ -176,6 +176,7 @@ pub async fn handle(workspace_id: kb.workspace_id,mounted_sources: &[],can_write: false,+ actor: Some(user.id),};let mut sink = ToolSink::default();let (text, _step) = tools::dispatch(&ctx, &mut sink, name, &args).await;diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rsindex b7869fe4..8818406b 100644--- a/crates/utopia-server/src/api/mod.rs+++ b/crates/utopia-server/src/api/mod.rs@@ -333,6 +333,15 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {).route("/kbs/{id}/review", get(review_routes::list)).route("/kbs/{id}/review/history", get(review_routes::history))+ // 记忆抽出、等人点头的事实(0015):按句取、逐条裁+ .route(+ "/kbs/{id}/review/pending",+ get(review_routes::pending_for_chunk),+ )+ .route(+ "/kbs/{id}/review/pending/{pending_id}",+ post(review_routes::decide_pending),+ ).route("/kbs/{id}/review/{review_id}", post(review_routes::decide))// 语义层映射的表态(0011)。跟消解审核并排——都是「引擎提议、人裁决」.route(diff --git a/crates/utopia-server/src/api/review_routes.rs b/crates/utopia-server/src/api/review_routes.rsindex 71933ea0..ba1a619e 100644--- a/crates/utopia-server/src/api/review_routes.rs+++ b/crates/utopia-server/src/api/review_routes.rs@@ -75,6 +75,8 @@ pub async fn list(let offset = q.offset.unwrap_or(0).max(0);let items = match queue {+ // 记忆抽出、等人点头的事实(0015)。排第一:它是人自己说的话+ "pending" => json!(utopia_store::pending::list(&state.pool, kb_id, limit, offset).await?),"duplicates" => {json!(utopia_store::resolution::list_reviews(&state.pool, kb_id, limit, offset).await?)}@@ -636,6 +638,90 @@ pub async fn decide_defect(/// 就按它改图。开关关着时不静默跳过:回一个明确的错,界面才说得出为什么没动。////// 同步跑,与一致性检查同一个理由:纯计算,没有模型调用也没有网络。+#[derive(Deserialize)]+pub struct PendingQuery {+ pub chunk_id: Uuid,+}++/// 一句记忆抽出的全部待确认项——对话里那张确认卡按这个取(0015)。+/// Viewer 也能看:看得见提议、看不见按钮,与 Review 页同一口径+pub async fn pending_for_chunk(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path(kb_id): Path<Uuid>,+ Query(q): Query<PendingQuery>,+) -> ApiResult<Json<serde_json::Value>> {+ require_kb(&state, &user, kb_id, Role::Viewer).await?;+ let items = utopia_store::pending::for_chunk(&state.pool, kb_id, q.chunk_id).await?;+ Ok(Json(json!({ "items": items })))+}++#[derive(Deserialize)]+pub struct DecidePendingBody {+ /// `confirm` 进账本;`reject` 记进 `rejected_facts`,下一轮重抽不再提+ pub action: String,+}++/// 人对一条待确认事实点头或摇头。+///+/// 两个动作都进决策台账,快照自包含——行删了之后台账上还读得出当时确认的是什么。+/// 确认走与抽取相同的那条路(事实 + 证据 + 时态对账),所以一句「Mira 交给 Devin 了」+/// 点头之后,Mira 那条会像从文档里抽出来时一样被闭合+pub async fn decide_pending(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path((kb_id, pending_id)): Path<(Uuid, Uuid)>,+ Json(body): Json<DecidePendingBody>,+) -> ApiResult<Json<serde_json::Value>> {+ require_kb(&state, &user, kb_id, Role::Editor).await?;+ match body.action.as_str() {+ "confirm" => {+ let done = utopia_store::pending::confirm(&state.pool, kb_id, pending_id).await?;+ let _ = utopia_store::audit::record(+ &state.pool,+ Some(kb_id),+ user.id,+ "fact.nod_confirmed",+ "fact",+ Some(done.fact_id),+ done.snapshot,+ )+ .await;+ state.emit_pending(kb_id);+ state.emit_review(kb_id);+ state.emit_graph(kb_id);+ Ok(Json(json!({+ "ok": true,+ "fact_id": done.fact_id,+ "created": done.created,+ "conflicts": done.conflicts,+ })))+ }+ "reject" => {+ let snap = utopia_store::pending::reject(&state.pool, kb_id, pending_id, Some(user.id))+ .await?;+ let _ = utopia_store::audit::record(+ &state.pool,+ Some(kb_id),+ user.id,+ "fact.nod_rejected",+ "pending_fact",+ Some(pending_id),+ snap,+ )+ .await;+ state.emit_pending(kb_id);+ state.emit_review(kb_id);+ Ok(Json(json!({ "ok": true })))+ }+ other => Err(utopia_core::AppError::invalid(+ "unknown_action",+ format!("action must be confirm or reject, got {other}"),+ )+ .into()),+ }+}+pub async fn run_inference(State(state): State<AppState>,AuthUser(user): AuthUser,diff --git a/crates/utopia-server/src/api/tools.rs b/crates/utopia-server/src/api/tools.rsindex 626303f3..22c41d9f 100644--- a/crates/utopia-server/src/api/tools.rs+++ b/crates/utopia-server/src/api/tools.rs@@ -32,6 +32,9 @@ pub struct ToolCtx<'a> {pub mounted_sources: &'a [DataSourceView],/// editor 及以上才有 `remember`pub can_write: bool,+ /// 在说话的人。`remember` 把它记成「谁说的」,一路跟到待确认队列(0015)。+ /// 对话里恒有值;MCP 也有——令牌以人的身份行事(0014)+ pub actor: Option<Uuid>,}/// 工具执行过程中往外攒的东西。@@ -343,23 +346,31 @@ pub async fn remember(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult}match utopia_store::memory::append_episode(&ctx.state.pool, ctx.kb_id, text, occurred_at).await{- Ok((doc_id, _chunk)) => {- // 摄入(embedding/索引/增量抽取)异步走队列,不阻塞对话+ Ok((doc_id, chunk_id)) => {+ // 摄入(embedding/索引/增量抽取)异步走队列,不阻塞对话。+ // 抽出来的事实**先等人点头**(0015)——所以这里只能如实说「记下了这句话」,+ // 说不出抽出了几条:抽取还没跑。卡片在任务完成时长到对话里let _ = utopia_store::jobs::enqueue(&ctx.state.pool,"memory_ingest",- json!({ "document_id": doc_id }),+ json!({ "document_id": doc_id, "proposed_by": ctx.actor }),).await;ctx.state.emit_document(ctx.kb_id, doc_id);(format!(- "Recorded (effective {}): {text}",+ "Recorded the sentence (effective {}): {text}\n\+ Facts extracted from it will be shown to the user for confirmation \+ before entering the graph. Tell the user exactly that: the sentence is \+ recorded, and the extracted facts await their confirmation. Do not claim \+ any fact has been added to the knowledge graph.",occurred_at.format("%Y-%m-%d")),json!({"kind": "tool", "label": "remember",- "detail": text.chars().take(60).collect::<String>()+ "detail": text.chars().take(60).collect::<String>(),+ // 对话里那张确认卡按它取待确认项;回放时也据此重画+ "chunk_id": chunk_id,}),)}diff --git a/crates/utopia-server/src/extraction.rs b/crates/utopia-server/src/extraction.rsindex 19b06fac..8aaf40b3 100644--- a/crates/utopia-server/src/extraction.rs+++ b/crates/utopia-server/src/extraction.rs@@ -212,8 +212,14 @@ async fn enqueue_bootstrap(state: &AppState, kb_id: Uuid) -> anyhow::Result<()>Ok(())}-pub async fn extract_document(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {- match run(state, document_id).await {+/// `proposed_by`:这篇文档若是记忆日志,抽出的事实等人点头,这一列记「谁说的」。+/// 批量摄入的文档传 None——那条路不经待确认队列,这个值用不上+pub async fn extract_document(+ state: &AppState,+ document_id: Uuid,+ proposed_by: Option<Uuid>,+) -> anyhow::Result<()> {+ match run(state, document_id, proposed_by).await {Ok(()) => Ok(()),Err(e) => {// 原因随状态落库:只进日志的错误等于没有错误@@ -280,7 +286,7 @@ async fn resolve(Ok(r.entity_id)}-async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {+async fn run(state: &AppState, document_id: Uuid, proposed_by: Option<Uuid>) -> anyhow::Result<()> {let doc = utopia_store::documents::get(&state.pool, document_id).await?;let kb = utopia_store::kbs::get(&state.pool, doc.kb_id).await?;let settings = utopia_store::settings::get(&state.pool, kb.workspace_id)@@ -389,6 +395,13 @@ async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {// 本轮要从头讲一遍这篇文档的故事,旧信号先清掉(重抽自动作数)let _ = utopia_store::extraction_drops::clear_for_document(&state.pool, document_id).await;+ // **记忆抽出的事实先等人点头**(0015)。一句 remember 一次一句、人就在对话里,+ // 确认成本最低的时刻就是说完那句话的时候;而批量摄入一次上万条,逐条确认+ // 不可能,那条路仍旧乐观写入 + 事后审阅。判据只有一个:这篇是不是记忆日志。+ // 实体照常消解并创建——`pending_facts.subject_id` 是外键,这是 0018 定下的取舍+ let await_nod = utopia_store::memory::is_memory_document(&state.pool, document_id).await?;+ let mut pending_count = 0usize;+let doc_time = doc.doc_time.map(|t| t.format("%Y-%m-%d").to_string());let chunks = utopia_store::documents::chunks_for_extraction(&state.pool, document_id).await?;@@ -716,6 +729,29 @@ async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {// 单位随事实落笔:类型上的单位以后改了,旧值仍按记录时的单位读object_value["unit"] = serde_json::json!(u);}+ if await_nod {+ if let utopia_store::pending::Outcome::Proposed(_) =+ utopia_store::pending::propose(+ &state.pool,+ utopia_store::pending::Proposal {+ kb_id: doc.kb_id,+ subject_id,+ predicate_id: Some(attr.id),+ object_id: None,+ object_value: Some(&object_value),+ proposed_predicate: Some(f.predicate.as_str()),+ validity,+ confidence,+ chunk_id: chunk.id,+ proposed_by,+ },+ )+ .await?+ {+ pending_count += 1;+ }+ continue;+ }let (fact_id, created) = utopia_store::graph::insert_value_fact(&state.pool,doc.kb_id,@@ -812,12 +848,36 @@ async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {Some(&format!("{subject_name} → {value}")),).await;+ let literal = serde_json::json!({ "value": value });+ if await_nod {+ if let utopia_store::pending::Outcome::Proposed(_) =+ utopia_store::pending::propose(+ &state.pool,+ utopia_store::pending::Proposal {+ kb_id: doc.kb_id,+ subject_id,+ predicate_id: None,+ object_id: None,+ object_value: Some(&literal),+ proposed_predicate: Some(f.predicate.as_str()),+ validity,+ confidence,+ chunk_id: chunk.id,+ proposed_by,+ },+ )+ .await?+ {+ pending_count += 1;+ }+ continue;+ }let (fact_id, created) = utopia_store::graph::insert_value_fact(&state.pool,doc.kb_id,subject_id,None,- &serde_json::json!({ "value": value }),+ &literal,validity,confidence,)@@ -1024,6 +1084,28 @@ async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {(predicate_id, subject_id, object_id)};+ if await_nod {+ if let utopia_store::pending::Outcome::Proposed(_) = utopia_store::pending::propose(+ &state.pool,+ utopia_store::pending::Proposal {+ kb_id: doc.kb_id,+ subject_id,+ predicate_id,+ object_id: Some(object_id),+ object_value: None,+ proposed_predicate: Some(f.predicate.as_str()),+ validity,+ confidence,+ chunk_id: chunk.id,+ proposed_by,+ },+ )+ .await?+ {+ pending_count += 1;+ }+ continue;+ }{let (fact_id, created) = utopia_store::graph::insert_fact(&state.pool,@@ -1092,6 +1174,12 @@ async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {// (LLM 调用/解析失败的块在上方 continue 掉,不打标,下次重试)utopia_store::documents::mark_chunk_extracted(&state.pool, chunk.id).await?;}+ // 队列里多了东西才叫醒人:Review 的计数与对话里那张确认卡都靠这一声+ if pending_count > 0 {+ tracing::info!(%document_id, pending_count, "记忆抽出的事实进了待确认队列");+ state.emit_pending(doc.kb_id);+ state.emit_review(doc.kb_id);+ }// 消歧后缀在实体创建时算会早于其事实写入——收尾时对本文档涉及的名字统一刷新let names: std::collections::HashSet<&str> =diff --git a/crates/utopia-server/src/main.rs b/crates/utopia-server/src/main.rsindex 01613d88..5d2b69d3 100644--- a/crates/utopia-server/src/main.rs+++ b/crates/utopia-server/src/main.rs@@ -33,6 +33,14 @@ use utopia_core::config::AppConfig;use utopia_search::SearchIndex;use uuid::Uuid;+/// 记忆那条路带着「谁说的」(0015);别的任务没有这个字段,读到 None 本就该如此+fn payload_proposed_by(payload: &serde_json::Value) -> Option<Uuid> {+ payload+ .get("proposed_by")+ .and_then(|v| v.as_str())+ .and_then(|s| s.parse().ok())+}+fn payload_document_id(payload: &serde_json::Value) -> anyhow::Result<Uuid> {payload.get("document_id")@@ -295,7 +303,7 @@ async fn dispatch(st: &state::AppState, job: &utopia_store::jobs::Job) -> anyhow}"memory_ingest" => {let id = payload_document_id(&job.payload)?;- pipeline::memory_ingest(st, id).await+ pipeline::memory_ingest(st, id, payload_proposed_by(&job.payload)).await}"explore_mappings" => {let kb_id: Uuid = job@@ -342,7 +350,7 @@ async fn dispatch(st: &state::AppState, job: &utopia_store::jobs::Job) -> anyhow}"extract_document" => {let id = payload_document_id(&job.payload)?;- extraction::extract_document(st, id).await+ extraction::extract_document(st, id, payload_proposed_by(&job.payload)).await}"bootstrap_ontology" => {let kb_id: Uuid = jobdiff --git a/crates/utopia-server/src/pipeline.rs b/crates/utopia-server/src/pipeline.rsindex c2f18945..c8802062 100644--- a/crates/utopia-server/src/pipeline.rs+++ b/crates/utopia-server/src/pipeline.rs@@ -93,7 +93,13 @@ async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {/// 记忆摄入(episodes 快速路径的后半程):新 episode chunk 补 embedding、/// 重建全文索引、触发增量抽取(extracted_at 为空的新 chunk 才会被抽)。/// 免解析免分块——episode 落库时已是 chunk。-pub async fn memory_ingest(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {+///+/// `proposed_by`:说这句话的人。一路传到抽取,落在 `pending_facts.proposed_by`(0015)+pub async fn memory_ingest(+ state: &AppState,+ document_id: Uuid,+ proposed_by: Option<Uuid>,+) -> anyhow::Result<()> {let doc = utopia_store::documents::get(&state.pool, document_id).await?;let kb_row = utopia_store::kbs::get(&state.pool, doc.kb_id).await?;let settings = utopia_store::settings::get(&state.pool, kb_row.workspace_id).await?;@@ -132,7 +138,7 @@ pub async fn memory_ingest(state: &AppState, document_id: Uuid) -> anyhow::Resulutopia_store::jobs::enqueue(&state.pool,"extract_document",- serde_json::json!({ "document_id": document_id }),+ serde_json::json!({ "document_id": document_id, "proposed_by": proposed_by }),).await?;}diff --git a/crates/utopia-server/src/state.rs b/crates/utopia-server/src/state.rsindex 453a61e0..f74f0041 100644--- a/crates/utopia-server/src/state.rs+++ b/crates/utopia-server/src/state.rs@@ -82,6 +82,16 @@ impl AppState {});}+ /// 一句记忆抽出了等人点头的事实(0015)。对话里那张确认卡按这个刷新——+ /// 抽取是异步的,卡片只能在任务完成时长出来,而不是在助手回话的那一刻+ pub fn emit_pending(&self, kb_id: Uuid) {+ let _ = self.events.send(AppEvent {+ kb_id: Some(kb_id),+ kind: "pending",+ document_id: None,+ });+ }+/// 图变了。推理往图里加过边之后要发一次——它不经过文档管道,/// 而 `document` 那条事件是文档管道专用的pub fn emit_graph(&self, kb_id: Uuid) {diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rsindex f5d9ade8..3c312517 100644--- a/crates/utopia-store/src/lib.rs+++ b/crates/utopia-store/src/lib.rs@@ -19,6 +19,7 @@ pub mod memory;pub mod model_limits;pub mod ontology;pub mod palette;+pub mod pending;pub mod reasoning;pub mod resolution;pub mod review;diff --git a/crates/utopia-store/src/pending.rs b/crates/utopia-store/src/pending.rsnew file mode 100644index 00000000..6d5fd233--- /dev/null+++ b/crates/utopia-store/src/pending.rs@@ -0,0 +1,350 @@+//! 等人点头的事实(见 `docs/decisions/0015`,表在 `migrations/0018`)。+//!+//! 一句记忆抽出来的三元组先落这里,**不进 `facts`**:不上图、不参与检索、+//! 不进推理。人在对话里或 Review 页看见「原句在上、三元组在下」之后点头,+//! 它才经与抽取相同的那条路(`insert_fact` + 证据 + 时态对账)进账本。+//!+//! **为什么另一张表而不是 `facts` 加一列**:五十多处查询按 `invalidated_at IS NULL`+//! 捞活事实,逐个补过滤漏一处就有一条没人点头的事实混进图里——而这张表存在的+//! 全部理由就是防这件事。分开之后忘了读它的后果是「看不见待确认队列」,+//! 方向对了。0013 的 `derived_facts` 是同一个判断。+//!+//! **只拦交互式的单条写入。** 批量摄入仍旧乐观写入 + 事后审阅——那条路不经这里。++use sqlx::PgPool;+use utopia_core::models::PendingFactView;+use utopia_core::{AppError, AppResult};+use uuid::Uuid;++use crate::graph::Validity;++/// 抽取器交过来的一条提议。字段与 `insert_fact` / `insert_value_fact` 对齐,+/// 多出 `proposed_predicate`(模型原话)、`chunk_id`(那句记忆)、`proposed_by`(谁说的)。+pub struct Proposal<'a> {+ pub kb_id: Uuid,+ pub subject_id: Uuid,+ /// None = 本体里没有对应的关系(0010)。**人要看见的正是这个空**+ pub predicate_id: Option<Uuid>,+ pub object_id: Option<Uuid>,+ pub object_value: Option<&'a serde_json::Value>,+ pub proposed_predicate: Option<&'a str>,+ pub validity: Validity<'a>,+ pub confidence: f32,+ pub chunk_id: Uuid,+ pub proposed_by: Option<Uuid>,+}++/// 提议的去向。三种「没提」都不是错误——重抽一句记忆会再次算出同样的三元组,+/// 不挡住就等于每抽一次都把人的决定抹掉一次。+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Outcome {+ Proposed(Uuid),+ /// 图上已经有一条一样的活事实——不必再问+ AlreadyAsserted,+ /// 已经在队列里等着+ AlreadyPending,+ /// 人拒绝过这个三元组(`rejected_facts`)+ Rejected,+}++pub async fn propose(pool: &PgPool, p: Proposal<'_>) -> AppResult<Outcome> {+ let asserted: Option<(i32,)> = sqlx::query_as(+ "SELECT 1 FROM facts+ WHERE kb_id = $1 AND subject_id = $2+ AND predicate_id IS NOT DISTINCT FROM $3+ AND object_id IS NOT DISTINCT FROM $4+ AND object_value IS NOT DISTINCT FROM $5+ AND invalidated_at IS NULL+ LIMIT 1",+ )+ .bind(p.kb_id)+ .bind(p.subject_id)+ .bind(p.predicate_id)+ .bind(p.object_id)+ .bind(p.object_value)+ .fetch_optional(pool)+ .await?;+ if asserted.is_some() {+ return Ok(Outcome::AlreadyAsserted);+ }+ let pending: Option<(i32,)> = sqlx::query_as(+ "SELECT 1 FROM pending_facts+ WHERE kb_id = $1 AND subject_id = $2+ AND predicate_id IS NOT DISTINCT FROM $3+ AND object_id IS NOT DISTINCT FROM $4+ AND object_value IS NOT DISTINCT FROM $5+ LIMIT 1",+ )+ .bind(p.kb_id)+ .bind(p.subject_id)+ .bind(p.predicate_id)+ .bind(p.object_id)+ .bind(p.object_value)+ .fetch_optional(pool)+ .await?;+ if pending.is_some() {+ return Ok(Outcome::AlreadyPending);+ }+ // 拒绝记录只按 (主语, 谓词, 宾语实体) 查。**字面值事实不查**:`rejected_facts`+ // 没有 object_value 列,按 (主语, 谓词) 挡会把「薪水 28000 被拒」扩大成+ // 「薪水这个属性永远不再提」。宁可多问一次,不替人拒掉一个新值+ if let Some(object_id) = p.object_id {+ let rejected: Option<(i32,)> = sqlx::query_as(+ "SELECT 1 FROM rejected_facts+ WHERE kb_id = $1 AND subject_id = $2+ AND predicate_id IS NOT DISTINCT FROM $3+ AND object_id = $4+ LIMIT 1",+ )+ .bind(p.kb_id)+ .bind(p.subject_id)+ .bind(p.predicate_id)+ .bind(object_id)+ .fetch_optional(pool)+ .await?;+ if rejected.is_some() {+ return Ok(Outcome::Rejected);+ }+ }+ let id = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO pending_facts+ (id, kb_id, subject_id, predicate_id, object_id, object_value, proposed_predicate,+ valid_from, valid_from_precision, valid_to, valid_to_precision,+ confidence, chunk_id, proposed_by)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)",+ )+ .bind(id)+ .bind(p.kb_id)+ .bind(p.subject_id)+ .bind(p.predicate_id)+ .bind(p.object_id)+ .bind(p.object_value)+ .bind(p.proposed_predicate)+ .bind(p.validity.from)+ .bind(p.validity.from_precision)+ .bind(p.validity.to)+ .bind(p.validity.to_precision)+ .bind(p.confidence)+ .bind(p.chunk_id)+ .bind(p.proposed_by)+ .execute(pool)+ .await?;+ Ok(Outcome::Proposed(id))+}++/// 给人看的一条待确认项:`utopia_core::models::PendingFactView`。+const VIEW_SELECT: &str = "\+ SELECT p.id, p.subject_id, s.canonical_name AS subject_name,+ p.predicate_id, r.label AS predicate_label, p.proposed_predicate,+ p.object_id, o.canonical_name AS object_name, p.object_value,+ p.valid_from, p.valid_from_precision, p.valid_to, p.valid_to_precision,+ p.confidence, p.chunk_id, c.text AS quote,+ p.proposed_by, u.display_name AS proposed_by_name, p.created_at+ FROM pending_facts p+ JOIN entities s ON s.id = p.subject_id+ LEFT JOIN relation_types r ON r.id = p.predicate_id+ LEFT JOIN entities o ON o.id = p.object_id+ JOIN chunks c ON c.id = p.chunk_id+ LEFT JOIN users u ON u.id = p.proposed_by";++pub async fn list(+ pool: &PgPool,+ kb_id: Uuid,+ limit: i64,+ offset: i64,+) -> AppResult<Vec<PendingFactView>> {+ Ok(sqlx::query_as(&format!(+ "{VIEW_SELECT} WHERE p.kb_id = $1 ORDER BY p.created_at DESC LIMIT $2 OFFSET $3"+ ))+ .bind(kb_id)+ .bind(limit)+ .bind(offset)+ .fetch_all(pool)+ .await?)+}++/// 一句记忆抽出的全部待确认项——对话里那张卡片按这个取。+pub async fn for_chunk(+ pool: &PgPool,+ kb_id: Uuid,+ chunk_id: Uuid,+) -> AppResult<Vec<PendingFactView>> {+ Ok(sqlx::query_as(&format!(+ "{VIEW_SELECT} WHERE p.kb_id = $1 AND p.chunk_id = $2 ORDER BY p.created_at"+ ))+ .bind(kb_id)+ .bind(chunk_id)+ .fetch_all(pool)+ .await?)+}++async fn get(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<PendingFactView> {+ sqlx::query_as(&format!("{VIEW_SELECT} WHERE p.kb_id = $1 AND p.id = $2"))+ .bind(kb_id)+ .bind(id)+ .fetch_optional(pool)+ .await?+ .ok_or(AppError::NotFound)+}++/// 决策台账要的自包含快照:行删了之后台账上还读得出当时确认或拒绝的是什么。+fn snapshot(v: &PendingFactView) -> serde_json::Value {+ serde_json::json!({+ "subject": v.subject_name,+ "predicate": v.predicate_label,+ "proposed_predicate": v.proposed_predicate,+ "object": v.object_name,+ "object_value": v.object_value,+ "valid_from": v.valid_from,+ "valid_to": v.valid_to,+ "confidence": v.confidence,+ "quote": v.quote,+ "proposed_by": v.proposed_by_name,+ })+}++pub struct Confirmed {+ pub fact_id: Uuid,+ /// false = 图上已有同一条活事实,这次只补了证据+ pub created: bool,+ /// 时态对账拿不准、进了 `fact_conflicts` 的条数+ pub conflicts: u32,+ pub snapshot: serde_json::Value,+}++/// 人点头:按抽取那条路进账本——落事实、挂证据、时态对账——然后从队列里拿掉。+///+/// **置信度不动。** 人的态度不用浮点数表达(0011 的教训),它在审计台账里。+///+/// 不包事务:`insert_fact` 按 (主语, 谓词, 宾语) 对活事实去重,中途断掉再点一次+/// 只会补证据、不会落第二条,删行在最后——幂等靡有余悸。+pub async fn confirm(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<Confirmed> {+ let v = get(pool, kb_id, id).await?;+ let validity = Validity {+ from: v.valid_from,+ from_precision: v.valid_from_precision.as_deref(),+ to: v.valid_to,+ to_precision: v.valid_to_precision.as_deref(),+ };+ let (fact_id, created) = match (v.object_id, v.object_value.as_ref()) {+ (Some(object_id), _) => {+ crate::graph::insert_fact(+ pool,+ kb_id,+ v.subject_id,+ v.predicate_id,+ object_id,+ validity,+ v.confidence,+ )+ .await?+ }+ (None, Some(value)) => {+ crate::graph::insert_value_fact(+ pool,+ kb_id,+ v.subject_id,+ v.predicate_id,+ value,+ validity,+ v.confidence,+ )+ .await?+ }+ (None, None) => {+ return Err(AppError::invalid(+ "pending_fact_has_no_object",+ "a pending fact must have an object entity or a literal value",+ ))+ }+ };+ // 证据指回那句记忆。引句就是整句——一条 episode 本来就只有一句+ crate::graph::add_evidence(+ pool,+ fact_id,+ v.chunk_id,+ Some(&v.quote),+ v.proposed_predicate.as_deref(),+ )+ .await?;++ // 与抽取相同的时态对账:带唯一性约束的状态关系,新事实闭合旧事实。+ // 这正是记忆该有的行为——「Mira 交给 Devin 了」说完,Mira 那条就该闭合+ let mut conflicts = 0u32;+ if created {+ if let Some(pid) = v.predicate_id {+ let meta: Option<(bool, bool, String)> = sqlx::query_as(+ "SELECT functional, inverse_functional, temporal FROM relation_types WHERE id = $1",+ )+ .bind(pid)+ .fetch_optional(pool)+ .await?;+ if let Some((functional, inverse_functional, temporal)) = meta {+ if temporal == "state" {+ let mut directions = Vec::new();+ if functional {+ directions.push(crate::temporal::Uniqueness::SubjectSide);+ }+ // 宾语侧唯一只对实体宾语有意义;字面值没有「谁被指着」+ if inverse_functional && v.object_id.is_some() {+ directions.push(crate::temporal::Uniqueness::ObjectSide);+ }+ for dir in directions {+ let report = crate::temporal::reconcile_new_fact(+ pool,+ kb_id,+ fact_id,+ v.subject_id,+ pid,+ v.object_id,+ v.object_value.as_ref(),+ dir,+ validity,+ v.confidence,+ )+ .await?;+ conflicts += report.conflicts;+ }+ }+ }+ }+ }+ sqlx::query("DELETE FROM pending_facts WHERE id = $1")+ .bind(id)+ .execute(pool)+ .await?;+ Ok(Confirmed {+ fact_id,+ created,+ conflicts,+ snapshot: snapshot(&v),+ })+}++/// 人拒绝:记进 `rejected_facts`(下一轮重抽先查它),从队列里拿掉。+/// 那句记忆本身留着——人确实说过那句话,只是没抽出可用的事实。+pub async fn reject(+ pool: &PgPool,+ kb_id: Uuid,+ id: Uuid,+ rejected_by: Option<Uuid>,+) -> AppResult<serde_json::Value> {+ let v = get(pool, kb_id, id).await?;+ sqlx::query(+ "INSERT INTO rejected_facts (kb_id, subject_id, predicate_id, object_id, rejected_by)+ VALUES ($1, $2, $3, $4, $5)",+ )+ .bind(kb_id)+ .bind(v.subject_id)+ .bind(v.predicate_id)+ .bind(v.object_id)+ .bind(rejected_by)+ .execute(pool)+ .await?;+ sqlx::query("DELETE FROM pending_facts WHERE id = $1")+ .bind(id)+ .execute(pool)+ .await?;+ Ok(snapshot(&v))+}diff --git a/crates/utopia-store/src/review.rs b/crates/utopia-store/src/review.rsindex dd87081f..6ccd24bf 100644--- a/crates/utopia-store/src/review.rs+++ b/crates/utopia-store/src/review.rs@@ -22,6 +22,7 @@ pub const LOW_CONFIDENCE_BELOW: f32 = 0.75;pub async fn counts(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewCounts> {Ok(sqlx::query_as("SELECT+ (SELECT count(*) FROM pending_facts WHERE kb_id = $1) AS pending,(SELECT count(*) FROM resolution_reviewsWHERE kb_id = $1 AND status = 'pending') AS duplicates,(SELECT count(*) FROM fact_conflictsdiff --git a/crates/utopia-store/tests/a_fact_awaits_a_nod.rs b/crates/utopia-store/tests/a_fact_awaits_a_nod.rsnew file mode 100644index 00000000..8314b347--- /dev/null+++ b/crates/utopia-store/tests/a_fact_awaits_a_nod.rs@@ -0,0 +1,204 @@+//! 记忆抽出的事实先等人点头(`docs/decisions/0015`,表在迁移 0018)——打在真库上。+//!+//! 守的是那次实测的反面:对话里说「Acme 把总部搬到了深圳」,图上**不能**立刻多出+//! 一条活边。提议只进 `pending_facts`;人点头之后它才按抽取那条路进账本(事实 ++//! 证据指回那句话 + 时态对账);摇头之后同一个三元组不再被提。++use sqlx::PgPool;+use uuid::Uuid;++struct Fixture {+ /// 夹具建的 org,收尾时从它删起(级联)+ org: Uuid,+ kb: Uuid,+ acme: Uuid,+ shenzhen: Uuid,+ shanghai: Uuid,+ hq: Uuid,+ chunk: Uuid,+}++async fn fixture(pool: &PgPool) -> anyhow::Result<Fixture> {+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'nod-test')")+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'nod-test')")+ .bind(ws)+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query("INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'nod-test')")+ .bind(kb)+ .bind(ws)+ .execute(pool)+ .await?;+ // 总部只有一个:functional 让时态对账有事可做+ let hq = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO relation_types (id, kb_id, key, label, functional)+ VALUES ($1, $2, 'headquartered_in', 'headquartered in', TRUE)",+ )+ .bind(hq)+ .bind(kb)+ .execute(pool)+ .await?;+ let (acme, shenzhen, shanghai) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ for (id, name) in [+ (acme, "Acme"),+ (shenzhen, "Shenzhen"),+ (shanghai, "Shanghai"),+ ] {+ sqlx::query("INSERT INTO entities (id, kb_id, canonical_name) VALUES ($1, $2, $3)")+ .bind(id)+ .bind(kb)+ .bind(name)+ .execute(pool)+ .await?;+ }+ // 那句记忆,走产品自己的路落成 chunk+ let (_doc, chunk) = utopia_store::memory::append_episode(+ pool,+ kb,+ "Acme moved its headquarters to Shenzhen on 2026-03-15.",+ chrono::Utc::now(),+ )+ .await?;+ Ok(Fixture {+ org,+ kb,+ acme,+ shenzhen,+ shanghai,+ hq,+ chunk,+ })+}++fn day(s: &str) -> chrono::DateTime<chrono::Utc> {+ chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d")+ .unwrap()+ .and_hms_opt(0, 0, 0)+ .unwrap()+ .and_utc()+}++async fn live_facts(pool: &PgPool, kb: Uuid) -> anyhow::Result<i64> {+ let (n,): (i64,) =+ sqlx::query_as("SELECT count(*) FROM facts WHERE kb_id = $1 AND invalidated_at IS NULL")+ .bind(kb)+ .fetch_one(pool)+ .await?;+ Ok(n)+}++#[tokio::test]+async fn a_remembered_fact_waits_for_a_nod() -> 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 = fixture(&pool).await?;++ let run = async {+ use utopia_store::pending::{self, Outcome, Proposal};+ let propose = |object: Uuid, from: &'static str| {+ pending::propose(+ &pool,+ Proposal {+ kb_id: f.kb,+ subject_id: f.acme,+ predicate_id: Some(f.hq),+ object_id: Some(object),+ object_value: None,+ proposed_predicate: Some("moved headquarters to"),+ validity: utopia_store::graph::Validity {+ from: Some(day(from)),+ from_precision: Some("day"),+ to: None,+ to_precision: None,+ },+ confidence: 0.9,+ chunk_id: f.chunk,+ proposed_by: None,+ },+ )+ };++ // 1. 提议不上图+ let first = propose(f.shenzhen, "2026-03-15").await?;+ assert!(matches!(first, Outcome::Proposed(_)), "第一次该进队列");+ assert_eq!(live_facts(&pool, f.kb).await?, 0, "提议阶段图上不能有活边");+ let queued = pending::for_chunk(&pool, f.kb, f.chunk).await?;+ assert_eq!(queued.len(), 1);+ assert_eq!(queued[0].subject_name, "Acme");+ assert!(queued[0].quote.contains("Acme moved its headquarters"), "原句要跟着提议一起给人看");++ // 2. 同一句重抽不重复提+ assert_eq!(propose(f.shenzhen, "2026-03-15").await?, Outcome::AlreadyPending);++ // 3. 点头:进账本,证据指回那句话,队列清空+ let Outcome::Proposed(id) = first else { unreachable!() };+ let done = pending::confirm(&pool, f.kb, id).await?;+ assert!(done.created, "确认该落一条新事实");+ assert_eq!(live_facts(&pool, f.kb).await?, 1);+ let (ev_chunk, ev_proposed): (Uuid, Option<String>) = sqlx::query_as(+ "SELECT chunk_id, proposed_predicate FROM fact_evidence WHERE fact_id = $1",+ )+ .bind(done.fact_id)+ .fetch_one(&pool)+ .await?;+ assert_eq!(ev_chunk, f.chunk, "证据要指回那句记忆");+ assert_eq!(ev_proposed.as_deref(), Some("moved headquarters to"));+ assert!(pending::for_chunk(&pool, f.kb, f.chunk).await?.is_empty());++ // 4. 图上已有的不再问+ assert_eq!(propose(f.shenzhen, "2026-03-15").await?, Outcome::AlreadyAsserted);++ // 5. 摇头有记忆:拒过的三元组下一轮不再被提+ let Outcome::Proposed(bad) = propose(f.shanghai, "2020-01-01").await? else {+ panic!("换一个宾语该是新提议");+ };+ pending::reject(&pool, f.kb, bad, None).await?;+ assert_eq!(propose(f.shanghai, "2020-01-01").await?, Outcome::Rejected);+ assert_eq!(live_facts(&pool, f.kb).await?, 1, "拒绝不碰图");++ // 6. 点头走的是抽取那条路:functional 关系的新值闭合旧值。+ // 拒绝记录按 (主语, 谓词, 宾语) 查,同一个宾语换日期照样被挡——+ // 所以换一个宾语实体来演接任+ let beijing = Uuid::now_v7();+ sqlx::query("INSERT INTO entities (id, kb_id, canonical_name) VALUES ($1, $2, 'Beijing')")+ .bind(beijing)+ .bind(f.kb)+ .execute(&pool)+ .await?;+ let Outcome::Proposed(next) = propose(beijing, "2027-01-01").await? else {+ panic!("接任该是新提议");+ };+ let moved = pending::confirm(&pool, f.kb, next).await?;+ assert!(moved.created);+ assert_eq!(moved.conflicts, 0, "先后清楚、置信够高,该自动闭合而不是进冲突");+ let (closed,): (i64,) = sqlx::query_as(+ "SELECT count(*) FROM facts+ WHERE kb_id = $1 AND object_id = $2 AND invalidated_at IS NULL AND valid_to IS NOT NULL",+ )+ .bind(f.kb)+ .bind(f.shenzhen)+ .fetch_one(&pool)+ .await?;+ assert_eq!(closed, 1, "深圳那条该被闭合成有终点的区间");+ Ok::<_, anyhow::Error>(())+ }+ .await;++ // 删掉夹具自己建的 org,级联带走工作区、知识库与其余一切。+ // 从前只删知识库,每跑一次就在库里多留一对空的 org / workspace——+ // 「生产代码里没有删 org 这个动作」是对的,但夹具不是生产代码,自己建的自己收+ sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(f.org)+ .execute(&pool)+ .await?;+ run+}diff --git a/docs/decisions/0015-recording-a-sentence-is-not-asserting-a-fact.md b/docs/decisions/0015-recording-a-sentence-is-not-asserting-a-fact.mdindex 80ddc2af..3c9a3863 100644--- a/docs/decisions/0015-recording-a-sentence-is-not-asserting-a-fact.md+++ b/docs/decisions/0015-recording-a-sentence-is-not-asserting-a-fact.md@@ -1,6 +1,6 @@# 0015 · 记下一句话,不等于断言一个事实-- **状态**:进行中 · schema 已落(迁移 `0018_a_fact_awaiting_a_nod`,与本文同一 PR #180)· **抽取侧尚未接线,三条决定一条都没落地;`remember` 已被整体停用作为临时闸**(2026-09-02 核,修订见文末)+- **状态**:已实施 · schema 在迁移 `0018`(#180),运行时随 [0016](0016-close-the-open-seams-before-cutting-new-ones.md) A1 接上:抽取分流进 `pending_facts`、Review 新一档、对话里跟在 remember 后面的确认卡、`remember` 重新打开。**决定 3 的措辞与本文写的不同**,见文末最后一条修订- **成文**:2026-09-01(约定见 [README](README.md))- **相关**:[0010](0010-no-relation-is-no-relation.md) 删掉兜底关系(本篇那条空谓词正是它的正确行为)、[0011](0011-a-mapping-is-not-a-fact.md) 批过「拿浮点数编码二值状态」——@@ -136,12 +136,33 @@ object_value, valid_from, valid_to, ..., confidence, derived_by_rule, supersedes**同一类问题的另一面**(#173,迁移 `0015_what_it_did_not_just_what_it_said`):跨轮回放助手上一轮的工具调用与结果,模型才知道自己做过什么,不会把上一轮的检索重跑一遍落到另一批同名实体上。本文讲的是「助手说的」与「图里得到的」之间的落差,那一条讲的是「助手说的」与「助手做的」之间的落差。+## 修订记录:接上运行时之后,三处与本文不同++**一、助手说不出「抽出 N 条」。** 决定 3 写的是「已记录,抽出 N 条待你确认」。抽取是异步走队列的,+`remember` 回话的那一刻抽取还没跑,N 不存在。两条路:把记忆抽取改成同步(一句话十来秒,卡住整个对话循环),+或者如实说「这句话记下了,从中抽出的事实会先给你确认,确认前不进图」,等抽取完成时再把确认卡**长到对话里**。+选了后者。卡片靠 SSE 的 `pending` 事件触发,按那句记忆的 chunk 取待确认项;回放旧会话时同样按 chunk 取,+还有没点头的就照样显示,都处理完了就不占地方。++**二、确认界面在两处,同一个组件。** Review 页新一档「等你点头」排在最前——它是人自己说的话,而且这一档里的+东西还没进图,别处每一档审的都是已经在图上的。对话里那张卡是同一行组件。载荷是声明式的(chunk + 三元组列表),+将来若要让别人的客户端渲染它(MCP 那一侧),换的是渲染器不是服务端。++**三、确认走的正是抽取那条路。** 事实 + 证据(指回那句记忆,引句就是整句)+ 时态对账。所以「Mira 交给+Devin 了」点头之后,Mira 那条会像从文档里抽出来时一样被闭合。置信度不动,人的态度在台账里+(`fact.nod_confirmed` / `fact.nod_rejected`,快照自包含)。++**顺带定下的**:拒绝记录按(主语, 谓词, 宾语实体)查,**字面值事实不查**——`rejected_facts` 没有 `object_value`+列,按(主语, 谓词)挡会把「薪水 28000 被拒」扩大成「薪水这个属性永远不再提」,宁可多问一次。+实体照常消解并创建,`pending_facts.subject_id` 是外键,这是 0018 定下的取舍;代价是几个暂时孤立的节点。+「谁说的」从 `remember` 经 `memory_ingest` 与 `extract_document` 的任务载荷一路传到 `proposed_by`。+## 未决- **闸只拦记忆,还是拦所有「单条、交互式」的写入?** 今天只有 `remember` 这一条路,但将来若有「在图上手工加一条边」的界面,它该走哪边?- **确认之后置信度取什么。** 人点了头还留 0.9,还是升到 1.0?0011 的教训说别拿- confidence 表达人的态度,那大概是「不动它」——但要想清楚。+ confidence 表达人的态度,那大概是「不动它」——但要想清楚。〔**已定:不动**。人的态度在台账里。〕- **拒绝之后那条记忆怎么办。** 文档还在(人确实说过那句话),只是没抽出可用的事实。下一轮重抽会不会又提议一遍?`concept_mappings` 那边靠 `status='rejected'` 挡住了重复提议,这里需要对应的东西。〔答了一半:`rejected_facts` 表与查重索引建好了,语义就是「这个三元组在这个库里被拒过」,但没有任何代码写它或查它。〕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.mdindex 5aa818e1..346b671f 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@@ -50,7 +50,7 @@### A · 收口——两到三周,不加新概念-**A1 · 把 0015 接上。** 抽取遇到记忆文档(`memory::is_memory_document`,已写好零调用)时写 `pending_facts` 而不是 `facts`;+**A1 · 把 0015 接上。**〔已做,形态与下文有两处不同,见 0015 末尾的修订:助手说不出 N,确认卡在对话里随抽取完成长出来。〕 抽取遇到记忆文档(`memory::is_memory_document`,已写好零调用)时写 `pending_facts` 而不是 `facts`;Review 加 `pending` 一档,界面**原句在上、三元组在下**;确认 → `insert_fact`,**置信度不动**(0011 的教训:别拿浮点数表达人的态度,人的态度在审计台账里);拒绝 → 写 `rejected_facts`,下一轮重抽先查它;`remember` 的回话改成「已记录,抽出 N 条待你确认」;然后把 `REMEMBER_ENABLED` 改回 true。**验收**:那条实测(「Acme 把总部搬到深圳」)跑一遍,图上不出现空谓词活边,Review 里出现一条带原句的待确认项。@@ -114,5 +114,9 @@ A 与 B 做完之后单独写一篇决策记录,那时再排。- **A1 的闸只拦记忆,还是拦所有单条交互式写入?** 0015 未决。今天只有 `remember` 一条路,先拦它;将来「在图上手工加一条边」的界面出现时,按同一张表走。- **C3 生成的中文描述算不算「原文保真」的例外?** 它不是导入的原文,是我们生成的投影。倾向记成投影(可重跑、可丢弃),原文 IRI 与英文描述保留在包里。- **B4 的阈值**:10 秒是拍的。+- **对话内 agent 生成的界面走哪个协议。** A1 的确认卡载荷是声明式的(chunk + 三元组列表),渲染器是我们的 React。+ 讨论过 A2UI(2026-09-02):它解决的是「你不控制的客户端渲染你 agent 的 UI」,而 Chat 页两头都是我们的;+ 卖点成立的地方在 MCP 那一侧,那里对应的是 MCP 自己的 UI 扩展,不是 A2UI。**判据是谁的客户端在看**,+ 等 MCP 放开写工具、有外部客户端要渲染这张卡时再定。- **要不要把抽取层拆出 `utopia-server`。** 今天约 6,500 行领域代码(extraction、type_resolution、bootstrap_ontology、predicate_match、adjudication、owl_import、连接器)住在 HTTP crate 里,依赖方向仍是干净的一条线。讨论过(2026-09-02)决定**不拆**:唯一实在的收益是脱离 server 测纯函数,而它们的单测今天已经不起 server;搬动 1,500 行的 `extraction.rs` 会让紧接着的 A1 diff 和 blame 变难看。判据留下:**等它造成实际损失再拆,损失的定义是「有东西没法脱离 server 测试」**。连接器那一块的边界等第三个连接器(飞书)来了再定。- **十万文档基准跑出来之后**,单进程 worker 与内嵌 Tantivy 的天花板在哪,决定了要不要在 v0.2 谈横向扩展。现在不谈。diff --git a/docs/decisions/README.md b/docs/decisions/README.mdindex ac215b94..eea954ed 100644--- a/docs/decisions/README.md+++ b/docs/decisions/README.md@@ -40,7 +40,7 @@| 0012 | [本体是一份契约,不只是一份建议](0012-the-ontology-is-a-contract-not-a-suggestion.md) | 已实施 · 违反率 57%→4%、反向 39→0 · 三条待做全未做 || 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 只读五工具 · **没有令牌界面** · 误导性的占位 crate 已删 |-| 0015 | [记下一句话,不等于断言一个事实](0015-recording-a-sentence-is-not-asserting-a-fact.md) | 进行中 · schema 已落、**运行时零接线** · `remember` 整体停用作临时闸 |+| 0015 | [记下一句话,不等于断言一个事实](0015-recording-a-sentence-is-not-asserting-a-fact.md) | 已实施 · 记忆抽出的事实进 `pending_facts`,Review 新档 + 跟在 remember 步骤后的确认卡 · `remember` 重新打开 · MCP 放开写是下一刀 || 0016 | [先把开着的口子收上,再开新的](0016-close-the-open-seams-before-cutting-new-ones.md) | 规划中 · v0.1.0 之后的排期:A 收口 → B 推理机 ∥ C 尺子与本体 → D 语义层 → E 企业交付;模拟引擎后置 |## 不是决策记录的那些diff --git a/web/src/api.ts b/web/src/api.tsindex 7fbe3b29..a196674e 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -307,6 +307,7 @@ export interface DerivedFact {/** 审核页的分档。**与服务端的 queue 参数是同一组字面量**——拼错会拿到* 一个明确的 unknown_queue 错误,而不是悄悄的空列表。 */export type ReviewQueue =+ | "pending"| "duplicates"| "conflicts"| "unconfirmed"@@ -318,6 +319,8 @@ export type ReviewQueue =/** 各档的真实条数。左栏的徽标读它,不读列表长度 */export interface ReviewCounts {+ /** 记忆抽出、等人点头的事实(0015) */+ pending: number;duplicates: number;conflicts: number;unconfirmed: number;@@ -472,6 +475,29 @@ export interface FactReviewItem {quote: string | null;}+/** 一句记忆抽出、等人点头的事实(0015)。`quote` 是那句记忆的全文——+ * 确认界面把原句放在三元组上面,人对着原句判断,而不是凭空判断三元组。 */+export interface PendingFactItem {+ id: string;+ subject_id: string;+ subject_name: string;+ predicate_id: string | null;+ /** 本体里的关系名;为空时显示 `proposed_predicate`(斜体,标明是原话) */+ predicate_label: string | null;+ proposed_predicate: string | null;+ object_id: string | null;+ object_name: string | null;+ object_value: { value?: unknown; unit?: string; summary?: string } | null;+ valid_from: string | null;+ valid_to: string | null;+ confidence: number;+ chunk_id: string;+ quote: string;+ proposed_by: string | null;+ proposed_by_name: string | null;+ created_at: string;+}+/** 时态冲突(自动闭合拿不准的那些):旧事实 vs 新事实。 */export interface ConflictItem {id: string;@@ -785,6 +811,9 @@ export interface ChatStep {kind: "search" | "docs" | "entity" | "facts" | "changes" | "query" | "tool";label: string;detail: string;+ /** `remember` 那一步带着它:那句记忆落成的 chunk。对话里的确认卡按它取+ * 待确认项(0015);回放时也据此重画 */+ chunk_id?: string;/** 这一步发生时正文已经有多长(UTF-16 码元,与 `string.length` 同一单位)。* 据此把轨迹穿回正文里,而不是全堆在最前面。* **这条迁移之前的消息没有它**——缺省时整段轨迹回到顶部,即旧的样子 */@@ -1521,6 +1550,16 @@ export const api = {method: "POST",body: JSON.stringify(body),}),+ /** 一句记忆抽出的全部待确认项(0015)。空数组 = 这句话没有等着人的东西了 */+ pendingForChunk: (kbId: string, chunkId: string) =>+ request<{ items: PendingFactItem[] }>(+ `/api/v1/kbs/${kbId}/review/pending?chunk_id=${chunkId}`,+ ),+ decidePending: (kbId: string, pendingId: string, action: "confirm" | "reject") =>+ request<{ ok: boolean; fact_id?: string; created?: boolean; conflicts?: number }>(+ `/api/v1/kbs/${kbId}/review/pending/${pendingId}`,+ { method: "POST", body: JSON.stringify({ action }) },+ ),decideReview: (kbId: string, reviewId: string, action: "merge" | "keep") =>request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/${reviewId}`, {method: "POST",diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex 0cf63133..1f31932d 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -1171,6 +1171,7 @@ export const en = {empty: "Nothing to review — the graph is clean.",historyEmpty: "No merges yet.",// 左栏分类导航+ railPending: "Awaiting your nod",railDuplicates: "Duplicates",railConflicts: "Conflicts",railUnconfirmed: "Unconfirmed",@@ -1192,6 +1193,8 @@ export const en = {"review.keep": "Kept apart","fact.confirm": "Confirmed","fact.reject": "Rejected",+ "fact.nod_confirmed": "Confirmed a remembered fact",+ "fact.nod_rejected": "Rejected a remembered fact","fact.close": "Closed","conflict.close_old": "Closed old","conflict.keep_both": "Kept both",@@ -1273,6 +1276,19 @@ export const en = {mappingsHint:"Proposed mappings from a business concept to how it is computed. Confirm one and Ask uses it instead of guessing from the schema.",mappingDerived: "derived",+ // 记忆抽出、等人点头的事实(0015)+ pending: "Awaiting your confirmation",+ pendingHint:+ "Facts extracted from what you asked the assistant to remember. Nothing here is in the graph yet: " ++ "the sentence is kept, the facts wait for your nod. Confirm to add with the sentence as evidence; " ++ "reject and it will not be proposed again.",+ pendingNoPredicate: "The ontology has no relation for this; the word is the model's own.",+ pendingNoPredicateChip: "no relation in ontology",+ pendingSaidBy: (name: string) => `said by ${name}`,+ nodCardTitle: (n: number) =>+ n === 1+ ? "One fact extracted from this. Confirm to add it to the graph, or reject."+ : `${n} facts extracted from this. Confirm to add them to the graph, or reject.`,lowConfidenceHint:"Extracted with confidence below 75%. Confirm to trust, reject to remove from the graph (the ledger keeps the record).",confirm: "Confirm",diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex f83b2495..8e7f3bb0 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -1054,6 +1054,7 @@ export const zh: Strings = {tabHistory: "历史",empty: "没有待审阅的——图谱是干净的。",historyEmpty: "还没有合并记录。",+ railPending: "等你点头",railDuplicates: "重复项",railConflicts: "冲突",railUnconfirmed: "未确认",@@ -1074,6 +1075,8 @@ export const zh: Strings = {"review.keep": "保持分开","fact.confirm": "已确认","fact.reject": "已驳回",+ "fact.nod_confirmed": "已确认一条记忆事实",+ "fact.nod_rejected": "已驳回一条记忆事实","fact.close": "已闭合","conflict.close_old": "闭合旧的","conflict.keep_both": "两条都留",@@ -1150,6 +1153,16 @@ export const zh: Strings = {mappingsHint:"从业务概念到「这个数怎么算」的提议。确认之后问数直接用这个口径,而不是每次从 schema 猜。",mappingDerived: "派生",+ // 记忆抽出、等人点头的事实(0015)+ pending: "等你确认",+ pendingHint:+ "从你让助手记住的话里抽出的事实。这里的东西都还没进图:那句话已经存下,事实等你点头。" ++ "确认后以那句话为证据进账本;驳回后不会再被提议。",+ pendingNoPredicate: "本体里没有这个关系,这个词是模型自己的说法。",+ pendingNoPredicateChip: "本体里没有这个关系",+ pendingSaidBy: (name: string) => `${name} 说的`,+ nodCardTitle: (n: number) =>+ n === 1 ? "从这句话里抽出 1 条事实。确认进图,或驳回。" : `从这句话里抽出 ${n} 条事实。确认进图,或驳回。`,lowConfidenceHint:"抽取时置信度低于 75%。确认表示采信,驳回表示从图谱移除(台账仍留有记录)。",confirm: "确认",diff --git a/web/src/pages/Chat.tsx b/web/src/pages/Chat.tsxindex f4402d49..1e9b69ea 100644--- a/web/src/pages/Chat.tsx+++ b/web/src/pages/Chat.tsx@@ -36,6 +36,7 @@ import { toast } from "../toast";import { useKb, useKbId } from "../kb";import { DangerConfirm, RAIL_CLS } from "../ui";import { liveAnswer, type Turn } from "../liveAnswer";+import { NodCard } from "./PendingFacts";/* `Turn` 定义在 liveAnswer 里:进行中的那一次也是一串 Turn,而它必须活得比这个组件长(见那个文件顶上的说明) */@@ -705,10 +706,15 @@ function TurnView({ turn, live }: { turn: Turn; live?: boolean }) {className="my-2.5 space-y-1 border-l border-white/15 pl-2.5">{seg.steps.map((s, j) => (- <div key={j} className="flex items-center gap-1.5 text-xs">- <span className="text-neutral-600">{stepIcon(s.kind)}</span>- <span className="text-neutral-400 truncate">{s.label}</span>- <span className="text-neutral-600 shrink-0">· {s.detail}</span>+ <div key={j}>+ <div className="flex items-center gap-1.5 text-xs">+ <span className="text-neutral-600">{stepIcon(s.kind)}</span>+ <span className="text-neutral-400 truncate">{s.label}</span>+ <span className="text-neutral-600 shrink-0">· {s.detail}</span>+ </div>+ {/* remember 那一步后面跟着确认卡(0015):这句话抽出的事实先等人点头。+ 抽取是异步的,卡片在任务完成时才长出来;回放时按同一个 chunk 重画 */}+ {s.chunk_id && <NodCard kbId={kbId} chunkId={s.chunk_id} />}</div>))}</div>diff --git a/web/src/pages/PendingFacts.tsx b/web/src/pages/PendingFacts.tsxnew file mode 100644index 00000000..94e5ef3d--- /dev/null+++ b/web/src/pages/PendingFacts.tsx@@ -0,0 +1,150 @@+/* 等人点头的事实(docs/decisions/0015)。+ 一句 remember 抽出的三元组先进待确认队列,不上图;人在这里点头它才进账本。+ **原句在上,三元组在下**:只列三元组等于要人凭空判断它对不对——+ 实测里 `Acme --?--> 深圳` 那条,人一看原句就知道该拒。+ 两处共用同一行组件:Review 页的「待确认」一档,与 Chat 里跟在 remember 步骤后面的那张卡。 */+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { api, type PendingFactItem } from "../api";+import { S } from "../i18n";+import { toast } from "../toast";++function ym(iso: string | null): string | null {+ return iso ? iso.slice(0, 7) : null;+}++/** 记忆落库时正文前面带着 `[YYYY-MM-DD HH:MM] `(`memory::append_episode` 加的时间戳)。+ * 卡片上要的是那句话本身,时间戳是索引用的,剥掉 */+function sentence(quote: string): string {+ return quote.replace(/^\[\d{4}-\d{2}-\d{2}(?: \d{2}:\d{2})?\]\s*/, "");+}++function objectText(f: PendingFactItem): string {+ if (f.object_name) return f.object_name;+ const v = f.object_value;+ if (!v) return "?";+ if (v.summary) return v.summary;+ const val = v.value === undefined || v.value === null ? "?" : String(v.value);+ return v.unit ? `${val} ${v.unit}` : val;+}++/** 点头是写图的动作,Editor 起步——与服务端 `require_kb(Role::Editor)` 同一口径。+ * Viewer 看得见提议、看不见按钮:按钮亮着却点不动,等于让人猜自己有没有权限。+ * 查询键与 Library 页共用(`kbOne`),不多打一次接口 */+export function useCanDecide(kbId: string | undefined): boolean {+ const kbDetail = useQuery({+ queryKey: ["kbOne", kbId],+ queryFn: () => api.kbDetail(kbId!),+ enabled: !!kbId,+ });+ return ["editor", "admin", "owner"].includes(kbDetail.data?.my_role ?? "");+}++export function PendingFactRow({+ fact,+ busy,+ canDecide,+ onConfirm,+ onReject,+}: {+ fact: PendingFactItem;+ busy: boolean;+ canDecide: boolean;+ onConfirm: () => void;+ onReject: () => void;+}) {+ const from = ym(fact.valid_from);+ const to = ym(fact.valid_to);+ const range = from || to ? `${from ?? "…"} → ${to ?? S.review.ongoing}` : null;+ return (+ <div className="glass rounded-xl p-4">+ {/* 原句先出。它是人自己说的,判断的依据就是它 */}+ <p className="text-xs text-neutral-400 italic">“{sentence(fact.quote)}”</p>+ <div className="mt-2.5 flex items-center gap-2 flex-wrap">+ <span className="text-sm font-medium text-white">{fact.subject_name}</span>+ <span className="text-xs text-neutral-500">+ —{" "}+ {fact.predicate_label ? (+ <span>{fact.predicate_label}</span>+ ) : (+ /* 本体里没有这个关系:显示原话,斜体标明它不是词表里的词(0010) */+ <span+ className="italic text-neutral-600"+ title={S.review.pendingNoPredicate}+ >+ {fact.proposed_predicate ?? S.graph.unknownPredicate}+ </span>+ )}{" "}+ →+ </span>+ <span className="text-sm font-medium text-white">{objectText(fact)}</span>+ {range && <span className="text-xs text-neutral-500">({range})</span>}+ {!fact.predicate_label && (+ <span className="u-chip u-chip-warn ml-auto">{S.review.pendingNoPredicateChip}</span>+ )}+ </div>+ <div className="mt-3 flex items-center gap-2">+ {fact.proposed_by_name && (+ <span className="text-[11px] text-neutral-600">+ {S.review.pendingSaidBy(fact.proposed_by_name)}+ </span>+ )}+ {canDecide && (+ <div className="ml-auto flex gap-2">+ <button+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs text-[var(--u-danger)]"+ disabled={busy}+ onClick={onReject}+ >+ {S.review.reject}+ </button>+ <button+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs"+ disabled={busy}+ onClick={onConfirm}+ >+ {S.review.confirm}+ </button>+ </div>+ )}+ </div>+ </div>+ );+}++/** 跟在 remember 步骤后面的确认卡。+ * 抽取是异步的,卡片在任务完成时才长出来(SSE `pending` 事件让查询失效重取);+ * 回放旧会话时同样按 chunk 取——还有没点头的就照样显示,都处理完了就不占地方。 */+export function NodCard({ kbId, chunkId }: { kbId: string; chunkId: string }) {+ const queryClient = useQueryClient();+ const canDecide = useCanDecide(kbId);+ const q = useQuery({+ queryKey: ["pending", kbId, chunkId],+ queryFn: () => api.pendingForChunk(kbId, chunkId),+ });+ const decide = useMutation({+ mutationFn: ({ id, action }: { id: string; action: "confirm" | "reject" }) =>+ api.decidePending(kbId, id, action),+ onError: (e: Error) => toast.error(e.message),+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: ["pending", kbId] });+ queryClient.invalidateQueries({ queryKey: ["review", kbId] });+ },+ });+ const items = q.data?.items ?? [];+ if (items.length === 0) return null;+ return (+ <div className="my-2 space-y-2">+ <div className="text-xs text-neutral-500">{S.review.nodCardTitle(items.length)}</div>+ {items.map((f) => (+ <PendingFactRow+ key={f.id}+ fact={f}+ busy={decide.isPending && decide.variables?.id === f.id}+ canDecide={canDecide}+ onConfirm={() => decide.mutate({ id: f.id, action: "confirm" })}+ onReject={() => decide.mutate({ id: f.id, action: "reject" })}+ />+ ))}+ </div>+ );+}diff --git a/web/src/pages/Review.tsx b/web/src/pages/Review.tsxindex 2c975218..2971cc37 100644--- a/web/src/pages/Review.tsx+++ b/web/src/pages/Review.tsx@@ -10,10 +10,12 @@ import {type ConflictItem,type FactReviewItem,type MergeLog,+ type PendingFactItem,type ReviewHistoryEvent,type ReviewItem,type ReviewSide,} from "../api";+import { PendingFactRow, useCanDecide } from "./PendingFacts";import { S } from "../i18n";import { useKb, useKbId } from "../kb";import { Chip, type ChipTone, Pager, RAIL_CLS, cn } from "../ui";@@ -597,6 +599,9 @@ function ViolationRow({/* ---------- 页面:左栏分类 + 单类内容区 ---------- */type Sel =+ // 记忆抽出、等人点头的事实(0015)。排第一:它是人自己说的话,+ // 而且在这一档里的东西**还没进图**——别处每一档审的都是已经在图上的+ | "pending"| "duplicates"| "conflicts"| "unconfirmed"@@ -611,6 +616,7 @@ type Sel =/** 走服务端分页的那几档(决策台账另有自己的接口) */const QUEUE_FETCHED: ReviewQueue[] = [+ "pending","duplicates","conflicts","unconfirmed",@@ -621,6 +627,7 @@ const QUEUE_FETCHED: ReviewQueue[] = [];const QUEUE_ORDER: Sel[] = [+ "pending","duplicates","conflicts","unconfirmed",@@ -629,6 +636,7 @@ const QUEUE_ORDER: Sel[] = ["defects",];const PAGE_SIZE: Record<Sel, number> = {+ pending: FACT_PAGE,duplicates: DUP_PAGE,conflicts: CONFLICT_PAGE,unconfirmed: FACT_PAGE,@@ -749,6 +757,22 @@ export function Review() {: api.rejectFact(kb!.id, id),onSettled: invalidate,});+ // 等人点头的事实(0015):确认进账本,驳回记进 rejected_facts+ // 点头是写图的动作:Viewer 看得见提议、看不见按钮(与服务端 Editor 门槛同口径)+ const canDecidePending = useCanDecide(kb?.id);+ const pendingAction = useMutation({+ mutationFn: ({+ id,+ action,+ }: {+ id: string;+ action: "confirm" | "reject";+ }) => api.decidePending(kb!.id, id, action),+ onSettled: () => {+ invalidate();+ queryClient.invalidateQueries({ queryKey: ["pending", kb?.id] });+ },+ });const defectAction = useMutation({mutationFn: ({id,@@ -804,6 +828,7 @@ export function Review() {// mappings 不是本页的一档(审批在「数据映射」页),但计数照收:// 收件箱该说「有几条等你」const counts: Record<Sel | "mappings", number> = {+ pending: c?.pending ?? 0,duplicates: c?.duplicates ?? 0,conflicts: c?.conflicts ?? 0,unconfirmed: c?.unconfirmed ?? 0,@@ -817,6 +842,7 @@ export function Review() {// 当前这一档的一页。**服务端已经切好了**,这里只按档收窄类型——// 收窄错了会在渲染时露馅,而不是悄悄显示空列表const rows = review.data?.queue === queueSel ? (review.data.items ?? []) : [];+ const asPending = () => rows as PendingFactItem[];const asDuplicates = () => rows as ReviewItem[];const asFacts = () => rows as FactReviewItem[];const asConflicts = () => rows as ConflictItem[];@@ -841,6 +867,7 @@ export function Review() {const isQueueSel = QUEUE_ORDER.includes(active);const SECTION: Record<Sel, { title: string; hint: string | null }> = {+ pending: { title: S.review.pending, hint: S.review.pendingHint },duplicates: { title: S.review.duplicates, hint: S.review.duplicatesHint },conflicts: { title: S.review.conflicts, hint: S.review.conflictsHint },unconfirmed: {@@ -869,6 +896,12 @@ export function Review() {<aside className={`${RAIL_CLS} flex flex-col overflow-y-auto u-scroll`}><RailHeader label={S.review.tabQueue} /><div className="px-2 space-y-0.5">+ <RailItem+ active={active === "pending"}+ label={S.review.railPending}+ count={counts.pending}+ onClick={() => select("pending")}+ /><RailItemactive={active === "duplicates"}label={S.review.railDuplicates}@@ -1032,6 +1065,28 @@ export function Review() {</div>)}+ {active === "pending" && counts.pending > 0 && (+ <div className="space-y-3">+ {asPending().map((fact) => (+ <PendingFactRow+ key={fact.id}+ fact={fact}+ canDecide={canDecidePending}+ busy={+ pendingAction.isPending &&+ pendingAction.variables?.id === fact.id+ }+ onConfirm={() =>+ pendingAction.mutate({ id: fact.id, action: "confirm" })+ }+ onReject={() =>+ pendingAction.mutate({ id: fact.id, action: "reject" })+ }+ />+ ))}+ </div>+ )}+{active === "lowconf" && counts.lowconf > 0 && (<div className="space-y-3">{asFacts().map((fact) => (diff --git a/web/src/useKbEvents.ts b/web/src/useKbEvents.tsindex f7d8bbe6..66b0e232 100644--- a/web/src/useKbEvents.ts+++ b/web/src/useKbEvents.ts@@ -19,6 +19,11 @@ export function useKbEvents(kbId: string | undefined) {es.addEventListener("review", () => {queryClient.invalidateQueries({ queryKey: ["review", kbId] });});+ // 一句记忆抽出了等人点头的事实(0015):对话里那张确认卡跟着长出来+ es.addEventListener("pending", () => {+ queryClient.invalidateQueries({ queryKey: ["pending", kbId] });+ queryClient.invalidateQueries({ queryKey: ["review", kbId] });+ });es.addEventListener("source", () => {queryClient.invalidateQueries({ queryKey: ["sources", kbId] });queryClient.invalidateQueries({ queryKey: ["documents", kbId] });