import fs from 'node:fs/promises'; import path from 'node:path'; import vm from 'node:vm'; import assert from 'node:assert/strict'; import crypto from 'node:crypto'; import { pathToFileURL } from 'node:url'; import { buildModel } from '../src/core/kfs/build.js'; import { WORKSHOP_OUTPUTS } from '../src/core/workshop-outputs.js'; const root = path.resolve('docs/workshop-final-local-20261110'); const work = path.resolve('work/workshop-final-local-20261110'); await fs.mkdir(work, { recursive: true }); const samples = JSON.parse(await fs.readFile(path.join(root, 'review-samples.json'))); const source = Object.fromEntries(samples.outputs.map(row => [row.id, row])); const sourceIds = { market: 'D1-01', social: 'D2-02', evidence: 'D2-01', opportunities: 'D2-04', validation: 'D2-06', value: 'D2-07', proposal: 'D2-08' }; const blank = () => ({ project: [], artifact: [], session: [], source: [], opportunity: [], insight: [] }); const raw = blank(); for (const [person, groupId] of [['a', 'sample-a'], ['b', 'sample-b']]) { raw.session.push({ objectId: 'sample-session-' + person, studentName: '同名样例', groupId, meta: { participantKey: 'participant:sample-person-' + person }, workshopKey: person === 'a' ? '样例办公午餐' : '样例家庭晚餐' }); } for (const output of WORKSHOP_OUTPUTS) { const original = source[sourceIds[output.key]]; assert.ok(original, sourceIds[output.key]); const report = structuredClone(original.report); report.executive = [original.finding, original.meaning, original.next]; if (output.key === 'social') { report.chapters = [{ id: output.anchor, title: '社媒场景线索', stage: 'S2', sections: [ { kind: 'para', text: '构造素材V12:“宿舍没锅,想找不需要煮、倒水也简单的夜宵。”该条无商品归属,只支持宿舍使用任务的品类线索,不归属某款或品牌,也不能推需求规模。' }, ] }]; } else report.chapters[0].id = output.anchor; raw.artifact.push({ objectId: 'render-sample-' + output.key, title: '【展示样例】' + original.title, artifactType: original.type, dataMode: 'sample', workshopKey: '样例办公午餐', ownerName: '同名样例', uploadedByKey: 'participant:sample-person-a', reportSeriesKey: 'sample-topic-a:' + sourceIds[output.key] + ':' + output.key, version: 2, stageCode: original.stage, report, rawText: original.rawText, updatedAt: '2026-11-10T02:00:00Z' }); } const history = structuredClone(raw.artifact[0]); history.objectId += '-history';history.version = 1;raw.artifact.push(history); const second = structuredClone(raw.artifact[0]);second.objectId += '-group-b';second.uploadedByKey = 'participant:sample-person-b';second.workshopKey = '样例家庭晚餐'; second.title = '【展示样例】家庭可煮条件的产品比较';raw.artifact.push(second); const missing = { objectId: 'render-sample-unknown', title: '【展示样例】未定模式和类别', rawText: '仅用于核验未知模式显示', artifactType: 'assessment_report' };raw.artifact.push(missing); const db = buildModel(raw); const groupState = { schema: 'ksf.member-groups.v1', revision: 0, groups: [{ id: 'sample-a', name: '样例A组' }, { id: 'sample-b', name: '样例B组' }], assignments: Object.fromEntries(db.members.filter(m => m.keys.length).map(m => [m.id, m.keys.includes('participant:sample-person-a') ? 'sample-a' : 'sample-b'])) }; await fs.writeFile(path.join(work, 'rendering-fixture.json'), JSON.stringify({ notice: '隔离浏览器展示样例,未保存至任何业务库', raw, groupState }, null, 2)); const { chromium } = await import(pathToFileURL(path.resolve('work/workshop-manual-tools/node_modules/playwright/index.mjs')).href); const browser = await chromium.launch({ headless: true, executablePath: 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe' }); const checks = [], errors = [], actions = []; const record = (name, extra = {}) => checks.push({ name, ...extra }); try { const context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, permissions: ['clipboard-read', 'clipboard-write'] }); const page = await context.newPage();page.on('pageerror', e => errors.push(e.message)); let activeRaw = raw, activeGroups = groupState, failGroups = false; await page.route('**/api/functions', async route => { const body = route.request().postDataJSON(), name = body.path; actions.push(name); assert.equal(name, '/ksfGetPublicBoard', 'Only the public board read may reach this intercepted endpoint'); return route.fulfill({ contentType: 'application/json', body: JSON.stringify({ result: { ok: true, data: { ...activeRaw, nextCursor: null } } }) }); }); await page.route('**/__dev/member-groups', route => { if (failGroups) return route.fulfill({ status: 503, contentType: 'application/json', body: JSON.stringify({ error: 'sample-group-read-unavailable' }) }); return route.fulfill({ contentType: 'application/json', body: JSON.stringify({ result: { ok: true, data: activeGroups } }) }); }); const base = 'http://127.0.0.1:4192'; const ready = async () => { await page.locator('view-workshop-outputs .filters').waitFor(); await page.waitForFunction(() => document.querySelector('kf-app')?.shadowRoot.querySelector('view-workshop-outputs')?._loading === false); }; const countIs = async expected => { await page.waitForFunction(n => document.querySelector('kf-app')?.shadowRoot.querySelector('view-workshop-outputs')?.renderRoot.querySelectorAll('[data-workshop-artifact]').length === n, expected); assert.equal(await page.locator('[data-workshop-artifact]').count(), expected); }; await page.goto(base + '/workshop');await ready(); await countIs(0);record('default-live-excludes-samples'); await page.getByLabel('资料范围', { exact: true }).selectOption('sample'); await page.locator('[data-workshop-artifact="render-sample-market"]').waitFor(); await countIs(8);record('sample-scope-latest-versions'); await page.getByLabel('小组', { exact: true }).selectOption('sample-a'); await countIs(7);record('same-name-group-stable-identity'); await page.getByLabel('研究课题', { exact: true }).selectOption('样例办公午餐'); const matrixRow = page.locator('[data-output-group="sample-a"]'); assert.equal(await matrixRow.getByRole('button', { name: /1份$/ }).count(), 7);record('seven-output-links'); await page.reload();await ready(); assert.equal(await page.getByLabel('小组', { exact: true }).inputValue(), 'sample-a'); await countIs(7);record('deep-link-refresh-retains-scope'); await page.getByLabel('成果类别', { exact: true }).selectOption('market'); await countIs(1); await page.getByLabel('显示历史版本', { exact: true }).check(); await countIs(2);record('history-toggle'); await page.getByLabel('显示历史版本', { exact: true }).uncheck(); for (const width of [1440, 390]) { await page.setViewportSize({ width, height: 1000 }); await page.getByLabel('成果类别', { exact: true }).selectOption(''); const size = await page.evaluate(() => ({ width: document.documentElement.clientWidth, scroll: document.documentElement.scrollWidth })); assert.ok(size.scroll <= size.width, JSON.stringify(size)); await page.screenshot({ path: path.join(root, `小组成果-${width}.png`), fullPage: true });record('group-view-no-page-overflow', { width }); } await page.setViewportSize({ width: 1440, height: 1000 }); for (const output of WORKSHOP_OUTPUTS) { await page.locator(`[data-workshop-artifact="render-sample-${output.key}"] .refs a`).first().click(); await page.locator('view-report').waitFor(); assert.equal(new URL(page.url()).searchParams.get('ch'), output.anchor); const returnTo = new URL(page.url()).searchParams.get('returnTo');assert.ok(returnTo.includes('sample-a')); await page.locator(`view-report [data-chapter="${output.anchor}"]`).waitFor(); const original = raw.artifact.find(a => a.objectId === 'render-sample-' + output.key); const chapter = original.report.chapters[0], normalize = text => String(text).replace(/\s+/gu, ''); const rendered = normalize(await page.locator('view-report').evaluate(el => el.renderRoot.textContent)); assert.ok(rendered.includes(normalize(chapter.title)), output.key); const cellText = cell => { if (Array.isArray(cell)) return cell.flatMap(v => Array.isArray(v) ? [String(v[0]), String(v[1]) + '%'] : [String(v)]); if (typeof cell === 'number') return [cell.toLocaleString('zh-CN')]; if (typeof cell === 'string' && original.report.evidence?.[cell]) return [original.report.evidence[cell].claim || cell]; return [String(cell ?? '—')]; }; const values = chapter.sections.flatMap(s => ['para', 'longpara'].includes(s.kind) ? [s.text || ''] : ['table', 'matrix'].includes(s.kind) ? [...(s.data?.cols || []), ...(s.data?.rows || []).flatMap(row => row.flatMap(cellText))] : []).filter(v => normalize(v)); for (const value of values) assert.ok(rendered.includes(normalize(value)), output.key + ': missing ' + value); await page.goBack();await ready();await countIs(7);record('chapter-content-link-and-return', { output: output.key, paragraphAndTableValues: values.length }); } await page.getByLabel('资料范围', { exact: true }).selectOption('unknown'); await page.getByLabel('研究课题', { exact: true }).selectOption(''); await page.getByLabel('小组', { exact: true }).selectOption(''); await countIs(1);record('unknown-mode-visible-separately'); failGroups = true;await page.reload();await ready(); await page.locator('view-workshop-outputs [role="alert"]').waitFor(); await countIs(1);record('group-read-failure-keeps-content'); failGroups = false; activeRaw = JSON.parse(await fs.readFile('work/workshop-board-acceptance-20261110/public-board.json')); activeGroups = JSON.parse(await fs.readFile('work/workshop-board-acceptance-20261110/public-groups.json')); await page.goto(base + '/workshop?mode=all');await ready(); await countIs(activeRaw.artifact.length);record('existing-public-snapshot-all-artifacts-retained', { artifacts: activeRaw.artifact.length }); await page.getByLabel('资料范围', { exact: true }).selectOption('live'); await countIs(15); assert.ok((await page.locator('view-workshop-outputs').evaluate(el => el.renderRoot.textContent)).includes('15 份成果未分组'));record('existing-live-ungrouped-not-invented'); await page.screenshot({ path: path.join(root, '现有数据-缺项如实显示.png'), fullPage: true }); await page.goto(base + '/reports/assessment');await page.locator('view-report-type').waitFor(); await page.waitForFunction(() => document.querySelector('kf-app')?.shadowRoot.querySelector('view-report-type')?.renderRoot.textContent.includes('评估与论证')); record('assessment-page-readable'); const manualUrl = base + '/docs/workshop-final-local-20261110/manual/index.html'; await page.goto(manualUrl);await page.locator('#prompt-text').waitFor(); const steps = await page.evaluate(() => window.WORKSHOP_MANUAL_DATA.steps.map(s => s.id)); assert.equal(steps.length, 15); for (const width of [1440, 390]) { await page.setViewportSize({ width, height: 1000 }); for (const id of steps) { await page.evaluate(id => { location.hash = id; }, id); await page.waitForFunction(id => location.hash === '#' + id && document.querySelector('.nav-item[aria-current="step"]')?.getAttribute('href') === '#' + id, id); const text = await page.locator('#prompt-text').textContent();assert.ok(text.length > 100); await page.locator('#copy-prompt').click();assert.equal((await page.evaluate(() => navigator.clipboard.readText())).replaceAll('\r\n', '\n'), text.replaceAll('\r\n', '\n')); assert.ok(await page.locator('#prompt-text').isVisible()); const size = await page.evaluate(() => ({ width: document.documentElement.clientWidth, scroll: document.documentElement.scrollWidth })); assert.ok(size.scroll <= size.width);record('manual-full-copy-visible-and-no-overflow', { width, id }); } await page.screenshot({ path: path.join(root, `手册-${width}.png`), fullPage: true }); } await page.goto(pathToFileURL(path.join(root, '康师傅工作坊操作手册-本地定稿.html')).href); await page.locator('#prompt-text').waitFor();assert.equal(await page.locator('.nav-item').count(), 15);record('standalone-file-opens-offline'); await page.goto(pathToFileURL(path.join(root, '提示词与高质反馈预览.html')).href); assert.equal(await page.locator('#module option').count(), 13); for (const width of [1440, 390]) { await page.setViewportSize({ width, height: 1000 }); for (const output of samples.outputs) { await page.locator('#module').selectOption(output.id); assert.ok((await page.locator('article.active .finding').textContent()).includes(output.finding)); assert.ok(!(await page.locator('article.active').textContent()).includes('49天')); const size = await page.evaluate(() => ({ width: document.documentElement.clientWidth, scroll: document.documentElement.scrollWidth })); assert.ok(size.scroll <= size.width);record('feedback-preview-content-and-overflow', { width, module: output.id }); } await page.screenshot({ path: path.join(root, `反馈预览-${width}.png`), fullPage: true }); } await context.close(); } finally { await browser.close(); } assert.deepEqual(errors, []); const sha = buffer => crypto.createHash('sha256').update(buffer).digest('hex'); const skill = path.resolve('skills/ksf-workshop-runtime'); const manifest = (await fs.readFile(path.join(skill, 'FILES.sha256'), 'utf8')).trim().split(/\r?\n/); for (const entry of manifest) { const [hash, name] = entry.split(' ');assert.equal(sha(await fs.readFile(path.join(skill, name))), hash, name); } const result = { schema: 'ksf.workshop.local-final-validation.v1', checkedAt: new Date().toISOString(), checks, browserChecksPassed: checks.length, browserErrors: errors, skillManifestFilesVerified: manifest.length, productionWrites: 0, deploymentPerformed: false, sampleFixtureIsolation: 'browser route interception only', actualHostOrEmployeeTrial: false, publicSnapshotReplay: 'existing read-only production audit data, not newly published content' }; await fs.writeFile(path.join(root, 'validation.json'), JSON.stringify(result, null, 2) + '\n'); console.log(JSON.stringify({ browserChecksPassed: checks.length, errors: errors.length, manifestFiles: manifest.length, productionWrites: 0 }));