World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
The review page can say what the base needs as a whole (#381)
WaylandYang34311ede27fd
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rsindex a8447948..f3b60b64 100644--- a/crates/utopia-core/src/models.rs+++ b/crates/utopia-core/src/models.rs@@ -1194,6 +1194,88 @@ pub struct ReviewCounts {pub merges: i64,}+/// 审核台的总览(#377):等着办的、办过的、库的成色。+///+/// 左栏的七个数只说「开着多少条」;总览要回答的是一个审核者进来时的三个+/// 问题——**有多少在等、等了多久、队列在消还是在涨**。三段各自一组查询,+/// 拼在一起一次返回。+#[derive(Debug, Clone, Serialize)]+pub struct ReviewSummary {+ pub waiting: ReviewWaiting,+ pub decided: ReviewDecided,+ pub health: ReviewHealth,+}++/// 一档队列里等着的:多少条、最老的一条从什么时候开始等+#[derive(Debug, Clone, Serialize, Default)]+pub struct QueueWait {+ pub count: i64,+ pub oldest_at: Option<DateTime<Utc>>,+}++/// 七档队列,与 [`ReviewCounts`] 同一套口径(同一套 WHERE),多了「最老」+#[derive(Debug, Clone, Serialize, Default)]+pub struct ReviewWaiting {+ pub pending: QueueWait,+ pub duplicates: QueueWait,+ pub conflicts: QueueWait,+ pub unconfirmed: QueueWait,+ pub lowconf: QueueWait,+ pub violations: QueueWait,+ pub defects: QueueWait,+}++/// 办过的:近 7 天与近 30 天两个窗口,加近 14 天每天一根柱+#[derive(Debug, Clone, Serialize)]+pub struct ReviewDecided {+ pub last_7d: DecidedWindow,+ pub last_30d: DecidedWindow,+ /// 近 14 天,按天,一天一条,没有决定的那天也在(count 0)——画柱子要等距+ pub daily: Vec<DecidedDay>,+}++/// 一个时间窗口里的决定:总数、其中 AI 自裁的(台账上没有 actor 的那些)、+/// 按动作分、按人分+#[derive(Debug, Clone, Serialize, Default)]+pub struct DecidedWindow {+ pub total: i64,+ pub automatic: i64,+ pub by_action: Vec<ActionCount>,+ pub by_actor: Vec<ActorCount>,+}++#[derive(Debug, Clone, Serialize)]+pub struct ActionCount {+ /// 台账上的动作名(review.merge / fact.confirm / conflict.close_old …)+ pub action: String,+ pub count: i64,+}++#[derive(Debug, Clone, Serialize)]+pub struct ActorCount {+ /// None = 后台自裁(攒批裁决那种没有客户端、没有人的动作)+ pub actor_id: Option<Uuid>,+ /// 台账里的身份快照;人被删了也认得出+ pub label: Option<String>,+ pub count: i64,+}++#[derive(Debug, Clone, Serialize)]+pub struct DecidedDay {+ pub day: chrono::NaiveDate,+ pub count: i64,+}++/// 库的成色:还在世的事实里有多少是暂定的——低置信、证据全被换掉了、+/// 正跟别的事实打架+#[derive(Debug, Clone, Serialize, Default)]+pub struct ReviewHealth {+ pub facts: i64,+ pub low_confidence: i64,+ pub unconfirmed: i64,+ pub contested: i64,+}+/// 一个关系声明了哪些 OWL 公理。////// **打包成一个东西传,不是一串参数。** 它们本来就是同一族——推理机diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rsindex 3e7e7a05..a6bb0909 100644--- a/crates/utopia-server/src/api/mod.rs+++ b/crates/utopia-server/src/api/mod.rs@@ -383,6 +383,7 @@ 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))+ .route("/kbs/{id}/review/summary", get(review_routes::summary))// 记忆抽出、等人点头的事实(0015):按句取、逐条裁.route("/kbs/{id}/review/pending",diff --git a/crates/utopia-server/src/api/review_routes.rs b/crates/utopia-server/src/api/review_routes.rsindex c91a0117..7a2816a5 100644--- a/crates/utopia-server/src/api/review_routes.rs+++ b/crates/utopia-server/src/api/review_routes.rs@@ -459,6 +459,18 @@ pub async fn history(Ok(Json(json!({ "events": events, "total": total })))}+/// 审核台的总览(#377):等着办的、办过的、库的成色。三段聚合,一次返回。+pub async fn summary(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path(kb_id): Path<Uuid>,+) -> ApiResult<Json<utopia_core::models::ReviewSummary>> {+ require_kb(&state, &user, kb_id, Role::Viewer).await?;+ Ok(Json(+ utopia_store::review_summary::summary(&state.pool, kb_id).await?,+ ))+}+#[derive(Deserialize)]pub struct DecideMappingReq {/// confirmed | rejecteddiff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rsindex 04918587..89a23e0f 100644--- a/crates/utopia-store/src/lib.rs+++ b/crates/utopia-store/src/lib.rs@@ -26,6 +26,7 @@ pub mod reasoning;pub mod record_axis;pub mod resolution;pub mod review;+pub mod review_summary;pub mod sealing;pub mod settings;pub mod sources;diff --git a/crates/utopia-store/src/review.rs b/crates/utopia-store/src/review.rsindex 6ccd24bf..0a383a49 100644--- a/crates/utopia-store/src/review.rs+++ b/crates/utopia-store/src/review.rs@@ -19,22 +19,24 @@ use uuid::Uuid;/// 迟早分叉成「徽标说 12 条,点进去 9 条」。pub const LOW_CONFIDENCE_BELOW: f32 = 0.75;+/// 「待确认」的判据,写成 SQL 片段,`counts` 与总览(`review_summary`)共用:+/// 有证据、但证据所在的分块全被新版本取代了。别名固定用 `f`。+pub const UNCONFIRMED_FACT: &str = "EXISTS (SELECT 1 FROM fact_evidence fe WHERE fe.fact_id = f.id)+ AND NOT EXISTS (SELECT 1 FROM fact_evidence fe+ JOIN chunks c ON c.id = fe.chunk_id+ WHERE fe.fact_id = f.id+ AND c.superseded_at IS NULL)";+pub async fn counts(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewCounts> {- Ok(sqlx::query_as(+ let sql = format!("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_conflictsWHERE kb_id = $1 AND status = 'open') AS conflicts,- -- 待确认 = 有证据、但证据所在的分块全被新版本取代了(SELECT count(*) FROM facts f- WHERE f.kb_id = $1 AND f.invalidated_at IS NULL- AND EXISTS (SELECT 1 FROM fact_evidence fe WHERE fe.fact_id = f.id)- AND NOT EXISTS (SELECT 1 FROM fact_evidence fe- JOIN chunks c ON c.id = fe.chunk_id- WHERE fe.fact_id = f.id- AND c.superseded_at IS NULL)) AS unconfirmed,+ WHERE f.kb_id = $1 AND f.invalidated_at IS NULL AND {unconfirmed}) AS unconfirmed,(SELECT count(*) FROM factsWHERE kb_id = $1 AND invalidated_at IS NULLAND confidence < $2 AND derived_by_rule IS NULL) AS lowconf,@@ -45,9 +47,11 @@ pub async fn counts(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewCounts> {(SELECT count(*) FROM ontology_defectsWHERE kb_id = $1 AND status = 'open') AS defects,(SELECT count(*) FROM entity_merges WHERE kb_id = $1) AS merges",- )- .bind(kb_id)- .bind(LOW_CONFIDENCE_BELOW)- .fetch_one(pool)- .await?)+ unconfirmed = UNCONFIRMED_FACT,+ );+ Ok(sqlx::query_as(&sql)+ .bind(kb_id)+ .bind(LOW_CONFIDENCE_BELOW)+ .fetch_one(pool)+ .await?)}diff --git a/crates/utopia-store/src/review_summary.rs b/crates/utopia-store/src/review_summary.rsnew file mode 100644index 00000000..619d3348--- /dev/null+++ b/crates/utopia-store/src/review_summary.rs@@ -0,0 +1,278 @@+//! 审核台的总览(#377):等着办的、办过的、库的成色。+//!+//! 与 [`crate::review::counts`] 同一个前提——**数数不取数**,每一段都是+//! 聚合查询,不把行拉下来在 Rust 里数。七档队列的 WHERE 与 `counts` 逐字+//! 相同(`unconfirmed` 那段抽成了常量共用),否则左栏的数和总览的数迟早+//! 分叉。+//!+//! 「办过的」读的是审计台账:review./fact./conflict./merge. 四族动作,与+//! 决策流水(`audit::review_history`)同一个筛子。没有 actor 的那些是后台+//! 自裁(攒批裁决),单独数出来——「AI 替你办了多少」本身就是一个数。++use chrono::{DateTime, Duration, NaiveDate, Utc};+use sqlx::PgPool;+use std::collections::BTreeMap;+use utopia_core::models::{+ ActionCount, ActorCount, DecidedDay, DecidedWindow, QueueWait, ReviewDecided, ReviewHealth,+ ReviewSummary, ReviewWaiting,+};+use utopia_core::AppResult;+use uuid::Uuid;++use crate::review::{LOW_CONFIDENCE_BELOW, UNCONFIRMED_FACT};++/// 「办过的」按天看多少天+pub const DAILY_DAYS: i64 = 14;+/// 「谁办的」最多列几个人+const TOP_ACTORS: i64 = 5;++/// 与 `audit::review_history` 同一个筛子:review 域的四族动作+const DECISION_ACTIONS: &str = "(e.action LIKE 'review.%' OR e.action LIKE 'fact.%'+ OR e.action LIKE 'conflict.%' OR e.action LIKE 'merge.%')";++pub async fn summary(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewSummary> {+ let (waiting, decided, health) = tokio::try_join!(+ waiting(pool, kb_id),+ decided(pool, kb_id),+ health(pool, kb_id),+ )?;+ Ok(ReviewSummary {+ waiting,+ decided,+ health,+ })+}++#[derive(sqlx::FromRow)]+struct WaitingRow {+ pending: i64,+ pending_oldest: Option<DateTime<Utc>>,+ duplicates: i64,+ duplicates_oldest: Option<DateTime<Utc>>,+ conflicts: i64,+ conflicts_oldest: Option<DateTime<Utc>>,+ unconfirmed: i64,+ unconfirmed_oldest: Option<DateTime<Utc>>,+ lowconf: i64,+ lowconf_oldest: Option<DateTime<Utc>>,+ violations: i64,+ violations_oldest: Option<DateTime<Utc>>,+ defects: i64,+ defects_oldest: Option<DateTime<Utc>>,+}++async fn waiting(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewWaiting> {+ // 每档一对 count/min,一条查询端回来。「最老」按各表自己的时钟:待办事实与+ // 重复、冲突是 created_at,公理与本体缺陷是 detected_at,两种事实队列是+ // 事实自己的 recorded_at——都是「从什么时候起就在等」+ let sql = format!(+ "SELECT+ (SELECT count(*) FROM pending_facts WHERE kb_id = $1) AS pending,+ (SELECT min(created_at) FROM pending_facts WHERE kb_id = $1) AS pending_oldest,+ (SELECT count(*) FROM resolution_reviews+ WHERE kb_id = $1 AND status = 'pending') AS duplicates,+ (SELECT min(created_at) FROM resolution_reviews+ WHERE kb_id = $1 AND status = 'pending') AS duplicates_oldest,+ (SELECT count(*) FROM fact_conflicts+ WHERE kb_id = $1 AND status = 'open') AS conflicts,+ (SELECT min(created_at) FROM fact_conflicts+ WHERE kb_id = $1 AND status = 'open') AS conflicts_oldest,+ (SELECT count(*) FROM facts f+ WHERE f.kb_id = $1 AND f.invalidated_at IS NULL AND {unconfirmed}) AS unconfirmed,+ (SELECT min(f.recorded_at) FROM facts f+ WHERE f.kb_id = $1 AND f.invalidated_at IS NULL AND {unconfirmed}) AS unconfirmed_oldest,+ (SELECT count(*) FROM facts+ WHERE kb_id = $1 AND invalidated_at IS NULL+ AND confidence < $2 AND derived_by_rule IS NULL) AS lowconf,+ (SELECT min(recorded_at) FROM facts+ WHERE kb_id = $1 AND invalidated_at IS NULL+ AND confidence < $2 AND derived_by_rule IS NULL) AS lowconf_oldest,+ (SELECT count(*) FROM axiom_violations+ WHERE kb_id = $1 AND status = 'open') AS violations,+ (SELECT min(detected_at) FROM axiom_violations+ WHERE kb_id = $1 AND status = 'open') AS violations_oldest,+ (SELECT count(*) FROM ontology_defects+ WHERE kb_id = $1 AND status = 'open') AS defects,+ (SELECT min(detected_at) FROM ontology_defects+ WHERE kb_id = $1 AND status = 'open') AS defects_oldest",+ unconfirmed = UNCONFIRMED_FACT,+ );+ let r: WaitingRow = sqlx::query_as(&sql)+ .bind(kb_id)+ .bind(LOW_CONFIDENCE_BELOW)+ .fetch_one(pool)+ .await?;+ let wait = |count: i64, oldest_at: Option<DateTime<Utc>>| QueueWait { count, oldest_at };+ Ok(ReviewWaiting {+ pending: wait(r.pending, r.pending_oldest),+ duplicates: wait(r.duplicates, r.duplicates_oldest),+ conflicts: wait(r.conflicts, r.conflicts_oldest),+ unconfirmed: wait(r.unconfirmed, r.unconfirmed_oldest),+ lowconf: wait(r.lowconf, r.lowconf_oldest),+ violations: wait(r.violations, r.violations_oldest),+ defects: wait(r.defects, r.defects_oldest),+ })+}++#[derive(sqlx::FromRow)]+struct ActionRow {+ action: String,+ automatic: bool,+ last_7d: i64,+ last_30d: i64,+}++#[derive(sqlx::FromRow)]+struct ActorRow {+ actor_id: Option<Uuid>,+ actor_label: Option<String>,+ last_7d: i64,+ last_30d: i64,+}++#[derive(sqlx::FromRow)]+struct DayRow {+ day: NaiveDate,+ count: i64,+}++async fn decided(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewDecided> {+ // 两个窗口一趟查完:按 30 天筛,7 天的用 FILTER 另数一遍+ let by_action: Vec<ActionRow> = sqlx::query_as(&format!(+ "SELECT e.action, (e.actor_id IS NULL) AS automatic,+ count(*) FILTER (WHERE e.created_at >= now() - interval '7 days') AS last_7d,+ count(*) AS last_30d+ FROM audit_events e+ WHERE e.kb_id = $1 AND {DECISION_ACTIONS}+ AND e.created_at >= now() - interval '30 days'+ GROUP BY e.action, automatic+ ORDER BY last_30d DESC, e.action"+ ))+ .bind(kb_id)+ .fetch_all(pool)+ .await?;+ let by_actor: Vec<ActorRow> = sqlx::query_as(&format!(+ "SELECT e.actor_id, min(e.actor_label) AS actor_label,+ count(*) FILTER (WHERE e.created_at >= now() - interval '7 days') AS last_7d,+ count(*) AS last_30d+ FROM audit_events e+ WHERE e.kb_id = $1 AND {DECISION_ACTIONS}+ AND e.created_at >= now() - interval '30 days'+ GROUP BY e.actor_id+ ORDER BY last_30d DESC+ LIMIT $2"+ ))+ .bind(kb_id)+ .bind(TOP_ACTORS)+ .fetch_all(pool)+ .await?;+ let days: Vec<DayRow> = sqlx::query_as(&format!(+ "SELECT (e.created_at AT TIME ZONE 'UTC')::date AS day, count(*) AS count+ FROM audit_events e+ WHERE e.kb_id = $1 AND {DECISION_ACTIONS}+ AND e.created_at >= (now() AT TIME ZONE 'UTC')::date - $2::int+ GROUP BY day"+ ))+ .bind(kb_id)+ .bind((DAILY_DAYS - 1) as i32)+ .fetch_all(pool)+ .await?;++ let window = |seven: bool| {+ let pick = |a: &ActionRow| if seven { a.last_7d } else { a.last_30d };+ let mut merged: BTreeMap<&str, i64> = BTreeMap::new();+ let mut total = 0;+ let mut automatic = 0;+ for a in &by_action {+ let n = pick(a);+ if n == 0 {+ continue;+ }+ total += n;+ if a.automatic {+ automatic += n;+ }+ *merged.entry(a.action.as_str()).or_default() += n;+ }+ let mut by_action: Vec<ActionCount> = merged+ .into_iter()+ .map(|(action, count)| ActionCount {+ action: action.to_string(),+ count,+ })+ .collect();+ by_action.sort_by(|x, y| y.count.cmp(&x.count).then_with(|| x.action.cmp(&y.action)));+ let mut by_actor: Vec<ActorCount> = by_actor+ .iter()+ .map(|r| ActorCount {+ actor_id: r.actor_id,+ label: r.actor_label.clone(),+ count: if seven { r.last_7d } else { r.last_30d },+ })+ .filter(|r| r.count > 0)+ .collect();+ by_actor.sort_by_key(|r| std::cmp::Reverse(r.count));+ DecidedWindow {+ total,+ automatic,+ by_action,+ by_actor,+ }+ };++ // 补齐没有决定的那些天——柱子要等距,缺一天图就说谎+ let by_day: BTreeMap<NaiveDate, i64> = days.into_iter().map(|d| (d.day, d.count)).collect();+ let today = Utc::now().date_naive();+ let daily = (0..DAILY_DAYS)+ .rev()+ .map(|back| {+ let day = today - Duration::days(back);+ DecidedDay {+ day,+ count: by_day.get(&day).copied().unwrap_or(0),+ }+ })+ .collect();++ Ok(ReviewDecided {+ last_7d: window(true),+ last_30d: window(false),+ daily,+ })+}++#[derive(sqlx::FromRow)]+struct HealthRow {+ facts: i64,+ low_confidence: i64,+ unconfirmed: i64,+ contested: i64,+}++async fn health(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewHealth> {+ // 只数在世的事实(invalidated_at IS NULL):作废的不算库的成色。+ // 「有争议」= 挂在一条还开着的冲突的任一端+ let sql = format!(+ "SELECT count(*) AS facts,+ count(*) FILTER (WHERE f.confidence < $2 AND f.derived_by_rule IS NULL) AS low_confidence,+ count(*) FILTER (WHERE {unconfirmed}) AS unconfirmed,+ count(*) FILTER (WHERE EXISTS (+ SELECT 1 FROM fact_conflicts c+ WHERE c.status = 'open'+ AND (c.old_fact_id = f.id OR c.new_fact_id = f.id))) AS contested+ FROM facts f+ WHERE f.kb_id = $1 AND f.invalidated_at IS NULL",+ unconfirmed = UNCONFIRMED_FACT,+ );+ let r: HealthRow = sqlx::query_as(&sql)+ .bind(kb_id)+ .bind(LOW_CONFIDENCE_BELOW)+ .fetch_one(pool)+ .await?;+ Ok(ReviewHealth {+ facts: r.facts,+ low_confidence: r.low_confidence,+ unconfirmed: r.unconfirmed,+ contested: r.contested,+ })+}diff --git a/crates/utopia-store/tests/a_review_has_a_summary.rs b/crates/utopia-store/tests/a_review_has_a_summary.rsnew file mode 100644index 00000000..ef07103d--- /dev/null+++ b/crates/utopia-store/tests/a_review_has_a_summary.rs@@ -0,0 +1,266 @@+//! 审核台的总览(#377),打在真库上。+//!+//! 三段都是 SQL 聚合,`cargo check` 一个字看不见;要钉住的是口径:+//!+//! - **等着办的**与左栏的计数同一套 WHERE,多出来的「最老」取的是各表自己的+//! 时钟(冲突是 created_at,事实队列是 recorded_at)+//! - **办过的**只认 review 域的四族动作,7 天窗口是 30 天窗口的子集,+//! 没有 actor 的算自裁,按天补齐到 14 条+//! - **成色**只数在世的事实;「有争议」是挂在开着的冲突任一端+//!+//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。++use chrono::{DateTime, Duration, Utc};+use sqlx::PgPool;+use uuid::Uuid;++struct Seed {+ kb: Uuid,+ org: Uuid,+ ada: Uuid,+ conflict_at: DateTime<Utc>,+ review_at: DateTime<Utc>,+}++async fn seed(pool: &PgPool) -> anyhow::Result<Seed> {+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ let (etype, rel) = (Uuid::now_v7(), Uuid::now_v7());+ let (a, b, c) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ let (f1, f2, f3) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ let (ada, bo) = (Uuid::now_v7(), Uuid::now_v7());+ let now = Utc::now();++ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'review-summary-test')")+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'review-summary-test')")+ .bind(ws)+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'review-summary-test')",+ )+ .bind(kb)+ .bind(ws)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'thing', 'Thing')",+ )+ .bind(etype)+ .bind(kb)+ .execute(pool)+ .await?;+ sqlx::query("INSERT INTO relation_types (id, kb_id, key, label) VALUES ($1, $2, $3, $3)")+ .bind(rel)+ .bind(kb)+ .bind(format!("knows_{}", Uuid::now_v7().simple()))+ .execute(pool)+ .await?;+ for (id, name) in [(a, "Ada"), (b, "Bo"), (c, "Cy")] {+ sqlx::query(+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",+ )+ .bind(id)+ .bind(kb)+ .bind(etype)+ .bind(name)+ .execute(pool)+ .await?;+ }+ // 三条在世的事实:f2 低置信(0.5 < 0.75),f1 与 f3 之间挂一条开着的冲突+ for (id, s, o, conf) in [(f1, a, b, 0.9f32), (f2, a, c, 0.5), (f3, b, c, 0.9)] {+ sqlx::query(+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, confidence)+ VALUES ($1, $2, $3, $4, $5, $6)",+ )+ .bind(id)+ .bind(kb)+ .bind(s)+ .bind(rel)+ .bind(o)+ .bind(conf)+ .execute(pool)+ .await?;+ }+ let conflict_at = now - Duration::days(3);+ sqlx::query(+ "INSERT INTO fact_conflicts (id, kb_id, old_fact_id, new_fact_id, reason, created_at)+ VALUES ($1, $2, $3, $4, 'simultaneous', $5)",+ )+ .bind(Uuid::now_v7())+ .bind(kb)+ .bind(f1)+ .bind(f3)+ .bind(conflict_at)+ .execute(pool)+ .await?;+ let review_at = now - Duration::days(5);+ sqlx::query(+ "INSERT INTO resolution_reviews (id, kb_id, left_id, right_id, score, created_at)+ VALUES ($1, $2, $3, $4, 0.8, $5)",+ )+ .bind(Uuid::now_v7())+ .bind(kb)+ .bind(a)+ .bind(b)+ .bind(review_at)+ .execute(pool)+ .await?;++ // 台账:Ada 两条在 7 天内,一条自裁在 7 天内,Bo 一条在 20 天前(30 天内),+ // Ada 还有一条 40 天前(窗口外);再夹一条不是 review 域的动作,不该被数+ let events: [(Option<Uuid>, Option<&str>, &str, i64); 6] = [+ (Some(ada), Some("Ada"), "review.merge", 1),+ (Some(ada), Some("Ada"), "fact.confirm", 2),+ (None, None, "review.keep", 3),+ (Some(bo), Some("Bo"), "conflict.close_old", 20),+ (Some(ada), Some("Ada"), "fact.reject", 40),+ (Some(ada), Some("Ada"), "document.upload", 1),+ ];+ for (actor, label, action, days_ago) in events {+ sqlx::query(+ "INSERT INTO audit_events (id, kb_id, actor_id, actor_label, action, target_kind, created_at)+ VALUES ($1, $2, $3, $4, $5, 'test', $6)",+ )+ .bind(Uuid::now_v7())+ .bind(kb)+ .bind(actor)+ .bind(label)+ .bind(action)+ .bind(now - Duration::days(days_ago))+ .execute(pool)+ .await?;+ }+ Ok(Seed {+ kb,+ org,+ ada,+ conflict_at,+ review_at,+ })+}++async fn teardown(pool: &PgPool, s: &Seed) -> anyhow::Result<()> {+ // 台账只增不删(触发器挡着 DELETE),这几行留在库里,挂着一个已经不存在+ // 的 kb_id,谁也读不到;组织不级联到库,两个都要删+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")+ .bind(s.kb)+ .execute(pool)+ .await?;+ sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(s.org)+ .execute(pool)+ .await?;+ Ok(())+}++fn close(a: Option<DateTime<Utc>>, b: DateTime<Utc>) -> bool {+ a.is_some_and(|a| (a - b).num_seconds().abs() < 2)+}++#[tokio::test]+async fn the_summary_reads_the_three_ledgers_with_one_yardstick() -> anyhow::Result<()> {+ let Some(url) = utopia_store::test_db::url() else {+ return Ok(());+ };+ let pool = PgPool::connect(&url).await?;+ let s = seed(&pool).await?;++ let got = utopia_store::review_summary::summary(&pool, s.kb).await;+ let counts = utopia_store::review::counts(&pool, s.kb).await;+ teardown(&pool, &s).await?;+ let sum = got?;+ let counts = counts?;++ // 等着办的:与左栏同一套数,多了最老的一条从何时起等+ let w = &sum.waiting;+ assert_eq!(w.conflicts.count, 1);+ assert!(+ close(w.conflicts.oldest_at, s.conflict_at),+ "冲突按 created_at"+ );+ assert_eq!(w.duplicates.count, 1);+ assert!(+ close(w.duplicates.oldest_at, s.review_at),+ "重复按 created_at"+ );+ assert_eq!(w.lowconf.count, 1);+ assert!(w.lowconf.oldest_at.is_some(), "低置信按事实的 recorded_at");+ assert_eq!(w.unconfirmed.count, 0);+ assert_eq!(w.pending.count, 0);+ assert_eq!(w.pending.oldest_at, None, "空队列没有「最老」");+ assert_eq!(w.violations.count, 0);+ assert_eq!(w.defects.count, 0);+ assert_eq!(+ (+ w.conflicts.count,+ w.duplicates.count,+ w.lowconf.count,+ w.unconfirmed.count+ ),+ (+ counts.conflicts,+ counts.duplicates,+ counts.lowconf,+ counts.unconfirmed+ ),+ "总览与左栏计数是同一套口径"+ );++ // 成色:三条在世的事实,一条低置信,两条挂在开着的冲突上+ assert_eq!(sum.health.facts, 3);+ assert_eq!(sum.health.low_confidence, 1);+ assert_eq!(sum.health.contested, 2);+ assert_eq!(sum.health.unconfirmed, 0);++ // 办过的:7 天窗口三条(两条 Ada、一条自裁),30 天窗口再加 Bo 的一条;+ // 40 天前的与非 review 域的动作都不算+ let d7 = &sum.decided.last_7d;+ assert_eq!(d7.total, 3);+ assert_eq!(d7.automatic, 1);+ let by_action: Vec<(&str, i64)> = d7+ .by_action+ .iter()+ .map(|a| (a.action.as_str(), a.count))+ .collect();+ assert_eq!(+ by_action,+ vec![("fact.confirm", 1), ("review.keep", 1), ("review.merge", 1)],+ "同数按动作名排序"+ );+ assert_eq!(d7.by_actor[0].actor_id, Some(s.ada));+ assert_eq!(d7.by_actor[0].label.as_deref(), Some("Ada"));+ assert_eq!(d7.by_actor[0].count, 2);+ assert!(+ d7.by_actor+ .iter()+ .any(|a| a.actor_id.is_none() && a.count == 1),+ "自裁的那条按「没有人」单列"+ );+ let d30 = &sum.decided.last_30d;+ assert_eq!(d30.total, 4);+ assert_eq!(d30.automatic, 1);+ assert!(+ d30.by_actor+ .iter()+ .any(|a| a.label.as_deref() == Some("Bo") && a.count == 1),+ "20 天前的那条进 30 天窗口"+ );++ // 按天:固定 14 条、今天在最后、加起来就是近 14 天的三条+ let daily = &sum.decided.daily;+ assert_eq!(daily.len() as i64, utopia_store::review_summary::DAILY_DAYS);+ assert_eq!(daily.last().map(|d| d.day), Some(Utc::now().date_naive()));+ assert_eq!(daily.iter().map(|d| d.count).sum::<i64>(), 3);+ for pair in daily.windows(2) {+ assert_eq!(+ pair[1].day - pair[0].day,+ Duration::days(1),+ "一天一条,不跳"+ );+ }+ Ok(())+}