@tbox.cn/app-template-agent 1.0.0-alpha.8 → 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 (109) 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 +4 -2
  7. package/apps/client/package.json +1 -0
  8. package/apps/client/scripts/._color-scan.test.mjs +0 -0
  9. package/apps/client/scripts/._experience-checks.mjs +0 -0
  10. package/apps/client/scripts/._geometry-kernel.test.mjs +0 -0
  11. package/apps/client/scripts/._in-process-checks.mjs +0 -0
  12. package/apps/client/scripts/._probe-checks.mjs +0 -0
  13. package/apps/client/scripts/._sample-entries.test.mjs +0 -0
  14. package/apps/client/scripts/._storyboard.test.mjs +0 -0
  15. package/apps/client/scripts/._theme-kernel.mjs +0 -0
  16. package/apps/client/scripts/._theme-kernel.test.mjs +0 -0
  17. package/apps/client/scripts/acceptance-changes.test.mjs +97 -0
  18. package/apps/client/scripts/check-evidence.mjs +361 -94
  19. package/apps/client/scripts/color-scan.mjs +66 -0
  20. package/apps/client/scripts/color-scan.test.mjs +25 -0
  21. package/apps/client/scripts/evidence-gate.mjs +248 -46
  22. package/apps/client/scripts/evidence-gate.test.mjs +63 -5
  23. package/apps/client/scripts/experience-checks.mjs +163 -0
  24. package/apps/client/scripts/geometry-kernel.test.mjs +92 -0
  25. package/apps/client/scripts/in-process-checks.mjs +51 -0
  26. package/apps/client/scripts/lib/._card-registry.mjs +0 -0
  27. package/apps/client/scripts/lib/._card-registry.test.mjs +0 -0
  28. package/apps/client/scripts/lib/._evidence-inputs.mjs +0 -0
  29. package/apps/client/scripts/lib/._evidence-inputs.test.mjs +0 -0
  30. package/apps/client/scripts/lib/._static-render.mjs +0 -0
  31. package/apps/client/scripts/lib/._static-render.test.mjs +0 -0
  32. package/apps/client/scripts/lib/card-registry.mjs +81 -0
  33. package/apps/client/scripts/lib/card-registry.test.mjs +59 -0
  34. package/apps/client/scripts/lib/evidence-inputs.mjs +91 -0
  35. package/apps/client/scripts/lib/evidence-inputs.test.mjs +27 -0
  36. package/apps/client/scripts/lib/static-render.mjs +35 -0
  37. package/apps/client/scripts/lib/static-render.test.mjs +21 -0
  38. package/apps/client/scripts/probe-checks.mjs +85 -0
  39. package/apps/client/scripts/render-card.mjs +76 -60
  40. package/apps/client/scripts/sample-entries.test.mjs +31 -0
  41. package/apps/client/scripts/storyboard.test.mjs +149 -0
  42. package/apps/client/scripts/surface-css.mjs +5 -2
  43. package/apps/client/scripts/theme-kernel.mjs +236 -0
  44. package/apps/client/scripts/theme-kernel.test.mjs +136 -0
  45. package/apps/client/src/styles/brand.css +11 -11
  46. package/apps/client/src/styles/tailwind.css +3 -4
  47. package/apps/client/vite.config.ts +2 -1
  48. package/apps/server/scripts/probe.mjs +6 -1
  49. package/apps/server/scripts/scenario-lib.mjs +54 -7
  50. package/apps/server/scripts/scenario.mjs +41 -7
  51. package/config/AGENTS.md +1 -0
  52. package/config/chat.json +21 -9
  53. package/docs/agent/card.md +1 -0
  54. package/docs/agent/kit.md +1 -1
  55. package/docs/agent/shell.md +1 -0
  56. package/docs/agent/style.md +3 -1
  57. package/docs/agent/verify.md +37 -8
  58. package/package.json +9 -6
  59. package/packages/agent-ui-kit/README.md +21 -1
  60. package/packages/agent-ui-kit/catalog.json +1 -1
  61. package/packages/agent-ui-kit/package.json +9 -1
  62. package/packages/agent-ui-kit/src/ChatPage.tsx +30 -1
  63. package/packages/agent-ui-kit/src/card/primitives.test.tsx +10 -0
  64. package/packages/agent-ui-kit/src/card/primitives.tsx +14 -10
  65. package/packages/agent-ui-kit/src/card/view-card.tsx +6 -1
  66. package/packages/agent-ui-kit/src/chat-config.ts +11 -7
  67. package/packages/agent-ui-kit/src/components/ActionBar/DebugButton.test.tsx +3 -0
  68. package/packages/agent-ui-kit/src/components/ActionBar/DebugButton.tsx +2 -7
  69. package/packages/agent-ui-kit/src/components/BottomSheet/._index.test.tsx +0 -0
  70. package/packages/agent-ui-kit/src/components/BottomSheet/._index.tsx +0 -0
  71. package/packages/agent-ui-kit/src/components/BottomSheet/index.test.tsx +90 -0
  72. package/packages/agent-ui-kit/src/components/BottomSheet/index.tsx +129 -0
  73. package/packages/agent-ui-kit/src/components/ChatInput/index.test.tsx +2 -2
  74. package/packages/agent-ui-kit/src/components/ChatInput/index.tsx +21 -16
  75. package/packages/agent-ui-kit/src/components/HistoryEntry/index.tsx +1 -0
  76. package/packages/agent-ui-kit/src/components/QuickCommands/index.tsx +2 -2
  77. package/packages/agent-ui-kit/src/components/ScrollToBottomButton/index.tsx +7 -3
  78. package/packages/agent-ui-kit/src/components/ToolCallBlock/index.tsx +4 -2
  79. package/packages/agent-ui-kit/src/index.ts +4 -0
  80. package/packages/agent-ui-kit/src/shell.contract.json +9 -0
  81. package/packages/agent-ui-kit/src/shell.test.ts +10 -0
  82. package/packages/agent-ui-kit/src/shell.ts +15 -0
  83. package/packages/agent-ui-kit/src/theme/contract.json +78 -1
  84. package/packages/agent-ui-kit/src/theme/theme-contract.test.ts +16 -0
  85. package/packages/agent-ui-kit/src/theme/tokens.css +1 -1
  86. package/pnpm-lock.template.yaml +97 -91
  87. package/pnpm-workspace.template.yaml +10 -10
  88. package/profiles/mall/._chat.overrides.json +0 -0
  89. package/profiles/mall/chat.overrides.json +12 -0
  90. package/profiles/mall/config/chat.json +14 -6
  91. package/profiles/mall.json +1 -1
  92. package/scripts/._deliver.mjs +0 -0
  93. package/scripts/._shell-probe.mjs +0 -0
  94. package/scripts/._storyboard.mjs +0 -0
  95. package/scripts/check-fast.mjs +1 -0
  96. package/scripts/checks.json +294 -17
  97. package/scripts/deliver.mjs +183 -0
  98. package/scripts/lib/._chrome-pipe.mjs +0 -0
  99. package/scripts/lib/._geometry-kernel.mjs +0 -0
  100. package/scripts/lib/chrome-pipe.mjs +95 -0
  101. package/scripts/lib/geometry-kernel.mjs +137 -0
  102. package/scripts/shell-probe.mjs +283 -0
  103. package/scripts/storyboard.mjs +350 -0
  104. package/profiles/mall/config/llm_provider.json +0 -5
  105. package/profiles/mall/config/plugins.json +0 -3
  106. package/scripts/gen-tailwind-sources.mjs +0 -55
  107. /package/{profiles/mall/config/._llm_provider.json → .tbox/factory/._chat.json} +0 -0
  108. /package/{profiles/mall/config/._plugins.json → apps/client/scripts/._acceptance-changes.test.mjs} +0 -0
  109. /package/{scripts/._gen-tailwind-sources.mjs → apps/client/scripts/._color-scan.mjs} +0 -0
@@ -15,13 +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
21
  import { createHash } from 'node:crypto';
22
+ import { createServer as createHttpServer } from 'node:http';
22
23
  import { createRequire } from 'node:module';
23
24
  import { buildSurfaceCss } from './surface-css.mjs';
24
- import { acceptanceDrift, contrastRatio, coverageSets, hashSourceTree, parseColor, scenarioKey, shouldReopen } from './evidence-gate.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';
25
33
 
26
34
  // 门禁里的场景与渲染不写真实状态文件。
27
35
  process.env.TBOX_STATE_MEMORY ??= '1';
@@ -75,8 +83,14 @@ try {
75
83
  '@config': path.join(appDir, 'config'),
76
84
  },
77
85
  },
78
- server: { middlewareMode: true, fs: { allow: [appDir] } },
86
+ // 零 socket:HMR 挂到永不 listen 的 http server,避免自建 24678 监听。
87
+ server: { middlewareMode: true, hmr: { server: createHttpServer() }, fs: { allow: [appDir] } },
79
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'] },
80
94
  });
81
95
  steps.push({ name: 'vite', ok: true, ms: Math.round(performance.now() - bootstrapStart) });
82
96
  } catch (error) {
@@ -95,6 +109,13 @@ const registryServer = await vite.ssrLoadModule('/@fs' + path.join(clientDir, '.
95
109
  return undefined;
96
110
  });
97
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
+
98
119
  // ── 1. styles ───────────────────────────────────────────────────────
99
120
  async function checkStyles() {
100
121
  const started = performance.now();
@@ -113,16 +134,36 @@ async function checkStyles() {
113
134
  try {
114
135
  const surface = await buildSurfaceCss(vite, { clientDir, appDir });
115
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
+ : [];
116
149
  if (surface.bytes < 20000 || surface.missing.length > 0) {
117
150
  fail('styles', [{
118
151
  id: 'styles-empty',
119
152
  message: `表面 CSS 不可信:${surface.bytes} 字节,缺哨兵 ${surface.missing.join('、') || '无'}`,
120
- fix: '确认 apps/client/src/styles/tailwind.css 存在且 @source 覆盖 src 与 kit;证据与 dev/build 共用 surface-css.mjs',
153
+ fix: '确认 apps/client/vite.config.ts 的 tboxModuleSourcesPlugin 在 tailwindcss() 之前;证据与 dev/build 共用 surface-css.mjs 与 app-build 的模块发现',
121
154
  recipe: 'style',
122
155
  }]);
123
- steps.push({ name: 'styles', ok: false, ms: Math.round(performance.now() - started), cssBytes: surface.bytes });
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 });
124
165
  } else {
125
- steps.push({ name: 'styles', ok: true, ms: Math.round(performance.now() - started), cssBytes: surface.bytes });
166
+ steps.push({ name: 'styles', ok: true, ms: Math.round(performance.now() - started), cssBytes: surface.bytes, moduleSources: moduleSources.length, expectedModules });
126
167
  }
127
168
  } catch (error) {
128
169
  fail('styles', [{
@@ -169,23 +210,26 @@ function checkUtilityClasses(cssText) {
169
210
  // ── 2. primitives ───────────────────────────────────────────────────
170
211
  function checkPrimitives() {
171
212
  const started = performance.now();
172
- const cards = registryServer?.cards ?? {};
213
+ const cards = mergedMetas;
173
214
  const cardTypes = new Set(Object.keys(cards));
174
215
  const tools = registryServer?.tools ?? [];
175
216
 
176
217
  for (const [cardType, meta] of Object.entries(cards)) {
177
- const samples = [
178
- ['sampleData', meta.sampleData],
179
- ...(Array.isArray(meta.samples) ? meta.samples.map((sample, index) => [`samples[${index}]`, sample?.data]) : []),
180
- ];
181
- for (const [label, data] of samples) {
182
- 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);
183
227
  if (!parsed.success) {
184
228
  errors.push({
185
229
  step: 'primitives',
186
230
  id: 'card-sample-invalid',
187
- message: `卡片样例不合法 ${cardType} ${label}: ${parsed.error.issues[0]?.message ?? parsed.error.message}`,
188
- 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`,
189
233
  recipe: 'card',
190
234
  });
191
235
  }
@@ -392,7 +436,7 @@ async function checkRender() {
392
436
  steps.push({ name: 'render', ok: true, ms: 0, skipped: true });
393
437
  return;
394
438
  }
395
- const metas = registryServer?.cards ?? {};
439
+ const metas = mergedMetas;
396
440
  if (Object.keys(metas).length === 0) {
397
441
  steps.push({ name: 'render', ok: true, ms: Math.round(performance.now() - started), cards: 0, rendered: 0, skipped: true });
398
442
  return;
@@ -400,8 +444,9 @@ async function checkRender() {
400
444
  const React = (await import('react')).default;
401
445
  const { renderToStaticMarkup } = await import('react-dom/server');
402
446
  const kit = await vite.ssrLoadModule('@tbox.cn/app-agent-ui-kit');
447
+ const staticRender = createStaticRenderer(renderToStaticMarkup);
403
448
 
404
- const components = registryClient?.cards ?? {};
449
+ const components = mergedComponents;
405
450
  // 与运行时 / 预览 / 截图同一条装配(SurfaceHarness),不再手搭 provider。
406
451
  const harness = kit.createSurfaceHarness({ cards: components });
407
452
  let rendered = 0;
@@ -409,41 +454,39 @@ async function checkRender() {
409
454
 
410
455
  for (const [cardType, meta] of Object.entries(metas)) {
411
456
  const Component = components[cardType];
457
+ const sourceFile = cardSourceHint(cardProvenance, cardType);
412
458
  if (!Component) {
413
459
  errors.push({
414
460
  step: 'render',
415
461
  id: 'card-client-missing',
416
462
  message: `客户端缺少卡片组件 ${cardType}`,
417
- fix: `补 apps/client/src/cards/${cardType}.card.tsx(export const card = defineCard({ type: '${cardType}' }, …))`,
463
+ fix: `补 ${sourceFile}(export const card = defineCard({ type: '${cardType}' }, …))`,
418
464
  recipe: 'card',
419
465
  });
420
466
  continue;
421
467
  }
422
- const samples = [
423
- ['sampleData', meta.sampleData],
424
- ...(Array.isArray(meta.samples) ? meta.samples.map((sample, index) => [sample?.label ?? `samples[${index}]`, sample?.data]) : []),
425
- ];
426
- for (const [label, data] of samples) {
468
+ for (const sample of sampleEntries(meta)) {
469
+ const { label, data } = sample;
427
470
  try {
428
- const html = renderToStaticMarkup(
429
- harness.wrap(React.createElement(Component, { data, cardId: `evidence-${cardType}`, isHistory: false, actionTokens: {} })),
471
+ const html = staticRender.render(
472
+ harness.wrap(React.createElement(Component, { data, cardId: `evidence-${cardType}`, isHistory: sample.isHistory === true, actionTokens: {} })),
430
473
  );
431
474
  rendered += 1;
432
475
  bytes += html.length;
433
- cardDigests.push({ cardType, label, source: 'sample', text: htmlDigest(html) });
476
+ cardDigests.push({ cardType, label, source: 'sample', hidden: sample.hidden === true, text: htmlDigest(html) });
434
477
  // 历史态是必验状态(只读、动作禁用):只验默认态会漏掉整类分支。
435
478
  if (label === 'sampleData') {
436
479
  try {
437
- const historyHtml = renderToStaticMarkup(
480
+ const historyHtml = staticRender.render(
438
481
  harness.wrap(React.createElement(Component, { data, cardId: `evidence-history-${cardType}`, isHistory: true, actionTokens: {} })),
439
482
  );
440
483
  if (!historyHtml.trim()) {
441
- errors.push({ step: 'render', file: `apps/client/src/cards/${cardType}.card.tsx`, id: 'card-state-empty', message: `卡片 ${cardType} 历史态渲染为空`, fix: '历史态不要返回空树(用 isHistory 只禁用动作,不隐藏内容)', recipe: 'card' });
484
+ errors.push({ step: 'render', file: sourceFile, id: 'card-state-empty', message: `卡片 ${cardType} 历史态渲染为空`, fix: '历史态不要返回空树(用 isHistory 只禁用动作,不隐藏内容)', recipe: 'card' });
442
485
  } else {
443
486
  historyRendered += 1;
444
487
  }
445
488
  } catch (error) {
446
- errors.push({ step: 'render', file: `apps/client/src/cards/${cardType}.card.tsx`, id: 'card-state-failed', message: `卡片 ${cardType} 历史态渲染抛错:${error?.message ?? error}`, fix: '历史态分支(isHistory)按报错栈修', recipe: 'card' });
489
+ errors.push({ step: 'render', file: sourceFile, id: 'card-state-failed', message: `卡片 ${cardType} 历史态渲染抛错:${error?.message ?? error}`, fix: '历史态分支(isHistory)按报错栈修', recipe: 'card' });
447
490
  }
448
491
  }
449
492
  if (html.trim() === '') {
@@ -458,7 +501,7 @@ async function checkRender() {
458
501
  } catch (error) {
459
502
  errors.push({
460
503
  step: 'render',
461
- file: `apps/client/src/cards/${cardType}.card.tsx`,
504
+ file: sourceFile,
462
505
  id: 'card-render-failed',
463
506
  message: `卡片 ${cardType} ${label} 渲染抛错:${error?.message ?? error}`,
464
507
  fix: '按报错栈修组件;数据形状以服务端 dataSchema 为准',
@@ -497,7 +540,7 @@ async function checkRender() {
497
540
  }
498
541
  }
499
542
 
500
- 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() });
501
544
  }
502
545
 
503
546
  // ── 4. scenarios ────────────────────────────────────────────────────
@@ -525,7 +568,7 @@ async function checkScenarios() {
525
568
  steps.push({ name: 'scenarios', ok: true, ms: Math.round(performance.now() - started), scenarios: 0, skipped: true });
526
569
  return;
527
570
  }
528
- const result = await lib.runScenarios({ appDir, registry: registryServer, files });
571
+ const result = await lib.runScenarios({ appDir, registry: { ...registryServer, cards: mergedMetas }, files });
529
572
  scenarioResults = result.results;
530
573
  scenarioInstances = result.instances ?? [];
531
574
  for (const item of result.results) {
@@ -592,7 +635,18 @@ function gateVerdict() {
592
635
  const scenarioItems = items.filter((item) => (item.by ?? 'scenario') === 'scenario' && !item.lane);
593
636
  // E1:review 改名为 handoff(旧名保留为别名)。名字本身不再邀请复审。
594
637
  // E2:证据策略声明本任务允许验证到哪一级;handoff 只接受策略判为不可验的维度。
595
- 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
+ }
596
650
  if (doc.policy && !['static', 'visual', 'flow'].includes(doc.policy)) {
597
651
  warn('policy-unknown', `scenarios/acceptance.jsonc 的 policy=${JSON.stringify(doc.policy)} 不支持(static / visual / flow),按 static 处理`, {
598
652
  fix: '改成三档之一,或删掉 policy 使用缺省 static',
@@ -600,6 +654,12 @@ function gateVerdict() {
600
654
  });
601
655
  }
602
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
+ };
603
663
  const originByFile = new Map();
604
664
  for (const result of scenarioResults) {
605
665
  let origin = 'spec';
@@ -610,12 +670,15 @@ function gateVerdict() {
610
670
  originByFile.set(result.file, origin);
611
671
  }
612
672
  const { covered, declared: declaredCovered } = coverageSets(scenarioResults, originByFile);
673
+ // D1:界面类验收项由故事板证明「渲染出来了且没有几何错误」——与场景覆盖分列,不混算。
674
+ const board = storyboardCoverage(items, readStoryboardResult().storyboard, policy);
613
675
  // 策略允许场景验证的项不能借 handoff 绕过:没有 reason 的 handoff 计入 incomplete。
614
676
  // 旧名 review 不要求 reason(历史应用平滑);新名 handoff 必须写清为什么当前策略验不了。
615
677
  const handoffWithoutReason = handoffItems.filter((item) => item.by === 'handoff' && !item.reason);
616
678
  const uncovered = [
617
679
  ...scenarioItems.filter((item) => !covered.has(item.id)).map((item) => item.id),
618
680
  ...handoffWithoutReason.map((item) => item.id),
681
+ ...[...board.failed.keys()],
619
682
  ];
620
683
  if (handoffWithoutReason.length > 0) {
621
684
  warn('handoff-misuse', `handoff 项缺 reason:${handoffWithoutReason.map((item) => item.id).join('、')}(能由场景判定的项不要标 handoff)`, {
@@ -646,6 +709,8 @@ function gateVerdict() {
646
709
  declared: { tools: declaredTools.size, actions: declaredActions.size, cards: declaredCards.size },
647
710
  missing: { tools: missingTools, actions: missingActions, cards: missingCards },
648
711
  };
712
+ // 自有工具 = 注册表里的工具减去模块声明的(模块工具不算「你自己写的」)。
713
+ const ownToolCount = Math.max(0, (registryServer?.tools?.length ?? 0) - moduleSurface.tools.length);
649
714
  const missingCapabilityText = [
650
715
  ...missingTools.map((id) => `工具 ${id}`),
651
716
  ...missingActions.map((id) => `动作 ${id}`),
@@ -660,6 +725,11 @@ function gateVerdict() {
660
725
  scenarioResults.length > 0
661
726
  ? `已验证:${scenarioResults.length} 个场景 / ${scenarioSteps} 步 / ${covered.size} 项`
662
727
  : '未运行:没有场景(先按 verify.md 写一条)',
728
+ storyboard: policy === 'static'
729
+ ? '未运行:当前策略 static'
730
+ : board.covered.size > 0
731
+ ? `已验证:${board.covered.size} 个界面项由故事板覆盖`
732
+ : '未运行:没有 by: "storyboard" 的验收项',
663
733
  render:
664
734
  cardDigests.length > 0
665
735
  ? `已验证:${cardDigests.length} 张卡 / ${scenarioInstances.length + cardDigests.length} 份样例`
@@ -667,7 +737,10 @@ function gateVerdict() {
667
737
  visual: policy === 'static' ? '未运行:当前策略 static(任务要求快速交付,不起浏览器)' : '未运行:本轮未执行浏览器(需要 --visual / dev server)',
668
738
  routing: policy === 'flow' ? '未运行:本轮未跑模型级验收' : '未运行:当前策略不要求模型级验收',
669
739
  };
670
- 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
+ ];
671
744
 
672
745
  let verdict;
673
746
  let next;
@@ -679,6 +752,11 @@ function gateVerdict() {
679
752
  next = hasSurface
680
753
  ? '先把需求拆成 scenarios/acceptance.jsonc 的验收项(id + text),再让场景用 covers 声明覆盖'
681
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`;
682
760
  } else if (missingCapabilityText.length > 0) {
683
761
  verdict = 'incomplete';
684
762
  next = `能力图还缺:${missingCapabilityText.join('、')};先在 acceptance.jsonc 声明,再补对应文件(new tool / new card / new action)`;
@@ -687,17 +765,38 @@ function gateVerdict() {
687
765
  next = `未覆盖验收项:${uncovered.join('、')};补场景并在 covers 里登记,或给确实无法自动判定的项标 by: "handoff" 并写 reason`;
688
766
  } else {
689
767
  verdict = 'deliverable';
768
+ const boardHint = uiHandoffHint();
690
769
  next =
691
770
  handoff.length > 0
692
- ? `把 handoff 的 ${handoff.length} 项原样写进交付说明,然后结束。这些项在当前策略(${policy})下无法验证,继续读代码不会改变它们的状态。`
771
+ ? `把 handoff 的 ${handoff.length} 项原样写进交付说明,然后结束。这些项在当前策略(${policy})下无法验证,继续读代码不会改变它们的状态${boardHint}。`
693
772
  : '交付条件已满足:总结并结束。不要继续复审或打磨。';
694
773
  }
695
774
 
696
- // T1 漂移:验收文件变了就记下来,不阻断。
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 : [] };
697
792
  const acceptance = acceptanceDrift(prevGate, acceptanceHash, acceptanceIds);
698
793
  const drift = [...acceptance.drift];
699
- if (acceptance.drift.length > 0) {
700
- warn('acceptance-drift', acceptance.drift[0].detail, { fix: '确认改动是有意的;交付包会列出漂移', recipe: 'verify' });
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
+ });
701
800
  }
702
801
  const scenarioHashes = {};
703
802
  const failedScenarios = [];
@@ -708,6 +807,11 @@ function gateVerdict() {
708
807
  } catch { /* 读失败不影响裁决 */ }
709
808
  if (!result.ok) failedScenarios.push(path.relative(appDir, result.file));
710
809
  }
810
+ // 场景删除也是漂移:失败后删场景会让门禁「变绿」,必须让用户看见。
811
+ for (const item of scenarioDrift(prevGate, scenarioHashes)) {
812
+ drift.push(item);
813
+ warn('scenario-drift', item.detail, { fix: '在交付说明里写清为什么删场景', recipe: 'verify' });
814
+ }
711
815
  if (prevGate && prevGate.scenarioHashes) {
712
816
  for (const [scenarioFile, hash] of Object.entries(scenarioHashes)) {
713
817
  const prevHash = prevGate.scenarioHashes[scenarioFile];
@@ -727,7 +831,49 @@ function gateVerdict() {
727
831
  next = '交付后内容有改动:重跑一次 check:fast 确认,再交付(不做硬停)。';
728
832
  }
729
833
 
834
+ // 能力偏离:与 create 的出厂基线快照比(画像覆盖已被快照吸收,不会误判成 agent 偏离)。
835
+ let capability = { skipped: true, reason: '缺出厂基线快照', items: [] };
836
+ try {
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
+
730
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 },
731
877
  trace: items.map((item) => ({
732
878
  id: item.id,
733
879
  text: item.text ?? '',
@@ -743,7 +889,9 @@ function gateVerdict() {
743
889
  ],
744
890
  };
745
891
  if (verdict === 'deliverable' && delivery.deferred.length > 0) {
746
- next = '把 deferred 的 ' + delivery.deferred.length + ' 项如实写进交付说明,然后结束。';
892
+ // 界面项被标 handoff 时给一次可执行出口:故事板能证明「渲染出来且没几何错误」。
893
+ const boardHint = uiHandoffHint();
894
+ next = '把 deferred 的 ' + delivery.deferred.length + ' 项如实写进交付说明,然后结束' + boardHint + '。';
747
895
  }
748
896
  const gateFile = path.join(appDir, '.tbox/evidence/gate.json');
749
897
  let changedFiles = 0;
@@ -765,6 +913,8 @@ function gateVerdict() {
765
913
  runs,
766
914
  acceptanceHash,
767
915
  acceptanceIds,
916
+ acceptanceDigest: digest,
917
+ acceptanceChanges: acceptanceChange.cumulative,
768
918
  scenarioHashes,
769
919
  failedScenarios,
770
920
  contentHash,
@@ -785,9 +935,11 @@ function gateVerdict() {
785
935
  items: items.length,
786
936
  covered: covered.size,
787
937
  declared: declaredCovered.size,
938
+ // 故事板覆盖单独计数,不与场景覆盖混算。
939
+ storyboard: board.covered.size,
788
940
  // 旧名保留一版(读取方可能仍看 review);新代码用 handoff。
789
941
  review: handoffItems.length,
790
- handoff: handoffItems.length,
942
+ handoff: handoffItems.length + board.handoff.size,
791
943
  uncovered,
792
944
  ...(file ? { file: path.relative(appDir, file) } : {}),
793
945
  },
@@ -810,8 +962,9 @@ function checkRenderSignals() {
810
962
  const byCard = new Map();
811
963
  for (const item of cardDigests) byCard.set(item.cardType, [...(byCard.get(item.cardType) ?? []), item]);
812
964
  for (const [cardType, list] of byCard) {
813
- if (list.length >= 2 && new Set(list.map((item) => item.text)).size === 1) {
814
- 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} 份样例渲染结果完全相同——状态没有真正区分`, {
815
968
  fix: '给不同状态不同的可见内容(状态标签/按钮/提示),或删掉重复样例',
816
969
  recipe: 'card',
817
970
  });
@@ -837,7 +990,7 @@ function checkRenderSignals() {
837
990
  // ── 4.5 状态覆盖(声明样例 + 场景实例) ──────────────────────────
838
991
  function checkCoverage() {
839
992
  const started = performance.now();
840
- const metas = registryServer?.cards ?? {};
993
+ const metas = mergedMetas;
841
994
  for (const [cardType, meta] of Object.entries(metas)) {
842
995
  const declared = [
843
996
  meta.sampleData,
@@ -932,7 +1085,7 @@ async function checkCardDensity() {
932
1085
  if (typeof estimate !== 'function') return { available: false, worst: 0, violations: [], reason: '契约未导出 estimateCardHeight' };
933
1086
  let worst = 0;
934
1087
  const violations = [];
935
- for (const [cardType, meta] of Object.entries(registryServer.cards ?? {})) {
1088
+ for (const [cardType, meta] of Object.entries(mergedMetas)) {
936
1089
  if (!meta || !meta.view) continue;
937
1090
  const samples = [meta.sampleData, ...(Array.isArray(meta.samples) ? meta.samples.map((sample) => sample && sample.data) : [])];
938
1091
  for (const data of samples) {
@@ -949,75 +1102,188 @@ async function checkCardDensity() {
949
1102
 
950
1103
  // ── 4.8 体验不变量(登记在 checks.json 的 experience 族)──────────────
951
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
+
952
1155
  async function checkExperience(cssBytes) {
953
1156
  const started = performance.now();
954
1157
  const items = [];
955
1158
  const push = (id, lane, status, detail) => items.push({ id, lane, status, detail });
956
1159
 
1160
+ // 登记表是检查项元数据的真源:level 决定阻断/告警,lane 决定车道,since 决定旧应用是否跳过。
1161
+ const checkMeta = new Map();
957
1162
  try {
958
- const html = readFileSync(path.join(clientDir, 'index.html'), 'utf8');
959
- const inline = [...html.matchAll(/<script\b([^>]*)>/gi)].filter((match) => !/\bsrc\s*=/.test(match[1]));
960
- push('boot.inline-script', 'static', inline.length === 0 ? 'pass' : 'fail', inline.length === 0 ? '入口零内联脚本' : '入口有 ' + inline.length + ' 段内联脚本');
961
- } catch (error) {
962
- push('boot.inline-script', 'static', 'fail', '读不到 apps/client/index.html:' + (error?.message ?? error));
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);
963
1191
  }
964
1192
 
1193
+ // 档位决定车道:static 时布局/运行时一律 not-run,即使本机有探针结果。
1194
+ let experiencePolicy = 'visual';
1195
+ let acceptanceDoc = {};
965
1196
  try {
966
- const bubble = path.join(appDir, 'packages/agent-ui-kit/src/components/MessageBubble/index.tsx');
967
- const source = readFileSync(bubble, 'utf8');
968
- push('shell.identity', 'static', source.includes('identity?.name') ? 'pass' : 'fail', '发送者名取 identity.name');
969
- } catch (error) {
970
- push('shell.identity', 'static', 'deferred', 'kit 副本不在预期位置:' + (error?.message ?? error));
971
- }
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;
972
1204
 
973
- const offScale = [];
974
- for (const root of [path.join(clientDir, 'src'), path.join(appDir, 'packages/agent-ui-kit/src')]) {
975
- if (!existsSync(root)) continue;
976
- const walk = (dir) => {
977
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
978
- const full = path.join(dir, entry.name);
979
- if (entry.isDirectory()) walk(full);
980
- else if (/\.(tsx?|css)$/.test(entry.name) && !entry.name.endsWith('.test.tsx')) {
981
- if (/text-\[\d+(?:\.\d+)?px\]/.test(readFileSync(full, 'utf8'))) offScale.push(path.relative(appDir, full));
982
- }
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;
983
1230
  }
984
- };
985
- walk(root);
986
- }
987
- push('shell.type-scale', 'static', offScale.length === 0 ? 'pass' : 'fail', offScale.length === 0 ? '档外字号 0 处' : '档外字号:' + offScale.slice(0, 5).join('、'));
988
- const contrast = checkContrast();
989
- push('shell.contrast', 'static', contrast.status, contrast.detail);
990
- push('css.sentinel', 'in-process', cssBytes >= 20000 ? 'pass' : 'fail', cssBytes + ' 字节');
1231
+ if (statSync(shellFile).mtimeMs + 1000 < newest) shellStale = '探针结果早于最近改动(重跑 pnpm probe:shell)';
1232
+ }
1233
+ } catch { shellResult = null; }
1234
+ if (shellStale) shellResult = null;
991
1235
 
992
- const cardCount = Object.keys(registryServer?.cards ?? {}).length;
993
- push('card.states', 'in-process', cardCount === 0 ? 'deferred' : historyRendered >= cardCount ? 'pass' : 'fail', cardCount === 0 ? '没有卡片' : '历史态 ' + historyRendered + '/' + cardCount);
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
+ }
994
1242
 
995
- const density = await checkCardDensity();
996
- const viewCards = Object.values(registryServer?.cards ?? {}).filter((meta) => meta && meta.view).length;
997
- if (cardCount === 0) {
998
- push('card.height', 'in-process', 'deferred', '没有卡片');
999
- } else if (!density.available) {
1000
- push('card.height', 'in-process', 'deferred', '视图卡密度未检查:' + density.reason);
1001
- } else if (viewCards === 0) {
1002
- push('card.height', 'in-process', 'pass', '没有视图卡(三件套不估算)');
1003
- } else {
1004
- if (density.worst > 506 && density.worst <= 633) {
1005
- warn('card-height-warn', '视图卡最高 ' + density.worst + 'px(超过一屏 60% 的 506px)', { fix: '优先减积木或拆卡;>633px 会阻断', recipe: 'card' });
1006
- }
1007
- push('card.height', 'in-process', density.violations.length > 0 ? 'fail' : 'pass', '最高 ' + density.worst + 'px' + (density.violations.length > 0 ? ';超限:' + density.violations.join('、') : ''));
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);
1008
1247
  }
1009
1248
 
1010
- push('shell.hit-target', 'browser', 'deferred', '浏览器车道未接入(平台车道暂缓)');
1011
- push('shell.quick-visible', 'browser', 'deferred', '浏览器车道未接入(平台车道暂缓)');
1012
- push('shell.blank', 'browser', 'deferred', '浏览器车道未接入(平台车道暂缓)');
1013
1249
  push('flow.persist', 'in-process', 'deferred', '需要重启探针(未接入)');
1014
1250
 
1015
- steps.push({ name: 'experience', ok: !items.some((item) => item.status === 'fail'), ms: Math.round(performance.now() - started), items });
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 });
1016
1279
  experienceItems = items;
1017
1280
  for (const item of items) {
1018
- if (item.status === 'fail') {
1019
- errors.push({ step: 'experience', id: item.id, message: '体验不变量未通过:' + item.id + '(' + item.detail + ')', fix: '按 docs/agent 对应配方修;不要把它标成 handoff', recipe: 'verify' });
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;
1020
1285
  }
1286
+ errors.push({ step: 'experience', id: item.id, message: '体验不变量未通过:' + item.id + '(' + item.detail + ')', fix: '按 docs/agent 对应配方修;不要把它标成 handoff', recipe: 'verify' });
1021
1287
  }
1022
1288
  }
1023
1289
 
@@ -1049,7 +1315,8 @@ const summary = {
1049
1315
  steps,
1050
1316
  registry: {
1051
1317
  tools: (registryServer?.tools ?? []).map((tool) => tool.id),
1052
- 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'])),
1053
1320
  actions: Object.keys(registryServer?.actions ?? {}),
1054
1321
  },
1055
1322
  warnings,