Skip to content

World's first open-source enterprise world model.

The entity panel gains a History tab for the record-time axis (#37)

WaylandYanga48ba9c50897
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index 2e19b2c5..2dd47a86 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -419,6 +419,35 @@ pub struct EntityFact {
pub last_evidence_time: Option<DateTime<Utc>>,
}
+/// 实体的一次认知变更(记录时间轴上的事件,与 EntityFact 的有效时间轴正交)。
+///
+/// 账本 append-only,所以"我们曾经怎么认为"全部留存:一条事实行最多产出两个
+/// 事件——写入(asserted / corrected)与作废(rejected,仅当没有后继修正行时;
+/// 有后继的话这次死亡已由那条 corrected 解释,不重复记)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct EntityHistoryEvent {
+ pub fact_id: Uuid,
+ /// 事件发生的记录时刻(写入 = recorded_at,作废 = invalidated_at)
+ pub at: DateTime<Utc>,
+ /// asserted(首次断言)| corrected(区间被修正)| rejected(认知被推翻)
+ pub kind: String,
+ pub direction: String,
+ pub predicate_label: String,
+ pub other_name: Option<String>,
+ pub object_value: Option<serde_json::Value>,
+ pub valid_from: Option<DateTime<Utc>>,
+ pub valid_to: Option<DateTime<Utc>>,
+ pub valid_precision: String,
+ pub confidence: f32,
+ /// 人工操作者;NULL = 引擎自动(抽取写入 / 时态对账闭合)
+ pub actor_name: Option<String>,
+ /// 触发本次变更的审计动作(fact.close / conflict.close_old / fact.reject …)
+ pub action: Option<String>,
+ pub document_id: Option<Uuid>,
+ pub filename: Option<String>,
+ pub quote: Option<String>,
+}
+
/// 消解审核项的一侧实体摘要。
#[derive(Debug, Clone, Serialize)]
pub struct ReviewSide {
diff --git a/crates/utopia-server/src/api/graph_routes.rs b/crates/utopia-server/src/api/graph_routes.rs
index abc75206..1cd302e6 100644
--- a/crates/utopia-server/src/api/graph_routes.rs
+++ b/crates/utopia-server/src/api/graph_routes.rs
@@ -157,3 +157,31 @@ pub async fn rebuild(
"entities_removed": entities, "facts_removed": facts, "queued": ids.len()
})))
}
+
+#[derive(Deserialize)]
+pub struct HistoryQuery {
+ #[serde(default)]
+ pub page: i64,
+ #[serde(default = "default_history_per")]
+ pub per: i64,
+}
+
+fn default_history_per() -> i64 {
+ 30
+}
+
+/// 实体的认知变更历史(记录时间轴):我们何时这么认为、又何时改了主意。
+/// 与 entity_detail(有效时间轴,只看现行)互补。
+pub async fn entity_history(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, entity_id)): Path<(Uuid, Uuid)>,
+ Query(q): Query<HistoryQuery>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Viewer).await?;
+ let per = q.per.clamp(1, 200);
+ let page = q.page.max(0);
+ let (events, total) =
+ utopia_store::graph::entity_history(&state.pool, kb_id, entity_id, per, page * per).await?;
+ Ok(Json(json!({ "events": events, "total": total })))
+}
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index c0652e5a..d946c5da 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -164,6 +164,10 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
"/kbs/{id}/entities/{entity_id}",
get(graph_routes::entity_detail),
)
+ .route(
+ "/kbs/{id}/entities/{entity_id}/history",
+ get(graph_routes::entity_history),
+ )
.route(
"/kbs/{id}/facts/{fact_id}/evidence",
get(graph_routes::fact_evidence),
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index 788eb919..43001c12 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -3,8 +3,8 @@
use sqlx::PgPool;
use std::collections::HashSet;
use utopia_core::models::{
- ChunkFactView, EntityFact, EntityType, EvidenceView, FactReviewItem, GraphEdge, GraphNode,
- RelationType,
+ ChunkFactView, EntityFact, EntityHistoryEvent, EntityType, EvidenceView, FactReviewItem,
+ GraphEdge, GraphNode, RelationType,
};
use utopia_core::{AppError, AppResult};
use uuid::Uuid;
@@ -693,3 +693,92 @@ pub async fn purge_graph(pool: &PgPool, kb_id: Uuid) -> AppResult<(i64, i64)> {
tx.commit().await?;
Ok((entity_count, fact_count))
}
+
+/// 实体的认知变更历史(记录时间轴)。
+///
+/// 与 entity_detail 的根本差别:那里 `invalidated_at IS NULL`,只答"现在认为是什么";
+/// 这里不过滤,答"我们何时这么认为、又何时改了主意"。数据一直都在——账本
+/// append-only,修正是插新行 + 标旧行作废,从不覆盖。
+///
+/// 一行事实最多产出两个事件:写入(asserted / corrected)与作废(rejected)。
+/// 有后继修正行的作废不单独记——那次死亡已由后继那条 corrected 解释。
+///
+/// 归因:审计台账里 fact.close 的 target 是**被闭合的旧行**,而修正行是新插的另一行,
+/// 所以按 COALESCE(supersedes, id) 回查;冲突裁决的 target 是 conflict 行,再绕一跳。
+/// 查不到审计记录 = 引擎自动(抽取写入或时态对账),actor 为 NULL。
+pub async fn entity_history(
+ pool: &PgPool,
+ kb_id: Uuid,
+ entity_id: Uuid,
+ limit: i64,
+ offset: i64,
+) -> AppResult<(Vec<EntityHistoryEvent>, i64)> {
+ const EVENTS: &str = "
+ WITH ef AS (
+ SELECT f.*,
+ CASE WHEN f.subject_id = $2 THEN 'out' ELSE 'in' END AS direction,
+ CASE WHEN f.subject_id = $2 THEN f.object_id ELSE f.subject_id END AS other_id
+ FROM facts f
+ WHERE f.kb_id = $1 AND (f.subject_id = $2 OR f.object_id = $2)
+ ),
+ ev AS (
+ SELECT ef.*, ef.recorded_at AS at,
+ CASE WHEN ef.supersedes IS NULL THEN 'asserted' ELSE 'corrected' END AS kind
+ FROM ef
+ UNION ALL
+ SELECT ef.*, ef.invalidated_at AS at, 'rejected' AS kind
+ FROM ef
+ WHERE ef.invalidated_at IS NOT NULL
+ AND NOT EXISTS (SELECT 1 FROM facts s WHERE s.supersedes = ef.id)
+ )";
+ let rows: Vec<EntityHistoryEvent> = sqlx::query_as(&format!(
+ "{EVENTS}
+ SELECT ev.id AS fact_id, ev.at, ev.kind, ev.direction,
+ r.label AS predicate_label, o.canonical_name AS other_name,
+ ev.object_value, ev.valid_from, ev.valid_to, ev.valid_precision,
+ ev.confidence, act.actor_name, act.action,
+ src.document_id, src.filename, src.quote
+ FROM ev
+ JOIN relation_types r ON r.id = ev.predicate_id
+ LEFT JOIN entities o ON o.id = ev.other_id
+ LEFT JOIN LATERAL (
+ SELECT u.display_name AS actor_name, a.action
+ FROM audit_events a
+ LEFT JOIN users u ON u.id = a.actor_id
+ WHERE a.kb_id = $1
+ -- 断言由抽取写入,从来不是人的决定:归因只问修正与推翻这两类事件,
+ -- 否则后发生的人工裁决会被错安到当初那条断言头上
+ AND ev.kind <> 'asserted'
+ AND a.action = ANY(CASE ev.kind
+ WHEN 'corrected' THEN ARRAY['fact.close', 'conflict.close_old']
+ ELSE ARRAY['fact.reject', 'conflict.reject_new'] END)
+ AND (a.target_id = COALESCE(ev.supersedes, ev.id)
+ OR a.target_id IN (SELECT c.id FROM fact_conflicts c
+ WHERE c.old_fact_id = COALESCE(ev.supersedes, ev.id)
+ OR c.new_fact_id = ev.id))
+ ORDER BY a.created_at DESC LIMIT 1
+ ) act ON true
+ LEFT JOIN LATERAL (
+ SELECT d.id AS document_id, d.filename, fe.quote
+ FROM fact_evidence fe
+ JOIN chunks c ON c.id = fe.chunk_id
+ JOIN documents d ON d.id = c.document_id
+ WHERE fe.fact_id = ev.id
+ ORDER BY fe.doc_version DESC NULLS LAST LIMIT 1
+ ) src ON true
+ ORDER BY ev.at DESC, ev.id
+ LIMIT $3 OFFSET $4"
+ ))
+ .bind(kb_id)
+ .bind(entity_id)
+ .bind(limit)
+ .bind(offset)
+ .fetch_all(pool)
+ .await?;
+ let (total,): (i64,) = sqlx::query_as(&format!("{EVENTS} SELECT count(*) FROM ev"))
+ .bind(kb_id)
+ .bind(entity_id)
+ .fetch_one(pool)
+ .await?;
+ Ok((rows, total))
+}
diff --git a/web/src/api.ts b/web/src/api.ts
index d9c3d78d..4c5c66fd 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -301,6 +301,28 @@ export interface EntityFact {
last_evidence_time: string | null;
}
+/** 实体的一次认知变更(记录时间轴上的事件,与 EntityFact 的有效时间轴正交)。 */
+export interface EntityHistoryEvent {
+ fact_id: string;
+ /** 记录时刻:写入 = recorded_at,作废 = invalidated_at */
+ at: string;
+ kind: "asserted" | "corrected" | "rejected";
+ direction: "out" | "in";
+ predicate_label: string;
+ other_name: string | null;
+ object_value: Record<string, unknown> | null;
+ valid_from: string | null;
+ valid_to: string | null;
+ valid_precision: string;
+ confidence: number;
+ /** null = 引擎自动(抽取写入 / 时态对账闭合) */
+ actor_name: string | null;
+ action: string | null;
+ document_id: string | null;
+ filename: string | null;
+ quote: string | null;
+}
+
export interface Evidence {
quote: string | null;
chunk_id: string;
@@ -546,6 +568,11 @@ export const api = {
request<{ entity: GraphNode; facts: EntityFact[] }>(
`/api/v1/kbs/${kbId}/entities/${entityId}`,
),
+ /** 认知变更历史(记录时间轴):服务端分页 */
+ 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}`,
+ ),
factEvidence: (kbId: string, factId: string) =>
request<{ evidence: Evidence[] }>(`/api/v1/kbs/${kbId}/facts/${factId}/evidence`),
documentDetail: (id: string) =>
diff --git a/web/src/i18n.ts b/web/src/i18n.ts
index ef2d439b..014d7025 100644
--- a/web/src/i18n.ts
+++ b/web/src/i18n.ts
@@ -415,6 +415,20 @@ export const S = {
"the current content no longer states it. It may still be true; review it under Review.",
viewRelations: "Relations",
viewTimeline: "Timeline",
+ /* 第三视图:记录时间轴——不是"事情何时发生",而是"我们何时这么认为" */
+ viewHistory: "History",
+ historyHint: "How this entity's record changed — and who changed it.",
+ historyEmpty: "Nothing recorded for this entity yet.",
+ historyKind: {
+ asserted: "Recorded",
+ corrected: "Interval corrected",
+ rejected: "Withdrawn",
+ } as Record<string, string>,
+ historyEngine: "engine",
+ /* 有效区间的变化:修正后区间闭合到某个时点 */
+ historyClosedAt: (t: string) => `closed at ${t}`,
+ historyFrom: (t: string) => `from ${t}`,
+ historyOngoing: "open-ended",
historicalNote: (n: number) =>
`${n} past fact${n === 1 ? "" : "s"} not shown — see Timeline →`,
undated: "Undated",
diff --git a/web/src/pages/EntityHistory.tsx b/web/src/pages/EntityHistory.tsx
new file mode 100644
index 00000000..f180b663
--- /dev/null
+++ b/web/src/pages/EntityHistory.tsx
@@ -0,0 +1,122 @@
+/* 实体的认知变更历史(记录时间轴)。
+ 与同面板的 Timeline 视图正交:那条轴问"这件事在现实里何时成立",这条轴问
+ "我们何时这么认为、又何时改了主意"。数据来自 append-only 账本里那些被
+ entity_detail 用 invalidated_at IS NULL 滤掉的行。 */
+import { useEffect, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Link } from "@tanstack/react-router";
+import { FileText, PencilLine, Undo2 } from "lucide-react";
+import { api, type EntityHistoryEvent } from "../api";
+import { S } from "../i18n";
+import { Pager } from "../ui";
+
+const PER = 20;
+
+/** 事件类型 → 图标与色调(语义色只给"被推翻",其余保持中性) */
+const KIND_ICON = {
+ asserted: FileText,
+ corrected: PencilLine,
+ rejected: Undo2,
+} as const;
+
+const KIND_TONE: Record<string, string> = {
+ asserted: "text-neutral-500",
+ corrected: "text-[var(--u-warn)]",
+ rejected: "text-[var(--u-danger)]",
+};
+
+const ymd = (iso: string) => iso.slice(0, 10);
+const ym = (iso: string | null) => (iso ? iso.slice(0, 7) : null);
+
+/** 宾语:实体名优先,其次字面值(属性事实)的摘要/值 */
+function objectText(e: EntityHistoryEvent): string {
+ if (e.other_name) return e.other_name;
+ const v = e.object_value as { summary?: unknown; value?: unknown } | null;
+ const raw = v?.summary ?? v?.value;
+ return raw === undefined || raw === null ? "—" : String(raw);
+}
+
+/** 这次变更对有效区间做了什么(记录轴上的事件,改的是有效轴上的边界) */
+function intervalNote(e: EntityHistoryEvent): string | null {
+ if (e.kind === "corrected") {
+ return e.valid_to ? S.graph.historyClosedAt(ym(e.valid_to)!) : null;
+ }
+ const from = ym(e.valid_from);
+ if (!from) return null;
+ return e.valid_to
+ ? `${from} → ${ym(e.valid_to)}`
+ : `${S.graph.historyFrom(from)} · ${S.graph.historyOngoing}`;
+}
+
+function EventRow({ e }: { e: EntityHistoryEvent }) {
+ const Icon = KIND_ICON[e.kind] ?? FileText;
+ const note = intervalNote(e);
+ return (
+ <div className="flex gap-2.5 px-2 py-2">
+ <Icon size={13} className={`mt-0.5 shrink-0 ${KIND_TONE[e.kind] ?? ""}`} />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-baseline gap-1.5 flex-wrap">
+ <span className="text-[11px] font-medium text-neutral-300">
+ {S.graph.historyKind[e.kind] ?? e.kind}
+ </span>
+ {note && <span className="u-num text-[11px] text-neutral-500">{note}</span>}
+ </div>
+ <div className="mt-0.5 text-[12.5px] text-neutral-400 truncate">
+ <span className="text-neutral-500">
+ {e.direction === "in" ? "← " : ""}
+ {e.predicate_label}
+ {e.direction === "in" ? "" : " →"}
+ </span>{" "}
+ <span className="text-neutral-200">{objectText(e)}</span>
+ </div>
+ <div className="mt-0.5 flex items-center gap-1.5 text-[10.5px] text-neutral-600">
+ <span className="u-num">{ymd(e.at)}</span>
+ <span>·</span>
+ {/* 归因:人名,或引擎(抽取写入 / 时态对账自动闭合) */}
+ <span>{e.actor_name ?? S.graph.historyEngine}</span>
+ {e.filename && e.document_id && (
+ <>
+ <span>·</span>
+ <Link
+ to="/doc/$docId"
+ params={{ docId: e.document_id }}
+ search={{}}
+ className="truncate hover:text-neutral-300"
+ title={e.quote ?? e.filename}
+ >
+ {e.filename}
+ </Link>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export function EntityHistory({ kbId, entityId }: { kbId: string; entityId: string }) {
+ const [page, setPage] = useState(0);
+ useEffect(() => setPage(0), [entityId]);
+ const q = useQuery({
+ queryKey: ["entityHistory", kbId, entityId, page],
+ queryFn: () => api.entityHistory(kbId, entityId, page, PER),
+ });
+
+ const total = q.data?.total ?? 0;
+ if (q.isPending) return <p className="p-2 text-sm text-neutral-500">{S.nav.loading}</p>;
+ // 只有"一条都没有"才是空。记录轴上首次断言本身就是一次事件——
+ // "我们何时、从哪份文档得知这件事"是这条轴要回答的问题的一半
+ if (total === 0) return <p className="p-2 text-xs text-neutral-500">{S.graph.historyEmpty}</p>;
+
+ return (
+ <div>
+ <p className="px-2 pb-1.5 text-[11px] text-neutral-600">{S.graph.historyHint}</p>
+ <div className="divide-y divide-white/[0.06]">
+ {(q.data?.events ?? []).map((e) => (
+ <EventRow key={`${e.fact_id}-${e.kind}`} e={e} />
+ ))}
+ </div>
+ <Pager total={total} pageSize={PER} page={page} onPage={setPage} />
+ </div>
+ );
+}
diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsx
index 92d37583..5fd88783 100644
--- a/web/src/pages/Graph.tsx
+++ b/web/src/pages/Graph.tsx
@@ -8,6 +8,7 @@ import FA2Layout from "graphology-layout-forceatlas2/worker";
import Sigma from "sigma";
import { createNodeBorderProgram } from "@sigma/node-border";
import { NodeSquareShellProgram } from "./squareShellProgram";
+import { EntityHistory } from "./EntityHistory";
import {
ArrowLeft,
ArrowRight,
@@ -1177,8 +1178,9 @@ function EntityPanel({
queryFn: () => api.entityDetail(kbId, entityId),
});
const [openFact, setOpenFact] = useState<string | null>(null);
- // Relations = 按关系分组(查关系);Timeline = 按时间摊开(读故事)
- const [view, setView] = useState<"relations" | "timeline">("relations");
+ // Relations = 按关系分组(查关系);Timeline = 有效时间轴(事情何时成立);
+ // History = 记录时间轴(我们何时这么认为、又何时改了主意)
+ const [view, setView] = useState<"relations" | "timeline" | "history">("relations");
const e: GraphNode | undefined = detail.data?.entity;
@@ -1240,7 +1242,7 @@ function EntityPanel({
{/* 视图切换:Relations(分组)| Timeline(年表) */}
<div className="px-4 pt-2.5">
<div className="flex rounded-lg overflow-hidden border border-white/10 w-fit">
- {(["relations", "timeline"] as const).map((v) => (
+ {(["relations", "timeline", "history"] as const).map((v) => (
<button
key={v}
onClick={() => setView(v)}
@@ -1250,7 +1252,11 @@ function EntityPanel({
: "text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-300"
}`}
>
- {v === "relations" ? S.graph.viewRelations : S.graph.viewTimeline}
+ {v === "relations"
+ ? S.graph.viewRelations
+ : v === "timeline"
+ ? S.graph.viewTimeline
+ : S.graph.viewHistory}
</button>
))}
</div>
@@ -1296,7 +1302,8 @@ function EntityPanel({
onNavigate={onNavigate}
/>
)}
- {detail.data?.facts.length === 0 && (
+ {view === "history" && <EntityHistory kbId={kbId} entityId={entityId} />}
+ {view !== "history" && detail.data?.facts.length === 0 && (
<p className="text-sm text-neutral-500 p-2">{S.graph.noFacts}</p>
)}
</div>