import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
// Evidence is owned by the actual UI/API test runs. Missing evidence stays pending.
// This script only generates the two report documents and never calls a business API.
const reportDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../reports/training-modes-20260905')
fs.mkdirSync(reportDir, { recursive: true })
const array = value => Array.isArray(value) ? value : value == null ? [] : [value]
const sensitive = /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]) => !sensitive.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 state = value => /^(PASS|PASSED)$/i.test(String(value)) ? 'PASS'
: /^(FAIL|FAILED)$/i.test(String(value)) ? 'FAIL'
: /^(BLOCKED|LIMITED)$/i.test(String(value)) ? 'BLOCKED'
: /^PASS_WITH_LIMITATIONS$/i.test(String(value)) ? 'PASS_WITH_LIMITATIONS' : 'PENDING'
const label = value => ({ PASS: '通过', FAIL: '失败', BLOCKED: '受限(需功能接线)', PASS_WITH_LIMITATIONS: '部分链路已验证,页面闭环受限', PENDING: '待补充证据' })[state(value)]
const badge = value => `${label(value)}`
const details = (value, title = '查看脱敏详细记录') => `${html(title)}
${html(pretty(value))} `
const bullets = items => `
${items.map(item => `- ${html(pretty(item))}
`).join('')}
`
const mdBullets = items => items.map(item => `- ${md(pretty(item))}`).join('\n')
const sources = [
{ file: 'evidence.json', title: '浏览器编排、重新打开及教学入口实测', kind: 'UI' },
{ file: 'api-evidence.json', title: '正式教学 API:人工事件与红蓝岗位运行', kind: 'API' },
].map(source => {
const absolute = path.join(reportDir, source.file)
const data = fs.existsSync(absolute) ? sanitize(JSON.parse(fs.readFileSync(absolute, 'utf8').replace(/^\uFEFF/, ''))) : null
const checks = array(data?.checks || data?.results || data?.tests).filter(item => item && !item.historical && !item.superseded)
const status = checks.some(check => state(check.status) === 'FAIL') ? 'FAIL'
: data?.status ? state(data.status) === 'PASS' && checks.some(check => state(check.status) === 'BLOCKED') ? 'BLOCKED' : state(data.status)
: checks.some(check => state(check.status) === 'BLOCKED') ? 'BLOCKED'
: checks.length && checks.every(check => state(check.status) === 'PASS') ? 'PASS' : 'PENDING'
return { ...source, data, checks, status }
})
const ui = sources[0].data || {}
const api = sources[1].data || {}
const projects = array(ui.projects || ui.trainingProjects || ui.retainedProjects)
const versionMismatches = Object.entries(api.references || {}).flatMap(([channel, reference]) => {
if (!reference) return []
const project = projects.find(item => String(item.id || item.projectId) === String(reference.projectId))
if (!projects.length) return []
const expected = project?.publishedVersionId || project?.finalVersionId
if (project?.apiTestVersionId && project?.apiVersionNote && String(project.apiTestVersionId) === String(reference.versionId)) return []
return expected && String(expected) === String(reference.versionId) ? [] : [{ channel, projectId: reference.projectId, uiPublishedVersionId: expected || '未记录', apiVersionId: reference.versionId }]
})
const checks = sources.flatMap(source => source.checks)
const counts = { passed: checks.filter(check => state(check.status) === 'PASS').length, blocked: checks.filter(check => state(check.status) === 'BLOCKED').length, failed: checks.filter(check => state(check.status) === 'FAIL').length, pending: checks.filter(check => state(check.status) === 'PENDING').length }
const overall = sources.some(source => source.status === 'FAIL') || counts.failed ? 'FAIL'
: sources.some(source => source.status === 'PENDING') || counts.pending || versionMismatches.length ? 'PENDING'
: counts.blocked || sources.some(source => ['BLOCKED', 'PASS_WITH_LIMITATIONS'].includes(source.status)) ? 'PASS_WITH_LIMITATIONS' : 'PASS'
const limitations = [...new Map(sources.flatMap(source => array(source.data?.limitations)).map(item => [pretty(item), item])).values()]
const followups = array(ui.confirmationItems || ui.followUpIssues || ui.featureConfirmations)
const commands = sources.flatMap(source => array(source.data?.commands))
const imagePattern = /^screenshots\/.+\.(?:png|jpe?g|webp)$/i
function imageRefs(value, inheritedCaption = '') {
if (typeof value === 'string') return imagePattern.test(value.replaceAll('\\', '/')) ? [{ path: value.replaceAll('\\', '/'), caption: inheritedCaption }] : []
if (Array.isArray(value)) return value.flatMap(item => imageRefs(item, inheritedCaption))
if (!value || typeof value !== 'object') return []
const caption = value.caption || value.title || value.label || value.name || inheritedCaption
return Object.values(value).flatMap(item => imageRefs(item, caption))
}
const images = [...new Map(sources.flatMap(source => imageRefs(source.data)).map(item => [item.path, item])).values()]
for (const image of images) {
const absolute = path.resolve(reportDir, image.path)
const relative = path.relative(reportDir, absolute)
if (path.isAbsolute(image.path) || relative.startsWith('..') || path.isAbsolute(relative) || !fs.existsSync(absolute) || !fs.statSync(absolute).isFile() || fs.statSync(absolute).size === 0) throw new Error(`截图不存在或路径非法:${image.path}`)
const real = path.relative(fs.realpathSync(reportDir), fs.realpathSync(absolute))
if (real.startsWith('..') || path.isAbsolute(real)) throw new Error(`截图越出目录:${image.path}`)
}
const imageUrl = value => value.split('/').map(encodeURIComponent).join('/')
const figure = image => `
${html(image.caption || image.path)} · 点击查看原图`
const mdFigure = image => `[})](${imageUrl(image.path)})`
const stages = [
{ title: '1 · 资料', items: [
'实际查看《维修训练内容设计.pdf》第 1–3、5–6 页扫描件。第 1–2 页将虚拟、混合现实、AI 指导下的实装组织为递进训练,流程包含构建场景、编排任务、组班下发、学员训练与数据报告。',
'本次使用狐狸与牛奶卡车测试素材验证软件链路,不将其视为原文装备维修内容或真实维修能力考核。原文已查看页面没有单列红蓝对抗规则;对抗依据现有教学实施、渠道合同、命令幂等及步骤事实文档验证。',
'合同来源:unreal_tran_api/wiki/14-教学实施模块.md、19-训练定义渠道合同.md、20-教学命令幂等.md、21-教学步骤运行事实.md。',
] },
{ title: '2 · 产品原型', items: [
'沿用现有训练编排工作台与模式配置表单,分别建立实装和对抗内容;保存、发布后重新打开检查步骤、分值、封面与模式参数。',
'实装默认运行入口为离线识别回放;对抗默认入口为本地工作台。分别记录界面实际行为,再通过正式 API 验证服务端教学闭环。',
] },
{ title: '3 · 设计', items: [
'实装配置三步人工确认,分值 30 / 30 / 40;完成进度按步骤推导为 33 / 67 / 100。验证失败重试、顺序约束、事件身份及重复事件处理。',
'对抗配置红蓝两队、每队两人,步骤和提交均由 COMMANDER 执行;OPERATOR 用于岗位拒绝测试。验证同队共享运行、跨队隔离、服务器时限、提交与教员评定。',
'任务固定引用已发布训练版本;只创建本次开发测试数据。人工确认和客户端模拟参数均明确标识为测试,不连接真实工位、PLC、摄像头或视觉服务。',
] },
{ title: '4 · 开发', items: array(ui.development || ui.fixes).length ? array(ui.development || ui.fixes) : [
'本轮业务修复与验证结果等待浏览器 evidence.json;本报告生成器不会修改业务数据或将待实施功能标为已完成。',
] },
]
const scope = [
'本报告区分编排 UI、默认教学 UI 和正式教学 API 三类证据;API 成功不能证明默认 UI 已连接该服务端运行。',
'实装的设备或视觉事件链路未接真实设备验证;人工确认测试不能替代实机联调、安全联锁或实际操作技能考核。',
'对抗的默认本地工作台与正式服务端任务分别留证;无证据时不声称多人跨浏览器实时协作或正式比赛胜负已联调。',
'正式 API 对抗由四个隔离学员会话依次操作;检查服务端截止时间已生效,未等待整局自然超时,不作为多人并发或网络同步压力测试。',
'100 分评定仅验证接口和结果留痕,不代表学员实际维修能力。测试不会向他人发送消息或下发真实设备指令。',
]
const modeRows = [
['实装实训', 'PHYSICAL', '正式 API 的 MANUAL 人工事件', '三步顺序、失败重试、来源权限、事件幂等、提交与评定', '默认离线识别页;设备 / 视觉接入另行联调'],
['对抗训练', 'CONFRONTATION', '正式 API 的红蓝两队共享运行', '岗位权限、两队隔离、顺序、时限、命令幂等、提交与评定', '默认本地工作台;不混同正式 API 运行'],
]
function tableHtml(headers, rows) { return `` }
function tableMd(headers, rows) { return `| ${headers.map(md).join(' | ')} |\n| ${headers.map(() => '---').join(' | ')} |\n${rows.map(row => `| ${row.map(value => md(recorded(value))).join(' | ')} |`).join('\n')}` }
const modeHeaders = ['模式', '正式渠道', '本轮 API 验证方法', '必检项', '默认界面边界']
const projectHeaders = ['训练 ID', '名称', '模式', '状态', '当前发布版本', 'API 已测版本', '步骤数']
const projectRows = projects.map(project => [project.id || project.projectId, project.name || project.title, project.trainingMode || project.mode || project.channel, project.finalStatus || project.status, project.publishedVersionId || project.finalVersionId, Object.values(api.references || {}).find(reference => reference && String(reference.projectId) === String(project.id || project.projectId))?.versionId, project.stepCount ?? project.steps?.length])
const runHeaders = ['任务 ID', '运行 ID', '渠道', '队伍', '状态', '完成度', '评定分']
const runRows = array(api.runs).map(run => [run.assignmentId, run.id, run.channel, run.team, run.status, run.progressPercent, run.score])
function sourceHtml(source) {
if (!source.data) return `${html(source.title)} ${badge('PENDING')}
等待 ${html(source.file)},未计为通过。
`
return `${html(source.data.title || source.title)} ${badge(source.status)}
证据类型:${source.kind} · ${html(source.file)}
${source.checks.map(check => `${html(check.title || check.name || '检查')} ${badge(check.status)}
${details(check)}`).join('')}${details(source.data, `${source.file} · 完整记录`)}`
}
function sourceMd(source) {
return `### ${md(source.data?.title || source.title)} · ${label(source.status)}\n\n证据类型:${source.kind}。\n\n${source.data ? source.checks.map(check => `- ${md(check.title || check.name || '检查')}:${label(check.status)}`).join('\n') : `等待 ${source.file},未计为通过。`}\n\n${source.data ? `${html(source.file)} · 脱敏完整记录
\n\n${html(pretty(source.data))}\n\n ` : ''}`
}
const summary = `证据组 ${sources.filter(source => source.status !== 'PENDING').length}/${sources.length} 已完成;检查通过 ${counts.passed},受限 ${counts.blocked},失败 ${counts.failed},待验证 ${counts.pending};已校验截图 ${images.length} 张。`
const conclusion = overall === 'PASS_WITH_LIMITATIONS' ? '编排与 API 已验证,教学页面闭环受限。需完成默认教学页面与正式任务运行的接线,才能从页面走完新模型对应的训练。' : ''
const generatedAt = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
const outputHtml = `实装与对抗训练实测报告 · 2026-09-05
${overall === 'PENDING' ? '报告草稿:最终证据尚不完整,不以配置完成或单独 API 成功替代界面全流程验证。
' : ''}
资料 → 产品原型 → 设计 → 开发
${stages.map(stage => `
${html(stage.title)}
${bullets(stage.items)}`).join('')}
两种模式的验证边界
${tableHtml(modeHeaders, modeRows)}
保留开发测试数据
${projects.length ? tableHtml(projectHeaders, projectRows) + projects.map(project => `${project.apiVersionNote ? `训练 ${html(project.id || project.projectId)}:${html(project.apiVersionNote)}
` : ''}${details(project, `训练 ${project.id || project.projectId} · 发布与配置记录`)}`).join('') : '等待 UI 最终项目记录。
'}正式教学任务与运行
${runRows.length ? tableHtml(runHeaders, runRows) : '等待 API 运行结果。
'}${api.retainedData ? details(api.retainedData, '本次新增数据 ID') : ''}随机测试密码与登录会话不写入报告;保留新建数据用于追溯。
5 · 测试
${html(summary)}
${versionMismatches.length ? `UI 与 API 证据引用的发布版本尚未一致,不能标记完整通过。
${details(versionMismatches)}` : ''}${sources.map(sourceHtml).join('')}${commands.length ? `测试命令与构建
${commands.map(command => `${html(command.command || command.name)} ${badge(command.status)}
${html(command.details || command.result || '')}
`).join('')}` : ''}
真实浏览器截图
截图只来自实际存在的文件;API 请求结果单列,不以 UI 截图代替。
${images.length ? `${images.map(figure).join('')}
` : '等待 evidence.json 引用实际截图。
'}
范围、限制与待确认项
${bullets(scope)}${limitations.length ? `实测边界与限制
${bullets(limitations)}` : ''}需要另行确认的功能范围
${followups.length ? bullets(followups) : '本栏等待最终证据中的功能范围结论;默认教学 UI 与正式运行的接线现状需按实际结果评估,不自动扩展实现。
'}`
const outputMd = `# 实装与对抗训练实测报告 · 2026-09-05
状态:**${label(overall)}**。${summary}
${conclusion}
范围:编排 UI、默认教学入口、正式教学 API 分开验证。
${stages.map(stage => `## ${stage.title}\n\n${mdBullets(stage.items)}`).join('\n\n')}
## 两种模式的验证边界
${tableMd(modeHeaders, modeRows)}
## 保留开发测试数据
${projects.length ? tableMd(projectHeaders, projectRows) : '等待最终 UI 项目记录。'}
${projects.filter(project => project.apiVersionNote).map(project => `> 训练 ${md(project.id || project.projectId)}:${md(project.apiVersionNote)}`).join('\n\n')}
### 正式教学任务与运行
${runRows.length ? tableMd(runHeaders, runRows) : '等待 API 运行结果。'}
随机测试密码与登录会话不写入报告;保留新建数据用于追溯。
## 5 · 测试
${versionMismatches.length ? `> UI 与 API 发布版本不一致,未计为完整通过。\n\n${html(pretty(versionMismatches))}\n` : ''}
${sources.map(sourceMd).join('\n\n')}
${commands.length ? `### 测试命令与构建\n\n${commands.map(command => `- ${md(command.command || command.name)}:${label(command.status)}。${md(command.details || command.result || '')}`).join('\n')}` : ''}
## 真实浏览器截图
${images.length ? images.map(mdFigure).join('\n\n') : '等待最终证据引用实际截图。'}
## 范围、限制与待确认项
${mdBullets(scope)}
${limitations.length ? `### 实测边界与限制\n\n${mdBullets(limitations)}\n` : ''}
### 需要另行确认的功能范围
${followups.length ? mdBullets(followups) : '等待最终证据中的功能范围结论;默认教学 UI 与正式运行接线现状按实际结果评估,不自动扩展实现。'}
报告生成:${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-modes-20260905/index.html', status: overall, checks: counts, images: images.length, sources: sources.map(({ file, status }) => ({ file, status })) }))