import test from 'node:test'; import assert from 'node:assert/strict'; import { agentReportVisuals, buildAgentReportLayout, agentReportPrimary, agentReportChartWidth, agentReportSupplementary, partitionAgentReportVisuals } from '../src/agent/agentReportLayout.ts'; import { parseAnalysisVisuals } from '../src/analysisVisualsModel.ts'; const trend = (metric, scope = {}, values = [.9515, .9529, .9546]) => ({ id: metric, metric, type: 'line', unit: 'ratio', sectionKey: 'trend', title: metric, subtitle: '', period: { year: 2026, monthStart: 8, monthEnd: 10 }, originTurnId: 'turn-layout', requiredFields: [], coverage: { totalRows: 3, returnedRows: 3, truncated: false }, scope: { year: 2026, monthStart: 8, monthEnd: 10, ...scope }, categories: ['2026-08', '2026-09', '2026-10'].map(key => ({ key, label: key })), series: [{ key: metric, label: metric, values }], evidenceRefs: [], }); test('an authorized period aggregate populates the header and the report keeps authored chapter order', () => { const markdown = `9月需要关注。\n\n## 趋势与阶段对照\n\n本期走势。\n\n## 月度明细\n\n| 月份 | 综合合格率 | 黑片合格率 | 亮片合格率 |\n|---|---|---|---|\n| 2026-08 | 95.15% | 97.31% | 97.77% |\n| 期间汇总 | 95.35% | 97.57% | 97.73% |`; const result = buildAgentReportLayout(markdown, [trend('composite_rate'), trend('black_rate', { stage: 'black' }), trend('bright_rate', { stage: 'bright' })]); assert.equal(result.lead, '9月需要关注。'); assert.deepEqual(result.sections.map(section => section.label), ['趋势与阶段对照', '月度明细']); assert.deepEqual(result.metrics.map(metric => metric.value), ['95.35', '97.57', '97.73']); assert.equal(result.sections[0].charts.paired, true); assert.equal(result.sections[0].charts.stats[0].value, '+0.31'); }); test('unmatched chart scopes cannot be paired and missing months cannot produce trend summaries', () => { const monthly = trend('composite_rate', {}, [.9515, null, .9546]); const result = buildAgentReportLayout('## 月度趋势\n\n按月观察。', [monthly, trend('black_rate', { department: '另一个范围' })]); assert.equal(result.sections[0].charts.paired, false); assert.deepEqual(result.sections[0].charts.stats, []); assert.deepEqual(result.metrics, []); }); test('two-month comparison uses unrounded signed values from the bound figure', () => { const visual = { ...trend('composite_rate'), type: 'column', sectionKey: 'overview', comparisonPeriod: { year: 2026, month: 9 }, categories: [{ key: 'comparison', label: '2026-09' }, { key: 'current', label: '2026-10' }], series: [{ key: 'composite_rate', values: [.9803797366305572, .977442975471237] }], }; const result = buildAgentReportLayout('下降0.29个百分点。\n\n## 口径说明\n\n同范围比较。', [visual]); assert.equal(result.lead, '下降0.29个百分点。'); assert.deepEqual(result.metrics.map(metric => metric.value), ['98.04', '97.74', '-0.29']); }); test('a checklist keeps the requested chapters and does not acquire invented metrics or charts', () => { const markdown = '先核对计量记录。\n\n## 现场核查\n\n1. 核对工位。\n2. 核对批次。\n\n## 待证实\n\n待核实现场。'; const result = buildAgentReportLayout(markdown, []); assert.deepEqual(result.sections.map(section => section.label), ['现场核查', '待证实']); assert.match(result.sections[0].markdown, /1\. 核对工位。\n2\. 核对批次。/); assert.ok(result.sections.every(section => section.charts.figures.length === 0)); assert.deepEqual(result.metrics, []); }); test('the live model stage-row aggregate table produces the same three header metrics without rewriting its text', () => { const markdown = `## 二、期间汇总正式指标(公司总体,1—10月聚合值) | 阶段 | 合格率 | 报废率 | 投入重量 | |---|---:|---:|---:| | 综合 | **95.35%** | — | — | | 黑片 | 97.57% | 2.46% | 12,129,113.00 kg | | 亮片 | 97.73% | 2.27% | 12,702,288.25 kg |`; const result = buildAgentReportLayout(markdown, []); assert.deepEqual(result.metrics.map(({ label, value }) => ({ label, value })), [ { label: '综合合格率', value: '95.35' }, { label: '黑片合格率', value: '97.57' }, { label: '亮片合格率', value: '97.73' }, ]); assert.equal(result.sections.map(section => section.markdown).join(''), markdown); }); test('a stage table for a single month cannot be mistaken for the period aggregate', () => { const markdown = `## 5月阶段对照 | 阶段 | 合格率 | |---|---:| | 综合 | 95.12% | | 黑片 | 97.31% | | 亮片 | 97.75% |`; assert.deepEqual(buildAgentReportLayout(markdown, []).metrics, []); }); test('a model-authored aggregate caption binds its following indicator-value table', () => { const markdown = '## 核心发现\n\n**期间汇总正式合格率**\n\n| 指标 | 正式值 |\n|---|---|\n| 综合合格率 | 95.35% |\n| 黑片合格率 | 97.57% |\n| 亮片合格率 | 97.73% |'; assert.deepEqual(buildAgentReportLayout(markdown, []).metrics.map(metric => metric.value), ['95.35', '97.57', '97.73']); }); test('an explicit period lead can present all three authored rates without a duplicate table', () => { const markdown = '2026年1—10月期间,综合合格率为 **95.35%**,黑片合格率为 **97.57%**,亮片合格率为 **97.73%**。\n\n## 趋势与阶段对照\n\n5月需要关注。'; const layout = buildAgentReportLayout(markdown, []); assert.deepEqual(layout.metrics.map(metric => metric.value), ['95.35', '97.57', '97.73']); assert.equal(layout.lead, markdown.split('\n\n')[0]); }); test('the two stage trends share one report panel with their original tenors and scopes preserved', () => { const inputs = [trend('composite_rate'), { ...trend('black_rate', { stage: 'black' }), chartable: true, requiredFields: [] }, { ...trend('bright_rate', { stage: 'bright' }), chartable: true, requiredFields: [] }]; const before = JSON.stringify(inputs); const panels = agentReportVisuals(inputs); assert.equal(panels.length, 2); assert.deepEqual(panels[1].series.map(series => series.key), ['black_rate', 'bright_rate']); assert.deepEqual(panels[1].series[1].values, inputs[2].series[0].values); assert.equal(parseAnalysisVisuals([panels[1]], 1).visuals[0]?.chartable, true); assert.equal(JSON.stringify(inputs), before); assert.equal(buildAgentReportLayout('## 趋势与阶段对照', panels).sections[0].charts.paired, true); const mismatched = { ...inputs[2], scope: { ...inputs[2].scope, department: '其他产业部' } }; assert.equal(agentReportVisuals([inputs[1], mismatched]).length, 2); }); test('a bold-prefixed original introduction becomes the lead exactly once', () => { const lead = '**主要发现:**2026年10月全公司综合合格率为 **95.46%**,黑片合格率97.54%,亮片合格率97.86%;产业部差异见下表。'; const body = '## 产业部差异\n\n保留原文。\n\n---\n\n## 报废结构\n\n原始表格。'; const result = buildAgentReportLayout(`${lead}\n\n${body}`, []); assert.equal(result.lead, lead); assert.equal(result.sections.map(section => section.markdown.trim()).join('\n\n'), body); assert.deepEqual(result.metrics.map(metric => metric.value), ['95.46', '97.54', '97.86']); }); test('company headline metrics never borrow a later department or infer absent stage rates', () => { for (const text of [ '全公司综合合格率95.46%;产业部黑片合格率97.54%,亮片合格率97.86%。', '全公司产业部对比:综合合格率95.46%,黑片合格率97.54%,亮片合格率97.86%。', '综合合格率95.46%,黑片合格率97.54%,亮片合格率97.86%。', ]) assert.deepEqual(buildAgentReportLayout(text, []).metrics, []); }); test('an explicit overall stage-column table supplies cards without rewriting shorthand prose', () => { const lead = '期间综合合格率95.35%,黑片、亮片合格率分别为97.57%和97.73%。'; const body = '## 一、总体表现\n\n综合合格率为95.35%。\n\n| 指标 | 黑片 | 亮片 |\n|---|---:|---:|\n| 合格率 | 97.57% | 97.73% |\n| 剔除本部报废后合格率 | — | 97.81% |'; const result = buildAgentReportLayout(lead + '\n\n' + body, []); assert.deepEqual(result.metrics.map(metric => metric.value), ['95.35', '97.57', '97.73']); assert.equal(result.lead, lead); assert.equal(result.sections[0].markdown, body); assert.deepEqual(buildAgentReportLayout(body.replace('总体表现', '5月对照'), []).metrics, []); assert.deepEqual(buildAgentReportLayout(body.replace('综合合格率为95.35%。', '综合合格率为95.35%,综合合格率为95.46%。'), []).metrics, []); }); test('the live stage-row report retains its three stated metrics and authored body', () => { const text='**导读:**全公司综合合格率95.35%,黑片97.57%、亮片97.73%。\n\n## 一、总体表现\n\n期间正式综合合格率为95.35%。\n\n| 阶段 | 投入重量 | 合格率 |\n|---|---:|---:|\n| 黑片 | 100 | 97.57% |\n| 亮片 | 200 | 97.73% |'; const layout=buildAgentReportLayout(text,[]); assert.deepEqual(layout.metrics.map(metric=>metric.value),['95.35','97.57','97.73']); assert.equal(layout.lead+'\n\n'+layout.sections[0].markdown,text); }); test('the primary chart uses an existing composite trend or the available stages without inventing a series', () => { const stages={...trend('black_rate'),id:'stages',series:[{key:'black_rate',values:[.97,.98,.97]},{key:'bright_rate',values:[.98,.97,.98]}]}; const overall=trend('composite_rate'),before=JSON.stringify([stages,overall]); assert.equal(agentReportPrimary([stages,overall]),overall); assert.equal(agentReportPrimary([stages]),stages); assert.equal(agentReportChartWidth(overall,[stages,overall]),660); assert.equal(agentReportChartWidth(stages,[stages,overall]),500); assert.equal(agentReportPrimary([]),undefined); assert.equal(JSON.stringify([stages,overall]),before); }); test('supplementary trends remain primary content when the question requests them', () => { const overall=trend('composite_rate'),scrap=trend('black_scrap_rate'),volume=trend('black_total_weight'); const inputs=[overall,scrap,volume]; assert.equal(agentReportSupplementary(scrap,inputs,'总体质量报告'),true); assert.equal(agentReportSupplementary(volume,inputs,'总体质量报告'),true); assert.equal(agentReportSupplementary(scrap,inputs,'分析报废率变化'),false); assert.equal(agentReportSupplementary(volume,inputs,'分析投入重量变化'),false); assert.equal(agentReportSupplementary(scrap,[scrap],'总体质量报告'),false); }); test('structure reports use formal composition before a monthly weight trend', () => { const monthly = { ...trend('current_scrap_weight'), unit: 'kg' }; const composition = { ...monthly, id: 'categories', type: 'donut', dimension: 'category', sectionKey: 'composition', metric: 'source_defect_weight' }; assert.equal(agentReportPrimary([monthly, composition], '亮片报废结构专题报告'), composition); assert.equal(agentReportSupplementary(monthly, [monthly, composition], '亮片报废结构专题报告'), true); }); test('repeated rankings preserve the requested Top and keep distinct metrics and scopes', () => { const ranking = { ...trend('bright_scrap_weight'), type: 'bar', unit: 'kg', dimension: 'group', sectionKey: 'group', categories: ['a','b','c','d','e'].map(key=>({key,label:key})), series: [{key:'bright_scrap_weight',values:[5,4,3,2,1]}] }; const expanded = { ...ranking, id: 'expanded', categories: [...ranking.categories,{key:'f',label:'f'}], series:[{key:'bright_scrap_weight',values:[5,4,3,2,1,.5]}] }; const copy = { ...ranking, id:'duplicate', evidenceRefs:['another-read'] }; const another = { ...ranking, id:'another-scope',scope:{department:'other'} }; const original = JSON.stringify([ranking,expanded,copy,another]); const figures=agentReportVisuals([ranking,expanded,copy,another], '业务分组Top5对比简报'); assert.deepEqual(figures.map(v=>v.id),[ranking.id,another.id]); assert.equal(JSON.stringify([ranking,expanded,copy,another]),original); }); test('a saved structure report without a formal composition image prefers its actual defect ranking over a trend',()=>{ const monthly={...trend('current_scrap_weight'),unit:'kg'}; const defects={...monthly,id:'defect-bars',type:'bar',dimension:'defect',metric:'source_defect_weight'}; assert.equal(agentReportPrimary([monthly,defects],'亮片报废结构专题报告'),defects); }); test('an available Top10 snapshot displays the requested Top5 without changing saved data or composition',()=>{ const ten={...trend('source_defect_weight'),unit:'kg',type:'bar',dimension:'defect', categories:Array.from({length:10},(_,i)=>({key:String(i),label:'项目'+i})), series:[{key:'source_defect_weight',label:'来源细分重量',values:[10,9,8,7,6,5,4,3,2,1]}],coverage:{totalRows:21,returnedRows:10,truncated:true}}; const pie={...ten,id:'composition',dimension:'category',type:'donut',categories:ten.categories.slice(0,4),series:[{key:'source_defect_weight',label:'正式类别重量',values:[4,3,2,1]}]}; const before=JSON.stringify([ten,pie]);const figures=agentReportVisuals([ten,pie],'亮片报废结构,具体缺陷Top5'); assert.equal(figures[0].categories.length,5);assert.deepEqual(figures[0].series[0].values,[10,9,8,7,6]); assert.equal(figures[0].coverage.returnedRows,5);assert.equal(figures[0].coverage.totalRows,21); assert.equal(figures[1].categories.length,4);assert.equal(JSON.stringify([ten,pie]),before); assert.equal(parseAnalysisVisuals([figures[0]],1).visuals[0]?.chartable,true,'the cropped visual must remain renderable by the export parser'); }); test('report primary and supplementary lists cannot render the same image twice', () => { const black = {...trend('black_total_weight'),unit:'kg'}; const bright = {...trend('bright_total_weight'),unit:'kg'}; const inputs = [black,bright,black]; const {primary,secondary,supplemental}=partitionAgentReportVisuals(inputs,'总体质量分析报告,重点展示月度趋势和黑片亮片报废结构'); const all=[primary,...secondary,...supplemental].filter(Boolean); assert.equal(all.length,2); assert.equal(new Set(all.map(v=>v.id)).size,2); assert.equal(agentReportSupplementary(primary,inputs,'总体质量分析报告,重点展示月度趋势和黑片亮片报废结构'),false); });