| 1 | use axum::extract::{Path, Query, State}; |
| 2 | use axum::Json; |
| 3 | use serde::Deserialize; |
| 4 | use serde_json::json; |
| 5 | use utopia_core::models::Role; |
| 6 | use utopia_core::AppError; |
| 7 | use uuid::Uuid; |
| 8 | |
| 9 | use crate::auth::AuthUser; |
| 10 | use crate::error::ApiResult; |
| 11 | use crate::state::AppState; |
| 12 | |
| 13 | pub(super) async fn require_kb( |
| 14 | state: &AppState, |
| 15 | user: &utopia_core::models::User, |
| 16 | kb_id: Uuid, |
| 17 | min: Role, |
| 18 | ) -> Result<utopia_core::models::KnowledgeBase, AppError> { |
| 19 | utopia_store::access::require_kb(&state.pool, user, kb_id, min).await |
| 20 | } |
| 21 | |
| 22 | /// `at`:可选 as-of 日期(YYYY-MM-DD 或 RFC3339)——服务端时间旅行。 |
| 23 | fn parse_at(raw: Option<&str>) -> Result<Option<chrono::DateTime<chrono::Utc>>, AppError> { |
| 24 | let Some(s) = raw.map(str::trim).filter(|s| !s.is_empty()) else { |
| 25 | return Ok(None); |
| 26 | }; |
| 27 | if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") { |
| 28 | return Ok(Some(d.and_hms_opt(0, 0, 0).unwrap().and_utc())); |
| 29 | } |
| 30 | chrono::DateTime::parse_from_rfc3339(s) |
| 31 | .map(|t| Some(t.with_timezone(&chrono::Utc))) |
| 32 | .map_err(|_| AppError::Validation("Invalid `at` (expected YYYY-MM-DD or RFC3339)".into())) |
| 33 | } |
| 34 | |
| 35 | /// 总览一次画多少个节点的**默认值**。上限本身是合理的——画一万个点没人看得懂; |
| 36 | /// 骗人的是把它当成规模显示,所以接口同时回总数 |
| 37 | const GRAPH_NODE_CAP: i64 = 150; |
| 38 | /// 调得再高也得有个天花板。**这个数不是拍的**:节点按度数降序取,越往后越是 |
| 39 | /// 边缘节点,而力导布局是 O(n²) 量级的——超过这个数,先垮的是「拖得动」 |
| 40 | /// 而不是「看得清」。要真看上万个点,那是另一种视图,不是把这个调大 |
| 41 | const GRAPH_NODE_CAP_MAX: i64 = 1000; |
| 42 | |
| 43 | #[derive(Deserialize)] |
| 44 | pub struct OverviewQuery { |
| 45 | #[serde(default)] |
| 46 | pub at: Option<String>, |
| 47 | /// 画多少个。不给就用默认值;给了也钳在 [10, GRAPH_NODE_CAP_MAX]—— |
| 48 | /// 界面上的按钮只给几档,但接口是公开的,别让一个 `limit=999999` 把库拖垮 |
| 49 | #[serde(default)] |
| 50 | pub limit: Option<i64>, |
| 51 | } |
| 52 | |
| 53 | pub async fn overview( |
| 54 | State(state): State<AppState>, |
| 55 | AuthUser(user): AuthUser, |
| 56 | Path(kb_id): Path<Uuid>, |
| 57 | Query(q): Query<OverviewQuery>, |
| 58 | ) -> ApiResult<Json<serde_json::Value>> { |
| 59 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 60 | let at = parse_at(q.at.as_deref())?; |
| 61 | // 画多少个是渲染的事,库里有多少是知识库的事——两个数都回,界面才说得出 |
| 62 | // 「画了 150 个,共 325 个」而不是把上限说成规模 |
| 63 | let limit = q |
| 64 | .limit |
| 65 | .unwrap_or(GRAPH_NODE_CAP) |
| 66 | .clamp(10, GRAPH_NODE_CAP_MAX); |
| 67 | let (nodes, edges, total_nodes, total_edges) = |
| 68 | utopia_store::graph::overview(&state.pool, kb_id, limit, at).await?; |
| 69 | Ok(Json(json!({ |
| 70 | "nodes": nodes, "edges": edges, |
| 71 | "total_nodes": total_nodes, "total_edges": total_edges, |
| 72 | }))) |
| 73 | } |
| 74 | |
| 75 | #[derive(Deserialize)] |
| 76 | pub struct NeighborhoodQuery { |
| 77 | pub entity: Uuid, |
| 78 | #[serde(default)] |
| 79 | pub hops: Option<u8>, |
| 80 | #[serde(default)] |
| 81 | pub at: Option<String>, |
| 82 | } |
| 83 | |
| 84 | pub async fn neighborhood( |
| 85 | State(state): State<AppState>, |
| 86 | AuthUser(user): AuthUser, |
| 87 | Path(kb_id): Path<Uuid>, |
| 88 | Query(q): Query<NeighborhoodQuery>, |
| 89 | ) -> ApiResult<Json<serde_json::Value>> { |
| 90 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 91 | let at = parse_at(q.at.as_deref())?; |
| 92 | let (nodes, edges) = |
| 93 | utopia_store::graph::neighborhood(&state.pool, kb_id, q.entity, q.hops.unwrap_or(2), at) |
| 94 | .await?; |
| 95 | Ok(Json(json!({ "nodes": nodes, "edges": edges }))) |
| 96 | } |
| 97 | |
| 98 | #[derive(Deserialize)] |
| 99 | pub struct EntitySearchQuery { |
| 100 | pub q: String, |
| 101 | #[serde(default)] |
| 102 | pub limit: Option<i64>, |
| 103 | #[serde(default)] |
| 104 | pub offset: Option<i64>, |
| 105 | } |
| 106 | |
| 107 | pub async fn search_entities( |
| 108 | State(state): State<AppState>, |
| 109 | AuthUser(user): AuthUser, |
| 110 | Path(kb_id): Path<Uuid>, |
| 111 | Query(query): Query<EntitySearchQuery>, |
| 112 | ) -> ApiResult<Json<serde_json::Value>> { |
| 113 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 114 | if query.q.trim().is_empty() { |
| 115 | return Ok(Json(json!({ "entities": [], "total": 0 }))); |
| 116 | } |
| 117 | // 一并回总数:「宁分勿合」本来就会造出一堆同名,固定十条时想找的那个 |
| 118 | // 可能根本不在这十条里,而界面上看不出来 |
| 119 | let (entities, total) = utopia_store::graph::search_entities( |
| 120 | &state.pool, |
| 121 | kb_id, |
| 122 | &query.q, |
| 123 | query.limit.unwrap_or(10).clamp(1, 100), |
| 124 | query.offset.unwrap_or(0).max(0), |
| 125 | ) |
| 126 | .await?; |
| 127 | Ok(Json(json!({ "entities": entities, "total": total }))) |
| 128 | } |
| 129 | |
| 130 | pub async fn entity_detail( |
| 131 | State(state): State<AppState>, |
| 132 | AuthUser(user): AuthUser, |
| 133 | Path((kb_id, entity_id)): Path<(Uuid, Uuid)>, |
| 134 | ) -> ApiResult<Json<serde_json::Value>> { |
| 135 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 136 | let (entity, facts) = utopia_store::graph::entity_detail(&state.pool, kb_id, entity_id).await?; |
| 137 | // 推出来的那些**单独回一个键**,不掺进 `facts`。前端据此给它们自己的一档: |
| 138 | // 一条派生边跟一条断言边混在同一个列表里,用户看不出「这条是文档里写的」 |
| 139 | // 和「这条是引擎推的」的区别,而那正是推理会污染知识的样子 |
| 140 | let derived = |
| 141 | utopia_store::reasoning::derived_for_entity(&state.pool, kb_id, entity_id).await?; |
| 142 | // 同名的那些**打开面板时就给**,不是等改名之后才回。 |
| 143 | // |
| 144 | // 从前它只随 `update_entity` 的响应回来,于是「把同名的合并进来」这个动作 |
| 145 | // 只有先改一次名才够得着——而两个张伟并存是「宁分勿合」的正当产物,不是 |
| 146 | // 改名改出来的。合并入口该长在能看见同名的地方。 |
| 147 | let same_name = utopia_store::graph::same_name_peers(&state.pool, kb_id, entity_id).await?; |
| 148 | // 没落地的派生(0017 §3)也单独一个键:它们连 `derived_facts` 都不在 |
| 149 | let blocked = |
| 150 | utopia_store::reasoning::blocked_for_entity(&state.pool, kb_id, entity_id).await?; |
| 151 | Ok(Json(json!({ |
| 152 | "entity": entity, "facts": facts, |
| 153 | "derived": derived, "blocked": blocked, "same_name": same_name, |
| 154 | }))) |
| 155 | } |
| 156 | |
| 157 | #[derive(Deserialize)] |
| 158 | pub struct EntityPatch { |
| 159 | #[serde(default)] |
| 160 | pub type_id: Option<Uuid>, |
| 161 | #[serde(default)] |
| 162 | pub canonical_name: Option<String>, |
| 163 | } |
| 164 | |
| 165 | /// 人工修正实体的类型或名字。抽取给的是初判,此前判错只能整库重抽。 |
| 166 | /// |
| 167 | /// 改名撞上同名实体不拦(两个张伟是"宁分勿合"的正当产物),改完把同名的报回去, |
| 168 | /// 由界面提示是否合并——判定它们是否真是同一个,是人的事。 |
| 169 | pub async fn update_entity( |
| 170 | State(state): State<AppState>, |
| 171 | AuthUser(user): AuthUser, |
| 172 | Path((kb_id, entity_id)): Path<(Uuid, Uuid)>, |
| 173 | Json(req): Json<EntityPatch>, |
| 174 | ) -> ApiResult<Json<serde_json::Value>> { |
| 175 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 176 | if req.type_id.is_none() && req.canonical_name.is_none() { |
| 177 | return Err(AppError::invalid("nothing_to_update", "Nothing to update").into()); |
| 178 | } |
| 179 | let (before, after) = utopia_store::graph::update_entity( |
| 180 | &state.pool, |
| 181 | kb_id, |
| 182 | entity_id, |
| 183 | req.type_id, |
| 184 | req.canonical_name.as_deref(), |
| 185 | ) |
| 186 | .await?; |
| 187 | |
| 188 | // 台账快照自包含:类型以后被删掉,这条记录仍然读得懂。 |
| 189 | // P4 要按 from/to 聚合"一个月里 37 个实体从 Product 挪到 Concept",所以分开记两个动作。 |
| 190 | if before.type_key != after.type_key { |
| 191 | let _ = utopia_store::audit::record( |
| 192 | &state.pool, |
| 193 | Some(kb_id), |
| 194 | user.id, |
| 195 | "entity.retyped", |
| 196 | "entity", |
| 197 | Some(entity_id), |
| 198 | json!({ |
| 199 | "name": after.name, |
| 200 | "from": { "key": before.type_key, "label": before.type_label }, |
| 201 | "to": { "key": after.type_key, "label": after.type_label }, |
| 202 | }), |
| 203 | ) |
| 204 | .await; |
| 205 | } |
| 206 | if before.name != after.name { |
| 207 | let _ = utopia_store::audit::record( |
| 208 | &state.pool, |
| 209 | Some(kb_id), |
| 210 | user.id, |
| 211 | "entity.renamed", |
| 212 | "entity", |
| 213 | Some(entity_id), |
| 214 | json!({ "from": before.name, "to": after.name, "type": after.type_label }), |
| 215 | ) |
| 216 | .await; |
| 217 | } |
| 218 | |
| 219 | let peers = utopia_store::graph::same_name_peers(&state.pool, kb_id, entity_id).await?; |
| 220 | state.emit_review(kb_id); |
| 221 | Ok(Json(json!({ "entity": after, "same_name": peers }))) |
| 222 | } |
| 223 | |
| 224 | pub async fn fact_evidence( |
| 225 | State(state): State<AppState>, |
| 226 | AuthUser(user): AuthUser, |
| 227 | Path((kb_id, fact_id)): Path<(Uuid, Uuid)>, |
| 228 | ) -> ApiResult<Json<serde_json::Value>> { |
| 229 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 230 | let evidence = utopia_store::graph::fact_evidence(&state.pool, fact_id).await?; |
| 231 | Ok(Json(json!({ "evidence": evidence }))) |
| 232 | } |
| 233 | |
| 234 | /// 一条派生事实的证明(0002 R2):前提按推导顺序,每条带证据,一路到原句。 |
| 235 | /// 派生已失效或不存在时 `proof` 为 null——不是错误,界面据此退回文本前提 |
| 236 | pub async fn derived_proof( |
| 237 | State(state): State<AppState>, |
| 238 | AuthUser(user): AuthUser, |
| 239 | Path((kb_id, derived_id)): Path<(Uuid, Uuid)>, |
| 240 | ) -> ApiResult<Json<serde_json::Value>> { |
| 241 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 242 | let proof = utopia_store::reasoning::proof(&state.pool, kb_id, derived_id).await?; |
| 243 | Ok(Json(json!({ "proof": proof }))) |
| 244 | } |
| 245 | |
| 246 | /// 没落地的派生的证明链(0017 §3):前提在那条 `derived_contradiction` 违规的 |
| 247 | /// `path` 里,展开方式与落了地的一样。违规不存在时 `steps` 为 null |
| 248 | pub async fn blocked_proof( |
| 249 | State(state): State<AppState>, |
| 250 | AuthUser(user): AuthUser, |
| 251 | Path((kb_id, violation_id)): Path<(Uuid, Uuid)>, |
| 252 | ) -> ApiResult<Json<serde_json::Value>> { |
| 253 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 254 | let steps = utopia_store::reasoning::blocked_proof(&state.pool, kb_id, violation_id).await?; |
| 255 | Ok(Json(json!({ "steps": steps }))) |
| 256 | } |
| 257 | |
| 258 | /// 手动触发抽取(failed 重试 / 补配模型后补抽)。 |
| 259 | pub async fn extract( |
| 260 | State(state): State<AppState>, |
| 261 | AuthUser(user): AuthUser, |
| 262 | Path(document_id): Path<Uuid>, |
| 263 | ) -> ApiResult<Json<serde_json::Value>> { |
| 264 | let doc = utopia_store::documents::get(&state.pool, document_id).await?; |
| 265 | require_kb(&state, &user, doc.kb_id, Role::Editor).await?; |
| 266 | // 手动触发 = 强制全量:清增量标记、解雇在跑的任务、置 queued、建任务,一个事务办完 |
| 267 | let job_id = utopia_store::documents::queue_extraction_one(&state.pool, document_id).await?; |
| 268 | state.emit_document(doc.kb_id, document_id); |
| 269 | Ok(Json(json!({ "job_id": job_id }))) |
| 270 | } |
| 271 | |
| 272 | /// 图谱重建(清算语义,KB admin):清空整个图层后全量重抽。 |
| 273 | /// 与来源级重抽的分工——重抽保留既有决策,重建放弃它们,换取 |
| 274 | /// "当前语料 × 当前本体"的确定性重演(早期脏抽取、本体大改后的收场手段)。 |
| 275 | /// 决策台账与裁决缓存刻意保留(见 store::graph::purge_graph)。 |
| 276 | pub async fn rebuild( |
| 277 | State(state): State<AppState>, |
| 278 | AuthUser(user): AuthUser, |
| 279 | Path(kb_id): Path<Uuid>, |
| 280 | ) -> ApiResult<Json<serde_json::Value>> { |
| 281 | require_kb(&state, &user, kb_id, Role::Admin).await?; |
| 282 | let (entities, facts) = utopia_store::graph::purge_graph(&state.pool, kb_id).await?; |
| 283 | // 任务由 queue_extraction 与状态同事务建好,这里只负责推送 |
| 284 | let ids = utopia_store::documents::queue_extraction(&state.pool, kb_id, None).await?; |
| 285 | for id in &ids { |
| 286 | state.emit_document(kb_id, *id); |
| 287 | } |
| 288 | state.emit_review(kb_id); |
| 289 | let _ = utopia_store::audit::record( |
| 290 | &state.pool, |
| 291 | Some(kb_id), |
| 292 | user.id, |
| 293 | "graph.rebuild", |
| 294 | "kb", |
| 295 | Some(kb_id), |
| 296 | json!({ "entities_removed": entities, "facts_removed": facts, "documents": ids.len() }), |
| 297 | ) |
| 298 | .await; |
| 299 | Ok(Json(json!({ |
| 300 | "entities_removed": entities, "facts_removed": facts, "queued": ids.len() |
| 301 | }))) |
| 302 | } |
| 303 | |
| 304 | #[derive(Deserialize)] |
| 305 | pub struct HistoryQuery { |
| 306 | #[serde(default)] |
| 307 | pub page: i64, |
| 308 | #[serde(default = "default_history_per")] |
| 309 | pub per: i64, |
| 310 | } |
| 311 | |
| 312 | fn default_history_per() -> i64 { |
| 313 | 30 |
| 314 | } |
| 315 | |
| 316 | /// 实体的认知变更历史(记录时间轴):我们何时这么认为、又何时改了主意。 |
| 317 | /// 与 entity_detail(有效时间轴,只看现行)互补。 |
| 318 | pub async fn entity_history( |
| 319 | State(state): State<AppState>, |
| 320 | AuthUser(user): AuthUser, |
| 321 | Path((kb_id, entity_id)): Path<(Uuid, Uuid)>, |
| 322 | Query(q): Query<HistoryQuery>, |
| 323 | ) -> ApiResult<Json<serde_json::Value>> { |
| 324 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 325 | let per = q.per.clamp(1, 200); |
| 326 | let page = q.page.max(0); |
| 327 | let (events, total) = |
| 328 | utopia_store::graph::entity_history(&state.pool, kb_id, entity_id, per, page * per).await?; |
| 329 | Ok(Json(json!({ "events": events, "total": total }))) |
| 330 | } |