|
- import fs from 'node:fs'
- import path from 'node:path'
- import { fileURLToPath } from 'node:url'
-
- // Browser runs own the evidence files. This generator only writes index.html
- // and report.md. Missing evidence remains pending, never an inferred pass.
- // Each JSON may use { status, title, checks/evidence/results/tests: [...],
- // projects: [...], commands: [...], limitations: [...] }. Unknown shapes remain
- // available as sanitized JSON details rather than being silently discarded.
- const reportDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../reports/training-live-20260905')
- fs.mkdirSync(reportDir, { recursive: true })
- const array = value => Array.isArray(value) ? value : value == null ? [] : [value]
- const sensitiveKey = /password|passwd|secret|token|ticket|authorization|cookie|signature|credential|api[_-]?key|username|loginName|accountName|headers|storageState/i
- const cleanText = value => String(value ?? '')
- .replace(/\bBearer\s+[^\s"'<>]+/gi, 'Bearer [已隐藏]')
- .replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi, '$1[已隐藏]@')
- .replace(/\b((?:access|refresh)?[_-]?token|password|passwd|secret|uploadTicket|signature|api[_-]?key|X-Amz-(?:Signature|Credential|Security-Token))\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;&}]+)/gi, '$1=[已隐藏]')
- .replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g, '[已隐藏]')
- function sanitize(value) {
- if (typeof value === 'string') return cleanText(value)
- if (Array.isArray(value)) return value.map(sanitize)
- if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value)
- .filter(([key]) => !sensitiveKey.test(key)).map(([key, item]) => [key, sanitize(item)]))
- return value
- }
- const html = value => cleanText(value).replace(/[&<>"']/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char])
- const md = value => cleanText(value).replace(/[|\[\]*_`<>]/g, char => `\\${char}`).replace(/\r?\n/g, ' ')
- const pretty = value => typeof value === 'string' ? value : JSON.stringify(value, null, 2)
- const recorded = value => value === undefined || value === null || value === '' ? '待最终证据' : value
- const status = value => {
- const normalized = String(value ?? '').toUpperCase()
- return normalized === 'PASS' || normalized === 'PASSED' ? 'PASS'
- : normalized === 'FAIL' || normalized === 'FAILED' ? 'FAIL' : 'PENDING'
- }
- const statusLabel = value => ({ PASS: '通过', FAIL: '失败', PENDING: '待补充证据' })[status(value)]
- const statusClass = value => status(value).toLowerCase()
-
- const sourceDefinitions = [
- { file: 'final-evidence.json', title: '真实编排、保存、发布及重新打开' },
- { file: 'readonly-evidence.json', title: '独立浏览器只读重开与真实画面验证' },
- { file: 'error-evidence.json', title: '失败、冲突与并发处理' },
- ]
- const sources = sourceDefinitions.map(definition => {
- const absolute = path.join(reportDir, definition.file)
- const data = fs.existsSync(absolute)
- ? sanitize(JSON.parse(fs.readFileSync(absolute, 'utf8').replace(/^\uFEFF/, ''))) : null
- const checks = data ? array(data.checks || data.evidence || data.results || data.tests) : []
- const assessed = checks.filter(item => item && item.superseded !== true && item.historical !== true)
- const sourceStatus = assessed.some(item => status(item.status) === 'FAIL') ? 'FAIL'
- : status(data?.status) !== 'PENDING' ? status(data.status)
- : assessed.length && assessed.every(item => status(item.status) === 'PASS') ? 'PASS'
- : assessed.some(item => status(item.status) === 'FAIL') ? 'FAIL' : 'PENDING'
- return { ...definition, data, checks, status: sourceStatus }
- })
- const final = sources[0].data || {}
- const projects = array(final.projects || final.retainedProjects || final.trainingProjects)
- const reopenedProjects = array(sources[1].data?.projects)
- const versionMismatches = projects.flatMap(project => {
- const expected = project.publishedVersionId || project.finalVersionId || project.currentVersionId
- if (!expected || !sources[1].data) return []
- const reopened = reopenedProjects.find(item => String(item.id || item.projectId) === String(project.id || project.projectId))
- const actual = reopened?.publishedVersionId || reopened?.currentVersionId
- return String(expected) === String(actual) ? [] : [{ projectId: project.id || project.projectId, expected, actual: actual || '未记录' }]
- })
- if (versionMismatches.length && sources[1].status !== 'FAIL') sources[1].status = 'PENDING'
- const allChecks = sources.flatMap(source => source.checks)
- .filter(item => item && item.superseded !== true && item.historical !== true)
- const passedChecks = allChecks.filter(item => status(item.status) === 'PASS').length
- const failedChecks = allChecks.filter(item => status(item.status) === 'FAIL').length
- const pendingChecks = allChecks.length - passedChecks - failedChecks
- const overall = sources.some(source => source.status === 'FAIL') || failedChecks ? 'FAIL'
- : sources.every(source => source.status === 'PASS') && !pendingChecks ? 'PASS' : 'PENDING'
- const commands = sources.flatMap(source => array(source.data?.commands))
- const limitations = [...new Map(sources.flatMap(source => array(source.data?.limitations || source.data?.followUpIssues))
- .map(item => [pretty(item), item])).values()]
- const generatedAt = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
-
- const history = [
- { path: 'screenshots/01-before-scene-catalog.png', caption: '过程记录:初建训练仍显示默认液压模板,仅记录起点,不作为故障对照或最终通过证据。' },
- { path: 'screenshots/02-published-scenes.png', caption: '过程记录:打开已发布场景目录。最终版本和固定依赖以最终证据为准。' },
- { path: 'screenshots/03-truck-bound.png', caption: '过程记录:首次绑定卡车时仍有 8 个旧模板步骤;不代表最终两步编排通过。' },
- { path: 'screenshots/04-truck-saved.png', caption: '过程记录:卡车训练阶段性保存;最终步骤、状态、版本和封面以最终证据为准。' },
- ].filter(item => fs.existsSync(path.join(reportDir, item.path)))
- const historyPaths = new Set(history.map(item => item.path))
- const screenshotPattern = /^screenshots\/[\w\W]+\.(?:png|jpe?g|webp)$/i
- const imagePaths = new Set()
- function imageRefs(value, inheritedCaption = '') {
- if (!value) return []
- if (typeof value === 'string') return screenshotPattern.test(value.replaceAll('\\', '/'))
- ? [{ path: value.replaceAll('\\', '/'), caption: inheritedCaption }] : []
- if (Array.isArray(value)) return value.flatMap(item => imageRefs(item, inheritedCaption))
- if (typeof value !== 'object') return []
- const caption = value.caption || value.title || value.label || value.name || inheritedCaption
- return Object.entries(value).flatMap(([key, item]) => imageRefs(item, caption || key))
- }
- function validateImage(relative) {
- const absolute = path.resolve(reportDir, relative)
- const relativeToRoot = path.relative(reportDir, absolute)
- if (path.isAbsolute(relative) || /^[a-z][a-z\d+.-]*:/i.test(relative)
- || relativeToRoot.startsWith('..') || path.isAbsolute(relativeToRoot)
- || !screenshotPattern.test(relative) || !fs.existsSync(absolute)
- || !fs.statSync(absolute).isFile() || fs.statSync(absolute).size === 0) {
- throw new Error(`截图引用不存在、为空或不在报告目录内:${relative}`)
- }
- const realRelative = path.relative(fs.realpathSync(reportDir), fs.realpathSync(absolute))
- if (realRelative.startsWith('..') || path.isAbsolute(realRelative)) throw new Error(`截图链接越出报告目录:${relative}`)
- imagePaths.add(relative)
- }
- const uniqueImages = refs => [...new Map(refs.map(ref => [ref.path, ref])).values()]
- const evidenceImages = uniqueImages(sources.flatMap(source => imageRefs(source.data)))
- evidenceImages.forEach(ref => validateImage(ref.path))
- history.forEach(ref => validateImage(ref.path))
- const finalImages = evidenceImages.filter(ref => !historyPaths.has(ref.path))
- const imageUrl = value => value.split('/').map(encodeURIComponent).join('/')
- const figure = ref => `<figure><a href="${html(imageUrl(ref.path))}" target="_blank" rel="noopener"><img src="${html(imageUrl(ref.path))}" alt="${html(ref.caption || ref.path)}" loading="lazy"></a><figcaption>${html(ref.caption || ref.path)} · 点击查看原图</figcaption></figure>`
- const mdFigure = ref => `[})](${imageUrl(ref.path)})`
- const details = (value, title = '查看脱敏后的完整记录') => `<details><summary>${html(title)}</summary><pre>${html(pretty(value))}</pre></details>`
- const bullets = items => `<ul>${items.map(item => `<li>${html(item)}</li>`).join('')}</ul>`
- const mdBullets = items => items.map(item => `- ${md(item)}`).join('\n')
- const badge = value => `<span class="badge ${statusClass(value)}">${statusLabel(value)}</span>`
-
- const stages = [
- { title: '1 · 资料', items: [
- '参考《文档/维修训练内容设计.pdf》(6 页)与已有场景制作成果。按“场景 → 任务步骤 → 学习 / 训练 / 评估”的资料结构检查实现。',
- '本次使用已发布的狐狸场景和牛奶卡车场景验证训练编排,确认真实模型可见、步骤目标来自绑定场景、保存及发布使用服务端版本。',
- ] },
- { title: '2 · 产品原型', items: [
- '沿用现有三维训练编排工作台:选择场景、选择三维对象、配置任务步骤、保存草稿和发布。',
- '新建时的液压模板仅作为现有界面起点;绑定新场景后不得继续选择该场景中不存在的液压设备。',
- ] },
- { title: '3 · 设计', items: [
- '两条独立训练分别绑定狐狸与卡车的明确发布版本;每条配置两步、每步 50 分,总计 100 分,并核验重新打开后的状态。',
- '保存时以三维视口截图生成训练封面;模型可见性要通过实际截图及模型显示 / 隐藏的像素差异判断。',
- '将正常流程、独立浏览器只读重开、资源失败、封面失败、版本冲突及并发切换分别留证。独立重开阻断所有业务写请求,核验模型像素可见性、封面哈希与发布依赖;不将其表述为只读角色权限测试。',
- ] },
- { title: '4 · 开发', items: [
- '场景目录对接已发布内容版本;GLB 通过受控下载读取;训练依赖固定到所选场景版本,恢复项目时保留来源元数据。',
- '修复蒙皮模型缩放后的骨骼矩阵与包围盒刷新;场景恢复、部位覆盖和高亮使用一致的尺寸计算。',
- '绑定场景后移除不存在的内置操作目标,过滤隐藏或已删除对象及其子目标。',
- '保存和发布等待异步操作完成;封面与内容在同一次版本保存中持久化;失败、冲突及并发切换必须保留可恢复状态。最终实现效果以下方真实测试记录为准。',
- '修复旧工程快照回写覆盖最新名称与训练形态;场景绑定进行中禁止保存和发布,避免模型尚未加载成功就写入新的场景依赖。',
- ] },
- ]
- const scopeItems = [
- '本次范围为训练编排、草稿保存、发布与重新打开,不包含创建教学任务、下发学员或完成学员训练。',
- '“预览训练”仍提示需发布后在教学实施中下发;本报告不将该提示视作学员训练已运行。',
- '本轮仅修复已实现功能的问题,无新增需要用户确认的功能改动。',
- ]
- const projectValue = (project, names) => names.map(name => project?.[name]).find(value => value !== undefined && value !== null && value !== '')
- function projectRow(project) {
- const scene = project.scene || project.sceneDependency || project.boundScene || {}
- return [
- projectValue(project, ['id', 'projectId', 'trainingProjectId']),
- projectValue(project, ['name', 'title']),
- projectValue(project, ['finalStatus', 'status']),
- projectValue(project, ['finalVersionId', 'currentVersionId', 'versionId']),
- projectValue(project, ['publishedVersionId']),
- projectValue(project, ['sceneProjectId', 'sceneId']) || projectValue(scene, ['projectId', 'sceneId', 'id']),
- projectValue(project, ['sceneVersionId']) || projectValue(scene, ['versionId', 'publishedVersionId']),
- projectValue(project, ['stepCount']) ?? (Array.isArray(project.steps) ? project.steps.length : undefined),
- projectValue(project, ['totalScore', 'score']),
- ].map(recorded)
- }
- const projectHeaders = ['训练 ID', '名称', '状态', '当前版本', '发布版本', '场景 ID', '固定场景版本', '步骤数', '总分']
- const htmlProjects = projects.length ? `<div class="table-scroll"><table><thead><tr>${projectHeaders.map(value => `<th>${html(value)}</th>`).join('')}</tr></thead><tbody>${projects.map(project => `<tr>${projectRow(project).map(value => `<td>${html(value)}</td>`).join('')}</tr>`).join('')}</tbody></table></div>${projects.map(project => details(project, `训练 ${recorded(projectValue(project, ['id', 'projectId', 'trainingProjectId']))}:版本、步骤、封面与依赖记录`)).join('')}`
- : '<p class="pending-note">已开始创建训练 161(狐狸)与 162(卡车);最终状态、版本、封面与场景依赖等待 final-evidence.json,不以阶段性保存结果代替最终记录。</p>'
- const mdProjects = projects.length ? `| ${projectHeaders.map(md).join(' | ')} |\n| ${projectHeaders.map(() => '---').join(' | ')} |\n${projects.map(project => `| ${projectRow(project).map(md).join(' | ')} |`).join('\n')}`
- : '已开始创建训练 161(狐狸)与 162(卡车);最终状态、版本、封面与场景依赖等待 final-evidence.json。'
- function sourceHtml(source) {
- if (!source.data) return `<article class="test"><h3>${html(source.title)} ${badge('PENDING')}</h3><p>等待 ${html(source.file)}。未计为通过。</p></article>`
- return `<article class="test"><h3>${html(source.data.title || source.title)} ${badge(source.status)}</h3>${source.checks.map((check, index) => `<div class="check"><h4>${html(check.title || check.name || check.label || `检查 ${index + 1}`)} ${badge(check.status)}</h4>${check.superseded || check.historical ? '<p class="pending-note">历史记录,不计入当前通过数。</p>' : ''}${details(check)}</div>`).join('')}${details(source.data, `${source.file} · 完整记录`)}</article>`
- }
- function sourceMd(source) {
- const title = source.data?.title || source.title
- if (!source.data) return `### ${title} · 待补充证据\n\n等待 ${source.file},未计为通过。`
- const checks = source.checks.map((check, index) => `- ${md(check.title || check.name || check.label || `检查 ${index + 1}`)}:${statusLabel(check.status)}${check.superseded || check.historical ? '(历史记录,不计入当前通过数)' : ''}`).join('\n')
- return `### ${title} · ${statusLabel(source.status)}\n\n${checks}\n\n<details><summary>${html(source.file)} · 脱敏完整记录</summary>\n\n<pre>${html(pretty(source.data))}</pre>\n\n</details>`
- }
- const summary = `证据组:${sources.filter(source => source.status === 'PASS').length}/${sources.length} 通过;明确检查:通过 ${passedChecks},失败 ${failedChecks},待验证 ${pendingChecks};已校验截图 ${imagePaths.size} 张。`
- const htmlCommands = commands.map(command => `<div class="check"><h4>${html(command.command || command.name || '验证命令')} ${badge(command.status)}</h4><p>${html(command.details || command.result || '')}</p></div>`).join('')
- const mdCommands = commands.map(command => `- ${md(command.command || command.name || '验证命令')}:${statusLabel(command.status)}。${md(command.details || command.result || '')}`).join('\n')
- const outputHtml = `<!doctype html>
- <html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>训练编排真实测试报告 · 2026-09-05</title>
- <style>
- :root{color-scheme:light;--ink:#203544;--muted:#607789;--line:#dce6ec;--green:#137d6e;--soft:#eef6f7}*{box-sizing:border-box}body{margin:0;background:#f3f6f8;color:var(--ink);font:15px/1.75 system-ui,-apple-system,"Microsoft YaHei",sans-serif}main{max-width:1220px;margin:auto;padding:32px 24px 64px}header{padding:30px 34px;background:#103c45;color:white;border-radius:16px}h1{font-size:29px;margin:0 0 12px}header p{color:#d7e8eb;margin:7px 0}nav{display:flex;gap:10px;flex-wrap:wrap;margin:22px 0}nav a{color:var(--green);text-decoration:none;background:white;border:1px solid var(--line);padding:6px 13px;border-radius:7px}section{background:white;border:1px solid var(--line);border-radius:12px;padding:26px 30px;margin:20px 0}h2{font-size:21px;margin:0 0 16px}h3{font-size:17px;margin:0 0 12px}h4{font-size:15px;margin:0 0 7px}p{margin:10px 0}ul{padding-left:22px}li+li{margin-top:7px}.badge{display:inline-block;vertical-align:middle;font-size:12px;font-weight:600;line-height:1.7;border-radius:4px;padding:2px 8px;margin-left:5px}.pass{color:#11634f;background:#e3f5ed}.fail{color:#9e2a35;background:#ffe9ec}.pending{color:#7b6121;background:#fff2cc}.muted{color:var(--muted)}.pending-note{padding:12px 16px;background:#fff8e7;border-left:3px solid #c09a3b}.stages{display:grid;grid-template-columns:1fr 1fr;gap:18px}.stage{border:1px solid var(--line);border-radius:8px;padding:20px}.stage ul{margin-bottom:0}.test+.test{border-top:1px solid var(--line);margin-top:22px;padding-top:22px}.check{border-left:3px solid var(--line);padding:8px 16px;margin:12px 0}details{margin:12px 0}summary{cursor:pointer;color:var(--green)}pre{white-space:pre-wrap;overflow-wrap:anywhere;max-height:600px;overflow:auto;padding:16px;background:#f5f8fa;border:1px solid var(--line);border-radius:7px;font:12px/1.6 ui-monospace,Consolas,monospace}.gallery{display:grid;grid-template-columns:1fr 1fr;gap:20px}figure{margin:0;border:1px solid var(--line);border-radius:8px;overflow:hidden;background:#fafcfd}figure img{width:100%;height:auto;display:block}figcaption{padding:10px 13px;color:var(--muted);font-size:13px}.table-scroll{overflow:auto}table{border-collapse:collapse;width:100%;font-size:13px}th,td{border:1px solid var(--line);text-align:left;padding:10px;white-space:nowrap}th{background:var(--soft)}footer{color:var(--muted);font-size:13px;text-align:center}a{color:var(--green)}@media(max-width:800px){main{padding:16px 12px 40px}header,section{padding:20px}h1{font-size:24px}.stages,.gallery{grid-template-columns:1fr}}@media print{body{background:white}main{max-width:none;padding:0}header{color:var(--ink);background:white;border:1px solid var(--line)}header p{color:var(--muted)}nav{display:none}section{break-inside:avoid}.gallery{grid-template-columns:1fr}details{break-inside:avoid}}
- </style></head><body><main>
- <header><h1>训练编排真实测试报告 ${badge(overall)}</h1><p>狐狸与牛奶卡车 · 场景 → 任务步骤 → 保存与发布</p><p>2026-09-05 · ${html(final.baseURL || 'http://127.0.0.1:6180')} · ${html(final.browser || 'Microsoft Edge / Playwright')} · ${html(final.role || '教员编排与独立浏览器只读重开')}</p><p>${html(summary)}</p></header>
- <nav><a href="#method">资料与实施</a><a href="#projects">保留训练数据</a><a href="#tests">测试证据</a><a href="#screenshots">最终截图</a><a href="#history">过程记录</a><a href="#scope">范围与限制</a><a href="report.md">Markdown 报告</a></nav>
- ${overall === 'PENDING' ? '<p class="pending-note">报告草稿:最终证据尚不完整。已有过程截图和开发记录不能代替保存、发布及重新打开的最终验证。</p>' : ''}
- <section id="method"><h2>资料 → 产品原型 → 设计 → 开发</h2><div class="stages">${stages.map(stage => `<article class="stage"><h3>${html(stage.title)}</h3>${bullets(stage.items)}</article>`).join('')}</div></section>
- <section id="projects"><h2>保留训练数据</h2>${htmlProjects}<p class="muted">保留两条真实训练供后续查看;本报告生成器不创建、修改或删除业务数据。</p></section>
- <section id="tests"><h2>5 · 测试</h2><p>${html(summary)}</p><p class="muted">过程检查记录执行当时的版本;最终数据以上方保留项目及同版本独立重开记录为准。</p>${versionMismatches.length ? `<p class="pending-note">独立重开证据尚未覆盖最终发布版本,不能标记完整通过。</p>${details(versionMismatches, '待重验的版本')}` : ''}${sources.map(sourceHtml).join('')}${commands.length ? `<h3>执行命令与验证结果</h3>${htmlCommands}` : '<p class="muted">命令与最终构建结果等待证据记录。</p>'}</section>
- <section id="screenshots"><h2>最终及异常验证截图</h2>${finalImages.length ? `<div class="gallery">${finalImages.map(figure).join('')}</div>` : '<p class="pending-note">等待最终证据引用实际截图。尚无最终截图不等于模型已通过可见性检查。</p>'}</section>
- <section id="history"><h2>过程截图 · 不计入最终通过结论</h2><p class="muted">这些截图只记录测试中途状态;最终两步、总分、版本和封面以上方证据为准。</p><div class="gallery">${history.map(figure).join('')}</div></section>
- <section id="scope"><h2>范围、限制与功能确认结论</h2>${bullets(scopeItems)}${limitations.length ? `<h3>实测限制与后续项</h3>${bullets(limitations.map(pretty))}` : ''}</section>
- <footer>报告生成:${html(generatedAt)}(Asia/Shanghai) · 来源:${sourceDefinitions.map(item => item.file).join('、')} · 图片均经本地文件校验</footer>
- </main></body></html>`
- const outputMd = `# 训练编排真实测试报告 · 2026-09-05
-
- 状态:**${statusLabel(overall)}**。${summary}
-
- ${overall === 'PENDING' ? '> 报告草稿:最终证据尚不完整,过程截图不能代替最终保存、发布和重新打开验证。\n' : ''}
- ${stages.map(stage => `## ${stage.title}\n\n${mdBullets(stage.items)}`).join('\n\n')}
-
- ## 保留训练数据
-
- ${mdProjects}
-
- 保留两条真实训练供后续查看;本报告生成器不创建、修改或删除业务数据。
-
- ## 5 · 测试
-
- 过程检查记录执行当时的版本;最终数据以上方保留项目及同版本独立重开记录为准。
-
- ${versionMismatches.length ? `> 独立重开证据尚未覆盖最终发布版本,不能标记完整通过。\n\n<pre>${html(pretty(versionMismatches))}</pre>\n` : ''}
- ${sources.map(sourceMd).join('\n\n')}
-
- ${commands.length ? `### 执行命令与验证结果\n\n${mdCommands}` : '命令与最终构建结果等待证据记录。'}
-
- ## 最终及异常验证截图
-
- ${finalImages.length ? finalImages.map(mdFigure).join('\n\n') : '等待最终证据引用实际截图;尚未将模型可见性计为通过。'}
-
- ## 过程截图 · 不计入最终通过结论
-
- ${history.map(mdFigure).join('\n\n')}
-
- ## 范围、限制与功能确认结论
-
- ${mdBullets(scopeItems)}
-
- ${limitations.length ? `### 实测限制与后续项\n\n${mdBullets(limitations.map(pretty))}\n` : ''}
- 报告生成:${generatedAt}(Asia/Shanghai)。
- `
- fs.writeFileSync(path.join(reportDir, 'index.html'), outputHtml, 'utf8')
- fs.writeFileSync(path.join(reportDir, 'report.md'), outputMd, 'utf8')
- console.log(JSON.stringify({ report: 'reports/training-live-20260905/index.html', status: overall, sources: sources.map(({ file, status: state }) => ({ file, status: state })), checks: { pass: passedChecks, fail: failedChecks, pending: pendingChecks }, images: imagePaths.size }))
|