Skip to content

World's first open-source enterprise world model.

A decision records why (#473)

WaylandYang84f45ec7810e
diff --git a/crates/utopia-extract/src/lib.rs b/crates/utopia-extract/src/lib.rs
index 02c4e1e6..0c452f66 100644
--- a/crates/utopia-extract/src/lib.rs
+++ b/crates/utopia-extract/src/lib.rs
@@ -638,7 +638,7 @@ pub fn build_adjudication_messages(pairs: &[AdjudicationPair]) -> Vec<ChatMessag
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\
+ \"unsure\". A precedent never overrides a contradiction in the facts. Some precedents quote what the person wrote when deciding: weigh that stated ground, not only the outcome; a decision made for a reason that does not hold here is not a precedent for this pair.\n\
\n\
Output exactly one JSON object and nothing else:\n\
{{\"verdicts\":[{{\"i\":0,\"verdict\":\"same|different|unsure\",\"confidence\":0.9,\
diff --git a/crates/utopia-server/src/adjudication.rs b/crates/utopia-server/src/adjudication.rs
index 13ff6eae..1176fd61 100644
--- a/crates/utopia-server/src/adjudication.rs
+++ b/crates/utopia-server/src/adjudication.rs
@@ -9,14 +9,21 @@ use sha2::{Digest, Sha256};
use std::collections::HashMap;
use utopia_core::models::ReviewItem;
use utopia_core::AppError;
+use utopia_store::governance as gov;
use uuid::Uuid;
const BATCH_SIZE: i64 = 12;
const AUTO_CONF: f32 = 0.8;
const MAX_ROUNDS: usize = 20;
+/// 每一百对里有几对**即使裁决器有把握也交给人**(0026)。没有这一份,人裁过的
+/// 语料会收缩成只剩难题:既不再代表一般的判法,也没有样本能量出机器与人的
+/// 一致率。按 id 取样而不是掷骰子:同一对每次跑到的答案一样,才好复现
+const HUMAN_SAMPLE_PCT: u128 = 10;
-/// 缓存键:类型 + 双方名字 + 事实摘要(与实体 id 无关——重传文档不重复付费)。
-fn pair_key(item: &ReviewItem) -> String {
+/// 缓存键:类型 + 双方名字 + 事实摘要 + 先例(与实体 id 无关——重传文档不重复付费)。
+/// **先例也进键**:答案随先例变(0025 说的正是这个,治理那一路因此干脆不用缓存);
+/// 人又裁了一笔,键就变,旧答案自然作废,不必去清
+fn pair_key(item: &ReviewItem, precedents: &[String]) -> String {
let side = |s: &utopia_core::models::ReviewSide| {
format!(
"{}|{}|{}",
@@ -28,10 +35,16 @@ fn pair_key(item: &ReviewItem) -> String {
};
let mut sides = [side(&item.left), side(&item.right)];
sides.sort();
- let digest = Sha256::digest(sides.join("##").as_bytes());
+ let digest =
+ Sha256::digest(format!("{}##{}", sides.join("##"), precedents.join("\n")).as_bytes());
digest.iter().map(|b| format!("{b:02x}")).collect()
}
+/// 这一对是不是抽给人看的那一份(见 HUMAN_SAMPLE_PCT)
+fn sampled_for_a_person(item: &ReviewItem) -> bool {
+ item.id.as_u128() % 100 < HUMAN_SAMPLE_PCT
+}
+
pub async fn adjudicate_entities(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {
let kb = utopia_store::kbs::get(&state.pool, kb_id).await?;
let settings = utopia_store::settings::get(&state.pool, kb.workspace_id).await?;
@@ -60,15 +73,18 @@ pub async fn adjudicate_entities(state: &AppState, kb_id: Uuid) -> anyhow::Resul
break;
}
- // 第一层:裁决缓存
- let mut to_ask: Vec<(ReviewItem, String)> = Vec::new();
+ // 第一层:裁决缓存。先例(人在这个库里对这些名字做过什么,连同他们写的理由)
+ // 先取出来:它既进提示词也进缓存键
+ let mut to_ask: Vec<(ReviewItem, String, Vec<String>)> = Vec::new();
for item in items {
- let key = pair_key(&item);
+ let precedents =
+ gov::render_lines(&gov::precedents_for(&state.pool, kb_id, &item).await?);
+ let key = pair_key(&item, &precedents);
match utopia_store::resolution::get_verdict(&state.pool, kb_id, &key).await? {
Some((same, conf)) => {
- apply_verdict(state, kb_id, &item, same, conf, "cached").await?
+ apply_verdict(state, kb_id, &item, same, conf, "cached", None).await?
}
- None => to_ask.push((item, key)),
+ None => to_ask.push((item, key, precedents)),
}
}
if to_ask.is_empty() {
@@ -78,7 +94,7 @@ pub async fn adjudicate_entities(state: &AppState, kb_id: Uuid) -> anyhow::Resul
// 第二层:攒批 LLM 裁决
let pairs: Vec<utopia_extract::AdjudicationPair> = to_ask
.iter()
- .map(|(item, _)| utopia_extract::AdjudicationPair {
+ .map(|(item, _, precedents)| utopia_extract::AdjudicationPair {
left: utopia_extract::AdjudicationSide {
name: item.left.name.clone(),
type_label: item
@@ -97,7 +113,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(),
+ precedents: precedents.clone(),
})
.collect();
let messages = utopia_extract::build_adjudication_messages(&pairs);
@@ -112,7 +128,7 @@ pub async fn adjudicate_entities(state: &AppState, kb_id: Uuid) -> anyhow::Resul
let by_i: HashMap<usize, &utopia_extract::AdjudicationVerdict> =
verdicts.iter().map(|v| (v.i, v)).collect();
- for (idx, (item, key)) in to_ask.iter().enumerate() {
+ for (idx, (item, key, _)) in to_ask.iter().enumerate() {
match by_i.get(&idx) {
Some(v) => {
let same = match v.verdict.as_str() {
@@ -130,7 +146,16 @@ pub async fn adjudicate_entities(state: &AppState, kb_id: Uuid) -> anyhow::Resul
&model,
)
.await?;
- apply_verdict(state, kb_id, item, same, conf, "adjudicated").await?;
+ apply_verdict(
+ state,
+ kb_id,
+ item,
+ same,
+ conf,
+ "adjudicated",
+ v.why.as_deref(),
+ )
+ .await?;
}
None => {
utopia_store::resolution::escalate_review(
@@ -148,6 +173,7 @@ pub async fn adjudicate_entities(state: &AppState, kb_id: Uuid) -> anyhow::Resul
Ok(())
}
+#[allow(clippy::too_many_arguments)]
async fn apply_verdict(
state: &AppState,
kb_id: Uuid,
@@ -155,7 +181,24 @@ async fn apply_verdict(
same: Option<bool>,
conf: f32,
via: &str,
+ why: Option<&str>,
) -> anyhow::Result<()> {
+ // 抽给人的那一份:机器有把握也不动手(0026)。理由写进队列那一列,
+ // 界面会说"这一对是抽样给你的",而不是让人以为裁决器没把握
+ if same.is_some() && conf >= AUTO_CONF && sampled_for_a_person(item) {
+ let verdict = if same == Some(true) {
+ "same"
+ } else {
+ "different"
+ };
+ utopia_store::resolution::escalate_review(
+ &state.pool,
+ item.id,
+ &format!("escalate_sample|{verdict} {conf:.2}"),
+ )
+ .await?;
+ return Ok(());
+ }
match same {
Some(true) if conf >= AUTO_CONF => {
let (target, source) =
@@ -191,6 +234,9 @@ async fn apply_verdict(
serde_json::json!({
"left": item.left.name, "right": item.right.name,
"score": item.score, "confidence": conf, "via": via,
+ // 模型的一句理由也留下:机器的行不是先例(0025 决定 1),
+ // 但人看 Decisions 时该看得见它凭什么
+ "why": why,
}),
)
.await;
@@ -225,6 +271,7 @@ async fn apply_verdict(
serde_json::json!({
"left": item.left.name, "right": item.right.name,
"score": item.score, "confidence": conf, "via": via,
+ "why": why,
}),
)
.await;
diff --git a/crates/utopia-server/src/api/review_routes.rs b/crates/utopia-server/src/api/review_routes.rs
index 134252fa..0a47025f 100644
--- a/crates/utopia-server/src/api/review_routes.rs
+++ b/crates/utopia-server/src/api/review_routes.rs
@@ -295,6 +295,9 @@ pub async fn resolve_conflict(
pub struct DecideBody {
/// merge | keep
pub action: String,
+ /// 人拍板时写的那一句(0026):什么让你这么定。可空
+ #[serde(default)]
+ pub rationale: Option<String>,
}
pub async fn decide(
@@ -317,9 +320,17 @@ pub async fn decide(
.await
.ok()
.flatten();
- utopia_store::resolution::decide_review(&state.pool, kb_id, review_id, &body.action, user.id)
- .await?;
+ utopia_store::resolution::decide_review(
+ &state.pool,
+ kb_id,
+ review_id,
+ &body.action,
+ user.id,
+ body.rationale.as_deref(),
+ )
+ .await?;
if let Some((l, r, score)) = snap {
+ // 理由也进台账:先例是从这里读的,不是从 resolution_reviews
let _ = utopia_store::audit::record(
&state.pool,
Some(kb_id),
@@ -331,7 +342,7 @@ pub async fn decide(
},
"review",
Some(review_id),
- json!({ "left": l, "right": r, "score": score }),
+ json!({ "left": l, "right": r, "score": score, "why": body.rationale }),
)
.await;
}
@@ -352,6 +363,9 @@ pub struct AgentAnswerBody {
/// merge | keep 答一条建议(与建议相同是接受,不同是改判);
/// revert 撤回一条自动合并;merge 也能推翻一条自动分开
pub action: String,
+ /// 什么让你这么答(0026)。改判 agent 的时候尤其值得写:那一句就是下次的先例
+ #[serde(default)]
+ pub rationale: Option<String>,
}
/// 人回答 agent 的一笔(0025)。回答走的是人的裁决路径:decided_by 是这个人,
@@ -370,8 +384,15 @@ pub async fn agent_answer(
);
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?;
+ utopia_store::resolution::decide_review(
+ &state.pool,
+ kb_id,
+ d.target_id,
+ act,
+ user.id,
+ body.rationale.as_deref(),
+ )
+ .await?;
let status = if act == d.action {
"accepted"
} else {
@@ -386,7 +407,8 @@ pub async fn agent_answer(
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 }),
+ json!({ "left": l, "right": r, "agent_decision": decision_id, "agent_action": d.action,
+ "why": body.rationale }),
)
.await;
}
@@ -471,6 +493,9 @@ pub struct BatchBody {
pub ids: Vec<Uuid>,
/// merge | keep,整批一个动作
pub action: String,
+ /// 整批一句理由(0026):一批同一个动作,多半也是同一个依据
+ #[serde(default)]
+ pub rationale: Option<String>,
}
/// 一批 id 最多多少条:够一屏「全选」,又挡住一次请求把库锁上几分钟
@@ -511,6 +536,7 @@ pub async fn batch(
&body.ids,
&body.action,
user.id,
+ body.rationale.as_deref(),
)
.await?;
let action = if body.action == "merge" {
@@ -527,7 +553,8 @@ pub async fn batch(
action,
"review",
Some(o.id),
- json!({ "left": l, "right": r, "score": score, "batch": body.ids.len() }),
+ json!({ "left": l, "right": r, "score": score, "batch": body.ids.len(),
+ "why": body.rationale }),
)
.await;
}
@@ -640,6 +667,9 @@ pub async fn revert_merge(
pub struct ManualMergeBody {
pub source: Uuid,
pub target: Uuid,
+ /// 什么让你把它们并起来(0026)。可空
+ #[serde(default)]
+ pub rationale: Option<String>,
}
/// 手动合并(实体面板"Merge into…"入口)。
@@ -660,13 +690,18 @@ pub async fn manual_merge(
.await
.ok()
.flatten();
+ let why = body
+ .rationale
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty());
let merge_id = utopia_store::resolution::merge_entities(
&state.pool,
kb_id,
body.source,
body.target,
Some(user.id),
- "manual merge",
+ why.unwrap_or("manual merge"),
)
.await?;
if let Some((pair,)) = snap {
@@ -678,7 +713,7 @@ pub async fn manual_merge(
"merge.manual",
"merge",
Some(merge_id),
- json!({ "source": s, "target": t }),
+ json!({ "source": s, "target": t, "why": why }),
)
.await;
}
diff --git a/crates/utopia-server/src/governance.rs b/crates/utopia-server/src/governance.rs
index f55d9362..546f9f6d 100644
--- a/crates/utopia-server/src/governance.rs
+++ b/crates/utopia-server/src/governance.rs
@@ -667,8 +667,14 @@ async fn lookup(
"review.keep" => "kept apart",
_ => "merged",
};
+ // 人写的理由跟在后面:第二层去查台账,查到的该是「凭什么」
+ let because = x
+ .why
+ .as_deref()
+ .map(|w| format!("; they wrote: \"{w}\""))
+ .unwrap_or_default();
format!(
- "\"{}\" ≟ \"{}\": {verb} by a person on {}",
+ "\"{}\" ≟ \"{}\": {verb} by a person on {}{because}",
x.left,
x.right,
x.at.format("%Y-%m-%d")
diff --git a/crates/utopia-store/src/governance.rs b/crates/utopia-store/src/governance.rs
index d44ea7ef..2850b919 100644
--- a/crates/utopia-store/src/governance.rs
+++ b/crates/utopia-store/src/governance.rs
@@ -34,6 +34,9 @@ pub struct Precedent {
pub left: String,
pub right: String,
pub at: DateTime<Utc>,
+ /// 人拍板时写的那一句(0026)。**先例带着理由才是先例**:只有结果的话,
+ /// 一次错误的合并会被读成"这类该合",错误洗成政策。老行没有这一列,为空
+ pub why: Option<String>,
}
impl Precedent {
@@ -68,7 +71,8 @@ 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";
+ created_at AS at,
+ NULLIF(detail->>'why', '') AS why";
pub async fn precedents_for(
pool: &PgPool,
@@ -184,21 +188,30 @@ async fn type_pair_stats(
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 because = |x: &Precedent| {
+ x.why
+ .as_deref()
+ .map(|w| format!("; they wrote: \"{w}\""))
+ .unwrap_or_default()
+ };
let mut out = Vec::new();
for x in &p.same_pair {
out.push(format!(
- "this same pair was {} by a person on {}",
+ "this same pair was {} by a person on {}{}",
verb(x),
- day(&x.at)
+ day(&x.at),
+ because(x)
));
}
for x in &p.same_name {
out.push(format!(
- "\"{}\" against \"{}\" was {} by a person on {}",
+ "\"{}\" against \"{}\" was {} by a person on {}{}",
x.left,
x.right,
verb(x),
- day(&x.at)
+ day(&x.at),
+ because(x)
));
}
if let Some(t) = &p.type_pair {
@@ -211,10 +224,11 @@ pub fn render_lines(p: &Precedents) -> Vec<String> {
}
for x in &p.reverts {
out.push(format!(
- "a merge of \"{}\" into \"{}\" was reverted by a person on {}",
+ "a merge of \"{}\" into \"{}\" was reverted by a person on {}{}",
x.left,
x.right,
- day(&x.at)
+ day(&x.at),
+ because(x)
));
}
out
@@ -227,7 +241,7 @@ pub fn precedents_json(p: &Precedents) -> serde_json::Value {
.map(|x| {
serde_json::json!({
"family": family, "event_id": x.event_id, "action": x.action,
- "left": x.left, "right": x.right, "at": x.at,
+ "left": x.left, "right": x.right, "at": x.at, "why": x.why,
})
})
.collect::<Vec<_>>()
@@ -1061,6 +1075,7 @@ mod tests {
left: "a".into(),
right: "b".into(),
at: Utc::now(),
+ why: None,
}
}
diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs
index ded9018e..e2ca12f1 100644
--- a/crates/utopia-store/src/resolution.rs
+++ b/crates/utopia-store/src/resolution.rs
@@ -1326,13 +1326,14 @@ pub async fn decide_reviews(
ids: &[Uuid],
action: &str,
user_id: Uuid,
+ rationale: Option<&str>,
) -> AppResult<Vec<ReviewBatchOutcome>> {
if action != "merge" && action != "keep" {
return Err(AppError::Validation("action must be merge or keep".into()));
}
let mut out = Vec::with_capacity(ids.len());
for &id in ids {
- let error = decide_review(pool, kb_id, id, action, user_id)
+ let error = decide_review(pool, kb_id, id, action, user_id, rationale)
.await
.err()
.map(|e| e.to_string());
@@ -1397,13 +1398,18 @@ pub async fn close_review_auto(
}
/// 人工定夺。merge 方向:度数高(事实多)的一方作为存活目标,平局取更早创建的。
+/// `rationale`:人拍板时写的那一句(0026)。**空着是允许的**——问的是「什么让你
+/// 这么定」,不是一张必填的表;但只要写了,它就跟着这一行和台账一起留下,
+/// 下一次裁决器和 agent 读先例时读到的就不只是结果。
pub async fn decide_review(
pool: &PgPool,
kb_id: Uuid,
review_id: Uuid,
action: &str,
user_id: Uuid,
+ rationale: Option<&str>,
) -> AppResult<()> {
+ let rationale = rationale.map(str::trim).filter(|s| !s.is_empty());
let row: Option<ReviewRow> = sqlx::query_as(
"SELECT id, left_id, right_id, score, reason, stage, created_at
FROM resolution_reviews WHERE id = $1 AND kb_id = $2 AND status = 'pending'",
@@ -1431,32 +1437,37 @@ pub async fn decide_review(
);
if l != r {
let (target, source) = merge_direction(pool, l, r).await?;
+ // 合并日志的 reason 也记这一句:Review › Merges 那一列读的是它
merge_entities(
pool,
kb_id,
source,
target,
Some(user_id),
- "review decision",
+ rationale.unwrap_or("review decision"),
)
.await?;
}
sqlx::query(
- "UPDATE resolution_reviews SET status = 'merged', decided_at = now(), decided_by = $2
+ "UPDATE resolution_reviews
+ SET status = 'merged', decided_at = now(), decided_by = $2, rationale = $3
WHERE id = $1",
)
.bind(review_id)
.bind(user_id)
+ .bind(rationale)
.execute(pool)
.await?;
}
"keep" => {
sqlx::query(
- "UPDATE resolution_reviews SET status = 'kept', decided_at = now(), decided_by = $2
+ "UPDATE resolution_reviews
+ SET status = 'kept', decided_at = now(), decided_by = $2, rationale = $3
WHERE id = $1",
)
.bind(review_id)
.bind(user_id)
+ .bind(rationale)
.execute(pool)
.await?;
}
diff --git a/crates/utopia-store/tests/a_batch_decides_like_a_person.rs b/crates/utopia-store/tests/a_batch_decides_like_a_person.rs
index 00862912..6fccb8e4 100644
--- a/crates/utopia-store/tests/a_batch_decides_like_a_person.rs
+++ b/crates/utopia-store/tests/a_batch_decides_like_a_person.rs
@@ -184,7 +184,8 @@ async fn run(pool: &PgPool, s: &Seed) -> anyhow::Result<()> {
s.kb,
&[s.same_a],
"smash",
- Uuid::now_v7()
+ Uuid::now_v7(),
+ None,
)
.await
.is_err());
@@ -198,6 +199,7 @@ async fn run(pool: &PgPool, s: &Seed) -> anyhow::Result<()> {
&[s.same_a, ghost, s.same_b],
"merge",
user,
+ None,
)
.await?;
assert_eq!(outcomes.len(), 3, "每个 id 一条结果,顺序照旧");
@@ -226,12 +228,14 @@ async fn run(pool: &PgPool, s: &Seed) -> anyhow::Result<()> {
// 已经裁过的再裁一次:报错、不重复合并
let again =
- utopia_store::resolution::decide_reviews(pool, s.kb, &[s.same_a], "keep", user).await?;
+ utopia_store::resolution::decide_reviews(pool, s.kb, &[s.same_a], "keep", user, None)
+ .await?;
assert!(again[0].error.is_some());
// 批量分开
let kept =
- utopia_store::resolution::decide_reviews(pool, s.kb, &[s.conflict], "keep", user).await?;
+ utopia_store::resolution::decide_reviews(pool, s.kb, &[s.conflict], "keep", user, None)
+ .await?;
assert!(kept[0].error.is_none());
let counts = utopia_store::review::counts(pool, s.kb).await?;
assert_eq!(counts.duplicates, 1, "只剩没类型的那对");
diff --git a/crates/utopia-store/tests/a_decision_records_why.rs b/crates/utopia-store/tests/a_decision_records_why.rs
new file mode 100644
index 00000000..dd0f5fa1
--- /dev/null
+++ b/crates/utopia-store/tests/a_decision_records_why.rs
@@ -0,0 +1,233 @@
+//! 一次裁决记下的是「为什么」(0026),打在真库上。
+//!
+//! 从前 `resolution_reviews` 记 status / decided_by / decided_at,`reason` 记的是
+//! 这一对**为什么被排进队列**。人拍板时想的那句话没有地方落,于是先例只有结果:
+//! 一次错误的合并被读成"这类该合",错误洗成政策。
+//!
+//! 三件事各自会以不同的方式坏掉:
+//! - **落库**:理由写进这一行,空白与只有空格算没写(不存一串空格)
+//! - **先例带理由**:治理与裁决器读先例走的是审计台账,不是这张表——所以理由
+//! 也得进 `detail.why`,`precedents_for` 才读得到,`render_lines` 才写得出
+//! - **老行不炸**:0026 之前的决定没有 why,`Precedent.why` 是 None,渲染照旧
+
+use sqlx::PgPool;
+use utopia_core::models::{ReviewItem, ReviewSide};
+use uuid::Uuid;
+
+struct Fixture {
+ org: Uuid,
+ kb: Uuid,
+ user: Uuid,
+ a: Uuid,
+ b: Uuid,
+ review: Uuid,
+}
+
+async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (user, person) = (Uuid::now_v7(), Uuid::now_v7());
+ let (a, b, review) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'why-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'why-test')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'why-test')")
+ .bind(kb)
+ .bind(ws)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO users (id, org_id, email, display_name, password_hash)
+ VALUES ($1, $2, $3, 'Decider', 'x')",
+ )
+ .bind(user)
+ .bind(org)
+ .bind(format!("decider-{}@test.local", user.simple()))
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'company', 'Company')",
+ )
+ .bind(person)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ for (id, name) in [(a, "Acme"), (b, "Acme Corp")] {
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
+ )
+ .bind(id)
+ .bind(kb)
+ .bind(person)
+ .bind(name)
+ .execute(pool)
+ .await?;
+ }
+ sqlx::query(
+ "INSERT INTO resolution_reviews (id, kb_id, left_id, right_id, score, reason, stage)
+ VALUES ($1, $2, $3, $4, 0.6, 'contains', 'human')",
+ )
+ .bind(review)
+ .bind(kb)
+ .bind(a)
+ .bind(b)
+ .execute(pool)
+ .await?;
+ Ok(Fixture {
+ org,
+ kb,
+ user,
+ a,
+ b,
+ review,
+ })
+}
+
+fn item(f: &Fixture) -> ReviewItem {
+ let side = |id: Uuid, name: &str| ReviewSide {
+ id,
+ name: name.into(),
+ type_label: Some("Company".into()),
+ color: "#888888".into(),
+ degree: 0,
+ disambiguator: None,
+ top_facts: vec![],
+ };
+ ReviewItem {
+ id: f.review,
+ left: side(f.a, "Acme"),
+ right: side(f.b, "Acme Corp"),
+ score: 0.6,
+ reason: Some("contains".into()),
+ stage: "human".into(),
+ created_at: chrono::Utc::now(),
+ proposal: None,
+ }
+}
+
+#[tokio::test]
+async fn a_decision_keeps_its_reason_and_the_precedent_carries_it() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ // 人把它们分开,并说了为什么
+ utopia_store::resolution::decide_review(
+ &pool,
+ f.kb,
+ f.review,
+ "keep",
+ f.user,
+ Some(" Acme Corp is the parent company; Acme is the product line "),
+ )
+ .await?;
+ let stored: (String, Option<String>) =
+ sqlx::query_as("SELECT status, rationale FROM resolution_reviews WHERE id = $1")
+ .bind(f.review)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(stored.0, "kept");
+ assert_eq!(
+ stored.1.as_deref(),
+ Some("Acme Corp is the parent company; Acme is the product line"),
+ "理由落在这一行上,两头的空格去掉"
+ );
+
+ // 先例走审计:路由把 why 写进 detail,这里照路由的写法记一笔
+ utopia_store::audit::record(
+ &pool,
+ Some(f.kb),
+ f.user,
+ "review.keep",
+ "review",
+ Some(f.review),
+ serde_json::json!({
+ "left": "Acme", "right": "Acme Corp", "score": 0.6,
+ "why": "Acme Corp is the parent company; Acme is the product line",
+ }),
+ )
+ .await?;
+ let p = utopia_store::governance::precedents_for(&pool, f.kb, &item(&f)).await?;
+ assert_eq!(p.same_pair.len(), 1, "同对先例一条");
+ assert_eq!(
+ p.same_pair[0].why.as_deref(),
+ Some("Acme Corp is the parent company; Acme is the product line"),
+ "先例带着人写的理由"
+ );
+ let lines = utopia_store::governance::render_lines(&p);
+ assert!(
+ lines.iter().any(
+ |l| l.contains("kept apart") && l.contains("they wrote: \"Acme Corp is the parent")
+ ),
+ "提示词里那一行要引用理由:{lines:?}"
+ );
+
+ // 老行:没有 why 的决定照样是先例,只是没有理由
+ utopia_store::audit::record(
+ &pool,
+ Some(f.kb),
+ f.user,
+ "review.keep",
+ "review",
+ Some(f.review),
+ serde_json::json!({ "left": "Acme", "right": "Acme Corp", "score": 0.6 }),
+ )
+ .await?;
+ let p = utopia_store::governance::precedents_for(&pool, f.kb, &item(&f)).await?;
+ assert_eq!(p.same_pair.len(), 2);
+ assert!(
+ p.same_pair.iter().any(|x| x.why.is_none()),
+ "0026 之前的行没有理由,读出来是 None 而不是报错"
+ );
+ let lines = utopia_store::governance::render_lines(&p);
+ assert!(
+ lines
+ .iter()
+ .any(|l| l.contains("kept apart") && !l.contains("they wrote")),
+ "没理由的那条不该凭空长出一句引文:{lines:?}"
+ );
+
+ // 空理由不落库
+ let review2 = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO resolution_reviews (id, kb_id, left_id, right_id, score, reason, stage)
+ VALUES ($1, $2, $3, $4, 0.6, 'contains', 'human')",
+ )
+ .bind(review2)
+ .bind(f.kb)
+ .bind(f.a)
+ .bind(f.b)
+ .execute(&pool)
+ .await?;
+ utopia_store::resolution::decide_review(&pool, f.kb, review2, "keep", f.user, Some(" "))
+ .await?;
+ let blank: Option<String> =
+ sqlx::query_scalar("SELECT rationale FROM resolution_reviews WHERE id = $1")
+ .bind(review2)
+ .fetch_one(&pool)
+ .await?;
+ assert!(blank.is_none(), "只有空格等于没写");
+
+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ sqlx::query("DELETE FROM users WHERE id = $1")
+ .bind(f.user)
+ .execute(&pool)
+ .await?;
+ let gone = sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ assert_eq!(gone.rows_affected(), 1, "一次性 org 没删掉");
+ Ok(())
+}
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 e581621d..f7f299d4 100644
--- a/crates/utopia-store/tests/a_governor_reads_the_ledger.rs
+++ b/crates/utopia-store/tests/a_governor_reads_the_ledger.rs
@@ -387,7 +387,7 @@ async fn run(pool: &PgPool, s: &Seed) -> anyhow::Result<()> {
);
// 人裁了张伟 1 对 2:同簇的张伟 2 对 3 的建议作废、回到队列;Apple 的不受影响
- utopia_store::resolution::decide_review(pool, s.kb, s.zw12, "keep", s.user).await?;
+ utopia_store::resolution::decide_review(pool, s.kb, s.zw12, "keep", s.user, None).await?;
// 同一对实体人裁过:不分左右;别的对没有
let zw = by_id(s.zw12);
assert_eq!(
@@ -552,7 +552,7 @@ async fn run(pool: &PgPool, s: &Seed) -> anyhow::Result<()> {
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)
+ utopia_store::resolution::decide_review(pool, s.kb, mercury.id, "keep", s.user, None)
.await
.is_err(),
"agent 正在裁的对,人裁不了"
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 8a87b30a..132a0b52 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**: decision 3 revised 2026-09-07 (three clusters a round, #458) · decision 10 added 2026-09-07 (identity rules, name shapes, type families, the labeled set and `govern.mjs`) · decision 4 revised 2026-09-06 (the agent's own confidence decides, history moves the bar or blocks) · 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)
+- **Status**: decision 3 revised 2026-09-07 (three clusters a round, #458) · decision 10 added 2026-09-07 (identity rules, name shapes, type families, the labeled set and `govern.mjs`) · decision 4 revised 2026-09-06 (the agent's own confidence decides, history moves the bar or blocks) · 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) · [0026](0026-a-decision-records-why.md) gives a decision its stated reason, hands the batch adjudicator the same precedents and quotes the reason into them
- **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.
diff --git a/docs/decisions/0026-a-decision-records-why.md b/docs/decisions/0026-a-decision-records-why.md
new file mode 100644
index 00000000..64f2587e
--- /dev/null
+++ b/docs/decisions/0026-a-decision-records-why.md
@@ -0,0 +1,58 @@
+# 0026 · A decision records why
+
+- **Status**: Implemented · migration 0038 adds `resolution_reviews.rationale`; every human decide path (`decide_review`, the batch, an answer to the agent, a manual merge from the entity panel) takes an optional rationale, keeps it on the row and writes it as `why` on the ledger event; `Precedent.why` carries it into the prompt lines and the `ledger_search` tool; the batch adjudicator now reads the same precedents and keys its verdict cache on them; one confident pair in ten goes to a person (`escalate_sample`); the model's own `why` is written beside machine decisions
+- **Written**: 2026-09-08 (conventions in the [README](README.md))
+- **Related**: [0025](0025-governance-reads-the-ledger-before-it-decides.md) made governance read the ledger; this record makes what it reads worth reading. #356 asked for it. The impact gate (#357) and the investigating adjudicator (#358) build on it; a rationale vocabulary that converges is a rule in the sense of [0021](0021-a-rule-reads-attributes-and-concludes-a-type.md).
+
+> A person merges "Acme / Acme Corp" because the two share an address, and keeps "Zhang Wei / Zhang Wei" apart because one is a professor and the other a student. The ledger records merged, kept, by whom, when. The next morning the agent reads "a person merged Acme with Acme Corp" and proposes to merge "Acme Bank" with "Acme Corp", because the outcome is all it can see. One merge made in a hurry is read as a policy by everything that comes after it.
+
+## What was there
+
+`resolution_reviews.reason` records why a pair was **queued**: `namesake`, `contains`, `escalate_unsure`, written by the code that queued it. Nothing records why it was **decided**. The ledger event a human decision leaves (`review.merge`, `review.keep`, `merge.manual`, `merge.revert`) carries the two names, the score and the actor, and 0025 reads those events back as precedents. A precedent was therefore a verdict without a ground, and the model was told to follow it.
+
+The batch adjudicator was worse off. 0025 gave the governor precedents and kept it off the verdict cache (decision 7) because a cached answer would be one taken without them; the adjudicator kept its cache and its ignorance, sending twelve pairs a call with no history at all. And since every pair it was confident about never reached a person, the corpus of human decisions was only the hard cases: neither representative of how a person judges in general, nor usable to measure how often the machine and a person agree.
+
+## Decisions
+
+### 1. A decision may carry a rationale
+
+One free-text column, `rationale`, beside `reason`, so the two questions stay two columns: why it was queued, why it was decided. The four human paths take it: `decide_review` and the batch, an answer to the agent's proposal, and the merge-in dialog on an entity. Whitespace is null. It is asked as a question, "What told you?", in a single input beside the buttons, and it may be left empty. A required field yields "ok" and "dup" and teaches the model that people decide for no reason.
+
+### 2. The rationale lives in the ledger too
+
+Precedents are read from `audit_events`, not from the reviews table (0025 decision 1: a precedent is what a person did, and the ledger is where that is). So the rationale is also written as `detail.why` on the four events. The column is for the row a person is looking at; the ledger is for every reader that comes later, including the export.
+
+### 3. A precedent quotes its reason
+
+`Precedent.why` is read by `precedents_for` from `detail->>'why'`. `render_lines` appends `; they wrote: "…"` to same-pair, same-name and revert precedents; the type-pair habit stays counts, because a sum of reasons is not a reason. The `ledger_search` tool of the investigating loop quotes it the same way. The prompt says what to do with it: weigh the stated ground, not only the outcome; a decision made for a reason that does not hold for this pair is not a precedent for this pair. The `why` a person never wrote renders as before, so the 0025 corpus is unchanged.
+
+### 4. The adjudicator reads precedents, and its cache knows
+
+The batch adjudicator now asks `precedents_for` for each pair and sends the rendered lines with the pair, as the governor does. Its cache stays, but `pair_key` folds the rendered precedent lines into the hash. A new human decision changes the lines, the lines change the key, and the stale verdict is simply never found again. Nothing invalidates anything, and a base with no history keys exactly as before.
+
+### 5. One confident pair in ten goes to a person anyway
+
+`HUMAN_SAMPLE_PCT = 10`, chosen by `review id % 100`, so the same pair is sampled on every run and a run is reproducible. The pair is escalated with `escalate_sample|<verdict> <confidence>` instead of being applied; the card says it was sampled and what the adjudicator would have said, so nobody reads it as doubt. Two things come out of it: the human corpus keeps ordinary pairs in it, and every sampled row holds both the machine's verdict and the person's, which is the raw material for an agreement rate.
+
+### 6. The machine's why is kept, and is not a precedent
+
+`apply_verdict` writes the model's one-line `why` into the ledger on the merges and keeps it makes. `precedents_for` still reads only people's rows, as 0025 decided; the line is there so that Decisions shows what the machine went on, and so that a later reader can compare it with what the person wrote on the sampled pairs.
+
+## What a reader sees
+
+The duplicate card has an input beside Keep / Merge; the batch toolbar has one input for the whole batch; the Agent queue's answers take one; the merge-in dialog on an entity takes one. Decisions shows the quoted why beside the row, for people and for the machine. A precedent under an agent decision ends with the quote. A sampled pair reads "Sampled for a person; the adjudicator was confident (same 0.92)".
+
+## Dead ends
+
+- **A required rationale.** See decision 1.
+- **A pick-list of reasons** (same address, subsidiary, different person). The list would be wrong for the next base, and free text costs nothing when the reader is a model. If a base's rationales converge on a vocabulary, that vocabulary is a rule and belongs in 0021's shape, not in a dropdown.
+- **A `decision_rationales` table.** Two readers, two places; the ledger already is the second place, and the export already carries it.
+- **Random sampling.** A coin makes a run unrepeatable, and a pair sampled on one run and not the next would be answered from the cache on the next.
+- **Sampling inside the governor too.** The governor already proposes rather than applies whenever its gate says so, and a person answers every proposal; adding a blind sample there would double-ask. Revisit if the fuse (0025 decision 9) ever trips on pairs the gate applied.
+
+## Open questions
+
+- **Impact, not confidence** (#357). The threshold and the sample are still about confidence. What a merge would drag along, the degree of each side, the facts that move, an earlier revert on the same names, is the next gate.
+- **An adjudicator that investigates** (#358). The batch sees names, types, top facts and now precedents; the governor's loop has tools. Whether the batch should escalate into the loop instead of into the human queue is the question.
+- **The agreement rate.** The sampled rows carry both verdicts; nothing computes the rate yet, and nothing moves `HUMAN_SAMPLE_PCT` from it.
+- **History on a merge target.** The merge shows under the withdrawals it caused in the same second, which is honest chronology and hard to read. Folding consequences under their cause is presentation, and belongs with the rationale it now has.
diff --git a/docs/decisions/README.md b/docs/decisions/README.md
index 1fc3b5fa..78e0702a 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 |
+| 0026 | [A decision records why](0026-a-decision-records-why.md) | Implemented · `resolution_reviews.rationale` and `why` on the ledger event from every human decide path, precedents quote it into the prompt and the `ledger_search` tool, the batch adjudicator reads precedents and keys its cache on them, one confident pair in ten goes to a person anyway (`escalate_sample`), the model's own why is kept beside machine decisions · the impact gate (#357) and the investigating adjudicator (#358) follow |
| 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 where the agent's own confidence decides and history lowers the bar or blocks (revised after the first big-file run), 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 · identity rules the model reads and two it cannot argue with (name shapes, type families), measured against a hand-labeled set of 411 name pairs by `scripts/bench/govern.mjs` |
| 0028 | [An event holds at the moment it names](0028-an-event-holds-at-the-moment-it-names.md) | Implemented (#486) · `Validity::under` normalises every write by the predicate's `temporal` (an event is one moment written at both ends, an eternal fact has no dates), `world_axis` and `read_span` read an event as the bucket it names and an undated event at no moment, an eternal fact at every moment · the prompt marks `[event]` / `[eternal]` and says what to write · no schema change, old rows read correctly · the panel's point rendering and the ontology hint are the UI cut |
diff --git a/migrations/0038_a_decision_records_why.sql b/migrations/0038_a_decision_records_why.sql
new file mode 100644
index 00000000..9113d0a6
--- /dev/null
+++ b/migrations/0038_a_decision_records_why.sql
@@ -0,0 +1,8 @@
+-- 0026:一次裁决记下的是「为什么」,不只是「是什么」。
+--
+-- `reason` 一列早就有,但它记的是这一对**为什么被排进队列**(namesake、
+-- escalate_unsure……),由排队的代码写。人拍板时想的那句话——"同一个地址"
+-- "一个是子公司"——没有地方落。于是裁决器和治理 agent 读先例时只看得见
+-- 结果,看不见依据:一次错误的合并会被当成"这类该合"的证据,错误洗成政策。
+-- 这一列记人写的那一句;空着是允许的,问的是「什么让你这么定」,不是一张表。
+ALTER TABLE resolution_reviews ADD COLUMN rationale TEXT;
diff --git a/web/src/api.ts b/web/src/api.ts
index 2a4fad61..3756b4cc 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -586,6 +586,8 @@ export type AgentPrecedent =
left: string;
right: string;
at: string;
+ /** 人拍板时写的那一句(0026);0026 之前的决定没有 */
+ why?: string | null;
}
| { family: "type_pair"; merged: number; kept: number; reverted: number };
@@ -2047,13 +2049,15 @@ export const api = {
`/api/v1/kbs/${kbId}/review?queue=${queue}&limit=${limit}&offset=${offset}&types=${types}`,
),
/** 一批重复项同一个动作(#428):每条各自裁、各自记台账,回来逐条说成没成 */
- reviewBatch: (kbId: string, ids: string[], action: "merge" | "keep") =>
+ /** `rationale`:人拍板时写的那一句(0026)——什么让你这么定。可不写;写了就跟着
+ * 决定一起进台账,下一次裁决器和 agent 读到的先例就不只是结果 */
+ reviewBatch: (kbId: string, ids: string[], action: "merge" | "keep", rationale?: string) =>
request<{
decided: number;
outcomes: { id: string; error: string | null }[];
}>(`/api/v1/kbs/${kbId}/review/batch`, {
method: "POST",
- body: JSON.stringify({ ids, action }),
+ body: JSON.stringify({ ids, action, rationale: rationale || null }),
}),
/** 闭合日期带精度(year | month | day):写多少位就是多少精度,服务端照存 */
closeFact: (kbId: string, factId: string, validTo: string, precision: string) =>
@@ -2084,10 +2088,10 @@ export const api = {
`/api/v1/kbs/${kbId}/review/pending/${pendingId}`,
{ method: "POST", body: JSON.stringify({ action }) },
),
- decideReview: (kbId: string, reviewId: string, action: "merge" | "keep") =>
+ decideReview: (kbId: string, reviewId: string, action: "merge" | "keep", rationale?: string) =>
request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/${reviewId}`, {
method: "POST",
- body: JSON.stringify({ action }),
+ body: JSON.stringify({ action, rationale: rationale || null }),
}),
/** 对一条数据映射口径表态(0011)。改状态不删行——拒绝留痕,下一轮探索不再提议它 */
decideMapping: (
@@ -2131,10 +2135,10 @@ export const api = {
* 第一个要看的就是「我们拿什么去找的」 */
/** 手动合并:把 source 并进 target。**方向要紧**——source 消失,
* 它的事实搬到 target 上;合并可整体回滚(entity_merges 记着快照) */
- mergeEntities: (kbId: string, source: string, target: string) =>
+ mergeEntities: (kbId: string, source: string, target: string, rationale?: string) =>
request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/entities/merge`, {
method: "POST",
- body: JSON.stringify({ source, target }),
+ body: JSON.stringify({ source, target, rationale: rationale || null }),
}),
typeResolutionPreview: (kbId: string) =>
request<{ items: TypeSuggestion[] }>(
@@ -2209,10 +2213,15 @@ export const api = {
request<ReviewSummary>(`/api/v1/kbs/${kbId}/review/summary`),
/** 回答 agent 的一笔(0025):merge / keep 答一条建议,revert 撤回一条自动合并,
* merge 也能推翻一条自动分开。走的是人的裁决路径,成为新先例 */
- agentAnswer: (kbId: string, decisionId: string, action: "merge" | "keep" | "revert") =>
+ agentAnswer: (
+ kbId: string,
+ decisionId: string,
+ action: "merge" | "keep" | "revert",
+ rationale?: string,
+ ) =>
request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/agent/${decisionId}`, {
method: "POST",
- body: JSON.stringify({ action }),
+ body: JSON.stringify({ action, rationale: rationale || null }),
}),
reviewHistory: (kbId: string, page: number, per = 20) =>
request<{ events: ReviewHistoryEvent[]; total: number }>(
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 48aad6af..3be258ce 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -1637,6 +1637,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",
+ /* 抽给人看的一份(0026):机器有把握也不动手,detail 是它本来的答案 */
+ escalate_sample: "Sampled for a person; the adjudicator was confident",
proposed: "The agent looked and left a proposal",
governed: "Decided by the agent from precedent",
namesake: "Two entities with this name in one document",
@@ -1659,6 +1661,8 @@ export const en = {
noFacts: "No recorded facts",
merge: "Merge",
keep: "Keep separate",
+ /** 理由框(0026)。是一个问题,不是一张表:可以不答 */
+ rationalePlaceholder: "What told you? Optional",
// 重复项的类型筛选与批量裁决(#428)
typesAny: "All",
typesSame: "Same type",
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 12163415..2d3cd984 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -1434,6 +1434,7 @@ export const zh: Strings = {
escalate_no_verdict: "裁决没有给出结论",
escalate_entity_changed: "裁决过程中实体发生了变化",
escalate_unsure: "裁决的把握不够",
+ escalate_sample: "抽给人看的一份;裁决器本有把握",
proposed: "agent 看过了,留了一条建议",
governed: "agent 按先例裁的",
namesake: "同一篇文档里有两个同名实体",
@@ -1454,6 +1455,7 @@ export const zh: Strings = {
noFacts: "没有记录的事实",
merge: "合并",
keep: "保持分开",
+ rationalePlaceholder: "什么让你这么定?可不写",
typesAny: "全部",
typesSame: "同类型",
typesConflict: "类型不同",
diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsx
index 2b4dc270..c01b8d6f 100644
--- a/web/src/pages/Graph.tsx
+++ b/web/src/pages/Graph.tsx
@@ -2686,13 +2686,16 @@ function EntityPanel({
const [mergeCandidate, setMergeCandidate] = useState<{ id: string; name: string } | null>(
null,
);
+ // 什么让你这么定(0026):可不写;写了就跟着合并进台账
+ const [mergeWhy, setMergeWhy] = useState("");
const merge = useMutation({
- mutationFn: (source: string) => api.mergeEntities(kbId, source, entityId),
+ mutationFn: ({ source, why }: { source: string; why: string }) =>
+ api.mergeEntities(kbId, source, entityId, why),
onSuccess: () => {
toast.success(S.toast.saved);
// 本地把并掉的那个摘掉,别等重取——它已经不存在了,留着会让人再点一次
setSameName((prev) =>
- (prev ?? sameName).filter((p) => p.id !== merge.variables),
+ (prev ?? sameName).filter((p) => p.id !== merge.variables?.source),
);
qc.invalidateQueries({ queryKey: ["entity", kbId, entityId] });
qc.invalidateQueries({ queryKey: ["graph"] });
@@ -2847,11 +2850,22 @@ function EntityPanel({
cancelLabel={S.graph.editCancel}
busy={merge.isPending}
onConfirm={() => {
- merge.mutate(mergeCandidate.id);
+ merge.mutate({ source: mergeCandidate.id, why: mergeWhy });
setMergeCandidate(null);
+ setMergeWhy("");
}}
- onCancel={() => setMergeCandidate(null)}
- />
+ onCancel={() => {
+ setMergeCandidate(null);
+ setMergeWhy("");
+ }}
+ >
+ <Input
+ className="w-full"
+ placeholder={S.review.rationalePlaceholder}
+ value={mergeWhy}
+ onChange={(e) => setMergeWhy(e.target.value)}
+ />
+ </DangerConfirm>
)}
{/* 视图切换:Relations(一张表,过去的折在组尾)| History(记录轴)| Derived */}
diff --git a/web/src/pages/Review.tsx b/web/src/pages/Review.tsx
index 3f184c5c..08613ad2 100644
--- a/web/src/pages/Review.tsx
+++ b/web/src/pages/Review.tsx
@@ -122,9 +122,11 @@ function DuplicateCard({
/** 批量选中(#428):勾在卡片左上,选了就跟着上面的批量按钮走 */
picked: boolean;
onPick: (picked: boolean) => void;
- onDecide: (action: "merge" | "keep") => void;
+ /** 第二个参数是人写的那一句(0026):什么让你这么定。可空 */
+ onDecide: (action: "merge" | "keep", rationale?: string) => void;
}) {
const reasonCode = item.reason?.split("|", 1)[0];
+ const [why, setWhy] = useState("");
return (
<div className={cn("glass rounded-panel p-4", picked && "u-picked")}>
@@ -182,16 +184,25 @@ function DuplicateCard({
{escalationText(item.reason)}
</span>
)}
- <div className="ml-auto flex gap-2 shrink-0">
+ {/* 理由框(0026):可不写;写了就跟着决定进台账,下一次先例带着它 */}
+ <div className="ml-auto flex items-center gap-2 shrink-0">
+ <Input
+ size="sm"
+ className="w-56"
+ placeholder={S.review.rationalePlaceholder}
+ value={why}
+ disabled={busy || locked}
+ onChange={(e) => setWhy(e.target.value)}
+ />
<Button variant="secondary" size="sm"
disabled={busy || locked}
- onClick={() => onDecide("keep")}
+ onClick={() => onDecide("keep", why)}
>
{S.review.keep}
</Button>
<Button variant="primary" size="sm"
disabled={busy || locked}
- onClick={() => onDecide("merge")}
+ onClick={() => onDecide("merge", why)}
>
{S.review.merge}
</Button>
@@ -493,7 +504,9 @@ function precedentText(p: AgentPrecedent): string {
: p.action === "review.keep"
? S.review.agentPrecedentKept
: S.review.agentPrecedentMerged;
- return `${p.left} ≟ ${p.right} · ${verb} · ${p.at.slice(0, 10)}`;
+ const line = `${p.left} ≟ ${p.right} · ${verb} · ${p.at.slice(0, 10)}`;
+ // 人写的那一句(0026)跟在后面:先例不只是结果
+ return p.why ? `${line} · “${p.why}”` : line;
}
function AgentRow({
@@ -503,9 +516,10 @@ function AgentRow({
}: {
d: AgentDecision;
busy: boolean;
- onAnswer: (action: "merge" | "keep" | "revert") => void;
+ onAnswer: (action: "merge" | "keep" | "revert", rationale?: string) => void;
}) {
const [open, setOpen] = useState(false);
+ const [why, setWhy] = useState("");
const precedents = d.precedents ?? [];
const trace = d.trace ?? [];
const hasDetail = precedents.length > 0 || trace.length > 0;
@@ -566,24 +580,35 @@ function AgentRow({
? 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">
+ <div className="ml-auto flex items-center gap-2 shrink-0">
+ {/* 回答 agent 也能带一句理由(0026)——它走的正是人的裁决路径 */}
+ {(d.status === "proposed" || d.status === "applied") && (
+ <Input
+ size="sm"
+ className="w-56"
+ placeholder={S.review.rationalePlaceholder}
+ value={why}
+ disabled={busy}
+ onChange={(e) => setWhy(e.target.value)}
+ />
+ )}
{d.status === "proposed" && (
<>
- <Button variant="secondary" size="sm" disabled={busy} onClick={() => onAnswer("keep")}>
+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => onAnswer("keep", why)}>
{S.review.keep}
</Button>
- <Button variant="primary" size="sm" disabled={busy} onClick={() => onAnswer("merge")}>
+ <Button variant="primary" size="sm" disabled={busy} onClick={() => onAnswer("merge", why)}>
{S.review.merge}
</Button>
</>
)}
{d.status === "applied" && d.action === "merge" && (
- <Button variant="secondary" size="sm" disabled={busy} onClick={() => onAnswer("revert")}>
+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => onAnswer("revert", why)}>
{S.review.revert}
</Button>
)}
{d.status === "applied" && d.action === "keep" && (
- <Button variant="secondary" size="sm" disabled={busy} onClick={() => onAnswer("merge")}>
+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => onAnswer("merge", why)}>
{S.review.merge}
</Button>
)}
@@ -628,6 +653,12 @@ function DecisionRow({ e }: { e: ReviewHistoryEvent }) {
{S.review.decisionActions[e.action] ?? e.action}
</Chip>
<span className="text-body text-ink-2 truncate min-w-0">{text}</span>
+ {/* 人(或模型)写的那一句(0026);老行没有 */}
+ {typeof d.why === "string" && d.why && (
+ <span className="text-small text-ink-2 truncate min-w-0">
+ “{d.why}”
+ </span>
+ )}
{typeof d.confidence === "number" && (
<span className="u-num text-small text-ink-2 shrink-0">
{Math.round(d.confidence * 100)}%
@@ -1025,6 +1056,7 @@ export function Review() {
// 之后勾着的东西已经不在眼前,留着会让「合并所选」合掉看不见的东西
const [types, setTypes] = useState<ReviewTypeFilter>("any");
const [picked, setPicked] = useState<Set<string>>(() => new Set());
+ const [batchWhy, setBatchWhy] = useState("");
useEffect(() => setPicked(new Set()), [page, sel, types]);
// 队列变化经 SSE 事件流推送(useKbEvents 挂在 Shell),无需轮询。
@@ -1074,21 +1106,42 @@ export function Review() {
};
const decide = useMutation({
- mutationFn: ({ id, action }: { id: string; action: "merge" | "keep" }) =>
- api.decideReview(kb!.id, id, action),
+ mutationFn: ({
+ id,
+ action,
+ rationale,
+ }: {
+ id: string;
+ action: "merge" | "keep";
+ rationale?: string;
+ }) => api.decideReview(kb!.id, id, action, rationale),
onSettled: invalidate,
});
// 回答 agent 的一笔(0025):走人的裁决路径,成为下一轮的先例
const agentAnswer = useMutation({
- mutationFn: ({ id, action }: { id: string; action: "merge" | "keep" | "revert" }) =>
- api.agentAnswer(kb!.id, id, action),
+ mutationFn: ({
+ id,
+ action,
+ rationale,
+ }: {
+ id: string;
+ action: "merge" | "keep" | "revert";
+ rationale?: string;
+ }) => api.agentAnswer(kb!.id, id, action, rationale),
onError: (e) => toast.error((e as Error).message),
onSettled: invalidate,
});
// 批量裁决:一批一个动作,回来逐条说成没成;没成的留在列表里,成了的消失
const batch = useMutation({
- mutationFn: ({ ids, action }: { ids: string[]; action: "merge" | "keep" }) =>
- api.reviewBatch(kb!.id, ids, action),
+ mutationFn: ({
+ ids,
+ action,
+ rationale,
+ }: {
+ ids: string[];
+ action: "merge" | "keep";
+ rationale?: string;
+ }) => api.reviewBatch(kb!.id, ids, action, rationale),
onSuccess: (r) => {
const failed = r.outcomes.filter((o) => o.error).length;
if (failed > 0) toast.error(S.review.batchDone(r.decided, failed));
@@ -1097,6 +1150,7 @@ export function Review() {
onError: (e) => toast.error((e as Error).message),
onSettled: () => {
setPicked(new Set());
+ setBatchWhy("");
invalidate();
},
});
@@ -1470,12 +1524,25 @@ export function Review() {
<span className="u-num text-small text-ink-2">
{S.review.selected(picked.size)}
</span>
+ {/* 一批一句理由(0026):这一批为什么一起这么定 */}
+ <Input
+ size="sm"
+ className="w-44"
+ placeholder={S.review.rationalePlaceholder}
+ value={batchWhy}
+ disabled={batch.isPending}
+ onChange={(e) => setBatchWhy(e.target.value)}
+ />
<Button
variant="secondary"
size="sm"
disabled={batch.isPending}
onClick={() =>
- batch.mutate({ ids: [...picked], action: "keep" })
+ batch.mutate({
+ ids: [...picked],
+ action: "keep",
+ rationale: batchWhy,
+ })
}
>
{S.review.keepSelected}
@@ -1485,7 +1552,11 @@ export function Review() {
size="sm"
disabled={batch.isPending}
onClick={() =>
- batch.mutate({ ids: [...picked], action: "merge" })
+ batch.mutate({
+ ids: [...picked],
+ action: "merge",
+ rationale: batchWhy,
+ })
}
>
{S.review.mergeSelected}
@@ -1516,8 +1587,8 @@ export function Review() {
(decide.isPending && decide.variables?.id === item.id) ||
(batch.isPending && picked.has(item.id))
}
- onDecide={(action) =>
- decide.mutate({ id: item.id, action })
+ onDecide={(action, rationale) =>
+ decide.mutate({ id: item.id, action, rationale })
}
/>
))}
@@ -1723,7 +1794,9 @@ export function Review() {
key={d.id}
d={d}
busy={agentAnswer.isPending && agentAnswer.variables?.id === d.id}
- onAnswer={(action) => agentAnswer.mutate({ id: d.id, action })}
+ onAnswer={(action, rationale) =>
+ agentAnswer.mutate({ id: d.id, action, rationale })
+ }
/>
))}
</div>
diff --git a/web/src/ui/dialog.tsx b/web/src/ui/dialog.tsx
index 1c1347e2..55f3f1d2 100644
--- a/web/src/ui/dialog.tsx
+++ b/web/src/ui/dialog.tsx
@@ -85,6 +85,7 @@ export function DangerConfirm({
busy,
onConfirm,
onCancel,
+ children,
}: {
title: string;
hint: string;
@@ -95,6 +96,8 @@ export function DangerConfirm({
busy?: boolean;
onConfirm: () => void;
onCancel: () => void;
+ /** 解锁框之下的补充控件(合并弹窗里的理由框);缺省没有 */
+ children?: ReactNode;
}) {
const [text, setText] = useState("");
const unlocked = !requireText || text === requireText;
@@ -133,6 +136,7 @@ export function DangerConfirm({
onChange={(e) => setText(e.target.value)}
/>
)}
+ {children}
</Dialog>
);
}