业务本体与标准实体:跨源键值对齐、对账共变算子、健康证据链与实体助手

- 新增标准业务实体(CanonicalEntity)模型、确定性跨源编码翻译、后台候选实体扫描与文档驱动实体智能助手
- 新增指标本体图谱(factor / reconciles_with / upstream_driver)、DAG 防环校验以及 ontology_neighbors / source_health 内置工具
- 新增跨源对账(analysis_reconcile)与滞后共变(analysis_cochange)分析算子,打通 [[h:H1]] 数据源健康证据链、报告导出与本体消融评测
- 数据目录新增「标准业务实体」视图与候选审阅工作台,口径页集成指标本体拓扑面板与端到端浏览器检查
This commit is contained in:
ThearchyHelios
2026-11-12 12:57:53 +08:00
parent 2f90f0eb3a
commit 8d9a712eae
106 changed files with 16654 additions and 295 deletions
+46 -43
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from 'react'
import { lazy, Suspense, useEffect, useRef, useState } from 'react'
import type { ReactNode, RefObject } from 'react'
import { Link, NavLink, Navigate, Route, Routes, useLocation, useNavigate } from 'react-router-dom'
import { Bell, BellOff, LogOut, Moon, RotateCw, Sun, UserRound } from 'lucide-react'
@@ -9,34 +9,7 @@ import type { CatalogCheck } from './store/catalog'
import { useStudio } from './store/studio'
import { useChat } from './store/chat'
import { useConversations } from './store/conversations'
import { ChatPage } from './pages/ChatPage'
import { StudioPage } from './pages/StudioPage'
import { RunsPage } from './pages/RunsPage'
import { ComparePage } from './pages/runs/ComparePage'
import { DataPage } from './pages/DataPage'
import { CatalogPage } from './pages/catalog/CatalogPage'
import { ToolsPage } from './pages/ToolsPage'
import { KnowledgePage } from './pages/KnowledgePage'
import { SettingsPage } from './pages/SettingsPage'
import { SchedulesPage } from './pages/schedules/SchedulesPage'
// 评测(下一轮第 4 波,评测-D8):顶级导航,搭建者以上可见
import { EvalsPage } from './pages/evals/EvalsPage'
import { CaliberCatalog } from './pages/ledger/CaliberCatalog'
import { CaliberDrafts } from './pages/ledger/CaliberDrafts'
import { NotFound } from './pages/NotFound'
// 应用平台:使用面(FE-5)、搭建面的应用编辑(FE-6)
import { AppsHome } from './pages/apps/AppsHome'
import { AppPage } from './pages/apps/AppPage'
import { EntryPage } from './pages/apps/EntryPage'
import { InstancePage } from './pages/apps/InstancePage'
import { TaskPage } from './pages/apps/TaskPage'
import { AppEditor } from './pages/apps/edit/AppEditor'
// 普通用户建应用:新建应用的起点、蓝图页(F5)
import { NewAppStart } from './pages/blueprints/NewAppStart'
import { BlueprintPage } from './pages/blueprints/BlueprintPage'
import { personalAppsOn } from './pages/blueprints/shared'
import { LoginPage } from './pages/LoginPage'
import { SharePage } from './pages/apps/SharePage'
import { Logo } from './components/Logo'
import {
CommandPalette, PAGES, ShortcutHelp, flushThemePref, openShortcutHelp, toggleCommandPalette, toggleNotify,
@@ -58,6 +31,33 @@ import { useLeaveBlocker } from './lib/leave'
import { useLocalActor } from './lib/actor'
import { APP_TEXT, AUTH_MODE_LABEL, AUTH_TEXT, ROLE_LABEL, RUN_COMPARE_TEXT, TASK_NOTIFY_TEXT, runName } from './lib/terms'
// 页面按需加载;外壳和导航始终可用,加载失败由现有错误边界提供恢复入口。
const ChatPage = lazy(() => import('./pages/ChatPage').then((module) => ({ default: module.ChatPage })))
const StudioPage = lazy(() => import('./pages/StudioPage').then((module) => ({ default: module.StudioPage })))
const RunsPage = lazy(() => import('./pages/RunsPage').then((module) => ({ default: module.RunsPage })))
const ComparePage = lazy(() => import('./pages/runs/ComparePage').then((module) => ({ default: module.ComparePage })))
const DataPage = lazy(() => import('./pages/DataPage').then((module) => ({ default: module.DataPage })))
const CatalogPage = lazy(() => import('./pages/catalog/CatalogPage').then((module) => ({ default: module.CatalogPage })))
const ToolsPage = lazy(() => import('./pages/ToolsPage').then((module) => ({ default: module.ToolsPage })))
const KnowledgePage = lazy(() => import('./pages/KnowledgePage').then((module) => ({ default: module.KnowledgePage })))
const SettingsPage = lazy(() => import('./pages/SettingsPage').then((module) => ({ default: module.SettingsPage })))
const SchedulesPage = lazy(() => import('./pages/schedules/SchedulesPage').then((module) => ({ default: module.SchedulesPage })))
const EvalsPage = lazy(() => import('./pages/evals/EvalsPage').then((module) => ({ default: module.EvalsPage })))
const CaliberCatalog = lazy(() => import('./pages/ledger/CaliberCatalog').then((module) => ({ default: module.CaliberCatalog })))
const CaliberDrafts = lazy(() => import('./pages/ledger/CaliberDrafts').then((module) => ({ default: module.CaliberDrafts })))
const NotFound = lazy(() => import('./pages/NotFound').then((module) => ({ default: module.NotFound })))
const AppsHome = lazy(() => import('./pages/apps/AppsHome').then((module) => ({ default: module.AppsHome })))
const AppPage = lazy(() => import('./pages/apps/AppPage').then((module) => ({ default: module.AppPage })))
const EntryPage = lazy(() => import('./pages/apps/EntryPage').then((module) => ({ default: module.EntryPage })))
const InstancePage = lazy(() => import('./pages/apps/InstancePage').then((module) => ({ default: module.InstancePage })))
const TaskPage = lazy(() => import('./pages/apps/TaskPage').then((module) => ({ default: module.TaskPage })))
const AppEditor = lazy(() => import('./pages/apps/edit/AppEditor').then((module) => ({ default: module.AppEditor })))
const NewAppStart = lazy(() => import('./pages/blueprints/NewAppStart').then((module) => ({ default: module.NewAppStart })))
const BlueprintPage = lazy(() => import('./pages/blueprints/BlueprintPage').then((module) => ({ default: module.BlueprintPage })))
const LoginPage = lazy(() => import('./pages/LoginPage').then((module) => ({ default: module.LoginPage })))
const SharePage = lazy(() => import('./pages/apps/SharePage').then((module) => ({ default: module.SharePage })))
/** 启动时认人(/auth/me)最多等多久再取目录 */
const AUTH_WAIT_MS = 2500
@@ -68,7 +68,13 @@ const AUTH_WAIT_MS = 2500
const SHARE_PAGE = typeof window !== 'undefined' && window.location.pathname === '/s'
export default function App() {
return SHARE_PAGE ? <SharePage /> : <Shell />
return <Suspense fallback={<PageLoading />}>{SHARE_PAGE ? <SharePage /> : <Shell />}</Suspense>
}
function PageLoading() {
return <div role="status" aria-live="polite" className="flex h-full min-h-40 items-center justify-center gap-2 text-sm text-dim">
<Spinner />正在加载页面…
</div>
}
function Shell() {
@@ -168,7 +174,7 @@ function Shell() {
<ErrorBoundary resetKey={location.pathname}>
{/* 开了登录的使用者只到得了「应用」和「设置」:别的地址(旧书签、手输)送回应用首页 */}
{roleRedirect ? <Navigate to={roleRedirect} replace /> : (
<Routes>
<Suspense fallback={<PageLoading />}><Routes>
{/* 默认落到对话页:多数人要的是答案,画布留给要自己编排的人。使用者落到应用首页 */}
<Route path="/" element={<HomeRedirect />} />
<Route path="/chat" element={<ChatPage />} />
@@ -218,7 +224,7 @@ function Shell() {
<Route path="/settings" element={<SettingsPage />} />
<Route path="/settings/:tab" element={<SettingsPage />} />
<Route path="*" element={<NotFound />} />
</Routes>
</Routes></Suspense>
)}
</ErrorBoundary>
</div>
@@ -358,17 +364,15 @@ function Nav({ stalled }: { stalled: CatalogCheck[] }) {
const live = studio.startsWith('run') || chat === 'run'
const pages = usePages()
// 整条导航约 690px 高(十个导航项),窗口再矮,最底下的遥测点和署名就被切掉、够不着。
// 矮窗口(521–660px)按高度收紧到 540px 左右(导航项 36px),≤520px 再收一档到 470px 左右(导航项 30px、
// 图标和字之间只留 2px:17px 图标 + 2px + 11px 字正好放下),而不是让导航滚动:导航一旦 overflow,挂在右侧的
// 悬停提示和遥测浮层也会被一起裁掉。加导航项时在 600px、520px、480px 高的窗口里量一遍(check-shell 的「窗口高 …px」)。
// 第十项「评测」加进来时量过:≤520px 那档还是 32px 的话,480px 高的窗口里遥测点超出视口 12px,所以收到 30px
// 11 项导航在中等高度用 36px,在 ≤520px 用 28px;最矮档图标和文字紧排,logo 同步收紧。
// 保留所有入口,且不在 nav 上加 overflow,以免裁掉侧向提示和遥测浮层。
// 增加入口后检查 700、600、520、480px:遥测和底部 padding 都必须留在视口内。
return (
<nav aria-label="主导航" className="relative z-30 flex w-16 shrink-0 flex-col border-r bg-panel">
<Link
to="/"
aria-label={live ? 'AgentLab 首页(有运行正在进行)' : 'AgentLab 首页'}
className="group relative mx-auto mb-2 mt-3 flex h-10 w-10 shrink-0 items-center justify-center rounded-lg outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-[var(--accent)] [@media(max-height:660px)]:mb-1 [@media(max-height:660px)]:mt-2 [@media(max-height:660px)]:h-9"
className="group relative mx-auto mb-2 mt-3 flex h-10 w-10 shrink-0 items-center justify-center rounded-lg outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-[var(--accent)] [@media(max-height:760px)]:mb-1 [@media(max-height:760px)]:mt-2 [@media(min-height:521px)_and_(max-height:760px)]:h-9 [@media(max-height:520px)]:h-7"
>
<Logo size={22} live={live} className="text-accent" title="" />
<Tip>
@@ -376,7 +380,7 @@ function Nav({ stalled }: { stalled: CatalogCheck[] }) {
<span className="text-faint">受限动态编排{live ? ' · 有运行正在进行' : ''}</span>
</Tip>
</Link>
<div aria-hidden className="mx-4 mb-2 h-px shrink-0 bg-hairline [@media(max-height:660px)]:mb-1" />
<div aria-hidden className="mx-4 mb-2 h-px shrink-0 bg-hairline [@media(max-height:760px)]:mb-1" />
<ul className="flex flex-col gap-0.5">
{pages.map((p) => (
@@ -386,9 +390,8 @@ function Nav({ stalled }: { stalled: CatalogCheck[] }) {
aria-keyshortcuts={ariaShortcut(p.shortcut)}
className={({ isActive }) => clsx(
'group relative flex h-12 w-full flex-col items-center justify-center gap-1 rounded-md text-2xs leading-none outline-none',
// 两档的高度不能叠在同一个窗口高度上:同时命中时后出的那条赢,而 Tailwind 把 660 那条排在后面,
// ≤520px 的那一档就一直没生效(九项在 480px 高的窗口里放不下)。所以 36px 那档只管 521–660px
'[@media(min-height:521px)_and_(max-height:660px)]:h-9 [@media(max-height:520px)]:h-[30px] [@media(max-height:520px)]:gap-0.5',
// 两档媒体条件互斥,避免 Tailwind 排序让中等高度规则覆盖最矮档。
'[@media(min-height:521px)_and_(max-height:760px)]:h-9 [@media(max-height:520px)]:h-7 [@media(max-height:520px)]:gap-0',
'transition-colors focus-visible:ring-2 focus-visible:ring-[var(--accent)]',
isActive ? 'bg-hover font-medium text-fg' : 'text-dim hover:bg-hover hover:text-fg',
)}
@@ -413,7 +416,7 @@ function Nav({ stalled }: { stalled: CatalogCheck[] }) {
))}
</ul>
<div className="mt-auto flex flex-col items-center gap-1.5 pb-2 pt-3 [@media(max-height:660px)]:gap-1 [@media(max-height:660px)]:pb-1 [@media(max-height:660px)]:pt-2">
<div className="mt-auto flex flex-col items-center gap-1.5 pb-2 pt-3 [@media(max-height:760px)]:gap-1 [@media(max-height:760px)]:pb-1 [@media(max-height:760px)]:pt-2">
<div className="flex items-center gap-0.5">
<NotifyToggle />
<ThemeToggle />
@@ -430,7 +433,7 @@ function Nav({ stalled }: { stalled: CatalogCheck[] }) {
/** 导航项右上角的徽标:图标右上角外侧,外圈一道面板底色的描边把它从图标上抠开 */
const BADGE_CLASS = clsx(
'group/badge absolute left-[calc(50%+7px)] top-[3px] z-10 flex h-4 min-w-4 items-center justify-center rounded-full px-1',
'[@media(max-height:660px)]:top-0',
'[@media(max-height:760px)]:top-0',
'bg-warn-solid text-[10px] font-semibold leading-none text-on-warn tnum ring-2 ring-[var(--bg-panel)]',
'outline-none focus-visible:ring-[var(--accent)]',
)
+7
View File
@@ -41,6 +41,7 @@ import { capabilities, endpoints, notify } from './capabilities'
import { blueprints, files, personal, templates } from './blueprints'
// 问数据的一轮在服务端跑(编排完善第 1 波):发起、看、停,实时流在 chatTurns.ts 的 streamChatTurn
import { chatTurns } from './chatTurns'
import { ontology } from './ontology'
// 请求层搬到了 http.ts(见那边的说明)。原先从这里导出的照旧从这里导出,调用方不用改;
// 请求函数也一并转出,给不在 api/ 下、又想直接发请求的地方用。api/ 下的命名空间文件请直接从 http.ts 导入
@@ -867,6 +868,10 @@ export const api = {
get<{ report?: { node_id?: string; doc_artifact?: string }; alias?: string; rendered?: string | null
chain?: EvidenceSegmentDetail['chain']; seal?: EvidenceSegmentDetail['seal']; redacted?: EvidenceSegmentDetail['redacted'] }>(
`/runs/${encodeURIComponent(runId)}/evidence/analyses/${encodeURIComponent(alias)}${qs({ report: opts?.report })}`, opts),
health: (runId: string, alias: string, opts?: RequestOptions & { report?: string }) =>
get<{ report?: { node_id?: string; doc_artifact?: string }; alias?: string; rendered?: string | null
chain?: EvidenceSegmentDetail['chain']; seal?: EvidenceSegmentDetail['seal']; redacted?: EvidenceSegmentDetail['redacted'] }>(
`/runs/${encodeURIComponent(runId)}/evidence/health/${encodeURIComponent(alias)}${qs({ report: opts?.report })}`, opts),
/**
* 审计表:每个有状态的片段按状态分组(有出处 / 无证据 / 可疑实体 / 旧运行猜测),附上封存核对的结果。
* groups 只要这几组(none、suspicious…)
@@ -1002,6 +1007,8 @@ export const api = {
// 问数据的一轮(服务端跑整轮:发起、看、停)
chatTurns,
// 业务本体:标准业务实体与跨口径指标拓扑
ontology,
}
/**
+167
View File
@@ -0,0 +1,167 @@
import type {
CanonicalEntity,
EntityApplyPatchOut,
EntityAssistantEvent,
EntityAssistantRequest,
EntityAttachmentOut,
EntityDiscoveryActiveOut,
EntityDiscoveryJob,
OntologyGraph,
OntologyStatus,
WorkflowOntology,
} from '../typesLedger'
import {
actorHeader,
BASE,
del,
failure,
get,
NETWORK_MESSAGE,
parseBody,
patch,
post,
qs,
report,
request,
upload,
type RequestOptions,
type UploadOptions,
} from './http'
export interface EntityReviewPayload {
target_kind: 'binding' | 'caliber_param'
item_id: string
status: OntologyStatus
reason?: string
version?: number
}
export interface EntityAssistantEnd {
error?: string
status?: number
code?: string
aborted?: boolean
}
export function streamEntityAssistant(
body: EntityAssistantRequest,
onEvent: (event: EntityAssistantEvent) => void,
onEnd: (end: EntityAssistantEnd) => void,
): () => void {
const controller = new AbortController()
const path = '/ontology/entities/assistant'
const emit = (line: string) => {
const text = line.replace(/\r$/, '')
if (!text.startsWith('data:')) return
const payload = text.slice(5).trim()
if (!payload) return
try {
const event = parseBody(payload) as Record<string, unknown> | null
if (event && typeof event === 'object' && typeof event.type === 'string') {
onEvent(event as unknown as EntityAssistantEvent)
}
} catch {
/* 忽略非事件行 */
}
}
void (async () => {
try {
const res = await fetch(BASE + path, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'text/event-stream', ...actorHeader() },
body: JSON.stringify(body),
signal: controller.signal,
})
if (!res.ok || !res.body) {
const err = failure(res.status, res.statusText, await res.text().catch(() => ''), path)
onEnd(err.kind === 'network' ? { error: NETWORK_MESSAGE } : { error: err.message, status: res.status, code: err.code })
return
}
report(true)
const reader = res.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
for (;;) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
let idx: number
while ((idx = buffer.indexOf('\n')) >= 0) {
emit(buffer.slice(0, idx))
buffer = buffer.slice(idx + 1)
}
}
buffer += decoder.decode()
if (buffer.trim()) emit(buffer)
onEnd({})
} catch (err) {
if (controller.signal.aborted || (err instanceof DOMException && err.name === 'AbortError')) {
onEnd({ aborted: true })
return
}
onEnd({ error: NETWORK_MESSAGE })
}
})()
return () => controller.abort()
}
export const ontology = {
listEntities: (opts?: RequestOptions & { source_name?: string; only_active?: boolean }) =>
get<{ items: CanonicalEntity[] }>(
`/ontology/entities${qs({
source_name: opts?.source_name,
only_active: opts?.only_active ? 'true' : undefined,
})}`,
opts,
),
getEntity: (id: string, opts?: RequestOptions) =>
get<CanonicalEntity>(`/ontology/entities/${encodeURIComponent(id)}`, opts),
createEntity: (body: Partial<CanonicalEntity> & { key: string; label: string }) =>
post<CanonicalEntity>('/ontology/entities', body),
updateEntity: (id: string, body: Partial<CanonicalEntity> & { version?: number }) =>
patch<CanonicalEntity>(`/ontology/entities/${encodeURIComponent(id)}`, body),
reviewEntity: (id: string, body: EntityReviewPayload) =>
post<CanonicalEntity>(`/ontology/entities/${encodeURIComponent(id)}/review`, body),
deleteEntity: (id: string) =>
del(`/ontology/entities/${encodeURIComponent(id)}`),
uploadAttachment: (
file: File,
opts?: UploadOptions & { saveToKb?: boolean; collection?: string },
) => {
const form = new FormData()
form.append('file', file)
form.append('save_to_kb', opts?.saveToKb ? 'true' : 'false')
form.append('collection', opts?.collection || 'default')
const path = '/ontology/entities/attachments'
return opts?.onProgress
? upload<EntityAttachmentOut>(path, form, opts)
: request<EntityAttachmentOut>(path, { method: 'POST', body: form, signal: opts?.signal })
},
applyPatch: (body: { operations: Record<string, unknown>[]; expected_versions?: Record<string, number> }) =>
post<EntityApplyPatchOut>('/ontology/entities/apply-patch', body),
streamAssistant: streamEntityAssistant,
createDiscoveryJob: (body: {
source_ids?: string[]
document_ids?: string[]
attachment_ids?: string[]
note?: string
}) => post<EntityDiscoveryJob>('/ontology/discovery-jobs', body),
activeDiscoveryJob: (opts?: RequestOptions) =>
get<EntityDiscoveryActiveOut>('/ontology/discovery-jobs/active', opts),
getDiscoveryJob: (jobId: string, opts?: RequestOptions) =>
get<EntityDiscoveryJob>(`/ontology/discovery-jobs/${encodeURIComponent(jobId)}`, opts),
cancelDiscoveryJob: (jobId: string) =>
post<EntityDiscoveryJob>(`/ontology/discovery-jobs/${encodeURIComponent(jobId)}/cancel`, {}),
graph: (opts?: RequestOptions & { include_proposed?: boolean }) =>
get<OntologyGraph>(
`/ontology/graph${qs({
include_proposed: opts?.include_proposed === false ? 'false' : undefined,
})}`,
opts,
),
workflow: (workflowId: string, opts?: RequestOptions & { version?: number }) =>
get<WorkflowOntology>(
`/ontology/workflows/${encodeURIComponent(workflowId)}${qs({ version: opts?.version })}`,
opts,
),
}
+5 -2
View File
@@ -401,7 +401,8 @@ function AnalysisItemList({ nodeId, value, issues, onChange }: {
</div>
)
}
const specs = op ? paramSpecs(op, item.mode).filter((p) => !(two && TWO_QUERY_SKIP.has(p.key))) : []
const skipTwoPeriods = two && op !== 'cochange'
const specs = op ? paramSpecs(op, item.mode).filter((p) => !(skipTwoPeriods && TWO_QUERY_SKIP.has(p.key))) : []
const headline = params.headline && typeof params.headline === 'object' ? params.headline as Record<string, string> : null
const setHeadline = (side: 'base' | 'target', t: string) => {
const next = { base: headline?.base ?? '', target: headline?.target ?? '', [side]: t.trim() }
@@ -412,7 +413,9 @@ function AnalysisItemList({ nodeId, value, issues, onChange }: {
if (on) {
next.base_query = item.from ?? ''
next.target_query = ''
for (const k of TWO_QUERY_SKIP) delete next[k]
if (op !== 'cochange') {
for (const k of TWO_QUERY_SKIP) delete next[k]
}
update(i, { ...item, from: undefined, params: next })
} else {
const from = typeof next.base_query === 'string' ? next.base_query : ''
+8 -2
View File
@@ -47,11 +47,17 @@ export function paramSpecs(op: AnalysisOp, mode?: string | null): ParamSpec[] {
}
case 'comparable':
return [...PERIODS, col('measure'), { key: 'grain', kind: 'grain' }]
case 'reconcile':
return [cols('by'), cols('target_by'), col('measure'), col('target_measure'), val('unit_factor'), val('label')]
case 'cochange':
return [col('period'), col('target_period'), col('measure'), col('driver_measure'), val('target'),
{ key: 'basis', kind: 'basis' }, { key: 'grain', kind: 'grain' }, { key: 'lag', kind: 'int' }, val('label')]
}
}
/** 这种分析能不能写成基期、本期两份查询(DecomposeArgs、ComparableArgs 有 base_query / target_query) */
export const allowsTwoQueries = (op: AnalysisOp): boolean => op === 'decompose' || op === 'comparable'
/** 这种分析能不能写成两份查询(DecomposeArgs、ComparableArgs、ReconcileArgs、CochangeArgs 有 base_query / target_query) */
export const allowsTwoQueries = (op: AnalysisOp): boolean =>
op === 'decompose' || op === 'comparable' || op === 'reconcile' || op === 'cochange'
/** 有总数核对(headline)的:可加、比率的变化拆解 */
export const allowsHeadline = (op: AnalysisOp, mode?: string | null): boolean =>
op === 'decompose' && mode !== 'factor'
+5 -2
View File
@@ -504,7 +504,6 @@ function PaletteView() {
const current = Math.min(active, Math.max(flat.length - 1, 0))
const optionId = (i: number) => `${listId}-opt-${i}`
useEffect(() => { setActive(0) }, [query])
useEffect(() => {
document.getElementById(optionId(current))?.scrollIntoView({ block: 'nearest' })
// 只跟着选中项走:用户拿滚轮翻列表时,别因为别的数据刷新把他拽回去
@@ -565,7 +564,11 @@ function PaletteView() {
placeholder="搜索页面、工作流、运行、对话或命令"
className="h-full min-w-0 flex-1 bg-transparent text-base text-fg outline-none placeholder:text-faint"
value={query}
onChange={(e) => setQuery(e.target.value)}
onChange={(e) => {
// 搜索结果与默认选中项同步提交;不能在 effect 中重置,否则快速 Enter 会执行旧索引。
setQuery(e.target.value)
setActive(0)
}}
autoComplete="off"
spellCheck={false}
/>
+4
View File
@@ -272,6 +272,10 @@ export function sourceOf(seg: EvidenceSegment, doc?: Pick<EvidenceDocData, 'cata
: loc.key ? E.citedValue(loc.key) : E.citedPhrase
return [`${E.title} ${cite.alias ?? ''}`.trim(), what].join(' · ')
}
if (cite.kind === 'source_health' || entry?.kind === 'source_health') {
const phrase = typeof entry?.phrase === 'string' ? entry.phrase : ''
return [`数据源健康核查 ${cite.alias ?? ''}`.trim(), phrase].filter(Boolean).join(' · ')
}
if (cite.kind === 'cell' || (cite.kind !== 'metric' && cite.kind !== 'input' && entry?.kind === 'query')) {
const where = locatorText(cite.locator)
return [EVIDENCE_TEXT.query(cite.alias ?? ''), where].filter(Boolean).join(' · ')
+7 -3
View File
@@ -13,13 +13,14 @@
*/
import { formatNumber } from './format'
/** 五个算子(contract.OPS),按契约的先后 */
export const ANALYSIS_OPS = ['decompose', 'baseline', 'trend', 'differ', 'comparable'] as const
/** 算子(contract.OPS),按契约的先后 */
export const ANALYSIS_OPS = ['decompose', 'baseline', 'trend', 'differ', 'comparable', 'reconcile', 'cochange'] as const
export type AnalysisOp = (typeof ANALYSIS_OPS)[number]
/** 算子的叫法:contract.OP_LABELS */
export const ANALYSIS_OP_LABEL: Record<AnalysisOp, string> = {
decompose: '变化拆解', baseline: '波动基线', trend: '趋势判断', differ: '差异检验', comparable: '可比性检查',
reconcile: '跨源对账', cochange: '伴随异动',
}
/** 模式的叫法:contract.MODE_LABELS(比率拆解和比率比较都叫「比率」) */
@@ -189,12 +190,15 @@ export const ANALYSIS_TEXT = {
by: '维度列', period: '期次列', base: '基期', target: '本期', measure: '度量列', numerator: '分子列', denominator: '分母列',
product: '乘积列', factors: '因子列', label: '度量的叫法', basis: '比较方式', grain: '期次粒度', lag: '和往前第几期比',
pairs: '只比这几对', reference: '对照组', mean: '均值列', sd: '标准差列', sum: '合计列', sumsq: '平方和列', n: '样本数列',
value: '值列',
value: '值列', target_by: '对侧维度列', target_measure: '对侧度量列', unit_factor: '单位换算系数',
target_period: '驱动期次列', driver_measure: '驱动度量列',
} as Record<string, string>,
paramPlaceholder: {
by: 'region', period: 'week', base: '2026-W41', target: '2026-W42', measure: 'gmv', numerator: 'refunds',
denominator: 'orders', product: 'gmv', factors: 'orders、aov', label: '销售额', lag: '1', reference: '华东',
mean: 'avg_amount', sd: 'sd_amount', sum: 'sum_amount', sumsq: 'sumsq_amount', n: 'orders', value: 'amount',
target_by: 'workcenter_code', target_measure: 'mirror_qty', unit_factor: '1', target_period: 'shift_date',
driver_measure: 'downtime_min',
} as Record<string, string>,
paramHint: {
label: '系统写判定语时用;不写数字、百分号和单位,留空则用列名或数据目录中的名称',
+10 -3
View File
@@ -6,6 +6,7 @@
*/
import type {
EvalAnalysisMode, EvalAnalysisOp, EvalAnalysisTools, EvalCatalogMode, EvalCause, EvalE1Band, EvalE3Band, EvalExpectationKind,
EvalOntologyTools,
EvalGoldKind, EvalJudgement, EvalOutcome, EvalPath, EvalRate, EvalStatus, EvalTextOutcome, EvalTransition, EvalTrialStatus,
EvalTrigger, EvalUpgradePolicy, EvalVerdict,
} from '../typesEval'
@@ -322,6 +323,7 @@ export const EVAL_TEXT = {
source: '主要来源', dispersed: '分散,没有主要来源', flat: '基本持平', mix: '主要来自结构变化', rate: '主要来自各段自身的变化',
mixed: '几方面都有影响', normal: '常规波动', anomaly: '超出常规波动', rising: '上升趋势', falling: '下降趋势',
no_trend: '没有明显趋势', differs: '差异站得住', no_evidence: '不足以下结论', comparable: '可比', incomparable: '不可比',
aligned: '对账一致', diverged: '对账存在偏差', co_anomalous: '伴随异动', target_normal: '驱动未见异动',
} as Record<EvalJudgement, string>,
direction: { up: '上升', down: '下降' } as Record<'up' | 'down', string>,
/** 「主要来源:华东(下降)」「西南高于华东」 */
@@ -375,14 +377,16 @@ export const EVAL_TEXT = {
title: '发起评测',
mode: '评测方式',
modes: {
single: '评一次', ab: 'A/B 对照', catalog: '目录贡献对照', analysis_tools: '分析工具贡献对照',
} as Record<'single' | 'ab' | 'catalog' | 'analysis_tools', string>,
single: '评一次', ab: 'A/B 对照', catalog: '目录贡献对照',
analysis_tools: '分析工具贡献对照', ontology_tools: '本体穿透贡献对照',
} as Record<'single' | 'ab' | 'catalog' | 'analysis_tools' | 'ontology_tools', string>,
modeHint: {
single: '按一组变体评一遍题集',
ab: '两到三臂各自一组变体,共用同一份期望答案,同一题几臂同时作答',
catalog: '预设的 A/B:当前目录 vs 关目录,可以再加一臂「只用已核实和已确认的项」,量出数据目录帮了多少',
analysis_tools: '预设的 A/B:分析工具开 vs 关,量出分析工具(变化拆解、波动基线……)帮了多少',
} as Record<'single' | 'ab' | 'catalog' | 'analysis_tools', string>,
ontology_tools: '预设的 A/B:本体穿透开 vs 关,量出跨源本体邻居与数据源健康核查帮了多少',
} as Record<'single' | 'ab' | 'catalog' | 'analysis_tools' | 'ontology_tools', string>,
arm: (name: string) => `${name} 臂`,
addArm: '再加一臂',
removeArm: '去掉这一臂',
@@ -407,6 +411,9 @@ export const EVAL_TEXT = {
analysisTools: '分析工具',
analysisToolsMode: { on: '开', off: '关' } as Record<EvalAnalysisTools, string>,
analysisToolsHint: '关掉时助手建图看不到分析工具和分析卡;工作流题按固定的版本运行,不受影响',
ontologyTools: '本体穿透',
ontologyToolsMode: { on: '开', off: '关' } as Record<EvalOntologyTools, string>,
ontologyToolsHint: '关掉时助手建图看不到本体穿透与源健康核查工具及邻居提示;工作流题按固定的版本运行,不受影响',
repeats: '每题重复几次',
repeatsHint: '模型有随机性:对照建议每题 3 次',
reviewedArm: '再加一臂「只用已核实和已确认的项」',
+7 -2
View File
@@ -234,7 +234,7 @@ export const LEDGER_UI = {
drafts: {
entry: '新增口径',
title: '从业务文档起草口径',
subtitle: '文档整理成定义和取数,自动试运行一次;去画布审改后由人签字发布',
subtitle: '先导入指标定义,再选择指标绑定数据、验证并发布;已有口径继续沿用',
back: '返回口径目录',
refresh: '刷新',
/** 列表按阶段筛:全部、起草中、待审、已丢弃、失败。ready / questions_open / path_pending / attached 都归「待审」 */
@@ -263,6 +263,11 @@ export const LEDGER_UI = {
/** 细状态里值得在阶段旁边多说一句的:没有图、接了运行 */
stageNote: (status: string) => status === 'path_pending' ? '还没有取数图'
: status === 'attached' ? '已接上一次运行' : '',
stageNoteNeedsGraph: '尚未生成取数图 · 待补充信息',
inventoryAwaitingHint: '定义已保留;请在上方「继续处理未完成指标」补充来源表、字段映射或固定条件后继续生成。',
questionsContinuationHint: '若需补齐表名、字段映射或计算口径,请在上方「继续处理未完成指标」填写说明以重新生成;下方勾选仅用于标记业务疑问已人工确认。',
droppedMore: (n: number) => `展开其余 ${formatNumber(n)} 条`,
droppedLess: '收起',
filterLabel: '按阶段筛',
summary: (metrics: number, questions: number) => `${formatNumber(metrics)} 个指标 · ${
questions ? `${formatNumber(questions)} 个未决问题` : '没有未决问题'}`,
@@ -274,7 +279,7 @@ export const LEDGER_UI = {
// ---- 发起:选文档、可选数据源和起草要求 ----
start: '起草一份新口径',
documents: '文档',
documentsHint: '从知识库里选;模型只读这些文档的段落',
documentsHint: '从知识库选择指标定义表;先保留公式、边界规则和原文,再生成取数',
noDocuments: '知识库里还没有已完成的文档',
noDocumentsBody: '先在知识页上传业务文档,切块完成后再来起草',
documentMeta: (collection: string, chunks: number) => `${collection} · ${formatNumber(chunks)} 段`,
+39 -2
View File
@@ -694,6 +694,8 @@ function PrefsTab() {
appsPersonal: boolean
// 允许建分享链接(服务端 apps.share_links,04 细案 C2,默认关)
appsShare: boolean
// 问数异常跨源排查策略(服务端 investigation.auto_escalate_on_anomaly,默认 prompt)
autoEscalate: 'prompt' | 'auto'
} | null>(null)
const [spend, setSpend] = useState<{ usd?: number; calls?: number; unpriced_calls?: number } | null>(null)
// 核查一组(双盲复算、反方审稿、审批质询)的草稿另放一份,和上面的共用保存条;verifySaves 是存过几次,今日核查花费跟着再取
@@ -752,6 +754,7 @@ function PrefsTab() {
appsDaily: String(values?.apps?.on_demand_daily_limit ?? APPS_DAILY_DEFAULT),
appsPersonal: values?.apps?.user_personal_apps === true,
appsShare: values?.apps?.share_links === true,
autoEscalate: (values?.investigation?.auto_escalate_on_anomaly === 'auto' ? 'auto' : 'prompt') as 'prompt' | 'auto',
}
const cur = draft ?? saved
const stepCap = Number(values?.limits?.max_agent_steps) || 100
@@ -853,7 +856,8 @@ function PrefsTab() {
const judgeChanged = changed.some((k) => JUDGE_DRAFT.has(k))
const draftChanged = changed.some((k) => DRAFT_MODEL_DRAFT.has(k))
const appsChanged = changed.some((k) => APPS_DRAFT.has(k))
const runChanged = changed.some((k) => k !== 'actor' && !APPS_DRAFT.has(k) && !JUDGE_DRAFT.has(k) && !DRAFT_MODEL_DRAFT.has(k))
const investigationChanged = changed.some((k) => INVESTIGATION_DRAFT.has(k))
const runChanged = changed.some((k) => k !== 'actor' && !APPS_DRAFT.has(k) && !JUDGE_DRAFT.has(k) && !DRAFT_MODEL_DRAFT.has(k) && !INVESTIGATION_DRAFT.has(k))
try {
// 裁判一组整组写:后端对没给的键回落到默认值,只发改过的那一项会把别的项冲回默认
const judge = judgeChanged ? {
@@ -878,7 +882,10 @@ function PrefsTab() {
? { ...(values.apps ?? {}), on_demand_daily_limit: Number(cur.appsDaily.trim()), user_personal_apps: cur.appsPersonal,
share_links: cur.appsShare }
: null
if (runChanged || judge || verify || ledger || analysis || catalogDraft || apps) {
const investigation = investigationChanged
? { ...(values.investigation ?? {}), auto_escalate_on_anomaly: cur.autoEscalate }
: null
if (runChanged || judge || verify || ledger || analysis || catalogDraft || apps || investigation) {
const run = {
...(values.run ?? {}),
default_memory_scope: cur.scope,
@@ -894,6 +901,7 @@ function PrefsTab() {
...(runChanged ? { run } : {}), ...(judge ? { judge } : {}), ...(verify ? { verify } : {}),
...(ledger ? { ledger } : {}), ...(analysis ? { analysis } : {}),
...(catalogDraft ? { catalog_draft: catalogDraft } : {}), ...(apps ? { apps } : {}),
...(investigation ? { investigation } : {}),
})
setValues((v) => ({
...(v ?? {}),
@@ -904,6 +912,7 @@ function PrefsTab() {
...(analysis ? { analysis: out?.analysis ?? analysis } : {}),
...(catalogDraft ? { catalog_draft: out?.catalog_draft ?? catalogDraft } : {}),
...(apps ? { apps: out?.apps ?? apps } : {}),
...(investigation ? { investigation: out?.investigation ?? investigation } : {}),
}))
// 每日上限改了:旁边那句「今天已花」的分母跟着变,顺手再取一次
if (judge) void loadSpend()
@@ -1231,6 +1240,31 @@ function PrefsTab() {
{values.analysis && <AnalysisSection cur={analysisCur} errors={analysisErrs} onEdit={editAnalysis} />}
<section data-investigation-settings="">
<SectionBar
title="问数异常跨源排查"
hint="简单查询在复核中命中指标契约告警、空结果或对账告警时,如何沿已确认业务本体升级排查关联数据源。"
/>
<Field
label="触发异常时的处置策略"
htmlFor="pref-auto-escalate"
hint="默认提示一键排查,保证日常普通查询零额外开销;自动升级模式在同一轮最多自动重试一次。"
>
{(p) => (
<select
{...p}
className="field max-w-md"
value={cur.autoEscalate}
data-setting-auto-escalate=""
onChange={(e) => edit({ autoEscalate: e.target.value === 'auto' ? 'auto' : 'prompt' })}
>
<option value="prompt">提示一键排查(默认,日常查询零额外开销)</option>
<option value="auto">自动升级跨源排查(每轮最多自动重试一次)</option>
</select>
)}
</Field>
</section>
{values.catalog_draft && (
<DraftModelSection provider={cur.draftProvider} model={cur.draftModel} onEdit={edit}
error={fieldError?.field === 'catalog_draft.provider' ? fieldError.message : undefined} />
@@ -1295,6 +1329,7 @@ function PrefsTab() {
draftProvider: DRAFT_MODEL_SETTING_TEXT.provider, draftModel: DRAFT_MODEL_SETTING_TEXT.model,
appsDaily: APP_SETTING_TEXT.onDemandLimit, appsPersonal: APP_SETTING_TEXT.personalApps,
appsShare: APP_SETTING_TEXT.shareLinks,
autoEscalate: '问数异常跨源排查',
})[k]).concat(verifyLabels(verifyKeys), ledgerLabels(ledgerKeys), analysisLabels(analysisKeys)).join('、')}
</span>
</span>
@@ -1334,6 +1369,8 @@ function PrefsTab() {
/** 应用一组在草稿里的几项:保存时整组写 apps */
const APPS_DRAFT = new Set(['appsDaily', 'appsPersonal', 'appsShare'])
/** 问数异常跨源排查设置项 */
const INVESTIGATION_DRAFT = new Set<string>(['autoEscalate'])
/** 按需视图每日上限的缺省值和最大值(同服务端 settings.APPS_DEFAULTS、APPS_DAILY_LIMIT_MAX) */
const APPS_DAILY_DEFAULT = 200
+35 -13
View File
@@ -37,36 +37,58 @@ export function useLoad<T>(load: (signal: AbortSignal) => Promise<T>, deps: unkn
const seq = useRef(0)
const loadRef = useRef(load)
loadRef.current = load
const run = useCallback((keep: boolean) => {
const pending = useRef<{ controller: AbortController; promise: Promise<void> } | null>(null)
const run = useCallback((keep: boolean): Promise<void> => {
// 明确刷新可能发生在保存之后,必须重新读取;旧请求即使忽略 abort,也不能覆盖新状态。
pending.current?.controller.abort()
const me = ++seq.current
const ctrl = new AbortController()
const controller = new AbortController()
setState((s) => (keep ? { ...s, loading: true } : { loading: true }))
loadRef.current(ctrl.signal).then(
const promise = Promise.resolve().then(() => loadRef.current(controller.signal)).then(
(data) => { if (me === seq.current) setState({ data, loading: false }) },
(error) => {
if (me !== seq.current || error?.name === 'AbortError') return
setState((s) => ({ data: keep ? s.data : undefined, error, loading: false }))
},
)
return () => ctrl.abort()
).finally(() => { if (me === seq.current) pending.current = null })
pending.current = { controller, promise }
return promise
}, [])
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => run(false), deps)
const reload = useCallback(() => { run(true) }, [run])
useEffect(() => {
void run(false)
return () => {
seq.current++
pending.current?.controller.abort()
pending.current = null
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps)
const reload = useCallback(() => run(true), [run])
useOnReconnect(reload)
return { ...state, reload }
}
/** 每 ms 毫秒调一次 fn,只在 active 时、页面可见时;回到前台立刻补一次 */
export function usePoll(fn: () => void, ms: number, active: boolean) {
export function usePoll(fn: () => void | Promise<unknown>, ms: number, active: boolean) {
const ref = useRef(fn)
const busy = useRef(false)
ref.current = fn
useEffect(() => {
if (!active) return
const tick = () => { if (!document.hidden) ref.current() }
const t = setInterval(tick, ms)
document.addEventListener('visibilitychange', tick)
return () => { clearInterval(t); document.removeEventListener('visibilitychange', tick) }
let stopped = false
let timer: ReturnType<typeof setTimeout>
const schedule = () => { if (!stopped) timer = setTimeout(() => { void tick() }, ms) }
const tick = async () => {
clearTimeout(timer)
if (stopped) return
if (document.hidden || busy.current) { schedule(); return }
busy.current = true
try { await ref.current() } finally { busy.current = false; schedule() }
}
const visible = () => { if (!document.hidden && !busy.current) void tick() }
schedule()
document.addEventListener('visibilitychange', visible)
return () => { stopped = true; clearTimeout(timer); document.removeEventListener('visibilitychange', visible) }
}, [ms, active])
}
@@ -61,7 +61,7 @@ export function NewAppStart() {
<BackLink to="/apps?tab=apps" label={APP_TEXT.backToApps} />
{!ready ? <Skeleton rows={4} />
: !scope ? (
<EmptyState icon={<LayoutGrid size={28} />} title={NEW_APP_TEXT.personalOff} body={NEW_APP_TEXT.personalOffBody}
<EmptyState offline={false} icon={<LayoutGrid size={28} />} title={NEW_APP_TEXT.personalOff} body={NEW_APP_TEXT.personalOffBody}
action={<Link to="/chat" className="btn btn-sm">{NEW_APP_TEXT.goChat}</Link>} />
) : (
<>
@@ -76,7 +76,7 @@ export function PublishSummary({ blueprintId, open, onClose, onFix }: {
// 执行中逐步打勾:每秒取一次
usePoll(() => {
if (!plan) return
void api.blueprints.plan(plan.id).then((p) => {
return api.blueprints.plan(plan.id).then((p) => {
setPlan(p)
if (p.status === 'done') void useBlueprint.getState().load(blueprintId, { force: true })
}).catch(() => undefined)
@@ -56,7 +56,7 @@ export function TrialSection({ blueprintId }: { blueprintId: string }) {
(signal) => (runId ? api.tasks.list({ run_id: runId, status: 'pending' }, { signal }) : Promise.resolve({ items: [] })),
[runId])
const running = !!model && Object.values(model.sources).some((s) => s.state === 'running')
usePoll(() => { reload(); reloadTasks() }, POLL_MS, running)
usePoll(() => Promise.all([reload(), reloadTasks()]), POLL_MS, running)
if (!bp) return null
if (!runId) {
File diff suppressed because it is too large Load Diff
+38 -2
View File
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from 'react'
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import {
ArrowLeft, BookMarked, Clock, Database, Download, ListFilter as ListFilterIcon, ScanSearch, Sparkles, Upload,
ArrowLeft, BookMarked, Clock, Database, Download, ListFilter as ListFilterIcon, Network, ScanSearch, Sparkles, Upload,
} from 'lucide-react'
import clsx from 'clsx'
import { ApiError, api } from '../../api/client'
@@ -38,6 +38,7 @@ import { ChangeDetail, ChangesOverview } from './ChangeDetail'
import { changesParamsOf, clearChanges, isChangesView, writeChangesParams, writtenTables } from './changes'
import { JobStrip, stripItems, useSourceJobs } from './JobStrip'
import type { StripItem } from './JobStrip'
import { CanonicalEntitiesView } from './CanonicalEntitiesView'
import type { SourceChangeCategory, SourceChangeCounts, SourceChangeResolveOut, SourceChangeStatusFilter } from '../../typesSource'
import { dueCount, filterCounts, listParamsOf, progressOf, rowFromDetail, usageSummary, visibleRows, writeListParams } from './model'
import type { ListFilter, ListParams, ListSort } from './model'
@@ -147,6 +148,7 @@ export function CatalogPage() {
const review = useMemo(() => reviewParamsOf(params), [params])
/** 变化视图:view=changes 时左栏是变化列表;cstatus、ccat 是筛选;change 是右栏打开的那一条 */
const inChanges = isChangesView(params)
const inEntities = params.get('view') === 'entities'
const changesParams = useMemo(() => changesParamsOf(params), [params])
const pageView: PageView = inChanges ? 'changes' : review.view
const inReview = pageView === 'review'
@@ -474,6 +476,20 @@ export function CatalogPage() {
? writeChangesParams(writeReviewParams(prev, { item: '' }), { open: true })
: clearChanges(writeReviewParams(prev, { view: v, item: '' }))))
}, [patchSearch])
const openEntities = useCallback(() => {
patchSearch((prev) => {
const next = clearChanges(writeReviewParams(prev, { view: 'list', item: '' }))
next.set('view', 'entities')
return next
})
}, [patchSearch])
const closeEntities = useCallback(() => {
patchSearch((prev) => {
const next = new URLSearchParams(prev)
if (next.get('view') === 'entities') next.delete('view')
return next
})
}, [patchSearch])
/** 变化视图的筛选:替换当前这条历史 */
const setChangesFilter = useCallback((p: { status?: SourceChangeStatusFilter; category?: SourceChangeCategory | null }) => {
patchSearch((prev) => writeChangesParams(prev, p), { replace: true })
@@ -586,7 +602,17 @@ export function CatalogPage() {
)
let body: ReactNode
if (!data) {
if (inEntities) {
body = (
<CanonicalEntitiesView
sourceId={sourceId}
sourceName={source?.name ?? sourceId}
sources={sources}
tables={rows.map((r) => r.table_name)}
onBack={closeEntities}
/>
)
} else if (!data) {
body = loadError
? (loadError instanceof ApiError && loadError.status === 404
? <EmptyState icon={<BookMarked size={22} />} title={CT.sourceMissing} body={CT.sourceMissingBody} offline={false}
@@ -699,6 +725,16 @@ export function CatalogPage() {
<div className="flex shrink-0 items-center gap-1.5">
{hasTables && headerProfile}
{hasTables && headerDraft}
<button
type="button"
className={clsx('btn btn-sm', inEntities && 'btn-primary')}
onClick={() => (inEntities ? closeEntities() : openEntities())}
aria-label="业务实体"
title="管理跨源对齐的标准业务实体与编码映射"
data-catalog-entities=""
>
<Network size={11} aria-hidden /> <span className="hidden md:inline">业务实体</span>
</button>
{hasTables && (
<button type="button" className="btn btn-sm" onClick={() => void exportCatalog()} disabled={exporting} aria-label={XT.export}
title={XT.exportHint} data-catalog-export="">
@@ -0,0 +1,823 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { Check, Database, FileText, Paperclip, Send, Sparkles, Square, X } from 'lucide-react'
import clsx from 'clsx'
import { api } from '../../api/client'
import type { DataSourceName, KbDocument } from '../../types'
import type {
EntityApplyPatchOut,
EntityAssistantEvent,
EntityAssistantMessage,
EntityAttachmentOut,
EntityPatchChange,
} from '../../typesLedger'
import { isComposing, Notice, Spinner, toast } from '../../components/ui'
import { humanizeError } from '../../lib/errors'
import { Markdown } from '../../run/Markdown'
const DEFAULT_ACCEPT = '.md,.markdown,.txt,.pdf,.docx,.pptx,.html,.htm,.xlsx,.csv,.tsv,.json,.yaml,.yml'
const errText = (err: unknown): string => {
const h = humanizeError(err)
return [h.title, h.reason].filter(Boolean).join(':')
}
type AssistantPart =
| { kind: 'text'; text: string }
| {
kind: 'query'
source: string
sql: string
columns: string[]
rows: unknown[][]
rowCount: number
truncated: boolean
error?: string | null
}
| {
kind: 'proposal'
id: string
changes: EntityPatchChange[]
}
interface UserTurn {
id: string
role: 'user'
content: string
}
interface AssistantTurn {
id: string
role: 'assistant'
parts: AssistantPart[]
state: 'streaming' | 'done' | 'stopped' | 'error'
error?: string
queries?: number
}
type ChatTurn = UserTurn | AssistantTurn
export function EntityAssistant({
currentSourceId,
currentSourceName,
sources,
focusEntityKey,
focusEntityLabel,
onApplied,
onClose,
}: {
currentSourceId: string
currentSourceName: string
sources: DataSourceName[]
focusEntityKey: string | null
focusEntityLabel: string | null
onApplied: (result: EntityApplyPatchOut) => void
onClose: () => void
}) {
const enabledSources = useMemo(() => sources.filter((s) => s.enabled !== false), [sources])
const resolveDefaultScope = () => {
if (currentSourceId && enabledSources.some((s) => s.id === currentSourceId)) {
return [currentSourceId]
}
const byName = enabledSources.find((s) => s.name === currentSourceName)
if (byName) return [byName.id]
return enabledSources.length > 0 ? [enabledSources[0].id] : []
}
const [selectedSourceIds, setSelectedSourceIds] = useState<string[]>(() => resolveDefaultScope())
const [scopeOpen, setScopeOpen] = useState(false)
const [turns, setTurns] = useState<ChatTurn[]>([])
const [input, setInput] = useState('')
const [attachments, setAttachments] = useState<EntityAttachmentOut[]>([])
const [kbDocs, setKbDocs] = useState<KbDocument[]>([])
const [selectedKbIds, setSelectedKbIds] = useState<string[]>([])
const [collections, setCollections] = useState<string[]>(['default'])
const [acceptExt, setAcceptExt] = useState(DEFAULT_ACCEPT)
const [saveToKb, setSaveToKb] = useState(false)
const [collection, setCollection] = useState('default')
const [uploading, setUploading] = useState(false)
const [docError, setDocError] = useState<string | null>(null)
const [changeStates, setChangeStates] = useState<Record<string, 'pending' | 'dropped'>>({})
const [allProposed, setAllProposed] = useState<EntityPatchChange[]>([])
const [expectedVersions, setExpectedVersions] = useState<Record<string, number>>({})
const [saving, setSaving] = useState(false)
const [saveError, setSaveError] = useState<string | null>(null)
const [savedNotice, setSavedNotice] = useState<string | null>(null)
const abortRef = useRef<(() => void) | null>(null)
const logRef = useRef<HTMLDivElement>(null)
const fileRef = useRef<HTMLInputElement>(null)
const seqRef = useRef(0)
const streaming = turns.some((t) => t.role === 'assistant' && t.state === 'streaming')
useEffect(() => {
let cancelled = false
void (async () => {
const [docsRes, colsRes, fmtRes] = await Promise.allSettled([
api.kb.documents(),
api.kb.collections(),
api.kb.formats(),
])
if (cancelled) return
if (docsRes.status === 'fulfilled') {
setKbDocs(docsRes.value.filter((d) => d.status !== 'failed'))
}
if (colsRes.status === 'fulfilled' && colsRes.value.length > 0) {
setCollections(Array.from(new Set(['default', ...colsRes.value.map((c) => c.collection).filter(Boolean)])))
}
if (fmtRes.status === 'fulfilled') {
const exts = Array.from(new Set([...(fmtRes.value.extensions ?? []), ...(fmtRes.value.tabular ?? [])]))
if (exts.length > 0) setAcceptExt(exts.join(','))
}
})()
return () => {
cancelled = true
abortRef.current?.()
}
}, [])
useEffect(() => {
setSelectedSourceIds(resolveDefaultScope())
setScopeOpen(false)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentSourceId, currentSourceName])
useEffect(() => {
const el = logRef.current
if (el) el.scrollTop = el.scrollHeight
}, [turns])
const selectedSourceSummary = useMemo(() => {
if (selectedSourceIds.length === 0) return '未选数据源(仅文档)'
const names = enabledSources
.filter((s) => selectedSourceIds.includes(s.id))
.map((s) => s.name)
if (names.length === 0) return currentSourceName || '当前数据源'
if (names.length <= 2) return names.join('、')
return `${names.slice(0, 2).join('、')} 等 ${names.length} 个源`
}, [enabledSources, selectedSourceIds, currentSourceName])
const toggleSourceScope = (id: string) => {
setSelectedSourceIds((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]))
}
// 按最后一次同 id 提案去重,筛出当前保留在待保存区的修改项
const pendingItems = useMemo(() => {
const map = new Map<string, EntityPatchChange>()
for (const ch of allProposed) {
map.set(ch.id, ch)
}
const items: EntityPatchChange[] = []
for (const ch of map.values()) {
if ((changeStates[ch.id] ?? 'pending') === 'pending') {
items.push(ch)
}
}
return items
}, [allProposed, changeStates])
const uploadFile = async (file: File | null) => {
if (!file) return
setUploading(true)
setDocError(null)
try {
const res = await api.ontology.uploadAttachment(file, {
saveToKb,
collection,
})
setAttachments((prev) => [...prev, res])
if (res.saved_to_kb && res.document_id) {
toast.ok(`已挂载《${res.title}》并存入知识库`)
const docs = await api.kb.documents().catch(() => null)
if (docs) setKbDocs(docs.filter((d) => d.status !== 'failed'))
} else {
toast.ok(`已挂载《${res.title}》`)
}
} catch (err) {
setDocError(errText(err))
} finally {
setUploading(false)
if (fileRef.current) fileRef.current.value = ''
}
}
const buildHistory = (list: ChatTurn[]): EntityAssistantMessage[] => {
const out: EntityAssistantMessage[] = []
for (const t of list) {
if (t.role === 'user') {
out.push({ role: 'user', content: t.content })
} else {
const txt = t.parts
.filter((p): p is { kind: 'text'; text: string } => p.kind === 'text')
.map((p) => p.text)
.join('')
.trim()
if (txt) out.push({ role: 'assistant', content: txt })
}
}
return out
}
const sendMessage = (overrideText?: string) => {
const text = (overrideText ?? input).trim()
if (!text || streaming) return
setInput('')
setSaveError(null)
setSavedNotice(null)
const seq = ++seqRef.current
const userTurn: UserTurn = { id: `u${seq}`, role: 'user', content: text }
const replyId = `a${seq}`
const assistantTurn: AssistantTurn = { id: replyId, role: 'assistant', parts: [], state: 'streaming' }
const nextTurns = [...turns, userTurn, assistantTurn]
setTurns(nextTurns)
const updateReply = (fn: (cur: AssistantTurn) => AssistantTurn) => {
setTurns((prev) => prev.map((t) => (t.id === replyId && t.role === 'assistant' ? fn(t) : t)))
}
const cancel = api.ontology.streamAssistant(
{
messages: buildHistory([...turns, userTurn]),
source_ids: selectedSourceIds,
focus_entity_key: focusEntityKey,
attachment_ids: attachments.map((a) => a.attachment_id),
document_ids: selectedKbIds,
pending_ops: pendingItems.map((p) => p.op_payload),
},
(ev: EntityAssistantEvent) => {
if (ev.type === 'text') {
updateReply((cur) => {
const parts = [...cur.parts]
const last = parts[parts.length - 1]
if (last && last.kind === 'text') {
parts[parts.length - 1] = { kind: 'text', text: last.text + ev.delta }
} else {
parts.push({ kind: 'text', text: ev.delta })
}
return { ...cur, parts }
})
} else if (ev.type === 'query') {
updateReply((cur) => ({
...cur,
parts: [
...cur.parts,
{
kind: 'query',
source: ev.source,
sql: ev.sql,
columns: ev.columns ?? [],
rows: ev.rows ?? [],
rowCount: ev.row_count ?? 0,
truncated: Boolean(ev.truncated),
error: ev.error,
},
],
}))
} else if (ev.type === 'proposal') {
const incoming = ev.changes ?? []
if (incoming.length > 0) {
setAllProposed((prev) => [...prev, ...incoming])
setChangeStates((prev) => {
const copy = { ...prev }
for (const ch of incoming) copy[ch.id] = 'pending'
return copy
})
if (ev.expected_versions) {
setExpectedVersions((prev) => ({ ...prev, ...ev.expected_versions }))
}
updateReply((cur) => ({
...cur,
parts: [
...cur.parts,
{
kind: 'proposal',
id: `p_${Date.now()}_${incoming.length}`,
changes: incoming,
},
],
}))
}
} else if (ev.type === 'done') {
updateReply((cur) => ({ ...cur, state: 'done', queries: ev.queries ?? 0 }))
} else if (ev.type === 'error') {
updateReply((cur) => ({ ...cur, state: 'error', error: ev.message }))
}
},
(end) => {
abortRef.current = null
if (end.aborted) {
updateReply((cur) => (cur.state === 'streaming' ? { ...cur, state: 'stopped' } : cur))
} else if (end.error) {
updateReply((cur) => ({ ...cur, state: 'error', error: end.error }))
} else {
updateReply((cur) => (cur.state === 'streaming' ? { ...cur, state: 'done' } : cur))
}
},
)
abortRef.current = cancel
}
const stopStream = () => {
abortRef.current?.()
abortRef.current = null
}
const toggleProposalItem = (id: string) => {
setChangeStates((prev) => ({
...prev,
[id]: (prev[id] ?? 'pending') === 'pending' ? 'dropped' : 'pending',
}))
}
const clearPending = () => {
setAllProposed([])
setChangeStates({})
setExpectedVersions({})
setSaveError(null)
}
const savePending = async () => {
if (pendingItems.length === 0 || saving) return
setSaving(true)
setSaveError(null)
setSavedNotice(null)
try {
const touchedKeys = new Set(pendingItems.map((p) => p.entity_key))
const versions: Record<string, number> = {}
for (const k of touchedKeys) {
if (k in expectedVersions) versions[k] = expectedVersions[k]
}
const res = await api.ontology.applyPatch({
operations: pendingItems.map((p) => p.op_payload),
expected_versions: Object.keys(versions).length > 0 ? versions : undefined,
})
clearPending()
setSavedNotice(`已保存 ${res.applied_count} 项实体变更(新建 ${res.created_entities} 个,更新 ${res.updated_entities} 个)`)
toast.ok('标准业务实体修改已生效')
onApplied(res)
} catch (err) {
setSaveError(errText(err))
} finally {
setSaving(false)
}
}
const availableKbToAdd = kbDocs.filter((d) => !selectedKbIds.includes(d.id))
return (
<aside
className="flex h-full w-[380px] shrink-0 flex-col border-l bg-panel text-xs 2xl:w-[420px]"
aria-label="实体助手"
data-entity-assistant=""
>
{/* 顶栏 */}
<div className="flex items-center justify-between border-b px-3 py-2.5">
<div className="flex items-center gap-1.5">
<Sparkles size={14} className="text-[var(--accent)]" aria-hidden />
<span className="font-semibold text-fg">实体助手</span>
{focusEntityLabel && (
<span className="truncate rounded border px-1.5 py-0.5 text-2xs text-faint">
当前:{focusEntityLabel}
</span>
)}
</div>
<button
type="button"
className="btn btn-xs btn-ghost"
onClick={() => {
stopStream()
onClose()
}}
aria-label="关闭实体助手"
data-entity-assistant-close=""
>
<X size={13} aria-hidden />
</button>
</div>
{/* 参与分析的数据源范围(默认仅当前数据源,需要跨源对齐时按需勾选) */}
{enabledSources.length > 0 && (
<div className="border-b bg-bg/40 px-3 py-2 text-2xs" data-entity-assistant-scope="">
<div className="flex items-center justify-between gap-2">
<div className="flex min-w-0 items-center gap-1.5 text-dim">
<Database size={11} className="shrink-0 text-faint" aria-hidden />
<span className="shrink-0">数据范围:</span>
<span className="truncate font-mono text-fg" data-entity-assistant-scope-summary="">
{selectedSourceSummary}
</span>
</div>
{enabledSources.length > 1 && (
<button
type="button"
className="btn btn-xs btn-ghost shrink-0"
disabled={streaming}
onClick={() => setScopeOpen((v) => !v)}
data-entity-assistant-scope-toggle=""
>
{scopeOpen ? '收起' : `跨源选择(${selectedSourceIds.length}/${enabledSources.length})`}
</button>
)}
</div>
{scopeOpen && enabledSources.length > 1 && (
<div className="mt-2 space-y-1.5 rounded border bg-panel p-2" data-entity-assistant-scope-panel="">
<div className="flex items-center justify-between text-faint">
<span>勾选本次要一起对齐的数据源</span>
<div className="flex items-center gap-1">
<button
type="button"
className="btn btn-xs btn-ghost"
onClick={() => setSelectedSourceIds(resolveDefaultScope())}
>
仅当前源
</button>
<button
type="button"
className="btn btn-xs btn-ghost"
onClick={() =>
setSelectedSourceIds(
selectedSourceIds.length === enabledSources.length ? [] : enabledSources.map((s) => s.id),
)
}
>
{selectedSourceIds.length === enabledSources.length ? '清空' : '全选'}
</button>
</div>
</div>
<div className="grid max-h-28 gap-1 overflow-y-auto sm:grid-cols-2">
{enabledSources.map((src) => (
<label key={src.id} className="flex cursor-pointer items-center gap-1.5 rounded px-1.5 py-0.5 hover:bg-elev">
<input
type="checkbox"
checked={selectedSourceIds.includes(src.id)}
onChange={() => toggleSourceScope(src.id)}
data-entity-assistant-source={src.id}
/>
<span className="truncate font-mono text-fg">{src.name}</span>
</label>
))}
</div>
</div>
)}
</div>
)}
{/* 业务文档与对照表挂载区 */}
<div className="space-y-1.5 border-b bg-bg/50 px-3 py-2" data-entity-doc-bar="">
<div className="flex flex-wrap items-center justify-between gap-1.5">
<div className="flex items-center gap-1.5">
<input
ref={fileRef}
type="file"
accept={acceptExt}
className="hidden"
onChange={(e) => void uploadFile(e.target.files?.[0] ?? null)}
data-entity-doc-input=""
/>
<button
type="button"
className="btn btn-xs"
disabled={uploading || streaming}
onClick={() => fileRef.current?.click()}
data-entity-doc-upload=""
>
{uploading ? <Spinner size={11} /> : <Paperclip size={11} aria-hidden />}
{uploading ? '正在解析…' : '挂载文档/对照表'}
</button>
{availableKbToAdd.length > 0 && (
<select
className="field max-w-[155px] py-0.5 text-2xs"
value=""
onChange={(e) => {
const id = e.target.value
if (id && !selectedKbIds.includes(id)) setSelectedKbIds((prev) => [...prev, id])
}}
aria-label="关联已有知识库文档"
data-entity-doc-kb-select=""
>
<option value="">关联知识库文档…</option>
{availableKbToAdd.map((doc) => (
<option key={doc.id} value={doc.id}>
{doc.title}
</option>
))}
</select>
)}
</div>
</div>
<div className="flex flex-wrap items-center gap-2 text-2xs text-dim">
<label className="inline-flex cursor-pointer items-center gap-1">
<input
type="checkbox"
checked={saveToKb}
onChange={(e) => setSaveToKb(e.target.checked)}
data-entity-doc-save-kb=""
/>
<span>同时存入知识库供后续复用</span>
</label>
{saveToKb && (
<select
className="field py-0 text-2xs"
value={collection}
onChange={(e) => setCollection(e.target.value)}
aria-label="选择知识库集合"
data-entity-doc-collection=""
>
{collections.map((c) => (
<option key={c} value={c}>{c}</option>
))}
</select>
)}
</div>
{docError && <Notice tone="err">{docError}</Notice>}
{(attachments.length > 0 || selectedKbIds.length > 0) && (
<div className="flex flex-wrap gap-1 pt-0.5">
{attachments.map((att) => (
<span
key={att.attachment_id}
className="inline-flex max-w-full items-center gap-1 rounded border bg-panel px-1.5 py-0.5 text-2xs"
data-entity-attached-doc={att.title}
>
<FileText size={10} className="shrink-0 text-faint" aria-hidden />
<span className="truncate">{att.title}</span>
{att.saved_to_kb && <span className="text-[var(--ok)]">· 已存知识库</span>}
<button
type="button"
className="text-faint hover:text-fg"
onClick={() => setAttachments((prev) => prev.filter((x) => x.attachment_id !== att.attachment_id))}
aria-label={`移除 ${att.title}`}
>
<X size={10} aria-hidden />
</button>
</span>
))}
{selectedKbIds.map((docId) => {
const doc = kbDocs.find((d) => d.id === docId)
const title = doc?.title ?? docId
return (
<span
key={docId}
className="inline-flex max-w-full items-center gap-1 rounded border bg-panel px-1.5 py-0.5 text-2xs"
data-entity-attached-doc={title}
>
<FileText size={10} className="shrink-0 text-faint" aria-hidden />
<span className="truncate">{title}</span>
<span className="text-faint">· 知识库</span>
<button
type="button"
className="text-faint hover:text-fg"
onClick={() => setSelectedKbIds((prev) => prev.filter((x) => x !== docId))}
aria-label={`移除 ${title}`}
>
<X size={10} aria-hidden />
</button>
</span>
)
})}
</div>
)}
</div>
{/* 对话记录 */}
<div
ref={logRef}
className="min-h-0 flex-1 space-y-3 overflow-y-auto p-3"
aria-busy={streaming}
data-entity-assistant-log=""
>
<div className="space-y-1.5 rounded-lg border bg-bg px-3 py-2.5 text-xs leading-relaxed text-dim">
<p>
告诉我需要添加或调整的业务实体,或者直接挂载业务文档、编码对照表;默认只分析当前数据源,如需跨库对齐可在上方点「跨源选择」加入目标库。
</p>
<div className="flex flex-wrap gap-1.5 pt-1">
<button
type="button"
className="btn btn-xs btn-ghost"
disabled={streaming}
onClick={() =>
sendMessage(
selectedSourceIds.length > 1
? '请盘点当前所选数据源之间值得优先对齐的标准业务实体并给出建议'
: '请盘点当前选定数据源中值得建立或完善的标准业务实体、表列绑定与口径参数,并给出建议',
)
}
data-entity-assistant-quick=""
>
{selectedSourceIds.length > 1 ? '盘点所选源可对齐实体' : '盘点当前源业务实体'}
</button>
</div>
</div>
{turns.map((turn) =>
turn.role === 'user' ? (
<div key={turn.id} className="flex justify-end" data-entity-assistant-msg="user">
<div className="max-w-[85%] whitespace-pre-wrap break-words rounded-lg bg-[var(--accent)]/15 px-3 py-2 text-fg">
{turn.content}
</div>
</div>
) : (
<div key={turn.id} className="space-y-2" data-entity-assistant-msg="assistant" data-turn-state={turn.state}>
{turn.parts.map((part, idx) => {
if (part.kind === 'text') {
return (
<div
key={idx}
className="min-w-0 break-words text-xs text-fg"
data-entity-assistant-text=""
>
<Markdown text={part.text} dense />
</div>
)
}
if (part.kind === 'query') {
return (
<details
key={idx}
className="rounded-lg border bg-bg text-2xs"
data-entity-assistant-query={part.error ? 'error' : 'ok'}
>
<summary className="cursor-pointer px-2.5 py-1.5 text-dim">
只读核查 · <span className="font-mono text-fg">{part.source}</span>
{part.error ? '(查询未成功)' : `(${part.rowCount} 行)`}
</summary>
<div className="space-y-1.5 border-t px-2.5 py-2">
<pre className="mono max-h-32 overflow-auto whitespace-pre-wrap break-words rounded bg-panel px-2 py-1">
{part.sql}
</pre>
{part.error ? (
<p className="text-[var(--err)]">{part.error}</p>
) : part.columns.length > 0 ? (
<div className="max-h-36 overflow-auto">
<table className="w-full border-collapse text-left">
<thead>
<tr className="border-b text-faint">
{part.columns.map((c) => (
<th key={c} className="px-1.5 py-1 font-medium">{c}</th>
))}
</tr>
</thead>
<tbody>
{part.rows.map((r, ri) => (
<tr key={ri} className="border-b last:border-b-0">
{r.map((cell, ci) => (
<td key={ci} className="px-1.5 py-1 font-mono">{cell == null ? 'NULL' : String(cell)}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
) : null}
</div>
</details>
)
}
return (
<section
key={part.id}
className="rounded-lg border bg-bg"
data-entity-assistant-proposal=""
>
<div className="border-b px-2.5 py-1.5 text-2xs font-medium text-fg">
实体修改提案 · {part.changes.length} 项
</div>
<ul className="divide-y">
{part.changes.map((c) => {
const state = changeStates[c.id] ?? 'pending'
const kept = state === 'pending'
return (
<li
key={c.id}
className={clsx('flex items-start justify-between gap-2 px-2.5 py-2 text-2xs', !kept && 'opacity-50')}
data-entity-proposal-item={c.id}
data-proposal-state={state}
>
<div className="min-w-0 space-y-0.5">
<div className="font-medium text-fg">{c.summary}</div>
{c.reason && <div className="text-faint">依据:{c.reason}</div>}
</div>
<button
type="button"
className="btn btn-xs shrink-0"
onClick={() => toggleProposalItem(c.id)}
data-entity-proposal-toggle=""
>
{kept ? '移出' : '保留'}
</button>
</li>
)
})}
</ul>
</section>
)
})}
{turn.state === 'streaming' && (
<div className="flex items-center gap-1.5 text-2xs text-faint">
<Spinner size={11} /> 正在思考与核对…
</div>
)}
{turn.state === 'error' && turn.error && (
<Notice tone="err" attr={{ 'data-entity-assistant-error': '' }}>
{turn.error}
</Notice>
)}
{turn.state === 'stopped' && (
<p className="text-2xs text-faint">已停止本轮回答</p>
)}
</div>
),
)}
</div>
{/* 保存反馈 */}
{saveError && (
<div className="border-t px-3 py-2">
<Notice tone="err" attr={{ 'data-entity-assistant-save-error': '' }}>{saveError}</Notice>
</div>
)}
{savedNotice && (
<div className="border-t px-3 py-2">
<Notice tone="info" attr={{ 'data-entity-assistant-saved': '' }}>{savedNotice}</Notice>
</div>
)}
{/* 待保存提案汇总条 */}
{pendingItems.length > 0 && (
<section className="space-y-2 border-t bg-elev px-3 py-2.5" data-entity-assistant-pending={pendingItems.length}>
<div className="flex items-center justify-between gap-2 text-2xs">
<span className="font-medium text-fg">待保存修改 · {pendingItems.length} 项</span>
<div className="flex items-center gap-1.5">
<button
type="button"
className="btn btn-xs btn-ghost"
disabled={saving}
onClick={clearPending}
data-entity-assistant-clear=""
>
清空
</button>
<button
type="button"
className="btn btn-xs btn-primary"
disabled={saving || streaming}
onClick={() => void savePending()}
data-entity-assistant-save=""
>
<Check size={11} aria-hidden />
{saving ? '正在保存…' : '保存修改'}
</button>
</div>
</div>
</section>
)}
{/* 输入框 */}
<div className="border-t p-2.5">
<div className="flex items-end gap-1.5">
<textarea
className="field min-h-[58px] flex-1 resize-none text-xs"
rows={2}
maxLength={4000}
placeholder="例如:根据刚上传的对照表,把 MES 和 ERP 的产线编码关联到生产产线实体…"
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey && !isComposing(e)) {
e.preventDefault()
sendMessage()
}
}}
data-entity-assistant-input=""
/>
{streaming ? (
<button
type="button"
className="btn btn-sm"
onClick={stopStream}
title="停止回答"
data-entity-assistant-stop=""
>
<Square size={12} aria-hidden /> 停止
</button>
) : (
<button
type="button"
className="btn btn-sm btn-primary"
disabled={!input.trim()}
onClick={() => sendMessage()}
data-entity-assistant-send=""
>
<Send size={12} aria-hidden /> 发送
</button>
)}
</div>
</div>
</aside>
)
}
@@ -0,0 +1,339 @@
import { useEffect, useRef, useState } from 'react'
import { FileText, Sparkles, Upload, X } from 'lucide-react'
import { api } from '../../api/client'
import type { DataSourceName, KbDocument } from '../../types'
import type { EntityAttachmentOut, EntityDiscoveryJob } from '../../typesLedger'
import { ErrorState, Modal, Notice, Spinner, toast } from '../../components/ui'
const DEFAULT_ACCEPT = '.md,.markdown,.txt,.pdf,.docx,.pptx,.html,.htm,.xlsx,.csv,.tsv,.json,.yaml,.yml'
export function EntityDiscoverDialog({
open,
onClose,
sources,
defaultSourceId,
onStarted,
}: {
open: boolean
onClose: () => void
sources: DataSourceName[]
defaultSourceId?: string
onStarted: (job: EntityDiscoveryJob) => void
}) {
const enabledSources = sources.filter((s) => s.enabled !== false)
const [selectedSources, setSelectedSources] = useState<string[]>([])
const [kbDocs, setKbDocs] = useState<KbDocument[]>([])
const [collections, setCollections] = useState<string[]>(['default'])
const [acceptExt, setAcceptExt] = useState(DEFAULT_ACCEPT)
const [selectedDocIds, setSelectedDocIds] = useState<string[]>([])
const [attachments, setAttachments] = useState<EntityAttachmentOut[]>([])
const [saveToKb, setSaveToKb] = useState(false)
const [collection, setCollection] = useState('default')
const [uploading, setUploading] = useState(false)
const [note, setNote] = useState('')
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState<unknown>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
useEffect(() => {
if (!open) return
const initialSources =
defaultSourceId && enabledSources.some((s) => s.id === defaultSourceId)
? [defaultSourceId]
: enabledSources.map((s) => s.id)
setSelectedSources(initialSources)
setSelectedDocIds([])
setAttachments([])
setNote('')
setError(null)
let cancelled = false
void (async () => {
const [docsRes, colsRes, fmtRes] = await Promise.allSettled([
api.kb.documents(),
api.kb.collections(),
api.kb.formats(),
])
if (cancelled) return
if (docsRes.status === 'fulfilled') {
setKbDocs(docsRes.value.filter((d) => d.status !== 'failed'))
}
if (colsRes.status === 'fulfilled' && colsRes.value.length > 0) {
const names = Array.from(new Set(['default', ...colsRes.value.map((c) => c.collection).filter(Boolean)]))
setCollections(names)
}
if (fmtRes.status === 'fulfilled') {
const exts = Array.from(new Set([...(fmtRes.value.extensions ?? []), ...(fmtRes.value.tabular ?? [])]))
if (exts.length > 0) setAcceptExt(exts.join(','))
}
})()
return () => {
cancelled = true
}
}, [open, sources, defaultSourceId])
const toggleSource = (id: string) => {
setSelectedSources((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]))
}
const toggleKbDoc = (id: string) => {
setSelectedDocIds((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]))
}
const handleFileChange = async (file: File | null) => {
if (!file) return
setUploading(true)
setError(null)
try {
const uploaded = await api.ontology.uploadAttachment(file, {
saveToKb,
collection,
})
setAttachments((prev) => [...prev, uploaded])
if (uploaded.saved_to_kb && uploaded.document_id) {
toast.ok(`已解析《${uploaded.title}》并同步存入知识库`)
const docs = await api.kb.documents().catch(() => null)
if (docs) setKbDocs(docs.filter((d) => d.status !== 'failed'))
} else {
toast.ok(`已解析文档《${uploaded.title}》`)
}
} catch (err) {
setError(err)
} finally {
setUploading(false)
if (fileInputRef.current) fileInputRef.current.value = ''
}
}
const submit = async () => {
if (selectedSources.length === 0 && selectedDocIds.length === 0 && attachments.length === 0) return
setSubmitting(true)
setError(null)
try {
const job = await api.ontology.createDiscoveryJob({
source_ids: selectedSources,
document_ids: selectedDocIds,
attachment_ids: attachments.map((a) => a.attachment_id),
note: note.trim() || undefined,
})
toast.ok('已启动候选业务实体扫描任务')
onStarted(job)
onClose()
} catch (err) {
setError(err)
} finally {
setSubmitting(false)
}
}
return (
<Modal
open={open}
onClose={onClose}
title="扫描发现候选业务实体"
width={620}
footer={(
<div className="flex items-center justify-end gap-2">
<button type="button" className="btn btn-sm btn-ghost" onClick={onClose} disabled={submitting}>
取消
</button>
<button
type="button"
className="btn btn-sm btn-primary"
disabled={
submitting
|| uploading
|| (selectedSources.length === 0 && selectedDocIds.length === 0 && attachments.length === 0)
}
onClick={() => void submit()}
data-discover-submit=""
>
<Sparkles size={13} aria-hidden />
{submitting ? '正在提交…' : '开始扫描发现'}
</button>
</div>
)}
>
<div className="space-y-4 text-xs" data-entity-discover-dialog="">
<Notice tone="info">
扫描结果中所有新增的表列绑定与口径参数映射均标记为「待确认」,不会直接影响线上问数穿透;扫描完成后可在实体列表逐项确认生效。
</Notice>
{error != null && <ErrorState error={error} compact />}
{/* 1. 参与扫描的数据源 */}
<section className="space-y-1.5">
<div className="flex items-center justify-between">
<span className="font-medium text-fg">参与扫描的数据源({selectedSources.length}/{enabledSources.length})</span>
{enabledSources.length > 0 && (
<div className="flex items-center gap-1">
{defaultSourceId && enabledSources.some((s) => s.id === defaultSourceId) && (
<button
type="button"
className="btn btn-xs btn-ghost"
onClick={() => setSelectedSources([defaultSourceId])}
>
仅当前源
</button>
)}
<button
type="button"
className="btn btn-xs btn-ghost"
onClick={() =>
setSelectedSources(
selectedSources.length === enabledSources.length ? [] : enabledSources.map((s) => s.id),
)
}
>
{selectedSources.length === enabledSources.length ? '清空选择' : '全选启用源'}
</button>
</div>
)}
</div>
{enabledSources.length === 0 ? (
<p className="text-2xs text-faint">暂无已启用的数据源,可上传业务文档或对照表提取实体定义。</p>
) : (
<div className="grid max-h-32 gap-1.5 overflow-y-auto rounded border p-2 sm:grid-cols-2">
{enabledSources.map((src) => (
<label key={src.id} className="flex cursor-pointer items-center gap-2 rounded px-1.5 py-1 hover:bg-elev">
<input
type="checkbox"
checked={selectedSources.includes(src.id)}
onChange={() => toggleSource(src.id)}
data-discover-source={src.id}
/>
<span className="truncate font-mono text-fg">{src.name}</span>
<span className="text-2xs text-faint">({src.kind})</span>
</label>
))}
</div>
)}
</section>
{/* 2. 上传业务文档或编码对照表 */}
<section className="space-y-2 rounded border p-2.5">
<div className="flex flex-wrap items-center justify-between gap-2">
<div>
<div className="font-medium text-fg">上传业务文档或主数据对照表(可选)</div>
<p className="text-2xs text-faint">支持 Markdown、Word、PDF 及 Excel / CSV 跨系统编码对照表。</p>
</div>
<div>
<input
ref={fileInputRef}
type="file"
accept={acceptExt}
className="hidden"
onChange={(e) => void handleFileChange(e.target.files?.[0] ?? null)}
data-discover-doc-input=""
/>
<button
type="button"
className="btn btn-xs"
disabled={uploading || submitting}
onClick={() => fileInputRef.current?.click()}
data-discover-doc-upload=""
>
{uploading ? <Spinner size={12} /> : <Upload size={12} aria-hidden />}
{uploading ? '正在解析…' : '选择文件'}
</button>
</div>
</div>
<div className="flex flex-wrap items-center gap-3 pt-0.5">
<label className="inline-flex cursor-pointer items-center gap-1.5 text-2xs text-dim">
<input
type="checkbox"
checked={saveToKb}
onChange={(e) => setSaveToKb(e.target.checked)}
data-discover-doc-save-kb=""
/>
<span>同时存入知识库供后续复用</span>
</label>
{saveToKb && (
<label className="inline-flex items-center gap-1.5 text-2xs text-dim">
<span>存入集合:</span>
<select
className="field py-0.5 text-2xs"
value={collection}
onChange={(e) => setCollection(e.target.value)}
data-discover-doc-collection=""
>
{collections.map((c) => (
<option key={c} value={c}>{c}</option>
))}
</select>
</label>
)}
</div>
{attachments.length > 0 && (
<ul className="space-y-1 pt-1">
{attachments.map((att) => (
<li
key={att.attachment_id}
className="flex items-center justify-between gap-2 rounded border bg-bg px-2 py-1 text-2xs"
data-discover-attachment={att.attachment_id}
>
<div className="flex min-w-0 items-center gap-1.5">
<FileText size={12} className="shrink-0 text-faint" aria-hidden />
<span className="truncate text-fg">{att.title}</span>
<span className="text-faint">({att.chunk_count} 段)</span>
{att.saved_to_kb && (
<span className="rounded border border-[var(--ok)]/30 px-1 py-0.2 text-[var(--ok)]">
已存入知识库
</span>
)}
</div>
<button
type="button"
className="btn btn-xs btn-ghost text-faint"
onClick={() => setAttachments((prev) => prev.filter((x) => x.attachment_id !== att.attachment_id))}
aria-label={`移除附件 ${att.title}`}
>
<X size={11} aria-hidden />
</button>
</li>
))}
</ul>
)}
</section>
{/* 3. 关联已有知识库文档 */}
{kbDocs.length > 0 && (
<section className="space-y-1.5">
<div className="font-medium text-fg">关联已有知识库文档(已选 {selectedDocIds.length} 份)</div>
<div className="max-h-28 space-y-1 overflow-y-auto rounded border p-2">
{kbDocs.map((doc) => (
<label key={doc.id} className="flex cursor-pointer items-center justify-between gap-2 rounded px-1.5 py-1 hover:bg-elev">
<span className="flex min-w-0 items-center gap-2">
<input
type="checkbox"
checked={selectedDocIds.includes(doc.id)}
onChange={() => toggleKbDoc(doc.id)}
data-discover-kb-doc={doc.id}
/>
<span className="truncate text-fg">{doc.title}</span>
</span>
<span className="shrink-0 text-2xs text-faint">{doc.collection}</span>
</label>
))}
</div>
</section>
)}
{/* 4. 扫描重点补充说明 */}
<label className="block space-y-1">
<span className="font-medium text-fg">扫描重点说明(可选)</span>
<textarea
className="field w-full"
rows={2}
maxLength={1000}
placeholder="例如:重点对齐 MES 与 ERP 的产线、车间和不良原因编码"
value={note}
onChange={(e) => setNote(e.target.value)}
data-discover-note=""
/>
</label>
</div>
</Modal>
)
}
+20 -6
View File
@@ -7,15 +7,16 @@ import { errorMessage } from '../../lib/errors'
import { formatCost, formatDateTime, shortId } from '../../lib/format'
import { EVAL_TEXT } from '../../lib/termsEval'
import type {
EvalAnalysisTools, EvalCatalogMode, EvalEstimate, EvalRun, EvalSnapshot, EvalStartBody, EvalSuite, EvalVariant,
EvalAnalysisTools, EvalCatalogMode, EvalEstimate, EvalOntologyTools, EvalRun, EvalSnapshot, EvalStartBody, EvalSuite, EvalVariant,
} from '../../typesEval'
import { ModelPick } from './parts'
const T = EVAL_TEXT.start
const MODES = ['single', 'ab', 'catalog', 'analysis_tools'] as const
const MODES = ['single', 'ab', 'catalog', 'analysis_tools', 'ontology_tools'] as const
type Mode = (typeof MODES)[number]
const CATALOG_MODES: EvalCatalogMode[] = ['live', 'reviewed', 'off', 'snapshot']
const ANALYSIS_TOOLS: EvalAnalysisTools[] = ['on', 'off']
const ONTOLOGY_TOOLS: EvalOntologyTools[] = ['on', 'off']
/** 一臂的变体(表单里的样子):全部键都在,交上去之前不改形状 */
export function blankVariant(base?: Partial<EvalVariant>): EvalVariant {
@@ -25,6 +26,7 @@ export function blankVariant(base?: Partial<EvalVariant>): EvalVariant {
judge: base?.judge ?? false,
catalog: { mode: base?.catalog?.mode ?? 'live', snapshot: base?.catalog?.snapshot ?? null },
analysis: { tools: base?.analysis?.tools ?? 'on' },
ontology: { tools: base?.ontology?.tools ?? 'on' },
repeats: base?.repeats ?? 1,
label: base?.label ?? null,
}
@@ -45,9 +47,9 @@ export function snapshotLabel(s: EvalSnapshot): string {
* 重复次数,名字。题集设置里的「默认变体」也用它(定时评测按默认变体评)。预设对照里由预设定的那一项(目录、分析工具)不摆
*/
export function ArmFields({ idPrefix, value, onChange, snapshots, withLabel = false, labelIndex = 0, hideCatalog = false,
hideAnalysis = false }: {
hideAnalysis = false, hideOntology = false }: {
idPrefix: string; value: EvalVariant; onChange: (v: EvalVariant) => void; snapshots: EvalSnapshot[]
withLabel?: boolean; labelIndex?: number; hideCatalog?: boolean; hideAnalysis?: boolean
withLabel?: boolean; labelIndex?: number; hideCatalog?: boolean; hideAnalysis?: boolean; hideOntology?: boolean
}) {
const set = (patch: Partial<EvalVariant>) => onChange({ ...value, ...patch })
const usable = usableSnapshots(snapshots)
@@ -95,6 +97,14 @@ export function ArmFields({ idPrefix, value, onChange, snapshots, withLabel = fa
</select>
</Field>
)}
{!hideOntology && (
<Field label={T.ontologyTools} htmlFor={`${idPrefix}-ontology`} hint={T.ontologyToolsHint}>
<select id={`${idPrefix}-ontology`} className="field w-24" value={value.ontology?.tools ?? 'on'} data-eval-ontology-tools=""
onChange={(e) => set({ ontology: { tools: e.target.value as EvalOntologyTools } })}>
{ONTOLOGY_TOOLS.map((m) => <option key={m} value={m}>{T.ontologyToolsMode[m]}</option>)}
</select>
</Field>
)}
<Field label={T.repeats} htmlFor={`${idPrefix}-repeats`} hint={T.repeatsHint}>
<select id={`${idPrefix}-repeats`} className="field w-24" value={value.repeats} data-eval-repeats=""
onChange={(e) => set({ repeats: Number(e.target.value) })}>
@@ -145,7 +155,7 @@ export function StartDialog({ open, onClose, suite, evaluations, onStarted }: {
const repeats = Math.max(first.repeats, 3)
return cur.length >= 2 ? cur : [{ ...first, repeats, label: first.label || 'A' }, { ...first, repeats, label: 'B' }]
}
return [m === 'catalog' || m === 'analysis_tools' ? { ...first, repeats: Math.max(first.repeats, 3) } : first]
return [m === 'catalog' || m === 'analysis_tools' || m === 'ontology_tools' ? { ...first, repeats: Math.max(first.repeats, 3) } : first]
})
}
@@ -161,6 +171,10 @@ export function StartDialog({ open, onClose, suite, evaluations, onStarted }: {
const { analysis: _a, label: _l, ...rest } = v
return { preset: 'analysis_tools', variant: rest, ...base }
}
if (mode === 'ontology_tools') {
const { ontology: _o, label: _l, ...rest } = v
return { preset: 'ontology_tools', variant: rest, ...base }
}
return { variant: v, ...base }
}, [mode, arms, reviewedArm, baseline])
const key = JSON.stringify(body)
@@ -224,7 +238,7 @@ export function StartDialog({ open, onClose, suite, evaluations, onStarted }: {
{mode !== 'ab' && (
<ArmFields idPrefix="eval-arm-0" value={arms[0] ?? blankVariant()} snapshots={snapshots} hideCatalog={mode === 'catalog'}
hideAnalysis={mode === 'analysis_tools'} onChange={(v) => setArms([v])} />
hideAnalysis={mode === 'analysis_tools'} hideOntology={mode === 'ontology_tools'} onChange={(v) => setArms([v])} />
)}
{mode === 'catalog' && (
<label className="flex items-center gap-2 text-xs">
+17 -1
View File
@@ -129,9 +129,25 @@ export function cellText(v: unknown): string {
return String(v)
}
const DIAGNOSIS_STAGE_LABELS: Record<string, string> = {
health_and_contract: '数据源健康与契约',
slice_localization: '切片定位',
ontology_penetration: '跨源本体穿透',
}
/** 一个期望是从哪里取什么:「「gmv」第 1 行」「指标「gmv」」「按「地区」配对的多行」…… */
export function expectationText(e: EvalExpectation): string {
if (e.kind === 'investigation') return `${e.status === 'partial' ? '明确保留调查缺口' : '完成调查'}${e.minimum_depth != null ? `,至少下钻 ${e.minimum_depth} 层` : ''}${e.max_queries != null ? `,最多查询 ${e.max_queries} 次` : ''}`
if (e.kind === 'investigation') {
const bits = [
e.status === 'partial' ? '明确保留调查缺口' : '完成调查',
e.require_source_health ? '需先核查数据源健康' : null,
e.min_ontology_hops != null ? `至少跨本体 ${e.min_ontology_hops} 跳` : null,
e.diagnosis_stage ? `诊断阶段:${DIAGNOSIS_STAGE_LABELS[e.diagnosis_stage] ?? e.diagnosis_stage}` : null,
e.minimum_depth != null ? `至少下钻 ${e.minimum_depth} 层` : null,
e.max_queries != null ? `最多查询 ${e.max_queries} 次` : null,
].filter(Boolean)
return bits.join(',')
}
const E = T.expectation
let text: string
switch (e.kind) {
+697
View File
@@ -0,0 +1,697 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Check, Plus, X } from 'lucide-react'
import clsx from 'clsx'
import { api } from '../../api/client'
import { ErrorState, Notice, Spinner, toast } from '../../components/ui'
import type {
CaliberDraft,
CanonicalEntity,
DraftMetric,
MetricOntologyLink,
OntologyFactorRole,
OntologyGraph,
OntologyLinkKind,
OntologyStatus,
WorkflowOntology,
} from '../../typesLedger'
const LINK_KIND_LABEL: Record<OntologyLinkKind, string> = {
factor: '构成因子',
reconciles_with: '跨源镜像对账',
upstream_driver: '跨源上游驱动',
}
const FACTOR_ROLE_LABEL: Record<OntologyFactorRole, string> = {
numerator: '分子',
denominator: '分母',
multiplier: '乘数',
addend: '加项',
subtrahend: '减项',
component: '组成部分',
}
const STATUS_LABEL: Record<OntologyStatus, string> = {
confirmed: '已确认',
verified: '已验证',
proposed: '待确认',
rejected: '已驳回',
}
function OntologyTopologySvg({
metrics,
workflowOntology,
publishedNames,
}: {
metrics: DraftMetric[]
workflowOntology: WorkflowOntology | null
publishedNames: Map<string, string>
}) {
const leftNodes: { id: string; label: string; sub: string }[] = []
const rightNodes: { id: string; label: string; sub: string }[] = []
const edges: {
fromId: string
toId: string
kind: OntologyLinkKind | 'lineage'
status: OntologyStatus
label: string
}[] = []
const leftSeen = new Set<string>()
const rightSeen = new Set<string>()
const centerNodes = metrics
.filter((m) => m.id)
.map((m) => ({ id: `self:${m.id!}`, metricId: m.id!, label: m.name || m.id! }))
const lineageMap = new Map<string, { source: string; tables: string[] }[]>()
for (const card of workflowOntology?.cards ?? []) {
for (const m of card.metrics ?? []) {
lineageMap.set(m.metric_id, m.lineage ?? [])
}
}
for (const m of metrics) {
if (!m.id) continue
const selfId = `self:${m.id}`
for (const link of m.links ?? []) {
if (link.status === 'rejected') continue
const tKey = `${link.target.workflow_id || 'self'}:${link.target.card_id}:${link.target.metric_id}`
const targetName = publishedNames.get(tKey)
?? metrics.find((x) => x.id === link.target.metric_id)?.name
?? link.target.metric_id
const sub = link.target.workflow_id ? `${link.target.workflow_id.slice(0, 8)} · ${link.target.card_id}` : '当前口径卡'
if (link.kind === 'factor') {
const nodeId = `right:${tKey}`
if (!rightSeen.has(nodeId)) {
rightSeen.add(nodeId)
rightNodes.push({ id: nodeId, label: targetName, sub })
}
edges.push({
fromId: selfId,
toId: nodeId,
kind: 'factor',
status: link.status ?? 'confirmed',
label: link.role ? FACTOR_ROLE_LABEL[link.role] : '构成因子',
})
} else {
const nodeId = `left:${tKey}`
if (!leftSeen.has(nodeId)) {
leftSeen.add(nodeId)
leftNodes.push({ id: nodeId, label: targetName, sub })
}
edges.push({
fromId: nodeId,
toId: selfId,
kind: link.kind,
status: link.status ?? 'confirmed',
label: LINK_KIND_LABEL[link.kind],
})
}
}
for (const lin of lineageMap.get(m.id) ?? []) {
const tableText = (lin.tables ?? []).join('、') || '取数表'
const nodeId = `table:${lin.source}:${tableText}`
if (!rightSeen.has(nodeId)) {
rightSeen.add(nodeId)
rightNodes.push({ id: nodeId, label: tableText, sub: `数据源:${lin.source}` })
}
edges.push({
fromId: selfId,
toId: nodeId,
kind: 'lineage',
status: 'verified',
label: '血缘',
})
}
}
const maxRows = Math.max(leftNodes.length, centerNodes.length, rightNodes.length, 1)
const rowH = 54
const height = Math.max(150, maxRows * rowH + 36)
const width = 680
const posMap = new Map<string, { x: number; y: number; w: number; h: number }>()
const placeCol = (list: { id: string }[], x: number) => {
const startY = Math.max(18, (height - list.length * rowH) / 2)
list.forEach((n, idx) => {
posMap.set(n.id, { x, y: startY + idx * rowH, w: 176, h: 38 })
})
}
placeCol(leftNodes, 16)
placeCol(centerNodes, 252)
placeCol(rightNodes, 488)
if (centerNodes.length === 0) return null
return (
<div className="space-y-1.5 rounded border bg-panel p-2.5" data-ontology-topology="">
<div className="flex flex-wrap items-center justify-between gap-2 text-2xs text-faint">
<span className="font-semibold text-dim">一跳本体拓扑与反向表血缘预览</span>
<span className="flex flex-wrap items-center gap-3">
<span>实线:已确认 / 已验证</span>
<span className="text-[var(--warn)]">虚线:建议态(待确认,不参与自动穿透)</span>
</span>
</div>
<div className="overflow-x-auto">
<svg
viewBox={`0 0 ${width} ${height}`}
className="h-auto w-full min-w-[540px]"
role="img"
aria-label="指标本体一跳拓扑图"
data-ontology-svg=""
>
{edges.map((edge, idx) => {
const a = posMap.get(edge.fromId)
const b = posMap.get(edge.toId)
if (!a || !b) return null
const x1 = a.x + a.w
const y1 = a.y + a.h / 2
const x2 = b.x
const y2 = b.y + b.h / 2
const mx = (x1 + x2) / 2
const stroke = edge.status === 'proposed'
? 'var(--warn)'
: edge.kind === 'lineage'
? 'var(--border-strong)'
: 'var(--accent)'
return (
<g key={idx}>
<path
d={`M ${x1} ${y1} C ${mx} ${y1}, ${mx} ${y2}, ${x2} ${y2}`}
fill="none"
stroke={stroke}
strokeWidth={1.5}
strokeDasharray={edge.status === 'proposed' ? '4 3' : undefined}
/>
<text
x={mx}
y={(y1 + y2) / 2 - 4}
textAnchor="middle"
fontSize="9"
fill="currentColor"
opacity={0.72}
>
{edge.label}
</text>
</g>
)
})}
{[...leftNodes.map((n) => ({ ...n, role: 'left' as const })),
...centerNodes.map((n) => ({ id: n.id, label: n.label, sub: '本卡指标', role: 'center' as const })),
...rightNodes.map((n) => ({ ...n, role: 'right' as const }))].map((node) => {
const p = posMap.get(node.id)
if (!p) return null
return (
<g key={node.id} transform={`translate(${p.x}, ${p.y})`}>
<rect
width={p.w}
height={p.h}
rx={6}
fill="var(--bg-elev)"
stroke={node.role === 'center' ? 'var(--accent)' : 'var(--border)'}
strokeWidth={node.role === 'center' ? 1.5 : 1}
/>
<text x={8} y={16} fontSize="11" fontWeight={node.role === 'center' ? 600 : 500} fill="currentColor">
{node.label.length > 14 ? `${node.label.slice(0, 14)}…` : node.label}
</text>
<text x={8} y={30} fontSize="9" fill="currentColor" opacity={0.6}>
{node.sub.length > 22 ? `${node.sub.slice(0, 22)}…` : node.sub}
</text>
</g>
)
})}
</svg>
</div>
</div>
)
}
export function OntologyPanel({
draft,
onSaved,
}: {
draft: CaliberDraft
onSaved: (fresh: CaliberDraft) => void
}) {
const metrics = useMemo(() => (draft.metrics ?? []).filter((m) => !!m.id), [draft.metrics])
const [open, setOpen] = useState(false)
const [busy, setBusy] = useState(false)
const [error, setError] = useState<unknown>(null)
const [entities, setEntities] = useState<CanonicalEntity[]>([])
const [graph, setGraph] = useState<OntologyGraph | null>(null)
const [workflowOntology, setWorkflowOntology] = useState<WorkflowOntology | null>(null)
const [selectedMetricId, setSelectedMetricId] = useState<string>(metrics[0]?.id ?? '')
const [kind, setKind] = useState<OntologyLinkKind>('reconciles_with')
const [pickedTarget, setPickedTarget] = useState('')
const [targetWorkflowId, setTargetWorkflowId] = useState('')
const [targetCardId, setTargetCardId] = useState('')
const [targetMetricId, setTargetMetricId] = useState('')
const [role, setRole] = useState<OntologyFactorRole>('component')
const [entityKey, setEntityKey] = useState('')
const [lagPeriods, setLagPeriods] = useState('0')
const [absTol, setAbsTol] = useState('')
const [relTol, setRelTol] = useState('0.02')
const [rationale, setRationale] = useState('')
const mounted = useRef(false)
useEffect(() => {
mounted.current = true
return () => { mounted.current = false }
}, [])
useEffect(() => {
if (!metrics.some((m) => m.id === selectedMetricId)) {
setSelectedMetricId(metrics[0]?.id ?? '')
}
}, [metrics, selectedMetricId])
const loadContext = useCallback(async () => {
try {
const [entRes, graphRes, wfRes] = await Promise.all([
api.ontology.listEntities().catch(() => ({ items: [] as CanonicalEntity[] })),
api.ontology.graph().catch(() => null),
draft.workflow_id ? api.ontology.workflow(draft.workflow_id).catch(() => null) : Promise.resolve(null),
])
if (!mounted.current) return
setEntities(entRes.items ?? [])
setGraph(graphRes)
setWorkflowOntology(wfRes)
} catch {
// 辅助拓扑信息读取失败不阻塞编辑
}
}, [draft.workflow_id])
useEffect(() => {
if (open) void loadContext()
}, [open, loadContext, draft.revision])
const publishedOptions = useMemo(() => {
const out: { key: string; workflow_id: string; card_id: string; metric_id: string; label: string }[] = []
if (draft.card_id) {
for (const m of metrics) {
if (!m.id) continue
out.push({
key: `${draft.workflow_id ?? ''}:${draft.card_id}:${m.id}`,
workflow_id: draft.workflow_id ?? '',
card_id: draft.card_id,
metric_id: m.id,
label: `当前口径卡 · ${m.name}(${m.id})`,
})
}
}
for (const card of graph?.cards ?? []) {
if (card.workflow_id === draft.workflow_id && card.card_id === draft.card_id) continue
for (const m of card.metrics ?? []) {
const key = `${card.workflow_id}:${card.card_id}:${m.metric_id}`
out.push({
key,
workflow_id: card.workflow_id,
card_id: card.card_id,
metric_id: m.metric_id,
label: `${card.caliber || card.workflow_name} v${card.version} · ${m.name}(${m.metric_id})`,
})
}
}
return out
}, [graph, metrics, draft.workflow_id, draft.card_id])
const publishedNames = useMemo(() => {
const map = new Map<string, string>()
for (const opt of publishedOptions) {
map.set(`${opt.workflow_id || 'self'}:${opt.card_id}:${opt.metric_id}`, opt.label.split(' · ').pop() ?? opt.metric_id)
}
return map
}, [publishedOptions])
if (!metrics.length || !draft.card_id || draft.revision == null) return null
const totalLinks = metrics.reduce((acc, m) => acc + (m.links?.filter((l) => l.status !== 'rejected').length ?? 0), 0)
const pendingLinks = metrics.reduce((acc, m) => acc + (m.links?.filter((l) => l.status === 'proposed').length ?? 0), 0)
const patchMetricLinks = async (metricId: string, nextLinks: MetricOntologyLink[], toastMsg: string) => {
setBusy(true)
setError(null)
try {
const reqId = globalThis.crypto?.randomUUID?.() ?? `ontology-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
const fresh = await api.caliberLedger.patchDraft(draft.id, {
operations: [{ op: 'set', metric_id: metricId, path: '/links', value: nextLinks }],
expected_revision: draft.revision!,
request_id: reqId,
target: { workflow_id: draft.workflow_id ?? undefined, card_id: draft.card_id! },
})
if (!mounted.current) return
onSaved(fresh)
toast.ok(toastMsg)
void loadContext()
} catch (e) {
if (mounted.current) setError(e)
} finally {
if (mounted.current) setBusy(false)
}
}
const addLink = async () => {
const metric = metrics.find((m) => m.id === selectedMetricId)
if (!metric?.id) return
const newLink: MetricOntologyLink = {
kind,
target: {
workflow_id: targetWorkflowId.trim(),
card_id: targetCardId.trim(),
metric_id: targetMetricId.trim(),
},
status: 'confirmed',
source: 'human',
...(kind === 'factor' ? { role } : {}),
...(entityKey ? { entity_key: entityKey } : {}),
...(kind === 'upstream_driver' && Number(lagPeriods) > 0 ? { lag_periods: Number(lagPeriods) } : {}),
...(kind === 'reconciles_with' && absTol.trim() !== '' ? { abs_tol: Number(absTol) } : {}),
...(kind === 'reconciles_with' && relTol.trim() !== '' ? { rel_tol: Number(relTol) } : {}),
...(rationale.trim() ? { rationale: rationale.trim() } : {}),
}
const existing = metric.links ?? []
await patchMetricLinks(metric.id, [...existing, newLink], '指标本体关系已保存;验证并发布该版本后生效')
setRationale('')
}
const updateLinkStatus = async (metric: DraftMetric, linkIdx: number, status: OntologyStatus) => {
if (!metric.id) return
const next = (metric.links ?? []).map((item, i) => (i === linkIdx ? { ...item, status } : item))
await patchMetricLinks(
metric.id,
next,
status === 'confirmed' ? '已确认该本体关系,发布后可参与跨源穿透' : '已驳回该候选本体关系',
)
}
const removeLink = async (metric: DraftMetric, linkIdx: number) => {
if (!metric.id) return
const next = (metric.links ?? []).filter((_, i) => i !== linkIdx)
await patchMetricLinks(metric.id, next, '已移除该本体关系')
}
const handlePickTarget = (val: string) => {
setPickedTarget(val)
const found = publishedOptions.find((o) => o.key === val)
if (found) {
setTargetWorkflowId(found.workflow_id)
setTargetCardId(found.card_id)
setTargetMetricId(found.metric_id)
}
}
return (
<details
className="rounded border p-2 text-xs"
data-ontology-panel=""
onToggle={(e) => setOpen((e.currentTarget as HTMLDetailsElement).open)}
>
<summary className="cursor-pointer font-semibold">
业务本体与跨源关系
{totalLinks > 0 ? ` · 已声明 ${totalLinks} 条` : '(可选配置)'}
{pendingLinks > 0 ? ` · 待确认 ${pendingLinks} 条` : ''}
</summary>
<div className="mt-3 space-y-3">
<p className="text-faint">
声明当前口径指标与其他口径指标之间的构成因子、跨源镜像对账或上游业务驱动关系。问数遇到异常时,仅沿「已确认」或「已验证」的关系自动穿透排查。
</p>
<OntologyTopologySvg
metrics={metrics}
workflowOntology={workflowOntology}
publishedNames={publishedNames}
/>
{!!workflowOntology?.issues?.length && (
<Notice tone="warn">
{workflowOntology.issues.map((iss, i) => (
<p key={i}>{iss.message}</p>
))}
</Notice>
)}
{/* 已有本体关系列表 */}
<div className="space-y-2" data-ontology-links-list="">
{metrics.map((metric) => {
const links = metric.links ?? []
const lineage = workflowOntology?.cards
?.flatMap((c) => c.metrics)
.find((m) => m.metric_id === metric.id)?.lineage ?? []
return (
<div key={metric.id} className="rounded border bg-elev p-2.5" data-ontology-metric={metric.id}>
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="font-medium text-fg">{metric.name}({metric.id})</span>
{lineage.length > 0 && (
<span className="text-2xs text-faint" data-ontology-lineage={metric.id}>
反向表血缘:{lineage.map((l) => `${l.source}(${l.tables.join('、')})`).join(';')}
</span>
)}
</div>
{links.length === 0 ? (
<p className="mt-1 text-2xs text-faint">尚未声明跨指标本体关系。</p>
) : (
<ul className="mt-2 space-y-1.5">
{links.map((link, idx) => {
const st = link.status ?? 'confirmed'
const targetText = `${link.target.workflow_id ? `${link.target.workflow_id.slice(0, 8)} / ` : ''}${link.target.card_id} / ${link.target.metric_id}`
return (
<li
key={link.id ?? idx}
className="flex flex-wrap items-center justify-between gap-2 rounded border bg-panel px-2 py-1.5 text-2xs"
data-ontology-link-row={link.id ?? String(idx)}
>
<div className="space-x-1.5">
<span className="font-semibold text-fg">{LINK_KIND_LABEL[link.kind] ?? link.kind}</span>
{link.role && <span className="text-dim">({FACTOR_ROLE_LABEL[link.role] ?? link.role})</span>}
<span className="font-mono text-dim">→ {targetText}</span>
{link.entity_key && <span className="text-faint">· 对齐实体:{link.entity_key}</span>}
{link.rel_tol != null && <span className="text-faint">· 相对容差:{link.rel_tol}</span>}
{link.abs_tol != null && <span className="text-faint">· 绝对容差:{link.abs_tol}</span>}
{!!link.lag_periods && <span className="text-faint">· 滞后 {link.lag_periods} 期</span>}
{link.rationale && <span className="text-faint">· {link.rationale}</span>}
</div>
<div className="flex items-center gap-1">
<span
className={clsx(
'rounded border px-1.5 py-0.5',
st === 'confirmed' || st === 'verified'
? 'border-[var(--ok)]/30 text-[var(--ok)]'
: st === 'proposed'
? 'border-[var(--warn)]/40 text-[var(--warn)]'
: 'border-[var(--border)] text-faint',
)}
>
{STATUS_LABEL[st] ?? st}
</span>
{st === 'proposed' && (
<>
<button
type="button"
className="btn btn-xs text-[var(--ok)]"
disabled={busy}
onClick={() => void updateLinkStatus(metric, idx, 'confirmed')}
data-ontology-link-confirm={link.id ?? String(idx)}
>
<Check size={11} aria-hidden /> 确认
</button>
<button
type="button"
className="btn btn-xs text-faint"
disabled={busy}
onClick={() => void updateLinkStatus(metric, idx, 'rejected')}
data-ontology-link-reject={link.id ?? String(idx)}
>
<X size={11} aria-hidden /> 驳回
</button>
</>
)}
<button
type="button"
className="btn btn-xs btn-ghost"
disabled={busy}
onClick={() => void removeLink(metric, idx)}
>
移除
</button>
</div>
</li>
)
})}
</ul>
)}
</div>
)
})}
</div>
{/* 新增本体关系表单 */}
<fieldset disabled={busy} className="space-y-2 rounded border p-2.5" data-ontology-add-form="">
<legend className="px-1 text-2xs font-semibold text-dim">添加指标本体关系</legend>
<div className="grid gap-2 sm:grid-cols-3">
<label className="block">
<span className="text-2xs text-dim">源指标</span>
<select
className="field mt-0.5 w-full"
value={selectedMetricId}
onChange={(e) => setSelectedMetricId(e.target.value)}
data-ontology-source-metric=""
>
{metrics.map((m) => (
<option key={m.id} value={m.id!}>{m.name}({m.id})</option>
))}
</select>
</label>
<label className="block">
<span className="text-2xs text-dim">关系类型</span>
<select
className="field mt-0.5 w-full"
value={kind}
onChange={(e) => setKind(e.target.value as OntologyLinkKind)}
data-ontology-kind-select=""
>
<option value="reconciles_with">跨源镜像对账</option>
<option value="factor">构成因子(公式拆解)</option>
<option value="upstream_driver">跨源上游驱动</option>
</select>
</label>
<label className="block">
<span className="text-2xs text-dim">从已发布口径快速选择目标</span>
<select
className="field mt-0.5 w-full"
value={pickedTarget}
onChange={(e) => handlePickTarget(e.target.value)}
data-ontology-target-picker=""
>
<option value="">手动输入或选择已发布指标…</option>
{publishedOptions.map((opt) => (
<option key={opt.key} value={opt.key}>{opt.label}</option>
))}
</select>
</label>
</div>
<div className="grid gap-2 sm:grid-cols-3">
<label className="block">
<span className="text-2xs text-dim">目标工作流标识(本卡可留空)</span>
<input
className="field mt-0.5 w-full font-mono"
placeholder="例如:wf_erp_settlement"
value={targetWorkflowId}
onChange={(e) => setTargetWorkflowId(e.target.value)}
data-ontology-target-workflow=""
/>
</label>
<label className="block">
<span className="text-2xs text-dim">目标口径卡节点标识</span>
<input
className="field mt-0.5 w-full font-mono"
placeholder="例如:metrics_card"
value={targetCardId}
onChange={(e) => setTargetCardId(e.target.value)}
data-ontology-target-card=""
/>
</label>
<label className="block">
<span className="text-2xs text-dim">目标指标标识</span>
<input
className="field mt-0.5 w-full font-mono"
placeholder="例如:settled_gmv"
value={targetMetricId}
onChange={(e) => setTargetMetricId(e.target.value)}
data-ontology-target-metric=""
/>
</label>
</div>
<div className="grid gap-2 sm:grid-cols-3">
{kind === 'factor' && (
<label className="block">
<span className="text-2xs text-dim">因子角色</span>
<select
className="field mt-0.5 w-full"
value={role}
onChange={(e) => setRole(e.target.value as OntologyFactorRole)}
>
{(Object.keys(FACTOR_ROLE_LABEL) as OntologyFactorRole[]).map((r) => (
<option key={r} value={r}>{FACTOR_ROLE_LABEL[r]}</option>
))}
</select>
</label>
)}
{kind !== 'factor' && (
<label className="block">
<span className="text-2xs text-dim">跨源对齐标准实体</span>
<select
className="field mt-0.5 w-full"
value={entityKey}
onChange={(e) => setEntityKey(e.target.value)}
data-ontology-entity-select=""
>
<option value="">不限定或按全局汇总对齐</option>
{entities.map((ent) => (
<option key={ent.key} value={ent.key}>{ent.label}({ent.key})</option>
))}
</select>
</label>
)}
{kind === 'reconciles_with' && (
<>
<label className="block">
<span className="text-2xs text-dim">相对容差(如 0.02 表示 2%)</span>
<input
className="field mt-0.5 w-full font-mono"
value={relTol}
onChange={(e) => setRelTol(e.target.value)}
/>
</label>
<label className="block">
<span className="text-2xs text-dim">绝对容差(可选)</span>
<input
className="field mt-0.5 w-full font-mono"
placeholder="例如:100"
value={absTol}
onChange={(e) => setAbsTol(e.target.value)}
/>
</label>
</>
)}
{kind === 'upstream_driver' && (
<label className="block">
<span className="text-2xs text-dim">滞后期数(0–12)</span>
<input
className="field mt-0.5 w-full font-mono"
value={lagPeriods}
onChange={(e) => setLagPeriods(e.target.value)}
/>
</label>
)}
</div>
<div className="flex flex-wrap items-end gap-2">
<label className="min-w-[220px] flex-1">
<span className="text-2xs text-dim">业务依据说明(可选)</span>
<input
className="field mt-0.5 w-full"
placeholder="说明这两个指标为何应当对账一致或存在上游驱动关系"
value={rationale}
onChange={(e) => setRationale(e.target.value)}
/>
</label>
<button
type="button"
className="btn btn-sm btn-primary"
disabled={busy || !selectedMetricId || !targetCardId.trim() || !targetMetricId.trim()}
onClick={() => void addLink()}
data-ontology-add-submit=""
>
{busy ? <Spinner size={11} /> : <Plus size={11} aria-hidden />} 添加并保存关系
</button>
</div>
</fieldset>
{error != null && <ErrorState error={error} compact />}
</div>
</details>
)
}
+112 -7
View File
@@ -26,7 +26,8 @@ import { useAtLeast, useLoginOn } from '../store/auth'
import { useCatalog } from '../store/catalog'
import { askKey, segmentKey, useEvidence, useExplore, useVerdicts } from '../store/evidence'
import type {
ApprovalReport, EvidenceAnalysisStep, EvidenceBlock, EvidenceChallengeVerdicts, EvidenceDocData, EvidenceDualCheck, EvidenceInput, EvidenceMerge,
ApprovalReport, EvidenceAnalysisStep, EvidenceBlock, EvidenceChallengeVerdicts, EvidenceDocData, EvidenceDualCheck, EvidenceHealthStep,
EvidenceInput, EvidenceMerge,
EvidenceOnDemand, EvidenceQuoteSource, EvidenceSeal, EvidenceSegment, EvidenceSegmentDetail, EvidenceStep, EvidenceUnit,
EvidenceUnitChallenge, EvidenceUntraced, EvidenceVerdict, EvidenceViolation,
} from '../types'
@@ -354,13 +355,15 @@ function SegmentBody({ panelId, doc, artifact, runId, runClass, seg, unit, block
// 后面接输入快照的查询步骤
const analysisChain = chain.filter((s) => s.step.startsWith('analysis')) as unknown as EvidenceAnalysisStep[]
const isAnalysis = cite?.kind === 'analysis' || entry?.kind === 'analysis' || analysisChain.some((s) => s.step === 'analysis')
const isMetric = !isAnalysis && (cite?.kind === 'metric' || entry?.kind === 'metric' || !!metricStep)
const isInput = !isAnalysis && (cite?.kind === 'input' || entry?.kind === 'input' || !!inputStep)
const healthChain = chain.filter((s) => s.step === 'source_health' || s.step === 'health_seal') as unknown as EvidenceHealthStep[]
const isHealth = !isAnalysis && (cite?.kind === 'source_health' || entry?.kind === 'source_health' || healthChain.some((s) => s.step === 'source_health'))
const isMetric = !isAnalysis && !isHealth && (cite?.kind === 'metric' || entry?.kind === 'metric' || !!metricStep)
const isInput = !isAnalysis && !isHealth && (cite?.kind === 'input' || entry?.kind === 'input' || !!inputStep)
// 三期:有出处的表名字段名、引文(原话对不上的引文也画这一节:说清原文在哪、对不上)
const isEntity = !isAnalysis && !isMetric && !isInput && seg.kind === 'entity' && state === 'deterministic'
const isQuote = !isAnalysis && !isMetric && !isInput && seg.kind === 'quote'
const isEntity = !isAnalysis && !isHealth && !isMetric && !isInput && seg.kind === 'entity' && state === 'deterministic'
const isQuote = !isAnalysis && !isHealth && !isMetric && !isInput && seg.kind === 'quote'
// 报告直接引用的查询单元格([[v:Q3.r5.amount]]、整表里的一格):证据链就是那一次查询
const isCell = !isAnalysis && !isMetric && !isInput && !isEntity && !isQuote
const isCell = !isAnalysis && !isHealth && !isMetric && !isInput && !isEntity && !isQuote
&& (cite?.kind === 'cell' || entry?.kind === 'query' || !!queries.length)
const bad = state === 'none' || state === 'suspect' || state === 'unverified'
const closest = closestNames(detail?.closest ?? entityStep?.closest)
@@ -533,6 +536,10 @@ function SegmentBody({ panelId, doc, artifact, runId, runClass, seg, unit, block
<AnalysisChain chain={analysisChain} seal={seal} pending={pending} failed={chainFailed} onQuery={jumpToQuery} />
)}
{isHealth && (
<HealthPart chain={healthChain} entry={entry} alias={cite?.alias} seal={seal} pending={pending} failed={chainFailed} />
)}
{isEntity && (
<EntityPart step={entityStep} entry={entry} cite={cite} seal={seal} pending={pending}
failed={chainFailed} catalog={doc.catalog} />
@@ -602,7 +609,7 @@ function SegmentBody({ panelId, doc, artifact, runId, runClass, seg, unit, block
{provenanceOn && runId && <EvidenceProvenance runId={runId} segId={seg.id} report={report} />}
{state === 'deterministic' && !isAnalysis && !isMetric && !isInput && !isCell && !isEntity && !isQuote && (
{state === 'deterministic' && !isAnalysis && !isHealth && !isMetric && !isInput && !isCell && !isEntity && !isQuote && (
<p className="text-dim">{sourceOf(seg, doc) || detail?.note}</p>
)}
@@ -2088,6 +2095,104 @@ function MergeTraces({ alias, merge }: { alias: string; merge: EvidenceMerge })
)
}
const HEALTH_VERDICT_LABEL: Record<string, { label: string; color: string }> = {
healthy: { label: '正常', color: 'var(--st-done)' },
ok: { label: '正常', color: 'var(--st-done)' },
degraded: { label: '存在缺口', color: 'var(--st-waiting)' },
gap: { label: '存在缺口', color: 'var(--st-waiting)' },
anomalous: { label: '异常', color: 'var(--st-failed)' },
error: { label: '核查出错', color: 'var(--st-failed)' },
}
function HealthPart({ chain, entry, alias, seal, pending, failed }: {
chain: EvidenceHealthStep[]
entry?: Record<string, any>
alias?: string
seal?: EvidenceSeal
pending: boolean
failed: string
}) {
const step = chain.find((s) => s.step === 'source_health')
const hSeal = chain.find((s) => s.step === 'health_seal')
const shownAlias = step?.alias ?? alias ?? (typeof entry?.alias === 'string' ? entry.alias : '')
const verdictCode = step?.verdict ?? (typeof entry?.verdict === 'string' ? entry.verdict : '')
const verdictMeta = verdictCode ? HEALTH_VERDICT_LABEL[verdictCode] : undefined
const phrase = step?.phrase ?? (typeof entry?.phrase === 'string' ? entry.phrase : '')
const sources = Array.isArray(step?.sources) ? step.sources.filter(Boolean)
: Array.isArray(entry?.sources) ? entry.sources.map(String).filter(Boolean) : []
const tables = Array.isArray(step?.tables) ? step.tables : []
const issues = Array.isArray(step?.issues) ? step.issues : []
const trusted = !!seal?.sealed && seal.ok !== false
const problems = [
step?.eid_ok === false ? EVIDENCE_TEXT.integrity.eid : '',
step?.hash_ok === false ? '健康核查快照与已记录哈希不一致' : '',
step?.render_ok === false && step?.hash_ok !== false ? '正文显示的健康核查结论与快照记录不一致' : '',
step?.note ?? '',
trusted && hSeal && hSeal.sealed === false && hSeal.note ? hSeal.note : '',
].filter(Boolean)
return (
<Part title={`数据源健康核查${shownAlias ? ` · ${shownAlias}` : ''}`} data-ev-health={shownAlias}>
<div className="flex flex-wrap items-center gap-1.5">
{verdictMeta ? (
<span className="chip" style={{ color: verdictMeta.color, borderColor: verdictMeta.color }}
data-ev-health-verdict={verdictCode}>
{verdictMeta.label}
</span>
) : verdictCode ? (
<span className="chip mono" data-ev-health-verdict={verdictCode}>{verdictCode}</span>
) : null}
{sources.map((src) => (
<span key={src} className="chip mono text-2xs" data-ev-health-source={src}>{src}</span>
))}
</div>
{phrase && <p className="mt-1 font-medium" data-ev-health-phrase="">{phrase}</p>}
{tables.length > 0 && (
<div className="mt-1.5 space-y-1">
<div className="text-2xs font-medium text-faint">已核查的数据表</div>
<ul className="space-y-1 rounded bg-bg px-2 py-1.5 text-2xs" data-ev-health-tables="">
{tables.map((tb, idx) => {
const name = [tb.source, tb.table].filter(Boolean).join('.') || NONE
const min = Array.isArray(tb.data_range) ? tb.data_range[0] : null
const max = Array.isArray(tb.data_range) ? tb.data_range[1] : null
const range = min || max ? `${min || '—'} ~ ${max || '—'}` : ''
const gapCount = typeof tb.gaps === 'number' && tb.gaps > 0 ? tb.gaps : 0
return (
<li key={`${name}-${idx}`} className="min-w-0 [overflow-wrap:anywhere]" data-ev-health-table={name}>
<span className="mono font-medium">{name}</span>
{tb.status && <span className="ml-1.5 text-dim">· {tb.status}</span>}
{tb.date_column && <span className="mono ml-1.5 text-faint">· {tb.date_column}</span>}
{range && <span className="mono ml-1.5 text-dim">({range})</span>}
{gapCount > 0 && (
<span className="ml-1.5" style={{ color: 'var(--st-waiting)' }}>
· 断档 {formatNumber(gapCount)} 处
</span>
)}
</li>
)
})}
</ul>
</div>
)}
{issues.length > 0 && (
<ul className="mt-1.5 space-y-0.5 text-2xs" style={{ color: 'var(--st-waiting)' }} data-ev-health-issues="">
{issues.map((iss, idx) => (
<li key={`${iss.code ?? ''}-${idx}`}>
· {iss.message || iss.code || NONE}
</li>
))}
</ul>
)}
<IntegrityList code="health" items={problems} />
{!step && (
<p className="mt-1.5 text-2xs text-faint" data-ev-chain={pending ? 'loading' : 'missing'}>
{pending ? '正在加载健康核查记录…' : failed || '未能获取健康核查记录'}
</p>
)}
</Part>
)
}
/** 接口没给查询步骤时:文档目录里记着的那次查询(编号、工具、行数),并照实说行没取到 */
function QueryFallback({ entry, alias, where, pending, failed }: {
entry?: Record<string, any>; alias?: string; where: string; pending: boolean; failed: string
+25 -4
View File
@@ -52,7 +52,14 @@ function summaryOf(data: RunLedger) {
* 服务端只给「确实能发起」的那一项口径身份(available):不能发起的那几项只是说明,界面上单独写一行、不摆按钮。
*/
function reconcileEntries(data: RunLedger): { action: LedgerReconcileAction; related?: LedgerRelated }[] {
return (data.actions ?? []).filter((a): a is LedgerReconcileAction => a.kind === 'reconcile').map((action) => ({
const seen = new Set<string>()
return (data.actions ?? []).filter((a): a is LedgerReconcileAction => {
if (a.kind !== 'reconcile') return false
const key = JSON.stringify([a.query, a.caliber, a.workflow_id, a.version, a.node_id, a.available])
if (seen.has(key)) return false
seen.add(key)
return true
}).map((action) => ({
action,
related: (data.queries ?? []).find((q) => q.artifact === action.query)?.candidates
.find((c) => c.caliber === action.caliber && c.status === 'related'),
@@ -92,6 +99,11 @@ export function LedgerTurn({ runId, runClass, done, readOnly = false }: {
}
const issue = (data.actions ?? []).find((a): a is LedgerIssueAction => a.kind === 'issue')
const reconciles = reconcileEntries(data)
const groups = new Map<string, typeof reconciles>()
for (const entry of reconciles) {
const key = JSON.stringify([entry.action.workflow_id, entry.action.version, caliberOf(entry.action)])
groups.set(key, [...(groups.get(key) ?? []), entry])
}
const issued = data.issued ?? []
const reconciled = data.reconciled ?? []
if (!summary.total && !issued.length && !reconciled.length && !marked) return null
@@ -114,7 +126,8 @@ export function LedgerTurn({ runId, runClass, done, readOnly = false }: {
{(issue || reconciles.length > 0) && (
<div className="flex flex-wrap items-start gap-1.5" data-ledger-actions="">
{issue && <IssueControl runId={runId} action={issue} slot={slot} readOnly={readOnly} />}
{reconciles.map(({ action, related }) => (
{[...groups].map(([key, entries]) => {
const controls = entries.map(({ action, related }, index) => (
// 服务端只给「确实能发起」的那一项身份:没有身份的那些是说明,不摆按钮(也就不发 undefined 的请求)
action.available === false ? (
<p key={`${action.query}|${action.caliber}`} className="text-2xs text-dim"
@@ -125,10 +138,18 @@ export function LedgerTurn({ runId, runClass, done, readOnly = false }: {
<button key={`${action.query}|${action.caliber}`} type="button" className="btn btn-xs" disabled={readOnly}
title={readOnly ? LEDGER_UI.reconcile.readOnly : undefined}
onClick={() => setDialog({ action, related })} data-ledger-turn-reconcile={action.caliber}>
<Scale size={11} aria-hidden /> {LEDGER_UI.reconcile.turnButton(caliberOf(action))}
<Scale size={11} aria-hidden /> {entries.length > 1
? `取数 ${index + 1} · ${(data.queries ?? []).find(q => q.artifact === action.query)?.tables?.join('、') || '查看并核对参数'}`
: LEDGER_UI.reconcile.turnButton(caliberOf(action))}
</button>
)
))}
))
return entries.length === 1 ? <span key={key}>{controls}</span>
: <details key={key} data-ledger-reconcile-group="" className="rounded border p-1.5">
<summary className="cursor-pointer text-2xs">{LEDGER_UI.reconcile.turnButton(caliberOf(entries[0].action))} · {entries.length} 份取数</summary>
<div className="mt-2 flex flex-wrap gap-1.5">{controls}</div>
</details>
})}
</div>
)}
<IssuedList data={data} />
+81 -2
View File
@@ -1370,6 +1370,37 @@ function toolStep(seq: number, tool: string, args: Record<string, any>): Step {
return { ...base, kind: 'schema', title: clip(`查看 ${tables.length} 张表的字段:${head}…`),
detail: tables.join('\n') }
}
if (tool === 'metric_query') {
const key = typeof args?.metric_key === 'string' && args.metric_key.trim() ? args.metric_key.trim() : ''
const argText = Object.keys(args ?? {}).length ? JSON.stringify(args, null, 2) : ''
return {
...base, kind: 'query', code: 'metric_query',
title: clip(key ? `查询标准指标 · ${key}` : '查询标准指标'),
detail: argText || undefined,
}
}
if (tool === 'ontology_neighbors') {
const metricId = typeof args?.metric_id === 'string' && args.metric_id.trim() ? args.metric_id.trim() : ''
const argText = Object.keys(args ?? {}).length ? JSON.stringify(args, null, 2) : ''
return {
...base, kind: 'tool', code: 'ontology_neighbors',
title: clip(metricId ? `查询指标本体邻域 · ${metricId}` : '查询指标本体邻域'),
detail: argText || undefined,
}
}
if (tool === 'source_health') {
const sources = Array.isArray(args?.sources)
? args.sources.map((s) => String(s ?? '').trim()).filter(Boolean)
: typeof args?.source === 'string' && args.source.trim() ? [args.source.trim()] : []
const argText = Object.keys(args ?? {}).length ? JSON.stringify(args, null, 2) : ''
return {
...base, kind: 'tool', code: 'source_health',
title: sources.length
? clip(`核查数据源健康 · ${sources.slice(0, 3).join('、')}${sources.length > 3 ? '…' : ''}`)
: '核查数据源健康',
detail: argText || undefined,
}
}
const op = analysisToolOp(tool)
if (op) {
// Agent 的分析工具:标题写算子的叫法(契约的叫法),不写 analysis_decompose;参数里没填的不列。判定语、编号等 tool.end
@@ -2330,6 +2361,18 @@ export function decodeRun(events: RunEvent[], final?: RunFinal, opts?: DecodeOpt
analysisSteps.set(key, step)
}
step.meta = dur(step.ms)
} else if (step.code === 'source_health' && !failed) {
const sh = d.source_health && typeof d.source_health === 'object' ? d.source_health as Record<string, any> : null
if (sh) {
const alias = typeof sh.alias === 'string' && sh.alias ? sh.alias : ''
const phrase = typeof sh.phrase === 'string' && sh.phrase ? sh.phrase : ''
const verdict = typeof sh.verdict === 'string' ? sh.verdict : ''
if (alias) step.title = clip(`${step.title} · 本节点 ${alias}`)
if (phrase) step.sub = step.sub ? `${phrase} · ${step.sub}` : phrase
if (verdict && verdict !== 'healthy' && verdict !== 'ok') step.level = 'warn'
}
if (typeof d.health_artifact === 'string' && d.health_artifact) step.artifact = d.health_artifact
step.meta = dur(step.ms)
} else if (step.kind === 'query' || step.kind === 'schema' || failed) {
// 查询保留 SQL 作为 detail,结果另挂;失败时结果就是错误原因
step.detail = failed ? `${step.detail ?? ''}\n\n${preview}`.trim() : step.detail
@@ -3529,7 +3572,7 @@ export function lookEventOf(op: CopilotOp): LookEvent | null {
op: 'look', id: String(op.id ?? ''), by: op.by === 'system' ? 'system' : 'model',
need: String(op.need ?? ''), status,
...(typeof op.reason === 'string' && op.reason ? { reason: op.reason } : {}),
elapsed_ms: num(op.elapsed_ms) ?? 0, objects,
elapsed_ms: num(op.elapsed_ms) ?? 0, objects, kinds: names(op.kinds),
}
}
@@ -3594,7 +3637,11 @@ export function copilotLook(op: CopilotOp):
const ms = look.elapsed_ms >= 10 ? look.elapsed_ms : undefined
if (look.status === 'failed') return { title: LOOK_TEXT.failed, level: 'warn', detail, ms }
if (look.status === 'index') {
return { title: look.reason ? LOOK_TEXT.index : LOOK_TEXT.indexEmpty, level: 'warn', detail, ms,
const kinds = look.kinds?.length ? look.kinds : [...new Set(look.objects.map(o => o.kind))]
const title = kinds.length === 1 && kinds[0] === 'caliber' ? '未匹配到明确口径,已提供口径目录'
: kinds.length && !kinds.includes('table') ? '未匹配到明确对象,已提供对应目录'
: look.reason ? LOOK_TEXT.index : LOOK_TEXT.indexEmpty
return { title, level: 'warn', detail, ms,
...(tableObjs.length ? { sub: [...new Set(tableObjs.map((o) => o.source))].join('、') } : {}) }
}
const title = !what ? LOOK_TEXT.nothing
@@ -3789,6 +3836,38 @@ export function decodeCopilot(ops: CopilotOp[], opts?: {
...(elapsed ? { ms: elapsed, meta: formatDuration(elapsed) } : {}) })
break
}
case 'grounding': {
const g = op.grounding && typeof op.grounding === 'object' ? op.grounding : null
if (!g) break
const mCount = Array.isArray(g.metrics) ? g.metrics.length : 0
const eCount = Array.isArray(g.entities) ? g.entities.length : 0
const tCount = Array.isArray(g.tables) ? g.tables.length : 0
const rCount = Array.isArray(g.guardrails) ? g.guardrails.length : 0
const parts: string[] = []
if (mCount) parts.push(`指标 ${mCount} 个`)
if (eCount) parts.push(`业务实体 ${eCount} 个`)
if (tCount) parts.push(`目录表 ${tCount} 张`)
if (rCount) parts.push(`防错规则 ${rCount} 条`)
const elapsed = num(g.elapsed_ms)
const lines: string[] = []
if (Array.isArray(g.metrics) && g.metrics.length) {
lines.push(`指标:${g.metrics.map((m: any) => `${m.name}(${m.key})`).join('、')}`)
}
if (Array.isArray(g.entities) && g.entities.length) {
lines.push(`业务实体:${g.entities.map((e: any) => e.matched_member?.canonical_label
? `${e.label} → ${e.matched_member.canonical_label}` : e.label).join('、')}`)
}
if (Array.isArray(g.tables) && g.tables.length) {
lines.push(`目录表:${g.tables.map((t: any) => `${t.datasource_name}.${t.table_name}`).join('、')}`)
}
add({
id: `gr-${i}`, seq: i, kind: 'schema', status: 'done', code: 'semantic_grounding',
title: parts.length ? `语义预命中 · ${parts.join('、')}` : '语义预命中 · 已连接数据源目录',
...(lines.length ? { detail: lines.join('\n') } : {}),
...(elapsed != null ? { ms: elapsed, meta: formatDuration(elapsed) } : {}),
})
break
}
case 'look':
case 'context': {
// 助手查看了哪些表、能力、工作流版本(look §2.6):一次查看一行,按先后排。老服务端的 context 操作照同一套说法
+3 -3
View File
@@ -400,11 +400,11 @@ const reloading: Partial<Record<CatalogKey, Promise<void>>> = {}
* 数据源目录(订阅版)。list 含停用的,按需自己 filter(enabled);state 同
* catalogListState,不是 ok 时空列表不代表「没有数据源」,别劝人去新建。
*
* 挂载时如果目录超过 maxAgeMs 没取过就后台重拉一次,先照旧给手上的那份。
* 挂载或 refreshKey(例如路由进入标识)变化时检查 maxAgeMs,过期就后台重拉一次,先展示缓存。
* 同一时刻多处挂载只会发一个请求(reload 自己不去重,这里记着在路上的那一次)。
* 启动的 refresh 还没落定时先不拉(那次本来就会取);落定时这张表没取回来,就补拉一次
*/
export function useDatasources(opts?: { maxAgeMs?: number }): { list: DataSource[]; state: CatalogListState } {
export function useDatasources(opts?: { maxAgeMs?: number; refreshKey?: string }): { list: DataSource[]; state: CatalogListState } {
const list = useCatalog((s) => s.datasources)
const state = useCatalogListState('datasources')
const loaded = useCatalog((s) => s.loaded)
@@ -416,7 +416,7 @@ export function useDatasources(opts?: { maxAgeMs?: number }): { list: DataSource
if ((at == null || Date.now() - at > maxAge) && !reloading.datasources) {
reloading.datasources = s.reload('datasources').finally(() => { reloading.datasources = undefined })
}
}, [maxAge, loaded])
}, [maxAge, loaded, opts?.refreshKey])
return { list, state }
}
+7
View File
@@ -96,6 +96,8 @@ export const askKey = (runId: string, report: string | undefined, unit: string)
/** 分析范围里一个编号的片段 id 前缀(证据面板拼的「scope:A1」,不在正文里;同服务端导出页的 SCOPE_REF) */
export const SCOPE_SEG = 'scope:'
/** 数据源健康核查的片段 id 前缀(「health:H1」) */
export const HEALTH_SEG = 'health:'
/**
* 片段的缓存键:`runId:segId`。一次运行里有好几份报告时片段 id 会撞(每份都从 s0 数起),
@@ -170,6 +172,11 @@ export const useEvidence = create<EvidenceState>((set, get) => {
// 不带 text:范围里的这一项写的是文档自己记着的判定语,正文这份是不是封存的那一份按工件 id 认
segment: { id: segmentId, kind: 'analysis' },
}))
: segmentId.startsWith(HEALTH_SEG)
? api.evidence.health(runId, segmentId.slice(HEALTH_SEG.length), { report }).then((r) => ({
report: r.report, chain: (r.chain ?? []) as unknown as EvidenceSegmentDetail['chain'], seal: r.seal, redacted: r.redacted,
segment: { id: segmentId, kind: 'source_health' },
}))
: api.evidence.segment(runId, segmentId, { report }))),
// 最近一次运行 → 它封存范围内的报告核对(report.checked)。审计接口的 reports 带着结论句策略(claims,
// 章上「无证据」要不要算没挂依据的结论句靠它);只要 reports,所以只取最小的「可疑实体」那一组行。
+54 -1
View File
@@ -1654,7 +1654,7 @@ export interface ConversationTurn {
/** 问数据一轮在服务端的任务现在怎样。status 用后台任务的状态词;stage 是在哪一步;attempt_seq 是这一次尝试从哪一条事件开始 */
export interface ChatTurnJob {
status: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled' | 'interrupted'
stage: 'build' | 'run' | 'waiting' | 'review' | null
stage: 'ground' | 'build' | 'run' | 'waiting' | 'review' | null
mode: string
run_id: string | null
attempt: number
@@ -1731,6 +1731,16 @@ export interface ReviewSignal {
reason?: string
}
export interface AnomalyEscalation {
available: boolean
mode: 'prompt' | 'auto'
auto_escalate: boolean
button_label: string
signals: string[]
reason: string
follow_up_instruction: string
}
export interface ReviewResult {
/** ok=没问题 / annotated=加了说明 / rewritten=重写过 / reverted=重写里有新数字被退回 */
verdict: 'ok' | 'annotated' | 'rewritten' | 'reverted'
@@ -1749,6 +1759,8 @@ export interface ReviewResult {
* 是 null。老服务端没有这个字段,问数据页照原来的规则自己判
*/
retry_instruction?: string | null
/** 简单问数命中硬异常信号时的跨源本体排查升级提示(P1) */
anomaly_escalation?: AnomalyEscalation | null
/** 复核这一次的用量(服务端 providers/usage.py 的汇总,没调模型时全 0):这一轮的花费 = 助手 + 运行 + 复核 */
usage?: {
cost_usd?: number | null; unpriced_calls?: number; calls?: number; input_tokens?: number; output_tokens?: number
@@ -2598,6 +2610,47 @@ export interface AnalysisItem {
hypothesis?: string
}
/** 数据源健康核查步骤(source_health / health_seal)的单条问题与单表检查明细 */
export interface EvidenceHealthIssue {
code?: string
severity?: 'alert' | 'warn' | 'info' | string
source?: string
table?: string | null
message?: string
}
export interface EvidenceHealthTable {
source?: string
table?: string
status?: string
date_column?: string | null
data_range?: (string | null)[] | null
basis?: string | null
gaps?: number
}
export interface EvidenceHealthStep {
step: 'source_health' | 'health_seal' | string
alias?: string
node_id?: string | null
label?: string | null
call_id?: string
artifact?: string | null
eid?: string
eid_ok?: boolean
rendered?: string
render_ok?: boolean
hash_ok?: boolean | null
verdict?: 'healthy' | 'degraded' | 'anomalous' | string
phrase?: string
sources?: string[]
issues?: EvidenceHealthIssue[]
tables?: EvidenceHealthTable[]
ledger?: boolean
sealed?: boolean
note?: string
}
export interface EvidenceStep extends Omit<EvidenceInput, 'status'> {
step: string
/**
+1
View File
@@ -860,6 +860,7 @@ export interface LookEvent {
reason?: string
elapsed_ms: number
objects: LookObject[]
kinds?: string[]
}
// ---------------------------------------------------------------------------
+15 -6
View File
@@ -90,17 +90,19 @@ export interface EvalSuiteDetail extends EvalSuite {
export type EvalCaseKind = 'ask' | 'workflow'
export type EvalExpectationKind = 'scalar' | 'table' | 'set' | 'none' | 'ask' | 'text' | 'contribution' | 'verdict' | 'investigation'
/** 分析期望用的分析方法(服务端 app/analysis/contract.OPS):贡献恒为 decompose,判定是另外四种 */
export type EvalAnalysisOp = 'decompose' | 'baseline' | 'trend' | 'differ' | 'comparable'
/** 分析期望用的分析方法(服务端 app/analysis/contract.OPS) */
export type EvalAnalysisOp = 'decompose' | 'baseline' | 'trend' | 'differ' | 'comparable' | 'reconcile' | 'cochange'
/** 分析方法的模式(contract.MODES):变化拆解 additive / ratio / factor,差异检验 rate / mean / rows */
export type EvalAnalysisMode = 'additive' | 'ratio' | 'factor' | 'rate' | 'mean' | 'rows'
/**
* 判定类(服务端 app/eval/judgements.JUDGEMENTS):期望和答案里的分析结论都按它比。贡献:source 主要来源、dispersed 分散、
* flat 基本持平、mix 结构变化为主、rate 各段自身的变化为主、mixed 两方面都有影响;判定:normal 常规波动、anomaly 超出常规波动、
* rising / falling / no_trend、differs 差异站得住、no_evidence 不足以下结论、comparable / incomparable
* rising / falling / no_trend、differs 差异站得住、no_evidence 不足以下结论、comparable / incomparable、aligned / diverged、
* co_anomalous / target_normal
*/
export type EvalJudgement = 'source' | 'dispersed' | 'flat' | 'mix' | 'rate' | 'mixed' | 'normal' | 'anomaly' | 'rising'
| 'falling' | 'no_trend' | 'differs' | 'no_evidence' | 'comparable' | 'incomparable'
| 'aligned' | 'diverged' | 'co_anomalous' | 'target_normal'
/**
* 一个期望。数值期望不许人填(评测-D4):只写从期望答案的结果里取哪一格、哪一列、整张表,值由 SQL / 口径算出来;分析期望
@@ -109,6 +111,9 @@ export type EvalJudgement = 'source' | 'dispersed' | 'flat' | 'mix' | 'rate' | '
export interface EvalExpectation {
minimum_depth?: number
max_queries?: number
min_ontology_hops?: number
require_source_health?: boolean
diagnosis_stage?: 'health_and_contract' | 'slice_localization' | 'ontology_penetration'
status?: 'complete' | 'partial'
stop_reason?: string
id?: string
@@ -377,21 +382,25 @@ export type EvalCatalogMode = 'live' | 'reviewed' | 'off' | 'snapshot'
/** 分析工具开、关(关的那一臂助手建图时看不到分析工具和分析卡) */
export type EvalAnalysisTools = 'on' | 'off'
/** 预设对照:目录贡献(当前目录 vs 关,可加「只用已核实和已确认的项」)、分析工具贡献(开 vs 关) */
export type EvalPreset = 'catalog' | 'catalog_reviewed' | 'analysis_tools'
/** 本体穿透开、关(关的那一臂助手建图时看不到本体穿透工具与邻居提示) */
export type EvalOntologyTools = 'on' | 'off'
/** 预设对照:目录贡献(当前目录 vs 关,可加「只用已核实和已确认的项」)、分析工具贡献(开 vs 关)、本体穿透贡献(开 vs 关) */
export type EvalPreset = 'catalog' | 'catalog_reviewed' | 'analysis_tools' | 'ontology_tools'
export interface EvalModelPair {
provider: string | null
model: string | null
}
/** 一臂变体:助手、写作模型,结论裁判,目录,分析工具,重复次数,名字。加分析工具之前存下的评测记录里没有 analysis(当开) */
/** 一臂变体:助手、写作模型,结论裁判,目录,分析工具,本体穿透,重复次数,名字。老评测记录里没有 analysis / ontology 时当开 */
export interface EvalVariant {
assistant: EvalModelPair
writer: EvalModelPair
judge: boolean
catalog: { mode: EvalCatalogMode; snapshot: string | null }
analysis: { tools: EvalAnalysisTools }
ontology: { tools: EvalOntologyTools }
repeats: number
label: string | null
}
+278 -1
View File
@@ -510,8 +510,270 @@ export interface DraftDefinition {
citations?: DraftCitation[]
}
export interface QuerySemantics {
version: 1
enabled: boolean
aliases: string[]
grain: string
aggregation: string
time: null | { start: string; end: string; timezone: string; basis: 'calendar_day' | 'production_day'; periods: ('day' | 'month')[]; description: string }
entities: { field: string; label: string; entity_key?: string | null; members: { value: string; label: string; aliases: string[] }[] }[]
}
export type OntologyLinkKind = 'factor' | 'reconciles_with' | 'upstream_driver'
export type OntologyFactorRole = 'numerator' | 'denominator' | 'multiplier' | 'addend' | 'subtrahend' | 'component'
export type OntologyStatus = 'proposed' | 'verified' | 'confirmed' | 'rejected'
export interface MetricOntologyTarget {
workflow_id: string
card_id: string
metric_id: string
version?: number
}
export interface MetricOntologyLink {
id?: string
kind: OntologyLinkKind
target: MetricOntologyTarget
status?: OntologyStatus
source?: 'human' | 'rule' | 'docdraft' | 'ai' | string
role?: OntologyFactorRole
entity_key?: string
lag_periods?: number
abs_tol?: number
rel_tol?: number
rationale?: string
citations?: Record<string, unknown>[]
}
export interface CanonicalEntityMember {
value: string
label: string
aliases: string[]
source_codes?: Record<string, string>
}
export interface CanonicalEntityBinding {
id?: string
source_id?: string | null
source_name: string
table_name: string
column_name: string
status: OntologyStatus
source: 'human' | 'rule' | 'ai' | 'profile' | string
note?: string
reason?: string
updated_at?: string
updated_by?: string | null
}
export interface CanonicalEntityCaliberParam {
id?: string
workflow_id: string
card_id?: string
param_name: string
status: OntologyStatus
source: 'human' | 'rule' | 'ai' | 'profile' | string
note?: string
}
export interface CanonicalEntity {
id: string
key: string
label: string
description: string
aliases: string[]
members: CanonicalEntityMember[]
bindings: CanonicalEntityBinding[]
caliber_params?: CanonicalEntityCaliberParam[]
version: number
created_by?: string | null
updated_by?: string | null
created_at?: string | null
updated_at?: string | null
}
export interface WorkflowOntologyMetric {
metric_id: string
name: string
unit: string
contract?: Record<string, unknown> | null
links: MetricOntologyLink[]
lineage: { node_id?: string; source: string; tables: string[] }[]
}
export interface WorkflowOntologyCard {
workflow_id: string
workflow_name: string
version: number
card_id: string
title: string
caliber: string
sources: string[]
tables_by_source: Record<string, string[]>
metrics: WorkflowOntologyMetric[]
}
export interface WorkflowOntologyEdge {
id: string
kind: OntologyLinkKind
status: OntologyStatus
source: string
role?: OntologyFactorRole | null
entity_key?: string | null
lag_periods?: number
abs_tol?: number | null
rel_tol?: number | null
rationale?: string
from: { workflow_id: string; version: number; card_id: string; metric_id: string }
to: { workflow_id: string; version?: number | null; card_id: string; metric_id: string }
}
export interface WorkflowOntology {
workflow_id: string
version: number
cards: WorkflowOntologyCard[]
edges: WorkflowOntologyEdge[]
issues: { level: string; code: string; message: string; node_id?: string | null; field?: string | null }[]
}
export interface OntologyGraph {
cards: WorkflowOntologyCard[]
edges: WorkflowOntologyEdge[]
entities: CanonicalEntity[]
table_bridges?: Record<string, unknown>[]
}
export interface EntityAttachmentOut {
attachment_id: string
title: string
mime: string
char_count: number
chunk_count: number
saved_to_kb: boolean
document_id?: string | null
collection?: string | null
}
export interface EntityPatchChange {
id: string
op: 'upsert_entity' | 'upsert_binding' | 'remove_binding' | 'upsert_member' | 'upsert_caliber_param' | string
entity_key: string
entity_label: string
summary: string
before?: unknown
after?: unknown
reason: string
op_payload: Record<string, unknown>
}
export interface EntityApplyPatchOut {
applied_count: number
created_entities: number
updated_entities: number
bindings_changed: number
caliber_params_changed: number
members_changed: number
entities: CanonicalEntity[]
problems?: string[]
}
export interface EntityAssistantMessage {
role: 'user' | 'assistant'
content: string
}
export interface EntityAssistantRequest {
messages: EntityAssistantMessage[]
source_ids?: string[]
focus_entity_key?: string | null
attachment_ids?: string[]
document_ids?: string[]
pending_ops?: Record<string, unknown>[]
}
export type EntityAssistantEvent =
| { type: 'text'; delta: string }
| {
type: 'query'
source: string
sql: string
columns: string[]
rows: unknown[][]
row_count: number
truncated: boolean
error?: string | null
}
| {
type: 'proposal'
changes: EntityPatchChange[]
expected_versions: Record<string, number>
}
| { type: 'done'; usage?: { input_tokens?: number; output_tokens?: number }; queries?: number }
| { type: 'error'; code?: string; message: string }
export interface EntityDiscoveryJob {
id: string
status: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled' | 'interrupted' | string
source_ids: string[]
document_ids: string[]
attachment_ids: string[]
note: string
phase: string
summary: {
sources_scanned?: number
source_names?: string[]
tables_scanned?: number
columns_scanned?: number
workflows_scanned?: number
documents_scanned?: number
doc_titles?: string[]
chunks_scanned?: number
model_id?: string
step_index?: number
step_total?: number
progress_pct?: number
model_chars?: number
ops_detected?: number
candidate_keys?: string[]
applied_count?: number
created_entities?: number
updated_entities?: number
proposed_bindings?: number
proposed_params?: number
added_members?: number
skipped_count?: number
skipped_reasons?: string[]
touched_entities?: { id: string; key: string; label: string }[]
}
error?: string | null
started_by?: string | null
started_at?: string | null
finished_at?: string | null
created_at?: string | null
updated_at?: string | null
}
export interface EntityDiscoveryActiveOut {
job: EntityDiscoveryJob | null
latest: EntityDiscoveryJob | null
}
export interface SemanticInventory {
version: number
note: string
warnings?: { document_id: string; line: number; quote: string; reason: string }[]
items: { id: string; name: string; kind: 'input' | 'metric'; section: string; formula: string; policy: string;
status: 'definition_only' | 'unavailable'; dependencies: string[]; implementation: string;
fields: Record<string, string>; source: { document_id: string; line: number; span: number[]; quote: string } }[]
rules: { document_id: string; section: string; text: string; line: number; span: number[] }[]
}
/** 草稿里的一条指标:业务定义 + 取数表达式;取数 SQL 在草稿图上(CaliberDraft.sql),这里不返回。 */
export interface DraftMetric {
source_definition_id?: string
semantic?: QuerySemantics
links?: MetricOntologyLink[]
id?: string
name: string
synonyms?: string[]
@@ -661,6 +923,7 @@ export interface DraftDocument {
/** GET /api/ledger/drafts 的一条:只有计数和状态,正文用 GET /api/ledger/drafts/{id} 看 */
export interface CaliberDraftSummary {
definition_count?: number
id: string
title: string
status: CaliberDraftStatus
@@ -924,8 +1187,20 @@ export interface DraftChangeReceipt {
binding: DraftBinding
}
export interface DraftDefinitionDiagnostic {
kind?: 'needs_info' | 'validation_failed' | string
reasons?: string[]
questions?: string[]
}
/** GET /api/ledger/drafts/{id}:payload 摊平在上层(documents / metrics / dropped / open_questions / alignment) */
export interface CaliberDraft extends CaliberDraftSummary {
semantic_inventory?: SemanticInventory
selected_definition_ids?: string[]
implementation_mode?: 'all' | 'selected'
definition_issues?: { definition_id: string; name: string; reason: string }[]
implementation_progress?: { total: number; completed: number; pending: number; blocked: number; active_names: string[] }
definition_diagnostics?: Record<string, DraftDefinitionDiagnostic>
job?: { status: string; attempt: number; error?: string | null; retryable: boolean }
/**
@@ -988,7 +1263,9 @@ export interface CaliberDraft extends CaliberDraftSummary {
collection?: string | null
datasource_id?: string | null
/** 起草时的文档 id 和附加要求 */
origin?: { documents?: string[]; guidance?: string }
origin?: { documents?: string[]; guidance?: string; fixed_filters?: string
continuation_from?: { draft_id: string; workflow_id?: string; revision: number; merge_required: boolean; merged_revision?: number }
}
created_by?: string | null
updated_at?: string | null
workflow_name?: string | null