Skip to content

World's first open-source enterprise world model.

A wrong date can be corrected without deleting the document (#311)

WaylandYang24d7207d0717
diff --git a/crates/utopia-server/src/api/graph_routes.rs b/crates/utopia-server/src/api/graph_routes.rs
index 8962ac27..3164703b 100644
--- a/crates/utopia-server/src/api/graph_routes.rs
+++ b/crates/utopia-server/src/api/graph_routes.rs
@@ -221,6 +221,177 @@ pub async fn update_entity(
Ok(Json(json!({ "entity": after, "same_name": peers })))
}
+/// 一条事实的新有效区间。**整体替换,不是部分更新**:区间的两端互相定义,
+/// 「把结束端清空」与「这次不动结束端」必须能分辨,而缺字段与 null 在 JSON 里
+/// 分不开。界面提交的是表单里的四个值,不是差异。
+#[derive(Deserialize)]
+pub struct FactTimePatch {
+ #[serde(default)]
+ pub valid_from: Option<chrono::DateTime<chrono::Utc>>,
+ #[serde(default)]
+ pub valid_from_precision: Option<String>,
+ #[serde(default)]
+ pub valid_to: Option<chrono::DateTime<chrono::Utc>>,
+ #[serde(default)]
+ pub valid_to_precision: Option<String>,
+ /// 为什么改。落进台账,不进图——「之前记错了」与「新证据说是六月」在账本上
+ /// 长得一样,硬加一个类型枚举会让入口变重而判据模糊;真需要分辨了,再从
+ /// 这里升格成字段
+ #[serde(default)]
+ pub note: Option<String>,
+}
+
+const DATE_PRECISIONS: [&str; 3] = ["year", "month", "day"];
+
+/// 修改前的区间,用于「一字未改」的判定与台账里的前后对照。
+#[derive(sqlx::FromRow)]
+struct FactInterval {
+ valid_from: Option<chrono::DateTime<chrono::Utc>>,
+ valid_from_precision: Option<String>,
+ valid_to: Option<chrono::DateTime<chrono::Utc>>,
+ valid_to_precision: Option<String>,
+}
+
+/// 复刻 `facts` 表的两条 CHECK,外加一条数据库没有的:起点不能晚于终点。
+///
+/// 在这里挡住是为了让错误说人话。交给数据库挡会得到一句约束名,而这三态
+/// (仍在持续 / 结束了不知哪天 / 某日结束)本来就是账本里最容易记混的地方。
+fn check_interval(p: &FactTimePatch) -> Result<(), AppError> {
+ // 起始端:没日期就没精度,且没有 unknown 档——「开始了但不知何时」与
+ // 「不知道有没有开始」在这个账本里不可区分(见迁移 0003 的注释)
+ match (&p.valid_from, p.valid_from_precision.as_deref()) {
+ (Some(_), Some(prec)) if DATE_PRECISIONS.contains(&prec) => {}
+ (None, None) => {}
+ _ => return Err(AppError::invalid(
+ "bad_valid_from",
+ "A start date needs a precision of year, month or day, and a precision needs a date.",
+ )),
+ }
+ // 结束端:有日期必有精度;没日期只能是仍在持续(都为空)或结束了不知哪天
+ match (&p.valid_to, p.valid_to_precision.as_deref()) {
+ (Some(_), Some(prec)) if DATE_PRECISIONS.contains(&prec) => {}
+ (None, None) => {}
+ (None, Some(prec)) if prec == utopia_store::graph::ENDED_UNKNOWN => {}
+ _ => {
+ return Err(AppError::invalid(
+ "bad_valid_to",
+ "An end date needs a precision of year, month or day. Leave the date empty for still going, or mark it ended with an unknown date.",
+ ))
+ }
+ }
+ if let (Some(from), Some(to)) = (p.valid_from, p.valid_to) {
+ if from > to {
+ return Err(AppError::invalid(
+ "interval_inverted",
+ "The start of the interval is after its end.",
+ ));
+ }
+ }
+ Ok(())
+}
+
+/// 人工修正一条事实的有效区间。抽取给的是初判,此前判错只能删掉文档重抽——
+/// 名字判错有 Review 可改(见 `update_entity`),时间判错没有入口,而这个
+/// 产品卖的正是时间。
+///
+/// 走账本不走原地改:`correct_interval` 作废旧行、插带 `supersedes` 的修正行。
+/// 于是这次修改本身出现在记录轴上(实体面板的 History),世界轴上只留新区间——
+/// 旧区间是我们记错了,不是世界曾经的样子,两段并排会被读成换过两次岗。
+pub async fn update_fact_time(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, fact_id)): Path<(Uuid, Uuid)>,
+ Json(req): Json<FactTimePatch>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ check_interval(&req)?;
+
+ // 归属与状态校验:本 KB 的、未作废的事实才可改。派生事实不在此列——
+ // 它的区间来自前提,改它等于改一个算出来的值,下一轮推理就会覆盖
+ let before: Option<FactInterval> = sqlx::query_as(
+ "SELECT valid_from, valid_from_precision, valid_to, valid_to_precision
+ FROM facts
+ WHERE id = $1 AND kb_id = $2 AND invalidated_at IS NULL AND derived_by_rule IS NULL",
+ )
+ .bind(fact_id)
+ .bind(kb_id)
+ .fetch_optional(&state.pool)
+ .await
+ .map_err(AppError::Db)?;
+ let Some(before) = before else {
+ return Err(AppError::NotFound.into());
+ };
+ // 一字未改就不写一条修正进账本:History 上多一行「改过」而区间没动,
+ // 读者会去找那个不存在的差异
+ if before.valid_from == req.valid_from
+ && before.valid_from_precision == req.valid_from_precision
+ && before.valid_to == req.valid_to
+ && before.valid_to_precision == req.valid_to_precision
+ {
+ return Ok(Json(json!({ "ok": true, "unchanged": true })));
+ }
+
+ let snap = crate::api::review_routes::fact_snapshot(&state, kb_id, fact_id).await;
+ let validity = utopia_store::graph::Validity {
+ from: req.valid_from,
+ from_precision: req.valid_from_precision.as_deref(),
+ to: req.valid_to,
+ to_precision: req.valid_to_precision.as_deref(),
+ };
+ let Some(corrected) =
+ utopia_store::temporal::correct_interval(&state.pool, fact_id, validity).await?
+ else {
+ // 并发:另一处已经改写或作废了它。让界面重取,不要把两次修正叠起来
+ return Err(AppError::invalid(
+ "fact_changed",
+ "This fact was changed by someone else. Reload and try again.",
+ )
+ .into());
+ };
+
+ // 改完要重新对账:把起点往前挪可能撞上前任的开放区间,那正是时态引擎
+ // 该管的事。复用搬移后的那条路径——换了区间与换了主宾一样,都让唯一性
+ // 不变量第一次看到这次相撞
+ let report =
+ utopia_store::temporal::reconcile_moved_facts(&state.pool, kb_id, &[corrected]).await?;
+
+ if let Some(mut d) = snap {
+ d["from"] = json!({
+ "valid_from": before.valid_from.map(|t| t.to_rfc3339()),
+ "valid_from_precision": before.valid_from_precision,
+ "valid_to": before.valid_to.map(|t| t.to_rfc3339()),
+ "valid_to_precision": before.valid_to_precision,
+ });
+ d["to"] = json!({
+ "valid_from": req.valid_from.map(|t| t.to_rfc3339()),
+ "valid_from_precision": req.valid_from_precision,
+ "valid_to": req.valid_to.map(|t| t.to_rfc3339()),
+ "valid_to_precision": req.valid_to_precision,
+ });
+ if let Some(note) = req.note.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
+ d["note"] = json!(note);
+ }
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "fact.time_corrected",
+ "fact",
+ Some(fact_id),
+ d,
+ )
+ .await;
+ }
+
+ state.emit_review(kb_id);
+ Ok(Json(json!({
+ "ok": true,
+ "fact_id": corrected,
+ "closed": report.corrected.len(),
+ "conflicts": report.conflicts,
+ })))
+}
+
pub async fn fact_evidence(
State(state): State<AppState>,
AuthUser(user): AuthUser,
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index aead03ad..8197fa6f 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -299,6 +299,11 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
"/kbs/{id}/facts/{fact_id}/evidence",
get(graph_routes::fact_evidence),
)
+ // 人工修正有效区间(302):与实体的 PATCH 对称,走账本不原地改
+ .route(
+ "/kbs/{id}/facts/{fact_id}",
+ patch(graph_routes::update_fact_time),
+ )
// 派生事实的证明(0002 R2):前提按顺序展开到原句
.route(
"/kbs/{id}/derived/{derived_id}/proof",
diff --git a/crates/utopia-server/src/api/review_routes.rs b/crates/utopia-server/src/api/review_routes.rs
index e44aef68..c91a0117 100644
--- a/crates/utopia-server/src/api/review_routes.rs
+++ b/crates/utopia-server/src/api/review_routes.rs
@@ -20,7 +20,11 @@ type ConflictSnapshot = (String, Option<String>, String, Option<String>, String)
/// 事实快照(决策台账用):reject 后事实从图里消失,台账必须自包含展示文本。
/// 一律在动作执行前取。
-async fn fact_snapshot(state: &AppState, kb_id: Uuid, fact_id: Uuid) -> Option<serde_json::Value> {
+pub(crate) async fn fact_snapshot(
+ state: &AppState,
+ kb_id: Uuid,
+ fact_id: Uuid,
+) -> Option<serde_json::Value> {
// 宾语可能是实体或字面值;结构化字面值优先取 summary(与队列卡片同一显示口径)
let row: Option<(String, Option<String>, Option<String>, f32)> = sqlx::query_as(
"SELECT s.canonical_name, COALESCE(r.label, fact_surface_predicate(f.id)),
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index e70b96fd..1f70f0f0 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -1027,7 +1027,11 @@ pub async fn entity_history(
AND ev.kind <> 'asserted'
AND a.action = ANY(CASE ev.kind
WHEN 'corrected' THEN
- ARRAY['fact.close', 'conflict.close_old', 'ontology.predicate_adopted']
+ ARRAY['fact.close', 'conflict.close_old', 'ontology.predicate_adopted',
+ -- 人工改区间(302)。少了这一条,人做的修正在
+ -- 这条轴上归给「engine」——一个决策账本把人的
+ -- 决定记成机器的,比不记还坏
+ 'fact.time_corrected']
-- 并入只可能由采纳造成,不会是 Review 里的拒绝
WHEN 'merged' THEN ARRAY['ontology.predicate_adopted']
ELSE ARRAY['fact.reject', 'conflict.reject_new',
diff --git a/crates/utopia-store/src/temporal.rs b/crates/utopia-store/src/temporal.rs
index 4c6d5f68..9c57b390 100644
--- a/crates/utopia-store/src/temporal.rs
+++ b/crates/utopia-store/src/temporal.rs
@@ -275,19 +275,77 @@ pub async fn close_superseded(
.bind(fact_id)
.execute(&mut *tx)
.await?;
+ copy_evidence(&mut tx, fact_id, corrected).await?;
+ tx.commit().await?;
+ Ok(corrected)
+}
+
+/// 证据引用随修正行复制。表层谓词一起搬:纠正的是时间区间,不是原文说了什么。
+async fn copy_evidence(
+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ from: Uuid,
+ to: Uuid,
+) -> AppResult<()> {
sqlx::query(
- // 表层谓词随证据一起搬:纠正的是时间区间,不是原文说了什么
"INSERT INTO fact_evidence (fact_id, chunk_id, quote, proposed_predicate, document_id, doc_version)
SELECT $1, chunk_id, quote, proposed_predicate, document_id, doc_version
FROM fact_evidence WHERE fact_id = $2
ON CONFLICT DO NOTHING",
)
+ .bind(to)
+ .bind(from)
+ .execute(&mut **tx)
+ .await?;
+ Ok(())
+}
+
+/// 人工修正一条事实的有效区间。与自动闭合同一机制(作废 + 改写),区别只在
+/// 两端都来自参数,而不是继承旧行的起点。
+///
+/// 抽取把「2023 年上半年」读成 1 月 1 日,在此之前只能删掉文档重抽一遍:
+/// 名字判错有 Review 可改,时间判错没有入口,而整条时间线都歪在那一个值上。
+///
+/// **不原地 UPDATE。** 原地改会把修正本身抹掉,而那正是记录轴要回放的东西
+/// (0019)——改过之后,问三月与问九月应当得到不同的区间。这也是这个函数
+/// 与一条 `UPDATE facts SET valid_from = …` 的全部差别。
+///
+/// 返回修正行 id;`None` 表示这条已被并发改写或作废,本次没有动手。
+pub async fn correct_interval(
+ pool: &PgPool,
+ fact_id: Uuid,
+ validity: crate::graph::Validity<'_>,
+) -> AppResult<Option<Uuid>> {
+ let mut tx = pool.begin().await?;
+ let corrected = Uuid::now_v7();
+ let inserted: Option<(Uuid,)> = sqlx::query_as(
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, object_value,
+ valid_from, valid_from_precision,
+ valid_to, valid_to_precision, confidence, supersedes)
+ SELECT $1, kb_id, subject_id, predicate_id, object_id, object_value,
+ $3, $4, $5, $6, confidence, id
+ FROM facts WHERE id = $2 AND invalidated_at IS NULL
+ RETURNING id",
+ )
.bind(corrected)
.bind(fact_id)
- .execute(&mut *tx)
+ .bind(validity.from)
+ .bind(validity.from_precision)
+ .bind(validity.to)
+ .bind(validity.to_precision)
+ .fetch_optional(&mut *tx)
.await?;
+ // 已被并发修正过:不重复动手(与 close_superseded 同一防线)
+ if inserted.is_none() {
+ tx.rollback().await?;
+ return Ok(None);
+ }
+ sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = $1")
+ .bind(fact_id)
+ .execute(&mut *tx)
+ .await?;
+ copy_evidence(&mut tx, fact_id, corrected).await?;
tx.commit().await?;
- Ok(corrected)
+ Ok(Some(corrected))
}
async fn record_conflict(
diff --git a/crates/utopia-store/tests/a_wrong_time_can_be_corrected.rs b/crates/utopia-store/tests/a_wrong_time_can_be_corrected.rs
new file mode 100644
index 00000000..d6785c38
--- /dev/null
+++ b/crates/utopia-store/tests/a_wrong_time_can_be_corrected.rs
@@ -0,0 +1,410 @@
+//! 人工修正一条事实的有效区间(302),打在真库上。
+//!
+//! 抽取把「2023 年上半年」读成 1 月 1 日,在此之前只能删掉文档重抽一遍。
+//! 这条路径的全部风险在于**它长得像一次 UPDATE**:改一个日期,图上就对了,
+//! 谁也看不出账本少了什么。所以这里钉的四样,`cargo check` 一样都看不见:
+//!
+//! - 旧行留在账本里并记下作废时刻,修正行以 `supersedes` 链回它——原地改
+//! 会让这次修改自己消失,而那正是记录轴要回放的东西(0019)
+//! - 证据随修正行复制。少了这一步,改完时间的事实立刻变成"无人陈述",
+//! 会被 stale 判定扫成灰的
+//! - 起点挪动之后要重新对账:挪过继任者的上任日,唯一性不变量才第一次
+//! 看到这次相撞
+//! - 已被作废的行改不动,返回 None 而不是凭空插一条挂在死行后面的修正
+//!
+//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。
+
+use sqlx::PgPool;
+use utopia_store::graph::Validity;
+use uuid::Uuid;
+
+struct Fixture {
+ kb: Uuid,
+ zhang: Uuid,
+ li: Uuid,
+ project: Uuid,
+ leads: Uuid,
+ chunk: Uuid,
+ doc: Uuid,
+}
+
+async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let etype = Uuid::now_v7();
+ let leads = Uuid::now_v7();
+ let (zhang, li, project) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (src, doc, chunk) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'time-edit-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'time-edit-test')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'time-edit-test')",
+ )
+ .bind(kb)
+ .bind(ws)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'thing', 'Thing')",
+ )
+ .bind(etype)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ // inverse_functional:一个项目同时只有一个人 leads 它——宾语侧的唯一性,
+ // 起点挪动要撞的正是这条不变量
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label, temporal, inverse_functional)
+ VALUES ($1, $2, 'leads', 'leads', 'state', TRUE)",
+ )
+ .bind(leads)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ for (id, name) in [(zhang, "Zhang San"), (li, "Li Si"), (project, "Phoenix")] {
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
+ )
+ .bind(id)
+ .bind(kb)
+ .bind(etype)
+ .bind(name)
+ .execute(pool)
+ .await?;
+ }
+ sqlx::query("INSERT INTO sources (id, kb_id, name) VALUES ($1, $2, 'time-edit-test')")
+ .bind(src)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO documents (id, kb_id, source_id, filename, sha256, status)
+ VALUES ($1, $2, $3, 'memo.md', 'timeedit', 'ready')",
+ )
+ .bind(doc)
+ .bind(kb)
+ .bind(src)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO chunks (id, kb_id, document_id, seq, text)
+ VALUES ($1, $2, $3, 0, 'Zhang San led Phoenix in the first half of 2023.')",
+ )
+ .bind(chunk)
+ .bind(kb)
+ .bind(doc)
+ .execute(pool)
+ .await?;
+ Ok(Fixture {
+ kb,
+ zhang,
+ li,
+ project,
+ leads,
+ chunk,
+ doc,
+ })
+}
+
+fn t(s: &str) -> chrono::DateTime<chrono::Utc> {
+ s.parse().unwrap()
+}
+
+/// 一条带证据的开放事实。
+async fn assert_fact(
+ pool: &PgPool,
+ f: &Fixture,
+ subject: Uuid,
+ from: &str,
+ precision: &str,
+) -> anyhow::Result<Uuid> {
+ let (id, _) = utopia_store::graph::insert_fact(
+ pool,
+ f.kb,
+ subject,
+ Some(f.leads),
+ f.project,
+ Validity::starting(Some(t(from)), Some(precision)),
+ 0.9,
+ )
+ .await?;
+ sqlx::query(
+ "INSERT INTO fact_evidence (fact_id, chunk_id, quote, document_id, doc_version)
+ VALUES ($1, $2, 'led Phoenix', $3, 1)",
+ )
+ .bind(id)
+ .bind(f.chunk)
+ .bind(f.doc)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+#[derive(sqlx::FromRow)]
+struct Row {
+ valid_from: Option<chrono::DateTime<chrono::Utc>>,
+ valid_from_precision: Option<String>,
+ valid_to: Option<chrono::DateTime<chrono::Utc>>,
+ valid_to_precision: Option<String>,
+ invalidated_at: Option<chrono::DateTime<chrono::Utc>>,
+ supersedes: Option<Uuid>,
+}
+
+async fn row(pool: &PgPool, id: Uuid) -> anyhow::Result<Row> {
+ Ok(sqlx::query_as(
+ "SELECT valid_from, valid_from_precision, valid_to, valid_to_precision,
+ invalidated_at, supersedes
+ FROM facts WHERE id = $1",
+ )
+ .bind(id)
+ .fetch_one(pool)
+ .await?)
+}
+
+async fn evidence_count(pool: &PgPool, id: Uuid) -> anyhow::Result<i64> {
+ let (n,): (i64,) = sqlx::query_as("SELECT count(*) FROM fact_evidence WHERE fact_id = $1")
+ .bind(id)
+ .fetch_one(pool)
+ .await?;
+ Ok(n)
+}
+
+/// 改一个日期,账本要留下改过的痕迹:旧行作废但不删,修正行链回它,证据跟着走。
+#[tokio::test]
+async fn correcting_a_date_leaves_the_old_reading_in_the_ledger() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ // 抽取读成了 1 月 1 日,精确到日——原文其实只说了「上半年」
+ let wrong = assert_fact(&pool, &f, f.zhang, "2023-01-01T00:00:00Z", "day").await?;
+
+ let corrected = utopia_store::temporal::correct_interval(
+ &pool,
+ wrong,
+ Validity::starting(Some(t("2023-06-01T00:00:00Z")), Some("month")),
+ )
+ .await?
+ .expect("这条还活着,应当改得动");
+
+ let old = row(&pool, wrong).await?;
+ assert!(
+ old.invalidated_at.is_some(),
+ "旧行要记下何时被推翻——原地 UPDATE 会让这次修改自己消失"
+ );
+ assert_eq!(
+ old.valid_from,
+ Some(t("2023-01-01T00:00:00Z")),
+ "旧行的世界区间一个字都不该动:它记录的是我们当时读成了什么"
+ );
+
+ let new = row(&pool, corrected).await?;
+ assert_eq!(new.supersedes, Some(wrong), "修正行要链回被它取代的那条");
+ assert!(new.invalidated_at.is_none(), "修正行是现行的");
+ assert_eq!(new.valid_from, Some(t("2023-06-01T00:00:00Z")));
+ assert_eq!(
+ new.valid_from_precision.as_deref(),
+ Some("month"),
+ "精度跟着值一起改——写到月就是月,不该继承旧行那个「日」"
+ );
+
+ assert_eq!(
+ evidence_count(&pool, corrected).await?,
+ 1,
+ "证据要随修正行复制。少了它,这条事实立刻变成「无人陈述」被扫成灰的"
+ );
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ run
+}
+
+/// 结束端的三态都要改得进去,尤其是**把闭区间重新打开**——
+/// 那是「当初误判它结束了」唯一的出路,而它长得像一次「什么都没填」。
+#[tokio::test]
+async fn an_end_that_was_never_there_can_be_taken_back() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ let fact = assert_fact(&pool, &f, f.zhang, "2023-01-01T00:00:00Z", "day").await?;
+ // 先闭合到 2024
+ let closed = utopia_store::temporal::correct_interval(
+ &pool,
+ fact,
+ Validity {
+ from: Some(t("2023-01-01T00:00:00Z")),
+ from_precision: Some("day"),
+ to: Some(t("2024-01-01T00:00:00Z")),
+ to_precision: Some("year"),
+ },
+ )
+ .await?
+ .expect("改得动");
+ assert_eq!(
+ row(&pool, closed).await?.valid_to,
+ Some(t("2024-01-01T00:00:00Z"))
+ );
+
+ // 判错了:它其实没结束。把结束端整个收回
+ let reopened = utopia_store::temporal::correct_interval(
+ &pool,
+ closed,
+ Validity::starting(Some(t("2023-01-01T00:00:00Z")), Some("day")),
+ )
+ .await?
+ .expect("改得动");
+ let r = row(&pool, reopened).await?;
+ assert!(r.valid_to.is_none(), "结束端收回了");
+ assert!(
+ r.valid_to_precision.is_none(),
+ "精度也要一起收回:留着 'year' 而日期为空,CHECK 会拦,而三值逻辑下这种组合曾经静默放行"
+ );
+ assert_eq!(r.supersedes, Some(closed), "两次修正串成链,不是各挂各的");
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ run
+}
+
+/// 改完起点要重新对账。**这是这一刀最容易漏掉的一半**:区间改对了,图上
+/// 那条边看着也对了,可它与继任者的关系没人再算一遍。
+///
+/// 这里的两个人在修改前后交换了身份——改之前张三 2025 上任,是李四的继任者;
+/// 改回 2023 之后他成了前任,该被闭合在李四的上任日上。唯一性不变量只在
+/// 这次对账里才第一次看到这件事。
+#[tokio::test]
+async fn moving_a_start_earlier_makes_it_the_predecessor() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ // 两条都开放:李四 2024-07 接任,张三被抽取读成 2025-01(错的,
+ // 他其实 2023 年就在任)。此刻不变量已经被违反,只是还没人算
+ let li_fact = assert_fact(&pool, &f, f.li, "2024-07-01T00:00:00Z", "month").await?;
+ let zhang_fact = assert_fact(&pool, &f, f.zhang, "2025-01-01T00:00:00Z", "month").await?;
+
+ // 把张三改回真实的 2023
+ let fixed = utopia_store::temporal::correct_interval(
+ &pool,
+ zhang_fact,
+ Validity::starting(Some(t("2023-01-01T00:00:00Z")), Some("month")),
+ )
+ .await?
+ .expect("改得动");
+ let report = utopia_store::temporal::reconcile_moved_facts(&pool, f.kb, &[fixed]).await?;
+
+ assert!(
+ !report.corrected.is_empty(),
+ "对账要动手:张三 2023 起、李四 2024-07 接任,两条不能都挂着开放区间"
+ );
+ // 新事实开始得更早 = 它是前任,闭合在旧事实的开始(引擎的判据)
+ assert!(
+ row(&pool, fixed).await?.invalidated_at.is_some(),
+ "被闭合的是张三自己那条,不是李四——早的那个是前任"
+ );
+ let current: Row = sqlx::query_as(
+ "SELECT valid_from, valid_from_precision, valid_to, valid_to_precision,
+ invalidated_at, supersedes
+ FROM facts WHERE supersedes = $1",
+ )
+ .bind(fixed)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(
+ current.valid_to,
+ Some(t("2024-07-01T00:00:00Z")),
+ "张三的区间闭合在李四的上任日"
+ );
+ assert_eq!(
+ current.valid_from,
+ Some(t("2023-01-01T00:00:00Z")),
+ "起点保持修正后的值"
+ );
+ assert!(
+ row(&pool, li_fact).await?.invalidated_at.is_none(),
+ "李四那条一动不动:他是现任,本来就该开放"
+ );
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ run
+}
+
+/// 已被作废的行改不动。少了这道闸,两个人同时改会串出两条各自挂在死行后面的
+/// 修正,图上凭空多一条边。
+#[tokio::test]
+async fn a_row_that_is_already_gone_cannot_be_corrected() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ let fact = assert_fact(&pool, &f, f.zhang, "2023-01-01T00:00:00Z", "day").await?;
+ let first = utopia_store::temporal::correct_interval(
+ &pool,
+ fact,
+ Validity::starting(Some(t("2023-06-01T00:00:00Z")), Some("month")),
+ )
+ .await?;
+ assert!(first.is_some());
+
+ // 第二次拿着同一个(已作废的)id 再改
+ let second = utopia_store::temporal::correct_interval(
+ &pool,
+ fact,
+ Validity::starting(Some(t("2022-01-01T00:00:00Z")), Some("year")),
+ )
+ .await?;
+ assert!(
+ second.is_none(),
+ "作废行改不动,要让调用方知道没动手——而不是插一条挂在死行后面的修正"
+ );
+ let (n,): (i64,) = sqlx::query_as("SELECT count(*) FROM facts WHERE supersedes = $1")
+ .bind(fact)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(n, 1, "一条死行只该有一个后继");
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ run
+}
diff --git a/web/src/api.ts b/web/src/api.ts
index 48e1b81b..db954c11 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -1438,6 +1438,30 @@ export const api = {
{ method: "PATCH", body: JSON.stringify(body) },
),
+ /** 人工修正一条事实的有效区间(302)。**整体替换**:四个值一起提交,
+ * 服务端作废旧行、插修正行——不是原地改,所以这次修改会出现在 History 上。 */
+ updateFactTime: (
+ kbId: string,
+ factId: string,
+ body: {
+ valid_from: string | null;
+ valid_from_precision: string | null;
+ valid_to: string | null;
+ valid_to_precision: string | null;
+ note?: string;
+ },
+ ) =>
+ request<{
+ ok: boolean;
+ unchanged?: boolean;
+ fact_id?: string;
+ closed?: number;
+ conflicts?: number;
+ }>(`/api/v1/kbs/${kbId}/facts/${factId}`, {
+ method: "PATCH",
+ body: JSON.stringify(body),
+ }),
+
entityHistory: (kbId: string, entityId: string, page: number, per = 30) =>
request<{ events: EntityHistoryEvent[]; total: number }>(
`/api/v1/kbs/${kbId}/entities/${entityId}/history?page=${page}&per=${per}`,
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index f1dd3c7d..8cea093e 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -839,9 +839,33 @@ export const en = {
undated: "Undated",
timelineEmpty: "No dated facts yet.",
lastConfirmed: (d: string) => `confirmed ${d}`,
+ /* 三种来源共用一个标记(引擎接任对账、Review 裁决、有人手改),所以这句
+ 不再声称是哪一种——加上人工编辑之后,原来那句「由对账闭合」会说错来源。
+ 想知道是谁改的,History 有 actor 和时刻 */
correctedHint:
- "This interval was closed by reconciliation (automatic succession or a review decision), " +
- "not stated verbatim in a document. The superseded assertion remains in the ledger.",
+ "This interval comes from a correction rather than a sentence in a document: " +
+ "automatic succession, a review decision, or someone editing it. " +
+ "The superseded assertion stays in the ledger — see History for who and when.",
+ /* ---- 人工修正有效区间(302) ---- */
+ editTime: "Correct the interval",
+ timeStart: "Start",
+ timeEnd: "End",
+ /* 结束端的三态,与账本里的三种写法一一对应(见迁移 0003 的注释) */
+ timeEndOpen: "Still going",
+ timeEndUnknown: "Ended, date unknown",
+ timeEndDate: "Ended on",
+ /* 写多少位就是多少精度:2023 是「那一年」,2023-06 是「那个月」 */
+ timeFormat: "2023, 2023-06 or 2023-06-15",
+ timeBadDate: "Use 2023, 2023-06 or 2023-06-15.",
+ timeNote: "Why (optional)",
+ timeNotePlaceholder: "The document says the first half of 2023",
+ timeSave: "Save",
+ timeCancel: "Cancel",
+ timeSaved: "Interval corrected",
+ timeSavedClosed: (n: number) =>
+ `Interval corrected — ${n} open fact${n === 1 ? "" : "s"} closed to match`,
+ timeSavedConflicts: (n: number) =>
+ `Interval corrected — ${n} conflict${n === 1 ? "" : "s"} need a ruling in Review`,
ongoing: "now",
/* 必须跟 ongoing 看得出区别:混淆这两个正是迁移 0046 要修的东西——
原文说 "former CEO",界面却显示 now */
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index cdb702d1..c100afe1 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -760,8 +760,24 @@ export const zh: Strings = {
timelineEmpty: "还没有带日期的事实。",
lastConfirmed: (d: string) => `${d} 确认`,
correctedHint:
- "这个区间是被调和过程闭合的(自动接续或一次审阅决定),并非文档里逐字这么写。" +
- "被取代的那条断言仍留在台账里。",
+ "这个区间来自一次修正,并非文档里逐字这么写:自动接续、审阅决定,或有人手工改过。" +
+ "被取代的那条断言仍留在台账里——谁改的、何时改的见「变更」。",
+ editTime: "修正区间",
+ timeStart: "起点",
+ timeEnd: "终点",
+ timeEndOpen: "仍在持续",
+ timeEndUnknown: "已结束,日期不详",
+ timeEndDate: "结束于",
+ timeFormat: "2023、2023-06 或 2023-06-15",
+ timeBadDate: "请写成 2023、2023-06 或 2023-06-15。",
+ timeNote: "原因(选填)",
+ timeNotePlaceholder: "文档说的是 2023 年上半年",
+ timeSave: "保存",
+ timeCancel: "取消",
+ timeSaved: "区间已修正",
+ timeSavedClosed: (n: number) => `区间已修正——顺带闭合了 ${n} 条现行事实`,
+ timeSavedConflicts: (n: number) =>
+ `区间已修正——${n} 条冲突待在审阅里裁决`,
ongoing: "至今",
endedUnknown: "已结束(时间不详)",
stats: (n: number, e: number, active: number | null) =>
diff --git a/web/src/pages/EntityHistory.tsx b/web/src/pages/EntityHistory.tsx
index 1955b4df..2b242001 100644
--- a/web/src/pages/EntityHistory.tsx
+++ b/web/src/pages/EntityHistory.tsx
@@ -60,10 +60,18 @@ function objectText(e: EntityHistoryEvent): string {
return raw === undefined || raw === null ? "—" : String(raw);
}
-/** 这次变更对有效区间做了什么(记录轴上的事件,改的是有效轴上的边界) */
+/** 这次变更对有效区间做了什么(记录轴上的事件,改的是有效轴上的边界)。
+ *
+ * 修正行**不再假设修正就是闭合**。从前这里是「有 valid_to 就说 closed at,
+ * 否则什么都不说」,那在只有自动闭合的年代成立;人工改起点(302)产生的
+ * 修正行没有结束端,于是整条事件只剩一个图标,看不出改成了什么。
+ *
+ * 两个分支说的都是修正**之后**的状态,不声称原因——引擎接任、Review 裁决
+ * 和有人手改在这一行上分不出来,也不必分:谁改的写在下面那行的归因里。 */
function intervalNote(e: EntityHistoryEvent): string | null {
- if (e.kind === "corrected") {
- return e.valid_to ? S.graph.historyClosedAt(ym(e.valid_to)!) : null;
+ // 结束端存在 = 区间在此闭合。这句对三种来源都成立
+ if (e.kind === "corrected" && e.valid_to) {
+ return S.graph.historyClosedAt(ym(e.valid_to)!);
}
const from = ym(e.valid_from);
if (!from) return null;
diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsx
index 367c142d..e64b0552 100644
--- a/web/src/pages/Graph.tsx
+++ b/web/src/pages/Graph.tsx
@@ -62,7 +62,7 @@ import {
type ProofStep,
} from "../api";
import { S } from "../i18n";
-import { DangerConfirm, localDate } from "../ui";
+import { Button, DangerConfirm, Input, localDate } from "../ui";
import { usePopoverFlip } from "../ui/popoverFlip";
import { useKb, useKbId } from "../kb";
import { toast } from "../toast";
@@ -2141,6 +2141,26 @@ function fmtTime(iso: string | null, precision: string | null): string | null {
return `${y}-${m}-${day}`;
}
+/** 输入框里的日期 → 时间戳 + 精度。**写多少位就是多少精度**,与抽取端
+ * `parse_time` 同一个约定:2023 是「那一年」,2023-06 是「那个月」。
+ *
+ * 这也是不用日期选择器的理由——选择器逼人给出一个日,而「文档只说了上半年」
+ * 正是这个表单要修的那种错。回读比对是因为 `new Date("2023-13")` 不报错。 */
+function parseDateInput(
+ s: string,
+): { iso: string; precision: string } | null {
+ const t = s.trim();
+ const shape = /^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/.exec(t);
+ if (!shape) return null;
+ const [, y, m, d] = shape;
+ const iso = `${y}-${m ?? "01"}-${d ?? "01"}T00:00:00.000Z`;
+ const parsed = new Date(iso);
+ if (Number.isNaN(parsed.getTime())) return null;
+ // 溢出静默:2023-13-01 会变成 2024-01-01,2023-02-30 会变成 3 月
+ if (parsed.toISOString().slice(0, 10) !== iso.slice(0, 10)) return null;
+ return { iso, precision: d ? "day" : m ? "month" : "year" };
+}
+
function fmtInterval(f: EntityFact): string {
if (f.temporal === "eternal") return "";
const from = fmtTime(f.valid_from, f.valid_from_precision);
@@ -3224,9 +3244,10 @@ function TimelineRow({
const interval = fmtInterval(fact);
const isOpenEnded = !fact.valid_to;
const literal = fmtObjectValue(fact.object_value);
+ const [editing, setEditing] = useState(false);
return (
<div
- className={`rounded-lg transition-colors ${open ? "bg-white/[0.05]" : "hover:bg-white/[0.04]"} ${
+ className={`group rounded-lg transition-colors ${open ? "bg-white/[0.05]" : "hover:bg-white/[0.04]"} ${
fact.stale ? "opacity-55" : ""
}`}
title={fact.stale ? S.graph.staleFactHint : undefined}
@@ -3239,11 +3260,37 @@ function TimelineRow({
⟲
</span>
)}
- {isOpenEnded && fact.last_evidence_time && (
- <span className="ml-auto text-neutral-600">
- {S.graph.lastConfirmed(localDate(fact.last_evidence_time))}
+ <span className="ml-auto flex items-center gap-1.5">
+ {isOpenEnded && fact.last_evidence_time && (
+ <span className="text-neutral-600">
+ {S.graph.lastConfirmed(localDate(fact.last_evidence_time))}
+ </span>
+ )}
+ {/* 这一档只有断言事实:派生的区间是算出来的,走 Derived 那条路径,
+ 改了下一轮推理也会覆盖(服务端另有 derived_by_rule 的防线) */}
+ <span
+ role="button"
+ tabIndex={0}
+ title={S.graph.editTime}
+ aria-label={S.graph.editTime}
+ onClick={(ev) => {
+ ev.stopPropagation();
+ setEditing((v) => !v);
+ }}
+ onKeyDown={(ev) => {
+ if (ev.key === "Enter" || ev.key === " ") {
+ ev.preventDefault();
+ ev.stopPropagation();
+ setEditing((v) => !v);
+ }
+ }}
+ className={`cursor-pointer rounded p-0.5 transition-opacity hover:text-neutral-200 focus-visible:opacity-100 ${
+ editing ? "opacity-100" : "opacity-0 group-hover:opacity-100"
+ }`}
+ >
+ <Pencil size={10} />
</span>
- )}
+ </span>
</div>
<div className="mt-0.5 flex items-center gap-1.5 text-[13px] text-neutral-200">
<span className="text-neutral-500 text-xs">
@@ -3296,11 +3343,161 @@ function TimelineRow({
)}
</div>
</button>
+ {editing && (
+ <TimeEditor
+ kbId={kbId}
+ fact={fact}
+ onDone={() => setEditing(false)}
+ />
+ )}
{open && <EvidenceList kbId={kbId} fact={fact} />}
</div>
);
}
+/** 有效区间的人工修正表单(302)。
+ *
+ * 两端一起提交而不是逐端改:区间的两端互相定义,「清空结束端」与「这次不动
+ * 结束端」得能分辨。结束端的三个选项与账本里的三种写法一一对应,所以这里
+ * 没有「留空即至今」这种隐含约定——那正是 valid_to IS NULL 一度承载两个意思
+ * 的老毛病。 */
+function TimeEditor({
+ kbId,
+ fact,
+ onDone,
+}: {
+ kbId: string;
+ fact: EntityFact;
+ onDone: () => void;
+}) {
+ const qc = useQueryClient();
+ const [from, setFrom] = useState(
+ fmtTime(fact.valid_from, fact.valid_from_precision) ?? "",
+ );
+ const [to, setTo] = useState(
+ fmtTime(fact.valid_to, fact.valid_to_precision) ?? "",
+ );
+ const [endMode, setEndMode] = useState<"open" | "unknown" | "date">(
+ fact.valid_to
+ ? "date"
+ : fact.valid_to_precision === "unknown"
+ ? "unknown"
+ : "open",
+ );
+ const [note, setNote] = useState("");
+
+ const save = useMutation({
+ mutationFn: () => {
+ const f = from.trim() ? parseDateInput(from) : null;
+ if (from.trim() && !f) throw new Error(S.graph.timeBadDate);
+ const t = endMode === "date" ? parseDateInput(to) : null;
+ if (endMode === "date" && !t) throw new Error(S.graph.timeBadDate);
+ return api.updateFactTime(kbId, fact.id, {
+ valid_from: f?.iso ?? null,
+ valid_from_precision: f?.precision ?? null,
+ valid_to: t?.iso ?? null,
+ valid_to_precision:
+ endMode === "date"
+ ? (t?.precision ?? null)
+ : endMode === "unknown"
+ ? "unknown"
+ : null,
+ note: note.trim() || undefined,
+ });
+ },
+ onSuccess: (r) => {
+ // 对账的后果要说出来:改了起点可能顺手闭合了继任者的开放区间,
+ // 也可能撞出一条需要人裁的冲突。不说的话图会自己变而没人知道为什么
+ if (r.conflicts) toast.success(S.graph.timeSavedConflicts(r.conflicts));
+ else if (r.closed) toast.success(S.graph.timeSavedClosed(r.closed));
+ else toast.success(S.graph.timeSaved);
+ qc.invalidateQueries({ queryKey: ["entity", kbId] });
+ qc.invalidateQueries({ queryKey: ["graph"] });
+ qc.invalidateQueries({ queryKey: ["review", kbId] });
+ onDone();
+ },
+ onError: (e: Error) => toast.error(e.message),
+ });
+
+ return (
+ <div
+ className="mx-2 mb-1.5 rounded-lg border border-white/10 bg-white/[0.03] p-2.5"
+ onClick={(ev) => ev.stopPropagation()}
+ >
+ <div className="flex items-center gap-2">
+ <label className="w-11 shrink-0 text-[11px] text-neutral-500">
+ {S.graph.timeStart}
+ </label>
+ <Input
+ value={from}
+ onChange={(e) => setFrom(e.target.value)}
+ placeholder={S.graph.timeFormat}
+ className="u-num flex-1 !py-1 !text-xs"
+ />
+ </div>
+ <div className="mt-1.5 flex items-start gap-2">
+ <label className="w-11 shrink-0 pt-1 text-[11px] text-neutral-500">
+ {S.graph.timeEnd}
+ </label>
+ <div className="flex-1 space-y-1">
+ {(
+ [
+ ["open", S.graph.timeEndOpen],
+ ["unknown", S.graph.timeEndUnknown],
+ ["date", S.graph.timeEndDate],
+ ] as const
+ ).map(([mode, label]) => (
+ <label
+ key={mode}
+ className="flex items-center gap-1.5 text-[11.5px] text-neutral-300"
+ >
+ <input
+ type="radio"
+ name={`end-${fact.id}`}
+ checked={endMode === mode}
+ onChange={() => setEndMode(mode)}
+ className="accent-white/70"
+ />
+ {label}
+ {mode === "date" && endMode === "date" && (
+ <Input
+ value={to}
+ onChange={(e) => setTo(e.target.value)}
+ placeholder={S.graph.timeFormat}
+ className="u-num ml-1 flex-1 !py-0.5 !text-xs"
+ />
+ )}
+ </label>
+ ))}
+ </div>
+ </div>
+ <div className="mt-1.5 flex items-center gap-2">
+ <label className="w-11 shrink-0 text-[11px] text-neutral-500">
+ {S.graph.timeNote}
+ </label>
+ <Input
+ value={note}
+ onChange={(e) => setNote(e.target.value)}
+ placeholder={S.graph.timeNotePlaceholder}
+ className="flex-1 !py-1 !text-xs"
+ />
+ </div>
+ <div className="mt-2 flex justify-end gap-1.5">
+ <Button size="sm" variant="ghost" onClick={onDone}>
+ {S.graph.timeCancel}
+ </Button>
+ <Button
+ size="sm"
+ onClick={() => save.mutate()}
+ disabled={save.isPending}
+ >
+ {S.graph.timeSave}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
/** 字面值宾语的显示:属性 {value,unit} / 问数映射 {summary} / 其他 JSON 兜底。 */
function fmtObjectValue(v: Record<string, unknown> | null): string | null {
if (!v) return null;