World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
The agent could read what was true, but not what we changed our mind about (#98)
WaylandYangaeabfc33439a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex f33a69b8..aca37ffa 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -62,6 +62,13 @@ jobs:# 第二遍必须也过:迁移改号后要能在已经跑过旧号的库上安全重放- name: 再跑一遍run: sqlx migrate run --database-url postgres://utopia:utopia@localhost:5432/utopia+ # 连库的测试只有这个 job 跑得动——rust job 没有数据库,那些测试在那边+ # 会跳过并显示绿色。不在这里跑一遍,等于写了测试却永远没执行过,+ # 比没写更糟:它会让人以为 SQL 有覆盖+ - name: 连库测试+ run: cargo test -p utopia-store --test graph_changes+ env:+ UTOPIA_DATABASE_URL: postgres://utopia:utopia@localhost:5432/utopiaweb:runs-on: ubuntu-latestdiff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rsindex 0b8ce8b7..28f424d8 100644--- a/crates/utopia-core/src/models.rs+++ b/crates/utopia-core/src/models.rs@@ -526,6 +526,34 @@ pub struct EntityHistoryEvent {pub quote: Option<String>,}+/// 一段**记录时间**窗口里,整个库上发生的认知变更。+///+/// 跟 `EntityHistoryEvent` 是同一批事件,两处不同:+/// 1. 开窗在**认知轴**上(recorded_at / invalidated_at),不锁定单个实体——+/// "上季度有什么变了"这种问题没有一个先验的实体可问;+/// 2. 主宾都写全(`direction` 是"以某实体为中心"才有的概念,这里没有中心)。+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]+pub struct GraphChange {+ pub fact_id: Uuid,+ /// 事件落在认知轴上的时刻(写入 = recorded_at,作废 = invalidated_at)+ pub at: DateTime<Utc>,+ /// asserted(新断言)| corrected(订正了前一条)| rejected(被推翻)| merged(并入他条)+ pub kind: String,+ pub subject_id: Uuid,+ pub subject_name: String,+ pub predicate_label: String,+ pub object_name: Option<String>,+ pub object_value: Option<serde_json::Value>,+ /// 这条断言说的是**世界轴**上的哪一段——与 `at` 正交,别读混+ pub valid_from: Option<DateTime<Utc>>,+ pub valid_to: Option<DateTime<Utc>>,+ pub valid_precision: String,+ pub confidence: f32,+ pub document_id: Option<Uuid>,+ pub filename: Option<String>,+ pub quote: Option<String>,+}+/// 消解审核项的一侧实体摘要。#[derive(Debug, Clone, Serialize)]pub struct ReviewSide {diff --git a/crates/utopia-server/src/api/chat.rs b/crates/utopia-server/src/api/chat.rsindex e6857048..5242319a 100644--- a/crates/utopia-server/src/api/chat.rs+++ b/crates/utopia-server/src/api/chat.rs@@ -9,7 +9,7 @@ use futures_util::{Stream, StreamExt};use serde::Deserialize;use serde_json::json;use std::convert::Infallible;-use utopia_core::models::{ChunkView, EntityFact, Role};+use utopia_core::models::{ChunkView, EntityFact, GraphChange, Role};use utopia_core::AppError;use utopia_llm::tool_result_message;use uuid::Uuid;@@ -28,6 +28,10 @@ const MAX_HISTORY: usize = 20;const MAX_ROUNDS: usize = 6;const SEARCH_TOP_K: usize = 6;const TOOL_CHUNK_CHARS: usize = 800;+/// 一次 changes 最多回多少条。刚灌完的库里 asserted 是成百上千条,全发出去+/// 只会把上下文填满而不增加信息——有信息量的是 corrected/rejected,那类事件+/// 本来就稀少。截断时 detail 写 "40+",模型据此知道该收窄窗口+const CHANGES_LIMIT: i64 = 40;#[derive(Deserialize)]pub struct ChatReq {@@ -189,14 +193,52 @@ fn base_tools() -> serde_json::Value {"required": ["entity_id"]}}+ },+ {+ "type": "function",+ "function": {+ "name": "changes",+ "description": "What the graph LEARNED or REVISED in a window of record time — the belief axis. Answers \"what changed since X\", \"what did we get wrong\", \"what is new this quarter\", and needs no entity, so use it when the question names a period rather than a subject. Events: asserted (new claim), corrected (a claim replaced by a revised one), rejected (a claim withdrawn), merged (folded into another claim) — each with the document it came from. NOT the same axis as entity_facts(at): that asks \"what was true on date D\"; this asks \"what did we change our mind about between D1 and D2\". A fact about 2019 can be recorded in 2026 — this windows on when we recorded it.",+ "parameters": {+ "type": "object",+ "properties": {+ "since": {+ "type": "string",+ "description": "Start of the window (YYYY-MM-DD), inclusive."+ },+ "until": {+ "type": "string",+ "description": "End of the window (YYYY-MM-DD), inclusive of that whole day. Omit for 'up to now'."+ },+ "entity_id": {+ "type": "string",+ "description": "Optional entity id from find_entities, to narrow the window to changes touching that one entity."+ },+ "kinds": {+ "type": "array",+ "items": {+ "type": "string",+ "enum": ["asserted", "corrected", "rejected", "merged"]+ },+ "description": "Optional filter. A freshly ingested corpus is nearly all 'asserted'; pass [\"corrected\", \"rejected\"] to isolate the places we actually changed our mind."+ }+ },+ "required": ["since"]+ }+ }}])}const SYSTEM_PROMPT: &str = "You are the assistant of Utopia, a temporal knowledge platform. \- You have tools: search_chunks (document search), find_entities and entity_facts (a \- bi-temporal knowledge graph where every relation carries a validity range), and \- search_docs (Utopia's own manual, the Charter).\n\+ You have tools: search_chunks (document search), find_entities, entity_facts and \+ changes (a bi-temporal knowledge graph), and search_docs (Utopia's own manual, the \+ Charter).\n\+ The graph has TWO independent time axes, and each graph tool reads exactly one:\n\+ - World time — when something was true. Read with entity_facts (`at` = as of that date).\n\+ - Record time — when we came to believe it, and when we revised it. Read with changes.\n\+ \"Who was CTO in 2019\" is world time; \"what did we learn last month\" and \"what did \+ we get wrong\" are record time. The same fact has a position on both.\n\Boundary: search_docs answers questions about Utopia itself (features, ingestion, \permissions, what fields like 'missing' or validity ranges mean); the other tools answer \questions about the knowledge stored in it. Never mix the manual into answers about the \@@ -210,6 +252,10 @@ const SYSTEM_PROMPT: &str = "You are the assistant of Utopia, a temporal knowled2. Facts carry validity ranges (from → to). For \"as of <date>\" questions pass `at` to \entity_facts and the server filters to that moment; for history questions omit `at` \to see the full timeline. State dates in the answer.\n\+ 2b. For \"what changed / what is new / what did we get wrong since <date>\", call changes — \+ it needs no entity. Name the document a correction came from in plain prose. Graph tools \+ return no [n] numbers and no URLs, so never write a bracketed citation or a placeholder \+ like [Link] after one — the document's name IS the attribution.\n\3. Several entities can share one name — check the disambiguator and pick the right one; \if genuinely ambiguous, ask the user which one they mean.\n\4. Stop calling tools as soon as you have enough evidence. Then answer concisely: cite \@@ -619,6 +665,50 @@ pub async fn chat(),}}+ "changes" => {+ let day = |k: &str| {+ args[k]+ .as_str()+ .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())+ };+ match changes_window(day("since"), day("until"), chrono::Utc::now()) {+ None => (+ "Invalid or missing `since` (expected YYYY-MM-DD).".to_string(),+ json!({ "kind": "changes", "label": "?", "detail": "invalid since" }),+ ),+ Some((since, until, window)) => {+ let entity = args["entity_id"]+ .as_str()+ .and_then(|s| s.parse::<Uuid>().ok());+ let kinds: Option<Vec<String>> = args["kinds"].as_array().map(|a| {+ a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()+ });+ let kinds = kinds.filter(|k: &Vec<String>| !k.is_empty());+ let rows = utopia_store::graph::graph_changes(+ &state.pool,+ kb_id,+ since,+ until,+ entity,+ kinds.as_deref(),+ CHANGES_LIMIT,+ )+ .await+ .unwrap_or_default();+ let text = if rows.is_empty() {+ format!("No recorded changes in {window}.")+ } else {+ rows.iter().map(change_line).collect::<Vec<_>>().join("\n")+ };+ let detail = if rows.len() as i64 == CHANGES_LIMIT {+ format!("{CHANGES_LIMIT}+ changes")+ } else {+ format!("{} changes", rows.len())+ };+ (text, json!({ "kind": "changes", "label": window, "detail": detail }))+ }+ }+ }"query_data" if !mounted_sources.is_empty() => {let ds_name = args["data_source"].as_str().map(str::trim).unwrap_or("");let sql = args["sql"].as_str().map(str::trim).unwrap_or("");@@ -799,6 +889,86 @@ fn fact_line(f: &EntityFact) -> String {format!("{core}{range} [{}%]", (f.confidence * 100.0).round() as i32)}+/// changes 的时间窗:把两个可选日期变成 (SQL 用的半开区间, 展示用的窗口串)。+///+/// **抽成纯函数是因为这里出过一次错。** `until` 进 SQL 前要加一天(说"到 3 月 31 日+/// 为止"的人要的是含 31 日,而 SQL 那头是 `< $3`),第一版把加过一天的值也印进了+/// 展示串,模型于是照着答"截至 8 月 30 日"——问的是 29 日。两个值必须一起算、+/// 一起被测住;分在两处写,迟早再次分叉。+///+/// `now` 从外面传进来而不是在里面取,纯粹是为了这个函数测得动。+fn changes_window(+ since: Option<chrono::NaiveDate>,+ until: Option<chrono::NaiveDate>,+ now: chrono::DateTime<chrono::Utc>,+) -> Option<(+ chrono::DateTime<chrono::Utc>,+ chrono::DateTime<chrono::Utc>,+ String,+)> {+ let from = since?;+ let start = from.and_hms_opt(0, 0, 0).unwrap().and_utc();+ let end = until+ .and_then(|d| d.succ_opt())+ .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc())+ .unwrap_or(now);+ // 展示用的是**问的那天**,没问就写 now——绝不是 end+ let label = format!(+ "{} → {}",+ from.format("%Y-%m-%d"),+ match until {+ Some(d) => d.format("%Y-%m-%d").to_string(),+ None => "now".to_string(),+ }+ );+ Some((start, end, label))+}++/// 认知轴上的一行。+///+/// 排版把两根轴**分开写**:`at` 前面标事件类型,世界轴的区间夹在括号里跟在断言后。+/// 若把它们排成一串日期,模型会把"2026 年记下的"读成"2026 年发生的"——那正是+/// 这个工具要防的误读。+fn change_line(c: &GraphChange) -> String {+ let object = match (&c.object_name, &c.object_value) {+ (Some(name), _) => name.clone(),+ (None, Some(v)) => match v {+ serde_json::Value::String(s) => s.clone(),+ other => other.to_string(),+ },+ (None, None) => "?".to_string(),+ };+ let range = match (&c.valid_from, &c.valid_to) {+ (Some(from), Some(to)) => {+ format!(+ " [valid {} → {}]",+ from.format("%Y-%m-%d"),+ to.format("%Y-%m-%d")+ )+ }+ (Some(from), None) => format!(" [valid {} → now]", from.format("%Y-%m-%d")),+ (None, Some(to)) => format!(" [valid → {}]", to.format("%Y-%m-%d")),+ (None, None) => String::new(),+ };+ // 文件名不带 [n]:引证编号是 chunk 的,这里只有 document,发一个编号出去+ // 会在界面上落成一条指不到东西的引证+ let src = match (&c.filename, &c.quote) {+ (Some(f), Some(q)) => format!(" — from \"{f}\": \"{}\"", truncate(q, 160)),+ (Some(f), None) => format!(" — from \"{f}\""),+ _ => String::new(),+ };+ format!(+ "{} {}: {} {} {}{}{}",+ c.at.format("%Y-%m-%d"),+ c.kind,+ c.subject_name,+ c.predicate_label,+ object,+ range,+ src+ )+}+/// 降级路径的系统提示(tool-calling 不可用时的一次性注入)。fn legacy_system_prompt(chunks: &[ChunkView]) -> String {if chunks.is_empty() {@@ -874,3 +1044,121 @@ pub async fn delete_conversation(utopia_store::conversations::delete(&state.pool, kb_id, user.id, conversation_id).await?;Ok(Json(json!({ "ok": true })))}++#[cfg(test)]+mod tests {+ use super::*;++ fn d(s: &str) -> chrono::NaiveDate {+ chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()+ }+ fn t(s: &str) -> chrono::DateTime<chrono::Utc> {+ s.parse().unwrap()+ }++ // --- changes_window -----------------------------------------------------++ /// 说"到 3 月 31 日为止"的人要的是**含 31 日**。SQL 那头是 `< end`,+ /// 所以 end 必须落在 4 月 1 日零点——差这一天,问 31 日会安静地丢掉 31 日+ #[test]+ fn until_names_a_day_the_window_must_contain() {+ let (start, end, label) = changes_window(+ Some(d("2026-03-01")),+ Some(d("2026-03-31")),+ t("2026-06-01T00:00:00Z"),+ )+ .unwrap();+ assert_eq!(start, t("2026-03-01T00:00:00Z"));+ assert_eq!(end, t("2026-04-01T00:00:00Z"));+ // 但**展示串里绝不能出现 04-01**:那是半开区间的内部细节,+ // 印出去等于告诉模型窗口比它要的宽一天,模型会照着答(这条真的发生过)+ assert_eq!(label, "2026-03-01 → 2026-03-31");+ }++ /// 没给 until 时,展示串写 now。写成 end 的格式化结果就等于把服务器时钟+ /// 当成用户问的边界——看着像个精确答案,其实只是"现在几点"+ #[test]+ fn an_open_window_says_now_rather_than_the_clock() {+ let now = t("2026-06-01T13:45:00Z");+ let (_, end, label) = changes_window(Some(d("2026-03-01")), None, now).unwrap();+ assert_eq!(end, now);+ assert_eq!(label, "2026-03-01 → now");+ }++ #[test]+ fn without_since_there_is_no_window() {+ assert!(changes_window(None, Some(d("2026-03-31")), t("2026-06-01T00:00:00Z")).is_none());+ }++ // --- change_line --------------------------------------------------------++ fn change(kind: &str) -> GraphChange {+ GraphChange {+ fact_id: Uuid::nil(),+ at: t("2026-08-28T10:00:00Z"),+ kind: kind.to_string(),+ subject_id: Uuid::nil(),+ subject_name: "Acme".to_string(),+ predicate_label: "founded in".to_string(),+ object_name: None,+ object_value: None,+ valid_from: None,+ valid_to: None,+ valid_precision: "day".to_string(),+ confidence: 0.9,+ document_id: None,+ filename: None,+ quote: None,+ }+ }++ /// 字面值要读成它自己。走 `Value::to_string()` 会把字符串连引号一起印出来,+ /// 模型于是把 `"1993"` 当成答案的一部分+ #[test]+ fn a_literal_value_reads_as_itself_not_as_json() {+ let mut c = change("asserted");+ c.object_value = Some(serde_json::json!("1993"));+ assert!(+ change_line(&c).ends_with("Acme founded in 1993"),+ "{}",+ change_line(&c)+ );+ }++ /// 两根轴必须在同一行里**看得出是两样东西**:记录时刻在前、无标签,+ /// 世界轴区间在后、带 `valid` 字样。排成一串裸日期,模型会把+ /// "2026 年记下的"读成"2026 年发生的"——这个工具存在的理由就是防这个+ #[test]+ fn the_record_time_and_the_valid_range_do_not_read_as_one_date_run() {+ let mut c = change("corrected");+ c.object_name = Some("Berlin".to_string());+ c.predicate_label = "headquartered in".to_string();+ c.valid_from = Some(t("2019-01-01T00:00:00Z"));+ let line = change_line(&c);+ assert!(line.starts_with("2026-08-28 corrected: "), "{line}");+ assert!(line.contains("[valid 2019-01-01 → now]"), "{line}");+ }++ /// 没有证据就什么都别说。凭空补一句 from "…" 会让一条无出处的断言+ /// 看起来有出处+ #[test]+ fn a_fact_with_no_evidence_claims_no_document() {+ let mut c = change("rejected");+ c.object_name = Some("Berlin".to_string());+ assert!(!change_line(&c).contains("from"), "{}", change_line(&c));+ }++ #[test]+ fn evidence_carries_the_filename_and_the_quote() {+ let mut c = change("corrected");+ c.object_name = Some("Berlin".to_string());+ c.filename = Some("annual-report.pdf".to_string());+ c.quote = Some("moved its head office to Berlin".to_string());+ let line = change_line(&c);+ assert!(line.contains("from \"annual-report.pdf\""), "{line}");+ assert!(+ line.contains("\"moved its head office to Berlin\""),+ "{line}"+ );+ }+}diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rsindex 699d3238..6796b0a6 100644--- a/crates/utopia-store/src/graph.rs+++ b/crates/utopia-store/src/graph.rs@@ -4,7 +4,7 @@ use sqlx::PgPool;use std::collections::HashSet;use utopia_core::models::{ChunkFactView, EntityFact, EntityHistoryEvent, EntityType, EvidenceView, FactReviewItem,- GraphEdge, GraphNode, ProposedPredicate, RelationType,+ GraphChange, GraphEdge, GraphNode, ProposedPredicate, RelationType,};use utopia_core::{AppError, AppResult};use uuid::Uuid;@@ -1235,6 +1235,81 @@ pub async fn entity_history(Ok((rows, total))}+/// 一段记录时间窗口里,全库的认知变更。+///+/// **窗口开在认知轴上**:`since`/`until` 比的是 recorded_at 与 invalidated_at,+/// 不是 valid_from/valid_to。这是与 `entity_facts(at)` 唯一也是全部的区别——+/// 那个问"某时刻世界什么样",这个问"某段时间里我们改了什么主意"。两者查同一张表、+/// 用不同的列,混起来会安静地给出一个看着合理的错答案。+///+/// 事件推导与 `entity_history` 同源(见那里的注释):一条事实行最多产出两个事件,+/// 且已被后继修正的死亡不重复记。+pub async fn graph_changes(+ pool: &PgPool,+ kb_id: Uuid,+ since: chrono::DateTime<chrono::Utc>,+ until: chrono::DateTime<chrono::Utc>,+ entity_id: Option<Uuid>,+ kinds: Option<&[String]>,+ limit: i64,+) -> AppResult<Vec<GraphChange>> {+ // 两个分支各自按**自己那根时间列**开窗,而不是先union再过滤:+ // 一条 2 月写入、8 月被推翻的事实,在"3–4 月"窗口里两个事件都不该出现+ const EVENTS: &str = "+ WITH ev AS (+ SELECT f.id, f.subject_id, f.predicate_id, f.object_id, f.object_value,+ f.valid_from, f.valid_to, f.valid_precision, f.confidence,+ f.recorded_at AS at,+ CASE WHEN f.supersedes IS NULL THEN 'asserted' ELSE 'corrected' END AS kind+ FROM facts f+ WHERE f.kb_id = $1 AND f.recorded_at >= $2 AND f.recorded_at < $3+ AND ($4::uuid IS NULL OR f.subject_id = $4 OR f.object_id = $4)+ UNION ALL+ SELECT f.id, f.subject_id, f.predicate_id, f.object_id, f.object_value,+ f.valid_from, f.valid_to, f.valid_precision, f.confidence,+ f.invalidated_at AS at,+ CASE WHEN EXISTS (SELECT 1 FROM fact_adoptions fa+ WHERE fa.old_fact_id = f.id AND fa.mode = 'merged'+ AND fa.reverted_at IS NULL)+ THEN 'merged' ELSE 'rejected' END AS kind+ FROM facts f+ WHERE f.kb_id = $1 AND f.invalidated_at >= $2 AND f.invalidated_at < $3+ AND NOT EXISTS (SELECT 1 FROM facts s WHERE s.supersedes = f.id)+ AND ($4::uuid IS NULL OR f.subject_id = $4 OR f.object_id = $4)+ )";+ Ok(sqlx::query_as(&format!(+ "{EVENTS}+ SELECT ev.id AS fact_id, ev.at, ev.kind,+ ev.subject_id, s.canonical_name AS subject_name,+ r.label AS predicate_label, o.canonical_name AS object_name,+ ev.object_value, ev.valid_from, ev.valid_to, ev.valid_precision,+ ev.confidence, src.document_id, src.filename, src.quote+ FROM ev+ JOIN relation_types r ON r.id = ev.predicate_id+ JOIN entities s ON s.id = ev.subject_id+ LEFT JOIN entities o ON o.id = ev.object_id+ LEFT JOIN LATERAL (+ SELECT d.id AS document_id, d.filename, fe.quote+ FROM fact_evidence fe+ JOIN chunks c ON c.id = fe.chunk_id+ JOIN documents d ON d.id = c.document_id+ WHERE fe.fact_id = ev.id+ ORDER BY fe.doc_version DESC NULLS LAST LIMIT 1+ ) src ON true+ WHERE $5::text[] IS NULL OR ev.kind = ANY($5)+ ORDER BY ev.at DESC, ev.id+ LIMIT $6"+ ))+ .bind(kb_id)+ .bind(since)+ .bind(until)+ .bind(entity_id)+ .bind(kinds)+ .bind(limit)+ .fetch_all(pool)+ .await?)+}+// ---------------------------------------------------------------------------// 谓词消解:把降级成 related_to 的事实认领回本体// ---------------------------------------------------------------------------diff --git a/crates/utopia-store/tests/graph_changes.rs b/crates/utopia-store/tests/graph_changes.rsnew file mode 100644index 00000000..b649a079--- /dev/null+++ b/crates/utopia-store/tests/graph_changes.rs@@ -0,0 +1,256 @@+//! `graph_changes` 的账本推导,打在真库上。+//!+//! 为什么非要连库:这段逻辑**整个活在 SQL 字符串里**,`cargo check` 和 clippy+//! 一个字都看不见。本项目已经在这上面栽过好几次(合并去重漏掉 object_value、+//! `UPDATE … RETURNING` 返回新值、CHECK 约束悄悄拒绝一种 kind),+//! 每次都是运行时才发现。+//!+//! 没有 `UTOPIA_DATABASE_URL` 时**跳过而不是失败**:这是本仓库第一个连库测试,+//! 不该让没起数据库的人 `cargo test` 变红。+//!+//! 自建自拆:造一个一次性 org/workspace/kb,跑完连 kb 一起删(facts/entities+//! 都是 ON DELETE CASCADE)。绝不碰已有的库。++use sqlx::PgPool;+use uuid::Uuid;++fn t(s: &str) -> chrono::DateTime<chrono::Utc> {+ s.parse().unwrap()+}++/// 造一个最小账本,返回 (kb_id, 主语实体, 宾语实体)。+///+/// 四条事实覆盖全部四种事件,外加一条**不该出现的**事件:+/// - A 03-10 写入,03-20 作废,但 B 接了它 → 只出 asserted,作废不重复记+/// - B 03-20 写入且 supersedes=A → corrected+/// - C 03-12 写入,03-25 作废且无后继 → asserted + rejected+/// - D 03-13 写入,03-26 作废且无后继,带 merged 采纳记录 → asserted + merged+async fn seed(pool: &PgPool) -> anyhow::Result<(Uuid, Uuid, Uuid)> {+ let org = Uuid::now_v7();+ let ws = Uuid::now_v7();+ let kb = Uuid::now_v7();+ let etype = Uuid::now_v7();+ let pred = Uuid::now_v7();+ let (subj, obj, other) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ let (a, b, c, d) = (+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ );++ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'changes-test')")+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'changes-test')")+ .bind(ws)+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'changes-test')",+ )+ .bind(kb)+ .bind(ws)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'thing', 'Thing')",+ )+ .bind(etype)+ .bind(kb)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO relation_types (id, kb_id, key, label) VALUES ($1, $2, 'located_in', 'located in')",+ )+ .bind(pred)+ .bind(kb)+ .execute(pool)+ .await?;+ for (id, name) in [(subj, "Acme"), (obj, "Berlin"), (other, "Paris")] {+ sqlx::query(+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",+ )+ .bind(id)+ .bind(kb)+ .bind(etype)+ .bind(name)+ .execute(pool)+ .await?;+ }++ let fact = |id: Uuid, o: Uuid, rec: &str, inv: Option<&str>, sup: Option<Uuid>| {+ let (rec, inv) = (t(rec), inv.map(t));+ sqlx::query(+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id,+ recorded_at, invalidated_at, supersedes)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",+ )+ .bind(id)+ .bind(kb)+ .bind(subj)+ .bind(pred)+ .bind(o)+ .bind(rec)+ .bind(inv)+ .bind(sup)+ };+ fact(+ a,+ obj,+ "2026-03-10T00:00:00Z",+ Some("2026-03-20T00:00:00Z"),+ None,+ )+ .execute(pool)+ .await?;+ fact(b, obj, "2026-03-20T00:00:00Z", None, Some(a))+ .execute(pool)+ .await?;+ fact(+ c,+ obj,+ "2026-03-12T00:00:00Z",+ Some("2026-03-25T00:00:00Z"),+ None,+ )+ .execute(pool)+ .await?;+ // D 的宾语换成 other:用来验证 entity_id 过滤认宾语侧+ fact(+ d,+ other,+ "2026-03-13T00:00:00Z",+ Some("2026-03-26T00:00:00Z"),+ None,+ )+ .execute(pool)+ .await?;++ sqlx::query(+ "INSERT INTO fact_adoptions (batch_id, kb_id, predicate_id, old_fact_id, new_fact_id, mode)+ VALUES ($1, $2, $3, $4, $5, 'merged')",+ )+ .bind(Uuid::now_v7())+ .bind(kb)+ .bind(pred)+ .bind(d)+ .bind(b)+ .execute(pool)+ .await?;++ Ok((kb, subj, other))+}++/// (kind, 日期) 的多重集,排序后好比对+fn shape(rows: &[utopia_core::models::GraphChange]) -> Vec<String> {+ let mut v: Vec<String> = rows+ .iter()+ .map(|c| format!("{} {}", c.at.format("%m-%d"), c.kind))+ .collect();+ v.sort();+ v+}++#[tokio::test]+async fn ledger_events_are_derived_as_specified() -> anyhow::Result<()> {+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");+ return Ok(());+ };+ let pool = PgPool::connect(&url).await?;+ let (kb, subj, other) = seed(&pool).await?;++ let run = |since: &'static str,+ until: &'static str,+ entity: Option<Uuid>,+ kinds: Option<Vec<String>>| {+ let pool = pool.clone();+ async move {+ utopia_store::graph::graph_changes(+ &pool,+ kb,+ t(since),+ t(until),+ entity,+ kinds.as_deref(),+ 100,+ )+ .await+ }+ };++ // 1. 整窗:四条事实产出六个事件,且 A 的死亡**不出现**——+ // 它已经被 B 那条 corrected 解释过了,再记一次就是同一件事说两遍+ let all = run("2026-03-01T00:00:00Z", "2026-04-01T00:00:00Z", None, None).await?;+ assert_eq!(+ shape(&all),+ vec![+ "03-10 asserted",+ "03-12 asserted",+ "03-13 asserted",+ "03-20 corrected",+ "03-25 rejected",+ "03-26 merged",+ ],+ "四种事件各就各位,且 03-20 没有 rejected"+ );++ // 2. 两个分支各按**自己那根时间列**开窗:截到 03-15,写入进得来、作废进不来+ let early = run("2026-03-01T00:00:00Z", "2026-03-15T00:00:00Z", None, None).await?;+ assert_eq!(+ shape(&early),+ vec!["03-10 asserted", "03-12 asserted", "03-13 asserted"]+ );++ // 3. kinds 过滤(text[] 绑定)+ let only = run(+ "2026-03-01T00:00:00Z",+ "2026-04-01T00:00:00Z",+ None,+ Some(vec!["rejected".into(), "merged".into()]),+ )+ .await?;+ assert_eq!(shape(&only), vec!["03-25 rejected", "03-26 merged"]);++ // 4. entity_id 过滤(uuid 绑定)认宾语侧:other 只在 D 上当宾语,+ // 却要能捞出 D 的两个事件+ let by_object = run(+ "2026-03-01T00:00:00Z",+ "2026-04-01T00:00:00Z",+ Some(other),+ None,+ )+ .await?;+ assert_eq!(shape(&by_object), vec!["03-13 asserted", "03-26 merged"]);++ // 5. 主语侧命中全部六条+ let by_subject = run(+ "2026-03-01T00:00:00Z",+ "2026-04-01T00:00:00Z",+ Some(subj),+ None,+ )+ .await?;+ assert_eq!(by_subject.len(), 6);++ // 6. 主宾与谓词都拼了出来,不是一堆 uuid+ let sample = all.iter().find(|c| c.kind == "corrected").unwrap();+ assert_eq!(sample.subject_name, "Acme");+ assert_eq!(sample.predicate_label, "located in");+ assert_eq!(sample.object_name.as_deref(), Some("Berlin"));++ // 拆台:facts/entities/… 全是 ON DELETE CASCADE+ let gone = sqlx::query(+ "DELETE FROM organizations WHERE id = (+ SELECT w.org_id FROM workspaces w+ JOIN knowledge_bases k ON k.workspace_id = w.id WHERE k.id = $1)",+ )+ .bind(kb)+ .execute(&pool)+ .await?;+ assert_eq!(gone.rows_affected(), 1, "一次性 org 没删掉");+ Ok(())+}diff --git a/migrations/0044_facts_belief_axis_idx.sql b/migrations/0044_facts_belief_axis_idx.sqlnew file mode 100644index 00000000..10803bc3--- /dev/null+++ b/migrations/0044_facts_belief_axis_idx.sql@@ -0,0 +1,17 @@+-- 认知轴一直没有索引。+--+-- 0004 给 facts 建了三个索引,全在世界轴上(valid_from/valid_to),且都带+-- `WHERE invalidated_at IS NULL`——只认活行。这套索引服务的是"某时刻什么为真"。+--+-- 但账本还有另一根轴:**什么时候写进来的、什么时候被推翻的**。按这根轴开窗+--("上个季度我们的认知有哪些变化")以前没有查询路径,所以缺索引一直没露头。+-- changes 工具把这根轴暴露给了 agent,缺索引就成了每问一次全表扫一遍。+--+-- 注意作废那条是**部分索引且条件取反**:活行的 invalidated_at 全是 NULL,+-- 把它们收进来只是让索引跟表一样大。被推翻的事实天然是少数。+CREATE INDEX IF NOT EXISTS facts_recorded_idx+ ON facts (kb_id, recorded_at DESC);++CREATE INDEX IF NOT EXISTS facts_invalidated_idx+ ON facts (kb_id, invalidated_at DESC)+ WHERE invalidated_at IS NOT NULL;diff --git a/web/src/api.ts b/web/src/api.tsindex c0d480d2..dc2fe5b0 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -533,7 +533,7 @@ export interface Source {/** Agentic 对话的行动轨迹(工具调用一步一条)。 */export interface ChatStep {- kind: "search" | "docs" | "entity" | "facts" | "query" | "tool";+ kind: "search" | "docs" | "entity" | "facts" | "changes" | "query" | "tool";label: string;detail: string;}diff --git a/web/src/pages/Chat.tsx b/web/src/pages/Chat.tsxindex a281d990..ef02c54c 100644--- a/web/src/pages/Chat.tsx+++ b/web/src/pages/Chat.tsx@@ -14,6 +14,7 @@ import {Check,ChevronDown,Database,+ GitCompareArrows,History,Search as SearchIcon,Square,@@ -459,6 +460,9 @@ function stepIcon(kind: ChatStep["kind"]) {if (kind === "docs") return <BookOpen size={11} />;if (kind === "entity") return <Waypoints size={11} />;if (kind === "facts") return <History size={11} />;+ // facts 读世界轴、changes 读认知轴,两个图谱工具给不同的图标——+ // 用户看步骤条时该看得出问的是哪根轴+ if (kind === "changes") return <GitCompareArrows size={11} />;if (kind === "query") return <Database size={11} />;return <Wrench size={11} />;}@@ -467,7 +471,7 @@ function stepIcon(kind: ChatStep["kind"]) {function orbState(kind?: ChatStep["kind"]): OrbState {if (kind === "search" || kind === "docs") return "searching";if (kind === "entity") return "connecting";- if (kind === "facts") return "solving";+ if (kind === "facts" || kind === "changes") return "solving";if (kind === "query" || kind === "tool") return "working";return "listening"; // 尚无步骤:刚接到消息}