| 1 | //! 审核队列 API:消解疑似重复对 + 低置信事实 + 合并日志/回滚。 |
| 2 | |
| 3 | use axum::extract::{Path, Query, State}; |
| 4 | use axum::Json; |
| 5 | use serde::Deserialize; |
| 6 | use serde_json::json; |
| 7 | use utopia_core::models::Role; |
| 8 | use uuid::Uuid; |
| 9 | |
| 10 | use super::graph_routes::require_kb; |
| 11 | use crate::auth::AuthUser; |
| 12 | use crate::error::ApiResult; |
| 13 | use crate::state::AppState; |
| 14 | |
| 15 | /// 一页多少条。**服务端的默认,不是上限**——前端可以要更少,多则被 clamp 挡住 |
| 16 | const REVIEW_PAGE: i64 = 10; |
| 17 | |
| 18 | /// 冲突双方的三元组快照:(旧主语, 旧宾语, 新主语, 新宾语, 谓词标签)。 |
| 19 | type ConflictSnapshot = (String, Option<String>, String, Option<String>, String); |
| 20 | |
| 21 | /// 事实快照(决策台账用):reject 后事实从图里消失,台账必须自包含展示文本。 |
| 22 | /// 一律在动作执行前取。 |
| 23 | async fn fact_snapshot(state: &AppState, kb_id: Uuid, fact_id: Uuid) -> Option<serde_json::Value> { |
| 24 | // 宾语可能是实体或字面值;结构化字面值优先取 summary(与队列卡片同一显示口径) |
| 25 | let row: Option<(String, Option<String>, Option<String>, f32)> = sqlx::query_as( |
| 26 | "SELECT s.canonical_name, COALESCE(r.label, fact_surface_predicate(f.id)), |
| 27 | COALESCE(o.canonical_name, f.object_value ->> 'summary', |
| 28 | f.object_value #>> '{}'), f.confidence |
| 29 | FROM facts f |
| 30 | JOIN entities s ON s.id = f.subject_id |
| 31 | LEFT JOIN relation_types r ON r.id = f.predicate_id |
| 32 | LEFT JOIN entities o ON o.id = f.object_id |
| 33 | WHERE f.id = $1 AND f.kb_id = $2", |
| 34 | ) |
| 35 | .bind(fact_id) |
| 36 | .bind(kb_id) |
| 37 | .fetch_optional(&state.pool) |
| 38 | .await |
| 39 | .ok() |
| 40 | .flatten(); |
| 41 | row.map(|(s, p, o, c)| json!({ "subject": s, "predicate": p, "object": o, "confidence": c })) |
| 42 | } |
| 43 | |
| 44 | #[derive(Deserialize)] |
| 45 | pub struct ReviewQuery { |
| 46 | /// 要看哪一档。缺省 duplicates |
| 47 | #[serde(default)] |
| 48 | pub queue: Option<String>, |
| 49 | #[serde(default)] |
| 50 | pub limit: Option<i64>, |
| 51 | #[serde(default)] |
| 52 | pub offset: Option<i64>, |
| 53 | } |
| 54 | |
| 55 | /// 审核队列:**计数与内容分开取**。 |
| 56 | /// |
| 57 | /// 从前一次把八个队列全端回来,每个固定 100 条,前端再客户端分页——于是左栏 |
| 58 | /// 的徽标是截断后的数字(库里 164 条低置信事实,界面写 100),而第十一页之后 |
| 59 | /// 的东西界面上不存在。 |
| 60 | /// |
| 61 | /// 现在:计数每次都回(八个 COUNT 一条查询,走的是与列表同一套 WHERE), |
| 62 | /// 内容只回当前那一档的一页。切换分档或翻页各发一次请求,代价是多几次往返, |
| 63 | /// 换来的是**数字不再骗人**,而且一个有十万条待办的库也翻得到底。 |
| 64 | pub async fn list( |
| 65 | State(state): State<AppState>, |
| 66 | AuthUser(user): AuthUser, |
| 67 | Path(kb_id): Path<Uuid>, |
| 68 | Query(q): Query<ReviewQuery>, |
| 69 | ) -> ApiResult<Json<serde_json::Value>> { |
| 70 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 71 | let counts = utopia_store::review::counts(&state.pool, kb_id).await?; |
| 72 | let queue = q.queue.as_deref().unwrap_or("duplicates"); |
| 73 | // 上限挡住「limit=1000000 把库拖垮」,同时留出足够一页的余量 |
| 74 | let limit = q.limit.unwrap_or(REVIEW_PAGE).clamp(1, 200); |
| 75 | let offset = q.offset.unwrap_or(0).max(0); |
| 76 | |
| 77 | let items = match queue { |
| 78 | // 记忆抽出、等人点头的事实(0015)。排第一:它是人自己说的话 |
| 79 | "pending" => json!(utopia_store::pending::list(&state.pool, kb_id, limit, offset).await?), |
| 80 | "duplicates" => { |
| 81 | json!(utopia_store::resolution::list_reviews(&state.pool, kb_id, limit, offset).await?) |
| 82 | } |
| 83 | "conflicts" => { |
| 84 | json!(utopia_store::temporal::list_conflicts(&state.pool, kb_id, limit, offset).await?) |
| 85 | } |
| 86 | "unconfirmed" => { |
| 87 | json!(utopia_store::graph::stale_facts(&state.pool, kb_id, limit, offset).await?) |
| 88 | } |
| 89 | "lowconf" => json!( |
| 90 | utopia_store::graph::low_confidence_facts( |
| 91 | &state.pool, |
| 92 | kb_id, |
| 93 | utopia_store::review::LOW_CONFIDENCE_BELOW, |
| 94 | limit, |
| 95 | offset, |
| 96 | ) |
| 97 | .await? |
| 98 | ), |
| 99 | "mappings" => { |
| 100 | json!(utopia_store::mappings::proposed(&state.pool, kb_id, limit, offset).await?) |
| 101 | } |
| 102 | "violations" => { |
| 103 | json!( |
| 104 | utopia_store::reasoning::open_violations(&state.pool, kb_id, limit, offset).await? |
| 105 | ) |
| 106 | } |
| 107 | "defects" => { |
| 108 | json!(utopia_store::reasoning::open_defects(&state.pool, kb_id, limit, offset).await?) |
| 109 | } |
| 110 | "merges" => { |
| 111 | json!(utopia_store::resolution::list_merges(&state.pool, kb_id, limit, offset).await?) |
| 112 | } |
| 113 | // 认不出的档名当成契约错误报出来,而不是悄悄回空——悄悄回空会让前端 |
| 114 | // 拼错一个字母之后看到「这一档清空了」 |
| 115 | other => { |
| 116 | return Err(utopia_core::AppError::invalid( |
| 117 | "unknown_queue", |
| 118 | format!("no review queue named {other}"), |
| 119 | ) |
| 120 | .into()) |
| 121 | } |
| 122 | }; |
| 123 | |
| 124 | Ok(Json(json!({ |
| 125 | "counts": counts, |
| 126 | "queue": queue, |
| 127 | "items": items, |
| 128 | }))) |
| 129 | } |
| 130 | |
| 131 | #[derive(Deserialize)] |
| 132 | pub struct CloseFactBody { |
| 133 | pub valid_to: chrono::DateTime<chrono::Utc>, |
| 134 | } |
| 135 | |
| 136 | /// 人工闭合一条事实的有效区间("这事在某时结束了")——走作废+改写, |
| 137 | /// 与自动闭合同一机制,账本可回放。 |
| 138 | pub async fn close_fact( |
| 139 | State(state): State<AppState>, |
| 140 | AuthUser(user): AuthUser, |
| 141 | Path((kb_id, fact_id)): Path<(Uuid, Uuid)>, |
| 142 | Json(body): Json<CloseFactBody>, |
| 143 | ) -> ApiResult<Json<serde_json::Value>> { |
| 144 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 145 | // 归属与状态校验:本 KB 的、未作废、开放区间的事实才可闭合 |
| 146 | let ok: Option<(Uuid,)> = sqlx::query_as( |
| 147 | "SELECT id FROM facts |
| 148 | WHERE id = $1 AND kb_id = $2 AND invalidated_at IS NULL AND valid_to IS NULL", |
| 149 | ) |
| 150 | .bind(fact_id) |
| 151 | .bind(kb_id) |
| 152 | .fetch_optional(&state.pool) |
| 153 | .await |
| 154 | .map_err(utopia_core::AppError::Db)?; |
| 155 | if ok.is_none() { |
| 156 | return Err(utopia_core::AppError::NotFound.into()); |
| 157 | } |
| 158 | let snap = fact_snapshot(&state, kb_id, fact_id).await; |
| 159 | // 人在界面上选的是一个日期,所以闭合点按日 |
| 160 | utopia_store::temporal::close_superseded(&state.pool, fact_id, body.valid_to, "day").await?; |
| 161 | if let Some(mut d) = snap { |
| 162 | d["valid_to"] = json!(body.valid_to.to_rfc3339()); |
| 163 | let _ = utopia_store::audit::record( |
| 164 | &state.pool, |
| 165 | Some(kb_id), |
| 166 | user.id, |
| 167 | "fact.close", |
| 168 | "fact", |
| 169 | Some(fact_id), |
| 170 | d, |
| 171 | ) |
| 172 | .await; |
| 173 | } |
| 174 | state.emit_review(kb_id); |
| 175 | Ok(Json(json!({ "ok": true }))) |
| 176 | } |
| 177 | |
| 178 | #[derive(Deserialize)] |
| 179 | pub struct ConflictBody { |
| 180 | /// close | keep | reject_new |
| 181 | pub action: String, |
| 182 | /// close 且新事实无起点时必填 |
| 183 | #[serde(default)] |
| 184 | pub close_at: Option<chrono::DateTime<chrono::Utc>>, |
| 185 | } |
| 186 | |
| 187 | /// 时态冲突裁决(S3:自动闭合拿不准的那些)。 |
| 188 | pub async fn resolve_conflict( |
| 189 | State(state): State<AppState>, |
| 190 | AuthUser(user): AuthUser, |
| 191 | Path((kb_id, conflict_id)): Path<(Uuid, Uuid)>, |
| 192 | Json(body): Json<ConflictBody>, |
| 193 | ) -> ApiResult<Json<serde_json::Value>> { |
| 194 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 195 | // 快照双方三元组:裁决会作废/改写事实,先抄后动 |
| 196 | let snap: Option<ConflictSnapshot> = sqlx::query_as( |
| 197 | "SELECT os.canonical_name, oo.canonical_name, ns.canonical_name, no_.canonical_name, |
| 198 | r.label |
| 199 | FROM fact_conflicts c |
| 200 | JOIN facts fo ON fo.id = c.old_fact_id |
| 201 | JOIN facts fn_ ON fn_.id = c.new_fact_id |
| 202 | JOIN entities os ON os.id = fo.subject_id |
| 203 | LEFT JOIN entities oo ON oo.id = fo.object_id |
| 204 | JOIN entities ns ON ns.id = fn_.subject_id |
| 205 | LEFT JOIN entities no_ ON no_.id = fn_.object_id |
| 206 | JOIN relation_types r ON r.id = fo.predicate_id |
| 207 | WHERE c.id = $1 AND c.kb_id = $2", |
| 208 | ) |
| 209 | .bind(conflict_id) |
| 210 | .bind(kb_id) |
| 211 | .fetch_optional(&state.pool) |
| 212 | .await |
| 213 | .ok() |
| 214 | .flatten(); |
| 215 | utopia_store::temporal::resolve_conflict( |
| 216 | &state.pool, |
| 217 | kb_id, |
| 218 | conflict_id, |
| 219 | &body.action, |
| 220 | body.close_at, |
| 221 | ) |
| 222 | .await?; |
| 223 | if let Some((os, oo, ns, no, pred)) = snap { |
| 224 | let action = match body.action.as_str() { |
| 225 | "close" => "conflict.close_old", |
| 226 | "keep" => "conflict.keep_both", |
| 227 | _ => "conflict.reject_new", |
| 228 | }; |
| 229 | let _ = utopia_store::audit::record( |
| 230 | &state.pool, |
| 231 | Some(kb_id), |
| 232 | user.id, |
| 233 | action, |
| 234 | "conflict", |
| 235 | Some(conflict_id), |
| 236 | json!({ |
| 237 | "predicate": pred, |
| 238 | "old_subject": os, "old_object": oo, |
| 239 | "new_subject": ns, "new_object": no, |
| 240 | "close_at": body.close_at.map(|t| t.to_rfc3339()), |
| 241 | }), |
| 242 | ) |
| 243 | .await; |
| 244 | } |
| 245 | state.emit_review(kb_id); |
| 246 | Ok(Json(json!({ "ok": true }))) |
| 247 | } |
| 248 | |
| 249 | #[derive(Deserialize)] |
| 250 | pub struct DecideBody { |
| 251 | /// merge | keep |
| 252 | pub action: String, |
| 253 | } |
| 254 | |
| 255 | pub async fn decide( |
| 256 | State(state): State<AppState>, |
| 257 | AuthUser(user): AuthUser, |
| 258 | Path((kb_id, review_id)): Path<(Uuid, Uuid)>, |
| 259 | Json(body): Json<DecideBody>, |
| 260 | ) -> ApiResult<Json<serde_json::Value>> { |
| 261 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 262 | let snap: Option<(String, String, f32)> = sqlx::query_as( |
| 263 | "SELECT a.canonical_name, b.canonical_name, rr.score |
| 264 | FROM resolution_reviews rr |
| 265 | JOIN entities a ON a.id = rr.left_id |
| 266 | JOIN entities b ON b.id = rr.right_id |
| 267 | WHERE rr.id = $1 AND rr.kb_id = $2", |
| 268 | ) |
| 269 | .bind(review_id) |
| 270 | .bind(kb_id) |
| 271 | .fetch_optional(&state.pool) |
| 272 | .await |
| 273 | .ok() |
| 274 | .flatten(); |
| 275 | utopia_store::resolution::decide_review(&state.pool, kb_id, review_id, &body.action, user.id) |
| 276 | .await?; |
| 277 | if let Some((l, r, score)) = snap { |
| 278 | let _ = utopia_store::audit::record( |
| 279 | &state.pool, |
| 280 | Some(kb_id), |
| 281 | user.id, |
| 282 | if body.action == "merge" { |
| 283 | "review.merge" |
| 284 | } else { |
| 285 | "review.keep" |
| 286 | }, |
| 287 | "review", |
| 288 | Some(review_id), |
| 289 | json!({ "left": l, "right": r, "score": score }), |
| 290 | ) |
| 291 | .await; |
| 292 | } |
| 293 | state.emit_review(kb_id); |
| 294 | Ok(Json(json!({ "ok": true }))) |
| 295 | } |
| 296 | |
| 297 | pub async fn confirm_fact( |
| 298 | State(state): State<AppState>, |
| 299 | AuthUser(user): AuthUser, |
| 300 | Path((kb_id, fact_id)): Path<(Uuid, Uuid)>, |
| 301 | ) -> ApiResult<Json<serde_json::Value>> { |
| 302 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 303 | let snap = fact_snapshot(&state, kb_id, fact_id).await; |
| 304 | utopia_store::graph::confirm_fact(&state.pool, kb_id, fact_id).await?; |
| 305 | if let Some(d) = snap { |
| 306 | let _ = utopia_store::audit::record( |
| 307 | &state.pool, |
| 308 | Some(kb_id), |
| 309 | user.id, |
| 310 | "fact.confirm", |
| 311 | "fact", |
| 312 | Some(fact_id), |
| 313 | d, |
| 314 | ) |
| 315 | .await; |
| 316 | } |
| 317 | state.emit_review(kb_id); |
| 318 | Ok(Json(json!({ "ok": true }))) |
| 319 | } |
| 320 | |
| 321 | pub async fn reject_fact( |
| 322 | State(state): State<AppState>, |
| 323 | AuthUser(user): AuthUser, |
| 324 | Path((kb_id, fact_id)): Path<(Uuid, Uuid)>, |
| 325 | ) -> ApiResult<Json<serde_json::Value>> { |
| 326 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 327 | let snap = fact_snapshot(&state, kb_id, fact_id).await; |
| 328 | utopia_store::graph::reject_fact(&state.pool, kb_id, fact_id).await?; |
| 329 | if let Some(d) = snap { |
| 330 | let _ = utopia_store::audit::record( |
| 331 | &state.pool, |
| 332 | Some(kb_id), |
| 333 | user.id, |
| 334 | "fact.reject", |
| 335 | "fact", |
| 336 | Some(fact_id), |
| 337 | d, |
| 338 | ) |
| 339 | .await; |
| 340 | } |
| 341 | state.emit_review(kb_id); |
| 342 | Ok(Json(json!({ "ok": true }))) |
| 343 | } |
| 344 | |
| 345 | pub async fn revert_merge( |
| 346 | State(state): State<AppState>, |
| 347 | AuthUser(user): AuthUser, |
| 348 | Path((kb_id, merge_id)): Path<(Uuid, Uuid)>, |
| 349 | ) -> ApiResult<Json<serde_json::Value>> { |
| 350 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 351 | let snap: Option<(String, String)> = sqlx::query_as( |
| 352 | "SELECT s.canonical_name, t.canonical_name |
| 353 | FROM entity_merges m |
| 354 | JOIN entities s ON s.id = m.source_id |
| 355 | JOIN entities t ON t.id = m.target_id |
| 356 | WHERE m.id = $1 AND m.kb_id = $2", |
| 357 | ) |
| 358 | .bind(merge_id) |
| 359 | .bind(kb_id) |
| 360 | .fetch_optional(&state.pool) |
| 361 | .await |
| 362 | .ok() |
| 363 | .flatten(); |
| 364 | utopia_store::resolution::revert_merge(&state.pool, kb_id, merge_id).await?; |
| 365 | if let Some((s, t)) = snap { |
| 366 | let _ = utopia_store::audit::record( |
| 367 | &state.pool, |
| 368 | Some(kb_id), |
| 369 | user.id, |
| 370 | "merge.revert", |
| 371 | "merge", |
| 372 | Some(merge_id), |
| 373 | json!({ "source": s, "target": t }), |
| 374 | ) |
| 375 | .await; |
| 376 | } |
| 377 | state.emit_review(kb_id); |
| 378 | Ok(Json(json!({ "ok": true }))) |
| 379 | } |
| 380 | |
| 381 | #[derive(Deserialize)] |
| 382 | pub struct ManualMergeBody { |
| 383 | pub source: Uuid, |
| 384 | pub target: Uuid, |
| 385 | } |
| 386 | |
| 387 | /// 手动合并(实体面板"Merge into…"入口)。 |
| 388 | pub async fn manual_merge( |
| 389 | State(state): State<AppState>, |
| 390 | AuthUser(user): AuthUser, |
| 391 | Path(kb_id): Path<Uuid>, |
| 392 | Json(body): Json<ManualMergeBody>, |
| 393 | ) -> ApiResult<Json<serde_json::Value>> { |
| 394 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 395 | let snap: Option<(String,)> = sqlx::query_as( |
| 396 | "SELECT s.canonical_name || ' → ' || t.canonical_name |
| 397 | FROM entities s, entities t WHERE s.id = $1 AND t.id = $2", |
| 398 | ) |
| 399 | .bind(body.source) |
| 400 | .bind(body.target) |
| 401 | .fetch_optional(&state.pool) |
| 402 | .await |
| 403 | .ok() |
| 404 | .flatten(); |
| 405 | let merge_id = utopia_store::resolution::merge_entities( |
| 406 | &state.pool, |
| 407 | kb_id, |
| 408 | body.source, |
| 409 | body.target, |
| 410 | Some(user.id), |
| 411 | "manual merge", |
| 412 | ) |
| 413 | .await?; |
| 414 | if let Some((pair,)) = snap { |
| 415 | let (s, t) = pair.split_once(" → ").unwrap_or((pair.as_str(), "")); |
| 416 | let _ = utopia_store::audit::record( |
| 417 | &state.pool, |
| 418 | Some(kb_id), |
| 419 | user.id, |
| 420 | "merge.manual", |
| 421 | "merge", |
| 422 | Some(merge_id), |
| 423 | json!({ "source": s, "target": t }), |
| 424 | ) |
| 425 | .await; |
| 426 | } |
| 427 | state.emit_review(kb_id); |
| 428 | Ok(Json(json!({ "merge_id": merge_id }))) |
| 429 | } |
| 430 | |
| 431 | #[derive(Deserialize)] |
| 432 | pub struct HistoryQuery { |
| 433 | #[serde(default)] |
| 434 | pub page: i64, |
| 435 | #[serde(default = "default_history_per")] |
| 436 | pub per: i64, |
| 437 | } |
| 438 | |
| 439 | fn default_history_per() -> i64 { |
| 440 | 20 |
| 441 | } |
| 442 | |
| 443 | /// 决策台账:review 域的审计事件,服务端分页。 |
| 444 | pub async fn history( |
| 445 | State(state): State<AppState>, |
| 446 | AuthUser(user): AuthUser, |
| 447 | Path(kb_id): Path<Uuid>, |
| 448 | Query(q): Query<HistoryQuery>, |
| 449 | ) -> ApiResult<Json<serde_json::Value>> { |
| 450 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 451 | let per = q.per.clamp(1, 100); |
| 452 | let page = q.page.max(0); |
| 453 | let (events, total) = |
| 454 | utopia_store::audit::review_history(&state.pool, kb_id, per, page * per).await?; |
| 455 | Ok(Json(json!({ "events": events, "total": total }))) |
| 456 | } |
| 457 | |
| 458 | #[derive(Deserialize)] |
| 459 | pub struct DecideMappingReq { |
| 460 | /// confirmed | rejected |
| 461 | pub status: String, |
| 462 | } |
| 463 | |
| 464 | /// 对一条语义层映射表态(0011)。 |
| 465 | /// |
| 466 | /// **改状态不删行**:确认发生过、拒绝也发生过。而拒绝留痕当下就有用—— |
| 467 | /// 下一轮探索会再次算出被拒绝过的那条,`propose` 的 `WHERE status = 'proposed'` |
| 468 | /// 据此不把它刷回待看。 |
| 469 | pub async fn decide_mapping( |
| 470 | State(state): State<AppState>, |
| 471 | AuthUser(user): AuthUser, |
| 472 | Path((kb_id, mapping_id)): Path<(Uuid, Uuid)>, |
| 473 | Json(req): Json<DecideMappingReq>, |
| 474 | ) -> ApiResult<Json<serde_json::Value>> { |
| 475 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 476 | if !matches!(req.status.as_str(), "confirmed" | "rejected") { |
| 477 | return Err(utopia_core::AppError::invalid( |
| 478 | "bad_status", |
| 479 | "status must be confirmed or rejected", |
| 480 | ) |
| 481 | .into()); |
| 482 | } |
| 483 | utopia_store::mappings::decide(&state.pool, kb_id, mapping_id, &req.status, user.id).await?; |
| 484 | let _ = utopia_store::audit::record( |
| 485 | &state.pool, |
| 486 | Some(kb_id), |
| 487 | user.id, |
| 488 | "mapping.decided", |
| 489 | "concept_mapping", |
| 490 | Some(mapping_id), |
| 491 | json!({ "status": req.status }), |
| 492 | ) |
| 493 | .await; |
| 494 | state.emit_review(kb_id); |
| 495 | Ok(Json(json!({ "ok": true }))) |
| 496 | } |
| 497 | |
| 498 | #[derive(Deserialize)] |
| 499 | pub struct DecideViolationReq { |
| 500 | /// fact_retracted | fact_closed | axiom_relaxed | accepted |
| 501 | pub resolution: String, |
| 502 | /// `fact_closed` 必填:旧断言在哪一天结束 |
| 503 | #[serde(default)] |
| 504 | pub close_at: Option<chrono::DateTime<chrono::Utc>>, |
| 505 | } |
| 506 | |
| 507 | /// 人裁决一处公理违规。 |
| 508 | /// |
| 509 | /// **三个出路而不是两个。** `axiom_relaxed` 是这一档独有的:矛盾可能出在定义 |
| 510 | /// 而不是数据——用户导的本体把某个属性声明成反对称,而他自己的语料里那关系 |
| 511 | /// 其实双向。这时该改的是本体,不是二十条事实。 |
| 512 | /// |
| 513 | /// 端点只记决定,不替人执行。撤事实走 `reject_fact`,改公理走本体页—— |
| 514 | /// 那两个动作各有自己的权限与台账,塞进这里会变成一个什么都能干的端点。 |
| 515 | pub async fn decide_violation( |
| 516 | State(state): State<AppState>, |
| 517 | AuthUser(user): AuthUser, |
| 518 | Path((kb_id, violation_id)): Path<(Uuid, Uuid)>, |
| 519 | Json(req): Json<DecideViolationReq>, |
| 520 | ) -> ApiResult<Json<serde_json::Value>> { |
| 521 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 522 | if !matches!( |
| 523 | req.resolution.as_str(), |
| 524 | "fact_retracted" | "fact_closed" | "axiom_relaxed" | "accepted" |
| 525 | ) { |
| 526 | return Err(utopia_core::AppError::invalid( |
| 527 | "bad_resolution", |
| 528 | "resolution 只能是 fact_retracted、fact_closed、axiom_relaxed 或 accepted", |
| 529 | ) |
| 530 | .into()); |
| 531 | } |
| 532 | let row: Option<(String, Uuid)> = sqlx::query_as( |
| 533 | "SELECT kind, left_fact FROM axiom_violations |
| 534 | WHERE id = $1 AND kb_id = $2 AND status = 'open'", |
| 535 | ) |
| 536 | .bind(violation_id) |
| 537 | .bind(kb_id) |
| 538 | .fetch_optional(&state.pool) |
| 539 | .await |
| 540 | .map_err(utopia_core::AppError::Db)?; |
| 541 | let Some((kind, left)) = row else { |
| 542 | return Err(utopia_core::AppError::NotFound.into()); |
| 543 | }; |
| 544 | // 派生撞断言那一类(0017)的修法就在卡片上,端点替人执行:撤旧断言、或给它一个 |
| 545 | // 结束日期。其它几类仍只记决定——那些卡片上两条都是断言,撤哪条端点判不了 |
| 546 | let repaired = kind == "derived_contradiction"; |
| 547 | match (repaired, req.resolution.as_str()) { |
| 548 | (true, "fact_retracted") => { |
| 549 | let snap = fact_snapshot(&state, kb_id, left).await; |
| 550 | utopia_store::graph::reject_fact(&state.pool, kb_id, left).await?; |
| 551 | if let Some(d) = snap { |
| 552 | let _ = utopia_store::audit::record( |
| 553 | &state.pool, |
| 554 | Some(kb_id), |
| 555 | user.id, |
| 556 | "fact.reject", |
| 557 | "fact", |
| 558 | Some(left), |
| 559 | d, |
| 560 | ) |
| 561 | .await; |
| 562 | } |
| 563 | } |
| 564 | (true, "fact_closed") => { |
| 565 | let Some(at) = req.close_at else { |
| 566 | return Err(utopia_core::AppError::invalid( |
| 567 | "close_at_required", |
| 568 | "fact_closed 要给出结束日期", |
| 569 | ) |
| 570 | .into()); |
| 571 | }; |
| 572 | let open: Option<(Uuid,)> = sqlx::query_as( |
| 573 | "SELECT id FROM facts |
| 574 | WHERE id = $1 AND invalidated_at IS NULL AND valid_to IS NULL", |
| 575 | ) |
| 576 | .bind(left) |
| 577 | .fetch_optional(&state.pool) |
| 578 | .await |
| 579 | .map_err(utopia_core::AppError::Db)?; |
| 580 | if open.is_none() { |
| 581 | return Err(utopia_core::AppError::invalid( |
| 582 | "not_open", |
| 583 | "这条断言已有结束日期,或已被撤", |
| 584 | ) |
| 585 | .into()); |
| 586 | } |
| 587 | let snap = fact_snapshot(&state, kb_id, left).await; |
| 588 | utopia_store::temporal::close_superseded(&state.pool, left, at, "day").await?; |
| 589 | if let Some(mut d) = snap { |
| 590 | d["valid_to"] = json!(at.to_rfc3339()); |
| 591 | let _ = utopia_store::audit::record( |
| 592 | &state.pool, |
| 593 | Some(kb_id), |
| 594 | user.id, |
| 595 | "fact.close", |
| 596 | "fact", |
| 597 | Some(left), |
| 598 | d, |
| 599 | ) |
| 600 | .await; |
| 601 | } |
| 602 | } |
| 603 | (false, "fact_closed") => { |
| 604 | return Err(utopia_core::AppError::invalid( |
| 605 | "bad_resolution", |
| 606 | "fact_closed 只用于 derived_contradiction", |
| 607 | ) |
| 608 | .into()); |
| 609 | } |
| 610 | _ => {} |
| 611 | } |
| 612 | utopia_store::reasoning::decide(&state.pool, kb_id, violation_id, &req.resolution, user.id) |
| 613 | .await?; |
| 614 | // 路清了就让派生落地,人不必再去点一次「推一遍」。撤与闭合把断言挪开了, |
| 615 | // 认可则在 materialize 里放行 |
| 616 | if repaired { |
| 617 | utopia_store::reasoning::materialize(&state.pool, kb_id).await?; |
| 618 | } |
| 619 | let _ = utopia_store::audit::record( |
| 620 | &state.pool, |
| 621 | Some(kb_id), |
| 622 | user.id, |
| 623 | "violation.decided", |
| 624 | "axiom_violation", |
| 625 | Some(violation_id), |
| 626 | json!({ "resolution": req.resolution }), |
| 627 | ) |
| 628 | .await; |
| 629 | state.emit_review(kb_id); |
| 630 | Ok(Json(json!({ "ok": true }))) |
| 631 | } |
| 632 | |
| 633 | /// 手动跑一遍一致性检查。 |
| 634 | /// |
| 635 | /// **同步跑而不是排任务**:这是纯计算,没有模型调用也没有网络——一个几万条 |
| 636 | /// 事实的库跑下来是毫秒级。排进任务队列只会让人点完按钮盯着一个"排队中", |
| 637 | /// 而队列真正要解决的是"这活儿要跑几分钟"。 |
| 638 | /// |
| 639 | /// `predicates_with_axioms` 一并回给前端:**零和零的含义不同**。没有公理时 |
| 640 | /// 结论是"没有判据",界面该说"先导一份带公理的本体",而不是"未发现矛盾"。 |
| 641 | pub async fn run_consistency_check( |
| 642 | State(state): State<AppState>, |
| 643 | AuthUser(user): AuthUser, |
| 644 | Path(kb_id): Path<Uuid>, |
| 645 | ) -> ApiResult<Json<serde_json::Value>> { |
| 646 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 647 | let report = utopia_store::reasoning::run(&state.pool, kb_id).await?; |
| 648 | // 本体自洽性一并算。两者判据同源(都是本体声明的公理),分两个按钮 |
| 649 | // 只会让人点两次 |
| 650 | let onto = utopia_store::reasoning::check_ontology(&state.pool, kb_id).await?; |
| 651 | let _ = utopia_store::audit::record( |
| 652 | &state.pool, |
| 653 | Some(kb_id), |
| 654 | user.id, |
| 655 | "consistency.checked", |
| 656 | "knowledge_base", |
| 657 | Some(kb_id), |
| 658 | json!({ |
| 659 | "edges": report.edges, |
| 660 | "predicates_with_axioms": report.predicates_with_axioms, |
| 661 | "found": report.found, |
| 662 | "inserted": report.inserted, |
| 663 | "cleared": report.cleared, |
| 664 | "defects_found": onto.found, |
| 665 | }), |
| 666 | ) |
| 667 | .await; |
| 668 | state.emit_review(kb_id); |
| 669 | Ok(Json(json!({ |
| 670 | "edges": report.edges, |
| 671 | "predicates_with_axioms": report.predicates_with_axioms, |
| 672 | "found": report.found, |
| 673 | "inserted": report.inserted, |
| 674 | "cleared": report.cleared, |
| 675 | // 本体自己那一档单独回。**不加进 found**:两个数不是一类东西, |
| 676 | // 加起来之后「3 处矛盾」既可能是三条事实抵触,也可能是本体自己写反了三处 |
| 677 | "classes": onto.classes, |
| 678 | "defects_found": onto.found, |
| 679 | "defects_new": onto.inserted, |
| 680 | }))) |
| 681 | } |
| 682 | |
| 683 | #[derive(Deserialize)] |
| 684 | pub struct DecideDefectReq { |
| 685 | /// fixed | accepted |
| 686 | pub resolution: String, |
| 687 | } |
| 688 | |
| 689 | /// 人对一处本体缺陷表态。 |
| 690 | /// |
| 691 | /// **两个出路而不是三个**:本体缺陷压根没看数据,所以没有「数据错了」这一条。 |
| 692 | pub async fn decide_defect( |
| 693 | State(state): State<AppState>, |
| 694 | AuthUser(user): AuthUser, |
| 695 | Path((kb_id, defect_id)): Path<(Uuid, Uuid)>, |
| 696 | Json(req): Json<DecideDefectReq>, |
| 697 | ) -> ApiResult<Json<serde_json::Value>> { |
| 698 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 699 | if !matches!(req.resolution.as_str(), "fixed" | "accepted") { |
| 700 | return Err(utopia_core::AppError::invalid( |
| 701 | "bad_resolution", |
| 702 | "resolution 只能是 fixed 或 accepted", |
| 703 | ) |
| 704 | .into()); |
| 705 | } |
| 706 | utopia_store::reasoning::decide_defect(&state.pool, kb_id, defect_id, &req.resolution, user.id) |
| 707 | .await?; |
| 708 | let _ = utopia_store::audit::record( |
| 709 | &state.pool, |
| 710 | Some(kb_id), |
| 711 | user.id, |
| 712 | "defect.decided", |
| 713 | "ontology_defect", |
| 714 | Some(defect_id), |
| 715 | json!({ "resolution": req.resolution }), |
| 716 | ) |
| 717 | .await; |
| 718 | state.emit_review(kb_id); |
| 719 | Ok(Json(json!({ "ok": true }))) |
| 720 | } |
| 721 | |
| 722 | /// 跑一遍推理(R1)。 |
| 723 | /// |
| 724 | /// **受 `materialize_inferences` 开关约束。** 默认关,因为这一步往图里加东西, |
| 725 | /// 而 0001 判据 2 说「本体是引导不是执法」——声明可能是错的,不该在用户没表态时 |
| 726 | /// 就按它改图。开关关着时不静默跳过:回一个明确的错,界面才说得出为什么没动。 |
| 727 | /// |
| 728 | /// 同步跑,与一致性检查同一个理由:纯计算,没有模型调用也没有网络。 |
| 729 | #[derive(Deserialize)] |
| 730 | pub struct PendingQuery { |
| 731 | pub chunk_id: Uuid, |
| 732 | } |
| 733 | |
| 734 | /// 一句记忆抽出的全部待确认项——对话里那张确认卡按这个取(0015)。 |
| 735 | /// Viewer 也能看:看得见提议、看不见按钮,与 Review 页同一口径 |
| 736 | pub async fn pending_for_chunk( |
| 737 | State(state): State<AppState>, |
| 738 | AuthUser(user): AuthUser, |
| 739 | Path(kb_id): Path<Uuid>, |
| 740 | Query(q): Query<PendingQuery>, |
| 741 | ) -> ApiResult<Json<serde_json::Value>> { |
| 742 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 743 | let items = utopia_store::pending::for_chunk(&state.pool, kb_id, q.chunk_id).await?; |
| 744 | Ok(Json(json!({ "items": items }))) |
| 745 | } |
| 746 | |
| 747 | #[derive(Deserialize)] |
| 748 | pub struct DecidePendingBody { |
| 749 | /// `confirm` 进账本;`reject` 记进 `rejected_facts`,下一轮重抽不再提 |
| 750 | pub action: String, |
| 751 | } |
| 752 | |
| 753 | /// 人对一条待确认事实点头或摇头。 |
| 754 | /// |
| 755 | /// 两个动作都进决策台账,快照自包含——行删了之后台账上还读得出当时确认的是什么。 |
| 756 | /// 确认走与抽取相同的那条路(事实 + 证据 + 时态对账),所以一句「Mira 交给 Devin 了」 |
| 757 | /// 点头之后,Mira 那条会像从文档里抽出来时一样被闭合 |
| 758 | pub async fn decide_pending( |
| 759 | State(state): State<AppState>, |
| 760 | AuthUser(user): AuthUser, |
| 761 | Path((kb_id, pending_id)): Path<(Uuid, Uuid)>, |
| 762 | Json(body): Json<DecidePendingBody>, |
| 763 | ) -> ApiResult<Json<serde_json::Value>> { |
| 764 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 765 | match body.action.as_str() { |
| 766 | "confirm" => { |
| 767 | let done = utopia_store::pending::confirm(&state.pool, kb_id, pending_id).await?; |
| 768 | let _ = utopia_store::audit::record( |
| 769 | &state.pool, |
| 770 | Some(kb_id), |
| 771 | user.id, |
| 772 | "fact.nod_confirmed", |
| 773 | "fact", |
| 774 | Some(done.fact_id), |
| 775 | done.snapshot, |
| 776 | ) |
| 777 | .await; |
| 778 | state.emit_pending(kb_id); |
| 779 | state.emit_review(kb_id); |
| 780 | state.emit_graph(kb_id); |
| 781 | Ok(Json(json!({ |
| 782 | "ok": true, |
| 783 | "fact_id": done.fact_id, |
| 784 | "created": done.created, |
| 785 | "conflicts": done.conflicts, |
| 786 | }))) |
| 787 | } |
| 788 | "reject" => { |
| 789 | let snap = utopia_store::pending::reject(&state.pool, kb_id, pending_id, Some(user.id)) |
| 790 | .await?; |
| 791 | let _ = utopia_store::audit::record( |
| 792 | &state.pool, |
| 793 | Some(kb_id), |
| 794 | user.id, |
| 795 | "fact.nod_rejected", |
| 796 | "pending_fact", |
| 797 | Some(pending_id), |
| 798 | snap, |
| 799 | ) |
| 800 | .await; |
| 801 | state.emit_pending(kb_id); |
| 802 | state.emit_review(kb_id); |
| 803 | Ok(Json(json!({ "ok": true }))) |
| 804 | } |
| 805 | other => Err(utopia_core::AppError::invalid( |
| 806 | "unknown_action", |
| 807 | format!("action must be confirm or reject, got {other}"), |
| 808 | ) |
| 809 | .into()), |
| 810 | } |
| 811 | } |
| 812 | |
| 813 | pub async fn run_inference( |
| 814 | State(state): State<AppState>, |
| 815 | AuthUser(user): AuthUser, |
| 816 | Path(kb_id): Path<Uuid>, |
| 817 | ) -> ApiResult<Json<serde_json::Value>> { |
| 818 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 819 | let on: bool = |
| 820 | sqlx::query_scalar("SELECT materialize_inferences FROM knowledge_bases WHERE id = $1") |
| 821 | .bind(kb_id) |
| 822 | .fetch_one(&state.pool) |
| 823 | .await |
| 824 | .map_err(utopia_core::AppError::Db)?; |
| 825 | if !on { |
| 826 | return Err(utopia_core::AppError::invalid( |
| 827 | "inference_off", |
| 828 | "materialized inference is off for this knowledge base", |
| 829 | ) |
| 830 | .into()); |
| 831 | } |
| 832 | let report = utopia_store::reasoning::materialize(&state.pool, kb_id).await?; |
| 833 | let _ = utopia_store::audit::record( |
| 834 | &state.pool, |
| 835 | Some(kb_id), |
| 836 | user.id, |
| 837 | "inference.materialized", |
| 838 | "knowledge_base", |
| 839 | Some(kb_id), |
| 840 | json!({ |
| 841 | "rules": report.rules, |
| 842 | "edges": report.edges, |
| 843 | "derived": report.derived, |
| 844 | "inserted": report.inserted, |
| 845 | "invalidated": report.invalidated, |
| 846 | "capped": report.capped, |
| 847 | }), |
| 848 | ) |
| 849 | .await; |
| 850 | state.emit_graph(kb_id); |
| 851 | Ok(Json(json!({ |
| 852 | "rules": report.rules, |
| 853 | "edges": report.edges, |
| 854 | "derived": report.derived, |
| 855 | "inserted": report.inserted, |
| 856 | "invalidated": report.invalidated, |
| 857 | "capped": report.capped, |
| 858 | }))) |
| 859 | } |