World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
The agent gets its switch, its queue and its place on the Overview (0025, UI cut) (#437)
WaylandYangd391b99a3a2a
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rsindex ee495192..caea8a7e 100644--- a/crates/utopia-core/src/models.rs+++ b/crates/utopia-core/src/models.rs@@ -767,6 +767,17 @@ pub struct ReviewSide {pub top_facts: Vec<String>,}+/// agent 在一对上留下的、还开着的建议(0025):卡片上挂一个标签,人在卡片上+/// 的裁决就是对它的回答+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]+pub struct ReviewProposal {+ pub id: Uuid,+ /// merge | keep | unsure+ pub action: String,+ pub confidence: f32,+ pub reason: Option<String>,+}+/// 消解审核项:疑似同一实体的灰区对。#[derive(Debug, Clone, Serialize)]pub struct ReviewItem {@@ -778,6 +789,8 @@ pub struct ReviewItem {pub created_at: DateTime<Utc>,pub left: ReviewSide,pub right: ReviewSide,+ /// agent 的建议,没有就是 None+ pub proposal: Option<ReviewProposal>,}/// 合并日志行(审核页历史区)。@@ -1219,6 +1232,8 @@ pub struct ReviewCounts {pub merges: i64,/// agent 写下、等人回答的建议(0025)pub agent: i64,+ /// agent 的全部记录(Agent 队列翻页用)+ pub agent_rows: i64,}/// agent 的一笔(0025):看了哪一对、想怎么办、凭什么、人怎么答的。@@ -1262,6 +1277,27 @@ pub struct ReviewSummary {pub waiting: ReviewWaiting,pub decided: ReviewDecided,pub health: ReviewHealth,+ pub agent: ReviewAgent,+}++/// agent 在这个库里做过什么(0025):开着的建议,以及近期每一笔现在的状态+#[derive(Debug, Clone, Serialize, Default)]+pub struct ReviewAgent {+ /// 等人回答的建议,不分时间+ pub open: i64,+ pub last_7d: AgentWindow,+ pub last_30d: AgentWindow,+}++/// 一个时间窗口里 agent 写下的行,按**现在的**状态数:自动裁了还站着的、+/// 人接受的、人改判的、人撤回的+#[derive(Debug, Clone, Serialize, Default)]+pub struct AgentWindow {+ pub applied: i64,+ pub proposed: i64,+ pub accepted: i64,+ pub overridden: i64,+ pub reverted: i64,}/// 一档队列里等着的:多少条、最老的一条从什么时候开始等diff --git a/crates/utopia-server/src/api/review_routes.rs b/crates/utopia-server/src/api/review_routes.rsindex 235659de..6225b6cc 100644--- a/crates/utopia-server/src/api/review_routes.rs+++ b/crates/utopia-server/src/api/review_routes.rs@@ -335,7 +335,14 @@ pub async fn decide().await;}- crate::governance::after_human_decision(&state, kb_id, &[review_id]).await;+ crate::governance::after_human_decision(+ &state,+ kb_id,+ &[review_id],+ Some(&body.action),+ user.id,+ )+ .await;state.emit_review(kb_id);Ok(Json(json!({ "ok": true })))}@@ -452,7 +459,7 @@ pub async fn agent_answer(.into())}}- crate::governance::after_human_decision(&state, kb_id, &[d.target_id]).await;+ crate::governance::after_human_decision(&state, kb_id, &[d.target_id], None, user.id).await;state.emit_review(kb_id);Ok(Json(json!({ "ok": true })))}@@ -528,7 +535,14 @@ pub async fn batch(.filter(|o| o.error.is_none()).map(|o| o.id).collect();- crate::governance::after_human_decision(&state, kb_id, &decided_ids).await;+ crate::governance::after_human_decision(+ &state,+ kb_id,+ &decided_ids,+ Some(&body.action),+ user.id,+ )+ .await;state.emit_review(kb_id);let decided = decided_ids.len();Ok(Json(json!({ "decided": decided, "outcomes": outcomes })))diff --git a/crates/utopia-server/src/governance.rs b/crates/utopia-server/src/governance.rsindex 28f9490d..6f20125e 100644--- a/crates/utopia-server/src/governance.rs+++ b/crates/utopia-server/src/governance.rs@@ -247,10 +247,23 @@ async fn audit(.await;}-/// 人裁了一对之后:同名或同实体的对上的建议过时、那些对回到队列;开关开着就排一轮。-/// 人批量分开三对张伟,agent 顺着同一簇把剩下的照办——#428 要的自动处理就是这一步-pub async fn after_human_decision(state: &AppState, kb_id: Uuid, review_ids: &[Uuid]) {+/// 人裁了一对之后:这一对上开着的建议就是被回答了(与建议相同是接受,不同是改判);+/// 同名或同实体的对上的建议过时、那些对回到队列;开关开着就排一轮。+/// 人批量分开三对张伟,agent 顺着同一簇把剩下的照办——#428 要的自动处理就是这一步。+/// `action` 为 None 时不答本对的建议(Agent 队列那条路自己已经答过了)+pub async fn after_human_decision(+ state: &AppState,+ kb_id: Uuid,+ review_ids: &[Uuid],+ action: Option<&str>,+ user_id: Uuid,+) {for &id in review_ids {+ if let Some(action) = action {+ if let Err(e) = governance::answer_open(&state.pool, kb_id, id, action, user_id).await {+ tracing::warn!(%kb_id, review = %id, error = %e, "治理:建议回答失败");+ }+ }if let Err(e) = governance::supersede_siblings(&state.pool, kb_id, id).await {tracing::warn!(%kb_id, review = %id, error = %e, "治理:建议作废失败");}diff --git a/crates/utopia-store/src/governance.rs b/crates/utopia-store/src/governance.rsindex eb474d73..670fb689 100644--- a/crates/utopia-store/src/governance.rs+++ b/crates/utopia-store/src/governance.rs@@ -441,6 +441,30 @@ pub async fn settle(Ok(())}+/// 人在卡片上裁了一对:这一对上开着的建议就此有了答案——动作与建议相同是+/// accepted,不同是 overridden;没有开着的建议就什么都不做+pub async fn answer_open(+ pool: &PgPool,+ kb_id: Uuid,+ review_id: Uuid,+ action: &str,+ user_id: Uuid,+) -> AppResult<()> {+ sqlx::query(+ "UPDATE agent_decisions+ SET status = CASE WHEN action = $3 THEN 'accepted' ELSE 'overridden' END,+ decided_at = now(), decided_by = $4+ WHERE kb_id = $1 AND target_kind = 'review' AND target_id = $2 AND status = 'proposed'",+ )+ .bind(kb_id)+ .bind(review_id)+ .bind(action)+ .bind(user_id)+ .execute(pool)+ .await?;+ Ok(())+}+/// 人裁了一对:同名或同实体的其他对上开着的建议过时了——那些建议是在没有这笔/// 先例时写的。标成 superseded,那些对回到队列,下一轮带着新先例再看pub async fn supersede_siblings(pool: &PgPool, kb_id: Uuid, review_id: Uuid) -> AppResult<u64> {diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rsindex 416bbf7c..210e9302 100644--- a/crates/utopia-store/src/resolution.rs+++ b/crates/utopia-store/src/resolution.rs@@ -1211,8 +1211,35 @@ pub(crate) async fn assemble_reviews(kb_id: Uuid,rows: Vec<ReviewRow>,) -> AppResult<Vec<ReviewItem>> {+ // 这一页上开着的建议(0025):一趟查完,按审核行挂上去+ let ids: Vec<Uuid> = rows.iter().map(|r| r.id).collect();+ let proposals: Vec<(Uuid, utopia_core::models::ReviewProposal)> =+ sqlx::query_as::<_, (Uuid, Uuid, String, f32, Option<String>)>(+ "SELECT target_id, id, action, confidence, reason FROM agent_decisions+ WHERE target_kind = 'review' AND target_id = ANY($1) AND status = 'proposed'",+ )+ .bind(&ids)+ .fetch_all(pool)+ .await?+ .into_iter()+ .map(|(target, id, action, confidence, reason)| {+ (+ target,+ utopia_core::models::ReviewProposal {+ id,+ action,+ confidence,+ reason,+ },+ )+ })+ .collect();let mut items = Vec::with_capacity(rows.len());for r in rows {+ let proposal = proposals+ .iter()+ .find(|(t, _)| *t == r.id)+ .map(|(_, p)| p.clone());items.push(ReviewItem {id: r.id,score: r.score,@@ -1221,6 +1248,7 @@ pub(crate) async fn assemble_reviews(created_at: r.created_at,left: review_side(pool, kb_id, r.left_id).await?,right: review_side(pool, kb_id, r.right_id).await?,+ proposal,});}Ok(items)diff --git a/crates/utopia-store/src/review.rs b/crates/utopia-store/src/review.rsindex 04e41709..1e6cac4e 100644--- a/crates/utopia-store/src/review.rs+++ b/crates/utopia-store/src/review.rs@@ -54,7 +54,8 @@ pub async fn counts(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewCounts> {WHERE kb_id = $1 AND status = 'open') AS defects,(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",+ WHERE kb_id = $1 AND status = 'proposed') AS agent,+ (SELECT count(*) FROM agent_decisions WHERE kb_id = $1) AS agent_rows",unconfirmed = UNCONFIRMED_FACT,same = crate::resolution::TypeFilter::Same.clause(),conflict = crate::resolution::TypeFilter::Conflict.clause(),diff --git a/crates/utopia-store/src/review_summary.rs b/crates/utopia-store/src/review_summary.rsindex 619d3348..8049bd89 100644--- a/crates/utopia-store/src/review_summary.rs+++ b/crates/utopia-store/src/review_summary.rs@@ -13,8 +13,8 @@ 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,+ ActionCount, ActorCount, AgentWindow, DecidedDay, DecidedWindow, QueueWait, ReviewAgent,+ ReviewDecided, ReviewHealth, ReviewSummary, ReviewWaiting,};use utopia_core::AppResult;use uuid::Uuid;@@ -31,15 +31,17 @@ const DECISION_ACTIONS: &str = "(e.action LIKE 'review.%' OR e.action LIKE 'factOR 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!(+ let (waiting, decided, health, agent) = tokio::try_join!(waiting(pool, kb_id),decided(pool, kb_id),health(pool, kb_id),+ agent(pool, kb_id),)?;Ok(ReviewSummary {waiting,decided,health,+ agent,})}@@ -249,6 +251,55 @@ struct HealthRow {contested: i64,}+#[derive(sqlx::FromRow)]+struct AgentRow {+ status: String,+ last_7d: i64,+ last_30d: i64,+}++/// agent 的记录(0025):开着的建议不分时间;两个窗口里写下的行按**现在的**+/// 状态数——「自动裁了还站着的」与「被撤回的」是两个数,合起来才是它动过手的+async fn agent(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewAgent> {+ let open: i64 = sqlx::query_scalar(+ "SELECT count(*) FROM agent_decisions WHERE kb_id = $1 AND status = 'proposed'",+ )+ .bind(kb_id)+ .fetch_one(pool)+ .await?;+ let rows: Vec<AgentRow> = sqlx::query_as(+ "SELECT status,+ count(*) FILTER (WHERE created_at >= now() - interval '7 days') AS last_7d,+ count(*) AS last_30d+ FROM agent_decisions+ WHERE kb_id = $1 AND created_at >= now() - interval '30 days'+ GROUP BY status",+ )+ .bind(kb_id)+ .fetch_all(pool)+ .await?;+ let window = |seven: bool| {+ let mut w = AgentWindow::default();+ for r in &rows {+ let n = if seven { r.last_7d } else { r.last_30d };+ match r.status.as_str() {+ "applied" => w.applied = n,+ "proposed" => w.proposed = n,+ "accepted" => w.accepted = n,+ "overridden" => w.overridden = n,+ "reverted" => w.reverted = n,+ _ => {}+ }+ }+ w+ };+ Ok(ReviewAgent {+ open,+ last_7d: window(true),+ last_30d: window(false),+ })+}+async fn health(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewHealth> {// 只数在世的事实(invalidated_at IS NULL):作废的不算库的成色。// 「有争议」= 挂在一条还开着的冲突的任一端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.mdindex 2d334cca..b5742f5b 100644--- a/docs/decisions/0025-governance-reads-the-ledger-before-it-decides.md+++ b/docs/decisions/0025-governance-reads-the-ledger-before-it-decides.md@@ -1,6 +1,6 @@# 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+- **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 3 (UI) implemented: the switch in base settings, the Agent queue with its rows and answers, the proposal chip on a duplicate card whose Merge / Keep answers the proposal, the Agent section on the Overview · cut 2 (a tool-using loop with a `defer` action) 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.@@ -64,7 +64,6 @@ Duplicates that the agent proposed on carry the reason code `proposed`; pairs it## 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.diff --git a/docs/decisions/README.md b/docs/decisions/README.mdindex 8ecb2b51..fdc7bcc1 100644--- a/docs/decisions/README.md+++ b/docs/decisions/README.md@@ -48,7 +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 |+| 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 switch, the Agent queue, the proposal chip and the Overview section in the UI · the tool-using loop and the fuse are open |## Not a decision recorddiff --git a/web/src/api.ts b/web/src/api.tsindex 034ba663..041653db 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -107,6 +107,9 @@ export interface Kb {materialize_inferences: boolean;/** 抽取结束自动排一轮类型消解(只自动落地子树内精化的那一档) */auto_type_resolution: boolean;+ /** 治理开关(0025,缺省关):agent 按先进先出过等人的重复对,先读台账里人的+ * 先例再裁;打开就开始,关掉就停 */+ governance: boolean;/** 多久重推一次(分钟)。事实持续在变,只靠手点会让派生一直是缺的 */inference_interval_minutes: number;/** 上次推完的时间 */@@ -436,7 +439,9 @@ export type ReviewQueue =| "mappings"| "violations"| "defects"- | "merges";+ | "merges"+ // agent 的每一笔(0025):建议、自动裁决与人的回答+ | "agent";/** 重复项按两边类型的关系筛:any 全部;same 两边都有类型且相等;conflict 都有且不等 */export type ReviewTypeFilter = "any" | "same" | "conflict";@@ -456,6 +461,10 @@ export interface ReviewCounts {violations: number;defects: number;merges: number;+ /** agent 写下、等人回答的建议(0025) */+ agent: number;+ /** agent 的全部记录(Agent 队列翻页用) */+ agent_rows: number;}/** 类型消解的一条建议:一个待精化的实体、送去检索的画像、以及候选类。@@ -518,6 +527,14 @@ export interface ReviewSide {top_facts: string[];}+/** agent 在一对上留下的、还开着的建议(0025);卡片上的裁决就是对它的回答 */+export interface ReviewProposal {+ id: string;+ action: "merge" | "keep" | "unsure";+ confidence: number;+ reason: string | null;+}+export interface ReviewItem {id: string;score: number;@@ -526,8 +543,40 @@ export interface ReviewItem {created_at: string;left: ReviewSide;right: ReviewSide;+ proposal: ReviewProposal | null;}+/** agent 的一笔(0025):看了哪一对、想怎么办、凭什么、人怎么答的 */+export interface AgentDecision {+ id: string;+ run_id: string;+ target_kind: "review";+ target_id: string;+ action: "merge" | "keep" | "unsure";+ confidence: number;+ reason: string | null;+ /** 它被给看的先例:同对 / 同名 / 撤回各一条一条,类型对的习惯是一条汇总 */+ precedents: AgentPrecedent[];+ status: "proposed" | "applied" | "accepted" | "overridden" | "reverted" | "superseded";+ merge_id: string | null;+ created_at: string;+ decided_at: string | null;+ decided_by_name: string | null;+ left: string | null;+ right: string | null;+}++export type AgentPrecedent =+ | {+ family: "same_pair" | "same_name" | "revert";+ event_id: string;+ action: string;+ left: string;+ right: string;+ at: string;+ }+ | { family: "type_pair"; merged: number; kept: number; reverted: number };+/** 数据映射的一条口径:业务概念 → 数据资产定义(见 docs/decisions/0011)。** 字段是列而不是 JSON 里的键——从前它是一条 `mapped_to` 事实,@@ -718,8 +767,19 @@ export interface DecidedWindow {by_actor: { actor_id: string | null; label: string | null; count: number }[];}+/** 一个时间窗口里 agent 写下的行,按现在的状态数 */+export interface AgentWindow {+ applied: number;+ proposed: number;+ accepted: number;+ overridden: number;+ reverted: number;+}+/** 审核台总览(#377):等着办的、办过的、库的成色。与左栏计数同一套口径 */export interface ReviewSummary {+ /** agent 在这个库里做过什么(0025) */+ agent: { open: number; last_7d: AgentWindow; last_30d: AgentWindow };waiting: Record<"pending" | "duplicates" | "conflicts" | "unconfirmed" | "lowconf" | "violations" | "defects",QueueWait@@ -2117,6 +2177,13 @@ export const api = {}),reviewSummary: (kbId: string) =>request<ReviewSummary>(`/api/v1/kbs/${kbId}/review/summary`),+ /** 回答 agent 的一笔(0025):merge / keep 答一条建议,revert 撤回一条自动合并,+ * merge 也能推翻一条自动分开。走的是人的裁决路径,成为新先例 */+ agentAnswer: (kbId: string, decisionId: string, action: "merge" | "keep" | "revert") =>+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/agent/${decisionId}`, {+ method: "POST",+ body: JSON.stringify({ action }),+ }),reviewHistory: (kbId: string, page: number, per = 20) =>request<{ events: ReviewHistoryEvent[]; total: number }>(`/api/v1/kbs/${kbId}/review/history?page=${page}&per=${per}`,diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex 9dc0775f..4f7707ca 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -1492,7 +1492,39 @@ export const en = {railDefects: "Ontology",railDecisions: "Decisions",railMerges: "Merges",+ railAgent: "Agent",categoryEmpty: "This queue is clear.",+ // agent 的队列(0025)+ agentTitle: "Agent",+ agentHint:+ "What the agent proposed or decided for this base, from the decisions people made here before. Answering here is your decision, and it becomes precedent for the next look.",+ agentEmpty: "The agent has not looked at anything yet.",+ agentActions: { merge: "Merge", keep: "Keep apart", unsure: "Unsure" } as Record<string, string>,+ agentStatus: {+ proposed: "Proposed",+ applied: "Applied",+ accepted: "Accepted",+ overridden: "Overridden",+ reverted: "Reverted",+ superseded: "Superseded",+ } as Record<string, string>,+ agentSuggests: (action: string, pct: number) => `Agent: ${action.toLowerCase()} · ${pct}%`,+ agentPrecedents: (n: number) => (n === 1 ? "1 precedent" : `${n} precedents`),+ agentPrecedentMerged: "merged by a person",+ agentPrecedentKept: "kept apart by a person",+ agentPrecedentReverted: "merge reverted by a person",+ agentPrecedentHabit: (merged: number, kept: number, reverted: number) =>+ `This type pair in this base: ${merged} merged, ${kept} kept apart, ${reverted} reverted`,+ agentAnsweredBy: (name: string, date: string) => `${name} · ${date}`,+ overviewAgent: "Agent",+ overviewAgentOff: "Governance is off for this base.",+ overviewAgentSettings: "Turn it on in settings",+ overviewAgentOpen: "Waiting for your answer",+ overviewAgentApplied: "Decided on its own",+ overviewAgentAccepted: "Proposals you accepted",+ overviewAgentOverridden: (n: number) =>+ n === 1 ? "1 overridden, last 30 days" : `${n} overridden, last 30 days`,+ overviewAgentReverted: "Reverted by you",// 总览(#377)overviewTitle: "Overview",overviewHint:@@ -1742,6 +1774,9 @@ export const en = {autoResolveTypes: "Resolve entity types after extraction",autoResolveTypesNote:"After each document is extracted, run a round of type resolution on entities the engine has not looked at yet. Only refinements within the current class are applied on their own — a re-classification across the tree still waits for you on the Ontology page. Every batch is listed there and can be undone.",+ governance: "Let the agent work the duplicates queue",+ governanceNote:+ "First in, first out. Before deciding a pair the agent reads what people in this base decided on the same names and the same kinds of pairs. It merges only where that history supports it, keeps apart on confidence, and leaves a proposal for everything else. Every decision is listed under Agent on the Review page and can be reverted. Turning this off stops the queue.",inferEvery: "Re-derive every",minutes: "minutes",lastInference: (when: string) => `last run ${when}`,diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex 215178bc..6d9ea974 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -1304,7 +1304,37 @@ export const zh: Strings = {railDefects: "本体",railDecisions: "决定",railMerges: "合并",+ railAgent: "Agent",categoryEmpty: "这个队列是空的。",+ agentTitle: "Agent",+ agentHint:+ "agent 依据这个库里人以前的决定,提议或裁决了什么。在这里回答就是你的决定,也会成为它下一次的先例。",+ agentEmpty: "agent 还没看过任何一对。",+ agentActions: { merge: "合并", keep: "分开", unsure: "说不准" } as Record<string, string>,+ agentStatus: {+ proposed: "建议",+ applied: "已裁",+ accepted: "已接受",+ overridden: "已改判",+ reverted: "已撤回",+ superseded: "已过时",+ } as Record<string, string>,+ agentSuggests: (action, pct) => `agent 建议${action} · ${pct}%`,+ agentPrecedents: (n) => `${n} 条先例`,+ agentPrecedentMerged: "人合过",+ agentPrecedentKept: "人分开过",+ agentPrecedentReverted: "人撤回过合并",+ agentPrecedentHabit: (merged, kept, reverted) =>+ `这种类型对在本库:合 ${merged}、分 ${kept}、撤回 ${reverted}`,+ agentAnsweredBy: (name, date) => `${name} · ${date}`,+ overviewAgent: "Agent",+ overviewAgentOff: "这个库的治理没有打开。",+ overviewAgentSettings: "去设置里打开",+ overviewAgentOpen: "等你回答",+ overviewAgentApplied: "自己裁的",+ overviewAgentAccepted: "你接受的建议",+ overviewAgentOverridden: (n) => `改判 ${n},近 30 天`,+ overviewAgentReverted: "你撤回的",overviewTitle: "总览",overviewHint: "这个库要你做什么:有多少在等、等了多久、办过什么、还有多少是暂定的。",overviewWaiting: "等着办的",@@ -1520,6 +1550,9 @@ export const zh: Strings = {autoResolveTypes: "抽取后自动消解实体类型",autoResolveTypesNote:"每篇文档抽完,对引擎还没看过的实体跑一轮类型消解。只有在现类子树里精化的才自动落地,跨轴的改判仍留在本体页等你。每一批都列在本体页,随时可以撤回。",+ governance: "让 agent 处理重复项队列",+ governanceNote:+ "先进先出。裁一对之前,agent 先读这个库里的人对同样的名字、同样的类型对做过什么决定:有先例撑着才合并,有把握就分开,其余的写成建议留给你。每一笔都列在审核页的 Agent 里,可以撤回。关掉,队列就停。",inferEvery: "每隔",minutes: "分钟重推",lastInference: (when: string) => `上次 ${when}`,diff --git a/web/src/pages/KbSettings.tsx b/web/src/pages/KbSettings.tsxindex 51a761f2..9b2f26fc 100644--- a/web/src/pages/KbSettings.tsx+++ b/web/src/pages/KbSettings.tsx@@ -90,6 +90,8 @@ export function KbSettings() {const [materialize, setMaterialize] = useState(false);// 类型消解自动跑(0016 C2):只自动落地子树内精化的那一档const [autoResolve, setAutoResolve] = useState(false);+ // 治理(0025):**缺省关**——它会合并实体,还没在哪个库上量过;打开就开始,关掉就停+ const [governance, setGovernance] = useState(false);const [inferMins, setInferMins] = useState(60);const [ontoLang, setOntoLang] = useState<"en" | "zh">("en");const [confirmingDelete, setConfirmingDelete] = useState(false);@@ -103,6 +105,7 @@ export function KbSettings() {setAutoExtend(kb.data.auto_extend_ontology);setMaterialize(kb.data.materialize_inferences);setAutoResolve(kb.data.auto_type_resolution);+ setGovernance(kb.data.governance);setInferMins(kb.data.inference_interval_minutes);setOntoLang(kb.data.ontology_lang);}@@ -122,6 +125,7 @@ export function KbSettings() {auto_extend_ontology: autoExtend,materialize_inferences: materialize,auto_type_resolution: autoResolve,+ governance,inference_interval_minutes: inferMins,ontology_lang: ontoLang,}),@@ -269,6 +273,16 @@ export function KbSettings() {label={S.kbset.autoResolveTypes}hint={S.kbset.autoResolveTypesNote}/>+ {/* 治理(0025):agent 按先进先出过等人的重复对,先读台账里人的先例再裁。+ 说明里要讲清三件事:读的是这个库的人的决定、合并要有先例撑着、+ 关掉队列就停 */}+ <Checkbox+ className="pt-1"+ checked={governance}+ onChange={(e) => setGovernance(e.target.checked)}+ label={S.kbset.governance}+ hint={S.kbset.governanceNote}+ />{/* 重推间隔。**只在开着的时候露出来**——关着时它不影响任何事,摆在那里只会让人以为设了就会推 */}{materialize && (diff --git a/web/src/pages/Review.tsx b/web/src/pages/Review.tsxindex 448852fc..ddd8572b 100644--- a/web/src/pages/Review.tsx+++ b/web/src/pages/Review.tsx@@ -4,6 +4,8 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { useNavigate, useSearch } from "@tanstack/react-router";import {api,+ type AgentDecision,+ type AgentPrecedent,type AxiomViolation,type ReviewQueue,type ReviewTypeFilter,@@ -30,6 +32,7 @@ import {type ChipTone,cn,Input,+ LinkButton,Pager,RAIL_CLS,RailItem,@@ -148,6 +151,15 @@ function DuplicateCard({)}</Chip>)}+ {/* agent 的建议(0025):这里的 Merge / Keep 就是对它的回答 */}+ {item.proposal && (+ <Chip tone="info" title={item.proposal.reason ?? undefined}>+ {S.review.agentSuggests(+ S.review.agentActions[item.proposal.action],+ Math.round(item.proposal.confidence * 100),+ )}+ </Chip>+ )}{reasonCode !== "namesake" && (<span className="text-small text-ink-3">{S.review.similarity(Math.round(item.score * 100))}@@ -442,6 +454,113 @@ function MergeRow({);}+/* ---------- agent 的一笔(0025) ---------- */++const AGENT_ACTION_TONE: Record<AgentDecision["action"], ChipTone> = {+ merge: "violet",+ keep: "neutral",+ unsure: "warn",+};++const AGENT_STATUS_TONE: Record<AgentDecision["status"], ChipTone> = {+ proposed: "warn",+ applied: "info",+ accepted: "success",+ overridden: "neutral",+ reverted: "danger",+ superseded: "neutral",+};++/** 一条先例写成一句话;类型对的习惯是汇总,单独一句 */+function precedentText(p: AgentPrecedent): string {+ if (p.family === "type_pair")+ return S.review.agentPrecedentHabit(p.merged, p.kept, p.reverted);+ const verb =+ p.action === "merge.revert"+ ? S.review.agentPrecedentReverted+ : p.action === "review.keep"+ ? S.review.agentPrecedentKept+ : S.review.agentPrecedentMerged;+ return `${p.left} ≟ ${p.right} · ${verb} · ${p.at.slice(0, 10)}`;+}++function AgentRow({+ d,+ busy,+ onAnswer,+}: {+ d: AgentDecision;+ busy: boolean;+ onAnswer: (action: "merge" | "keep" | "revert") => void;+}) {+ const [open, setOpen] = useState(false);+ const precedents = d.precedents ?? [];+ return (+ <div className="glass rounded-xl px-4 py-3">+ <div className="flex items-center gap-3">+ <Chip tone={AGENT_ACTION_TONE[d.action]}>{S.review.agentActions[d.action]}</Chip>+ <span className="text-body text-ink-2 truncate min-w-0">+ {d.left ?? "?"} ≟ {d.right ?? "?"}+ </span>+ <span className="u-num text-small text-ink-3 shrink-0">+ {Math.round(d.confidence * 100)}%+ </span>+ <Chip tone={AGENT_STATUS_TONE[d.status]} className="ml-auto shrink-0">+ {S.review.agentStatus[d.status]}+ </Chip>+ </div>+ {(d.reason || precedents.length > 0) && (+ <div className="mt-1 flex items-center gap-3 text-small text-ink-3">+ {d.reason && <span className="truncate min-w-0">{d.reason}</span>}+ {precedents.length > 0 && (+ <LinkButton className="shrink-0" onClick={() => setOpen((v) => !v)}>+ {S.review.agentPrecedents(precedents.length)}+ </LinkButton>+ )}+ </div>+ )}+ {open && precedents.length > 0 && (+ <ul className="mt-2 space-y-1 border-t border-line pt-2 text-small text-ink-3">+ {precedents.map((p, i) => (+ <li key={i} className="truncate">+ {precedentText(p)}+ </li>+ ))}+ </ul>+ )}+ <div className="mt-2 flex items-center gap-2">+ <span className="text-fine text-ink-3">+ {d.decided_by_name+ ? S.review.agentAnsweredBy(d.decided_by_name, (d.decided_at ?? d.created_at).slice(0, 10))+ : d.created_at.slice(0, 10)}+ </span>+ <div className="ml-auto flex gap-2 shrink-0">+ {d.status === "proposed" && (+ <>+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => onAnswer("keep")}>+ {S.review.keep}+ </Button>+ <Button variant="primary" size="sm" disabled={busy} onClick={() => onAnswer("merge")}>+ {S.review.merge}+ </Button>+ </>+ )}+ {d.status === "applied" && d.action === "merge" && (+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => onAnswer("revert")}>+ {S.review.revert}+ </Button>+ )}+ {d.status === "applied" && d.action === "keep" && (+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => onAnswer("merge")}>+ {S.review.merge}+ </Button>+ )}+ </div>+ </div>+ </div>+ );+}+/* ---------- 决策台账行 ---------- */const DECISION_TONE: Record<string, ChipTone> = {@@ -804,6 +923,9 @@ type Sel =| "violations"// 本体自己的自相矛盾。**与 violations 分开**:那一档看事实,这一档只看定义| "defects"+ // agent 的每一笔(0025):建议等人答,自动裁的可撤。它不是七档之一——+ // 七档问「这条知识对不对」,这一档问「机器替你办的对不对」+ | "agent"| "decisions"| "merges";@@ -817,6 +939,7 @@ const QUEUE_FETCHED: ReviewQueue[] = ["violations","defects","merges",+ "agent",];const QUEUE_ORDER: Sel[] = [@@ -841,6 +964,7 @@ const PAGE_SIZE: Record<Paged, number> = {defects: FACT_PAGE,merges: MERGE_PAGE,decisions: 20,+ agent: 20,};function RailHeader({ label }: { label: string }) {@@ -860,8 +984,11 @@ export function Review() {const navigate = useNavigate();// 面板的争议 chip 带着 queue / item 跳过来:先落到那一档,再把那张卡点亮const search = useSearch({ from: "/app/kb/$kbId/review" });+ // 深链接认七档与 agent 那一档(0025 的告警会指过来);别的落到总览const [sel, setSel] = useState<Sel | null>(- QUEUE_ORDER.includes(search.queue as Sel) ? (search.queue as Sel) : null,+ QUEUE_ORDER.includes(search.queue as Sel) || search.queue === "agent"+ ? (search.queue as Sel)+ : null,);const [page, setPage] = useState(0);// 重复项的类型筛选与批量选中(#428)。选中集合按页清:翻页、换档、换筛选@@ -921,6 +1048,13 @@ export function Review() {api.decideReview(kb!.id, id, action),onSettled: invalidate,});+ // 回答 agent 的一笔(0025):走人的裁决路径,成为下一轮的先例+ const agentAnswer = useMutation({+ mutationFn: ({ id, action }: { id: string; action: "merge" | "keep" | "revert" }) =>+ api.agentAnswer(kb!.id, id, action),+ onError: (e) => toast.error((e as Error).message),+ onSettled: invalidate,+ });// 批量裁决:一批一个动作,回来逐条说成没成;没成的留在列表里,成了的消失const batch = useMutation({mutationFn: ({ ids, action }: { ids: string[]; action: "merge" | "keep" }) =>@@ -1047,6 +1181,7 @@ export function Review() {defects: c?.defects ?? 0,merges: c?.merges ?? 0,decisions: history.data?.total ?? 0,+ agent: c?.agent ?? 0,};// 当前这一档的一页。**服务端已经切好了**,这里只按档收窄类型——// 收窄错了会在渲染时露馅,而不是悄悄显示空列表@@ -1058,6 +1193,7 @@ export function Review() {const asViolations = () => rows as AxiomViolation[];const asDefects = () => rows as OntologyDefect[];const asMerges = () => rows as MergeLog[];+ const asAgent = () => rows as AgentDecision[];const queueEmpty = QUEUE_ORDER.every((k) => counts[k] === 0);// 没带 ?queue= 进来就落在总览上——从前是「第一个非空队列」,那等于替人@@ -1090,6 +1226,7 @@ export function Review() {defects: { title: S.review.defects, hint: S.review.defectsHint },decisions: { title: S.review.decisionsTitle, hint: S.review.decisionsHint },merges: { title: S.review.mergeHistory, hint: null },+ agent: { title: S.review.agentTitle, hint: S.review.agentHint },};return (@@ -1160,6 +1297,14 @@ export function Review() {>{S.review.railDefects}</RailItem>+ {/* agent 的队列(0025):徽标是等人回答的建议数 */}+ <RailItem+ active={active === "agent"}+ count={counts.agent}+ onClick={() => select("agent")}+ >+ {S.review.railAgent}+ </RailItem></div><RailHeader label={S.review.tabHistory} /><div className="px-3 space-y-1">@@ -1239,7 +1384,14 @@ export function Review() {{(summary.error as Error).message}</p>) : summary.data ? (- <ReviewOverview summary={summary.data} onPick={select} />+ <ReviewOverview+ summary={summary.data}+ governance={kb?.governance ?? false}+ onPick={select}+ onSettings={() =>+ navigate({ to: "/kb/$kbId/settings", params: { kbId } })+ }+ />) : null)}{active === "duplicates" && counts.duplicates > 0 && (@@ -1516,6 +1668,37 @@ export function Review() {</div>)}+ {active === "agent" &&+ ((c?.agent_rows ?? 0) === 0 ? (+ <div className="glass rounded-xl p-8 text-center text-body text-ink-3">+ {S.review.agentEmpty}+ {!kb?.governance && (+ <>+ {" "}+ {S.review.overviewAgentOff}{" "}+ <LinkButton+ onClick={() =>+ navigate({ to: "/kb/$kbId/settings", params: { kbId } })+ }+ >+ {S.review.overviewAgentSettings}+ </LinkButton>+ </>+ )}+ </div>+ ) : (+ <div className="space-y-2">+ {asAgent().map((d) => (+ <AgentRow+ key={d.id}+ d={d}+ busy={agentAnswer.isPending && agentAnswer.variables?.id === d.id}+ onAnswer={(action) => agentAnswer.mutate({ id: d.id, action })}+ />+ ))}+ </div>+ ))}+{active === "merges" &&(counts.merges === 0 ? (<div className="glass rounded-xl p-8 text-center text-body text-ink-3">@@ -1552,7 +1735,7 @@ export function Review() {{/* 单一分页:queue/merges 走客户端切片,decisions 服务端分页;总览没有页 */}{active !== "decisions" && active !== "overview" && (<Pager- total={counts[active]}+ total={active === "agent" ? (c?.agent_rows ?? 0) : counts[active]}pageSize={PAGE_SIZE[active]}page={page}onPage={setPage}diff --git a/web/src/pages/ReviewOverview.tsx b/web/src/pages/ReviewOverview.tsxindex 62ed4812..1a21fef6 100644--- a/web/src/pages/ReviewOverview.tsx+++ b/web/src/pages/ReviewOverview.tsx@@ -89,13 +89,18 @@ function DailyBars({ days }: { days: ReviewSummary["decided"]["daily"] }) {export function ReviewOverview({summary,+ governance,onPick,+ onSettings,}: {summary: ReviewSummary;+ /** 这个库的治理开关(0025):关着时 Agent 那一段说明去哪里打开 */+ governance: boolean;/** 点某一档的「去处理」:落到左栏那一档 */- onPick: (queue: WaitingQueue) => void;+ onPick: (queue: WaitingQueue | "agent") => void;+ onSettings: () => void;}) {- const { waiting, decided, health } = summary;+ const { waiting, decided, health, agent } = summary;const waitingTotal = WAITING.reduce((n, w) => n + waiting[w.key].count, 0);const share = (n: number) =>health.facts === 0 ? "—" : `${Math.round((n / health.facts) * 1000) / 10}%`;@@ -180,6 +185,46 @@ export function ReviewOverview({)}</section>+ {/* agent 做过的(0025):开着的建议、自动裁了还站着的、人接受 / 改判 / 撤回的。+ 开关关着且什么都没做过时只说一句去哪里打开,不摆四个零 */}+ <section>+ <SectionHead>{S.review.overviewAgent}</SectionHead>+ {!governance && (+ <p className="mb-3 text-small text-ink-3">+ {S.review.overviewAgentOff}{" "}+ <LinkButton onClick={onSettings}>{S.review.overviewAgentSettings}</LinkButton>+ </p>+ )}+ {(governance || agent.open > 0 || agent.last_30d.applied > 0) && (+ <div className="grid grid-cols-2 gap-3 md:grid-cols-4">+ <Stat+ value={agent.open}+ label={S.review.overviewAgentOpen}+ action={+ agent.open > 0+ ? { label: S.review.overviewOpen, onClick: () => onPick("agent") }+ : undefined+ }+ />+ <Stat+ value={agent.last_7d.applied}+ label={S.review.overviewAgentApplied}+ note={S.review.overviewLast7}+ />+ <Stat+ value={agent.last_30d.accepted}+ label={S.review.overviewAgentAccepted}+ note={S.review.overviewAgentOverridden(agent.last_30d.overridden)}+ />+ <Stat+ value={agent.last_30d.reverted}+ label={S.review.overviewAgentReverted}+ note={S.review.overviewLast30}+ />+ </div>+ )}+ </section>+{/* 库的成色 */}<section><SectionHead>{S.review.overviewHealth}</SectionHead>