mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-24 05:02:00 +00:00
合入 W2-c 前端:分析卡节点与分析项编辑器、报告节点两个新字段、设置「分析」一节、问数据时间线的分析步骤与出具横幅三项、运行对比的分析卡一区、证据面板与正文接上分析结论(六步出处链、闭合核对、两期可比性、说法违规标注、分析范围)、可验证报告核对页与分析样本页、口径账本摘要防 NaN;服务端补分析工具事件里的判定与分析结论的单独出处接口
# Conflicts: # backend/tests/test_eval_schedule.py
This commit is contained in:
@@ -856,6 +856,14 @@ export const api = {
|
||||
get<EvidenceSegmentDetail>(
|
||||
`/runs/${encodeURIComponent(runId)}/evidence/segments/${encodeURIComponent(segmentId)}${qs({ report: opts?.report })}`,
|
||||
opts),
|
||||
/**
|
||||
* 报告末尾「分析范围」里的一个编号(A1):那份分析结论的出处链,和点开正文里它的判定语同一条。正文没引用的结论也点得开;
|
||||
* 证据目录里没有这份结论 404。report 同片段接口
|
||||
*/
|
||||
analysis: (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/analyses/${encodeURIComponent(alias)}${qs({ report: opts?.report })}`, opts),
|
||||
/**
|
||||
* 审计表:每个有状态的片段按状态分组(有出处 / 无证据 / 可疑实体 / 旧运行猜测),附上封存核对的结果。
|
||||
* groups 只要这几组(none、suspicious…)
|
||||
|
||||
@@ -15,7 +15,15 @@ import { formatShortcut } from '../lib/keys'
|
||||
import { INPUT_FIELD_TEXT, JUDGE_FIELD_LABEL, JUDGE_ON_UNSUPPORTED_HINT, JUDGE_ON_UNSUPPORTED_LABEL, JUDGE_SETTING_TEXT, MERGE_TEXT, CATALOG_UI_TEXT, NODE_TYPE_LABEL, PROVIDER_REF_TEXT, SUBGRAPH_UPGRADE_HELP, judgeByModelText, upgradeNewerText } from '../lib/terms'
|
||||
import { TemplateText } from './TemplateText'
|
||||
import { MERGE_ALIAS, isQueryNode, mergeAlias } from './mergeInputs'
|
||||
import type { NodeType, Provider, ValidationIssue, WorkflowVersion } from '../types'
|
||||
import {
|
||||
ITEM_ID, TWO_QUERY_SKIP, allowsHeadline, allowsParent, allowsTwoQueries, itemsOf, nextItemId, paramSpecs, paramText,
|
||||
paramValue, withMode, withOp, type ParamSpec,
|
||||
} from './analysisItems'
|
||||
import {
|
||||
ANALYSIS_MODES, ANALYSIS_MODE_LABEL, ANALYSIS_OPS, ANALYSIS_OP_LABEL, ANALYSIS_SETTING_KEYS, ANALYSIS_SETTING_LABEL,
|
||||
ANALYSIS_TEXT, isAnalysisOp, settingRangeText, settingValueProblem, type AnalysisSettingKey,
|
||||
} from '../lib/termsAnalysis'
|
||||
import type { AnalysisItem, NodeType, Provider, ValidationIssue, WorkflowVersion } from '../types'
|
||||
|
||||
/** 检查器里一条落到字段上的问题 */
|
||||
type FieldIssue = ValidationIssue & { at: FieldRef | null }
|
||||
@@ -151,6 +159,34 @@ function NodeRefsInput({ nodeId, type, value, onChange }: {
|
||||
)
|
||||
}
|
||||
|
||||
/** 上游能当查询输入的节点(选了数据库查询工具的「调用工具」节点、合并查询):合并查询、分析卡共用 */
|
||||
function useUpstreamQueries(nodeId: string): { value: string; label: string; hint?: string }[] {
|
||||
const nodes = useStudio((s) => s.nodes)
|
||||
const edges = useStudio((s) => s.edges)
|
||||
return useMemo(() => {
|
||||
const parents = new Map<string, string[]>()
|
||||
for (const e of edges) parents.set(e.target, [...(parents.get(e.target) ?? []), e.source])
|
||||
const seen = new Set<string>()
|
||||
const stack = [...(parents.get(nodeId) ?? [])]
|
||||
while (stack.length) {
|
||||
const id = stack.pop()!
|
||||
if (seen.has(id) || id === nodeId) continue
|
||||
seen.add(id)
|
||||
stack.push(...(parents.get(id) ?? []))
|
||||
}
|
||||
return nodes
|
||||
.filter((n) => seen.has(n.id) && isQueryNode(n))
|
||||
.map((n) => {
|
||||
const label = String(n.data?.label || n.id)
|
||||
const tool = String((n.data?.config as Record<string, any> | undefined)?.tool ?? '')
|
||||
return {
|
||||
value: n.id, label: label === n.id ? label : `${label}(${n.id})`,
|
||||
hint: n.data?.nodeType === 'merge' ? NODE_TYPE_LABEL.merge : tool,
|
||||
}
|
||||
})
|
||||
}, [nodes, edges, nodeId])
|
||||
}
|
||||
|
||||
interface MergeRow { alias: string; node: string }
|
||||
|
||||
/** config.inputs({别名: 节点 id})→ 行。对象的键顺序就是行的顺序 */
|
||||
@@ -178,28 +214,7 @@ function MergeInputList({ nodeId, value, issues, onChange }: {
|
||||
const nodes = useStudio((s) => s.nodes)
|
||||
const edges = useStudio((s) => s.edges)
|
||||
const uid = useId()
|
||||
const options = useMemo(() => {
|
||||
const parents = new Map<string, string[]>()
|
||||
for (const e of edges) parents.set(e.target, [...(parents.get(e.target) ?? []), e.source])
|
||||
const seen = new Set<string>()
|
||||
const stack = [...(parents.get(nodeId) ?? [])]
|
||||
while (stack.length) {
|
||||
const id = stack.pop()!
|
||||
if (seen.has(id) || id === nodeId) continue
|
||||
seen.add(id)
|
||||
stack.push(...(parents.get(id) ?? []))
|
||||
}
|
||||
return nodes
|
||||
.filter((n) => seen.has(n.id) && isQueryNode(n))
|
||||
.map((n) => {
|
||||
const label = String(n.data?.label || n.id)
|
||||
const tool = String((n.data?.config as Record<string, any> | undefined)?.tool ?? '')
|
||||
return {
|
||||
value: n.id, label: label === n.id ? label : `${label}(${n.id})`,
|
||||
hint: n.data?.nodeType === 'merge' ? NODE_TYPE_LABEL.merge : tool,
|
||||
}
|
||||
})
|
||||
}, [nodes, edges, nodeId])
|
||||
const options = useUpstreamQueries(nodeId)
|
||||
|
||||
const external = useMemo(() => mergeRowsOf(value), [value])
|
||||
const [rows, setRows] = useState<MergeRow[]>(external)
|
||||
@@ -295,6 +310,319 @@ function MergeInputList({ nodeId, value, issues, onChange }: {
|
||||
)
|
||||
}
|
||||
|
||||
const AT = ANALYSIS_TEXT.node
|
||||
|
||||
/** 选一个上游查询节点。已经选了、后来删掉或挪到下游的节点照样列出来并说明,好让人看见并改掉 */
|
||||
function QueryPick({ id, value, options, onChange }: {
|
||||
id: string; value: string; options: { value: string; label: string }[]; onChange: (v: string) => void
|
||||
}) {
|
||||
const known = options.some((o) => o.value === value)
|
||||
return (
|
||||
<select id={id} className="field text-xs" value={value} onChange={(e) => onChange(e.target.value)}>
|
||||
<option value="" disabled>{AT.pickFrom}</option>
|
||||
{options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
|
||||
{value && !known && <option value={value} disabled>{AT.missingNode(value)}</option>}
|
||||
</select>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 分析卡的分析项(engine/schema.analysis_issues 的配置):每一项一个标识、一种分析方法(有模式的再选模式)、要分析的上游
|
||||
* 查询节点(或基期、本期两份查询),再按方法摆参数格(analysisItems.paramSpecs);可加、比率的变化拆解另有总数核对、下钻。
|
||||
* 阈值不在这里写(统一写在阈值覆盖里)。服务端按 items[i].<键> 报的问题落在那一格下面,定位按 [data-item] [data-sub] 落进来
|
||||
*/
|
||||
function AnalysisItemList({ nodeId, value, issues, onChange }: {
|
||||
nodeId: string; value: any; issues: FieldIssue[]; onChange: (v: any) => void
|
||||
}) {
|
||||
const uid = useId()
|
||||
const options = useUpstreamQueries(nodeId)
|
||||
const items = itemsOf(value)
|
||||
const commit = (next: AnalysisItem[]) => onChange(next)
|
||||
const update = (i: number, next: AnalysisItem) => commit(items.map((it, j) => (j === i ? next : it)))
|
||||
const setParam = (i: number, key: string, v: unknown) => {
|
||||
const params = { ...(items[i].params ?? {}) }
|
||||
if (v === undefined) delete params[key]
|
||||
else params[key] = v
|
||||
update(i, { ...items[i], params })
|
||||
}
|
||||
const add = () => commit([...items, { id: nextItemId(items), params: {} }])
|
||||
return (
|
||||
<div>
|
||||
{items.map((item, i) => {
|
||||
const own = issues.filter((x) => x.at?.index === i)
|
||||
const at = (sub: string) => own.filter((x) => x.at?.sub === sub || x.at?.sub?.startsWith(`${sub}.`))
|
||||
const lines = (sub: string) => at(sub).map((x, k) => <IssueLine key={k} issue={x} />)
|
||||
const op = isAnalysisOp(item.op) ? item.op : null
|
||||
const modes = op ? ANALYSIS_MODES[op] : undefined
|
||||
const params = (item.params && typeof item.params === 'object' ? item.params : {}) as Record<string, any>
|
||||
const two = !!op && allowsTwoQueries(op) && ('base_query' in params || 'target_query' in params)
|
||||
const id = String(item.id ?? '')
|
||||
const dup = !!id && items.some((other, j) => j !== i && String(other.id ?? '') === id)
|
||||
const local = !id || !ITEM_ID.test(id) ? AT.idInvalid : dup ? AT.idDuplicate(id) : ''
|
||||
const tone = own.some((x) => x.level === 'error') || local ? 'error' : own.length ? 'warning' : undefined
|
||||
const before = items.slice(0, i).filter((it) => it.op === 'decompose' && it.id)
|
||||
const parent = params.parent && typeof params.parent === 'object' ? params.parent as { of?: string; key?: unknown } : null
|
||||
const field = (spec: ParamSpec) => {
|
||||
const fid = `${uid}-${i}-p-${spec.key}`
|
||||
const label = AT.param[spec.key] ?? spec.key
|
||||
const text = paramText(spec.kind, params[spec.key])
|
||||
const set = (t: string) => setParam(i, spec.key, paramValue(spec.kind, t))
|
||||
let control
|
||||
if (spec.kind === 'basis' || spec.kind === 'grain') {
|
||||
const opts = spec.kind === 'basis' ? AT.basis : AT.grain
|
||||
control = (
|
||||
<select id={fid} className="field text-xs" value={text} onChange={(e) => set(e.target.value)}>
|
||||
{Object.entries(opts).filter(([k]) => !(spec.kind === 'basis' && k === 'change')).map(([k, v]) => (
|
||||
<option key={k} value={k}>{v}</option>
|
||||
))}
|
||||
{text && !(text in opts) && <option value={text} disabled>{text}</option>}
|
||||
</select>
|
||||
)
|
||||
} else if (spec.kind === 'pairs') {
|
||||
control = <textarea id={fid} className="field mono text-xs" rows={2} value={text} spellCheck={false}
|
||||
placeholder="华东、华南" onChange={(e) => set(e.target.value)} />
|
||||
} else if (spec.kind === 'value') {
|
||||
// 期次、对照组、叫法可以按运行输入写 {{ }}(执行时先渲染再分析)
|
||||
control = <TemplateText id={fid} multiline={false} nodeId={nodeId} className="text-xs" value={text}
|
||||
placeholder={AT.paramPlaceholder[spec.key]} onChange={set} />
|
||||
} else {
|
||||
control = <input id={fid} className="field mono text-xs" value={text} spellCheck={false}
|
||||
inputMode={spec.kind === 'int' ? 'numeric' : undefined}
|
||||
placeholder={AT.paramPlaceholder[spec.key]} onChange={(e) => set(e.target.value)} />
|
||||
}
|
||||
const hint = spec.kind === 'columns' ? AT.listHint : spec.kind === 'pairs' ? AT.pairsHint : AT.paramHint[spec.key]
|
||||
return (
|
||||
<div key={spec.key} className="min-w-0">
|
||||
<Sub label={label} htmlFor={fid} sub={`params.${spec.key}`}>
|
||||
{control}
|
||||
{hint && <div className="mt-0.5 text-2xs leading-snug text-faint">{hint}</div>}
|
||||
</Sub>
|
||||
{lines(`params.${spec.key}`)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const specs = op ? paramSpecs(op, item.mode).filter((p) => !(two && 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() }
|
||||
setParam(i, 'headline', next.base || next.target ? next : undefined)
|
||||
}
|
||||
const toggleTwo = (on: boolean) => {
|
||||
const next = { ...params }
|
||||
if (on) {
|
||||
next.base_query = item.from ?? ''
|
||||
next.target_query = ''
|
||||
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 : ''
|
||||
delete next.base_query
|
||||
delete next.target_query
|
||||
update(i, { ...item, from, params: next })
|
||||
}
|
||||
}
|
||||
// 落在某一格下面的问题在那一格下面说,其余的(格式不对、多写了这种分析没有的参数……)放在这一项的最后
|
||||
const placed = ['id', 'op', 'mode', 'hypothesis', ...(two ? ['params.base_query', 'params.target_query'] : ['from']),
|
||||
...specs.map((p) => `params.${p.key}`),
|
||||
...(op && allowsHeadline(op, item.mode) ? ['params.headline'] : []),
|
||||
...(op && allowsParent(op, item.mode) && (before.length > 0 || parent) ? ['params.parent'] : [])]
|
||||
const rest = own.filter((x) => !placed.some((sub) => x.at?.sub === sub || x.at?.sub?.startsWith(`${sub}.`)))
|
||||
return (
|
||||
<Row key={i} item={i} removeLabel={AT.removeItem(id)} tone={tone}
|
||||
onRemove={() => commit(items.filter((_, j) => j !== i))}>
|
||||
<div className="flex gap-1.5" data-analysis-item={id || i}>
|
||||
<Sub label={AT.id} htmlFor={`${uid}-${i}-id`} className="w-20 shrink-0" sub="id">
|
||||
<input id={`${uid}-${i}-id`} className="field mono text-xs" value={id} spellCheck={false}
|
||||
aria-invalid={!!local || undefined}
|
||||
onChange={(e) => update(i, { ...item, id: e.target.value.trim() })} />
|
||||
</Sub>
|
||||
<Sub label={AT.op} htmlFor={`${uid}-${i}-op`} className="min-w-0 flex-1" sub="op">
|
||||
<select id={`${uid}-${i}-op`} className="field text-xs" value={item.op ?? ''}
|
||||
onChange={(e) => update(i, withOp(item, e.target.value))}>
|
||||
<option value="" disabled>{AT.pickOp}</option>
|
||||
{ANALYSIS_OPS.map((o) => <option key={o} value={o}>{ANALYSIS_OP_LABEL[o]}</option>)}
|
||||
{!!item.op && !op && <option value={item.op} disabled>{AT.unknownOp(item.op)}</option>}
|
||||
</select>
|
||||
</Sub>
|
||||
{modes && (
|
||||
<Sub label={AT.mode} htmlFor={`${uid}-${i}-mode`} className="w-[5.5rem] shrink-0" sub="mode">
|
||||
<select id={`${uid}-${i}-mode`} className="field text-xs" value={item.mode ?? ''}
|
||||
onChange={(e) => update(i, withMode(item, e.target.value))}>
|
||||
<option value="" disabled>{AT.pickMode}</option>
|
||||
{modes.map((m) => <option key={m} value={m}>{ANALYSIS_MODE_LABEL[m]}</option>)}
|
||||
{!!item.mode && !modes.includes(item.mode) && <option value={item.mode} disabled>{AT.unknownMode(item.mode)}</option>}
|
||||
</select>
|
||||
</Sub>
|
||||
)}
|
||||
</div>
|
||||
{local && !at('id').length && (
|
||||
<div className="flex items-start gap-1 text-2xs leading-snug" style={{ color: 'var(--err)' }}>
|
||||
<XCircle size={11} className="mt-px shrink-0" aria-hidden />
|
||||
<span className="min-w-0 [overflow-wrap:anywhere]">{local}</span>
|
||||
</div>
|
||||
)}
|
||||
{lines('id')}
|
||||
{lines('op')}
|
||||
{lines('mode')}
|
||||
{id && ITEM_ID.test(id) && (
|
||||
<div className="mono truncate text-2xs text-faint" title={AT.idHint(nodeId, id)}>{AT.idHint(nodeId, id)}</div>
|
||||
)}
|
||||
{two ? (
|
||||
<div className="grid grid-cols-2 gap-1.5">
|
||||
<div className="min-w-0">
|
||||
<Sub label={AT.baseQuery} htmlFor={`${uid}-${i}-bq`} sub="params.base_query">
|
||||
<QueryPick id={`${uid}-${i}-bq`} value={String(params.base_query ?? '')} options={options}
|
||||
onChange={(v) => setParam(i, 'base_query', v)} />
|
||||
</Sub>
|
||||
{lines('params.base_query')}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<Sub label={AT.targetQuery} htmlFor={`${uid}-${i}-tq`} sub="params.target_query">
|
||||
<QueryPick id={`${uid}-${i}-tq`} value={String(params.target_query ?? '')} options={options}
|
||||
onChange={(v) => setParam(i, 'target_query', v)} />
|
||||
</Sub>
|
||||
{lines('params.target_query')}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<Sub label={AT.from} htmlFor={`${uid}-${i}-from`} sub="from">
|
||||
<QueryPick id={`${uid}-${i}-from`} value={String(item.from ?? '')} options={options}
|
||||
onChange={(v) => update(i, { ...item, from: v })} />
|
||||
</Sub>
|
||||
{lines('from')}
|
||||
</div>
|
||||
)}
|
||||
{op && allowsTwoQueries(op) && (
|
||||
<label className="flex items-center gap-1.5 text-2xs text-dim">
|
||||
<input type="checkbox" checked={two} onChange={(e) => toggleTwo(e.target.checked)} data-analysis-two="" />
|
||||
{AT.twoQueries}
|
||||
</label>
|
||||
)}
|
||||
{!options.length && <div className="text-2xs leading-snug text-faint">{AT.noUpstream}</div>}
|
||||
{specs.length > 0 && (
|
||||
<div className="grid grid-cols-2 gap-1.5" data-analysis-params="">
|
||||
{specs.map(field)}
|
||||
</div>
|
||||
)}
|
||||
{op && allowsHeadline(op, item.mode) && (
|
||||
<div data-sub="params.headline">
|
||||
<div className="mb-0.5 text-2xs text-faint">{AT.headline}</div>
|
||||
<div className="grid grid-cols-2 gap-1.5">
|
||||
{(['base', 'target'] as const).map((side) => (
|
||||
<Sub key={side} label={side === 'base' ? AT.headlineBase : AT.headlineTarget}
|
||||
htmlFor={`${uid}-${i}-h-${side}`} sub={`params.headline.${side}`}>
|
||||
<input id={`${uid}-${i}-h-${side}`} className="field mono text-xs" spellCheck={false}
|
||||
value={headline?.[side] ?? ''} placeholder={side === 'base' ? 'weekly.r0.gmv' : 'weekly.r1.gmv'}
|
||||
onChange={(e) => setHeadline(side, e.target.value)} />
|
||||
</Sub>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-0.5 text-2xs leading-snug text-faint">{AT.headlineHint}。{AT.cellHint}</div>
|
||||
{lines('params.headline')}
|
||||
</div>
|
||||
)}
|
||||
{op && allowsParent(op, item.mode) && (before.length > 0 || parent) && (
|
||||
<div data-sub="params.parent">
|
||||
<div className="grid grid-cols-2 gap-1.5">
|
||||
<Sub label={AT.parentOf} htmlFor={`${uid}-${i}-po`}>
|
||||
<select id={`${uid}-${i}-po`} className="field text-xs" value={parent?.of ?? ''}
|
||||
onChange={(e) => setParam(i, 'parent', e.target.value
|
||||
? { of: e.target.value, key: Array.isArray(parent?.key) ? parent!.key : [] } : undefined)}>
|
||||
<option value="">{AT.noParent}</option>
|
||||
{before.map((it) => <option key={String(it.id)} value={String(it.id)}>{String(it.id)}</option>)}
|
||||
{parent?.of && !before.some((it) => it.id === parent.of) && <option value={parent.of} disabled>{parent.of}</option>}
|
||||
</select>
|
||||
</Sub>
|
||||
{parent && (
|
||||
<Sub label={AT.parentKey} htmlFor={`${uid}-${i}-pk`}>
|
||||
<input id={`${uid}-${i}-pk`} className="field mono text-xs" spellCheck={false} placeholder="华东"
|
||||
value={paramText('columns', parent.key)}
|
||||
onChange={(e) => setParam(i, 'parent', { of: parent.of, key: paramValue('columns', e.target.value) ?? [] })} />
|
||||
</Sub>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-0.5 text-2xs leading-snug text-faint">{AT.parentHint}</div>
|
||||
{lines('params.parent')}
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<Sub label={AT.hypothesis} htmlFor={`${uid}-${i}-hyp`} sub="hypothesis">
|
||||
<input id={`${uid}-${i}-hyp`} className="field text-xs" value={item.hypothesis ?? ''}
|
||||
placeholder={AT.hypothesisPlaceholder}
|
||||
onChange={(e) => update(i, { ...item, hypothesis: e.target.value || undefined })} />
|
||||
</Sub>
|
||||
<div className="mt-0.5 text-2xs leading-snug text-faint">{AT.hypothesisHint}</div>
|
||||
{lines('hypothesis')}
|
||||
</div>
|
||||
{rest.map((x, k) => <IssueLine key={k} issue={x} />)}
|
||||
</Row>
|
||||
)
|
||||
})}
|
||||
<button type="button" className="btn btn-sm w-full justify-center" onClick={add} data-analysis-add="">
|
||||
<Plus size={11} /> {AT.addItem}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 分析卡的阈值覆盖:只列写了的几项,「添加阈值覆盖」从没写的里面选。键和叫法同设置里的分析一组(contract.LABELS),范围先在
|
||||
* 这里按 contract.RANGES 说,两两之间的大小(「明显超出」要大于「超出常规波动」……)由服务端核、问题落在这一栏下面。
|
||||
* 全部删掉写回 undefined:没覆盖就不留一个空对象
|
||||
*/
|
||||
function AnalysisOverrides({ value, issues, onChange }: { value: any; issues: FieldIssue[]; onChange: (v: any) => void }) {
|
||||
const uid = useId()
|
||||
const current: Record<string, unknown> = value && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
||||
// 正在填的字先记在本地:「0.」这种还不是数的字写回去会被转成别的
|
||||
const [drafts, setDrafts] = useState<Record<string, string>>({})
|
||||
const keys = Object.keys(current)
|
||||
const free = ANALYSIS_SETTING_KEYS.filter((k) => !(k in current))
|
||||
const write = (next: Record<string, unknown>) => onChange(Object.keys(next).length ? next : undefined)
|
||||
const set = (key: string, text: string) => {
|
||||
setDrafts((d) => ({ ...d, [key]: text }))
|
||||
const t = text.trim()
|
||||
write({ ...current, [key]: t !== '' && Number.isFinite(Number(t)) ? Number(t) : t })
|
||||
}
|
||||
const remove = (key: string) => {
|
||||
const next = { ...current }
|
||||
delete next[key]
|
||||
setDrafts((d) => { const c = { ...d }; delete c[key]; return c })
|
||||
write(next)
|
||||
}
|
||||
return (
|
||||
<div data-analysis-overrides="">
|
||||
{keys.map((key, i) => {
|
||||
const known = (ANALYSIS_SETTING_KEYS as readonly string[]).includes(key)
|
||||
const label = known ? ANALYSIS_SETTING_LABEL[key as AnalysisSettingKey] : key
|
||||
const text = drafts[key] ?? (current[key] == null ? '' : String(current[key]))
|
||||
const problem = known ? settingValueProblem(key as AnalysisSettingKey, text) : null
|
||||
const fid = `${uid}-${i}`
|
||||
return (
|
||||
<Row key={key} removeLabel={AT.removeOverride(label)} tone={problem ? 'error' : undefined} onRemove={() => remove(key)}>
|
||||
<Sub label={label} htmlFor={fid} sub={key}>
|
||||
<input id={fid} className="field tnum text-xs" inputMode="decimal" value={text} aria-invalid={!!problem || undefined}
|
||||
data-analysis-override={key} onChange={(e) => set(key, e.target.value)} />
|
||||
</Sub>
|
||||
<div className="text-2xs leading-snug" style={{ color: problem ? 'var(--err)' : 'var(--text-faint)' }}>
|
||||
{problem ?? (known ? settingRangeText(key as AnalysisSettingKey) : '')}
|
||||
</div>
|
||||
</Row>
|
||||
)
|
||||
})}
|
||||
{!keys.length && <div className="mb-1.5 text-2xs text-faint">{AT.noOverrides}</div>}
|
||||
{issues.map((x, k) => <IssueLine key={k} issue={x} />)}
|
||||
{free.length > 0 ? (
|
||||
<select className="field text-xs" value="" aria-label={AT.addOverride} data-analysis-add-override=""
|
||||
onChange={(e) => { if (e.target.value) set(e.target.value, '') }}>
|
||||
<option value="">{AT.addOverride}</option>
|
||||
{free.map((k) => <option key={k} value={k}>{ANALYSIS_SETTING_LABEL[k]}</option>)}
|
||||
</select>
|
||||
) : <div className="text-2xs text-faint">{AT.allOverridden}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 子工作流钉住版本后的升版处置:和口径卡的是同一个下拉——直接借口径卡的字段定义,选项、
|
||||
* 文案一字不差,只换说明里「和谁同一套」那半句。上游在钉住的那一版之后又发了版时,正式运行
|
||||
@@ -790,6 +1118,12 @@ function FieldInput({ field, id, nodeId, syntax, value, config, invalid, describ
|
||||
case 'mergeInputs':
|
||||
return <MergeInputList nodeId={nodeId} value={value} issues={issues} onChange={onChange} />
|
||||
|
||||
case 'analysisItems':
|
||||
return <AnalysisItemList nodeId={nodeId} value={value} issues={issues} onChange={onChange} />
|
||||
|
||||
case 'analysisOverrides':
|
||||
return <AnalysisOverrides value={value} issues={issues} onChange={onChange} />
|
||||
|
||||
case 'caliberFrom':
|
||||
return <CaliberFromPicker id={id} value={value} invalid={invalid} describedBy={describedBy} />
|
||||
|
||||
|
||||
@@ -67,8 +67,13 @@ export function revealField(nodeId: string, field?: FieldRef | string | null, op
|
||||
const sheet = document.querySelector('[data-inspector-sheet]') ?? document
|
||||
const box = sheet.querySelector<HTMLElement>(`[data-field="${CSS.escape(at.key)}"]`)
|
||||
const item = at.index != null ? box?.querySelector<HTMLElement>(`[data-item="${at.index}"]`) : null
|
||||
// 只有子键没有序号的(合并查询的 inputs.<别名>):在整个字段里按子键找那一行
|
||||
const part = at.sub ? (item ?? box)?.querySelector<HTMLElement>(`[data-sub="${CSS.escape(at.sub)}"]`) : null
|
||||
// 只有子键没有序号的(合并查询的 inputs.<别名>):在整个字段里按子键找那一行。子键带点号的(分析项的 params.headline.base、
|
||||
// params.parent.key)找不到那一格时逐段往上退,落到它所在的那一块(params.parent)
|
||||
const scope = item ?? box
|
||||
let part: HTMLElement | null | undefined = null
|
||||
for (let sub = at.sub; sub && !part; sub = sub.includes('.') ? sub.slice(0, sub.lastIndexOf('.')) : '') {
|
||||
part = scope?.querySelector<HTMLElement>(`[data-sub="${CSS.escape(sub)}"]`)
|
||||
}
|
||||
const target = part ?? item ?? box
|
||||
if (!target) return
|
||||
const still = window.matchMedia('(prefers-reduced-motion: reduce)').matches
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
CHALLENGE_TEXT, claimTally, DUAL_CHECK_TEXT, issuanceLabel, REJECTED_TEXT, reportStampText, RUN_CLASS_LABEL, UPGRADE_POLICY_LABEL,
|
||||
} from '../lib/terms'
|
||||
import { useReportStamp, type ReportStamp } from './reportStamp'
|
||||
import { analysisCardSummary } from './analysisItems'
|
||||
import { ApprovalCard } from '../run/RunPanel'
|
||||
import type { NodeState, NodeTrace } from '../run/trace'
|
||||
import { useRunClock } from '../run/useRunClock'
|
||||
@@ -86,6 +87,9 @@ function summarize(type: NodeType, config: Record<string, any>): string {
|
||||
}
|
||||
return `${config.caliber || '口径'} ${config.caliber_version || 'v1'} · ${(config.metrics ?? []).length} 个指标`
|
||||
}
|
||||
case 'analysis':
|
||||
// 做哪几种分析:「波动基线、变化拆解(可加)」,叫法照契约(lib/termsAnalysis)
|
||||
return analysisCardSummary(config)
|
||||
case 'report': {
|
||||
const from = Array.isArray(config.metrics_from) ? config.metrics_from.length : 0
|
||||
return `${first(config.instructions) || '未填写作要求'} · ${from ? `${from} 张口径卡` : '上游全部口径卡'}`
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
// ===========================================================================
|
||||
// 分析卡(节点类型 analysis)的一项:每种分析在检查器里给哪些参数格、参数怎么在格子和配置之间转换、卡片上的摘要。
|
||||
//
|
||||
// 参数名和服务端 tools/builtin/analysis.py 各参数模型里的字段一致(分析卡按同一份参数模型校验,engine/schema.analysis_issues):
|
||||
// 主输入写在 from(对应 Agent 工具的 query),基期、本期是两份查询时写在 params 的 base_query、target_query;阈值不写在参数里,
|
||||
// 统一写在卡上的阈值覆盖。这里只决定界面上摆哪几格、按什么先后,规则以服务端校验为准(写错了检查器照服务端的说法提示)。
|
||||
// ===========================================================================
|
||||
|
||||
import { ANALYSIS_MODES, ANALYSIS_TEXT, analysisMethodLabel, isAnalysisOp, type AnalysisOp } from '../lib/termsAnalysis'
|
||||
import type { AnalysisItem } from '../types'
|
||||
|
||||
/** 一格参数的写法:列名、几列(顿号、逗号分隔)、期次的值(可以写 {{ }})、整数、两种下拉、几对 */
|
||||
export type ParamKind = 'column' | 'columns' | 'value' | 'int' | 'basis' | 'grain' | 'pairs'
|
||||
|
||||
export interface ParamSpec {
|
||||
key: string
|
||||
kind: ParamKind
|
||||
}
|
||||
|
||||
const col = (key: string): ParamSpec => ({ key, kind: 'column' })
|
||||
const cols = (key: string): ParamSpec => ({ key, kind: 'columns' })
|
||||
const val = (key: string): ParamSpec => ({ key, kind: 'value' })
|
||||
|
||||
/** 两期写在同一份查询里时的期次三格(期次列、基期、本期) */
|
||||
const PERIODS: ParamSpec[] = [col('period'), val('base'), val('target')]
|
||||
|
||||
/**
|
||||
* 每种分析(算子 + 模式)摆哪几格,按这个先后。总数核对(headline)、下钻(parent)、两份查询另有自己的一块,不在这里。
|
||||
* label(度量的叫法)放在最后:留空用列名或数据目录里的名字
|
||||
*/
|
||||
export function paramSpecs(op: AnalysisOp, mode?: string | null): ParamSpec[] {
|
||||
switch (op) {
|
||||
case 'decompose':
|
||||
if (mode === 'ratio') return [cols('by'), ...PERIODS, col('numerator'), col('denominator'), val('label')]
|
||||
if (mode === 'factor') return [...PERIODS, col('product'), cols('factors'), val('label')]
|
||||
return [cols('by'), ...PERIODS, col('measure'), val('label')]
|
||||
case 'baseline':
|
||||
return [col('period'), col('measure'), val('target'), { key: 'basis', kind: 'basis' }, { key: 'grain', kind: 'grain' },
|
||||
{ key: 'lag', kind: 'int' }, val('label')]
|
||||
case 'trend':
|
||||
return [col('period'), col('measure'), { key: 'grain', kind: 'grain' }, val('label')]
|
||||
case 'differ': {
|
||||
const values = mode === 'mean' ? [col('mean'), col('sd'), col('sum'), col('sumsq'), col('n')]
|
||||
: mode === 'rows' ? [col('value')] : [col('numerator'), col('denominator')]
|
||||
return [cols('by'), val('reference'), { key: 'pairs', kind: 'pairs' }, ...values, ...(mode === 'rows' ? [] : PERIODS),
|
||||
val('label')]
|
||||
}
|
||||
case 'comparable':
|
||||
return [...PERIODS, col('measure'), { key: 'grain', kind: 'grain' }]
|
||||
}
|
||||
}
|
||||
|
||||
/** 这种分析能不能写成基期、本期两份查询(DecomposeArgs、ComparableArgs 有 base_query / target_query) */
|
||||
export const allowsTwoQueries = (op: AnalysisOp): boolean => op === 'decompose' || op === 'comparable'
|
||||
/** 有总数核对(headline)的:可加、比率的变化拆解 */
|
||||
export const allowsHeadline = (op: AnalysisOp, mode?: string | null): boolean =>
|
||||
op === 'decompose' && mode !== 'factor'
|
||||
/** 能下钻(parent)的:可加、比率的变化拆解(乘积拆解不按维度拆) */
|
||||
export const allowsParent = allowsHeadline
|
||||
|
||||
/** 两份查询时期次三格不写(两份各自只有一期) */
|
||||
export const TWO_QUERY_SKIP = new Set(['period', 'base', 'target'])
|
||||
|
||||
/** 这种分析会写到的全部参数键:换分析方法、模式时,这几样以外的参数去掉(服务端按多写的参数报错) */
|
||||
export function paramKeys(op: AnalysisOp, mode?: string | null): Set<string> {
|
||||
const keys = new Set(paramSpecs(op, mode).map((p) => p.key))
|
||||
if (allowsTwoQueries(op)) { keys.add('base_query'); keys.add('target_query') }
|
||||
if (allowsHeadline(op, mode)) keys.add('headline')
|
||||
if (allowsParent(op, mode)) keys.add('parent')
|
||||
return keys
|
||||
}
|
||||
|
||||
/** 「region、channel」「region, channel」→ ['region', 'channel'] */
|
||||
export function splitList(text: string): string[] {
|
||||
return text.split(/[、,,\s]+/).map((s) => s.trim()).filter(Boolean)
|
||||
}
|
||||
|
||||
/** 配置里的一格 → 格子里的字 */
|
||||
export function paramText(kind: ParamKind, value: unknown): string {
|
||||
if (value == null) return ''
|
||||
if (kind === 'columns') return Array.isArray(value) ? value.map(String).join('、') : String(value)
|
||||
if (kind === 'pairs') {
|
||||
return Array.isArray(value)
|
||||
? value.map((p) => (Array.isArray(p) ? p.map(String).join('、') : String(p))).join('\n')
|
||||
: String(value)
|
||||
}
|
||||
return String(value)
|
||||
}
|
||||
|
||||
/** 格子里的字 → 配置里的一格;空的返回 undefined(参数里不留这个键) */
|
||||
export function paramValue(kind: ParamKind, text: string): unknown {
|
||||
const t = text.trim()
|
||||
if (!t) return undefined
|
||||
if (kind === 'columns') return splitList(t)
|
||||
if (kind === 'pairs') return t.split('\n').map((line) => splitList(line)).filter((p) => p.length)
|
||||
// 整数格写了不是整数的字照原样交给服务端校验(它会说清该写什么),不在这里悄悄丢掉
|
||||
if (kind === 'int') return /^-?\d+$/.test(t) ? Number(t) : t
|
||||
return t
|
||||
}
|
||||
|
||||
/** 配置里的 items → 一项一项(不是对象的项原样留着,服务端会报「格式有误」) */
|
||||
export function itemsOf(value: unknown): AnalysisItem[] {
|
||||
return Array.isArray(value) ? value.map((v) => (v && typeof v === 'object' ? v as AnalysisItem : {})) : []
|
||||
}
|
||||
|
||||
/** 标识的写法(服务端 schema.ANALYSIS_ITEM_ID):下游按 nodes.<卡>.results.<标识> 取判定 */
|
||||
export const ITEM_ID = /^[A-Za-z_][A-Za-z0-9_]*$/
|
||||
|
||||
/** 新加一项的标识:a1、a2……不和已有的重名 */
|
||||
export function nextItemId(items: AnalysisItem[]): string {
|
||||
const taken = new Set(items.map((i) => String(i.id ?? '')))
|
||||
for (let k = items.length + 1; ; k += 1) if (!taken.has(`a${k}`)) return `a${k}`
|
||||
}
|
||||
|
||||
/** 换分析方法:有模式的取第一种模式,参数只留新方法用得到的,输入和假设留着 */
|
||||
export function withOp(item: AnalysisItem, op: string): AnalysisItem {
|
||||
if (!isAnalysisOp(op)) return { ...item, op, mode: undefined }
|
||||
const mode = ANALYSIS_MODES[op]?.[0]
|
||||
return withParams({ ...item, op, mode }, op, mode)
|
||||
}
|
||||
|
||||
/** 换模式:参数只留这种模式用得到的 */
|
||||
export function withMode(item: AnalysisItem, mode: string): AnalysisItem {
|
||||
return isAnalysisOp(item.op) ? withParams({ ...item, mode }, item.op, mode) : { ...item, mode }
|
||||
}
|
||||
|
||||
function withParams(item: AnalysisItem, op: AnalysisOp, mode: string | null | undefined): AnalysisItem {
|
||||
const keep = paramKeys(op, mode)
|
||||
const params = Object.fromEntries(Object.entries(item.params ?? {}).filter(([k]) => keep.has(k)))
|
||||
const next: AnalysisItem = { ...item, params }
|
||||
if (!ANALYSIS_MODES[op]) delete next.mode
|
||||
return next
|
||||
}
|
||||
|
||||
/** 卡片正文的摘要:「波动基线、变化拆解(可加)」,超过三项写「等 N 项」 */
|
||||
export function analysisCardSummary(config: Record<string, any>): string {
|
||||
const items = itemsOf(config.items)
|
||||
if (!items.length) return ANALYSIS_TEXT.node.summaryEmpty
|
||||
const names = items.map((i) => (i.op ? analysisMethodLabel(i.op, i.mode) : ANALYSIS_TEXT.node.summaryNoOp))
|
||||
const head = names.slice(0, 3).join('、')
|
||||
return names.length > 3 ? `${head}${ANALYSIS_TEXT.node.summaryMore(names.length)}` : head
|
||||
}
|
||||
|
||||
interface CardNodeLike {
|
||||
id: string
|
||||
data?: { nodeType?: string; label?: string; config?: Record<string, any> }
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询节点连到分析卡:第一项还没选输入(也不是两份查询)的分析项顺手选上它,和连线同一步撤销(同合并查询的 connectMergeInput)。
|
||||
* 已经有项用着它、或者每一项都选好了输入时不动
|
||||
*/
|
||||
export function connectAnalysisInput<T extends CardNodeLike>(nodes: T[], source: string | null, target: string | null,
|
||||
isQuery: (n: T | undefined) => boolean): T[] | null {
|
||||
if (!source || !target || source === target) return null
|
||||
const to = nodes.find((n) => n.id === target)
|
||||
if (to?.data?.nodeType !== 'analysis' || !isQuery(nodes.find((n) => n.id === source))) return null
|
||||
const items = itemsOf(to.data?.config?.items)
|
||||
const uses = (it: AnalysisItem) => [it.from, it.params?.base_query, it.params?.target_query].includes(source)
|
||||
if (items.some(uses)) return null
|
||||
const i = items.findIndex((it) => !String(it.from ?? '').trim() && !('base_query' in (it.params ?? {})))
|
||||
if (i < 0) return null
|
||||
const next = items.map((it, j) => (j === i ? { ...it, from: source } : it))
|
||||
return nodes.map((n) => (n.id === target ? { ...n, data: { ...n.data, config: { ...(n.data?.config ?? {}), items: next } } } : n))
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import {
|
||||
Bot, Braces, Brain, CheckCircle2, Code2, Combine, Database, FileInput, FileOutput, FileText,
|
||||
Bot, Braces, Brain, ChartColumnStacked, CheckCircle2, Code2, Combine, Database, FileInput, FileOutput, FileText,
|
||||
Gauge, GitBranch, GitCompareArrows, Hand, Repeat, Search, ShieldAlert, Shuffle, Users, Wrench,
|
||||
} from 'lucide-react'
|
||||
import {
|
||||
APPROVAL_POLICY_LABEL, CHALLENGE_TEXT, DUAL_CHECK_TEXT, MERGE_TEXT, NODE_TYPE_LABEL, REJECTED_TEXT, UPGRADE_POLICY_LABEL,
|
||||
} from '../lib/terms'
|
||||
import { ANALYSIS_FIELD_LABEL, ANALYSIS_OPTION_LABEL, ANALYSIS_TEXT } from '../lib/termsAnalysis'
|
||||
import type { NodeType } from '../types'
|
||||
import { dualCheckFields, dualCheckSummary } from './DualCheckFields'
|
||||
import { HUMAN_PROCESS_FIELDS, TOOL_WRITE_FIELDS } from './humanFields'
|
||||
@@ -15,6 +16,7 @@ export type FieldType =
|
||||
| 'text' | 'textarea' | 'prompt' | 'code' | 'number' | 'select' | 'switch'
|
||||
| 'json' | 'model' | 'tools' | 'skills' | 'collection'
|
||||
| 'ioFields' | 'cases' | 'agents' | 'metricsList' | 'nodeRefs' | 'caliberFrom' | 'judge' | 'mergeInputs'
|
||||
| 'analysisItems' | 'analysisOverrides'
|
||||
|
||||
/**
|
||||
* 这个字段里写的是什么语法。
|
||||
@@ -654,6 +656,29 @@ export const NODE_DEFS: Record<NodeType, NodeDef> = {
|
||||
+ '反引号中无从核对的名称标为「疑似不存在的名称」',
|
||||
unknownLabel: (v) => `${v}:无法识别的值,请从上方选项中选择`,
|
||||
},
|
||||
{
|
||||
// 后端认 off / check / strict(schema.ANALYSIS_CLAIMS_VALUES),没写按 check:缺省放第一项,没写时下拉正好落在它上面。
|
||||
// 选项以 engine/labels.py 的短说法开头
|
||||
key: 'analysis_claims', label: ANALYSIS_FIELD_LABEL.analysis_claims, type: 'select',
|
||||
options: [
|
||||
{ value: 'check', label: `${ANALYSIS_OPTION_LABEL.analysis_claims.check}(默认):仍有的在报告中标注,不影响出具档位` },
|
||||
{ value: 'strict', label: `${ANALYSIS_OPTION_LABEL.analysis_claims.strict}:按最多重写次数重写,出具随之降档` },
|
||||
{ value: 'off', label: ANALYSIS_OPTION_LABEL.analysis_claims.off },
|
||||
],
|
||||
help: '「主要来自」「超出常规波动」「持续上升」这类判断要挂对应的分析结论且判定对得上;「由于」「导致」这类原因要有'
|
||||
+ '知识库原话或运行输入作依据,否则写成待核实的推测。受管级别发布须选择「重写后仍有的计入缺口」',
|
||||
unknownLabel: (v) => `${v}:无法识别的值,请从上方选项中选择`,
|
||||
},
|
||||
{
|
||||
// 后端认 auto / off(schema.ANALYSIS_SCOPE_VALUES),没写按 auto
|
||||
key: 'analysis_scope', label: ANALYSIS_FIELD_LABEL.analysis_scope, type: 'select', advanced: true,
|
||||
options: [
|
||||
{ value: 'auto', label: `${ANALYSIS_OPTION_LABEL.analysis_scope.auto}(默认)` },
|
||||
{ value: 'off', label: ANALYSIS_OPTION_LABEL.analysis_scope.off },
|
||||
],
|
||||
help: '报告末尾由系统写一段:现象、拆过、排除、没拆、检验,写作者改不了,随报告封存',
|
||||
unknownLabel: (v) => `${v}:无法识别的值,请从上方选项中选择`,
|
||||
},
|
||||
...MODEL_FIELDS,
|
||||
{ key: 'system', label: '系统提示', type: 'textarea', advanced: true, placeholder: '你是…' },
|
||||
...COMMON_TAIL,
|
||||
@@ -698,6 +723,20 @@ export const NODE_DEFS: Record<NodeType, NodeDef> = {
|
||||
metrics: [{ id: 'total', name: '', unit: '', expression: '' }],
|
||||
},
|
||||
},
|
||||
analysis: {
|
||||
type: 'analysis', label: NODE_TYPE_LABEL.analysis, category: '把关', icon: ChartColumnStacked,
|
||||
description: ANALYSIS_TEXT.node.description,
|
||||
hasTarget: true, sources: [{ id: 'out', label: '' }],
|
||||
// 配置的键照服务端 engine/schema.analysis_issues:items(每项 id、op、mode、from、params、hypothesis)、overrides(阈值覆盖,
|
||||
// 键和范围同设置里的分析一组)。产出 nodes.<卡>.results.<项> = {status, verdict, direction, values, phrase, artifact}
|
||||
fields: [
|
||||
{ key: 'items', label: ANALYSIS_FIELD_LABEL.items, type: 'analysisItems', help: ANALYSIS_TEXT.node.itemsHint },
|
||||
{ key: 'overrides', label: ANALYSIS_FIELD_LABEL.overrides, type: 'analysisOverrides', help: ANALYSIS_TEXT.node.overridesHint },
|
||||
...COMMON_TAIL,
|
||||
],
|
||||
// 带一项空的:拖进画布就看得到一项要填什么(同口径卡带一个空指标)
|
||||
defaults: { items: [{ id: 'a1', params: {} }] },
|
||||
},
|
||||
dual_check: {
|
||||
type: 'dual_check', label: NODE_TYPE_LABEL.dual_check, category: '把关', icon: GitCompareArrows,
|
||||
description: DUAL_CHECK_TEXT.description,
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import type { JSX } from 'react'
|
||||
import fixtures from '../../run/__tests__/fixtures.json'
|
||||
import { AssistantStream, type StreamTurn } from '../../run/AssistantStream'
|
||||
import { decodeRun } from '../../run/decode'
|
||||
import { analysisTeamRun } from '../../run/__tests__/synthetic'
|
||||
import type { RunEvent } from '../../types'
|
||||
|
||||
/**
|
||||
* 分析能力一轮在问数据时间线、出具横幅上的样子,scripts/check-stream.mjs 按它检查:
|
||||
*
|
||||
* - ?syn=analysis:两轮真跑出来的事件(fixtures.json 的 analysis_agent、analysis_card,后端测试库里的虚构零售库 shop、模型换成
|
||||
* 脚本录下的)。第一轮 Agent 查两次库、写错一次变化拆解(调用有误)、做变化拆解、波动基线(算不了)、可比性检查,报告有 3 处
|
||||
* 分析说法标注(check,不影响档位);第二轮分析卡两项(波动基线算不了、按地区拆解)
|
||||
* - ?syn=analysis-issued:出具横幅里分析能力一轮的三项都在——分析说法 strict 记了缺口、指标两期有条件可比和不可比、报告引用的
|
||||
* 指标没追到原始数据(受管级别记了缺口)
|
||||
* - ?syn=analysis-team:协作成员调分析工具(编号是成员自己的)
|
||||
*
|
||||
* 地区、门店、指标、数字都是虚构的;说法照服务端的写法
|
||||
*/
|
||||
|
||||
type Fixture = Record<string, RunEvent[]>
|
||||
const F = fixtures as unknown as Fixture
|
||||
|
||||
const outputOf = (events: RunEvent[]) => (events.find((e) => e.type === 'run.finished')?.data as { output?: Record<string, unknown> })?.output
|
||||
|
||||
function recordedTurns(): StreamTurn[] {
|
||||
const agent = F.analysis_agent
|
||||
const card = F.analysis_card
|
||||
return [
|
||||
{ id: 'analysis-agent', question: '本周销售额为什么下降', phase: 'done', status: '已完成',
|
||||
steps: decodeRun(agent, { status: 'succeeded' }), output: outputOf(agent), runId: 'syn-analysis-agent', runClass: 'exploratory' },
|
||||
{ id: 'analysis-card', question: '按模板出本周的异动分析', phase: 'done', status: '已完成',
|
||||
steps: decodeRun(card, { status: 'succeeded' }), output: outputOf(card), runId: 'syn-analysis-card', runClass: 'exploratory' },
|
||||
]
|
||||
}
|
||||
|
||||
/** 三项都在的出具声明(照 engine/nodes/io.py 的形状;strict 的那几处原话照服务端 analysis_claims 的写法) */
|
||||
export const ANALYSIS_ISSUANCE = {
|
||||
mode: 'citations', tier: 'degraded', matched_numbers: 3, metrics_checked: 1, missing_required: [], missing_expected: [],
|
||||
unmatched_numbers: [], calibers: [],
|
||||
gaps: [
|
||||
'报告「写周报」有 1 处分析说法未通过核对(1 处与所挂结论的判定对不上):判断要挂对应的分析结论并照判定写,原因要有知识库原话或运行输入作依据',
|
||||
'指标「环比」两期不可比:两边除了日期,筛选的还不一样',
|
||||
'指标「客单价」的输入没追到原始数据:vars.aov(停在「沙箱估算」)',
|
||||
],
|
||||
analysis_claims: {
|
||||
mode: 'strict', count: 1, counts: { analysis_claim_mismatch: 1 }, counted: true,
|
||||
violations: [{ code: 'analysis_claim_mismatch', text: '主要来自', claim: 'source', op: 'decompose', analyses: ['A1'], unit: 'u3',
|
||||
segment: 's12', span: [80, 84], message: '「主要来自华南」与所挂的分析结论 A1 对不上:判定的主要来源是华东,不是华南',
|
||||
context: '其中下降主要来自华南。' }],
|
||||
},
|
||||
comparability: [
|
||||
{ metric: 'wow', name: '环比', verdict: 'incomparable', phrase: '两期不可比:两边除了日期,筛选的还不一样', reasons: ['两边除了日期,筛选的还不一样'] },
|
||||
{ metric: 'mom', name: '月环比', verdict: 'conditional', phrase: '两期有条件可比:两段的周末天数不同:4 天对 6 天',
|
||||
reasons: ['两段的周末天数不同:4 天对 6 天'] },
|
||||
],
|
||||
untraced: { metrics: [{ metric: 'aov', name: '客单价', stops: [{ path: 'vars.aov', node_id: 'estimate' }] }], counted: true },
|
||||
}
|
||||
|
||||
function issuedTurn(): StreamTurn {
|
||||
const at = Date.now() / 1000 - 30
|
||||
const output = { 周报: '本周销售额下降,主要来自华东。', _issuance: ANALYSIS_ISSUANCE }
|
||||
const events: RunEvent[] = [
|
||||
{ seq: 1, type: 'run.started', node_id: null, ts: at, data: { nodes: 1 } },
|
||||
{ seq: 2, type: 'node.started', node_id: 'done', ts: at + 1, data: { node_type: 'output', label: '成果' } },
|
||||
{ seq: 3, type: 'issuance', node_id: 'done', ts: at + 1.2, data: { tier: 'degraded', mode: 'citations',
|
||||
gaps: ANALYSIS_ISSUANCE.gaps, analysis_claims: { mode: 'strict', count: 1, counted: true } } },
|
||||
{ seq: 4, type: 'node.finished', node_id: 'done', ts: at + 1.3, data: { duration_ms: 300 } },
|
||||
{ seq: 5, type: 'run.finished', node_id: null, ts: at + 1.4, data: { output, duration_ms: 1400 } },
|
||||
]
|
||||
return { id: 'analysis-issued', question: '本周销售周报', phase: 'done', status: '已完成',
|
||||
steps: decodeRun(events, { status: 'succeeded' }), output, runId: 'syn-analysis-issued', runClass: 'formal' }
|
||||
}
|
||||
|
||||
function teamTurn(): StreamTurn {
|
||||
const ev = analysisTeamRun()
|
||||
return { id: 'analysis-team', question: '销售额为什么下降', phase: 'done', status: '已完成',
|
||||
steps: decodeRun(ev, { status: 'succeeded' }), runId: 'syn-analysis-team' }
|
||||
}
|
||||
|
||||
export const cases: Record<string, () => JSX.Element> = {
|
||||
analysis: () => (
|
||||
<div className="h-screen" data-fixture="analysis"><AssistantStream turns={recordedTurns()} /></div>
|
||||
),
|
||||
'analysis-issued': () => (
|
||||
<div className="h-screen" data-fixture="analysis-issued"><AssistantStream turns={[issuedTurn()]} /></div>
|
||||
),
|
||||
'analysis-team': () => (
|
||||
<div className="h-screen" data-fixture="analysis-team"><AssistantStream turns={[teamTurn()]} /></div>
|
||||
),
|
||||
}
|
||||
@@ -32,6 +32,7 @@ import evidenceEntity from '../run/__tests__/evidence-entity.json'
|
||||
import evidenceJudge from '../run/__tests__/evidence-judge.json'
|
||||
import evidenceVerdict from '../run/__tests__/evidence-verdict.json'
|
||||
import evidenceProvenance from '../run/__tests__/evidence-provenance.json'
|
||||
import evidenceAnalysis from '../run/__tests__/evidence-analysis.json'
|
||||
import { EvidenceGuessView } from '../run/EvidenceGuess'
|
||||
import { IssuanceBanner } from '../run/AssistantStream'
|
||||
import mdPinned from '../run/__tests__/markdown-pinned.json'
|
||||
@@ -214,6 +215,14 @@ const EV_VERDICT_EXPLORE = evidenceVerdict.explore.doc as unknown as EvidenceDoc
|
||||
* 片段接口、推断来源接口、导入清单的工件都由 check-evidence 用 page.route 伪造(按 runId 认出这一份夹具)
|
||||
*/
|
||||
const EV_PROVENANCE = evidenceProvenance.doc as unknown as EvidenceDocData
|
||||
/**
|
||||
* 分析能力一轮:判定语、具名的数、结果表的格(evidence-analysis.json,真运行组装的文档)。agent 那份有三句说法违规和系统写的
|
||||
* 分析范围;card 是分析卡的结论(报告里有一张表引用结果表的格);metric 是口径卡指标上挂着两期可比性。片段接口、证据图、分析
|
||||
* 范围编号的出处链由 check-evidence 用 page.route 伪造(按 runId 认出这一份夹具)
|
||||
*/
|
||||
const EV_ANALYSIS = evidenceAnalysis.agent.doc as unknown as EvidenceDocData
|
||||
const EV_ANALYSIS_CARD = evidenceAnalysis.card.doc as unknown as EvidenceDocData
|
||||
const EV_ANALYSIS_METRIC = evidenceAnalysis.metric.doc as unknown as EvidenceDocData
|
||||
/** 同一份旧契约的出具,去掉位置:老运行就是这样,只能按字符串标 */
|
||||
const LEGACY_LOOSE = {
|
||||
matched: EV_LEGACY.matched.map(({ start: _s, end: _e, ...m }) => m),
|
||||
@@ -452,6 +461,28 @@ function EvidenceOnly() {
|
||||
label="answer" dense tally />
|
||||
</div>
|
||||
</div>
|
||||
{/* 分析能力一轮:分析结论的出处链、说法违规的标注、系统写的分析范围、口径卡指标上的两期可比性 */}
|
||||
<div className="flex flex-col gap-4" id="evidence-analysis-demo">
|
||||
<div id="evidence-analysis" className="rounded-lg border p-3">
|
||||
<div className="mb-1 text-2xs text-faint">分析结论(Agent 的分析工具)、说法违规、分析范围</div>
|
||||
<EvidenceDoc doc={EV_ANALYSIS} artifact={evidenceAnalysis.agent.doc_artifact} runId={evidenceAnalysis.agent.run_id}
|
||||
runClass="exploratory" label="answer" tally />
|
||||
</div>
|
||||
<div id="evidence-analysis-narrow" className="rounded-lg border bg-panel p-2.5" style={{ width: 360, maxWidth: '100%' }}>
|
||||
<EvidenceDoc doc={EV_ANALYSIS} artifact={evidenceAnalysis.agent.doc_artifact} runId={evidenceAnalysis.agent.run_id}
|
||||
runClass="exploratory" label="answer" dense tally />
|
||||
</div>
|
||||
<div id="evidence-analysis-card" className="rounded-lg border p-3">
|
||||
<div className="mb-1 text-2xs text-faint">分析卡的结论(模板定好的分析),表格里引用结果表的格</div>
|
||||
<EvidenceDoc doc={EV_ANALYSIS_CARD} artifact={evidenceAnalysis.card.doc_artifact} runId={evidenceAnalysis.card.run_id}
|
||||
runClass="exploratory" label="answer" tally />
|
||||
</div>
|
||||
<div id="evidence-analysis-metric" className="rounded-lg border p-3">
|
||||
<div className="mb-1 text-2xs text-faint">口径卡指标上的两期可比性</div>
|
||||
<EvidenceDoc doc={EV_ANALYSIS_METRIC} artifact={evidenceAnalysis.metric.doc_artifact}
|
||||
runId={evidenceAnalysis.metric.run_id} runClass="exploratory" label="answer" tally />
|
||||
</div>
|
||||
</div>
|
||||
<div id="evidence-long" className="rounded-lg border p-3">
|
||||
<div className="mb-1 text-2xs text-faint">长报告:{EV_LONG.blocks.length} 块,块级 content-visibility,超过 3000 字先折叠</div>
|
||||
<EvidenceDoc doc={EV_LONG} label="长报告" tally />
|
||||
|
||||
@@ -82,6 +82,7 @@
|
||||
--nt-human: #ce91e6;
|
||||
--nt-validate: #ebb1fd;
|
||||
--nt-metrics: #cbaddb;
|
||||
--nt-analysis: #c09dd9;
|
||||
--nt-report: #a9b0ec;
|
||||
--nt-dual_check: #a98ee0;
|
||||
--nt-challenge: #dcb7ef;
|
||||
@@ -151,6 +152,7 @@
|
||||
--nt-human: #6f3d81;
|
||||
--nt-validate: #885398;
|
||||
--nt-metrics: #6e557b;
|
||||
--nt-analysis: #674a82;
|
||||
--nt-report: #4f5694;
|
||||
--nt-dual_check: #5a4a91;
|
||||
--nt-challenge: #7d4c8f;
|
||||
@@ -214,6 +216,7 @@
|
||||
--nt-human: #6f3d81;
|
||||
--nt-validate: #885398;
|
||||
--nt-metrics: #6e557b;
|
||||
--nt-analysis: #674a82;
|
||||
--nt-report: #4f5694;
|
||||
--nt-dual_check: #5a4a91;
|
||||
--nt-challenge: #7d4c8f;
|
||||
@@ -428,6 +431,7 @@
|
||||
.nt-transform { --nt: var(--nt-transform); }
|
||||
.nt-subgraph { --nt: var(--nt-subgraph); }
|
||||
.nt-metrics { --nt: var(--nt-metrics); }
|
||||
.nt-analysis { --nt: var(--nt-analysis); }
|
||||
.nt-report { --nt: var(--nt-report); }
|
||||
.nt-dual_check { --nt: var(--nt-dual_check); }
|
||||
.nt-challenge { --nt: var(--nt-challenge); }
|
||||
@@ -1667,6 +1671,18 @@
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
/* 说法违规(分析能力一轮):那段文字是可点的片段,但只在判断词那几个字下面画线——波浪线、提醒色,和「无证据」的点状线分得开;
|
||||
整段不画线 */
|
||||
.ev-seg[data-ev-state="claim"] { text-decoration-line: none; }
|
||||
.ev-claim-word {
|
||||
text-decoration-line: underline;
|
||||
text-decoration-style: wavy;
|
||||
text-decoration-color: var(--st-waiting);
|
||||
text-decoration-thickness: 1px;
|
||||
text-underline-offset: 3px;
|
||||
-webkit-box-decoration-break: clone;
|
||||
box-decoration-break: clone;
|
||||
}
|
||||
/* 句末的「无证据」小标签:字形加文字,去掉颜色也读得出 */
|
||||
.ev-tag {
|
||||
margin: 0 3px;
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
EVIDENCE_AUDIT_TEXT, EVIDENCE_KIND_LABEL, EVIDENCE_STATE_LABEL, EVIDENCE_TEXT, JUDGE_TEXT, UPGRADE_POLICY_LABEL,
|
||||
claimTally, evidenceTally, type ClaimTallyCounts,
|
||||
} from './terms'
|
||||
import { ANALYSIS_TEXT } from './termsAnalysis'
|
||||
import { NONE, formatNumber, shortId } from './format'
|
||||
import type {
|
||||
EvidenceBlock, EvidenceCaliberSource, EvidenceCaliberUpgrade, EvidenceCandidate, EvidenceDocData, EvidenceFieldRef,
|
||||
@@ -237,6 +238,21 @@ export function citeLabel(alias: string, doc: Pick<EvidenceDocData, 'catalog'>,
|
||||
return typeof entry?.label === 'string' ? entry.label : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* 证据图里一份分析结论派生自谁(edges 的 rel derived_from:A → Q 是它的输入快照,A → A 是下钻的上一层),按图里的先后、去重。
|
||||
* 只认同一份报告的边(多份报告的运行里同一个编号可能各指各的);不是分析结论、证据图没给边的是空列表
|
||||
*/
|
||||
export function derivedFrom(graph: EvidenceGraph | undefined, alias: string, report?: string): string[] {
|
||||
const out: string[] = []
|
||||
for (const e of graph?.edges ?? []) {
|
||||
const edge = e as { from?: string; to?: string; rel?: string; report?: string }
|
||||
if (edge.rel !== 'derived_from' || edge.from !== alias || !edge.to) continue
|
||||
if (report && edge.report && edge.report !== report) continue
|
||||
if (!out.includes(edge.to)) out.push(edge.to)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* 片段的来源说一句:「口径卡指标 环比增幅」「运行输入 week」「查询 Q3 · 第 6 行 · amount」。
|
||||
* 单元格先看 cite 的种类:查询条目在目录里是 query,引用它的一格是 cell
|
||||
@@ -245,6 +261,14 @@ export function sourceOf(seg: EvidenceSegment, doc?: Pick<EvidenceDocData, 'cata
|
||||
const cite = seg.cite
|
||||
if (!cite) return ''
|
||||
const entry = cite.alias ? doc?.catalog?.[cite.alias] : undefined
|
||||
if (cite.kind === 'analysis' || entry?.kind === 'analysis') {
|
||||
// 分析结论:判定语([[a:A1]])、具名的数([[a:A1.top_share]])、结果表的一格([[v:A1.r0.delta]],cite 的种类是 cell)
|
||||
const E = ANALYSIS_TEXT.evidence
|
||||
const loc = cite.locator ?? {}
|
||||
const what = cite.kind === 'cell' ? E.citedCell(Number(loc.row) || 0, String(loc.column ?? ''))
|
||||
: loc.key ? E.citedValue(loc.key) : E.citedPhrase
|
||||
return [`${E.title} ${cite.alias ?? ''}`.trim(), what].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(' · ')
|
||||
@@ -1273,6 +1297,8 @@ export interface AuditRow {
|
||||
sealed: boolean | null
|
||||
/** 结论句那几行:是哪一句(正文里有句末徽标时点这一行打开它的「模型的解释」) */
|
||||
unit?: string
|
||||
/** 违规那几行的问题代码(说法违规的叫法按它取:ANALYSIS_TEXT.claim.label) */
|
||||
issue?: string
|
||||
}
|
||||
|
||||
const GROUP_OF: Record<EvidenceStateCode, AuditGroup> = {
|
||||
@@ -1330,6 +1356,7 @@ export function auditFromApi(body: unknown): AuditRow[] {
|
||||
sentence: String(r.sentence ?? '').trim(),
|
||||
sealed: typeof r.sealed === 'boolean' ? r.sealed : null,
|
||||
...(kind === 'claim' && typeof r.unit === 'string' && r.unit ? { unit: r.unit } : {}),
|
||||
...(kind === 'violation' && typeof r.issue === 'string' && r.issue ? { issue: r.issue } : {}),
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
@@ -189,6 +189,7 @@ export const NODE_TYPE_LABEL: Record<NodeType, string> = {
|
||||
human: '人工审批',
|
||||
validate: '结构校验',
|
||||
metrics: '口径卡',
|
||||
analysis: '分析卡',
|
||||
report: '报告撰写',
|
||||
dual_check: '双盲复算',
|
||||
challenge: '反方审稿',
|
||||
@@ -1164,6 +1165,7 @@ export const EVIDENCE_KIND_LABEL: Record<string, string> = {
|
||||
entity: '表或字段',
|
||||
column: '字段',
|
||||
quote: '引文',
|
||||
analysis: '分析结论',
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
/**
|
||||
* 分析能力一轮(docs/design/analysis-round)的界面文案:分析卡的检查器和卡片、问数据时间线上的分析一步、证据面板的分析一步与
|
||||
* 口径卡指标上的可比性、正文里的说法违规与系统写的「分析范围」、出具声明里的三项、设置「分析」一节、运行对比的分析卡一节。
|
||||
*
|
||||
* 叫法只有服务端契约一份(backend/app/analysis/contract.py 的 OP_LABELS / MODE_LABELS / LABELS,engine/labels.py 的分析卡字段与
|
||||
* 报告节点两个新字段引用它们):这里的 ANALYSIS_OP_LABEL、ANALYSIS_MODE_LABEL、ANALYSIS_SETTING_LABEL、ANALYSIS_FIELD_LABEL 和它们
|
||||
* 一字不差(scripts/check-studio、check-manage 读后端源码逐项比对)。判定语、判定标准、算不了的原因、附带说明、代入式、闭合核对
|
||||
* 的数、说法违规的原话都是服务端写好的,界面照原样显示,不按判定码、原因码自己拼。规矩同 terms.ts 开头的术语表。
|
||||
*
|
||||
* 术语:一次分析的结果叫「分析结论」,编号 A1、A2……;系统写的那一句叫「判定语」;判定的依据叫「判定标准」;做不成的叫「没有做成」
|
||||
* (服务端判定语的写法),原因叫「算不了的原因」;写错的调用叫「调用有误」,不记成结论;Agent 写的那句叫「Agent 写的假设」。
|
||||
*/
|
||||
import { formatNumber } from './format'
|
||||
|
||||
/** 五个算子(contract.OPS),按契约的先后 */
|
||||
export const ANALYSIS_OPS = ['decompose', 'baseline', 'trend', 'differ', 'comparable'] 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: '可比性检查',
|
||||
}
|
||||
|
||||
/** 模式的叫法:contract.MODE_LABELS(比率拆解和比率比较都叫「比率」) */
|
||||
export const ANALYSIS_MODE_LABEL: Record<string, string> = {
|
||||
additive: '可加', ratio: '比率', factor: '乘积', rate: '比率', mean: '均值', rows: '逐行明细',
|
||||
}
|
||||
|
||||
/** 有模式的算子和它们的模式:contract.MODES。其余算子没有模式 */
|
||||
export const ANALYSIS_MODES: Partial<Record<AnalysisOp, readonly string[]>> = {
|
||||
decompose: ['additive', 'ratio', 'factor'],
|
||||
differ: ['rate', 'mean', 'rows'],
|
||||
}
|
||||
|
||||
export const isAnalysisOp = (op: unknown): op is AnalysisOp => typeof op === 'string' && (ANALYSIS_OPS as readonly string[]).includes(op)
|
||||
|
||||
/**
|
||||
* 「变化拆解(可加)」「波动基线」:同 contract.method_label。认不出的算子、模式原样写出来,不编叫法。证据面板、导出页用服务端
|
||||
* 给的 method_label;事件里只有算子和模式的(时间线、运行对比)照这一份拼
|
||||
*/
|
||||
export function analysisMethodLabel(op: unknown, mode?: unknown): string {
|
||||
const name = isAnalysisOp(op) ? ANALYSIS_OP_LABEL[op] : String(op ?? '')
|
||||
if (mode == null || mode === '') return name
|
||||
return `${name}(${ANALYSIS_MODE_LABEL[String(mode)] ?? String(mode)})`
|
||||
}
|
||||
|
||||
/** Agent 分析工具的名字(contract.TOOL_NAMES:analysis_<算子>)→ 算子;不是分析工具为 null */
|
||||
export function analysisToolOp(tool: unknown): AnalysisOp | null {
|
||||
const m = typeof tool === 'string' ? /^analysis_([a-z]+)$/.exec(tool.trim()) : null
|
||||
return m && isAnalysisOp(m[1]) ? m[1] : null
|
||||
}
|
||||
|
||||
/** 分析卡、报告节点新字段的叫法:engine/labels.py 的 _FIELD_BY_TYPE['analysis'] 与 FIELD_LABEL */
|
||||
export const ANALYSIS_FIELD_LABEL = {
|
||||
items: '分析项',
|
||||
overrides: '阈值覆盖',
|
||||
analysis_claims: '分析说法核对',
|
||||
analysis_scope: '分析范围',
|
||||
} as const
|
||||
|
||||
/** 报告节点两个新字段取值的短说法:engine/labels.py 的 _OPTION_LABEL(下拉的选项以它开头,后面可以带一句用途) */
|
||||
export const ANALYSIS_OPTION_LABEL = {
|
||||
analysis_claims: { off: '不核对', check: '重写一次后标出', strict: '重写后仍有的计入缺口' },
|
||||
analysis_scope: { auto: '有分析结论时附上', off: '不附' },
|
||||
} as const
|
||||
|
||||
/** 分析设置的键(contract.DEFAULTS 的先后) */
|
||||
export const ANALYSIS_SETTING_KEYS = [
|
||||
'main_share', 'concentration', 'offset_ratio', 'flat_pct', 'k_warn', 'k_alert', 'min_history', 'max_history',
|
||||
'trend_min_points', 'trend_alpha', 'differ_alpha', 'min_n', 'min_expected', 'min_denominator', 'max_calls',
|
||||
'max_drill_depth', 'table_top_k',
|
||||
] as const
|
||||
export type AnalysisSettingKey = (typeof ANALYSIS_SETTING_KEYS)[number]
|
||||
|
||||
/** 每一项的叫法:contract.LABELS(设置页、阈值覆盖、服务端报错同一套) */
|
||||
export const ANALYSIS_SETTING_LABEL: Record<AnalysisSettingKey, string> = {
|
||||
main_share: '「主要来源」的占比',
|
||||
concentration: '「集中」的合计占比',
|
||||
offset_ratio: '记为「抵消」的比例',
|
||||
flat_pct: '「基本持平」的幅度',
|
||||
k_warn: '「超出常规波动」的倍数',
|
||||
k_alert: '「明显超出」的倍数',
|
||||
min_history: '至少几期历史',
|
||||
max_history: '最多用几期历史',
|
||||
trend_min_points: '趋势至少几期',
|
||||
trend_alpha: '趋势的显著性水平',
|
||||
differ_alpha: '差异检验的显著性水平',
|
||||
min_n: '均值比较的最小样本数',
|
||||
min_expected: '比率比较的最小期望频数',
|
||||
min_denominator: '比率拆解的最小分母',
|
||||
max_calls: 'Agent 每次执行最多分析几次',
|
||||
max_drill_depth: '最多下钻几层',
|
||||
table_top_k: '列出前几段',
|
||||
}
|
||||
|
||||
/** 每一项的类型和闭区间:contract.RANGES(整数项只收整数)。界面先按它说哪一项不对,两两之间的大小交给服务端核 */
|
||||
export const ANALYSIS_SETTING_RANGE: Record<AnalysisSettingKey, readonly ['float' | 'int', number, number]> = {
|
||||
main_share: ['float', 0.3, 0.9],
|
||||
concentration: ['float', 0.5, 0.99],
|
||||
offset_ratio: ['float', 0.05, 1.0],
|
||||
flat_pct: ['float', 0.0, 0.1],
|
||||
k_warn: ['float', 1.0, 5.0],
|
||||
k_alert: ['float', 1.5, 8.0],
|
||||
min_history: ['int', 4, 104],
|
||||
max_history: ['int', 8, 260],
|
||||
trend_min_points: ['int', 4, 104],
|
||||
trend_alpha: ['float', 0.001, 0.2],
|
||||
differ_alpha: ['float', 0.001, 0.2],
|
||||
min_n: ['int', 2, 10_000],
|
||||
min_expected: ['int', 1, 50],
|
||||
min_denominator: ['int', 1, 100_000],
|
||||
max_calls: ['int', 1, 50],
|
||||
max_drill_depth: ['int', 1, 6],
|
||||
table_top_k: ['int', 3, 30],
|
||||
}
|
||||
|
||||
/** 设置页把这几项分成几组(只是排版,键和叫法照上面) */
|
||||
export const ANALYSIS_SETTING_GROUPS: { title: string; keys: AnalysisSettingKey[] }[] = [
|
||||
{ title: '变化拆解', keys: ['main_share', 'concentration', 'offset_ratio', 'flat_pct', 'min_denominator', 'table_top_k'] },
|
||||
{ title: '波动基线与趋势判断', keys: ['k_warn', 'k_alert', 'min_history', 'max_history', 'trend_min_points', 'trend_alpha'] },
|
||||
{ title: '差异检验', keys: ['differ_alpha', 'min_n', 'min_expected'] },
|
||||
{ title: '次数与层数', keys: ['max_calls', 'max_drill_depth'] },
|
||||
]
|
||||
|
||||
/** 范围写成人话:「0.3 到 0.9 之间」「4 到 104 之间的整数」 */
|
||||
export function settingRangeText(key: AnalysisSettingKey): string {
|
||||
const [kind, lo, hi] = ANALYSIS_SETTING_RANGE[key]
|
||||
return kind === 'int' ? `${formatNumber(lo)} 到 ${formatNumber(hi)} 之间的整数` : `${lo} 到 ${hi} 之间`
|
||||
}
|
||||
|
||||
/** 一项填的值有什么问题(类型、范围),没问题为 null。说法同服务端 contract.settings_problem */
|
||||
export function settingValueProblem(key: AnalysisSettingKey, raw: string): string | null {
|
||||
const text = raw.trim()
|
||||
const [kind, lo, hi] = ANALYSIS_SETTING_RANGE[key]
|
||||
const label = ANALYSIS_SETTING_LABEL[key]
|
||||
if (!text || !Number.isFinite(Number(text))) return `${label}要填数字`
|
||||
const n = Number(text)
|
||||
if (kind === 'int' && !/^-?\d+$/.test(text)) return `${label}要填整数`
|
||||
if (n < lo || n > hi) return `${label}要在 ${lo} 到 ${hi} 之间`
|
||||
return null
|
||||
}
|
||||
|
||||
export const ANALYSIS_TEXT = {
|
||||
/** 记录页工件清单里分析结论那一行的说明(工件没记算子时) */
|
||||
artifactHint: '分析结论:判定、方法、计算、输入和复算所需的一切',
|
||||
// ---- 分析卡:节点库、检查器、卡片 ----
|
||||
node: {
|
||||
description: '对上游查询节点的结果固定做几项确定性分析:变化拆解、波动基线、趋势判断、差异检验、可比性检查。判定由平台按设置的阈值算出,报告可引用、可查看出处',
|
||||
itemsHint: '每一项做一种分析:选分析方法、要分析的上游查询节点,再按方法填列名和期次。判定语由系统按平台的方法写好,报告引用它,不另写判断',
|
||||
overridesHint: '只对这张卡生效,写进工作流、随版本固定;未覆盖的项跟随「设置 → 偏好设置 → 分析」。Agent 的分析工具没有阈值覆盖',
|
||||
addItem: '添加分析项',
|
||||
removeItem: (id: string) => `删除分析项 ${id || '(未命名)'}`,
|
||||
id: '标识',
|
||||
idHint: (node: string, id: string) => `下游条件分支按 nodes.${node}.results.${id || '<标识>'}.verdict 取判定`,
|
||||
idInvalid: '标识只能用字母、数字和下划线,且不以数字开头',
|
||||
idDuplicate: (id: string) => `标识「${id}」与另一项重复,请换一个`,
|
||||
op: '分析方法',
|
||||
pickOp: '选择分析方法',
|
||||
mode: '模式',
|
||||
pickMode: '选择模式',
|
||||
unknownOp: (op: string) => `${op}:无法识别的分析方法,请从上方选项中选择`,
|
||||
unknownMode: (mode: string) => `${mode}:无法识别的模式,请从上方选项中选择`,
|
||||
from: '输入',
|
||||
pickFrom: '选择上游的查询节点',
|
||||
noUpstream: '上游没有查询节点。请先在本节点之前连接选择了数据库查询工具的「调用工具」节点,或「合并查询」节点',
|
||||
missingNode: (id: string) => `节点「${id}」不在上游或已删除,请重新选择`,
|
||||
twoQueries: '基期、本期是两份查询',
|
||||
baseQuery: '基期查询',
|
||||
targetQuery: '本期查询',
|
||||
hypothesis: '在验证什么',
|
||||
hypothesisHint: '一句话,只在证据面板显示,不进报告正文',
|
||||
hypothesisPlaceholder: '下降是不是集中在某个地区',
|
||||
params: '参数',
|
||||
listHint: '多列用顿号或逗号分隔',
|
||||
cellHint: '写成「节点 ID.r行号.列名」,行号从 0 数',
|
||||
headline: '总数核对',
|
||||
headlineHint: '给出基期、本期总数那两格,系统核对拆开后各段之和是否对得上',
|
||||
headlineBase: '基期总数那一格',
|
||||
headlineTarget: '本期总数那一格',
|
||||
parent: '下钻',
|
||||
parentHint: '这一项是前面某个变化拆解里某一段的拆解',
|
||||
parentOf: '上一层分析项',
|
||||
parentKey: '那一段的维度值',
|
||||
noParent: '不下钻',
|
||||
pairsHint: '每行一对,两个组之间用顿号或逗号分隔',
|
||||
/** 参数的叫法(tools/builtin/analysis.py 各参数模型里的字段,分析卡按同一份校验) */
|
||||
param: {
|
||||
by: '维度列', period: '期次列', base: '基期', target: '本期', measure: '度量列', numerator: '分子列', denominator: '分母列',
|
||||
product: '乘积列', factors: '因子列', label: '度量的叫法', basis: '比较方式', grain: '期次粒度', lag: '和往前第几期比',
|
||||
pairs: '只比这几对', reference: '对照组', mean: '均值列', sd: '标准差列', sum: '合计列', sumsq: '平方和列', n: '样本数列',
|
||||
value: '值列',
|
||||
} 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',
|
||||
} as Record<string, string>,
|
||||
paramHint: {
|
||||
label: '系统写判定语时用;不写数字、百分号和单位,留空则用列名或数据目录中的名称',
|
||||
target: '留空取最后一期',
|
||||
lag: '日缺省 7(和上周同一天比),周、月缺省 1;同比写 52(周)或 12(月)',
|
||||
reference: '其余各组各和它比;留空则各组与其余各组合计比',
|
||||
} as Record<string, string>,
|
||||
basis: { '': '和比较期比的变化率(缺省)', change: '和比较期比的变化率', level: '值本身(存量、比率用)' } as Record<string, string>,
|
||||
grain: { '': '按期次的写法推断', day: '日', week: '周', month: '月', quarter: '季度' } as Record<string, string>,
|
||||
/** differ 均值模式:给均值、标准差、样本数,或合计、平方和、样本数 */
|
||||
meanShape: { sd: '均值、标准差、样本数', sumsq: '合计、平方和、样本数' } as Record<string, string>,
|
||||
// ---- 阈值覆盖 ----
|
||||
addOverride: '添加阈值覆盖',
|
||||
pickOverride: '选择要覆盖的阈值',
|
||||
removeOverride: (label: string) => `删除阈值覆盖「${label}」`,
|
||||
noOverrides: '未覆盖:全部跟随设置',
|
||||
allOverridden: '全部阈值都已覆盖',
|
||||
// ---- 卡片 ----
|
||||
summaryEmpty: '未配置分析项',
|
||||
summaryNoOp: '未选择分析方法',
|
||||
summaryMore: (n: number) => `等 ${formatNumber(n)} 项`,
|
||||
},
|
||||
|
||||
// ---- 问数据时间线:Agent 的分析工具、分析卡的每一项 ----
|
||||
step: {
|
||||
/** 运行中的状态字(store/chat) */
|
||||
running: (label: string) => `正在执行分析:${label}…`,
|
||||
/** 一步的标题:「变化拆解(可加)· A1」;分析卡的一项:「变化拆解(可加)· where」 */
|
||||
title: (method: string, alias?: string | null) => (alias ? `${method} · ${alias}` : method),
|
||||
callError: '调用有误,没有记成结论',
|
||||
callErrorNext: '这次调用没有记成结论,Agent 会按这条说明改正参数后重新调用',
|
||||
refused: '没有做成',
|
||||
refusedNext: '算不了也是一条结论:报告里可以照实写出原因,不能据此下判断',
|
||||
hypothesis: 'Agent 写的假设',
|
||||
itemHypothesis: '在验证什么',
|
||||
args: '参数',
|
||||
phrase: '判定语',
|
||||
/** 分析卡那一项的标识 */
|
||||
item: (id: string) => `分析项「${id}」`,
|
||||
},
|
||||
|
||||
// ---- 时间线上的几条提醒(log 的 code:report_analysis_claims、analysis_refused、metric_comparability_skipped) ----
|
||||
log: {
|
||||
claims: (n: number | undefined, strict: boolean) => `报告${n ? `有 ${formatNumber(n)} 处` : '有'}分析说法未通过核对,`
|
||||
+ (strict ? '已计入出具缺口' : '已在报告中标注'),
|
||||
refused: (method: string, item?: string) => `${method}${item ? `(分析项「${item}」)` : ''}没有做成`,
|
||||
comparabilitySkipped: (metric: string) => `指标${metric ? `「${metric}」` : ''}用到的两次查询没有做成可比性检查`,
|
||||
comparabilitySkippedNext: '指标照常计算,两期能不能直接比请自行核对',
|
||||
},
|
||||
|
||||
// ---- 证据面板的分析一步(照导出页 report_export/runtime.js 的说法) ----
|
||||
evidence: {
|
||||
title: '分析结论',
|
||||
titleOf: (alias: string, method: string) => `${['分析结论', alias].filter(Boolean).join(' ')} · ${method || '—'}`,
|
||||
phrase: '判定语',
|
||||
criterion: '判定标准',
|
||||
subjects: '点名的段',
|
||||
direction: '方向',
|
||||
directionLabel: { up: '上升', down: '下降' } as Record<string, string>,
|
||||
caveats: '附带说明',
|
||||
reason: '算不了的原因',
|
||||
citedPart: '这一处引用的是',
|
||||
citedPhrase: '判定语',
|
||||
citedValue: (key: string) => `具名的数「${key}」`,
|
||||
citedCell: (row: number, column: string) => `结果表第 ${formatNumber(row + 1)} 行「${column}」`,
|
||||
who: '谁做的',
|
||||
origin: { card: '分析卡(模板定好的分析)', agent: 'Agent 现场做的分析', metric: '口径卡执行时自动做的可比性检查' } as Record<string, string>,
|
||||
hypothesis: 'Agent 写的假设',
|
||||
refused: '这次分析没有做成',
|
||||
renderOk: '与按结论渲染的结果一致',
|
||||
renderBad: '与按结论渲染的结果不一致',
|
||||
method: '方法',
|
||||
methodVersion: '方法与版本',
|
||||
params: '参数',
|
||||
settings: '实际用的阈值',
|
||||
probes: '现查结果',
|
||||
probeBasis: { live: '现查', profile: '剖析', observed: '取值观察' } as Record<string, string>,
|
||||
probeBound: (expr: string, value: string) => `按运行当天现算的界 ${expr} = ${value}`,
|
||||
probeEmpty: '这一列一个值都没有',
|
||||
probeRange: (min: string, max: string) => `${min} 至 ${max}`,
|
||||
calc: '计算',
|
||||
values: '具名的数',
|
||||
formulas: '关键数的代入式',
|
||||
resultTable: '结果表',
|
||||
resultRows: (shown: number, total: number) => `列出 ${formatNumber(shown)} 行,共 ${formatNumber(total)} 行`,
|
||||
input: '输入',
|
||||
inputOf: (ref: string) => `输入 ${ref}`.trim(),
|
||||
role: '角色',
|
||||
ref: '调用里写的名字',
|
||||
query: '查询',
|
||||
columnsUsed: '用到的列',
|
||||
rowsUsed: '用到的行',
|
||||
allRows: '全部行',
|
||||
rowsList: (rows: number[]) => rows.map((r) => `第 ${formatNumber(r + 1)} 行`).join('、'),
|
||||
headline: '总数那一格',
|
||||
headlineRatio: '整体比率那一格',
|
||||
cellAt: (row: number, column: string) => `第 ${formatNumber(row + 1)} 行「${column}」`,
|
||||
closure: '闭合核对',
|
||||
closureOk: (h: string, t: string) => `总数 ${h} 与各段之和 ${t} 闭合`,
|
||||
closureBad: (h: string, t: string) => `总数 ${h} 与各段之和 ${t} 对不上`,
|
||||
ratioClosureOk: (h: string, t: string) => `整体比率 ${h} 与各段分子之和 ÷ 分母之和 ${t} 闭合`,
|
||||
ratioClosureBad: (h: string, t: string) => `整体比率 ${h} 与各段分子之和 ÷ 分母之和 ${t} 对不上`,
|
||||
parent: '下钻自',
|
||||
gotoInput: (alias: string) => `查看输入 ${alias}`,
|
||||
inputOfAnalysis: (alias: string) => `分析结论 ${alias} 的输入`,
|
||||
/** 整句面板「挂的依据」里一份分析结论派生自谁(证据图的 derived_from 边) */
|
||||
derivedFrom: (aliases: string[]) => `派生自 ${aliases.join('、')}`,
|
||||
recompute: '复算',
|
||||
seal: '封存',
|
||||
artifact: '结论工件',
|
||||
inLedger: '封存范围内的台账记过这份分析结论',
|
||||
notInLedger: '封存范围内的台账里没有这份分析结论',
|
||||
viaCard: '记在口径卡的指标集里,随卡封存(不进台账)',
|
||||
chainPending: '正在加载判定、方法和输入…',
|
||||
// ---- 口径卡指标上的两期可比性 ----
|
||||
comparability: '两期可比性',
|
||||
comparabilityLabel: { comparable: '两期可比', conditional: '两期有条件可比', incomparable: '两期不可比' } as Record<string, string>,
|
||||
comparabilityOpen: '展开这份可比性结论(判定、方法、计算、输入、复算、封存)',
|
||||
comparabilityClose: '收起可比性结论',
|
||||
comparabilityReasons: '原因',
|
||||
comparabilityUnsealed: '这份可比性结论不在封存范围内,不能作为证据',
|
||||
comparabilityHash: '可比性结论与哈希不一致,疑似被修改',
|
||||
},
|
||||
|
||||
// ---- 正文:说法违规的标注、系统写的「分析范围」 ----
|
||||
claim: {
|
||||
/** 标注的种类(服务端 analysis_claims.CODES):给人看的短说法同审计的标签 */
|
||||
label: {
|
||||
analysis_claim_uncited: '判断词未挂分析结论',
|
||||
analysis_claim_mismatch: '判断与分析结论不符',
|
||||
causal_unsupported: '因果说法没有依据',
|
||||
} as Record<string, string>,
|
||||
tag: '说法待核',
|
||||
hint: '这句话里的判断词没有挂对应的分析结论、判断与所挂结论对不上,或原因没有依据:系统无法核对,点开看原因',
|
||||
panelTitle: '说法核对',
|
||||
analyses: '所挂的分析结论',
|
||||
noAnalyses: '这句没有挂分析结论',
|
||||
count: (n: number) => `${formatNumber(n)} 处说法待核`,
|
||||
},
|
||||
scope: {
|
||||
title: '分析范围',
|
||||
hint: '系统按这次的分析结论写的一段,不是写作者写的,随报告封存;编号可点开看出处',
|
||||
phenomena: '现象',
|
||||
decomposed: '拆过',
|
||||
excluded: '排除',
|
||||
refused: '算不了',
|
||||
notDecomposed: '没拆',
|
||||
tests: '检验',
|
||||
notDecomposedList: (dims: string[]) => `候选维度里没拆过的:${dims.join('、')}`,
|
||||
notDecomposedNone: '候选维度都拆过了',
|
||||
notDecomposedUnknown: '候选维度核对不了',
|
||||
drill: (parent: string) => `下钻自 ${parent}`,
|
||||
dims: (dims: string[]) => `按${dims.join('、')}`,
|
||||
/** 服务端 ScopeBlock.corrected:只做了一次(一次里比了多对的已按次数校正)/ 不止一次(几次之间没有校正) */
|
||||
testsText: (n: number, corrected: boolean | null | undefined) => `做了 ${formatNumber(n)} 次差异检验${corrected === true
|
||||
? '(一次里比了几对的已按次数校正)' : corrected === false ? ',几次检验之间没有按次数校正' : ''}`,
|
||||
open: (alias: string) => `查看分析结论 ${alias} 的出处`,
|
||||
},
|
||||
|
||||
// ---- 出具声明的三项:分析说法核对、指标的可比性、追不到原始数据的指标 ----
|
||||
issuance: {
|
||||
claimsTitle: (n: number, counted: boolean) => (counted
|
||||
? `${formatNumber(n)} 处分析说法未通过核对,已计入出具缺口`
|
||||
: `${formatNumber(n)} 处分析说法未通过核对(已标注,不影响出具档位)`),
|
||||
claimsStrictClean: '分析说法已按严格核对,没有未通过的',
|
||||
claimsNext: '判断要挂对应的分析结论并照判定写;原因要有知识库原话或运行输入作依据,否则写成待核实的推测',
|
||||
comparabilityTitle: '指标的两期可比性',
|
||||
comparabilityItem: (name: string, phrase: string) => `指标「${name}」:${phrase}`,
|
||||
untracedTitle: (counted: boolean) => (counted ? '报告引用的指标未追到原始数据(已计入出具缺口)' : '报告引用的指标未追到原始数据'),
|
||||
untracedItem: (name: string, stops: string[]) => `指标「${name}」${stops.length ? `:${stops.join(';')}` : ''}`,
|
||||
},
|
||||
|
||||
// ---- 设置「分析」一节 ----
|
||||
settings: {
|
||||
title: '分析',
|
||||
hint: '分析工具和分析卡判定用的阈值、次数上限。发起运行时快照进这次运行;Agent 改不了这些阈值,分析卡上可以写阈值覆盖',
|
||||
invalid: '分析的设置中有无效值,请修正后再保存',
|
||||
current: (value: string) => `当前 ${value}`,
|
||||
},
|
||||
|
||||
// ---- 运行对比 ----
|
||||
compare: {
|
||||
title: '分析卡',
|
||||
hint: '两次运行的分析卡按节点和分析项对齐,只列出两次的判定和判定语,不拆变化来源',
|
||||
change: {
|
||||
same: '判定一致', verdict: '判定变了', phrase: '判定一致,判定语里的数变了', added: '这次新增', removed: '这次没有',
|
||||
} as Record<string, string>,
|
||||
base: '基准运行',
|
||||
target: '这次运行',
|
||||
none: '—',
|
||||
item: (title: string, item: string) => `${title} · ${item}`,
|
||||
},
|
||||
}
|
||||
@@ -44,6 +44,10 @@ import {
|
||||
LedgerSection, ledgerChanged, ledgerDraftOf, ledgerErrors, ledgerLabels, ledgerPayload, type LedgerDraft,
|
||||
} from './settings/LedgerSettings'
|
||||
import { LEDGER_UI } from '../lib/termsLedger'
|
||||
import {
|
||||
AnalysisSection, analysisChanged, analysisDraftOf, analysisErrors, analysisLabels, analysisPayload, type AnalysisDraft,
|
||||
} from './settings/AnalysisSettings'
|
||||
import { ANALYSIS_TEXT } from '../lib/termsAnalysis'
|
||||
import { ACCESS_KEY_TEXT } from '../lib/termsApp'
|
||||
|
||||
// 提到模块级:tab 名同时是 URL 的最后一段,两处各写一份迟早对不上。
|
||||
@@ -697,6 +701,8 @@ function PrefsTab() {
|
||||
const [verifySaves, setVerifySaves] = useState(0)
|
||||
// 口径账本一组(自动按口径出具、每日上限、比对时限、升版后重算几组,pages/settings/LedgerSettings):草稿另放一份,共用保存条
|
||||
const [ledgerDraft, setLedgerDraft] = useState<LedgerDraft | null>(null)
|
||||
// 分析一组(判定用的阈值、次数上限,pages/settings/AnalysisSettings):草稿另放一份,共用保存条
|
||||
const [analysisDraft, setAnalysisDraft] = useState<AnalysisDraft | null>(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [savedFlash, setSavedFlash] = useState(0)
|
||||
const [saveError, setSaveError] = useState<unknown>(null)
|
||||
@@ -791,9 +797,14 @@ function PrefsTab() {
|
||||
const ledgerKeys = values?.ledger ? ledgerChanged(ledgerCur, ledgerSaved) : []
|
||||
const ledgerErrs = ledgerErrors(ledgerCur, ledgerSaved)
|
||||
const ledgerInvalid = Object.values(ledgerErrs).some(Boolean)
|
||||
const invalid = guardInvalid || judgeInvalid || verifyInvalid || ledgerInvalid || !!appsError
|
||||
const analysisSaved = analysisDraftOf(values?.analysis)
|
||||
const analysisCur = analysisDraft ?? analysisSaved
|
||||
const analysisKeys = values?.analysis ? analysisChanged(analysisCur, analysisSaved) : []
|
||||
const analysisErrs = analysisErrors(analysisCur, analysisSaved)
|
||||
const analysisInvalid = Object.values(analysisErrs).some(Boolean)
|
||||
const invalid = guardInvalid || judgeInvalid || verifyInvalid || ledgerInvalid || analysisInvalid || !!appsError
|
||||
const changed = (Object.keys(saved) as (keyof typeof saved)[]).filter((k) => cur[k] !== saved[k])
|
||||
const dirty = values ? changed.length + verifyKeys.length + ledgerKeys.length : 0
|
||||
const dirty = values ? changed.length + verifyKeys.length + ledgerKeys.length + analysisKeys.length : 0
|
||||
// 外壳唯一的 blocker 在地址(pathname)变化时问:切标签、导航、⌘K、⌥ 数字、后退都算
|
||||
useLeaveGuard(dirty > 0, () => confirmLeave(dirty))
|
||||
|
||||
@@ -818,6 +829,11 @@ function PrefsTab() {
|
||||
setFieldError(null)
|
||||
setLedgerDraft({ ...ledgerCur, ...patch })
|
||||
}
|
||||
const editAnalysis = (patch: Partial<AnalysisDraft>) => {
|
||||
setSaveError(null)
|
||||
setFieldError(null)
|
||||
setAnalysisDraft({ ...analysisCur, ...patch })
|
||||
}
|
||||
|
||||
/**
|
||||
* 署名只在这台浏览器里,先落本机:它不该跟着后端一起「没存上」。运行默认值
|
||||
@@ -853,6 +869,8 @@ function PrefsTab() {
|
||||
const verify = verifyKeys.length ? verifyPayload(verifyCur) : null
|
||||
// 口径账本一组同样整组写(LedgerSettings 的 ledgerPayload)
|
||||
const ledger = ledgerKeys.length ? ledgerPayload(ledgerCur) : null
|
||||
// 分析一组同样整组写(AnalysisSettings 的 analysisPayload)
|
||||
const analysis = analysisKeys.length ? analysisPayload(analysisCur) : null
|
||||
// 起草模型一组:两项一起写,空着的存 null(跟随助手的模型)
|
||||
const catalogDraft = draftChanged ? { provider: cur.draftProvider || null, model: cur.draftModel.trim() || null } : null
|
||||
// 应用一组同样整组写:别的键(以后加的)照原样带回去
|
||||
@@ -860,7 +878,7 @@ 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 || catalogDraft || apps) {
|
||||
if (runChanged || judge || verify || ledger || analysis || catalogDraft || apps) {
|
||||
const run = {
|
||||
...(values.run ?? {}),
|
||||
default_memory_scope: cur.scope,
|
||||
@@ -874,7 +892,7 @@ function PrefsTab() {
|
||||
}
|
||||
const out = await api.settings.put({
|
||||
...(runChanged ? { run } : {}), ...(judge ? { judge } : {}), ...(verify ? { verify } : {}),
|
||||
...(ledger ? { ledger } : {}),
|
||||
...(ledger ? { ledger } : {}), ...(analysis ? { analysis } : {}),
|
||||
...(catalogDraft ? { catalog_draft: catalogDraft } : {}), ...(apps ? { apps } : {}),
|
||||
})
|
||||
setValues((v) => ({
|
||||
@@ -883,6 +901,7 @@ function PrefsTab() {
|
||||
...(judge ? { judge: out?.judge ?? judge } : {}),
|
||||
...(verify ? { verify: out?.verify ?? verify } : {}),
|
||||
...(ledger ? { ledger: out?.ledger ?? ledger } : {}),
|
||||
...(analysis ? { analysis: out?.analysis ?? analysis } : {}),
|
||||
...(catalogDraft ? { catalog_draft: out?.catalog_draft ?? catalogDraft } : {}),
|
||||
...(apps ? { apps: out?.apps ?? apps } : {}),
|
||||
}))
|
||||
@@ -893,6 +912,7 @@ function PrefsTab() {
|
||||
setDraft(null)
|
||||
setVerifyDraft(null)
|
||||
setLedgerDraft(null)
|
||||
setAnalysisDraft(null)
|
||||
setSavedFlash(Date.now())
|
||||
} catch (e) {
|
||||
// 署名已经存上了:留在草稿里的只剩运行默认值,条上的计数跟着变少
|
||||
@@ -1209,6 +1229,8 @@ function PrefsTab() {
|
||||
|
||||
{values.ledger && <LedgerSection cur={ledgerCur} errors={ledgerErrs} onEdit={editLedger} />}
|
||||
|
||||
{values.analysis && <AnalysisSection cur={analysisCur} errors={analysisErrs} onEdit={editAnalysis} />}
|
||||
|
||||
{values.catalog_draft && (
|
||||
<DraftModelSection provider={cur.draftProvider} model={cur.draftModel} onEdit={edit}
|
||||
error={fieldError?.field === 'catalog_draft.provider' ? fieldError.message : undefined} />
|
||||
@@ -1273,7 +1295,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,
|
||||
})[k]).concat(verifyLabels(verifyKeys), ledgerLabels(ledgerKeys)).join('、')}
|
||||
})[k]).concat(verifyLabels(verifyKeys), ledgerLabels(ledgerKeys), analysisLabels(analysisKeys)).join('、')}
|
||||
</span>
|
||||
</span>
|
||||
{saveError != null && (
|
||||
@@ -1284,13 +1306,17 @@ function PrefsTab() {
|
||||
)}
|
||||
<span className="flex-1" />
|
||||
<button className="btn btn-sm btn-ghost" disabled={saving}
|
||||
onClick={() => { setDraft(null); setVerifyDraft(null); setLedgerDraft(null); setSaveError(null); setFieldError(null) }}>放弃</button>
|
||||
onClick={() => {
|
||||
setDraft(null); setVerifyDraft(null); setLedgerDraft(null); setAnalysisDraft(null); setSaveError(null)
|
||||
setFieldError(null)
|
||||
}}>放弃</button>
|
||||
<button className="btn btn-sm btn-primary" disabled={saving || invalid}
|
||||
title={guardInvalid ? '护栏设置中有无效值,请修正后再保存'
|
||||
: judgeInvalid ? '证据裁判的上限有无效值,请修正后再保存'
|
||||
: appsError ? APP_SETTING_TEXT.onDemandLimitInvalid
|
||||
: verifyInvalid ? VERIFY_SETTING_TEXT.section.saveInvalid
|
||||
: ledgerInvalid ? LEDGER_UI.settings.saveInvalid : undefined}
|
||||
: ledgerInvalid ? LEDGER_UI.settings.saveInvalid
|
||||
: analysisInvalid ? ANALYSIS_TEXT.settings.invalid : undefined}
|
||||
onClick={() => void save()}>
|
||||
{saving ? <Spinner size={11} /> : <Check size={12} aria-hidden />} 保存设置
|
||||
</button>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { RUN_COMPARE_TEXT } from '../../lib/terms'
|
||||
import type { RunComparison } from '../../types'
|
||||
import { useCandidates, useComparison, useDefaultBase, useRunRecord } from './compare/data'
|
||||
import { comparePath, type CompareVia } from './compare/entry'
|
||||
import { Analyses } from './compare/Analyses'
|
||||
import { Metrics } from './compare/Metrics'
|
||||
import { compareErrorKind, isGone } from './compare/model'
|
||||
import { CompareError, type CompareErrorContext } from './compare/parts'
|
||||
@@ -124,6 +125,7 @@ function Comparison({ data }: { data: RunComparison }) {
|
||||
<Summary summary={data.summary} filter={filter} onFilter={setFilter} />
|
||||
<NotesSection notes={data.notes ?? []} />
|
||||
<Metrics metrics={data.metrics ?? []} filter={filter} onClearFilter={() => setFilter(null)} />
|
||||
<Analyses analyses={data.analyses} />
|
||||
<Queries queries={data.queries ?? []} />
|
||||
<TemplateSection template={data.template} />
|
||||
</>
|
||||
|
||||
@@ -13,8 +13,9 @@ import {
|
||||
} from '../../lib/evidence'
|
||||
import { formatNumber } from '../../lib/format'
|
||||
import { EVIDENCE_AUDIT_TEXT as T, UPGRADE_TEXT } from '../../lib/terms'
|
||||
import { ANALYSIS_TEXT } from '../../lib/termsAnalysis'
|
||||
import { IssuanceBanner } from '../../run/AssistantStream'
|
||||
import { EvidenceDoc, type EvidenceDocHandle } from '../../run/EvidenceDoc'
|
||||
import { EvidenceDoc, claimMarksOf, type EvidenceDocHandle } from '../../run/EvidenceDoc'
|
||||
import { EvidenceGuessView } from '../../run/EvidenceGuess'
|
||||
import { ReportInquiry, inquiryOpen, locateIn, useInquiryAccess } from '../../run/Inquiry'
|
||||
import { Markdown, inlineStyles } from '../../run/Markdown'
|
||||
@@ -119,7 +120,8 @@ export function EvidencePane({ run, output, labelOf, refreshKey }: {
|
||||
// 只收有状态的片段,和 EvidenceDoc 能打开的是同一批:违规行指着的文字片段(粗体、链接里的可疑名字)、
|
||||
// 结构片段(列表序号 100. 里的数字)在正文里没有能点的地方,画成按钮就是点了没反应。
|
||||
// 结论句的行(证据相矛盾、证据不足……)打开的是这一句的句末徽标(`报告:claim:句子`):句子有判定(封存的、
|
||||
// 证据图里封存后追加的)才有徽标
|
||||
// 证据图里封存后追加的)才有徽标。分析说法违规(判断词未挂分析结论……)落在的那段文字没有状态,正文里也点得开
|
||||
//(claimMarksOf,和 EvidenceDoc 画波浪线的是同一批)
|
||||
const openable = useMemo(() => {
|
||||
const keys = new Set<string>()
|
||||
for (const r of reports) {
|
||||
@@ -129,6 +131,7 @@ export function EvidencePane({ run, output, labelOf, refreshKey }: {
|
||||
for (const seg of u.segments ?? []) if (segmentState(seg)) keys.add(`${r.node_id}:${seg.id}`)
|
||||
if (verdictState(unitVerdict(u, late))) keys.add(`${r.node_id}:claim:${u.id}`)
|
||||
}
|
||||
if (doc) for (const id of claimMarksOf(doc).keys()) keys.add(`${r.node_id}:${id}`)
|
||||
}
|
||||
return keys
|
||||
}, [reports, docOf, graph])
|
||||
@@ -619,7 +622,8 @@ function AuditLine({ row, current, openable, multiReport, labelOf, onOpen, onFoc
|
||||
const meta = EVIDENCE_STATE[row.state]
|
||||
const text = plain(row.text)
|
||||
const sentence = plain(row.sentence)
|
||||
const label = `${text},${meta.label}${row.source ? `:${row.source}` : ''}`
|
||||
const claimIssue = row.kind === 'violation' && row.issue ? ANALYSIS_TEXT.claim.label[row.issue] : undefined
|
||||
const label = `${text},${claimIssue ?? meta.label}${row.source ? `:${row.source}` : ''}`
|
||||
const common = {
|
||||
tabIndex: current ? 0 : -1, 'data-audit-focus': row.key, onFocus, onKeyDown: onKey,
|
||||
className: clsx('mono max-w-full truncate rounded-sm text-left outline-none focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-[color:var(--accent)]',
|
||||
@@ -638,8 +642,11 @@ function AuditLine({ row, current, openable, multiReport, labelOf, onOpen, onFoc
|
||||
<span {...common} className={clsx(common.className, 'block')} title={text}>{text}</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-2 py-1.5" style={{ color: meta.color }}>
|
||||
{meta.glyph && <span aria-hidden className="mr-0.5">{meta.glyph}</span>}{meta.label}
|
||||
<td className="px-2 py-1.5" style={{ color: meta.color }} data-audit-issue={row.issue ?? ''}>
|
||||
{/* 说法违规(判断词未挂分析结论……):写它自己的叫法,不写「无证据」——说的不是数字没有出处 */}
|
||||
{claimIssue
|
||||
? <>{meta.glyph && <span aria-hidden className="mr-0.5">{meta.glyph}</span>}{claimIssue}</>
|
||||
: <>{meta.glyph && <span aria-hidden className="mr-0.5">{meta.glyph}</span>}{meta.label}</>}
|
||||
</td>
|
||||
<td className="px-2 py-1.5">
|
||||
<span className="block text-dim [overflow-wrap:anywhere]" data-audit-source="">{row.source || '—'}</span>
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useId } from 'react'
|
||||
import { ANALYSIS_TEXT, analysisMethodLabel } from '../../../lib/termsAnalysis'
|
||||
import type { RunCompareAnalysis, RunCompareAnalysisSide } from '../../../types'
|
||||
import { Block } from './parts'
|
||||
|
||||
const C = ANALYSIS_TEXT.compare
|
||||
|
||||
/**
|
||||
* 分析卡区(engine/compare._analyses):两次运行的分析卡按节点和分析项对齐,一项一行——算子的叫法、两次的判定语、变了没有。
|
||||
* 只列出两次的判定,不拆变化来源(方案 W1-c 的最小可用)。判定语、判定都是服务端给的原样;变化(same / verdict / phrase /
|
||||
* added / removed)是服务端比出来的,界面只按它挑颜色。两次运行都没有分析卡(老服务端没有这一项)时不画这一区
|
||||
*/
|
||||
export function Analyses({ analyses }: { analyses?: RunCompareAnalysis[] }) {
|
||||
const id = useId()
|
||||
if (!analyses?.length) return null
|
||||
return (
|
||||
<Block id={`${id}-analyses`} title={C.title} count={String(analyses.length)} hint={C.hint} attr={{ 'data-compare-analyses': '' }}>
|
||||
<ul className="divide-y">
|
||||
{analyses.map((a) => <AnalysisItem key={`${a.node_id}:${a.item}`} a={a} />)}
|
||||
</ul>
|
||||
</Block>
|
||||
)
|
||||
}
|
||||
|
||||
function Side({ label, side }: { label: string; side: RunCompareAnalysisSide | null }) {
|
||||
return (
|
||||
<div className="min-w-0" data-compare-analysis-side={label}>
|
||||
<div className="text-2xs text-faint">{label}</div>
|
||||
<div className="text-xs [overflow-wrap:anywhere]" style={side?.status === 'refused' ? { color: 'var(--st-waiting)' } : undefined}>
|
||||
{side ? (side.phrase || C.none) : C.none}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AnalysisItem({ a }: { a: RunCompareAnalysis }) {
|
||||
const changed = a.change !== 'same'
|
||||
const color = a.change === 'verdict' ? 'var(--warn)' : a.change === 'added' ? 'var(--accent)' : 'var(--text-dim)'
|
||||
return (
|
||||
<li className="py-2.5 first:pt-0 last:pb-0" data-compare-analysis={`${a.node_id}:${a.item}`} data-change={a.change}>
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<span className="min-w-0 text-xs font-medium [overflow-wrap:anywhere]" title={a.node_id}>{C.item(a.title || a.node_id, a.item)}</span>
|
||||
<span className="text-2xs text-faint">{analysisMethodLabel(a.op, a.mode)}</span>
|
||||
<span className="chip shrink-0" data-compare-analysis-change="" style={{
|
||||
color, borderColor: `color-mix(in srgb, ${color} 40%, transparent)`,
|
||||
background: changed && a.change === 'verdict' ? `color-mix(in srgb, ${color} 12%, transparent)` : undefined,
|
||||
}}>
|
||||
{C.change[a.change] ?? a.change}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-1.5 grid grid-cols-2 gap-3 max-sm:grid-cols-1">
|
||||
<Side label={C.base} side={a.base} />
|
||||
<Side label={C.target} side={a.target} />
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
|
||||
import type { Approval, Run, RunStatus, RunUsage } from '../../types'
|
||||
import { ANALYSIS_TEXT, analysisMethodLabel } from '../../lib/termsAnalysis'
|
||||
import {
|
||||
RUN_STATUS_ORDER, STATUS, resolveStatus, serverStatusOf, type StatusCode,
|
||||
} from '../../lib/status'
|
||||
@@ -341,6 +342,7 @@ export const ARTIFACT_KIND_LABEL: Record<string, string> = {
|
||||
challenge: '反方审稿记录',
|
||||
inquiry_answer: INQUIRY_TEXT.artifactKind,
|
||||
metric_input: RUN_ARTIFACTS_TEXT.kindMetricInput,
|
||||
analysis_result: ANALYSIS_TEXT.evidence.title,
|
||||
}
|
||||
export const artifactKindLabel = (kind: string): string => ARTIFACT_KIND_LABEL[kind] ?? kind
|
||||
|
||||
@@ -355,6 +357,10 @@ export function artifactDescription(kind: string, meta?: Record<string, any> | n
|
||||
case 'metric_set': return meta?.caliber
|
||||
? `口径卡「${meta.caliber}」${meta.version ?? ''}` : '口径卡的指标、算式和输入'
|
||||
case 'report_doc': return '报告:逐段的片段和每个数字的出处'
|
||||
// 一份分析结论(工件行的 meta 里有 {op, status}):哪一种分析,没有做成的照实写
|
||||
case 'analysis_result': return meta?.op
|
||||
? `${analysisMethodLabel(meta.op)}${meta.status === 'refused' ? `(${ANALYSIS_TEXT.step.refused})` : ''}`
|
||||
: ANALYSIS_TEXT.artifactHint
|
||||
// 查库时冻结的表结构(工件行的 meta 里有 {source, tables: 表数量}):报告里的表名、字段名按它核对
|
||||
case 'schema_snapshot': return meta?.source
|
||||
? `表结构:数据源「${meta.source}」${typeof meta.tables === 'number' ? ` · ${meta.tables} 张表` : ''}` : '查询时保存的表结构'
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { Field, SectionBar } from '../../components/ui'
|
||||
import {
|
||||
ANALYSIS_SETTING_GROUPS, ANALYSIS_SETTING_KEYS, ANALYSIS_SETTING_LABEL, ANALYSIS_TEXT, settingRangeText, settingValueProblem,
|
||||
type AnalysisSettingKey,
|
||||
} from '../../lib/termsAnalysis'
|
||||
|
||||
/*
|
||||
* 设置页「偏好设置」里「分析」一节(服务端 api/settings.py 的 analysis 一组,docs/design/analysis-round/01-算子与判定.md §10):
|
||||
* 判定用的阈值(「主要来源」的占比、「超出常规波动」的倍数……)、Agent 每次执行最多分析几次、最多下钻几层、列出前几段。
|
||||
*
|
||||
* 照 LedgerSettings.tsx 的写法:草稿由 PrefsTab 持有、和其余设置共用一条保存条(这一节只画、只报改动),存的时候整组写
|
||||
* analysis——服务端对没给的项回落到缺省,只发改过的那一项会把别的项冲回缺省。字段名、范围都照服务端 analysis/contract.py
|
||||
* (LABELS、RANGES,lib/termsAnalysis 一字不差地抄着,check-manage 逐项比对),422 的报错写的也是这些叫法。两两之间的大小
|
||||
* (「明显超出」要大于「超出常规波动」、最多用几期不小于至少几期、「集中」不小于「主要来源」)交给服务端核,报错照原话显示。
|
||||
*/
|
||||
|
||||
export type AnalysisDraft = Record<AnalysisSettingKey, string>
|
||||
|
||||
const isRecord = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
|
||||
|
||||
/** GET /settings 的 analysis 一组(服务端给的是生效的样子,没存过的补了缺省)→ 草稿 */
|
||||
export function analysisDraftOf(group: unknown): AnalysisDraft {
|
||||
const g = isRecord(group) ? group : {}
|
||||
return Object.fromEntries(ANALYSIS_SETTING_KEYS.map((k) => {
|
||||
const v = g[k]
|
||||
return [k, typeof v === 'number' && Number.isFinite(v) ? String(v) : '']
|
||||
})) as AnalysisDraft
|
||||
}
|
||||
|
||||
/** 改过的项:字不同、而且不是同一个数(服务端把 2 存成 2.0,写「2.0」不算改) */
|
||||
export function analysisChanged(cur: AnalysisDraft, saved: AnalysisDraft): AnalysisSettingKey[] {
|
||||
const same = (a: string, b: string) => a.trim() === b.trim()
|
||||
|| (a.trim() !== '' && b.trim() !== '' && Number.isFinite(Number(a)) && Number(a) === Number(b))
|
||||
return ANALYSIS_SETTING_KEYS.filter((k) => !same(cur[k], saved[k]))
|
||||
}
|
||||
|
||||
/** 保存条上这几项的叫法:和字段名、服务端报错同一套 */
|
||||
export const analysisLabels = (keys: AnalysisSettingKey[]): string[] => keys.map((k) => ANALYSIS_SETTING_LABEL[k])
|
||||
|
||||
/** 各项的问题(类型、范围)。只校验改过的:存着的值不合规不该挡住别的设置保存 */
|
||||
export function analysisErrors(cur: AnalysisDraft, saved: AnalysisDraft): Partial<Record<AnalysisSettingKey, string>> {
|
||||
const out: Partial<Record<AnalysisSettingKey, string>> = {}
|
||||
for (const k of analysisChanged(cur, saved)) {
|
||||
const problem = settingValueProblem(k, cur[k])
|
||||
if (problem) out[k] = problem
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 草稿 → 存进去的整组 analysis */
|
||||
export function analysisPayload(cur: AnalysisDraft): Record<string, number> {
|
||||
return Object.fromEntries(ANALYSIS_SETTING_KEYS.map((k) => [k, Number(cur[k].trim())]))
|
||||
}
|
||||
|
||||
const id = (k: AnalysisSettingKey) => `pref-analysis-${k.replace(/_/g, '-')}`
|
||||
|
||||
export function AnalysisSection({ cur, errors, onEdit }: {
|
||||
cur: AnalysisDraft
|
||||
errors: Partial<Record<AnalysisSettingKey, string>>
|
||||
onEdit: (patch: Partial<AnalysisDraft>) => void
|
||||
}) {
|
||||
return (
|
||||
<section data-analysis-settings="">
|
||||
<SectionBar title={ANALYSIS_TEXT.settings.title} hint={ANALYSIS_TEXT.settings.hint} />
|
||||
<div className="space-y-4">
|
||||
{ANALYSIS_SETTING_GROUPS.map((group) => (
|
||||
<div key={group.title} data-analysis-settings-group={group.title}>
|
||||
<div className="mb-1.5 text-2xs font-medium text-dim">{group.title}</div>
|
||||
<div className="grid grid-cols-2 gap-3 max-sm:grid-cols-1">
|
||||
{group.keys.map((k) => (
|
||||
<Field key={k} label={ANALYSIS_SETTING_LABEL[k]} htmlFor={id(k)} error={errors[k]} hint={settingRangeText(k)}>
|
||||
{(p) => (
|
||||
<input {...p} className="field tnum max-w-40" inputMode="decimal" value={cur[k]} data-analysis-setting={k}
|
||||
onChange={(e) => onEdit({ [k]: e.target.value } as Partial<AnalysisDraft>)} />
|
||||
)}
|
||||
</Field>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
} from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import {
|
||||
AlertCircle, AlertTriangle, ArrowDown, Brain, ChevronRight, CircleCheck, CircleDot, CornerDownRight,
|
||||
AlertCircle, AlertTriangle, ArrowDown, Brain, ChartColumnStacked, ChevronRight, CircleCheck, CircleDot, CornerDownRight,
|
||||
Database, Download, ExternalLink, FileCode, FileDown, GitBranch, Hand, Info, ListChecks, Play, Settings2,
|
||||
Scale, ShieldCheck, Sparkles, Table2, Terminal, UserX, Users, Wrench, XCircle,
|
||||
} from 'lucide-react'
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
nodeTypeLabel,
|
||||
} from '../lib/terms'
|
||||
import { SqlCheckList } from './SqlChecks'
|
||||
import { ANALYSIS_TEXT } from '../lib/termsAnalysis'
|
||||
import {
|
||||
ISSUANCE_HINT, childrenByExec, compactSteps, parseQueryResult, progressOf, splitIssuanceGaps, spread, teamVerdictOf,
|
||||
type Exec, type FixKind, type ResultTable as Table, type Step, type StepKind, type TeamMemberEx,
|
||||
@@ -28,7 +29,9 @@ import {
|
||||
import { CODE_COLUMN, CopyChip, LEADING_ZERO, Markdown, type MarkSpec } from './Markdown'
|
||||
import { ClaimTally, EvidenceField, type EvidenceDocHandle } from './EvidenceDoc'
|
||||
import { EVIDENCE_STATE, claimProblems, docTally, evidenceFields, issuanceMarks, type EvidenceTally } from '../lib/evidence'
|
||||
import type { EvidenceDocData, IssuanceSqlCheck } from '../types'
|
||||
import type {
|
||||
EvidenceDocData, IssuanceAnalysisClaims, IssuanceComparability, IssuanceSqlCheck, IssuanceUntraced,
|
||||
} from '../types'
|
||||
import { useRunClock } from './useRunClock'
|
||||
import { CatalogPatchCard } from './CatalogPatchCard'
|
||||
import type { CatalogPatch } from './catalogPatch'
|
||||
@@ -131,7 +134,7 @@ export interface StreamTurn {
|
||||
}
|
||||
|
||||
const ICONS: Record<StepKind, typeof Wrench> = {
|
||||
node: CircleDot, think: Brain, llm: Sparkles, query: Database, schema: Table2,
|
||||
node: CircleDot, think: Brain, llm: Sparkles, query: Database, schema: Table2, analysis: ChartColumnStacked,
|
||||
tool: Wrench, code: Terminal, branch: GitBranch, human: Hand,
|
||||
issuance: FileCode, note: CircleDot, error: XCircle, lifecycle: CircleCheck,
|
||||
}
|
||||
@@ -1011,6 +1014,11 @@ const REVEAL_TRIES = 4
|
||||
const notable = (s: Step): boolean =>
|
||||
s.status === 'failed' || s.status === 'running' || s.status === 'waiting' || s.status === 'rejected'
|
||||
|| s.level === 'error' || s.level === 'warn'
|
||||
/**
|
||||
* 折起来时也留着的:上面那些,加上分析的那几行——判定语就是这一步查出来的结论(变化来自哪里、算不算异常),收进「前面的 N 条」
|
||||
* 就看不到 Agent 是怎么下的判断。它们不算出了问题(分轮的警示标记只看 notable)
|
||||
*/
|
||||
const kept = (s: Step): boolean => notable(s) || s.kind === 'analysis'
|
||||
|
||||
function StepList({ steps, depth, turnMs, fold = false }: {
|
||||
steps: Step[]; depth: number; turnMs?: number
|
||||
@@ -1025,7 +1033,7 @@ function StepList({ steps, depth, turnMs, fold = false }: {
|
||||
// 问题的一律留着。反过来只画前 20 条的话,长运行跑到后面,正在跑的那一步反而
|
||||
// 被收进「展开其余」里看不见
|
||||
const keep = fold && rows.length > 6 ? 3 : rows.length > LIST_CAP ? LIST_HEAD : 0
|
||||
const shown = !all && keep ? rows.filter((s, i) => notable(s) || i >= rows.length - keep) : rows
|
||||
const shown = !all && keep ? rows.filter((s, i) => kept(s) || i >= rows.length - keep) : rows
|
||||
const hidden = rows.length - shown.length
|
||||
// 画布上点名要看的节点正好收在前面那一截里:先展开,上面的定位下一帧就找得到它
|
||||
useLayoutEffect(() => {
|
||||
@@ -1086,7 +1094,8 @@ function StepLine({ step, depth, turnMs }: { step: Step; depth: number; turnMs?:
|
||||
const [open, setOpen] = useState(false)
|
||||
const Icon = ICONS[step.kind] ?? CircleDot
|
||||
const result = step.result
|
||||
const expandable = !!(step.detail || result || step.raw || step.artifact || step.checks?.length)
|
||||
const expandable = !!(step.detail || result || step.raw || step.artifact || step.checks?.length
|
||||
|| step.analysis?.phrase || step.analysis?.hypothesis)
|
||||
const table = result ? parseQueryResult(result) : null
|
||||
const status = step.status ?? 'done'
|
||||
// 失败的节点:收着的时候就说为什么(和轮次顶上的报错同一份 lib/explain),展开再看原因、
|
||||
@@ -1136,6 +1145,7 @@ function StepLine({ step, depth, turnMs }: { step: Step; depth: number; turnMs?:
|
||||
data-node-id={step.nodeId}
|
||||
data-step-status={failed ? 'failed' : status}
|
||||
data-step-code={step.code}
|
||||
data-step-kind={step.kind}
|
||||
aria-busy={running || undefined}
|
||||
>
|
||||
<button
|
||||
@@ -1539,8 +1549,26 @@ function StepDetail({ step, table, explained }: {
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{step.analysis && (step.analysis.phrase || step.analysis.hypothesis) && (
|
||||
// 分析:判定语(服务端写好的一句,收着时副标题可能被截断)、Agent 写的假设(只在这里和证据面板显示,不是结论)
|
||||
<dl className="space-y-0.5 text-2xs leading-relaxed" data-step-analysis={step.analysis.alias ?? step.analysis.item ?? ''}>
|
||||
{step.analysis.phrase && (
|
||||
<div className="flex gap-1.5">
|
||||
<dt className="shrink-0 text-faint">{ANALYSIS_TEXT.step.phrase}</dt>
|
||||
<dd className="min-w-0 text-fg [overflow-wrap:anywhere]" data-step-analysis-phrase="">{step.analysis.phrase}</dd>
|
||||
</div>
|
||||
)}
|
||||
{step.analysis.hypothesis && (
|
||||
<div className="flex gap-1.5">
|
||||
<dt className="shrink-0 text-faint">{step.analysis.item ? ANALYSIS_TEXT.step.itemHypothesis : ANALYSIS_TEXT.step.hypothesis}</dt>
|
||||
<dd className="min-w-0 text-dim [overflow-wrap:anywhere]" data-step-analysis-hypothesis="">{step.analysis.hypothesis}</dd>
|
||||
</div>
|
||||
)}
|
||||
</dl>
|
||||
)}
|
||||
{detail && (
|
||||
<div className="group/detail relative">
|
||||
{step.kind === 'analysis' && <div className="mb-0.5 text-2xs text-dim">{ANALYSIS_TEXT.step.args}</div>}
|
||||
{step.kind === 'query' && (
|
||||
<div className="mb-0.5 flex items-center gap-2 text-2xs text-dim">
|
||||
<span className={step.merge ? undefined : 'mono'}>{step.merge ? MERGE_TEXT.sql : 'SQL'}</span>
|
||||
@@ -2362,6 +2390,75 @@ export function IssuanceSqlChecks({ tier, checks }: { tier: string; checks: Issu
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 出具声明里分析能力一轮的三项(engine/nodes/io.py),都只在有的时候带:
|
||||
* - analysis_claims:分析说法核对,strict 或有违规时有——几处、记没记缺口(strict 记缺口、check 只标注)、前几处的原话
|
||||
* - comparability:报告引用的指标里两期有条件可比、不可比的,判定语和原因(不可比的另记了缺口,在其余缺口里)
|
||||
* - untraced:报告引用的指标里输入没追到原始数据的,追到哪个节点为止(受管级别的正式运行记缺口)
|
||||
* 说法都是服务端写好的(违规的原话、判定语、原因),这里只排版;颜色跟着档位,同 IssuanceSqlChecks
|
||||
*/
|
||||
export function IssuanceAnalysis({ tier, claims, comparability, untraced }: {
|
||||
tier: string; claims?: IssuanceAnalysisClaims | null; comparability?: IssuanceComparability[]; untraced?: IssuanceUntraced | null
|
||||
}) {
|
||||
const I = ANALYSIS_TEXT.issuance
|
||||
const tone = tier === 'withheld' ? 'var(--st-failed)' : 'var(--st-waiting)'
|
||||
const violations = (claims?.violations ?? []).filter((v) => v && typeof v === 'object')
|
||||
const count = typeof claims?.count === 'number' ? claims.count : violations.length
|
||||
const metrics = (untraced?.metrics ?? []).filter((m) => m && typeof m === 'object')
|
||||
if (!(claims && (count > 0 || claims.counted)) && !comparability?.length && !metrics.length) return null
|
||||
const box = { borderColor: `color-mix(in srgb, ${tone} 45%, var(--border))`, background: `color-mix(in srgb, ${tone} 6%, transparent)` }
|
||||
return (
|
||||
<>
|
||||
{claims && (count > 0 || claims.counted) && (
|
||||
<div className="mt-1.5 rounded border px-2 py-1.5 text-2xs leading-relaxed" style={box}
|
||||
data-issuance-analysis-claims={claims.counted ? 'counted' : 'flagged'}>
|
||||
<div className="flex items-center gap-1 font-medium" style={{ color: tone }}>
|
||||
<AlertTriangle size={11} aria-hidden /> {count > 0 ? I.claimsTitle(count, !!claims.counted) : I.claimsStrictClean}
|
||||
</div>
|
||||
{violations.length > 0 && (
|
||||
<ul className="mt-0.5 space-y-0.5">
|
||||
{violations.map((v, i) => (
|
||||
<li key={`${v.code}:${v.segment ?? i}`} className="[overflow-wrap:anywhere]" data-issuance-analysis-claim={v.code}>
|
||||
{v.text && <span className="font-medium text-fg">「{v.text}」</span>}
|
||||
<span className="text-dim">({ANALYSIS_TEXT.claim.label[v.code] ?? v.code})</span>
|
||||
{v.message && <span className="text-fg">:{v.message}</span>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{count > 0 && <div className="mt-0.5 text-dim">{I.claimsNext}</div>}
|
||||
</div>
|
||||
)}
|
||||
{!!comparability?.length && (
|
||||
<div className="mt-1.5 text-2xs leading-relaxed" style={{ color: tone }} data-issuance-comparability={comparability.length}>
|
||||
<div className="font-medium">{I.comparabilityTitle}</div>
|
||||
<ul className="mt-0.5 space-y-0.5 pl-2 [overflow-wrap:anywhere]">
|
||||
{comparability.map((c, i) => (
|
||||
<li key={`${c.metric ?? ''}:${i}`} data-issuance-comparability-item={c.verdict ?? ''}>
|
||||
· {I.comparabilityItem(c.name || c.metric || '', c.phrase || ANALYSIS_TEXT.evidence.comparabilityLabel[c.verdict ?? ''] || '')}
|
||||
{!!c.reasons?.length && <span className="text-dim">({c.reasons.join(';')})</span>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{metrics.length > 0 && (
|
||||
<div className="mt-1.5 text-2xs leading-relaxed" style={{ color: tone }} data-issuance-untraced={untraced?.counted ? 'counted' : 'flagged'}>
|
||||
<div className="font-medium">{I.untracedTitle(!!untraced?.counted)}</div>
|
||||
<ul className="mt-0.5 space-y-0.5 pl-2 [overflow-wrap:anywhere]">
|
||||
{metrics.map((m, i) => (
|
||||
<li key={`${m.metric ?? ''}:${i}`}>
|
||||
· {I.untracedItem(m.name || m.metric || '', (m.stops ?? []).map((st) => EVIDENCE_TEXT.originStop(st.path ?? '',
|
||||
EVIDENCE_TEXT.originNode(st.label || st.node_id || '', st.type ? nodeTypeLabel(st.type) : ''))))}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 出具横幅里双盲复算、反方审稿报上来的一组缺口:failed「核查未通过」、unfinished「核查未完成」。排在「校验未全部完成」
|
||||
* 上面,样子和它一样(同一种提醒色、小标题加圆点列表),一条都没有时不画
|
||||
@@ -2495,6 +2592,9 @@ export function IssuanceBanner({ issuance, runClass, evidence }: {
|
||||
)}
|
||||
|
||||
{!!sqlChecks.length && <IssuanceSqlChecks tier={tier} checks={sqlChecks} />}
|
||||
<IssuanceAnalysis tier={tier} claims={issuance?.analysis_claims}
|
||||
comparability={Array.isArray(issuance?.comparability) ? issuance.comparability : undefined}
|
||||
untraced={issuance?.untraced} />
|
||||
<IssuanceGaps kind="failed" title={DUAL_CHECK_TEXT.verifyGaps.failed} gaps={verifyFailed} />
|
||||
<IssuanceGaps kind="unfinished" title={DUAL_CHECK_TEXT.verifyGaps.unfinished} gaps={verifyUnfinished} />
|
||||
{!!gaps.length && (
|
||||
|
||||
@@ -0,0 +1,472 @@
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import { ChevronRight } from 'lucide-react'
|
||||
import { evidenceValue as valueText } from '../lib/evidence'
|
||||
import { NONE, shortId } from '../lib/format'
|
||||
import { EVIDENCE_TEXT } from '../lib/terms'
|
||||
import { ANALYSIS_TEXT } from '../lib/termsAnalysis'
|
||||
import type {
|
||||
AnalysisProbe, AnalysisScope, AnalysisScopeItem, EvidenceAnalysisStep, EvidenceComparability, EvidenceSeal, EvidenceViolation,
|
||||
} from '../types'
|
||||
import { ResultTable } from './AssistantStream'
|
||||
import { useEvidenceHost } from './evidenceHost'
|
||||
|
||||
/*
|
||||
* 证据面板、正文里分析结论的几块(docs/design/analysis-round/00-总方案.md §3.3、§3.6):
|
||||
*
|
||||
* - 分析结论的出处链:判定(判定语、判定标准、点名的段、附带说明、算不了的原因、这一处引用的是哪一项、谁做的、Agent 写的假设)
|
||||
* → 方法(方法与版本、参数、实际用的阈值、现查结果)→ 计算(关键数的代入式、具名的数、结果表)→ 输入(每份一步:角色、落到哪个
|
||||
* Q、用到的列和行、总数那一格和闭合核对、下钻的上一层)→ 复算 → 封存。步骤、说法照导出页(backend/app/report_export/runtime.js
|
||||
* 的 analysisPart…analysisSealPart):同一条链两处说法一样。输入快照的查询步骤由证据面板照常画(QueryPart),这里只画分析的几步
|
||||
* - 口径卡指标上的两期可比性:判定、判定语、原因,展开看那份可比性结论的整条链
|
||||
* - 正文里的说法违规:判断词未挂分析结论、判断与分析结论不符、因果说法没有依据,原话照服务端
|
||||
* - 报告末尾系统写的「分析范围」:现象、拆过、排除、算不了、没拆、检验,编号点得开
|
||||
*
|
||||
* 界面层不放逻辑:判定语、判定标准、原因、附带说明、代入式、闭合核对的数、复算的那一句都是服务端写好的字,这里只排版。
|
||||
*/
|
||||
|
||||
const E = ANALYSIS_TEXT.evidence
|
||||
|
||||
/** 面板里的一节:小标题 + 内容(同 EvidencePanel 的 Part) */
|
||||
function Part({ title, children, ...rest }: { title: ReactNode; children: ReactNode } & Record<`data-${string}`, string>) {
|
||||
return (
|
||||
<div {...rest}>
|
||||
<div className="mb-1 text-2xs font-medium text-faint">{title}</div>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 一组「名称 · 值」 */
|
||||
function Rows({ rows }: { rows: ([string, ReactNode] | null | false | undefined)[] }) {
|
||||
const shown = rows.filter((r): r is [string, ReactNode] => !!r)
|
||||
if (!shown.length) return null
|
||||
return (
|
||||
<dl className="space-y-1">
|
||||
{shown.map(([k, v]) => (
|
||||
<div key={k} className="flex gap-2">
|
||||
<dt className="w-20 shrink-0 text-2xs text-faint">{k}</dt>
|
||||
<dd className="min-w-0 flex-1 [overflow-wrap:anywhere]">{v}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
)
|
||||
}
|
||||
|
||||
/** 逐项复核出来的问题:正常时不说,出问题才醒目(同 EvidencePanel 的 IntegrityList) */
|
||||
function Problems({ code, items }: { code: string; items: string[] }) {
|
||||
if (!items.length) return null
|
||||
return (
|
||||
<ul className="mt-1.5 space-y-0.5 rounded border px-2 py-1" data-ev-integrity={code}
|
||||
style={{ color: 'var(--st-failed)', borderColor: 'var(--st-failed)', background: 'var(--st-failed-soft)' }}>
|
||||
{items.map((t) => <li key={t}>{t}</li>)}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
const subjectsText = (subjects: unknown): string => (Array.isArray(subjects)
|
||||
? subjects.map((s) => (Array.isArray(s) ? s.map((x) => valueText(x)).join(' · ') : valueText(s))).join('、') : '')
|
||||
|
||||
/** 现查结果的一条:有 expr 的是按运行当天现算的界,其余是一列的实际范围;现查到的范围最早、最晚都空是这一列一个值都没有 */
|
||||
function probeText(p: AnalysisProbe): string {
|
||||
const how = `(${E.probeBasis[String(p.basis ?? '')] ?? p.basis ?? NONE}${p.at ? ` · ${p.at}` : ''})`
|
||||
if (typeof p.expr === 'string' && p.expr) return `${E.probeBound(p.expr, p.value || NONE)}${how}`
|
||||
const where = `${p.table || NONE}.${p.column || NONE}`
|
||||
const empty = p.basis === 'live' && !p.min && !p.max
|
||||
return `${where}:${empty ? E.probeEmpty : E.probeRange(p.min || NONE, p.max || NONE)}${how}`
|
||||
}
|
||||
|
||||
function NodeName({ id, label }: { id?: string | null; label?: string | null }) {
|
||||
const host = useEvidenceHost()
|
||||
if (!id) return null
|
||||
const known = host.nodeLabel?.(id)
|
||||
if (host.onNode && known !== undefined) {
|
||||
return (
|
||||
<button type="button" className="chip max-w-full truncate transition-colors hover:bg-hover" data-ev-node={id}
|
||||
title={`在画布上选中并对准「${known || id}」`} onClick={() => host.onNode!(id)}>
|
||||
{known || label || id}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
return <span data-ev-node={id}>{label || id}</span>
|
||||
}
|
||||
|
||||
/** 判定:判定语和它的依据,谁做的,复算、封存的结论(细节在后面几步) */
|
||||
function JudgedPart({ step, recompute, seal, overall }: {
|
||||
step: EvidenceAnalysisStep; recompute?: EvidenceAnalysisStep; seal?: EvidenceAnalysisStep; overall?: EvidenceSeal
|
||||
}) {
|
||||
const verdict = step.verdict && typeof step.verdict === 'object' ? step.verdict : null
|
||||
const cited = step.cited ?? {}
|
||||
const citedText = cited.what === 'value' ? E.citedValue(String(cited.key ?? ''))
|
||||
: cited.what === 'cell' ? E.citedCell(Number(cited.row) || 0, String(cited.column ?? '')) : E.citedPhrase
|
||||
const refused = step.status === 'refused'
|
||||
const trusted = !!overall?.sealed && overall.ok !== false
|
||||
const problems = [
|
||||
step.eid_ok === false ? EVIDENCE_TEXT.integrity.eid : '',
|
||||
step.render_ok === false && step.hash_ok !== false ? E.renderBad : '',
|
||||
step.note ?? '',
|
||||
trusted && seal && seal.sealed === false && seal.note ? seal.note : '',
|
||||
].filter(Boolean)
|
||||
const recomputeTone = recompute?.status === 'same' ? 'ok' : recompute?.status === 'different' ? 'bad' : 'none'
|
||||
return (
|
||||
<Part title={E.titleOf(step.alias ?? '', step.method_label ?? '')} data-ev-analysis={step.alias ?? ''}>
|
||||
{step.phrase && (
|
||||
<p className="font-medium" data-ev-analysis-phrase="">{step.phrase}</p>
|
||||
)}
|
||||
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-2xs text-dim">
|
||||
{refused && (
|
||||
<span className="chip" style={{ color: 'var(--st-waiting)', borderColor: 'var(--st-waiting)' }} data-ev-analysis-refused="">
|
||||
{E.refused}
|
||||
</span>
|
||||
)}
|
||||
<span data-ev-analysis-origin={step.origin ?? ''}>{E.origin[String(step.origin ?? '')] ?? NONE}</span>
|
||||
<NodeName id={step.node_id} label={step.label} />
|
||||
{step.artifact && <span className="mono text-faint" title={`${E.artifact} ${step.artifact}`}>{E.artifact} {shortId(step.artifact)}</span>}
|
||||
</div>
|
||||
<Problems code="analysis" items={problems} />
|
||||
<div className="mt-2">
|
||||
<Rows rows={[
|
||||
step.criterion ? [E.criterion, step.criterion] : null,
|
||||
verdict?.subjects?.length ? [E.subjects, subjectsText(verdict.subjects)] : null,
|
||||
verdict?.direction ? [E.direction, E.directionLabel[verdict.direction] ?? verdict.direction] : null,
|
||||
refused && step.reason ? [E.reason, <span key="r" style={{ color: 'var(--st-waiting)' }}>{step.reason}</span>] : null,
|
||||
[E.citedPart, <span key="c" data-ev-analysis-cited={cited.what ?? 'phrase'}>{citedText}</span>],
|
||||
step.caveats?.length ? [E.caveats, (
|
||||
<ul key="cv" className="space-y-0.5" data-ev-analysis-caveats="">
|
||||
{step.caveats.map((c, i) => <li key={`${c.code ?? ''}-${i}`}>{c.text}</li>)}
|
||||
</ul>
|
||||
)] : null,
|
||||
step.hypothesis ? [E.hypothesis, (
|
||||
<span key="h" data-ev-analysis-hypothesis="">
|
||||
{step.hypothesis}
|
||||
{step.hypothesis_note && <span className="mt-0.5 block text-2xs text-faint">{step.hypothesis_note}</span>}
|
||||
</span>
|
||||
)] : null,
|
||||
recompute ? [E.recompute, (
|
||||
<span key="rc" data-ev-analysis-recompute={recomputeTone}
|
||||
style={{ color: recomputeTone === 'ok' ? 'var(--st-done)' : recomputeTone === 'bad' ? 'var(--st-failed)' : 'var(--st-cancelled)' }}>
|
||||
{recompute.text || NONE}
|
||||
</span>
|
||||
)] : null,
|
||||
seal ? [E.seal, (
|
||||
<span key="s" data-ev-analysis-seal={seal.via === 'metric_set' ? 'card' : seal.ledger ? 'ledger' : 'none'}>
|
||||
{seal.via === 'metric_set' ? E.viaCard : seal.ledger ? E.inLedger : E.notInLedger}
|
||||
</span>
|
||||
)] : null,
|
||||
]} />
|
||||
</div>
|
||||
</Part>
|
||||
)
|
||||
}
|
||||
|
||||
/** 方法:方法与版本、参数(规范化后的)、实际用的阈值(只列这个算子用到的)、现查结果 */
|
||||
function MethodPart({ step }: { step: EvidenceAnalysisStep }) {
|
||||
const params = step.params && typeof step.params === 'object' && Object.keys(step.params).length ? step.params : null
|
||||
return (
|
||||
<Part title={E.method} data-ev-analysis-method="">
|
||||
<Rows rows={[
|
||||
[E.methodVersion, <span key="m">{step.method_label || NONE} · <span className="mono">{step.method || NONE}</span></span>],
|
||||
step.settings?.length ? [E.settings, (
|
||||
<ul key="s" className="space-y-0.5" data-ev-analysis-settings="">
|
||||
{step.settings.map((x) => (
|
||||
<li key={x.key}>{x.label || x.key} <span className="mono tnum">{valueText(x.value)}</span></li>
|
||||
))}
|
||||
</ul>
|
||||
)] : null,
|
||||
step.probes?.length ? [E.probes, (
|
||||
<ul key="p" className="space-y-0.5" data-ev-analysis-probes="">
|
||||
{step.probes.map((p, i) => <li key={i}>{probeText(p)}</li>)}
|
||||
</ul>
|
||||
)] : null,
|
||||
]} />
|
||||
{params && (
|
||||
<div className="mt-1.5">
|
||||
<div className="mb-0.5 text-2xs text-faint">{E.params}</div>
|
||||
<pre className="mono max-h-36 overflow-auto whitespace-pre-wrap rounded bg-bg px-1.5 py-1 text-2xs leading-relaxed text-dim [overflow-wrap:anywhere]"
|
||||
data-ev-analysis-params="">
|
||||
{JSON.stringify(params, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</Part>
|
||||
)
|
||||
}
|
||||
|
||||
/** 计算:关键数的代入式、具名的数(被引用的那个描出来)、结果表(被引用的那一格高亮,遮罩的列写「已遮罩」) */
|
||||
function CalcPart({ step }: { step: EvidenceAnalysisStep }) {
|
||||
const table = step.table && Array.isArray(step.table.columns) && Array.isArray(step.table.rows) ? step.table : null
|
||||
const labels = table?.labels ?? {}
|
||||
const heads = table ? table.columns.map((c) => labels[c] || c) : []
|
||||
const index = table ? (Array.isArray(table.row_index) ? table.row_index : table.rows.map((_, i) => i)) : []
|
||||
const masked = new Set(table?.masked ?? [])
|
||||
// 高亮的格按快照行号给:换成窗口里的下标、列 id 换成表头上的叫法
|
||||
const cells = (table?.highlight?.cells ?? [])
|
||||
.map(([r, c]) => [index.indexOf(r), labels[c] || c] as [number, string]).filter(([i]) => i >= 0)
|
||||
return (
|
||||
<Part title={E.calc} data-ev-analysis-calc="">
|
||||
{!!step.formulas?.length && (
|
||||
<div className="mb-1.5">
|
||||
<div className="mb-0.5 text-2xs text-faint">{E.formulas}</div>
|
||||
<pre className="mono whitespace-pre-wrap rounded bg-bg px-1.5 py-1 text-2xs leading-relaxed [overflow-wrap:anywhere]"
|
||||
data-ev-analysis-formulas="">
|
||||
{step.formulas.map((f) => f.text ?? '').filter(Boolean).join('\n')}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
{!!step.values?.length && (
|
||||
<div className="mb-1.5">
|
||||
<div className="mb-0.5 text-2xs text-faint">{E.values}</div>
|
||||
<ul className="flex flex-wrap gap-1" data-ev-analysis-values="">
|
||||
{step.values.map((v) => (
|
||||
<li key={v.key} className="chip mono" data-ev-analysis-value={v.key}
|
||||
{...(v.cited ? { 'data-ev-cited': '' } : {})}
|
||||
style={v.cited ? { color: 'var(--st-done)', borderColor: 'var(--st-done)' } : undefined}>
|
||||
{v.key} <span className="tnum">{v.rendered ?? NONE}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{table && (
|
||||
<div data-ev-analysis-table="">
|
||||
<div className="mb-0.5 text-2xs text-faint">
|
||||
{E.resultTable}({E.resultRows(table.rows.length, table.total_rows ?? table.rows.length)})
|
||||
</div>
|
||||
<ResultTable table={{
|
||||
columns: heads,
|
||||
rows: table.rows.map((r) => (Array.isArray(r) ? r.map((v, j) => (masked.has(table.columns[j]) ? EVIDENCE_TEXT.masked : v)) : [])),
|
||||
truncated: false,
|
||||
}} highlight={{ rows: [], cols: [], cells }} masked={[...masked].map((c) => labels[c] || c)} />
|
||||
{table.window_truncated && <p className="mt-0.5 text-2xs text-faint">{EVIDENCE_TEXT.windowCut(table.rows.length)}</p>}
|
||||
</div>
|
||||
)}
|
||||
</Part>
|
||||
)
|
||||
}
|
||||
|
||||
/** 输入的一份:角色、调用里写的名字、落到哪个 Q(点一下跳到那个查询步骤)、用到的列和行、总数那一格和闭合核对、下钻的上一层 */
|
||||
function InputPart({ step, onQuery, trusted }: { step: EvidenceAnalysisStep; onQuery?: (alias: string) => void; trusted: boolean }) {
|
||||
const closure = step.closure && typeof step.closure === 'object' ? step.closure : null
|
||||
const ratio = closure?.mode === 'ratio'
|
||||
const closed = closure ? (ratio ? (closure.closed ? E.ratioClosureOk : E.ratioClosureBad)
|
||||
: (closure.closed ? E.closureOk : E.closureBad))(closure.headline ?? NONE, closure.total ?? NONE) : null
|
||||
const rows = Array.isArray(step.rows) ? E.rowsList(step.rows.filter((r): r is number => typeof r === 'number'))
|
||||
: step.rows === 'all' ? E.allRows : null
|
||||
const where = step.query || step.alias || ''
|
||||
const parent = step.role === 'parent'
|
||||
return (
|
||||
<Part title={where ? E.inputOf(where) : E.input} data-ev-analysis-input={step.role ?? ''}>
|
||||
<Rows rows={[
|
||||
[E.role, step.role_label || step.role || NONE],
|
||||
step.ref ? [E.ref, <code key="r" className="mono">{step.ref}</code>] : null,
|
||||
step.query ? [E.query, onQuery
|
||||
? <button key="q" type="button" className="chip mono hover:bg-hover" data-ev-goto-query={step.query}
|
||||
onClick={() => onQuery(step.query!)}>{EVIDENCE_TEXT.gotoQuery(step.query)}</button>
|
||||
: <span key="q" className="mono">{step.query}</span>] : null,
|
||||
parent && step.alias ? [E.parent, <span key="p" className="mono">{step.alias}</span>] : null,
|
||||
step.columns?.length ? [E.columnsUsed, <span key="c" className="mono">{step.columns.join('、')}</span>] : null,
|
||||
rows ? [E.rowsUsed, rows] : null,
|
||||
'value' in step && !parent ? [ratio ? E.headlineRatio : E.headline, (
|
||||
<span key="v" className="tnum">
|
||||
{step.column != null && typeof step.row === 'number' ? `${E.cellAt(step.row, step.column)} = ` : ''}{valueText(step.value)}
|
||||
</span>
|
||||
)] : null,
|
||||
closure && closed ? [E.closure, (
|
||||
<span key="cl" data-ev-analysis-closure={closure.closed ? 'closed' : 'open'}
|
||||
style={{ color: closure.closed ? 'var(--st-done)' : 'var(--st-waiting)' }}>{closed}</span>
|
||||
)] : null,
|
||||
step.phrase ? [E.phrase, step.phrase] : null,
|
||||
]} />
|
||||
<Problems code="sealed" items={trusted && step.sealed === false ? [EVIDENCE_TEXT.integrity.sealed] : []} />
|
||||
</Part>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 分析结论的出处链(查询步骤之外的那几步)。pending、failed 是证据链还没回来、回不来时的说法(同指标一节);onQuery 点输入里的
|
||||
* Q 跳到下面的查询步骤(证据面板给)
|
||||
*/
|
||||
export function AnalysisChain({ chain, seal, pending, failed, onQuery }: {
|
||||
chain: EvidenceAnalysisStep[]
|
||||
seal?: EvidenceSeal
|
||||
pending?: boolean
|
||||
failed?: string
|
||||
onQuery?: (alias: string) => void
|
||||
}) {
|
||||
const judged = chain.find((s) => s.step === 'analysis')
|
||||
if (!judged) {
|
||||
return (
|
||||
<Part title={E.title} data-ev-analysis="">
|
||||
<p className="text-2xs text-faint" data-ev-chain={pending ? 'loading' : 'missing'}>
|
||||
{pending ? E.chainPending : failed || EVIDENCE_TEXT.chainMissing}
|
||||
</p>
|
||||
</Part>
|
||||
)
|
||||
}
|
||||
const trusted = !!seal?.sealed && seal.ok !== false
|
||||
const method = chain.find((s) => s.step === 'analysis_method')
|
||||
const calc = chain.find((s) => s.step === 'analysis_calc')
|
||||
const inputs = chain.filter((s) => s.step === 'analysis_input')
|
||||
return (
|
||||
<>
|
||||
<JudgedPart step={judged} recompute={chain.find((s) => s.step === 'analysis_recompute')}
|
||||
seal={chain.find((s) => s.step === 'analysis_seal')} overall={seal} />
|
||||
{method && <MethodPart step={method} />}
|
||||
{calc && <CalcPart step={calc} />}
|
||||
{inputs.map((s, i) => <InputPart key={`${s.ref ?? ''}-${s.role ?? ''}-${i}`} step={s} onQuery={onQuery} trusted={trusted} />)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 指标步骤上的两期可比性(口径卡跨两份同形查询算的环比、同比,执行时自动做的检查):判定、判定语、原因一句一个,展开看那份
|
||||
* 可比性结论的整条链(两份输入快照的查询步骤指标链里已经有了,不再给)。不进台账、随口径卡的指标集封存
|
||||
*/
|
||||
export function ComparabilityRow({ comparability, seal }: { comparability: EvidenceComparability; seal?: EvidenceSeal }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const verdict = String(comparability.verdict ?? '')
|
||||
const tone = verdict === 'comparable' ? 'var(--st-done)' : verdict === 'incomparable' ? 'var(--st-failed)' : 'var(--st-waiting)'
|
||||
const steps = Array.isArray(comparability.steps) ? comparability.steps.filter((s) => s && typeof s === 'object') : []
|
||||
const trusted = !!seal?.sealed && seal.ok !== false
|
||||
const problems = [
|
||||
comparability.hash_ok === false ? E.comparabilityHash : '',
|
||||
trusted && comparability.sealed === false && comparability.hash_ok !== false ? E.comparabilityUnsealed : '',
|
||||
].filter(Boolean)
|
||||
return (
|
||||
<div data-ev-comparability={verdict}>
|
||||
<dt className="text-2xs text-faint">{E.comparability}</dt>
|
||||
<dd>
|
||||
<div className="flex flex-wrap items-baseline gap-x-1.5">
|
||||
<span className="chip" style={{ color: tone, borderColor: tone }}>{E.comparabilityLabel[verdict] ?? (verdict || NONE)}</span>
|
||||
{comparability.phrase && <span data-ev-comparability-phrase="">{comparability.phrase}</span>}
|
||||
</div>
|
||||
{!!comparability.reasons?.length && (
|
||||
<ul className="mt-0.5 space-y-0.5 text-2xs text-dim" data-ev-comparability-reasons="">
|
||||
{comparability.reasons.map((r) => <li key={r}>· {r}</li>)}
|
||||
</ul>
|
||||
)}
|
||||
<Problems code="comparability" items={problems} />
|
||||
{steps.length > 0 && (
|
||||
<button type="button" className="btn btn-xs btn-ghost -ml-1 mt-0.5" aria-expanded={open}
|
||||
data-ev-comparability-toggle="" onClick={() => setOpen((v) => !v)}>
|
||||
<ChevronRight size={11} aria-hidden style={{ transform: open ? 'rotate(90deg)' : 'none' }} />
|
||||
{open ? E.comparabilityClose : E.comparabilityOpen}
|
||||
</button>
|
||||
)}
|
||||
{open && (
|
||||
<div className="mt-1 space-y-3 border-l-2 pl-2" data-ev-comparability-chain="">
|
||||
<AnalysisChain chain={steps} seal={seal} />
|
||||
</div>
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 说法违规的代码(服务端 engine/analysis_claims.CODES) */
|
||||
export const CLAIM_CODES = new Set(Object.keys(ANALYSIS_TEXT.claim.label))
|
||||
export const isClaimViolation = (v: Pick<EvidenceViolation, 'code'>): boolean => CLAIM_CODES.has(v.code)
|
||||
|
||||
/** 证据面板:落在这个片段上的说法违规,一处一条:种类、服务端的原话、所挂的分析结论(点一下看那份结论) */
|
||||
export function ClaimFlags({ violations, onAnalysis }: {
|
||||
violations: EvidenceViolation[]
|
||||
onAnalysis?: (alias: string) => void
|
||||
}) {
|
||||
if (!violations.length) return null
|
||||
return (
|
||||
<Part title={ANALYSIS_TEXT.claim.panelTitle} data-ev-claim-flags={String(violations.length)}>
|
||||
<ul className="space-y-1.5">
|
||||
{violations.map((v, i) => (
|
||||
<li key={`${v.code}-${i}`} className="rounded border px-2 py-1" data-ev-claim-flag={v.code}
|
||||
style={{ borderColor: 'color-mix(in srgb, var(--st-waiting) 45%, var(--border))' }}>
|
||||
<div className="flex flex-wrap items-baseline gap-x-1.5">
|
||||
{v.text && <span className="font-semibold">「{v.text}」</span>}
|
||||
<span className="chip" style={{ color: 'var(--st-waiting)' }}>{ANALYSIS_TEXT.claim.label[v.code] ?? v.code}</span>
|
||||
</div>
|
||||
{v.message && <p className="mt-0.5 text-dim">{v.message}</p>}
|
||||
<div className="mt-0.5 flex flex-wrap items-center gap-1 text-2xs text-faint">
|
||||
{v.analyses?.length ? (
|
||||
<>
|
||||
<span>{ANALYSIS_TEXT.claim.analyses}</span>
|
||||
{v.analyses.map((a) => (onAnalysis
|
||||
? <button key={a} type="button" className="chip mono hover:bg-hover" data-ev-claim-analysis={a}
|
||||
onClick={() => onAnalysis(a)}>{a}</button>
|
||||
: <span key={a} className="mono">{a}</span>))}
|
||||
</>
|
||||
) : v.code !== 'causal_unsupported' && <span>{ANALYSIS_TEXT.claim.noAnalyses}</span>}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Part>
|
||||
)
|
||||
}
|
||||
|
||||
/** 分析范围的一条:编号(点得开)、判定语;拆过的写按哪些维度、下钻自谁;算不了的判定语里已经写了原因 */
|
||||
function ScopeLine({ item, onOpen }: { item: AnalysisScopeItem; onOpen?: (alias: string) => void }) {
|
||||
const alias = item.alias ?? ''
|
||||
const extra = [item.dims?.length ? ANALYSIS_TEXT.scope.dims(item.dims) : '', item.parent ? ANALYSIS_TEXT.scope.drill(item.parent) : '']
|
||||
.filter(Boolean).join(' · ')
|
||||
return (
|
||||
<li className="flex items-baseline gap-1.5" data-ev-scope-item={alias}>
|
||||
{alias && (onOpen
|
||||
? <button type="button" className="chip mono shrink-0 hover:bg-hover" data-seg={`scope:${alias}`}
|
||||
aria-label={ANALYSIS_TEXT.scope.open(alias)} onClick={() => onOpen(alias)}>{alias}</button>
|
||||
: <span className="chip mono shrink-0">{alias}</span>)}
|
||||
<span className="min-w-0 [overflow-wrap:anywhere]">
|
||||
{item.phrase || NONE}
|
||||
{extra && <span className="ml-1 text-2xs text-faint">({extra})</span>}
|
||||
</span>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 报告末尾系统写的「分析范围」(文档的 analysis_scope,contract.ScopeBlock):不是写作者写的,随报告封存。几组都照服务端分好的
|
||||
* 排:现象(可比性、基线、趋势)、拆过(按下钻链,上一层在前)、排除(分散、差异不足以下结论)、算不了、没拆(候选维度里没拆过的;
|
||||
* 核对不了时照实说)、检验(做了几次差异检验、校正过没有)。编号点得开(onOpen 打开那份结论的出处链)
|
||||
*/
|
||||
export function ScopeSection({ scope, onOpen }: { scope: AnalysisScope; onOpen?: (alias: string) => void }) {
|
||||
const S = ANALYSIS_TEXT.scope
|
||||
const groups: [string, string, AnalysisScopeItem[]][] = [
|
||||
['phenomena', S.phenomena, scope.phenomena ?? []],
|
||||
['decomposed', S.decomposed, scope.decomposed ?? []],
|
||||
['excluded', S.excluded, scope.excluded ?? []],
|
||||
['refused', S.refused, scope.refused ?? []],
|
||||
]
|
||||
const shown = groups.filter(([, , items]) => items.length)
|
||||
const notDecomposed = scope.not_decomposed === null || scope.not_decomposed === undefined
|
||||
? (scope.note || (scope.not_decomposed === null ? S.notDecomposedUnknown : ''))
|
||||
: scope.not_decomposed.length ? S.notDecomposedList(scope.not_decomposed) : S.notDecomposedNone
|
||||
const tests = typeof scope.tests === 'number' && scope.tests > 0 ? S.testsText(scope.tests, scope.corrected) : ''
|
||||
if (!shown.length && !notDecomposed && !tests) return null
|
||||
return (
|
||||
<section className="mt-3 rounded-lg border px-3 py-2" data-ev-scope="" aria-label={S.title}>
|
||||
<div className="flex flex-wrap items-baseline gap-x-2">
|
||||
<h4 className="text-xs font-semibold">{S.title}</h4>
|
||||
<span className="text-2xs text-faint">{S.hint}</span>
|
||||
</div>
|
||||
<dl className="mt-1.5 space-y-1.5 text-xs">
|
||||
{shown.map(([key, title, items]) => (
|
||||
<div key={key} data-ev-scope-group={key}>
|
||||
<dt className="text-2xs font-medium text-faint">{title}</dt>
|
||||
<dd><ul className="mt-0.5 space-y-0.5">{items.map((it, i) => <ScopeLine key={`${it.alias ?? ''}-${i}`} item={it} onOpen={onOpen} />)}</ul></dd>
|
||||
</div>
|
||||
))}
|
||||
{notDecomposed && (
|
||||
<div data-ev-scope-group="not_decomposed">
|
||||
<dt className="text-2xs font-medium text-faint">{S.notDecomposed}</dt>
|
||||
<dd className="mt-0.5" data-ev-scope-not-decomposed={scope.not_decomposed == null ? 'unknown' : String(scope.not_decomposed.length)}>
|
||||
{notDecomposed}
|
||||
</dd>
|
||||
</div>
|
||||
)}
|
||||
{tests && (
|
||||
<div data-ev-scope-group="tests">
|
||||
<dt className="text-2xs font-medium text-faint">{S.tests}</dt>
|
||||
<dd className="mt-0.5">{tests}</dd>
|
||||
</div>
|
||||
)}
|
||||
</dl>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import {
|
||||
Fragment, forwardRef, memo, useCallback, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo,
|
||||
useRef, useState, type CSSProperties, type FocusEvent as ReactFocusEvent,
|
||||
type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent, type RefObject,
|
||||
type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent, type ReactNode, type RefObject,
|
||||
} from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import {
|
||||
@@ -10,10 +10,12 @@ import {
|
||||
import clsx from 'clsx'
|
||||
import { rovingTarget } from '../components/ui'
|
||||
import {
|
||||
EVIDENCE_STATE, alertTier, claimCounts, claimLabel, claimProblems, conflicting, docTally, segmentKind, segmentLabel,
|
||||
segmentState, tallySummary, unitText, isJudged, limitOf, unitVerdict, verdictMissing, verdictState, withVerdicts,
|
||||
EVIDENCE_STATE, alertTier, claimCounts, claimLabel, claimProblems, codePointIndex, conflicting, docTally, segmentKind,
|
||||
segmentLabel, segmentState, tallySummary, unitText, isJudged, limitOf, unitVerdict, verdictMissing, verdictState, withVerdicts,
|
||||
type EvidenceStateCode, type EvidenceTally as Tally,
|
||||
} from '../lib/evidence'
|
||||
import { ANALYSIS_TEXT } from '../lib/termsAnalysis'
|
||||
import { ScopeSection, isClaimViolation } from './EvidenceAnalysis'
|
||||
import { formatNumber } from '../lib/format'
|
||||
import {
|
||||
CHALLENGE_TEXT, EVIDENCE_STATE_LABEL, EVIDENCE_TEXT, INQUIRY_TEXT, JUDGE_TEXT, LEDGER_TEXT, claimTally, evidenceTally,
|
||||
@@ -55,6 +57,11 @@ import { BlockView, Markdown, StyledSlice, inlineStyles, numericColumns, type In
|
||||
* 相关口径的数不加标记,只在证据面板的「口径」一步里说。标签按运行另取(GET /runs/{id}/ledger,store/ledger 按退避
|
||||
* 等比对出结果),正式运行、没有运行的文档不取。
|
||||
*
|
||||
* 分析能力一轮:判定语([[a:A1]])是一个系统渲染的片段,和数字一样画「有出处」、点得开(证据面板的分析一步)。说法违规
|
||||
* (判断词未挂分析结论、判断与分析结论不符、因果说法没有依据,文档的 violations 按 unit / segment / span 给)标在正文上:判断词
|
||||
* 那几个字画琥珀色波浪线,那段文字是一个可点的片段,句末挂「说法待核」,n / N 跳得到;点开看服务端的原话和所挂的结论。正文
|
||||
* 后面是系统写的「分析范围」(文档的 analysis_scope),编号点得开。
|
||||
*
|
||||
* 长报告:事件都挂在容器上(片段只带 data-seg),块用 memo,外加
|
||||
* content-visibility: auto;超过 TEXT_CAP 的部分先折叠,跳转到折叠里的片段时自动展开。
|
||||
*/
|
||||
@@ -125,8 +132,47 @@ interface Model {
|
||||
grid: Map<string, string>
|
||||
}
|
||||
|
||||
/**
|
||||
* 说法违规落在哪段文字上:片段 id → 违规的种类、判断词在这段文字里的位置(UTF-16 下标,[起, 止))。服务端的 span 是全文的码点
|
||||
* 位置,片段自己的 span 也是,相减后按码点换成下标;没给 span 的整段都算。只认说法违规(isClaimViolation)、能落到一段非结构
|
||||
* 片段上的
|
||||
*/
|
||||
type ClaimMarks = Map<string, { codes: string[]; ranges: [number, number][] }>
|
||||
|
||||
export function claimMarksOf(doc: EvidenceDocData): ClaimMarks {
|
||||
const out: ClaimMarks = new Map()
|
||||
const list = (doc.violations ?? []).filter((v) => isClaimViolation(v) && v.segment)
|
||||
if (!list.length) return out
|
||||
const segs = new Map<string, EvidenceSegment>()
|
||||
for (const b of doc.blocks ?? []) for (const u of b.units ?? []) for (const sg of u.segments ?? []) segs.set(sg.id, sg)
|
||||
for (const v of list) {
|
||||
const seg = segs.get(v.segment!)
|
||||
if (!seg || seg.kind === 'structural' || segmentState(seg)) continue
|
||||
const mark = out.get(seg.id) ?? { codes: [], ranges: [] }
|
||||
if (!mark.codes.includes(v.code)) mark.codes.push(v.code)
|
||||
const at = codePointIndex(seg.text)
|
||||
const from = v.span && seg.span ? v.span[0] - seg.span[0] : 0
|
||||
const to = v.span && seg.span ? v.span[1] - seg.span[0] : Infinity
|
||||
const a = Math.max(0, Math.min(seg.text.length, at(Math.max(0, from))))
|
||||
const z = Math.max(a, Math.min(seg.text.length, to === Infinity ? seg.text.length : at(Math.max(0, to))))
|
||||
if (z > a) mark.ranges.push([a, z])
|
||||
out.set(seg.id, mark)
|
||||
}
|
||||
for (const m of out.values()) {
|
||||
// 有重叠的合在一起;一处位置都没认出来的整段画线
|
||||
m.ranges.sort((x, y) => x[0] - y[0])
|
||||
m.ranges = m.ranges.reduce<[number, number][]>((acc, r) => {
|
||||
const last = acc[acc.length - 1]
|
||||
if (last && r[0] <= last[1]) last[1] = Math.max(last[1], r[1])
|
||||
else acc.push([...r])
|
||||
return acc
|
||||
}, [])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function buildModel(blocks: EvidenceBlock[], overlay?: Record<string, EvidenceVerdict>, ask = false,
|
||||
marks?: Record<string, string>): Model {
|
||||
marks?: Record<string, string>, claims?: ClaimMarks): Model {
|
||||
const order: string[] = []
|
||||
const index = new Map<string, number>()
|
||||
const seg = new Map<string, { seg: EvidenceSegment; unit: EvidenceUnit; block: number }>()
|
||||
@@ -146,13 +192,15 @@ function buildModel(blocks: EvidenceBlock[], overlay?: Record<string, EvidenceVe
|
||||
for (const s of unit.segments ?? []) {
|
||||
if (s.kind !== 'structural') total += s.text.length
|
||||
const state = segmentState(s)
|
||||
if (!state) continue
|
||||
// 说法违规落在的那段文字:本身没有状态,也进键盘顺序,算第 1 轮的问题(n / N 跳得到)
|
||||
const claimed = !state && !!claims?.has(s.id)
|
||||
if (!state && !claimed) continue
|
||||
seg.set(s.id, { seg: s, unit, block: b })
|
||||
index.set(s.id, order.length)
|
||||
order.push(s.id)
|
||||
if (first) { unitFirst.push(s.id); first = false }
|
||||
unitOf.set(s.id, unitFirst.length - 1)
|
||||
const t = alertTier(state)
|
||||
const t = claimed ? 1 : alertTier(state)
|
||||
if (t) tiered.push([s.id, t])
|
||||
if (loc) {
|
||||
cell.set(s.id, { block: b, row: loc.row, col: loc.col })
|
||||
@@ -377,7 +425,9 @@ export const EvidenceDoc = forwardRef<EvidenceDocHandle, {
|
||||
const graph = useRunGraph(runId, report, artifact, settled)
|
||||
// 被反方审过的句子:句末挂标记(和裁判的判定并在一个徽标里),点开是整句面板
|
||||
const marks = useMemo(() => challengeMarks(graph, report, artifact), [graph, report, artifact])
|
||||
const model = useMemo(() => buildModel(blocks, overlay, ask, marks), [blocks, overlay, ask, marks])
|
||||
// 说法违规标在正文上:判断词画线、那段文字可点(文档的 violations,服务端核出来的)
|
||||
const claimMarks = useMemo(() => claimMarksOf(doc), [doc])
|
||||
const model = useMemo(() => buildModel(blocks, overlay, ask, marks, claimMarks), [blocks, overlay, ask, marks, claimMarks])
|
||||
// 来自口径的数字上的小标记:按运行取的口径账本里这份报告的标签(只画 caliber 一种)
|
||||
const ledger = useRunLedger(runId, ledgerEnabled(runId, runClass))
|
||||
const labels = report ? ledger?.data?.reports?.[report]?.labels : undefined
|
||||
@@ -478,8 +528,28 @@ export const EvidenceDoc = forwardRef<EvidenceDocHandle, {
|
||||
setAnnounce(`${EVIDENCE_TEXT.violations}:${formatNumber(doc.violations?.length ?? 0)} 条`)
|
||||
}, [claim, instance, doc])
|
||||
|
||||
/**
|
||||
* 打开一份分析结论:分析范围里的编号、说法违规里所挂的结论。正文引用了它的判定语就落到那个片段(看得到上下文),没引用的打开
|
||||
* 它自己的出处链(分析范围那一项)
|
||||
*/
|
||||
const openAnalysis = useCallback((alias: string, opts?: { scope?: boolean }) => {
|
||||
const phrase = !opts?.scope
|
||||
? [...model.seg.values()].find((x) => x.seg.kind === 'analysis' && x.seg.cite?.alias === alias && !x.seg.cite?.locator?.key)
|
||||
: undefined
|
||||
if (phrase) {
|
||||
focusSeg(phrase.seg.id, { flash: true })
|
||||
openSeg(phrase.seg.id)
|
||||
return
|
||||
}
|
||||
if (doc.catalog?.[alias]?.kind !== 'analysis') return
|
||||
claim(instance)
|
||||
setView({ kind: 'scope', alias })
|
||||
setAnnounce(`${ANALYSIS_TEXT.evidence.title} ${alias}`)
|
||||
}, [model, doc, focusSeg, openSeg, claim, instance])
|
||||
|
||||
const close = useCallback((refocus = true) => {
|
||||
const back = view?.kind === 'seg' ? view.id : view?.kind === 'unit' ? badgeKey(view.id) : current
|
||||
const back = view?.kind === 'seg' ? view.id : view?.kind === 'unit' ? badgeKey(view.id)
|
||||
: view?.kind === 'scope' ? `scope:${view.alias}` : current
|
||||
setView(null)
|
||||
setAnnounce('')
|
||||
if (refocus && back) requestAnimationFrame(() => segEl(back)?.focus())
|
||||
@@ -616,6 +686,7 @@ export const EvidenceDoc = forwardRef<EvidenceDocHandle, {
|
||||
onClose={() => close()}
|
||||
onLocate={(id) => { focusSeg(id, { flash: true }); openSeg(id) }}
|
||||
onViolations={openViolations}
|
||||
onAnalysis={(alias) => openAnalysis(alias)}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -676,7 +747,7 @@ export const EvidenceDoc = forwardRef<EvidenceDocHandle, {
|
||||
<DocBlock block={block} dense={dense} doc={doc} visual={visual}
|
||||
current={b === currentBlock ? current : null}
|
||||
active={b === activeBlock ? activeSeg : null}
|
||||
panelId={panelId} model={model} ask={ask} calibers={caliberMarks} />
|
||||
panelId={panelId} model={model} ask={ask} calibers={caliberMarks} claims={claimMarks} />
|
||||
{mode === 'inline' && b === activeBlock && panelNode}
|
||||
</Fragment>
|
||||
))}
|
||||
@@ -695,6 +766,11 @@ export const EvidenceDoc = forwardRef<EvidenceDocHandle, {
|
||||
<button type="button" className="text-[var(--accent)] hover:underline" onClick={() => setExpanded(false)}>收起</button>
|
||||
</div>
|
||||
)}
|
||||
{doc.analysis_scope && (
|
||||
// 系统写的「分析范围」:不是写作者写的,随报告封存(不进正文、不过核对);编号点得开
|
||||
<ScopeSection scope={doc.analysis_scope} onOpen={(alias) => openAnalysis(alias, { scope: true })} />
|
||||
)}
|
||||
{mode === 'inline' && view?.kind === 'scope' && panelNode}
|
||||
{mode === 'dock' && panelNode && dock && createPortal(panelNode, dock)}
|
||||
{mode !== 'inline' && mode !== 'dock' && panelNode && createPortal(panelNode, document.body)}
|
||||
</div>
|
||||
@@ -890,10 +966,12 @@ export function ClaimTally({ claims, lead }: { claims: ClaimTallyCounts; lead: b
|
||||
/** 列表项的开头:结构片段里带着行首的 - / 1. 。列表项被分成几句时,后面几句接在同一项里 */
|
||||
const ITEM_START = /(^|\n)[ \t]*([-*+]|\d+[.)])[ \t]+$/
|
||||
|
||||
const DocBlock = memo(function DocBlock({ block, dense, doc, visual, current, active, panelId, model, ask, calibers }: {
|
||||
const DocBlock = memo(function DocBlock({ block, dense, doc, visual, current, active, panelId, model, ask, calibers, claims }: {
|
||||
block: EvidenceBlock
|
||||
/** 来自口径的数字:片段 id → 小标记(口径账本) */
|
||||
calibers?: CaliberMarks
|
||||
/** 说法违规落在的文字:片段 id → 判断词的位置 */
|
||||
claims?: ClaimMarks
|
||||
dense: boolean
|
||||
doc: EvidenceDocData
|
||||
/** 句末徽标从这里取:这一句眼下的判定(封存后追加的盖过文档里的) */
|
||||
@@ -918,7 +996,7 @@ const DocBlock = memo(function DocBlock({ block, dense, doc, visual, current, ac
|
||||
}
|
||||
const unit = (u: EvidenceUnit, opts?: { code?: boolean; tag?: boolean }) => (
|
||||
<UnitView key={u.id} unit={u} doc={doc} current={current} active={active} panelId={panelId}
|
||||
code={opts?.code} tag={opts?.tag ?? true} badge={model.badge.get(badgeKey(u.id))} calibers={calibers}
|
||||
code={opts?.code} tag={opts?.tag ?? true} badge={model.badge.get(badgeKey(u.id))} calibers={calibers} claims={claims}
|
||||
ask={ask && askable(u, block) ? (model.ask.has(askKey(u.id)) ? 'roving' : 'follow') : undefined} />
|
||||
)
|
||||
|
||||
@@ -1047,10 +1125,11 @@ function ChallengeMark({ verdict, look, after }: { verdict: string; look: MarkLo
|
||||
* 一枚徽标(也是按钮),证据相矛盾(和旧的证据不支持)的整句铺浅底——字本身不画线。被反方审过的
|
||||
* 句子同样挂徽标(和判定并在一起),点开都是整句面板
|
||||
*/
|
||||
function UnitView({ unit, doc, current, active, panelId, code, tag, badge, ask, calibers }: {
|
||||
function UnitView({ unit, doc, current, active, panelId, code, tag, badge, ask, calibers, claims }: {
|
||||
unit: EvidenceUnit; doc: EvidenceDocData; current: string | null; active: string | null; panelId: string
|
||||
code?: boolean; tag: boolean; badge?: Badge
|
||||
calibers?: CaliberMarks
|
||||
claims?: ClaimMarks
|
||||
/**
|
||||
* 审批质询的「质询」:roving 是这一句一个可点的都没有,「质询」本身进键盘顺序;follow 跟在这一句后面,焦点在这一句上时
|
||||
* 按 Tab 到达
|
||||
@@ -1062,6 +1141,7 @@ function UnitView({ unit, doc, current, active, panelId, code, tag, badge, ask,
|
||||
const styles = useMemo<InlineStyles | null>(() => (code ? null : inlineStyles(text)), [text, code])
|
||||
let pos = 0
|
||||
const alerts = new Set<EvidenceStateCode>()
|
||||
let claimTag = false
|
||||
const nodes = segs.map((s) => {
|
||||
const from = pos
|
||||
pos += s.text.length
|
||||
@@ -1069,6 +1149,32 @@ function UnitView({ unit, doc, current, active, panelId, code, tag, badge, ask,
|
||||
const body = styles
|
||||
? <StyledSlice text={text} styles={styles} from={from} to={pos} links={!state} />
|
||||
: s.text
|
||||
const claimed = !state ? claims?.get(s.id) : undefined
|
||||
if (claimed) {
|
||||
// 说法违规:判断词画琥珀色波浪线,整段文字是一个可点的片段(点开看服务端的原话),句末挂「说法待核」
|
||||
claimTag = true
|
||||
const slice = (a: number, z: number) => (styles
|
||||
? <StyledSlice text={text} styles={styles} from={from + a} to={from + z} links={false} /> : s.text.slice(a, z))
|
||||
const parts: ReactNode[] = []
|
||||
let at = 0
|
||||
claimed.ranges.forEach(([a, z], k) => {
|
||||
if (a > at) parts.push(<Fragment key={`t${k}`}>{slice(at, a)}</Fragment>)
|
||||
parts.push(<span key={`w${k}`} className="ev-claim-word" data-ev-claim-word="">{slice(a, z)}</span>)
|
||||
at = z
|
||||
})
|
||||
if (at < s.text.length) parts.push(<Fragment key="rest">{slice(at, s.text.length)}</Fragment>)
|
||||
const open = active === s.id
|
||||
const labels = claimed.codes.map((c) => ANALYSIS_TEXT.claim.label[c] ?? c).join('、')
|
||||
return (
|
||||
<button key={s.id} type="button" className="ev-seg" data-seg={s.id} data-ev-state="claim"
|
||||
data-ev-claim-issue={claimed.codes.join(' ')} tabIndex={current === s.id ? 0 : -1}
|
||||
aria-label={`${s.text},${ANALYSIS_TEXT.claim.tag}:${labels}`} aria-expanded={open}
|
||||
aria-controls={open ? panelId : undefined} title={ANALYSIS_TEXT.claim.hint}
|
||||
style={{ '--ev-soft': 'var(--st-waiting-soft)' } as CSSProperties}>
|
||||
{s.strong ? <strong className="font-semibold">{parts}</strong> : parts}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
if (!state) return <span key={s.id}>{s.strong ? <strong className="font-semibold">{body}</strong> : body}</span>
|
||||
const meta = EVIDENCE_STATE[state]
|
||||
if (meta.alert && TAG_TEXT[state]) alerts.add(state)
|
||||
@@ -1133,6 +1239,11 @@ function UnitView({ unit, doc, current, active, panelId, code, tag, badge, ask,
|
||||
{EVIDENCE_STATE[state].glyph}{TAG_TEXT[state]}
|
||||
</span>
|
||||
))}
|
||||
{tag && claimTag && (
|
||||
<span className="ev-tag" aria-hidden="true" title={ANALYSIS_TEXT.claim.hint} data-ev-tag="claim">
|
||||
?{ANALYSIS_TEXT.claim.tag}
|
||||
</span>
|
||||
)}
|
||||
{badge && (meta || look) && (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -9,7 +9,7 @@ import clsx from 'clsx'
|
||||
import { ApiError } from '../api/client'
|
||||
import { Spinner, StatusBadge, isComposing } from '../components/ui'
|
||||
import {
|
||||
EVIDENCE_KIND_STYLE, EVIDENCE_STATE, caliberSourceText, caliberUpgradeText, citeLabel, claimBasis, closestNames,
|
||||
EVIDENCE_KIND_STYLE, EVIDENCE_STATE, caliberSourceText, caliberUpgradeText, citeLabel, claimBasis, closestNames, derivedFrom,
|
||||
docForeign, entitySources, evidenceTrace, evidenceValue as valueText, graphDoc, inputSource, integrityFailures, isJudged,
|
||||
isJudgeLimit, judgeFlags, judgeLimitWords, judgeable, judgedVerdicts, limitOf, pointsToSettings,
|
||||
locatable, locatorText, notableInput, queryOf, queryWindow, quoteWhere, quoteWindow, reasonOf, rewriteOf, sealVerdict,
|
||||
@@ -26,7 +26,7 @@ import { useAtLeast, useLoginOn } from '../store/auth'
|
||||
import { useCatalog } from '../store/catalog'
|
||||
import { askKey, segmentKey, useEvidence, useExplore, useVerdicts } from '../store/evidence'
|
||||
import type {
|
||||
ApprovalReport, EvidenceBlock, EvidenceChallengeVerdicts, EvidenceDocData, EvidenceDualCheck, EvidenceInput, EvidenceMerge,
|
||||
ApprovalReport, EvidenceAnalysisStep, EvidenceBlock, EvidenceChallengeVerdicts, EvidenceDocData, EvidenceDualCheck, EvidenceInput, EvidenceMerge,
|
||||
EvidenceOnDemand, EvidenceQuoteSource, EvidenceSeal, EvidenceSegment, EvidenceSegmentDetail, EvidenceStep, EvidenceUnit,
|
||||
EvidenceUnitChallenge, EvidenceUntraced, EvidenceVerdict, EvidenceViolation,
|
||||
} from '../types'
|
||||
@@ -34,6 +34,8 @@ import { ArtifactViewer, ResultTable } from './AssistantStream'
|
||||
import { ChallengeSummary, ClaimVerdictPending, type ClaimWait } from './ChallengeSummary'
|
||||
import { useEvidenceHost } from './evidenceHost'
|
||||
import { EvidenceProvenance } from './EvidenceProvenance'
|
||||
import { AnalysisChain, ClaimFlags, ComparabilityRow, isClaimViolation } from './EvidenceAnalysis'
|
||||
import { ANALYSIS_TEXT } from '../lib/termsAnalysis'
|
||||
import { LedgerPart } from './LedgerStep'
|
||||
import { CopyChip } from './Markdown'
|
||||
import { SqlCheckList } from './SqlChecks'
|
||||
@@ -135,8 +137,10 @@ function unverifiedOf(input: EvidenceInput): string {
|
||||
|
||||
export type PanelMode = 'side' | 'drawer' | 'inline' | 'dock'
|
||||
export type PanelView = { kind: 'seg'; id: string } | { kind: 'unit'; id: string } | { kind: 'violations' }
|
||||
/** 报告末尾「分析范围」里的一个编号(A1):那份分析结论的出处链(GET …/evidence/analyses/{alias}) */
|
||||
| { kind: 'scope'; alias: string }
|
||||
|
||||
export function EvidencePanel({ id, mode, doc, artifact, runId, runClass, marks, view, onClose, onLocate, onViolations }: {
|
||||
export function EvidencePanel({ id, mode, doc, artifact, runId, runClass, marks, view, onClose, onLocate, onViolations, onAnalysis }: {
|
||||
id: string
|
||||
mode: PanelMode
|
||||
doc: EvidenceDocData
|
||||
@@ -155,13 +159,16 @@ export function EvidencePanel({ id, mode, doc, artifact, runId, runClass, marks,
|
||||
/** 跳到正文里的某个片段(违规清单里的「定位」) */
|
||||
onLocate: (segId: string) => void
|
||||
onViolations: () => void
|
||||
/** 打开一份分析结论(说法违规里所挂的结论、分析范围里的编号):正文引用了它就落到那个判定语,没引用的打开它的出处链 */
|
||||
onAnalysis?: (alias: string) => void
|
||||
}) {
|
||||
const titleId = `${id}-title`
|
||||
// 推断的来源只在面板这次打开期间缓存:回答里有当前状态(原件已清除、接受已作废)和取决于数据文件现状的结论,
|
||||
// 关掉面板(卸载)或换了运行就作废,再打开重新取。同一次打开里来回点同一片段只取一次
|
||||
const holdProvenance = useEvidence((s) => s.holdProvenance)
|
||||
useEffect(() => (runId ? holdProvenance(runId) : undefined), [runId, holdProvenance])
|
||||
const found = useMemo(() => (view.kind === 'seg' ? findSeg(doc, view.id) : null), [doc, view])
|
||||
const found = useMemo(() => (view.kind === 'seg' ? findSeg(doc, view.id) : view.kind === 'scope' ? scopeSeg(doc, view.alias) : null),
|
||||
[doc, view])
|
||||
const claimAt = useMemo(() => (view.kind === 'unit' ? findUnit(doc, view.id) : null), [doc, view])
|
||||
const overlay = useVerdicts(runId, doc.node_id || undefined)
|
||||
const claimVerdict = claimAt ? unitVerdict(claimAt.unit, overlay) : undefined
|
||||
@@ -232,7 +239,7 @@ export function EvidencePanel({ id, mode, doc, artifact, runId, runClass, marks,
|
||||
: found
|
||||
? <SegmentBody panelId={id} doc={doc} artifact={artifact} runId={runId} runClass={runClass} seg={found.seg}
|
||||
unit={found.unit} block={found.block} mark={marks?.[found.unit.id]} onViolations={onViolations}
|
||||
onLocate={onLocate} />
|
||||
onLocate={onLocate} onAnalysis={onAnalysis} scope={view.kind === 'scope'} />
|
||||
: claimAt
|
||||
? <ClaimBody doc={doc} artifact={artifact} runId={runId} runClass={runClass} unit={claimAt.unit}
|
||||
block={claimAt.block} mark={marks?.[claimAt.unit.id]} />
|
||||
@@ -252,6 +259,24 @@ function findSeg(doc: EvidenceDocData, id: string): { seg: EvidenceSegment; unit
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 分析范围里一个编号的「片段」:不在正文里,按目录里那份结论的判定语拼一个(片段 id scope:<编号>,store 按它改取
|
||||
* GET …/evidence/analyses/{alias})。目录里没有这份结论的为 null
|
||||
*/
|
||||
function scopeSeg(doc: EvidenceDocData, alias: string): { seg: EvidenceSegment; unit: EvidenceUnit; block: EvidenceBlock } | null {
|
||||
const entry = doc.catalog?.[alias]
|
||||
if (entry?.kind !== 'analysis') return null
|
||||
const phrase = (doc.analysis_scope ? [
|
||||
...(doc.analysis_scope.phenomena ?? []), ...(doc.analysis_scope.decomposed ?? []), ...(doc.analysis_scope.excluded ?? []),
|
||||
...(doc.analysis_scope.refused ?? []),
|
||||
] : []).find((i) => i.alias === alias)?.phrase
|
||||
const seg: EvidenceSegment = {
|
||||
id: `scope:${alias}`, kind: 'analysis', state: 'deterministic', text: phrase || alias,
|
||||
cite: { alias, kind: 'analysis', status: 'resolved', locator: {}, eid: entry.eid },
|
||||
}
|
||||
return { seg, unit: { id: `scope:${alias}`, segments: [seg] }, block: { id: 'scope', type: 'paragraph', units: [] } }
|
||||
}
|
||||
|
||||
function findUnit(doc: EvidenceDocData, id: string): { unit: EvidenceUnit; block: EvidenceBlock } | null {
|
||||
for (const block of doc.blocks ?? []) {
|
||||
const unit = (block.units ?? []).find((u) => u.id === id)
|
||||
@@ -276,7 +301,7 @@ function flashOnce(el: HTMLElement) {
|
||||
setTimeout(() => { if (el.dataset.flash === 'focus') delete el.dataset.flash }, 1600)
|
||||
}
|
||||
|
||||
function SegmentBody({ panelId, doc, artifact, runId, runClass, seg, unit, block, mark, onViolations, onLocate }: {
|
||||
function SegmentBody({ panelId, doc, artifact, runId, runClass, seg, unit, block, mark, onViolations, onLocate, onAnalysis, scope = false }: {
|
||||
panelId: string
|
||||
doc: EvidenceDocData; artifact?: string; runId?: string; runClass?: string; seg: EvidenceSegment; unit: EvidenceUnit
|
||||
block: EvidenceBlock
|
||||
@@ -285,6 +310,10 @@ function SegmentBody({ panelId, doc, artifact, runId, runClass, seg, unit, block
|
||||
onViolations: () => void
|
||||
/** 跳到正文里的某个片段(推演区「报告中会变的地方」的定位) */
|
||||
onLocate: (segId: string) => void
|
||||
/** 打开一份分析结论(说法违规里所挂的结论) */
|
||||
onAnalysis?: (alias: string) => void
|
||||
/** 分析范围里的编号:不在正文里,不画所在的句子、口径、模型的解释和反方审稿 */
|
||||
scope?: boolean
|
||||
}) {
|
||||
const report = doc.node_id || undefined
|
||||
const key = runId ? segmentKey(runId, seg.id, report) : ''
|
||||
@@ -321,13 +350,17 @@ function SegmentBody({ panelId, doc, artifact, runId, runClass, seg, unit, block
|
||||
const entityStep = chain.find((s) => s.step === 'entity')
|
||||
const quoteStep = chain.find((s) => s.step === 'quote')
|
||||
const queries = chain.filter((s) => s.step === 'query')
|
||||
const isMetric = cite?.kind === 'metric' || entry?.kind === 'metric' || !!metricStep
|
||||
const isInput = cite?.kind === 'input' || entry?.kind === 'input' || !!inputStep
|
||||
// 分析结论:判定语、具名的数(cite 的种类是 analysis),结果表的一格(cite 是 cell、目录条目是 analysis)。链是分析的几步,
|
||||
// 后面接输入快照的查询步骤
|
||||
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 isEntity = !isMetric && !isInput && seg.kind === 'entity' && state === 'deterministic'
|
||||
const isQuote = !isMetric && !isInput && seg.kind === 'quote'
|
||||
const isEntity = !isAnalysis && !isMetric && !isInput && seg.kind === 'entity' && state === 'deterministic'
|
||||
const isQuote = !isAnalysis && !isMetric && !isInput && seg.kind === 'quote'
|
||||
// 报告直接引用的查询单元格([[v:Q3.r5.amount]]、整表里的一格):证据链就是那一次查询
|
||||
const isCell = !isMetric && !isInput && !isEntity && !isQuote
|
||||
const isCell = !isAnalysis && !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)
|
||||
@@ -388,6 +421,13 @@ function SegmentBody({ panelId, doc, artifact, runId, runClass, seg, unit, block
|
||||
return i >= 0 ? { index: i, alias: queries[i].alias ?? '', go: () => jumpTo(i) } : undefined
|
||||
}
|
||||
const violations = (doc.violations ?? []).filter((v) => v.segment === seg.id)
|
||||
// 说法违规(判断词没挂对分析结论、因果没有依据):落在这一段文字上的,单列一节,不和裸数字那些原因混在一起
|
||||
const claimFlags = violations.filter(isClaimViolation)
|
||||
// 分析结论的输入里点 Q:跳到下面那个查询步骤
|
||||
const jumpToQuery = (alias: string) => {
|
||||
const i = queries.findIndex((q) => q.alias === alias)
|
||||
if (i >= 0) jumpTo(i)
|
||||
}
|
||||
// 数字推演:按(运行、报告、口径卡、指标)认一份草稿。同一个指标的几处引用之间来回切,推演不收起(定位到另一处
|
||||
// 引用也是这样);换了指标、换成别的片段才收起清空。卡和指标先按文档目录认:切片段时证据链还没回来,也认得出是同一个
|
||||
const whatifCard = entry?.kind === 'metric' ? entry.node_id : metricStep?.node_id
|
||||
@@ -443,9 +483,13 @@ function SegmentBody({ panelId, doc, artifact, runId, runClass, seg, unit, block
|
||||
]} />
|
||||
)}
|
||||
|
||||
<Part title={EVIDENCE_TEXT.sentence} data-ev-sentence="">
|
||||
<Sentence unit={unit} active={seg.id} />
|
||||
</Part>
|
||||
{!scope && (
|
||||
<Part title={EVIDENCE_TEXT.sentence} data-ev-sentence="">
|
||||
<Sentence unit={unit} active={seg.id} />
|
||||
</Part>
|
||||
)}
|
||||
|
||||
{claimFlags.length > 0 && <ClaimFlags violations={claimFlags} onAnalysis={onAnalysis} />}
|
||||
|
||||
{state === 'deterministic' && (isMetric || isCell) && !docIssue && (
|
||||
// 口径账本:出处链最上面的「口径」一步(来自口径 / 相关口径 / 这次的推理)。比对在封存之后做,这一步按运行另取
|
||||
@@ -484,6 +528,11 @@ function SegmentBody({ panelId, doc, artifact, runId, runClass, seg, unit, block
|
||||
</Part>
|
||||
)}
|
||||
|
||||
{isAnalysis && (
|
||||
// 分析结论:判定 → 方法 → 计算 → 输入;输入快照的查询步骤照常在下面画
|
||||
<AnalysisChain chain={analysisChain} seal={seal} pending={pending} failed={chainFailed} onQuery={jumpToQuery} />
|
||||
)}
|
||||
|
||||
{isEntity && (
|
||||
<EntityPart step={entityStep} entry={entry} cite={cite} seal={seal} pending={pending}
|
||||
failed={chainFailed} catalog={doc.catalog} />
|
||||
@@ -553,16 +602,20 @@ function SegmentBody({ panelId, doc, artifact, runId, runClass, seg, unit, block
|
||||
|
||||
{provenanceOn && runId && <EvidenceProvenance runId={runId} segId={seg.id} report={report} />}
|
||||
|
||||
{state === 'deterministic' && !isMetric && !isInput && !isCell && !isEntity && !isQuote && (
|
||||
{state === 'deterministic' && !isAnalysis && !isMetric && !isInput && !isCell && !isEntity && !isQuote && (
|
||||
<p className="text-dim">{sourceOf(seg, doc) || detail?.note}</p>
|
||||
)}
|
||||
|
||||
<JudgePart doc={doc} unit={unit} block={block} runId={runId} runClass={runClass}
|
||||
onDemand={detail?.unit?.on_demand} answered={detail?.unit?.verdict} pending={pending} />
|
||||
{isAnalysis && detail?.note && <p className="text-2xs leading-relaxed text-faint" data-ev-analysis-note="">{detail.note}</p>}
|
||||
|
||||
{!scope && (
|
||||
<JudgePart doc={doc} unit={unit} block={block} runId={runId} runClass={runClass}
|
||||
onDemand={detail?.unit?.on_demand} answered={detail?.unit?.verdict} pending={pending} />
|
||||
)}
|
||||
|
||||
{/* 反方审稿对这一句的判断:点句中的数字也看得到。片段接口还没答、答不了时先按正文标记写判断。正文不是封存的那一份
|
||||
时都不用:服务端认的是封存的那份文档 */}
|
||||
{!docIssue && (segChallenge || mark) && (
|
||||
{!scope && !docIssue && (segChallenge || mark) && (
|
||||
<ChallengePart challenge={segChallenge} mark={mark} wait={segWait} unit={unit} report={report}
|
||||
onRetry={() => { if (runId) void loadSegment(runId, seg.id, report) }} />
|
||||
)}
|
||||
@@ -652,12 +705,14 @@ function ClaimBody({ doc, artifact, runId, runClass, unit, block, mark }: {
|
||||
// 有指标依据时才去取证据图(正文挂上时一般已经取过,取过的不再发)
|
||||
const graphSlot = useEvidence((s) => (runId ? s.graphs[runId] : undefined))
|
||||
const loadGraph = useEvidence((s) => s.loadGraph)
|
||||
const metricCite = (unit.cites ?? []).some((alias) => doc.catalog?.[alias]?.kind === 'metric')
|
||||
// 分析结论的依据另写它派生自哪几份查询、哪一层拆解(证据图的 derived_from 边),同样要证据图
|
||||
const graphCite = (unit.cites ?? []).some((alias) => ['metric', 'analysis'].includes(String(doc.catalog?.[alias]?.kind)))
|
||||
useEffect(() => {
|
||||
if (runId && metricCite) void loadGraph(runId)
|
||||
}, [runId, metricCite, loadGraph])
|
||||
if (runId && graphCite) void loadGraph(runId)
|
||||
}, [runId, graphCite, loadGraph])
|
||||
const graph = !foreign && graphSlot?.status === 'ok' ? graphSlot.data : undefined
|
||||
const cites = (unit.cites ?? []).map((alias) => ({ alias, label: citeLabel(alias, doc, graph, report, !!runId) }))
|
||||
const cites = (unit.cites ?? []).map((alias) => ({ alias, label: citeLabel(alias, doc, graph, report, !!runId),
|
||||
derived: doc.catalog?.[alias]?.kind === 'analysis' ? derivedFrom(graph, alias, report) : [] }))
|
||||
// 讲方法、讲结构的句子:SQL 和字段清单直接列在挂的依据下面。正文不是封存的那份时不列(链是另一份报告的)
|
||||
const basis = useMemo(() => (foreign ? null : claimBasis(unit, doc)), [foreign, unit, doc])
|
||||
// 反方审稿对这一句的判断:服务端只认审的就是封存的这一份文档;正文不是那一份时不用。片段接口还没答、答不了时先按正文
|
||||
@@ -685,9 +740,14 @@ function ClaimBody({ doc, artifact, runId, runClass, unit, block, mark }: {
|
||||
{cites.length ? (
|
||||
<ul className="space-y-0.5">
|
||||
{cites.map((c) => (
|
||||
<li key={c.alias} className="flex min-w-0 items-baseline gap-1.5">
|
||||
<li key={c.alias} className="flex min-w-0 items-baseline gap-1.5" data-ev-cite={c.alias}>
|
||||
<span className="mono shrink-0 font-medium">{c.alias}</span>
|
||||
{c.label && <span className="min-w-0 truncate text-dim" title={c.label}>{c.label}</span>}
|
||||
{c.derived.length > 0 && (
|
||||
<span className="shrink-0 text-2xs text-faint" data-ev-derived={c.derived.join(',')}>
|
||||
{ANALYSIS_TEXT.evidence.derivedFrom(c.derived)}
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -1478,6 +1538,10 @@ function MetricPart({ step, entry, inputs, runId, runClass, seal, pending, faile
|
||||
: step.recompute_ok ? EVIDENCE_TEXT.recomputeOk : EVIDENCE_TEXT.recomputeBad}
|
||||
</dd>
|
||||
</div>
|
||||
{step.comparability && typeof step.comparability === 'object' && (
|
||||
// 跨两份同形查询算的环比、同比:口径卡执行时自动做的可比性检查,展开看那份可比性结论的整条链
|
||||
<ComparabilityRow comparability={step.comparability} seal={seal} />
|
||||
)}
|
||||
{untraced && (
|
||||
<div>
|
||||
<dt className="text-2xs text-faint">{EVIDENCE_TEXT.origin}</dt>
|
||||
@@ -1849,6 +1913,11 @@ function QueryPart({ id, step, seal, masked, pick }: {
|
||||
· {MERGE_TEXT.mergedInto(step.merged_into)}
|
||||
</span>
|
||||
)}
|
||||
{step.input_of && (
|
||||
<span className="ml-1.5 font-normal" data-ev-input-of={step.input_of}>
|
||||
· {ANALYSIS_TEXT.evidence.inputOfAnalysis(step.input_of)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{host.onNode && <NodeChip id={step.node_id} />}
|
||||
{step.sql && (
|
||||
@@ -2057,6 +2126,8 @@ const CODE_LABEL: Record<string, string> = {
|
||||
unverified_entity: '无法核实的名称',
|
||||
absence_claim: ABSENCE_CLAIM_TEXT.label,
|
||||
masked_cell: MASKED_CELL_TEXT.label,
|
||||
// 分析说法核对(engine/analysis_claims.CODES):叫法同审计
|
||||
...ANALYSIS_TEXT.claim.label,
|
||||
}
|
||||
|
||||
/** 违规清单:报告撰写节点核对出来的全部问题,画得出线的能定位,画不出的说清在哪 */
|
||||
|
||||
@@ -21,13 +21,22 @@ import { ReconcileDialog, ReconcileResults } from './LedgerReconcile'
|
||||
* 能不能自动、不能的原因都是服务端给的;摘要只是把主报告里服务端标好的数按标签数一数、写出是哪份口径。
|
||||
*/
|
||||
|
||||
/** 摘要的几个数:主报告里服务端标好的标签按种类数,来自口径的写出是哪几份口径(按出现的先后) */
|
||||
/** 摘要认的四种标签。服务端不给别的标签(分析结论的数不和口径比对,00-总方案 D11),以后多了也不计、不出 NaN */
|
||||
const COUNTED_KINDS = ['caliber', 'related', 'reasoning', 'unknown'] as const
|
||||
type CountedKind = (typeof COUNTED_KINDS)[number]
|
||||
const counted = (kind: unknown): kind is CountedKind => (COUNTED_KINDS as readonly unknown[]).includes(kind)
|
||||
|
||||
/**
|
||||
* 摘要的几个数:主报告里服务端标好的标签按种类数,来自口径的写出是哪几份口径(按出现的先后)。认不出种类的标签(不是对象、
|
||||
* 没有 kind、不是四种之一)不计,也不算进总数:总数要等于四种之和,摘要那一句才说得平
|
||||
*/
|
||||
function summaryOf(data: RunLedger) {
|
||||
const labels = Object.values((data.primary ? data.reports?.[data.primary]?.labels : undefined) ?? {})
|
||||
const counts = { caliber: 0, related: 0, reasoning: 0, unknown: 0 }
|
||||
.filter((l) => !!l && typeof l === 'object' && counted(l.kind))
|
||||
const counts: Record<CountedKind, number> = { caliber: 0, related: 0, reasoning: 0, unknown: 0 }
|
||||
const calibers: string[] = []
|
||||
for (const l of labels) {
|
||||
counts[l.kind] += 1
|
||||
counts[l.kind as CountedKind] += 1
|
||||
if (l.kind === 'caliber') {
|
||||
const name = caliberOf(l)
|
||||
if (!calibers.includes(name)) calibers.push(name)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -715,3 +715,44 @@ export const COPILOT_OBJECT_ISSUES = [
|
||||
{ op: 'remove_node', id: 'old' },
|
||||
{ op: 'final', graph: { nodes: [{ id: 'lp' }, { id: 'ask' }] }, issues: [] },
|
||||
]
|
||||
|
||||
/**
|
||||
* 协作成员调分析工具(分析能力一轮):分析员查一次按地区两周的销售额,做一次变化拆解、一次波动基线(两周历史不够,算不了)。
|
||||
* 字段照 engine/nodes/multi.py:tool.end 带 agent、analysis_artifact 和判定那一小段(tools/analysis.event_view,编号是成员自己的
|
||||
* 分析容器里的);算不了的另有一条 analysis_refused 的提醒(带 agent、call_id)。preview 是结论 JSON 的前一截,判定语在截掉的那段里
|
||||
*/
|
||||
export const TEAM_PHRASE = '销售额下降 340(-12.6%),主要来自华东(-300,占 88.2%)'
|
||||
export function analysisTeamRun(): RunEvent[] {
|
||||
const { out, ev } = builder('syn-analysis-team')
|
||||
const sql = 'SELECT region, week, SUM(amount) AS gmv FROM orders GROUP BY region, week ORDER BY region, week'
|
||||
ev('run.started', null, { nodes: 3, resumed: false })
|
||||
ev('node.started', 'team', { node_type: 'supervisor', label: '销售分析团队' })
|
||||
ev('agent.route.start', 'team', { round: 0 })
|
||||
ev('agent.route.end', 'team', { round: 0, duration_ms: 900, agents: ['分析员'], parallel: 1, done: false, reason: '先拆一下变化来自哪里' }, 0.9)
|
||||
ev('agent.step.start', 'team', { agent: '分析员', instruction: '拆一下销售额的变化', round: 0, parallel: 1 })
|
||||
ev('tool.start', 'team', { tool: 'db_query__shop', agent: '分析员', call_id: 'm1', args: { sql } }, 0.2)
|
||||
ev('tool.end', 'team', { tool: 'db_query__shop', agent: '分析员', call_id: 'm1', duration_ms: 30,
|
||||
preview: JSON.stringify({ columns: ['region', 'week', 'gmv'], rows: [['华东', '2026-W41', 1000], ['华东', '2026-W42', 700]], row_count: 8 }) }, 0.03)
|
||||
ev('tool.start', 'team', { tool: 'analysis_decompose', agent: '分析员', call_id: 'm2', args: {
|
||||
mode: 'additive', query: 'Q1', by: ['region'], period: 'week', base: '2026-W41', target: '2026-W42', measure: 'gmv',
|
||||
label: '销售额', hypothesis: '下降是不是集中在某个地区', parent: null } }, 0.2)
|
||||
ev('tool.end', 'team', { tool: 'analysis_decompose', agent: '分析员', call_id: 'm2', duration_ms: 8,
|
||||
preview: '{\n "analysis_artifact": "a1f0", \n "result": {\n "op": "decompose",\n "mode": "additive",\n "method": "decompose.additive@1",',
|
||||
analysis_artifact: 'a1f0c3d2b4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f9',
|
||||
analysis: { alias: 'A1', op: 'decompose', mode: 'additive', status: 'ok', verdict: 'driver', direction: 'down', phrase: TEAM_PHRASE,
|
||||
reason_code: null } }, 0.01)
|
||||
ev('tool.start', 'team', { tool: 'analysis_baseline', agent: '分析员', call_id: 'm3', args: { query: 'Q1', period: 'week', measure: 'gmv' } }, 0.1)
|
||||
ev('tool.end', 'team', { tool: 'analysis_baseline', agent: '分析员', call_id: 'm3', duration_ms: 4,
|
||||
preview: '{\n "analysis_artifact": "b2e1",',
|
||||
analysis_artifact: 'b2e1d4c3a5f6e70819203b4c5d6e7f8091a2b3c4d5e6f70819203b4c5d6e7f80',
|
||||
analysis: { alias: 'A2', op: 'baseline', mode: null, status: 'refused', verdict: null, direction: null,
|
||||
phrase: '波动基线没有做成:只有 0 期历史,至少要 8 期', reason_code: 'history_short' } }, 0.01)
|
||||
ev('log', 'team', { level: 'warn', code: 'analysis_refused', agent: '分析员', call_id: 'm3', tool: 'analysis_baseline',
|
||||
reason_code: 'history_short', reason: '只有 0 期历史,至少要 8 期', message: '分析员 的 analysis_baseline 没有做成:只有 0 期历史,至少要 8 期' })
|
||||
ev('agent.step.end', 'team', { agent: '分析员', duration_ms: 1200, round: 0, parallel: 1, preview: TEAM_PHRASE }, 0.3)
|
||||
ev('agent.route.start', 'team', { round: 1 })
|
||||
ev('agent.route.end', 'team', { round: 1, duration_ms: 600, agents: [], parallel: 0, done: true, reason: '已经说清来源' }, 0.6)
|
||||
ev('node.finished', 'team', { duration_ms: 3200, attempt: 1, preview: TEAM_PHRASE })
|
||||
ev('run.finished', null, { output: { 结论: TEAM_PHRASE }, timing: { wall_ms: 3400, active_ms: 3400, wait_ms: 0 } })
|
||||
return out
|
||||
}
|
||||
|
||||
+143
-1
@@ -15,6 +15,7 @@ import { catalogPatchOf, patchBeforeText, patchValueText, patchWhere } from './c
|
||||
import { LEDGER_FEEDBACK_TEXT, RECALL_TEXT } from '../lib/termsRecall'
|
||||
import { claimCountsOf, isJudged, statsTally } from '../lib/evidence'
|
||||
import { isSqlCheckCode, sortSqlChecks, sqlCheckOf, sqlChecksOf, sqlCheckWhere, sqlRuleLabel } from '../lib/sqlcheck'
|
||||
import { ANALYSIS_TEXT, analysisMethodLabel, analysisToolOp } from '../lib/termsAnalysis'
|
||||
|
||||
// 泳道数据画布也要用(supervisor 节点要展开成协作矩阵),所以类型放在
|
||||
// types.ts 里;这里再导出一遍,老引用不用改
|
||||
@@ -80,6 +81,7 @@ export type StepKind =
|
||||
| 'llm' // 模型调用
|
||||
| 'query' // 数据库查询
|
||||
| 'schema' // 看表结构
|
||||
| 'analysis' // 分析:Agent 的分析工具、分析卡的一项
|
||||
| 'tool' // 其他工具
|
||||
| 'code' // 沙箱代码
|
||||
| 'branch' // 分支走向
|
||||
@@ -163,6 +165,8 @@ export interface Step {
|
||||
tier?: string
|
||||
/** 合并查询那一行(merge.end):合并了哪几个输入、几条警告。SQL 在 detail,预览在 result */
|
||||
merge?: MergeStep
|
||||
/** 分析那一行(Agent 分析工具的 tool.start / tool.end、分析卡一项的 analysis.end):算子、判定语、编号。参数在 detail */
|
||||
analysis?: AnalysisStep
|
||||
/** 对照数据目录的 SQL 检查结果:查询那一行(tool.end.checks)、指标所依据的查询没通过检查那一行(log.checks) */
|
||||
checks?: SqlCheckItem[]
|
||||
/** fix 要去的不是这一行所在的节点(指标的问题出在来源查询节点的 SQL 上):去哪个节点、落到哪一栏 */
|
||||
@@ -181,6 +185,25 @@ export interface MergeStepInput {
|
||||
source?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 分析的一步:判定语、编号、算不了的原因码都是服务端给的(tool.end 的 analysis,tools/analysis.event_view;分析卡的 analysis.end),
|
||||
* 界面只排版。写错的调用(tool.error 带 call_error)没有判定,callError 是服务端的代码
|
||||
*/
|
||||
export interface AnalysisStep {
|
||||
op?: string
|
||||
mode?: string | null
|
||||
/** Agent 工具的结论在本节点的编号(A1);分析卡的一项用 item */
|
||||
alias?: string | null
|
||||
item?: string
|
||||
status?: string
|
||||
verdict?: string | null
|
||||
phrase?: string
|
||||
reasonCode?: string | null
|
||||
callError?: string
|
||||
/** Agent 写的「这次在验证什么」(调用参数里的 hypothesis) */
|
||||
hypothesis?: string
|
||||
}
|
||||
|
||||
export interface MergeStep {
|
||||
inputs: MergeStepInput[]
|
||||
/** 执行时的警告条数。警告的原文由同一节点紧接着的 log(merge_key_type…)各占一行,不在这里重复 */
|
||||
@@ -889,6 +912,35 @@ function explainLog(code: string | undefined, message: string, d: Record<string,
|
||||
next: MASKED_CELL_TEXT.next,
|
||||
}
|
||||
}
|
||||
case 'report_analysis_claims': {
|
||||
// 判断词没挂对分析结论、原因没有依据,重写后仍有(report.py):读结构化字段 count、texts,不从原话里认。check 照常产出、
|
||||
// 只标注;strict 另记了出具缺口(原话里说了,详情里有)
|
||||
const n = typeof d.count === 'number' && d.count > 0 ? d.count : undefined
|
||||
const texts = strs(d.texts)
|
||||
return {
|
||||
title: ANALYSIS_TEXT.log.claims(n, d.mode === 'strict'),
|
||||
sub: texts.length ? texts.map((t) => `「${t}」`).join('、') : undefined,
|
||||
next: ANALYSIS_TEXT.issuance.claimsNext,
|
||||
}
|
||||
}
|
||||
case 'analysis_refused': {
|
||||
// 分析那一行不在(老事件)时才走到这里:照结构化字段写哪一种分析没有做成、原因
|
||||
const tool = analysisToolOp(d.tool)
|
||||
const op = typeof d.op === 'string' ? d.op : tool
|
||||
return {
|
||||
title: ANALYSIS_TEXT.log.refused(analysisMethodLabel(op), str(d.item)),
|
||||
sub: str(d.reason),
|
||||
next: ANALYSIS_TEXT.step.refusedNext,
|
||||
}
|
||||
}
|
||||
case 'metric_comparability_skipped': {
|
||||
// 口径卡的环比、同比用到两份同形查询,可比性检查没做成(metrics.py):指标照常算,两期能不能直接比要自己核对
|
||||
return {
|
||||
title: ANALYSIS_TEXT.log.comparabilitySkipped(str(d.metric_name) ?? str(d.metric) ?? ''),
|
||||
sub: str(d.reason),
|
||||
next: ANALYSIS_TEXT.log.comparabilitySkippedNext,
|
||||
}
|
||||
}
|
||||
case 'report_catalog_trimmed': {
|
||||
// 写作目录超出篇幅(report.py _trimmed_message)。读结构化字段(queries、omitted、nodes),不从原话里认
|
||||
const total = typeof d.queries === 'number' ? d.queries : undefined
|
||||
@@ -1318,11 +1370,48 @@ function toolStep(seq: number, tool: string, args: Record<string, any>): Step {
|
||||
return { ...base, kind: 'schema', title: clip(`查看 ${tables.length} 张表的字段:${head}…`),
|
||||
detail: tables.join('\n') }
|
||||
}
|
||||
const op = analysisToolOp(tool)
|
||||
if (op) {
|
||||
// Agent 的分析工具:标题写算子的叫法(契约的叫法),不写 analysis_decompose;参数里没填的不列。判定语、编号等 tool.end
|
||||
const shown = Object.fromEntries(Object.entries(args ?? {}).filter(([k, v]) => v != null && k !== 'hypothesis'))
|
||||
const hypothesis = typeof args?.hypothesis === 'string' && args.hypothesis.trim() ? args.hypothesis.trim() : undefined
|
||||
return {
|
||||
...base, kind: 'analysis', title: analysisMethodLabel(op, args?.mode),
|
||||
detail: Object.keys(shown).length ? JSON.stringify(shown, null, 2) : undefined,
|
||||
analysis: { op, ...(args?.mode ? { mode: String(args.mode) } : {}), ...(hypothesis ? { hypothesis } : {}) },
|
||||
}
|
||||
}
|
||||
const argText = Object.keys(args ?? {}).length
|
||||
? JSON.stringify(args, null, 2) : ''
|
||||
return { ...base, kind: 'tool', title: clip(`调用 ${tool}`), detail: argText || undefined }
|
||||
}
|
||||
|
||||
/**
|
||||
* tool.end 的 analysis(tools/analysis.event_view)折进分析那一行:标题接上编号,副标题是判定语(算不了的就是「…没有做成:原因」,
|
||||
* 服务端写好的);算不了的用提醒色。老服务端没有这一段:preview 只是结论的前一截,判定语多半被截掉,只照参数写叫法,不从里面拼
|
||||
*/
|
||||
function settleAnalysis(step: Step, d: Record<string, any>): void {
|
||||
const view = d.analysis && typeof d.analysis === 'object' ? d.analysis as Record<string, any> : null
|
||||
const info: AnalysisStep = { ...(step.analysis ?? {}) }
|
||||
if (view) {
|
||||
if (typeof view.op === 'string') info.op = view.op
|
||||
if (view.mode != null) info.mode = String(view.mode)
|
||||
if (typeof view.alias === 'string' && view.alias) info.alias = view.alias
|
||||
if (typeof view.status === 'string') info.status = view.status
|
||||
if (typeof view.verdict === 'string') info.verdict = view.verdict
|
||||
if (typeof view.phrase === 'string' && view.phrase) info.phrase = view.phrase
|
||||
if (typeof view.reason_code === 'string') info.reasonCode = view.reason_code
|
||||
}
|
||||
step.analysis = info
|
||||
step.title = ANALYSIS_TEXT.step.title(analysisMethodLabel(info.op, info.mode), info.alias)
|
||||
if (info.phrase) step.sub = step.sub ? `${info.phrase} · ${step.sub}` : info.phrase
|
||||
if (info.status === 'refused') {
|
||||
step.level = 'warn'
|
||||
step.next = ANALYSIS_TEXT.step.refusedNext
|
||||
}
|
||||
if (typeof d.analysis_artifact === 'string' && d.analysis_artifact) step.artifact = d.analysis_artifact
|
||||
}
|
||||
|
||||
/** 低于这个毫秒数的节点不参与并行分组:瞬时节点谁跟谁都"重叠",是噪音不是信息 */
|
||||
const CONCURRENT_MIN_MS = 30
|
||||
/** 开始时刻相差在这个数以内算"同一批出发"。实测 fan-out 的几路相差不到 1ms */
|
||||
@@ -1739,6 +1828,11 @@ export function decodeRun(events: RunEvent[], final?: RunFinal, opts?: DecodeOpt
|
||||
const escalated = new Map<string, { step: Step; tool: string; reason: string }[]>()
|
||||
/** node_id → 起止时刻。用来事后认出"哪几个节点是同时跑的" */
|
||||
const spans = new Map<string, { start: number; end: number; ms: number }>()
|
||||
/**
|
||||
* 分析那一行(Agent 工具按 call_id,分析卡按节点 + 项):紧跟着的那条「没有做成」的提醒(log analysis_refused)说的是同一件事,
|
||||
* 那一行已经写了判定语(「…没有做成:原因」),不再另起一行
|
||||
*/
|
||||
const analysisSteps = new Map<string, Step>()
|
||||
|
||||
/** 协作团队的状态只有一个来源:reduceTeam。画布那边调的是同一个函数 */
|
||||
const trackTeam = (event: RunEvent): void => {
|
||||
@@ -2216,7 +2310,24 @@ export function decodeRun(events: RunEvent[], final?: RunFinal, opts?: DecodeOpt
|
||||
step.sub = step.sub ? `${step.sub} · ${counts}` : counts
|
||||
if (n('error') || n('warning')) step.level = 'warn'
|
||||
}
|
||||
if (step.kind === 'query' || step.kind === 'schema' || failed) {
|
||||
if (step.kind === 'analysis') {
|
||||
// 分析:成了的照 tool.end 的 analysis 写判定语和编号(结论工件在 analysis_artifact,preview 是结论 JSON 的前一截,
|
||||
// 不摆出来)。写错的调用(call_error)和别的工具报错一样算这一次没成,但它没有记成结论、原话交回了 Agent,Agent 会
|
||||
// 照着改了再调:副标题说清没记成结论,下一步写在行下面,原话在展开区
|
||||
if (failed) {
|
||||
const why = String(d.error ?? preview)
|
||||
step.sub = d.call_error ? ANALYSIS_TEXT.step.callError : step.sub
|
||||
step.result = why
|
||||
if (d.call_error) {
|
||||
step.analysis = { ...(step.analysis ?? {}), callError: String(d.call_error) }
|
||||
step.next = ANALYSIS_TEXT.step.callErrorNext
|
||||
}
|
||||
} else {
|
||||
settleAnalysis(step, d)
|
||||
analysisSteps.set(key, step)
|
||||
}
|
||||
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
|
||||
step.result = preview
|
||||
@@ -2720,6 +2831,12 @@ export function decodeRun(events: RunEvent[], final?: RunFinal, opts?: DecodeOpt
|
||||
break
|
||||
}
|
||||
}
|
||||
if (d.code === 'analysis_refused') {
|
||||
// 一份分析没有做成:分析那一行已经写了「…没有做成:原因」,同一件事不再另起一行。找不到那一行(老事件)才照下面说
|
||||
const key = typeof d.call_id === 'string' && d.call_id ? `call:${d.call_id}`
|
||||
: `${nodeId ?? '_'}:item:${String(d.item ?? '')}`
|
||||
if (analysisSteps.has(key)) break
|
||||
}
|
||||
// 双盲复算、反方审稿的日志按 code 和结构化字段解读:info 的也上时间线,没有原话的老日志照样说得出来。
|
||||
// 后端标了 warn / error 的照它的来,explainLog 认为该提醒的(有缺口、有推翻)也用提醒色
|
||||
if (typeof d.code === 'string' && VERIFY_LOG_CODES.has(d.code)) {
|
||||
@@ -2863,6 +2980,31 @@ export function decodeRun(events: RunEvent[], final?: RunFinal, opts?: DecodeOpt
|
||||
break
|
||||
}
|
||||
|
||||
case 'analysis.end': {
|
||||
// 分析卡的一项做完了(engine/nodes/analysis.py):标题写算子的叫法和这一项的标识,副标题是判定语(服务端写好的,算不了
|
||||
// 的是「…没有做成:原因」)。结论工件可以点开
|
||||
const item = typeof d.item === 'string' ? d.item : ''
|
||||
const info: AnalysisStep = {
|
||||
...(typeof d.op === 'string' ? { op: d.op } : {}), ...(d.mode != null ? { mode: String(d.mode) } : {}),
|
||||
...(item ? { item } : {}), ...(typeof d.status === 'string' ? { status: d.status } : {}),
|
||||
...(typeof d.verdict === 'string' ? { verdict: d.verdict } : {}),
|
||||
...(typeof d.phrase === 'string' && d.phrase ? { phrase: d.phrase } : {}),
|
||||
...(typeof d.reason_code === 'string' ? { reasonCode: d.reason_code } : {}),
|
||||
}
|
||||
const refused = d.status === 'refused'
|
||||
const row: Step = {
|
||||
id: `an-${seq}`, seq, kind: 'analysis', nodeId, status: 'done',
|
||||
title: ANALYSIS_TEXT.step.title(analysisMethodLabel(d.op, d.mode), item),
|
||||
...(info.phrase ? { sub: info.phrase } : {}),
|
||||
...(refused ? { level: 'warn' as const, next: ANALYSIS_TEXT.step.refusedNext } : {}),
|
||||
...(typeof d.analysis_artifact === 'string' && d.analysis_artifact ? { artifact: d.analysis_artifact } : {}),
|
||||
analysis: info,
|
||||
}
|
||||
analysisSteps.set(`${nodeId ?? '_'}:item:${item}`, row)
|
||||
push(row, nodeId)
|
||||
break
|
||||
}
|
||||
|
||||
case 'merge.end': {
|
||||
// 合并查询:几次查询的结果在库外按键合并。和查询同一类(kind query):detail 是合并 SQL,result 是预览,
|
||||
// 工件是合并结果的查询快照。输入列在 merge 里,展开区单列一块;警告的原文由紧跟着的 log 各占一行
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { create } from 'zustand'
|
||||
import { ANALYSIS_TEXT, analysisMethodLabel, analysisToolOp } from '../lib/termsAnalysis'
|
||||
import { ApiError, api, streamRun } from '../api/client'
|
||||
import { streamChatTurn, type ChatTurnEvent, type ChatTurnStart } from '../api/chatTurns'
|
||||
import type { CopilotOp, FixKind, RunFinal } from '../run/decode'
|
||||
@@ -1649,9 +1650,12 @@ function watch(flow: Flow, runId: string, after = 0): () => void {
|
||||
switch (event.type) {
|
||||
case 'tool.start': {
|
||||
const tool = String(d.tool ?? '')
|
||||
// 分析工具写算子的叫法(契约的叫法,lib/termsAnalysis),不写 analysis_decompose
|
||||
const op = analysisToolOp(tool)
|
||||
patch((t) => (t.phase !== 'running' ? {} : {
|
||||
status: tool.startsWith('db_query') ? '正在查询数据…'
|
||||
: tool.startsWith('db_schema') ? '正在读取数据结构…'
|
||||
: op ? ANALYSIS_TEXT.step.running(analysisMethodLabel(op, d.args?.mode))
|
||||
: tool ? `正在调用 ${tool}…` : '正在运行…',
|
||||
}))
|
||||
break
|
||||
|
||||
@@ -94,6 +94,9 @@ interface EvidenceState {
|
||||
export const docKey = (runId: string, report?: string) => `${runId}@${report ?? ''}`
|
||||
export const askKey = (runId: string, report: string | undefined, unit: string) => `${docKey(runId, report)}:${unit}`
|
||||
|
||||
/** 分析范围里一个编号的片段 id 前缀(证据面板拼的「scope:A1」,不在正文里;同服务端导出页的 SCOPE_REF) */
|
||||
export const SCOPE_SEG = 'scope:'
|
||||
|
||||
/**
|
||||
* 片段的缓存键:`runId:segId`。一次运行里有好几份报告时片段 id 会撞(每份都从 s0 数起),
|
||||
* 带上报告节点:`runId:segId@report`
|
||||
@@ -159,8 +162,15 @@ export const useEvidence = create<EvidenceState>((set, get) => {
|
||||
}),
|
||||
loadGraph: (runId) => fill('graphs', runId, () => api.evidence.graph(runId)),
|
||||
reloadGraph: (runId) => fill('graphs', runId, () => api.evidence.graph(runId), true),
|
||||
// 分析范围里的编号(片段 id「scope:A1」,证据面板拼的,不在正文里):取那份分析结论的出处链,按片段答复的样子放进同一张表
|
||||
loadSegment: (runId, segmentId, report) =>
|
||||
fill('segments', segmentKey(runId, segmentId, report), () => api.evidence.segment(runId, segmentId, { report })),
|
||||
fill('segments', segmentKey(runId, segmentId, report), () => (segmentId.startsWith(SCOPE_SEG)
|
||||
? api.evidence.analysis(runId, segmentId.slice(SCOPE_SEG.length), { report }).then((r) => ({
|
||||
report: r.report, chain: r.chain ?? [], seal: r.seal, redacted: r.redacted,
|
||||
// 不带 text:范围里的这一项写的是文档自己记着的判定语,正文这份是不是封存的那一份按工件 id 认
|
||||
segment: { id: segmentId, kind: 'analysis' },
|
||||
}))
|
||||
: api.evidence.segment(runId, segmentId, { report }))),
|
||||
// 最近一次运行 → 它封存范围内的报告核对(report.checked)。审计接口的 reports 带着结论句策略(claims,
|
||||
// 章上「无证据」要不要算没挂依据的结论句靠它);只要 reports,所以只取最小的「可疑实体」那一组行。
|
||||
// 老后端没有审计接口时退回证据图(没有 claims,没挂依据的结论句不计入)。没有运行、没有报告都是空表,不画章
|
||||
|
||||
@@ -5,7 +5,8 @@ import {
|
||||
} from '@xyflow/react'
|
||||
import { api, streamCopilot, streamRun } from '../api/client'
|
||||
import { copilotReceipt, mergeNodeConfig, toolChangesOf } from '../canvas/copilotMerge'
|
||||
import { connectMergeInput } from '../canvas/mergeInputs'
|
||||
import { connectMergeInput, isQueryNode } from '../canvas/mergeInputs'
|
||||
import { connectAnalysisInput } from '../canvas/analysisItems'
|
||||
import { contentSig, isMissingEndpoint, normalizeUpgrade } from '../canvas/issues'
|
||||
import { NODE_DEFS, sourceHandles } from '../canvas/nodeDefs'
|
||||
import { toast } from '../components/ui'
|
||||
@@ -1420,8 +1421,9 @@ export const useStudio = create<StudioState>((set, get) => ({
|
||||
onConnect: (conn) => {
|
||||
if (locked(get)) return
|
||||
commit(set, get, '连线')
|
||||
// 查询节点连到合并查询:顺手把它加成合并的输入(别名取有意义的短名),和连线同一步撤销
|
||||
// 查询节点连到合并查询:顺手把它加成合并的输入(别名取有意义的短名);连到分析卡:还没选输入的第一项选上它。和连线同一步撤销
|
||||
const nodes = connectMergeInput(get().nodes, conn.source, conn.target)
|
||||
?? connectAnalysisInput(get().nodes, conn.source, conn.target, isQueryNode)
|
||||
set({
|
||||
edges: addEdge({ ...conn, type: 'flow' }, get().edges),
|
||||
...(nodes ? { nodes } : {}),
|
||||
|
||||
+256
-5
@@ -1,7 +1,7 @@
|
||||
export type NodeType =
|
||||
| 'input' | 'output' | 'llm' | 'agent' | 'supervisor' | 'tool' | 'code' | 'merge'
|
||||
| 'branch' | 'loop' | 'subgraph' | 'memory' | 'retrieve' | 'transform'
|
||||
| 'human' | 'validate' | 'metrics' | 'report' | 'dual_check' | 'challenge'
|
||||
| 'human' | 'validate' | 'metrics' | 'analysis' | 'report' | 'dual_check' | 'challenge'
|
||||
|
||||
export interface GraphNode {
|
||||
id: string
|
||||
@@ -1771,9 +1771,9 @@ export interface EvidenceCitation {
|
||||
ref?: string
|
||||
/** 目录里的别名,如 m:gmv、i:week、Q1 */
|
||||
alias?: string
|
||||
/** 引文:hit 是检索快照里第几条命中,start / end 是引文在那条原文里的码点位置 */
|
||||
/** 引文:hit 是检索快照里第几条命中,start / end 是引文在那条原文里的码点位置;分析结论的具名的数:key([[a:A1.top_share]]) */
|
||||
locator?: { metric?: string; field?: string; row?: number; column?: string; table?: string
|
||||
hit?: number; start?: number; end?: number }
|
||||
hit?: number; start?: number; end?: number; key?: string }
|
||||
eid?: string
|
||||
/** metric / input / cell / table / column / quote / query */
|
||||
kind?: string
|
||||
@@ -2008,8 +2008,15 @@ export interface EvidenceBlock {
|
||||
}
|
||||
|
||||
export interface EvidenceViolation {
|
||||
/** uncited_number / unresolved_ref / render_mismatch / eid_mismatch / … */
|
||||
/**
|
||||
* uncited_number / unresolved_ref / render_mismatch / eid_mismatch / …;分析能力一轮的说法违规:analysis_claim_uncited
|
||||
* (判断词未挂分析结论)、analysis_claim_mismatch(判断与分析结论不符)、causal_unsupported(因果说法没有依据)
|
||||
*/
|
||||
code: string
|
||||
/** 说法违规:判断词的类(source、anomaly、causal……)、要挂的算子、所挂的分析结论编号 */
|
||||
claim?: string
|
||||
op?: string
|
||||
analyses?: string[]
|
||||
message?: string
|
||||
span?: [number, number]
|
||||
text?: string
|
||||
@@ -2021,6 +2028,8 @@ export interface EvidenceViolation {
|
||||
}
|
||||
|
||||
export interface EvidenceStats {
|
||||
/** 说法违规几处(只有记了分析说法核对的文档有) */
|
||||
analysis_claims?: number
|
||||
units?: number
|
||||
segments?: number
|
||||
claims?: number
|
||||
@@ -2062,6 +2071,10 @@ export interface EvidenceDocData {
|
||||
violations?: EvidenceViolation[]
|
||||
/** 四期:写作时结论句策略是 judge 才有 */
|
||||
judge?: EvidenceJudgeSummary
|
||||
/** 分析能力一轮:报告节点核分析说法时记下的处置(check / strict)和说法表版本;老文档没有 */
|
||||
analysis_claims?: { mode?: string; lexicon?: number }
|
||||
/** 系统写的「分析范围」:这次有分析结论、报告节点没关掉时才有 */
|
||||
analysis_scope?: AnalysisScope
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2122,7 +2135,8 @@ export interface EvidenceGraph {
|
||||
challenge_verdicts?: EvidenceChallengeVerdicts }[]
|
||||
evidence?: { alias?: string; eid?: string; kind?: string; label?: string; node_id?: string; artifact?: string
|
||||
sealed?: boolean; cited_by?: string[]; report?: string }[]
|
||||
edges?: { from: string; to: string; rel: string }[]
|
||||
/** cites(片段 → 证据)、supports(句子 → 依据)、derived_from(分析结论 → 它的输入 Q、下钻的上一层 A);report 是哪份报告的边 */
|
||||
edges?: { from: string; to: string; rel: string; report?: string }[]
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2371,6 +2385,207 @@ export interface EvidenceUntraced {
|
||||
type: string | null
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 分析能力一轮(docs/design/analysis-round):分析结论在证据里的样子。形状照服务端 api/evidence.py 的 _analysis_chain、
|
||||
// _comparability_view,报告文档的 analysis_scope(analysis.contract.ScopeBlock),出具声明的 analysis_claims / comparability /
|
||||
// untraced(engine/nodes/io.py)。判定语、判定标准、原因、附带说明、代入式、闭合核对的数都是服务端写好的字,界面照原样显示
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 分析结论的判定:判定码、点名的段(一段一个列表,多维时几个值;乘积拆解是因子名)、方向 */
|
||||
export interface AnalysisVerdict {
|
||||
code?: string
|
||||
subjects?: (string | number | null)[][]
|
||||
direction?: 'up' | 'down' | null
|
||||
}
|
||||
|
||||
/** 附带说明:一种说法,服务端渲染好的一句 */
|
||||
export interface AnalysisCaveat { code?: string; text?: string }
|
||||
|
||||
/** 可比性检查现查的一条:一列的实际范围(table、column、min、max),或按运行当天现算的界(expr、value) */
|
||||
export interface AnalysisProbe {
|
||||
source?: string
|
||||
table?: string
|
||||
column?: string
|
||||
min?: string | null
|
||||
max?: string | null
|
||||
basis?: 'live' | 'profile' | 'observed' | string
|
||||
at?: string
|
||||
expr?: string
|
||||
value?: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* 出处链里分析结论的六步(step 依次是 analysis、analysis_method、analysis_calc、analysis_input(每份输入一步)、
|
||||
* analysis_recompute、analysis_seal)共用的形状:每一步只带自己那几项
|
||||
*/
|
||||
export interface EvidenceAnalysisStep {
|
||||
step: string
|
||||
alias?: string
|
||||
// ---- analysis:判定 ----
|
||||
op?: string
|
||||
mode?: string | null
|
||||
/** 「变化拆解(可加)」:服务端 contract.method_label */
|
||||
method_label?: string
|
||||
/** card 分析卡、agent Agent 现场做的、metric 口径卡执行时自动做的可比性检查 */
|
||||
origin?: 'card' | 'agent' | 'metric' | string
|
||||
item?: string
|
||||
call_id?: string
|
||||
node_id?: string | null
|
||||
label?: string | null
|
||||
artifact?: string | null
|
||||
eid?: string
|
||||
eid_ok?: boolean
|
||||
/** 这一处引用的是结论的哪一项:判定语、具名的数(key)、结果表的一格(row、column) */
|
||||
cited?: { what?: 'phrase' | 'value' | 'cell' | string; key?: string; row?: number; column?: string; raw?: unknown; conv?: string }
|
||||
rendered?: string
|
||||
render_ok?: boolean
|
||||
hash_ok?: boolean | null
|
||||
status?: string
|
||||
reason_code?: string | null
|
||||
reason?: string | null
|
||||
phrase?: string
|
||||
criterion?: string
|
||||
verdict?: AnalysisVerdict | null
|
||||
caveats?: AnalysisCaveat[]
|
||||
hypothesis?: string
|
||||
hypothesis_note?: string
|
||||
note?: string
|
||||
// ---- analysis_method:方法、参数、实际用的阈值、现查结果 ----
|
||||
method?: string
|
||||
params?: Record<string, unknown>
|
||||
settings?: { key: string; label?: string; value: unknown }[]
|
||||
probes?: AnalysisProbe[]
|
||||
// ---- analysis_calc:具名的数、代入式、结果表 ----
|
||||
values?: { key: string; raw?: unknown; rendered?: string; cited?: boolean }[]
|
||||
formulas?: { label?: string; text?: string }[]
|
||||
table?: {
|
||||
columns: string[]
|
||||
labels?: Record<string, string>
|
||||
total_rows?: number
|
||||
row_index?: number[]
|
||||
rows: unknown[][]
|
||||
masked?: string[]
|
||||
highlight?: { cells?: [number, string][] }
|
||||
window_truncated?: boolean
|
||||
}
|
||||
// ---- analysis_input:一份输入 ----
|
||||
/** 这一步是哪份结论的输入 */
|
||||
of?: string
|
||||
ref?: string
|
||||
role?: string
|
||||
role_label?: string
|
||||
columns?: string[]
|
||||
rows?: 'all' | number[]
|
||||
row?: number
|
||||
column?: string
|
||||
value?: string | null
|
||||
/** 输入落到报告目录的哪个 Q */
|
||||
query?: string | null
|
||||
sealed?: boolean
|
||||
/** headline 那一格和结论里总数的闭合核对:mode 可加对各段之和,比率对各段分子之和 ÷ 分母之和 */
|
||||
closure?: { mode?: string; total_key?: string; total?: string; headline?: string; closed?: boolean }
|
||||
// ---- analysis_recompute:复算(服务端算好的那一句) ----
|
||||
text?: string
|
||||
// ---- analysis_seal:封存 ----
|
||||
ledger?: boolean
|
||||
/** metric_set:口径卡指标上的可比性结论,记在指标集里、随卡封存 */
|
||||
via?: string
|
||||
}
|
||||
|
||||
/** 指标步骤上的两期可比性(api/evidence._comparability_view):判定、判定语、原因,连同那份可比性结论的出处链 */
|
||||
export interface EvidenceComparability {
|
||||
verdict?: 'comparable' | 'conditional' | 'incomparable' | string
|
||||
phrase?: string
|
||||
reasons?: string[]
|
||||
artifact?: string | null
|
||||
hash_ok?: boolean | null
|
||||
sealed?: boolean
|
||||
method?: string
|
||||
criterion?: string
|
||||
caveats?: AnalysisCaveat[]
|
||||
probes?: AnalysisProbe[]
|
||||
/** 判定 → 方法 → 计算 → 输入 → 复算 → 封存(两份输入快照的查询步骤指标链里已经有了,不再给) */
|
||||
steps?: EvidenceAnalysisStep[]
|
||||
}
|
||||
|
||||
/** 报告文档里系统写的「分析范围」的一条(contract.ScopeItem) */
|
||||
export interface AnalysisScopeItem {
|
||||
alias?: string
|
||||
op?: string
|
||||
mode?: string | null
|
||||
/** 拆解的维度(给人看的叫法) */
|
||||
dims?: string[]
|
||||
verdict?: string | null
|
||||
phrase?: string
|
||||
/** 下钻:上一层的编号 */
|
||||
parent?: string | null
|
||||
reason?: string | null
|
||||
}
|
||||
|
||||
/** 报告文档的 analysis_scope(contract.ScopeBlock):不进正文、不过裸数字和说法核对,随文档封存 */
|
||||
export interface AnalysisScope {
|
||||
phenomena?: AnalysisScopeItem[]
|
||||
decomposed?: AnalysisScopeItem[]
|
||||
excluded?: AnalysisScopeItem[]
|
||||
refused?: AnalysisScopeItem[]
|
||||
/** 候选维度里没拆过的叫法;null 是候选维度核对不了(看 note) */
|
||||
not_decomposed?: string[] | null
|
||||
note?: string | null
|
||||
/** 这次做了几次差异检验 */
|
||||
tests?: number
|
||||
/** 检验校正过没有:只做了一次为 true,不止一次为 false,没做为 null */
|
||||
corrected?: boolean | null
|
||||
}
|
||||
|
||||
/** 出具声明的 analysis_claims:处置、几处、记没记缺口、按种类的计数、前几处(同报告文档的说法违规) */
|
||||
export interface IssuanceAnalysisClaims {
|
||||
mode?: 'check' | 'strict' | string
|
||||
count?: number
|
||||
counts?: Record<string, number>
|
||||
counted?: boolean
|
||||
violations?: EvidenceViolation[]
|
||||
}
|
||||
|
||||
/** 出具声明的 comparability:两期有条件可比、不可比的指标,一条一个 */
|
||||
export interface IssuanceComparability {
|
||||
metric?: string
|
||||
name?: string
|
||||
verdict?: string
|
||||
phrase?: string
|
||||
reasons?: string[]
|
||||
artifact?: string
|
||||
}
|
||||
|
||||
/** 出具声明的 untraced:报告引用的指标里输入追不到原始数据的,counted 是记了缺口(受管级别的正式运行) */
|
||||
export interface IssuanceUntraced {
|
||||
metrics?: { metric?: string; name?: string; stops?: { path?: string; node_id?: string | null; label?: string | null; type?: string | null }[] }[]
|
||||
counted?: boolean
|
||||
}
|
||||
|
||||
/** Agent 分析工具 tool.end 的 analysis(服务端 tools/analysis.event_view):preview 只是结论的前一截,判定语从这里读 */
|
||||
export interface AnalysisEventView {
|
||||
/** 这份结论在本节点的编号(「【分析 An】」那个);不记台账的执行没有 */
|
||||
alias?: string | null
|
||||
op?: string
|
||||
mode?: string | null
|
||||
status?: 'ok' | 'refused' | string
|
||||
verdict?: string | null
|
||||
direction?: string | null
|
||||
phrase?: string
|
||||
reason_code?: string | null
|
||||
}
|
||||
|
||||
/** 分析卡的一项(节点配置 items[i],engine/schema.analysis_issues 校验) */
|
||||
export interface AnalysisItem {
|
||||
id?: string
|
||||
op?: string
|
||||
mode?: string | null
|
||||
/** 要分析的上游查询节点(调用数据库查询工具的「调用工具」节点,或「合并查询」);两份查询时写在 params 的 base_query、target_query */
|
||||
from?: string
|
||||
params?: Record<string, any>
|
||||
hypothesis?: string
|
||||
}
|
||||
|
||||
export interface EvidenceStep extends Omit<EvidenceInput, 'status'> {
|
||||
step: string
|
||||
/**
|
||||
@@ -2477,6 +2692,10 @@ export interface EvidenceStep extends Omit<EvidenceInput, 'status'> {
|
||||
merge?: EvidenceMerge
|
||||
/** 这一步是哪次合并查询的输入(合并结果在目录里的编号):排在那个合并步骤后面,高亮的是追到的格 */
|
||||
merged_into?: string
|
||||
/** query:这一步是哪份分析结论的输入(结论在目录里的编号 A…):接在那份结论的输入后面 */
|
||||
input_of?: string
|
||||
/** metric:跨两份同形查询算的环比、同比,口径卡执行时自动做的可比性检查。没做过检查的指标没有这个键 */
|
||||
comparability?: EvidenceComparability
|
||||
// ---- entity:表或字段(三期)----
|
||||
/** entity:table / column */
|
||||
kind?: string
|
||||
@@ -4371,12 +4590,38 @@ export interface RunCompareQuery {
|
||||
}
|
||||
|
||||
/** GET /runs/{id}/compare?base=。任一未封存或封存核对不一致 409;不是同一工作流、是同一次运行 422 */
|
||||
/** 运行对比里分析卡的一边(analysis.end 那一项):没有这一项为 null */
|
||||
export interface RunCompareAnalysisSide {
|
||||
status?: string | null
|
||||
verdict?: string | null
|
||||
direction?: string | null
|
||||
phrase?: string
|
||||
artifact?: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* 运行对比里分析卡的一项(engine/compare._analyses):两次运行的分析卡按节点和项的标识对齐。change:same 判定和判定语都一样、
|
||||
* verdict 状态或判定变了、phrase 判定一样而判定语里的数变了、added / removed 只在一边有
|
||||
*/
|
||||
export interface RunCompareAnalysis {
|
||||
node_id: string
|
||||
title?: string
|
||||
item: string
|
||||
op?: string | null
|
||||
mode?: string | null
|
||||
base: RunCompareAnalysisSide | null
|
||||
target: RunCompareAnalysisSide | null
|
||||
change: 'same' | 'verdict' | 'phrase' | 'added' | 'removed' | string
|
||||
}
|
||||
|
||||
export interface RunComparison {
|
||||
target: RunCompareRef
|
||||
base: RunCompareRef
|
||||
summary: RunCompareSummary
|
||||
template: RunCompareTemplate
|
||||
metrics: RunCompareMetric[]
|
||||
/** 分析卡按项对齐(分析能力一轮);老服务端没有 */
|
||||
analyses?: RunCompareAnalysis[]
|
||||
queries: RunCompareQuery[]
|
||||
notes: string[]
|
||||
}
|
||||
@@ -4505,6 +4750,12 @@ export interface DualCheckConfig {
|
||||
enabled?: boolean | null
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置里的 analysis 一组(GET /settings 给的是补齐缺省之后的完整一组):判定用的阈值、Agent 每次执行最多分析几次、最多下钻
|
||||
* 几层、列出前几段。键、叫法、范围见 lib/termsAnalysis(照服务端 analysis/contract.py)
|
||||
*/
|
||||
export type AnalysisSettings = Record<string, number>
|
||||
|
||||
/** 设置里的 verify 一组(GET /settings 给的是补齐默认之后的完整一组;上限为 null 表示不限) */
|
||||
export interface VerifySettings {
|
||||
provider: string | null
|
||||
|
||||
Reference in New Issue
Block a user