@tbox.cn/app-template-agent 1.0.0-alpha.7 → 1.0.0-alpha.9

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 (161) hide show
  1. package/.gitignore +7 -0
  2. package/.tbox/app.json +1 -1
  3. package/.tbox/default-modules.json +1 -1
  4. package/.tbox/factory/chat.json +9 -0
  5. package/.tbox/miniapp-containers.json +1 -1
  6. package/AGENTS.md +11 -8
  7. package/apps/client/index.html +0 -43
  8. package/apps/client/package.json +1 -0
  9. package/apps/client/scripts/acceptance-changes.test.mjs +97 -0
  10. package/apps/client/scripts/check-evidence.mjs +625 -108
  11. package/apps/client/scripts/color-scan.mjs +66 -0
  12. package/apps/client/scripts/color-scan.test.mjs +25 -0
  13. package/apps/client/scripts/evidence-gate.mjs +337 -0
  14. package/apps/client/scripts/evidence-gate.test.mjs +135 -0
  15. package/apps/client/scripts/experience-checks.mjs +163 -0
  16. package/apps/client/scripts/geometry-kernel.test.mjs +92 -0
  17. package/apps/client/scripts/in-process-checks.mjs +51 -0
  18. package/apps/client/scripts/lib/card-registry.mjs +81 -0
  19. package/apps/client/scripts/lib/card-registry.test.mjs +59 -0
  20. package/apps/client/scripts/lib/evidence-inputs.mjs +91 -0
  21. package/apps/client/scripts/lib/evidence-inputs.test.mjs +27 -0
  22. package/apps/client/scripts/lib/static-render.mjs +35 -0
  23. package/apps/client/scripts/lib/static-render.test.mjs +21 -0
  24. package/apps/client/scripts/probe-checks.mjs +85 -0
  25. package/apps/client/scripts/render-card.mjs +95 -126
  26. package/apps/client/scripts/sample-entries.test.mjs +31 -0
  27. package/apps/client/scripts/storyboard.test.mjs +149 -0
  28. package/apps/client/scripts/surface-css.mjs +54 -0
  29. package/apps/client/scripts/theme-kernel.mjs +236 -0
  30. package/apps/client/scripts/theme-kernel.test.mjs +136 -0
  31. package/apps/client/src/app.config.ts +4 -1
  32. package/apps/client/src/styles/brand.css +13 -14
  33. package/apps/client/src/styles/tailwind.css +20 -21
  34. package/apps/client/vite.config.ts +2 -1
  35. package/apps/server/scripts/probe.mjs +6 -1
  36. package/apps/server/scripts/scenario-lib.mjs +56 -8
  37. package/apps/server/scripts/scenario.mjs +41 -7
  38. package/config/AGENTS.md +1 -0
  39. package/config/chat.json +21 -9
  40. package/docs/agent/agent-prompt.md +1 -1
  41. package/docs/agent/card-action.md +5 -0
  42. package/docs/agent/card.md +45 -2
  43. package/docs/agent/kit.md +3 -3
  44. package/docs/agent/shell.md +1 -0
  45. package/docs/agent/style.md +11 -3
  46. package/docs/agent/tool-emits-card.md +7 -2
  47. package/docs/agent/tool.md +2 -0
  48. package/docs/agent/verify.md +59 -16
  49. package/package.json +21 -7
  50. package/packages/agent-ui-kit/AGENTS.md +1 -1
  51. package/packages/agent-ui-kit/README.md +21 -1
  52. package/packages/agent-ui-kit/catalog.json +8 -4
  53. package/packages/agent-ui-kit/package.json +9 -1
  54. package/packages/agent-ui-kit/src/._surface.tsx +0 -0
  55. package/packages/agent-ui-kit/src/ChatPage.tsx +70 -17
  56. package/packages/agent-ui-kit/src/card/._action-list-pending.test.tsx +0 -0
  57. package/packages/agent-ui-kit/src/card/._define-card.test.ts +0 -0
  58. package/packages/agent-ui-kit/src/card/._view-card-inline.test.tsx +0 -0
  59. package/packages/agent-ui-kit/src/card/._view-card.test.tsx +0 -0
  60. package/packages/agent-ui-kit/src/card/._view-card.tsx +0 -0
  61. package/packages/agent-ui-kit/src/card/action-list-pending.test.tsx +91 -0
  62. package/packages/agent-ui-kit/src/card/define-card.test.ts +25 -0
  63. package/packages/agent-ui-kit/src/card/define-card.ts +18 -5
  64. package/packages/agent-ui-kit/src/card/primitives.test.tsx +10 -0
  65. package/packages/agent-ui-kit/src/card/primitives.tsx +136 -37
  66. package/packages/agent-ui-kit/src/card/view-card-inline.test.tsx +42 -0
  67. package/packages/agent-ui-kit/src/card/view-card.test.tsx +79 -0
  68. package/packages/agent-ui-kit/src/card/view-card.tsx +250 -0
  69. package/packages/agent-ui-kit/src/chat-config.ts +11 -7
  70. package/packages/agent-ui-kit/src/components/ActionBar/DebugButton.test.tsx +3 -0
  71. package/packages/agent-ui-kit/src/components/ActionBar/DebugButton.tsx +2 -7
  72. package/packages/agent-ui-kit/src/components/BottomSheet/._index.test.tsx +0 -0
  73. package/packages/agent-ui-kit/src/components/BottomSheet/._index.tsx +0 -0
  74. package/packages/agent-ui-kit/src/components/BottomSheet/index.test.tsx +90 -0
  75. package/packages/agent-ui-kit/src/components/BottomSheet/index.tsx +129 -0
  76. package/packages/agent-ui-kit/src/components/ChatInput/index.test.tsx +2 -2
  77. package/packages/agent-ui-kit/src/components/ChatInput/index.tsx +22 -17
  78. package/packages/agent-ui-kit/src/components/HistoryEntry/index.tsx +3 -2
  79. package/packages/agent-ui-kit/src/components/MessageBubble/index.tsx +11 -5
  80. package/packages/agent-ui-kit/src/components/QuickCommands/index.test.tsx +3 -1
  81. package/packages/agent-ui-kit/src/components/QuickCommands/index.tsx +31 -8
  82. package/packages/agent-ui-kit/src/components/ScrollToBottomButton/index.tsx +7 -3
  83. package/packages/agent-ui-kit/src/components/ToolCallBlock/index.tsx +4 -2
  84. package/packages/agent-ui-kit/src/index.ts +8 -0
  85. package/packages/agent-ui-kit/src/preview-provider.tsx +47 -0
  86. package/packages/agent-ui-kit/src/shell.contract.json +9 -0
  87. package/packages/agent-ui-kit/src/shell.test.ts +10 -0
  88. package/packages/agent-ui-kit/src/shell.ts +15 -0
  89. package/packages/agent-ui-kit/src/surface.test.tsx +35 -0
  90. package/packages/agent-ui-kit/src/surface.tsx +44 -0
  91. package/packages/agent-ui-kit/src/theme/base.css +9 -11
  92. package/packages/agent-ui-kit/src/theme/contract.json +123 -2
  93. package/packages/agent-ui-kit/src/theme/theme-contract.test.ts +16 -0
  94. package/packages/agent-ui-kit/src/theme/tokens.css +9 -12
  95. package/pnpm-lock.template.yaml +97 -91
  96. package/pnpm-workspace.template.yaml +10 -10
  97. package/profiles/mall/._chat.overrides.json +0 -0
  98. package/profiles/mall/chat.overrides.json +12 -0
  99. package/profiles/mall/config/chat.json +14 -6
  100. package/profiles/mall.json +1 -1
  101. package/scripts/._assert-pack.mjs +0 -0
  102. package/scripts/._deliver.mjs +0 -0
  103. package/scripts/._shell-probe.mjs +0 -0
  104. package/scripts/._storyboard.mjs +0 -0
  105. package/scripts/assert-pack.mjs +48 -0
  106. package/scripts/check-css-target.mjs +6 -3
  107. package/scripts/check-fast.mjs +1 -0
  108. package/scripts/checks.json +400 -26
  109. package/scripts/deliver.mjs +183 -0
  110. package/scripts/lib/._chrome-pipe.mjs +0 -0
  111. package/scripts/lib/._geometry-kernel.mjs +0 -0
  112. package/scripts/lib/chrome-pipe.mjs +95 -0
  113. package/scripts/lib/geometry-kernel.mjs +137 -0
  114. package/scripts/shell-probe.mjs +283 -0
  115. package/scripts/storyboard.mjs +350 -0
  116. package/.tbox/card-render/baseline/demo.png +0 -0
  117. package/.tbox/card-render/demo.html +0 -342
  118. package/.tbox/card-render/demo.png +0 -0
  119. package/.tbox/card-render/scale-demo.audit.html +0 -984
  120. package/.tbox/card-render/scale-demo.html +0 -939
  121. package/.tbox/evidence/cards.txt +0 -1
  122. package/.tbox/evidence/gate.json +0 -1
  123. package/.tbox/evidence/last-gate.json +0 -1
  124. package/.tbox/evidence/scenarios.json +0 -1
  125. package/apps/client/.tbox-gen/app-registry.ts +0 -3
  126. package/apps/client/.tbox-gen/documents/_tbox/card-preview.html +0 -62
  127. package/apps/client/.tbox-gen/documents/index.html +0 -63
  128. package/apps/client/.tbox-gen/entries/card-preview.tsx +0 -6
  129. package/apps/client/.tbox-gen/entries/index.tsx +0 -11
  130. package/apps/client/.tbox-gen/manifest.json +0 -17
  131. package/apps/client/.tbox-gen/registry.client.ts +0 -6
  132. package/apps/client/.tbox-gen/registry.server.ts +0 -15
  133. package/apps/client/STYLE_GUIDE.md +0 -48
  134. package/apps/client/VISUAL_RESTORE.md +0 -90
  135. package/profiles/mall/config/llm_provider.json +0 -5
  136. package/profiles/mall/config/plugins.json +0 -3
  137. package/scripts/compat-probe.mjs +0 -108
  138. package/scripts/gen-tailwind-sources.mjs +0 -55
  139. /package/.tbox/{card-render/._demo.html → factory/._chat.json} +0 -0
  140. /package/{.tbox/card-render/._demo.png → apps/client/scripts/._acceptance-changes.test.mjs} +0 -0
  141. /package/{.tbox/card-render/._scale-demo.audit.html → apps/client/scripts/._color-scan.mjs} +0 -0
  142. /package/{.tbox/card-render/._scale-demo.html → apps/client/scripts/._color-scan.test.mjs} +0 -0
  143. /package/{.tbox/card-render/baseline/._demo.png → apps/client/scripts/._evidence-gate.mjs} +0 -0
  144. /package/{.tbox/evidence/._cards.txt → apps/client/scripts/._evidence-gate.test.mjs} +0 -0
  145. /package/{.tbox/evidence/._gate.json → apps/client/scripts/._experience-checks.mjs} +0 -0
  146. /package/{.tbox/evidence/._last-gate.json → apps/client/scripts/._geometry-kernel.test.mjs} +0 -0
  147. /package/{.tbox/evidence/._scenarios.json → apps/client/scripts/._in-process-checks.mjs} +0 -0
  148. /package/apps/client/{._STYLE_GUIDE.md → scripts/._probe-checks.mjs} +0 -0
  149. /package/apps/client/{._VISUAL_RESTORE.md → scripts/._sample-entries.test.mjs} +0 -0
  150. /package/apps/client/{.tbox-gen/._app-registry.ts → scripts/._storyboard.test.mjs} +0 -0
  151. /package/apps/client/{.tbox-gen/._manifest.json → scripts/._surface-css.mjs} +0 -0
  152. /package/apps/client/{.tbox-gen/._registry.client.ts → scripts/._theme-kernel.mjs} +0 -0
  153. /package/apps/client/{.tbox-gen/._registry.server.ts → scripts/._theme-kernel.test.mjs} +0 -0
  154. /package/apps/client/{.tbox-gen/documents/._index.html → scripts/lib/._card-registry.mjs} +0 -0
  155. /package/apps/client/{.tbox-gen/documents/_tbox/._card-preview.html → scripts/lib/._card-registry.test.mjs} +0 -0
  156. /package/apps/client/{.tbox-gen/entries/._card-preview.tsx → scripts/lib/._evidence-inputs.mjs} +0 -0
  157. /package/apps/client/{.tbox-gen/entries/._index.tsx → scripts/lib/._evidence-inputs.test.mjs} +0 -0
  158. /package/{profiles/mall/config/._llm_provider.json → apps/client/scripts/lib/._static-render.mjs} +0 -0
  159. /package/{profiles/mall/config/._plugins.json → apps/client/scripts/lib/._static-render.test.mjs} +0 -0
  160. /package/{scripts/._compat-probe.mjs → packages/agent-ui-kit/src/._preview-provider.tsx} +0 -0
  161. /package/{scripts/._gen-tailwind-sources.mjs → packages/agent-ui-kit/src/._surface.test.tsx} +0 -0
@@ -3,8 +3,8 @@
3
3
  * check-evidence — `check:fast` 的证据包(T0 增强)。
4
4
  *
5
5
  * 一个进程里跑四步,任何一步失败即给出可执行的修复信息:
6
- * ① styles —— 用与构建相同的 less 编译应用品牌样式;
7
- * ② primitives —— 卡片样例过 schema、出卡/动作类型已注册、出卡提示、字号下限、颜色语法;
6
+ * ① styles —— 用与 dev/build 相同的 Vite + Tailwind 管线编译整份表面样式(哨兵 + 体积自检);
7
+ * ② primitives —— 卡片样例过 schema、出卡/动作类型已注册、出卡提示、档外字号、类名死码;
8
8
  * ③ render —— 每张卡 × 每个样例经真实 React 组件渲染(SSR),不抛错;
9
9
  * ④ scenarios —— `scenarios/*.json` 全部通过(没有场景记 notRun,不算失败)。
10
10
  *
@@ -15,9 +15,21 @@
15
15
  * 退出码:0 = 无错误(告警不影响);1 = 有错误。
16
16
  */
17
17
  import { execFileSync } from 'node:child_process';
18
- import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
18
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
19
19
  import path from 'node:path';
20
20
  import process from 'node:process';
21
+ import { createHash } from 'node:crypto';
22
+ import { createServer as createHttpServer } from 'node:http';
23
+ import { createRequire } from 'node:module';
24
+ import { buildSurfaceCss } from './surface-css.mjs';
25
+ import { duplicateSampleLabels, sampleEntries } from './render-card.mjs';
26
+ import { collectCards, cardSourceHint, cardMetaSourceHint } from './lib/card-registry.mjs';
27
+ import { createStaticRenderer } from './lib/static-render.mjs';
28
+ import { evidenceInputFiles } from './lib/evidence-inputs.mjs';
29
+ import { STATIC_CHECKS, runStaticChecks } from './experience-checks.mjs';
30
+ import { IN_PROCESS_CHECKS, runInProcessChecks } from './in-process-checks.mjs';
31
+ import { PROBE_CHECKS, STORYBOARD_CHECKS, mergeProbeChecks, mergeStoryboardChecks } from './probe-checks.mjs';
32
+ import { acceptanceChangesOf, acceptanceDrift, capabilityDrift, defaultModuleDrift, contrastRatio, coverageSets, hashSourceTree, matchFrame, parseColor, resolvePolicy, scenarioDrift, scenarioKey, shouldReopen, storyboardCoverage, summarizeAcceptanceChanges, versionAtLeast } from './evidence-gate.mjs';
21
33
 
22
34
  // 门禁里的场景与渲染不写真实状态文件。
23
35
  process.env.TBOX_STATE_MEMORY ??= '1';
@@ -28,8 +40,6 @@ const args = new Set(process.argv.slice(2));
28
40
  const withRender = !args.has('--no-render');
29
41
  const withScenarios = !args.has('--no-scenarios');
30
42
 
31
- const MIN_DESIGN_FONT_PX = 22; // ≈11 屏幕像素(750 设计稿,rootValue 100)
32
-
33
43
  const steps = [];
34
44
  const warnings = [];
35
45
  const notRun = [];
@@ -37,6 +47,9 @@ const errors = [];
37
47
  let scenarioResults = [];
38
48
  let scenarioInstances = [];
39
49
  const cardDigests = [];
50
+ let historyRendered = 0;
51
+ let experienceItems = [];
52
+ let cardFacts = [];
40
53
 
41
54
  const json = (value) => JSON.stringify(value);
42
55
 
@@ -54,6 +67,7 @@ function fail(step, items) {
54
67
  // 在仓库内(非发布态)会因无扩展名 import 解析失败。这里只需要 TSX 转换、别名与 less。
55
68
  const { createServer } = await import('vite');
56
69
  const react = (await import('@vitejs/plugin-react')).default;
70
+ const tailwindcss = (await import('@tailwindcss/vite')).default;
57
71
  let vite;
58
72
  const bootstrapStart = performance.now();
59
73
  try {
@@ -62,15 +76,21 @@ try {
62
76
  root: clientDir,
63
77
  appType: 'custom',
64
78
  logLevel: 'error',
65
- plugins: [react()],
79
+ plugins: [tailwindcss(), react()],
66
80
  resolve: {
67
81
  alias: {
68
82
  '@': path.join(clientDir, 'src'),
69
83
  '@config': path.join(appDir, 'config'),
70
84
  },
71
85
  },
72
- server: { middlewareMode: true, fs: { allow: [appDir] } },
86
+ // 零 socket:HMR 挂到永不 listen 的 http server,避免自建 24678 监听。
87
+ server: { middlewareMode: true, hmr: { server: createHttpServer() }, fs: { allow: [appDir] } },
73
88
  optimizeDeps: { noDiscovery: true, include: [] },
89
+ // SSR 加载客户端 registry 时,依赖里带 CSS 的包必须交给 Vite 内联处理:
90
+ // Node 直连 antd-mobile 的 CJS 入口会 require 它自己的 global.css,直接 SyntaxError。
91
+ // 新增同类运行时依赖(带 CSS 副作用)时补进这张名单,否则 pnpm check:fast 的
92
+ // registry 步骤会在模块客户端代码 import 到它时报「Unexpected token ':'」。
93
+ ssr: { noExternal: ['antd-mobile'] },
74
94
  });
75
95
  steps.push({ name: 'vite', ok: true, ms: Math.round(performance.now() - bootstrapStart) });
76
96
  } catch (error) {
@@ -89,6 +109,13 @@ const registryServer = await vite.ssrLoadModule('/@fs' + path.join(clientDir, '.
89
109
  return undefined;
90
110
  });
91
111
 
112
+ // 证据面卡片视图:与运行时同序(app 先、模块后;后者覆盖)——模块卡不能只存在于运行时。
113
+ const cardView = collectCards({ server: registryServer, client: registryClient });
114
+ const mergedMetas = cardView.metas;
115
+ const mergedComponents = cardView.components;
116
+ const cardProvenance = cardView.provenance;
117
+ for (const item of cardView.warnings) warn(item.id, item.message);
118
+
92
119
  // ── 1. styles ───────────────────────────────────────────────────────
93
120
  async function checkStyles() {
94
121
  const started = performance.now();
@@ -102,10 +129,42 @@ async function checkStyles() {
102
129
  steps.push({ name: 'styles', ok: true, ms: Math.round(performance.now() - started), skipped: true });
103
130
  return;
104
131
  }
105
- // 用同一个 Vite 实例过一遍(CSS 由 Vite 的 postcss 管线解析):不再依赖 less。
132
+ // 与 dev/build 同一条管线(surface-css.mjs):不是「brand.css 语法没坏」,
133
+ // 而是「整份表面样式真的生成了」——空 CSS / 缺哨兵一律失败,截图与证据才可信。
106
134
  try {
107
- await vite.transformRequest('/src/styles/brand.css');
108
- steps.push({ name: 'styles', ok: true, ms: Math.round(performance.now() - started) });
135
+ const surface = await buildSurfaceCss(vite, { clientDir, appDir });
136
+ checkUtilityClasses(surface.cssText);
137
+ const moduleSources = surface.moduleSources ?? [];
138
+ const moduleIds = new Set(moduleSources.map((dir) => path.basename(path.dirname(path.dirname(dir)))));
139
+ const registryFile = path.join(clientDir, '.tbox-gen/registry.client.ts');
140
+ const registryText = existsSync(registryFile) ? readFileSync(registryFile, 'utf8') : '';
141
+ const expectedModuleIds = new Set(
142
+ [...registryText.matchAll(/\/(module-[^/'"]+)\/src\/client\/index\.ts/g)].map((match) => match[1]),
143
+ );
144
+ const expectedModules = expectedModuleIds.size || (Array.isArray(registryClient?.modules) ? registryClient.modules.length : 0);
145
+ const missingModuleIds = [...expectedModuleIds].filter((id) => !moduleIds.has(id));
146
+ const missingModuleCss = moduleIds.has('module-mall-core')
147
+ ? ['#fff8e9', 'container-type'].filter((token) => !surface.cssText.includes(token))
148
+ : [];
149
+ if (surface.bytes < 20000 || surface.missing.length > 0) {
150
+ fail('styles', [{
151
+ id: 'styles-empty',
152
+ message: `表面 CSS 不可信:${surface.bytes} 字节,缺哨兵 ${surface.missing.join('、') || '无'}`,
153
+ fix: '确认 apps/client/vite.config.ts 的 tboxModuleSourcesPlugin 在 tailwindcss() 之前;证据与 dev/build 共用 surface-css.mjs 与 app-build 的模块发现',
154
+ recipe: 'style',
155
+ }]);
156
+ steps.push({ name: 'styles', ok: false, ms: Math.round(performance.now() - started), cssBytes: surface.bytes, moduleSources: moduleSources.length, expectedModules });
157
+ } else if (moduleSources.length < expectedModules || missingModuleIds.length > 0 || missingModuleCss.length > 0) {
158
+ fail('styles', [{
159
+ id: 'styles-module-sources-missing',
160
+ message: `模块样式未进入扫描面:sources=${moduleSources.length}/${expectedModules},缺 ${missingModuleIds.join('、') || missingModuleCss.join('、') || '模块源码'}`,
161
+ fix: '确认 apps/client/vite.config.ts 的 tboxModuleSourcesPlugin 在 tailwindcss() 之前,且 surface-css.mjs 使用 app-build 的 collectModuleSourceDirs',
162
+ recipe: 'style',
163
+ }]);
164
+ steps.push({ name: 'styles', ok: false, ms: Math.round(performance.now() - started), cssBytes: surface.bytes, moduleSources: moduleSources.length, expectedModules, missingModuleIds });
165
+ } else {
166
+ steps.push({ name: 'styles', ok: true, ms: Math.round(performance.now() - started), cssBytes: surface.bytes, moduleSources: moduleSources.length, expectedModules });
167
+ }
109
168
  } catch (error) {
110
169
  fail('styles', [{
111
170
  id: 'styles-compile-failed',
@@ -116,36 +175,61 @@ async function checkStyles() {
116
175
  }
117
176
  }
118
177
 
119
- // ── 2. primitives ───────────────────────────────────────────────────
120
- function walkLess(dir, out = []) {
121
- if (!existsSync(dir)) return out;
122
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
123
- const full = path.join(dir, entry.name);
124
- if (entry.isDirectory()) walkLess(full, out);
125
- else if (entry.name.endsWith('.less')) out.push(full);
126
- }
127
- return out;
178
+ /**
179
+ * 死类:源码里像工具类、CSS 里却没有对应规则。
180
+ * Tailwind 对不认识的类不报错、只是不生成——拼错的类名(如 bg-primary-light)会静默失效。
181
+ * 只检查纯字母数字/连字符的 token(任意值、变体、模板插值都跳过),先告警不阻断。
182
+ */
183
+ function checkUtilityClasses(cssText) {
184
+ const cardsDir = path.join(clientDir, 'src/cards');
185
+ if (!existsSync(cardsDir)) return;
186
+ const seen = new Set();
187
+ for (const entry of readdirSync(cardsDir)) {
188
+ if (!entry.endsWith('.tsx')) continue;
189
+ const source = readFileSync(path.join(cardsDir, entry), 'utf8');
190
+ for (const match of source.matchAll(/className=(?:"([^"]*)"|\{'([^']*)'\})/g)) {
191
+ const value = match[1] ?? match[2] ?? '';
192
+ if (value.includes('${')) continue;
193
+ for (const token of value.split(/\s+/)) {
194
+ if (!token || token.includes(':') || token.includes('[') || token.includes('/') || token.includes('__')) continue;
195
+ if (!looksLikeUtility(token)) continue;
196
+ if (seen.has(token)) continue;
197
+ seen.add(token);
198
+ const pattern = new RegExp('\\.' + token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![\\w-])');
199
+ if (!pattern.test(cssText)) {
200
+ warn('utility-class-missing', `apps/client/src/cards/${entry}: 类名 ${token} 没有生成 CSS(拼写或未登记)`, {
201
+ fix: '对照 docs/agent/style.md 的语义色与档位;任意值改用方括号写法',
202
+ recipe: 'style',
203
+ });
204
+ }
205
+ }
206
+ }
207
+ }
128
208
  }
129
209
 
210
+ // ── 2. primitives ───────────────────────────────────────────────────
130
211
  function checkPrimitives() {
131
212
  const started = performance.now();
132
- const cards = registryServer?.cards ?? {};
213
+ const cards = mergedMetas;
133
214
  const cardTypes = new Set(Object.keys(cards));
134
215
  const tools = registryServer?.tools ?? [];
135
216
 
136
217
  for (const [cardType, meta] of Object.entries(cards)) {
137
- const samples = [
138
- ['sampleData', meta.sampleData],
139
- ...(Array.isArray(meta.samples) ? meta.samples.map((sample, index) => [`samples[${index}]`, sample?.data]) : []),
140
- ];
141
- for (const [label, data] of samples) {
142
- const parsed = meta.dataSchema.safeParse(data);
218
+ const duplicates = duplicateSampleLabels(meta);
219
+ if (duplicates.length > 0) {
220
+ warn('card-sample-label-duplicate', `${cardType} 的样例 label 重复:${duplicates.join('、')}(帧键/渲染文件名会互相覆盖)`, {
221
+ fix: `改 ${cardMetaSourceHint(cardProvenance, cardType)} 里的 samples[].label,同卡内必须唯一`,
222
+ recipe: 'card',
223
+ });
224
+ }
225
+ for (const sample of sampleEntries(meta)) {
226
+ const parsed = meta.dataSchema.safeParse(sample.data);
143
227
  if (!parsed.success) {
144
228
  errors.push({
145
229
  step: 'primitives',
146
230
  id: 'card-sample-invalid',
147
- message: `卡片样例不合法 ${cardType} ${label}: ${parsed.error.issues[0]?.message ?? parsed.error.message}`,
148
- fix: `补 apps/server/src/cards/${cardType}.card.ts 的 sampleData/samples`,
231
+ message: `卡片样例不合法 ${cardType} ${sample.label}: ${parsed.error.issues[0]?.message ?? parsed.error.message}`,
232
+ fix: `补 ${cardMetaSourceHint(cardProvenance, cardType)} 的 sampleData/samples`,
149
233
  recipe: 'card',
150
234
  });
151
235
  }
@@ -244,35 +328,13 @@ function checkPrimitives() {
244
328
  }
245
329
  }
246
330
 
247
- for (const file of walkLess(path.join(clientDir, 'src'))) {
248
- const rel = path.relative(appDir, file);
249
- readFileSync(file, 'utf8').split('\n').forEach((line, index) => {
250
- const at = `${rel}:${index + 1}`;
251
- for (const match of line.matchAll(/font-size:\s*(\d+(?:\.\d+)?)px\b/g)) {
252
- const size = Number(match[1]);
253
- if (size > 0 && size < MIN_DESIGN_FONT_PX) {
254
- warn('font-too-small', `${at}: font-size ${size}px 低于可读下限 ${MIN_DESIGN_FONT_PX}px(≈${Math.round(size / 2)} 屏幕像素)`, {
255
- fix: '设计稿 750 宽:正文 ≥22px、辅助 ≥22px;屏幕像素 = 设计稿/2',
256
- recipe: 'style',
257
- });
258
- }
259
- }
260
- if (/rgb\(\s*\d+\s+\d+\s+\d+\s*\/|\brgb\([^)]*\s\/\s/.test(line)) {
261
- warn('color-syntax', `${at}: 使用 CSS Color 4 空格语法,旧 web-view 整条失效`, {
262
- fix: '改用 rgba(r, g, b, a)',
263
- recipe: 'style',
264
- });
265
- }
266
- });
267
- }
268
-
269
331
  steps.push({ name: 'primitives', ok: !errors.some((item) => item.step === 'primitives'), ms: Math.round(performance.now() - started) });
270
332
  }
271
333
 
272
334
  // ── 2b. tailwind 类名禁忌(禁用项)────────────────────────────────────
273
335
  // Tailwind 对不认识的类不报错、只是不生成——所以这几类必须让它们出声。
274
- // 规则与 docs/agent/style.md 一一对应:默认调色板、语义色的透明度修饰符(依赖 color-mix)、
275
- // 档外字号、元素级 --tbox-asset-* 声明(会截断 html[data-theme] 覆写继承)。
336
+ // 规则与 docs/agent/style.md 一一对应:默认调色板、档外字号、类名紧贴插值、
337
+ // 元素级 --tbox-asset-* 声明(会截断 html[data-theme] 覆写继承)。
276
338
  /** 判断一个 token 像不像工具类(去掉变体前缀后看末段):用来把 BEM 钩子排除在外 */
277
339
  function looksLikeUtility(token) {
278
340
  if (token.includes('__')) return false;
@@ -296,12 +358,6 @@ const TAILWIND_BANNED = [
296
358
  message: '用了 Tailwind 默认调色板(不生成 CSS,且产物会带 oklch)',
297
359
  fix: '换成语义色:text-foreground / bg-card / border-border 等(docs/agent/style.md)',
298
360
  },
299
- {
300
- id: 'color-opacity-modifier',
301
- pattern: /\b(?:bg|text|border|ring|outline|fill|stroke|from|to|via|divide|placeholder|decoration)-(?!xs\b|sm\b|base\b|lg\b|xl\b|2xl\b|3xl\b)[a-z][a-z0-9-]*\/\d{1,3}\b/,
302
- message: '用了颜色透明度修饰符(依赖 color-mix,旧内核回落为不透明)',
303
- fix: '改带 alpha 的任意值,如 bg-[rgba(255,255,255,0.18)]',
304
- },
305
361
  {
306
362
  id: 'font-size-off-scale',
307
363
  pattern: /\btext-\[\d+(?:\.\d+)?px\]/,
@@ -380,55 +436,59 @@ async function checkRender() {
380
436
  steps.push({ name: 'render', ok: true, ms: 0, skipped: true });
381
437
  return;
382
438
  }
383
- const metas = registryServer?.cards ?? {};
439
+ const metas = mergedMetas;
384
440
  if (Object.keys(metas).length === 0) {
385
441
  steps.push({ name: 'render', ok: true, ms: Math.round(performance.now() - started), cards: 0, rendered: 0, skipped: true });
386
442
  return;
387
443
  }
388
444
  const React = (await import('react')).default;
389
445
  const { renderToStaticMarkup } = await import('react-dom/server');
390
- const { createStore } = await import('zustand/vanilla');
391
- const { useStore } = await import('zustand');
392
446
  const kit = await vite.ssrLoadModule('@tbox.cn/app-agent-ui-kit');
447
+ const staticRender = createStaticRenderer(renderToStaticMarkup);
393
448
 
394
- const store = createStore(() => ({ sendUiAction() {}, isGenerating: false }));
395
- const hook = (selector) => useStore(store, selector);
396
- hook.getState = store.getState;
397
- hook.setState = store.setState;
398
- hook.subscribe = store.subscribe;
399
-
400
- const components = registryClient?.cards ?? {};
449
+ const components = mergedComponents;
450
+ // 与运行时 / 预览 / 截图同一条装配(SurfaceHarness),不再手搭 provider。
451
+ const harness = kit.createSurfaceHarness({ cards: components });
401
452
  let rendered = 0;
402
453
  let bytes = 0;
403
454
 
404
455
  for (const [cardType, meta] of Object.entries(metas)) {
405
456
  const Component = components[cardType];
457
+ const sourceFile = cardSourceHint(cardProvenance, cardType);
406
458
  if (!Component) {
407
459
  errors.push({
408
460
  step: 'render',
409
461
  id: 'card-client-missing',
410
462
  message: `客户端缺少卡片组件 ${cardType}`,
411
- fix: `补 apps/client/src/cards/${cardType}.card.tsx(export const card = defineCard({ type: '${cardType}' }, …))`,
463
+ fix: `补 ${sourceFile}(export const card = defineCard({ type: '${cardType}' }, …))`,
412
464
  recipe: 'card',
413
465
  });
414
466
  continue;
415
467
  }
416
- const samples = [
417
- ['sampleData', meta.sampleData],
418
- ...(Array.isArray(meta.samples) ? meta.samples.map((sample, index) => [sample?.label ?? `samples[${index}]`, sample?.data]) : []),
419
- ];
420
- for (const [label, data] of samples) {
468
+ for (const sample of sampleEntries(meta)) {
469
+ const { label, data } = sample;
421
470
  try {
422
- const html = renderToStaticMarkup(
423
- React.createElement(
424
- kit.KitChatProvider,
425
- { store: hook, cards: components, rawCards: components },
426
- React.createElement(Component, { data, cardId: `evidence-${cardType}`, isHistory: false, actionTokens: {} }),
427
- ),
471
+ const html = staticRender.render(
472
+ harness.wrap(React.createElement(Component, { data, cardId: `evidence-${cardType}`, isHistory: sample.isHistory === true, actionTokens: {} })),
428
473
  );
429
474
  rendered += 1;
430
475
  bytes += html.length;
431
- cardDigests.push({ cardType, label, source: 'sample', text: htmlDigest(html) });
476
+ cardDigests.push({ cardType, label, source: 'sample', hidden: sample.hidden === true, text: htmlDigest(html) });
477
+ // 历史态是必验状态(只读、动作禁用):只验默认态会漏掉整类分支。
478
+ if (label === 'sampleData') {
479
+ try {
480
+ const historyHtml = staticRender.render(
481
+ harness.wrap(React.createElement(Component, { data, cardId: `evidence-history-${cardType}`, isHistory: true, actionTokens: {} })),
482
+ );
483
+ if (!historyHtml.trim()) {
484
+ errors.push({ step: 'render', file: sourceFile, id: 'card-state-empty', message: `卡片 ${cardType} 历史态渲染为空`, fix: '历史态不要返回空树(用 isHistory 只禁用动作,不隐藏内容)', recipe: 'card' });
485
+ } else {
486
+ historyRendered += 1;
487
+ }
488
+ } catch (error) {
489
+ errors.push({ step: 'render', file: sourceFile, id: 'card-state-failed', message: `卡片 ${cardType} 历史态渲染抛错:${error?.message ?? error}`, fix: '历史态分支(isHistory)按报错栈修', recipe: 'card' });
490
+ }
491
+ }
432
492
  if (html.trim() === '') {
433
493
  errors.push({
434
494
  step: 'render',
@@ -441,7 +501,7 @@ async function checkRender() {
441
501
  } catch (error) {
442
502
  errors.push({
443
503
  step: 'render',
444
- file: `apps/client/src/cards/${cardType}.card.tsx`,
504
+ file: sourceFile,
445
505
  id: 'card-render-failed',
446
506
  message: `卡片 ${cardType} ${label} 渲染抛错:${error?.message ?? error}`,
447
507
  fix: '按报错栈修组件;数据形状以服务端 dataSchema 为准',
@@ -456,9 +516,7 @@ async function checkRender() {
456
516
  if (!Component) continue;
457
517
  try {
458
518
  const html = renderToStaticMarkup(
459
- React.createElement(
460
- kit.KitChatProvider,
461
- { store: hook, cards: components, rawCards: components },
519
+ harness.wrap(
462
520
  React.createElement(Component, {
463
521
  data: instance.data,
464
522
  cardId: `evidence-scenario-${instance.cardType}-${instance.step}`,
@@ -482,7 +540,7 @@ async function checkRender() {
482
540
  }
483
541
  }
484
542
 
485
- steps.push({ name: 'render', ok: !errors.some((item) => item.step === 'render'), ms: Math.round(performance.now() - started), cards: Object.keys(metas).length, rendered, bytes });
543
+ steps.push({ name: 'render', ok: !errors.some((item) => item.step === 'render'), ms: Math.round(performance.now() - started), cards: Object.keys(metas).length, rendered, bytes, ssrWarnings: staticRender.suppressed() });
486
544
  }
487
545
 
488
546
  // ── 4. scenarios ────────────────────────────────────────────────────
@@ -510,7 +568,7 @@ async function checkScenarios() {
510
568
  steps.push({ name: 'scenarios', ok: true, ms: Math.round(performance.now() - started), scenarios: 0, skipped: true });
511
569
  return;
512
570
  }
513
- const result = await lib.runScenarios({ appDir, registry: registryServer, files });
571
+ const result = await lib.runScenarios({ appDir, registry: { ...registryServer, cards: mergedMetas }, files });
514
572
  scenarioResults = result.results;
515
573
  scenarioInstances = result.instances ?? [];
516
574
  for (const item of result.results) {
@@ -564,28 +622,63 @@ function gateVerdict() {
564
622
  const file = ['scenarios/acceptance.jsonc', 'scenarios/acceptance.json'].map((name) => path.join(appDir, name)).find((name) => existsSync(name));
565
623
  const doc = file ? readJsonc(file) : {};
566
624
  const items = doc.items ?? [];
567
- const scenarioItems = items.filter((item) => (item.by ?? 'scenario') === 'scenario');
625
+ const acceptanceRaw = file ? readFileSync(file, 'utf8') : '';
626
+ const acceptanceHash = acceptanceRaw ? createHash('sha256').update(acceptanceRaw).digest('hex').slice(0, 16) : null;
627
+ const acceptanceIds = items.map((item) => String(item.id));
628
+ let prevGate;
629
+ try {
630
+ prevGate = JSON.parse(readFileSync(path.join(appDir, '.tbox/evidence/gate.json'), 'utf8'));
631
+ } catch {
632
+ prevGate = undefined;
633
+ }
634
+ const deferredByLane = items.filter((item) => item.lane === 'browser' || item.lane === 'model');
635
+ const scenarioItems = items.filter((item) => (item.by ?? 'scenario') === 'scenario' && !item.lane);
568
636
  // E1:review 改名为 handoff(旧名保留为别名)。名字本身不再邀请复审。
569
637
  // E2:证据策略声明本任务允许验证到哪一级;handoff 只接受策略判为不可验的维度。
570
- const policy = ['static', 'visual', 'flow'].includes(doc.policy) ? doc.policy : 'static';
638
+ const policyResolution = resolvePolicy({
639
+ platformPolicy: process.env.TBOX_POLICY,
640
+ docPolicy: doc.policy,
641
+ docPolicyReason: doc.policyReason,
642
+ });
643
+ const policy = policyResolution.policy;
644
+ if (policyResolution.downgradeIgnored) {
645
+ warn('policy-downgrade-ignored', 'acceptance.jsonc 把档位降到 static 但没写 policyReason:按用户意图不明处理,本轮按 visual 执行', {
646
+ fix: '补 policyReason(用户原话),或用 TBOX_POLICY 由平台注入档位',
647
+ recipe: 'verify',
648
+ });
649
+ }
571
650
  if (doc.policy && !['static', 'visual', 'flow'].includes(doc.policy)) {
572
651
  warn('policy-unknown', `scenarios/acceptance.jsonc 的 policy=${JSON.stringify(doc.policy)} 不支持(static / visual / flow),按 static 处理`, {
573
652
  fix: '改成三档之一,或删掉 policy 使用缺省 static',
574
653
  recipe: 'verify',
575
654
  });
576
655
  }
577
- const handoffItems = items.filter((item) => item.by === 'handoff' || item.by === 'review');
578
- const covered = new Set();
656
+ const handoffItems = items.filter((item) => (item.by === 'handoff' || item.by === 'review') && !item.lane);
657
+ /** ui.* 被标 handoff 时的一句出口提示:故事板只证明渲染与几何,不判美丑。 */
658
+ const uiHandoffHint = () => {
659
+ const uiItems = handoffItems.filter((item) => String(item.id).startsWith('ui.'));
660
+ if (uiItems.length === 0 || policy === 'static') return '';
661
+ return ';其中 ' + uiItems.map((item) => item.id).join('、') + ' 可由故事板证明:改成 by: "storyboard" 并写 frames(如 ["card:*@320"])';
662
+ };
663
+ const originByFile = new Map();
579
664
  for (const result of scenarioResults) {
580
- if (!result.ok) continue;
581
- for (const id of result.covers ?? []) covered.add(id);
665
+ let origin = 'spec';
666
+ try {
667
+ const parsed = JSON.parse(readFileSync(result.file, "utf8"));
668
+ if (parsed && parsed.origin) origin = String(parsed.origin);
669
+ } catch { origin = 'spec'; }
670
+ originByFile.set(result.file, origin);
582
671
  }
672
+ const { covered, declared: declaredCovered } = coverageSets(scenarioResults, originByFile);
673
+ // D1:界面类验收项由故事板证明「渲染出来了且没有几何错误」——与场景覆盖分列,不混算。
674
+ const board = storyboardCoverage(items, readStoryboardResult().storyboard, policy);
583
675
  // 策略允许场景验证的项不能借 handoff 绕过:没有 reason 的 handoff 计入 incomplete。
584
676
  // 旧名 review 不要求 reason(历史应用平滑);新名 handoff 必须写清为什么当前策略验不了。
585
677
  const handoffWithoutReason = handoffItems.filter((item) => item.by === 'handoff' && !item.reason);
586
678
  const uncovered = [
587
679
  ...scenarioItems.filter((item) => !covered.has(item.id)).map((item) => item.id),
588
680
  ...handoffWithoutReason.map((item) => item.id),
681
+ ...[...board.failed.keys()],
589
682
  ];
590
683
  if (handoffWithoutReason.length > 0) {
591
684
  warn('handoff-misuse', `handoff 项缺 reason:${handoffWithoutReason.map((item) => item.id).join('、')}(能由场景判定的项不要标 handoff)`, {
@@ -616,6 +709,8 @@ function gateVerdict() {
616
709
  declared: { tools: declaredTools.size, actions: declaredActions.size, cards: declaredCards.size },
617
710
  missing: { tools: missingTools, actions: missingActions, cards: missingCards },
618
711
  };
712
+ // 自有工具 = 注册表里的工具减去模块声明的(模块工具不算「你自己写的」)。
713
+ const ownToolCount = Math.max(0, (registryServer?.tools?.length ?? 0) - moduleSurface.tools.length);
619
714
  const missingCapabilityText = [
620
715
  ...missingTools.map((id) => `工具 ${id}`),
621
716
  ...missingActions.map((id) => `动作 ${id}`),
@@ -630,6 +725,11 @@ function gateVerdict() {
630
725
  scenarioResults.length > 0
631
726
  ? `已验证:${scenarioResults.length} 个场景 / ${scenarioSteps} 步 / ${covered.size} 项`
632
727
  : '未运行:没有场景(先按 verify.md 写一条)',
728
+ storyboard: policy === 'static'
729
+ ? '未运行:当前策略 static'
730
+ : board.covered.size > 0
731
+ ? `已验证:${board.covered.size} 个界面项由故事板覆盖`
732
+ : '未运行:没有 by: "storyboard" 的验收项',
633
733
  render:
634
734
  cardDigests.length > 0
635
735
  ? `已验证:${cardDigests.length} 张卡 / ${scenarioInstances.length + cardDigests.length} 份样例`
@@ -637,7 +737,10 @@ function gateVerdict() {
637
737
  visual: policy === 'static' ? '未运行:当前策略 static(任务要求快速交付,不起浏览器)' : '未运行:本轮未执行浏览器(需要 --visual / dev server)',
638
738
  routing: policy === 'flow' ? '未运行:本轮未跑模型级验收' : '未运行:当前策略不要求模型级验收',
639
739
  };
640
- const handoff = handoffItems.map((item) => `${item.id} ${item.text ?? ''}`.trim());
740
+ const handoff = [
741
+ ...handoffItems.map((item) => `${item.id} ${item.text ?? ''}`.trim()),
742
+ ...[...board.handoff.entries()].map(([id, reason]) => `${id}(故事板未覆盖:${reason})`),
743
+ ];
641
744
 
642
745
  let verdict;
643
746
  let next;
@@ -649,6 +752,11 @@ function gateVerdict() {
649
752
  next = hasSurface
650
753
  ? '先把需求拆成 scenarios/acceptance.jsonc 的验收项(id + text),再让场景用 covers 声明覆盖'
651
754
  : '交付条件已满足:总结并结束。不要继续复审或打磨。';
755
+ } else if (ownToolCount === 0 && items.length > 0) {
756
+ // 首验前移:验收已写、还没有自己的工具时,next 直接给第一项竖切的命令(不再只说「补文件」)。
757
+ const firstId = String(items[0].id ?? '').toLowerCase().replace(/[^a-z0-9-]+/g, '-').slice(0, 32) || 'first';
758
+ verdict = 'incomplete';
759
+ next = `先做第一项竖切:pnpm exec tbox-app new feature ${firstId} --view(工具 + 视图卡 + 场景),然后 pnpm check:fast`;
652
760
  } else if (missingCapabilityText.length > 0) {
653
761
  verdict = 'incomplete';
654
762
  next = `能力图还缺:${missingCapabilityText.join('、')};先在 acceptance.jsonc 声明,再补对应文件(new tool / new card / new action)`;
@@ -657,19 +765,135 @@ function gateVerdict() {
657
765
  next = `未覆盖验收项:${uncovered.join('、')};补场景并在 covers 里登记,或给确实无法自动判定的项标 by: "handoff" 并写 reason`;
658
766
  } else {
659
767
  verdict = 'deliverable';
768
+ const boardHint = uiHandoffHint();
660
769
  next =
661
770
  handoff.length > 0
662
- ? `把 handoff 的 ${handoff.length} 项原样写进交付说明,然后结束。这些项在当前策略(${policy})下无法验证,继续读代码不会改变它们的状态。`
771
+ ? `把 handoff 的 ${handoff.length} 项原样写进交付说明,然后结束。这些项在当前策略(${policy})下无法验证,继续读代码不会改变它们的状态${boardHint}。`
663
772
  : '交付条件已满足:总结并结束。不要继续复审或打磨。';
664
773
  }
665
774
 
666
- const gateFile = path.join(appDir, '.tbox/evidence/gate.json');
667
- let previous;
775
+ // 验收变更:从「哈希变了」升级成「哪一项怎么变」,并跨轮累计。
776
+ const digest = {};
777
+ for (const item of items) {
778
+ digest[String(item.id)] = {
779
+ text: createHash('sha256').update(String(item.text ?? '')).digest('hex').slice(0, 12),
780
+ handoff: item.by === 'handoff' || item.by === 'review',
781
+ coveredBy: [],
782
+ };
783
+ }
784
+ // 覆盖关系与「这次场景过没过」无关:场景失败由裁决本身报,不能同时把验收项记成被弱化。
785
+ for (const result of scenarioResults) {
786
+ for (const id of result.covers ?? []) {
787
+ if (digest[id]) digest[id].coveredBy.push(scenarioKey(appDir, result.file));
788
+ }
789
+ }
790
+ // 验收文件整份缺省(还没写)不算「删除了全部验收项」:没有基线就没有弱化可谈。
791
+ const acceptanceChange = file ? acceptanceChangesOf(prevGate, digest) : { changes: [], cumulative: Array.isArray(prevGate?.acceptanceChanges) ? prevGate.acceptanceChanges : [] };
792
+ const acceptance = acceptanceDrift(prevGate, acceptanceHash, acceptanceIds);
793
+ const drift = [...acceptance.drift];
794
+ const weakening = summarizeAcceptanceChanges(acceptanceChange.cumulative);
795
+ if (weakening.length > 0) {
796
+ warn('acceptance-drift', '验收变更:' + weakening.slice(0, 5).join('、') + ';若是用户要求,在交付答复中说明原因,否则恢复', {
797
+ fix: '把改动改回去,或在交付说明里写清是用户要求',
798
+ recipe: 'verify',
799
+ });
800
+ }
801
+ const scenarioHashes = {};
802
+ const failedScenarios = [];
803
+ for (const result of scenarioResults) {
804
+ try {
805
+ const relative = scenarioKey(appDir, result.file);
806
+ scenarioHashes[relative] = createHash("sha256").update(readFileSync(result.file, "utf8")).digest("hex").slice(0, 16);
807
+ } catch { /* 读失败不影响裁决 */ }
808
+ if (!result.ok) failedScenarios.push(path.relative(appDir, result.file));
809
+ }
810
+ // 场景删除也是漂移:失败后删场景会让门禁「变绿」,必须让用户看见。
811
+ for (const item of scenarioDrift(prevGate, scenarioHashes)) {
812
+ drift.push(item);
813
+ warn('scenario-drift', item.detail, { fix: '在交付说明里写清为什么删场景', recipe: 'verify' });
814
+ }
815
+ if (prevGate && prevGate.scenarioHashes) {
816
+ for (const [scenarioFile, hash] of Object.entries(scenarioHashes)) {
817
+ const prevHash = prevGate.scenarioHashes[scenarioFile];
818
+ if (prevHash && prevHash !== hash && Array.isArray(prevGate.failedScenarios) && prevGate.failedScenarios.includes(scenarioFile)) {
819
+ const detail = '失败后改了场景期望:' + scenarioFile;
820
+ drift.push({ kind: 'expect', detail });
821
+ warn('expect-drift', detail, { fix: '在交付说明里写清为什么改期望', recipe: 'verify' });
822
+ }
823
+ }
824
+ }
825
+
826
+ // 软闩:交付后再改内容 -> reopened(只降级,不阻断)。
827
+ let contentHash = null;
828
+ try { contentHash = hashSourceTree(appDir).hash; } catch { contentHash = null; }
829
+ if (shouldReopen(prevGate, verdict, contentHash)) {
830
+ verdict = 'reopened';
831
+ next = '交付后内容有改动:重跑一次 check:fast 确认,再交付(不做硬停)。';
832
+ }
833
+
834
+ // 能力偏离:与 create 的出厂基线快照比(画像覆盖已被快照吸收,不会误判成 agent 偏离)。
835
+ let capability = { skipped: true, reason: '缺出厂基线快照', items: [] };
668
836
  try {
669
- previous = JSON.parse(readFileSync(gateFile, 'utf8'));
670
- } catch {
671
- previous = undefined;
837
+ const factoryFile = path.join(appDir, '.tbox/factory/chat.json');
838
+ const actualFile = path.join(appDir, 'config/chat.json');
839
+ if (existsSync(factoryFile) && existsSync(actualFile)) {
840
+ const factoryDoc = JSON.parse(readFileSync(factoryFile, 'utf8'));
841
+ const actualDoc = JSON.parse(readFileSync(actualFile, 'utf8'));
842
+ capability = capabilityDrift({ factory: factoryDoc.chat ?? {}, actual: actualDoc });
843
+ for (const item of capability.items) {
844
+ warn('capability-drift', `能力偏离出厂:${item.key} ${String(item.factory)} → ${String(item.actual)}(${item.change})`, {
845
+ fix: item.change === 'user-intent'
846
+ ? '恢复出厂值;能力偏离会进交付包'
847
+ : '在交付说明的「偏离出厂」里声明',
848
+ recipe: 'shell',
849
+ });
850
+ }
851
+ }
852
+ } catch { /* 快照损坏不阻断裁决 */ }
853
+
854
+ // 出厂模块集偏离:删掉出厂模块(例如默认的支付模块)在会话里看得见,不阻断。
855
+ let moduleDrift = { skipped: true, reason: '缺出厂模块快照', items: [] };
856
+ try {
857
+ const factoryFile = path.join(appDir, '.tbox/factory/modules.json');
858
+ const actualFile = path.join(appDir, '.tbox/default-modules.json');
859
+ if (existsSync(factoryFile)) {
860
+ const actualDoc = existsSync(actualFile) ? JSON.parse(readFileSync(actualFile, 'utf8')) : [];
861
+ moduleDrift = defaultModuleDrift({ factory: JSON.parse(readFileSync(factoryFile, 'utf8')), actual: actualDoc });
862
+ for (const item of moduleDrift.items) {
863
+ warn('module-drift', '出厂模块偏离:' + item.key + (item.kind === 'module-removed' ? ' 已移除' : ' 是新增的'), {
864
+ fix: '删掉/加上是用户的决定时,在交付说明的「偏离出厂」里写清楚;否则 module add 加回来',
865
+ recipe: 'shell',
866
+ });
867
+ }
868
+ }
869
+ } catch { /* 快照损坏不阻断裁决 */ }
870
+
871
+ const delivery = {
872
+ acceptanceChanges: acceptanceChange.cumulative,
873
+ acceptanceChangeSummary: weakening,
874
+ capabilityDrift: capability.items,
875
+ moduleDrift: moduleDrift.items,
876
+ capabilityBaseline: capability.skipped ? { skipped: true, reason: capability.reason } : { skipped: false },
877
+ trace: items.map((item) => ({
878
+ id: item.id,
879
+ text: item.text ?? '',
880
+ covered: covered.has(item.id),
881
+ declared: declaredCovered.has(item.id),
882
+ ...(item.lane ? { lane: item.lane } : {}),
883
+ })),
884
+ facts: cardFacts,
885
+ drift,
886
+ deferred: [
887
+ ...deferredByLane.map((item) => ({ id: item.id, lane: item.lane, reason: '验收项声明为 ' + item.lane + ' 车道' })),
888
+ ...experienceItems.filter((item) => item.status === "deferred").map((item) => ({ id: item.id, lane: item.lane, reason: item.detail })),
889
+ ],
890
+ };
891
+ if (verdict === 'deliverable' && delivery.deferred.length > 0) {
892
+ // 界面项被标 handoff 时给一次可执行出口:故事板能证明「渲染出来且没几何错误」。
893
+ const boardHint = uiHandoffHint();
894
+ next = '把 deferred 的 ' + delivery.deferred.length + ' 项如实写进交付说明,然后结束' + boardHint + '。';
672
895
  }
896
+ const gateFile = path.join(appDir, '.tbox/evidence/gate.json');
673
897
  let changedFiles = 0;
674
898
  try {
675
899
  changedFiles = execFileSync('git', ['status', '--porcelain'], { cwd: appDir, encoding: 'utf8' })
@@ -678,11 +902,24 @@ function gateVerdict() {
678
902
  } catch {
679
903
  changedFiles = 0;
680
904
  }
681
- const runs = previous?.verdict === 'deliverable' ? (previous.runs ?? 0) + 1 : 0;
682
- const sinceDeliverable = previous?.verdict === 'deliverable' ? { runs, changedFiles } : undefined;
905
+ const runs = prevGate?.verdict === 'deliverable' ? (prevGate.runs ?? 0) + 1 : 0;
906
+ const sinceDeliverable = prevGate?.verdict === 'deliverable' ? { runs, changedFiles } : undefined;
683
907
  try {
684
908
  mkdirSync(path.dirname(gateFile), { recursive: true });
685
- writeFileSync(gateFile, JSON.stringify({ verdict, at: Date.now(), changedFiles, runs }));
909
+ writeFileSync(gateFile, JSON.stringify({
910
+ verdict,
911
+ at: Date.now(),
912
+ changedFiles,
913
+ runs,
914
+ acceptanceHash,
915
+ acceptanceIds,
916
+ acceptanceDigest: digest,
917
+ acceptanceChanges: acceptanceChange.cumulative,
918
+ scenarioHashes,
919
+ failedScenarios,
920
+ contentHash,
921
+ deliveredAt: verdict === 'deliverable' ? (prevGate && prevGate.verdict === 'deliverable' ? (prevGate.deliveredAt ?? Date.now()) : Date.now()) : (prevGate ? prevGate.deliveredAt : undefined),
922
+ }));
686
923
  } catch {
687
924
  // 只读环境不影响裁决
688
925
  }
@@ -697,13 +934,17 @@ function gateVerdict() {
697
934
  acceptance: {
698
935
  items: items.length,
699
936
  covered: covered.size,
937
+ declared: declaredCovered.size,
938
+ // 故事板覆盖单独计数,不与场景覆盖混算。
939
+ storyboard: board.covered.size,
700
940
  // 旧名保留一版(读取方可能仍看 review);新代码用 handoff。
701
941
  review: handoffItems.length,
702
- handoff: handoffItems.length,
942
+ handoff: handoffItems.length + board.handoff.size,
703
943
  uncovered,
704
944
  ...(file ? { file: path.relative(appDir, file) } : {}),
705
945
  },
706
946
  ...(sinceDeliverable ? { sinceDeliverable } : {}),
947
+ delivery,
707
948
  };
708
949
  }
709
950
 
@@ -721,8 +962,9 @@ function checkRenderSignals() {
721
962
  const byCard = new Map();
722
963
  for (const item of cardDigests) byCard.set(item.cardType, [...(byCard.get(item.cardType) ?? []), item]);
723
964
  for (const [cardType, list] of byCard) {
724
- if (list.length >= 2 && new Set(list.map((item) => item.text)).size === 1) {
725
- warn('render-identical', `${cardType} 的 ${list.length} 份样例渲染结果完全相同——状态没有真正区分`, {
965
+ const visible = list.filter((item) => item.hidden !== true);
966
+ if (visible.length >= 2 && new Set(visible.map((item) => item.text)).size === 1) {
967
+ warn('render-identical', `${cardType} 的 ${visible.length} 份样例渲染结果完全相同——状态没有真正区分`, {
726
968
  fix: '给不同状态不同的可见内容(状态标签/按钮/提示),或删掉重复样例',
727
969
  recipe: 'card',
728
970
  });
@@ -748,7 +990,7 @@ function checkRenderSignals() {
748
990
  // ── 4.5 状态覆盖(声明样例 + 场景实例) ──────────────────────────
749
991
  function checkCoverage() {
750
992
  const started = performance.now();
751
- const metas = registryServer?.cards ?? {};
993
+ const metas = mergedMetas;
752
994
  for (const [cardType, meta] of Object.entries(metas)) {
753
995
  const declared = [
754
996
  meta.sampleData,
@@ -774,6 +1016,277 @@ function checkCoverage() {
774
1016
  steps.push({ name: 'coverage', ok: true, ms: Math.round(performance.now() - started), instances: scenarioInstances.length });
775
1017
  }
776
1018
 
1019
+ // 对比度:纯色令牌静态算 WCAG;var()/color-mix 派生的标 deferred(浏览器车道暂缓)。
1020
+ function parseCssTokens(files) {
1021
+ const values = new Map();
1022
+ for (const file of files) {
1023
+ if (!file || !existsSync(file)) continue;
1024
+ const css = readFileSync(file, 'utf8').replace(/\/\*[\s\S]*?\*\//g, '');
1025
+ for (const match of css.matchAll(/(--tbox-[\w-]+)\s*:\s*([^;]+);/g)) {
1026
+ values.set(match[1], match[2].trim());
1027
+ }
1028
+ }
1029
+ return values;
1030
+ }
1031
+
1032
+ function checkContrast() {
1033
+ const kitDir = path.join(appDir, 'packages/agent-ui-kit');
1034
+ const contractPath = path.join(kitDir, 'src/theme/contract.json');
1035
+ if (!existsSync(contractPath)) return { status: 'deferred', detail: '主题契约不在预期位置' };
1036
+ const contract = JSON.parse(readFileSync(contractPath, 'utf8'));
1037
+ const pairs = contract.pairs ?? [];
1038
+ if (pairs.length === 0) return { status: 'deferred', detail: '没有登记对比度对' };
1039
+ const require = createRequire(path.join(clientDir, 'package.json'));
1040
+ let themePackage = '@tbox.cn/app-theme-tbox';
1041
+ try {
1042
+ // 以装配真源的实际 import 为准(theme use 会改写这一行);找不到再退回依赖清单。
1043
+ const appConfig = readFileSync(path.join(clientDir, 'src/app.config.ts'), 'utf8');
1044
+ const imported = /@tbox\.cn\/app-theme-([a-z0-9-]+)\/index\.css/.exec(appConfig);
1045
+ if (imported) {
1046
+ themePackage = '@tbox.cn/app-theme-' + imported[1];
1047
+ } else {
1048
+ const clientPkg = JSON.parse(readFileSync(path.join(clientDir, 'package.json'), 'utf8'));
1049
+ const installed = Object.keys({ ...(clientPkg.dependencies ?? {}), ...(clientPkg.devDependencies ?? {}) }).filter((name) => name.startsWith('@tbox.cn/app-theme-')).sort();
1050
+ if (installed[0]) themePackage = installed[0];
1051
+ }
1052
+ } catch { /* 用出厂主题 */ }
1053
+ let themeCss;
1054
+ try { themeCss = require.resolve(themePackage + '/index.css'); } catch { themeCss = undefined; }
1055
+ const tokens = parseCssTokens([
1056
+ path.join(kitDir, 'src/theme/tokens.css'),
1057
+ themeCss,
1058
+ path.join(clientDir, 'src/styles/brand.css'),
1059
+ ]);
1060
+ const resolved = new Map();
1061
+ for (const [key, raw] of tokens) {
1062
+ const color = parseColor(raw);
1063
+ if (color) resolved.set(key, color);
1064
+ }
1065
+ const failures = [];
1066
+ const deferred = [];
1067
+ for (const pair of pairs) {
1068
+ const fg = resolved.get(pair.fg);
1069
+ const bg = resolved.get(pair.bg);
1070
+ if (!fg || !bg) { deferred.push(pair.fg + ' on ' + pair.bg); continue; }
1071
+ const ratio = contrastRatio(fg, bg);
1072
+ if (ratio < pair.min) failures.push(pair.fg + ' on ' + pair.bg + ' = ' + ratio.toFixed(2) + ' < ' + pair.min);
1073
+ }
1074
+ if (failures.length > 0) return { status: 'fail', detail: failures.join(';') };
1075
+ if (deferred.length > 0) return { status: 'deferred', detail: '无法静态解析:' + deferred.join(';') };
1076
+ return { status: 'pass', detail: pairs.length + ' 对全部达到阈值' };
1077
+ }
1078
+
1079
+ // 视图卡的静态密度:版式归平台后高度是视图树的函数,不用开浏览器。
1080
+ async function checkCardDensity() {
1081
+ if (!registryServer) return { available: false, worst: 0, violations: [], reason: '没有服务端 registry' };
1082
+ let contracts;
1083
+ try { contracts = await vite.ssrLoadModule('@tbox.cn/app-contracts'); } catch { return { available: false, worst: 0, violations: [], reason: '契约模块加载失败' }; }
1084
+ const estimate = contracts.estimateCardHeight;
1085
+ if (typeof estimate !== 'function') return { available: false, worst: 0, violations: [], reason: '契约未导出 estimateCardHeight' };
1086
+ let worst = 0;
1087
+ const violations = [];
1088
+ for (const [cardType, meta] of Object.entries(mergedMetas)) {
1089
+ if (!meta || !meta.view) continue;
1090
+ const samples = [meta.sampleData, ...(Array.isArray(meta.samples) ? meta.samples.map((sample) => sample && sample.data) : [])];
1091
+ for (const data of samples) {
1092
+ if (!data) continue;
1093
+ try {
1094
+ const height = estimate(data);
1095
+ if (height > worst) worst = height;
1096
+ if (height > 633) violations.push(cardType + ' ' + height + 'px');
1097
+ } catch { /* 形状不对由 render 报 */ }
1098
+ }
1099
+ }
1100
+ return { available: true, worst, violations };
1101
+ }
1102
+
1103
+ // ── 4.8 体验不变量(登记在 checks.json 的 experience 族)──────────────
1104
+ // 只跑不需要浏览器的车道(静态 / 进程内);浏览器与模型车道写 deferred,由平台补验。
1105
+ /** 目录树最新 mtime(跳过构建产物与依赖);目录不存在返回 0。 */
1106
+ /** 故事板结果 + 过期原因(帧早于卡片/品牌改动时按未运行处理,不拿旧图冒充当前)。 */
1107
+ function readStoryboardResult() {
1108
+ const file = path.join(appDir, '.tbox/evidence/storyboard.json');
1109
+ if (!existsSync(file)) return { storyboard: null, stale: '' };
1110
+ try {
1111
+ // 与 storyboard 的缓存键同源:卡片、品牌层、壳配置、kit、模块卡任一变了,旧图都按未运行处理。
1112
+ const inputs = evidenceInputFiles(appDir);
1113
+ const newest = inputs.reduce((latest, file) => {
1114
+ try {
1115
+ return Math.max(latest, statSync(file).mtimeMs);
1116
+ } catch {
1117
+ return latest;
1118
+ }
1119
+ }, 0);
1120
+ const storyboard = JSON.parse(readFileSync(file, 'utf8'));
1121
+ if (Number(storyboard.protocolVersion ?? 1) > 1) {
1122
+ return { storyboard: null, stale: '故事板协议版本 ' + storyboard.protocolVersion + ' 高于门禁支持的 1(升级模板)' };
1123
+ }
1124
+ if (statSync(file).mtimeMs + 1000 < newest) return { storyboard: null, stale: '故事板早于最近改动(重跑 pnpm storyboard)' };
1125
+ return { storyboard, stale: '' };
1126
+ } catch {
1127
+ return { storyboard: null, stale: '' };
1128
+ }
1129
+ }
1130
+
1131
+ function newestMtime(root) {
1132
+ let newest = 0;
1133
+ const walk = (dir) => {
1134
+ let entries;
1135
+ try {
1136
+ entries = readdirSync(dir, { withFileTypes: true });
1137
+ } catch {
1138
+ return;
1139
+ }
1140
+ for (const entry of entries) {
1141
+ if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name === '.git') continue;
1142
+ const full = path.join(dir, entry.name);
1143
+ if (entry.isDirectory()) walk(full);
1144
+ else {
1145
+ try {
1146
+ newest = Math.max(newest, statSync(full).mtimeMs);
1147
+ } catch { /* 竞态删除忽略 */ }
1148
+ }
1149
+ }
1150
+ };
1151
+ walk(root);
1152
+ return newest;
1153
+ }
1154
+
1155
+ async function checkExperience(cssBytes) {
1156
+ const started = performance.now();
1157
+ const items = [];
1158
+ const push = (id, lane, status, detail) => items.push({ id, lane, status, detail });
1159
+
1160
+ // 登记表是检查项元数据的真源:level 决定阻断/告警,lane 决定车道,since 决定旧应用是否跳过。
1161
+ const checkMeta = new Map();
1162
+ try {
1163
+ const doc = JSON.parse(readFileSync(path.join(appDir, 'scripts/checks.json'), 'utf8'));
1164
+ for (const check of doc.checks ?? []) checkMeta.set(check.id, check);
1165
+ } catch { /* 缺登记表时按 error 处理 */ }
1166
+ const levelOf = (id) => checkMeta.get(id)?.level === 'warning' ? 'warning' : 'error';
1167
+ let appVersion = '';
1168
+ try {
1169
+ appVersion = JSON.parse(readFileSync(path.join(appDir, '.tbox/app.json'), 'utf8')).templateVersion ?? '';
1170
+ } catch { /* 版本未知 → 不做 since 过滤 */ }
1171
+
1172
+ // 静态车道走执行器:新增检查只需 checks.json 一行 + experience-checks.mjs 一段。
1173
+ // 顺序按执行器声明(与历史 items 顺序一致),只跑登记为 phase=static 的 id。
1174
+ const staticIds = Object.keys(STATIC_CHECKS).filter((id) => checkMeta.get(id)?.phase === 'static');
1175
+ for (const item of runStaticChecks({ appDir, clientDir }, staticIds)) {
1176
+ push(item.id, checkMeta.get(item.id)?.lane ?? 'static', item.status, item.detail);
1177
+ }
1178
+ // 进程内车道走执行器:上下文中转,新增检查只需 checks.json + in-process-checks.mjs。
1179
+ const inProcessIds = Object.keys(IN_PROCESS_CHECKS).filter((id) => checkMeta.get(id)?.phase === 'in-process');
1180
+ const inProcessContext = {
1181
+ cssBytes,
1182
+ registryServer: { ...registryServer, cards: mergedMetas },
1183
+ registryClient: { ...registryClient, cards: mergedComponents },
1184
+ historyRendered,
1185
+ checkContrast,
1186
+ checkCardDensity,
1187
+ warn,
1188
+ };
1189
+ for (const item of await runInProcessChecks(inProcessContext, inProcessIds)) {
1190
+ push(item.id, checkMeta.get(item.id)?.lane ?? 'in-process', item.status, item.detail);
1191
+ }
1192
+
1193
+ // 档位决定车道:static 时布局/运行时一律 not-run,即使本机有探针结果。
1194
+ let experiencePolicy = 'visual';
1195
+ let acceptanceDoc = {};
1196
+ try {
1197
+ acceptanceDoc = readJsonc(path.join(appDir, 'scenarios/acceptance.jsonc'));
1198
+ } catch { /* 缺验收文件不阻断档位解析 */ }
1199
+ experiencePolicy = resolvePolicy({
1200
+ platformPolicy: process.env.TBOX_POLICY,
1201
+ docPolicy: acceptanceDoc.policy,
1202
+ docPolicyReason: acceptanceDoc.policyReason,
1203
+ }).policy;
1204
+
1205
+ // 布局车道:探针结果在 .tbox/evidence/shell.json(pnpm probe:shell);没有就如实 not-run。
1206
+ let shellResult = null;
1207
+ let shellStale = '';
1208
+ try {
1209
+ const shellFile = path.join(appDir, '.tbox/evidence/shell.json');
1210
+ if (existsSync(shellFile)) {
1211
+ // 探针结果早于壳/主题/kit 的最近改动 → 过期,按未运行处理(不拿旧结果冒充当前)。
1212
+ const inputs = [
1213
+ 'config/chat.json',
1214
+ 'apps/client/src/styles/brand.css',
1215
+ 'apps/client/src/styles/tokens.css',
1216
+ ].map((rel) => path.join(appDir, rel)).filter((file) => existsSync(file));
1217
+ // 整个 kit 源码都算探针输入(组件改动不只发生在 ChatPage/ChatInput);壳源/主题接线/依赖变更同样算。
1218
+ const newest = Math.max(
1219
+ ...inputs.map((file) => statSync(file).mtimeMs),
1220
+ newestMtime(path.join(appDir, 'packages/agent-ui-kit/src')),
1221
+ newestMtime(path.join(appDir, 'apps/client/src')),
1222
+ statSync(path.join(appDir, 'apps/client/package.json')).mtimeMs,
1223
+ 0,
1224
+ );
1225
+ shellResult = JSON.parse(readFileSync(shellFile, 'utf8'));
1226
+ // 协议版本高于门禁:不认识的结果不能当通过,也不能当失败——记 skip。
1227
+ if (Number(shellResult.protocolVersion ?? 1) > 1) {
1228
+ shellStale = '探针协议版本 ' + shellResult.protocolVersion + ' 高于门禁支持的 1(升级模板)';
1229
+ shellResult = null;
1230
+ }
1231
+ if (statSync(shellFile).mtimeMs + 1000 < newest) shellStale = '探针结果早于最近改动(重跑 pnpm probe:shell)';
1232
+ }
1233
+ } catch { shellResult = null; }
1234
+ if (shellStale) shellResult = null;
1235
+
1236
+ const { storyboard, stale: storyboardStale } = readStoryboardResult();
1237
+ // 探针车道走合并器:只按登记 id 取结果,档位/过期/协议语义在模块里。
1238
+ const probeIds = Object.keys(PROBE_CHECKS).filter((id) => checkMeta.get(id)?.phase === 'probe');
1239
+ for (const item of mergeProbeChecks({ probe: shellResult, ids: probeIds, policy: experiencePolicy, stale: shellStale })) {
1240
+ push(item.id, checkMeta.get(item.id)?.lane ?? item.lane, item.status, item.detail);
1241
+ }
1242
+
1243
+ const storyboardIds = Object.keys(STORYBOARD_CHECKS).filter((id) => checkMeta.get(id)?.phase === 'probe');
1244
+ const cardCount = Object.keys(mergedMetas).length;
1245
+ for (const item of mergeStoryboardChecks({ storyboard, ids: storyboardIds, policy: experiencePolicy, stale: storyboardStale, cardCount })) {
1246
+ push(item.id, checkMeta.get(item.id)?.lane ?? item.lane, item.status, item.detail);
1247
+ }
1248
+
1249
+ push('flow.persist', 'in-process', 'deferred', '需要重启探针(未接入)');
1250
+
1251
+ // 登记面与实现面一致:checks.json 里 source=experience 的 id 必须在本次证据里出现。
1252
+ try {
1253
+ const registry = JSON.parse(readFileSync(path.join(appDir, 'scripts', 'checks.json'), 'utf8'));
1254
+ // 自身先计入:登记表包含 checks.registry,不能自证缺失。
1255
+ const implemented = new Set([...items.map((item) => item.id), 'checks.registry']);
1256
+ const missing = (registry.checks ?? [])
1257
+ .filter((check) => check.source === 'experience' && !implemented.has(check.id))
1258
+ .map((check) => check.id);
1259
+ push('checks.registry', 'static', missing.length > 0 ? 'fail' : 'pass',
1260
+ missing.length > 0 ? '登记了但未实现:' + missing.join('、') : '检查项登记与实现一致');
1261
+ } catch {
1262
+ push('checks.registry', 'static', 'deferred', '读不到 scripts/checks.json');
1263
+ }
1264
+
1265
+ // 车道以登记表为准(旧条目缺 lane 时保留代码判定的车道)。
1266
+ for (const item of items) {
1267
+ const lane = checkMeta.get(item.id)?.lane;
1268
+ if (lane) item.lane = lane;
1269
+ // 检查项晚于应用模板版本(把新 checks.json 拷进旧应用)→ skip,不误报。
1270
+ const since = checkMeta.get(item.id)?.since;
1271
+ if (since && appVersion && !versionAtLeast(appVersion, since)) {
1272
+ item.status = 'skip';
1273
+ item.detail = '检查项晚于应用模板版本(since ' + since + ',应用 ' + appVersion + ')';
1274
+ }
1275
+ }
1276
+
1277
+ const errorFails = items.filter((item) => item.status === 'fail' && levelOf(item.id) === 'error');
1278
+ steps.push({ name: 'experience', ok: errorFails.length === 0, ms: Math.round(performance.now() - started), items });
1279
+ experienceItems = items;
1280
+ for (const item of items) {
1281
+ if (item.status !== 'fail') continue;
1282
+ if (levelOf(item.id) === 'warning') {
1283
+ warn('check-warning', '检查项未通过(告警级,不阻断):' + item.id + '(' + item.detail + ')', { fix: '按 docs/agent 对应配方修', recipe: 'verify' });
1284
+ continue;
1285
+ }
1286
+ errors.push({ step: 'experience', id: item.id, message: '体验不变量未通过:' + item.id + '(' + item.detail + ')', fix: '按 docs/agent 对应配方修;不要把它标成 handoff', recipe: 'verify' });
1287
+ }
1288
+ }
1289
+
777
1290
  // ── 执行 ────────────────────────────────────────────────────────────
778
1291
  await checkStyles();
779
1292
  if (registryServer) checkPrimitives();
@@ -782,6 +1295,8 @@ await checkScenarios();
782
1295
  if (registryServer) checkCoverage();
783
1296
  await checkRender();
784
1297
  checkRenderSignals();
1298
+ const stylesStep = steps.find((step) => step.name === 'styles');
1299
+ await checkExperience(stylesStep?.cssBytes ?? 0);
785
1300
  const verdict = gateVerdict();
786
1301
  try {
787
1302
  const dir = path.join(appDir, '.tbox/evidence');
@@ -800,13 +1315,15 @@ const summary = {
800
1315
  steps,
801
1316
  registry: {
802
1317
  tools: (registryServer?.tools ?? []).map((tool) => tool.id),
803
- cards: Object.keys(registryServer?.cards ?? {}),
1318
+ cards: Object.keys(mergedMetas),
1319
+ cardSources: mergedMetas && Object.fromEntries(Object.entries(cardProvenance).map(([cardType, source]) => [cardType, source.kind === 'module' ? source.moduleId : 'app'])),
804
1320
  actions: Object.keys(registryServer?.actions ?? {}),
805
1321
  },
806
1322
  warnings,
807
1323
  notRun,
808
1324
  evidence: { cards: cardDigests.length, scenarios: scenarioResults.length, instances: scenarioInstances.length },
809
1325
  ...verdict,
1326
+ experience: experienceItems,
810
1327
  };
811
1328
  if (errors.length > 0) summary.errors = errors;
812
1329