Elffuss BraidHub

kikocis/utopia public

dev · 25.4 KiBRawPermalink
1//! 七个工具的**执行**,与谁在调用它们无关。
2//!
3//! 从前这些是 `chat.rs` 里一个 `match` 的七条分支,每条 20–70 行,闭包捕获着
4//! 流式循环的局部变量。那样写在只有对话一个调用方时没问题——**而 MCP 是第二个**。
5//! 抽出来之后两边共用同一份实现,不会出现「对话里的 entity_facts 和 MCP 里的
6//! 不是同一个东西」。
7//!
8//! 工具定义(给模型看的 JSON schema)仍在 `chat.rs`:那是提示词的一部分,
9//! 随对话策略走;这里只管拿到参数之后干什么。
10
11use serde_json::json;
12use utopia_core::models::{ChunkView, DataSourceView, EntityFact, GraphChange};
13use uuid::Uuid;
14
15use crate::retrieval;
16use crate::state::AppState;
17
18const SEARCH_TOP_K: usize = 6;
19const TOOL_CHUNK_CHARS: usize = 800;
20/// 一次 changes 最多回多少条。刚灌完的库里 asserted 是成百上千条,全发出去
21/// 只会把上下文填满而不增加信息——有信息量的是 corrected/rejected,那类事件
22/// 本来就稀少。截断时 detail 写 "40+",模型据此知道该收窄窗口
23const CHANGES_LIMIT: i64 = 40;
24
25/// 一次工具调用看得见的世界。**只读**——工具改不了它。
26pub 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 /// 在说话的人。`remember` 把它记成「谁说的」,一路跟到待确认队列(0015)。
36 /// 对话里恒有值;MCP 也有——令牌以人的身份行事(0014)
37 pub actor: Option<Uuid>,
38}
39
40/// 工具执行过程中往外攒的东西。
41///
42/// **引用编号是有状态的**:`[3]` 里的 3 取决于这一轮之前已经引过几个,
43/// 所以不能让每个工具各算各的再合并——那样同一个 chunk 会拿到两个号。
44#[derive(Default)]
45pub struct ToolSink {
46 /// 去重键(chunk uuid,或 `charter:{slug}#{anchor}`),下标 +1 就是引用号
47 pub source_ids: Vec<String>,
48 /// 发给前端的引用清单,与 `source_ids` 同序
49 pub sources: Vec<serde_json::Value>,
50 /// 这一轮认下的实体,落进会话供下一轮回放
51 pub resolved: Vec<serde_json::Value>,
52}
53
54/// 一次工具调用的产出:给模型的文本 + 给界面的一步。
55pub type ToolResult = (String, serde_json::Value);
56
57/// 按名字派发。**未知工具不是错误**——模型偶尔会编一个名字出来,
58/// 告诉它没有这个工具,它下一轮就换一个,比中断整场对话好。
59pub async fn dispatch(
60 ctx: &ToolCtx<'_>,
61 sink: &mut ToolSink,
62 name: &str,
63 args: &serde_json::Value,
64) -> ToolResult {
65 match name {
66 "search_chunks" => search_chunks(ctx, sink, args).await,
67 "search_docs" => search_docs(ctx, sink, args).await,
68 "find_entities" => find_entities(ctx, sink, args).await,
69 "entity_facts" => entity_facts(ctx, args).await,
70 "changes" => changes(ctx, args).await,
71 "query_data" if !ctx.mounted_sources.is_empty() => query_data(ctx, args).await,
72 "remember" if ctx.can_write => remember(ctx, args).await,
73 other => (
74 format!("Unknown tool: {other}"),
75 json!({ "kind": "tool", "label": other, "detail": "unknown" }),
76 ),
77 }
78}
79
80/// 已经引过的给回原号,没引过的落一个新号。**同一个 chunk 在一轮对话里
81/// 只能有一个号**,否则模型引 `[2]` 而界面上有两个 `[2]`。
82fn cite(sink: &mut ToolSink, key: String, make: impl FnOnce(usize) -> serde_json::Value) -> usize {
83 match sink.source_ids.iter().position(|id| *id == key) {
84 Some(i) => i + 1,
85 None => {
86 sink.source_ids.push(key);
87 sink.sources.push(make(sink.source_ids.len()));
88 sink.source_ids.len()
89 }
90 }
91}
92
93pub async fn search_chunks(
94 ctx: &ToolCtx<'_>,
95 sink: &mut ToolSink,
96 args: &serde_json::Value,
97) -> ToolResult {
98 // 必填参数由 `chat::check_call` 在派发之前挡下,所以这里不再回落到
99 // 用户那句原话——回落产出的是一个看起来没问题的错误答案
100 let q = args["query"].as_str().unwrap_or_default().to_string();
101 let chunks = retrieval::hybrid(ctx.state, ctx.kb_id, ctx.workspace_id, &q, SEARCH_TOP_K)
102 .await
103 .unwrap_or_default();
104 let mut lines = Vec::new();
105 for c in &chunks {
106 let n = cite(sink, c.id.to_string(), |n| source_json(n, c));
107 lines.push(format!(
108 "[{n}] \"{}\" section {}:\n{}",
109 c.filename,
110 c.seq + 1,
111 truncate(&c.text, TOOL_CHUNK_CHARS)
112 ));
113 }
114 let text = if lines.is_empty() {
115 "No results.".to_string()
116 } else {
117 lines.join("\n\n")
118 };
119 (
120 text,
121 json!({ "kind": "search", "label": q, "detail": format!("{} sources", chunks.len()) }),
122 )
123}
124
125pub async fn search_docs(
126 ctx: &ToolCtx<'_>,
127 sink: &mut ToolSink,
128 args: &serde_json::Value,
129) -> ToolResult {
130 // 必填参数由 `chat::check_call` 在派发之前挡下,所以这里不再回落到
131 // 用户那句原话——回落产出的是一个看起来没问题的错误答案
132 let q = args["query"].as_str().unwrap_or_default().to_string();
133 let hits = ctx.state.docs.search(&q, 4).unwrap_or_default();
134 let mut lines = Vec::new();
135 for h in &hits {
136 let key = format!("charter:{}#{}", h.slug, h.anchor);
137 let n = cite(sink, key, |n| charter_source_json(n, h));
138 lines.push(format!(
139 "[{n}] Utopia Charter — {} › {}:\n{}",
140 h.title,
141 h.heading,
142 truncate(&h.body, 1600)
143 ));
144 }
145 let text = if lines.is_empty() {
146 "No matching manual sections.".to_string()
147 } else {
148 lines.join("\n\n")
149 };
150 (
151 text,
152 json!({ "kind": "docs", "label": q, "detail": format!("{} sections", hits.len()) }),
153 )
154}
155
156pub async fn find_entities(
157 ctx: &ToolCtx<'_>,
158 sink: &mut ToolSink,
159 args: &serde_json::Value,
160) -> ToolResult {
161 let name = args["name"].as_str().unwrap_or("").to_string();
162 let (hits, _) = utopia_store::graph::search_entities(&ctx.state.pool, ctx.kb_id, &name, 8, 0)
163 .await
164 .unwrap_or_default();
165 let text = if hits.is_empty() {
166 "No matching entities.".to_string()
167 } else {
168 hits.iter()
169 .map(|n| {
170 let dis = n
171 .disambiguator
172 .as_deref()
173 .map(|d| format!(" ({d})"))
174 .unwrap_or_default();
175 format!(
176 "{} | {}{} | {} | {} facts",
177 n.id,
178 n.name,
179 dis,
180 // 没判出类型的实体照样能被搜到、被引用(0009)
181 n.type_label.as_deref().unwrap_or("untyped"),
182 n.degree
183 )
184 })
185 .collect::<Vec<_>>()
186 .join("\n")
187 };
188 for n in &hits {
189 sink.resolved.push(json!({
190 "id": n.id.to_string(), "name": n.name, "type": n.type_label
191 }));
192 }
193 (
194 text,
195 json!({ "kind": "entity", "label": name, "detail": format!("{} matches", hits.len()) }),
196 )
197}
198
199pub async fn entity_facts(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult {
200 let id = args["entity_id"]
201 .as_str()
202 .and_then(|s| s.parse::<Uuid>().ok());
203 // as-of 过滤:T 时刻有效 = 起点不晚于 T(或未知)且终点晚于 T(或开放)
204 let at = args["at"]
205 .as_str()
206 .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
207 .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc());
208 let Some(id) = id else {
209 return (
210 "Invalid entity_id (expected the uuid returned by find_entities).".to_string(),
211 json!({ "kind": "facts", "label": "?", "detail": "invalid id" }),
212 );
213 };
214 match utopia_store::graph::entity_detail(&ctx.state.pool, ctx.kb_id, id).await {
215 Ok((node, mut facts)) => {
216 if let Some(t) = at {
217 facts.retain(|f| {
218 f.valid_from.is_none_or(|from| from <= t) && f.valid_to.is_none_or(|to| to > t)
219 });
220 }
221 let text = if facts.is_empty() {
222 match at {
223 Some(t) => format!(
224 "{}: no facts valid as of {}.",
225 node.name,
226 t.format("%Y-%m-%d")
227 ),
228 None => format!("{}: no recorded facts.", node.name),
229 }
230 } else {
231 facts.iter().map(fact_line).collect::<Vec<_>>().join("\n")
232 };
233 let detail = match at {
234 Some(t) => format!("{} facts as of {}", facts.len(), t.format("%Y-%m-%d")),
235 None => format!("{} facts", facts.len()),
236 };
237 (
238 text,
239 json!({ "kind": "facts", "label": node.name, "detail": detail }),
240 )
241 }
242 Err(_) => (
243 "Entity not found.".to_string(),
244 json!({ "kind": "facts", "label": "?", "detail": "not found" }),
245 ),
246 }
247}
248
249pub async fn changes(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult {
250 let day = |k: &str| {
251 args[k]
252 .as_str()
253 .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
254 };
255 let Some((since, until, window)) =
256 changes_window(day("since"), day("until"), chrono::Utc::now())
257 else {
258 return (
259 "Invalid or missing `since` (expected YYYY-MM-DD).".to_string(),
260 json!({ "kind": "changes", "label": "?", "detail": "invalid since" }),
261 );
262 };
263 let entity = args["entity_id"]
264 .as_str()
265 .and_then(|s| s.parse::<Uuid>().ok());
266 let kinds: Option<Vec<String>> = args["kinds"].as_array().map(|a| {
267 a.iter()
268 .filter_map(|v| v.as_str().map(str::to_string))
269 .collect()
270 });
271 let kinds = kinds.filter(|k: &Vec<String>| !k.is_empty());
272 let rows = utopia_store::graph::graph_changes(
273 &ctx.state.pool,
274 ctx.kb_id,
275 since,
276 until,
277 entity,
278 kinds.as_deref(),
279 CHANGES_LIMIT,
280 )
281 .await
282 .unwrap_or_default();
283 let text = if rows.is_empty() {
284 format!("No recorded changes in {window}.")
285 } else {
286 rows.iter().map(change_line).collect::<Vec<_>>().join("\n")
287 };
288 let detail = if rows.len() as i64 == CHANGES_LIMIT {
289 format!("{CHANGES_LIMIT}+ changes")
290 } else {
291 format!("{} changes", rows.len())
292 };
293 (
294 text,
295 json!({ "kind": "changes", "label": window, "detail": detail }),
296 )
297}
298
299pub async fn query_data(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult {
300 let ds_name = args["data_source"].as_str().map(str::trim).unwrap_or("");
301 let sql = args["sql"].as_str().map(str::trim).unwrap_or("");
302 let purpose = args["purpose"].as_str().map(str::trim).unwrap_or("");
303 // 安全边界:只允许本 KB 挂载的源(凭据不出服务端)
304 let found = ctx
305 .mounted_sources
306 .iter()
307 .find(|d| d.name.eq_ignore_ascii_case(ds_name));
308 let text = match found {
309 None => format!(
310 "Unknown data source '{ds_name}'. Mounted sources: {}",
311 ctx.mounted_sources
312 .iter()
313 .map(|d| d.name.as_str())
314 .collect::<Vec<_>>()
315 .join(", ")
316 ),
317 Some(ds) => match run_query(ctx.state, ds.id, sql).await {
318 Ok(out) => out,
319 // 错误透传:模型可据此修正 SQL 重试
320 Err(e) => format!("Query failed: {e}"),
321 },
322 };
323 let detail = if purpose.is_empty() {
324 sql.chars().take(60).collect::<String>()
325 } else {
326 purpose.to_string()
327 };
328 (
329 text,
330 json!({ "kind": "query", "label": ds_name, "detail": detail }),
331 )
332}
333
334pub async fn remember(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolResult {
335 let text = args["text"].as_str().map(str::trim).unwrap_or("");
336 let occurred_at = args["occurred_at"]
337 .as_str()
338 .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
339 .map(|d| d.and_hms_opt(12, 0, 0).unwrap().and_utc())
340 .unwrap_or_else(chrono::Utc::now);
341 if text.is_empty() {
342 return (
343 "remember requires non-empty text.".to_string(),
344 json!({ "kind": "tool", "label": "remember", "detail": "empty" }),
345 );
346 }
347 match utopia_store::memory::append_episode(&ctx.state.pool, ctx.kb_id, text, occurred_at).await
348 {
349 Ok((doc_id, chunk_id)) => {
350 // 摄入(embedding/索引/增量抽取)异步走队列,不阻塞对话。
351 // 抽出来的事实**先等人点头**(0015)——所以这里只能如实说「记下了这句话」,
352 // 说不出抽出了几条:抽取还没跑。卡片在任务完成时长到对话里
353 let _ = utopia_store::jobs::enqueue(
354 &ctx.state.pool,
355 "memory_ingest",
356 json!({ "document_id": doc_id, "proposed_by": ctx.actor }),
357 )
358 .await;
359 ctx.state.emit_document(ctx.kb_id, doc_id);
360 (
361 format!(
362 "Recorded the sentence (effective {}): {text}\n\
363 Facts extracted from it will be shown to the user for confirmation \
364 before entering the graph. Tell the user exactly that: the sentence is \
365 recorded, and the extracted facts await their confirmation. Do not claim \
366 any fact has been added to the knowledge graph.",
367 occurred_at.format("%Y-%m-%d")
368 ),
369 json!({
370 "kind": "tool", "label": "remember",
371 "detail": text.chars().take(60).collect::<String>(),
372 // 对话里那张确认卡按它取待确认项;回放时也据此重画
373 "chunk_id": chunk_id,
374 }),
375 )
376 }
377 Err(e) => (
378 format!("Failed to record: {e}"),
379 json!({ "kind": "tool", "label": "remember", "detail": "failed" }),
380 ),
381 }
382}
383
384// ---------------------------------------------------------------------------
385// 排版与执行的辅助。**对话降级路径也用它们**,所以是 pub(super) 而不是私有
386// ---------------------------------------------------------------------------
387
388pub(super) fn source_json(n: usize, c: &ChunkView) -> serde_json::Value {
389 json!({
390 "n": n,
391 "chunk_id": c.id,
392 "document_id": c.document_id,
393 "filename": c.filename,
394 "excerpt": truncate(&c.text, 160),
395 })
396}
397
398/// Charter 引用:前端渲染成手册行,链到 /docs/{slug}#{anchor}。
399pub(super) fn charter_source_json(n: usize, h: &utopia_search::DocsSection) -> serde_json::Value {
400 json!({
401 "n": n,
402 "kind": "charter",
403 "slug": h.slug,
404 "anchor": h.anchor,
405 "heading": h.heading,
406 "filename": h.title,
407 "excerpt": truncate(&h.body, 160),
408 })
409}
410
411/// 问数执行:安全闸(解析白名单)→ 引擎执行(只读会话 + 强制 LIMIT + 超时)→ JSON 行。
412async fn run_query(state: &AppState, ds_id: Uuid, sql: &str) -> anyhow::Result<String> {
413 let (engine, conn) = utopia_store::datasources::engine_and_conn(&state.pool, ds_id).await?;
414 // 闸门按引擎选方言:Databricks 的反引号、Snowflake 的 :: 转型都得先过得了解析
415 let guarded = crate::query_engine::guard_sql_for(&engine, sql)?;
416 let result = crate::query_engine::engine_for(&engine, &conn)?
417 .execute(&guarded)
418 .await?;
419 let mut out = String::new();
420 if result.rows.is_empty() {
421 out.push_str("(no rows)");
422 } else {
423 out.push_str(&result.rows.join("\n"));
424 out.push_str(&format!("\n({} rows", result.rows.len()));
425 if result.truncated {
426 out.push_str(&format!(
427 ", truncated at {} — aggregate in SQL for totals",
428 crate::query_engine::ROW_CAP
429 ));
430 }
431 out.push(')');
432 }
433 Ok(out)
434}
435
436/// 事实行:"works at → 星云科技 (2023-08 → now) [90%]",in 方向用 ←。
437fn fact_line(f: &EntityFact) -> String {
438 let other = f.other_name.as_deref().unwrap_or("?");
439 // 本体没认下、原文说法也没留下时用 "?"——与 other 同一个约定。
440 // 不编一个"相关"出来:那正是删掉 related_to 要消灭的东西
441 let pred = f.predicate_label.as_deref().unwrap_or("?");
442 let core = if f.direction == "out" {
443 format!("{pred} → {other}")
444 } else {
445 format!("{pred} ← {other}")
446 };
447 let range = match (&f.valid_from, &f.valid_to) {
448 (Some(from), Some(to)) => {
449 format!(" ({} → {})", from.format("%Y-%m-%d"), to.format("%Y-%m-%d"))
450 }
451 (Some(from), None) => format!(" ({} → now)", from.format("%Y-%m-%d")),
452 (None, Some(to)) => format!(" (→ {})", to.format("%Y-%m-%d")),
453 (None, None) => String::new(),
454 };
455 format!("{core}{range} [{}%]", (f.confidence * 100.0).round() as i32)
456}
457
458/// changes 的时间窗:把两个可选日期变成 (SQL 用的半开区间, 展示用的窗口串)。
459///
460/// **抽成纯函数是因为这里出过一次错。** `until` 进 SQL 前要加一天(说"到 3 月 31 日
461/// 为止"的人要的是含 31 日,而 SQL 那头是 `< $3`),第一版把加过一天的值也印进了
462/// 展示串,模型于是照着答"截至 8 月 30 日"——问的是 29 日。两个值必须一起算、
463/// 一起被测住;分在两处写,迟早再次分叉。
464///
465/// `now` 从外面传进来而不是在里面取,纯粹是为了这个函数测得动。
466fn changes_window(
467 since: Option<chrono::NaiveDate>,
468 until: Option<chrono::NaiveDate>,
469 now: chrono::DateTime<chrono::Utc>,
470) -> Option<(
471 chrono::DateTime<chrono::Utc>,
472 chrono::DateTime<chrono::Utc>,
473 String,
474)> {
475 let from = since?;
476 let start = from.and_hms_opt(0, 0, 0).unwrap().and_utc();
477 let end = until
478 .and_then(|d| d.succ_opt())
479 .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc())
480 .unwrap_or(now);
481 // 展示用的是**问的那天**,没问就写 now——绝不是 end
482 let label = format!(
483 "{} → {}",
484 from.format("%Y-%m-%d"),
485 match until {
486 Some(d) => d.format("%Y-%m-%d").to_string(),
487 None => "now".to_string(),
488 }
489 );
490 Some((start, end, label))
491}
492
493/// 认知轴上的一行。
494///
495/// 排版把两根轴**分开写**:`at` 前面标事件类型,世界轴的区间夹在括号里跟在断言后。
496/// 若把它们排成一串日期,模型会把"2026 年记下的"读成"2026 年发生的"——那正是
497/// 这个工具要防的误读。
498fn change_line(c: &GraphChange) -> String {
499 let object = match (&c.object_name, &c.object_value) {
500 (Some(name), _) => name.clone(),
501 (None, Some(v)) => match v {
502 serde_json::Value::String(s) => s.clone(),
503 other => other.to_string(),
504 },
505 (None, None) => "?".to_string(),
506 };
507 let range = match (&c.valid_from, &c.valid_to) {
508 (Some(from), Some(to)) => {
509 format!(
510 " [valid {} → {}]",
511 from.format("%Y-%m-%d"),
512 to.format("%Y-%m-%d")
513 )
514 }
515 (Some(from), None) => format!(" [valid {} → now]", from.format("%Y-%m-%d")),
516 (None, Some(to)) => format!(" [valid → {}]", to.format("%Y-%m-%d")),
517 (None, None) => String::new(),
518 };
519 // 文件名不带 [n]:引证编号是 chunk 的,这里只有 document,发一个编号出去
520 // 会在界面上落成一条指不到东西的引证
521 let src = match (&c.filename, &c.quote) {
522 (Some(f), Some(q)) => format!(" — from \"{f}\": \"{}\"", truncate(q, 160)),
523 (Some(f), None) => format!(" — from \"{f}\""),
524 _ => String::new(),
525 };
526 format!(
527 "{} {}: {} {} {}{}{}",
528 c.at.format("%Y-%m-%d"),
529 c.kind,
530 c.subject_name,
531 c.predicate_label.as_deref().unwrap_or("?"),
532 object,
533 range,
534 src
535 )
536}
537
538pub(super) fn truncate(text: &str, max_chars: usize) -> String {
539 let t = text.trim();
540 if t.chars().count() <= max_chars {
541 t.to_string()
542 } else {
543 let cut: String = t.chars().take(max_chars).collect();
544 format!("{cut}…")
545 }
546}
547
548#[cfg(test)]
549mod tests {
550 use super::*;
551
552 fn d(s: &str) -> chrono::NaiveDate {
553 chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()
554 }
555 fn t(s: &str) -> chrono::DateTime<chrono::Utc> {
556 s.parse().unwrap()
557 }
558
559 // --- changes_window -----------------------------------------------------
560
561 /// 说"到 3 月 31 日为止"的人要的是**含 31 日**。SQL 那头是 `< end`,
562 /// 所以 end 必须落在 4 月 1 日零点——差这一天,问 31 日会安静地丢掉 31 日
563 #[test]
564 fn until_names_a_day_the_window_must_contain() {
565 let (start, end, label) = changes_window(
566 Some(d("2026-03-01")),
567 Some(d("2026-03-31")),
568 t("2026-06-01T00:00:00Z"),
569 )
570 .unwrap();
571 assert_eq!(start, t("2026-03-01T00:00:00Z"));
572 assert_eq!(end, t("2026-04-01T00:00:00Z"));
573 // 但**展示串里绝不能出现 04-01**:那是半开区间的内部细节,
574 // 印出去等于告诉模型窗口比它要的宽一天,模型会照着答(这条真的发生过)
575 assert_eq!(label, "2026-03-01 → 2026-03-31");
576 }
577
578 /// 没给 until 时,展示串写 now。写成 end 的格式化结果就等于把服务器时钟
579 /// 当成用户问的边界——看着像个精确答案,其实只是"现在几点"
580 #[test]
581 fn an_open_window_says_now_rather_than_the_clock() {
582 let now = t("2026-06-01T13:45:00Z");
583 let (_, end, label) = changes_window(Some(d("2026-03-01")), None, now).unwrap();
584 assert_eq!(end, now);
585 assert_eq!(label, "2026-03-01 → now");
586 }
587
588 #[test]
589 fn without_since_there_is_no_window() {
590 assert!(changes_window(None, Some(d("2026-03-31")), t("2026-06-01T00:00:00Z")).is_none());
591 }
592
593 // --- change_line --------------------------------------------------------
594
595 fn change(kind: &str) -> GraphChange {
596 GraphChange {
597 fact_id: Uuid::nil(),
598 at: t("2026-08-28T10:00:00Z"),
599 kind: kind.to_string(),
600 subject_id: Uuid::nil(),
601 subject_name: "Acme".to_string(),
602 predicate_label: Some("founded in".to_string()),
603 object_name: None,
604 object_value: None,
605 valid_from: None,
606 valid_to: None,
607 // 两端都没日期就没有精度——夹具也得守这条不变量(见 `facts.valid_from_precision`)
608 // 两端都没日期,所以两端都没有精度(见 facts 的两个精度列)
609 valid_from_precision: None,
610 valid_to_precision: None,
611 confidence: 0.9,
612 document_id: None,
613 filename: None,
614 quote: None,
615 }
616 }
617
618 /// 字面值要读成它自己。走 `Value::to_string()` 会把字符串连引号一起印出来,
619 /// 模型于是把 `"1993"` 当成答案的一部分
620 #[test]
621 fn a_literal_value_reads_as_itself_not_as_json() {
622 let mut c = change("asserted");
623 c.object_value = Some(serde_json::json!("1993"));
624 assert!(
625 change_line(&c).ends_with("Acme founded in 1993"),
626 "{}",
627 change_line(&c)
628 );
629 }
630
631 /// 两根轴必须在同一行里**看得出是两样东西**:记录时刻在前、无标签,
632 /// 世界轴区间在后、带 `valid` 字样。排成一串裸日期,模型会把
633 /// "2026 年记下的"读成"2026 年发生的"——这个工具存在的理由就是防这个
634 #[test]
635 fn the_record_time_and_the_valid_range_do_not_read_as_one_date_run() {
636 let mut c = change("corrected");
637 c.object_name = Some("Berlin".to_string());
638 c.predicate_label = Some("headquartered in".to_string());
639 c.valid_from = Some(t("2019-01-01T00:00:00Z"));
640 let line = change_line(&c);
641 assert!(line.starts_with("2026-08-28 corrected: "), "{line}");
642 assert!(line.contains("[valid 2019-01-01 → now]"), "{line}");
643 }
644
645 /// 没有证据就什么都别说。凭空补一句 from "…" 会让一条无出处的断言
646 /// 看起来有出处
647 #[test]
648 fn a_fact_with_no_evidence_claims_no_document() {
649 let mut c = change("rejected");
650 c.object_name = Some("Berlin".to_string());
651 assert!(!change_line(&c).contains("from"), "{}", change_line(&c));
652 }
653
654 #[test]
655 fn evidence_carries_the_filename_and_the_quote() {
656 let mut c = change("corrected");
657 c.object_name = Some("Berlin".to_string());
658 c.filename = Some("annual-report.pdf".to_string());
659 c.quote = Some("moved its head office to Berlin".to_string());
660 let line = change_line(&c);
661 assert!(line.contains("from \"annual-report.pdf\""), "{line}");
662 assert!(
663 line.contains("\"moved its head office to Berlin\""),
664 "{line}"
665 );
666 }
667}