World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
The agent looks before it asks (0025, second cut) (#438)
WaylandYang2dc991f146bf
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rsindex caea8a7e..c3a59847 100644--- a/crates/utopia-core/src/models.rs+++ b/crates/utopia-core/src/models.rs@@ -1252,6 +1252,12 @@ pub struct AgentDecisionView {/// proposed | applied | accepted | overridden | reverted | supersededpub status: String,pub merge_id: Option<Uuid>,+ /// defer 留给人的那一个问题;只有 unsure 的行才有+ pub question: Option<String>,+ /// 它看了什么:[{tool, args, note}]+ pub trace: serde_json::Value,+ /// 循环里花的模型调用次数+ pub calls: i32,pub created_at: DateTime<Utc>,pub decided_at: Option<DateTime<Utc>>,pub decided_by_name: Option<String>,diff --git a/crates/utopia-extract/src/governor.rs b/crates/utopia-extract/src/governor.rsnew file mode 100644index 00000000..beb1c95b--- /dev/null+++ b/crates/utopia-extract/src/governor.rs@@ -0,0 +1,311 @@+//! 治理的第二层(0025 第二刀):攒批判不定的对,逐条带工具再看一遍。+//!+//! 模型能看的东西:一侧的全部事实、一侧的原文片段、台账里人对某个名字的决定、+//! 库里名字相近的其他实体。结束只有两种:`decide`(same / different + 置信度 ++//! 一句理由)或 `defer`(留给人一个具体的问题)。工具定义、提示词与回合的解析+//! 在这里;跑循环、查库的在 server 的 governance 任务里——这里不碰库也不碰模型。++use serde_json::{json, Value};++use crate::AdjudicationPair;++/// 一对最多查几次再表态。够看两侧的事实与原文各一次、翻一次台账,还剩一次+pub const MAX_STEPS: usize = 6;++/// 攒批那一眼说了什么:带进第二眼,模型知道自己上次为什么没定+pub struct EarlierLook<'a> {+ /// same | different | unsure+ pub verdict: &'a str,+ pub confidence: f32,+ pub why: Option<&'a str>,+}++/// 模型在一个回合里要的事+#[derive(Debug, PartialEq)]+pub enum Step {+ /// 查一样东西:facts / quotes / ledger / namesakes+ Lookup {+ tool: String,+ args: Value,+ },+ Decide {+ same: bool,+ confidence: f32,+ why: String,+ },+ Defer {+ question: String,+ },+ /// 认不出的工具名或缺参数:告诉模型,别猜+ Unknown(String),+}++/// OpenAI 协议的 function 定义+pub fn tools() -> Value {+ let side = json!({+ "type": "object",+ "properties": { "side": { "type": "string", "enum": ["A", "B"] } },+ "required": ["side"]+ });+ let query = json!({+ "type": "object",+ "properties": { "query": { "type": "string" } },+ "required": ["query"]+ });+ json!([+ { "type": "function", "function": {+ "name": "facts",+ "description": "Every recorded fact of one side (A or B): its relations to other entities, with time ranges where known.",+ "parameters": side }},+ { "type": "function", "function": {+ "name": "quotes",+ "description": "Source passages that mention one side: the sentences its facts were extracted from, each with the document it comes from.",+ "parameters": side }},+ { "type": "function", "function": {+ "name": "ledger",+ "description": "What people in this base decided before about a name: merges, keeps and reverted merges whose names contain the query.",+ "parameters": query }},+ { "type": "function", "function": {+ "name": "namesakes",+ "description": "Other entities in this base whose name contains the query, with their type and how many facts they carry.",+ "parameters": query }},+ { "type": "function", "function": {+ "name": "decide",+ "description": "Give the verdict for this pair.",+ "parameters": {+ "type": "object",+ "properties": {+ "verdict": { "type": "string", "enum": ["same", "different"] },+ "confidence": { "type": "number", "minimum": 0, "maximum": 1 },+ "why": { "type": "string", "description": "One sentence naming the fact, passage or precedent that settled it." }+ },+ "required": ["verdict", "confidence", "why"]+ }}},+ { "type": "function", "function": {+ "name": "defer",+ "description": "Leave the pair for a person, when no lookup can settle it.",+ "parameters": {+ "type": "object",+ "properties": {+ "question": { "type": "string", "description": "The one question a person could answer at a glance, naming the fact or document that would settle it." }+ },+ "required": ["question"]+ }}}+ ])+}++/// 对话的开头:系统提示 + 这一对 + 上一眼的结论+pub fn messages(pair: &AdjudicationPair, earlier: &EarlierLook) -> Vec<Value> {+ let system = format!(+ "You are an entity-resolution adjudicator for a knowledge graph, looking at ONE pair of \+ records that an earlier, quicker look could not settle. Decide whether the two records \+ refer to the SAME real-world entity or are namesakes.\n\+ \n\+ Judge by the facts: employer or affiliation, role, time ranges, connected entities. \+ Identical names alone are NEVER sufficient evidence of sameness. Contradictory \+ affiliations in overlapping time periods mean different entities; non-overlapping \+ periods can be one person who changed jobs. One name containing the other is usually \+ the longer one abbreviated (documents drop the qualifier after first mention), unless \+ the longer one adds a noun or a phrase at the end: a project, a programme, a team or a \+ component is its own record.\n\+ \n\+ You may look things up before answering, at most {MAX_STEPS} lookups: the facts of a \+ side, the source passages that mention a side, what people in this base decided about \+ a name, and other entities with a similar name. People's earlier decisions are how the \+ owners of this base want such cases judged; follow them unless the facts of this pair \+ clearly differ, and never let one override a contradiction in the facts. Look only for \+ what would change your answer.\n\+ \n\+ Finish with exactly one tool call: decide (same or different, a confidence in 0~1, and \+ one sentence naming the fact, passage or precedent that settled it) or defer (when no \+ lookup can settle it: leave the ONE question a person could answer at a glance, naming \+ the fact or document that would settle it). A wrong merge is far more damaging than \+ leaving two records separate: when the evidence is thin, defer."+ );+ let side = |label: &str, s: &crate::AdjudicationSide| {+ let facts = if s.facts.is_empty() {+ " (no recorded facts)".to_string()+ } else {+ s.facts+ .iter()+ .map(|f| format!(" - {f}"))+ .collect::<Vec<_>>()+ .join("\n")+ };+ format!("Record {label}: \"{}\" ({})\n{facts}", s.name, s.type_label)+ };+ let precedents = if pair.precedents.is_empty() {+ String::new()+ } else {+ let lines = pair+ .precedents+ .iter()+ .map(|l| format!(" - {l}"))+ .collect::<Vec<_>>()+ .join("\n");+ format!("Precedents (decided by people in this base):\n{lines}\n")+ };+ let why = earlier.why.map(|w| format!(" — {w}")).unwrap_or_default();+ let user = format!(+ "{}\n{}\n{precedents}The earlier look said: {} ({:.2}){why}.",+ side("A", &pair.left),+ side("B", &pair.right),+ earlier.verdict,+ earlier.confidence,+ );+ vec![+ json!({ "role": "system", "content": system }),+ json!({ "role": "user", "content": user }),+ ]+}++/// 模型让工具循环去找结论时的提醒+pub const NUDGE: &str = "Finish with the decide or defer tool.";++/// 一个工具调用读成一步。参数是协议原样的 JSON 字符串+pub fn read_step(name: &str, arguments: &str) -> Step {+ let args: Value = serde_json::from_str(arguments).unwrap_or(json!({}));+ match name {+ "facts" | "quotes" => match args["side"].as_str() {+ Some("A") | Some("B") => Step::Lookup {+ tool: name.into(),+ args,+ },+ _ => Step::Unknown(format!("{name} needs side A or B")),+ },+ "ledger" | "namesakes" => match args["query"].as_str() {+ Some(q) if !q.trim().is_empty() => Step::Lookup {+ tool: name.into(),+ args,+ },+ _ => Step::Unknown(format!("{name} needs a query")),+ },+ "decide" => {+ let same = match args["verdict"].as_str() {+ Some("same") => true,+ Some("different") => false,+ _ => return Step::Unknown("decide needs verdict same or different".into()),+ };+ let confidence = args["confidence"]+ .as_f64()+ .map(|c| c as f32)+ .unwrap_or(0.5)+ .clamp(0.0, 1.0);+ let why = args["why"].as_str().unwrap_or("").trim().to_string();+ Step::Decide {+ same,+ confidence,+ why,+ }+ }+ "defer" => match args["question"].as_str().map(str::trim) {+ Some(q) if !q.is_empty() => Step::Defer {+ question: q.to_string(),+ },+ _ => Step::Unknown("defer needs a question".into()),+ },+ other => Step::Unknown(format!("no tool named {other}")),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::AdjudicationSide;++ #[test]+ fn a_lookup_needs_its_argument() {+ assert_eq!(+ read_step("facts", r#"{"side":"A"}"#),+ Step::Lookup {+ tool: "facts".into(),+ args: json!({ "side": "A" })+ }+ );+ assert!(matches!(+ read_step("facts", r#"{"side":"C"}"#),+ Step::Unknown(_)+ ));+ assert!(matches!(read_step("ledger", r#"{}"#), Step::Unknown(_)));+ assert!(matches!(read_step("ledger", "not json"), Step::Unknown(_)));+ assert!(matches!(+ read_step("namesakes", r#"{"query":"Apple"}"#),+ Step::Lookup { .. }+ ));+ }++ #[test]+ fn a_decision_is_read_and_clamped() {+ assert_eq!(+ read_step(+ "decide",+ r#"{"verdict":"same","confidence":1.7,"why":"one CEO"}"#+ ),+ Step::Decide {+ same: true,+ confidence: 1.0,+ why: "one CEO".into()+ }+ );+ assert!(matches!(+ read_step("decide", r#"{"verdict":"maybe"}"#),+ Step::Unknown(_)+ ));+ assert_eq!(+ read_step(+ "defer",+ r#"{"question":" Is the 2024 CFO the same person? "}"#+ ),+ Step::Defer {+ question: "Is the 2024 CFO the same person?".into()+ }+ );+ assert!(matches!(+ read_step("defer", r#"{"question":""}"#),+ Step::Unknown(_)+ ));+ assert!(matches!(read_step("smash", "{}"), Step::Unknown(_)));+ }++ #[test]+ fn the_opening_carries_the_pair_and_the_earlier_look() {+ let pair = AdjudicationPair {+ left: AdjudicationSide {+ name: "Zhang Wei".into(),+ type_label: "Person".into(),+ facts: vec!["works at → Nebula".into()],+ },+ right: AdjudicationSide {+ name: "Zhang Wei".into(),+ type_label: "Person".into(),+ facts: vec![],+ },+ precedents: vec!["this same pair was kept apart by a person on 2026-09-01".into()],+ };+ let m = messages(+ &pair,+ &EarlierLook {+ verdict: "unsure",+ confidence: 0.5,+ why: Some("no facts on B"),+ },+ );+ assert_eq!(m.len(), 2);+ let user = m[1]["content"].as_str().unwrap();+ assert!(user.contains("Record A: \"Zhang Wei\" (Person)"));+ assert!(user.contains("(no recorded facts)"));+ assert!(user.contains("kept apart by a person"));+ assert!(user.contains("The earlier look said: unsure (0.50) — no facts on B."));+ let tools = tools();+ let names: Vec<&str> = tools+ .as_array()+ .unwrap()+ .iter()+ .map(|t| t["function"]["name"].as_str().unwrap())+ .collect();+ assert_eq!(+ names,+ ["facts", "quotes", "ledger", "namesakes", "decide", "defer"]+ );+ }+}diff --git a/crates/utopia-extract/src/lib.rs b/crates/utopia-extract/src/lib.rsindex fcb31122..b47f3694 100644--- a/crates/utopia-extract/src/lib.rs+++ b/crates/utopia-extract/src/lib.rs@@ -5,6 +5,8 @@ use chrono::{DateTime, NaiveDate, TimeZone, Utc};use serde::Deserialize;use utopia_llm::ChatMessage;+pub mod governor;+#[derive(Debug, Deserialize)]pub struct Extraction {#[serde(default)]diff --git a/crates/utopia-server/src/governance.rs b/crates/utopia-server/src/governance.rsindex 6f20125e..c28be980 100644--- a/crates/utopia-server/src/governance.rs+++ b/crates/utopia-server/src/governance.rs@@ -1,9 +1,13 @@//! 治理任务(0025):开关开着就把等人的重复对按先进先出过一遍,先读台账再裁。//!-//! 队头带着它的簇进一次模型调用;过闸的自己动手(合并可撤、分开可再合),-//! 过不了的写成建议留给人。两簇之间看一眼开关,关掉就停在这里——「关闭后队列-//! 自动终止」就是那一行。模型缺席时任务成功结束、什么都不动:没有依据的裁决-//! 不如不裁,队列原地等。+//! 两层。第一层是攒批:队头带着它的簇进一次模型调用,先例已经在提示词里;过闸的+//! 自己动手(合并可撤、分开可再合)。第二层(第二刀)只接第一层**判不定**的对:+//! 逐条带工具再看一遍——一侧的全部事实、原文片段、台账里人对这个名字的决定、+//! 同名的其他实体——看完要么 decide,要么 defer 留一个具体的问题给人。硬规则拦下+//! 的对(类型冲突、有撤回、与人对这一对的决定相反)不进第二层:再看也不会改规则。+//!+//! 两簇之间看一眼开关,关掉就停在这里——「关闭后队列自动终止」就是那一行。模型+//! 缺席时任务成功结束、什么都不动:没有依据的裁决不如不裁,队列原地等。//!//! 与攒批裁决器(`adjudication`)的分工:开关关着,那一档照旧独自判灰区对;//! 开着,抽取结束排的是这里,灰区对与等人的对都从这条队列走。这里不读也不写@@ -11,16 +15,71 @@use crate::llm_util;use crate::state::AppState;+use serde_json::{json, Value};use std::collections::HashMap;-use utopia_core::models::ReviewItem;+use utopia_core::models::{LlmSettings, ReviewItem};use utopia_core::AppError;-use utopia_store::governance::{self, Gate, NewDecision, Precedents};+use utopia_extract::governor::{self, Step};+use utopia_llm::{tool_result_message, LlmClient};+use utopia_store::governance::{self as gov, Gate, NewDecision, Precedents, AUTO_CONF};use uuid::Uuid;/// 一次模型调用带几对:队头加它的簇const BATCH_SIZE: i64 = 12;/// 一个任务最多走几轮,之后再排一个接着走——让别的库的任务也轮得上const MAX_ROUNDS: usize = 20;+/// 每库每天第二层最多花几次模型调用。用完了,判不定的对照第一刀写成建议+const LOOP_DAILY_CALLS: i64 = 300;+/// 一次工具结果最多给模型多少字:原文片段与事实列表都可能很长+const TOOL_OUTPUT_CHARS: usize = 3000;++/// 一轮任务里到处要带的东西+struct Ctx<'a> {+ state: &'a AppState,+ kb_id: Uuid,+ run_id: Uuid,+ client: &'a LlmClient,+ settings: &'a Option<LlmSettings>,+}++/// 对一对的一次看法:第一层给的,或第二层看完改过的+struct Look {+ same: Option<bool>,+ conf: f32,+ why: Option<String>,+ /// defer 留下的问题+ question: Option<String>,+ /// 第二层看了什么+ trace: Vec<Value>,+ /// 第二层花的模型调用+ calls: i32,+}++impl Look {+ fn from_batch(same: Option<bool>, conf: f32, why: Option<String>) -> Self {+ Look {+ same,+ conf,+ why,+ question: None,+ trace: Vec::new(),+ calls: 0,+ }+ }++ /// 第一层没定:没判决,或置信度不到线+ fn uncertain(&self) -> bool {+ self.same.is_none() || self.conf < AUTO_CONF+ }++ fn action(&self) -> &'static str {+ match self.same {+ Some(true) => "merge",+ Some(false) => "keep",+ None => "unsure",+ }+ }+}pub async fn govern(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {let kb = utopia_store::kbs::get(&state.pool, kb_id).await?;@@ -32,7 +91,13 @@ pub async fn govern(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {tracing::info!(%kb_id, "治理:没有配聊天模型,队列原地等");return Ok(());};- let run_id = Uuid::now_v7();+ let ctx = Ctx {+ state,+ kb_id,+ run_id: Uuid::now_v7(),+ client: &client,+ settings: &settings,+ };for _ in 0..MAX_ROUNDS {// 关闭后队列自动终止:每一簇之前看一眼@@ -40,45 +105,35 @@ pub async fn govern(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {tracing::info!(%kb_id, "治理:开关已关,停在这里");return Ok(());}- let Some(head) = governance::queue(&state.pool, kb_id, 1)- .await?- .into_iter()- .next()- else {+ let Some(head) = gov::queue(&state.pool, kb_id, 1).await?.into_iter().next() else {return Ok(());};let mut items = vec![head];- let siblings =- governance::cluster_of(&state.pool, kb_id, &items[0], BATCH_SIZE - 1).await?;+ let siblings = gov::cluster_of(&state.pool, kb_id, &items[0], BATCH_SIZE - 1).await?;items.extend(siblings);let mut precedents = Vec::with_capacity(items.len());for item in &items {- precedents.push(governance::precedents_for(&state.pool, kb_id, item).await?);+ precedents.push(gov::precedents_for(&state.pool, kb_id, item).await?);}let pairs: Vec<utopia_extract::AdjudicationPair> = items.iter().zip(&precedents)- .map(|(item, p)| utopia_extract::AdjudicationPair {- left: side(&item.left),- right: side(&item.right),- precedents: governance::render_lines(p),- })+ .map(|(item, p)| pair_of(item, p)).collect();let messages = utopia_extract::build_adjudication_messages(&pairs);- let _permit = match settings.as_ref().map(|s| llm_util::acquire_chat(state, s)) {- Some(f) => f.await,- None => None,+ let reply = {+ let _permit = permit(&ctx).await;+ // 调用/解析失败 → 任务按退避重试;重试耗尽后这些对留在队列里,人照样能裁+ client.chat(&messages).await?};- // 调用/解析失败 → 任务按退避重试;重试耗尽后这些对留在队列里,人照样能裁- let reply = client.chat(&messages).await?;let verdicts = utopia_extract::parse_adjudication(&reply)?;let by_i: HashMap<usize, &utopia_extract::AdjudicationVerdict> =verdicts.iter().map(|v| (v.i, v)).collect();for (idx, item) in items.iter().enumerate() {- let (same, conf, why) = match by_i.get(&idx) {- Some(v) => (+ let look = match by_i.get(&idx) {+ Some(v) => Look::from_batch(match v.verdict.as_str() {"same" => Some(true),"different" => Some(false),@@ -87,79 +142,95 @@ pub async fn govern(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {v.confidence.unwrap_or(0.5).clamp(0.0, 1.0),v.why.clone(),),- None => (None, 0.0, None),+ None => Look::from_batch(None, 0.0, None),};- settle(- state,- kb_id,- run_id,- item,- &precedents[idx],- same,- conf,- why.as_deref(),- )- .await?;+ settle(&ctx, item, &pairs[idx], &precedents[idx], look).await?;}state.emit_review(kb_id);}// 轮数用完还有积压:再排一个,下一轮从队头接着走- if !governance::queue(&state.pool, kb_id, 1).await?.is_empty() {- utopia_store::jobs::enqueue_unless_queued(- &state.pool,- "govern",- serde_json::json!({ "kb_id": kb_id }),- )- .await?;+ 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(())}-fn side(s: &utopia_core::models::ReviewSide) -> utopia_extract::AdjudicationSide {- utopia_extract::AdjudicationSide {+async fn permit(ctx: &Ctx<'_>) -> Option<tokio::sync::OwnedSemaphorePermit> {+ match ctx.settings.as_ref() {+ Some(s) => llm_util::acquire_chat(ctx.state, s).await,+ None => None,+ }+}++fn pair_of(item: &ReviewItem, p: &Precedents) -> utopia_extract::AdjudicationPair {+ let side = |s: &utopia_core::models::ReviewSide| utopia_extract::AdjudicationSide {name: s.name.clone(),type_label: s.type_label.clone().unwrap_or_else(|| "untyped".into()),facts: s.top_facts.clone(),+ };+ utopia_extract::AdjudicationPair {+ left: side(&item.left),+ right: side(&item.right),+ precedents: gov::render_lines(p),}}-/// 一对的判决落地:过闸就动手并记 applied,否则转人工并记 proposed-#[allow(clippy::too_many_arguments)]+/// 一对的判决落地:第一层判不定的先进第二层再看;过闸就动手并记 applied,+/// 否则转人工并记 proposed(带着问题与轨迹)async fn settle(- state: &AppState,- kb_id: Uuid,- run_id: Uuid,+ ctx: &Ctx<'_>,item: &ReviewItem,+ pair: &utopia_extract::AdjudicationPair,p: &Precedents,- same: Option<bool>,- conf: f32,- why: Option<&str>,+ mut look: Look,) -> anyhow::Result<()> {- let pool = &state.pool;+ let pool = &ctx.state.pool;+ let kb_id = ctx.kb_id;let types_conflict = matches!((&item.left.type_label, &item.right.type_label),(Some(a), Some(b)) if a != b);- let action = match same {- Some(true) => "merge",- Some(false) => "keep",- None => "unsure",- };- let precedents = governance::precedents_json(p);++ // 第二层:只接判不定的,硬规则拦下的不进。预算用完了照第一刀写建议+ if gov::gate(look.same, look.conf, types_conflict, p) == Gate::Propose+ && look.uncertain()+ && p.reverts.is_empty()+ {+ let spent = gov::loop_calls_today(pool, kb_id).await?;+ if spent < LOOP_DAILY_CALLS {+ match investigate(ctx, item, pair, &look).await {+ Ok(l) => look = l,+ // 第二层失败不拖累第一层:这一对照第一层的看法写成建议+ Err(e) => {+ tracing::warn!(%kb_id, review = %item.id, error = %e, "治理:第二层没跑完")+ }+ }+ } else {+ tracing::info!(%kb_id, spent, "治理:今天的循环预算用完,判不定的只写建议");+ }+ }++ let action = look.action();+ let precedents = gov::precedents_json(p);+ let conf = look.conf;let decision = |status: &'static str, merge_id: Option<Uuid>| NewDecision {- run_id,+ run_id: ctx.run_id,target_id: item.id,action,confidence: conf,- reason: why,+ reason: look.why.as_deref(),precedents: precedents.clone(),status,merge_id,+ question: look.question.as_deref(),+ trace: Value::Array(look.trace.clone()),+ calls: look.calls,};- match governance::gate(same, conf, types_conflict, p) {- Gate::Apply if same == Some(true) => {+ match gov::gate(look.same, look.conf, types_conflict, p) {+ Gate::Apply if look.same == Some(true) => {let reason = format!("governed|{conf:.2}");// 同簇连锁:前一对合完,这一对的一侧可能已经并进了别人——合活着的那个let (l, r) = (@@ -170,8 +241,8 @@ async fn settle(// 两边已经是同一个实体:只剩把审核行关上utopia_store::resolution::close_review_auto(pool, item.id, "merged", &reason).await?;- let id = governance::record(pool, kb_id, decision("applied", None)).await?;- audit(state, kb_id, "review.merge", item, conf, id).await;+ let id = gov::record(pool, kb_id, decision("applied", None)).await?;+ audit(ctx, "review.merge", item, conf, id).await;return Ok(());}let (target, source) = utopia_store::resolution::merge_direction(pool, l, r).await?;@@ -183,9 +254,8 @@ async fn settle(Ok(merge_id) => {utopia_store::resolution::close_review_auto(pool, item.id, "merged", &reason).await?;- let id = governance::record(pool, kb_id, decision("applied", Some(merge_id)))- .await?;- audit(state, kb_id, "review.merge", item, conf, id).await;+ let id = gov::record(pool, kb_id, decision("applied", Some(merge_id))).await?;+ audit(ctx, "review.merge", item, conf, id).await;}// 同簇连锁合并已吞掉一方:留给人,并记一条 unsure 免得下一轮又撞上Err(AppError::Conflict(_)) | Err(AppError::NotFound) => {@@ -195,7 +265,7 @@ async fn settle("escalate_entity_changed",).await?;- governance::record(+ gov::record(pool,kb_id,NewDecision {@@ -212,34 +282,234 @@ async fn settle(Gate::Apply => {let reason = format!("governed|{conf:.2}");utopia_store::resolution::close_review_auto(pool, item.id, "kept", &reason).await?;- let id = governance::record(pool, kb_id, decision("applied", None)).await?;- audit(state, kb_id, "review.keep", item, conf, id).await;+ let id = gov::record(pool, kb_id, decision("applied", None)).await?;+ audit(ctx, "review.keep", item, conf, id).await;}Gate::Propose => {utopia_store::resolution::escalate_review(pool, item.id, "proposed").await?;- governance::record(pool, kb_id, decision("proposed", None)).await?;+ gov::record(pool, kb_id, decision("proposed", None)).await?;}}Ok(())}-/// 决策台账:actor 为空(机器),detail 里说是治理、置信度多少、对应哪条 agent 决定-async fn audit(- state: &AppState,- kb_id: Uuid,- action: &str,+/// 第二层:带工具逐条再看。模型每回合要么查一样东西(查完把结果喂回去),要么+/// decide / defer 收尾。回合数封顶;模型不用工具收尾就提醒一次,再不收尾就当没定+async fn investigate(+ ctx: &Ctx<'_>,item: &ReviewItem,- conf: f32,- id: Uuid,-) {+ pair: &utopia_extract::AdjudicationPair,+ earlier: &Look,+) -> anyhow::Result<Look> {+ let tools = governor::tools();+ let mut messages = governor::messages(+ pair,+ &governor::EarlierLook {+ verdict: match earlier.same {+ Some(true) => "same",+ Some(false) => "different",+ None => "unsure",+ },+ confidence: earlier.conf,+ why: earlier.why.as_deref(),+ },+ );+ let mut trace: Vec<Value> = Vec::new();+ let mut calls = 0;+ let mut nudged = false;++ // 回合上限 = 查询次数 + 收尾那一次 + 一次提醒+ for _ in 0..(governor::MAX_STEPS + 2) {+ let turn = {+ let _permit = permit(ctx).await;+ ctx.client.chat_tools(&messages, &tools).await?+ };+ calls += 1;+ messages.push(turn.to_message());+ if turn.tool_calls.is_empty() {+ if nudged {+ break;+ }+ nudged = true;+ messages.push(json!({ "role": "user", "content": governor::NUDGE }));+ continue;+ }+ for call in &turn.tool_calls {+ match governor::read_step(&call.name, &call.arguments) {+ Step::Decide {+ same,+ confidence,+ why,+ } => {+ return Ok(Look {+ same: Some(same),+ conf: confidence,+ why: Some(why).filter(|w| !w.is_empty()),+ question: None,+ trace,+ calls,+ });+ }+ Step::Defer { question } => {+ return Ok(Look {+ same: None,+ conf: 0.0,+ why: None,+ question: Some(question),+ trace,+ calls,+ });+ }+ Step::Lookup { tool, args } => {+ let out = if trace.len() >= governor::MAX_STEPS {+ "Lookup limit reached; finish with decide or defer.".to_string()+ } else {+ let (out, note) = lookup(ctx, item, &tool, &args).await?;+ trace.push(json!({ "tool": tool, "args": args, "note": note }));+ out+ };+ messages.push(tool_result_message(&call.id, &out));+ }+ Step::Unknown(problem) => {+ messages.push(tool_result_message(&call.id, &problem));+ }+ }+ }+ }+ // 看了,没收尾:当没定,轨迹留下+ Ok(Look {+ same: None,+ conf: 0.0,+ why: Some("the agent looked but did not conclude".into()),+ question: None,+ trace,+ calls,+ })+}++/// 跑一个工具:给模型的文本,以及写进轨迹的一句话+async fn lookup(+ ctx: &Ctx<'_>,+ item: &ReviewItem,+ tool: &str,+ args: &Value,+) -> anyhow::Result<(String, String)> {+ let pool = &ctx.state.pool;+ let kb_id = ctx.kb_id;+ let side = |s: &str| {+ if s == "A" {+ &item.left+ } else {+ &item.right+ }+ };+ let clip = |s: String| {+ if s.chars().count() > TOOL_OUTPUT_CHARS {+ let mut t: String = s.chars().take(TOOL_OUTPUT_CHARS).collect();+ t.push_str("\n…");+ t+ } else {+ s+ }+ };+ let (out, note) = match tool {+ "facts" => {+ let s = args["side"].as_str().unwrap_or("A");+ let e = side(s);+ let lines = utopia_store::resolution::entity_fact_lines(pool, kb_id, e.id, 30).await?;+ let n = lines.len();+ let out = if lines.is_empty() {+ "(no recorded facts)".to_string()+ } else {+ lines.join("\n")+ };+ (out, format!("{n} facts of {s} \"{}\"", e.name))+ }+ "quotes" => {+ let s = args["side"].as_str().unwrap_or("A");+ let e = side(s);+ let rows = gov::quotes_of(pool, kb_id, e.id, 6).await?;+ let n = rows.len();+ let out = if rows.is_empty() {+ "(no source passages)".to_string()+ } else {+ rows.iter()+ .map(|(doc, q)| format!("[{doc}] {q}"))+ .collect::<Vec<_>>()+ .join("\n")+ };+ (out, format!("{n} passages about {s} \"{}\"", e.name))+ }+ "ledger" => {+ let q = args["query"].as_str().unwrap_or("");+ let rows = gov::ledger_search(pool, kb_id, q, 10).await?;+ let n = rows.len();+ let out = if rows.is_empty() {+ "(no decisions by people about this name)".to_string()+ } else {+ rows.iter()+ .map(|x| {+ let verb = match x.action.as_str() {+ "merge.revert" => "merge reverted",+ "review.keep" => "kept apart",+ _ => "merged",+ };+ format!(+ "\"{}\" ≟ \"{}\": {verb} by a person on {}",+ x.left,+ x.right,+ x.at.format("%Y-%m-%d")+ )+ })+ .collect::<Vec<_>>()+ .join("\n")+ };+ (out, format!("{n} decisions about \"{q}\""))+ }+ "namesakes" => {+ let q = args["query"].as_str().unwrap_or("");+ let rows = gov::namesakes(pool, kb_id, q, 10).await?;+ let n = rows.len();+ let out = if rows.is_empty() {+ "(no other entity with such a name)".to_string()+ } else {+ rows.iter()+ .map(|x| {+ format!(+ "\"{}\" ({}) · {} facts{}",+ x.name,+ x.type_label.as_deref().unwrap_or("untyped"),+ x.facts,+ if x.merged {+ " · merged into another"+ } else {+ ""+ }+ )+ })+ .collect::<Vec<_>>()+ .join("\n")+ };+ (out, format!("{n} entities named like \"{q}\""))+ }+ other => (+ format!("no tool named {other}"),+ format!("unknown tool {other}"),+ ),+ };+ Ok((clip(out), note))+}++/// 决策台账:actor 为空(机器),detail 里说是治理、置信度多少、对应哪条 agent 决定+async fn audit(ctx: &Ctx<'_>, action: &str, item: &ReviewItem, conf: f32, id: Uuid) {let _ = utopia_store::audit::record_opt(- &state.pool,- Some(kb_id),+ &ctx.state.pool,+ Some(ctx.kb_id),None,action,"review",Some(item.id),- serde_json::json!({+ json!({"left": item.left.name, "right": item.right.name, "score": item.score,"confidence": conf, "via": "governor", "decision": id,}),@@ -260,11 +530,11 @@ pub async fn after_human_decision() {for &id in review_ids {if let Some(action) = action {- if let Err(e) = governance::answer_open(&state.pool, kb_id, id, action, user_id).await {+ if let Err(e) = gov::answer_open(&state.pool, kb_id, id, action, user_id).await {tracing::warn!(%kb_id, review = %id, error = %e, "治理:建议回答失败");}}- if let Err(e) = governance::supersede_siblings(&state.pool, kb_id, id).await {+ if let Err(e) = gov::supersede_siblings(&state.pool, kb_id, id).await {tracing::warn!(%kb_id, review = %id, error = %e, "治理:建议作废失败");}}@@ -273,7 +543,7 @@ pub async fn after_human_decision(if let Err(e) = utopia_store::jobs::enqueue_unless_queued(&state.pool,"govern",- serde_json::json!({ "kb_id": kb_id }),+ json!({ "kb_id": kb_id }),).await{diff --git a/crates/utopia-store/src/governance.rs b/crates/utopia-store/src/governance.rsindex 670fb689..b0dabeb7 100644--- a/crates/utopia-store/src/governance.rs+++ b/crates/utopia-store/src/governance.rs@@ -341,6 +341,12 @@ pub struct NewDecision<'a> {/// proposed | appliedpub status: &'a str,pub merge_id: Option<Uuid>,+ /// defer 留给人的问题(第二刀)+ pub question: Option<&'a str>,+ /// 循环看了什么:[{tool, args, note}]+ pub trace: serde_json::Value,+ /// 循环里花的模型调用+ pub calls: i32,}pub async fn record(pool: &PgPool, kb_id: Uuid, d: NewDecision<'_>) -> AppResult<Uuid> {@@ -348,8 +354,8 @@ pub async fn record(pool: &PgPool, kb_id: Uuid, d: NewDecision<'_>) -> AppResultsqlx::query("INSERT INTO agent_decisions(id, kb_id, run_id, target_kind, target_id, action, confidence, reason,- precedents, status, merge_id)- VALUES ($1, $2, $3, 'review', $4, $5, $6, $7, $8, $9, $10)",+ precedents, status, merge_id, question, trace, calls)+ VALUES ($1, $2, $3, 'review', $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)",).bind(id).bind(kb_id)@@ -361,13 +367,116 @@ pub async fn record(pool: &PgPool, kb_id: Uuid, d: NewDecision<'_>) -> AppResult.bind(d.precedents).bind(d.status).bind(d.merge_id)+ .bind(d.question)+ .bind(d.trace)+ .bind(d.calls).execute(pool).await?;Ok(id)}+/// 今天这个库在循环里花了几次模型调用:每库每天的预算按它算+pub async fn loop_calls_today(pool: &PgPool, kb_id: Uuid) -> AppResult<i64> {+ let n: i64 = sqlx::query_scalar(+ "SELECT COALESCE(sum(calls), 0)::bigint FROM agent_decisions+ WHERE kb_id = $1 AND created_at >= date_trunc('day', now())",+ )+ .bind(kb_id)+ .fetch_one(pool)+ .await?;+ Ok(n)+}++/// 工具:提到这个实体的原文片段——它的事实是从哪句话里抽出来的,出自哪份文档。+/// 证据上有 quote 就用 quote,没有就截分块开头+pub async fn quotes_of(+ pool: &PgPool,+ kb_id: Uuid,+ entity_id: Uuid,+ limit: i64,+) -> AppResult<Vec<(String, String)>> {+ let rows: Vec<(String, String)> = sqlx::query_as(+ "SELECT DISTINCT ON (fe.chunk_id) d.filename,+ COALESCE(NULLIF(fe.quote, ''), left(c.text, 240))+ FROM facts f+ JOIN fact_evidence fe ON fe.fact_id = f.id+ JOIN chunks c ON c.id = fe.chunk_id+ JOIN documents d ON d.id = c.document_id+ WHERE f.kb_id = $1 AND f.invalidated_at IS NULL+ AND (f.subject_id = $2 OR f.object_id = $2)+ ORDER BY fe.chunk_id, f.confidence DESC+ LIMIT $3",+ )+ .bind(kb_id)+ .bind(entity_id)+ .bind(limit)+ .fetch_all(pool)+ .await?;+ Ok(rows)+}++/// 工具:台账里人对某个名字做过的决定——名字包含 query 的合并、分开与撤回+pub async fn ledger_search(+ pool: &PgPool,+ kb_id: Uuid,+ query: &str,+ limit: i64,+) -> AppResult<Vec<Precedent>> {+ let like = format!("%{}%", query.trim().to_lowercase());+ let rows: Vec<Precedent> = sqlx::query_as(&format!(+ "SELECT {COLS} FROM audit_events+ WHERE kb_id = $1 AND actor_id IS NOT NULL+ AND action IN ('review.merge', 'review.keep', 'merge.manual', 'merge.revert')+ AND ({L} LIKE $2 OR {R} LIKE $2)+ ORDER BY created_at DESC LIMIT $3"+ ))+ .bind(kb_id)+ .bind(&like)+ .bind(limit)+ .fetch_all(pool)+ .await?;+ Ok(rows)+}++/// 工具:库里名字包含 query 的其他实体——叫这个名字的有几个、各是什么、各有多少事实+#[derive(Debug, Clone, sqlx::FromRow)]+pub struct Namesake {+ pub name: String,+ pub type_label: Option<String>,+ pub facts: i64,+ pub merged: bool,+}++pub async fn namesakes(+ pool: &PgPool,+ kb_id: Uuid,+ query: &str,+ limit: i64,+) -> AppResult<Vec<Namesake>> {+ let like = format!("%{}%", query.trim().to_lowercase());+ let rows: Vec<Namesake> = sqlx::query_as(+ "SELECT e.canonical_name AS name, t.label AS type_label,+ (SELECT count(*) FROM facts f+ WHERE f.invalidated_at IS NULL+ AND (f.subject_id = e.id OR f.object_id = e.id)) AS facts,+ (e.merged_into IS NOT NULL) AS merged+ FROM entities e+ LEFT JOIN entity_types t ON t.id = e.type_id+ WHERE e.kb_id = $1 AND lower(e.canonical_name) LIKE $2+ ORDER BY e.merged_into IS NOT NULL, facts DESC, e.canonical_name+ LIMIT $3",+ )+ .bind(kb_id)+ .bind(&like)+ .bind(limit)+ .fetch_all(pool)+ .await?;+ Ok(rows)+}+const VIEW: &str = "SELECT d.id, d.run_id, d.target_kind, d.target_id, d.action, d.confidence,- d.reason, d.precedents, d.status, d.merge_id, d.created_at, d.decided_at,+ d.reason, d.precedents, d.status, d.merge_id, d.question, d.trace, d.calls,+ d.created_at, d.decided_at,u.display_name AS decided_by_name,a.canonical_name AS \"left\", b.canonical_name AS \"right\"FROM agent_decisions ddiff --git a/crates/utopia-store/tests/a_governor_reads_the_ledger.rs b/crates/utopia-store/tests/a_governor_reads_the_ledger.rsindex 1fff645d..e2e78b6b 100644--- a/crates/utopia-store/tests/a_governor_reads_the_ledger.rs+++ b/crates/utopia-store/tests/a_governor_reads_the_ledger.rs@@ -284,6 +284,9 @@ async fn run(pool: &PgPool, s: &Seed) -> anyhow::Result<()> {precedents: governance::precedents_json(&p),status: "proposed",merge_id: None,+ question: None,+ trace: serde_json::json!([]),+ calls: 0,},).await?;@@ -299,6 +302,9 @@ async fn run(pool: &PgPool, s: &Seed) -> anyhow::Result<()> {precedents: serde_json::json!([]),status: "proposed",merge_id: None,+ question: None,+ trace: serde_json::json!([]),+ calls: 0,},).await?;@@ -328,6 +334,9 @@ async fn run(pool: &PgPool, s: &Seed) -> anyhow::Result<()> {precedents: serde_json::json!([]),status: "proposed",merge_id: None,+ question: None,+ trace: serde_json::json!([]),+ calls: 0,},).await@@ -367,6 +376,55 @@ async fn run(pool: &PgPool, s: &Seed) -> anyhow::Result<()> {.is_err());+ // 第二刀的工具:翻台账、找同名、数今天花的调用+ let hits = governance::ledger_search(pool, s.kb, "apple", 10).await?;+ assert_eq!(+ hits.len(),+ 2,+ "Apple Inc. 的合并与 Apple Records 的分开都含 apple"+ );+ assert!(+ governance::ledger_search(pool, s.kb, "zhang", 10)+ .await?+ .iter()+ .all(|x| x.action == "review.keep"),+ "机器合的那条不算"+ );+ let alike = governance::namesakes(pool, s.kb, "zhang wei", 10).await?;+ assert_eq!(alike.len(), 3, "三个张伟");+ assert!(alike+ .iter()+ .all(|x| x.type_label.as_deref() == Some("Person") && !x.merged));+ assert!(+ governance::quotes_of(pool, s.kb, alike_id(pool, s.kb).await?, 6)+ .await?+ .is_empty(),+ "没有事实就没有原文"+ );+ let looked = governance::record(+ pool,+ s.kb,+ NewDecision {+ run_id,+ target_id: s.mercury,+ action: "unsure",+ confidence: 0.0,+ reason: None,+ precedents: serde_json::json!([]),+ status: "proposed",+ merge_id: None,+ question: Some("Is the Mercury that filed the 2024 report the company or the person?"),+ trace: serde_json::json!([{ "tool": "facts", "args": { "side": "A" }, "note": "0 facts of A" }]),+ calls: 3,+ },+ )+ .await?;+ let d = governance::get(pool, s.kb, looked).await?;+ assert_eq!(d.calls, 3);+ assert!(d.question.as_deref().unwrap().starts_with("Is the Mercury"));+ assert_eq!(d.trace[0]["tool"], "facts");+ assert_eq!(governance::loop_calls_today(pool, s.kb).await?, 3);+// 定时扫描:开关开着且有没看过的对 → 在;关了 → 不在assert!(governance::due(pool).await?.contains(&s.kb));sqlx::query("UPDATE knowledge_bases SET governance = FALSE WHERE id = $1")@@ -377,6 +435,17 @@ async fn run(pool: &PgPool, s: &Seed) -> anyhow::Result<()> {Ok(())}+/// 随便一个张伟的 id:原文工具要一个实体+async fn alike_id(pool: &PgPool, kb: Uuid) -> anyhow::Result<Uuid> {+ let id: Uuid = sqlx::query_scalar(+ "SELECT id FROM entities WHERE kb_id = $1 AND canonical_name = 'Zhang Wei' LIMIT 1",+ )+ .bind(kb)+ .fetch_one(pool)+ .await?;+ Ok(id)+}+#[tokio::test]async fn a_governor_reads_the_ledger() -> anyhow::Result<()> {let Some(url) = utopia_store::test_db::url() else {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 b5742f5b..f47e3bc2 100644--- a/docs/decisions/0025-governance-reads-the-ledger-before-it-decides.md+++ b/docs/decisions/0025-governance-reads-the-ledger-before-it-decides.md@@ -1,6 +1,6 @@# 0025 · Governance reads the ledger before it decides-- **Status**: cut 1 implemented · migration 0035 adds `knowledge_bases.governance` and `agent_decisions`; `governance` in the store holds the precedent families, the first-in-first-out queue with its clusters, the gate and the table; the `govern` job in the server reads the switch, calls the model with precedents and applies or proposes; `?queue=agent`, `ReviewCounts.agent` and `POST /kbs/{id}/review/agent/{decision_id}` on the API · cut 3 (UI) implemented: the switch in base settings, the Agent queue with its rows and answers, the proposal chip on a duplicate card whose Merge / Keep answers the proposal, the Agent section on the Overview · cut 2 (a tool-using loop with a `defer` action) and cut 4 (the fuse) are open, see the last section+- **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- **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.@@ -46,6 +46,12 @@ A partial unique index allows one open proposal per pair. The table is the AgentAccepting or overriding a proposal calls `decide_review` with the person's id, exactly as the Review page does; reverting an applied merge calls `revert_merge`; merging over an applied keep calls `merge_entities` with the person as `merged_by`. Each writes the usual audit row plus the decision id. So an answer is a person's decision in every table that records decisions, and by decision 1 it is precedent for the next look.+### 8. A pair the batch cannot settle is looked at again, with tools, and then decided or asked about++The batch judges twelve pairs from their top facts and the precedent lines, and its verdict is `unsure` or under the threshold often enough that a base's proposals would otherwise be mostly shrugs. Those pairs, and only those, go through a second look: one pair per conversation, with tools. The model may ask for the full facts of a side, the source passages the facts came from (with the document each is in), what people decided about any name (a substring search of the ledger, so "Apple Computer" turns up for "Apple"), and other entities named alike. At most six lookups, then one of two endings: `decide` with a verdict, a confidence and one sentence naming the fact, passage or precedent that settled it, or `defer` with the one question a person could answer at a glance, naming the fact or document that would settle it. The verdict goes through the same gate as the batch's; nothing the loop finds lets it merge without precedent or against a rule. The question is stored on the row and shown as the row's text; the lookups are stored as a trace and shown under the row, so the explanation of a proposal is what the agent looked at.++Pairs 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.+### 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.@@ -63,8 +69,8 @@ Duplicates that the agent proposed on carry the reason code `proposed`; pairs it## Open questions-- **Cut 2, the loop.** Today the governor is the adjudicator with precedents and a gate. The next cut lets the model ask for an entity's facts, a source chunk or a ledger search instead of receiving one block, and adds a `defer` action that leaves a specific question for a person on the row.- **Cut 4, the fuse.** Two reverts of applied merges within seven days turn the switch off and raise an alert; the person turns it back on.- **Other queues.** Conflicts have three human actions to learn from (`conflict.close_old`, `keep_both`, `reject_new`); unconfirmed and low-confidence facts have `fact.confirm` and `fact.reject`. Nods (`pending_facts`, 0015) stay out: the person who said it nods.- **Cross-base precedent.** A workspace's other bases may hold the same names. Kept to one base until someone asks.-- **A budget.** A job runs twenty clusters and re-enqueues itself while backlog remains. A per-base daily budget of model calls is the obvious next guard, but the thresholds above are the ones that need measuring first.+- **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.+- **Tools the loop does not have yet.** The graph around a side beyond its direct facts, the entity's disambiguator history, a full-text search of the corpus. Add one when a deferred question keeps asking for it.diff --git a/docs/decisions/README.md b/docs/decisions/README.mdindex fdc7bcc1..0902e06e 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 · the tool-using loop and the fuse are open |+| 0025 | [Governance reads the ledger before it decides](0025-governance-reads-the-ledger-before-it-decides.md) | Cut 1 implemented · a per-base `governance` switch, a `govern` job that works the duplicates queue first in, first out with each head's cluster, precedents pulled from the ledger into the prompt, a gate that merges only with precedent, every look a row in `agent_decisions`, answers through the person's own decide path · the switch, the Agent queue, the proposal chip and the Overview section in the UI · 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 |## Not a decision recorddiff --git a/migrations/0036_the_agent_asks_before_it_guesses.sql b/migrations/0036_the_agent_asks_before_it_guesses.sqlnew file mode 100644index 00000000..277b90e0--- /dev/null+++ b/migrations/0036_the_agent_asks_before_it_guesses.sql@@ -0,0 +1,12 @@+-- 0025 第二刀:攒批判不定的对,agent 逐条带工具再看一遍,看完还定不了就留一个+-- 具体的问题给人,不猜。+--+-- question:defer 留下的那一个问题——人一眼能答的那种,点名哪条事实或哪份文档+-- 能定。只有 action = unsure 的行才有。+-- trace: 它看了什么:[{tool, args, note}],一条一次查询。轨迹就是解释——+-- 「查了 A 的事实、读了两段原文、翻了台账里 Apple 的决定」。+-- calls: 这一行在循环里花了几次模型调用;每库每天的循环预算按它算。+ALTER TABLE agent_decisions+ ADD COLUMN question TEXT,+ ADD COLUMN trace JSONB NOT NULL DEFAULT '[]',+ ADD COLUMN calls INT NOT NULL DEFAULT 0;diff --git a/web/src/api.ts b/web/src/api.tsindex 041653db..53a5a024 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -559,6 +559,12 @@ export interface AgentDecision {precedents: AgentPrecedent[];status: "proposed" | "applied" | "accepted" | "overridden" | "reverted" | "superseded";merge_id: string | null;+ /** defer 留给人的那一个问题;只有 unsure 的行才有 */+ question: string | null;+ /** 第二层看了什么:一条一次查询 */+ trace: { tool: string; args: Record<string, string>; note: string }[];+ /** 第二层花的模型调用 */+ calls: number;created_at: string;decided_at: string | null;decided_by_name: string | null;diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex 4f7707ca..d5e82c51 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -1516,6 +1516,9 @@ export const en = {agentPrecedentHabit: (merged: number, kept: number, reverted: number) =>`This type pair in this base: ${merged} merged, ${kept} kept apart, ${reverted} reverted`,agentAnsweredBy: (name: string, date: string) => `${name} · ${date}`,+ agentAsks: "Asks:",+ agentLookups: (n: number) => (n === 1 ? "1 lookup" : `${n} lookups`),+ agentLookedAt: "Looked at",overviewAgent: "Agent",overviewAgentOff: "Governance is off for this base.",overviewAgentSettings: "Turn it on in settings",diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex 6d9ea974..a25263aa 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -1327,6 +1327,9 @@ export const zh: Strings = {agentPrecedentHabit: (merged, kept, reverted) =>`这种类型对在本库:合 ${merged}、分 ${kept}、撤回 ${reverted}`,agentAnsweredBy: (name, date) => `${name} · ${date}`,+ agentAsks: "问:",+ agentLookups: (n) => `查了 ${n} 次`,+ agentLookedAt: "看了",overviewAgent: "Agent",overviewAgentOff: "这个库的治理没有打开。",overviewAgentSettings: "去设置里打开",diff --git a/web/src/pages/Review.tsx b/web/src/pages/Review.tsxindex ddd8572b..a700ae24 100644--- a/web/src/pages/Review.tsx+++ b/web/src/pages/Review.tsx@@ -495,6 +495,8 @@ function AgentRow({}) {const [open, setOpen] = useState(false);const precedents = d.precedents ?? [];+ const trace = d.trace ?? [];+ const hasDetail = precedents.length > 0 || trace.length > 0;return (<div className="glass rounded-xl px-4 py-3"><div className="flex items-center gap-3">@@ -509,23 +511,41 @@ function AgentRow({{S.review.agentStatus[d.status]}</Chip></div>- {(d.reason || precedents.length > 0) && (+ {/* defer 留下的问题(第二刀):这是给人看的正文,不是注脚 */}+ {d.question && (+ <p className="mt-1 text-body text-ink">+ <span className="text-ink-3">{S.review.agentAsks} </span>+ {d.question}+ </p>+ )}+ {(d.reason || hasDetail) && (<div className="mt-1 flex items-center gap-3 text-small text-ink-3">{d.reason && <span className="truncate min-w-0">{d.reason}</span>}- {precedents.length > 0 && (+ {hasDetail && (<LinkButton className="shrink-0" onClick={() => setOpen((v) => !v)}>- {S.review.agentPrecedents(precedents.length)}+ {[+ precedents.length > 0 ? S.review.agentPrecedents(precedents.length) : null,+ trace.length > 0 ? S.review.agentLookups(trace.length) : null,+ ]+ .filter(Boolean)+ .join(" · ")}</LinkButton>)}</div>)}- {open && precedents.length > 0 && (+ {open && hasDetail && (<ul className="mt-2 space-y-1 border-t border-line pt-2 text-small text-ink-3">{precedents.map((p, i) => (- <li key={i} className="truncate">+ <li key={`p${i}`} className="truncate">{precedentText(p)}</li>))}+ {/* 轨迹就是解释:它查了什么,一行一次 */}+ {trace.map((t, i) => (+ <li key={`t${i}`} className="truncate">+ {S.review.agentLookedAt} {t.note}+ </li>+ ))}</ul>)}<div className="mt-2 flex items-center gap-2">