Skip to content

World's first open-source enterprise world model.

The cluster the agent is deciding is locked, and the Review page says it is working (#460)

WaylandYang872b91c09b0b
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index 3e61c253..be424d07 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -1236,6 +1236,10 @@ pub struct ReviewCounts {
pub agent: i64,
/// agent 的全部记录(Agent 队列翻页用)
pub agent_rows: i64,
+ /// 这个库的 govern 任务此刻在跑
+ pub agent_running: bool,
+ /// 等 agent 看的对:等人的重复对里还没有建议的
+ pub agent_queue: i64,
}
/// agent 的一笔(0025):看了哪一对、想怎么办、凭什么、人怎么答的。
@@ -1291,6 +1295,10 @@ pub struct ReviewSummary {
/// agent 在这个库里做过什么(0025):开着的建议,以及近期每一笔现在的状态
#[derive(Debug, Clone, Serialize, Default)]
pub struct ReviewAgent {
+ /// 此刻在跑
+ pub running: bool,
+ /// 还没轮到 agent 看的对
+ pub queue: i64,
/// 等人回答的建议,不分时间
pub open: i64,
pub last_7d: AgentWindow,
diff --git a/crates/utopia-server/src/governance.rs b/crates/utopia-server/src/governance.rs
index 6db28070..e554b20f 100644
--- a/crates/utopia-server/src/governance.rs
+++ b/crates/utopia-server/src/governance.rs
@@ -115,18 +115,44 @@ pub async fn govern(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {
settings: &settings,
};
+ // 上一次任务半路留下的锁先放掉;跑完(不管怎么结束的)再放一次
+ gov::release_locks(&state.pool, kb_id).await?;
+ let outcome = rounds(&ctx).await;
+ if let Err(e) = gov::release_locks(&state.pool, kb_id).await {
+ tracing::warn!(%kb_id, error = %e, "治理:放锁失败");
+ }
+ state.emit_review(kb_id);
+ let more = outcome?;
+
+ // 轮数用完还有积压:再排一个,下一轮从队头接着走
+ if more {
+ utopia_store::jobs::enqueue_unless_queued(&state.pool, "govern", json!({ "kb_id": kb_id }))
+ .await?;
+ }
+ Ok(())
+}
+
+/// 一轮轮走到队列空、开关关或轮数用完。回 true = 轮数用完还有积压
+async fn rounds(ctx: &Ctx<'_>) -> anyhow::Result<bool> {
+ let state = ctx.state;
+ let kb_id = ctx.kb_id;
+ let client = ctx.client;
for _ in 0..MAX_ROUNDS {
// 关闭后队列自动终止:每一簇之前看一眼
if !utopia_store::kbs::get(&state.pool, kb_id).await?.governance {
tracing::info!(%kb_id, "治理:开关已关,停在这里");
- return Ok(());
+ return Ok(false);
}
let Some(head) = gov::queue(&state.pool, kb_id, 1).await?.into_iter().next() else {
- return Ok(());
+ return Ok(false);
};
let mut items = vec![head];
let siblings = gov::cluster_of(&state.pool, kb_id, &items[0], BATCH_SIZE - 1).await?;
items.extend(siblings);
+ // 这一簇归 agent 了:人在这几分钟里不能裁它们,界面上看得见
+ let ids: Vec<Uuid> = items.iter().map(|i| i.id).collect();
+ gov::lock(&state.pool, kb_id, &ids).await?;
+ state.emit_review(kb_id);
let mut precedents = Vec::with_capacity(items.len());
for item in &items {
@@ -147,7 +173,7 @@ pub async fn govern(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {
{
Some(merged) => {
settle(
- &ctx,
+ ctx,
item,
&pairs[idx],
&precedents[idx],
@@ -163,7 +189,7 @@ pub async fn govern(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {
asked.iter().map(|&i| pairs[i].clone()).collect();
let messages = utopia_extract::build_adjudication_messages(&batch);
let reply = {
- let _permit = permit(&ctx).await;
+ let _permit = permit(ctx).await;
// 调用/解析失败 → 任务按退避重试;重试耗尽后这些对留在队列里,人照样能裁
client.chat(&messages).await?
};
@@ -184,18 +210,12 @@ pub async fn govern(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {
),
None => Look::from_batch(None, 0.0, None),
};
- settle(&ctx, &items[idx], &pairs[idx], &precedents[idx], look).await?;
+ settle(ctx, &items[idx], &pairs[idx], &precedents[idx], look).await?;
}
}
state.emit_review(kb_id);
}
-
- // 轮数用完还有积压:再排一个,下一轮从队头接着走
- if !gov::queue(&state.pool, kb_id, 1).await?.is_empty() {
- utopia_store::jobs::enqueue_unless_queued(&state.pool, "govern", json!({ "kb_id": kb_id }))
- .await?;
- }
- Ok(())
+ Ok(!gov::queue(&state.pool, kb_id, 1).await?.is_empty())
}
async fn permit(ctx: &Ctx<'_>) -> Option<tokio::sync::OwnedSemaphorePermit> {
diff --git a/crates/utopia-store/src/governance.rs b/crates/utopia-store/src/governance.rs
index a1877093..ca35f98f 100644
--- a/crates/utopia-store/src/governance.rs
+++ b/crates/utopia-store/src/governance.rs
@@ -807,6 +807,76 @@ pub async fn get(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<AgentDecisio
.ok_or(AppError::NotFound)
}
+/// 这个库的 govern 任务此刻在跑
+pub async fn agent_running(pool: &PgPool, kb_id: Uuid) -> AppResult<bool> {
+ let running = sqlx::query_scalar(
+ "SELECT EXISTS (SELECT 1 FROM jobs WHERE kind = 'govern' AND status = 'running'
+ AND payload->>'kb_id' = $1)",
+ )
+ .bind(kb_id.to_string())
+ .fetch_one(pool)
+ .await?;
+ Ok(running)
+}
+
+/// 还没轮到 agent 看的对:等人的、还没有开着的建议的
+pub async fn queue_len(pool: &PgPool, kb_id: Uuid) -> AppResult<i64> {
+ let n = sqlx::query_scalar(&format!(
+ "SELECT count(*) FROM resolution_reviews rr
+ WHERE rr.kb_id = $1 AND rr.status = 'pending' AND {OPEN_PROPOSAL}"
+ ))
+ .bind(kb_id)
+ .fetch_one(pool)
+ .await?;
+ Ok(n)
+}
+
+/// agent 正在裁的一簇:标成 adjudicating,界面上按钮灰掉、接口上拒绝人改——模型
+/// 调用在飞的时候人把一对裁了,落地那一步会撞上
+pub async fn lock(pool: &PgPool, kb_id: Uuid, ids: &[Uuid]) -> AppResult<()> {
+ sqlx::query(
+ "UPDATE resolution_reviews SET stage = 'adjudicating'
+ WHERE kb_id = $1 AND id = ANY($2) AND status = 'pending'",
+ )
+ .bind(kb_id)
+ .bind(ids)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 任务开始与结束时放开所有锁:一轮中途出错、开关关掉,都不能把对锁死
+pub async fn release_locks(pool: &PgPool, kb_id: Uuid) -> AppResult<u64> {
+ let n = sqlx::query(
+ "UPDATE resolution_reviews SET stage = 'human'
+ WHERE kb_id = $1 AND status = 'pending' AND stage = 'adjudicating'",
+ )
+ .bind(kb_id)
+ .execute(pool)
+ .await?
+ .rows_affected();
+ Ok(n)
+}
+
+/// 这一对此刻是不是 agent 正在裁的:治理开着、任务在跑、这一对标着 adjudicating。
+/// 三个条件缺一个都不算锁——任务没在跑的 adjudicating 只是旧裁决器留下的标记,人照样能裁
+pub async fn locked_by_agent(pool: &PgPool, kb_id: Uuid, review_id: Uuid) -> AppResult<bool> {
+ let locked = sqlx::query_scalar(
+ "SELECT EXISTS (
+ SELECT 1 FROM resolution_reviews rr
+ JOIN knowledge_bases k ON k.id = rr.kb_id
+ WHERE rr.id = $2 AND rr.kb_id = $1 AND rr.status = 'pending'
+ AND rr.stage = 'adjudicating' AND k.governance
+ AND EXISTS (SELECT 1 FROM jobs j WHERE j.kind = 'govern' AND j.status = 'running'
+ AND j.payload->>'kb_id' = $1::text))",
+ )
+ .bind(kb_id)
+ .bind(review_id)
+ .fetch_one(pool)
+ .await?;
+ Ok(locked)
+}
+
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'",
diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs
index 210e9302..ded9018e 100644
--- a/crates/utopia-store/src/resolution.rs
+++ b/crates/utopia-store/src/resolution.rs
@@ -1413,6 +1413,13 @@ pub async fn decide_review(
.fetch_optional(pool)
.await?;
let row = row.ok_or(AppError::NotFound)?;
+ // agent 正在裁的一对(0025):等它的建议,或者关掉开关
+ if crate::governance::locked_by_agent(pool, kb_id, review_id).await? {
+ return Err(AppError::Conflict(
+ "The agent is deciding this pair right now; wait for its proposal or turn governance off."
+ .into(),
+ ));
+ }
match action {
"merge" => {
diff --git a/crates/utopia-store/src/review.rs b/crates/utopia-store/src/review.rs
index 1e6cac4e..8463a93f 100644
--- a/crates/utopia-store/src/review.rs
+++ b/crates/utopia-store/src/review.rs
@@ -55,7 +55,14 @@ pub async fn counts(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewCounts> {
(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,
- (SELECT count(*) FROM agent_decisions WHERE kb_id = $1) AS agent_rows",
+ (SELECT count(*) FROM agent_decisions WHERE kb_id = $1) AS agent_rows,
+ EXISTS (SELECT 1 FROM jobs j WHERE j.kind = 'govern' AND j.status = 'running'
+ AND j.payload->>'kb_id' = $1::text) AS agent_running,
+ (SELECT count(*) FROM resolution_reviews rr
+ WHERE rr.kb_id = $1 AND rr.status = 'pending'
+ AND NOT EXISTS (SELECT 1 FROM agent_decisions d
+ WHERE d.target_kind = 'review' AND d.target_id = rr.id
+ AND d.status = 'proposed')) AS agent_queue",
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.rs
index 8049bd89..ba92f12c 100644
--- a/crates/utopia-store/src/review_summary.rs
+++ b/crates/utopia-store/src/review_summary.rs
@@ -294,6 +294,8 @@ async fn agent(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewAgent> {
w
};
Ok(ReviewAgent {
+ running: crate::governance::agent_running(pool, kb_id).await?,
+ queue: crate::governance::queue_len(pool, kb_id).await?,
open,
last_7d: window(true),
last_30d: window(false),
diff --git a/crates/utopia-store/tests/a_governor_reads_the_ledger.rs b/crates/utopia-store/tests/a_governor_reads_the_ledger.rs
index 956f7485..e581621d 100644
--- a/crates/utopia-store/tests/a_governor_reads_the_ledger.rs
+++ b/crates/utopia-store/tests/a_governor_reads_the_ledger.rs
@@ -541,6 +541,35 @@ async fn run(pool: &PgPool, s: &Seed) -> anyhow::Result<()> {
.execute(pool)
.await?;
+ // agent 正在裁的一簇锁住(0025 第五刀):任务在跑 + 标着 adjudicating + 开关开着,
+ // 三样齐了人才裁不了;任务一停,标记只是标记
+ sqlx::query("INSERT INTO jobs (kind, payload, status) VALUES ('govern', $1, 'running')")
+ .bind(serde_json::json!({ "kb_id": s.kb }))
+ .execute(pool)
+ .await?;
+ assert!(governance::agent_running(pool, s.kb).await?);
+ let mercury = by_id(s.mercury);
+ governance::lock(pool, s.kb, &[mercury.id]).await?;
+ assert!(governance::locked_by_agent(pool, s.kb, mercury.id).await?);
+ assert!(
+ utopia_store::resolution::decide_review(pool, s.kb, mercury.id, "keep", s.user)
+ .await
+ .is_err(),
+ "agent 正在裁的对,人裁不了"
+ );
+ assert_eq!(governance::release_locks(pool, s.kb).await?, 1);
+ assert!(!governance::locked_by_agent(pool, s.kb, mercury.id).await?);
+ sqlx::query("DELETE FROM jobs WHERE kind = 'govern' AND payload->>'kb_id' = $1")
+ .bind(s.kb.to_string())
+ .execute(pool)
+ .await?;
+ assert!(!governance::agent_running(pool, s.kb).await?);
+ assert_eq!(
+ governance::queue_len(pool, s.kb).await?,
+ 3,
+ "orion、mercury、zw23 等 agent 看"
+ );
+
// 定时扫描:开关开着且有没看过的对 → 在;关了 → 不在
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.md
index 8ac02523..047dd86f 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
@@ -86,6 +86,8 @@ The adjudicator's cache is keyed on names, types and facts. The governor's answe
## What a reader sees
+While a `govern` job runs, the cluster it is deciding is locked: those pairs carry `stage = adjudicating`, the Review card shows "The agent is deciding this pair" with its buttons off, "Select this page" skips them, and `decide_review` refuses them with a 409 until the round ends. The lock is three conditions together, the switch on, the job running, the stage set, so a stale `adjudicating` mark from a crashed job or from the old adjudicator never locks anything; the job also clears every mark when it starts and when it ends. The Overview's Agent section says the agent is working and how many pairs it has still to look at, and the Agent item in the rail carries a pulsing dot for as long as it runs.
+
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
diff --git a/web/src/api.ts b/web/src/api.ts
index 52fa7e17..479128d4 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -467,6 +467,10 @@ export interface ReviewCounts {
agent: number;
/** agent 的全部记录(Agent 队列翻页用) */
agent_rows: number;
+ /** 这个库的 govern 任务此刻在跑 */
+ agent_running: boolean;
+ /** 还没轮到 agent 看的对 */
+ agent_queue: number;
}
/** 类型消解的一条建议:一个待精化的实体、送去检索的画像、以及候选类。
@@ -787,7 +791,7 @@ export interface AgentWindow {
/** 审核台总览(#377):等着办的、办过的、库的成色。与左栏计数同一套口径 */
export interface ReviewSummary {
/** agent 在这个库里做过什么(0025) */
- agent: { open: number; last_7d: AgentWindow; last_30d: AgentWindow };
+ agent: { running: boolean; queue: number; open: number; last_7d: AgentWindow; last_30d: AgentWindow };
waiting: Record<
"pending" | "duplicates" | "conflicts" | "unconfirmed" | "lowconf" | "violations" | "defects",
QueueWait
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 29716d81..8bb90093 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -1533,6 +1533,10 @@ export const en = {
overviewAgentOverridden: (n: number) =>
n === 1 ? "1 overridden, last 30 days" : `${n} overridden, last 30 days`,
overviewAgentReverted: "Reverted by you",
+ overviewAgentRunning: (n: number) =>
+ n === 0 ? "The agent is working on its last cluster" : `The agent is working · ${n} pairs still to look at`,
+ overviewAgentQueue: (n: number) => (n === 1 ? "1 pair waiting for the agent" : `${n} pairs waiting for the agent`),
+ agentDeciding: "The agent is deciding this pair",
// 总览(#377)
overviewTitle: "Overview",
overviewHint:
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 1f3fb29d..e128429c 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -1343,6 +1343,9 @@ export const zh: Strings = {
overviewAgentAccepted: "你接受的建议",
overviewAgentOverridden: (n) => `改判 ${n},近 30 天`,
overviewAgentReverted: "你撤回的",
+ overviewAgentRunning: (n) => (n === 0 ? "agent 在处理最后一簇" : `agent 处理中 · 还有 ${n} 对没看`),
+ overviewAgentQueue: (n) => `${n} 对等 agent 看`,
+ agentDeciding: "agent 正在裁这一对",
overviewTitle: "总览",
overviewHint: "这个库要你做什么:有多少在等、等了多久、办过什么、还有多少是暂定的。",
overviewWaiting: "等着办的",
diff --git a/web/src/pages/Review.tsx b/web/src/pages/Review.tsx
index 137f328f..1953294c 100644
--- a/web/src/pages/Review.tsx
+++ b/web/src/pages/Review.tsx
@@ -110,12 +110,15 @@ function typesDiffer(item: ReviewItem): boolean {
function DuplicateCard({
item,
busy,
+ locked,
picked,
onPick,
onDecide,
}: {
item: ReviewItem;
busy: boolean;
+ /** agent 正在裁这一对(0025):这几分钟里人不能动它,接口也会拒绝 */
+ locked: boolean;
/** 批量选中(#428):勾在卡片左上,选了就跟着上面的批量按钮走 */
picked: boolean;
onPick: (picked: boolean) => void;
@@ -129,7 +132,7 @@ function DuplicateCard({
<Checkbox
className="shrink-0 self-start"
checked={picked}
- disabled={busy}
+ disabled={busy || locked}
onChange={(e) => onPick(e.target.checked)}
label={<span className="sr-only">{S.review.pickPair}</span>}
/>
@@ -138,13 +141,20 @@ function DuplicateCard({
<SideCard side={item.right} />
</div>
<div className="mt-3 pt-3 flex items-center gap-3 border-t border-line">
- <span
- className={`u-chip ${item.stage === "human" ? "u-chip-warn" : "u-chip-neutral"}`}
- >
- {item.stage === "human"
- ? S.review.stageHuman
- : S.review.stageAdjudicating}
- </span>
+ {locked ? (
+ <span className="u-chip u-chip-info">
+ <span className="mr-2 inline-block h-2 w-2 rounded-full bg-warn animate-pulse" />
+ {S.review.agentDeciding}
+ </span>
+ ) : (
+ <span
+ className={`u-chip ${item.stage === "human" ? "u-chip-warn" : "u-chip-neutral"}`}
+ >
+ {item.stage === "human"
+ ? S.review.stageHuman
+ : S.review.stageAdjudicating}
+ </span>
+ )}
{typesDiffer(item) && (
<Chip tone="warn" title={S.review.typesDifferHint}>
{S.review.typesDiffer(
@@ -174,13 +184,13 @@ function DuplicateCard({
)}
<div className="ml-auto flex gap-2 shrink-0">
<Button variant="secondary" size="sm"
- disabled={busy}
+ disabled={busy || locked}
onClick={() => onDecide("keep")}
>
{S.review.keep}
</Button>
<Button variant="primary" size="sm"
- disabled={busy}
+ disabled={busy || locked}
onClick={() => onDecide("merge")}
>
{S.review.merge}
@@ -1214,6 +1224,10 @@ export function Review() {
const asDefects = () => rows as OntologyDefect[];
const asMerges = () => rows as MergeLog[];
const asAgent = () => rows as AgentDecision[];
+ // agent 正在裁的一对(0025):任务在跑、这一对标着 adjudicating。批量选页时跳过它们
+ const lockedByAgent = (item: ReviewItem) =>
+ !!c?.agent_running && item.stage === "adjudicating";
+ const selectable = () => asDuplicates().filter((d) => !lockedByAgent(d));
const queueEmpty = QUEUE_ORDER.every((k) => counts[k] === 0);
// 没带 ?queue= 进来就落在总览上——从前是「第一个非空队列」,那等于替人
@@ -1321,6 +1335,7 @@ export function Review() {
<RailItem
active={active === "agent"}
count={counts.agent}
+ dot={c?.agent_running ? "bg-warn animate-pulse" : undefined}
onClick={() => select("agent")}
>
{S.review.railAgent}
@@ -1438,13 +1453,13 @@ export function Review() {
<Checkbox
className="ml-auto"
checked={
- asDuplicates().length > 0 &&
- asDuplicates().every((d) => picked.has(d.id))
+ selectable().length > 0 &&
+ selectable().every((d) => picked.has(d.id))
}
onChange={(e) =>
setPicked(
e.target.checked
- ? new Set(asDuplicates().map((d) => d.id))
+ ? new Set(selectable().map((d) => d.id))
: new Set(),
)
}
@@ -1487,6 +1502,7 @@ export function Review() {
<DuplicateCard
key={item.id}
item={item}
+ locked={lockedByAgent(item)}
picked={picked.has(item.id)}
onPick={(on) =>
setPicked((prev) => {
diff --git a/web/src/pages/ReviewOverview.tsx b/web/src/pages/ReviewOverview.tsx
index 8692f708..896c208f 100644
--- a/web/src/pages/ReviewOverview.tsx
+++ b/web/src/pages/ReviewOverview.tsx
@@ -191,6 +191,15 @@ export function ReviewOverview({
<LinkButton onClick={onSettings}>{S.review.overviewAgentSettings}</LinkButton>
</p>
)}
+ {/* 此刻在跑:一颗脉动的点加还剩几对;没跑但有积压:几对等它 */}
+ {agent.running ? (
+ <p className="mb-3 flex items-center text-small text-ink-2">
+ <span className="mr-2 inline-block h-2 w-2 rounded-full bg-warn animate-pulse" />
+ {S.review.overviewAgentRunning(agent.queue)}
+ </p>
+ ) : governance && agent.queue > 0 ? (
+ <p className="mb-3 text-small text-ink-3">{S.review.overviewAgentQueue(agent.queue)}</p>
+ ) : null}
{(governance || agent.open > 0 || agent.last_30d.applied > 0) && (
<div className="grid grid-cols-2 gap-3 md:grid-cols-4">
<Stat