#!/usr/bin/env node 'use strict' /** * 守门测试:现状事实基线 docs/standards/architecture-current-state.md 里记录的 * 关键常量必须与代码一致(双向:代码改了要同步文档,文档被改错要打红)。 * * 动机:本项目已经两次因「凭印象改性能代码」返工—— * ① v3.80.0 把「拖动用 DOM transform」误套到平移 → v3.80.1 回退; * ② flush 同步开销优化过了全部门禁却实测零收益。 * 本用例把「现状事实」钉在门禁里,避免文档与代码各自漂移。 * * 只做只读断言,不修改任何代码;失败即 process.exit(1)(与既有 node 测试一致)。 */ const fs = require('fs') const path = require('path') const { execFileSync } = require('child_process') const root = path.join(__dirname, '..') const read = (p) => fs.readFileSync(path.join(root, p), 'utf8') const appJs = read('app.js') const blobStore = read('src/image-blob-store.js') const histStore = read('src/canvas-history-store.js') const sessStore = read('src/workspace-sessions-store.js') const factsDoc = read('docs/standards/architecture-current-state.md') const changelog = read('docs/history/spec-changelog.md') const rulebook = read('docs/standards/engineering-rulebook.md') let failed = 0 const assert = (name, ok, detail) => { if (ok) { console.log(' PASS ' + name) } else { failed++ console.log(' FAIL ' + name + (detail ? ' —— ' + detail : '')) } } const codeValueOf = (src, name) => { const m = src.match(new RegExp('\\b' + name + '\\s*=\\s*(\\d+)')) return m ? Number(m[1]) : null } // ── 1. 数值常量:代码值 == 事实文档记录的现值 ───────────────────────────── const NUMERIC = [ ['W_OBJURL_MAX', appJs, 50], ['W_BLOBREF_MAX', appJs, 50], ['DISPLAY_THUMB_CACHE_MAX', appJs, 300], // v3.26.109:缩略图 1024px(640 时 dpr=2、节点 400px 就会解码原图 → footprint 峰值 2.7G) ['DISPLAY_THUMB_MAX', appJs, 512], ['outThumbCacheMax', appJs, 400], ['W_MAX_LOADED_BOARDS', appJs, 3], ['W_SESSION_MAX', sessStore, 5], ['HISTORY_MAX', histStore, 20], ['HISTORY_MIN_KEEP', histStore, 3], ['W_IMG_URL_TRIES', appJs, 3], ['DEFAULT_BLOB_CACHE_MAX', blobStore, 200], ] console.log('1) 数值常量(代码 == 事实文档)') for (const [name, src, expected] of NUMERIC) { const actual = codeValueOf(src, name) assert(name + ' 代码现值 == ' + expected, actual === expected, '实际 ' + actual) assert(name + ' 文档记录了 ' + expected, factsDoc.includes(name + ' = ' + expected)) } // ── 2. 字符串常量 ──────────────────────────────────────────────────────── console.log('2) 字符串 / 开关常量') assert("IDB_REF_PREFIX = 'ref_'(legacy 形态)", /const IDB_REF_PREFIX = 'ref_'/.test(appJs)) assert("文档记录了 IDB_REF_PREFIX = 'ref_'", factsDoc.includes("IDB_REF_PREFIX = 'ref_'")) assert('W_IMG_BLOB_PRIMARY_DEFAULT = true(新写入主通道启用)', /const W_IMG_BLOB_PRIMARY_DEFAULT = true/.test(appJs)) // ── 3. 视口裁剪余量:统一 280,且不得回退成 560 ───────────── // v3.26.109:cullRect 从 app.js 收编到 src/canvas-geometry.js(cullRectsOf), // v3.26.143:带图节点也回到 280,避免平移边缘反复卸载/重解码;内存靠图片管线控制。 console.log('3) 视口裁剪余量(禁止把 v3.80.0 的 ±560 写回来)') const geomJs = read('src/canvas-geometry.js') const cullStart = geomJs.indexOf('const CULL_PAD_WIDE = 280') const cullEnd = geomJs.indexOf('function nodeVisibleIn') assert('定位到 cullRectsOf 代码块', cullStart > 0 && cullEnd > cullStart) if (cullStart > 0 && cullEnd > cullStart) { const cull = geomJs.slice(cullStart, cullEnd) assert('宽边距常量是 280', /CULL_PAD_WIDE = 280/.test(cull)) assert('带图节点紧边距也是 280', /CULL_PAD_TIGHT = 280/.test(cull)) // 2026-12-02:cullRectsOf 重构成 mk(pad){ const p = pad + extra; ... },变量名从 pad 变 p。 // 守卫改为「先认 p = pad + extra,再数 4 条边都按 p 收放」——语义不变,也不会因为改名而假绿。 const hasP = /const p = pad \+ extra/.test(cull) const hasPad = (cull.match(/- p\b|\+ p\b/g) || []).length assert('裁剪矩形 4 条边都按 p(=pad+extra) 收放', hasP && hasPad === 4, 'p=' + hasP + ' 边数=' + hasPad) assert('裁剪矩形不含 560(历史值已废止)', !/560/.test(cull)) assert('app.js 只做装配(不再内联 cullRect 数值)', !/const cullRect = React\.useMemo/.test(appJs)) assert('文档记录了 280 余量', factsDoc.includes('280')) assert('文档未把 560 当现值', !/余量.{0,6}560/.test(factsDoc)) } // ── 4. 两处阈值并存(含义不同,别被合并成一个) ─────────────────────────── console.log('4) 两处阈值并存') assert('代码含大图判定阈值 3000', /3000/.test(appJs)) assert('代码含画布保存保留阈值 16384', /16384/.test(appJs)) assert('文档同时点名 3000 与 16384', factsDoc.includes('3000') && factsDoc.includes('16384')) // ── 5. 护栏本身必须留在文档里(防止后来人"清理"掉教训) ──────────────────── console.log('5) 护栏条目必须存在') for (const [name, needle] of [ ['平移仍用 setViewport', 'setViewport'], ['平移回归记录(v3.80.0)', 'v3.80.0'], ['回归回退版本(v3.80.1)', 'v3.80.1'], ['flush 零收益记录', '零收益'], ['同步卸载守卫(别删剥离层)', '同步'], ["'v3.6.0' 是构建期占位标记", "'v3.6.0'"], ]) { assert('文档含:' + name, factsDoc.includes(needle)) } assert('变更历史已登记现值条目 1.3.5', /### 1\.3\.5/.test(changelog)) assert('规则库 §13.34.7 的 memBlobs 待办已标注作废', /memBlobs/.test(rulebook) && /已于 v3\.0\.2 解决/.test(rulebook)) // ── 6. 计数类事实:文档里的「模块数 / 快照项数 / 门禁 spec 数 / 门禁链」必须与实际一致 ── // 动机:这些数字此前只靠人维护,已多次悄悄漂移(46 vs 53、38/39 vs 45、47 vs 53、10/11 vs 12、 // 门禁链漏 test:facts)。纳入守门后,改结构就必须同步文档,否则打红。 console.log('6) 计数类事实(文档 == 代码)') const srcCount = fs.readdirSync(path.join(root, 'src')).filter((n) => n.endsWith('.js')).length const readsSnapshot = JSON.parse(read('tests/fixtures/iwb-app-global-reads.json')) const orderSnapshot = JSON.parse(read('tests/fixtures/iwb-source-modules-order.json')) const gateSpecCount = require(path.join(root, 'scripts', 'list-e2e-specs')).discoverSpecs(path.join(root, 'tests')).specs.length assert('文档 §1 模块数 == 实际 ' + srcCount, factsDoc.includes('现 **' + srcCount + '** 个模块')) assert('文档 F11 模块数 == 实际 ' + srcCount, factsDoc.includes('**' + srcCount + ' 个模块')) assert('文档耦合面项数 == 快照长度 ' + readsSnapshot.length, factsDoc.includes('(**' + readsSnapshot.length + '** 项)')) assert('文档 sourceModules 项数 == 快照长度 ' + orderSnapshot.length, factsDoc.includes('顺序(**' + orderSnapshot.length + '** 项)')) assert('文档门禁 spec 数 == 实际 ' + gateSpecCount, factsDoc.includes('**' + gateSpecCount + '** 个进门禁')) assert('文档门禁链含 test:facts', factsDoc.includes('test:facts')) // ── 6b. 行数棘轮硬数字(2026-11-24,P0-②)──────────────────────────────────── // 动机:MAX_APP_JS_LINES 等上限被抄进 CONTRIBUTING 与本文档,此前**无人校验**, // 实测已漂 415 行(文档 8,700 vs 真实 9,115)。规则与测量都在 scripts/ratchet-metrics.js, // 与 sync-facts 共用一份 —— 避免「同步器说改了、守卫说没改」。 console.log('6b) 棘轮硬数字(文档 == 代码)') const ratchetMetrics = require(path.join(root, 'scripts', 'ratchet-metrics')) const measured = ratchetMetrics.measure() for (const [kind, file] of [['contributing', 'CONTRIBUTING.md'], ['arch', 'docs/standards/architecture-current-state.md']]) { const text = fs.readFileSync(path.join(root, file), 'utf8') const res = ratchetMetrics.rewriteDoc(kind, text, measured) assert(file + ' 的棘轮数字与代码一致', res.changed.length === 0, '以下数字过时:' + res.changed.join(', ') + ' —— 跑 `node scripts/sync-facts.js --write` 自动修') } // ── 7. 基线锚点:文档记录的「基线 SHA + 线上版本」必须与实际一致 ────────────── // 动机:本文档第 4 行的锚点写着「每次 main 有新提交或线上发版后必须同步」,但此前 // **没有任何机制强制它** —— 事实上它长期停在 `e40d8b4`/v3.20.0(而实际已是 v3.21.0), // 文档自己也承认「曾长期停在 09bfe61/v3.1.1,误导性极强」。 // // 判据设计(避免"每次提交都红"的无谓摩擦): // 锚点不是跟 HEAD 比,而是跟**最近一次改版本的提交**(bump 版本的 commit)比。 // ⇒ 日常提交/docs 更新**不会**打红;只有**发版**(改 package.json 版本号)才要求 // 同步本文档的锚点。这正好对应文档的原始要求「每次…线上发版后必须同步」。 // 强校验两项:① 锚点 SHA == 最近一次 bump 版本的 commit 的 SHA; // ② 锚点记录的线上版本 == 该 commit 处 package.json 的版本。 console.log('7) 基线锚点(文档 == 实际)') const git = (args) => execFileSync('git', args, { cwd: root, encoding: 'utf-8' }).trim() const versionAt = (sha) => { try { return JSON.parse(execFileSync('git', ['show', sha + ':package.json'], { cwd: root, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] })).version } catch (e) { return '' } } // 最近一次 bump package.json 版本的提交:**按版本值实际变化**定位 // (不能用 `git log -S '"version"'` —— bump 版本并不改变 "version" 这个字符串的出现次数, // 那样会命中历史里任何一个碰过该字段的提交,定位到无关的旧版本。) // 逐个回看 package.json 的历史提交,找到「版本值与父提交不同」的那一个。 let anchorSha = '' let anchorVersion = '' let historyComplete = true const currentVersion = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf-8')).version try { // 浅克隆检测:GitHub Actions 默认 depth=1 ⇒ 父提交不可读 ⇒ 无法定位「bump 版本的提交」。 // CI 已用 `fetch-depth: 0` 取全历史(仓库仅 ~3MB,成本可忽略);此处仍做检测, // 以便在别处的浅克隆环境**降级为只校验版本**而不是给出错误的 SHA 期望。 try { historyComplete = git(['rev-parse', '--is-shallow-repository']) !== 'true' } catch (e) { historyComplete = true } const dirty = git(['status', '--porcelain', 'package.json']) if (dirty) { // package.json 有未提交改动 —— **但这不等于「版本号被 bump 了」** // (例如只改了 test:unit 脚本,版本号没动)。只有**版本值确实变了**才算发版进行中。 const headVersion = versionAt(git(['rev-parse', '--short', 'HEAD'])) if (headVersion && headVersion !== currentVersion) { // 版本号确实变了 ⇒ 发版进行中:锚点取 HEAD(即将产生的提交), // 版本取**工作区的实际值**(那才是要写进文档的版本号)。 anchorSha = git(['rev-parse', '--short', 'HEAD']) anchorVersion = currentVersion } // 否则:版本没变 ⇒ 沿用「最近一次 bump 版本的提交」作为锚点(与干净工作区同逻辑) } if (!anchorSha) { const shas = git(['log', '--format=%h', '--', 'package.json']).split('\n') for (const sha of shas) { if (!sha) continue const v = versionAt(sha) const pv = versionAt(sha + '^') if (!pv) { // 父提交不可读(浅克隆 / 历史被裁剪)⇒ 无法判定该提交是否 bump 了版本。 // 这种情况**不能**当成「没找到锚点」而打红(否则浅克隆环境必然红)—— // 退化判据:若该提交自身的版本 == 当前 package.json 版本,则它就是锚点。 if (v && v === currentVersion) { anchorSha = sha; anchorVersion = v; break } continue } if (v && pv && v !== pv) { anchorSha = sha; anchorVersion = v; break } } } } catch (e) { anchorSha = '' } if (anchorSha) { if (historyComplete) { assert('文档基线锚点 == 最近一次 bump 版本的提交 (' + anchorSha + ')', factsDoc.includes('main = ' + anchorSha), '文档未记录该 SHA;应把第 4 行改为「基线 `main = ' + anchorSha + '`」') } else { console.log(' SKIP 文档基线锚点 SHA 校验(浅克隆,历史不完整 —— 无法定位 bump 提交)') } assert('文档锚点记录的线上版本 == ' + anchorSha + ' 处的版本 (v' + anchorVersion + ')', factsDoc.includes('(线上 `v' + anchorVersion + '+') || factsDoc.includes('(线上 `v' + anchorVersion + '+'), '文档第 4 行的线上版本应与 package.json 在 ' + anchorSha + ' 处的版本一致(v' + anchorVersion + ')') } else { assert('能定位最近一次 bump 版本的提交(用于校验基线锚点)', false, '未能定位锚点 commit') } // ── 8. CONTRIBUTING.md 里的计数类数字必须与实际一致 ────────────────────── // 动机:贡献指南是新人和(未来的)自己的**入口**。若它写错门禁链/文件数, // 照着做会踩空 —— 而「指南里的数字悄悄过期」正是本项目反复出现的问题 // (见 §7 计数类事实的由来)。故把它也纳入守门。 console.log('8) CONTRIBUTING.md 计数(文档 == 实际)') const contribPath = path.join(root, 'CONTRIBUTING.md') if (fs.existsSync(contribPath)) { const contrib = fs.readFileSync(contribPath, 'utf8') const pkg = JSON.parse(read('package.json')) const unitFiles = [...new Set(((pkg.scripts['test:unit'] || '') + ' ' + (pkg.scripts.test || '') + ' ' + (pkg.scripts['test:facts'] || '')).match(/tests\/[a-z0-9-]+\.js/g) || [])] const gateSpecs = require(path.join(root, 'scripts', 'list-e2e-specs')).discoverSpecs(path.join(root, 'tests')).specs.length const srcCount2 = fs.readdirSync(path.join(root, 'src')).filter((n) => n.endsWith('.js')).length assert('CONTRIBUTING 的单测文件数 == 实际 ' + unitFiles.length, contrib.includes(unitFiles.length + ' 个单测文件'), 'CONTRIBUTING.md §3 里的单测文件数应改为 ' + unitFiles.length + " —— 跑 `node scripts/sync-facts.js --write` 自动同步") assert('CONTRIBUTING 的门禁 spec 数 == 实际 ' + gateSpecs, contrib.includes(gateSpecs + ' 个 spec') || contrib.includes('进门禁'), 'CONTRIBUTING.md 里的门禁 spec 数应与实际一致(' + gateSpecs + ')') assert('CONTRIBUTING 的 src 模块数 == 实际 ' + srcCount2, !/本仓有约 \d+ 处源码文本钉点(分布在 \d+ 个文件)/.test(contrib) || /分布在 \d+ 个文件/.test(contrib), 'CONTRIBUTING.md §6 的源码钉点描述应与实际一致') // 注意:package.json 可能**根本没有** dependencies 字段(不是空对象)⇒ 两种都算「无运行时依赖」 const runtimeDeps = pkg.dependencies || pkg.peerDependencies || pkg.optionalDependencies || {} // 桌面版分支:新增 3 个 @tauri-apps 插件作为运行时依赖(Web 版仍为 0) const depNames = Object.keys(runtimeDeps) const desktopOnlyDeps = depNames.every((d) => d.indexOf('@tauri-apps/') === 0) assert('CONTRIBUTING 声明运行时依赖(Web 无 / 桌面仅 Tauri 插件)', (depNames.length === 0 && /运行时依赖[\s\S]{0,60}?无/.test(contrib)) || (desktopOnlyDeps && /Tauri/.test(contrib)), 'CONTRIBUTING.md §2 的运行时依赖描述应与 package.json 一致') } else { console.log(' SKIP(无 CONTRIBUTING.md)') } // ── 9. 门禁完整性:每个单测文件都必须真的被跑(防「孤儿测试」)─────────────── // 动机(2026-10-27 体检发现的真实问题): // `tests/storage-log-failure-test.js` 与 `tests/runtime-diagnostics-hotpath-test.js` // 当时都**存在且能跑通**,但都没接进 `verify:ci` 链 ⇒ **从来没跑过**。 // 「看起来有测试守着,其实没跑」= 假覆盖率,比没测试更危险(掩盖缺陷)。 // 其中 storage-log-failure-test 是 D 阶段为规则库 §13.38 写的 —— 说明规则里写的 // 「有测试守」当时并不成立。(根因:做守门负例时执行过 `git checkout package.json`, // 把未提交的登记一起冲掉了。) // 判据:`tests/*-test.js` 里的每个文件,都必须出现在 verify:ci 链的某个 script 里。 // 确需**有意**排除的(如纯手工探针),必须登记到 ALLOW_ORPHAN 并写明原因 —— // 不允许「悄悄存在但不跑」。 console.log('9) 门禁完整性(孤儿单测)') const ALLOW_ORPHAN = new Map([]) // 文件 → 排除原因(当前为空:所有单测都必须跑) try { const pkg = JSON.parse(read('package.json')) const gateScripts = ['test:unit', 'test', 'test:facts'] const referenced = new Set() for (const k of gateScripts) { for (const m of String(pkg.scripts[k] || '').matchAll(/tests\/[A-Za-z0-9_.-]+\.js/g)) referenced.add(m[0]) } // verify:ci 必须真的串起这三段(否则上面的收集就没有意义) const verifyCi = String(pkg.scripts['verify:ci'] || '') assert('verify:ci 串起 test:unit / test / test:facts', /test:unit/.test(verifyCi) && /\btest\b/.test(verifyCi) && /test:facts/.test(verifyCi), '当前 verify:ci = ' + verifyCi) const allUnitTests = fs.readdirSync(path.join(root, 'tests')).filter((f) => f.endsWith('-test.js')).map((f) => 'tests/' + f) const orphans = allUnitTests.filter((f) => !referenced.has(f) && !ALLOW_ORPHAN.has(f)) assert('所有单测文件都进了门禁(无孤儿)', orphans.length === 0, '以下单测存在但不跑:「' + orphans.join('、') + '」—— 要么接进 verify:ci 链,要么登记到 ALLOW_ORPHAN 并写明原因') // 反向:门禁引用的文件必须都存在(防止改名后静默失效) const missing = [...referenced].filter((f) => !fs.existsSync(path.join(root, f))) assert('门禁引用的单测文件都存在', missing.length === 0, '以下文件被门禁引用但不存在:「' + missing.join('、') + '」') // 允许排除的必须写明原因(不为空字符串) const badAllow = [...ALLOW_ORPHAN.entries()].filter(([, why]) => !String(why || '').trim()) assert('ALLOW_ORPHAN 的每项都写了排除原因', badAllow.length === 0, '缺原因:「' + badAllow.map(([f]) => f).join('、') + '」') } catch (e) { assert('门禁完整性检查可执行', false, String((e && e.message) || e)) } console.log('') if (failed) { console.error('architecture-facts-guard: ' + failed + ' 项失败') // 2026-11-07:失败时给可执行指引,而不是只说"应为 N" console.log('') console.log('提示:文档/快照类事实可用一条命令同步 ——') console.log(' node scripts/sync-facts.js # 先看差异(dry-run)') console.log(' node scripts/sync-facts.js --write # 写入可机械同步的部分') console.log(' IWB_WRITE_BOUNDARY_SNAPSHOT=1 node tests/architecture-boundary-guard-test.js # 更新耦合面快照') console.log('') process.exit(1) } console.log('architecture-facts-guard: 全部通过')