World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Show saved property regression comparisons so people can check ontology edits against source statements. (#1184)
Virtue039bb5cde28587f
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rsindex 447de450..360bef0c 100644--- a/crates/utopia-core/src/models.rs+++ b/crates/utopia-core/src/models.rs@@ -333,6 +333,8 @@ pub struct ChunkFactView {/// 本体没认下这条关系时回落到原文说法;两者都拿不出时为 None(更早的历史数据长这样)pub predicate: Option<String>,pub inferred: bool,+ /// A live open statement can supply a human-confirmed regression expectation.+ pub is_open_statement: bool,pub object_id: Option<Uuid>,pub object: Option<String>,pub valid_from: Option<DateTime<Utc>>,diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rsindex c3627f07..a0211913 100644--- a/crates/utopia-server/src/api/mod.rs+++ b/crates/utopia-server/src/api/mod.rs@@ -289,7 +289,7 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {.route("/kbs/{id}/ontology", get(ontology_routes::get)).route("/kbs/{id}/ontology/regressions",- post(ontology_regression_routes::create),+ get(ontology_regression_routes::list).post(ontology_regression_routes::create),)// 业务规则(0021):读规则要 Viewer,写要 Editor.route(diff --git a/crates/utopia-server/src/api/ontology_regression_routes.rs b/crates/utopia-server/src/api/ontology_regression_routes.rsindex 1d933a72..976b81b3 100644--- a/crates/utopia-server/src/api/ontology_regression_routes.rs+++ b/crates/utopia-server/src/api/ontology_regression_routes.rs@@ -18,6 +18,15 @@ pub struct Create {pub direction: String,}+pub async fn list(+ State(state): State<AppState>,+ AuthUser(user): AuthUser,+ Path(kb): Path<Uuid>,+) -> ApiResult<Json<Value>> {+ require_kb(&state.pool, &user, kb, Role::Viewer).await?;+ Ok(Json(json!({"cases": cases::views(&state.pool, kb).await?})))+}+pub async fn create(State(state): State<AppState>,AuthUser(user): AuthUser,@@ -37,6 +46,7 @@ pub async fn create(},).await?;+ state.emit_review(kb);Ok((StatusCode::CREATED, Json(json!({"id": id}))))}diff --git a/crates/utopia-server/src/api/ontology_regression_routes_tests.rs b/crates/utopia-server/src/api/ontology_regression_routes_tests.rsindex 7d2805f1..6ba5da68 100644--- a/crates/utopia-server/src/api/ontology_regression_routes_tests.rs+++ b/crates/utopia-server/src/api/ontology_regression_routes_tests.rs@@ -150,3 +150,122 @@ async fn editor_adds_regression_case_while_viewer_and_cross_kb_statement_are_rej.await?;result}++#[tokio::test]+async fn viewer_reads_only_live_cases_in_the_authorized_kb() -> anyhow::Result<()> {+ let Some(url) = utopia_store::test_db::url() else {+ return Ok(());+ };+ let pool = PgPool::connect(&url).await?;+ utopia_store::db::migrate(&pool).await?;+ let (+ org,+ workspace,+ kb,+ foreign_kb,+ viewer,+ subject,+ foreign_subject,+ property,+ foreign_property,+ ) = (+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ );+ sqlx::raw_sql(&format!(+ r#"+ INSERT INTO organizations(id,name) VALUES ('{org}','case-list-test');+ INSERT INTO workspaces(id,org_id,name) VALUES ('{workspace}','{org}','case-list-test');+ INSERT INTO knowledge_bases(id,workspace_id,name,visibility) VALUES+ ('{kb}','{workspace}','case-list-test','restricted'),+ ('{foreign_kb}','{workspace}','foreign-case-list-test','restricted');+ INSERT INTO users(id,org_id,email,password_hash,display_name)+ VALUES ('{viewer}','{org}','{viewer}@example.test','unused','Viewer');+ INSERT INTO kb_members(kb_id,user_id,role) VALUES ('{kb}','{viewer}','viewer');+ INSERT INTO entities(id,kb_id,canonical_name) VALUES+ ('{subject}','{kb}','Alice'), ('{foreign_subject}','{foreign_kb}','Foreign');+ INSERT INTO relation_types(id,kb_id,key,label,kind) VALUES+ ('{property}','{kb}','knows','knows','relation'),+ ('{foreign_property}','{foreign_kb}','foreign','foreign','relation');+ "#+ ))+ .execute(&pool)+ .await?;+ let result = async {+ let mut statement = Uuid::nil();+ for (case_kb, entity, expected) in [+ (kb, subject, property),+ (foreign_kb, foreign_subject, foreign_property),+ ] {+ let id = graph::insert_open_statement(+ &pool, case_kb, entity, "knows", graph::FactObject::Entity(entity), None, 1.0,+ ).await?.0;+ utopia_store::ontology_regressions::add(&pool, case_kb,+ utopia_store::ontology_regressions::NewCase {+ statement_id: id, expected_property_id: expected,+ expected_direction: "forward", created_by: viewer, origin: "person",+ },+ ).await?;+ if case_kb == kb {+ statement = id;+ }+ }+ let cached = json!({"passed": true, "human_bound": true, "actual_property_id": property,+ "actual_direction": "forward", "status": "bound"});+ sqlx::query("UPDATE ontology_regression_cases SET last_result=$2,last_checked_at=now() WHERE kb_id=$1")+ .bind(kb).bind(&cached).execute(&pool).await?;+ let checked_at: chrono::DateTime<chrono::Utc> = sqlx::query_scalar(+ "SELECT last_checked_at FROM ontology_regression_cases WHERE kb_id=$1",+ ).bind(kb).fetch_one(&pool).await?;+ let directory = tempfile::tempdir()?;+ let config = utopia_core::config::AppConfig {+ data_dir: directory.path().to_string_lossy().into_owned(), ..Default::default()+ };+ let search = Arc::new(utopia_search::SearchIndex::open(&directory.path().join("search"))?);+ let state = crate::state::AppState::new(pool.clone(), &config, search, "test-only".into());+ let token = crate::auth::issue_token(&state, viewer)?;+ let app = crate::api::router(state, &config);+ for (requested_kb, expected) in [(kb, StatusCode::OK), (foreign_kb, StatusCode::NOT_FOUND)] {+ let response = app.clone().oneshot(Request::builder()+ .uri(format!("/api/v1/kbs/{requested_kb}/ontology/regressions"))+ .header("authorization", format!("Bearer {token}"))+ .body(Body::empty())?).await?;+ anyhow::ensure!(response.status() == expected);+ if requested_kb == kb {+ let body: serde_json::Value = serde_json::from_slice(&to_bytes(response.into_body(), 65536).await?)?;+ let cases = body["cases"].as_array().unwrap();+ anyhow::ensure!(cases.len() == 1);+ let case = &cases[0];+ anyhow::ensure!(case["statement_id"] == json!(statement) && case["kb_id"] == json!(kb));+ anyhow::ensure!(case["subject_label"] == "Alice" && case["object_label"] == "Alice" && case["phrase"] == "knows");+ anyhow::ensure!(case["expected_property_key"] == "knows" && case["actual_property_label"] == "knows" && case["created_by_label"] == "Viewer");+ anyhow::ensure!(case["last_result"] == cached && case["last_checked_at"] == json!(checked_at));+ }+ }+ let unchanged: chrono::DateTime<chrono::Utc> = sqlx::query_scalar(+ "SELECT last_checked_at FROM ontology_regression_cases WHERE kb_id=$1",+ ).bind(kb).fetch_one(&pool).await?;+ anyhow::ensure!(unchanged == checked_at);+ sqlx::query("UPDATE facts SET invalidated_at=now() WHERE id=$1").bind(statement).execute(&pool).await?;+ let response = app.oneshot(Request::builder()+ .uri(format!("/api/v1/kbs/{kb}/ontology/regressions"))+ .header("authorization", format!("Bearer {token}"))+ .body(Body::empty())?).await?;+ anyhow::ensure!(response.status() == StatusCode::OK);+ let body: serde_json::Value = serde_json::from_slice(&to_bytes(response.into_body(), 65536).await?)?;+ anyhow::ensure!(body["cases"] == json!([]));+ anyhow::Ok(())+ }.await;+ sqlx::query("DELETE FROM organizations WHERE id=$1")+ .bind(org)+ .execute(&pool)+ .await?;+ result+}diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rsindex 7425fad2..f10cb230 100644--- a/crates/utopia-store/src/graph.rs+++ b/crates/utopia-store/src/graph.rs@@ -2071,8 +2071,11 @@ pub async fn document_extractions(let rows: Vec<ChunkFactView> = sqlx::query_as("SELECT fe.chunk_id, f.id AS fact_id,f.subject_id, s.canonical_name AS subject,- COALESCE(r.label, fact_surface_predicate(f.id)) AS predicate,+ -- 开放陈述的短语在 facts 本身,不依赖旧证据的 proposed_predicate。+ CASE WHEN f.layer='open' THEN f.phrase+ ELSE COALESCE(r.label, fact_surface_predicate(f.id)) END AS predicate,r.id IS NULL AS inferred,+ (f.layer='open' AND nullif(btrim(f.phrase),'') IS NOT NULL) AS is_open_statement,-- 宾语是一样东西就用它的名字,是字面值(名字、金额、百分比)就用那个值。-- 只取 canonical_name 的话,每一条值宾语的陈述在阅读页右栏都是主语加短语、-- 后面空着一片——「Hugging Face, Inc. known as」后面什么都没有diff --git a/crates/utopia-store/src/ontology_regressions.rs b/crates/utopia-store/src/ontology_regressions.rsindex 8dbb1bdd..d546e625 100644--- a/crates/utopia-store/src/ontology_regressions.rs+++ b/crates/utopia-store/src/ontology_regressions.rs@@ -29,6 +29,48 @@ pub struct NewCase<'a> {pub origin: &'a str,}+#[derive(Debug, Serialize, sqlx::FromRow)]+pub struct CaseView {+ #[serde(flatten)]+ #[sqlx(flatten)]+ pub case: Case,+ pub subject_id: Uuid,+ pub subject_label: String,+ pub phrase: String,+ pub object_id: Option<Uuid>,+ pub object_label: Option<String>,+ pub object_value: Option<serde_json::Value>,+ pub expected_property_label: String,+ pub expected_property_key: String,+ pub actual_property_label: Option<String>,+ pub actual_property_key: Option<String>,+ pub created_by_label: Option<String>,+}++/// The workbench reads saved results and live source labels without evaluating or writing.+pub async fn views(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<CaseView>> {+ Ok(sqlx::query_as(+ "SELECT c.*, f.subject_id, s.canonical_name AS subject_label, f.phrase,+ f.object_id, o.canonical_name AS object_label, f.object_value,+ expected.label AS expected_property_label, expected.key AS expected_property_key,+ actual.label AS actual_property_label, actual.key AS actual_property_key,+ u.display_name AS created_by_label+ FROM ontology_regression_cases c+ JOIN facts f ON f.kb_id=c.kb_id AND f.id=c.statement_id+ JOIN entities s ON s.kb_id=f.kb_id AND s.id=f.subject_id+ LEFT JOIN entities o ON o.kb_id=f.kb_id AND o.id=f.object_id+ JOIN relation_types expected ON expected.kb_id=c.kb_id AND expected.id=c.expected_property_id+ LEFT JOIN relation_types actual ON actual.kb_id=c.kb_id+ AND actual.id=(c.last_result->>'actual_property_id')::uuid+ LEFT JOIN users u ON u.id=c.created_by+ WHERE c.kb_id=$1 AND f.layer='open' AND f.invalidated_at IS NULL+ ORDER BY c.created_at DESC,c.id",+ )+ .bind(kb_id)+ .fetch_all(pool)+ .await?)+}+pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Case>> {Ok(sqlx::query_as("SELECT c.* FROM ontology_regression_cases c WHERE c.kb_id=$1diff --git a/crates/utopia-store/tests/store/no_predicate_still_shows.rs b/crates/utopia-store/tests/store/no_predicate_still_shows.rsindex 60870ecf..49086946 100644--- a/crates/utopia-store/tests/store/no_predicate_still_shows.rs+++ b/crates/utopia-store/tests/store/no_predicate_still_shows.rs@@ -216,6 +216,9 @@ async fn a_fact_without_a_predicate_is_still_visible_everywhere() -> anyhow::Res"文档页看不见没有说法的事实");+ assert!(chunk_facts.iter().all(|c| !c.is_open_statement),+ "历史投影即便有原文说法,也不能用投影 ID 添加陈述案例");+// 宾语是字面值的那条:阅读页右栏只认 canonical_name 的时候,它在界面上是// 主语加短语、后面空着一片(「Hugging Face, Inc. known as」)let valued = Uuid::now_v7();@@ -240,6 +243,8 @@ async fn a_fact_without_a_predicate_is_still_visible_everywhere() -> anyhow::Reslet v = chunk_facts.iter().find(|c| c.fact_id == valued).unwrap();assert_eq!(v.object.as_deref(), Some("Acme Inc."), "值宾语在文档页是空的");assert!(v.object_id.is_none(), "字面值没有实体可跳");+ assert!(v.is_open_statement, "有短语的原始陈述可添加案例");+ assert_eq!(v.predicate.as_deref(), Some("known as"), "确认案例要显示原文短语");// 5. 实体历史(外层 FROM 是 CTE,别名写错会直接报 missing FROM-clause)let (hist, _) = utopia_store::graph::entity_history(&pool, f.kb, f.subject, 50, 0).await?;diff --git a/docs/decisions/0061-the-ontology-is-proposed-from-the-open-graph-and-judged-by-its-questions.md b/docs/decisions/0061-the-ontology-is-proposed-from-the-open-graph-and-judged-by-its-questions.mdindex 661d27ab..843db7f3 100644--- a/docs/decisions/0061-the-ontology-is-proposed-from-the-open-graph-and-judged-by-its-questions.md+++ b/docs/decisions/0061-the-ontology-is-proposed-from-the-open-graph-and-judged-by-its-questions.md@@ -73,6 +73,25 @@ reported at its original time. These cases observe alignment without another evamodel call, evaluation job, or version identity. They are not a semantic accuracybenchmark. The workbench view follows in a second PR.+## Cut 2 workbench boundary — 2026-10-10++The [second slice welcomed on merging #1178](https://github.com/deeplethe/utopia/pull/1178#pullrequestreview-5477806071)+shows a base's live statement cases in the ontology workbench. A Viewer reads+`GET /api/v1/kbs/{kb_id}/ontology/regressions`: source and property labels,+expected and actual direction, the latest stored comparison and its check time,+and origin and attribution. Expanding a case reads the existing evidence route+and links back to the document. A preserved human binding is called a human+decision, not an independent match; the binding's decision time remains distinct+from the comparison's check time.++An Editor uses “Make a case” beside an open statement in the document viewer,+chooses the expected property without a model answer preselected, and confirms+its direction through the existing POST. Typed projections and legacy facts do+not supply statement IDs. Literal statements offer forward attributes only.+The list refreshes through the existing graph and review events; refreshing reads+saved results and never starts alignment. No evaluator, job, schema migration,+or version identity is added.+## Status historyThe status line as it stood on 2026-09-27, before status lines were cut to one line:diff --git a/web/src/api.ts b/web/src/api.tsindex 614de938..a821a443 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -359,6 +359,8 @@ export interface SyncRun {export interface ChunkFact {chunk_id: string;fact_id: string;+ /** A live open-layer statement with a usable phrase, eligible for a regression case. */+ is_open_statement: boolean;subject_id: string;subject: string;/** 本体没认下这条关系时是原文说法;两者都拿不出时为 null */@@ -1174,6 +1176,38 @@ export interface EntityHistoryEvent {to_type_label: string | null;}+/** Stored comparisons against the regular phrase-alignment decisions. */+export interface OntologyRegressionCase {+ id: string;+ kb_id: string;+ statement_id: string;+ expected_property_id: string;+ expected_direction: "forward" | "reverse";+ created_by: string | null;+ created_at: string;+ origin: "adoption" | "person";+ last_checked_at: string | null;+ last_result: {+ passed: boolean;+ human_bound: boolean;+ actual_property_id: string | null;+ actual_direction: "forward" | "reverse" | null;+ status: "bound" | "none" | "undecided";+ decided_at: string | null;+ } | null;+ subject_id: string;+ subject_label: string;+ phrase: string;+ object_id: string | null;+ object_label: string | null;+ object_value: Record<string, unknown> | null;+ expected_property_label: string;+ expected_property_key: string;+ actual_property_label: string | null;+ actual_property_key: string | null;+ created_by_label: string | null;+}+export interface Evidence {/** 模型在这一块里实际用的谓词说法。本体外的谓词不落到关系上,界面显示的就是这里 */proposed_predicate: string | null;@@ -2207,6 +2241,22 @@ export const api = {entity_types: EntityTypeView[];relation_types: RelationTypeView[];}>(`/api/v1/kbs/${kbId}/ontology`),+ ontologyRegressions: (kbId: string) =>+ request<{ cases: OntologyRegressionCase[] }>(+ `/api/v1/kbs/${kbId}/ontology/regressions`,+ ),+ addOntologyRegression: (+ kbId: string,+ body: {+ statement_id: string;+ relation_type_id: string;+ direction: "forward" | "reverse";+ },+ ) =>+ request<{ id: string }>(`/api/v1/kbs/${kbId}/ontology/regressions`, {+ method: "POST",+ body: JSON.stringify(body),+ }),createEntityType: (kbId: string, body: Record<string, unknown>) =>request<{ id: string }>(`/api/v1/kbs/${kbId}/ontology/entity-types`, {method: "POST",diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex 83c780f9..6676918f 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -1344,6 +1344,40 @@ export const en = {`Saved. ${n} waiting ${n === 1 ? "file is" : "files are"} being read.`,},ontology: {+ casesShort: "Regression cases",+ casesTitle: "Property regression cases",+ casesHint: "The last recorded comparisons of expected properties with alignment decisions. Refresh reads these results; property edits trigger the regular alignment process.",+ casesEmpty: "No cases yet. Adopt a property proposal or add an open statement from a document.",+ caseStatement: "Statement",+ caseExpected: "Expected",+ caseActual: "Actual",+ caseResult: "Result",+ caseChecked: "Last checked",+ caseOrigin: "Added by",+ casePassed: "Matches",+ caseMismatch: "Mismatch",+ caseNotChecked: "Not checked",+ caseUnbound: "No property bound",+ caseUndecided: "Undecided",+ caseUnavailableProperty: "Bound property no longer available",+ caseDecidedAt: "Decision made",+ caseNoProperties: "Create a suitable property in Ontology before adding this case.",+ caseHumanBound: "Human decision retained",+ caseHumanHint: "A manual binding is preserved and counts as passing. This is not an independent model check.",+ caseAdoption: "Proposal adoption",+ casePerson: "Manual case",+ caseUnknownCreator: "Former member",+ caseEvidence: "Show source evidence",+ caseHideEvidence: "Hide source evidence",+ caseMake: "Add regression case",+ caseAddTitle: "Add a property regression case",+ caseAddHint: "Save the property and direction this open statement should bind to. Its existing alignment decision will be compared with this expectation.",+ caseExpectedProperty: "Expected property",+ caseDirection: "Direction",+ caseForward: "Subject → Object",+ caseReverse: "Object → Subject",+ caseAdded: "Regression case added",+ caseAdd: "Add case",title: "Ontology",hint: "Classes & properties",tabClasses: "Classes",diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex c804902d..cc493763 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -1191,6 +1191,40 @@ export const zh: Strings = {savedRequeued: (n: number) => `已保存。${n} 个等待中的文件开始读取。`,},ontology: {+ casesShort: "回归案例",+ casesTitle: "属性回归案例",+ casesHint: "显示最近记录的预期属性与对齐决定的对比结果。刷新只读取这些结果;修改属性后由现有对齐流程更新。",+ casesEmpty: "还没有案例。采纳属性提案,或从文档中添加一条开放陈述。",+ caseStatement: "陈述",+ caseExpected: "预期",+ caseActual: "实际",+ caseResult: "结果",+ caseChecked: "最近检查",+ caseOrigin: "添加来源",+ casePassed: "一致",+ caseMismatch: "不一致",+ caseNotChecked: "未检查",+ caseUnbound: "未绑定属性",+ caseUndecided: "未决定",+ caseUnavailableProperty: "原绑定属性已不可用",+ caseDecidedAt: "决定时间",+ caseNoProperties: "请先在本体中创建适合的属性,再添加此案例。",+ caseHumanBound: "保留人工决定",+ caseHumanHint: "人工绑定予以保留,并按通过计入。这不代表一次独立的模型检查。",+ caseAdoption: "采纳提案",+ casePerson: "手动添加",+ caseUnknownCreator: "已离开的成员",+ caseEvidence: "展开原文证据",+ caseHideEvidence: "收起原文证据",+ caseMake: "添加回归案例",+ caseAddTitle: "添加属性回归案例",+ caseAddHint: "保存这条开放陈述应绑定的属性及方向,再将已有的对齐决定与此预期比较。",+ caseExpectedProperty: "预期属性",+ caseDirection: "方向",+ caseForward: "主语 → 宾语",+ caseReverse: "宾语 → 主语",+ caseAdded: "回归案例已添加",+ caseAdd: "添加案例",title: "本体",hint: "类与属性",tabClasses: "类",diff --git a/web/src/pages/AddOntologyRegressionDialog.tsx b/web/src/pages/AddOntologyRegressionDialog.tsxnew file mode 100644index 00000000..a07a6088--- /dev/null+++ b/web/src/pages/AddOntologyRegressionDialog.tsx@@ -0,0 +1,79 @@+/** A person writes the expectation; the current model binding is never preselected. */+import { useState } from "react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { api } from "../api";+import { S } from "../i18n";+import { toast } from "../toast";+import { Field, FormDialog, Loading, SearchSelect, Segmented } from "../ui";++export function AddOntologyRegressionDialog({+ kbId, statementId, statement, isValue, onClose,+}: {+ kbId: string;+ statementId: string;+ statement: string;+ isValue: boolean;+ onClose: () => void;+}) {+ const qc = useQueryClient();+ const ontology = useQuery({+ queryKey: ["ontology", kbId],+ queryFn: () => api.ontology(kbId),+ });+ const [property, setProperty] = useState("");+ const [direction, setDirection] = useState<"forward" | "reverse">("forward");+ const options = (ontology.data?.relation_types ?? [])+ .filter((p) => p.kind === (isValue ? "attribute" : "relation"))+ .map((p) => ({ value: p.id, label: p.label, hint: p.key }));+ const add = useMutation({+ mutationFn: () => api.addOntologyRegression(kbId, {+ statement_id: statementId,+ relation_type_id: property,+ direction: isValue ? "forward" : direction,+ }),+ onSuccess: () => {+ qc.invalidateQueries({ queryKey: ["ontologyRegressions", kbId] });+ toast.success(S.ontology.caseAdded);+ onClose();+ },+ onError: (e) => toast.error((e as Error).message),+ });+ return (+ <FormDialog+ title={S.ontology.caseAddTitle}+ description={S.ontology.caseAddHint}+ closeLabel={S.ui.close}+ saveLabel={S.ontology.caseAdd}+ cancelLabel={S.ontology.cancel}+ canSave={options.some((p) => p.value === property)}+ busy={add.isPending}+ onSave={() => add.mutate()}+ onCancel={onClose}+ >+ <p className="mb-4 text-body text-ink">{statement}</p>+ {ontology.isError ? (+ <p role="alert" className="text-small text-danger">{(ontology.error as Error).message}</p>+ ) : ontology.isPending ? (+ <Loading>{S.nav.loading}</Loading>+ ) : options.length === 0 ? (+ <p className="text-small text-ink-2">{S.ontology.caseNoProperties}</p>+ ) : (+ <div className="space-y-4">+ <Field label={S.ontology.caseExpectedProperty}>+ <SearchSelect value={property} options={options} onChange={setProperty} />+ </Field>+ <Field label={S.ontology.caseDirection}>+ <Segmented+ value={direction}+ onChange={setDirection}+ options={[+ { value: "forward" as const, label: S.ontology.caseForward },+ ...(!isValue ? [{ value: "reverse" as const, label: S.ontology.caseReverse }] : []),+ ]}+ />+ </Field>+ </div>+ )}+ </FormDialog>+ );+}diff --git a/web/src/pages/DocViewer.tsx b/web/src/pages/DocViewer.tsxindex 4df88e18..5a6649fd 100644--- a/web/src/pages/DocViewer.tsx+++ b/web/src/pages/DocViewer.tsx@@ -6,7 +6,8 @@ import { S } from "../i18n";import { useKbId } from "../kb";import { originHint, originLabel } from "../origin";import { fmtTime } from "../time";-import { GroupLabel, PageHeader, Pager, pageSlice } from "../ui";+import { GroupLabel, LinkButton, PageHeader, Pager, pageSlice } from "../ui";+import { AddOntologyRegressionDialog } from "./AddOntologyRegressionDialog";import { QuotedText } from "../ui/citation";import { SourcesRail } from "./SourcesRail";@@ -21,6 +22,7 @@ function factRange(f: ChunkFact): string | null {export function DocViewer() {const kbId = useKbId();+ const [caseStatement, setCaseStatement] = useState<ChunkFact | null>(null);const { docId } = useParams({ from: "/app/kb/$kbId/doc/$docId" });const { chunk, quote } = useSearch({ from: "/app/kb/$kbId/doc/$docId" });const navigate = useNavigate();@@ -29,6 +31,13 @@ export function DocViewer() {queryKey: ["docDetail", docId],queryFn: () => api.documentDetail(docId),});+ // 角色仅详情接口返回;复用 KbScope 的键,不能从工作区 KB 列表判断写权限。+ const roleKbId = detail.data?.document.kb_id;+ const role = useQuery({+ queryKey: ["kbOne", roleKbId],+ queryFn: () => api.kbDetail(roleKbId!),+ enabled: !!roleKbId,+ });// 反向证据链:各分块抽出的事实(一次取整文档,按 chunk 分组)const extractions = useQuery({queryKey: ["docExtractions", docId],@@ -46,6 +55,7 @@ export function DocViewer() {// null = 自动定位:有引用跳转时翻到目标分块所在页const [page, setPage] = useState<number | null>(null);useEffect(() => setPage(null), [chunk, docId]);+ useEffect(() => setCaseStatement(null), [docId]);const highlightRef = useRef<HTMLDivElement>(null);// 引用跳转:滚动到目标分块点亮一下,稍候淡出恢复普通状态(不常驻高亮)@@ -190,6 +200,12 @@ export function DocViewer() {)}</div>{range && <div className="u-num text-fine text-ink-2">{range}</div>}+ {f.is_open_statement &&+ ["editor", "admin", "owner"].includes(role.data?.my_role ?? "") && (+ <LinkButton className="mt-1 text-fine" onClick={() => setCaseStatement(f)}>+ {S.ontology.caseMake}+ </LinkButton>+ )}</div>);})}@@ -203,6 +219,16 @@ export function DocViewer() {<Pager total={chunks.length} pageSize={DOC_PAGE} page={safePage} onPage={setPage} /></div></div>+ {caseStatement && (+ <AddOntologyRegressionDialog+ key={caseStatement.fact_id}+ kbId={doc.kb_id}+ statementId={caseStatement.fact_id}+ statement={`${caseStatement.subject} ${caseStatement.predicate ?? ""} ${caseStatement.object ?? ""}`}+ isValue={!caseStatement.object_id}+ onClose={() => setCaseStatement(null)}+ />+ )}</div>);}diff --git a/web/src/pages/Ontology.tsx b/web/src/pages/Ontology.tsxindex 0e096282..6bd6876c 100644--- a/web/src/pages/Ontology.tsx+++ b/web/src/pages/Ontology.tsx@@ -9,6 +9,7 @@ import {ArrowLeft,ArrowLeftRight,ArrowRight,+ CheckCheck,ChevronRight,Inbox,Link2,@@ -43,6 +44,7 @@ import { useKb } from "../kb";import { toast } from "../toast";import { OntologySchemaGraph, type SchemaSelection } from "./OntologySchemaGraph";import { RulesPanel } from "./RulesPanel";+import { OntologyRegressionsPanel } from "./OntologyRegressionsPanel";import {AttributeDialog,ClassDialog,@@ -103,6 +105,7 @@ type Sel =| { kind: "class"; id: string }| { kind: "relation"; id: string }| { kind: "misses" }+ | { kind: "regressions" }| { kind: "uniqueness" }// 业务规则那一页。**focusId 是从模式图上点一条规则边过来的**——那一行高亮,// 不必在一页规则里再找一遍@@ -162,7 +165,8 @@ export function Ontology() {sel?.kind === "refine" ||sel?.kind === "uniqueness" ||sel?.kind === "rules" ||- sel?.kind === "misses";+ sel?.kind === "misses" ||+ sel?.kind === "regressions";// 模式图详情面板停在哪一段。**跨选中保留**:在实例上挨个类看下去,// 是一种真实的读法,每换一个类就被弹回定义页会打断它const [panelTab, setPanelTab] = useState<@@ -456,6 +460,13 @@ export function Ontology() {>{S.ontology.uniquenessShort}</RailItem>+ <RailItem+ active={sel?.kind === "regressions"}+ icon={<CheckCheck size={14} />}+ onClick={() => setSel({ kind: "regressions" })}+ >+ {S.ontology.casesShort}+ </RailItem>{/* 底部常驻:抽取未匹配信号(有存量时带数量徽标) */}<RailItemactive={sel?.kind === "misses"}@@ -487,7 +498,8 @@ export function Ontology() {sel?.kind === "refine" ||sel?.kind === "misses" ||sel?.kind === "uniqueness" ||- sel?.kind === "rules" ? (+ sel?.kind === "rules" ||+ sel?.kind === "regressions" ? (<div className="flex-1 min-w-0 overflow-y-auto u-scroll px-8 py-6"><div>{sel.kind === "import" ? (@@ -512,6 +524,8 @@ export function Ontology() {onError={onError}/></div>+ ) : sel.kind === "regressions" ? (+ <OntologyRegressionsPanel kbId={kb.id} />) : sel.kind === "rules" ? (<div><RulesPaneldiff --git a/web/src/pages/OntologyRegressionsPanel.test.ts b/web/src/pages/OntologyRegressionsPanel.test.tsnew file mode 100644index 00000000..d8622a82--- /dev/null+++ b/web/src/pages/OntologyRegressionsPanel.test.ts@@ -0,0 +1,65 @@+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { describe, expect, it, vi } from "vitest";+import { api, type OntologyRegressionCase } from "../api";+import { S } from "../i18n";+import { OntologyRegressionsPanel } from "./OntologyRegressionsPanel";++const base: OntologyRegressionCase = {+ id: "case", kb_id: "kb", statement_id: "statement",+ expected_property_id: "works-for", expected_direction: "forward",+ created_by: "actor", created_at: "2026-10-10T00:00:00Z", origin: "adoption",+ last_checked_at: "2026-10-10T01:00:00Z",+ last_result: {+ passed: true, human_bound: false, actual_property_id: "works-for",+ actual_direction: "forward", status: "bound", decided_at: "2026-10-10T01:00:00Z",+ },+ subject_id: "person", subject_label: "Alice", phrase: "works at",+ object_id: "company", object_label: "Acme", object_value: null,+ expected_property_label: "Works for", expected_property_key: "works_for",+ actual_property_label: "Works for", actual_property_key: "works_for",+ created_by_label: "Reviewer",+};++function render(cases: OntologyRegressionCase[]) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ client.setQueryData(["ontologyRegressions", "kb"], { cases });+ return renderToStaticMarkup(createElement(QueryClientProvider, {+ client,+ children: createElement(OntologyRegressionsPanel, { kbId: "kb" }),+ }));+}++describe("stored property regression comparisons", () => {+ it("distinguishes mismatches, matches and missing checks without requesting evidence", () => {+ const evidence = vi.spyOn(api, "factEvidence");+ try {+ const html = render([+ base,+ { ...base, id: "wrong-direction", last_result: { ...base.last_result!, passed: false, actual_direction: "reverse" } },+ { ...base, id: "pending", last_result: null, last_checked_at: null, actual_property_label: null },+ ]);+ for (const text of [S.ontology.casePassed, S.ontology.caseMismatch, S.ontology.caseNotChecked, S.ontology.caseForward, S.ontology.caseReverse, "Alice", "Acme", "Reviewer"]) {+ expect(html).toContain(text);+ }+ expect(evidence).not.toHaveBeenCalled();+ } finally {+ evidence.mockRestore();+ }+ });++ it("keeps a recorded binding distinct from an undecided result when its property is unavailable", () => {+ const html = render([{ ...base, actual_property_label: null, actual_property_key: null }]);+ expect(html).toContain(S.ontology.caseUnavailableProperty);+ expect(html).toContain(S.ontology.caseDecidedAt);+ expect(html).not.toContain(S.ontology.caseUndecided);+ });++ it("calls a preserved manual binding a human decision instead of an independent match", () => {+ const html = render([{ ...base, last_result: { ...base.last_result!, human_bound: true } }]);+ expect(html).toContain(S.ontology.caseHumanBound);+ expect(html).toContain(S.ontology.caseHumanHint);+ expect(html).not.toContain(`>${S.ontology.casePassed}<`);+ });+});diff --git a/web/src/pages/OntologyRegressionsPanel.tsx b/web/src/pages/OntologyRegressionsPanel.tsxnew file mode 100644index 00000000..8a73aa8b--- /dev/null+++ b/web/src/pages/OntologyRegressionsPanel.tsx@@ -0,0 +1,183 @@+/** Read the comparisons recorded by regular alignment; refreshing never runs a model. */+import { Fragment, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { Link } from "@tanstack/react-router";+import { ChevronDown, ChevronRight, ExternalLink, RefreshCw } from "lucide-react";+import { api, type OntologyRegressionCase } from "../api";+import { S } from "../i18n";+import { fmtObjectValue } from "../objectValue";+import {+ Button,+ IconButton,+ Loading,+ PageHeader,+ Status,+ Table,+ TBody,+ Td,+ Th,+ THead,+ Tr,+ localDateTime,+} from "../ui";++const directionText = (direction: "forward" | "reverse") =>+ direction === "reverse" ? S.ontology.caseReverse : S.ontology.caseForward;++export function OntologyRegressionsPanel({ kbId }: { kbId: string }) {+ const cases = useQuery({+ queryKey: ["ontologyRegressions", kbId],+ queryFn: () => api.ontologyRegressions(kbId),+ });+ return (+ <div>+ <PageHeader+ title={S.ontology.casesTitle}+ sub={S.ontology.casesHint}+ actions={+ <Button+ size="sm"+ disabled={cases.isFetching}+ onClick={() => cases.refetch()}+ >+ <RefreshCw size={14} />+ {S.nav.refresh}+ </Button>+ }+ />+ {cases.isError ? (+ <p role="alert" className="text-body text-danger">+ {(cases.error as Error).message}+ </p>+ ) : cases.isPending ? (+ <Loading>{S.nav.loading}</Loading>+ ) : cases.data.cases.length === 0 ? (+ <p className="text-body text-ink-2">{S.ontology.casesEmpty}</p>+ ) : (+ <Table>+ <THead>+ <Tr>+ <Th>{S.ontology.caseStatement}</Th>+ <Th>{S.ontology.caseExpected}</Th>+ <Th>{S.ontology.caseActual}</Th>+ <Th>{S.ontology.caseResult}</Th>+ <Th>{S.ontology.caseChecked}</Th>+ <Th>{S.ontology.caseOrigin}</Th>+ </Tr>+ </THead>+ <TBody>+ {cases.data.cases.map((item) => (+ <CaseRow key={item.id} kbId={kbId} item={item} />+ ))}+ </TBody>+ </Table>+ )}+ </div>+ );+}++function CaseRow({ kbId, item }: { kbId: string; item: OntologyRegressionCase }) {+ const [open, setOpen] = useState(false);+ const result = item.last_result;+ return (+ <Fragment>+ <Tr>+ <Td>+ <div className="flex items-start gap-2">+ <IconButton+ size="sm"+ label={open ? S.ontology.caseHideEvidence : S.ontology.caseEvidence}+ aria-expanded={open}+ onClick={() => setOpen(!open)}+ >+ {open ? <ChevronDown size={14} /> : <ChevronRight size={14} />}+ </IconButton>+ <div className="min-w-0 break-words">+ <span>{item.subject_label}</span>{" "}+ <span className="text-ink-2">{item.phrase}</span>{" "}+ <span>{item.object_label ?? fmtObjectValue(item.object_value) ?? "—"}</span>+ </div>+ </div>+ </Td>+ <Td>+ <div>{item.expected_property_label}</div>+ <div className="text-fine text-ink-2">{directionText(item.expected_direction)}</div>+ </Td>+ <Td>+ <div>+ {item.actual_property_label ??+ (result?.status === "bound" ? S.ontology.caseUnavailableProperty : result?.status === "none" ? S.ontology.caseUnbound : result ? S.ontology.caseUndecided : "—")}+ </div>+ {result?.actual_direction && (+ <div className="text-fine text-ink-2">{directionText(result.actual_direction)}</div>+ )}+ {result?.decided_at && (+ <div className="mt-1 text-fine text-ink-2">+ {S.ontology.caseDecidedAt}: <span className="u-num">{localDateTime(result.decided_at)}</span>+ </div>+ )}+ </Td>+ <Td>+ <Status tone={!result ? "neutral" : result.passed ? "success" : "warn"}>+ {!result ? S.ontology.caseNotChecked : result.human_bound ? S.ontology.caseHumanBound : result.passed ? S.ontology.casePassed : S.ontology.caseMismatch}+ </Status>+ {result?.human_bound && (+ <p className="mt-1 max-w-64 text-fine text-ink-2">{S.ontology.caseHumanHint}</p>+ )}+ </Td>+ <Td className="text-small u-num">+ {item.last_checked_at ? localDateTime(item.last_checked_at) : "—"}+ </Td>+ <Td>+ <div className="text-small">+ {item.origin === "adoption" ? S.ontology.caseAdoption : S.ontology.casePerson}+ </div>+ <div className="text-fine text-ink-2">{item.created_by_label ?? S.ontology.caseUnknownCreator}</div>+ <div className="text-fine text-ink-2 u-num">{localDateTime(item.created_at)}</div>+ </Td>+ </Tr>+ {open && (+ <Tr>+ <Td colSpan={6}>+ <CaseEvidence kbId={kbId} statementId={item.statement_id} />+ </Td>+ </Tr>+ )}+ </Fragment>+ );+}++function CaseEvidence({ kbId, statementId }: { kbId: string; statementId: string }) {+ const evidence = useQuery({+ queryKey: ["evidence", statementId],+ queryFn: () => api.factEvidence(kbId, statementId),+ });+ if (evidence.isError) return <p role="alert" className="text-small text-danger">{(evidence.error as Error).message}</p>;+ if (evidence.isPending) return <Loading>{S.nav.loading}</Loading>;+ if (evidence.data.evidence.length === 0) return <p className="text-small text-ink-2">{S.graph.noEvidence}</p>;+ return (+ <div className="space-y-3">+ {evidence.data.evidence.map((ev) => (+ <div key={ev.chunk_id} className="text-small">+ <p className="whitespace-pre-wrap text-ink">{ev.quote ? `“${ev.quote}”` : S.graph.noQuote}</p>+ <div className="mt-1 flex items-center gap-2 text-fine text-ink-2">+ {ev.document_deleted ? (+ <span>{ev.filename} · {S.graph.sourceDeleted}</span>+ ) : (+ <Link+ to="/kb/$kbId/doc/$docId"+ params={{ kbId, docId: ev.document_id }}+ search={{ chunk: ev.chunk_id }}+ className="u-hover-ink inline-flex items-center gap-1"+ >+ {S.graph.sectionRef(ev.filename, ev.seq + 1)}+ <ExternalLink size={11} />+ </Link>+ )}+ {ev.stale && <span>{S.graph.fromVersion(ev.doc_version)}</span>}+ </div>+ </div>+ ))}+ </div>+ );+}diff --git a/web/src/queryDefaults.ts b/web/src/queryDefaults.tsindex 0a30399b..ed032028 100644--- a/web/src/queryDefaults.ts+++ b/web/src/queryDefaults.ts@@ -34,6 +34,7 @@ export const STREAM_KEYS = ["pending","sources","mappings",+ "ontologyRegressions",] as const;/** 一次会话内不变的键头;换人靠清空缓存 */export const SESSION_KEYS = ["me", "health", "deployment"] as const;diff --git a/web/src/useKbEvents.ts b/web/src/useKbEvents.tsindex 07de914f..8ca6a47f 100644--- a/web/src/useKbEvents.ts+++ b/web/src/useKbEvents.ts@@ -64,9 +64,9 @@ export function useKbEvents(kbId: string | undefined) {`/api/v1/kbs/${kbId}/events`,{document: () => push(["documents", kbId], ["graph"]),- graph: () => push(["graph"]),+ graph: () => push(["graph"], ["ontologyRegressions", kbId]),// 映射探索跑完发的也是 review:Pending 那一栏得跟着刷新- review: () => push(["review", kbId], ["mappings", kbId]),+ review: () => push(["review", kbId], ["mappings", kbId], ["ontologyRegressions", kbId]),// 一句记忆抽出了等人点头的事实(0015):对话里那张确认卡跟着长出来pending: () => push(["pending", kbId], ["review", kbId]),source: () => push(["sources", kbId], ["documents", kbId]),