Elffuss BraidHub

kikocis/utopia public

The tools stop being part of the conversation loop (#175)
Changeseta2d4f93d4eea9ab087bc08c52ee13ffd60e0061b585c608eeddaf6e3326a1854
AuthorWaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-09-02 15:40 +08:00
CommitterGitHub <noreply@github.com> · 2026-09-02 15:40 +08:00
Parents62e2c279c2f7

Browse the files at this changeset

3 files changed

modified crates/utopia-server/src/api/chat.rs +18 −546
@@ -2,6 +2,7 @@
22 //! 事件序列:step*(行动轨迹)| sources(引用清单,随检索增量更新)| delta*(增量文本)→ done | error。
33 //! 模型不支持 tool-calling 时自动降级为一次性 RAG 注入。
44
5+use super::tools;
56 use crate::live::Frame;
67 use axum::extract::{Path, Query, State};
78 use axum::response::sse::{Event, KeepAlive, Sse};
@@ -10,7 +11,7 @@
1011 use serde::Deserialize;
1112 use serde_json::json;
1213 use std::convert::Infallible;
13-use utopia_core::models::{ChunkView, EntityFact, GraphChange, Role};
14+use utopia_core::models::{ChunkView, Role};
1415 use utopia_core::AppError;
1516 use utopia_llm::tool_result_message;
1617 use uuid::Uuid;
@@ -27,12 +28,6 @@
2728
2829 const MAX_HISTORY: usize = 20;
2930 const MAX_ROUNDS: usize = 6;
30-const SEARCH_TOP_K: usize = 6;
31-const TOOL_CHUNK_CHARS: usize = 800;
32-/// 一次 changes 最多回多少条。刚灌完的库里 asserted 是成百上千条,全发出去
33-/// 只会把上下文填满而不增加信息——有信息量的是 corrected/rejected,那类事件
34-/// 本来就稀少。截断时 detail 写 "40+",模型据此知道该收窄窗口
35-const CHANGES_LIMIT: i64 = 40;
3631
3732 #[derive(Deserialize)]
3833 pub struct ChatReq {
@@ -514,17 +509,14 @@
514509 // 会话 id 先行下发(新会话由此告知前端)
515510 yield Frame::new("conversation", json!({ "id": conversation_id }).to_string());
516511
517- // 引用清单:跨轮累积、去重、编号稳定。键 = chunk uuid 或 "charter:{slug}#{anchor}"
518- let mut source_ids: Vec<String> = Vec::new();
519- let mut sources: Vec<serde_json::Value> = Vec::new();
512+ // 引用清单与这一轮认下的实体。**攒在工具外面**——`[3]` 里的 3 取决于
513+ // 之前已经引过几个,各个工具各算各的会让同一个 chunk 拿到两个号
514+ let mut sink = tools::ToolSink::default();
520515 // 落库累积:assistant 全文与行动轨迹(历史回放用)
521516 let mut answer_acc = String::new();
522517 let mut steps_acc: Vec<serde_json::Value> = Vec::new();
523518 // 这一轮的工具往返,原样留一份落库:下一轮回放它,模型才知道自己做过什么
524519 let mut exchange_acc: Vec<serde_json::Value> = Vec::new();
525- // 这一轮认下的实体,落库供下一轮回放。**只记身份不记正文**——
526- // 工具结果里是 chunk 全文,每轮重复堆进上下文几轮就把窗口吃光
527- let mut resolved_acc: Vec<serde_json::Value> = Vec::new();
528520
529521 let mut rounds = 0usize;
530522 loop {
@@ -547,8 +539,8 @@
547539 &state.pool, conversation_id, "assistant", &answer_acc,
548540 &utopia_store::conversations::TurnRecord {
549541 steps: serde_json::Value::Array(steps_acc.clone()),
550- sources: serde_json::Value::Array(sources.clone()),
551- resolved: serde_json::Value::Array(resolved_acc.clone()),
542+ sources: serde_json::Value::Array(sink.sources.clone()),
543+ resolved: serde_json::Value::Array(sink.resolved.clone()),
552544 tool_exchange: serde_json::Value::Array(exchange_acc.clone()),
553545 },
554546 ).await;
@@ -598,7 +590,7 @@
598590 &utopia_store::conversations::TurnRecord {
599591 steps: serde_json::Value::Array(steps_acc.clone()),
600592 sources: serde_json::Value::Array(legacy_sources.clone()),
601- resolved: serde_json::Value::Array(resolved_acc.clone()),
593+ resolved: serde_json::Value::Array(sink.resolved.clone()),
602594 tool_exchange: serde_json::Value::Array(exchange_acc.clone()),
603595 },
604596 ).await;
@@ -642,8 +634,8 @@
642634 &state.pool, conversation_id, "assistant", &answer_acc,
643635 &utopia_store::conversations::TurnRecord {
644636 steps: serde_json::Value::Array(steps_acc.clone()),
645- sources: serde_json::Value::Array(sources.clone()),
646- resolved: serde_json::Value::Array(resolved_acc.clone()),
637+ sources: serde_json::Value::Array(sink.sources.clone()),
638+ resolved: serde_json::Value::Array(sink.resolved.clone()),
647639 tool_exchange: serde_json::Value::Array(exchange_acc.clone()),
648640 },
649641 ).await;
@@ -672,279 +664,14 @@
672664 continue;
673665 }
674666 };
675- let (result, step) = match call.name.as_str() {
676- "search_chunks" => {
677- // check_call 已经保证 query 在且非空——这里不再有回落
678- let q = args["query"].as_str().unwrap_or_default().to_string();
679- let chunks = retrieval::hybrid(&state, kb_id, workspace_id, &q, SEARCH_TOP_K)
680- .await
681- .unwrap_or_default();
682- let mut lines = Vec::new();
683- for c in &chunks {
684- let key = c.id.to_string();
685- let n = match source_ids.iter().position(|id| *id == key) {
686- Some(i) => i + 1,
687- None => {
688- source_ids.push(key);
689- sources.push(source_json(source_ids.len(), c));
690- source_ids.len()
691- }
692- };
693- lines.push(format!(
694- "[{n}] \"{}\" section {}:\n{}",
695- c.filename,
696- c.seq + 1,
697- truncate(&c.text, TOOL_CHUNK_CHARS)
698- ));
699- }
700- let text = if lines.is_empty() {
701- "No results.".to_string()
702- } else {
703- lines.join("\n\n")
704- };
705- (text, json!({ "kind": "search", "label": q, "detail": format!("{} sources", chunks.len()) }))
706- }
707- "search_docs" => {
708- // 同上:check_call 已经拦过,这里不再回落到用户原话
709- let q = args["query"].as_str().unwrap_or_default().to_string();
710- let hits = state.docs.search(&q, 4).unwrap_or_default();
711- let mut lines = Vec::new();
712- for h in &hits {
713- let key = format!("charter:{}#{}", h.slug, h.anchor);
714- let n = match source_ids.iter().position(|id| *id == key) {
715- Some(i) => i + 1,
716- None => {
717- source_ids.push(key);
718- sources.push(charter_source_json(source_ids.len(), h));
719- source_ids.len()
720- }
721- };
722- lines.push(format!(
723- "[{n}] Utopia Charter — {} › {}:\n{}",
724- h.title,
725- h.heading,
726- truncate(&h.body, 1600)
727- ));
728- }
729- let text = if lines.is_empty() {
730- "No matching manual sections.".to_string()
731- } else {
732- lines.join("\n\n")
733- };
734- (text, json!({ "kind": "docs", "label": q, "detail": format!("{} sections", hits.len()) }))
735- }
736- "find_entities" => {
737- let name = args["name"].as_str().unwrap_or("").to_string();
738- let (hits, _) =
739- utopia_store::graph::search_entities(&state.pool, kb_id, &name, 8, 0)
740- .await
741- .unwrap_or_default();
742- let text = if hits.is_empty() {
743- "No matching entities.".to_string()
744- } else {
745- hits.iter()
746- .map(|n| {
747- let dis = n
748- .disambiguator
749- .as_deref()
750- .map(|d| format!(" ({d})"))
751- .unwrap_or_default();
752- format!(
753- "{} | {}{} | {} | {} facts",
754- n.id,
755- n.name,
756- dis,
757- // 没判出类型的实体照样能被搜到、被引用(0009)
758- n.type_label.as_deref().unwrap_or("untyped"),
759- n.degree
760- )
761- })
762- .collect::<Vec<_>>()
763- .join("\n")
764- };
765- for n in &hits {
766- resolved_acc.push(json!({
767- "id": n.id.to_string(), "name": n.name, "type": n.type_label
768- }));
769- }
770- (text, json!({ "kind": "entity", "label": name, "detail": format!("{} matches", hits.len()) }))
771- }
772- "entity_facts" => {
773- let id = args["entity_id"].as_str().and_then(|s| s.parse::<Uuid>().ok());
774- // as-of 过滤:T 时刻有效 = 起点不晚于 T(或未知)且终点晚于 T(或开放)
775- let at = args["at"]
776- .as_str()
777- .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
778- .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc());
779- match id {
780- Some(id) => match utopia_store::graph::entity_detail(&state.pool, kb_id, id).await {
781- Ok((node, mut facts)) => {
782- if let Some(t) = at {
783- facts.retain(|f| {
784- f.valid_from.is_none_or(|from| from <= t)
785- && f.valid_to.is_none_or(|to| to > t)
786- });
787- }
788- let text = if facts.is_empty() {
789- match at {
790- Some(t) => format!(
791- "{}: no facts valid as of {}.",
792- node.name,
793- t.format("%Y-%m-%d")
794- ),
795- None => format!("{}: no recorded facts.", node.name),
796- }
797- } else {
798- facts.iter().map(fact_line).collect::<Vec<_>>().join("\n")
799- };
800- let detail = match at {
801- Some(t) => format!(
802- "{} facts as of {}",
803- facts.len(),
804- t.format("%Y-%m-%d")
805- ),
806- None => format!("{} facts", facts.len()),
807- };
808- (text, json!({ "kind": "facts", "label": node.name, "detail": detail }))
809- }
810- Err(_) => (
811- "Entity not found.".to_string(),
812- json!({ "kind": "facts", "label": "?", "detail": "not found" }),
813- ),
814- },
815- None => (
816- "Invalid entity_id (expected the uuid returned by find_entities)."
817- .to_string(),
818- json!({ "kind": "facts", "label": "?", "detail": "invalid id" }),
819- ),
820- }
821- }
822- "changes" => {
823- let day = |k: &str| {
824- args[k]
825- .as_str()
826- .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
827- };
828- match changes_window(day("since"), day("until"), chrono::Utc::now()) {
829- None => (
830- "Invalid or missing `since` (expected YYYY-MM-DD).".to_string(),
831- json!({ "kind": "changes", "label": "?", "detail": "invalid since" }),
832- ),
833- Some((since, until, window)) => {
834- let entity = args["entity_id"]
835- .as_str()
836- .and_then(|s| s.parse::<Uuid>().ok());
837- let kinds: Option<Vec<String>> = args["kinds"].as_array().map(|a| {
838- a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()
839- });
840- let kinds = kinds.filter(|k: &Vec<String>| !k.is_empty());
841- let rows = utopia_store::graph::graph_changes(
842- &state.pool,
843- kb_id,
844- since,
845- until,
846- entity,
847- kinds.as_deref(),
848- CHANGES_LIMIT,
849- )
850- .await
851- .unwrap_or_default();
852- let text = if rows.is_empty() {
853- format!("No recorded changes in {window}.")
854- } else {
855- rows.iter().map(change_line).collect::<Vec<_>>().join("\n")
856- };
857- let detail = if rows.len() as i64 == CHANGES_LIMIT {
858- format!("{CHANGES_LIMIT}+ changes")
859- } else {
860- format!("{} changes", rows.len())
861- };
862- (text, json!({ "kind": "changes", "label": window, "detail": detail }))
863- }
864- }
865- }
866- "query_data" if !mounted_sources.is_empty() => {
867- let ds_name = args["data_source"].as_str().map(str::trim).unwrap_or("");
868- let sql = args["sql"].as_str().map(str::trim).unwrap_or("");
869- let purpose = args["purpose"].as_str().map(str::trim).unwrap_or("");
870- // 安全边界:只允许本 KB 挂载的源(凭据不出服务端)
871- let found = mounted_sources
872- .iter()
873- .find(|d| d.name.eq_ignore_ascii_case(ds_name));
874- let text = match found {
875- None => format!(
876- "Unknown data source '{ds_name}'. Mounted sources: {}",
877- mounted_sources
878- .iter()
879- .map(|d| d.name.as_str())
880- .collect::<Vec<_>>()
881- .join(", ")
882- ),
883- Some(ds) => {
884- match run_query(&state, ds.id, sql).await {
885- Ok(out) => out,
886- // 错误透传:模型可据此修正 SQL 重试
887- Err(e) => format!("Query failed: {e}"),
888- }
889- }
890- };
891- let detail = if purpose.is_empty() {
892- sql.chars().take(60).collect::<String>()
893- } else {
894- purpose.to_string()
895- };
896- (text, json!({ "kind": "query", "label": ds_name, "detail": detail }))
897- }
898- "remember" if can_write => {
899- let text = args["text"].as_str().map(str::trim).unwrap_or("");
900- let occurred_at = args["occurred_at"]
901- .as_str()
902- .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
903- .map(|d| d.and_hms_opt(12, 0, 0).unwrap().and_utc())
904- .unwrap_or_else(chrono::Utc::now);
905- if text.is_empty() {
906- (
907- "remember requires non-empty text.".to_string(),
908- json!({ "kind": "tool", "label": "remember", "detail": "empty" }),
909- )
910- } else {
911- match utopia_store::memory::append_episode(
912- &state.pool, kb_id, text, occurred_at,
913- )
914- .await
915- {
916- Ok((doc_id, _chunk)) => {
917- // 摄入(embedding/索引/增量抽取)异步走队列,不阻塞对话
918- let _ = utopia_store::jobs::enqueue(
919- &state.pool,
920- "memory_ingest",
921- json!({ "document_id": doc_id }),
922- )
923- .await;
924- state.emit_document(kb_id, doc_id);
925- (
926- format!(
927- "Recorded (effective {}): {text}",
928- occurred_at.format("%Y-%m-%d")
929- ),
930- json!({
931- "kind": "tool", "label": "remember",
932- "detail": text.chars().take(60).collect::<String>()
933- }),
934- )
935- }
936- Err(e) => (
937- format!("Failed to record: {e}"),
938- json!({ "kind": "tool", "label": "remember", "detail": "failed" }),
939- ),
940- }
941- }
942- }
943- other => (
944- format!("Unknown tool: {other}"),
945- json!({ "kind": "tool", "label": other, "detail": "unknown" }),
946- ),
667+ let ctx = tools::ToolCtx {
668+ state: &state,
669+ kb_id,
670+ workspace_id,
671+ mounted_sources: &mounted_sources,
672+ can_write,
947673 };
674+ let (result, step) = tools::dispatch(&ctx, &mut sink, &call.name, &args).await;
948675 // **这一步发生在正文的哪个位置。**
949676 //
950677 // 模型是边说边调的:说一句、查一下、再说一句。SSE 上 `delta` 与
@@ -965,7 +692,7 @@
965692 if step["kind"] == "search" || step["kind"] == "docs" {
966693 yield Frame::new(
967694 "sources",
968- serde_json::to_string(&sources).unwrap_or_else(|_| "[]".into()),
695+ serde_json::to_string(&sink.sources).unwrap_or_else(|_| "[]".into()),
969696 );
970697 }
971698 let result_msg = tool_result_message(&call.id, &result);
@@ -1078,145 +805,6 @@
1078805 })
1079806 }
1080807
1081-/// Charter 引用:前端渲染成手册行,链到 /docs/{slug}#{anchor}。
1082-fn charter_source_json(n: usize, h: &utopia_search::DocsSection) -> serde_json::Value {
1083- json!({
1084- "n": n,
1085- "kind": "charter",
1086- "slug": h.slug,
1087- "anchor": h.anchor,
1088- "heading": h.heading,
1089- "filename": h.title,
1090- "excerpt": truncate(&h.body, 160),
1091- })
1092-}
1093-
1094-/// 事实行:"works at → 星云科技 (2023-08 → now) [90%]",in 方向用 ←。
1095-/// 问数执行:安全闸(解析白名单)→ 引擎执行(只读会话 + 强制 LIMIT + 超时)→ JSON 行。
1096-async fn run_query(state: &AppState, ds_id: Uuid, sql: &str) -> anyhow::Result<String> {
1097- let guarded = crate::query_engine::guard_sql(sql)?;
1098- let (engine, conn) = utopia_store::datasources::engine_and_conn(&state.pool, ds_id).await?;
1099- let result = crate::query_engine::engine_for(&engine, &conn)?
1100- .execute(&guarded)
1101- .await?;
1102- let mut out = String::new();
1103- if result.rows.is_empty() {
1104- out.push_str("(no rows)");
1105- } else {
1106- out.push_str(&result.rows.join("\n"));
1107- out.push_str(&format!("\n({} rows", result.rows.len()));
1108- if result.truncated {
1109- out.push_str(&format!(
1110- ", truncated at {} — aggregate in SQL for totals",
1111- crate::query_engine::ROW_CAP
1112- ));
1113- }
1114- out.push(')');
1115- }
1116- Ok(out)
1117-}
1118-
1119-fn fact_line(f: &EntityFact) -> String {
1120- let other = f.other_name.as_deref().unwrap_or("?");
1121- // 本体没认下、原文说法也没留下时用 "?"——与 other 同一个约定。
1122- // 不编一个"相关"出来:那正是删掉 related_to 要消灭的东西
1123- let pred = f.predicate_label.as_deref().unwrap_or("?");
1124- let core = if f.direction == "out" {
1125- format!("{pred} → {other}")
1126- } else {
1127- format!("{pred} ← {other}")
1128- };
1129- let range = match (&f.valid_from, &f.valid_to) {
1130- (Some(from), Some(to)) => {
1131- format!(" ({} → {})", from.format("%Y-%m-%d"), to.format("%Y-%m-%d"))
1132- }
1133- (Some(from), None) => format!(" ({} → now)", from.format("%Y-%m-%d")),
1134- (None, Some(to)) => format!(" (→ {})", to.format("%Y-%m-%d")),
1135- (None, None) => String::new(),
1136- };
1137- format!("{core}{range} [{}%]", (f.confidence * 100.0).round() as i32)
1138-}
1139-
1140-/// changes 的时间窗:把两个可选日期变成 (SQL 用的半开区间, 展示用的窗口串)。
1141-///
1142-/// **抽成纯函数是因为这里出过一次错。** `until` 进 SQL 前要加一天(说"到 3 月 31 日
1143-/// 为止"的人要的是含 31 日,而 SQL 那头是 `< $3`),第一版把加过一天的值也印进了
1144-/// 展示串,模型于是照着答"截至 8 月 30 日"——问的是 29 日。两个值必须一起算、
1145-/// 一起被测住;分在两处写,迟早再次分叉。
1146-///
1147-/// `now` 从外面传进来而不是在里面取,纯粹是为了这个函数测得动。
1148-fn changes_window(
1149- since: Option<chrono::NaiveDate>,
1150- until: Option<chrono::NaiveDate>,
1151- now: chrono::DateTime<chrono::Utc>,
1152-) -> Option<(
1153- chrono::DateTime<chrono::Utc>,
1154- chrono::DateTime<chrono::Utc>,
1155- String,
1156-)> {
1157- let from = since?;
1158- let start = from.and_hms_opt(0, 0, 0).unwrap().and_utc();
1159- let end = until
1160- .and_then(|d| d.succ_opt())
1161- .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc())
1162- .unwrap_or(now);
1163- // 展示用的是**问的那天**,没问就写 now——绝不是 end
1164- let label = format!(
1165- "{} → {}",
1166- from.format("%Y-%m-%d"),
1167- match until {
1168- Some(d) => d.format("%Y-%m-%d").to_string(),
1169- None => "now".to_string(),
1170- }
1171- );
1172- Some((start, end, label))
1173-}
1174-
1175-/// 认知轴上的一行。
1176-///
1177-/// 排版把两根轴**分开写**:`at` 前面标事件类型,世界轴的区间夹在括号里跟在断言后。
1178-/// 若把它们排成一串日期,模型会把"2026 年记下的"读成"2026 年发生的"——那正是
1179-/// 这个工具要防的误读。
1180-fn change_line(c: &GraphChange) -> String {
1181- let object = match (&c.object_name, &c.object_value) {
1182- (Some(name), _) => name.clone(),
1183- (None, Some(v)) => match v {
1184- serde_json::Value::String(s) => s.clone(),
1185- other => other.to_string(),
1186- },
1187- (None, None) => "?".to_string(),
1188- };
1189- let range = match (&c.valid_from, &c.valid_to) {
1190- (Some(from), Some(to)) => {
1191- format!(
1192- " [valid {} → {}]",
1193- from.format("%Y-%m-%d"),
1194- to.format("%Y-%m-%d")
1195- )
1196- }
1197- (Some(from), None) => format!(" [valid {} → now]", from.format("%Y-%m-%d")),
1198- (None, Some(to)) => format!(" [valid → {}]", to.format("%Y-%m-%d")),
1199- (None, None) => String::new(),
1200- };
1201- // 文件名不带 [n]:引证编号是 chunk 的,这里只有 document,发一个编号出去
1202- // 会在界面上落成一条指不到东西的引证
1203- let src = match (&c.filename, &c.quote) {
1204- (Some(f), Some(q)) => format!(" — from \"{f}\": \"{}\"", truncate(q, 160)),
1205- (Some(f), None) => format!(" — from \"{f}\""),
1206- _ => String::new(),
1207- };
1208- format!(
1209- "{} {}: {} {} {}{}{}",
1210- c.at.format("%Y-%m-%d"),
1211- c.kind,
1212- c.subject_name,
1213- c.predicate_label.as_deref().unwrap_or("?"),
1214- object,
1215- range,
1216- src
1217- )
1218-}
1219-
1220808 /// 降级路径的系统提示(tool-calling 不可用时的一次性注入)。
1221809 fn legacy_system_prompt(chunks: &[ChunkView]) -> String {
1222810 if chunks.is_empty() {
@@ -1340,122 +928,6 @@
1340928 mod tests {
1341929 use super::*;
1342930
1343- fn d(s: &str) -> chrono::NaiveDate {
1344- chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()
1345- }
1346- fn t(s: &str) -> chrono::DateTime<chrono::Utc> {
1347- s.parse().unwrap()
1348- }
1349-
1350- // --- changes_window -----------------------------------------------------
1351-
1352- /// 说"到 3 月 31 日为止"的人要的是**含 31 日**。SQL 那头是 `< end`,
1353- /// 所以 end 必须落在 4 月 1 日零点——差这一天,问 31 日会安静地丢掉 31 日
1354- #[test]
1355- fn until_names_a_day_the_window_must_contain() {
1356- let (start, end, label) = changes_window(
1357- Some(d("2026-03-01")),
1358- Some(d("2026-03-31")),
1359- t("2026-06-01T00:00:00Z"),
1360- )
1361- .unwrap();
1362- assert_eq!(start, t("2026-03-01T00:00:00Z"));
1363- assert_eq!(end, t("2026-04-01T00:00:00Z"));
1364- // 但**展示串里绝不能出现 04-01**:那是半开区间的内部细节,
1365- // 印出去等于告诉模型窗口比它要的宽一天,模型会照着答(这条真的发生过)
1366- assert_eq!(label, "2026-03-01 → 2026-03-31");
1367- }
1368-
1369- /// 没给 until 时,展示串写 now。写成 end 的格式化结果就等于把服务器时钟
1370- /// 当成用户问的边界——看着像个精确答案,其实只是"现在几点"
1371- #[test]
1372- fn an_open_window_says_now_rather_than_the_clock() {
1373- let now = t("2026-06-01T13:45:00Z");
1374- let (_, end, label) = changes_window(Some(d("2026-03-01")), None, now).unwrap();
1375- assert_eq!(end, now);
1376- assert_eq!(label, "2026-03-01 → now");
1377- }
1378-
1379- #[test]
1380- fn without_since_there_is_no_window() {
1381- assert!(changes_window(None, Some(d("2026-03-31")), t("2026-06-01T00:00:00Z")).is_none());
1382- }
1383-
1384- // --- change_line --------------------------------------------------------
1385-
1386- fn change(kind: &str) -> GraphChange {
1387- GraphChange {
1388- fact_id: Uuid::nil(),
1389- at: t("2026-08-28T10:00:00Z"),
1390- kind: kind.to_string(),
1391- subject_id: Uuid::nil(),
1392- subject_name: "Acme".to_string(),
1393- predicate_label: Some("founded in".to_string()),
1394- object_name: None,
1395- object_value: None,
1396- valid_from: None,
1397- valid_to: None,
1398- // 两端都没日期就没有精度——夹具也得守这条不变量(见 `facts.valid_from_precision`)
1399- // 两端都没日期,所以两端都没有精度(见 facts 的两个精度列)
1400- valid_from_precision: None,
1401- valid_to_precision: None,
1402- confidence: 0.9,
1403- document_id: None,
1404- filename: None,
1405- quote: None,
1406- }
1407- }
1408-
1409- /// 字面值要读成它自己。走 `Value::to_string()` 会把字符串连引号一起印出来,
1410- /// 模型于是把 `"1993"` 当成答案的一部分
1411- #[test]
1412- fn a_literal_value_reads_as_itself_not_as_json() {
1413- let mut c = change("asserted");
1414- c.object_value = Some(serde_json::json!("1993"));
1415- assert!(
1416- change_line(&c).ends_with("Acme founded in 1993"),
1417- "{}",
1418- change_line(&c)
1419- );
1420- }
1421-
1422- /// 两根轴必须在同一行里**看得出是两样东西**:记录时刻在前、无标签,
1423- /// 世界轴区间在后、带 `valid` 字样。排成一串裸日期,模型会把
1424- /// "2026 年记下的"读成"2026 年发生的"——这个工具存在的理由就是防这个
1425- #[test]
1426- fn the_record_time_and_the_valid_range_do_not_read_as_one_date_run() {
1427- let mut c = change("corrected");
1428- c.object_name = Some("Berlin".to_string());
1429- c.predicate_label = Some("headquartered in".to_string());
1430- c.valid_from = Some(t("2019-01-01T00:00:00Z"));
1431- let line = change_line(&c);
1432- assert!(line.starts_with("2026-08-28 corrected: "), "{line}");
1433- assert!(line.contains("[valid 2019-01-01 → now]"), "{line}");
1434- }
1435-
1436- /// 没有证据就什么都别说。凭空补一句 from "…" 会让一条无出处的断言
1437- /// 看起来有出处
1438- #[test]
1439- fn a_fact_with_no_evidence_claims_no_document() {
1440- let mut c = change("rejected");
1441- c.object_name = Some("Berlin".to_string());
1442- assert!(!change_line(&c).contains("from"), "{}", change_line(&c));
1443- }
1444-
1445- #[test]
1446- fn evidence_carries_the_filename_and_the_quote() {
1447- let mut c = change("corrected");
1448- c.object_name = Some("Berlin".to_string());
1449- c.filename = Some("annual-report.pdf".to_string());
1450- c.quote = Some("moved its head office to Berlin".to_string());
1451- let line = change_line(&c);
1452- assert!(line.contains("from \"annual-report.pdf\""), "{line}");
1453- assert!(
1454- line.contains("\"moved its head office to Berlin\""),
1455- "{line}"
1456- );
1457- }
1458-
1459931 // --- check_call ---------------------------------------------------------
1460932
1461933 /// 参数在半路断掉——模型撞上 token 上限时就长这样。
modified crates/utopia-server/src/api/mod.rs +1 −0
@@ -14,6 +14,7 @@
1414 mod search_routes;
1515 mod settings_routes;
1616 mod sources_routes;
17+mod tools;
1718 mod workspaces;
1819
1920 use axum::extract::DefaultBodyLimit;
added crates/utopia-server/src/api/tools.rs +655 −0
@@ -0,0 +1,655 @@
1+//! 七个工具的**执行**,与谁在调用它们无关。
2+//!
3+//! 从前这些是 `chat.rs` 里一个 `match` 的七条分支,每条 20–70 行,闭包捕获着
4+//! 流式循环的局部变量。那样写在只有对话一个调用方时没问题——**而 MCP 是第二个**。
5+//! 抽出来之后两边共用同一份实现,不会出现「对话里的 entity_facts 和 MCP 里的
6+//! 不是同一个东西」。
7+//!
8+//! 工具定义(给模型看的 JSON schema)仍在 `chat.rs`:那是提示词的一部分,
9+//! 随对话策略走;这里只管拿到参数之后干什么。
10+
11+use serde_json::json;
12+use utopia_core::models::{ChunkView, DataSourceView, EntityFact, GraphChange};
13+use uuid::Uuid;
14+
15+use crate::retrieval;
16+use crate::state::AppState;
17+
18+const SEARCH_TOP_K: usize = 6;
19+const TOOL_CHUNK_CHARS: usize = 800;
20+/// 一次 changes 最多回多少条。刚灌完的库里 asserted 是成百上千条,全发出去
21+/// 只会把上下文填满而不增加信息——有信息量的是 corrected/rejected,那类事件
22+/// 本来就稀少。截断时 detail 写 "40+",模型据此知道该收窄窗口
23+const CHANGES_LIMIT: i64 = 40;
24+
25+/// 一次工具调用看得见的世界。**只读**——工具改不了它。
26+pub struct ToolCtx<'a> {
27+ pub state: &'a AppState,
28+ pub kb_id: Uuid,
29+ pub workspace_id: Uuid,
30+ /// 本库挂载的数据源。**`query_data` 的安全边界就是这个列表**:
31+ /// 凭据不出服务端,模型只能按名字点单
32+ pub mounted_sources: &'a [DataSourceView],
33+ /// editor 及以上才有 `remember`
34+ pub can_write: bool,
35+}
36+
37+/// 工具执行过程中往外攒的东西。
38+///
39+/// **引用编号是有状态的**:`[3]` 里的 3 取决于这一轮之前已经引过几个,
40+/// 所以不能让每个工具各算各的再合并——那样同一个 chunk 会拿到两个号。
41+#[derive(Default)]
42+pub struct ToolSink {
43+ /// 去重键(chunk uuid,或 `charter:{slug}#{anchor}`),下标 +1 就是引用号
44+ pub source_ids: Vec<String>,
45+ /// 发给前端的引用清单,与 `source_ids` 同序
46+ pub sources: Vec<serde_json::Value>,
47+ /// 这一轮认下的实体,落进会话供下一轮回放
48+ pub resolved: Vec<serde_json::Value>,
49+}
50+
51+/// 一次工具调用的产出:给模型的文本 + 给界面的一步。
52+pub type ToolResult = (String, serde_json::Value);
53+
54+/// 按名字派发。**未知工具不是错误**——模型偶尔会编一个名字出来,
55+/// 告诉它没有这个工具,它下一轮就换一个,比中断整场对话好。
56+pub async fn dispatch(
57+ ctx: &ToolCtx<'_>,
58+ sink: &mut ToolSink,
59+ name: &str,
60+ args: &serde_json::Value,
61+) -> ToolResult {
62+ match name {
63+ "search_chunks" => search_chunks(ctx, sink, args).await,
64+ "search_docs" => search_docs(ctx, sink, args).await,
65+ "find_entities" => find_entities(ctx, sink, args).await,
66+ "entity_facts" => entity_facts(ctx, args).await,
67+ "changes" => changes(ctx, args).await,
68+ "query_data" if !ctx.mounted_sources.is_empty() => query_data(ctx, args).await,
69+ "remember" if ctx.can_write => remember(ctx, args).await,
70+ other => (
71+ format!("Unknown tool: {other}"),
72+ json!({ "kind": "tool", "label": other, "detail": "unknown" }),
73+ ),
74+ }
75+}
76+
77+/// 已经引过的给回原号,没引过的落一个新号。**同一个 chunk 在一轮对话里
78+/// 只能有一个号**,否则模型引 `[2]` 而界面上有两个 `[2]`。
79+fn cite(sink: &mut ToolSink, key: String, make: impl FnOnce(usize) -> serde_json::Value) -> usize {
80+ match sink.source_ids.iter().position(|id| *id == key) {
81+ Some(i) => i + 1,
82+ None => {
83+ sink.source_ids.push(key);
84+ sink.sources.push(make(sink.source_ids.len()));
85+ sink.source_ids.len()
86+ }
87+ }
88+}
89+
90+pub async fn search_chunks(
91+ ctx: &ToolCtx<'_>,
92+ sink: &mut ToolSink,
93+ args: &serde_json::Value,
94+) -> ToolResult {
95+ // 必填参数由 `chat::check_call` 在派发之前挡下,所以这里不再回落到
96+ // 用户那句原话——回落产出的是一个看起来没问题的错误答案
97+ let q = args["query"].as_str().unwrap_or_default().to_string();
98+ let chunks = retrieval::hybrid(ctx.state, ctx.kb_id, ctx.workspace_id, &q, SEARCH_TOP_K)
99+ .await
100+ .unwrap_or_default();
101+ let mut lines = Vec::new();
102+ for c in &chunks {
103+ let n = cite(sink, c.id.to_string(), |n| source_json(n, c));
104+ lines.push(format!(
105+ "[{n}] \"{}\" section {}:\n{}",
106+ c.filename,
107+ c.seq + 1,
108+ truncate(&c.text, TOOL_CHUNK_CHARS)
109+ ));
110+ }
111+ let text = if lines.is_empty() {
112+ "No results.".to_string()
113+ } else {
114+ lines.join("\n\n")
115+ };
116+ (
117+ text,
118+ json!({ "kind": "search", "label": q, "detail": format!("{} sources", chunks.len()) }),
119+ )
120+}
121+
122+pub async fn search_docs(
123+ ctx: &ToolCtx<'_>,
124+ sink: &mut ToolSink,
125+ args: &serde_json::Value,
126+) -> ToolResult {
127+ // 必填参数由 `chat::check_call` 在派发之前挡下,所以这里不再回落到
128+ // 用户那句原话——回落产出的是一个看起来没问题的错误答案
129+ let q = args["query"].as_str().unwrap_or_default().to_string();
130+ let hits = ctx.state.docs.search(&q, 4).unwrap_or_default();
131+ let mut lines = Vec::new();
132+ for h in &hits {
133+ let key = format!("charter:{}#{}", h.slug, h.anchor);
134+ let n = cite(sink, key, |n| charter_source_json(n, h));
135+ lines.push(format!(
136+ "[{n}] Utopia Charter — {} › {}:\n{}",
137+ h.title,
138+ h.heading,
139+ truncate(&h.body, 1600)
140+ ));
141+ }
142+ let text = if lines.is_empty() {
143+ "No matching manual sections.".to_string()
144+ } else {
145+ lines.join("\n\n")
146+ };
147+ (
148+ text,
149+ json!({ "kind": "docs", "label": q, "detail": format!("{} sections", hits.len()) }),
150+ )
151+}
152+
153+pub async fn find_entities(
154+ ctx: &ToolCtx<'_>,
155+ sink: &mut ToolSink,
156+ args: &serde_json::Value,
157+) -> ToolResult {
158+ let name = args["name"].as_str().unwrap_or("").to_string();
159+ let (hits, _) = utopia_store::graph::search_entities(&ctx.state.pool, ctx.kb_id, &name, 8, 0)
160+ .await
161+ .unwrap_or_default();
162+ let text = if hits.is_empty() {
163+ "No matching entities.".to_string()
164+ } else {
165+ hits.iter()
166+ .map(|n| {
167+ let dis = n
168+ .disambiguator
169+ .as_deref()
170+ .map(|d| format!(" ({d})"))
171+ .unwrap_or_default();
172+ format!(
173+ "{} | {}{} | {} | {} facts",
174+ n.id,
175+ n.name,
176+ dis,
177+ // 没判出类型的实体照样能被搜到、被引用(0009)
178+ n.type_label.as_deref().unwrap_or("untyped"),
179+ n.degree
180+ )
181+ })
182+ .collect::<Vec<_>>()
183+ .join("\n")
184+ };
185+ for n in &hits {
186+ sink.resolved.push(json!({
187+ "id": n.id.to_string(), "name": n.name, "type": n.type_label
188+ }));
189+ }
190+ (
191+ text,
192+ json!({ "kind": "entity", "label": name, "detail": format!("{} matches", hits.len()) }),
193+ )
194+}
195+
196+pub async fn entity_facts(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult {
197+ let id = args["entity_id"]
198+ .as_str()
199+ .and_then(|s| s.parse::<Uuid>().ok());
200+ // as-of 过滤:T 时刻有效 = 起点不晚于 T(或未知)且终点晚于 T(或开放)
201+ let at = args["at"]
202+ .as_str()
203+ .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
204+ .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc());
205+ let Some(id) = id else {
206+ return (
207+ "Invalid entity_id (expected the uuid returned by find_entities).".to_string(),
208+ json!({ "kind": "facts", "label": "?", "detail": "invalid id" }),
209+ );
210+ };
211+ match utopia_store::graph::entity_detail(&ctx.state.pool, ctx.kb_id, id).await {
212+ Ok((node, mut facts)) => {
213+ if let Some(t) = at {
214+ facts.retain(|f| {
215+ f.valid_from.is_none_or(|from| from <= t) && f.valid_to.is_none_or(|to| to > t)
216+ });
217+ }
218+ let text = if facts.is_empty() {
219+ match at {
220+ Some(t) => format!(
221+ "{}: no facts valid as of {}.",
222+ node.name,
223+ t.format("%Y-%m-%d")
224+ ),
225+ None => format!("{}: no recorded facts.", node.name),
226+ }
227+ } else {
228+ facts.iter().map(fact_line).collect::<Vec<_>>().join("\n")
229+ };
230+ let detail = match at {
231+ Some(t) => format!("{} facts as of {}", facts.len(), t.format("%Y-%m-%d")),
232+ None => format!("{} facts", facts.len()),
233+ };
234+ (
235+ text,
236+ json!({ "kind": "facts", "label": node.name, "detail": detail }),
237+ )
238+ }
239+ Err(_) => (
240+ "Entity not found.".to_string(),
241+ json!({ "kind": "facts", "label": "?", "detail": "not found" }),
242+ ),
243+ }
244+}
245+
246+pub async fn changes(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult {
247+ let day = |k: &str| {
248+ args[k]
249+ .as_str()
250+ .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
251+ };
252+ let Some((since, until, window)) =
253+ changes_window(day("since"), day("until"), chrono::Utc::now())
254+ else {
255+ return (
256+ "Invalid or missing `since` (expected YYYY-MM-DD).".to_string(),
257+ json!({ "kind": "changes", "label": "?", "detail": "invalid since" }),
258+ );
259+ };
260+ let entity = args["entity_id"]
261+ .as_str()
262+ .and_then(|s| s.parse::<Uuid>().ok());
263+ let kinds: Option<Vec<String>> = args["kinds"].as_array().map(|a| {
264+ a.iter()
265+ .filter_map(|v| v.as_str().map(str::to_string))
266+ .collect()
267+ });
268+ let kinds = kinds.filter(|k: &Vec<String>| !k.is_empty());
269+ let rows = utopia_store::graph::graph_changes(
270+ &ctx.state.pool,
271+ ctx.kb_id,
272+ since,
273+ until,
274+ entity,
275+ kinds.as_deref(),
276+ CHANGES_LIMIT,
277+ )
278+ .await
279+ .unwrap_or_default();
280+ let text = if rows.is_empty() {
281+ format!("No recorded changes in {window}.")
282+ } else {
283+ rows.iter().map(change_line).collect::<Vec<_>>().join("\n")
284+ };
285+ let detail = if rows.len() as i64 == CHANGES_LIMIT {
286+ format!("{CHANGES_LIMIT}+ changes")
287+ } else {
288+ format!("{} changes", rows.len())
289+ };
290+ (
291+ text,
292+ json!({ "kind": "changes", "label": window, "detail": detail }),
293+ )
294+}
295+
296+pub async fn query_data(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult {
297+ let ds_name = args["data_source"].as_str().map(str::trim).unwrap_or("");
298+ let sql = args["sql"].as_str().map(str::trim).unwrap_or("");
299+ let purpose = args["purpose"].as_str().map(str::trim).unwrap_or("");
300+ // 安全边界:只允许本 KB 挂载的源(凭据不出服务端)
301+ let found = ctx
302+ .mounted_sources
303+ .iter()
304+ .find(|d| d.name.eq_ignore_ascii_case(ds_name));
305+ let text = match found {
306+ None => format!(
307+ "Unknown data source '{ds_name}'. Mounted sources: {}",
308+ ctx.mounted_sources
309+ .iter()
310+ .map(|d| d.name.as_str())
311+ .collect::<Vec<_>>()
312+ .join(", ")
313+ ),
314+ Some(ds) => match run_query(ctx.state, ds.id, sql).await {
315+ Ok(out) => out,
316+ // 错误透传:模型可据此修正 SQL 重试
317+ Err(e) => format!("Query failed: {e}"),
318+ },
319+ };
320+ let detail = if purpose.is_empty() {
321+ sql.chars().take(60).collect::<String>()
322+ } else {
323+ purpose.to_string()
324+ };
325+ (
326+ text,
327+ json!({ "kind": "query", "label": ds_name, "detail": detail }),
328+ )
329+}
330+
331+pub async fn remember(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult {
332+ let text = args["text"].as_str().map(str::trim).unwrap_or("");
333+ let occurred_at = args["occurred_at"]
334+ .as_str()
335+ .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
336+ .map(|d| d.and_hms_opt(12, 0, 0).unwrap().and_utc())
337+ .unwrap_or_else(chrono::Utc::now);
338+ if text.is_empty() {
339+ return (
340+ "remember requires non-empty text.".to_string(),
341+ json!({ "kind": "tool", "label": "remember", "detail": "empty" }),
342+ );
343+ }
344+ match utopia_store::memory::append_episode(&ctx.state.pool, ctx.kb_id, text, occurred_at).await
345+ {
346+ Ok((doc_id, _chunk)) => {
347+ // 摄入(embedding/索引/增量抽取)异步走队列,不阻塞对话
348+ let _ = utopia_store::jobs::enqueue(
349+ &ctx.state.pool,
350+ "memory_ingest",
351+ json!({ "document_id": doc_id }),
352+ )
353+ .await;
354+ ctx.state.emit_document(ctx.kb_id, doc_id);
355+ (
356+ format!(
357+ "Recorded (effective {}): {text}",
358+ occurred_at.format("%Y-%m-%d")
359+ ),
360+ json!({
361+ "kind": "tool", "label": "remember",
362+ "detail": text.chars().take(60).collect::<String>()
363+ }),
364+ )
365+ }
366+ Err(e) => (
367+ format!("Failed to record: {e}"),
368+ json!({ "kind": "tool", "label": "remember", "detail": "failed" }),
369+ ),
370+ }
371+}
372+
373+// ---------------------------------------------------------------------------
374+// 排版与执行的辅助。**对话降级路径也用它们**,所以是 pub(super) 而不是私有
375+// ---------------------------------------------------------------------------
376+
377+pub(super) fn source_json(n: usize, c: &ChunkView) -> serde_json::Value {
378+ json!({
379+ "n": n,
380+ "chunk_id": c.id,
381+ "document_id": c.document_id,
382+ "filename": c.filename,
383+ "excerpt": truncate(&c.text, 160),
384+ })
385+}
386+
387+/// Charter 引用:前端渲染成手册行,链到 /docs/{slug}#{anchor}。
388+pub(super) fn charter_source_json(n: usize, h: &utopia_search::DocsSection) -> serde_json::Value {
389+ json!({
390+ "n": n,
391+ "kind": "charter",
392+ "slug": h.slug,
393+ "anchor": h.anchor,
394+ "heading": h.heading,
395+ "filename": h.title,
396+ "excerpt": truncate(&h.body, 160),
397+ })
398+}
399+
400+/// 问数执行:安全闸(解析白名单)→ 引擎执行(只读会话 + 强制 LIMIT + 超时)→ JSON 行。
401+async fn run_query(state: &AppState, ds_id: Uuid, sql: &str) -> anyhow::Result<String> {
402+ let guarded = crate::query_engine::guard_sql(sql)?;
403+ let (engine, conn) = utopia_store::datasources::engine_and_conn(&state.pool, ds_id).await?;
404+ let result = crate::query_engine::engine_for(&engine, &conn)?
405+ .execute(&guarded)
406+ .await?;
407+ let mut out = String::new();
408+ if result.rows.is_empty() {
409+ out.push_str("(no rows)");
410+ } else {
411+ out.push_str(&result.rows.join("\n"));
412+ out.push_str(&format!("\n({} rows", result.rows.len()));
413+ if result.truncated {
414+ out.push_str(&format!(
415+ ", truncated at {} — aggregate in SQL for totals",
416+ crate::query_engine::ROW_CAP
417+ ));
418+ }
419+ out.push(')');
420+ }
421+ Ok(out)
422+}
423+
424+/// 事实行:"works at → 星云科技 (2023-08 → now) [90%]",in 方向用 ←。
425+fn fact_line(f: &EntityFact) -> String {
426+ let other = f.other_name.as_deref().unwrap_or("?");
427+ // 本体没认下、原文说法也没留下时用 "?"——与 other 同一个约定。
428+ // 不编一个"相关"出来:那正是删掉 related_to 要消灭的东西
429+ let pred = f.predicate_label.as_deref().unwrap_or("?");
430+ let core = if f.direction == "out" {
431+ format!("{pred} → {other}")
432+ } else {
433+ format!("{pred} ← {other}")
434+ };
435+ let range = match (&f.valid_from, &f.valid_to) {
436+ (Some(from), Some(to)) => {
437+ format!(" ({} → {})", from.format("%Y-%m-%d"), to.format("%Y-%m-%d"))
438+ }
439+ (Some(from), None) => format!(" ({} → now)", from.format("%Y-%m-%d")),
440+ (None, Some(to)) => format!(" (→ {})", to.format("%Y-%m-%d")),
441+ (None, None) => String::new(),
442+ };
443+ format!("{core}{range} [{}%]", (f.confidence * 100.0).round() as i32)
444+}
445+
446+/// changes 的时间窗:把两个可选日期变成 (SQL 用的半开区间, 展示用的窗口串)。
447+///
448+/// **抽成纯函数是因为这里出过一次错。** `until` 进 SQL 前要加一天(说"到 3 月 31 日
449+/// 为止"的人要的是含 31 日,而 SQL 那头是 `< $3`),第一版把加过一天的值也印进了
450+/// 展示串,模型于是照着答"截至 8 月 30 日"——问的是 29 日。两个值必须一起算、
451+/// 一起被测住;分在两处写,迟早再次分叉。
452+///
453+/// `now` 从外面传进来而不是在里面取,纯粹是为了这个函数测得动。
454+fn changes_window(
455+ since: Option<chrono::NaiveDate>,
456+ until: Option<chrono::NaiveDate>,
457+ now: chrono::DateTime<chrono::Utc>,
458+) -> Option<(
459+ chrono::DateTime<chrono::Utc>,
460+ chrono::DateTime<chrono::Utc>,
461+ String,
462+)> {
463+ let from = since?;
464+ let start = from.and_hms_opt(0, 0, 0).unwrap().and_utc();
465+ let end = until
466+ .and_then(|d| d.succ_opt())
467+ .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc())
468+ .unwrap_or(now);
469+ // 展示用的是**问的那天**,没问就写 now——绝不是 end
470+ let label = format!(
471+ "{} → {}",
472+ from.format("%Y-%m-%d"),
473+ match until {
474+ Some(d) => d.format("%Y-%m-%d").to_string(),
475+ None => "now".to_string(),
476+ }
477+ );
478+ Some((start, end, label))
479+}
480+
481+/// 认知轴上的一行。
482+///
483+/// 排版把两根轴**分开写**:`at` 前面标事件类型,世界轴的区间夹在括号里跟在断言后。
484+/// 若把它们排成一串日期,模型会把"2026 年记下的"读成"2026 年发生的"——那正是
485+/// 这个工具要防的误读。
486+fn change_line(c: &GraphChange) -> String {
487+ let object = match (&c.object_name, &c.object_value) {
488+ (Some(name), _) => name.clone(),
489+ (None, Some(v)) => match v {
490+ serde_json::Value::String(s) => s.clone(),
491+ other => other.to_string(),
492+ },
493+ (None, None) => "?".to_string(),
494+ };
495+ let range = match (&c.valid_from, &c.valid_to) {
496+ (Some(from), Some(to)) => {
497+ format!(
498+ " [valid {} → {}]",
499+ from.format("%Y-%m-%d"),
500+ to.format("%Y-%m-%d")
501+ )
502+ }
503+ (Some(from), None) => format!(" [valid {} → now]", from.format("%Y-%m-%d")),
504+ (None, Some(to)) => format!(" [valid → {}]", to.format("%Y-%m-%d")),
505+ (None, None) => String::new(),
506+ };
507+ // 文件名不带 [n]:引证编号是 chunk 的,这里只有 document,发一个编号出去
508+ // 会在界面上落成一条指不到东西的引证
509+ let src = match (&c.filename, &c.quote) {
510+ (Some(f), Some(q)) => format!(" — from \"{f}\": \"{}\"", truncate(q, 160)),
511+ (Some(f), None) => format!(" — from \"{f}\""),
512+ _ => String::new(),
513+ };
514+ format!(
515+ "{} {}: {} {} {}{}{}",
516+ c.at.format("%Y-%m-%d"),
517+ c.kind,
518+ c.subject_name,
519+ c.predicate_label.as_deref().unwrap_or("?"),
520+ object,
521+ range,
522+ src
523+ )
524+}
525+
526+pub(super) fn truncate(text: &str, max_chars: usize) -> String {
527+ let t = text.trim();
528+ if t.chars().count() <= max_chars {
529+ t.to_string()
530+ } else {
531+ let cut: String = t.chars().take(max_chars).collect();
532+ format!("{cut}…")
533+ }
534+}
535+
536+#[cfg(test)]
537+mod tests {
538+ use super::*;
539+
540+ fn d(s: &str) -> chrono::NaiveDate {
541+ chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()
542+ }
543+ fn t(s: &str) -> chrono::DateTime<chrono::Utc> {
544+ s.parse().unwrap()
545+ }
546+
547+ // --- changes_window -----------------------------------------------------
548+
549+ /// 说"到 3 月 31 日为止"的人要的是**含 31 日**。SQL 那头是 `< end`,
550+ /// 所以 end 必须落在 4 月 1 日零点——差这一天,问 31 日会安静地丢掉 31 日
551+ #[test]
552+ fn until_names_a_day_the_window_must_contain() {
553+ let (start, end, label) = changes_window(
554+ Some(d("2026-03-01")),
555+ Some(d("2026-03-31")),
556+ t("2026-06-01T00:00:00Z"),
557+ )
558+ .unwrap();
559+ assert_eq!(start, t("2026-03-01T00:00:00Z"));
560+ assert_eq!(end, t("2026-04-01T00:00:00Z"));
561+ // 但**展示串里绝不能出现 04-01**:那是半开区间的内部细节,
562+ // 印出去等于告诉模型窗口比它要的宽一天,模型会照着答(这条真的发生过)
563+ assert_eq!(label, "2026-03-01 → 2026-03-31");
564+ }
565+
566+ /// 没给 until 时,展示串写 now。写成 end 的格式化结果就等于把服务器时钟
567+ /// 当成用户问的边界——看着像个精确答案,其实只是"现在几点"
568+ #[test]
569+ fn an_open_window_says_now_rather_than_the_clock() {
570+ let now = t("2026-06-01T13:45:00Z");
571+ let (_, end, label) = changes_window(Some(d("2026-03-01")), None, now).unwrap();
572+ assert_eq!(end, now);
573+ assert_eq!(label, "2026-03-01 → now");
574+ }
575+
576+ #[test]
577+ fn without_since_there_is_no_window() {
578+ assert!(changes_window(None, Some(d("2026-03-31")), t("2026-06-01T00:00:00Z")).is_none());
579+ }
580+
581+ // --- change_line --------------------------------------------------------
582+
583+ fn change(kind: &str) -> GraphChange {
584+ GraphChange {
585+ fact_id: Uuid::nil(),
586+ at: t("2026-08-28T10:00:00Z"),
587+ kind: kind.to_string(),
588+ subject_id: Uuid::nil(),
589+ subject_name: "Acme".to_string(),
590+ predicate_label: Some("founded in".to_string()),
591+ object_name: None,
592+ object_value: None,
593+ valid_from: None,
594+ valid_to: None,
595+ // 两端都没日期就没有精度——夹具也得守这条不变量(见 `facts.valid_from_precision`)
596+ // 两端都没日期,所以两端都没有精度(见 facts 的两个精度列)
597+ valid_from_precision: None,
598+ valid_to_precision: None,
599+ confidence: 0.9,
600+ document_id: None,
601+ filename: None,
602+ quote: None,
603+ }
604+ }
605+
606+ /// 字面值要读成它自己。走 `Value::to_string()` 会把字符串连引号一起印出来,
607+ /// 模型于是把 `"1993"` 当成答案的一部分
608+ #[test]
609+ fn a_literal_value_reads_as_itself_not_as_json() {
610+ let mut c = change("asserted");
611+ c.object_value = Some(serde_json::json!("1993"));
612+ assert!(
613+ change_line(&c).ends_with("Acme founded in 1993"),
614+ "{}",
615+ change_line(&c)
616+ );
617+ }
618+
619+ /// 两根轴必须在同一行里**看得出是两样东西**:记录时刻在前、无标签,
620+ /// 世界轴区间在后、带 `valid` 字样。排成一串裸日期,模型会把
621+ /// "2026 年记下的"读成"2026 年发生的"——这个工具存在的理由就是防这个
622+ #[test]
623+ fn the_record_time_and_the_valid_range_do_not_read_as_one_date_run() {
624+ let mut c = change("corrected");
625+ c.object_name = Some("Berlin".to_string());
626+ c.predicate_label = Some("headquartered in".to_string());
627+ c.valid_from = Some(t("2019-01-01T00:00:00Z"));
628+ let line = change_line(&c);
629+ assert!(line.starts_with("2026-08-28 corrected: "), "{line}");
630+ assert!(line.contains("[valid 2019-01-01 → now]"), "{line}");
631+ }
632+
633+ /// 没有证据就什么都别说。凭空补一句 from "…" 会让一条无出处的断言
634+ /// 看起来有出处
635+ #[test]
636+ fn a_fact_with_no_evidence_claims_no_document() {
637+ let mut c = change("rejected");
638+ c.object_name = Some("Berlin".to_string());
639+ assert!(!change_line(&c).contains("from"), "{}", change_line(&c));
640+ }
641+
642+ #[test]
643+ fn evidence_carries_the_filename_and_the_quote() {
644+ let mut c = change("corrected");
645+ c.object_name = Some("Berlin".to_string());
646+ c.filename = Some("annual-report.pdf".to_string());
647+ c.quote = Some("moved its head office to Berlin".to_string());
648+ let line = change_line(&c);
649+ assert!(line.contains("from \"annual-report.pdf\""), "{line}");
650+ assert!(
651+ line.contains("\"moved its head office to Berlin\""),
652+ "{line}"
653+ );
654+ }
655+}