feat(qa-ops): 完成复检留档与人工复核闭环

治理侧保存输入观测版本、自动复检及人工复核历史,输入变化失效、版本冲突和幂等重放不覆盖人工记录。批量质量数量使用完整筛选元数据,未采集原文不伪造快照,延迟旧扫描不回退新输入。

验证:全仓 make verify 退出码0,Go656及前端253通过;五包竞态、源/组织/质量隔离PG、真实只读源和隔离网页读回复核通过。默认91个可选集成跳过不计通过。未接AI模型,不写DobotAI源库,未推送、未合并、未部署。
This commit is contained in:
姚章浩
2026-10-17 22:37:26 +08:00
parent 9556db1ef0
commit 4b3aaff321
30 changed files with 2483 additions and 30 deletions
+51 -2
View File
@@ -7,9 +7,13 @@ import './qaOps.css'
import { QARegions } from './QARegions'
import { QAUsage } from './QAUsage'
import { QAMonthly } from './QAMonthly'
import { QAQualityEditor, QAQualityCounts } from './QAQuality'
import { qualityLabels } from './qaQuality'
import { usageLabels } from './qaUsage'
interface ViewProps {
onQualitySaved?: (record: QARecord) => void
onReloadDetail?: () => void
page: QARecordPage | null
status: QAStatus | null
loading: boolean
@@ -96,7 +100,10 @@ export function QAOperationsView(props: ViewProps) {
>
<span
className={
key === 'coverage' && item.coverage.verdict === 'uncovered' ? 'qa-ops-uncovered' : ''
key === 'coverage' &&
(item.quality?.effective.coverage ?? item.coverage.verdict) === 'uncovered'
? 'qa-ops-uncovered'
: ''
}
>
{qaCellValue(item, key) ?? '—'}
@@ -111,6 +118,9 @@ export function QAOperationsView(props: ViewProps) {
>
详情
</button>
{item.quality ? (
<small className="qa-quality-state">{qualityLabels[item.quality.state]}</small>
) : null}
</td>
</tr>
))}
@@ -149,7 +159,9 @@ export function QAOperationsView(props: ViewProps) {
if (event.key === 'Escape') props.onCloseDetail()
if (event.key === 'Tab') {
const buttons = Array.from(
event.currentTarget.querySelectorAll<HTMLElement>('button, a[href], input, [tabindex="0"]')
event.currentTarget.querySelectorAll<HTMLElement>(
'button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), summary, [tabindex="0"]'
)
)
const first = buttons[0],
last = buttons[buttons.length - 1]
@@ -242,6 +254,17 @@ export function QAOperationsView(props: ViewProps) {
{detail.source_coverage.evaluator_version || '无版本'}
</p>
<p className="qa-ops-muted">{detail.source_coverage.reason_code || '未记录判定原因'}</p>
{detail.quality ? (
<QAQualityEditor
key={detail.id}
recordId={detail.id}
quality={detail.quality}
onSaved={props.onQualitySaved ?? (() => {})}
onReload={props.onReloadDetail ?? (() => {})}
/>
) : (
<p className="qa-ops-muted">质量留档/人工复核未配置。</p>
)}
<h4>用户反馈</h4>
<p>
提问人:
@@ -287,6 +310,7 @@ export function QAOperations() {
const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState(false)
const [revision, setRevision] = useState(0)
const [qualityRevision, setQualityRevision] = useState(0)
const [detail, setDetail] = useState<QARecord | null>(null)
const [detailLoading, setDetailLoading] = useState(false)
const [detailError, setDetailError] = useState<string | null>(null)
@@ -481,6 +505,7 @@ export function QAOperations() {
<p className="qa-ops-slice-note">
部门/区域保留源快照,缺失时按当前通讯录补全;使用统计不是绩效结论。外语翻译与AI评估仍暂缓,空值不默认填“否”。
</p>
{view === 'records' ? <QAQualityCounts query={query} revision={qualityRevision} /> : null}
{view === 'usage' ? (
<QAUsage query={query} />
) : (
@@ -492,6 +517,30 @@ export function QAOperations() {
detail={detail}
detailLoading={detailLoading}
detailError={detailError}
onReloadDetail={() => {
if (detail) void select(detail.id)
}}
onQualitySaved={(fresh) => {
if (fresh.id !== detail?.id) return
setDetail(fresh)
setPage((old) => {
if (!old) return old
const all = new Set(old.columns)
const f = fresh.quality?.effective
if (f) {
if (f.coverage) all.add('coverage')
if (f.correctness) all.add('is_correct')
for (const key of ['product_category', 'problem_type', 'root_cause'] as const)
if (f[key]) all.add(key)
}
return {
...old,
items: old.items.map((item) => (item.id === fresh.id ? fresh : item)),
columns: qaColumns.filter((c) => all.has(c.key)).map((c) => c.key),
}
})
setQualityRevision((v) => v + 1)
}}
onSelect={(id) => void select(id)}
onCloseDetail={close}
onLoadMore={() => void loadMore()}
+43
View File
@@ -0,0 +1,43 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, it, expect } from 'vitest'
import { QAQualityEditor, QAQualitySummaryView } from './QAQuality'
import { qualityFixture, summaryFixture } from './qaQuality.fixture'
import { parseQAQuality, parseQualitySummary } from './qaQuality'
describe('manual quality operations', () => {
it('renders separate evidence, session reviewer and safe text', () => {
const html = renderToStaticMarkup(
<QAQualityEditor
recordId="fixture"
quality={parseQAQuality(qualityFixture)}
onSaved={() => {}}
onReload={() => {}}
/>
)
for (const value of ['人工复核', '保存并读回', '覆盖结论', '正确性', '复核理由', 'fixture-admin'])
expect(html).toContain(value)
expect(html).not.toContain('<script>')
})
it('labels stale manual judgment as needing reconfirmation', () => {
const html = renderToStaticMarkup(
<QAQualityEditor
recordId="fixture"
quality={{ ...parseQAQuality(qualityFixture), state: 'stale' }}
onSaved={() => {}}
onReload={() => {}}
/>
)
expect(html).toContain('待重新核对')
})
it('does not turn unavailable quality counts into zeros or rates', () => {
const html = renderToStaticMarkup(
<QAQualitySummaryView data={null} error="质量存储不可用" loading={false} onRefresh={() => {}} />
)
expect(html).toContain('质量存储不可用')
expect(html).not.toContain('覆盖率')
const ok = renderToStaticMarkup(
<QAQualitySummaryView data={parseQualitySummary(summaryFixture)} error="" loading={false} onRefresh={() => {}} />
)
expect(ok).toContain('完整筛选范围')
expect(ok).toContain('AI 评估未接入')
})
})
+483
View File
@@ -0,0 +1,483 @@
import { useEffect, useRef, useState } from 'react'
import type { FormEvent } from 'react'
import { getPayload, fetchQARecord } from './qaOps'
import type { QAQuery, QARecord } from './qaOps'
import { newOperationID } from './operationKey'
import {
emptyQualityFields,
qualityLabels,
parseQAQuality,
parseQualityHistory,
parseQualitySnapshot,
parseQualitySummary,
} from './qaQuality'
import type { QAQuality, QualityFields, QualityHistory, QualitySnapshot, QualitySummary } from './qaQuality'
const stamp = (v: string) => new Date(v).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
const message = (e: unknown) => (e instanceof Error ? e.message : '质量操作失败,请重试')
interface EditorProps {
recordId: string
quality: QAQuality
onSaved: (record: QARecord) => void
onReload: () => void
}
export function QAQualityEditor({ recordId, quality, onSaved, onReload }: EditorProps) {
const initial = quality.state === 'reviewed' ? quality.effective : emptyQualityFields
const [fields, setFields] = useState<QualityFields>({ ...initial }),
[reason, setReason] = useState(quality.state === 'reviewed' ? quality.latest_review?.reason || '' : ''),
[loading, setLoading] = useState(false),
[error, setError] = useState(''),
[notice, setNotice] = useState('')
const [history, setHistory] = useState<QualityHistory | null>(null),
[snapshot, setSnapshot] = useState<QualitySnapshot | null>(null),
[historyError, setHistoryError] = useState(''),
[historyLoading, setHistoryLoading] = useState(false)
const saving = useRef<AbortController | null>(null),
reading = useRef<AbortController | null>(null),
snapshotReading = useRef<AbortController | null>(null),
nonce = useRef({ signature: '', value: '' })
useEffect(() => {
setFields({ ...(quality.state === 'reviewed' ? quality.effective : emptyQualityFields) })
setReason(quality.state === 'reviewed' ? quality.latest_review?.reason || '' : '')
setHistory(null)
setSnapshot(null)
}, [
recordId,
quality.input_hash,
quality.input_epoch,
quality.revision,
quality.state,
quality.effective,
quality.latest_review,
])
useEffect(
() => () => {
saving.current?.abort()
reading.current?.abort()
snapshotReading.current?.abort()
},
[]
)
const change = (key: keyof QualityFields, value: string) => {
setFields({
...fields,
[key]: value,
...(key === 'correctness' && value === 'correct' ? { root_cause: '' } : {}),
...(key === 'coverage' && value !== 'excluded' ? { exclusion_reason: '' } : {}),
})
setNotice('')
setError('')
}
const submit = async (event: FormEvent) => {
event.preventDefault()
if (loading) return
setLoading(true)
setError('')
setNotice('')
const controller = new AbortController()
saving.current = controller
const body = {
input_hash: quality.input_hash,
input_epoch: quality.input_epoch,
base_revision: quality.revision,
fields,
reason,
}
const signature = JSON.stringify(body)
try {
if (nonce.current.signature !== signature) nonce.current = { signature, value: newOperationID() }
const raw = await getPayload(
`/api/v1/qa-ops/records/${encodeURIComponent(recordId)}/reviews`,
controller.signal,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-quality' },
body: JSON.stringify({ ...body, nonce: nonce.current.value }),
}
)
if (!raw || typeof raw !== 'object') throw Error('复核回执无效')
const receipt = raw as Record<string, unknown>
parseQAQuality(receipt.view)
if (!Number.isSafeInteger(receipt.saved_revision) || Number(receipt.saved_revision) < 1)
throw Error('复核回执缺少版本')
const savedRevision = Number(receipt.saved_revision)
const audit = parseQualityHistory(
await getPayload(
`/api/v1/qa-ops/records/${encodeURIComponent(recordId)}/quality/history?review_before=${savedRevision + 1}`,
controller.signal
)
)
const saved = audit.reviews.find((r) => r.revision === savedRevision)
if (
!saved ||
saved.input_hash !== body.input_hash ||
saved.input_epoch !== body.input_epoch ||
saved.reason !== reason ||
Object.keys(fields).some(
(key) => saved.fields[key as keyof QualityFields] !== fields[key as keyof QualityFields]
)
)
throw Error('保存后的精确复核记录尚未读回,请用原表单重试,重复请求不会重复留档')
const fresh = await fetchQARecord(recordId, controller.signal)
if (!fresh.quality || fresh.quality.revision < savedRevision)
throw Error('复核已留档但当前问答尚未读回,请重新读取')
if (!controller.signal.aborted) {
setNotice(
`已保存并读回复核第 ${savedRevision} 版${fresh.quality.state === 'stale' ? ';原始输入又有变化,旧结论不再生效' : ''}`
)
onSaved(fresh)
}
} catch (e) {
if (!controller.signal.aborted) setError(message(e))
} finally {
if (!controller.signal.aborted) setLoading(false)
}
}
const loadHistory = async (kind: 'initial' | 'reviews' | 'checks' = 'initial') => {
reading.current?.abort()
const controller = new AbortController()
reading.current = controller
setHistoryError('')
setHistoryLoading(true)
const params = new URLSearchParams()
if (kind === 'reviews' && history?.next_review) params.set('review_before', String(history.next_review))
if (kind === 'checks' && history?.next_check) params.set('check_before', String(history.next_check))
try {
const next = parseQualityHistory(
await getPayload(
`/api/v1/qa-ops/records/${encodeURIComponent(recordId)}/quality/history${params.size ? '?' + params : ''}`,
controller.signal
)
)
if (!controller.signal.aborted)
setHistory((old) =>
kind === 'initial' || !old
? next
: kind === 'reviews'
? { ...old, reviews: [...old.reviews, ...next.reviews], next_review: next.next_review }
: { ...old, checks: [...old.checks, ...next.checks], next_check: next.next_check }
)
} catch (e) {
if (!controller.signal.aborted) setHistoryError(message(e))
} finally {
if (!controller.signal.aborted) setHistoryLoading(false)
}
}
const loadInput = async (epoch: number) => {
snapshotReading.current?.abort()
const controller = new AbortController()
snapshotReading.current = controller
setHistoryError('')
setSnapshot(null)
try {
const next = parseQualitySnapshot(
await getPayload(
`/api/v1/qa-ops/records/${encodeURIComponent(recordId)}/quality/inputs/${epoch}`,
controller.signal
)
)
if (next.payload.id !== recordId || next.input_epoch !== epoch) throw Error('历史输入版本不匹配')
if (!controller.signal.aborted) setSnapshot(next)
} catch (e) {
if (!controller.signal.aborted) setHistoryError(message(e))
}
}
return (
<section className="qa-quality-editor" aria-label="人工复核与留档">
<h4>
人工复核 <span>{qualityLabels[quality.state]}</span>
</h4>
{quality.state === 'stale' ? (
<p className="qa-ops-warning">
待重新核对:原始问答输入已变化,旧人工结论仅供查阅,不再用于当前有效结果。请核对完整问题、答案、引用与媒体。
</p>
) : null}
{quality.latest_review ? (
<p className="qa-ops-muted">
最近复核:{quality.latest_review.reviewer} · {stamp(quality.latest_review.created_at)} · 第{' '}
{quality.latest_review.revision} 版
</p>
) : null}
<p className="qa-ops-muted">
AI 评估未接入。自动规则、源端判断和人工结论独立保留;以下分类沿用正式标签,不自动猜测。复核人取登录身份。
</p>
{error ? (
<div role="alert" className="error-banner">
{error}{' '}
<button type="button" onClick={onReload} disabled={loading}>
重新读取问答
</button>
</div>
) : null}
{notice ? <p role="status">{notice}</p> : null}
<form onSubmit={(event) => void submit(event)} aria-label="人工复核表单" className="qa-quality-form">
<label>
覆盖结论
<select
required
disabled={loading}
value={fields.coverage}
onChange={(e) => change('coverage', e.target.value)}
>
<option value="">请选择</option>
{['covered', 'uncovered', 'partial', 'pending', 'excluded'].map((key) => (
<option key={key} value={key}>
{qualityLabels[key]}
</option>
))}
</select>
</label>
<label>
正确性
<select
required
disabled={loading}
value={fields.correctness}
onChange={(e) => change('correctness', e.target.value)}
>
<option value="">请选择</option>
{['correct', 'incorrect', 'pending'].map((key) => (
<option key={key} value={key}>
{qualityLabels[key]}
</option>
))}
</select>
</label>
<label>
产品分类(可留空)
<input
disabled={loading}
value={fields.product_category}
maxLength={128}
onChange={(e) => change('product_category', e.target.value)}
placeholder="沿用正式标签"
/>
</label>
<label>
问题类型(可留空)
<input
disabled={loading}
value={fields.problem_type}
maxLength={128}
onChange={(e) => change('problem_type', e.target.value)}
placeholder="沿用正式标签"
/>
</label>
<label className="qa-quality-full">
根因分析(有依据才填)
<textarea
disabled={loading || fields.correctness === 'correct'}
value={fields.root_cause}
maxLength={2000}
onChange={(e) => change('root_cause', e.target.value)}
/>
</label>
{fields.coverage === 'excluded' ? (
<label className="qa-quality-full">
不计入原因
<textarea
required
disabled={loading}
value={fields.exclusion_reason}
maxLength={2000}
onChange={(e) => change('exclusion_reason', e.target.value)}
/>
</label>
) : null}
<label className="qa-quality-full">
复核理由
<textarea
required
disabled={loading}
value={reason}
maxLength={4000}
onChange={(e) => {
setReason(e.target.value)
setNotice('')
}}
placeholder="说明核对依据;不确定时选择待确认"
/>
</label>
{quality.automatic.result.verdict === 'uncovered' && ['covered', 'partial'].includes(fields.coverage) ? (
<p className="qa-ops-warning qa-quality-full">
将采用有理由的人工结论;“暂无已发布”的自动命中记录仍保留,不伪装为未命中。
</p>
) : null}
<button
type="submit"
disabled={
loading ||
!fields.coverage ||
!fields.correctness ||
!reason.trim() ||
(fields.coverage === 'excluded' && !fields.exclusion_reason.trim())
}
>
{loading ? '正在保存并核对…' : '保存并读回'}
</button>
</form>
<p className="qa-ops-muted qa-ops-organization">
当前输入第 {quality.input_epoch} 次观察 · 复核版本 {quality.revision} · 自动复检已留档于{' '}
{stamp(quality.automatic.created_at)}。当前输入指纹:{quality.input_hash}
</p>
<button type="button" disabled={historyLoading} onClick={() => void loadHistory()}>
读取复核/复检历史
</button>
{historyError ? (
<p role="alert" className="error-banner">
{historyError}
</p>
) : null}
{history ? (
<div className="qa-quality-history">
<h4>人工修改历史</h4>
{history.reviews.length ? (
history.reviews.map((r) => (
<article key={r.revision}>
<strong>
复核 #{r.revision} · {r.reviewer} · {stamp(r.created_at)}
</strong>
<p>
{qualityLabels[r.fields.coverage]} / {qualityLabels[r.fields.correctness]} ·{' '}
{r.fields.product_category || '产品未填'} / {r.fields.problem_type || '类型未填'}
</p>
<p>{r.reason}</p>
{r.fields.root_cause ? <p>根因:{r.fields.root_cause}</p> : null}
{r.fields.exclusion_reason ? <p>不计入原因:{r.fields.exclusion_reason}</p> : null}
<button type="button" onClick={() => void loadInput(r.input_epoch)}>
查看第 {r.input_epoch} 次输入
</button>
</article>
))
) : (
<p>尚无人工修改记录。</p>
)}
{history.next_review ? (
<button disabled={historyLoading} type="button" onClick={() => void loadHistory('reviews')}>
更多人工历史
</button>
) : null}
<h4>自动复检历史(不是 AI 评估)</h4>
{history.checks.map((c) => (
<article key={c.id}>
<p>
输入 #{c.input_epoch} · {c.result.rule_version} · {stamp(c.created_at)}
</p>
<p>
{c.result.verdict === 'uncovered' ? '命中“暂无已发布”:未覆盖' : '未命中:仍待评估,不默认覆盖'}
;当次源判断:{c.source.verdict || '未记录'}
</p>
<button type="button" disabled={!c.input_available} onClick={() => void loadInput(c.input_epoch)}>
{c.input_available ? `查看第 ${c.input_epoch} 次输入` : '此版本仅留存指纹/命中元数据'}
</button>
</article>
))}
{history.next_check ? (
<button disabled={historyLoading} type="button" onClick={() => void loadHistory('checks')}>
更多复检历史
</button>
) : null}
</div>
) : null}
{snapshot ? (
<section aria-label="历史评估输入">
<h4>历史输入 #{snapshot.input_epoch}</h4>
<p>{stamp(snapshot.created_at)} · 仅此历史版本,不代表当前答案</p>
<h5>原始问题</h5>
<pre>{snapshot.payload.question}</pre>
<h5>当时答案</h5>
<pre>{snapshot.payload.answer}</pre>
<details>
<summary>当时引用与媒体</summary>
<pre>
{JSON.stringify({ references: snapshot.payload.references, media: snapshot.payload.media }, null, 2)}
</pre>
</details>
</section>
) : null}
</section>
)
}
interface SummaryProps {
data: QualitySummary | null
loading: boolean
error: string
onRefresh: () => void
}
export function QAQualitySummaryView({ data, loading, error, onRefresh }: SummaryProps) {
return (
<section className="qa-quality-summary" aria-label="质量数量">
<button type="button" disabled={loading} onClick={onRefresh}>
{loading ? '正在复检留档…' : '复检留档与质量数量'}
</button>
{error ? (
<p role="alert" className="error-banner">
{error}
</p>
) : null}
{data && !error && !loading ? (
<>
<p>
完整筛选范围 {data.summary.total} 条 · 已复核 {data.summary.reviewed} · 未复核 {data.summary.unreviewed} ·
待重新核对 {data.summary.stale} · 人工待确认 {data.summary.pending_confirmation} · 规则命中未覆盖{' '}
{data.summary.rule_uncovered}
</p>
<p className="qa-ops-muted">
AI 评估未接入;人工待确认是已复核中的子集,规则命中可与人工结论不同。不计算比例。读取:{stamp(data.as_of)}
</p>
</>
) : !error && !loading ? (
<span className="qa-ops-muted">按当前完整时间/关键词范围留档,不按当前页估算。</span>
) : null}
</section>
)
}
export function QAQualityCounts({ query, revision }: { query: QAQuery | null; revision: number }) {
const [data, setData] = useState<QualitySummary | null>(null),
[loading, setLoading] = useState(false),
[error, setError] = useState(''),
[requested, setRequested] = useState(false),
[refresh, setRefresh] = useState(0)
useEffect(() => {
if (!query || !requested) {
setData(null)
return
}
const controller = new AbortController()
setData(null)
setError('')
setLoading(true)
getPayload('/api/v1/qa-ops/quality/query', controller.signal, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-quality' },
body: JSON.stringify({ start: query.start, end: query.end, keyword: query.keyword }),
})
.then((raw) => {
const next = parseQualitySummary(raw)
if (
(next.start !== query.start && Date.parse(next.start) !== Date.parse(query.start)) ||
Date.parse(next.end) !== Date.parse(query.end) ||
next.keyword !== query.keyword
)
throw Error('质量数量与当前查询范围不一致')
if (!controller.signal.aborted) setData(next)
})
.catch((e) => {
if (!controller.signal.aborted) setError(message(e))
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false)
})
return () => controller.abort()
}, [query, revision, requested, refresh])
return (
<QAQualitySummaryView
data={data}
loading={loading}
error={error}
onRefresh={() => {
setRequested(true)
setRefresh((v) => v + 1)
}}
/>
)
}
+75
View File
@@ -55,6 +55,81 @@
grid-template-columns: minmax(0, 1fr);
}
}
.qa-quality-state {
display: block;
margin-top: 5px;
color: var(--ink-mute);
white-space: nowrap;
}
.qa-quality-summary {
padding: 10px 14px;
border: 1px solid var(--border-base);
background: var(--bg-panel);
font-size: 12px;
}
.qa-quality-summary > span {
margin-left: 10px;
}
.qa-quality-summary p {
margin: 7px 0 0;
line-height: 1.5;
}
.qa-quality-editor {
border-top: 1px solid var(--border-base);
margin-top: 20px;
padding-top: 2px;
}
.qa-quality-form {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.qa-quality-form label {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
font-size: 12px;
color: var(--ink-mute);
}
.qa-quality-form input,
.qa-quality-form select,
.qa-quality-form textarea {
width: 100%;
min-width: 0;
padding: 8px;
border: 1px solid var(--border-strong);
border-radius: var(--r-sm);
background: var(--bg-panel);
color: var(--ink-strong);
font: inherit;
}
.qa-quality-form textarea {
min-height: 68px;
resize: vertical;
}
.qa-quality-full {
grid-column: 1/-1;
}
.qa-quality-editor > p {
font-size: 12px;
line-height: 1.6;
}
.qa-quality-history article {
border-bottom: 1px solid var(--border-base);
padding: 10px 0;
overflow-wrap: anywhere;
font-size: 12px;
}
.qa-quality-editor pre {
max-height: 300px;
overflow: auto;
}
@media (max-width: 500px) {
.qa-quality-form {
grid-template-columns: minmax(0, 1fr);
}
}
.qa-ops-header h2 {
margin: 0 0 5px;
font-size: 21px;
+22
View File
@@ -1,3 +1,5 @@
import { parseQAQuality } from './qaQuality'
import type { QAQuality } from './qaQuality'
export const qaColumns = [
{ key: 'question_chinese', label: '中文问题' },
{ key: 'answer', label: 'AI答案' },
@@ -69,6 +71,7 @@ export function mergeQAPages(current: QARecordPage, next: QARecordPage): QARecor
}
}
export interface QARecord {
quality?: QAQuality
organization?: QARecordOrganization
id: string
status: string
@@ -145,6 +148,7 @@ export function parseQARecord(value: unknown): QARecord {
const askerValue = text(feedback.asker_value)
if (!['', 'up', 'down'].includes(askerValue)) return invalid()
const item: QARecord = {
...(row.quality === undefined ? {} : { quality: parseQAQuality(row.quality) }),
id: text(row.id),
status: text(row.status),
question: text(row.question),
@@ -279,6 +283,24 @@ export async function fetchQAStatus(signal?: AbortSignal): Promise<QAStatus> {
}
export function qaCellValue(item: QARecord, column: QAColumn): string | null {
const f = item.quality?.effective
if (f) {
if (column === 'coverage')
return f.coverage
? (
{ covered: '是', uncovered: '否', partial: '部分覆盖', pending: '待确认', excluded: '不计入' } as Record<
string,
string
>
)[f.coverage]
: null
if (column === 'is_correct')
return f.correctness
? ({ correct: '是', incorrect: '否', pending: '待确认' } as Record<string, string>)[f.correctness]
: null
if (column === 'product_category' || column === 'problem_type' || column === 'root_cause') return f[column] || null
}
if (column === 'coverage') return item.coverage.verdict === 'uncovered' ? '否' : null
if (column === 'is_correct') return typeof item.is_correct === 'boolean' ? (item.is_correct ? '是' : '否') : null
if (column === 'feedback') {
+50
View File
@@ -0,0 +1,50 @@
export const hash = 'a'.repeat(64)
export const fields = {
coverage: 'covered',
correctness: 'correct',
product_category: 'MG400',
problem_type: '咨询',
root_cause: '',
exclusion_reason: '',
}
export const check = {
input_available: true,
id: 1,
input_epoch: 1,
input_hash: hash,
result: {
state: 'checked',
verdict: 'uncovered',
rule_version: 'governance-answer-substring-v1',
matched_text: '暂无已发布',
},
source: { verdict: 'covered', reason_code: 'source only', evaluator_version: 'v5' },
created_at: '2026-10-17T12:00:00Z',
}
export const review = {
revision: 1,
input_epoch: 1,
input_hash: hash,
fields,
reason: '<script>示例理由</script>',
reviewer: 'fixture-admin',
created_at: '2026-10-17T12:01:00Z',
}
export const qualityFixture = {
input_hash: hash,
input_epoch: 1,
revision: 1,
state: 'reviewed',
automatic: check,
latest_review: review,
effective: fields,
}
export const summaryFixture = {
summary: { total: 3, reviewed: 1, unreviewed: 1, stale: 1, pending_confirmation: 0, rule_uncovered: 2 },
start: '2026-10-14T00:00:00Z',
end: '2026-10-15T00:00:00Z',
keyword: '',
as_of: '2026-10-17T12:01:00Z',
scope: 'whole_filter',
ai_state: 'not_configured',
}
+51
View File
@@ -0,0 +1,51 @@
import { describe, it, expect } from 'vitest'
import { parseQAQuality, parseQualitySummary, parseQualityHistory } from './qaQuality'
import { qualityFixture, summaryFixture, check, review } from './qaQuality.fixture'
import { parseQARecord, qaCellValue } from './qaOps'
describe('quality evidence contracts', () => {
it('renders effective manual labels in agreed columns without changing the rule result', () => {
const record = parseQARecord({
id: 'fixture',
status: 'succeeded',
question: '示例',
answer: '暂无已发布',
asked_at: '2026-10-17T12:00:00Z',
time_source: 'request_message.created_at',
asker: '',
trigger_person: '',
department: '',
region: '',
references: [],
media: [],
source_coverage: check.source,
feedback: { asker_value: '', up: 0, down: 0 },
coverage: check.result,
quality: qualityFixture,
})
expect(qaCellValue(record, 'coverage')).toBe('是')
expect(qaCellValue(record, 'is_correct')).toBe('是')
expect(qaCellValue(record, 'product_category')).toBe('MG400')
expect(record.coverage.verdict).toBe('uncovered')
})
it('separates immutable rule/source results and explicit human outcomes', () => {
const v = parseQAQuality(qualityFixture)
expect(v.effective.coverage).toBe('covered')
expect(v.automatic.result.verdict).toBe('uncovered')
})
it('rejects stale conclusions kept effective and forged revisions', () => {
expect(() =>
parseQAQuality({ ...qualityFixture, state: 'stale', input_epoch: 2, automatic: { ...check, input_epoch: 2 } })
).toThrow()
expect(() => parseQAQuality({ ...qualityFixture, revision: 2 })).toThrow()
})
it('keeps scope counts whole and conservative without made-up rates', () => {
expect(parseQualitySummary(summaryFixture).summary.total).toBe(3)
expect(() => parseQualitySummary({ ...summaryFixture, summary: { ...summaryFixture.summary, total: 4 } })).toThrow()
})
it('retains pageable human and automatic history independently', () => {
expect(
parseQualityHistory({ reviews: [review], checks: [check], next_review: 0, next_check: 0 }).reviews
).toHaveLength(1)
})
})
+264
View File
@@ -0,0 +1,264 @@
export interface QualityFields {
coverage: string
correctness: string
product_category: string
problem_type: string
root_cause: string
exclusion_reason: string
}
export interface QualityCheck {
input_available: boolean
id: number
input_epoch: number
input_hash: string
result: { state: string; verdict?: string; rule_version: string; matched_text?: string }
source: { verdict: string; reason_code: string; evaluator_version: string }
created_at: string
}
export interface QualityReview {
revision: number
input_epoch: number
input_hash: string
fields: QualityFields
reason: string
reviewer: string
created_at: string
}
export interface QAQuality {
input_hash: string
input_epoch: number
revision: number
state: 'unreviewed' | 'reviewed' | 'stale'
automatic: QualityCheck
latest_review: QualityReview | null
effective: QualityFields
}
export interface QualityHistory {
reviews: QualityReview[]
checks: QualityCheck[]
next_review: number
next_check: number
}
export interface QualitySnapshot {
input_epoch: number
input_hash: string
created_at: string
payload: { id: string; question: string; answer: string; status: string; references: unknown; media: unknown }
}
export interface QualitySummary {
summary: {
total: number
reviewed: number
unreviewed: number
stale: number
pending_confirmation: number
rule_uncovered: number
}
start: string
end: string
keyword: string
as_of: string
scope: 'whole_filter'
ai_state: 'not_configured'
}
export const emptyQualityFields: QualityFields = {
coverage: '',
correctness: '',
product_category: '',
problem_type: '',
root_cause: '',
exclusion_reason: '',
}
export const qualityLabels: Record<string, string> = {
covered: '已覆盖',
uncovered: '未覆盖',
partial: '部分覆盖',
pending: '待确认',
excluded: '不计入',
correct: '正确',
incorrect: '错误',
unreviewed: '未复核',
reviewed: '已复核',
stale: '待重新核对',
}
const bad = (): never => {
throw new Error('质量留档响应无效,未展示可能失真的结论')
}
const obj = (v: unknown): Record<string, unknown> =>
v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : bad()
const text = (v: unknown): string => (typeof v === 'string' ? v : bad())
const num = (v: unknown): number => (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 ? v : bad())
const positive = (v: unknown): number => {
const n = num(v)
return n > 0 ? n : bad()
}
const hash = (v: unknown): string => {
const t = text(v)
return /^[a-f0-9]{64}$/.test(t) ? t : bad()
}
const stamp = (v: unknown): string => {
const t = text(v)
return Number.isFinite(Date.parse(t)) ? t : bad()
}
function fields(v: unknown, complete = false): QualityFields {
const r = obj(v)
const f = {
coverage: text(r.coverage),
correctness: text(r.correctness),
product_category: text(r.product_category),
problem_type: text(r.problem_type),
root_cause: text(r.root_cause),
exclusion_reason: text(r.exclusion_reason),
}
if (
!['', 'covered', 'uncovered', 'partial', 'pending', 'excluded'].includes(f.coverage) ||
!['', 'correct', 'incorrect', 'pending'].includes(f.correctness) ||
(complete && (!f.coverage || !f.correctness)) ||
(f.correctness === 'correct' && f.root_cause !== '') ||
(f.coverage === 'excluded' && !f.exclusion_reason.trim()) ||
(f.coverage !== 'excluded' && f.exclusion_reason !== '')
)
return bad()
return f
}
function check(value: unknown): QualityCheck {
const v = obj(value),
r = obj(v.result),
s = obj(v.source)
const state = text(r.state),
rule_version = text(r.rule_version)
if (
!rule_version ||
(state !== 'pending' && state !== 'checked') ||
(state === 'checked' && (r.verdict !== 'uncovered' || r.matched_text !== '暂无已发布')) ||
(state === 'pending' && r.verdict !== undefined)
)
return bad()
return {
input_available: typeof v.input_available === 'boolean' ? v.input_available : bad(),
id: positive(v.id),
input_epoch: positive(v.input_epoch),
input_hash: hash(v.input_hash),
result: {
state,
rule_version,
...(r.verdict === undefined ? {} : { verdict: text(r.verdict), matched_text: text(r.matched_text) }),
},
source: {
verdict: text(s.verdict),
reason_code: text(s.reason_code),
evaluator_version: text(s.evaluator_version),
},
created_at: stamp(v.created_at),
}
}
function review(value: unknown): QualityReview {
const v = obj(value),
reason = text(v.reason),
reviewer = text(v.reviewer)
if (!reason.trim() || !reviewer) return bad()
return {
revision: positive(v.revision),
input_epoch: positive(v.input_epoch),
input_hash: hash(v.input_hash),
fields: fields(v.fields, true),
reason,
reviewer,
created_at: stamp(v.created_at),
}
}
export function parseQAQuality(value: unknown): QAQuality {
const v = obj(value),
state = text(v.state)
if (!['unreviewed', 'reviewed', 'stale'].includes(state)) return bad()
const automatic = check(v.automatic),
latest_review = v.latest_review === null ? null : review(v.latest_review),
input_hash = hash(v.input_hash),
input_epoch = positive(v.input_epoch),
revision = num(v.revision),
effective = fields(v.effective)
if (
automatic.input_hash !== input_hash ||
automatic.input_epoch !== input_epoch ||
(latest_review && latest_review.revision !== revision) ||
(!latest_review && revision !== 0)
)
return bad()
const actual = latest_review
? latest_review.input_hash === input_hash && latest_review.input_epoch === input_epoch
? 'reviewed'
: 'stale'
: 'unreviewed'
if (state !== actual) return bad()
const expected =
state === 'reviewed' ? latest_review!.fields : { ...emptyQualityFields, coverage: automatic.result.verdict || '' }
for (const key of Object.keys(expected) as (keyof QualityFields)[]) if (expected[key] !== effective[key]) return bad()
return { input_hash, input_epoch, revision, state: state as QAQuality['state'], automatic, latest_review, effective }
}
export function parseQualitySummary(value: unknown): QualitySummary {
const v = obj(value),
s = obj(v.summary),
summary = {
total: num(s.total),
reviewed: num(s.reviewed),
unreviewed: num(s.unreviewed),
stale: num(s.stale),
pending_confirmation: num(s.pending_confirmation),
rule_uncovered: num(s.rule_uncovered),
}
const start = stamp(v.start),
end = stamp(v.end)
if (
v.scope !== 'whole_filter' ||
v.ai_state !== 'not_configured' ||
summary.total !== summary.reviewed + summary.unreviewed + summary.stale ||
summary.pending_confirmation > summary.reviewed ||
summary.rule_uncovered > summary.total ||
Date.parse(start) >= Date.parse(end)
)
return bad()
return {
summary,
start,
end,
keyword: text(v.keyword),
as_of: stamp(v.as_of),
scope: 'whole_filter',
ai_state: 'not_configured',
}
}
export function parseQualityHistory(value: unknown): QualityHistory {
const v = obj(value)
if (!Array.isArray(v.reviews) || !Array.isArray(v.checks)) return bad()
const reviews = v.reviews.map(review),
checks = v.checks.map(check),
next_review = num(v.next_review),
next_check = num(v.next_check)
if (
reviews.length > 20 ||
checks.length > 20 ||
reviews.some((r, i) => i > 0 && r.revision >= reviews[i - 1].revision) ||
checks.some((c, i) => i > 0 && c.id >= checks[i - 1].id) ||
(next_review && next_review !== reviews.at(-1)?.revision) ||
(next_check && next_check !== checks.at(-1)?.id)
)
return bad()
return { reviews, checks, next_review, next_check }
}
export function parseQualitySnapshot(value: unknown): QualitySnapshot {
const v = obj(value),
p = obj(v.payload)
return {
input_epoch: positive(v.input_epoch),
input_hash: hash(v.input_hash),
created_at: stamp(v.created_at),
payload: {
id: text(p.id),
question: text(p.question),
answer: text(p.answer),
status: text(p.status),
references: p.references,
media: p.media,
},
}
}