@tbox.cn/app-template-agent 0.10.37 → 1.0.0-alpha.10

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 (455) hide show
  1. package/._.gitignore +0 -0
  2. package/._.nvmrc +0 -0
  3. package/._AGENTS.md +0 -0
  4. package/._ENV.md +0 -0
  5. package/._LEGAL.md +0 -0
  6. package/._LICENSE +0 -0
  7. package/._README.md +0 -0
  8. package/._eslint.config.mjs +0 -0
  9. package/._package.json +0 -0
  10. package/._pnpm-lock.template.yaml +0 -0
  11. package/._pnpm-workspace.template.yaml +0 -0
  12. package/._tsconfig.base.json +0 -0
  13. package/.gitignore +14 -2
  14. package/.tbox/._app.json +0 -0
  15. package/.tbox/._default-modules.json +0 -0
  16. package/.tbox/._miniapp-containers.json +0 -0
  17. package/.tbox/app.json +3 -19
  18. package/.tbox/default-modules.json +4 -1
  19. package/.tbox/factory/._chat.json +0 -0
  20. package/.tbox/factory/chat.json +9 -0
  21. package/.tbox/miniapp-containers.json +1 -1
  22. package/AGENTS.md +96 -148
  23. package/ENV.md +4 -4
  24. package/README.md +31 -27
  25. package/apps/._AGENTS.md +0 -0
  26. package/apps/AGENTS.md +9 -0
  27. package/apps/client/._index.html +0 -0
  28. package/apps/client/._package.json +0 -0
  29. package/apps/client/._tsconfig.json +0 -0
  30. package/apps/client/._vite.config.ts +0 -0
  31. package/apps/client/index.html +1 -20
  32. package/apps/client/package.json +7 -5
  33. package/apps/client/scripts/._acceptance-changes.test.mjs +0 -0
  34. package/apps/client/scripts/._check-evidence.mjs +0 -0
  35. package/apps/client/scripts/._color-scan.mjs +0 -0
  36. package/apps/client/scripts/._color-scan.test.mjs +0 -0
  37. package/apps/client/scripts/._evidence-gate.mjs +0 -0
  38. package/apps/client/scripts/._evidence-gate.test.mjs +0 -0
  39. package/apps/client/scripts/._experience-checks.mjs +0 -0
  40. package/apps/client/scripts/._geometry-kernel.test.mjs +0 -0
  41. package/apps/client/scripts/._in-process-checks.mjs +0 -0
  42. package/apps/client/scripts/._probe-checks.mjs +0 -0
  43. package/apps/client/scripts/._render-card.mjs +0 -0
  44. package/apps/client/scripts/._sample-entries.test.mjs +0 -0
  45. package/apps/client/scripts/._storyboard.test.mjs +0 -0
  46. package/apps/client/scripts/._surface-css.mjs +0 -0
  47. package/apps/client/scripts/._theme-kernel.mjs +0 -0
  48. package/apps/client/scripts/._theme-kernel.test.mjs +0 -0
  49. package/apps/client/scripts/acceptance-changes.test.mjs +97 -0
  50. package/apps/client/scripts/check-evidence.mjs +1402 -0
  51. package/apps/client/scripts/color-scan.mjs +66 -0
  52. package/apps/client/scripts/color-scan.test.mjs +25 -0
  53. package/apps/client/scripts/evidence-gate.mjs +337 -0
  54. package/apps/client/scripts/evidence-gate.test.mjs +135 -0
  55. package/apps/client/scripts/experience-checks.mjs +163 -0
  56. package/apps/client/scripts/geometry-kernel.test.mjs +92 -0
  57. package/apps/client/scripts/in-process-checks.mjs +51 -0
  58. package/apps/client/scripts/lib/._card-registry.mjs +0 -0
  59. package/apps/client/scripts/lib/._card-registry.test.mjs +0 -0
  60. package/apps/client/scripts/lib/._evidence-inputs.mjs +0 -0
  61. package/apps/client/scripts/lib/._evidence-inputs.test.mjs +0 -0
  62. package/apps/client/scripts/lib/._static-render.mjs +0 -0
  63. package/apps/client/scripts/lib/._static-render.test.mjs +0 -0
  64. package/apps/client/scripts/lib/card-registry.mjs +81 -0
  65. package/apps/client/scripts/lib/card-registry.test.mjs +59 -0
  66. package/apps/client/scripts/lib/evidence-inputs.mjs +91 -0
  67. package/apps/client/scripts/lib/evidence-inputs.test.mjs +27 -0
  68. package/apps/client/scripts/lib/static-render.mjs +35 -0
  69. package/apps/client/scripts/lib/static-render.test.mjs +21 -0
  70. package/apps/client/scripts/probe-checks.mjs +85 -0
  71. package/apps/client/scripts/render-card.mjs +710 -0
  72. package/apps/client/scripts/sample-entries.test.mjs +31 -0
  73. package/apps/client/scripts/storyboard.test.mjs +149 -0
  74. package/apps/client/scripts/surface-css.mjs +55 -0
  75. package/apps/client/scripts/theme-kernel.mjs +236 -0
  76. package/apps/client/scripts/theme-kernel.test.mjs +136 -0
  77. package/apps/client/src/._app.config.ts +0 -0
  78. package/apps/client/src/._vite-env.d.ts +0 -0
  79. package/apps/client/src/app.config.ts +43 -0
  80. package/apps/client/src/cards/._AGENTS.md +0 -0
  81. package/apps/client/src/cards/._registry.ts +0 -0
  82. package/apps/client/src/cards/AGENTS.md +11 -0
  83. package/apps/client/src/cards/registry.ts +6 -19
  84. package/apps/client/src/pages/._page.tsx +0 -0
  85. package/apps/client/src/pages/index/._index.tsx +0 -0
  86. package/apps/client/src/pages/index/index.tsx +1 -1
  87. package/apps/client/src/pages/page.tsx +11 -0
  88. package/apps/client/src/store/._chat.ts +0 -0
  89. package/apps/client/src/store/chat.ts +7 -3
  90. package/apps/client/src/styles/._brand.css +0 -0
  91. package/apps/client/src/styles/._tailwind.css +0 -0
  92. package/apps/client/src/styles/brand.css +50 -0
  93. package/apps/client/src/styles/tailwind.css +326 -0
  94. package/apps/client/src/test/._setup.ts +0 -0
  95. package/apps/client/src/vite-env.d.ts +0 -2
  96. package/apps/client/vite.config.ts +7 -53
  97. package/apps/server/._package.json +0 -0
  98. package/apps/server/._tsconfig.json +0 -0
  99. package/apps/server/._tsup.config.ts +0 -0
  100. package/apps/server/._vitest.config.ts +0 -0
  101. package/apps/server/package.json +1 -1
  102. package/apps/server/scripts/._probe.mjs +0 -0
  103. package/apps/server/scripts/._scenario-lib.mjs +0 -0
  104. package/apps/server/scripts/._scenario.mjs +0 -0
  105. package/apps/server/scripts/probe.mjs +387 -0
  106. package/apps/server/scripts/scenario-lib.mjs +295 -0
  107. package/apps/server/scripts/scenario.mjs +67 -0
  108. package/apps/server/src/._app.ts +0 -0
  109. package/apps/server/src/._dev.ts +0 -0
  110. package/apps/server/src/._index.ts +0 -0
  111. package/apps/server/src/._intent-routes.ts +0 -0
  112. package/apps/server/src/._pre-tools.ts +0 -0
  113. package/apps/server/src/app.ts +17 -17
  114. package/apps/server/src/cards/._AGENTS.md +0 -0
  115. package/apps/server/src/cards/AGENTS.md +19 -0
  116. package/apps/server/src/cli/._collect-registry.ts +0 -0
  117. package/apps/server/src/cli/._plugin-doctor.ts +0 -0
  118. package/apps/server/src/cli/._plugin-inspect.ts +0 -0
  119. package/apps/server/src/cli/collect-registry.ts +7 -11
  120. package/apps/server/src/config/._integration.ts +0 -0
  121. package/apps/server/src/dev.ts +38 -64
  122. package/apps/server/src/index.ts +27 -45
  123. package/apps/server/src/pre-tools.ts +7 -16
  124. package/apps/server/src/tools/._AGENTS.md +0 -0
  125. package/apps/server/src/tools/AGENTS.md +23 -0
  126. package/apps/server/tests/._agent-prompt.test.ts +0 -0
  127. package/apps/server/tests/._cards-registry.test.ts +0 -0
  128. package/apps/server/tests/._deployment-loader.test.ts +0 -0
  129. package/apps/server/tests/._intent-dispatcher.test.ts +0 -0
  130. package/apps/server/tests/._tool-runtime.test.ts +0 -0
  131. package/apps/server/tests/cards-registry.test.ts +1 -1
  132. package/apps/server/tests/helpers/._register.ts +0 -0
  133. package/apps/server/tests/helpers/register.ts +10 -0
  134. package/apps/server/tests/tool-runtime.test.ts +1 -28
  135. package/apps/server/tsconfig.json +1 -1
  136. package/apps/server/tsup.config.ts +6 -3
  137. package/config/._AGENTS.md +0 -0
  138. package/config/._README.md +0 -0
  139. package/config/._chat.json +0 -0
  140. package/config/._integrations.json +0 -0
  141. package/config/._llm_provider.json +0 -0
  142. package/config/._plugins.json +0 -0
  143. package/config/AGENTS.md +14 -0
  144. package/config/README.md +4 -4
  145. package/config/chat.json +25 -7
  146. package/config/integrations.json +1 -1
  147. package/docs/agent/._agent-prompt.md +0 -0
  148. package/docs/agent/._card-action.md +0 -0
  149. package/docs/agent/._card.md +0 -0
  150. package/docs/agent/._conversation.md +0 -0
  151. package/docs/agent/._kit.md +0 -0
  152. package/docs/agent/._shell.md +0 -0
  153. package/docs/agent/._state.md +0 -0
  154. package/docs/agent/._style.md +0 -0
  155. package/docs/agent/._tool-emits-card.md +0 -0
  156. package/docs/agent/._tool.md +0 -0
  157. package/docs/agent/._verify.md +0 -0
  158. package/docs/agent/agent-prompt.md +38 -0
  159. package/docs/agent/card-action.md +101 -0
  160. package/docs/agent/card.md +159 -0
  161. package/docs/agent/conversation.md +52 -0
  162. package/docs/agent/kit.md +80 -0
  163. package/docs/agent/shell.md +77 -0
  164. package/docs/agent/state.md +85 -0
  165. package/docs/agent/style.md +107 -0
  166. package/docs/agent/tool-emits-card.md +62 -0
  167. package/docs/agent/tool.md +71 -0
  168. package/docs/agent/verify.md +188 -0
  169. package/eslint.config.mjs +18 -0
  170. package/modules/provider-custom/._AGENTS.md +0 -0
  171. package/modules/provider-custom/._INTEGRATION.md +0 -0
  172. package/modules/provider-custom/._LICENSE +0 -0
  173. package/modules/provider-custom/._README.md +0 -0
  174. package/modules/provider-custom/._package.json +0 -0
  175. package/modules/provider-custom/._tbox.module.json +0 -0
  176. package/modules/provider-custom/._tsconfig.json +0 -0
  177. package/modules/provider-custom/._tsup.config.ts +0 -0
  178. package/{packages → modules}/provider-custom/AGENTS.md +6 -6
  179. package/modules/provider-custom/INTEGRATION.md +10 -0
  180. package/{packages → modules}/provider-custom/package.json +1 -0
  181. package/modules/provider-custom/src/._index.ts +0 -0
  182. package/modules/provider-custom/src/server/._example-adapter.ts +0 -0
  183. package/modules/provider-custom/src/server/._index.ts +0 -0
  184. package/{packages → modules}/provider-custom/src/server/example-adapter.ts +2 -2
  185. package/{packages → modules}/provider-custom/src/server/index.ts +1 -1
  186. package/modules/provider-custom/tests/._provider-custom.test.ts +0 -0
  187. package/package.json +38 -7
  188. package/packages/agent-ui-kit/._AGENTS.md +0 -0
  189. package/packages/agent-ui-kit/._LICENSE +0 -0
  190. package/packages/agent-ui-kit/._README.md +0 -0
  191. package/packages/agent-ui-kit/._catalog.json +0 -0
  192. package/packages/agent-ui-kit/._package.json +0 -0
  193. package/packages/agent-ui-kit/._tsconfig.json +0 -0
  194. package/packages/agent-ui-kit/._vitest.config.ts +0 -0
  195. package/packages/agent-ui-kit/AGENTS.md +8 -0
  196. package/packages/agent-ui-kit/README.md +59 -6
  197. package/packages/agent-ui-kit/assets/._keyboard-circle.svg +0 -0
  198. package/packages/agent-ui-kit/assets/._more-circle.svg +0 -0
  199. package/packages/agent-ui-kit/assets/._new-chat.svg +0 -0
  200. package/packages/agent-ui-kit/assets/._quick-command-star.svg +0 -0
  201. package/packages/agent-ui-kit/assets/._send-gradient.svg +0 -0
  202. package/packages/agent-ui-kit/assets/._stop@2x.png +0 -0
  203. package/packages/agent-ui-kit/assets/._voice-circle.svg +0 -0
  204. package/packages/agent-ui-kit/catalog.json +855 -0
  205. package/packages/agent-ui-kit/package.json +24 -9
  206. package/packages/agent-ui-kit/src/._ChatPage.tsx +0 -0
  207. package/packages/agent-ui-kit/src/._chat-config.test.ts +0 -0
  208. package/packages/agent-ui-kit/src/._chat-config.ts +0 -0
  209. package/packages/agent-ui-kit/src/._icons.ts +0 -0
  210. package/packages/agent-ui-kit/src/._index.ts +0 -0
  211. package/packages/agent-ui-kit/src/._preview-provider.tsx +0 -0
  212. package/packages/agent-ui-kit/src/._shell.contract.json +0 -0
  213. package/packages/agent-ui-kit/src/._shell.test.ts +0 -0
  214. package/packages/agent-ui-kit/src/._shell.ts +0 -0
  215. package/packages/agent-ui-kit/src/._store-context.tsx +0 -0
  216. package/packages/agent-ui-kit/src/._surface.test.tsx +0 -0
  217. package/packages/agent-ui-kit/src/._surface.tsx +0 -0
  218. package/packages/agent-ui-kit/src/._types.ts +0 -0
  219. package/packages/agent-ui-kit/src/._vite-env.d.ts +0 -0
  220. package/packages/agent-ui-kit/src/ChatPage.tsx +115 -20
  221. package/packages/agent-ui-kit/src/card/._action-list-pending.test.tsx +0 -0
  222. package/packages/agent-ui-kit/src/card/._define-card.test.ts +0 -0
  223. package/packages/agent-ui-kit/src/card/._define-card.ts +0 -0
  224. package/packages/agent-ui-kit/src/card/._primitives.test.tsx +0 -0
  225. package/packages/agent-ui-kit/src/card/._primitives.tsx +0 -0
  226. package/packages/agent-ui-kit/src/card/._use-card-actions.ts +0 -0
  227. package/packages/agent-ui-kit/src/card/._view-card-inline.test.tsx +0 -0
  228. package/packages/agent-ui-kit/src/card/._view-card.test.tsx +0 -0
  229. package/packages/agent-ui-kit/src/card/._view-card.tsx +0 -0
  230. package/packages/agent-ui-kit/src/card/action-list-pending.test.tsx +91 -0
  231. package/packages/agent-ui-kit/src/card/define-card.test.ts +25 -0
  232. package/packages/agent-ui-kit/src/card/define-card.ts +47 -0
  233. package/packages/agent-ui-kit/src/card/primitives.test.tsx +157 -0
  234. package/packages/agent-ui-kit/src/card/primitives.tsx +717 -0
  235. package/packages/agent-ui-kit/src/card/use-card-actions.ts +86 -0
  236. package/packages/agent-ui-kit/src/card/view-card-inline.test.tsx +42 -0
  237. package/packages/agent-ui-kit/src/card/view-card.test.tsx +79 -0
  238. package/packages/agent-ui-kit/src/card/view-card.tsx +250 -0
  239. package/packages/agent-ui-kit/src/chat-config.test.ts +35 -71
  240. package/packages/agent-ui-kit/src/chat-config.ts +29 -7
  241. package/packages/agent-ui-kit/src/components/._CardRenderer.tsx +0 -0
  242. package/packages/agent-ui-kit/src/components/ActionBar/._DebugButton.test.tsx +0 -0
  243. package/packages/agent-ui-kit/src/components/ActionBar/._DebugButton.tsx +0 -0
  244. package/packages/agent-ui-kit/src/components/ActionBar/._index.test.tsx +0 -0
  245. package/packages/agent-ui-kit/src/components/ActionBar/._index.tsx +0 -0
  246. package/packages/agent-ui-kit/src/components/ActionBar/DebugButton.test.tsx +3 -0
  247. package/packages/agent-ui-kit/src/components/ActionBar/DebugButton.tsx +5 -10
  248. package/packages/agent-ui-kit/src/components/ActionBar/index.tsx +13 -14
  249. package/packages/agent-ui-kit/src/components/BottomSheet/._index.test.tsx +0 -0
  250. package/packages/agent-ui-kit/src/components/BottomSheet/._index.tsx +0 -0
  251. package/packages/agent-ui-kit/src/components/BottomSheet/index.test.tsx +97 -0
  252. package/packages/agent-ui-kit/src/components/BottomSheet/index.tsx +49 -0
  253. package/packages/agent-ui-kit/src/components/ChatHeader/._index.test.tsx +0 -0
  254. package/packages/agent-ui-kit/src/components/ChatHeader/._index.tsx +0 -0
  255. package/packages/agent-ui-kit/src/components/ChatHeader/index.tsx +19 -17
  256. package/packages/agent-ui-kit/src/components/ChatInput/._index.test.tsx +0 -0
  257. package/packages/agent-ui-kit/src/components/ChatInput/._index.tsx +0 -0
  258. package/packages/agent-ui-kit/src/components/ChatInput/index.test.tsx +2 -2
  259. package/packages/agent-ui-kit/src/components/ChatInput/index.tsx +44 -33
  260. package/packages/agent-ui-kit/src/components/ChatInput/voice/._VoicePressField.tsx +0 -0
  261. package/packages/agent-ui-kit/src/components/ChatInput/voice/._VoiceRecordingOverlay.tsx +0 -0
  262. package/packages/agent-ui-kit/src/components/ChatInput/voice/._machine.ts +0 -0
  263. package/packages/agent-ui-kit/src/components/ChatInput/voice/._useVoicePress.ts +0 -0
  264. package/packages/agent-ui-kit/src/components/ChatInput/voice/VoicePressField.tsx +12 -3
  265. package/packages/agent-ui-kit/src/components/ChatInput/voice/VoiceRecordingOverlay.tsx +9 -9
  266. package/packages/agent-ui-kit/src/components/ChatInput/voice/useVoicePress.ts +1 -1
  267. package/packages/agent-ui-kit/src/components/HistoryEntry/._index.tsx +0 -0
  268. package/packages/agent-ui-kit/src/components/HistoryEntry/index.tsx +4 -4
  269. package/packages/agent-ui-kit/src/components/MediaList/._index.tsx +0 -0
  270. package/packages/agent-ui-kit/src/components/MediaList/index.tsx +42 -28
  271. package/packages/agent-ui-kit/src/components/MessageBubble/._index.test.tsx +0 -0
  272. package/packages/agent-ui-kit/src/components/MessageBubble/._index.tsx +0 -0
  273. package/packages/agent-ui-kit/src/components/MessageBubble/index.tsx +59 -28
  274. package/packages/agent-ui-kit/src/components/PullDownIndicator/._index.tsx +0 -0
  275. package/packages/agent-ui-kit/src/components/PullDownIndicator/index.tsx +3 -4
  276. package/packages/agent-ui-kit/src/components/QuickCommands/._index.test.tsx +0 -0
  277. package/packages/agent-ui-kit/src/components/QuickCommands/._index.tsx +0 -0
  278. package/packages/agent-ui-kit/src/components/QuickCommands/index.test.tsx +3 -1
  279. package/packages/agent-ui-kit/src/components/QuickCommands/index.tsx +33 -10
  280. package/packages/agent-ui-kit/src/components/ReasoningBlock/._index.tsx +0 -0
  281. package/packages/agent-ui-kit/src/components/ReasoningBlock/index.tsx +14 -9
  282. package/packages/agent-ui-kit/src/components/ScrollToBottomButton/._index.tsx +0 -0
  283. package/packages/agent-ui-kit/src/components/ScrollToBottomButton/index.tsx +7 -5
  284. package/packages/agent-ui-kit/src/components/ToolCallBlock/._detail.test.ts +0 -0
  285. package/packages/agent-ui-kit/src/components/ToolCallBlock/._detail.ts +0 -0
  286. package/packages/agent-ui-kit/src/components/ToolCallBlock/._index.test.tsx +0 -0
  287. package/packages/agent-ui-kit/src/components/ToolCallBlock/._index.tsx +0 -0
  288. package/packages/agent-ui-kit/src/components/ToolCallBlock/._titles.ts +0 -0
  289. package/packages/agent-ui-kit/src/components/ToolCallBlock/index.tsx +58 -38
  290. package/packages/agent-ui-kit/src/hooks/._use-drag-gesture.test.ts +0 -0
  291. package/packages/agent-ui-kit/src/hooks/._use-drag-gesture.ts +0 -0
  292. package/packages/agent-ui-kit/src/hooks/._use-pull-down-history.ts +0 -0
  293. package/packages/agent-ui-kit/src/hooks/._use-pull-down-wheel-native.test.ts +0 -0
  294. package/packages/agent-ui-kit/src/hooks/._useMediaUpload.ts +0 -0
  295. package/packages/agent-ui-kit/src/hooks/._useTTSAutoPlay.ts +0 -0
  296. package/packages/agent-ui-kit/src/icons.ts +39 -0
  297. package/packages/agent-ui-kit/src/index.ts +76 -2
  298. package/packages/agent-ui-kit/src/overlay/._Overlay.tsx +0 -0
  299. package/packages/agent-ui-kit/src/overlay/._focus.ts +0 -0
  300. package/packages/agent-ui-kit/src/overlay/._index.ts +0 -0
  301. package/packages/agent-ui-kit/src/overlay/._inert.ts +0 -0
  302. package/packages/agent-ui-kit/src/overlay/._layers.ts +0 -0
  303. package/packages/agent-ui-kit/src/overlay/._overlay.ssr.test.tsx +0 -0
  304. package/packages/agent-ui-kit/src/overlay/._overlay.test.tsx +0 -0
  305. package/packages/agent-ui-kit/src/overlay/._presence.ts +0 -0
  306. package/packages/agent-ui-kit/src/overlay/._scroll-lock.ts +0 -0
  307. package/packages/agent-ui-kit/src/overlay/._stack.ts +0 -0
  308. package/packages/agent-ui-kit/src/overlay/._use-overlay.ts +0 -0
  309. package/packages/agent-ui-kit/src/overlay/Overlay.tsx +154 -0
  310. package/packages/agent-ui-kit/src/overlay/focus.ts +53 -0
  311. package/packages/agent-ui-kit/src/overlay/index.ts +16 -0
  312. package/packages/agent-ui-kit/src/overlay/inert.ts +27 -0
  313. package/packages/agent-ui-kit/src/overlay/layers.ts +21 -0
  314. package/packages/agent-ui-kit/src/overlay/overlay.ssr.test.tsx +27 -0
  315. package/packages/agent-ui-kit/src/overlay/overlay.test.tsx +209 -0
  316. package/packages/agent-ui-kit/src/overlay/presence.ts +86 -0
  317. package/packages/agent-ui-kit/src/overlay/scroll-lock.ts +62 -0
  318. package/packages/agent-ui-kit/src/overlay/stack.ts +111 -0
  319. package/packages/agent-ui-kit/src/overlay/use-overlay.ts +80 -0
  320. package/packages/agent-ui-kit/src/preview-provider.tsx +47 -0
  321. package/packages/agent-ui-kit/src/shell.contract.json +75 -0
  322. package/packages/agent-ui-kit/src/shell.test.ts +72 -0
  323. package/packages/agent-ui-kit/src/shell.ts +60 -0
  324. package/packages/agent-ui-kit/src/surface.test.tsx +35 -0
  325. package/packages/agent-ui-kit/src/surface.tsx +44 -0
  326. package/packages/agent-ui-kit/src/test/._setup.ts +0 -0
  327. package/packages/agent-ui-kit/src/theme/._base.css +0 -0
  328. package/packages/agent-ui-kit/src/theme/._contract.json +0 -0
  329. package/packages/agent-ui-kit/src/theme/._motion.css +0 -0
  330. package/packages/agent-ui-kit/src/theme/._theme-contract.test.ts +0 -0
  331. package/packages/agent-ui-kit/src/theme/._theme.ts +0 -0
  332. package/packages/agent-ui-kit/src/theme/._tokens.css +0 -0
  333. package/packages/agent-ui-kit/src/theme/base.css +167 -0
  334. package/packages/agent-ui-kit/src/theme/contract.json +123 -2
  335. package/packages/agent-ui-kit/src/theme/theme-contract.test.ts +19 -3
  336. package/packages/agent-ui-kit/src/theme/{tokens.less → tokens.css} +19 -20
  337. package/packages/agent-ui-kit/src/utils/._copyText.ts +0 -0
  338. package/packages/agent-ui-kit/src/utils/._haptics.test.ts +0 -0
  339. package/packages/agent-ui-kit/src/utils/._haptics.ts +0 -0
  340. package/packages/agent-ui-kit/src/utils/._image-preview-host.tsx +0 -0
  341. package/packages/agent-ui-kit/src/utils/._imagePreview.test.ts +0 -0
  342. package/packages/agent-ui-kit/src/utils/._imagePreview.ts +0 -0
  343. package/packages/agent-ui-kit/src/utils/._pull-down-machine.test.ts +0 -0
  344. package/packages/agent-ui-kit/src/utils/._pull-down-machine.ts +0 -0
  345. package/packages/agent-ui-kit/src/utils/._session-error.ts +0 -0
  346. package/packages/agent-ui-kit/src/utils/._toast.test.ts +0 -0
  347. package/packages/agent-ui-kit/src/utils/._toast.ts +0 -0
  348. package/packages/agent-ui-kit/src/utils/._tool-call-display.test.ts +0 -0
  349. package/packages/agent-ui-kit/src/utils/._tool-call-display.ts +0 -0
  350. package/packages/agent-ui-kit/src/utils/image-preview-host.tsx +95 -0
  351. package/packages/agent-ui-kit/src/utils/imagePreview.test.ts +32 -0
  352. package/packages/agent-ui-kit/src/utils/imagePreview.ts +14 -5
  353. package/packages/agent-ui-kit/src/utils/toast.test.ts +64 -0
  354. package/packages/agent-ui-kit/src/utils/toast.ts +100 -7
  355. package/packages/contracts-mall/._package.json +0 -0
  356. package/packages/contracts-mall/._tsconfig.json +0 -0
  357. package/packages/contracts-mall/src/._index.ts +0 -0
  358. package/packages/contracts-mall/src/._runtime.ts +0 -0
  359. package/packages/contracts-mall/src/server/._index.ts +0 -0
  360. package/packages/shared/._AGENTS.md +0 -0
  361. package/packages/shared/._package.json +0 -0
  362. package/packages/shared/._tsconfig.json +0 -0
  363. package/packages/shared/AGENTS.md +13 -0
  364. package/packages/shared/package.json +20 -0
  365. package/packages/shared/src/._index.ts +0 -0
  366. package/packages/shared/src/index.ts +8 -0
  367. package/packages/shared/tsconfig.json +7 -0
  368. package/pnpm-lock.template.yaml +781 -846
  369. package/pnpm-workspace.template.yaml +19 -11
  370. package/profiles/._mall.json +0 -0
  371. package/profiles/mall/._TEMPLATE.md +0 -0
  372. package/profiles/mall/._chat.overrides.json +0 -0
  373. package/profiles/mall/chat.overrides.json +12 -0
  374. package/profiles/mall/config/._agent.jsonc +0 -0
  375. package/profiles/mall/config/._chat.json +0 -0
  376. package/profiles/mall/config/._knowledge.json +0 -0
  377. package/profiles/mall/config/chat.json +14 -6
  378. package/profiles/mall.json +2 -2
  379. package/scenarios/._README.md +0 -0
  380. package/scenarios/README.md +7 -0
  381. package/scripts/._assert-pack.mjs +0 -0
  382. package/scripts/._build.sh +0 -0
  383. package/scripts/._check-css-target.mjs +0 -0
  384. package/scripts/._check-fast.mjs +0 -0
  385. package/scripts/._check-workspace.mjs +0 -0
  386. package/scripts/._checks.json +0 -0
  387. package/scripts/._deliver.mjs +0 -0
  388. package/scripts/._dev-alipay.mjs +0 -0
  389. package/scripts/._dev.sh +0 -0
  390. package/scripts/._generate.mjs +0 -0
  391. package/scripts/._prepare.sh +0 -0
  392. package/scripts/._shell-probe.mjs +0 -0
  393. package/scripts/._smoke.mjs +0 -0
  394. package/scripts/._start.sh +0 -0
  395. package/scripts/._stop.sh +0 -0
  396. package/scripts/._storyboard.mjs +0 -0
  397. package/scripts/._verify-generated.mjs +0 -0
  398. package/scripts/assert-pack.mjs +48 -0
  399. package/scripts/check-css-target.mjs +54 -0
  400. package/scripts/check-fast.mjs +119 -0
  401. package/scripts/check-workspace.mjs +68 -19
  402. package/scripts/checks.json +627 -0
  403. package/scripts/deliver.mjs +183 -0
  404. package/scripts/dev-alipay.mjs +1 -1
  405. package/scripts/generate.mjs +3 -0
  406. package/scripts/lib/._chrome-pipe.mjs +0 -0
  407. package/scripts/lib/._geometry-kernel.mjs +0 -0
  408. package/scripts/lib/chrome-pipe.mjs +95 -0
  409. package/scripts/lib/geometry-kernel.mjs +137 -0
  410. package/scripts/shell-probe.mjs +280 -0
  411. package/scripts/storyboard.mjs +350 -0
  412. package/scripts/verify-generated.mjs +22 -127
  413. package/tsconfig.base.json +1 -0
  414. package/apps/client/STYLE_GUIDE.md +0 -81
  415. package/apps/client/VISUAL_RESTORE.md +0 -90
  416. package/apps/client/src/app.tsx +0 -11
  417. package/apps/client/src/business/App.tsx +0 -11
  418. package/apps/client/src/business/README.md +0 -99
  419. package/apps/client/src/business/routes.json +0 -3
  420. package/apps/client/src/main.tsx +0 -17
  421. package/apps/client/src/modules.ts +0 -33
  422. package/apps/client/src/platform/AgentChatApp.tsx +0 -14
  423. package/apps/client/src/platform/AppShell.tsx +0 -42
  424. package/apps/client/src/platform/agent-runtime.ts +0 -16
  425. package/apps/client/src/platform/bootstrap.ts +0 -55
  426. package/apps/client/src/platform/card-preview-page.tsx +0 -12
  427. package/apps/client/src/platform/mount-page.tsx +0 -25
  428. package/apps/client/src/platform/state/createPersistedStore.ts +0 -19
  429. package/apps/server/src/app-tools.ts +0 -14
  430. package/apps/server/src/modules.ts +0 -38
  431. package/apps/server/src/tools/clock.ts +0 -24
  432. package/apps/server/src/tools/translate.ts +0 -47
  433. package/packages/agent-ui-kit/src/ChatPage.less +0 -66
  434. package/packages/agent-ui-kit/src/components/ActionBar/index.less +0 -123
  435. package/packages/agent-ui-kit/src/components/ChatHeader/index.less +0 -148
  436. package/packages/agent-ui-kit/src/components/ChatInput/index.less +0 -394
  437. package/packages/agent-ui-kit/src/components/HistoryEntry/index.less +0 -49
  438. package/packages/agent-ui-kit/src/components/MediaList/index.less +0 -241
  439. package/packages/agent-ui-kit/src/components/MessageBubble/index.less +0 -325
  440. package/packages/agent-ui-kit/src/components/PullDownIndicator/index.less +0 -32
  441. package/packages/agent-ui-kit/src/components/QuickCommands/index.less +0 -63
  442. package/packages/agent-ui-kit/src/components/ReasoningBlock/index.less +0 -90
  443. package/packages/agent-ui-kit/src/components/ScrollToBottomButton/index.less +0 -32
  444. package/packages/agent-ui-kit/src/components/ToolCallBlock/index.less +0 -312
  445. package/packages/agent-ui-kit/src/theme/global.less +0 -99
  446. package/profiles/mall/config/llm_provider.json +0 -5
  447. package/profiles/mall/config/plugins.json +0 -3
  448. /package/{packages → modules}/provider-custom/LICENSE +0 -0
  449. /package/{packages → modules}/provider-custom/README.md +0 -0
  450. /package/{packages → modules}/provider-custom/src/index.ts +0 -0
  451. /package/{packages → modules}/provider-custom/tbox.module.json +0 -0
  452. /package/{packages → modules}/provider-custom/tests/provider-custom.test.ts +0 -0
  453. /package/{packages → modules}/provider-custom/tsconfig.json +0 -0
  454. /package/{packages → modules}/provider-custom/tsup.config.ts +0 -0
  455. /package/packages/agent-ui-kit/src/theme/{motion.less → motion.css} +0 -0
@@ -0,0 +1,1402 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * check-evidence — `check:fast` 的证据包(T0 增强)。
4
+ *
5
+ * 一个进程里跑四步,任何一步失败即给出可执行的修复信息:
6
+ * ① styles —— 用与 dev/build 相同的 Vite + Tailwind 管线编译整份表面样式(哨兵 + 体积自检);
7
+ * ② primitives —— 卡片样例过 schema、出卡/动作类型已注册、出卡提示、档外字号、类名死码;
8
+ * ③ render —— 每张卡 × 每个样例经真实 React 组件渲染(SSR),不抛错;
9
+ * ④ scenarios —— `scenarios/*.json` 全部通过(没有场景记 notRun,不算失败)。
10
+ *
11
+ * 三步共用一个 Vite 实例(`ssrLoadModule` 同时加载客户端卡片与服务端 registry),
12
+ * 合并进程是把四步压进 8 秒预算的前提;分开起进程会超时(实测 3.2–3.9 秒 → 合并 2.1–2.4 秒)。
13
+ *
14
+ * 用法:node scripts/check-evidence.mjs [--no-render] [--no-scenarios] [--json]
15
+ * 退出码:0 = 无错误(告警不影响);1 = 有错误。
16
+ */
17
+ import { execFileSync } from 'node:child_process';
18
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
19
+ import path from 'node:path';
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 { checkCss } from '@tbox.cn/app-build/compat';
26
+ import { duplicateSampleLabels, sampleEntries } from './render-card.mjs';
27
+ import { collectCards, cardSourceHint, cardMetaSourceHint } from './lib/card-registry.mjs';
28
+ import { createStaticRenderer } from './lib/static-render.mjs';
29
+ import { evidenceInputFiles } from './lib/evidence-inputs.mjs';
30
+ import { STATIC_CHECKS, runStaticChecks } from './experience-checks.mjs';
31
+ import { IN_PROCESS_CHECKS, runInProcessChecks } from './in-process-checks.mjs';
32
+ import { PROBE_CHECKS, STORYBOARD_CHECKS, mergeProbeChecks, mergeStoryboardChecks } from './probe-checks.mjs';
33
+ import { acceptanceChangesOf, acceptanceDrift, capabilityDrift, defaultModuleDrift, contrastRatio, coverageSets, hashSourceTree, matchFrame, parseColor, resolvePolicy, scenarioDrift, scenarioKey, shouldReopen, storyboardCoverage, summarizeAcceptanceChanges, versionAtLeast } from './evidence-gate.mjs';
34
+
35
+ // 门禁里的场景与渲染不写真实状态文件。
36
+ process.env.TBOX_STATE_MEMORY ??= '1';
37
+
38
+ const appDir = path.resolve(import.meta.dirname, '..', '..', '..');
39
+ const clientDir = path.join(appDir, 'apps/client');
40
+ const args = new Set(process.argv.slice(2));
41
+ const withRender = !args.has('--no-render');
42
+ const withScenarios = !args.has('--no-scenarios');
43
+
44
+ const steps = [];
45
+ const warnings = [];
46
+ const notRun = [];
47
+ const errors = [];
48
+ let scenarioResults = [];
49
+ let scenarioInstances = [];
50
+ const cardDigests = [];
51
+ let historyRendered = 0;
52
+ let experienceItems = [];
53
+ let cardFacts = [];
54
+
55
+ const json = (value) => JSON.stringify(value);
56
+
57
+ function warn(id, message, extra = {}) {
58
+ warnings.push({ id, message, ...extra });
59
+ }
60
+
61
+ function fail(step, items) {
62
+ steps.push({ name: step, ok: false, ms: 0 });
63
+ for (const item of items) errors.push({ step, ...(typeof item === 'string' ? { message: item } : item) });
64
+ }
65
+
66
+ // ── 0. 一个 Vite 实例 ────────────────────────────────────────────────
67
+ // 不加载应用自己的 vite.config.ts:它把 @tbox.cn/app-build 等仓内源码包当外部依赖交给 Node ESM,
68
+ // 在仓库内(非发布态)会因无扩展名 import 解析失败。这里只需要 TSX 转换、别名与 less。
69
+ const { createServer } = await import('vite');
70
+ const react = (await import('@vitejs/plugin-react')).default;
71
+ const tailwindcss = (await import('@tailwindcss/vite')).default;
72
+ let vite;
73
+ const bootstrapStart = performance.now();
74
+ try {
75
+ vite = await createServer({
76
+ configFile: false,
77
+ root: clientDir,
78
+ appType: 'custom',
79
+ logLevel: 'error',
80
+ plugins: [tailwindcss(), react()],
81
+ resolve: {
82
+ alias: {
83
+ '@': path.join(clientDir, 'src'),
84
+ '@config': path.join(appDir, 'config'),
85
+ },
86
+ },
87
+ // 零 socket:HMR 挂到永不 listen 的 http server,避免自建 24678 监听。
88
+ server: { middlewareMode: true, hmr: { server: createHttpServer() }, fs: { allow: [appDir] } },
89
+ optimizeDeps: { noDiscovery: true, include: [] },
90
+ });
91
+ steps.push({ name: 'vite', ok: true, ms: Math.round(performance.now() - bootstrapStart) });
92
+ } catch (error) {
93
+ fail('vite', [{ message: `Vite 启动失败:${error?.message ?? error}`, fix: '检查依赖安装与 .tbox-gen 是否生成' }]);
94
+ process.stdout.write(json({ ok: false, durationMs: 0, steps, errors }) + '\n');
95
+ process.exit(1);
96
+ }
97
+
98
+ const registryClient = await vite.ssrLoadModule('/.tbox-gen/registry.client.ts').catch((error) => {
99
+ fail('registry', [{ id: 'registry-load-failed', message: `客户端 registry 加载失败:${error?.message ?? error}`, fix: '跑 pnpm generate 重新生成 .tbox-gen' }]);
100
+ return undefined;
101
+ });
102
+
103
+ const registryServer = await vite.ssrLoadModule('/@fs' + path.join(clientDir, '.tbox-gen/registry.server.ts')).catch((error) => {
104
+ fail('registry', [{ id: 'registry-load-failed', message: `服务端 registry 加载失败:${error?.message ?? error}`, fix: '跑 pnpm generate 重新生成 .tbox-gen' }]);
105
+ return undefined;
106
+ });
107
+
108
+ // 证据面卡片视图:与运行时同序(app 先、模块后;后者覆盖)——模块卡不能只存在于运行时。
109
+ const cardView = collectCards({ server: registryServer, client: registryClient });
110
+ const mergedMetas = cardView.metas;
111
+ const mergedComponents = cardView.components;
112
+ const cardProvenance = cardView.provenance;
113
+ for (const item of cardView.warnings) warn(item.id, item.message);
114
+
115
+ // ── 1. styles ───────────────────────────────────────────────────────
116
+ async function checkStyles() {
117
+ const started = performance.now();
118
+ const entry = path.join(clientDir, 'src/styles/brand.css');
119
+ if (!existsSync(entry)) {
120
+ notRun.push('styles');
121
+ warn('styles-entry-missing', '没有 apps/client/src/styles/brand.css:品牌变量无法校验', {
122
+ fix: '新建 brand.css(只放品牌变量覆写,模板出厂自带),app.config.ts 里 import 它',
123
+ recipe: 'style',
124
+ });
125
+ steps.push({ name: 'styles', ok: true, ms: Math.round(performance.now() - started), skipped: true });
126
+ return;
127
+ }
128
+ // 与 dev/build 同一条管线(surface-css.mjs):不是「brand.css 语法没坏」,
129
+ // 而是「整份表面样式真的生成了」——空 CSS / 缺哨兵一律失败,截图与证据才可信。
130
+ try {
131
+ const surface = await buildSurfaceCss(vite, { clientDir, appDir });
132
+ checkUtilityClasses(surface.cssText);
133
+ const moduleSources = surface.moduleSources ?? [];
134
+ const moduleIds = new Set(moduleSources.map((dir) => path.basename(path.dirname(path.dirname(dir)))));
135
+ const registryFile = path.join(clientDir, '.tbox-gen/registry.client.ts');
136
+ const registryText = existsSync(registryFile) ? readFileSync(registryFile, 'utf8') : '';
137
+ const expectedModuleIds = new Set(
138
+ [...registryText.matchAll(/\/(module-[^/'"]+)\/src\/client\/index\.ts/g)].map((match) => match[1]),
139
+ );
140
+ const expectedModules = expectedModuleIds.size || (Array.isArray(registryClient?.modules) ? registryClient.modules.length : 0);
141
+ const missingModuleIds = [...expectedModuleIds].filter((id) => !moduleIds.has(id));
142
+ const missingModuleCss = moduleIds.has('module-mall-core')
143
+ ? ['#fff8e9', 'container-type'].filter((token) => !surface.cssText.includes(token))
144
+ : [];
145
+ if (surface.bytes < 20000 || surface.missing.length > 0) {
146
+ fail('styles', [{
147
+ id: 'styles-empty',
148
+ message: `表面 CSS 不可信:${surface.bytes} 字节,缺哨兵 ${surface.missing.join('、') || '无'}`,
149
+ fix: '确认 apps/client/vite.config.ts 的 tboxModuleSourcesPlugin 在 tailwindcss() 之前;证据与 dev/build 共用 surface-css.mjs 与 app-build 的模块发现',
150
+ recipe: 'style',
151
+ }]);
152
+ steps.push({ name: 'styles', ok: false, ms: Math.round(performance.now() - started), cssBytes: surface.bytes, moduleSources: moduleSources.length, expectedModules });
153
+ } else if (moduleSources.length < expectedModules || missingModuleIds.length > 0 || missingModuleCss.length > 0) {
154
+ fail('styles', [{
155
+ id: 'styles-module-sources-missing',
156
+ message: `模块样式未进入扫描面:sources=${moduleSources.length}/${expectedModules},缺 ${missingModuleIds.join('、') || missingModuleCss.join('、') || '模块源码'}`,
157
+ fix: '确认 apps/client/vite.config.ts 的 tboxModuleSourcesPlugin 在 tailwindcss() 之前,且 surface-css.mjs 使用 app-build 的 collectModuleSourceDirs',
158
+ recipe: 'style',
159
+ }]);
160
+ steps.push({ name: 'styles', ok: false, ms: Math.round(performance.now() - started), cssBytes: surface.bytes, moduleSources: moduleSources.length, expectedModules, missingModuleIds });
161
+ } else {
162
+ steps.push({ name: 'styles', ok: true, ms: Math.round(performance.now() - started), cssBytes: surface.bytes, moduleSources: moduleSources.length, expectedModules });
163
+ }
164
+
165
+ // 产物兼容门禁(与模板 build / 根 verify:css 同一内核)。
166
+ // 表面 CSS 含模块:拆两层归因——基础面(app+kit+主题)越线 = error;
167
+ // 仅由模块引入的越线 = warning(模块独立发布,与类名规则同策略,收敛后升 error)。
168
+ const compatStarted = performance.now();
169
+ const baseline = JSON.parse(readFileSync(path.join(appDir, 'package.json'), 'utf8'))?.tbox?.compat?.baseline;
170
+ const allCompat = checkCss(surface.cssText, { baseline });
171
+ if (allCompat.errors.length > 0) {
172
+ warn('compat-baseline-invalid', `兼容门禁跳过:${allCompat.errors.join(';')}`, {
173
+ fix: '模板 package.json 的 tbox.compat.baseline 写矩阵 { safari, chrome }',
174
+ recipe: 'style',
175
+ });
176
+ } else {
177
+ const baseFindings = moduleSources.length > 0
178
+ ? checkCss((await buildSurfaceCss(vite, { clientDir, appDir, modules: false })).cssText, { baseline }).findings
179
+ : allCompat.findings;
180
+ const signature = (item) => `${item.feature}|${item.sample}`;
181
+ const baseSignatures = new Set(baseFindings.map(signature));
182
+ for (const finding of allCompat.findings) {
183
+ if (baseSignatures.has(signature(finding))) {
184
+ errors.push({
185
+ step: 'compat',
186
+ file: 'apps/client',
187
+ id: finding.feature,
188
+ message: `${finding.message}(${finding.sample})`,
189
+ fix: finding.fix,
190
+ recipe: 'style',
191
+ });
192
+ } else {
193
+ warn(`compat-${finding.feature}`, `模块 CSS 越线:${finding.message}(${finding.sample})——升级模块或补 vh/静态回退`, {
194
+ fix: finding.fix,
195
+ recipe: 'style',
196
+ });
197
+ }
198
+ }
199
+ const moduleFindings = allCompat.findings.length - baseFindings.length;
200
+ steps.push({
201
+ name: 'compat',
202
+ ok: baseFindings.length === 0,
203
+ ms: Math.round(performance.now() - compatStarted),
204
+ findings: allCompat.findings.length,
205
+ moduleFindings: Math.max(moduleFindings, 0),
206
+ });
207
+ }
208
+ } catch (error) {
209
+ fail('styles', [{
210
+ id: 'styles-compile-failed',
211
+ message: `样式编译失败 ${path.relative(appDir, entry)}:${error?.message ?? error}`,
212
+ fix: '修掉 CSS 语法/变量错误;变量名以 docs/agent/kit.md 的 token 表为准',
213
+ recipe: 'style',
214
+ }]);
215
+ }
216
+ }
217
+
218
+ /**
219
+ * 死类:源码里像工具类、CSS 里却没有对应规则。
220
+ * Tailwind 对不认识的类不报错、只是不生成——拼错的类名(如 bg-primary-light)会静默失效。
221
+ * 只检查纯字母数字/连字符的 token(任意值、变体、模板插值都跳过),先告警不阻断。
222
+ */
223
+ function checkUtilityClasses(cssText) {
224
+ const cardsDir = path.join(clientDir, 'src/cards');
225
+ if (!existsSync(cardsDir)) return;
226
+ const seen = new Set();
227
+ for (const entry of readdirSync(cardsDir)) {
228
+ if (!entry.endsWith('.tsx')) continue;
229
+ const source = readFileSync(path.join(cardsDir, entry), 'utf8');
230
+ for (const match of source.matchAll(/className=(?:"([^"]*)"|\{'([^']*)'\})/g)) {
231
+ const value = match[1] ?? match[2] ?? '';
232
+ if (value.includes('${')) continue;
233
+ for (const token of value.split(/\s+/)) {
234
+ if (!token || token.includes(':') || token.includes('[') || token.includes('/') || token.includes('__')) continue;
235
+ if (!looksLikeUtility(token)) continue;
236
+ if (seen.has(token)) continue;
237
+ seen.add(token);
238
+ const pattern = new RegExp('\\.' + token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![\\w-])');
239
+ if (!pattern.test(cssText)) {
240
+ warn('utility-class-missing', `apps/client/src/cards/${entry}: 类名 ${token} 没有生成 CSS(拼写或未登记)`, {
241
+ fix: '对照 docs/agent/style.md 的语义色与档位;任意值改用方括号写法',
242
+ recipe: 'style',
243
+ });
244
+ }
245
+ }
246
+ }
247
+ }
248
+ }
249
+
250
+ // ── 2. primitives ───────────────────────────────────────────────────
251
+ function checkPrimitives() {
252
+ const started = performance.now();
253
+ const cards = mergedMetas;
254
+ const cardTypes = new Set(Object.keys(cards));
255
+ const tools = registryServer?.tools ?? [];
256
+
257
+ for (const [cardType, meta] of Object.entries(cards)) {
258
+ const duplicates = duplicateSampleLabels(meta);
259
+ if (duplicates.length > 0) {
260
+ warn('card-sample-label-duplicate', `${cardType} 的样例 label 重复:${duplicates.join('、')}(帧键/渲染文件名会互相覆盖)`, {
261
+ fix: `改 ${cardMetaSourceHint(cardProvenance, cardType)} 里的 samples[].label,同卡内必须唯一`,
262
+ recipe: 'card',
263
+ });
264
+ }
265
+ for (const sample of sampleEntries(meta)) {
266
+ const parsed = meta.dataSchema.safeParse(sample.data);
267
+ if (!parsed.success) {
268
+ errors.push({
269
+ step: 'primitives',
270
+ id: 'card-sample-invalid',
271
+ message: `卡片样例不合法 ${cardType} ${sample.label}: ${parsed.error.issues[0]?.message ?? parsed.error.message}`,
272
+ fix: `补 ${cardMetaSourceHint(cardProvenance, cardType)} 的 sampleData/samples`,
273
+ recipe: 'card',
274
+ });
275
+ }
276
+ }
277
+ }
278
+
279
+ const toolsDir = path.join(appDir, 'apps/server/src/tools');
280
+ const knownToolIds = new Set(tools.map((tool) => tool.id));
281
+ if (existsSync(toolsDir)) {
282
+ for (const name of readdirSync(toolsDir).filter((file) => file.endsWith('.tool.ts'))) {
283
+ const source = readFileSync(path.join(toolsDir, name), 'utf8');
284
+ const id = /id:\s*'([^']+)'/.exec(source)?.[1];
285
+ if (id && !knownToolIds.has(id)) {
286
+ warn('tool-not-registered', `${name}: 工具 id "${id}" 未进入 registry`, {
287
+ fix: '检查是否漏了 export const tool(app-build 只扫描具名导出)',
288
+ recipe: 'tool',
289
+ });
290
+ }
291
+ const declared = [...source.matchAll(/cardType:\s*'([^']+)'/g)].map((match) => match[1]);
292
+ for (const cardType of new Set(declared)) {
293
+ if (!cardTypes.has(cardType)) {
294
+ errors.push({
295
+ step: 'primitives',
296
+ file: `apps/server/src/tools/${name}`,
297
+ id: 'card-type-unknown',
298
+ message: `出卡类型 "${cardType}" 未注册`,
299
+ fix: `补 apps/server/src/cards/${cardType}.card.ts 与 apps/client/src/cards/${cardType}.card.tsx`,
300
+ recipe: 'card',
301
+ });
302
+ }
303
+ }
304
+ if (declared.length > 0 && !/可展示卡片/.test(source)) {
305
+ warn('card-emission-hint', `${name}: 出卡工具的 description 未声明「命中数据时结果附可展示卡片(cards)。」`, {
306
+ fix: '用 withCardEmissionHint 或在 description 里补这句,否则模型不知道可以出卡',
307
+ recipe: 'tool-emits-card',
308
+ });
309
+ }
310
+ }
311
+ }
312
+
313
+ const actionsDir = path.join(appDir, 'apps/server/src/actions');
314
+ if (existsSync(actionsDir)) {
315
+ for (const name of readdirSync(actionsDir).filter((file) => file.endsWith('.action.ts'))) {
316
+ const source = readFileSync(path.join(actionsDir, name), 'utf8');
317
+ const declaredTypes = [...source.matchAll(/cardType:\s*(\[[^\]]*\]|'[^']+')/g)].flatMap((match) =>
318
+ match[1].startsWith('[') ? [...match[1].matchAll(/'([^']+)'/g)].map((item) => item[1]) : [match[1].slice(1, -1)],
319
+ );
320
+ for (const cardType of new Set(declaredTypes)) {
321
+ if (!cardTypes.has(cardType)) {
322
+ errors.push({
323
+ step: 'primitives',
324
+ file: `apps/server/src/actions/${name}`,
325
+ id: 'action-card-unknown',
326
+ message: `动作挂在不存在的卡片 "${cardType}" 上(按钮不会出现)`,
327
+ fix: `补 apps/server/src/cards/${cardType}.card.ts`,
328
+ recipe: 'card-action',
329
+ });
330
+ }
331
+ }
332
+ }
333
+ }
334
+
335
+ // 按钮动作引用与注册表对齐(E3):invoke 字面量 → 动作存在、且挂在这张卡上。
336
+ const actions = registryServer?.actions ?? {};
337
+ const actionsDirClient = path.join(clientDir, 'src/cards');
338
+ if (existsSync(actionsDirClient)) {
339
+ for (const name of readdirSync(actionsDirClient).filter((file) => file.endsWith('.card.tsx'))) {
340
+ const cardType = name.slice(0, -'.card.tsx'.length);
341
+ const source = readFileSync(path.join(actionsDirClient, name), 'utf8');
342
+ const ids = new Set([...source.matchAll(/\binvoke\s*:\s*\{\s*id\s*:\s*'([^']+)'/g)].map((match) => match[1]));
343
+ for (const id of ids) {
344
+ const action = actions[id];
345
+ if (!action) {
346
+ errors.push({
347
+ step: 'primitives',
348
+ file: `apps/client/src/cards/${name}`,
349
+ id: 'action-invoke-unknown',
350
+ message: `按钮 invoke 的动作 "${id}" 未注册`,
351
+ fix: `补 apps/server/src/actions/${id}.action.ts,或改 invoke 的 id`,
352
+ recipe: 'card-action',
353
+ });
354
+ continue;
355
+ }
356
+ const bound = Array.isArray(action.cardType) ? action.cardType : [action.cardType];
357
+ if (!bound.includes(cardType)) {
358
+ errors.push({
359
+ step: 'primitives',
360
+ file: `apps/client/src/cards/${name}`,
361
+ id: 'action-invoke-card-mismatch',
362
+ message: `动作 "${id}" 没有绑定到 ${cardType}(声明:${bound.join('、') || '无'})`,
363
+ fix: `把 ${cardType} 加进动作的 cardType,或从这张卡上撤掉该按钮`,
364
+ recipe: 'card-action',
365
+ });
366
+ }
367
+ }
368
+ }
369
+ }
370
+
371
+ steps.push({ name: 'primitives', ok: !errors.some((item) => item.step === 'primitives'), ms: Math.round(performance.now() - started) });
372
+ }
373
+
374
+ // ── 2b. tailwind 类名禁忌(禁用项)────────────────────────────────────
375
+ // Tailwind 对不认识的类不报错、只是不生成——所以这几类必须让它们出声。
376
+ // 规则与 docs/agent/style.md 一一对应:默认调色板、档外字号、类名紧贴插值、
377
+ // 元素级 --tbox-asset-* 声明(会截断 html[data-theme] 覆写继承)。
378
+ /** 判断一个 token 像不像工具类(去掉变体前缀后看末段):用来把 BEM 钩子排除在外 */
379
+ function looksLikeUtility(token) {
380
+ if (token.includes('__')) return false;
381
+ let depth = 0;
382
+ let cut = 0;
383
+ for (let i = 0; i < token.length; i += 1) {
384
+ const ch = token[i];
385
+ if (ch === '[') depth += 1;
386
+ else if (ch === ']') depth -= 1;
387
+ else if (ch === ':' && depth === 0) cut = i + 1;
388
+ }
389
+ const base = token.slice(cut);
390
+ if (base.startsWith('[')) return base.length > 3 && base.includes(']');
391
+ return /^(?:-?(?:m|p)[trblxy]?|w|h|size|min|max|gap|space|inset|top|right|bottom|left|z|flex|grid|block|inline|hidden|items|justify|content|self|place|order|col|row|basis|grow|shrink|text|font|leading|tracking|whitespace|break|truncate|line-clamp|bg|border|rounded|shadow|ring|outline|opacity|transition|duration|ease|delay|animate|cursor|appearance|fill|stroke|object|aspect|overflow|divide|sr-only|tabular-nums|antialiased|from|via|to)(?:-|$)/.test(base);
392
+ }
393
+
394
+ const TAILWIND_BANNED = [
395
+ {
396
+ id: 'palette-color',
397
+ pattern: /\b(?:bg|text|border|from|to|via|ring|outline|fill|stroke|divide|placeholder|decoration)-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d{2,3}\b/,
398
+ message: '用了 Tailwind 默认调色板(不生成 CSS,且产物会带 oklch)',
399
+ fix: '换成语义色:text-foreground / bg-card / border-border 等(docs/agent/style.md)',
400
+ },
401
+ {
402
+ id: 'font-size-off-scale',
403
+ pattern: /\btext-\[\d+(?:\.\d+)?px\]/,
404
+ message: '字号越档(档位 12/14/16/18/20/24/30;4xl=36 仅特殊场景)',
405
+ fix: '用 text-xs/sm/base/lg/xl/2xl/3xl;确需精确值改 line-height 或行内样式',
406
+ // 例外:活动卡的 badge / meta 标注档(11px)。只放行这一类钩子,不得扩散。
407
+ skipLine: (line) => /text-\[11px\]/.test(line) && /ap-badge|__meta|__badge|__hint/.test(line),
408
+ },
409
+ {
410
+ id: 'class-before-interpolation',
411
+ // 类名紧贴 `${` 时扫描器拿不到完整候选(实测 `gap-1.5${…}` 整条不生成 CSS)
412
+ pattern: /(?:^|[\s'"`{])([a-z[][\w:[\]/.(),#%-]*)\$\{/,
413
+ message: '类名紧贴模板插值(扫描器会漏掉这条类,样式静默不生效)',
414
+ fix: '在 `${` 前留一个空格:`text-xs ${cond ? … : …}`',
415
+ skip: (token) => !looksLikeUtility(token),
416
+ },
417
+ {
418
+ id: 'element-asset-declaration',
419
+ pattern: /\[--tbox-asset-/,
420
+ message: '在元素上声明 --tbox-asset-*(会截断 html[data-theme] 覆写继承)',
421
+ fix: '素材变量归主题包;元素只消费 var(--tbox-asset-*, 兜底)',
422
+ },
423
+ ];
424
+
425
+ function checkTailwindClasses() {
426
+ const started = performance.now();
427
+ // 模块源码也扫:模块是独立发布的包,违规先以 warn 呈现(模板先行、模块随发版收敛),
428
+ // 收敛完成后把判定切回 errors 即可升级为阻断。
429
+ const roots = [
430
+ path.join(clientDir, 'src'),
431
+ path.join(appDir, 'packages/agent-ui-kit/src'),
432
+ path.join(appDir, 'modules'),
433
+ ];
434
+ const files = [];
435
+ const walkTsx = (dir) => {
436
+ if (!existsSync(dir)) return;
437
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
438
+ const full = path.join(dir, entry.name);
439
+ if (entry.isDirectory()) {
440
+ if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name === '.tbox') continue;
441
+ walkTsx(full);
442
+ } else if (entry.name.endsWith('.tsx') || entry.name.endsWith('.ts')) files.push(full);
443
+ }
444
+ };
445
+ roots.forEach(walkTsx);
446
+ for (const file of files) {
447
+ // 统一 POSIX 分隔符:模块判定与报告路径跨平台一致
448
+ const rel = path.relative(appDir, file).split(path.sep).join('/');
449
+ readFileSync(file, 'utf8').split('\n').forEach((line, index) => {
450
+ for (const rule of TAILWIND_BANNED) {
451
+ const match = rule.pattern.exec(line);
452
+ if (!match) continue;
453
+ if (rule.skip?.(match[1] ?? '')) continue;
454
+ if (rule.skipLine?.(line)) continue;
455
+ const finding = {
456
+ step: 'primitives',
457
+ file: `${rel}:${index + 1}`,
458
+ id: rule.id,
459
+ message: `${rule.message}:${match[0]}`,
460
+ fix: rule.fix,
461
+ recipe: 'style',
462
+ };
463
+ if (rel.startsWith('modules/')) {
464
+ warn(rule.id, `${finding.file} ${finding.message}(模块侧先告警;收敛后升 error)`, { fix: rule.fix });
465
+ } else {
466
+ errors.push(finding);
467
+ }
468
+ }
469
+ });
470
+ }
471
+ steps.push({ name: 'tailwind', ok: !errors.some((item) => item.step === 'primitives'), ms: Math.round(performance.now() - started), files: files.length });
472
+ }
473
+
474
+ function htmlDigest(html) {
475
+ return String(html)
476
+ .replace(/<script[\s\S]*?<\/script>/g, ' ')
477
+ .replace(/<style[\s\S]*?<\/style>/g, ' ')
478
+ .replace(/<[^>]+>/g, ' ')
479
+ .replace(/&nbsp;/g, ' ')
480
+ .replace(/\s+/g, ' ')
481
+ .trim()
482
+ .slice(0, 240);
483
+ }
484
+
485
+ // ── 3. render ───────────────────────────────────────────────────────
486
+ async function checkRender() {
487
+ const started = performance.now();
488
+ if (!withRender) {
489
+ notRun.push('render');
490
+ steps.push({ name: 'render', ok: true, ms: 0, skipped: true });
491
+ return;
492
+ }
493
+ const metas = mergedMetas;
494
+ if (Object.keys(metas).length === 0) {
495
+ steps.push({ name: 'render', ok: true, ms: Math.round(performance.now() - started), cards: 0, rendered: 0, skipped: true });
496
+ return;
497
+ }
498
+ const React = (await import('react')).default;
499
+ const { renderToStaticMarkup } = await import('react-dom/server');
500
+ const kit = await vite.ssrLoadModule('@tbox.cn/app-agent-ui-kit');
501
+ const staticRender = createStaticRenderer(renderToStaticMarkup);
502
+
503
+ const components = mergedComponents;
504
+ // 与运行时 / 预览 / 截图同一条装配(SurfaceHarness),不再手搭 provider。
505
+ const harness = kit.createSurfaceHarness({ cards: components });
506
+ let rendered = 0;
507
+ let bytes = 0;
508
+
509
+ for (const [cardType, meta] of Object.entries(metas)) {
510
+ const Component = components[cardType];
511
+ const sourceFile = cardSourceHint(cardProvenance, cardType);
512
+ if (!Component) {
513
+ errors.push({
514
+ step: 'render',
515
+ id: 'card-client-missing',
516
+ message: `客户端缺少卡片组件 ${cardType}`,
517
+ fix: `补 ${sourceFile}(export const card = defineCard({ type: '${cardType}' }, …))`,
518
+ recipe: 'card',
519
+ });
520
+ continue;
521
+ }
522
+ for (const sample of sampleEntries(meta)) {
523
+ const { label, data } = sample;
524
+ try {
525
+ const html = staticRender.render(
526
+ harness.wrap(React.createElement(Component, { data, cardId: `evidence-${cardType}`, isHistory: sample.isHistory === true, actionTokens: {} })),
527
+ );
528
+ rendered += 1;
529
+ bytes += html.length;
530
+ cardDigests.push({ cardType, label, source: 'sample', hidden: sample.hidden === true, text: htmlDigest(html) });
531
+ // 历史态是必验状态(只读、动作禁用):只验默认态会漏掉整类分支。
532
+ if (label === 'sampleData') {
533
+ try {
534
+ const historyHtml = staticRender.render(
535
+ harness.wrap(React.createElement(Component, { data, cardId: `evidence-history-${cardType}`, isHistory: true, actionTokens: {} })),
536
+ );
537
+ if (!historyHtml.trim()) {
538
+ errors.push({ step: 'render', file: sourceFile, id: 'card-state-empty', message: `卡片 ${cardType} 历史态渲染为空`, fix: '历史态不要返回空树(用 isHistory 只禁用动作,不隐藏内容)', recipe: 'card' });
539
+ } else {
540
+ historyRendered += 1;
541
+ }
542
+ } catch (error) {
543
+ errors.push({ step: 'render', file: sourceFile, id: 'card-state-failed', message: `卡片 ${cardType} 历史态渲染抛错:${error?.message ?? error}`, fix: '历史态分支(isHistory)按报错栈修', recipe: 'card' });
544
+ }
545
+ }
546
+ if (html.trim() === '') {
547
+ errors.push({
548
+ step: 'render',
549
+ id: 'card-render-empty',
550
+ message: `卡片 ${cardType} ${label} 渲染为空`,
551
+ fix: '组件返回了空树;检查数据字段与条件分支',
552
+ recipe: 'card',
553
+ });
554
+ }
555
+ } catch (error) {
556
+ errors.push({
557
+ step: 'render',
558
+ file: sourceFile,
559
+ id: 'card-render-failed',
560
+ message: `卡片 ${cardType} ${label} 渲染抛错:${error?.message ?? error}`,
561
+ fix: '按报错栈修组件;数据形状以服务端 dataSchema 为准',
562
+ recipe: 'card',
563
+ });
564
+ }
565
+ }
566
+ }
567
+
568
+ for (const instance of scenarioInstances) {
569
+ const Component = components[instance.cardType];
570
+ if (!Component) continue;
571
+ try {
572
+ const html = renderToStaticMarkup(
573
+ harness.wrap(
574
+ React.createElement(Component, {
575
+ data: instance.data,
576
+ cardId: `evidence-scenario-${instance.cardType}-${instance.step}`,
577
+ isHistory: false,
578
+ actionTokens: {},
579
+ }),
580
+ ),
581
+ );
582
+ rendered += 1;
583
+ bytes += html.length;
584
+ cardDigests.push({ cardType: instance.cardType, label: `${instance.file}#${instance.step}`, source: 'scenario', text: htmlDigest(html) });
585
+ } catch (error) {
586
+ errors.push({
587
+ step: 'render',
588
+ file: instance.file,
589
+ id: 'scenario-card-render-failed',
590
+ message: `${instance.file} #${instance.step} 的 ${instance.cardType} 实例渲染抛错:${error?.message ?? error}`,
591
+ fix: '按报错栈修组件;数据形状以服务端 dataSchema 为准',
592
+ recipe: 'card',
593
+ });
594
+ }
595
+ }
596
+
597
+ 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() });
598
+ }
599
+
600
+ // ── 4. scenarios ────────────────────────────────────────────────────
601
+ async function checkScenarios() {
602
+ const started = performance.now();
603
+ if (!withScenarios) {
604
+ notRun.push('scenarios');
605
+ steps.push({ name: 'scenarios', ok: true, ms: 0, skipped: true });
606
+ return;
607
+ }
608
+ if (!existsSync(path.join(appDir, 'scenarios'))) {
609
+ notRun.push('scenarios');
610
+ steps.push({ name: 'scenarios', ok: true, ms: Math.round(performance.now() - started), scenarios: 0, skipped: true });
611
+ return;
612
+ }
613
+ if (!registryServer) {
614
+ steps.push({ name: 'scenarios', ok: false, ms: Math.round(performance.now() - started) });
615
+ return;
616
+ }
617
+ try {
618
+ const lib = await vite.ssrLoadModule('/@fs' + path.join(appDir, 'apps/server/scripts/scenario-lib.mjs'));
619
+ const files = lib.resolveScenarioFiles(appDir, []);
620
+ if (files.length === 0) {
621
+ notRun.push('scenarios');
622
+ steps.push({ name: 'scenarios', ok: true, ms: Math.round(performance.now() - started), scenarios: 0, skipped: true });
623
+ return;
624
+ }
625
+ const result = await lib.runScenarios({ appDir, registry: { ...registryServer, cards: mergedMetas }, files });
626
+ scenarioResults = result.results;
627
+ scenarioInstances = result.instances ?? [];
628
+ for (const item of result.results) {
629
+ for (const line of item.failures) {
630
+ errors.push({ step: 'scenarios', id: 'scenario-failed', file: item.file, message: line, fix: '按失败断言修工具/动作;期望值只写稳定字段', recipe: 'verify' });
631
+ }
632
+ }
633
+ const totalSteps = result.results.reduce((sum, item) => sum + item.steps, 0);
634
+ steps.push({ name: 'scenarios', ok: result.ok, ms: Math.round(performance.now() - started), files: result.scenarios, steps: totalSteps, passed: result.ok ? totalSteps : undefined });
635
+ } catch (error) {
636
+ fail('scenarios', [{ message: `场景执行失败:${error?.message ?? error}`, fix: '检查 scenarios/*.json 格式与工具 id', recipe: 'verify' }]);
637
+ }
638
+ }
639
+
640
+ // ── 5. 验收项与裁决(V1–V3) ─────────────────────────────────────
641
+ function readJsonc(file) {
642
+ const raw = readFileSync(file, 'utf8')
643
+ .replace(/\/\*[\s\S]*?\*\//g, '')
644
+ .replace(/(^|[^:])\/\/[^\n]*/g, '$1')
645
+ .replace(/,\s*([}\]])/g, '$1');
646
+ return JSON.parse(raw);
647
+ }
648
+
649
+ /**
650
+ * 模块声明面(C3):`modules/<id>/tbox.module.json` 的 declare.tools/cards/actions。
651
+ * 生成 registry 的 tools/cards 只含应用目录;模块能力在运行时由模块 register 装配,
652
+ * 能力图必须把它们算进来,否则 profile/mall 应用的缺口会永远显示「缺工具」。
653
+ */
654
+ function moduleDeclaredSurface(appDir) {
655
+ const surface = { tools: new Set(), cards: new Set(), actions: new Set() };
656
+ const root = path.join(appDir, 'modules');
657
+ if (!existsSync(root)) return surface;
658
+ for (const name of readdirSync(root)) {
659
+ const file = path.join(root, name, 'tbox.module.json');
660
+ if (!existsSync(file)) continue;
661
+ try {
662
+ // tbox.module.json 是严格 JSON:直接 parse,避免 readJsonc 的注释剥离误伤字符串
663
+ const declare = JSON.parse(readFileSync(file, 'utf8')).declare ?? {};
664
+ for (const tool of declare.tools ?? []) surface.tools.add(typeof tool === 'string' ? tool : tool?.id);
665
+ for (const card of declare.cards ?? []) surface.cards.add(typeof card === 'string' ? card : card?.cardType);
666
+ for (const action of declare.actions ?? []) surface.actions.add(typeof action === 'string' ? action : action?.id);
667
+ } catch {
668
+ // 模块清单坏掉由 build 扫描器报错;这里只做能力图,不重复报
669
+ }
670
+ }
671
+ for (const set of [surface.tools, surface.cards, surface.actions]) set.delete(undefined);
672
+ return surface;
673
+ }
674
+
675
+ function gateVerdict() {
676
+ const file = ['scenarios/acceptance.jsonc', 'scenarios/acceptance.json'].map((name) => path.join(appDir, name)).find((name) => existsSync(name));
677
+ const doc = file ? readJsonc(file) : {};
678
+ const items = doc.items ?? [];
679
+ const acceptanceRaw = file ? readFileSync(file, 'utf8') : '';
680
+ const acceptanceHash = acceptanceRaw ? createHash('sha256').update(acceptanceRaw).digest('hex').slice(0, 16) : null;
681
+ const acceptanceIds = items.map((item) => String(item.id));
682
+ let prevGate;
683
+ try {
684
+ prevGate = JSON.parse(readFileSync(path.join(appDir, '.tbox/evidence/gate.json'), 'utf8'));
685
+ } catch {
686
+ prevGate = undefined;
687
+ }
688
+ const deferredByLane = items.filter((item) => item.lane === 'browser' || item.lane === 'model');
689
+ const scenarioItems = items.filter((item) => (item.by ?? 'scenario') === 'scenario' && !item.lane);
690
+ // E1:review 改名为 handoff(旧名保留为别名)。名字本身不再邀请复审。
691
+ // E2:证据策略声明本任务允许验证到哪一级;handoff 只接受策略判为不可验的维度。
692
+ const policyResolution = resolvePolicy({
693
+ platformPolicy: process.env.TBOX_POLICY,
694
+ docPolicy: doc.policy,
695
+ docPolicyReason: doc.policyReason,
696
+ });
697
+ const policy = policyResolution.policy;
698
+ if (policyResolution.downgradeIgnored) {
699
+ warn('policy-downgrade-ignored', 'acceptance.jsonc 把档位降到 static 但没写 policyReason:按用户意图不明处理,本轮按 visual 执行', {
700
+ fix: '补 policyReason(用户原话),或用 TBOX_POLICY 由平台注入档位',
701
+ recipe: 'verify',
702
+ });
703
+ }
704
+ if (doc.policy && !['static', 'visual', 'flow'].includes(doc.policy)) {
705
+ warn('policy-unknown', `scenarios/acceptance.jsonc 的 policy=${JSON.stringify(doc.policy)} 不支持(static / visual / flow),按 static 处理`, {
706
+ fix: '改成三档之一,或删掉 policy 使用缺省 static',
707
+ recipe: 'verify',
708
+ });
709
+ }
710
+ const handoffItems = items.filter((item) => (item.by === 'handoff' || item.by === 'review') && !item.lane);
711
+ /** ui.* 被标 handoff 时的一句出口提示:故事板只证明渲染与几何,不判美丑。 */
712
+ const uiHandoffHint = () => {
713
+ const uiItems = handoffItems.filter((item) => String(item.id).startsWith('ui.'));
714
+ if (uiItems.length === 0 || policy === 'static') return '';
715
+ return ';其中 ' + uiItems.map((item) => item.id).join('、') + ' 可由故事板证明:改成 by: "storyboard" 并写 frames(如 ["card:*@320"])';
716
+ };
717
+ const originByFile = new Map();
718
+ for (const result of scenarioResults) {
719
+ let origin = 'spec';
720
+ try {
721
+ const parsed = JSON.parse(readFileSync(result.file, "utf8"));
722
+ if (parsed && parsed.origin) origin = String(parsed.origin);
723
+ } catch { origin = 'spec'; }
724
+ originByFile.set(result.file, origin);
725
+ }
726
+ const { covered, declared: declaredCovered } = coverageSets(scenarioResults, originByFile);
727
+ // D1:界面类验收项由故事板证明「渲染出来了且没有几何错误」——与场景覆盖分列,不混算。
728
+ const board = storyboardCoverage(items, readStoryboardResult().storyboard, policy);
729
+ // 策略允许场景验证的项不能借 handoff 绕过:没有 reason 的 handoff 计入 incomplete。
730
+ // 旧名 review 不要求 reason(历史应用平滑);新名 handoff 必须写清为什么当前策略验不了。
731
+ const handoffWithoutReason = handoffItems.filter((item) => item.by === 'handoff' && !item.reason);
732
+ const uncovered = [
733
+ ...scenarioItems.filter((item) => !covered.has(item.id)).map((item) => item.id),
734
+ ...handoffWithoutReason.map((item) => item.id),
735
+ ...[...board.failed.keys()],
736
+ ];
737
+ if (handoffWithoutReason.length > 0) {
738
+ warn('handoff-misuse', `handoff 项缺 reason:${handoffWithoutReason.map((item) => item.id).join('、')}(能由场景判定的项不要标 handoff)`, {
739
+ fix: '补一条场景并写 covers,或给 handoff 项加 reason 说明为什么当前策略验不了',
740
+ recipe: 'verify',
741
+ });
742
+ }
743
+ const hasSurface = (registryServer?.tools?.length ?? 0) + (registryServer?.actions?.length ?? 0) > 0;
744
+
745
+ // C3 能力图:验收项上的 tool/action/card 名字键声明「这件事经由什么实现」。
746
+ // 声明了但还没注册 = 缺口;门禁把它列出来,完成的定义从第三分钟起就存在。
747
+ const declaredTools = new Set(items.map((item) => item.tool).filter(Boolean));
748
+ const declaredActions = new Set(items.map((item) => item.action).filter(Boolean));
749
+ const declaredCards = new Set(
750
+ items.flatMap((item) => (Array.isArray(item.on) ? item.on : item.card ? [item.card] : [])).filter(Boolean),
751
+ );
752
+ const registeredTools = new Set((registryServer?.tools ?? []).map((tool) => tool.id));
753
+ const registeredActions = new Set(Object.keys(registryServer?.actions ?? {}));
754
+ const registeredCards = new Set(Object.keys(registryServer?.cards ?? {}));
755
+ const moduleSurface = moduleDeclaredSurface(appDir);
756
+ for (const id of moduleSurface.tools) registeredTools.add(id);
757
+ for (const id of moduleSurface.actions) registeredActions.add(id);
758
+ for (const id of moduleSurface.cards) registeredCards.add(id);
759
+ const missingTools = [...declaredTools].filter((id) => !registeredTools.has(id));
760
+ const missingActions = [...declaredActions].filter((id) => !registeredActions.has(id));
761
+ const missingCards = [...declaredCards].filter((id) => !registeredCards.has(id));
762
+ const capabilities = {
763
+ declared: { tools: declaredTools.size, actions: declaredActions.size, cards: declaredCards.size },
764
+ missing: { tools: missingTools, actions: missingActions, cards: missingCards },
765
+ };
766
+ // 自有工具 = 注册表里的工具减去模块声明的(模块工具不算「你自己写的」)。
767
+ const ownToolCount = Math.max(0, (registryServer?.tools?.length ?? 0) - moduleSurface.tools.length);
768
+ const missingCapabilityText = [
769
+ ...missingTools.map((id) => `工具 ${id}`),
770
+ ...missingActions.map((id) => `动作 ${id}`),
771
+ ...missingCards.map((id) => `卡片 ${id}`),
772
+ ];
773
+
774
+ // 每个验收维度一个状态:已验证 / 未运行(带原因)。验不了的进 handoff,不留作疑问。
775
+ const scenarioSteps = scenarioResults.reduce((sum, item) => sum + (item.steps ?? 0), 0);
776
+ const coverage = {
777
+ structure: '已验证:生成 / 类型 / 结构 / 原语',
778
+ logic:
779
+ scenarioResults.length > 0
780
+ ? `已验证:${scenarioResults.length} 个场景 / ${scenarioSteps} 步 / ${covered.size} 项`
781
+ : '未运行:没有场景(先按 verify.md 写一条)',
782
+ storyboard: policy === 'static'
783
+ ? '未运行:当前策略 static'
784
+ : board.covered.size > 0
785
+ ? `已验证:${board.covered.size} 个界面项由故事板覆盖`
786
+ : '未运行:没有 by: "storyboard" 的验收项',
787
+ render:
788
+ cardDigests.length > 0
789
+ ? `已验证:${cardDigests.length} 张卡 / ${scenarioInstances.length + cardDigests.length} 份样例`
790
+ : '未运行:没有卡片',
791
+ visual: policy === 'static' ? '未运行:当前策略 static(任务要求快速交付,不起浏览器)' : '未运行:本轮未执行浏览器(需要 --visual / dev server)',
792
+ routing: policy === 'flow' ? '未运行:本轮未跑模型级验收' : '未运行:当前策略不要求模型级验收',
793
+ };
794
+ const handoff = [
795
+ ...handoffItems.map((item) => `${item.id} ${item.text ?? ''}`.trim()),
796
+ ...[...board.handoff.entries()].map(([id, reason]) => `${id}(故事板未覆盖:${reason})`),
797
+ ];
798
+
799
+ let verdict;
800
+ let next;
801
+ if (errors.length > 0) {
802
+ verdict = 'failing';
803
+ next = `先修第一个失败项:${errors[0].message}${errors[0].fix ? `(${errors[0].fix})` : ''}`;
804
+ } else if (!file) {
805
+ verdict = hasSurface ? 'unspecified' : 'deliverable';
806
+ next = hasSurface
807
+ ? '先把需求拆成 scenarios/acceptance.jsonc 的验收项(id + text),再让场景用 covers 声明覆盖'
808
+ : '交付条件已满足:总结并结束。不要继续复审或打磨。';
809
+ } else if (ownToolCount === 0 && items.length > 0) {
810
+ // 首验前移:验收已写、还没有自己的工具时,next 直接给第一项竖切的命令(不再只说「补文件」)。
811
+ const firstId = String(items[0].id ?? '').toLowerCase().replace(/[^a-z0-9-]+/g, '-').slice(0, 32) || 'first';
812
+ verdict = 'incomplete';
813
+ next = `先做第一项竖切:pnpm exec tbox-app new feature ${firstId} --view(工具 + 视图卡 + 场景),然后 pnpm check:fast`;
814
+ } else if (missingCapabilityText.length > 0) {
815
+ verdict = 'incomplete';
816
+ next = `能力图还缺:${missingCapabilityText.join('、')};先在 acceptance.jsonc 声明,再补对应文件(new tool / new card / new action)`;
817
+ } else if (uncovered.length > 0) {
818
+ verdict = 'incomplete';
819
+ next = `未覆盖验收项:${uncovered.join('、')};补场景并在 covers 里登记,或给确实无法自动判定的项标 by: "handoff" 并写 reason`;
820
+ } else {
821
+ verdict = 'deliverable';
822
+ const boardHint = uiHandoffHint();
823
+ next =
824
+ handoff.length > 0
825
+ ? `把 handoff 的 ${handoff.length} 项原样写进交付说明,然后结束。这些项在当前策略(${policy})下无法验证,继续读代码不会改变它们的状态${boardHint}。`
826
+ : '交付条件已满足:总结并结束。不要继续复审或打磨。';
827
+ }
828
+
829
+ // 验收变更:从「哈希变了」升级成「哪一项怎么变」,并跨轮累计。
830
+ const digest = {};
831
+ for (const item of items) {
832
+ digest[String(item.id)] = {
833
+ text: createHash('sha256').update(String(item.text ?? '')).digest('hex').slice(0, 12),
834
+ handoff: item.by === 'handoff' || item.by === 'review',
835
+ coveredBy: [],
836
+ };
837
+ }
838
+ // 覆盖关系与「这次场景过没过」无关:场景失败由裁决本身报,不能同时把验收项记成被弱化。
839
+ for (const result of scenarioResults) {
840
+ for (const id of result.covers ?? []) {
841
+ if (digest[id]) digest[id].coveredBy.push(scenarioKey(appDir, result.file));
842
+ }
843
+ }
844
+ // 验收文件整份缺省(还没写)不算「删除了全部验收项」:没有基线就没有弱化可谈。
845
+ const acceptanceChange = file ? acceptanceChangesOf(prevGate, digest) : { changes: [], cumulative: Array.isArray(prevGate?.acceptanceChanges) ? prevGate.acceptanceChanges : [] };
846
+ const acceptance = acceptanceDrift(prevGate, acceptanceHash, acceptanceIds);
847
+ const drift = [...acceptance.drift];
848
+ const weakening = summarizeAcceptanceChanges(acceptanceChange.cumulative);
849
+ if (weakening.length > 0) {
850
+ warn('acceptance-drift', '验收变更:' + weakening.slice(0, 5).join('、') + ';若是用户要求,在交付答复中说明原因,否则恢复', {
851
+ fix: '把改动改回去,或在交付说明里写清是用户要求',
852
+ recipe: 'verify',
853
+ });
854
+ }
855
+ const scenarioHashes = {};
856
+ const failedScenarios = [];
857
+ for (const result of scenarioResults) {
858
+ try {
859
+ const relative = scenarioKey(appDir, result.file);
860
+ scenarioHashes[relative] = createHash("sha256").update(readFileSync(result.file, "utf8")).digest("hex").slice(0, 16);
861
+ } catch { /* 读失败不影响裁决 */ }
862
+ if (!result.ok) failedScenarios.push(path.relative(appDir, result.file));
863
+ }
864
+ // 场景删除也是漂移:失败后删场景会让门禁「变绿」,必须让用户看见。
865
+ for (const item of scenarioDrift(prevGate, scenarioHashes)) {
866
+ drift.push(item);
867
+ warn('scenario-drift', item.detail, { fix: '在交付说明里写清为什么删场景', recipe: 'verify' });
868
+ }
869
+ if (prevGate && prevGate.scenarioHashes) {
870
+ for (const [scenarioFile, hash] of Object.entries(scenarioHashes)) {
871
+ const prevHash = prevGate.scenarioHashes[scenarioFile];
872
+ if (prevHash && prevHash !== hash && Array.isArray(prevGate.failedScenarios) && prevGate.failedScenarios.includes(scenarioFile)) {
873
+ const detail = '失败后改了场景期望:' + scenarioFile;
874
+ drift.push({ kind: 'expect', detail });
875
+ warn('expect-drift', detail, { fix: '在交付说明里写清为什么改期望', recipe: 'verify' });
876
+ }
877
+ }
878
+ }
879
+
880
+ // 软闩:交付后再改内容 -> reopened(只降级,不阻断)。
881
+ let contentHash = null;
882
+ try { contentHash = hashSourceTree(appDir).hash; } catch { contentHash = null; }
883
+ if (shouldReopen(prevGate, verdict, contentHash)) {
884
+ verdict = 'reopened';
885
+ next = '交付后内容有改动:重跑一次 check:fast 确认,再交付(不做硬停)。';
886
+ }
887
+
888
+ // 能力偏离:与 create 的出厂基线快照比(画像覆盖已被快照吸收,不会误判成 agent 偏离)。
889
+ let capability = { skipped: true, reason: '缺出厂基线快照', items: [] };
890
+ try {
891
+ const factoryFile = path.join(appDir, '.tbox/factory/chat.json');
892
+ const actualFile = path.join(appDir, 'config/chat.json');
893
+ if (existsSync(factoryFile) && existsSync(actualFile)) {
894
+ const factoryDoc = JSON.parse(readFileSync(factoryFile, 'utf8'));
895
+ const actualDoc = JSON.parse(readFileSync(actualFile, 'utf8'));
896
+ capability = capabilityDrift({ factory: factoryDoc.chat ?? {}, actual: actualDoc });
897
+ for (const item of capability.items) {
898
+ warn('capability-drift', `能力偏离出厂:${item.key} ${String(item.factory)} → ${String(item.actual)}(${item.change})`, {
899
+ fix: item.change === 'user-intent'
900
+ ? '恢复出厂值;能力偏离会进交付包'
901
+ : '在交付说明的「偏离出厂」里声明',
902
+ recipe: 'shell',
903
+ });
904
+ }
905
+ }
906
+ } catch { /* 快照损坏不阻断裁决 */ }
907
+
908
+ // 出厂模块集偏离:删掉出厂模块(例如默认的支付模块)在会话里看得见,不阻断。
909
+ let moduleDrift = { skipped: true, reason: '缺出厂模块快照', items: [] };
910
+ try {
911
+ const factoryFile = path.join(appDir, '.tbox/factory/modules.json');
912
+ const actualFile = path.join(appDir, '.tbox/default-modules.json');
913
+ if (existsSync(factoryFile)) {
914
+ const actualDoc = existsSync(actualFile) ? JSON.parse(readFileSync(actualFile, 'utf8')) : [];
915
+ moduleDrift = defaultModuleDrift({ factory: JSON.parse(readFileSync(factoryFile, 'utf8')), actual: actualDoc });
916
+ for (const item of moduleDrift.items) {
917
+ warn('module-drift', '出厂模块偏离:' + item.key + (item.kind === 'module-removed' ? ' 已移除' : ' 是新增的'), {
918
+ fix: '删掉/加上是用户的决定时,在交付说明的「偏离出厂」里写清楚;否则 module add 加回来',
919
+ recipe: 'shell',
920
+ });
921
+ }
922
+ }
923
+ } catch { /* 快照损坏不阻断裁决 */ }
924
+
925
+ const delivery = {
926
+ acceptanceChanges: acceptanceChange.cumulative,
927
+ acceptanceChangeSummary: weakening,
928
+ capabilityDrift: capability.items,
929
+ moduleDrift: moduleDrift.items,
930
+ capabilityBaseline: capability.skipped ? { skipped: true, reason: capability.reason } : { skipped: false },
931
+ trace: items.map((item) => ({
932
+ id: item.id,
933
+ text: item.text ?? '',
934
+ covered: covered.has(item.id),
935
+ declared: declaredCovered.has(item.id),
936
+ ...(item.lane ? { lane: item.lane } : {}),
937
+ })),
938
+ facts: cardFacts,
939
+ drift,
940
+ deferred: [
941
+ ...deferredByLane.map((item) => ({ id: item.id, lane: item.lane, reason: '验收项声明为 ' + item.lane + ' 车道' })),
942
+ ...experienceItems.filter((item) => item.status === "deferred").map((item) => ({ id: item.id, lane: item.lane, reason: item.detail })),
943
+ ],
944
+ };
945
+ if (verdict === 'deliverable' && delivery.deferred.length > 0) {
946
+ // 界面项被标 handoff 时给一次可执行出口:故事板能证明「渲染出来且没几何错误」。
947
+ const boardHint = uiHandoffHint();
948
+ next = '把 deferred 的 ' + delivery.deferred.length + ' 项如实写进交付说明,然后结束' + boardHint + '。';
949
+ }
950
+ const gateFile = path.join(appDir, '.tbox/evidence/gate.json');
951
+ let changedFiles = 0;
952
+ try {
953
+ changedFiles = execFileSync('git', ['status', '--porcelain'], { cwd: appDir, encoding: 'utf8' })
954
+ .split('\n')
955
+ .filter((line) => line.trim() && !line.includes('.tbox/')).length;
956
+ } catch {
957
+ changedFiles = 0;
958
+ }
959
+ const runs = prevGate?.verdict === 'deliverable' ? (prevGate.runs ?? 0) + 1 : 0;
960
+ const sinceDeliverable = prevGate?.verdict === 'deliverable' ? { runs, changedFiles } : undefined;
961
+ try {
962
+ mkdirSync(path.dirname(gateFile), { recursive: true });
963
+ writeFileSync(gateFile, JSON.stringify({
964
+ verdict,
965
+ at: Date.now(),
966
+ changedFiles,
967
+ runs,
968
+ acceptanceHash,
969
+ acceptanceIds,
970
+ acceptanceDigest: digest,
971
+ acceptanceChanges: acceptanceChange.cumulative,
972
+ scenarioHashes,
973
+ failedScenarios,
974
+ contentHash,
975
+ deliveredAt: verdict === 'deliverable' ? (prevGate && prevGate.verdict === 'deliverable' ? (prevGate.deliveredAt ?? Date.now()) : Date.now()) : (prevGate ? prevGate.deliveredAt : undefined),
976
+ }));
977
+ } catch {
978
+ // 只读环境不影响裁决
979
+ }
980
+
981
+ return {
982
+ verdict,
983
+ next,
984
+ policy,
985
+ coverage,
986
+ capabilities,
987
+ handoff,
988
+ acceptance: {
989
+ items: items.length,
990
+ covered: covered.size,
991
+ declared: declaredCovered.size,
992
+ // 故事板覆盖单独计数,不与场景覆盖混算。
993
+ storyboard: board.covered.size,
994
+ // 旧名保留一版(读取方可能仍看 review);新代码用 handoff。
995
+ review: handoffItems.length,
996
+ handoff: handoffItems.length + board.handoff.size,
997
+ uncovered,
998
+ ...(file ? { file: path.relative(appDir, file) } : {}),
999
+ },
1000
+ ...(sinceDeliverable ? { sinceDeliverable } : {}),
1001
+ delivery,
1002
+ };
1003
+ }
1004
+
1005
+ // ── 3.5 渲染与路由的启发式告警(E3) ─────────────────────────────
1006
+ // 交付后最常见的两类复审是「界面看不见」与「模型会不会调用工具」。这里把能机器判断的
1007
+ // 形态问题变成告警(不阻断):空渲染、状态样例渲染完全相同、工具描述缺失/重复。
1008
+ function checkRenderSignals() {
1009
+ const empty = cardDigests.filter((item) => !item.text || item.text.trim().length < 6);
1010
+ if (empty.length > 0) {
1011
+ warn('render-empty', `${empty.length} 份卡片渲染结果为空:${empty.map((item) => `${item.cardType}/${item.label}`).join('、')}`, {
1012
+ fix: '检查组件是否按 cardType 注册、样例数据是否为空',
1013
+ recipe: 'card',
1014
+ });
1015
+ }
1016
+ const byCard = new Map();
1017
+ for (const item of cardDigests) byCard.set(item.cardType, [...(byCard.get(item.cardType) ?? []), item]);
1018
+ for (const [cardType, list] of byCard) {
1019
+ const visible = list.filter((item) => item.hidden !== true);
1020
+ if (visible.length >= 2 && new Set(visible.map((item) => item.text)).size === 1) {
1021
+ warn('render-identical', `${cardType} 的 ${visible.length} 份样例渲染结果完全相同——状态没有真正区分`, {
1022
+ fix: '给不同状态不同的可见内容(状态标签/按钮/提示),或删掉重复样例',
1023
+ recipe: 'card',
1024
+ });
1025
+ }
1026
+ }
1027
+ const tools = registryServer?.tools ?? [];
1028
+ const byDescription = new Map();
1029
+ for (const tool of tools) {
1030
+ const description = String(tool.description ?? '').trim();
1031
+ if (!description) {
1032
+ warn('tool-description-empty', `工具 ${tool.id} 的 description 为空——模型没有依据选择它`, { fix: '写「什么时候用」,不要写「做什么」', recipe: 'tool' });
1033
+ continue;
1034
+ }
1035
+ const duplicate = byDescription.get(description);
1036
+ if (duplicate) {
1037
+ warn('tool-description-duplicate', `工具 ${duplicate} 与 ${tool.id} 的 description 完全相同——模型无法区分`, { fix: '让两个工具的描述各自说明触发场景', recipe: 'tool' });
1038
+ } else {
1039
+ byDescription.set(description, tool.id);
1040
+ }
1041
+ }
1042
+ }
1043
+
1044
+ // ── 4.5 状态覆盖(声明样例 + 场景实例) ──────────────────────────
1045
+ function checkCoverage() {
1046
+ const started = performance.now();
1047
+ const metas = mergedMetas;
1048
+ for (const [cardType, meta] of Object.entries(metas)) {
1049
+ const declared = [
1050
+ meta.sampleData,
1051
+ ...(Array.isArray(meta.samples) ? meta.samples.map((sample) => sample?.data) : []),
1052
+ ];
1053
+ const fromScenarios = scenarioInstances.filter((item) => item.cardType === cardType).map((item) => item.data);
1054
+ const samples = [...declared, ...fromScenarios];
1055
+ const shape = meta.dataSchema?.shape;
1056
+ if (!shape || typeof shape !== 'object') continue;
1057
+ for (const [field, schema] of Object.entries(shape)) {
1058
+ const values = schema?._def?.values;
1059
+ if (!Array.isArray(values) || values.length === 0) continue;
1060
+ const seen = new Set(samples.map((data) => data?.[field]).filter((value) => value !== undefined));
1061
+ const missing = values.filter((value) => !seen.has(value));
1062
+ if (missing.length > 0) {
1063
+ warn('card-sample-coverage', `${cardType}.${field} 的状态 ${JSON.stringify(missing)} 既没有样例也没有场景实例`, {
1064
+ fix: '补一条 samples,或让场景真的走到这个状态(场景实例自动计入覆盖)',
1065
+ recipe: 'card',
1066
+ });
1067
+ }
1068
+ }
1069
+ }
1070
+ steps.push({ name: 'coverage', ok: true, ms: Math.round(performance.now() - started), instances: scenarioInstances.length });
1071
+ }
1072
+
1073
+ // 对比度:纯色令牌静态算 WCAG;var()/color-mix 派生的标 deferred(浏览器车道暂缓)。
1074
+ function parseCssTokens(files) {
1075
+ const values = new Map();
1076
+ for (const file of files) {
1077
+ if (!file || !existsSync(file)) continue;
1078
+ const css = readFileSync(file, 'utf8').replace(/\/\*[\s\S]*?\*\//g, '');
1079
+ for (const match of css.matchAll(/(--tbox-[\w-]+)\s*:\s*([^;]+);/g)) {
1080
+ values.set(match[1], match[2].trim());
1081
+ }
1082
+ }
1083
+ return values;
1084
+ }
1085
+
1086
+ function checkContrast() {
1087
+ const kitDir = path.join(appDir, 'packages/agent-ui-kit');
1088
+ const contractPath = path.join(kitDir, 'src/theme/contract.json');
1089
+ if (!existsSync(contractPath)) return { status: 'deferred', detail: '主题契约不在预期位置' };
1090
+ const contract = JSON.parse(readFileSync(contractPath, 'utf8'));
1091
+ const pairs = contract.pairs ?? [];
1092
+ if (pairs.length === 0) return { status: 'deferred', detail: '没有登记对比度对' };
1093
+ const require = createRequire(path.join(clientDir, 'package.json'));
1094
+ let themePackage = '@tbox.cn/app-theme-tbox';
1095
+ try {
1096
+ // 以装配真源的实际 import 为准(theme use 会改写这一行);找不到再退回依赖清单。
1097
+ const appConfig = readFileSync(path.join(clientDir, 'src/app.config.ts'), 'utf8');
1098
+ const imported = /@tbox\.cn\/app-theme-([a-z0-9-]+)\/index\.css/.exec(appConfig);
1099
+ if (imported) {
1100
+ themePackage = '@tbox.cn/app-theme-' + imported[1];
1101
+ } else {
1102
+ const clientPkg = JSON.parse(readFileSync(path.join(clientDir, 'package.json'), 'utf8'));
1103
+ const installed = Object.keys({ ...(clientPkg.dependencies ?? {}), ...(clientPkg.devDependencies ?? {}) }).filter((name) => name.startsWith('@tbox.cn/app-theme-')).sort();
1104
+ if (installed[0]) themePackage = installed[0];
1105
+ }
1106
+ } catch { /* 用出厂主题 */ }
1107
+ let themeCss;
1108
+ try { themeCss = require.resolve(themePackage + '/index.css'); } catch { themeCss = undefined; }
1109
+ const tokens = parseCssTokens([
1110
+ path.join(kitDir, 'src/theme/tokens.css'),
1111
+ themeCss,
1112
+ path.join(clientDir, 'src/styles/brand.css'),
1113
+ ]);
1114
+ const resolved = new Map();
1115
+ for (const [key, raw] of tokens) {
1116
+ const color = parseColor(raw);
1117
+ if (color) resolved.set(key, color);
1118
+ }
1119
+ const failures = [];
1120
+ const deferred = [];
1121
+ for (const pair of pairs) {
1122
+ const fg = resolved.get(pair.fg);
1123
+ const bg = resolved.get(pair.bg);
1124
+ if (!fg || !bg) { deferred.push(pair.fg + ' on ' + pair.bg); continue; }
1125
+ const ratio = contrastRatio(fg, bg);
1126
+ if (ratio < pair.min) failures.push(pair.fg + ' on ' + pair.bg + ' = ' + ratio.toFixed(2) + ' < ' + pair.min);
1127
+ }
1128
+ if (failures.length > 0) return { status: 'fail', detail: failures.join(';') };
1129
+ if (deferred.length > 0) return { status: 'deferred', detail: '无法静态解析:' + deferred.join(';') };
1130
+ return { status: 'pass', detail: pairs.length + ' 对全部达到阈值' };
1131
+ }
1132
+
1133
+ // 视图卡的静态密度:版式归平台后高度是视图树的函数,不用开浏览器。
1134
+ async function checkCardDensity() {
1135
+ if (!registryServer) return { available: false, worst: 0, violations: [], reason: '没有服务端 registry' };
1136
+ let contracts;
1137
+ try { contracts = await vite.ssrLoadModule('@tbox.cn/app-contracts'); } catch { return { available: false, worst: 0, violations: [], reason: '契约模块加载失败' }; }
1138
+ const estimate = contracts.estimateCardHeight;
1139
+ if (typeof estimate !== 'function') return { available: false, worst: 0, violations: [], reason: '契约未导出 estimateCardHeight' };
1140
+ let worst = 0;
1141
+ const violations = [];
1142
+ for (const [cardType, meta] of Object.entries(mergedMetas)) {
1143
+ if (!meta || !meta.view) continue;
1144
+ const samples = [meta.sampleData, ...(Array.isArray(meta.samples) ? meta.samples.map((sample) => sample && sample.data) : [])];
1145
+ for (const data of samples) {
1146
+ if (!data) continue;
1147
+ try {
1148
+ const height = estimate(data);
1149
+ if (height > worst) worst = height;
1150
+ if (height > 633) violations.push(cardType + ' ' + height + 'px');
1151
+ } catch { /* 形状不对由 render 报 */ }
1152
+ }
1153
+ }
1154
+ return { available: true, worst, violations };
1155
+ }
1156
+
1157
+ // ── 4.8 体验不变量(登记在 checks.json 的 experience 族)──────────────
1158
+ // 只跑不需要浏览器的车道(静态 / 进程内);浏览器与模型车道写 deferred,由平台补验。
1159
+ /** 目录树最新 mtime(跳过构建产物与依赖);目录不存在返回 0。 */
1160
+ /** 故事板结果 + 过期原因(帧早于卡片/品牌改动时按未运行处理,不拿旧图冒充当前)。 */
1161
+ function readStoryboardResult() {
1162
+ const file = path.join(appDir, '.tbox/evidence/storyboard.json');
1163
+ if (!existsSync(file)) return { storyboard: null, stale: '' };
1164
+ try {
1165
+ // 与 storyboard 的缓存键同源:卡片、品牌层、壳配置、kit、模块卡任一变了,旧图都按未运行处理。
1166
+ const inputs = evidenceInputFiles(appDir);
1167
+ const newest = inputs.reduce((latest, file) => {
1168
+ try {
1169
+ return Math.max(latest, statSync(file).mtimeMs);
1170
+ } catch {
1171
+ return latest;
1172
+ }
1173
+ }, 0);
1174
+ const storyboard = JSON.parse(readFileSync(file, 'utf8'));
1175
+ if (Number(storyboard.protocolVersion ?? 1) > 1) {
1176
+ return { storyboard: null, stale: '故事板协议版本 ' + storyboard.protocolVersion + ' 高于门禁支持的 1(升级模板)' };
1177
+ }
1178
+ if (statSync(file).mtimeMs + 1000 < newest) return { storyboard: null, stale: '故事板早于最近改动(重跑 pnpm storyboard)' };
1179
+ return { storyboard, stale: '' };
1180
+ } catch {
1181
+ return { storyboard: null, stale: '' };
1182
+ }
1183
+ }
1184
+
1185
+ function newestMtime(root) {
1186
+ let newest = 0;
1187
+ const walk = (dir) => {
1188
+ let entries;
1189
+ try {
1190
+ entries = readdirSync(dir, { withFileTypes: true });
1191
+ } catch {
1192
+ return;
1193
+ }
1194
+ for (const entry of entries) {
1195
+ if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name === '.git') continue;
1196
+ const full = path.join(dir, entry.name);
1197
+ if (entry.isDirectory()) walk(full);
1198
+ else {
1199
+ try {
1200
+ newest = Math.max(newest, statSync(full).mtimeMs);
1201
+ } catch { /* 竞态删除忽略 */ }
1202
+ }
1203
+ }
1204
+ };
1205
+ walk(root);
1206
+ return newest;
1207
+ }
1208
+
1209
+ async function checkExperience(cssBytes) {
1210
+ const started = performance.now();
1211
+ const items = [];
1212
+ const push = (id, lane, status, detail) => items.push({ id, lane, status, detail });
1213
+
1214
+ // 登记表是检查项元数据的真源:level 决定阻断/告警,lane 决定车道,since 决定旧应用是否跳过。
1215
+ const checkMeta = new Map();
1216
+ try {
1217
+ const doc = JSON.parse(readFileSync(path.join(appDir, 'scripts/checks.json'), 'utf8'));
1218
+ for (const check of doc.checks ?? []) checkMeta.set(check.id, check);
1219
+ } catch { /* 缺登记表时按 error 处理 */ }
1220
+ const levelOf = (id) => checkMeta.get(id)?.level === 'warning' ? 'warning' : 'error';
1221
+ let appVersion = '';
1222
+ try {
1223
+ appVersion = JSON.parse(readFileSync(path.join(appDir, '.tbox/app.json'), 'utf8')).templateVersion ?? '';
1224
+ } catch { /* 版本未知 → 不做 since 过滤 */ }
1225
+
1226
+ // 静态车道走执行器:新增检查只需 checks.json 一行 + experience-checks.mjs 一段。
1227
+ // 顺序按执行器声明(与历史 items 顺序一致),只跑登记为 phase=static 的 id。
1228
+ const staticIds = Object.keys(STATIC_CHECKS).filter((id) => checkMeta.get(id)?.phase === 'static');
1229
+ for (const item of runStaticChecks({ appDir, clientDir }, staticIds)) {
1230
+ push(item.id, checkMeta.get(item.id)?.lane ?? 'static', item.status, item.detail);
1231
+ }
1232
+ // 进程内车道走执行器:上下文中转,新增检查只需 checks.json + in-process-checks.mjs。
1233
+ const inProcessIds = Object.keys(IN_PROCESS_CHECKS).filter((id) => checkMeta.get(id)?.phase === 'in-process');
1234
+ const inProcessContext = {
1235
+ cssBytes,
1236
+ registryServer: { ...registryServer, cards: mergedMetas },
1237
+ registryClient: { ...registryClient, cards: mergedComponents },
1238
+ historyRendered,
1239
+ checkContrast,
1240
+ checkCardDensity,
1241
+ warn,
1242
+ };
1243
+ for (const item of await runInProcessChecks(inProcessContext, inProcessIds)) {
1244
+ push(item.id, checkMeta.get(item.id)?.lane ?? 'in-process', item.status, item.detail);
1245
+ }
1246
+
1247
+ // 档位决定车道:static 时布局/运行时一律 not-run,即使本机有探针结果。
1248
+ let experiencePolicy = 'visual';
1249
+ let acceptanceDoc = {};
1250
+ try {
1251
+ acceptanceDoc = readJsonc(path.join(appDir, 'scenarios/acceptance.jsonc'));
1252
+ } catch { /* 缺验收文件不阻断档位解析 */ }
1253
+ experiencePolicy = resolvePolicy({
1254
+ platformPolicy: process.env.TBOX_POLICY,
1255
+ docPolicy: acceptanceDoc.policy,
1256
+ docPolicyReason: acceptanceDoc.policyReason,
1257
+ }).policy;
1258
+
1259
+ // 布局车道:探针结果在 .tbox/evidence/shell.json(pnpm probe:shell);没有就如实 not-run。
1260
+ let shellResult = null;
1261
+ let shellStale = '';
1262
+ try {
1263
+ const shellFile = path.join(appDir, '.tbox/evidence/shell.json');
1264
+ if (existsSync(shellFile)) {
1265
+ // 探针结果早于壳/主题/kit 的最近改动 → 过期,按未运行处理(不拿旧结果冒充当前)。
1266
+ const inputs = [
1267
+ 'config/chat.json',
1268
+ 'apps/client/src/styles/brand.css',
1269
+ 'apps/client/src/styles/tokens.css',
1270
+ ].map((rel) => path.join(appDir, rel)).filter((file) => existsSync(file));
1271
+ // 整个 kit 源码都算探针输入(组件改动不只发生在 ChatPage/ChatInput);壳源/主题接线/依赖变更同样算。
1272
+ const newest = Math.max(
1273
+ ...inputs.map((file) => statSync(file).mtimeMs),
1274
+ newestMtime(path.join(appDir, 'packages/agent-ui-kit/src')),
1275
+ newestMtime(path.join(appDir, 'apps/client/src')),
1276
+ statSync(path.join(appDir, 'apps/client/package.json')).mtimeMs,
1277
+ 0,
1278
+ );
1279
+ shellResult = JSON.parse(readFileSync(shellFile, 'utf8'));
1280
+ // 协议版本高于门禁:不认识的结果不能当通过,也不能当失败——记 skip。
1281
+ if (Number(shellResult.protocolVersion ?? 1) > 1) {
1282
+ shellStale = '探针协议版本 ' + shellResult.protocolVersion + ' 高于门禁支持的 1(升级模板)';
1283
+ shellResult = null;
1284
+ }
1285
+ if (statSync(shellFile).mtimeMs + 1000 < newest) shellStale = '探针结果早于最近改动(重跑 pnpm probe:shell)';
1286
+ }
1287
+ } catch { shellResult = null; }
1288
+ if (shellStale) shellResult = null;
1289
+
1290
+ const { storyboard, stale: storyboardStale } = readStoryboardResult();
1291
+ // 探针车道走合并器:只按登记 id 取结果,档位/过期/协议语义在模块里。
1292
+ const probeIds = Object.keys(PROBE_CHECKS).filter((id) => checkMeta.get(id)?.phase === 'probe');
1293
+ for (const item of mergeProbeChecks({ probe: shellResult, ids: probeIds, policy: experiencePolicy, stale: shellStale })) {
1294
+ push(item.id, checkMeta.get(item.id)?.lane ?? item.lane, item.status, item.detail);
1295
+ }
1296
+
1297
+ const storyboardIds = Object.keys(STORYBOARD_CHECKS).filter((id) => checkMeta.get(id)?.phase === 'probe');
1298
+ const cardCount = Object.keys(mergedMetas).length;
1299
+ for (const item of mergeStoryboardChecks({ storyboard, ids: storyboardIds, policy: experiencePolicy, stale: storyboardStale, cardCount })) {
1300
+ push(item.id, checkMeta.get(item.id)?.lane ?? item.lane, item.status, item.detail);
1301
+ }
1302
+
1303
+ push('flow.persist', 'in-process', 'deferred', '需要重启探针(未接入)');
1304
+
1305
+ // 登记面与实现面一致:checks.json 里 source=experience 的 id 必须在本次证据里出现。
1306
+ try {
1307
+ const registry = JSON.parse(readFileSync(path.join(appDir, 'scripts', 'checks.json'), 'utf8'));
1308
+ // 自身先计入:登记表包含 checks.registry,不能自证缺失。
1309
+ const implemented = new Set([...items.map((item) => item.id), 'checks.registry']);
1310
+ const missing = (registry.checks ?? [])
1311
+ .filter((check) => check.source === 'experience' && !implemented.has(check.id))
1312
+ .map((check) => check.id);
1313
+ push('checks.registry', 'static', missing.length > 0 ? 'fail' : 'pass',
1314
+ missing.length > 0 ? '登记了但未实现:' + missing.join('、') : '检查项登记与实现一致');
1315
+ } catch {
1316
+ push('checks.registry', 'static', 'deferred', '读不到 scripts/checks.json');
1317
+ }
1318
+
1319
+ // 车道以登记表为准(旧条目缺 lane 时保留代码判定的车道)。
1320
+ for (const item of items) {
1321
+ const lane = checkMeta.get(item.id)?.lane;
1322
+ if (lane) item.lane = lane;
1323
+ // 检查项晚于应用模板版本(把新 checks.json 拷进旧应用)→ skip,不误报。
1324
+ const since = checkMeta.get(item.id)?.since;
1325
+ if (since && appVersion && !versionAtLeast(appVersion, since)) {
1326
+ item.status = 'skip';
1327
+ item.detail = '检查项晚于应用模板版本(since ' + since + ',应用 ' + appVersion + ')';
1328
+ }
1329
+ }
1330
+
1331
+ const errorFails = items.filter((item) => item.status === 'fail' && levelOf(item.id) === 'error');
1332
+ steps.push({ name: 'experience', ok: errorFails.length === 0, ms: Math.round(performance.now() - started), items });
1333
+ experienceItems = items;
1334
+ for (const item of items) {
1335
+ if (item.status !== 'fail') continue;
1336
+ if (levelOf(item.id) === 'warning') {
1337
+ warn('check-warning', '检查项未通过(告警级,不阻断):' + item.id + '(' + item.detail + ')', { fix: '按 docs/agent 对应配方修', recipe: 'verify' });
1338
+ continue;
1339
+ }
1340
+ errors.push({ step: 'experience', id: item.id, message: '体验不变量未通过:' + item.id + '(' + item.detail + ')', fix: '按 docs/agent 对应配方修;不要把它标成 handoff', recipe: 'verify' });
1341
+ }
1342
+ }
1343
+
1344
+ // ── 执行 ────────────────────────────────────────────────────────────
1345
+ await checkStyles();
1346
+ if (registryServer) checkPrimitives();
1347
+ checkTailwindClasses();
1348
+ await checkScenarios();
1349
+ if (registryServer) checkCoverage();
1350
+ await checkRender();
1351
+ checkRenderSignals();
1352
+ const stylesStep = steps.find((step) => step.name === 'styles');
1353
+ await checkExperience(stylesStep?.cssBytes ?? 0);
1354
+ const verdict = gateVerdict();
1355
+ try {
1356
+ const dir = path.join(appDir, '.tbox/evidence');
1357
+ mkdirSync(dir, { recursive: true });
1358
+ writeFileSync(path.join(dir, 'cards.txt'), cardDigests.map((item) => `- ${item.cardType} [${item.source}:${item.label}] ${item.text}`).join('\n') + '\n');
1359
+ writeFileSync(path.join(dir, 'scenarios.json'), JSON.stringify(scenarioResults, null, 2) + '\n');
1360
+ } catch {
1361
+ // 只读环境不影响门禁
1362
+ }
1363
+ await vite.close();
1364
+
1365
+ const ok = errors.length === 0;
1366
+ const summary = {
1367
+ ok,
1368
+ durationMs: Math.round(steps.reduce((sum, step) => sum + (step.ms ?? 0), 0)),
1369
+ steps,
1370
+ registry: {
1371
+ tools: (registryServer?.tools ?? []).map((tool) => tool.id),
1372
+ cards: Object.keys(mergedMetas),
1373
+ cardSources: mergedMetas && Object.fromEntries(Object.entries(cardProvenance).map(([cardType, source]) => [cardType, source.kind === 'module' ? source.moduleId : 'app'])),
1374
+ actions: Object.keys(registryServer?.actions ?? {}),
1375
+ },
1376
+ warnings,
1377
+ notRun,
1378
+ evidence: { cards: cardDigests.length, scenarios: scenarioResults.length, instances: scenarioInstances.length },
1379
+ ...verdict,
1380
+ experience: experienceItems,
1381
+ };
1382
+ if (errors.length > 0) summary.errors = errors;
1383
+
1384
+ if (!ok) {
1385
+ for (const item of errors) {
1386
+ const where = item.file ? `${item.file}: ` : '';
1387
+ console.error(` ❌ [${item.step}]${item.id ? ` [${item.id}]` : ''} ${where}${item.message}`);
1388
+ if (item.fix) console.error(` 修复:${item.fix}${item.recipe ? `(docs/agent/${item.recipe}.md)` : ''}`);
1389
+ }
1390
+ }
1391
+ for (const item of warnings) console.error(` ⚠️ ${item.message}`);
1392
+
1393
+ try {
1394
+ const dir = path.join(appDir, '.tbox/evidence');
1395
+ mkdirSync(dir, { recursive: true });
1396
+ writeFileSync(path.join(dir, 'last-gate.json'), json(summary));
1397
+ } catch {
1398
+ // 只读环境不影响门禁
1399
+ }
1400
+
1401
+ process.stdout.write(json(summary) + '\n');
1402
+ if (!ok) process.exitCode = 1;