cardbuddy 0.13.3 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +7 -3
  2. package/dist/cli.js +4 -4
  3. package/dist/config.js +7 -7
  4. package/dist/init.js +15 -4
  5. package/dist/portGuard.js +2 -2
  6. package/dist/preview-editor/assets/index-DnXqKrCc.js +307 -0
  7. package/dist/preview-editor/assets/index-cbTCHp8J.css +1 -0
  8. package/dist/preview-editor/index.html +2 -2
  9. package/dist/standalone.js +14 -6
  10. package/dist/vendored/card-editor/api.js +6 -6
  11. package/dist/vendored/mcp/client.mjs +53 -3
  12. package/dist/vendored/mcp/tools.mjs +17 -1
  13. package/dist/vendored/server/core/ai-chat.js +1443 -271
  14. package/dist/vendored/server/core/cardFiles.js +271 -39
  15. package/dist/vendored/server/core/cardImportMeta.js +16 -0
  16. package/dist/vendored/server/core/chatHistory.js +122 -0
  17. package/dist/vendored/server/core/index.js +10 -3
  18. package/dist/vendored/server/core/turnJournal.js +386 -0
  19. package/dist/vendored/skills/card-skill-trainer/SKILL.md +399 -222
  20. package/dist/vendored/skills/card-skill-trainer/scripts/build_dataset.py +103 -19
  21. package/dist/vendored/skills/card-skill-trainer/scripts/diagnose_case.mjs +378 -200
  22. package/dist/vendored/skills/card-skill-trainer/scripts/lib/runs.mjs +147 -0
  23. package/dist/vendored/skills/card-skill-trainer/scripts/lib/scoring.mjs +297 -4
  24. package/dist/vendored/skills/card-skill-trainer/scripts/plan_next_round.mjs +484 -0
  25. package/dist/vendored/skills/card-skill-trainer/scripts/round_diff.mjs +77 -96
  26. package/dist/vendored/skills/card-skill-trainer/scripts/run_round.mjs +237 -62
  27. package/dist/vendored/skills/card-skill-trainer/scripts/score_round.mjs +74 -35
  28. package/dist/vendored/skills/dsl-card-ai/SKILL.md +15 -2
  29. package/dist/vendored/skills/dsl-card-generator/SKILL.md +5 -3
  30. package/dist/vendored/skills/dsl-card-generator/references/generation_pitfalls.md +120 -0
  31. package/dist/vendored/skills/dsl-card-generator/references/previewer_contract.md +10 -0
  32. package/dist/vendored/skills/dsl-card-generator/references/quickref.md +15 -1
  33. package/dist/vendored/skills/dsl-card-generator/references/recipe_snippets/canvas-radar.json +2 -2
  34. package/dist/vendored/skills/dsl-card-generator/references/recipe_snippets/scatter-pill-band.json +10 -0
  35. package/dist/vendored/skills/dsl-card-generator/references/recipes.md +43 -1
  36. package/dist/vendored/skills/dsl-card-generator/references/rules.md +33 -6
  37. package/dist/vendored/skills/dsl-card-generator/references/slices_convention.md +12 -5
  38. package/dist/vendored/skills/dsl-card-generator/scripts/add_component.mjs +5 -10
  39. package/dist/vendored/skills/dsl-card-generator/scripts/crop_slices.mjs +47 -10
  40. package/dist/vendored/skills/dsl-card-generator/scripts/expand_ir.mjs +12 -4
  41. package/dist/vendored/skills/dsl-card-generator/scripts/lib/design_sample.mjs +388 -328
  42. package/dist/vendored/skills/dsl-card-generator/scripts/lib/slice_pixels.mjs +109 -0
  43. package/dist/vendored/skills/dsl-card-generator/scripts/render_card.mjs +45 -7
  44. package/dist/vendored/skills/dsl-card-generator/scripts/route_input.mjs +7 -3
  45. package/dist/vendored/skills/dsl-card-generator/scripts/spec_audit.mjs +110 -23
  46. package/dist/vendored/skills/dsl-card-generator/scripts/spec_to_schema_v3.mjs +2954 -127
  47. package/dist/vendored/skills/dsl-card-generator/scripts/spec_tree.mjs +128 -3
  48. package/dist/vendored/skills/dsl-card-generator/scripts/validate_schema.py +28 -0
  49. package/dist/vendored/skills/finmall-card-sync/SKILL.md +1 -1
  50. package/dist/vendored/skills/finmall-session-navigator/SKILL.md +1 -1
  51. package/dist/vendored/skills/finmall-session-navigator/scripts/session-manager.mjs +1 -1
  52. package/dist/vendored/skills/shared/finmall-config.mjs +4 -4
  53. package/dist/vendored/skills/sketch-spec-to-card/SKILL.md +2 -2
  54. package/dist/vendored/skills/sketch-spec-to-card/scripts/parse_meaxure.py +29 -2
  55. package/dist/vendored/tools/finmall-env.mjs +6 -6
  56. package/package.json +1 -1
  57. package/dist/preview-editor/assets/index-CQScMhyg.css +0 -1
  58. package/dist/preview-editor/assets/index-pW1J4vP3.js +0 -276
  59. package/dist/vendored/skills/card-skill-trainer/baselines/v3-r038n.json +0 -43
  60. package/dist/vendored/skills/card-skill-trainer/baselines/v3-r039n.json +0 -47
  61. package/dist/vendored/skills/card-skill-trainer/baselines/v3-r050n.json +0 -48
@@ -0,0 +1,147 @@
1
+ // 轮次产物读取与轮间对比(唯一来源)。
2
+ // round_diff.mjs / score_round.mjs / plan_next_round.mjs 共用本模块,禁止各写一套读取逻辑:
3
+ // 「一轮」有两种载体——完整轮目录 training/runs/<round>/reports/*.json,
4
+ // 以及入库的压缩锚点 training/anchors/<round>.json(干净克隆无 runs/ 时唯一可对账的基线)。
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+
8
+ /** 报告目录里的附属产物(非单案例报告),统计与对比都要排除。 */
9
+ const AUX_REPORT_RE = /^(summary|skipped|review|semantic|inherited|next-round-plan|convergence-report|lesson-drafts|agent-audit|visual-fix)/
10
+
11
+ /** 目标是否为压缩锚点/汇总 JSON 文件(而非轮目录)。 */
12
+ export function isRunFile(target) {
13
+ return fs.existsSync(target) && fs.statSync(target).isFile()
14
+ }
15
+
16
+ /**
17
+ * 载入一轮的全部单案例报告。
18
+ * @param {string} runDirOrFile 轮目录(training/runs/r262)或压缩锚点文件(training/anchors/r176.json)
19
+ * @returns {Map<string, object>} caseId → report
20
+ */
21
+ export function loadRunReports(runDirOrFile) {
22
+ const resolved = path.resolve(runDirOrFile)
23
+ if (!fs.existsSync(resolved)) throw new Error(`轮次产物不存在:${resolved}`)
24
+ const map = new Map()
25
+ if (fs.statSync(resolved).isFile()) {
26
+ const anchor = JSON.parse(fs.readFileSync(resolved, 'utf8'))
27
+ const list = Array.isArray(anchor.cases) ? anchor.cases : Object.values(anchor.cases || {})
28
+ for (const report of list) if (report && report.caseId) map.set(report.caseId, report)
29
+ if (!map.size) throw new Error(`锚点文件里没有案例:${resolved}`)
30
+ return map
31
+ }
32
+ const reportDir = path.join(resolved, 'reports')
33
+ if (!fs.existsSync(reportDir)) throw new Error(`找不到报告目录:${reportDir}`)
34
+ for (const file of fs.readdirSync(reportDir)) {
35
+ if (!file.endsWith('.json') || AUX_REPORT_RE.test(file)) continue
36
+ let report = null
37
+ try { report = JSON.parse(fs.readFileSync(path.join(reportDir, file), 'utf8')) } catch { continue }
38
+ // 只认带 caseId 的对象报告,防止 skipped-*.json 之类附属产物混入统计
39
+ if (report && !Array.isArray(report) && typeof report.caseId === 'string') map.set(report.caseId, report)
40
+ }
41
+ return map
42
+ }
43
+
44
+ /** 轮目录的 reports/ 路径(锚点文件则返回其所在目录)。 */
45
+ export function reportsDirOf(runDirOrFile) {
46
+ const resolved = path.resolve(runDirOrFile)
47
+ return isRunFile(resolved) ? path.dirname(resolved) : path.join(resolved, 'reports')
48
+ }
49
+
50
+ /** 读取 score_round 产出的 summary.json(不存在返回 null)。 */
51
+ export function loadRunSummary(runDirOrFile) {
52
+ const file = path.join(reportsDirOf(runDirOrFile), 'summary.json')
53
+ if (!fs.existsSync(file)) return null
54
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }
55
+ }
56
+
57
+ const average = (values) => {
58
+ const numbers = values.filter((value) => typeof value === 'number' && Number.isFinite(value))
59
+ return numbers.length ? numbers.reduce((sum, value) => sum + value, 0) / numbers.length : null
60
+ }
61
+
62
+ /** 轮级指标聚合(round_diff 的 delta 表、plan_next_round 的门禁都吃这份口径)。 */
63
+ export function roundMetrics(reports) {
64
+ const list = reports instanceof Map ? [...reports.values()] : reports
65
+ const fidelities = list.map((report) => report.fidelity?.overall).filter((v) => typeof v === 'number')
66
+ return {
67
+ total: list.length,
68
+ passed: list.filter((report) => report.passed).length,
69
+ passRate: list.length ? list.filter((report) => report.passed).length / list.length : null,
70
+ fidelity: average(list.map((report) => report.fidelity?.overall)),
71
+ pixel: average(list.map((report) => report.pixel?.ratio)),
72
+ position: average(list.map((report) => report.fidelity?.position)),
73
+ structure: average(list.map((report) => report.pixel?.structure)),
74
+ components: average(list.map((report) => report.fidelity?.components)),
75
+ minFidelity: fidelities.length ? Math.min(...fidelities) : null,
76
+ }
77
+ }
78
+
79
+ /**
80
+ * 轮间对比:状态迁移(修复/回归/持续失败)+ 逐案例指标 delta + 两轮均值。
81
+ * @param {Map<string,object>} fromReports 基线轮(或压缩锚点)
82
+ * @param {Map<string,object>} toReports 本轮
83
+ */
84
+ export function compareRounds(fromReports, toReports) {
85
+ const fixed = []
86
+ const regressed = []
87
+ const stillFailing = []
88
+ const added = []
89
+ const metricDeltas = []
90
+ const pickers = {
91
+ fidelity: (report) => report.fidelity?.overall,
92
+ pixel: (report) => report.pixel?.ratio,
93
+ position: (report) => report.fidelity?.position,
94
+ structure: (report) => report.pixel?.structure,
95
+ components: (report) => report.fidelity?.components,
96
+ }
97
+ for (const [caseId, toReport] of toReports) {
98
+ const fromReport = fromReports.get(caseId)
99
+ if (!fromReport) { added.push(caseId); continue }
100
+ const name = toReport.name || toReport.artboardName || fromReport.name || fromReport.artboardName || ''
101
+ if (fromReport.passed && !toReport.passed) regressed.push({ caseId, name })
102
+ else if (!fromReport.passed && toReport.passed) fixed.push({ caseId, name })
103
+ else if (!fromReport.passed && !toReport.passed) stillFailing.push({ caseId, name })
104
+ const delta = {}
105
+ for (const [key, pick] of Object.entries(pickers)) {
106
+ const before = pick(fromReport)
107
+ const after = pick(toReport)
108
+ if (typeof before === 'number' && typeof after === 'number') delta[key] = after - before
109
+ }
110
+ if (Object.keys(delta).length) metricDeltas.push({ caseId, delta })
111
+ }
112
+ const removed = [...fromReports.keys()].filter((caseId) => !toReports.has(caseId))
113
+ return {
114
+ fixed,
115
+ regressed,
116
+ stillFailing,
117
+ added,
118
+ removed,
119
+ metricDeltas,
120
+ sharedCount: toReports.size - added.length,
121
+ from: roundMetrics(fromReports),
122
+ to: roundMetrics(toReports),
123
+ }
124
+ }
125
+
126
+ /** 列出 training/runs 下已有轮目录(按轮号数字升序,非 rNNN 命名按字典序排在后面)。 */
127
+ export function listRounds(runsRoot) {
128
+ if (!fs.existsSync(runsRoot)) return []
129
+ const roundKey = (name) => {
130
+ const matched = /^r(\d+)/.exec(name)
131
+ return matched ? Number(matched[1]) : Number.NaN
132
+ }
133
+ return fs.readdirSync(runsRoot, { withFileTypes: true })
134
+ .filter((entry) => entry.isDirectory())
135
+ .map((entry) => entry.name)
136
+ .filter((name) => fs.existsSync(path.join(runsRoot, name, 'reports')))
137
+ .sort((a, b) => {
138
+ const left = roundKey(a)
139
+ const right = roundKey(b)
140
+ if (Number.isNaN(left) && Number.isNaN(right)) return a.localeCompare(b)
141
+ if (Number.isNaN(left)) return 1
142
+ if (Number.isNaN(right)) return -1
143
+ return left - right
144
+ })
145
+ }
146
+
147
+ export { AUX_REPORT_RE, average }
@@ -137,7 +137,7 @@ export function rectMask(normalizedRects, width, height) {
137
137
  return mask
138
138
  }
139
139
 
140
- export function imageFidelity(designBuffer, renderBuffer, exclusionRects = []) {
140
+ export function imageFidelity(designBuffer, renderBuffer, exclusionRects = [], pixelOnlyRects = []) {
141
141
  try {
142
142
  const designPng = PNG.sync.read(designBuffer)
143
143
  const renderPng = PNG.sync.read(renderBuffer)
@@ -151,7 +151,7 @@ export function imageFidelity(designBuffer, renderBuffer, exclusionRects = []) {
151
151
  Math.max(designPng.width, renderPng.width)))
152
152
  const left = resizePixels(designPng, width, height)
153
153
  const right = resizePixels(renderPng, width, height)
154
- const mask = rectMask(exclusionRects, width, height)
154
+ const mask = rectMask([...exclusionRects, ...pixelOnlyRects], width, height)
155
155
  let different = 0
156
156
  let compared = 0
157
157
  for (let index = 0; index < left.length; index += 4) {
@@ -521,5 +521,298 @@ export function fidelityScore(image, expected, actual, textRecallValue, position
521
521
  }
522
522
  }
523
523
 
524
- // ── Post-rendering vertical layout correction ──
525
- // Compares rendered text element y-positions with spec coordinates,
524
+ // ── 单案例通过门(唯一来源)──
525
+ // run_round 的 passed 判定、score_round 的失败签名/晋级门、plan_next_round 的归因聚类、
526
+ // SKILL.md 的验收表全部以本表为准。改门必须同步改 SKILL.md:
527
+ // tools/tests/scoring.test.mjs 会反向断言文档表格里的数字与此处逐条一致(防口径漂移)。
528
+ export const PASS_GATE = [
529
+ { key: 'validate', label: 'validate ERROR', op: '<=', target: 0, pick: (report) => report.validate?.errors ?? 0 },
530
+ { key: 'lint', label: 'lint ERROR', op: '<=', target: 0, pick: (report) => report.lint?.errors ?? 0 },
531
+ { key: 'render', label: '渲染失败', op: '<=', target: 0, pick: (report) => (report.error ? 1 : 0) },
532
+ { key: 'pixelDiff', label: '像素差异', op: '<=', target: 0.08, pick: (report) => report.pixel?.ratio },
533
+ { key: 'overall', label: 'UI 还原度', op: '>=', target: 0.85, pick: (report) => report.fidelity?.overall },
534
+ { key: 'components', label: '组件相似度', op: '>=', target: 0.75, pick: (report) => report.fidelity?.components },
535
+ { key: 'position', label: '位置还原度', op: '>=', target: 0.80, pick: (report) => report.fidelity?.position },
536
+ { key: 'textOverflow', label: '文本溢出', op: '>=', target: 0.90, pick: (report) => report.fidelity?.textOverflow },
537
+ { key: 'structure', label: '结构还原度', op: '>=', target: 0.85, pick: (report) => report.pixel?.structure },
538
+ { key: 'color', label: '色彩还原度', op: '>=', target: 0.90, pick: (report) => report.pixel?.color },
539
+ { key: 'dimension', label: '尺寸还原度', op: '>=', target: 0.95, pick: (report) => report.pixel?.dimension },
540
+ { key: 'duplication', label: '重复内容', op: '>=', target: 0.95, pick: (report) => report.duplication?.overall ?? 1 },
541
+ ]
542
+
543
+ /**
544
+ * 归一化缺口:该维度离门还差多少(相对目标的占比,0=达标,越大越严重)。
545
+ * 缺失指标(null/NaN)按最严重处理,避免「没跑出分」被当成通过。
546
+ */
547
+ function gateDeficit(entry, actual) {
548
+ if (typeof actual !== 'number' || !Number.isFinite(actual)) return 1
549
+ if (entry.op === '<=') {
550
+ if (actual <= entry.target) return 0
551
+ return entry.target === 0 ? 1 : (actual - entry.target) / entry.target
552
+ }
553
+ if (actual >= entry.target) return 0
554
+ return entry.target === 0 ? 1 : (entry.target - actual) / entry.target
555
+ }
556
+
557
+ /**
558
+ * 逐维评估单案例门。返回全部未达标维度(按缺口降序),供报告落盘与失败聚类使用。
559
+ * @param {object} report run_round 产出的单案例报告
560
+ * @returns {{passed: boolean, failures: Array<{key: string, label: string, op: string, target: number, actual: number|null, deficit: number}>}}
561
+ */
562
+ export function evaluatePassGate(report) {
563
+ const failures = []
564
+ for (const entry of PASS_GATE) {
565
+ const actual = entry.pick(report || {})
566
+ const numeric = typeof actual === 'number' && Number.isFinite(actual)
567
+ const met = numeric && (entry.op === '<=' ? actual <= entry.target : actual >= entry.target)
568
+ if (met) continue
569
+ failures.push({
570
+ key: entry.key,
571
+ label: entry.label,
572
+ op: entry.op,
573
+ target: entry.target,
574
+ actual: numeric ? actual : null,
575
+ deficit: Number(gateDeficit(entry, actual).toFixed(4)),
576
+ })
577
+ }
578
+ failures.sort((a, b) => b.deficit - a.deficit)
579
+ return { passed: failures.length === 0, failures }
580
+ }
581
+
582
+ // 签名词表沿用历史口径(round_diff / lessons 里的旧签名仍可对齐),
583
+ // 新增 render-failed 与 text-overflow-below-90% 两类此前被吞进 metric-gate 的失败。
584
+ const SIGNATURE_BY_KEY = {
585
+ validate: (failure) => `validate-errors:${failure.actual ?? 0}`,
586
+ lint: (failure) => `lint-errors:${failure.actual ?? 0}`,
587
+ render: () => 'render-failed',
588
+ pixelDiff: () => 'pixel-diff-over-8%',
589
+ overall: () => 'overall-fidelity-below-85%',
590
+ components: () => 'component-count-mismatch',
591
+ position: () => 'position-accuracy-below-80%',
592
+ textOverflow: () => 'text-overflow-below-90%',
593
+ structure: () => 'layout-structure-mismatch',
594
+ color: () => 'color-distribution-mismatch',
595
+ dimension: () => 'aspect-ratio-mismatch',
596
+ duplication: () => 'duplicate-content-detected',
597
+ }
598
+
599
+ /**
600
+ * 主失败签名:取「归一化缺口最大」的维度,而不是固定优先级顺序。
601
+ * 旧实现按写死顺序命中即返回,会把 comp=0.42/pos=0.42 的缺组件卡报成
602
+ * duplicate-content-detected(重影只超 1 处),把下一轮修复带偏。
603
+ * @returns {string|null} 通过时返回 null
604
+ */
605
+ export function failureSignature(report) {
606
+ if (report?.error) return `case-error:${errorKind(report.error)}`
607
+ const { failures } = evaluatePassGate(report)
608
+ if (!failures.length) return null
609
+ const worst = failures[0]
610
+ return (SIGNATURE_BY_KEY[worst.key] || (() => worst.key))(worst)
611
+ }
612
+
613
+ /** 异常文本粗分桶:跨轮签名趋势要稳定,原始 error 串带案例细节会碎成一次性签名。 */
614
+ export function errorKind(message) {
615
+ const text = String(message || '')
616
+ if (/render|chrome|cdp|screenshot|websocket|timeout|超时|session|浏览器/i.test(text)) return 'render-failed'
617
+ // 缺输入要先于 generate 判定:`ENOENT ... spec.json` 里含 "json",否则会被误归成生成失败
618
+ if (/enoent|no such file|not found|找不到/i.test(text)) return 'missing-input'
619
+ if (/generate|schema|json|validate|lint/i.test(text)) return 'generate-failed'
620
+ return 'other'
621
+ }
622
+
623
+ // 维度 → 失败类默认归属(SKILL.md 的 PARSER/DSL/STYLE/DATA/INTERACTION/ASSET/EVALUATOR 分类)
624
+ const FAILURE_CLASS_BY_KEY = {
625
+ validate: 'DSL',
626
+ lint: 'DSL',
627
+ render: 'EVALUATOR',
628
+ pixelDiff: 'STYLE',
629
+ overall: 'STYLE',
630
+ components: 'DSL',
631
+ position: 'STYLE',
632
+ textOverflow: 'STYLE',
633
+ structure: 'STYLE',
634
+ color: 'STYLE',
635
+ dimension: 'STYLE',
636
+ duplication: 'DSL',
637
+ }
638
+
639
+ /**
640
+ * 失败归因(机器可读):只认指标与标注缺陷证据,不认业务词。
641
+ * 结论写进报告 failureClass,plan_next_round 按它聚类并给修复落点建议。
642
+ * @returns {{failureClass: string, reason: string}|null} 通过时返回 null
643
+ */
644
+ export function attributeFailure(report) {
645
+ if (!report || report.passed) return null
646
+ if (report.error) {
647
+ const kind = errorKind(report.error)
648
+ return {
649
+ failureClass: kind === 'generate-failed' ? 'DSL' : 'EVALUATOR',
650
+ reason: `异常 ${kind}:${String(report.error).slice(0, 120)}`,
651
+ }
652
+ }
653
+ const upstream = report.upstream
654
+ if (upstream && upstream.passed === false) {
655
+ const detail = [
656
+ upstream.annotationCompleteness != null ? `标注完整性 ${upstream.annotationCompleteness.toFixed(3)}` : '',
657
+ upstream.textRetention != null ? `文本保留 ${upstream.textRetention.toFixed(3)}` : '',
658
+ upstream.structuralFocus === false ? '结构聚焦失败' : '',
659
+ ].filter(Boolean).join(' / ')
660
+ return { failureClass: 'PARSER', reason: `上游聚焦门未过:${detail || '未知'}` }
661
+ }
662
+ const { failures } = evaluatePassGate(report)
663
+ if (!failures.length) return null
664
+ const worst = failures[0]
665
+ const missingSlices = (upstream?.annotationDefects || [])
666
+ .filter((defect) => defect && defect.type === 'missing-slice').length
667
+ const mediaScore = report.fidelity?.mediaComponents
668
+ if (worst.key === 'components' && (missingSlices > 0 || (typeof mediaScore === 'number' && mediaScore < 0.5))) {
669
+ return {
670
+ failureClass: 'ASSET',
671
+ reason: `组件计数缺口最大(comp=${fmtNum(worst.actual)}),且标注缺切图 ${missingSlices} 处 / 媒体得分 ${fmtNum(mediaScore)}:素材或裁切兜底问题优先`,
672
+ }
673
+ }
674
+ if (worst.key === 'pixelDiff' && missingSlices > 0 && (report.pixel?.structure ?? 0) >= 0.85) {
675
+ return {
676
+ failureClass: 'ASSET',
677
+ reason: `结构达标(struct=${fmtNum(report.pixel?.structure)})但像素差 ${fmtNum(report.pixel?.ratio)},标注缺切图 ${missingSlices} 处:差异主要来自素材来源`,
678
+ }
679
+ }
680
+ const textRecall = report.textRecall
681
+ if (typeof textRecall === 'number' && textRecall < 0.85 && ['overall', 'components', 'position'].includes(worst.key)) {
682
+ return { failureClass: 'DATA', reason: `文本召回 ${fmtNum(textRecall)} 偏低,绑定/文案派生丢失主导(最差维度 ${worst.key}=${fmtNum(worst.actual)})` }
683
+ }
684
+ const failureClass = FAILURE_CLASS_BY_KEY[worst.key] || 'STYLE'
685
+ return {
686
+ failureClass,
687
+ reason: `最差维度 ${worst.label}=${fmtNum(worst.actual)}(门 ${worst.op} ${worst.target},缺口 ${(worst.deficit * 100).toFixed(1)}%);未达标 ${failures.length} 项:${failures.map((f) => f.key).join(',')}`,
688
+ }
689
+ }
690
+
691
+ function fmtNum(value) {
692
+ return typeof value === 'number' && Number.isFinite(value) ? value.toFixed(3) : 'N/A'
693
+ }
694
+
695
+ // 掩膜覆盖率复核线:单案例掩膜面积占比超过该值时,「通过」结论必须人工看图复核——
696
+ // 掩膜豁免的是非标字体带 / 缺切图 / 裁切兜底,覆盖过大意味着参与评分的像素已不代表整卡。
697
+ export const MASK_REVIEW_THRESHOLD = 0.25
698
+
699
+ /**
700
+ * 掩膜覆盖率:pixelExclusions(非标字体带 / 缺切图 / 裁切兜底)在卡面上占多大比例。
701
+ * 掩膜是「不计分」而不是「还原对」,覆盖率过高时通过结论不可信,必须人工复核。
702
+ * @param {Array<{x:number,y:number,width:number,height:number,reason?:string}>} rects 归一化矩形
703
+ * @param {number} gridSize 采样网格边长
704
+ * @returns {{total: number, byReason: Object<string, number>}}
705
+ */
706
+ export function exclusionCoverage(rects, gridSize = 128) {
707
+ const list = (rects || []).filter((rect) => rect && Number.isFinite(rect.x) && Number.isFinite(rect.y))
708
+ if (!list.length) return { total: 0, byReason: {} }
709
+ const cells = gridSize * gridSize
710
+ const hit = new Uint8Array(cells)
711
+ const byReason = {}
712
+ for (const rect of list) {
713
+ const reason = String(rect.reason || 'unspecified')
714
+ const x0 = Math.max(0, Math.floor(rect.x * gridSize))
715
+ const y0 = Math.max(0, Math.floor(rect.y * gridSize))
716
+ const x1 = Math.min(gridSize, Math.ceil((rect.x + (rect.width || 0)) * gridSize))
717
+ const y1 = Math.min(gridSize, Math.ceil((rect.y + (rect.height || 0)) * gridSize))
718
+ let count = 0
719
+ for (let y = y0; y < y1; y += 1) {
720
+ for (let x = x0; x < x1; x += 1) {
721
+ const index = y * gridSize + x
722
+ if (hit[index]) continue
723
+ hit[index] = 1
724
+ count += 1
725
+ }
726
+ }
727
+ byReason[reason] = Number((((byReason[reason] || 0) * cells) + count).toFixed(0)) / cells
728
+ }
729
+ const covered = hit.reduce((sum, value) => sum + value, 0)
730
+ return { total: Number((covered / cells).toFixed(4)), byReason }
731
+ }
732
+
733
+ // ── 轮级门(唯一来源)──
734
+ // passRate 目标 0.95:全量规模下允许 5% 尾部失败进入下轮焦点集;
735
+ // below80=0 与 minFidelity>=0.82 是硬底线,防止用通过率松动掩盖灾难性样本。
736
+ export const ROUND_GATE_TARGETS = {
737
+ passRate: 0.95,
738
+ avgFidelity: 0.86,
739
+ avgPosition: 0.80,
740
+ minFidelity: 0.82,
741
+ below80: 0,
742
+ duplicationFailures: 0,
743
+ lintErrors: 0,
744
+ validateErrors: 0,
745
+ renderFailures: 0,
746
+ upstreamFailures: 0,
747
+ }
748
+
749
+ // 泛化盲测门:新批次/未见样本的晋级前置条件(SKILL.md「泛化盲测门」同源)。
750
+ export const GENERALIZATION_GATE = {
751
+ minSamples: 24,
752
+ passRate: 0.85,
753
+ avgFidelity: 0.78,
754
+ maxAnchorGap: 0.10,
755
+ }
756
+
757
+ /**
758
+ * 轮级晋级门评估。target=0 的按计数门(必须恰好 0),其余按比率门(>= target)。
759
+ * @param {object} summary score_round 产出的 summary(或等价字段集合)
760
+ */
761
+ export function evaluateRoundGate(summary) {
762
+ const actualByKey = {
763
+ passRate: summary?.passRate,
764
+ avgFidelity: summary?.avgFidelity,
765
+ avgPosition: summary?.avgPositionFidelity,
766
+ minFidelity: summary?.minFidelity,
767
+ below80: summary?.below80,
768
+ duplicationFailures: summary?.duplicationFailures,
769
+ lintErrors: summary?.lintErrors,
770
+ validateErrors: summary?.validateErrors,
771
+ renderFailures: summary?.renderFailures,
772
+ upstreamFailures: summary?.upstreamFailures,
773
+ }
774
+ const gate = {}
775
+ for (const [key, target] of Object.entries(ROUND_GATE_TARGETS)) {
776
+ const value = actualByKey[key]
777
+ const numeric = typeof value === 'number' && Number.isFinite(value)
778
+ const met = target === 0 ? (numeric && value === 0) : (numeric && value >= target)
779
+ gate[key] = { target, actual: numeric ? value : null, met }
780
+ }
781
+ return gate
782
+ }
783
+
784
+ /**
785
+ * 泛化盲测门评估:盲测轮 + 锚点轮均值对比。
786
+ * @param {object} blindSummary 盲测轮 summary
787
+ * @param {object} anchorSummary 锚点轮 summary(可缺省,缺省时跳过差值项)
788
+ */
789
+ export function evaluateGeneralizationGate(blindSummary, anchorSummary) {
790
+ const blindFidelity = blindSummary?.avgFidelity
791
+ const anchorFidelity = anchorSummary?.avgFidelity
792
+ const gap = typeof blindFidelity === 'number' && typeof anchorFidelity === 'number'
793
+ ? anchorFidelity - blindFidelity
794
+ : null
795
+ const checks = {
796
+ samples: {
797
+ target: `>= ${GENERALIZATION_GATE.minSamples}`,
798
+ actual: blindSummary?.total ?? null,
799
+ met: (blindSummary?.total ?? 0) >= GENERALIZATION_GATE.minSamples,
800
+ },
801
+ passRate: {
802
+ target: GENERALIZATION_GATE.passRate,
803
+ actual: blindSummary?.passRate ?? null,
804
+ met: (blindSummary?.passRate ?? 0) >= GENERALIZATION_GATE.passRate,
805
+ },
806
+ avgFidelity: {
807
+ target: GENERALIZATION_GATE.avgFidelity,
808
+ actual: blindFidelity ?? null,
809
+ met: (blindFidelity ?? 0) >= GENERALIZATION_GATE.avgFidelity,
810
+ },
811
+ anchorGap: {
812
+ target: `<= ${GENERALIZATION_GATE.maxAnchorGap}`,
813
+ actual: gap == null ? null : Number(gap.toFixed(4)),
814
+ met: gap == null ? false : gap <= GENERALIZATION_GATE.maxAnchorGap,
815
+ },
816
+ }
817
+ return { ...checks, passed: Object.values(checks).every((check) => check.met) }
818
+ }