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

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 (91) hide show
  1. package/.tbox/app.json +1 -1
  2. package/.tbox/default-modules.json +1 -1
  3. package/.tbox/miniapp-containers.json +1 -1
  4. package/AGENTS.md +8 -7
  5. package/apps/client/index.html +0 -43
  6. package/apps/client/scripts/check-evidence.mjs +327 -77
  7. package/apps/client/scripts/evidence-gate.mjs +135 -0
  8. package/apps/client/scripts/evidence-gate.test.mjs +77 -0
  9. package/apps/client/scripts/render-card.mjs +20 -67
  10. package/apps/client/scripts/surface-css.mjs +51 -0
  11. package/apps/client/src/app.config.ts +4 -1
  12. package/apps/client/src/styles/brand.css +2 -3
  13. package/apps/client/src/styles/tailwind.css +17 -17
  14. package/apps/server/scripts/scenario-lib.mjs +2 -1
  15. package/docs/agent/agent-prompt.md +1 -1
  16. package/docs/agent/card-action.md +5 -0
  17. package/docs/agent/card.md +44 -2
  18. package/docs/agent/kit.md +2 -2
  19. package/docs/agent/style.md +8 -2
  20. package/docs/agent/tool-emits-card.md +7 -2
  21. package/docs/agent/tool.md +2 -0
  22. package/docs/agent/verify.md +23 -9
  23. package/package.json +16 -5
  24. package/packages/agent-ui-kit/AGENTS.md +1 -1
  25. package/packages/agent-ui-kit/catalog.json +7 -3
  26. package/packages/agent-ui-kit/package.json +1 -1
  27. package/packages/agent-ui-kit/src/ChatPage.tsx +40 -16
  28. package/packages/agent-ui-kit/src/card/action-list-pending.test.tsx +91 -0
  29. package/packages/agent-ui-kit/src/card/define-card.test.ts +25 -0
  30. package/packages/agent-ui-kit/src/card/define-card.ts +18 -5
  31. package/packages/agent-ui-kit/src/card/primitives.tsx +122 -27
  32. package/packages/agent-ui-kit/src/card/view-card-inline.test.tsx +42 -0
  33. package/packages/agent-ui-kit/src/card/view-card.test.tsx +79 -0
  34. package/packages/agent-ui-kit/src/card/view-card.tsx +245 -0
  35. package/packages/agent-ui-kit/src/components/ChatInput/index.tsx +1 -1
  36. package/packages/agent-ui-kit/src/components/HistoryEntry/index.tsx +2 -2
  37. package/packages/agent-ui-kit/src/components/MessageBubble/index.tsx +11 -5
  38. package/packages/agent-ui-kit/src/components/QuickCommands/index.test.tsx +3 -1
  39. package/packages/agent-ui-kit/src/components/QuickCommands/index.tsx +31 -8
  40. package/packages/agent-ui-kit/src/index.ts +4 -0
  41. package/packages/agent-ui-kit/src/preview-provider.tsx +47 -0
  42. package/packages/agent-ui-kit/src/surface.test.tsx +35 -0
  43. package/packages/agent-ui-kit/src/surface.tsx +44 -0
  44. package/packages/agent-ui-kit/src/theme/base.css +9 -11
  45. package/packages/agent-ui-kit/src/theme/contract.json +45 -1
  46. package/packages/agent-ui-kit/src/theme/tokens.css +8 -11
  47. package/pnpm-lock.template.yaml +91 -91
  48. package/pnpm-workspace.template.yaml +10 -10
  49. package/scripts/assert-pack.mjs +48 -0
  50. package/scripts/check-css-target.mjs +6 -3
  51. package/scripts/checks.json +123 -26
  52. package/.tbox/card-render/baseline/demo.png +0 -0
  53. package/.tbox/card-render/demo.html +0 -342
  54. package/.tbox/card-render/demo.png +0 -0
  55. package/.tbox/card-render/scale-demo.audit.html +0 -984
  56. package/.tbox/card-render/scale-demo.html +0 -939
  57. package/.tbox/evidence/cards.txt +0 -1
  58. package/.tbox/evidence/gate.json +0 -1
  59. package/.tbox/evidence/last-gate.json +0 -1
  60. package/.tbox/evidence/scenarios.json +0 -1
  61. package/apps/client/.tbox-gen/._manifest.json +0 -0
  62. package/apps/client/.tbox-gen/._registry.client.ts +0 -0
  63. package/apps/client/.tbox-gen/._registry.server.ts +0 -0
  64. package/apps/client/.tbox-gen/app-registry.ts +0 -3
  65. package/apps/client/.tbox-gen/documents/._index.html +0 -0
  66. package/apps/client/.tbox-gen/documents/_tbox/._card-preview.html +0 -0
  67. package/apps/client/.tbox-gen/documents/_tbox/card-preview.html +0 -62
  68. package/apps/client/.tbox-gen/documents/index.html +0 -63
  69. package/apps/client/.tbox-gen/entries/._card-preview.tsx +0 -0
  70. package/apps/client/.tbox-gen/entries/._index.tsx +0 -0
  71. package/apps/client/.tbox-gen/entries/card-preview.tsx +0 -6
  72. package/apps/client/.tbox-gen/entries/index.tsx +0 -11
  73. package/apps/client/.tbox-gen/manifest.json +0 -17
  74. package/apps/client/.tbox-gen/registry.client.ts +0 -6
  75. package/apps/client/.tbox-gen/registry.server.ts +0 -15
  76. package/apps/client/STYLE_GUIDE.md +0 -48
  77. package/apps/client/VISUAL_RESTORE.md +0 -90
  78. package/scripts/._compat-probe.mjs +0 -0
  79. package/scripts/compat-probe.mjs +0 -108
  80. /package/{.tbox/card-render/._demo.html → apps/client/scripts/._evidence-gate.mjs} +0 -0
  81. /package/{.tbox/card-render/._demo.png → apps/client/scripts/._evidence-gate.test.mjs} +0 -0
  82. /package/{.tbox/card-render/._scale-demo.audit.html → apps/client/scripts/._surface-css.mjs} +0 -0
  83. /package/{.tbox/card-render/._scale-demo.html → packages/agent-ui-kit/src/._preview-provider.tsx} +0 -0
  84. /package/{.tbox/card-render/baseline/._demo.png → packages/agent-ui-kit/src/._surface.test.tsx} +0 -0
  85. /package/{.tbox/evidence/._cards.txt → packages/agent-ui-kit/src/._surface.tsx} +0 -0
  86. /package/{.tbox/evidence/._gate.json → packages/agent-ui-kit/src/card/._action-list-pending.test.tsx} +0 -0
  87. /package/{.tbox/evidence/._last-gate.json → packages/agent-ui-kit/src/card/._define-card.test.ts} +0 -0
  88. /package/{.tbox/evidence/._scenarios.json → packages/agent-ui-kit/src/card/._view-card-inline.test.tsx} +0 -0
  89. /package/{apps/client/._STYLE_GUIDE.md → packages/agent-ui-kit/src/card/._view-card.test.tsx} +0 -0
  90. /package/{apps/client/._VISUAL_RESTORE.md → packages/agent-ui-kit/src/card/._view-card.tsx} +0 -0
  91. /package/{apps/client/.tbox-gen/._app-registry.ts → scripts/._assert-pack.mjs} +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
  *
@@ -18,6 +18,10 @@ import { execFileSync } from 'node:child_process';
18
18
  import { existsSync, mkdirSync, readdirSync, readFileSync, 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 { createRequire } from 'node:module';
23
+ import { buildSurfaceCss } from './surface-css.mjs';
24
+ import { acceptanceDrift, contrastRatio, coverageSets, hashSourceTree, parseColor, scenarioKey, shouldReopen } from './evidence-gate.mjs';
21
25
 
22
26
  // 门禁里的场景与渲染不写真实状态文件。
23
27
  process.env.TBOX_STATE_MEMORY ??= '1';
@@ -28,8 +32,6 @@ const args = new Set(process.argv.slice(2));
28
32
  const withRender = !args.has('--no-render');
29
33
  const withScenarios = !args.has('--no-scenarios');
30
34
 
31
- const MIN_DESIGN_FONT_PX = 22; // ≈11 屏幕像素(750 设计稿,rootValue 100)
32
-
33
35
  const steps = [];
34
36
  const warnings = [];
35
37
  const notRun = [];
@@ -37,6 +39,9 @@ const errors = [];
37
39
  let scenarioResults = [];
38
40
  let scenarioInstances = [];
39
41
  const cardDigests = [];
42
+ let historyRendered = 0;
43
+ let experienceItems = [];
44
+ let cardFacts = [];
40
45
 
41
46
  const json = (value) => JSON.stringify(value);
42
47
 
@@ -54,6 +59,7 @@ function fail(step, items) {
54
59
  // 在仓库内(非发布态)会因无扩展名 import 解析失败。这里只需要 TSX 转换、别名与 less。
55
60
  const { createServer } = await import('vite');
56
61
  const react = (await import('@vitejs/plugin-react')).default;
62
+ const tailwindcss = (await import('@tailwindcss/vite')).default;
57
63
  let vite;
58
64
  const bootstrapStart = performance.now();
59
65
  try {
@@ -62,7 +68,7 @@ try {
62
68
  root: clientDir,
63
69
  appType: 'custom',
64
70
  logLevel: 'error',
65
- plugins: [react()],
71
+ plugins: [tailwindcss(), react()],
66
72
  resolve: {
67
73
  alias: {
68
74
  '@': path.join(clientDir, 'src'),
@@ -102,10 +108,22 @@ async function checkStyles() {
102
108
  steps.push({ name: 'styles', ok: true, ms: Math.round(performance.now() - started), skipped: true });
103
109
  return;
104
110
  }
105
- // 用同一个 Vite 实例过一遍(CSS 由 Vite 的 postcss 管线解析):不再依赖 less。
111
+ // 与 dev/build 同一条管线(surface-css.mjs):不是「brand.css 语法没坏」,
112
+ // 而是「整份表面样式真的生成了」——空 CSS / 缺哨兵一律失败,截图与证据才可信。
106
113
  try {
107
- await vite.transformRequest('/src/styles/brand.css');
108
- steps.push({ name: 'styles', ok: true, ms: Math.round(performance.now() - started) });
114
+ const surface = await buildSurfaceCss(vite, { clientDir, appDir });
115
+ checkUtilityClasses(surface.cssText);
116
+ if (surface.bytes < 20000 || surface.missing.length > 0) {
117
+ fail('styles', [{
118
+ id: 'styles-empty',
119
+ message: `表面 CSS 不可信:${surface.bytes} 字节,缺哨兵 ${surface.missing.join('、') || '无'}`,
120
+ fix: '确认 apps/client/src/styles/tailwind.css 存在且 @source 覆盖 src 与 kit;证据与 dev/build 共用 surface-css.mjs',
121
+ recipe: 'style',
122
+ }]);
123
+ steps.push({ name: 'styles', ok: false, ms: Math.round(performance.now() - started), cssBytes: surface.bytes });
124
+ } else {
125
+ steps.push({ name: 'styles', ok: true, ms: Math.round(performance.now() - started), cssBytes: surface.bytes });
126
+ }
109
127
  } catch (error) {
110
128
  fail('styles', [{
111
129
  id: 'styles-compile-failed',
@@ -116,17 +134,39 @@ async function checkStyles() {
116
134
  }
117
135
  }
118
136
 
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;
137
+ /**
138
+ * 死类:源码里像工具类、CSS 里却没有对应规则。
139
+ * Tailwind 对不认识的类不报错、只是不生成——拼错的类名(如 bg-primary-light)会静默失效。
140
+ * 只检查纯字母数字/连字符的 token(任意值、变体、模板插值都跳过),先告警不阻断。
141
+ */
142
+ function checkUtilityClasses(cssText) {
143
+ const cardsDir = path.join(clientDir, 'src/cards');
144
+ if (!existsSync(cardsDir)) return;
145
+ const seen = new Set();
146
+ for (const entry of readdirSync(cardsDir)) {
147
+ if (!entry.endsWith('.tsx')) continue;
148
+ const source = readFileSync(path.join(cardsDir, entry), 'utf8');
149
+ for (const match of source.matchAll(/className=(?:"([^"]*)"|\{'([^']*)'\})/g)) {
150
+ const value = match[1] ?? match[2] ?? '';
151
+ if (value.includes('${')) continue;
152
+ for (const token of value.split(/\s+/)) {
153
+ if (!token || token.includes(':') || token.includes('[') || token.includes('/') || token.includes('__')) continue;
154
+ if (!looksLikeUtility(token)) continue;
155
+ if (seen.has(token)) continue;
156
+ seen.add(token);
157
+ const pattern = new RegExp('\\.' + token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![\\w-])');
158
+ if (!pattern.test(cssText)) {
159
+ warn('utility-class-missing', `apps/client/src/cards/${entry}: 类名 ${token} 没有生成 CSS(拼写或未登记)`, {
160
+ fix: '对照 docs/agent/style.md 的语义色与档位;任意值改用方括号写法',
161
+ recipe: 'style',
162
+ });
163
+ }
164
+ }
165
+ }
166
+ }
128
167
  }
129
168
 
169
+ // ── 2. primitives ───────────────────────────────────────────────────
130
170
  function checkPrimitives() {
131
171
  const started = performance.now();
132
172
  const cards = registryServer?.cards ?? {};
@@ -244,35 +284,13 @@ function checkPrimitives() {
244
284
  }
245
285
  }
246
286
 
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
287
  steps.push({ name: 'primitives', ok: !errors.some((item) => item.step === 'primitives'), ms: Math.round(performance.now() - started) });
270
288
  }
271
289
 
272
290
  // ── 2b. tailwind 类名禁忌(禁用项)────────────────────────────────────
273
291
  // Tailwind 对不认识的类不报错、只是不生成——所以这几类必须让它们出声。
274
- // 规则与 docs/agent/style.md 一一对应:默认调色板、语义色的透明度修饰符(依赖 color-mix)、
275
- // 档外字号、元素级 --tbox-asset-* 声明(会截断 html[data-theme] 覆写继承)。
292
+ // 规则与 docs/agent/style.md 一一对应:默认调色板、档外字号、类名紧贴插值、
293
+ // 元素级 --tbox-asset-* 声明(会截断 html[data-theme] 覆写继承)。
276
294
  /** 判断一个 token 像不像工具类(去掉变体前缀后看末段):用来把 BEM 钩子排除在外 */
277
295
  function looksLikeUtility(token) {
278
296
  if (token.includes('__')) return false;
@@ -296,12 +314,6 @@ const TAILWIND_BANNED = [
296
314
  message: '用了 Tailwind 默认调色板(不生成 CSS,且产物会带 oklch)',
297
315
  fix: '换成语义色:text-foreground / bg-card / border-border 等(docs/agent/style.md)',
298
316
  },
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
317
  {
306
318
  id: 'font-size-off-scale',
307
319
  pattern: /\btext-\[\d+(?:\.\d+)?px\]/,
@@ -387,17 +399,11 @@ async function checkRender() {
387
399
  }
388
400
  const React = (await import('react')).default;
389
401
  const { renderToStaticMarkup } = await import('react-dom/server');
390
- const { createStore } = await import('zustand/vanilla');
391
- const { useStore } = await import('zustand');
392
402
  const kit = await vite.ssrLoadModule('@tbox.cn/app-agent-ui-kit');
393
403
 
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
404
  const components = registryClient?.cards ?? {};
405
+ // 与运行时 / 预览 / 截图同一条装配(SurfaceHarness),不再手搭 provider。
406
+ const harness = kit.createSurfaceHarness({ cards: components });
401
407
  let rendered = 0;
402
408
  let bytes = 0;
403
409
 
@@ -420,15 +426,26 @@ async function checkRender() {
420
426
  for (const [label, data] of samples) {
421
427
  try {
422
428
  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
- ),
429
+ harness.wrap(React.createElement(Component, { data, cardId: `evidence-${cardType}`, isHistory: false, actionTokens: {} })),
428
430
  );
429
431
  rendered += 1;
430
432
  bytes += html.length;
431
433
  cardDigests.push({ cardType, label, source: 'sample', text: htmlDigest(html) });
434
+ // 历史态是必验状态(只读、动作禁用):只验默认态会漏掉整类分支。
435
+ if (label === 'sampleData') {
436
+ try {
437
+ const historyHtml = renderToStaticMarkup(
438
+ harness.wrap(React.createElement(Component, { data, cardId: `evidence-history-${cardType}`, isHistory: true, actionTokens: {} })),
439
+ );
440
+ 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' });
442
+ } else {
443
+ historyRendered += 1;
444
+ }
445
+ } 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' });
447
+ }
448
+ }
432
449
  if (html.trim() === '') {
433
450
  errors.push({
434
451
  step: 'render',
@@ -456,9 +473,7 @@ async function checkRender() {
456
473
  if (!Component) continue;
457
474
  try {
458
475
  const html = renderToStaticMarkup(
459
- React.createElement(
460
- kit.KitChatProvider,
461
- { store: hook, cards: components, rawCards: components },
476
+ harness.wrap(
462
477
  React.createElement(Component, {
463
478
  data: instance.data,
464
479
  cardId: `evidence-scenario-${instance.cardType}-${instance.step}`,
@@ -564,7 +579,17 @@ function gateVerdict() {
564
579
  const file = ['scenarios/acceptance.jsonc', 'scenarios/acceptance.json'].map((name) => path.join(appDir, name)).find((name) => existsSync(name));
565
580
  const doc = file ? readJsonc(file) : {};
566
581
  const items = doc.items ?? [];
567
- const scenarioItems = items.filter((item) => (item.by ?? 'scenario') === 'scenario');
582
+ const acceptanceRaw = file ? readFileSync(file, 'utf8') : '';
583
+ const acceptanceHash = acceptanceRaw ? createHash('sha256').update(acceptanceRaw).digest('hex').slice(0, 16) : null;
584
+ const acceptanceIds = items.map((item) => String(item.id));
585
+ let prevGate;
586
+ try {
587
+ prevGate = JSON.parse(readFileSync(path.join(appDir, '.tbox/evidence/gate.json'), 'utf8'));
588
+ } catch {
589
+ prevGate = undefined;
590
+ }
591
+ const deferredByLane = items.filter((item) => item.lane === 'browser' || item.lane === 'model');
592
+ const scenarioItems = items.filter((item) => (item.by ?? 'scenario') === 'scenario' && !item.lane);
568
593
  // E1:review 改名为 handoff(旧名保留为别名)。名字本身不再邀请复审。
569
594
  // E2:证据策略声明本任务允许验证到哪一级;handoff 只接受策略判为不可验的维度。
570
595
  const policy = ['static', 'visual', 'flow'].includes(doc.policy) ? doc.policy : 'static';
@@ -574,12 +599,17 @@ function gateVerdict() {
574
599
  recipe: 'verify',
575
600
  });
576
601
  }
577
- const handoffItems = items.filter((item) => item.by === 'handoff' || item.by === 'review');
578
- const covered = new Set();
602
+ const handoffItems = items.filter((item) => (item.by === 'handoff' || item.by === 'review') && !item.lane);
603
+ const originByFile = new Map();
579
604
  for (const result of scenarioResults) {
580
- if (!result.ok) continue;
581
- for (const id of result.covers ?? []) covered.add(id);
605
+ let origin = 'spec';
606
+ try {
607
+ const parsed = JSON.parse(readFileSync(result.file, "utf8"));
608
+ if (parsed && parsed.origin) origin = String(parsed.origin);
609
+ } catch { origin = 'spec'; }
610
+ originByFile.set(result.file, origin);
582
611
  }
612
+ const { covered, declared: declaredCovered } = coverageSets(scenarioResults, originByFile);
583
613
  // 策略允许场景验证的项不能借 handoff 绕过:没有 reason 的 handoff 计入 incomplete。
584
614
  // 旧名 review 不要求 reason(历史应用平滑);新名 handoff 必须写清为什么当前策略验不了。
585
615
  const handoffWithoutReason = handoffItems.filter((item) => item.by === 'handoff' && !item.reason);
@@ -663,13 +693,59 @@ function gateVerdict() {
663
693
  : '交付条件已满足:总结并结束。不要继续复审或打磨。';
664
694
  }
665
695
 
666
- const gateFile = path.join(appDir, '.tbox/evidence/gate.json');
667
- let previous;
668
- try {
669
- previous = JSON.parse(readFileSync(gateFile, 'utf8'));
670
- } catch {
671
- previous = undefined;
696
+ // T1 漂移:验收文件变了就记下来,不阻断。
697
+ const acceptance = acceptanceDrift(prevGate, acceptanceHash, acceptanceIds);
698
+ const drift = [...acceptance.drift];
699
+ if (acceptance.drift.length > 0) {
700
+ warn('acceptance-drift', acceptance.drift[0].detail, { fix: '确认改动是有意的;交付包会列出漂移', recipe: 'verify' });
701
+ }
702
+ const scenarioHashes = {};
703
+ const failedScenarios = [];
704
+ for (const result of scenarioResults) {
705
+ try {
706
+ const relative = scenarioKey(appDir, result.file);
707
+ scenarioHashes[relative] = createHash("sha256").update(readFileSync(result.file, "utf8")).digest("hex").slice(0, 16);
708
+ } catch { /* 读失败不影响裁决 */ }
709
+ if (!result.ok) failedScenarios.push(path.relative(appDir, result.file));
672
710
  }
711
+ if (prevGate && prevGate.scenarioHashes) {
712
+ for (const [scenarioFile, hash] of Object.entries(scenarioHashes)) {
713
+ const prevHash = prevGate.scenarioHashes[scenarioFile];
714
+ if (prevHash && prevHash !== hash && Array.isArray(prevGate.failedScenarios) && prevGate.failedScenarios.includes(scenarioFile)) {
715
+ const detail = '失败后改了场景期望:' + scenarioFile;
716
+ drift.push({ kind: 'expect', detail });
717
+ warn('expect-drift', detail, { fix: '在交付说明里写清为什么改期望', recipe: 'verify' });
718
+ }
719
+ }
720
+ }
721
+
722
+ // 软闩:交付后再改内容 -> reopened(只降级,不阻断)。
723
+ let contentHash = null;
724
+ try { contentHash = hashSourceTree(appDir).hash; } catch { contentHash = null; }
725
+ if (shouldReopen(prevGate, verdict, contentHash)) {
726
+ verdict = 'reopened';
727
+ next = '交付后内容有改动:重跑一次 check:fast 确认,再交付(不做硬停)。';
728
+ }
729
+
730
+ const delivery = {
731
+ trace: items.map((item) => ({
732
+ id: item.id,
733
+ text: item.text ?? '',
734
+ covered: covered.has(item.id),
735
+ declared: declaredCovered.has(item.id),
736
+ ...(item.lane ? { lane: item.lane } : {}),
737
+ })),
738
+ facts: cardFacts,
739
+ drift,
740
+ deferred: [
741
+ ...deferredByLane.map((item) => ({ id: item.id, lane: item.lane, reason: '验收项声明为 ' + item.lane + ' 车道' })),
742
+ ...experienceItems.filter((item) => item.status === "deferred").map((item) => ({ id: item.id, lane: item.lane, reason: item.detail })),
743
+ ],
744
+ };
745
+ if (verdict === 'deliverable' && delivery.deferred.length > 0) {
746
+ next = '把 deferred 的 ' + delivery.deferred.length + ' 项如实写进交付说明,然后结束。';
747
+ }
748
+ const gateFile = path.join(appDir, '.tbox/evidence/gate.json');
673
749
  let changedFiles = 0;
674
750
  try {
675
751
  changedFiles = execFileSync('git', ['status', '--porcelain'], { cwd: appDir, encoding: 'utf8' })
@@ -678,11 +754,22 @@ function gateVerdict() {
678
754
  } catch {
679
755
  changedFiles = 0;
680
756
  }
681
- const runs = previous?.verdict === 'deliverable' ? (previous.runs ?? 0) + 1 : 0;
682
- const sinceDeliverable = previous?.verdict === 'deliverable' ? { runs, changedFiles } : undefined;
757
+ const runs = prevGate?.verdict === 'deliverable' ? (prevGate.runs ?? 0) + 1 : 0;
758
+ const sinceDeliverable = prevGate?.verdict === 'deliverable' ? { runs, changedFiles } : undefined;
683
759
  try {
684
760
  mkdirSync(path.dirname(gateFile), { recursive: true });
685
- writeFileSync(gateFile, JSON.stringify({ verdict, at: Date.now(), changedFiles, runs }));
761
+ writeFileSync(gateFile, JSON.stringify({
762
+ verdict,
763
+ at: Date.now(),
764
+ changedFiles,
765
+ runs,
766
+ acceptanceHash,
767
+ acceptanceIds,
768
+ scenarioHashes,
769
+ failedScenarios,
770
+ contentHash,
771
+ deliveredAt: verdict === 'deliverable' ? (prevGate && prevGate.verdict === 'deliverable' ? (prevGate.deliveredAt ?? Date.now()) : Date.now()) : (prevGate ? prevGate.deliveredAt : undefined),
772
+ }));
686
773
  } catch {
687
774
  // 只读环境不影响裁决
688
775
  }
@@ -697,6 +784,7 @@ function gateVerdict() {
697
784
  acceptance: {
698
785
  items: items.length,
699
786
  covered: covered.size,
787
+ declared: declaredCovered.size,
700
788
  // 旧名保留一版(读取方可能仍看 review);新代码用 handoff。
701
789
  review: handoffItems.length,
702
790
  handoff: handoffItems.length,
@@ -704,6 +792,7 @@ function gateVerdict() {
704
792
  ...(file ? { file: path.relative(appDir, file) } : {}),
705
793
  },
706
794
  ...(sinceDeliverable ? { sinceDeliverable } : {}),
795
+ delivery,
707
796
  };
708
797
  }
709
798
 
@@ -774,6 +863,164 @@ function checkCoverage() {
774
863
  steps.push({ name: 'coverage', ok: true, ms: Math.round(performance.now() - started), instances: scenarioInstances.length });
775
864
  }
776
865
 
866
+ // 对比度:纯色令牌静态算 WCAG;var()/color-mix 派生的标 deferred(浏览器车道暂缓)。
867
+ function parseCssTokens(files) {
868
+ const values = new Map();
869
+ for (const file of files) {
870
+ if (!file || !existsSync(file)) continue;
871
+ const css = readFileSync(file, 'utf8').replace(/\/\*[\s\S]*?\*\//g, '');
872
+ for (const match of css.matchAll(/(--tbox-[\w-]+)\s*:\s*([^;]+);/g)) {
873
+ values.set(match[1], match[2].trim());
874
+ }
875
+ }
876
+ return values;
877
+ }
878
+
879
+ function checkContrast() {
880
+ const kitDir = path.join(appDir, 'packages/agent-ui-kit');
881
+ const contractPath = path.join(kitDir, 'src/theme/contract.json');
882
+ if (!existsSync(contractPath)) return { status: 'deferred', detail: '主题契约不在预期位置' };
883
+ const contract = JSON.parse(readFileSync(contractPath, 'utf8'));
884
+ const pairs = contract.pairs ?? [];
885
+ if (pairs.length === 0) return { status: 'deferred', detail: '没有登记对比度对' };
886
+ const require = createRequire(path.join(clientDir, 'package.json'));
887
+ let themePackage = '@tbox.cn/app-theme-tbox';
888
+ try {
889
+ // 以装配真源的实际 import 为准(theme use 会改写这一行);找不到再退回依赖清单。
890
+ const appConfig = readFileSync(path.join(clientDir, 'src/app.config.ts'), 'utf8');
891
+ const imported = /@tbox\.cn\/app-theme-([a-z0-9-]+)\/index\.css/.exec(appConfig);
892
+ if (imported) {
893
+ themePackage = '@tbox.cn/app-theme-' + imported[1];
894
+ } else {
895
+ const clientPkg = JSON.parse(readFileSync(path.join(clientDir, 'package.json'), 'utf8'));
896
+ const installed = Object.keys({ ...(clientPkg.dependencies ?? {}), ...(clientPkg.devDependencies ?? {}) }).filter((name) => name.startsWith('@tbox.cn/app-theme-')).sort();
897
+ if (installed[0]) themePackage = installed[0];
898
+ }
899
+ } catch { /* 用出厂主题 */ }
900
+ let themeCss;
901
+ try { themeCss = require.resolve(themePackage + '/index.css'); } catch { themeCss = undefined; }
902
+ const tokens = parseCssTokens([
903
+ path.join(kitDir, 'src/theme/tokens.css'),
904
+ themeCss,
905
+ path.join(clientDir, 'src/styles/brand.css'),
906
+ ]);
907
+ const resolved = new Map();
908
+ for (const [key, raw] of tokens) {
909
+ const color = parseColor(raw);
910
+ if (color) resolved.set(key, color);
911
+ }
912
+ const failures = [];
913
+ const deferred = [];
914
+ for (const pair of pairs) {
915
+ const fg = resolved.get(pair.fg);
916
+ const bg = resolved.get(pair.bg);
917
+ if (!fg || !bg) { deferred.push(pair.fg + ' on ' + pair.bg); continue; }
918
+ const ratio = contrastRatio(fg, bg);
919
+ if (ratio < pair.min) failures.push(pair.fg + ' on ' + pair.bg + ' = ' + ratio.toFixed(2) + ' < ' + pair.min);
920
+ }
921
+ if (failures.length > 0) return { status: 'fail', detail: failures.join(';') };
922
+ if (deferred.length > 0) return { status: 'deferred', detail: '无法静态解析:' + deferred.join(';') };
923
+ return { status: 'pass', detail: pairs.length + ' 对全部达到阈值' };
924
+ }
925
+
926
+ // 视图卡的静态密度:版式归平台后高度是视图树的函数,不用开浏览器。
927
+ async function checkCardDensity() {
928
+ if (!registryServer) return { available: false, worst: 0, violations: [], reason: '没有服务端 registry' };
929
+ let contracts;
930
+ try { contracts = await vite.ssrLoadModule('@tbox.cn/app-contracts'); } catch { return { available: false, worst: 0, violations: [], reason: '契约模块加载失败' }; }
931
+ const estimate = contracts.estimateCardHeight;
932
+ if (typeof estimate !== 'function') return { available: false, worst: 0, violations: [], reason: '契约未导出 estimateCardHeight' };
933
+ let worst = 0;
934
+ const violations = [];
935
+ for (const [cardType, meta] of Object.entries(registryServer.cards ?? {})) {
936
+ if (!meta || !meta.view) continue;
937
+ const samples = [meta.sampleData, ...(Array.isArray(meta.samples) ? meta.samples.map((sample) => sample && sample.data) : [])];
938
+ for (const data of samples) {
939
+ if (!data) continue;
940
+ try {
941
+ const height = estimate(data);
942
+ if (height > worst) worst = height;
943
+ if (height > 633) violations.push(cardType + ' ' + height + 'px');
944
+ } catch { /* 形状不对由 render 报 */ }
945
+ }
946
+ }
947
+ return { available: true, worst, violations };
948
+ }
949
+
950
+ // ── 4.8 体验不变量(登记在 checks.json 的 experience 族)──────────────
951
+ // 只跑不需要浏览器的车道(静态 / 进程内);浏览器与模型车道写 deferred,由平台补验。
952
+ async function checkExperience(cssBytes) {
953
+ const started = performance.now();
954
+ const items = [];
955
+ const push = (id, lane, status, detail) => items.push({ id, lane, status, detail });
956
+
957
+ 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));
963
+ }
964
+
965
+ 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
+ }
972
+
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
+ }
983
+ }
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 + ' 字节');
991
+
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);
994
+
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('、') : ''));
1008
+ }
1009
+
1010
+ push('shell.hit-target', 'browser', 'deferred', '浏览器车道未接入(平台车道暂缓)');
1011
+ push('shell.quick-visible', 'browser', 'deferred', '浏览器车道未接入(平台车道暂缓)');
1012
+ push('shell.blank', 'browser', 'deferred', '浏览器车道未接入(平台车道暂缓)');
1013
+ push('flow.persist', 'in-process', 'deferred', '需要重启探针(未接入)');
1014
+
1015
+ steps.push({ name: 'experience', ok: !items.some((item) => item.status === 'fail'), ms: Math.round(performance.now() - started), items });
1016
+ experienceItems = items;
1017
+ 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' });
1020
+ }
1021
+ }
1022
+ }
1023
+
777
1024
  // ── 执行 ────────────────────────────────────────────────────────────
778
1025
  await checkStyles();
779
1026
  if (registryServer) checkPrimitives();
@@ -782,6 +1029,8 @@ await checkScenarios();
782
1029
  if (registryServer) checkCoverage();
783
1030
  await checkRender();
784
1031
  checkRenderSignals();
1032
+ const stylesStep = steps.find((step) => step.name === 'styles');
1033
+ await checkExperience(stylesStep?.cssBytes ?? 0);
785
1034
  const verdict = gateVerdict();
786
1035
  try {
787
1036
  const dir = path.join(appDir, '.tbox/evidence');
@@ -807,6 +1056,7 @@ const summary = {
807
1056
  notRun,
808
1057
  evidence: { cards: cardDigests.length, scenarios: scenarioResults.length, instances: scenarioInstances.length },
809
1058
  ...verdict,
1059
+ experience: experienceItems,
810
1060
  };
811
1061
  if (errors.length > 0) summary.errors = errors;
812
1062