Skip to content

World's first open-source enterprise world model.

A token acts as you, and MCP speaks through it (#180)

WaylandYangb5643ff23f71
diff --git a/Cargo.lock b/Cargo.lock
index 72700bd8..afdd530a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4871,6 +4871,7 @@ dependencies = [
"cron",
"pgvector",
"serde_json",
+ "sha2 0.11.0",
"sqlx",
"tokio",
"tracing",
diff --git a/Cargo.toml b/Cargo.toml
index 59e8fc65..af52b8aa 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -35,7 +35,7 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
anyhow = "1"
-uuid = { version = "1", features = ["v7", "serde"] }
+uuid = { version = "1", features = ["v4", "v7", "serde"] }
chrono = { version = "0.4", features = ["serde"] }
argon2 = { version = "0.5", features = ["std"] }
jsonwebtoken = { version = "10", features = ["rust_crypto"] }
diff --git a/crates/utopia-server/src/api/chat.rs b/crates/utopia-server/src/api/chat.rs
index 464e1349..aadb6bbb 100644
--- a/crates/utopia-server/src/api/chat.rs
+++ b/crates/utopia-server/src/api/chat.rs
@@ -29,6 +29,18 @@ const KNOWN_ENTITY_LIMIT: usize = 20;
const MAX_HISTORY: usize = 20;
const MAX_ROUNDS: usize = 6;
+/// **`remember` 暂时停用**(见 `docs/decisions/0015`)。
+///
+/// 它今天会把一句话直接变成图上一条活边,而中间那一步没人看得见:实测里
+/// 「记住 Acme 把总部搬到了深圳」落成的是一条 **空谓词、0.9 置信** 的边——
+/// 本体里没有「搬迁到」这类关系,抽取落不上就留空(按 0010 这是对的),
+/// 于是助手宣称的和图里得到的不是一回事。
+///
+/// 0018 建好了 `pending_facts`:抽出来的先等人点头。**抽取侧接上那张表
+/// 之后,把这里改回 true。** 在那之前宁可没有这个工具,也不要一个会
+/// 悄悄改图的工具。
+pub(super) const REMEMBER_ENABLED: bool = false;
+
#[derive(Deserialize)]
pub struct ChatReq {
/// 缺省 = 新建会话(SSE 首个 `conversation` 事件回传 id)
@@ -75,7 +87,7 @@ fn tools_schema(can_write: bool, data_source_names: &[String]) -> serde_json::Va
}));
}
}
- if can_write {
+ if can_write && REMEMBER_ENABLED {
if let Some(arr) = tools.as_array_mut() {
arr.push(json!({
"type": "function",
@@ -179,7 +191,12 @@ const MEMORY_PROMPT: &str = "\
\"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.";
-fn base_tools() -> serde_json::Value {
+/// 工具的 JSON schema——**给模型看的那一份**。
+///
+/// 留在 `chat.rs` 而不是 `tools.rs`:它是提示词的一部分,随对话策略走;
+/// `tools.rs` 只管拿到参数之后干什么(见那个模块顶上的说明)。
+/// MCP 也读它,所以对同模块开放——两边描述同一批工具,各写一份必然分叉。
+pub(super) fn base_tools() -> serde_json::Value {
json!([
{
"type": "function",
@@ -411,7 +428,7 @@ pub async fn chat(
let producer = async_stream::stream! {
let ds_names: Vec<String> = mounted_sources.iter().map(|d| d.name.clone()).collect();
let tools = tools_schema(can_write, &ds_names);
- let mut system_prompt = if can_write {
+ let mut system_prompt = if can_write && REMEMBER_ENABLED {
format!("{SYSTEM_PROMPT}\n{MEMORY_PROMPT}")
} else {
SYSTEM_PROMPT.to_string()
diff --git a/crates/utopia-server/src/api/mcp.rs b/crates/utopia-server/src/api/mcp.rs
new file mode 100644
index 00000000..a133f412
--- /dev/null
+++ b/crates/utopia-server/src/api/mcp.rs
@@ -0,0 +1,202 @@
+//! MCP 服务端(Streamable HTTP)。
+//!
+//! 一条路由:`POST /api/v1/kbs/{kb_id}/mcp`,收 JSON-RPC 2.0。
+//!
+//! **传输选 Streamable HTTP 不选 stdio**,理由在 `docs/decisions/0014`:Utopia
+//! 本来就是个服务端,stdio 要么起一个子进程反过来连它、要么再开一个连接池;
+//! 而这是多人部署,五个人各连各的应该由同一个部署统一服务。
+//!
+//! **每个 POST 都重新认证一次。** 规范允许把一次握手的结果沿用整条连接,
+//! 而 0014 那条纪律说得很清楚:
+//!
+//! > 校验 scope 要在每个工具入口,不在握手。`revoked_at` 中途被写上时必须
+//! > 立刻生效。
+//!
+//! 这里做成无状态之后,那条性质是白得的——没有「连接」这个东西可以被信任。
+//!
+//! **响应用 `application/json` 而不是 SSE。** 规范允许两者,而这些工具是
+//! 一问一答,没有服务端主动推的东西;SSE 是给通知用的,这一版不需要。
+
+use axum::extract::{Path, State};
+use axum::http::HeaderMap;
+use axum::Json;
+use serde_json::{json, Value};
+use utopia_core::models::Role;
+use uuid::Uuid;
+
+use super::tools::{self, ToolCtx, ToolSink};
+use crate::error::ApiResult;
+use crate::state::AppState;
+
+/// 实现的协议版本。客户端报别的版本时照样按这个答——
+/// 规范要求服务端回自己支持的版本,由客户端决定接不接受
+const PROTOCOL_VERSION: &str = "2025-06-18";
+
+/// 这一版放出去的工具。**只读四个**(0014):
+///
+/// `query_data` 对生产库跑 SQL,`remember` 往账本里写,两者各自还有没答完的
+/// 问题——外部 agent 写进来的事实挂什么证据、跑 SQL 的审计怎么记。先把身份
+/// 这条路走通。
+const EXPOSED: [&str; 4] = ["search_chunks", "search_docs", "find_entities", "changes"];
+/// `entity_facts` 也在内,单列是因为上面那个数组要定长
+const EXPOSED_EXTRA: &str = "entity_facts";
+
+fn is_exposed(name: &str) -> bool {
+ EXPOSED.contains(&name) || name == EXPOSED_EXTRA
+}
+
+/// 认证 + 授权。**两道,不是一道。**
+///
+/// 令牌说「这是谁、这枚钥匙够到哪几个库」;`require_kb` 说「这个人在这个库里
+/// 是什么角色」。前者只收窄,后者才是权限——一枚 scope 全开的令牌落在一个
+/// viewer 手上,仍旧只是 viewer。
+async fn authorize(
+ state: &AppState,
+ headers: &HeaderMap,
+ kb_id: Uuid,
+) -> Result<
+ (
+ utopia_core::models::User,
+ utopia_store::tokens::Authenticated,
+ ),
+ utopia_core::AppError,
+> {
+ let raw = headers
+ .get(axum::http::header::AUTHORIZATION)
+ .and_then(|v| v.to_str().ok())
+ .and_then(|v| v.strip_prefix("Bearer "))
+ .ok_or(utopia_core::AppError::Unauthorized)?;
+ let auth = utopia_store::tokens::authenticate(&state.pool, raw.trim()).await?;
+ // 令牌的范围:限定过库的,够不着别的
+ if !auth.covers(kb_id) {
+ return Err(utopia_core::AppError::Forbidden);
+ }
+ // 人:停用立即生效(find_user_by_id 会挡住)
+ let user = utopia_store::accounts::find_user_by_id(&state.pool, auth.user_id)
+ .await?
+ .ok_or(utopia_core::AppError::Unauthorized)?;
+ // 角色:和网页端走同一个守卫,一行没改
+ utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
+ Ok((user, auth))
+}
+
+/// OpenAI 形状 → MCP 形状。
+///
+/// **共用 `chat.rs` 那一份定义**,而不是在这里另写一套。名字与参数 schema 是
+/// 与 `tools.rs` 执行侧的契约,抄成两份迟早分叉——那正是上一步把工具抽出来
+/// 要避免的事。
+///
+/// 已知的瑕疵:描述是给应用内助手写的,`search_chunks` 那句还提着「可以引用
+/// 成 [n]」,而 MCP 客户端拿不到引用编号。共用一份的好处大过这句话的代价,
+/// 真要分开时再说。
+fn to_mcp_tools(openai: &Value) -> Vec<Value> {
+ openai
+ .as_array()
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|t| {
+ let f = t.get("function")?;
+ let name = f.get("name")?.as_str()?;
+ if !is_exposed(name) {
+ return None;
+ }
+ Some(json!({
+ "name": name,
+ "description": f.get("description").and_then(|d| d.as_str()).unwrap_or(""),
+ "inputSchema": f.get("parameters").cloned().unwrap_or(json!({
+ "type": "object", "properties": {}
+ })),
+ }))
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+fn ok(id: Option<Value>, result: Value) -> Json<Value> {
+ Json(json!({ "jsonrpc": "2.0", "id": id, "result": result }))
+}
+
+/// JSON-RPC 的错误不是 HTTP 的错误:**传输成功了,方法失败了**。
+/// 回 200 带 error 体,客户端才解析得动。
+fn rpc_err(id: Option<Value>, code: i64, message: &str) -> Json<Value> {
+ Json(json!({
+ "jsonrpc": "2.0", "id": id,
+ "error": { "code": code, "message": message }
+ }))
+}
+
+pub async fn handle(
+ State(state): State<AppState>,
+ Path(kb_id): Path<Uuid>,
+ headers: HeaderMap,
+ Json(req): Json<Value>,
+) -> ApiResult<Json<Value>> {
+ let (user, auth) = authorize(&state, &headers, kb_id).await?;
+ let id = req.get("id").cloned();
+ let method = req.get("method").and_then(|m| m.as_str()).unwrap_or("");
+ let params = req.get("params").cloned().unwrap_or(json!({}));
+
+ Ok(match method {
+ "initialize" => ok(
+ id,
+ json!({
+ "protocolVersion": PROTOCOL_VERSION,
+ "capabilities": { "tools": { "listChanged": false } },
+ "serverInfo": { "name": "utopia", "version": env!("CARGO_PKG_VERSION") },
+ }),
+ ),
+ // 通知没有 id,按规范不该回响应体;但 HTTP 这一侧总得回点什么,
+ // 回 202 语义更准,这里为了保持处理器签名统一回一个空结果
+ "notifications/initialized" | "notifications/cancelled" => ok(None, json!({})),
+ "ping" => ok(id, json!({})),
+ "tools/list" => ok(
+ id,
+ json!({ "tools": to_mcp_tools(&super::chat::base_tools()) }),
+ ),
+ "tools/call" => {
+ let name = params.get("name").and_then(|n| n.as_str()).unwrap_or("");
+ let args = params.get("arguments").cloned().unwrap_or(json!({}));
+ if !is_exposed(name) {
+ // 未暴露的工具(query_data / remember)要说清是「这一版没放出来」,
+ // 而不是「没有这个工具」——前者客户端不会反复重试
+ return Ok(rpc_err(
+ id,
+ -32601,
+ &format!("Tool '{name}' is not exposed over MCP in this version"),
+ ));
+ }
+ let kb = utopia_store::kbs::get(&state.pool, kb_id).await?;
+ // 这一版只放只读工具,所以 mounted_sources 空、can_write 假:
+ // **就算令牌 scope 是 write 也不放开**——scope 是上限不是授权,
+ // 而这一版的上限由 EXPOSED 定
+ let ctx = ToolCtx {
+ state: &state,
+ kb_id,
+ workspace_id: kb.workspace_id,
+ mounted_sources: &[],
+ can_write: false,
+ };
+ let mut sink = ToolSink::default();
+ let (text, _step) = tools::dispatch(&ctx, &mut sink, name, &args).await;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "mcp.tool_called",
+ "personal_token",
+ Some(auth.token_id),
+ json!({ "tool": name }),
+ )
+ .await;
+ ok(
+ id,
+ json!({
+ "content": [{ "type": "text", "text": text }],
+ "isError": false,
+ }),
+ )
+ }
+ other => rpc_err(id, -32601, &format!("Unknown method: {other}")),
+ })
+}
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index 3449f22c..b7869fe4 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -8,12 +8,14 @@ mod events_routes;
mod graph_routes;
mod kbs;
mod mapping_routes;
+mod mcp;
mod members_routes;
pub(crate) mod ontology_routes;
mod review_routes;
mod search_routes;
mod settings_routes;
mod sources_routes;
+mod token_routes;
mod tools;
mod workspaces;
@@ -120,6 +122,15 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
"/admin/data-sources/{id}/grants/{workspace_id}",
axum::routing::put(datasource_routes::grant).delete(datasource_routes::revoke),
)
+ .route("/kbs/{id}/mcp", post(mcp::handle))
+ .route(
+ "/me/tokens",
+ get(token_routes::list).post(token_routes::issue),
+ )
+ .route(
+ "/me/tokens/{token_id}",
+ axum::routing::delete(token_routes::revoke),
+ )
.route("/kbs/{id}/mappings", get(mapping_routes::list))
.route(
"/kbs/{id}/mappings/{mapping_id}",
diff --git a/crates/utopia-server/src/api/token_routes.rs b/crates/utopia-server/src/api/token_routes.rs
new file mode 100644
index 00000000..c56283e3
--- /dev/null
+++ b/crates/utopia-server/src/api/token_routes.rs
@@ -0,0 +1,94 @@
+//! 个人访问令牌的发放与撤销(0014)。
+//!
+//! **走的是账户级路由,不是知识库级**——令牌属于人,而人可以进好几个库。
+//! 哪几个库归令牌自己的 `kb_ids` 管,那是收窄,不是授权。
+
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use serde_json::json;
+use uuid::Uuid;
+
+use crate::auth::AuthUser;
+use crate::error::ApiResult;
+use crate::state::AppState;
+
+#[derive(Deserialize)]
+pub struct IssueReq {
+ pub name: String,
+ /// read | write。缺省只读——要让 agent 写进账本,得显式勾
+ #[serde(default = "default_scope")]
+ pub scope: String,
+ /// 缺省 = 这个人能进的全部库
+ #[serde(default)]
+ pub kb_ids: Option<Vec<Uuid>>,
+ /// 多少天后过期。缺省 90 天;显式给 0 表示不过期
+ #[serde(default = "default_days")]
+ pub expires_in_days: i64,
+}
+fn default_scope() -> String {
+ "read".into()
+}
+/// 90 天。**不过期是能选的,但不是缺省**——一枚配在别人笔记本上的钥匙,
+/// 忘了它存在是常态
+fn default_days() -> i64 {
+ 90
+}
+
+/// 发一枚。**明文只在这一次的响应里出现**,之后库里只有哈希。
+pub async fn issue(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Json(req): Json<IssueReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ let expires_at = (req.expires_in_days > 0)
+ .then(|| chrono::Utc::now() + chrono::Duration::days(req.expires_in_days));
+ let (view, plain) = utopia_store::tokens::issue(
+ &state.pool,
+ user.id,
+ &req.name,
+ &req.scope,
+ req.kb_ids.as_deref(),
+ expires_at,
+ )
+ .await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ None,
+ user.id,
+ "token.issued",
+ "personal_token",
+ Some(view.id),
+ json!({ "name": view.name, "scope": view.scope }),
+ )
+ .await;
+ // `token` 这个字段只在这里出现一次。列表接口永远给不出它
+ Ok(Json(json!({ "token": plain, "info": view })))
+}
+
+pub async fn list(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+) -> ApiResult<Json<serde_json::Value>> {
+ let tokens = utopia_store::tokens::list(&state.pool, user.id).await?;
+ Ok(Json(json!({ "tokens": tokens })))
+}
+
+pub async fn revoke(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(token_id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ utopia_store::tokens::revoke(&state.pool, user.id, token_id).await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ None,
+ user.id,
+ "token.revoked",
+ "personal_token",
+ Some(token_id),
+ json!({}),
+ )
+ .await;
+ Ok(Json(json!({ "ok": true })))
+}
diff --git a/crates/utopia-store/Cargo.toml b/crates/utopia-store/Cargo.toml
index 5ea3e1f9..d02c65f5 100644
--- a/crates/utopia-store/Cargo.toml
+++ b/crates/utopia-store/Cargo.toml
@@ -14,6 +14,7 @@ sqlx.workspace = true
tokio.workspace = true
serde_json.workspace = true
uuid.workspace = true
+sha2.workspace = true
chrono.workspace = true
anyhow.workspace = true
tracing.workspace = true
diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rs
index 111ad607..f5d9ade8 100644
--- a/crates/utopia-store/src/lib.rs
+++ b/crates/utopia-store/src/lib.rs
@@ -25,4 +25,5 @@ pub mod review;
pub mod settings;
pub mod sources;
pub mod temporal;
+pub mod tokens;
pub mod workspaces;
diff --git a/crates/utopia-store/src/memory.rs b/crates/utopia-store/src/memory.rs
index 4fa04ceb..d188ed4e 100644
--- a/crates/utopia-store/src/memory.rs
+++ b/crates/utopia-store/src/memory.rs
@@ -107,3 +107,20 @@ pub async fn append_episode(
tx.commit().await?;
Ok((doc_id, chunk_id))
}
+
+/// 这篇文档是不是记忆日志。
+///
+/// **抽取据此决定事实要不要人点头**(0015):记忆是人在对话里特意说的一句话,
+/// 一次一条、人就在现场,确认成本最低;而摄进来的文档一次上万条,逐条确认
+/// 是不可能的,那条路仍旧乐观写入 + 事后审阅。
+pub async fn is_memory_document(pool: &PgPool, document_id: Uuid) -> AppResult<bool> {
+ let found: Option<(i32,)> = sqlx::query_as(
+ "SELECT 1 FROM documents d JOIN sources s ON s.id = d.source_id
+ WHERE d.id = $1 AND s.kind = $2",
+ )
+ .bind(document_id)
+ .bind(MEMORY_SOURCE_KIND)
+ .fetch_optional(pool)
+ .await?;
+ Ok(found.is_some())
+}
diff --git a/crates/utopia-store/src/tokens.rs b/crates/utopia-store/src/tokens.rs
new file mode 100644
index 00000000..ce165c4d
--- /dev/null
+++ b/crates/utopia-store/src/tokens.rs
@@ -0,0 +1,178 @@
+//! 个人访问令牌(见 `docs/decisions/0014`)。
+//!
+//! **令牌以发它的人的身份行事,但不必是这个人的全部**:
+//!
+//! ```text
+//! 有效权限 = 这个人的角色 ∩ 这枚令牌的 scope
+//! ```
+//!
+//! 交集不是并集——viewer 的令牌勾上 write 也还是只读。所以这个模块只回答
+//! 「这串字符对应谁、这枚令牌准他干到哪一步」,**准不准他碰某个库仍旧由
+//! `access::require_kb` 判**,一行都不用改。
+
+use chrono::{DateTime, Utc};
+use sha2::{Digest, Sha256};
+use sqlx::PgPool;
+use utopia_core::models::TokenView;
+use utopia_core::{AppError, AppResult};
+use uuid::Uuid;
+
+/// 明文令牌的前缀。与 `sources.ingest_token` 的 `utp_` 区分开——
+/// 两者能干的事差很远,在日志或配置文件里一眼要认得出是哪一种
+const PREFIX: &str = "utp_pat_";
+/// 列表里给人认的那一小截(含前缀)。够对上配置文件里那一串,又不足以复原
+const SHOWN: usize = 16;
+
+/// 校验通过后拿到的东西:谁,以及这枚令牌准他干到哪一步。
+pub struct Authenticated {
+ pub user_id: Uuid,
+ pub token_id: Uuid,
+ /// read | write
+ pub scope: String,
+ /// None = 这个人能进的全部库
+ pub kb_ids: Option<Vec<Uuid>>,
+}
+
+impl Authenticated {
+ /// 这枚令牌准不准碰这个库。
+ ///
+ /// **这不是权限判断,是范围判断。** 返回 true 只说明「令牌没把它排除掉」,
+ /// 那个人在这个库里是什么角色,还得照常问 `access::require_kb`。
+ pub fn covers(&self, kb_id: Uuid) -> bool {
+ match &self.kb_ids {
+ None => true,
+ Some(ids) => ids.contains(&kb_id),
+ }
+ }
+
+ pub fn can_write(&self) -> bool {
+ self.scope == "write"
+ }
+}
+
+/// **SHA-256,不是 argon2。** 这一处与密码的存法不同,两个理由:
+///
+/// 1. **令牌是高熵随机串,不是人选的密码。** argon2 慢是为了让爆破一个
+/// 「password123」变得不划算;对 244 位随机数,慢一百万倍也照样爆不动,
+/// 买不到任何东西。
+/// 2. **argon2 每行盐不同,查不了。** 校验是热路径(每次工具调用一次),
+/// 而 `WHERE token_hash = $1` 走唯一索引是一次命中;换成 argon2 就得
+/// 把所有令牌取回来逐个 verify——发得越多越慢。
+fn hash(token: &str) -> String {
+ Sha256::digest(token.as_bytes())
+ .iter()
+ .map(|b| format!("{b:02x}"))
+ .collect()
+}
+
+/// 发一枚。**返回的明文是它唯一一次出现**——库里只存哈希,丢了只能重发。
+pub async fn issue(
+ pool: &PgPool,
+ user_id: Uuid,
+ name: &str,
+ scope: &str,
+ kb_ids: Option<&[Uuid]>,
+ expires_at: Option<DateTime<Utc>>,
+) -> AppResult<(TokenView, String)> {
+ let name = name.trim();
+ if name.is_empty() || name.chars().count() > 64 {
+ return AppResult::Err(AppError::invalid(
+ "bad_token_name",
+ "Token name must be 1-64 characters",
+ ));
+ }
+ if !matches!(scope, "read" | "write") {
+ return Err(AppError::invalid(
+ "bad_token_scope",
+ "Scope must be read or write",
+ ));
+ }
+ // 两个 v4 拼起来 ≈ 244 位熵。与 `new_ingest_token` 同一个做法,
+ // 换个前缀是为了在日志里分得清
+ let plain = format!(
+ "{PREFIX}{}{}",
+ Uuid::new_v4().simple(),
+ Uuid::new_v4().simple()
+ );
+ let id = Uuid::now_v7();
+ let view: TokenView = sqlx::query_as(
+ "INSERT INTO personal_tokens
+ (id, user_id, name, token_hash, token_prefix, scope, kb_ids, expires_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
+ RETURNING id, name, token_prefix, scope, kb_ids, expires_at,
+ last_used_at, revoked_at, created_at",
+ )
+ .bind(id)
+ .bind(user_id)
+ .bind(name)
+ .bind(hash(&plain))
+ .bind(&plain[..SHOWN])
+ .bind(scope)
+ .bind(kb_ids)
+ .bind(expires_at)
+ .fetch_one(pool)
+ .await?;
+ Ok((view, plain))
+}
+
+/// 我发过哪几把。撤销过的也列——**撤过这件事本身要看得见**。
+pub async fn list(pool: &PgPool, user_id: Uuid) -> AppResult<Vec<TokenView>> {
+ Ok(sqlx::query_as(
+ "SELECT id, name, token_prefix, scope, kb_ids, expires_at,
+ last_used_at, revoked_at, created_at
+ FROM personal_tokens WHERE user_id = $1 ORDER BY created_at DESC",
+ )
+ .bind(user_id)
+ .fetch_all(pool)
+ .await?)
+}
+
+/// 撤一把。**打戳不删行**:删了行,「这把钥匙存在过」就查不到了,
+/// 而那正是事后追查要问的第一件事。
+pub async fn revoke(pool: &PgPool, user_id: Uuid, token_id: Uuid) -> AppResult<()> {
+ let res = sqlx::query(
+ "UPDATE personal_tokens SET revoked_at = now()
+ WHERE id = $2 AND user_id = $1 AND revoked_at IS NULL",
+ )
+ .bind(user_id)
+ .bind(token_id)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
+
+/// 明文 → 这是谁、准干到哪一步。
+///
+/// **过期与撤销在 SQL 里判,不在 Rust 里判。** 取回来再比较的话,
+/// 「取回来」和「比较」之间那一段时间里被撤掉的令牌照样能过——而 MCP 的
+/// 连接是长命的,这一段能长到有意义。
+///
+/// 顺手写 `last_used_at`:撤销之前人要答得出「这把还在用吗」,
+/// 没有这个数没人敢撤。
+pub async fn authenticate(pool: &PgPool, plain: &str) -> AppResult<Authenticated> {
+ if !plain.starts_with(PREFIX) {
+ return Err(AppError::Unauthorized);
+ }
+ let row: Option<(Uuid, Uuid, String, Option<Vec<Uuid>>)> = sqlx::query_as(
+ "UPDATE personal_tokens SET last_used_at = now()
+ WHERE token_hash = $1
+ AND revoked_at IS NULL
+ AND (expires_at IS NULL OR expires_at > now())
+ RETURNING id, user_id, scope, kb_ids",
+ )
+ .bind(hash(plain))
+ .fetch_optional(pool)
+ .await?;
+ let Some((token_id, user_id, scope, kb_ids)) = row else {
+ return Err(AppError::Unauthorized);
+ };
+ Ok(Authenticated {
+ user_id,
+ token_id,
+ scope,
+ kb_ids,
+ })
+}
diff --git a/crates/utopia-store/tests/a_token_is_the_person_but_not_all_of_them.rs b/crates/utopia-store/tests/a_token_is_the_person_but_not_all_of_them.rs
new file mode 100644
index 00000000..870eda7e
--- /dev/null
+++ b/crates/utopia-store/tests/a_token_is_the_person_but_not_all_of_them.rs
@@ -0,0 +1,193 @@
+//! 个人访问令牌(0014 / 迁移 0015)。
+//!
+//! 这一枚令牌是给 MCP 客户端用的:长命、配在别人机器上的一个文件里、以发它的
+//! 人的身份行事。所以它必须撤得掉、过得了期、而且**范围只能比这个人更小**。
+//!
+//! 钉五件事:
+//!
+//! - **明文只出现一次**。库里只有哈希,拿到整张表也复原不出那串字符
+//! - **撤销立刻生效**。而且是打戳不删行——「这把钥匙存在过」要查得到
+//! - **过期立刻失效**,判断在 SQL 里做,不在取回来之后做
+//! - **`kb_ids` 只收窄**。限定到一个库的令牌,够不着另一个
+//! - **`last_used_at` 会被写上**。撤之前人要答得出「这把还在用吗」
+
+use chrono::{Duration, Utc};
+use sqlx::PgPool;
+use utopia_store::tokens;
+use uuid::Uuid;
+
+struct Fixture {
+ org: Uuid,
+ user: Uuid,
+ kb_a: Uuid,
+ kb_b: Uuid,
+}
+
+async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
+ let org = Uuid::now_v7();
+ let ws = Uuid::now_v7();
+ let user = Uuid::now_v7();
+ let (kb_a, kb_b) = (Uuid::now_v7(), Uuid::now_v7());
+
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'token-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'token-test')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ for (kb, name) in [(kb_a, "kb-a"), (kb_b, "kb-b")] {
+ sqlx::query("INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, $3)")
+ .bind(kb)
+ .bind(ws)
+ .bind(name)
+ .execute(pool)
+ .await?;
+ }
+ sqlx::query(
+ "INSERT INTO users (id, org_id, email, password_hash, display_name)
+ VALUES ($1, $2, $3, 'x', 'Token Test')",
+ )
+ .bind(user)
+ .bind(org)
+ .bind(format!("{user}@token.test"))
+ .execute(pool)
+ .await?;
+
+ Ok(Fixture {
+ org,
+ user,
+ kb_a,
+ kb_b,
+ })
+}
+
+#[tokio::test]
+async fn a_token_is_the_person_but_not_all_of_them() -> anyhow::Result<()> {
+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ // ---- 一、发一枚,明文只这一次拿得到
+ let (view, plain) = tokens::issue(&pool, f.user, "我的笔记本", "read", None, None).await?;
+ assert!(plain.starts_with("utp_pat_"), "前缀要认得出是哪一种令牌");
+ assert_eq!(view.scope, "read", "**缺省只读**:要写得显式勾");
+ assert!(view.revoked_at.is_none());
+
+ let stored: String =
+ sqlx::query_scalar("SELECT token_hash FROM personal_tokens WHERE id = $1")
+ .bind(view.id)
+ .fetch_one(&pool)
+ .await?;
+ assert_ne!(stored, plain, "库里存的必须是哈希");
+ assert!(
+ !stored.contains(&plain[8..24]),
+ "**明文的任何一段都不该出现在库里**——拿到整张表也复原不出来"
+ );
+
+ // ---- 二、认得回来,而且顺手写了 last_used_at
+ let auth = tokens::authenticate(&pool, &plain).await?;
+ assert_eq!(auth.user_id, f.user, "令牌以发它的人的身份行事");
+ assert!(!auth.can_write(), "read 的令牌不能写");
+ let used: Option<chrono::DateTime<Utc>> =
+ sqlx::query_scalar("SELECT last_used_at FROM personal_tokens WHERE id = $1")
+ .bind(view.id)
+ .fetch_one(&pool)
+ .await?;
+ assert!(used.is_some(), "**撤之前人要答得出「这把还在用吗」**");
+
+ // ---- 三、伪造的、前缀不对的,一律不认
+ assert!(
+ tokens::authenticate(&pool, "utp_pat_deadbeef")
+ .await
+ .is_err(),
+ "编一串出来不该认"
+ );
+ assert!(
+ tokens::authenticate(&pool, &plain.replace("utp_pat_", "utp_"))
+ .await
+ .is_err(),
+ "摄入令牌的前缀不该走这条路"
+ );
+
+ // ---- 四、kb_ids 只收窄
+ let (_, scoped) =
+ tokens::issue(&pool, f.user, "只给 A 库", "write", Some(&[f.kb_a]), None).await?;
+ let auth = tokens::authenticate(&pool, &scoped).await?;
+ assert!(auth.covers(f.kb_a), "授权过的库够得着");
+ assert!(
+ !auth.covers(f.kb_b),
+ "**限定到一个库的令牌够不着另一个**——哪怕这个人两个库都能进"
+ );
+ assert!(auth.can_write(), "write 的令牌能写");
+ // 不限定的那一枚照样覆盖全部
+ assert!(tokens::authenticate(&pool, &plain).await?.covers(f.kb_b));
+
+ // ---- 五、撤销立刻生效,而且行还在
+ tokens::revoke(&pool, f.user, view.id).await?;
+ assert!(
+ tokens::authenticate(&pool, &plain).await.is_err(),
+ "**撤了就立刻不认**——判断在 SQL 里,不在取回来之后"
+ );
+ let still_there: i64 =
+ sqlx::query_scalar("SELECT count(*) FROM personal_tokens WHERE id = $1")
+ .bind(view.id)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(still_there, 1, "打戳不删行:这把钥匙存在过要查得到");
+ assert!(
+ tokens::revoke(&pool, f.user, view.id).await.is_err(),
+ "撤两次的第二次该说没有这一行可撤"
+ );
+
+ // ---- 六、过期
+ let (expired_view, expired) = tokens::issue(
+ &pool,
+ f.user,
+ "早就过期的",
+ "read",
+ None,
+ Some(Utc::now() - Duration::hours(1)),
+ )
+ .await?;
+ assert!(
+ tokens::authenticate(&pool, &expired).await.is_err(),
+ "过了期就不认"
+ );
+
+ // ---- 七、列表把撤过的、过期的都列出来
+ let all = tokens::list(&pool, f.user).await?;
+ assert_eq!(all.len(), 3, "撤销过的也要列——撤过这件事本身要看得见");
+ assert!(
+ all.iter()
+ .any(|t| t.id == view.id && t.revoked_at.is_some()),
+ "列表要标出哪一把被撤了"
+ );
+ assert!(
+ all.iter().all(|t| t.token_prefix.starts_with("utp_pat_")),
+ "列表只给前缀,不给明文"
+ );
+ assert!(all.iter().any(|t| t.id == expired_view.id));
+
+ // 别人的令牌撤不动
+ let other = Uuid::now_v7();
+ assert!(
+ tokens::revoke(&pool, other, expired_view.id).await.is_err(),
+ "**令牌是谁的谁才撤得动**"
+ );
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ 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.md
new file mode 100644
index 00000000..cda3b952
--- /dev/null
+++ b/docs/decisions/0015-recording-a-sentence-is-not-asserting-a-fact.md
@@ -0,0 +1,133 @@
+# 0015 · 记下一句话,不等于断言一个事实
+
+- **状态**:规划中 · schema 未动
+- **成文**:2026-09-01(约定见 [README](README.md))
+- **相关**:[0010](0010-no-relation-is-no-relation.md) 删掉兜底关系(本篇那条空谓词正是它的
+ 正确行为)、[0011](0011-a-mapping-is-not-a-fact.md) 批过「拿浮点数编码二值状态」——
+ 本篇的实现红线;[0014](0014-identity-from-the-person-scope-from-the-token.md) 里
+ 「MCP 不开写」的主要顾虑,被本篇的闸消掉
+
+> 起因是一次实测,不是推演。跑通 `remember` 之后回头查库,看到的东西和助手说的
+> 对不上。
+
+## 那一次实测
+
+对话里说:
+
+> Please remember this: Acme moved its headquarters to Shenzhen on 2026-03-15.
+
+助手答:
+
+> I've recorded that **Acme moved its headquarters to Shenzhen** on March 15, 2026.
+
+而图里落下的是:
+
+```
+Acme --(空谓词)-> Shenzhen confidence 0.9 invalidated_at 空
+```
+
+谓词是空的——本体里没有「搬迁到 / 总部位于」这类关系,抽取落不上就留空。**按 0010
+这是正确行为**(不编一个 `related_to` 出来)。但结果是图上多了一条 0.9 置信、没有
+语义的边,而且**说的和进去的不是一回事,人没有任何办法发现**。
+
+## 现状:根本没有确认这道闸
+
+查之前以为 `unconfirmed` 队列就是它。不是,它的定义是:
+
+```sql
+-- 待确认 = 有证据、但证据所在的分块全被新版本取代了
+```
+
+那是**证据过期**队列。`lowconf` 是 `confidence < 0.75`。两个都是事后清理:低置信事实
+在队列里躺着的时候,它已经是图上一条活边(`invalidated_at IS NULL`)。
+
+所以:**任何抽取出来的事实,一落库就生效,没有任何一步需要人点头。**
+
+## 这对批量摄入是对的,对 `remember` 不是
+
+灌 500 篇文档抽出一万条事实,让人逐条确认是不可能的。乐观写入 + 事后审阅是那条路上
+唯一可行的设计,本篇不动它。
+
+`remember` 是另一回事,三点都不一样:
+
+| | 文档摄入 | remember |
+|---|---|---|
+| 量 | 一次上万条 | 一次一句 |
+| 人在哪 | 上传完就走了 | **就在对话里** |
+| 素材 | 外部证据 | 人自己特意说的一句话 |
+
+确认成本最低的那一刻,恰好就是他说完那句话的那一刻。
+
+## 真正的病不是「少一道闸」
+
+是**助手宣称的和图里得到的不一致**。
+
+「已记录 Acme 把总部搬到深圳」听起来像是那件事进去了;实际进去的是一条无谓词的边。
+所以二次确认的价值主要不在多点一下,在于**让人看见即将断言的是什么**——看到
+`Acme --?-> Shenzhen`,人会立刻说这不对。
+
+这也决定了确认界面该长什么样:**原句在上,抽出的三元组在下**,两者并排。只列三元组
+等于要人凭空判断它对不对。
+
+## 决定
+
+1. **`remember` 写文档这一步不变。** 那只是记录「你说过这句话」,本身无害,也确实
+ 该立刻可检索。
+2. **从记忆抽出的事实,进图前要人确认。** 未确认的不参与检索、不上图、不进推理。
+3. **助手的话照实说**:「已记录,抽出 N 条待你确认」,不宣称完成。
+
+## 修订记录:第一版把状态加在 `facts` 上,错了
+
+**原本的方案**是给 `facts` 加三列(`nod` / `nodded_by` / `nodded_at`),
+`nod = 'pending'` 表示等人点头。迁移写完、`insert_fact` 的参数也穿好了,
+才发现这是**这个仓库半个月前刚踩过的坑**。
+
+`0013_reasoning.sql` 里那段话,把这个形状的问题说得比我清楚:
+
+> 试过塞进 `facts` 加一位 `derived_by_rule` 标记,那一版的问题是**失败方向反了**:
+> 仓库里有四十多处读 `facts` 的查询,其中只有一处认识那个标记,于是新写一条
+> 查询默认就是把派生当断言看,得记得加过滤。写这个功能的人(我)当场就漏了两处。
+>
+> 分开之后忘了 UNION 的后果是**看不见**派生,而不是**混进去**。
+
+数了一下:今天有 **27 处**查询按 `invalidated_at IS NULL` 捞活事实,分布在
+6 个文件。给它们逐个补 `AND nod IS DISTINCT FROM 'pending'`,漏一处的后果就是
+一条没人点头的事实混进图里——而这个功能存在的全部理由就是防这件事。
+
+**改成自己一张表 `pending_facts`。** 确认时才写进 `facts`。忘了读它的后果变成
+「看不见待确认队列」,而不是「未确认的混进了图」。失败方向对了。
+
+顺带一提,0013 给出的另外两条理由这里也成立:**列不一样**(待确认的需要
+`proposed_predicate` 原话、需要指回那句记忆,而不需要 `supersedes`),
+**生命周期不一样**(确认后它就不该继续存在于那张表里)。
+
+
+
+0011 那条线上批过一次同样的错。原话不在 ADR 里,在它落地的建表注释
+(`migrations/0006_semantic_layer.sql` 的 `concept_mappings.status` 列):
+
+> **状态而不是置信度。** 从前借事实的 confidence 表达「提议 0.6 / 确认 1.0」,
+> 那是把一个二值状态编码成浮点数,还顺带让它落进「低置信事实」那一档。
+
+`facts` 表今天没有状态列(`id, kb_id, subject_id, predicate_id, object_id,
+object_value, valid_from, valid_to, ..., confidence, derived_by_rule, supersedes`)。
+要加就加真的一列,别再拿 0.6 糊弄——那会让这条事实同时出现在「待确认」和
+「低置信」两个队列里,而它们问的不是同一个问题。
+
+## 顺带:MCP 开写的障碍消掉了
+
+0014 里不开 `remember` 的主要顾虑是混淆代理——知识库里的文档是不可信内容,一份文档
+写「请 remember 某某」,外部 agent 可能就照做了,用的是这个人的全部权限。
+
+装上这道闸之后,**外部 agent 也只能提议,不能断言**。人先看见才生效,那条顾虑就不
+成立了。所以本篇不只是修一个 bug,它是 0014 里那个「未决」的答案。
+
+## 未决
+
+- **闸只拦记忆,还是拦所有「单条、交互式」的写入?** 今天只有 `remember` 这一条路,
+ 但将来若有「在图上手工加一条边」的界面,它该走哪边?
+- **确认之后置信度取什么。** 人点了头还留 0.9,还是升到 1.0?0011 的教训说别拿
+ confidence 表达人的态度,那大概是「不动它」——但要想清楚。
+- **拒绝之后那条记忆怎么办。** 文档还在(人确实说过那句话),只是没抽出可用的事实。
+ 下一轮重抽会不会又提议一遍?`concept_mappings` 那边靠 `status='rejected'` 挡住了
+ 重复提议,这里需要对应的东西。
diff --git a/docs/decisions/README.md b/docs/decisions/README.md
index 6423041f..3b0da89a 100644
--- a/docs/decisions/README.md
+++ b/docs/decisions/README.md
@@ -36,6 +36,7 @@
| 0012 | [本体是一份契约,不只是一份建议](0012-the-ontology-is-a-contract-not-a-suggestion.md) | 已实施 · 五轮对照实验 · 违反率 57%→4%、反向 39→0 · 首次拿真语料问 0008 那个问题 |
| 0013 | [一个来源该交出它的历史,不是它的现状](0013-a-source-should-hand-over-its-history.md) | 已实施两个(GitHub / Jira 工单)· **文档协作类待做** |
| 0014 | [身份跟着人,范围跟着令牌](0014-identity-from-the-person-scope-from-the-token.md) | 规划中 · MCP 服务端的第一块地基 · 含一条被否掉的岔路(KB 级机器令牌)|
+| 0015 | [记下一句话,不等于断言一个事实](0015-recording-a-sentence-is-not-asserting-a-fact.md) | 规划中 · 起因是一次实测:助手说的与图里落的不是一回事 · **含一次就地推翻**(状态加在 facts 上 → 自己一张表)· 消掉 0014 里「不开写」的顾虑 |
## 不是决策记录的那些
diff --git a/migrations/0017_personal_tokens.sql b/migrations/0017_personal_tokens.sql
new file mode 100644
index 00000000..9b08c3a1
--- /dev/null
+++ b/migrations/0017_personal_tokens.sql
@@ -0,0 +1,53 @@
+-- 个人访问令牌:给 MCP 客户端一把长命的钥匙(见 docs/decisions/0014)。
+--
+-- **它以这个人的身份行事,但不必是这个人的全部。**
+--
+-- 有效权限 = 这个人的角色 ∩ 这枚令牌的 scope
+--
+-- 交集不是并集:viewer 的令牌勾上 write 也还是只读。scope 是上限,不是授权。
+--
+-- 为什么不发机器令牌(0014 里留痕的那条岔路):机器身份要引入第三套授权模型,
+-- 而且 `audit_events.actor_id` 会多出一类「不是任何人做的」记录——账本存在的
+-- 理由正是「谁在什么时候认下了什么」。
+CREATE TABLE personal_tokens (
+ id UUID PRIMARY KEY,
+ -- **有外键且级联**,与 `audit_events.actor_id` 的裸 UUID 相反:
+ -- 台账要活得比用户久,钥匙不该。人没了,他的钥匙就该一起没
+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ -- 人自己起的名字,"我的笔记本"。撤销时要认得出撤的是哪一把
+ name TEXT NOT NULL,
+
+ -- **哈希存,与 `sources.ingest_token` 的明文相反。**
+ --
+ -- 那一条的理由是「DB 失守时文档本体早已泄露,哈希化没有额外收益」,
+ -- 而它成立是因为 ingest_token 只能**往里推文档**。这一把不一样:它经
+ -- `query_data` 能读出 Utopia 之外的生产库。数仓在另一台机器上、装着另一批
+ -- 数据,不该跟着 Utopia 的库一起丢。**爆炸半径不同,所以存法不同。**
+ token_hash TEXT NOT NULL UNIQUE,
+ -- 给人认的前缀(`utp_ab12…`)。列表里要能一眼对上配置文件里那一串,
+ -- 而不必把整条明文留下来
+ token_prefix TEXT NOT NULL,
+
+ -- read = 只读工具;write = 额外放开 remember。**默认只读**:
+ -- 要让 agent 写进账本,得显式勾
+ scope TEXT NOT NULL DEFAULT 'read' CHECK (scope IN ('read', 'write')),
+ -- 限定到哪几个库。NULL = 这个人能进的全部。
+ -- 裸 UUID 数组不是懒:库删了这一项只是失效,不该把令牌整个删掉
+ kb_ids UUID[],
+
+ -- NULL = 不过期。界面默认给 90 天——不过期是能选的,但不是缺省
+ expires_at TIMESTAMPTZ,
+ -- 「这把还在用吗」。撤之前要答得出这个问题,否则没人敢撤
+ last_used_at TIMESTAMPTZ,
+ -- **撤销不删行**:撤过这件事本身要留痕。删了行,「这把钥匙存在过」
+ -- 就查不到了,而那正是事后追查要问的第一件事
+ revoked_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- 校验是热路径:**每次工具调用都要查一遍**,不是握手时查一次。
+-- 那是 0014_data_source_grants 的教训——列表过滤不是守卫,MCP 的对应形态是
+-- 「信任一整条连接的生命周期」,而 revoked_at 在中途被写上时必须立刻生效
+CREATE UNIQUE INDEX personal_tokens_hash_idx ON personal_tokens (token_hash);
+-- 「我发过哪几把」:账户页按人列,最近发的在前
+CREATE INDEX personal_tokens_user_idx ON personal_tokens (user_id, created_at DESC);
diff --git a/migrations/0018_a_fact_awaiting_a_nod.sql b/migrations/0018_a_fact_awaiting_a_nod.sql
new file mode 100644
index 00000000..823cddac
--- /dev/null
+++ b/migrations/0018_a_fact_awaiting_a_nod.sql
@@ -0,0 +1,70 @@
+-- 等人点头的事实(见 docs/decisions/0015)。
+--
+-- 起因是一次实测:对话里说「记住 Acme 把总部搬到了深圳」,助手回「已记录」,
+-- 而图里落下的是一条 **空谓词、0.9 置信** 的边——本体里没有「搬迁到」这类关系,
+-- 抽取落不上就留空(按 0010 这是对的)。**说的和进去的不是一回事,人无从发现。**
+--
+-- **自己一张表,不进 `facts`。**
+--
+-- 第一版是给 `facts` 加一列 `nod`。那正是 0013 记下的那个错的形状:
+--
+-- > 试过塞进 `facts` 加一位 `derived_by_rule` 标记,那一版的问题是**失败方向反了**:
+-- > 仓库里有四十多处读 `facts` 的查询,其中只有一处认识那个标记……
+-- > 分开之后忘了 UNION 的后果是**看不见**派生,而不是**混进去**。
+--
+-- 今天有 27 处查询按 `invalidated_at IS NULL` 捞活事实,分布在 6 个文件。
+-- 逐个补过滤,漏一处就有一条没人点头的事实混进图里——而这张表存在的全部理由
+-- 就是防这件事。分开之后,忘了读它的后果是「待确认队列看不见」,不是「未确认
+-- 的进了图」。
+--
+-- **只拦交互式的单条写入,不拦批量摄入。** 灌 500 篇文档抽出一万条事实,
+-- 让人逐条确认是不可能的;那条路仍旧乐观写入 + 事后审阅。而 `remember`
+-- 一次一句、人就在对话里,确认成本最低的那一刻恰好就在眼前。
+CREATE TABLE pending_facts (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ subject_id UUID NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
+ -- 可空,与 `facts.predicate_id` 一致:本体里没有对应关系时留空(0010)。
+ -- **而人要看见的正是这个空** —— 那条实测里空谓词就是该被拒的理由
+ predicate_id UUID REFERENCES relation_types(id) ON DELETE SET NULL,
+ object_id UUID REFERENCES entities(id) ON DELETE CASCADE,
+ object_value JSONB,
+ -- 模型原话里的说法。谓词落空时,人靠它判断「本体该不该长出这条关系」
+ proposed_predicate TEXT,
+
+ valid_from TIMESTAMPTZ,
+ valid_from_precision TEXT,
+ valid_to TIMESTAMPTZ,
+ valid_to_precision TEXT,
+ confidence REAL NOT NULL DEFAULT 0.5,
+
+ -- 出自哪一句记忆。**确认界面要把原句和三元组并排显示**——
+ -- 只列三元组等于要人凭空判断它对不对
+ chunk_id UUID NOT NULL REFERENCES chunks(id) ON DELETE CASCADE,
+ -- 谁的话。`remember` 今天不记这个,一并补上(0015 点名的缺口)
+ proposed_by UUID REFERENCES users(id),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- 待确认队列按库捞,还要数个数
+CREATE INDEX pending_facts_kb_idx ON pending_facts (kb_id, created_at DESC);
+-- 一句记忆抽出的若干条要一起显示
+CREATE INDEX pending_facts_chunk_idx ON pending_facts (chunk_id);
+
+-- 拒绝过的不该被下一轮重抽刷回来。
+--
+-- `concept_mappings` 那边靠 `status = 'rejected'` 挡住重复提议;这里同理,
+-- 但**拒绝的记录不能留在 pending_facts 里**——那张表的语义是「等着人看」,
+-- 混进已经看过的会让计数说谎。所以另开一张,只记「这个三元组在这个库里
+-- 被拒过」。
+CREATE TABLE rejected_facts (
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ subject_id UUID NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
+ -- 谓词可空,所以进不了主键;用 COALESCE 过的表达式索引来查重
+ predicate_id UUID REFERENCES relation_types(id) ON DELETE SET NULL,
+ object_id UUID REFERENCES entities(id) ON DELETE CASCADE,
+ rejected_by UUID REFERENCES users(id),
+ rejected_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX rejected_facts_lookup_idx
+ ON rejected_facts (kb_id, subject_id, object_id);