World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Two reverts in a week turn the agent off (0025, fourth cut) (#439)
WaylandYange39ed625e0f5
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rsindex c3a59847..3e61c253 100644--- a/crates/utopia-core/src/models.rs+++ b/crates/utopia-core/src/models.rs@@ -919,6 +919,8 @@ pub struct KnowledgeBase {/// 治理开关(0025,缺省关):开着,govern 任务按先进先出过等人的重复对,/// 先读台账里人的先例再裁;关掉,任务在两簇之间看到就停pub governance: bool,+ /// 这次打开治理的时刻;保险丝只数它之后的撤回(0025 决定 9)+ pub governance_since: Option<DateTime<Utc>>,/// 多久重推一次(分钟)。见 `knowledge_bases.inference_interval_minutes`pub inference_interval_minutes: i32,/// 上次推完的时间。**答的是「上次看过没有」,不是「上次改过没有」**diff --git a/crates/utopia-server/src/api/review_routes.rs b/crates/utopia-server/src/api/review_routes.rsindex 6225b6cc..134252fa 100644--- a/crates/utopia-server/src/api/review_routes.rs+++ b/crates/utopia-server/src/api/review_routes.rs@@ -410,6 +410,8 @@ pub async fn agent_answer(json!({ "source": l, "target": r, "agent_decision": decision_id }),).await;+ // 撤回 agent 的合并到了两次:保险丝+ crate::governance::fuse(&state, kb_id).await;}("applied", "merge") if d.action == "keep" => {let (left_id, right_id): (Uuid, Uuid) = sqlx::query_as(@@ -628,6 +630,8 @@ pub async fn revert_merge().await;}+ // 撤的是 agent 自己裁的合并:那一行记成 reverted,并看保险丝(0025)+ crate::governance::after_revert(&state, kb_id, merge_id, user.id).await;state.emit_review(kb_id);Ok(Json(json!({ "ok": true })))}diff --git a/crates/utopia-server/src/governance.rs b/crates/utopia-server/src/governance.rsindex c28be980..cebe088a 100644--- a/crates/utopia-server/src/governance.rs+++ b/crates/utopia-server/src/governance.rs@@ -15,12 +15,14 @@use crate::llm_util;use crate::state::AppState;+use chrono::{Duration, Utc};use serde_json::{json, Value};use std::collections::HashMap;-use utopia_core::models::{LlmSettings, ReviewItem};+use utopia_core::models::{LlmSettings, ReviewItem, Role};use utopia_core::AppError;use utopia_extract::governor::{self, Step};use utopia_llm::{tool_result_message, LlmClient};+use utopia_store::alerts;use utopia_store::governance::{self as gov, Gate, NewDecision, Precedents, AUTO_CONF};use uuid::Uuid;@@ -517,6 +519,76 @@ async fn audit(ctx: &Ctx<'_>, action: &str, item: &ReviewItem, conf: f32, id: Uu.await;}+/// 保险丝(0025 决定 9):这次打开以来、七天之内,人撤回 agent 的自动合并到了两次,+/// 开关自动关掉,发一条告警,台账记一笔。它替人做主做错了两回,该停下来等人再开;+/// 人再打开时 governance_since 更新,之前的撤回不再算+pub async fn fuse(state: &AppState, kb_id: Uuid) {+ let pool = &state.pool;+ let kb = match utopia_store::kbs::get(pool, kb_id).await {+ Ok(kb) if kb.governance => kb,+ _ => return,+ };+ let window = Utc::now() - Duration::days(gov::FUSE_WINDOW_DAYS);+ let since = kb.governance_since.map_or(window, |s| s.max(window));+ let reverts = match gov::reverts_since(pool, kb_id, since).await {+ Ok(n) => n,+ Err(e) => {+ tracing::warn!(%kb_id, error = %e, "治理:数撤回失败");+ return;+ }+ };+ if reverts < gov::FUSE_REVERTS {+ return;+ }+ match gov::trip(pool, kb_id).await {+ Ok(true) => {}+ Ok(false) => return,+ Err(e) => {+ tracing::warn!(%kb_id, error = %e, "治理:关开关失败");+ return;+ }+ }+ tracing::warn!(%kb_id, reverts, "治理:保险丝跳了,开关已关");+ if let Err(e) = alerts::raise(+ pool,+ alerts::NewAlert {+ kb_id: Some(kb_id),+ severity: "warning",+ kind: alerts::kind::GOVERNANCE_TRIPPED,+ min_role: Role::Editor,+ subject_type: Some("kb"),+ subject_id: Some(kb_id),+ detail: json!({+ "kb": kb.name, "reverts": reverts, "window_days": gov::FUSE_WINDOW_DAYS,+ }),+ },+ )+ .await+ {+ tracing::warn!(%kb_id, error = %e, "上报 governance.tripped 失败");+ }+ let _ = utopia_store::audit::record_opt(+ pool,+ Some(kb_id),+ None,+ "kb.updated",+ "kb",+ Some(kb_id),+ json!({ "governance": false, "via": "fuse", "reverts": reverts }),+ )+ .await;+ state.emit_review(kb_id);+}++/// 人从合并历史撤回了一条合并:是 agent 自己裁的就记成 reverted,然后看保险丝+pub async fn after_revert(state: &AppState, kb_id: Uuid, merge_id: Uuid, user_id: Uuid) {+ match gov::settle_by_merge(&state.pool, kb_id, merge_id, user_id).await {+ Ok(Some(_)) => fuse(state, kb_id).await,+ Ok(None) => {}+ Err(e) => tracing::warn!(%kb_id, merge = %merge_id, error = %e, "治理:记撤回失败"),+ }+}+/// 人裁了一对之后:这一对上开着的建议就是被回答了(与建议相同是接受,不同是改判);/// 同名或同实体的对上的建议过时、那些对回到队列;开关开着就排一轮。/// 人批量分开三对张伟,agent 顺着同一簇把剩下的照办——#428 要的自动处理就是这一步。diff --git a/crates/utopia-store/src/alerts.rs b/crates/utopia-store/src/alerts.rsindex d4bbfe97..dca115ee 100644--- a/crates/utopia-store/src/alerts.rs+++ b/crates/utopia-store/src/alerts.rs@@ -54,6 +54,10 @@ pub mod kind {/// 库级:映射探索跑完了,一条口径都没提出来。`severity = info`,`min_role = editor`——/// 不是故障,是"你在等的那件事没有结果",而页面上没有别的地方能说这句话(#223)pub const MAPPING_EXPLORATION_EMPTY: &str = "mapping.exploration_empty";+ /// 库级:治理的保险丝跳了——七天内人撤回 agent 的自动合并两次,开关自动关掉+ /// (0025 决定 9)。`severity = warning`,`min_role = editor`:裁重复项的人就是+ /// 该去看 Agent 队列、决定要不要再打开的人+ pub const GOVERNANCE_TRIPPED: &str = "governance.tripped";}/// 一次故障。打包成结构体不只是为了参数个数——调用点写 `severity: "error"`diff --git a/crates/utopia-store/src/governance.rs b/crates/utopia-store/src/governance.rsindex b0dabeb7..d1c6fc49 100644--- a/crates/utopia-store/src/governance.rs+++ b/crates/utopia-store/src/governance.rs@@ -600,6 +600,57 @@ pub async fn supersede_siblings(pool: &PgPool, kb_id: Uuid, review_id: Uuid) ->Ok(n)}+/// 保险丝(0025 决定 9):多少天里撤回几次就跳+pub const FUSE_WINDOW_DAYS: i64 = 7;+pub const FUSE_REVERTS: i64 = 2;++/// 从某一刻起,人撤回了 agent 的自动合并几次+pub async fn reverts_since(pool: &PgPool, kb_id: Uuid, since: DateTime<Utc>) -> AppResult<i64> {+ let n = sqlx::query_scalar(+ "SELECT count(*) FROM agent_decisions+ WHERE kb_id = $1 AND status = 'reverted' AND decided_at >= $2",+ )+ .bind(kb_id)+ .bind(since)+ .fetch_one(pool)+ .await?;+ Ok(n)+}++/// 保险丝跳闸:开关开着就关掉。回 true 表示这一次真的关了——告警只发一次+pub async fn trip(pool: &PgPool, kb_id: Uuid) -> AppResult<bool> {+ let n = sqlx::query(+ "UPDATE knowledge_bases SET governance = FALSE, updated_at = now()+ WHERE id = $1 AND governance",+ )+ .bind(kb_id)+ .execute(pool)+ .await?+ .rows_affected();+ Ok(n > 0)+}++/// 人从合并历史撤回了一条合并:如果那是 agent 自己裁的,那一行记成 reverted。+/// 回那一行的 id;不是 agent 的合并就是 None+pub async fn settle_by_merge(+ pool: &PgPool,+ kb_id: Uuid,+ merge_id: Uuid,+ user_id: Uuid,+) -> AppResult<Option<Uuid>> {+ let id = sqlx::query_scalar(+ "UPDATE agent_decisions SET status = 'reverted', decided_at = now(), decided_by = $3+ WHERE kb_id = $1 AND merge_id = $2 AND status = 'applied'+ RETURNING id",+ )+ .bind(kb_id)+ .bind(merge_id)+ .bind(user_id)+ .fetch_optional(pool)+ .await?;+ Ok(id)+}+/// 开关开着、队列里还有 agent 没看过的对的库:定时扫描用pub async fn due(pool: &PgPool) -> AppResult<Vec<Uuid>> {let ids = sqlx::query_scalar(&format!(diff --git a/crates/utopia-store/src/kbs.rs b/crates/utopia-store/src/kbs.rsindex 2282a9a2..20f23bc1 100644--- a/crates/utopia-store/src/kbs.rs+++ b/crates/utopia-store/src/kbs.rs@@ -122,6 +122,9 @@ pub async fn update(inference_interval_minutes = COALESCE($8, inference_interval_minutes),auto_type_resolution = COALESCE($9, auto_type_resolution),governance = COALESCE($10, governance),+ -- 从关到开的那一刻记下来:保险丝只数它之后的撤回。SET 右边读的是旧值+ governance_since = CASE WHEN $10 IS TRUE AND NOT governance THEN now()+ ELSE governance_since END,updated_at = now()WHERE id = $1 RETURNING *",)diff --git a/crates/utopia-store/tests/a_governor_reads_the_ledger.rs b/crates/utopia-store/tests/a_governor_reads_the_ledger.rsindex e2e78b6b..4de9b784 100644--- a/crates/utopia-store/tests/a_governor_reads_the_ledger.rs+++ b/crates/utopia-store/tests/a_governor_reads_the_ledger.rs@@ -425,6 +425,65 @@ async fn run(pool: &PgPool, s: &Seed) -> anyhow::Result<()> {assert_eq!(d.trace[0]["tool"], "facts");assert_eq!(governance::loop_calls_today(pool, s.kb).await?, 3);+ // 保险丝(第四刀):撤回的次数从某一刻数起;跳闸只在开着时发生、只发生一次;+ // 合并历史里撤回 agent 的合并,那一行也记成 reverted+ let (a, b) = (alike_id(pool, s.kb).await?, {+ let id: Uuid = sqlx::query_scalar(+ "SELECT id FROM entities WHERE kb_id = $1 AND canonical_name = 'Someone' LIMIT 1",+ )+ .bind(s.kb)+ .fetch_one(pool)+ .await?;+ id+ });+ let merge_id =+ utopia_store::resolution::merge_entities(pool, s.kb, a, b, None, "governed|0.90").await?;+ let applied = governance::record(+ pool,+ s.kb,+ NewDecision {+ run_id,+ target_id: s.orion,+ action: "merge",+ confidence: 0.9,+ reason: None,+ precedents: serde_json::json!([]),+ status: "applied",+ merge_id: Some(merge_id),+ question: None,+ trace: serde_json::json!([]),+ calls: 0,+ },+ )+ .await?;+ let an_hour_ago = Utc::now() - Duration::hours(1);+ assert_eq!(governance::reverts_since(pool, s.kb, an_hour_ago).await?, 0);+ assert_eq!(+ governance::settle_by_merge(pool, s.kb, Uuid::now_v7(), s.user).await?,+ None,+ "不是 agent 的合并:没有行可记"+ );+ assert_eq!(+ governance::settle_by_merge(pool, s.kb, merge_id, s.user).await?,+ Some(applied)+ );+ assert_eq!(+ governance::get(pool, s.kb, applied).await?.status,+ "reverted"+ );+ assert_eq!(governance::reverts_since(pool, s.kb, an_hour_ago).await?, 1);+ assert_eq!(+ governance::reverts_since(pool, s.kb, Utc::now() + Duration::hours(1)).await?,+ 0,+ "只数那一刻之后的"+ );+ assert!(governance::trip(pool, s.kb).await?, "开着:关了");+ assert!(!governance::trip(pool, s.kb).await?, "已经关了:不再算跳闸");+ sqlx::query("UPDATE knowledge_bases SET governance = TRUE WHERE id = $1")+ .bind(s.kb)+ .execute(pool)+ .await?;+// 定时扫描:开关开着且有没看过的对 → 在;关了 → 不在assert!(governance::due(pool).await?.contains(&s.kb));sqlx::query("UPDATE knowledge_bases SET governance = FALSE WHERE id = $1")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 f47e3bc2..e8362bee 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 (#434) · 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, #437) 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 implemented: migration 0036 adds `question`, `trace` and `calls` to `agent_decisions`; `governor` in the extract crate holds the tools, the opening and the step reader; `investigate` in the server job runs the loop for pairs the batch could not settle (decision 8) · cut 4 (the fuse) is open, see the last section+- **Status**: cut 1 implemented (#434) · 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, #437) 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 implemented: migration 0036 adds `question`, `trace` and `calls` to `agent_decisions`; `governor` in the extract crate holds the tools, the opening and the step reader; `investigate` in the server job runs the loop for pairs the batch could not settle (decision 8) · cut 4 implemented: migration 0037 adds `knowledge_bases.governance_since`; `fuse` in the server job turns the switch off after two reverts of the agent's merges since it was turned on, within seven days, raises `governance.tripped` and writes the ledger (decision 9)- **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.@@ -52,6 +52,12 @@ The batch judges twelve pairs from their top facts and the precedent lines, andPairs the hard rules stop never enter the loop: a type conflict, a reverted merge in the history, a same-pair precedent that contradicts the verdict. More looking would not change a rule. A base has a daily budget of loop calls (three hundred); when it is spent, uncertain pairs are proposed from the batch's verdict as in cut 1, so the loop can never run away on a large backlog. A model that stops calling tools is nudged once and then treated as not having concluded, with the trace kept.+### 9. Two reverts in a week turn the switch off++A person reverting one of the agent's merges is the strongest signal the ledger has: the agent stood in for a person and was wrong in the one way that costs work to undo. Two of them within seven days, counted from the moment the switch was last turned on, turn the switch off. The base gets a `governance.tripped` alert for its editors and a `kb.updated` row with the machine as the actor, so the switch-off is in the ledger like every other decision. The queue stops at its next cluster boundary as it does for any switch-off; proposals already made stay for people to answer. Turning the switch back on records `governance_since` afresh, so the two reverts that tripped it do not trip it again on the first mistake after a restart.++Both revert paths count: the Agent queue's Revert and the Merges page's Revert on a merge the agent made (the latter now marks the agent's row `reverted` too, so the queue and the history agree). A person merging over an applied keep, or overriding a proposal, does not count: those are corrections to a suggestion, not to a change in the graph.+### 7. The governor does not touch the verdict cacheThe 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.@@ -69,7 +75,6 @@ Duplicates that the agent proposed on carry the reason code `proposed`; pairs it## Open questions-- **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 for the batch.** The loop has a daily budget (decision 8); the batch does not. A job runs twenty clusters and re-enqueues itself while backlog remains, which is what the adjudicator always did. Whether a base needs a cap on that too is a question for a large corpus.diff --git a/docs/decisions/README.md b/docs/decisions/README.mdindex 0902e06e..fccbfc79 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 switch, the Agent queue, the proposal chip and the Overview section in the UI · a pair the batch cannot settle is looked at again with tools and then decided or asked about, within a daily budget · the fuse is 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 · a pair the batch cannot settle is looked at again with tools and then decided or asked about, within a daily budget · two reverts in a week turn the switch off and raise an alert |## Not a decision recorddiff --git a/migrations/0037_the_fuse_trips_on_the_second_revert.sql b/migrations/0037_the_fuse_trips_on_the_second_revert.sqlnew file mode 100644index 00000000..cacc59f3--- /dev/null+++ b/migrations/0037_the_fuse_trips_on_the_second_revert.sql@@ -0,0 +1,6 @@+-- 0025 第四刀:保险丝。+--+-- 七天内人撤回 agent 的自动合并两次,开关自动关掉并发一条告警:它替人做主做错了+-- 两回,该停下来等人再开。只数这次打开之后的撤回——人重新打开时,之前那两次不再+-- 算,否则一开就再跳。governance_since 记的就是这次打开的时刻。+ALTER TABLE knowledge_bases ADD COLUMN governance_since TIMESTAMPTZ;diff --git a/web/src/api.ts b/web/src/api.tsindex 53a5a024..52fa7e17 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -110,6 +110,8 @@ export interface Kb {/** 治理开关(0025,缺省关):agent 按先进先出过等人的重复对,先读台账里人的* 先例再裁;打开就开始,关掉就停 */governance: boolean;+ /** 这次打开治理的时刻;保险丝只数它之后的撤回 */+ governance_since: string | null;/** 多久重推一次(分钟)。事实持续在变,只靠手点会让派生一直是缺的 */inference_interval_minutes: number;/** 上次推完的时间 */diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex d5e82c51..d5808d1e 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -217,6 +217,10 @@ export const en = {title: "The model account cannot pay for requests",hint: "Extraction and embedding are stopped and will not resume on their own. Top up the account, or set an endpoint that can serve in Administration → Models.",},+ "governance.tripped": {+ title: "The agent stopped deciding on its own",+ hint: "Two of its merges were reverted within seven days, so the switch went off. Look at what it did under Review → Agent, then turn it back on in the base settings when you want it to resume.",+ },} as Record<string, { title: string; hint: string } | undefined>,// 没见过的 kind 也要能显示:新告警源上线时前端可能还没更新unknownKind: (kind: string) => kind,diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex a25263aa..10ad8f2d 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -184,6 +184,10 @@ export const zh: Strings = {title: "映射探索没有提出任何口径",hint: "模型读了挂载的库表结构,但没找到可提的指标或维度。到「数据映射 > 数据源」刷新结构、给列加注释,再探索一次。",},+ "governance.tripped": {+ title: "agent 停止自动裁决了",+ hint: "七天内它的合并被撤回了两次,开关已自动关掉。到「审核 > Agent」看看它做了什么,想让它接着跑就在库设置里再打开。",+ },"llm.unreachable": {title: "模型端点没有给出可用的回答",hint: "抽取与向量化已停摆。去「管理 → 模型」里检查端点地址。",