World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Governance reads the ledger before it decides (0025, first cut) (#434)
WaylandYang1e061e7faafb
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rsindex 28446f2e..ee495192 100644--- a/crates/utopia-core/src/models.rs+++ b/crates/utopia-core/src/models.rs@@ -903,6 +903,9 @@ pub struct KnowledgeBase {/// 抽取结束自动排一轮类型消解(0016 C2)。**只自动落地在原类子树里精化的那一档**,/// 跨轴的改判仍留给人。缺省开:基准上自动那一档的命中 39/41(#297),且每批可撤pub auto_type_resolution: bool,+ /// 治理开关(0025,缺省关):开着,govern 任务按先进先出过等人的重复对,+ /// 先读台账里人的先例再裁;关掉,任务在两簇之间看到就停+ pub governance: bool,/// 多久重推一次(分钟)。见 `knowledge_bases.inference_interval_minutes`pub inference_interval_minutes: i32,/// 上次推完的时间。**答的是「上次看过没有」,不是「上次改过没有」**@@ -1214,6 +1217,31 @@ pub struct ReviewCounts {pub violations: i64,pub defects: i64,pub merges: i64,+ /// agent 写下、等人回答的建议(0025)+ pub agent: i64,+}++/// agent 的一笔(0025):看了哪一对、想怎么办、凭什么、人怎么答的。+/// `left` / `right` 是那一对的名字,合并之后仍按当时的实体读得出+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]+pub struct AgentDecisionView {+ pub id: Uuid,+ pub run_id: Uuid,+ pub target_kind: String,+ pub target_id: Uuid,+ /// merge | keep | unsure+ pub action: String,+ pub confidence: f32,+ pub reason: Option<String>,+ pub precedents: serde_json::Value,+ /// proposed | applied | accepted | overridden | reverted | superseded+ pub status: String,+ pub merge_id: Option<Uuid>,+ pub created_at: DateTime<Utc>,+ pub decided_at: Option<DateTime<Utc>>,+ pub decided_by_name: Option<String>,+ pub left: Option<String>,+ pub right: Option<String>,}/// 批量裁决里一条的结果:`error` 为 None 就是成功。一条失败不拖累其余的,diff --git a/crates/utopia-extract/src/lib.rs b/crates/utopia-extract/src/lib.rsindex ea3b0961..fcb31122 100644--- a/crates/utopia-extract/src/lib.rs+++ b/crates/utopia-extract/src/lib.rs@@ -505,6 +505,8 @@ pub struct AdjudicationSide {pub struct AdjudicationPair {pub left: AdjudicationSide,pub right: AdjudicationSide,+ /// 这个库里的人对这一对、这个名字、这种类型对做过什么(0025)。空就不提+ pub precedents: Vec<String>,}#[derive(Debug, Deserialize)]@@ -513,6 +515,9 @@ pub struct AdjudicationVerdict {pub verdict: String,#[serde(default)]pub confidence: Option<f32>,+ /// 一句理由;带先例的裁决要说依据了哪条+ #[serde(default)]+ pub why: Option<String>,}#[derive(Debug, Deserialize)]@@ -545,13 +550,21 @@ pub fn build_adjudication_messages(pairs: &[AdjudicationPair]) -> Vec<ChatMessagPlatform, \"Qiming X7 programme\" is not the Qiming X7, and \"沧海平台项目\" is not \\"沧海平台\" — a project, a programme, a team or a component is its own record.\n\\n\+ Some pairs carry precedents: decisions people made in this same knowledge base on \+ these names, or on pairs of the same two types. Treat them as how the owners of this \+ base want such cases judged. Follow a precedent on the same pair unless the facts of \+ this pair clearly differ from it; when precedents disagree with each other, answer \+ \"unsure\". A precedent never overrides a contradiction in the facts.\n\+ \n\Output exactly one JSON object and nothing else:\n\- {\"verdicts\":[{\"i\":0,\"verdict\":\"same|different|unsure\",\"confidence\":0.9}]}\n\+ {\"verdicts\":[{\"i\":0,\"verdict\":\"same|different|unsure\",\"confidence\":0.9,\+ \"why\":\"one sentence\"}]}\n\\n\Rules:\n\1. One verdict per pair, using the pair's number as \"i\".\n\2. confidence in 0~1.\n\- 3. Be conservative: if the evidence is insufficient to decide, answer \"unsure\" — \+ 3. \"why\" is one short sentence; when a precedent decided it, say which.\n\+ 4. Be conservative: if the evidence is insufficient to decide, answer \"unsure\" — \a wrong merge is far more damaging than leaving two records separate.".to_string();@@ -569,8 +582,19 @@ pub fn build_adjudication_messages(pairs: &[AdjudicationPair]) -> Vec<ChatMessag};format!("\"{}\" ({})\n{}", s.name, s.type_label, facts)};+ let precedents = if p.precedents.is_empty() {+ String::new()+ } else {+ let lines = p+ .precedents+ .iter()+ .map(|l| format!(" - {l}"))+ .collect::<Vec<_>>()+ .join("\n");+ format!("Precedents (decided by people in this base):\n{lines}\n")+ };user.push_str(&format!(- "Pair {i}:\nRecord A: {}\nRecord B: {}\n\n",+ "Pair {i}:\nRecord A: {}\nRecord B: {}\n{precedents}\n",fmt(&p.left),fmt(&p.right)));diff --git a/crates/utopia-server/src/adjudication.rs b/crates/utopia-server/src/adjudication.rsindex c60c728e..13ff6eae 100644--- a/crates/utopia-server/src/adjudication.rs+++ b/crates/utopia-server/src/adjudication.rs@@ -97,6 +97,7 @@ pub async fn adjudicate_entities(state: &AppState, kb_id: Uuid) -> anyhow::Resul.unwrap_or_else(|| "untyped".into()),facts: item.right.top_facts.clone(),},+ precedents: Vec::new(),}).collect();let messages = utopia_extract::build_adjudication_messages(&pairs);diff --git a/crates/utopia-server/src/api/kbs.rs b/crates/utopia-server/src/api/kbs.rsindex 13d0a542..cb75f91d 100644--- a/crates/utopia-server/src/api/kbs.rs+++ b/crates/utopia-server/src/api/kbs.rs@@ -47,6 +47,10 @@ pub struct UpdateKbReq {/// 抽取结束自动排一轮类型消解(缺省开)。见 docs/decisions/0016 C2#[serde(default)]pub auto_type_resolution: Option<bool>,+ /// 治理开关(缺省关):开着,agent 按先进先出过等人的重复对,先读台账再裁;+ /// 打开那一刻就排一轮,关掉后任务在两簇之间看到就停。见 docs/decisions/0025+ #[serde(default)]+ pub governance: Option<bool>,}/// 用户可见的 KB 列表(restricted 库仅矩阵成员与系统管理员可见)。@@ -105,6 +109,7 @@ pub async fn create(None,None,None,+ None,).await?;}@@ -185,8 +190,14 @@ pub async fn update(req.materialize_inferences,req.inference_interval_minutes,req.auto_type_resolution,+ req.governance,).await?;+ // 打开开关就自动开始处理:排一轮,同库已排着的不重复+ if req.governance == Some(true) {+ utopia_store::jobs::enqueue_unless_queued(&state.pool, "govern", json!({ "kb_id": id }))+ .await?;+ }// 审计只记不阻断let _ = utopia_store::audit::record(&state.pool,@@ -195,7 +206,7 @@ pub async fn update("kb.updated","kb",Some(id),- json!({ "name": req.name, "visibility": req.visibility }),+ json!({ "name": req.name, "visibility": req.visibility, "governance": req.governance }),).await;Ok(Json(kb))diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rsindex 1580701e..76d93474 100644--- a/crates/utopia-server/src/api/mod.rs+++ b/crates/utopia-server/src/api/mod.rs@@ -389,6 +389,10 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {.route("/kbs/{id}/review/history", get(review_routes::history)).route("/kbs/{id}/review/summary", get(review_routes::summary)).route("/kbs/{id}/review/batch", post(review_routes::batch))+ .route(+ "/kbs/{id}/review/agent/{decision_id}",+ post(review_routes::agent_answer),+ )// 记忆抽出、等人点头的事实(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 39e48993..235659de 100644--- a/crates/utopia-server/src/api/review_routes.rs+++ b/crates/utopia-server/src/api/review_routes.rs@@ -124,6 +124,8 @@ pub async fn list("merges" => {json!(utopia_store::resolution::list_merges(&state.pool, kb_id, limit, offset).await?)}+ // agent 的每一笔(0025):建议、自动裁决与人的回答,最新的在前+ "agent" => json!(utopia_store::governance::list(&state.pool, kb_id, limit, offset).await?),// 认不出的档名当成契约错误报出来,而不是悄悄回空——悄悄回空会让前端// 拼错一个字母之后看到「这一档清空了」other => {@@ -333,6 +335,124 @@ pub async fn decide().await;}+ crate::governance::after_human_decision(&state, kb_id, &[review_id]).await;+ state.emit_review(kb_id);+ Ok(Json(json!({ "ok": true })))+}++#[derive(Deserialize)]+pub struct AgentAnswerBody {+ /// merge | keep 答一条建议(与建议相同是接受,不同是改判);+ /// revert 撤回一条自动合并;merge 也能推翻一条自动分开+ pub action: String,+}++/// 人回答 agent 的一笔(0025)。回答走的是人的裁决路径:decided_by 是这个人,+/// 台账记的是这个人——它就此成为下一轮的先例+pub async fn agent_answer(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path((kb_id, decision_id)): Path<(Uuid, Uuid)>,+ Json(body): Json<AgentAnswerBody>,+) -> ApiResult<Json<serde_json::Value>> {+ require_kb(&state, &user, kb_id, Role::Editor).await?;+ let d = utopia_store::governance::get(&state.pool, kb_id, decision_id).await?;+ let (l, r) = (+ d.left.clone().unwrap_or_default(),+ d.right.clone().unwrap_or_default(),+ );+ match (d.status.as_str(), body.action.as_str()) {+ ("proposed", act @ ("merge" | "keep")) => {+ utopia_store::resolution::decide_review(&state.pool, kb_id, d.target_id, act, user.id)+ .await?;+ let status = if act == d.action {+ "accepted"+ } else {+ "overridden"+ };+ utopia_store::governance::settle(&state.pool, kb_id, decision_id, status, user.id)+ .await?;+ let _ = utopia_store::audit::record(+ &state.pool,+ Some(kb_id),+ user.id,+ if act == "merge" { "review.merge" } else { "review.keep" },+ "review",+ Some(d.target_id),+ json!({ "left": l, "right": r, "agent_decision": decision_id, "agent_action": d.action }),+ )+ .await;+ }+ ("applied", "revert") => {+ let merge_id = d.merge_id.ok_or_else(|| {+ utopia_core::AppError::invalid(+ "not_a_merge",+ "Only an applied merge can be reverted; a pair kept apart can be merged instead.",+ )+ })?;+ utopia_store::resolution::revert_merge(&state.pool, kb_id, merge_id).await?;+ utopia_store::governance::settle(&state.pool, kb_id, decision_id, "reverted", user.id)+ .await?;+ let _ = utopia_store::audit::record(+ &state.pool,+ Some(kb_id),+ user.id,+ "merge.revert",+ "merge",+ Some(merge_id),+ json!({ "source": l, "target": r, "agent_decision": decision_id }),+ )+ .await;+ }+ ("applied", "merge") if d.action == "keep" => {+ let (left_id, right_id): (Uuid, Uuid) = sqlx::query_as(+ "SELECT left_id, right_id FROM resolution_reviews WHERE id = $1 AND kb_id = $2",+ )+ .bind(d.target_id)+ .bind(kb_id)+ .fetch_optional(&state.pool)+ .await+ .map_err(utopia_core::AppError::from)?+ .ok_or(utopia_core::AppError::NotFound)?;+ let (target, source) =+ utopia_store::resolution::merge_direction(&state.pool, left_id, right_id).await?;+ let merge_id = utopia_store::resolution::merge_entities(+ &state.pool,+ kb_id,+ source,+ target,+ Some(user.id),+ "overrode agent keep",+ )+ .await?;+ utopia_store::governance::settle(+ &state.pool,+ kb_id,+ decision_id,+ "overridden",+ user.id,+ )+ .await?;+ let _ = utopia_store::audit::record(+ &state.pool,+ Some(kb_id),+ user.id,+ "merge.manual",+ "merge",+ Some(merge_id),+ json!({ "source": l, "target": r, "agent_decision": decision_id }),+ )+ .await;+ }+ (status, action) => {+ return Err(utopia_core::AppError::invalid(+ "agent_answer",+ format!("cannot {action} an agent decision that is {status}"),+ )+ .into())+ }+ }+ crate::governance::after_human_decision(&state, kb_id, &[d.target_id]).await;state.emit_review(kb_id);Ok(Json(json!({ "ok": true })))}@@ -403,8 +523,14 @@ pub async fn batch(.await;}}+ let decided_ids: Vec<Uuid> = outcomes+ .iter()+ .filter(|o| o.error.is_none())+ .map(|o| o.id)+ .collect();+ crate::governance::after_human_decision(&state, kb_id, &decided_ids).await;state.emit_review(kb_id);- let decided = outcomes.iter().filter(|o| o.error.is_none()).count();+ let decided = decided_ids.len();Ok(Json(json!({ "decided": decided, "outcomes": outcomes })))}diff --git a/crates/utopia-server/src/extraction.rs b/crates/utopia-server/src/extraction.rsindex 54938126..685a24c9 100644--- a/crates/utopia-server/src/extraction.rs+++ b/crates/utopia-server/src/extraction.rs@@ -1751,8 +1751,19 @@ async fn run(state: &AppState, document_id: Uuid, proposer: Proposer) -> anyhow:utopia_store::documents::set_graph_status(&state.pool, document_id, "done").await?;state.emit_document(doc.kb_id, document_id);- // 灰区对进了审核队列 → 触发攒批裁决任务(独立后台跑,抽取本身到此已完成)- if needs_adjudication {+ // 灰区对进了审核队列 → 触发攒批裁决任务(独立后台跑,抽取本身到此已完成)。+ // 治理开着(0025)排的是治理任务:灰区对与直接转人工的对都从那条先进先出的+ // 队列走,先读台账再裁;同库已排着的不重复+ if kb.governance {+ if needs_adjudication || human_reviews_found {+ utopia_store::jobs::enqueue_unless_queued(+ &state.pool,+ "govern",+ serde_json::json!({ "kb_id": doc.kb_id }),+ )+ .await?;+ }+ } else if needs_adjudication {utopia_store::jobs::enqueue(&state.pool,"adjudicate_entities",diff --git a/crates/utopia-server/src/governance.rs b/crates/utopia-server/src/governance.rsnew file mode 100644index 00000000..28f9490d--- /dev/null+++ b/crates/utopia-server/src/governance.rs@@ -0,0 +1,272 @@+//! 治理任务(0025):开关开着就把等人的重复对按先进先出过一遍,先读台账再裁。+//!+//! 队头带着它的簇进一次模型调用;过闸的自己动手(合并可撤、分开可再合),+//! 过不了的写成建议留给人。两簇之间看一眼开关,关掉就停在这里——「关闭后队列+//! 自动终止」就是那一行。模型缺席时任务成功结束、什么都不动:没有依据的裁决+//! 不如不裁,队列原地等。+//!+//! 与攒批裁决器(`adjudication`)的分工:开关关着,那一档照旧独自判灰区对;+//! 开着,抽取结束排的是这里,灰区对与等人的对都从这条队列走。这里不读也不写+//! 裁决缓存——缓存键里没有先例,而这里的答案随先例变。++use crate::llm_util;+use crate::state::AppState;+use std::collections::HashMap;+use utopia_core::models::ReviewItem;+use utopia_core::AppError;+use utopia_store::governance::{self, Gate, NewDecision, Precedents};+use uuid::Uuid;++/// 一次模型调用带几对:队头加它的簇+const BATCH_SIZE: i64 = 12;+/// 一个任务最多走几轮,之后再排一个接着走——让别的库的任务也轮得上+const MAX_ROUNDS: usize = 20;++pub async fn govern(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {+ let kb = utopia_store::kbs::get(&state.pool, kb_id).await?;+ if !kb.governance {+ return Ok(());+ }+ let settings = utopia_store::settings::get(&state.pool, kb.workspace_id).await?;+ let Some(client) = settings.as_ref().and_then(llm_util::chat_client) else {+ tracing::info!(%kb_id, "治理:没有配聊天模型,队列原地等");+ return Ok(());+ };+ let run_id = Uuid::now_v7();++ for _ in 0..MAX_ROUNDS {+ // 关闭后队列自动终止:每一簇之前看一眼+ if !utopia_store::kbs::get(&state.pool, kb_id).await?.governance {+ tracing::info!(%kb_id, "治理:开关已关,停在这里");+ return Ok(());+ }+ let Some(head) = governance::queue(&state.pool, kb_id, 1)+ .await?+ .into_iter()+ .next()+ else {+ return Ok(());+ };+ let mut items = vec![head];+ let siblings =+ governance::cluster_of(&state.pool, kb_id, &items[0], BATCH_SIZE - 1).await?;+ items.extend(siblings);++ let mut precedents = Vec::with_capacity(items.len());+ for item in &items {+ precedents.push(governance::precedents_for(&state.pool, kb_id, item).await?);+ }+ let pairs: Vec<utopia_extract::AdjudicationPair> = items+ .iter()+ .zip(&precedents)+ .map(|(item, p)| utopia_extract::AdjudicationPair {+ left: side(&item.left),+ right: side(&item.right),+ precedents: governance::render_lines(p),+ })+ .collect();+ let messages = utopia_extract::build_adjudication_messages(&pairs);+ let _permit = match settings.as_ref().map(|s| llm_util::acquire_chat(state, s)) {+ Some(f) => f.await,+ None => None,+ };+ // 调用/解析失败 → 任务按退避重试;重试耗尽后这些对留在队列里,人照样能裁+ let reply = client.chat(&messages).await?;+ let verdicts = utopia_extract::parse_adjudication(&reply)?;+ let by_i: HashMap<usize, &utopia_extract::AdjudicationVerdict> =+ verdicts.iter().map(|v| (v.i, v)).collect();++ for (idx, item) in items.iter().enumerate() {+ let (same, conf, why) = match by_i.get(&idx) {+ Some(v) => (+ match v.verdict.as_str() {+ "same" => Some(true),+ "different" => Some(false),+ _ => None,+ },+ v.confidence.unwrap_or(0.5).clamp(0.0, 1.0),+ v.why.clone(),+ ),+ None => (None, 0.0, None),+ };+ settle(+ state,+ kb_id,+ run_id,+ item,+ &precedents[idx],+ same,+ conf,+ why.as_deref(),+ )+ .await?;+ }+ state.emit_review(kb_id);+ }++ // 轮数用完还有积压:再排一个,下一轮从队头接着走+ if !governance::queue(&state.pool, kb_id, 1).await?.is_empty() {+ utopia_store::jobs::enqueue_unless_queued(+ &state.pool,+ "govern",+ serde_json::json!({ "kb_id": kb_id }),+ )+ .await?;+ }+ Ok(())+}++fn side(s: &utopia_core::models::ReviewSide) -> utopia_extract::AdjudicationSide {+ utopia_extract::AdjudicationSide {+ name: s.name.clone(),+ type_label: s.type_label.clone().unwrap_or_else(|| "untyped".into()),+ facts: s.top_facts.clone(),+ }+}++/// 一对的判决落地:过闸就动手并记 applied,否则转人工并记 proposed+#[allow(clippy::too_many_arguments)]+async fn settle(+ state: &AppState,+ kb_id: Uuid,+ run_id: Uuid,+ item: &ReviewItem,+ p: &Precedents,+ same: Option<bool>,+ conf: f32,+ why: Option<&str>,+) -> anyhow::Result<()> {+ let pool = &state.pool;+ let types_conflict = matches!(+ (&item.left.type_label, &item.right.type_label),+ (Some(a), Some(b)) if a != b+ );+ let action = match same {+ Some(true) => "merge",+ Some(false) => "keep",+ None => "unsure",+ };+ let precedents = governance::precedents_json(p);+ let decision = |status: &'static str, merge_id: Option<Uuid>| NewDecision {+ run_id,+ target_id: item.id,+ action,+ confidence: conf,+ reason: why,+ precedents: precedents.clone(),+ status,+ merge_id,+ };++ match governance::gate(same, conf, types_conflict, p) {+ Gate::Apply if same == Some(true) => {+ let reason = format!("governed|{conf:.2}");+ // 同簇连锁:前一对合完,这一对的一侧可能已经并进了别人——合活着的那个+ let (l, r) = (+ utopia_store::resolution::survivor(pool, kb_id, item.left.id).await?,+ utopia_store::resolution::survivor(pool, kb_id, item.right.id).await?,+ );+ if l == r {+ // 两边已经是同一个实体:只剩把审核行关上+ utopia_store::resolution::close_review_auto(pool, item.id, "merged", &reason)+ .await?;+ let id = governance::record(pool, kb_id, decision("applied", None)).await?;+ audit(state, kb_id, "review.merge", item, conf, id).await;+ return Ok(());+ }+ let (target, source) = utopia_store::resolution::merge_direction(pool, l, r).await?;+ match utopia_store::resolution::merge_entities(+ pool, kb_id, source, target, None, &reason,+ )+ .await+ {+ Ok(merge_id) => {+ utopia_store::resolution::close_review_auto(pool, item.id, "merged", &reason)+ .await?;+ let id = governance::record(pool, kb_id, decision("applied", Some(merge_id)))+ .await?;+ audit(state, kb_id, "review.merge", item, conf, id).await;+ }+ // 同簇连锁合并已吞掉一方:留给人,并记一条 unsure 免得下一轮又撞上+ Err(AppError::Conflict(_)) | Err(AppError::NotFound) => {+ utopia_store::resolution::escalate_review(+ pool,+ item.id,+ "escalate_entity_changed",+ )+ .await?;+ governance::record(+ pool,+ kb_id,+ NewDecision {+ action: "unsure",+ reason: Some("one side changed while this cluster was being decided"),+ ..decision("proposed", None)+ },+ )+ .await?;+ }+ Err(e) => return Err(e.into()),+ }+ }+ Gate::Apply => {+ let reason = format!("governed|{conf:.2}");+ utopia_store::resolution::close_review_auto(pool, item.id, "kept", &reason).await?;+ let id = governance::record(pool, kb_id, decision("applied", None)).await?;+ audit(state, kb_id, "review.keep", item, conf, id).await;+ }+ Gate::Propose => {+ utopia_store::resolution::escalate_review(pool, item.id, "proposed").await?;+ governance::record(pool, kb_id, decision("proposed", None)).await?;+ }+ }+ Ok(())+}++/// 决策台账:actor 为空(机器),detail 里说是治理、置信度多少、对应哪条 agent 决定+async fn audit(+ state: &AppState,+ kb_id: Uuid,+ action: &str,+ item: &ReviewItem,+ conf: f32,+ id: Uuid,+) {+ let _ = utopia_store::audit::record_opt(+ &state.pool,+ Some(kb_id),+ None,+ action,+ "review",+ Some(item.id),+ serde_json::json!({+ "left": item.left.name, "right": item.right.name, "score": item.score,+ "confidence": conf, "via": "governor", "decision": id,+ }),+ )+ .await;+}++/// 人裁了一对之后:同名或同实体的对上的建议过时、那些对回到队列;开关开着就排一轮。+/// 人批量分开三对张伟,agent 顺着同一簇把剩下的照办——#428 要的自动处理就是这一步+pub async fn after_human_decision(state: &AppState, kb_id: Uuid, review_ids: &[Uuid]) {+ for &id in review_ids {+ if let Err(e) = governance::supersede_siblings(&state.pool, kb_id, id).await {+ tracing::warn!(%kb_id, review = %id, error = %e, "治理:建议作废失败");+ }+ }+ match utopia_store::kbs::get(&state.pool, kb_id).await {+ Ok(kb) if kb.governance => {+ if let Err(e) = utopia_store::jobs::enqueue_unless_queued(+ &state.pool,+ "govern",+ serde_json::json!({ "kb_id": kb_id }),+ )+ .await+ {+ tracing::warn!(%kb_id, error = %e, "治理任务入队失败");+ }+ }+ _ => {}+ }+}diff --git a/crates/utopia-server/src/main.rs b/crates/utopia-server/src/main.rsindex 8bbf2578..503420b0 100644--- a/crates/utopia-server/src/main.rs+++ b/crates/utopia-server/src/main.rs@@ -9,6 +9,7 @@ mod docs_corpus;mod error;mod extraction;mod github_issues;+mod governance;mod http_fetch;mod ingest_sources;mod jira_issues;@@ -242,6 +243,34 @@ async fn main() -> anyhow::Result<()> {}});+ // 治理的定时扫描(0025):开关开着、队列里还有 agent 没看过的对的库,每小时排一轮。+ // 抽取结束与人的裁决各自即时排;这一轮兜的是失败重试耗尽之后留下的积压,+ // 所以是小时不是分钟——模型挂了的时候,每分钟撞一次没有意义+ let gov_state = state.clone();+ tokio::spawn(async move {+ let mut tick = tokio::time::interval(std::time::Duration::from_secs(3600));+ tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);+ loop {+ tick.tick().await;+ match utopia_store::governance::due(&gov_state.pool).await {+ Ok(due) => {+ for kb_id in due {+ if let Err(e) = utopia_store::jobs::enqueue_unless_queued(+ &gov_state.pool,+ "govern",+ serde_json::json!({ "kb_id": kb_id }),+ )+ .await+ {+ tracing::warn!(kb_id = %kb_id, error = %e, "治理任务入队失败");+ }+ }+ }+ Err(e) => tracing::warn!(error = %e, "扫描治理积压失败"),+ }+ }+ });+let app = api::router(state, &cfg);let listener = tokio::net::TcpListener::bind(&cfg.bind_addr).await?;tracing::info!("Utopia 服务启动于 http://{}", cfg.bind_addr);@@ -428,6 +457,15 @@ async fn dispatch(st: &state::AppState, job: &utopia_store::jobs::Job) -> anyhow.ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;adjudication::adjudicate_entities(st, kb_id).await}+ "govern" => {+ let kb_id: Uuid = job+ .payload+ .get("kb_id")+ .and_then(|v| v.as_str())+ .and_then(|s| s.parse().ok())+ .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;+ governance::govern(st, kb_id).await+ }"sync_source" => {let source_id: Uuid = job.payloaddiff --git a/crates/utopia-store/src/governance.rs b/crates/utopia-store/src/governance.rsnew file mode 100644index 00000000..eb474d73--- /dev/null+++ b/crates/utopia-store/src/governance.rs@@ -0,0 +1,600 @@+//! 治理(0025):agent 先读台账再裁。+//!+//! 三件事:**先例**——这个库里的人对这一对、这个名字、这种类型对做过什么;+//! **队列**——等人的重复对按先进先出排,队头带着它的簇(同名或同实体的其他对)+//! 一起走;**闸门**——一个纯函数,说这条判决是自己动手还是写成建议。模型调用在+//! server 的 `governance` 任务里,这里不碰模型。+//!+//! 先例只认人的决定(actor 不为空)。agent 自己裁过的不算——否则它引用自己,+//! 越判越自信。人接受了 agent 的建议算:那一笔是人签的,走的是人的裁决路径。++use chrono::{DateTime, Utc};+use serde::Serialize;+use sqlx::PgPool;+use utopia_core::models::{AgentDecisionView, ReviewItem};+use utopia_core::{AppError, AppResult};+use uuid::Uuid;++use crate::resolution::{assemble_reviews, ReviewRow};++/// 自己动手的置信度线。比攒批裁决器的 0.8 高一点:那一档只看这一对,这里是替人做主+pub const AUTO_CONF: f32 = 0.85;+/// 类型对的习惯要有多少笔人的决定才算数+pub const TYPE_PAIR_MIN: i64 = 5;+/// 每族先例最多带几条进提示词+const PER_FAMILY: i64 = 8;++#[derive(Debug, Clone, Serialize, sqlx::FromRow)]+pub struct Precedent {+ pub event_id: Uuid,+ /// review.merge | review.keep | merge.manual | merge.revert+ pub action: String,+ pub left: String,+ pub right: String,+ pub at: DateTime<Utc>,+}++impl Precedent {+ /// 这一笔是把两个记录合了,还是分开了+ pub fn merged(&self) -> bool {+ matches!(self.action.as_str(), "review.merge" | "merge.manual")+ }+}++#[derive(Debug, Clone, Default, Serialize, sqlx::FromRow)]+pub struct TypePairStats {+ pub merged: i64,+ pub kept: i64,+ pub reverted: i64,+}++#[derive(Debug, Clone, Default, Serialize)]+pub struct Precedents {+ /// 人对这两个名字(不分左右)做过的决定+ pub same_pair: Vec<Precedent>,+ /// 其中一个名字对别的名字:这个名字是重名磁铁,还是一直被合+ pub same_name: Vec<Precedent>,+ /// 这个库对这种类型对的习惯;一侧没类型就没有+ pub type_pair: Option<TypePairStats>,+ /// 涉及任一名字的撤回:有一笔就只建议不动手+ pub reverts: Vec<Precedent>,+}++/// 台账里两族 detail 的写法:review.* 记 left/right,merge.* 记 source/target+const L: &str = "lower(COALESCE(detail->>'left', detail->>'source', ''))";+const R: &str = "lower(COALESCE(detail->>'right', detail->>'target', ''))";+const COLS: &str = "id AS event_id, action,+ COALESCE(detail->>'left', detail->>'source', '') AS \"left\",+ COALESCE(detail->>'right', detail->>'target', '') AS \"right\",+ created_at AS at";++pub async fn precedents_for(+ pool: &PgPool,+ kb_id: Uuid,+ item: &ReviewItem,+) -> AppResult<Precedents> {+ let (a, b) = (+ item.left.name.to_lowercase(),+ item.right.name.to_lowercase(),+ );+ let is_pair = format!("(({L} = $2 AND {R} = $3) OR ({L} = $3 AND {R} = $2))");+ let touches = format!("({L} IN ($2, $3) OR {R} IN ($2, $3))");++ let same_pair: Vec<Precedent> = sqlx::query_as(&format!(+ "SELECT {COLS} FROM audit_events+ WHERE kb_id = $1 AND actor_id IS NOT NULL+ AND action IN ('review.merge', 'review.keep', 'merge.manual') AND {is_pair}+ ORDER BY created_at DESC LIMIT $4"+ ))+ .bind(kb_id)+ .bind(&a)+ .bind(&b)+ .bind(PER_FAMILY)+ .fetch_all(pool)+ .await?;++ let same_name: Vec<Precedent> = sqlx::query_as(&format!(+ "SELECT {COLS} FROM audit_events+ WHERE kb_id = $1 AND actor_id IS NOT NULL+ AND action IN ('review.merge', 'review.keep', 'merge.manual')+ AND {touches} AND NOT {is_pair}+ ORDER BY created_at DESC LIMIT $4"+ ))+ .bind(kb_id)+ .bind(&a)+ .bind(&b)+ .bind(PER_FAMILY)+ .fetch_all(pool)+ .await?;++ let reverts: Vec<Precedent> = sqlx::query_as(&format!(+ "SELECT {COLS} FROM audit_events+ WHERE kb_id = $1 AND action = 'merge.revert' AND {touches}+ ORDER BY created_at DESC LIMIT $4"+ ))+ .bind(kb_id)+ .bind(&a)+ .bind(&b)+ .bind(PER_FAMILY)+ .fetch_all(pool)+ .await?;++ let types: Vec<(Uuid, Option<Uuid>)> =+ sqlx::query_as("SELECT id, type_id FROM entities WHERE id = ANY($1)")+ .bind(vec![item.left.id, item.right.id])+ .fetch_all(pool)+ .await?;+ let type_of = |id: Uuid| types.iter().find(|t| t.0 == id).and_then(|t| t.1);+ let type_pair = match (type_of(item.left.id), type_of(item.right.id)) {+ (Some(ta), Some(tb)) => Some(type_pair_stats(pool, kb_id, ta, tb).await?),+ _ => None,+ };++ Ok(Precedents {+ same_pair,+ same_name,+ type_pair,+ reverts,+ })+}++/// 这个库对这种类型对的习惯:人合了多少、分了多少、合了又撤回多少+async fn type_pair_stats(+ pool: &PgPool,+ kb_id: Uuid,+ ta: Uuid,+ tb: Uuid,+) -> AppResult<TypePairStats> {+ let (merged, kept): (i64, i64) = sqlx::query_as(+ "SELECT count(*) FILTER (WHERE rr.status = 'merged'),+ count(*) FILTER (WHERE rr.status = 'kept')+ FROM resolution_reviews rr+ JOIN entities a ON a.id = rr.left_id+ JOIN entities b ON b.id = rr.right_id+ WHERE rr.kb_id = $1 AND rr.decided_by IS NOT NULL+ AND ((a.type_id = $2 AND b.type_id = $3) OR (a.type_id = $3 AND b.type_id = $2))",+ )+ .bind(kb_id)+ .bind(ta)+ .bind(tb)+ .fetch_one(pool)+ .await?;+ let reverted: i64 = sqlx::query_scalar(+ "SELECT count(*) FROM entity_merges m+ JOIN entities s ON s.id = m.source_id+ JOIN entities t ON t.id = m.target_id+ WHERE m.kb_id = $1 AND m.reverted_at IS NOT NULL+ AND ((s.type_id = $2 AND t.type_id = $3) OR (s.type_id = $3 AND t.type_id = $2))",+ )+ .bind(kb_id)+ .bind(ta)+ .bind(tb)+ .fetch_one(pool)+ .await?;+ Ok(TypePairStats {+ merged,+ kept,+ reverted,+ })+}++/// 先例写成提示词里的行。英文:读者是模型+pub fn render_lines(p: &Precedents) -> Vec<String> {+ let verb = |x: &Precedent| if x.merged() { "merged" } else { "kept apart" };+ let day = |t: &DateTime<Utc>| t.format("%Y-%m-%d").to_string();+ let mut out = Vec::new();+ for x in &p.same_pair {+ out.push(format!(+ "this same pair was {} by a person on {}",+ verb(x),+ day(&x.at)+ ));+ }+ for x in &p.same_name {+ out.push(format!(+ "\"{}\" against \"{}\" was {} by a person on {}",+ x.left,+ x.right,+ verb(x),+ day(&x.at)+ ));+ }+ if let Some(t) = &p.type_pair {+ if t.merged + t.kept > 0 {+ out.push(format!(+ "for pairs of these two types in this base, people merged {}, kept {} apart, and later reverted {} merge(s)",+ t.merged, t.kept, t.reverted+ ));+ }+ }+ for x in &p.reverts {+ out.push(format!(+ "a merge of \"{}\" into \"{}\" was reverted by a person on {}",+ x.left,+ x.right,+ day(&x.at)+ ));+ }+ out+}++/// 落进 agent_decisions.precedents 的样子:每条带一个 family+pub fn precedents_json(p: &Precedents) -> serde_json::Value {+ let tag = |family: &str, xs: &[Precedent]| {+ xs.iter()+ .map(|x| {+ serde_json::json!({+ "family": family, "event_id": x.event_id, "action": x.action,+ "left": x.left, "right": x.right, "at": x.at,+ })+ })+ .collect::<Vec<_>>()+ };+ let mut all = tag("same_pair", &p.same_pair);+ all.extend(tag("same_name", &p.same_name));+ all.extend(tag("revert", &p.reverts));+ if let Some(t) = &p.type_pair {+ all.push(serde_json::json!({+ "family": "type_pair", "merged": t.merged, "kept": t.kept, "reverted": t.reverted,+ }));+ }+ serde_json::Value::Array(all)+}++#[derive(Debug, PartialEq, Eq)]+pub enum Gate {+ /// 自己动手:合并可撤,分开可再合+ Apply,+ /// 写成建议留给人+ Propose,+}++/// 硬规则先于置信度:类型冲突不合、有撤回只建议、与人对这一对的决定相反只建议。+/// 合并要有先例撑着——这一对合过、这个名字合过且从没分过、或这种类型对有明显的+/// 合并习惯且没撤回过;分开只要置信度。一个库里没有任何人的历史,就不会自己合+pub fn gate(same: Option<bool>, conf: f32, types_conflict: bool, p: &Precedents) -> Gate {+ let Some(same) = same else {+ return Gate::Propose;+ };+ if conf < AUTO_CONF || !p.reverts.is_empty() {+ return Gate::Propose;+ }+ if p.same_pair.iter().any(|x| x.merged() != same) {+ return Gate::Propose;+ }+ if !same {+ return Gate::Apply;+ }+ if types_conflict {+ return Gate::Propose;+ }+ let pair_support = p.same_pair.iter().any(|x| x.merged());+ let name_support =+ p.same_name.iter().any(|x| x.merged()) && p.same_name.iter().all(|x| x.merged());+ let habit = p.type_pair.as_ref().is_some_and(|t| {+ t.merged + t.kept >= TYPE_PAIR_MIN && t.merged >= t.kept && t.reverted == 0+ });+ if pair_support || name_support || habit {+ Gate::Apply+ } else {+ Gate::Propose+ }+}++/// 有一条开着的建议的对不进队列:agent 已经问过了,等人答+const OPEN_PROPOSAL: &str = "NOT EXISTS (SELECT 1 FROM agent_decisions d+ WHERE d.target_kind = 'review' AND d.target_id = rr.id AND d.status = 'proposed')";++/// 等人的重复对,先进先出+pub async fn queue(pool: &PgPool, kb_id: Uuid, limit: i64) -> AppResult<Vec<ReviewItem>> {+ let rows: Vec<ReviewRow> = sqlx::query_as(&format!(+ "SELECT rr.id, rr.left_id, rr.right_id, rr.score, rr.reason, rr.stage, rr.created_at+ FROM resolution_reviews rr+ WHERE rr.kb_id = $1 AND rr.status = 'pending' AND {OPEN_PROPOSAL}+ ORDER BY rr.created_at, rr.id LIMIT $2"+ ))+ .bind(kb_id)+ .bind(limit)+ .fetch_all(pool)+ .await?;+ assemble_reviews(pool, kb_id, rows).await+}++/// 队头的簇:与它同名或同实体的其他等人的对,同样先进先出+pub async fn cluster_of(+ pool: &PgPool,+ kb_id: Uuid,+ head: &ReviewItem,+ limit: i64,+) -> AppResult<Vec<ReviewItem>> {+ let rows: Vec<ReviewRow> = sqlx::query_as(&format!(+ "SELECT rr.id, rr.left_id, rr.right_id, rr.score, rr.reason, rr.stage, rr.created_at+ FROM resolution_reviews rr+ JOIN entities a ON a.id = rr.left_id+ JOIN entities b ON b.id = rr.right_id+ WHERE rr.kb_id = $1 AND rr.status = 'pending' AND rr.id <> $2 AND {OPEN_PROPOSAL}+ AND (rr.left_id = ANY($3) OR rr.right_id = ANY($3)+ OR lower(a.canonical_name) = ANY($4) OR lower(b.canonical_name) = ANY($4))+ ORDER BY rr.created_at, rr.id LIMIT $5"+ ))+ .bind(kb_id)+ .bind(head.id)+ .bind(vec![head.left.id, head.right.id])+ .bind(vec![+ head.left.name.to_lowercase(),+ head.right.name.to_lowercase(),+ ])+ .bind(limit)+ .fetch_all(pool)+ .await?;+ assemble_reviews(pool, kb_id, rows).await+}++pub struct NewDecision<'a> {+ pub run_id: Uuid,+ pub target_id: Uuid,+ /// merge | keep | unsure+ pub action: &'a str,+ pub confidence: f32,+ pub reason: Option<&'a str>,+ pub precedents: serde_json::Value,+ /// proposed | applied+ pub status: &'a str,+ pub merge_id: Option<Uuid>,+}++pub async fn record(pool: &PgPool, kb_id: Uuid, d: NewDecision<'_>) -> AppResult<Uuid> {+ let id = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO agent_decisions+ (id, kb_id, run_id, target_kind, target_id, action, confidence, reason,+ precedents, status, merge_id)+ VALUES ($1, $2, $3, 'review', $4, $5, $6, $7, $8, $9, $10)",+ )+ .bind(id)+ .bind(kb_id)+ .bind(d.run_id)+ .bind(d.target_id)+ .bind(d.action)+ .bind(d.confidence)+ .bind(d.reason)+ .bind(d.precedents)+ .bind(d.status)+ .bind(d.merge_id)+ .execute(pool)+ .await?;+ Ok(id)+}++const VIEW: &str = "SELECT d.id, d.run_id, d.target_kind, d.target_id, d.action, d.confidence,+ d.reason, d.precedents, d.status, d.merge_id, d.created_at, d.decided_at,+ u.display_name AS decided_by_name,+ a.canonical_name AS \"left\", b.canonical_name AS \"right\"+ FROM agent_decisions d+ LEFT JOIN users u ON u.id = d.decided_by+ LEFT JOIN resolution_reviews rr ON rr.id = d.target_id+ LEFT JOIN entities a ON a.id = rr.left_id+ LEFT JOIN entities b ON b.id = rr.right_id";++/// Agent 队列:最新的在前+pub async fn list(+ pool: &PgPool,+ kb_id: Uuid,+ limit: i64,+ offset: i64,+) -> AppResult<Vec<AgentDecisionView>> {+ let rows = sqlx::query_as(&format!(+ "{VIEW} WHERE d.kb_id = $1 ORDER BY d.created_at DESC, d.id DESC LIMIT $2 OFFSET $3"+ ))+ .bind(kb_id)+ .bind(limit)+ .bind(offset)+ .fetch_all(pool)+ .await?;+ Ok(rows)+}++pub async fn get(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<AgentDecisionView> {+ sqlx::query_as(&format!("{VIEW} WHERE d.kb_id = $1 AND d.id = $2"))+ .bind(kb_id)+ .bind(id)+ .fetch_optional(pool)+ .await?+ .ok_or(AppError::NotFound)+}++pub async fn count_proposed(pool: &PgPool, kb_id: Uuid) -> AppResult<i64> {+ let n = sqlx::query_scalar(+ "SELECT count(*) FROM agent_decisions WHERE kb_id = $1 AND status = 'proposed'",+ )+ .bind(kb_id)+ .fetch_one(pool)+ .await?;+ Ok(n)+}++/// 人的回答:accepted / overridden 答一条建议,reverted / overridden 答一条自动裁决。+/// 已经答过的不能再答——那是另一个人刚做的决定+pub async fn settle(+ pool: &PgPool,+ kb_id: Uuid,+ id: Uuid,+ status: &str,+ user_id: Uuid,+) -> AppResult<()> {+ let n = sqlx::query(+ "UPDATE agent_decisions SET status = $3, decided_at = now(), decided_by = $4+ WHERE kb_id = $1 AND id = $2 AND status IN ('proposed', 'applied')",+ )+ .bind(kb_id)+ .bind(id)+ .bind(status)+ .bind(user_id)+ .execute(pool)+ .await?+ .rows_affected();+ if n == 0 {+ return Err(AppError::Conflict(+ "this decision has already been answered".into(),+ ));+ }+ Ok(())+}++/// 人裁了一对:同名或同实体的其他对上开着的建议过时了——那些建议是在没有这笔+/// 先例时写的。标成 superseded,那些对回到队列,下一轮带着新先例再看+pub async fn supersede_siblings(pool: &PgPool, kb_id: Uuid, review_id: Uuid) -> AppResult<u64> {+ let n = sqlx::query(+ "UPDATE agent_decisions d SET status = 'superseded', decided_at = now()+ FROM resolution_reviews me+ JOIN entities ma ON ma.id = me.left_id+ JOIN entities mb ON mb.id = me.right_id,+ resolution_reviews rr+ JOIN entities a ON a.id = rr.left_id+ JOIN entities b ON b.id = rr.right_id+ WHERE me.id = $2 AND me.kb_id = $1+ AND d.kb_id = $1 AND d.status = 'proposed'+ AND d.target_kind = 'review' AND d.target_id = rr.id AND rr.id <> me.id+ AND (rr.left_id IN (me.left_id, me.right_id) OR rr.right_id IN (me.left_id, me.right_id)+ OR lower(a.canonical_name) IN (lower(ma.canonical_name), lower(mb.canonical_name))+ OR lower(b.canonical_name) IN (lower(ma.canonical_name), lower(mb.canonical_name)))",+ )+ .bind(kb_id)+ .bind(review_id)+ .execute(pool)+ .await?+ .rows_affected();+ Ok(n)+}++/// 开关开着、队列里还有 agent 没看过的对的库:定时扫描用+pub async fn due(pool: &PgPool) -> AppResult<Vec<Uuid>> {+ let ids = sqlx::query_scalar(&format!(+ "SELECT kb.id FROM knowledge_bases kb+ WHERE kb.governance AND EXISTS (+ SELECT 1 FROM resolution_reviews rr+ WHERE rr.kb_id = kb.id AND rr.status = 'pending' AND {OPEN_PROPOSAL})"+ ))+ .fetch_all(pool)+ .await?;+ Ok(ids)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn p(action: &str) -> Precedent {+ Precedent {+ event_id: Uuid::now_v7(),+ action: action.into(),+ left: "a".into(),+ right: "b".into(),+ at: Utc::now(),+ }+ }++ fn stats(merged: i64, kept: i64, reverted: i64) -> Option<TypePairStats> {+ Some(TypePairStats {+ merged,+ kept,+ reverted,+ })+ }++ fn with_stats(merged: i64, kept: i64, reverted: i64) -> Precedents {+ Precedents {+ type_pair: stats(merged, kept, reverted),+ ..Default::default()+ }+ }++ #[test]+ fn unsure_and_low_confidence_are_proposed() {+ let none = Precedents::default();+ assert_eq!(gate(None, 0.99, false, &none), Gate::Propose);+ assert_eq!(gate(Some(false), 0.6, false, &none), Gate::Propose);+ assert_eq!(gate(Some(true), 0.84, false, &none), Gate::Propose);+ }++ #[test]+ fn keeping_apart_needs_confidence_only() {+ let none = Precedents::default();+ assert_eq!(gate(Some(false), 0.9, false, &none), Gate::Apply);+ // 类型冲突的对也能自己分开:分开不改图+ assert_eq!(gate(Some(false), 0.9, true, &none), Gate::Apply);+ }++ #[test]+ fn merging_needs_precedent() {+ let none = Precedents::default();+ assert_eq!(gate(Some(true), 0.99, false, &none), Gate::Propose);+ let pair = Precedents {+ same_pair: vec![p("review.merge")],+ ..Default::default()+ };+ assert_eq!(gate(Some(true), 0.9, false, &pair), Gate::Apply);+ let name = Precedents {+ same_name: vec![p("merge.manual"), p("review.merge")],+ ..Default::default()+ };+ assert_eq!(gate(Some(true), 0.9, false, &name), Gate::Apply);+ let mixed = Precedents {+ same_name: vec![p("review.merge"), p("review.keep")],+ ..Default::default()+ };+ assert_eq!(gate(Some(true), 0.9, false, &mixed), Gate::Propose);+ assert_eq!(+ gate(Some(true), 0.9, false, &with_stats(6, 2, 0)),+ Gate::Apply+ );+ assert_eq!(+ gate(Some(true), 0.9, false, &with_stats(3, 1, 0)),+ Gate::Propose,+ "习惯要够 {TYPE_PAIR_MIN} 笔才算"+ );+ assert_eq!(+ gate(Some(true), 0.9, false, &with_stats(6, 2, 1)),+ Gate::Propose,+ "撤回过的类型对不算习惯"+ );+ }++ #[test]+ fn hard_rules_come_first() {+ let pair = Precedents {+ same_pair: vec![p("review.merge")],+ ..Default::default()+ };+ assert_eq!(+ gate(Some(true), 0.99, true, &pair),+ Gate::Propose,+ "类型冲突不合"+ );+ let reverted = Precedents {+ same_pair: vec![p("review.merge")],+ reverts: vec![p("merge.revert")],+ ..Default::default()+ };+ assert_eq!(gate(Some(true), 0.99, false, &reverted), Gate::Propose);+ assert_eq!(gate(Some(false), 0.99, false, &reverted), Gate::Propose);+ let kept = Precedents {+ same_pair: vec![p("review.keep")],+ ..Default::default()+ };+ assert_eq!(+ gate(Some(true), 0.99, false, &kept),+ Gate::Propose,+ "人分开过这一对,模型说合,只建议"+ );+ let merged = Precedents {+ same_pair: vec![p("review.merge")],+ ..Default::default()+ };+ assert_eq!(+ gate(Some(false), 0.99, false, &merged),+ Gate::Propose,+ "人合过这一对,模型说分,只建议"+ );+ }+}diff --git a/crates/utopia-store/src/kbs.rs b/crates/utopia-store/src/kbs.rsindex a89b7179..2282a9a2 100644--- a/crates/utopia-store/src/kbs.rs+++ b/crates/utopia-store/src/kbs.rs@@ -85,6 +85,7 @@ pub async fn update(materialize_inferences: Option<bool>,inference_interval_minutes: Option<i32>,auto_type_resolution: Option<bool>,+ governance: Option<bool>,) -> AppResult<KnowledgeBase> {// 改语言不回头重写已有的类——它们已经是这个库的数据,可能有人手工调过。// 这一列往后管的是**新**描述(自动扩本体、AI 建议)写成什么语言@@ -120,6 +121,7 @@ pub async fn update(materialize_inferences = COALESCE($7, materialize_inferences),inference_interval_minutes = COALESCE($8, inference_interval_minutes),auto_type_resolution = COALESCE($9, auto_type_resolution),+ governance = COALESCE($10, governance),updated_at = now()WHERE id = $1 RETURNING *",)@@ -132,6 +134,7 @@ pub async fn update(.bind(materialize_inferences).bind(inference_interval_minutes).bind(auto_type_resolution)+ .bind(governance).fetch_optional(pool).await?.ok_or(AppError::NotFound)diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rsindex 29bab318..26758b3b 100644--- a/crates/utopia-store/src/lib.rs+++ b/crates/utopia-store/src/lib.rs@@ -12,6 +12,7 @@ pub mod db;pub mod documents;pub mod export;pub mod extraction_drops;+pub mod governance;pub mod graph;pub mod jobs;pub mod kbs;diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rsindex 83ade944..416bbf7c 100644--- a/crates/utopia-store/src/resolution.rs+++ b/crates/utopia-store/src/resolution.rs@@ -1102,7 +1102,7 @@ pub async fn create_review(}#[derive(Debug, sqlx::FromRow)]-struct ReviewRow {+pub(crate) struct ReviewRow {id: Uuid,left_id: Uuid,right_id: Uuid,@@ -1206,7 +1206,7 @@ pub async fn entity_fact_lines(.collect())}-async fn assemble_reviews(+pub(crate) async fn assemble_reviews(pool: &PgPool,kb_id: Uuid,rows: Vec<ReviewRow>,@@ -1388,16 +1388,24 @@ pub async fn decide_review(match action {"merge" => {- let (target, source) = merge_direction(pool, row.left_id, row.right_id).await?;- merge_entities(- pool,- kb_id,- source,- target,- Some(user_id),- "review decision",- )- .await?;+ // 同名连锁(A-B 合了,B-C 还等着):B 已并进 A,这一对实际上是 A-C。+ // 跟着 merged_into 走到活着的那个再合;两边走到同一个,就只剩把审核行关上+ let (l, r) = (+ survivor(pool, kb_id, row.left_id).await?,+ survivor(pool, kb_id, row.right_id).await?,+ );+ if l != r {+ let (target, source) = merge_direction(pool, l, r).await?;+ merge_entities(+ pool,+ kb_id,+ source,+ target,+ Some(user_id),+ "review decision",+ )+ .await?;+ }sqlx::query("UPDATE resolution_reviews SET status = 'merged', decided_at = now(), decided_by = $2WHERE id = $1",@@ -1422,6 +1430,25 @@ pub async fn decide_review(Ok(())}+/// 跟着 `merged_into` 走到还活着的那个实体。同簇连锁合并之后,一对里的一侧可能已经+/// 并进了别人;合并要合的是活着的那个,不是那条已经空了的行+pub async fn survivor(pool: &PgPool, kb_id: Uuid, mut id: Uuid) -> AppResult<Uuid> {+ for _ in 0..16 {+ let next: Option<Option<Uuid>> =+ sqlx::query_scalar("SELECT merged_into FROM entities WHERE id = $1 AND kb_id = $2")+ .bind(id)+ .bind(kb_id)+ .fetch_optional(pool)+ .await?;+ match next {+ Some(Some(n)) => id = n,+ Some(None) => return Ok(id),+ None => return Err(AppError::NotFound),+ }+ }+ Err(AppError::Conflict("merge chain too long".into()))+}+/// 合并方向:返回 (target 存活, source 被并)。pub async fn merge_direction(pool: &PgPool, a: Uuid, b: Uuid) -> AppResult<(Uuid, Uuid)> {let (deg_a,): (i64,) = sqlx::query_as(diff --git a/crates/utopia-store/src/review.rs b/crates/utopia-store/src/review.rsindex 268c8fe7..04e41709 100644--- a/crates/utopia-store/src/review.rs+++ b/crates/utopia-store/src/review.rs@@ -52,7 +52,9 @@ pub async fn counts(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewCounts> {WHERE kb_id = $1 AND status = 'open') AS violations,(SELECT count(*) FROM ontology_defectsWHERE kb_id = $1 AND status = 'open') AS defects,- (SELECT count(*) FROM entity_merges WHERE kb_id = $1) AS merges",+ (SELECT count(*) FROM entity_merges WHERE kb_id = $1) AS merges,+ (SELECT count(*) FROM agent_decisions+ WHERE kb_id = $1 AND status = 'proposed') AS agent",unconfirmed = UNCONFIRMED_FACT,same = crate::resolution::TypeFilter::Same.clause(),conflict = crate::resolution::TypeFilter::Conflict.clause(),diff --git a/crates/utopia-store/tests/a_governor_reads_the_ledger.rs b/crates/utopia-store/tests/a_governor_reads_the_ledger.rsnew file mode 100644index 00000000..1fff645d--- /dev/null+++ b/crates/utopia-store/tests/a_governor_reads_the_ledger.rs@@ -0,0 +1,390 @@+//! 治理先读台账(0025),打在真库上。+//!+//! 要钉住的行为:+//!+//! - **先例只认人的**:同一对被人分开过两次算两条,机器自己合过的那条不算;+//! 这一对合过、这个名字对别的名字、这种类型对的习惯、涉及这个名字的撤回,+//! 四族各归各+//! - **闸门**:人分开过的对模型说合只建议;合过的对模型说合就动手;有撤回只建议;+//! 类型冲突不合;没有任何先例不合,但能分+//! - **队列先进先出**,队头带着同名或同实体的簇;写了建议的对不再进队列;+//! 人裁了一对,同簇的建议作废、那些对回到队列+//! - **回答**:一条建议只能答一次;开关关了的库不在定时扫描里+//!+//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。+//! 台账只增不删,种下的几行留在库里(kb 已删,kb_id 悬空,本就允许)。++use chrono::{Duration, Utc};+use sqlx::PgPool;+use utopia_store::governance::{self, Gate, NewDecision};+use uuid::Uuid;++struct Seed {+ kb: Uuid,+ org: Uuid,+ user: Uuid,+ /// 张伟 1 对 张伟 2:人分开过两次+ zw12: Uuid,+ /// Apple 对 Apple Inc.:人合过+ apple: Uuid,+ /// Orion 对 Orion Labs:合过又撤回+ orion: Uuid,+ /// Mercury(公司)对 Mercury(人):类型冲突+ mercury: Uuid,+ /// 张伟 2 对 张伟 3:与第一对同名同实体,进簇+ zw23: Uuid,+}++async fn seed(pool: &PgPool) -> anyhow::Result<Seed> {+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ let (person, company) = (Uuid::now_v7(), Uuid::now_v7());+ let user = Uuid::now_v7();+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'governor-test')")+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO users (id, org_id, email, display_name, password_hash)+ VALUES ($1, $2, $3, 'Governor Tester', 'x')",+ )+ .bind(user)+ .bind(org)+ .bind(format!("governor-{}@test.local", user.simple()))+ .execute(pool)+ .await?;+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'governor-test')")+ .bind(ws)+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO knowledge_bases (id, workspace_id, name, governance)+ VALUES ($1, $2, 'governor-test', TRUE)",+ )+ .bind(kb)+ .bind(ws)+ .execute(pool)+ .await?;+ for (id, key, label) in [+ (person, "person", "Person"),+ (company, "org", "Organization"),+ ] {+ sqlx::query("INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, $3, $4)")+ .bind(id)+ .bind(kb)+ .bind(key)+ .bind(label)+ .execute(pool)+ .await?;+ }+ let entity = |type_id: Uuid, name: &str| {+ let id = Uuid::now_v7();+ let name = name.to_string();+ let pool = pool.clone();+ async move {+ sqlx::query(+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",+ )+ .bind(id)+ .bind(kb)+ .bind(type_id)+ .bind(name)+ .execute(&pool)+ .await+ .map(|_| id)+ }+ };+ let zw1 = entity(person, "Zhang Wei").await?;+ let zw2 = entity(person, "Zhang Wei").await?;+ let zw3 = entity(person, "Zhang Wei").await?;+ let apple1 = entity(company, "Apple").await?;+ let apple2 = entity(company, "Apple Inc.").await?;+ let orion1 = entity(company, "Orion").await?;+ let orion2 = entity(company, "Orion Labs").await?;+ let mercury1 = entity(company, "Mercury").await?;+ let mercury2 = entity(person, "Mercury").await?;++ // 等人的对,created_at 隔开一分钟:先进先出要看得出顺序+ let t0 = Utc::now() - Duration::hours(1);+ let mut n = 0;+ let mut review = |l: Uuid, r: Uuid| {+ let id = Uuid::now_v7();+ let at = t0 + Duration::minutes(n);+ n += 1;+ let pool = pool.clone();+ async move {+ sqlx::query(+ "INSERT INTO resolution_reviews+ (id, kb_id, left_id, right_id, score, reason, stage, created_at)+ VALUES ($1, $2, $3, $4, 1.0, 'namesake', 'human', $5)",+ )+ .bind(id)+ .bind(kb)+ .bind(l)+ .bind(r)+ .bind(at)+ .execute(&pool)+ .await+ .map(|_| id)+ }+ };+ let zw12 = review(zw1, zw2).await?;+ let apple = review(apple1, apple2).await?;+ let orion = review(orion1, orion2).await?;+ let mercury = review(mercury1, mercury2).await?;+ let zw23 = review(zw2, zw3).await?;++ // 台账:人的决定。actor 为空的那条是机器裁的,不算先例+ let ledger = |actor: Option<Uuid>, action: &str, detail: serde_json::Value| {+ let action = action.to_string();+ let pool = pool.clone();+ async move {+ sqlx::query(+ "INSERT INTO audit_events (id, kb_id, actor_id, action, target_kind, detail)+ VALUES ($1, $2, $3, $4, 'review', $5)",+ )+ .bind(Uuid::now_v7())+ .bind(kb)+ .bind(actor)+ .bind(action)+ .bind(detail)+ .execute(&pool)+ .await+ .map(|_| ())+ }+ };+ let pair = |l: &str, r: &str| serde_json::json!({ "left": l, "right": r, "score": 1.0 });+ ledger(Some(user), "review.keep", pair("Zhang Wei", "Zhang Wei")).await?;+ ledger(Some(user), "review.keep", pair("Zhang Wei", "Zhang Wei")).await?;+ ledger(None, "review.merge", pair("Zhang Wei", "Zhang Wei")).await?;+ ledger(Some(user), "review.merge", pair("Apple Inc.", "Apple")).await?;+ ledger(Some(user), "review.keep", pair("Apple", "Apple Records")).await?;+ ledger(+ Some(user),+ "merge.revert",+ serde_json::json!({ "source": "Orion", "target": "Orion Labs" }),+ )+ .await?;++ // 这种类型对的习惯:人裁过的 Person×Person 对,一合三分+ for status in ["merged", "kept", "kept", "kept"] {+ let (a, b) = (+ entity(person, "Someone").await?,+ entity(person, "Someone").await?,+ );+ sqlx::query(+ "INSERT INTO resolution_reviews+ (id, kb_id, left_id, right_id, score, stage, status, decided_at, decided_by)+ VALUES ($1, $2, $3, $4, 1.0, 'human', $5, now(), $6)",+ )+ .bind(Uuid::now_v7())+ .bind(kb)+ .bind(a)+ .bind(b)+ .bind(status)+ .bind(user)+ .execute(pool)+ .await?;+ }++ Ok(Seed {+ kb,+ org,+ user,+ zw12,+ apple,+ orion,+ mercury,+ zw23,+ })+}++async fn teardown(pool: &PgPool, s: &Seed) -> anyhow::Result<()> {+ 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(())+}++async fn run(pool: &PgPool, s: &Seed) -> anyhow::Result<()> {+ // 先进先出+ let q = governance::queue(pool, s.kb, 10).await?;+ let ids: Vec<Uuid> = q.iter().map(|i| i.id).collect();+ assert_eq!(ids, vec![s.zw12, s.apple, s.orion, s.mercury, s.zw23]);+ let by_id = |id: Uuid| q.iter().find(|i| i.id == id).cloned().unwrap();++ // 队头的簇:同名同实体的张伟 2 对 3+ let cluster = governance::cluster_of(pool, s.kb, &by_id(s.zw12), 11).await?;+ assert_eq!(+ cluster.iter().map(|i| i.id).collect::<Vec<_>>(),+ vec![s.zw23]+ );++ // 四族先例+ let p = governance::precedents_for(pool, s.kb, &by_id(s.zw12)).await?;+ assert_eq!(p.same_pair.len(), 2, "人分开过两次;机器合过的那条不算");+ assert!(p.same_pair.iter().all(|x| !x.merged()));+ assert!(p.same_name.is_empty());+ assert!(p.reverts.is_empty());+ let t = p.type_pair.clone().expect("两边都有类型");+ assert_eq!((t.merged, t.kept, t.reverted), (1, 3, 0));+ assert_eq!(governance::gate(Some(false), 0.9, false, &p), Gate::Apply);+ assert_eq!(+ governance::gate(Some(true), 0.99, false, &p),+ Gate::Propose,+ "人分开过,模型说合,只建议"+ );++ let p = governance::precedents_for(pool, s.kb, &by_id(s.apple)).await?;+ assert_eq!(p.same_pair.len(), 1, "左右对调也算这一对");+ assert!(p.same_pair[0].merged());+ assert_eq!(+ p.same_name.len(),+ 1,+ "Apple 对 Apple Records 是这个名字对别的名字"+ );+ assert_eq!(governance::gate(Some(true), 0.9, false, &p), Gate::Apply);+ assert_eq!(governance::gate(Some(true), 0.7, false, &p), Gate::Propose);+ let lines = governance::render_lines(&p);+ assert!(lines[0].starts_with("this same pair was merged by a person on "));+ assert!(lines+ .iter()+ .any(|l| l.contains("\"Apple\" against \"Apple Records\" was kept apart")));++ let p = governance::precedents_for(pool, s.kb, &by_id(s.orion)).await?;+ assert_eq!(p.reverts.len(), 1);+ assert_eq!(governance::gate(Some(true), 0.99, false, &p), Gate::Propose);+ assert_eq!(+ governance::gate(Some(false), 0.99, false, &p),+ Gate::Propose+ );++ let m = by_id(s.mercury);+ let p = governance::precedents_for(pool, s.kb, &m).await?;+ assert!(p.type_pair.is_some());+ assert_eq!(governance::gate(Some(true), 0.99, true, &p), Gate::Propose);+ assert_eq!(governance::gate(Some(false), 0.9, true, &p), Gate::Apply);++ // 写了建议的对不再进队列+ let run_id = Uuid::now_v7();+ let d_apple = governance::record(+ pool,+ s.kb,+ NewDecision {+ run_id,+ target_id: s.apple,+ action: "merge",+ confidence: 0.7,+ reason: Some("the same pair was merged before"),+ precedents: governance::precedents_json(&p),+ status: "proposed",+ merge_id: None,+ },+ )+ .await?;+ let d_zw23 = governance::record(+ pool,+ s.kb,+ NewDecision {+ run_id,+ target_id: s.zw23,+ action: "keep",+ confidence: 0.6,+ reason: None,+ precedents: serde_json::json!([]),+ status: "proposed",+ merge_id: None,+ },+ )+ .await?;+ let ids: Vec<Uuid> = governance::queue(pool, s.kb, 10)+ .await?+ .iter()+ .map(|i| i.id)+ .collect();+ assert_eq!(ids, vec![s.zw12, s.orion, s.mercury]);+ assert_eq!(governance::count_proposed(pool, s.kb).await?, 2);+ assert_eq!(utopia_store::review::counts(pool, s.kb).await?.agent, 2);+ let listed = governance::list(pool, s.kb, 10, 0).await?;+ assert_eq!(listed.len(), 2, "最新的在前");+ assert_eq!(listed[0].id, d_zw23);+ assert_eq!(listed[1].left.as_deref(), Some("Apple"));+ assert_eq!(listed[1].right.as_deref(), Some("Apple Inc."));+ assert!(+ governance::record(+ pool,+ s.kb,+ NewDecision {+ run_id,+ target_id: s.apple,+ action: "keep",+ confidence: 0.5,+ reason: None,+ precedents: serde_json::json!([]),+ status: "proposed",+ merge_id: None,+ },+ )+ .await+ .is_err(),+ "一个目标同时只有一条开着的建议"+ );++ // 人裁了张伟 1 对 2:同簇的张伟 2 对 3 的建议作废、回到队列;Apple 的不受影响+ utopia_store::resolution::decide_review(pool, s.kb, s.zw12, "keep", s.user).await?;+ assert_eq!(governance::supersede_siblings(pool, s.kb, s.zw12).await?, 1);+ assert_eq!(+ governance::get(pool, s.kb, d_zw23).await?.status,+ "superseded"+ );+ assert_eq!(+ governance::get(pool, s.kb, d_apple).await?.status,+ "proposed"+ );+ let ids: Vec<Uuid> = governance::queue(pool, s.kb, 10)+ .await?+ .iter()+ .map(|i| i.id)+ .collect();+ assert_eq!(ids, vec![s.orion, s.mercury, s.zw23]);+ // 张伟 2 对 3 的同对先例还是种下的两条:decide_review 本身不写台账,台账由路由层记+ let p = governance::precedents_for(pool, s.kb, &by_id(s.zw23)).await?;+ assert_eq!(p.same_pair.len(), 2);++ // 回答一条建议:答过就不能再答+ governance::settle(pool, s.kb, d_apple, "accepted", s.user).await?;+ let d = governance::get(pool, s.kb, d_apple).await?;+ assert_eq!(d.status, "accepted");+ assert_eq!(d.decided_by_name.as_deref(), Some("Governor Tester"));+ assert!(+ governance::settle(pool, s.kb, d_apple, "overridden", s.user)+ .await+ .is_err()+ );++ // 定时扫描:开关开着且有没看过的对 → 在;关了 → 不在+ assert!(governance::due(pool).await?.contains(&s.kb));+ sqlx::query("UPDATE knowledge_bases SET governance = FALSE WHERE id = $1")+ .bind(s.kb)+ .execute(pool)+ .await?;+ assert!(!governance::due(pool).await?.contains(&s.kb));+ Ok(())+}++#[tokio::test]+async fn a_governor_reads_the_ledger() -> 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 outcome = run(&pool, &s).await;+ teardown(&pool, &s).await?;+ outcome+}diff --git a/docs/decisions/0025-governance-reads-the-ledger-before-it-decides.md b/docs/decisions/0025-governance-reads-the-ledger-before-it-decides.mdnew file mode 100644index 00000000..2d334cca--- /dev/null+++ b/docs/decisions/0025-governance-reads-the-ledger-before-it-decides.md@@ -0,0 +1,71 @@+# 0025 · Governance reads the ledger before it decides++- **Status**: cut 1 implemented · migration 0035 adds `knowledge_bases.governance` and `agent_decisions`; `governance` in the store holds the precedent families, the first-in-first-out queue with its clusters, the gate and the table; the `govern` job in the server reads the switch, calls the model with precedents and applies or proposes; `?queue=agent`, `ReviewCounts.agent` and `POST /kbs/{id}/review/agent/{decision_id}` on the API · cut 2 (a tool-using loop with a `defer` action), cut 3 (the switch, the Agent queue and the Overview section in the UI) and cut 4 (the fuse) are open, see the last section+- **Written**: 2026-09-06 (conventions in the [README](README.md))+- **Related**: [0016](0016-close-the-open-seams-before-cutting-new-ones.md) C2 gave a base its first automation switch, `auto_type_resolution`, and this record copies its shape; #428 asked for bulk and automatic handling of same-name pairs and got the batch path (#429, #430) this builds on; [0020](0020-an-auditor-reads-it-without-us.md) made the ledger complete enough to be read back; [0015](0015-recording-a-sentence-is-not-asserting-a-fact.md) keeps a person's own sentences out of any machine's reach.++> Three hundred namesake pairs wait in Review. A person merges the first ten "Apple / Apple Inc." pairs and keeps the first ten "Zhang Wei / Zhang Wei" pairs apart, and the remaining two hundred and eighty wait for the same person to do the same thing two hundred and eighty more times. The record of those twenty decisions is in the ledger, with names, scores, times and who. Nothing reads it.++## What the adjudicator does today++The resolver files a grey-zone pair as `resolution_reviews` in stage `adjudicating`. The adjudicator (`adjudication.rs`) sends twelve pairs per model call with each side's name, type and top facts, caches the verdict under a key of names, types and facts, and at confidence 0.8 merges or keeps; anything else is escalated to stage `human` with a reason code. From then on the machine never looks at the pair again. The prompt has no history: the same "Zhang Wei" a person has kept apart three times is judged from zero the fourth time, and the pair a person merged yesterday is judged from zero today.++The people using a base have meanwhile written every decision they made into `audit_events`: `review.merge` and `review.keep` with both names, `merge.manual`, `merge.revert`, and the `fact.*` and `conflict.*` families for the other queues. Every row carries who and when. That is the precedent.++## Decisions++### 1. The ledger is the precedent, and only people write it++For a pair the governor asks the ledger four questions: what people decided on these two names (either order), what people decided about either name against other names, how this base decides pairs of this type pair (merged, kept, later reverted), and whether a merge involving either name was reverted. Only rows with an actor count. The agent's own rows never count, or it would cite itself and grow more confident with every round. A proposal a person accepted counts, because the acceptance goes through the person's decide path and is recorded as that person's decision (decision 6). The retrieved precedents go into the adjudication prompt as lines in plain English, and the model is asked to say in one sentence which one it relied on.++### 2. A switch per base, off by default; on starts the queue, off stops it++`knowledge_bases.governance`, a boolean, next to `auto_type_resolution`. Turning it on enqueues a `govern` job at once; an extraction that leaves pairs behind enqueues one; a person's decision enqueues one; an hourly sweep enqueues one for every base whose queue holds pairs the agent has not looked at. All four go through `enqueue_unless_queued`, so a base has at most one job waiting. The job re-reads the switch before every cluster and returns when it is off: turning the switch off ends the queue at the next cluster boundary, and nothing already decided is undone.++Off is the default for the opposite reason `auto_type_resolution` defaults to on: that one was measured (39/41) and moves a type one step down its own subtree, this one merges entities and has not been measured on any base yet. A base earns automation by having history to read, and its owner turns it on.++Two decisions folded into this one. The record first had three states, off / suggest / auto. The gate (decision 4) already turns everything that does not clear it into a proposal, so "suggest" is what the switch does for the pairs it cannot decide, and a second knob would explain the same thing twice. The sweep is hourly because the instant triggers cover the live cases; the sweep exists for backlog left after a job's retries ran out, and a model that is down should not be hit every minute.++### 3. First in, first out, and the head brings its cluster++The queue is every pending pair without an open proposal, oldest first. The head's cluster is every other queued pair that shares a name or an entity with it, up to twelve in all, and the whole cluster goes into one model call. Oldest first because the oldest has waited longest and because the order is one a person can predict; the cluster because a name should be judged consistently in one sitting, not once per pair across separate calls, and because the cluster is the unit #428 asked about: three "Zhang Wei" pairs a person kept apart and nine more that should follow.++### 4. Merging needs precedent, keeping apart needs confidence, hard rules come first++The gate is a pure function of the verdict, its confidence, whether the two types conflict, and the precedents. In order: an `unsure` verdict is proposed; confidence below 0.85 is proposed; any reverted merge involving either name is proposed; a verdict that contradicts what a person decided on this same pair is proposed. A `different` verdict that survives those is applied. A `same` verdict is proposed when the types conflict, and otherwise applied only with support: this pair was merged before, this name was merged before and never kept apart, or this type pair has at least five human decisions, merges at least as many as keeps, and no reverts. A base with no human history therefore never merges on its own; it proposes, and the answers become the history.++Keeping apart is cheap: it changes no fact and a manual merge undoes it. Merging moves facts and a revert has to unwind them, so it is the side that needs a person to have gone first. The threshold sits above the adjudicator's 0.8 because the adjudicator judges one pair in isolation and the governor is standing in for a person.++### 5. Every look is a row in `agent_decisions`++One row per pair the agent looked at: the pair, the action (`merge`, `keep`, `unsure`), the confidence, the model's sentence, the precedents it was shown, and a status. `proposed` waits for a person; `applied` was decided and can be reverted; `accepted`, `overridden` and `reverted` are a person's answers; `superseded` means a person decided a sibling (same name or same entity) after the proposal was written, so the proposal is stale and the pair returns to the queue to be looked at again with the new precedent. That last transition is the cascade: a person keeps one "Zhang Wei" pair apart, the agent's open proposals on the other "Zhang Wei" pairs are superseded, the next job finds them at the head of the queue with a same-pair precedent, and the gate lets it keep them apart itself.++A partial unique index allows one open proposal per pair. The table is the Agent queue on the Review page and the source of the acceptance, override and revert counts; nothing has to be reconstructed from the ledger.++### 6. Answers go through the person's path++Accepting or overriding a proposal calls `decide_review` with the person's id, exactly as the Review page does; reverting an applied merge calls `revert_merge`; merging over an applied keep calls `merge_entities` with the person as `merged_by`. Each writes the usual audit row plus the decision id. So an answer is a person's decision in every table that records decisions, and by decision 1 it is precedent for the next look.++### 7. The governor does not touch the verdict cache++The adjudicator's cache is keyed on names, types and facts. The governor's answer also depends on the precedents, which change with every human decision; a cached verdict would be one taken without them. The governor neither reads nor writes the cache, and the two are kept apart by the switch: off, the adjudicator runs the adjudicating stage as before; on, extraction enqueues the governor instead and both stages flow through the one queue.++## What a reader sees++Duplicates that the agent proposed on carry the reason code `proposed`; pairs it decided are closed with `governed|<confidence>` and appear under Merges and in History with the machine as the actor, as auto-merges always have. `?queue=agent` lists the rows of decision 5 newest first with both names, the reason and the precedents. The cut-3 UI puts the switch in the base settings, the queue in the Review rail and the counts on the Overview.++## Dead ends++- **Suggestion columns on `resolution_reviews`.** Four columns for action, confidence, reason and precedents. They cover only duplicates, keep no record of how a person answered, and cannot express "superseded"; the table is one more table and answers all three.+- **Three states: off, suggest, auto.** See decision 2. The gate makes suggesting the fallback for anything it will not apply, so the middle state was already there.+- **Precedent by embedding.** Embed each decided pair and retrieve the nearest. Name and type families already cover what actually recurs, and the nearest neighbour brings back pairs that look alike and were decided for reasons the vector cannot see. Reconsider when cut 2 gives the model a search tool it can steer.+- **A minute-level sweep.** The other schedulers tick every minute. A dead model would then be called once a minute per base with backlog until someone noticed.++## Open questions++- **Cut 2, the loop.** Today the governor is the adjudicator with precedents and a gate. The next cut lets the model ask for an entity's facts, a source chunk or a ledger search instead of receiving one block, and adds a `defer` action that leaves a specific question for a person on the row.+- **Cut 3, the UI.** The switch in base settings, the Agent queue, a chip on a pair that carries a proposal, the agent section on the Overview. Left unmerged until it has been looked at on the dev server.+- **Cut 4, the fuse.** Two reverts of applied merges within seven days turn the switch off and raise an alert; the person turns it back on.+- **Other queues.** Conflicts have three human actions to learn from (`conflict.close_old`, `keep_both`, `reject_new`); unconfirmed and low-confidence facts have `fact.confirm` and `fact.reject`. Nods (`pending_facts`, 0015) stay out: the person who said it nods.+- **Cross-base precedent.** A workspace's other bases may hold the same names. Kept to one base until someone asks.+- **A budget.** A job runs twenty clusters and re-enqueues itself while backlog remains. A per-base daily budget of model calls is the obvious next guard, but the thresholds above are the ones that need measuring first.diff --git a/docs/decisions/README.md b/docs/decisions/README.mdindex 0b235f12..8ecb2b51 100644--- a/docs/decisions/README.md+++ b/docs/decisions/README.md@@ -48,6 +48,7 @@ The test for writing one: if someone (including us) looks at a piece of code in| 0022 | [An unknown date is not an open one](0022-an-unknown-date-is-not-an-open-one.md) | Implemented in two cuts (#394 and the derived cut) · `world_axis` predicate beside `record_axis`, `facts.attested_at` anchors a missing start or an undated end at the document that attests it, every read and both client filters on the read interval, an undated ending closes the dated row it ends, derived rows intersect premise intervals as read and carry no precision on an anchored bound · two anchors (`attested_from` / `attested_to`), so a bare open row closes too (#393) || 0023 | [RSS observations are not documents](0023-rss-observations-are-not-documents.md) | Implemented in #326 || 0024 | [The world axis reaches the second](0024-the-world-axis-reaches-the-second.md) | Implemented · the precision ladder runs year → second (not below: no source states less), a stored value is truncated to its precision by CHECK on all three tables, a clock time without a zone is a date, one list spells the ladder in the extractor, the renderers, the export and the evaluator; a derived bound takes the precision of the premise that set it |+| 0025 | [Governance reads the ledger before it decides](0025-governance-reads-the-ledger-before-it-decides.md) | Cut 1 implemented · a per-base `governance` switch, a `govern` job that works the duplicates queue first in, first out with each head's cluster, precedents pulled from the ledger into the prompt, a gate that merges only with precedent, every look a row in `agent_decisions`, answers through the person's own decide path · the tool-using loop, the UI and the fuse are open |## Not a decision recorddiff --git a/migrations/0035_governance_reads_the_ledger.sql b/migrations/0035_governance_reads_the_ledger.sqlnew file mode 100644index 00000000..58a21cf6--- /dev/null+++ b/migrations/0035_governance_reads_the_ledger.sql@@ -0,0 +1,40 @@+-- 0025:治理自己跑,先读台账再裁。+--+-- 每库一个开关 governance(缺省关)。开着:抽取结束、有人裁决之后、打开开关那一刻、+-- 每小时一次,排一个 govern 任务,把等人的重复对按先进先出过一遍;两簇之间看一眼+-- 开关,关掉就停在那里。缺省关:合并是改图的动作,agent 的命中还没在哪个库上量过,+-- 与 auto_type_resolution 缺省开的理由正相反(那一档量过 39/41,且只往子树走一格)。+--+-- agent 的每一笔是 agent_decisions 的一行:建议(proposed,等人接受或改判)、自己+-- 裁了(applied,可撤)、人的回答(accepted / overridden / reverted)、被后来的人裁决+-- 盖过(superseded:同名或同实体的另一对由人定了,这条建议过时,那一对回到队列)。+-- 这张表就是审核台的 Agent 队列,也是接受率 / 改判率 / 撤回数的来源。+ALTER TABLE knowledge_bases ADD COLUMN governance BOOLEAN NOT NULL DEFAULT FALSE;++CREATE TABLE agent_decisions (+ id UUID PRIMARY KEY,+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,+ -- 哪一轮 govern 任务:同一轮里的行是一起看的+ run_id UUID NOT NULL,+ -- 现在只有 review(重复对);冲突与事实队列接进来时扩这个 CHECK+ target_kind TEXT NOT NULL CHECK (target_kind IN ('review')),+ target_id UUID NOT NULL,+ -- unsure 也留一行:看过了、说不准,人知道它问过+ action TEXT NOT NULL CHECK (action IN ('merge', 'keep', 'unsure')),+ confidence REAL NOT NULL DEFAULT 0,+ -- 模型给的一句理由,原话+ reason TEXT,+ -- 它引用的先例:[{event_id, action, left, right, at}]+ precedents JSONB NOT NULL DEFAULT '[]',+ status TEXT NOT NULL CHECK (status IN+ ('proposed', 'applied', 'accepted', 'overridden', 'reverted', 'superseded')),+ -- applied 且是合并时:entity_merges 的那一行,撤回走它+ merge_id UUID REFERENCES entity_merges(id) ON DELETE SET NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ decided_at TIMESTAMPTZ,+ decided_by UUID REFERENCES users(id)+);+CREATE INDEX agent_decisions_kb_idx ON agent_decisions (kb_id, created_at DESC);+-- 一个目标同时只有一条开着的建议+CREATE UNIQUE INDEX agent_decisions_open_idx+ ON agent_decisions (target_kind, target_id) WHERE status = 'proposed';diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex ba5c3ae7..9dc0775f 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -1542,6 +1542,8 @@ export const en = {escalate_no_verdict: "The adjudicator returned no verdict",escalate_entity_changed: "The entity changed while being adjudicated",escalate_unsure: "The adjudicator was not confident enough",+ proposed: "The agent looked and left a proposal",+ governed: "Decided by the agent from precedent",namesake: "Two entities with this name in one document",/* 画像分不开时的并列:分数是真的,所以百分比照常显示(与 namesake 的哨兵值不同) */namesake_tie: "Same name, and the profiles cannot tell them apart",diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex cdda46fc..215178bc 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -1347,6 +1347,8 @@ export const zh: Strings = {escalate_no_verdict: "裁决没有给出结论",escalate_entity_changed: "裁决过程中实体发生了变化",escalate_unsure: "裁决的把握不够",+ proposed: "agent 看过了,留了一条建议",+ governed: "agent 按先例裁的",namesake: "同一篇文档里有两个同名实体",namesake_tie: "同名,画像分不出谁是谁",contains: "一个名字包含另一个",