不调整顺序<\/li>/);
assert.match(html, /原始值1.52;不能拆开代码<\/code><\/pre>/);
assert.match(html, /缺陷仍需核查(包括料废;责废)。没有依据确认生产原因。/);
const listed = renderToStaticMarkup(React.createElement(AiMarkdown, { content: '- 已核实结论\n\n亮片未完整核实。', layout: 'conclusions' }));
assert.doesNotMatch(listed, /analysis-conclusion-lead/);
});
const narrativeSource = readFileSync(new URL('../src/AnalysisNarrative.tsx', import.meta.url), 'utf8');
const readingSource = narrativeSource.slice(narrativeSource.indexOf('export function ReadingSummary('), narrativeSource.indexOf('\nfunction metricName('));
const ReadingSummary = component(readingSource, 'ReadingSummary', { AiMarkdown });
const hooks = { useMemo: fn => fn(), useState: initial => [initial, () => {}], useRef: initial => ({ current: initial }), useEffect: () => {} };
const conclusionSource = readFileSync(new URL('../src/AnalysisConclusion.tsx', import.meta.url), 'utf8');
const AnalysisConclusion = component(conclusionSource, 'AnalysisConclusion', { AiMarkdown, buildConclusionDocument });
const common = { ...hooks, AiMarkdown, AnalysisConclusion, ReadingSummary, buildAnalysisReadingModel, buildAnalysisNarrative, conclusionMarkdown,
AnalysisVisuals: ({ visuals = [] }) => React.createElement('div', null, visuals.map(visual => React.createElement('figure', { key: visual.id, 'data-chat-visual-id': visual.id }, React.createElement('h3', { className: 'analysis-visual-heading-copy' }, visual.title), React.createElement('p', null, visual.subtitle)))), NarrativeEvidence: () => null, FocusProductTable: () => null,
useCompactRateComparison: () => false, AnalysisProductDrilldown: () => null, resolveProductDrilldown: () => ({ reason: 'test' }) };
const AnalysisNarrative = component(narrativeSource.slice(narrativeSource.indexOf('export function AnalysisNarrative(')), 'AnalysisNarrative', common);
const reportSource = readFileSync(new URL('../src/AnalysisReportNarrative.tsx', import.meta.url), 'utf8');
const AnalysisReportNarrative = component(reportSource, 'AnalysisReportNarrative', { ...common,
reportVisuals: source => source.result?.visuals || source.visuals || [], ReportVisualFigure: ({ visual }) => React.createElement('figure', { 'data-report-visual-id': visual.id }, React.createElement('strong', { className: 'q-report-visual-heading' }, visual.title), React.createElement('figcaption', null, visual.subtitle)), ReportVisualDataTable: ({ visual }) => React.createElement('table', { 'data-report-table-id': visual.id }) });
const renderChat = data => renderToStaticMarkup(React.createElement(AnalysisNarrative, { answer: data.result.answer, visuals: data.result.visuals, question: data.question, turnId: data.id, turn: data }));
const renderReport = data => renderToStaticMarkup(React.createElement(AnalysisReportNarrative, { turn: data, answer: data.result.answer, images: [] }));
const visibleSummary = html => html.match(/([\s\S]*?)<\/div>/)?.[1];
test('comparison readout uses the checked change, preserving rounded stage values and explicit scope', () => {
const sentence='汽车交通2026年9月黑片合格率**97.27%**,较8月的**97.58%**下降**0.30个百分点**。';
const value=checkedConclusionComparison(sentence);
assert.equal(value.change,'-0.30'); assert.equal(value.currentLabel,'汽车交通2026年9月');
assert.equal(value.previousLabel,'8月'); assert.equal(value.current,'97.27%'); assert.equal(value.previous,'97.58%');
for (const invalid of ['9月合格率95.13%。','9月合格率95.13%,较8月95.57%。','9月合格率101.00%,较8月95.57%下降0.44个百分点。']) assert.equal(checkedConclusionComparison(invalid),null);
assert.equal(checkedConclusionComparison('9月合格率0.00%,较8月95.57%下降95.57个百分点。').current,'0.00%');
});
test('conclusion chapters put each authorized figure beside its cited topic, without inventing additional charts', () => {
const data=turn({...summary(),lead:'2026年9月综合合格率95.13%,较8月的95.57%下降0.44个百分点。[Q11111111]',evidence:[
'**产业部变化**(仅作核查方向):\n\n| 产业部 | 变化 |\n| --- | --- |\n| 甲 | 下降0.60个百分点 |\n[Q22222222]',
'**重点规格**:甲规格报废增加128.45 kg。[Q11111111]']});
const figures=[{...chart,id:'department',metric:'rate_drop_pp',dimension:'department',evidenceRefs:['Q22222222']},{...chart,id:'product',metric:'scrap_delta',dimension:'product'}];
const document=buildConclusionDocument(buildAnalysisReadingModel('',[],data.question,data).reading,figures);
assert.equal(document.comparison.change,'-0.44');
assert.deepEqual(document.sections.find(x=>x.title==='产业部变化').visuals.map(v=>v.id),['department']);
assert.deepEqual(document.sections.find(x=>x.title==='重点规格').visuals.map(v=>v.id),['product']);
assert.deepEqual(document.sections.flatMap(x=>x.visuals.map(v=>v.id)),['department','product']);
assert.equal(document.sections.find(x=>x.title==='产业部变化').note,'(仅作核查方向)');
assert.ok(document.sections.every(x=>!x.markdown.includes('[Q')));
const mismatch=buildConclusionDocument(buildAnalysisReadingModel('',[],data.question,data).reading,[{...figures[0],evidenceRefs:['Q11111111']}]);
assert.equal(mismatch.sections.find(x=>x.title==='产业部变化').visuals.length,0);
assert.equal(mismatch.sections.at(-1).visuals[0].id,'department');
});
test('reference-style cards and chapters keep chat/report values, figures and ordering identical without source labels', () => {
const data=turn({...summary(),lead:'2026年9月综合合格率**95.13%**,较8月的**95.57%**下降**0.44个百分点**。[Q11111111]',evidence:['### 重点规格\n\n| 规格 | 变化 |\n| --- | --- |\n| 甲 | 下降0.60个百分点 |\n[Q22222222]']});
data.result.answer=data.result.readingSummary.lead+'\n\n'+data.result.readingSummary.evidence[0];
for(const html of [renderChat(data),renderReport(data)]) {
assert.match(html,/analysis-comparison-current[^>]*>
2026年9月<\/span>95.13%<\/strong>/);
assert.match(html,/-0.44/); assert.match(html,/95.57%/);
assert.equal((html.match(//g)||[]).length,1);
assert.doesNotMatch(html,/Q11111111|Q22222222|关键依据|数据依据|analysis-full-appendix/);
}
const fenced=buildConclusionDocument({...buildAnalysisReadingModel('',[],data.question,data).reading,evidence:['```text\n### 不作为章节\n```'],fullAnswer:''},[]);
assert.equal(fenced.sections.some(x=>x.title==='不作为章节'),false);
});
test('pure chart chapter title is rendered once in chat and report while chart caption and scope remain', () => {
const title = '产品规格报废总重排名';
const ranking = { ...chart, id: 'ranking', type: 'bar', title, unit: 'kg', subtitle: '黑片+亮片',
scope: { year: 2026, month: 9, releaseId: 'release' }, period: { year: 2026, month: 9 }, comparisonPeriod: undefined,
categories: [{ key: 'product-a', label: '规格甲' }], series: [{ key: 'current_scrap_weight', label: '报废总重', values: [65] }],
evidenceRefs: ['Q11111111'], requiredFields: ['black_scrap_weight', 'bright_scrap_weight'], metric: 'current_scrap_weight',
sectionKey: 'product', dimension: 'product', coverage: { totalRows: 20, returnedRows: 1, truncated: true, shareBasis: 'all_scope_weight', denominator: 1000 } };
const data = turn({ ...summary(), lead: '本月重点规格报废情况已核验。[Q11111111]', evidence: [`### ${title}\n\n[Q11111111]`], notices: [], evidenceRefs: ['Q11111111'], visualIds: ['ranking'] });
data.result.answer = `${data.result.readingSummary.lead}\n\n${data.result.readingSummary.evidence[0]}`;
data.result.visuals = [ranking];
data.result.queryEvidenceRefs = ['Q11111111'];
data.plan = { task: { version: 1, kind: 'metrics', visualPreference: 'required', visualType: 'bar', fields: ['scrapWeight'], dimensions: ['product'], stages: [], period: { year: 2026, month: 9 }, comparisonRequired: false, filters: {} } };
for (const html of [renderChat(data), renderReport(data)]) {
assert.equal((html.match(new RegExp(title, 'g')) || []).length, 1, html);
assert.match(html, /黑片+亮片/);
}
const withBody = structuredClone(data);
withBody.result.readingSummary.evidence = [`### ${title}\n\n| 规格 | 报废总重 |\n| --- | --- |\n| 规格甲 | 65 kg |\n[Q11111111]`];
withBody.result.answer = `${withBody.result.readingSummary.lead}\n\n${withBody.result.readingSummary.evidence[0]}`;
for (const html of [renderChat(withBody), renderReport(withBody)]) {
assert.equal((html.match(new RegExp(title, 'g')) || []).length, 2, html);
assert.match(html, //);
assert.match(html, /规格甲/);
}
const semanticTitle = structuredClone(data);
semanticTitle.result.readingSummary.evidence = ['### 重点规格\n\n[Q11111111]'];
semanticTitle.result.answer = `${semanticTitle.result.readingSummary.lead}\n\n${semanticTitle.result.readingSummary.evidence[0]}`;
for (const html of [renderChat(semanticTitle), renderReport(semanticTitle)]) {
assert.match(html, /重点规格/);
assert.equal((html.match(new RegExp(title, 'g')) || []).length, 1, html);
}
});
test('cause summary follows the server semantic selection including late defect clues and exact rate ranking', () => {
const data = turn(), { model, reading } = buildAnalysisReadingModel(data.result.answer, data.result.visuals, data.question, data);
const before = JSON.stringify(model);
assert.equal(reading.lead, summary().lead);
assert.deepEqual(reading.evidence, summary().evidence);
assert.deepEqual(reading.notices, summary().notices);
assert.equal(reading.fullAnswer, data.result.answer);
assert.equal(reading.hasAppendix, true); assert.equal(reading.visualCount, 1);
assert.equal(JSON.stringify(model), before);
assert.match(reading.lead, /缺角/); assert.match(reading.evidence[1], /乙组.*第一.*甲组第二/);
});
test('chat and report show conclusions once without evidence or an appendix', () => {
const data = turn(); data.result.answer = summary().lead + '\n\n' + summary().evidence.join('\n\n') + '\n\n## 完整统计依据\n\n第四段原因线索、完整代码块。';
assert.equal(visibleSummary(renderChat(data)), visibleSummary(renderReport(data)));
for (const html of [renderChat(data), renderReport(data)]) {
assert.match(html, /缺角报废增加128.45/);
assert.doesNotMatch(html, /完整代码块|第四段原因线索|analysis-full-appendix|关键依据|数据依据|Q11111111|Q22222222|analysis-evidence-ref/);
assert.equal((html.match(/9月合格率下降,缺角报废增加/g) || []).length, 1);
assert.equal((html.match(/亮片未覆盖全部月份,不能据此判定生产原因/g) || []).length, 1);
}
});
test('historical paragraphs remain complete and visible without synthesized core summary or appendix', () => {
const data = turn(undefined); delete data.result.readingSummary;
const reading = analysisReadingSummary(data.result.answer, buildAnalysisNarrative(data.result.answer, [chart]));
assert.equal(reading.hasAppendix, false); assert.equal(reading.lead, ''); assert.deepEqual(reading.evidence, []);
assert.equal(reading.fullAnswer, data.result.answer);
for (const html of [renderChat(data), renderReport(data)]) {
assert.doesNotMatch(html, /analysis-reading-summary|analysis-full-appendix/);
for (const fragment of ['第二段原始内容', '第三段原始内容', '第四段原因线索', '末行', '完整代码块']) assert.match(html, new RegExp(fragment));
}
});
test('malformed summaries and undeclared or unauthorized refs safely fall back to all original paragraphs', () => {
const cases = [null, [], {}, { ...summary(), version: 2 }, { ...summary(), lead: '' }, { ...summary(), evidence: 'bad' },
{ ...summary(), notices: [null] }, { ...summary(), extra: 'untrusted' }, { ...summary(), evidenceRefs: ['Q99999999'] },
{ ...summary(), lead: '伪造依据[Q99999999]' }, { ...summary(), lead: 'illegal\u0000text' }];
for (const invalid of cases) {
const data = turn(invalid);
assert.equal(parseServerReadingSummary(data), null, JSON.stringify(invalid));
for (const html of [renderChat(data), renderReport(data)]) {
assert.doesNotMatch(html, /analysis-reading-summary|analysis-full-appendix/);
assert.match(html, /第四段原因线索/); assert.match(html, /完整代码块/);
}
}
});
test('current empty allowlists or redacted nested results cannot borrow stale flattened data or charts', () => {
const data = turn(); data.result.queryEvidenceRefs = [];
assert.equal(parseServerReadingSummary(data), null);
assert.equal(parseServerReadingSummary({ ...turn().result, result: { answer: '当前权限已收窄', readingSummary: null, queryEvidenceRefs: [] } }), null);
assert.equal(parseServerReadingSummary({ ...turn().result, result: { answer: '当前权限已收窄' } }), null);
});
test('older server refs remain compatible while summary-only refs get usable evidence anchors', () => {
const data = turn(); delete data.result.queryEvidenceRefs;
data.result.evidence = [{ evidenceRef: 'Q22222222' }];
assert.deepEqual(parseServerReadingSummary(data), summary());
data.result.answer = '全部原文,不含摘要独有的缺陷引用。';
const { model } = buildAnalysisReadingModel(data.result.answer, data.result.visuals, data.question, data);
assert.ok(model.evidence.some(entry => entry.ref === 'Q22222222'));
assert.ok(model.evidenceLabels.Q22222222);
delete data.result.evidence; data.result.results = [{ evidenceRef: 'Q22222222' }];
assert.deepEqual(parseServerReadingSummary(data), summary());
});
test('summary content renders as escaped text without executing HTML', () => {
const data = turn({ ...summary(), lead: ' [Q11111111]' }); data.result.answer = data.result.readingSummary.lead;
for (const html of [renderChat(data), renderReport(data)]) {
assert.match(html, /<script>alert\(1\)<\/script>/);
assert.doesNotMatch(html, /