Skip to content

World's first open-source enterprise world model.

Graph fact lines say when an end was derived by the timeline or an interval corrected by a person (#976)

Maya Kid0815a4153533
diff --git a/crates/utopia-cli/src/main.rs b/crates/utopia-cli/src/main.rs
index 3e341fc4..47e8fb19 100644
--- a/crates/utopia-cli/src/main.rs
+++ b/crates/utopia-cli/src/main.rs
@@ -82,7 +82,7 @@ struct ManifestDataDir {
/// not a side effect of a code change.
// 是迁移文件的**个数**,不是最大的编号(守卫 `schema_version_policy_compares_against_current`
// 按个数比):编号有空缺时两者不同——0071 由一个开放 PR 占着,0072 先落,个数是 71
-const CURRENT_SCHEMA_VERSION: u32 = 87;
+const CURRENT_SCHEMA_VERSION: u32 = 88;
fn main() -> anyhow::Result<()> {
dotenvy::dotenv().ok();
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index ed0f7272..ce6d2527 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -839,6 +839,12 @@ pub struct EntityFact {
pub stale: bool,
/// 修正行(supersedes 链上):区间闭合来自引擎对账/人工裁决而非抽取原文
pub corrected: bool,
+ /// 终点是时间线推出来的(`facts.end_derived`):后一条事实开始时引擎把它关上,原文没说
+ /// 这一天(#970)
+ pub end_derived: bool,
+ /// 区间是人改过的:supersedes 链上有一条 `fact.time_corrected` 审计(#970)。与
+ /// `corrected` 不同,那一位是任何一次改写:自动接续、审阅裁决、人手改
+ pub time_corrected: bool,
/// 证据集合里最新的文档时间——开放事实的"最后确认时间"(时效性透明化)
pub last_evidence_time: Option<DateTime<Utc>>,
/// 有争议(0017 §3):`{ kind, ref_id, derived? }`——哪一种(违规的 kind,或
diff --git a/crates/utopia-server/src/api/chat.rs b/crates/utopia-server/src/api/chat.rs
index 17a5d4b7..aeaf6e5f 100644
--- a/crates/utopia-server/src/api/chat.rs
+++ b/crates/utopia-server/src/api/chat.rs
@@ -630,6 +630,9 @@ const SYSTEM_PROMPT: &str = "You are the assistant of Utopia, a temporal knowled
results carry them, and so does each fact line of entity_facts, neighbors, timeline and \
paths_between: its [n] opens the passage that fact was read from. A fact line without \
a number (a derived fact, or one whose documents are gone) is stated without a bracket. \
+ An end marked `end derived` was set by the timeline when a later fact began, and a range \
+ marked `corrected` was changed by a person: neither is in the passage the line's [n] \
+ opens, so never attribute it to that passage. \
If the evidence is insufficient, say so explicitly — never fabricate.\n\
5. Always respond in the same language as the user's question.";
diff --git a/crates/utopia-server/src/api/chat_graph_citation_tests.rs b/crates/utopia-server/src/api/chat_graph_citation_tests.rs
index b1e7c200..00a09c66 100644
--- a/crates/utopia-server/src/api/chat_graph_citation_tests.rs
+++ b/crates/utopia-server/src/api/chat_graph_citation_tests.rs
@@ -14,6 +14,8 @@
//! 几句;块被新版本取代后换成仍有效的那一块,`as_of` 回到取代之前又是原来那块
//! - 检索和图谱工具在一轮里共用一个号:图谱引到检索登过的块,号不变、补上那句话;只补了
//! 引文、条数没变,来源帧也再发一次
+//! - 原句里没有的日期在行上说出来(#970):时间线推出来的终点写 `end derived`,人改过的
+//! 区间写 `corrected`,号照旧;对话与 MCP 一样,规则 4 说不许把它们归到原句
//!
//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。
use super::*;
@@ -619,3 +621,157 @@ async fn a_quote_added_to_a_search_hit_is_published() -> anyhow::Result<()> {
f.cleanup().await?;
run
}
+
+/// #970 的两处:周七 2025-09-01 接手,时间线把李四那一段关在那天;人把张三的起点从章程的
+/// 2023-01-10 改成 2023-02-01。两行的号仍打开它们读出来的原句,而原句里没有这两个日期,
+/// 所以行上说出日期从哪来
+#[tokio::test]
+async fn a_fact_line_says_when_a_date_is_not_the_passages() -> anyhow::Result<()> {
+ let Some(f) = fixture(Scripted::new(vec![])).await? else {
+ return Ok(());
+ };
+ let run = async {
+ let s = seed(&f.pool, f.kb).await?;
+ let (leads, person, aurora): (Uuid, Uuid, Uuid) = sqlx::query_as(
+ "SELECT r.id, t.id, e.id FROM relation_types r, entity_types t, entities e
+ WHERE r.kb_id = $1 AND r.key = 'leads' AND t.kb_id = $1 AND t.key = 'person'
+ AND e.kb_id = $1 AND e.canonical_name = 'Project Aurora'",
+ )
+ .bind(f.kb)
+ .fetch_one(&f.pool)
+ .await?;
+ let row_of = |name: &'static str| {
+ let pool = f.pool.clone();
+ let kb = f.kb;
+ async move {
+ sqlx::query_scalar::<_, Uuid>(
+ "SELECT f.id FROM facts f JOIN entities e ON e.id = f.subject_id
+ WHERE f.kb_id = $1 AND e.canonical_name = $2 AND f.predicate_id = $3
+ AND f.invalidated_at IS NULL",
+ )
+ .bind(kb)
+ .bind(name)
+ .bind(leads)
+ .fetch_one(&pool)
+ .await
+ }
+ };
+ let (zhang, li) = (row_of("Zhang San").await?, row_of("Li Si").await?);
+ let (zhou, d_update, update, zhou_fact) =
+ (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ // 插进去的只有本地生成的 UUID 和写死的日期
+ sqlx::raw_sql(&format!(
+ r#"
+ INSERT INTO entities(id,kb_id,type_id,canonical_name,created_at) VALUES
+ ('{zhou}','{kb}','{person}','Zhou Qi','2026-01-01');
+ INSERT INTO documents(id,kb_id,filename,sha256,created_at,doc_time) VALUES
+ ('{d_update}','{kb}','leadership-update.md',repeat('5',64),'2026-01-01','2025-09-01');
+ INSERT INTO chunks(id,kb_id,document_id,seq,text,created_at) VALUES
+ ('{update}','{kb}','{d_update}',0,'Zhou Qi leads Project Aurora from 2025-09-01.','2026-01-01');
+ INSERT INTO facts(id,kb_id,subject_id,predicate_id,object_id,valid_from,valid_from_precision,
+ recorded_at,confidence) VALUES
+ ('{zhou_fact}','{kb}','{zhou}','{leads}','{aurora}','2025-09-01','day','2026-01-01',0.9);
+ INSERT INTO fact_evidence(fact_id,chunk_id,document_id,doc_version,quote) VALUES
+ ('{zhou_fact}','{update}','{d_update}',1,'Zhou Qi leads Project Aurora from 2025-09-01.');
+ UPDATE relation_types SET inverse_functional = TRUE WHERE id = '{leads}';
+ "#,
+ kb = f.kb
+ ))
+ .execute(&f.pool)
+ .await?;
+ // 一个项目同时只有一个 lead:对账把李四那一段关在周七接手那天
+ utopia_store::temporal::reconcile_moved_facts(&f.pool, f.kb, &[li, zhou_fact]).await?;
+ // 人改张三的起点,终点照旧;审计记在被改的那一行上(PATCH /facts/{id} 同一条路)
+ let day = |s: &str| s.parse::<chrono::DateTime<chrono::Utc>>().unwrap();
+ utopia_store::temporal::correct_interval(
+ &f.pool,
+ zhang,
+ utopia_store::graph::Validity {
+ from: Some(day("2023-02-01T00:00:00Z")),
+ from_precision: Some("day"),
+ to: Some(day("2024-07-05T00:00:00Z")),
+ to_precision: Some("day"),
+ attested_at: None,
+ from_grade: None,
+ },
+ )
+ .await?
+ .expect("the row was live");
+ utopia_store::audit::record(
+ &f.pool,
+ Some(f.kb),
+ f.user.id,
+ "fact.time_corrected",
+ "fact",
+ Some(zhang),
+ json!({ "note": "The charter date was the approval date" }),
+ )
+ .await?;
+
+ let chat = ctx(&f, None);
+ let mut sink = ToolSink::default();
+ for tool in ["entity_facts", "neighbors", "timeline"] {
+ let text = dispatch(&chat, &mut sink, tool, &json!({"entity": "Project Aurora"}))
+ .await
+ .text;
+ let zhang_line = line(&text, "Zhang San");
+ assert!(
+ zhang_line.contains("2023-02-01 → 2024-07-05, corrected)"),
+ "{tool}: {text}"
+ );
+ let li_line = line(&text, "Li Si");
+ assert!(
+ li_line.contains("2024-07-05 → 2025-09-01, end derived)"),
+ "{tool}: {text}"
+ );
+ assert!(
+ line(&text, "Zhou Qi").contains("2025-09-01 → now)"),
+ "{tool}: {text}"
+ );
+ // 号照旧:打开的仍是那条事实读出来的原句
+ let (z, l) = (marks(zhang_line), marks(li_line));
+ assert_eq!((z.len(), l.len()), (1, 1), "{tool}: {text}");
+ assert_eq!(chunk_of(&sink, z[0]), s.charter, "{tool}");
+ assert_eq!(chunk_of(&sink, l[0]), s.handover, "{tool}");
+ }
+ let path = dispatch(
+ &chat,
+ &mut sink,
+ "paths_between",
+ &json!({"from": "Wang Wu", "to": "Li Si"}),
+ )
+ .await
+ .text;
+ assert!(
+ path.contains("2024-07-05 → 2025-09-01, end derived)"),
+ "{path}"
+ );
+
+ // MCP 的文字带着同样的标记:它们是这一行的事实,不是引用
+ let mcp = ctx(&f, Some(Uuid::now_v7()));
+ let plain = dispatch(
+ &mcp,
+ &mut ToolSink::default(),
+ "entity_facts",
+ &json!({"entity": "Project Aurora"}),
+ )
+ .await
+ .text;
+ assert!(
+ plain.contains(", corrected)") && plain.contains(", end derived)"),
+ "{plain}"
+ );
+ assert!(marks(&plain).is_empty(), "{plain}");
+
+ // 规则 4 说这两种日期不在原句里
+ assert!(
+ SYSTEM_PROMPT.contains("An end marked `end derived`")
+ && SYSTEM_PROMPT.contains("a range marked `corrected`"),
+ "{SYSTEM_PROMPT}"
+ );
+ anyhow::Ok(())
+ }
+ .await;
+ f.cleanup().await?;
+ run
+}
diff --git a/crates/utopia-server/src/api/tools.rs b/crates/utopia-server/src/api/tools.rs
index c3f25293..10b741b3 100644
--- a/crates/utopia-server/src/api/tools.rs
+++ b/crates/utopia-server/src/api/tools.rs
@@ -1084,6 +1084,8 @@ pub(super) fn fact_line(f: &EntityFact) -> String {
to_precision: f.valid_to_precision.as_deref(),
holds_from: f.holds_from,
holds_to: f.holds_to,
+ end_derived: f.end_derived,
+ corrected: f.time_corrected,
});
let range = if range.is_empty() {
range
@@ -1249,6 +1251,9 @@ fn change_line(c: &GraphChange) -> String {
to_precision: c.valid_to_precision.as_deref(),
holds_from: None,
holds_to: None,
+ // 记录轴上的一次变更,不是事实行:它自己就说了改的是什么
+ end_derived: false,
+ corrected: false,
});
let range = if range.is_empty() {
range
@@ -1481,6 +1486,8 @@ mod tests {
evidence_count: 1,
stale: false,
corrected: false,
+ end_derived: false,
+ time_corrected: false,
last_evidence_time: None,
contested: None,
}
diff --git a/crates/utopia-server/src/api/tools_graph.rs b/crates/utopia-server/src/api/tools_graph.rs
index 0119d17a..2829e521 100644
--- a/crates/utopia-server/src/api/tools_graph.rs
+++ b/crates/utopia-server/src/api/tools_graph.rs
@@ -381,6 +381,8 @@ fn range_text(f: &EntityFact) -> String {
to_precision: f.valid_to_precision.as_deref(),
holds_from: f.holds_from,
holds_to: f.holds_to,
+ end_derived: f.end_derived,
+ corrected: f.time_corrected,
});
if range.is_empty() {
range
@@ -1133,6 +1135,8 @@ pub(super) fn edge_text(prev: Uuid, e: &PathEdge) -> String {
to_precision: e.valid_to_precision.as_deref(),
holds_from: e.holds_from,
holds_to: e.holds_to,
+ end_derived: e.end_derived,
+ corrected: e.time_corrected,
});
let range = if range.is_empty() {
range
@@ -1460,6 +1464,8 @@ mod tests {
evidence_count: 1,
stale: false,
corrected: false,
+ end_derived: false,
+ time_corrected: false,
last_evidence_time: None,
contested: None,
}
@@ -1587,6 +1593,8 @@ mod tests {
holds_from: Some("2021-01-01T00:00:00Z".parse().unwrap()),
holds_to: None,
confidence: 0.9,
+ end_derived: false,
+ time_corrected: false,
};
let p = Path {
nodes: vec![a, x, b],
diff --git a/crates/utopia-server/src/time_text.rs b/crates/utopia-server/src/time_text.rs
index 881e74ce..d9d1cdfd 100644
--- a/crates/utopia-server/src/time_text.rs
+++ b/crates/utopia-server/src/time_text.rs
@@ -31,7 +31,9 @@ pub fn world(t: DateTime<Utc>, precision: Option<&str>) -> String {
}
}
-/// 一条事实的两端:原文说的(`valid_*` 与精度)和读出来的(`holds_*`,0022)。
+/// 一条事实的两端:原文说的(`valid_*` 与精度)和读出来的(`holds_*`,0022),以及日期
+/// 从哪来(#970):终点是时间线推出来的、区间是人改过的,这两样都不在那一行 `[n]` 打开的
+/// 原句里。
#[derive(Debug, Clone, Copy, Default)]
pub struct Span<'a> {
pub valid_from: Option<DateTime<Utc>>,
@@ -40,6 +42,10 @@ pub struct Span<'a> {
pub to_precision: Option<&'a str>,
pub holds_from: Option<DateTime<Utc>>,
pub holds_to: Option<DateTime<Utc>>,
+ /// 终点是后一条事实开始时时间线关上的(`facts.end_derived`)
+ pub end_derived: bool,
+ /// 区间是人改过的(supersedes 链上有 `fact.time_corrected`)
+ pub corrected: bool,
}
/// `from → to`,给模型看。
@@ -48,6 +54,10 @@ pub struct Span<'a> {
/// 只是从那份证据起有据可查。终点:原文给了按精度写;结束了不知哪天写
/// `ended by <锚点>`(没有锚点时写 `ended, date unknown`);否则 `now`。
/// 两端都无可写时返回空串,调用方据此决定不带括号。
+///
+/// 日期不是原文说的就跟在后面说出来(#970):人改过的区间写 `corrected`,时间线推出来的
+/// 终点写 `end derived`(只在有终点时)。这是这一行的事实,不是引用:`[n]` 仍是那条事实
+/// 读出来的原句,而原句里没有这两种日期
pub fn span(s: Span<'_>) -> String {
let from = match (s.valid_from, s.holds_from) {
(Some(t), _) => Some(world(t, s.from_precision)),
@@ -66,11 +76,21 @@ pub fn span(s: Span<'_>) -> String {
(None, true, None) => Some("ended, date unknown".to_string()),
(None, false, _) => None,
};
- match (from, to) {
+ let derived = s.end_derived && to.is_some();
+ let range = match (from, to) {
(None, None) => String::new(),
(Some(f), None) => format!("{f} → now"),
(None, Some(t)) => format!("→ {t}"),
(Some(f), Some(t)) => format!("{f} → {t}"),
+ };
+ let marks: Vec<&str> = [(s.corrected, "corrected"), (derived, "end derived")]
+ .into_iter()
+ .filter_map(|(on, mark)| on.then_some(mark))
+ .collect();
+ match (range.is_empty(), marks.is_empty()) {
+ (_, true) => range,
+ (true, false) => marks.join(", "),
+ (false, false) => format!("{range}, {}", marks.join(", ")),
}
}
@@ -128,6 +148,7 @@ mod tests {
to_precision: Some("month"),
holds_from: day("2023-01-01T00:00:00Z"),
holds_to: day("2024-07-01T00:00:00Z"),
+ ..Span::default()
}),
"2023 → 2024-07"
);
@@ -148,6 +169,7 @@ mod tests {
to_precision: Some("unknown"),
holds_from: day("2023-06-01T00:00:00Z"),
holds_to: day("2025-10-15T00:00:00Z"),
+ ..Span::default()
}),
"2023-06-01 → ended, date unknown"
);
@@ -161,4 +183,67 @@ mod tests {
);
assert_eq!(span(Span::default()), "");
}
+
+ /// 日期不是原文说的,就在区间后面说出来(#970):时间线关上的终点、人改过的区间。
+ /// 没有终点就没有「推出来的终点」;区间为空却改过,只说改过
+ #[test]
+ fn a_span_says_when_a_date_is_not_the_passages() {
+ let day = |s: &str| Some(t(s));
+ let closed = Span {
+ valid_from: day("2024-07-05T00:00:00Z"),
+ from_precision: Some("day"),
+ valid_to: day("2025-09-01T00:00:00Z"),
+ to_precision: Some("day"),
+ ..Span::default()
+ };
+ assert_eq!(
+ span(Span {
+ end_derived: true,
+ ..closed
+ }),
+ "2024-07-05 → 2025-09-01, end derived"
+ );
+ assert_eq!(
+ span(Span {
+ corrected: true,
+ ..closed
+ }),
+ "2024-07-05 → 2025-09-01, corrected"
+ );
+ assert_eq!(
+ span(Span {
+ corrected: true,
+ end_derived: true,
+ ..closed
+ }),
+ "2024-07-05 → 2025-09-01, corrected, end derived"
+ );
+ // 时间线关在一个没说起点的后任上:结束了不知哪天,也是推出来的
+ assert_eq!(
+ span(Span {
+ valid_to: None,
+ to_precision: Some("unknown"),
+ end_derived: true,
+ ..closed
+ }),
+ "2024-07-05 → ended, date unknown, end derived"
+ );
+ // 开着的行没有终点可推
+ assert_eq!(
+ span(Span {
+ valid_to: None,
+ to_precision: None,
+ end_derived: true,
+ ..closed
+ }),
+ "2024-07-05 → now"
+ );
+ assert_eq!(
+ span(Span {
+ corrected: true,
+ ..Span::default()
+ }),
+ "corrected"
+ );
+ }
}
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index 4d993d43..90510798 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -1532,6 +1532,26 @@ pub async fn entity_node(
.await?)
}
+/// 本库被人改过区间的行(`fact.time_corrected` 审计记在被改的那一行上,#970)。查询开头
+/// 取一次,每一行只顺着自己的 supersedes 链对它。取的这一次走部分索引
+/// `audit_events_time_corrected_idx`(迁移 0097):只收这一种动作,不读这个库别的审计。`$1` 是库
+pub(crate) const TIME_CORRECTED_TARGETS: &str = "time_corrected_targets AS MATERIALIZED (
+ SELECT DISTINCT target_id FROM audit_events
+ WHERE kb_id = $1 AND action = 'fact.time_corrected' AND target_id IS NOT NULL)";
+
+/// 这一行的区间是不是人改过的:它的 supersedes 链上有一行在 [`TIME_CORRECTED_TARGETS`] 里。
+/// 改完之后时间线再关它、合并再搬它,都是在链上往下接,往上仍找得到那一次人改
+pub(crate) fn time_corrected_sql(alias: &str) -> String {
+ format!(
+ "EXISTS (WITH RECURSIVE chain(id) AS (
+ SELECT {alias}.supersedes WHERE {alias}.supersedes IS NOT NULL
+ UNION
+ SELECT p.supersedes FROM facts p JOIN chain ON p.id = chain.id
+ WHERE p.supersedes IS NOT NULL)
+ SELECT 1 FROM chain JOIN time_corrected_targets t ON t.target_id = chain.id)"
+ )
+}
+
/// 实体详情:节点信息 + 事实时间线。
pub async fn entity_detail(
pool: &PgPool,
@@ -1545,7 +1565,8 @@ pub async fn entity_detail(
.ok_or(AppError::NotFound)?;
let mut facts: Vec<EntityFact> = sqlx::query_as(&format!(
- "SELECT f.id, {said_as} AS said_as, f.recorded_at, f.invalidated_at, f.supersedes,
+ "WITH {targets}
+ SELECT f.id, {said_as} AS said_as, f.recorded_at, f.invalidated_at, f.supersedes,
ARRAY(SELECT DISTINCT fe.document_id FROM fact_evidence fe
WHERE fe.fact_id = f.id AND fe.document_id IS NOT NULL
ORDER BY fe.document_id) AS document_ids,
@@ -1564,6 +1585,7 @@ pub async fn entity_detail(
WHERE fe.fact_id = f.id AND {chunk_live})
) AS stale,
(f.supersedes IS NOT NULL) AS corrected,
+ f.end_derived, {time_corrected} AS time_corrected,
(SELECT MAX(COALESCE(d.doc_time, d.created_at))
FROM fact_evidence fe JOIN documents d ON d.id = fe.document_id
WHERE fe.fact_id = f.id) AS last_evidence_time,
@@ -1595,6 +1617,8 @@ pub async fn entity_detail(
AND ({subject} = $2 OR {object} = $2)
AND {not_name}
ORDER BY f.valid_from NULLS LAST, f.recorded_at",
+ targets = TIME_CORRECTED_TARGETS,
+ time_corrected = time_corrected_sql("f"),
not_name = crate::names::not_a_name("f"),
said_as = said_as("f"),
represented = represented_by_typed("f"),
diff --git a/crates/utopia-store/src/paths.rs b/crates/utopia-store/src/paths.rs
index e69baacb..b44d3c55 100644
--- a/crates/utopia-store/src/paths.rs
+++ b/crates/utopia-store/src/paths.rs
@@ -71,6 +71,9 @@ pub struct PathEdge {
pub holds_from: Option<DateTime<Utc>>,
pub holds_to: Option<DateTime<Utc>>,
pub confidence: f32,
+ /// 终点是时间线推出来的;区间是人改过的(#970,同 `EntityFact`)
+ pub end_derived: bool,
+ pub time_corrected: bool,
}
#[derive(Debug, Clone)]
@@ -385,12 +388,14 @@ async fn details(
let subject = record_axis::owner_at("f", "subject_id", as_of.map(|_| 3), false);
let object = record_axis::owner_at("f", "object_id", as_of.map(|_| 3), true);
let rows: Vec<PathEdge> = sqlx::query_as(&format!(
- "SELECT f.id AS fact_id,
+ "WITH {targets}
+ SELECT f.id AS fact_id,
{subject} AS subject_id, s.canonical_name AS subject_name,
{object} AS object_id, o.canonical_name AS object_name,
COALESCE(r.label, fact_surface_predicate(f.id)) AS predicate,
f.valid_from, f.valid_from_precision, f.valid_to, f.valid_to_precision,
- {holds_from} AS holds_from, {holds_to} AS holds_to, f.confidence
+ {holds_from} AS holds_from, {holds_to} AS holds_to, f.confidence,
+ f.end_derived, {time_corrected} AS time_corrected
FROM facts f
LEFT JOIN relation_types r ON r.id = f.predicate_id
JOIN entities s ON s.id = {subject}
@@ -398,6 +403,8 @@ async fn details(
WHERE f.kb_id = $1 AND f.id = ANY($2)",
holds_from = world_axis::facts_holds_from("f"),
holds_to = world_axis::facts_holds_to("f"),
+ targets = crate::graph::TIME_CORRECTED_TARGETS,
+ time_corrected = crate::graph::time_corrected_sql("f"),
))
.bind(kb_id)
.bind(fact_ids)
diff --git a/crates/utopia-store/tests/store/a_fact_says_where_its_dates_came_from.rs b/crates/utopia-store/tests/store/a_fact_says_where_its_dates_came_from.rs
new file mode 100644
index 00000000..f33a124a
--- /dev/null
+++ b/crates/utopia-store/tests/store/a_fact_says_where_its_dates_came_from.rs
@@ -0,0 +1,167 @@
+//! 一条事实的日期从哪来(#970)。图谱工具的每条事实行带 `[n]`,打开的是那条事实读出来的
+//! 原句(#968),可有两种日期原句里没有:
+//!
+//! - 时间线推出来的终点:李四自 2024-07-05 领 Aurora,周七 2025-09-01 接手,`leads` 一个项目
+//! 同时只有一个,对账把李四那一段关在 2025-09-01——`end_derived`;
+//! - 人改过的区间:张三的起点被人从 2023-01-10 改成 2023-02-01,`fact.time_corrected` 记在
+//! 被改的那一行上——`time_corrected`,之后这一行再被改写也仍然是。
+//!
+//! 人手关上的一段两个都不是;它仍是一条修正行(`corrected`,网页证据栏那句提示按它说)。
+//!
+//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。
+
+use chrono::{DateTime, Utc};
+use serde_json::json;
+use sqlx::PgPool;
+use utopia_core::models::EntityFact;
+use utopia_store::graph::{self, Validity};
+use uuid::Uuid;
+
+fn t(s: &str) -> DateTime<Utc> {
+ s.parse().expect("fixed timestamp")
+}
+
+/// 一个日精度的日子
+fn day(s: &str) -> DateTime<Utc> {
+ t(&format!("{s}T00:00:00Z"))
+}
+
+fn since(at: &str) -> Validity<'static> {
+ Validity::starting(Some(day(at)), Some("day"))
+}
+
+fn between(from: &str, to: &str) -> Validity<'static> {
+ Validity {
+ to: Some(day(to)),
+ to_precision: Some("day"),
+ ..since(from)
+ }
+}
+
+/// Aurora 身上那个人的那一行:(终点是推出来的, 区间是人改过的, 是修正行)
+fn flags(facts: &[EntityFact], who: &str) -> (bool, bool, bool) {
+ let f = facts
+ .iter()
+ .find(|f| f.other_name.as_deref() == Some(who))
+ .unwrap_or_else(|| panic!("no fact of {who}"));
+ (f.end_derived, f.time_corrected, f.corrected)
+}
+
+#[tokio::test]
+async fn a_fact_says_where_its_dates_came_from() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let ids: Vec<Uuid> = (0..13).map(|_| Uuid::now_v7()).collect();
+ let (org, ws, kb, user, person, project) = (ids[0], ids[1], ids[2], ids[3], ids[4], ids[5]);
+ let (leads, advises, zhang, li, zhou, wang, aurora) =
+ (ids[6], ids[7], ids[8], ids[9], ids[10], ids[11], ids[12]);
+ // Only locally generated UUIDs are interpolated into fixture SQL.
+ sqlx::raw_sql(&format!(
+ "INSERT INTO organizations (id, name) VALUES ('{org}', 'dates-came-from');
+ INSERT INTO workspaces (id, org_id, name) VALUES ('{ws}', '{org}', 'dates-came-from');
+ INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ('{kb}', '{ws}', 'dates-came-from');
+ INSERT INTO users (id, org_id, email, display_name, password_hash)
+ VALUES ('{user}', '{org}', '{user}@dates.test', 'editor', 'unused');
+ INSERT INTO entity_types (id, kb_id, key, label, color, shape) VALUES
+ ('{person}', '{kb}', 'person', 'person', '#7fd0ff', 'circle'),
+ ('{project}', '{kb}', 'project', 'project', '#7fd0ff', 'circle');
+ INSERT INTO relation_types (id, kb_id, key, label, temporal, inverse_functional) VALUES
+ ('{leads}', '{kb}', 'leads', 'leads', 'state', TRUE),
+ ('{advises}', '{kb}', 'advises', 'advises', 'state', FALSE);
+ INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES
+ ('{zhang}', '{kb}', '{person}', 'Zhang San'), ('{li}', '{kb}', '{person}', 'Li Si'),
+ ('{zhou}', '{kb}', '{person}', 'Zhou Qi'), ('{wang}', '{kb}', '{person}', 'Wang Wu'),
+ ('{aurora}', '{kb}', '{project}', 'Aurora');"
+ ))
+ .execute(&pool)
+ .await?;
+
+ let run = async {
+ let fact = |who: Uuid, predicate: Uuid, validity: Validity<'static>| {
+ let pool = pool.clone();
+ async move {
+ graph::insert_fact(&pool, kb, who, Some(predicate), aurora, validity, 0.9)
+ .await
+ .map(|(id, _)| id)
+ }
+ };
+ // 周七接手:一个项目同时只有一个 lead,对账把李四那一段关在 2025-09-01
+ let li_row = fact(li, leads, since("2024-07-05")).await?;
+ let zhou_row = fact(zhou, leads, since("2025-09-01")).await?;
+ utopia_store::temporal::reconcile_moved_facts(&pool, kb, &[li_row, zhou_row]).await?;
+
+ // 人改张三的起点,终点照旧;审计记在被改的那一行上(与 PATCH /facts/{id} 同一条路)
+ let zhang_row = fact(zhang, leads, between("2023-01-10", "2024-07-05")).await?;
+ let corrected = utopia_store::temporal::correct_interval(
+ &pool,
+ zhang_row,
+ between("2023-02-01", "2024-07-05"),
+ )
+ .await?
+ .expect("the row was live");
+ utopia_store::audit::record(
+ &pool,
+ Some(kb),
+ user,
+ "fact.time_corrected",
+ "fact",
+ Some(zhang_row),
+ json!({ "note": "The charter date was the approval date" }),
+ )
+ .await?;
+
+ // 人手关上的一段:一条修正行,但终点是人给的,区间也没被改过
+ let wang_row = graph::insert_fact(
+ &pool,
+ kb,
+ wang,
+ Some(advises),
+ aurora,
+ since("2023-03-02"),
+ 0.9,
+ )
+ .await?
+ .0;
+ utopia_store::temporal::close_superseded(&pool, wang_row, t("2024-01-01T00:00:00Z"), "day")
+ .await?;
+
+ let (_, facts) = graph::entity_detail(&pool, kb, aurora, None, None).await?;
+ assert_eq!(
+ flags(&facts, "Li Si"),
+ (true, false, true),
+ "the timeline closed it"
+ );
+ assert_eq!(flags(&facts, "Zhou Qi"), (false, false, false));
+ assert_eq!(
+ flags(&facts, "Zhang San"),
+ (false, true, true),
+ "a person corrected it"
+ );
+ assert_eq!(
+ flags(&facts, "Wang Wu"),
+ (false, false, true),
+ "closed by hand: rewritten, but neither mark"
+ );
+
+ // 改过的区间再被改写一次(这里是关上),往上的链里仍有那一次人改
+ utopia_store::temporal::close_superseded(
+ &pool,
+ corrected,
+ t("2024-06-30T00:00:00Z"),
+ "day",
+ )
+ .await?;
+ let (_, facts) = graph::entity_detail(&pool, kb, aurora, None, None).await?;
+ assert_eq!(flags(&facts, "Zhang San"), (false, true, true));
+ anyhow::Ok(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(org)
+ .execute(&pool)
+ .await?;
+ run
+}
diff --git a/crates/utopia-store/tests/store/main.rs b/crates/utopia-store/tests/store/main.rs
index 576590da..c3495a7f 100644
--- a/crates/utopia-store/tests/store/main.rs
+++ b/crates/utopia-store/tests/store/main.rs
@@ -45,6 +45,7 @@ mod a_dirty_ledger_stops_the_migration;
mod a_disambiguator_follows_the_ontology;
mod a_document_opening_is_its_first_live_chunk;
mod a_fact_awaits_a_nod;
+mod a_fact_says_where_its_dates_came_from;
mod a_failed_job_finds_its_way_back;
mod a_forward_reference_is_judged_at_commit;
mod a_governor_reads_the_ledger;
diff --git a/docs/design/chat-and-mcp.md b/docs/design/chat-and-mcp.md
index 67d49193..cf43a22e 100644
--- a/docs/design/chat-and-mcp.md
+++ b/docs/design/chat-and-mcp.md
@@ -54,7 +54,9 @@ premises carry theirs where they are shown; MCP text stays unnumbered, its evide
entry a graph fact cites carries the sentence the fact was read from (`quotes`, one chunk keeping
one number however many of its sentences are cited, a search hit gaining the sentence when a graph
tool cites it), and the preview and the document page mark it, so the number opens the sentence
-itself (#968's follow-up). The
+itself (#968's follow-up). A date that passage does not state says so on the line, in chat and MCP
+alike: an end the timeline derived reads `…, end derived`, an interval a person corrected
+`…, corrected`, and the prompt says neither is attributed to the passage (#970). The
previous turn's tool calls are replayed so the model knows what it did, not only
what it said [0015]; a turn that gathers nothing, such as a restatement, keeps the previous answer's
sources for the citation numbers it repeats (#943).
diff --git a/migrations/0097_a_corrected_interval_is_found_by_its_row.sql b/migrations/0097_a_corrected_interval_is_found_by_its_row.sql
new file mode 100644
index 00000000..6ad8eef8
--- /dev/null
+++ b/migrations/0097_a_corrected_interval_is_found_by_its_row.sql
@@ -0,0 +1,7 @@
+-- 事实行上说「这一段是人改过的」(#970):读一个实体的事实时,要知道本库哪些行被人改过区间,
+-- 也就是 `fact.time_corrected` 的审计记在了哪些行上。`audit_events` 只有 (kb_id, created_at)
+-- 的索引,按动作找要把这个库的审计整个读一遍——一个没人改过区间的库也一样,而实体面板和
+-- 四个图谱工具每次读都要问。部分索引只收这一种动作,库里改过几行它就几行。
+CREATE INDEX IF NOT EXISTS audit_events_time_corrected_idx
+ ON audit_events (kb_id, target_id)
+ WHERE action = 'fact.time_corrected' AND target_id IS NOT NULL;