Elffuss BraidHub

kikocis/utopia public

de93f0eb4620 · 24.3 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}
36
37/// 工具执行过程中往外攒的东西。
38///
39/// **引用编号是有状态的**:`[3]` 里的 3 取决于这一轮之前已经引过几个,
40/// 所以不能让每个工具各算各的再合并——那样同一个 chunk 会拿到两个号。
41#[derive(Default)]
42pub 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/// 一次工具调用的产出:给模型的文本 + 给界面的一步。
52pub type ToolResult = (String, serde_json::Value);
53
54/// 按名字派发。**未知工具不是错误**——模型偶尔会编一个名字出来,
55/// 告诉它没有这个工具,它下一轮就换一个,比中断整场对话好。
56pub 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]`。
79fn 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
90pub 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
122pub 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
153pub 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
196pub 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
246pub 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
296pub 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
331pub 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
377pub(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}。
388pub(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 行。
401async 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 方向用 ←。
425fn 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` 从外面传进来而不是在里面取,纯粹是为了这个函数测得动。
454fn 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/// 这个工具要防的误读。
486fn 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
526pub(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)]
537mod 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}