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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/.gitignore +7 -0
  2. package/.tbox/app.json +1 -1
  3. package/.tbox/default-modules.json +1 -1
  4. package/.tbox/factory/chat.json +9 -0
  5. package/.tbox/miniapp-containers.json +1 -1
  6. package/AGENTS.md +11 -8
  7. package/apps/client/index.html +0 -43
  8. package/apps/client/package.json +1 -0
  9. package/apps/client/scripts/acceptance-changes.test.mjs +97 -0
  10. package/apps/client/scripts/check-evidence.mjs +625 -108
  11. package/apps/client/scripts/color-scan.mjs +66 -0
  12. package/apps/client/scripts/color-scan.test.mjs +25 -0
  13. package/apps/client/scripts/evidence-gate.mjs +337 -0
  14. package/apps/client/scripts/evidence-gate.test.mjs +135 -0
  15. package/apps/client/scripts/experience-checks.mjs +163 -0
  16. package/apps/client/scripts/geometry-kernel.test.mjs +92 -0
  17. package/apps/client/scripts/in-process-checks.mjs +51 -0
  18. package/apps/client/scripts/lib/card-registry.mjs +81 -0
  19. package/apps/client/scripts/lib/card-registry.test.mjs +59 -0
  20. package/apps/client/scripts/lib/evidence-inputs.mjs +91 -0
  21. package/apps/client/scripts/lib/evidence-inputs.test.mjs +27 -0
  22. package/apps/client/scripts/lib/static-render.mjs +35 -0
  23. package/apps/client/scripts/lib/static-render.test.mjs +21 -0
  24. package/apps/client/scripts/probe-checks.mjs +85 -0
  25. package/apps/client/scripts/render-card.mjs +95 -126
  26. package/apps/client/scripts/sample-entries.test.mjs +31 -0
  27. package/apps/client/scripts/storyboard.test.mjs +149 -0
  28. package/apps/client/scripts/surface-css.mjs +54 -0
  29. package/apps/client/scripts/theme-kernel.mjs +236 -0
  30. package/apps/client/scripts/theme-kernel.test.mjs +136 -0
  31. package/apps/client/src/app.config.ts +4 -1
  32. package/apps/client/src/styles/brand.css +13 -14
  33. package/apps/client/src/styles/tailwind.css +20 -21
  34. package/apps/client/vite.config.ts +2 -1
  35. package/apps/server/scripts/probe.mjs +6 -1
  36. package/apps/server/scripts/scenario-lib.mjs +56 -8
  37. package/apps/server/scripts/scenario.mjs +41 -7
  38. package/config/AGENTS.md +1 -0
  39. package/config/chat.json +21 -9
  40. package/docs/agent/agent-prompt.md +1 -1
  41. package/docs/agent/card-action.md +5 -0
  42. package/docs/agent/card.md +45 -2
  43. package/docs/agent/kit.md +3 -3
  44. package/docs/agent/shell.md +1 -0
  45. package/docs/agent/style.md +11 -3
  46. package/docs/agent/tool-emits-card.md +7 -2
  47. package/docs/agent/tool.md +2 -0
  48. package/docs/agent/verify.md +59 -16
  49. package/package.json +21 -7
  50. package/packages/agent-ui-kit/AGENTS.md +1 -1
  51. package/packages/agent-ui-kit/README.md +21 -1
  52. package/packages/agent-ui-kit/catalog.json +8 -4
  53. package/packages/agent-ui-kit/package.json +9 -1
  54. package/packages/agent-ui-kit/src/._surface.tsx +0 -0
  55. package/packages/agent-ui-kit/src/ChatPage.tsx +70 -17
  56. package/packages/agent-ui-kit/src/card/._action-list-pending.test.tsx +0 -0
  57. package/packages/agent-ui-kit/src/card/._define-card.test.ts +0 -0
  58. package/packages/agent-ui-kit/src/card/._view-card-inline.test.tsx +0 -0
  59. package/packages/agent-ui-kit/src/card/._view-card.test.tsx +0 -0
  60. package/packages/agent-ui-kit/src/card/._view-card.tsx +0 -0
  61. package/packages/agent-ui-kit/src/card/action-list-pending.test.tsx +91 -0
  62. package/packages/agent-ui-kit/src/card/define-card.test.ts +25 -0
  63. package/packages/agent-ui-kit/src/card/define-card.ts +18 -5
  64. package/packages/agent-ui-kit/src/card/primitives.test.tsx +10 -0
  65. package/packages/agent-ui-kit/src/card/primitives.tsx +136 -37
  66. package/packages/agent-ui-kit/src/card/view-card-inline.test.tsx +42 -0
  67. package/packages/agent-ui-kit/src/card/view-card.test.tsx +79 -0
  68. package/packages/agent-ui-kit/src/card/view-card.tsx +250 -0
  69. package/packages/agent-ui-kit/src/chat-config.ts +11 -7
  70. package/packages/agent-ui-kit/src/components/ActionBar/DebugButton.test.tsx +3 -0
  71. package/packages/agent-ui-kit/src/components/ActionBar/DebugButton.tsx +2 -7
  72. package/packages/agent-ui-kit/src/components/BottomSheet/._index.test.tsx +0 -0
  73. package/packages/agent-ui-kit/src/components/BottomSheet/._index.tsx +0 -0
  74. package/packages/agent-ui-kit/src/components/BottomSheet/index.test.tsx +90 -0
  75. package/packages/agent-ui-kit/src/components/BottomSheet/index.tsx +129 -0
  76. package/packages/agent-ui-kit/src/components/ChatInput/index.test.tsx +2 -2
  77. package/packages/agent-ui-kit/src/components/ChatInput/index.tsx +22 -17
  78. package/packages/agent-ui-kit/src/components/HistoryEntry/index.tsx +3 -2
  79. package/packages/agent-ui-kit/src/components/MessageBubble/index.tsx +11 -5
  80. package/packages/agent-ui-kit/src/components/QuickCommands/index.test.tsx +3 -1
  81. package/packages/agent-ui-kit/src/components/QuickCommands/index.tsx +31 -8
  82. package/packages/agent-ui-kit/src/components/ScrollToBottomButton/index.tsx +7 -3
  83. package/packages/agent-ui-kit/src/components/ToolCallBlock/index.tsx +4 -2
  84. package/packages/agent-ui-kit/src/index.ts +8 -0
  85. package/packages/agent-ui-kit/src/preview-provider.tsx +47 -0
  86. package/packages/agent-ui-kit/src/shell.contract.json +9 -0
  87. package/packages/agent-ui-kit/src/shell.test.ts +10 -0
  88. package/packages/agent-ui-kit/src/shell.ts +15 -0
  89. package/packages/agent-ui-kit/src/surface.test.tsx +35 -0
  90. package/packages/agent-ui-kit/src/surface.tsx +44 -0
  91. package/packages/agent-ui-kit/src/theme/base.css +9 -11
  92. package/packages/agent-ui-kit/src/theme/contract.json +123 -2
  93. package/packages/agent-ui-kit/src/theme/theme-contract.test.ts +16 -0
  94. package/packages/agent-ui-kit/src/theme/tokens.css +9 -12
  95. package/pnpm-lock.template.yaml +97 -91
  96. package/pnpm-workspace.template.yaml +10 -10
  97. package/profiles/mall/._chat.overrides.json +0 -0
  98. package/profiles/mall/chat.overrides.json +12 -0
  99. package/profiles/mall/config/chat.json +14 -6
  100. package/profiles/mall.json +1 -1
  101. package/scripts/._assert-pack.mjs +0 -0
  102. package/scripts/._deliver.mjs +0 -0
  103. package/scripts/._shell-probe.mjs +0 -0
  104. package/scripts/._storyboard.mjs +0 -0
  105. package/scripts/assert-pack.mjs +48 -0
  106. package/scripts/check-css-target.mjs +6 -3
  107. package/scripts/check-fast.mjs +1 -0
  108. package/scripts/checks.json +400 -26
  109. package/scripts/deliver.mjs +183 -0
  110. package/scripts/lib/._chrome-pipe.mjs +0 -0
  111. package/scripts/lib/._geometry-kernel.mjs +0 -0
  112. package/scripts/lib/chrome-pipe.mjs +95 -0
  113. package/scripts/lib/geometry-kernel.mjs +137 -0
  114. package/scripts/shell-probe.mjs +283 -0
  115. package/scripts/storyboard.mjs +350 -0
  116. package/.tbox/card-render/baseline/demo.png +0 -0
  117. package/.tbox/card-render/demo.html +0 -342
  118. package/.tbox/card-render/demo.png +0 -0
  119. package/.tbox/card-render/scale-demo.audit.html +0 -984
  120. package/.tbox/card-render/scale-demo.html +0 -939
  121. package/.tbox/evidence/cards.txt +0 -1
  122. package/.tbox/evidence/gate.json +0 -1
  123. package/.tbox/evidence/last-gate.json +0 -1
  124. package/.tbox/evidence/scenarios.json +0 -1
  125. package/apps/client/.tbox-gen/app-registry.ts +0 -3
  126. package/apps/client/.tbox-gen/documents/_tbox/card-preview.html +0 -62
  127. package/apps/client/.tbox-gen/documents/index.html +0 -63
  128. package/apps/client/.tbox-gen/entries/card-preview.tsx +0 -6
  129. package/apps/client/.tbox-gen/entries/index.tsx +0 -11
  130. package/apps/client/.tbox-gen/manifest.json +0 -17
  131. package/apps/client/.tbox-gen/registry.client.ts +0 -6
  132. package/apps/client/.tbox-gen/registry.server.ts +0 -15
  133. package/apps/client/STYLE_GUIDE.md +0 -48
  134. package/apps/client/VISUAL_RESTORE.md +0 -90
  135. package/profiles/mall/config/llm_provider.json +0 -5
  136. package/profiles/mall/config/plugins.json +0 -3
  137. package/scripts/compat-probe.mjs +0 -108
  138. package/scripts/gen-tailwind-sources.mjs +0 -55
  139. /package/.tbox/{card-render/._demo.html → factory/._chat.json} +0 -0
  140. /package/{.tbox/card-render/._demo.png → apps/client/scripts/._acceptance-changes.test.mjs} +0 -0
  141. /package/{.tbox/card-render/._scale-demo.audit.html → apps/client/scripts/._color-scan.mjs} +0 -0
  142. /package/{.tbox/card-render/._scale-demo.html → apps/client/scripts/._color-scan.test.mjs} +0 -0
  143. /package/{.tbox/card-render/baseline/._demo.png → apps/client/scripts/._evidence-gate.mjs} +0 -0
  144. /package/{.tbox/evidence/._cards.txt → apps/client/scripts/._evidence-gate.test.mjs} +0 -0
  145. /package/{.tbox/evidence/._gate.json → apps/client/scripts/._experience-checks.mjs} +0 -0
  146. /package/{.tbox/evidence/._last-gate.json → apps/client/scripts/._geometry-kernel.test.mjs} +0 -0
  147. /package/{.tbox/evidence/._scenarios.json → apps/client/scripts/._in-process-checks.mjs} +0 -0
  148. /package/apps/client/{._STYLE_GUIDE.md → scripts/._probe-checks.mjs} +0 -0
  149. /package/apps/client/{._VISUAL_RESTORE.md → scripts/._sample-entries.test.mjs} +0 -0
  150. /package/apps/client/{.tbox-gen/._app-registry.ts → scripts/._storyboard.test.mjs} +0 -0
  151. /package/apps/client/{.tbox-gen/._manifest.json → scripts/._surface-css.mjs} +0 -0
  152. /package/apps/client/{.tbox-gen/._registry.client.ts → scripts/._theme-kernel.mjs} +0 -0
  153. /package/apps/client/{.tbox-gen/._registry.server.ts → scripts/._theme-kernel.test.mjs} +0 -0
  154. /package/apps/client/{.tbox-gen/documents/._index.html → scripts/lib/._card-registry.mjs} +0 -0
  155. /package/apps/client/{.tbox-gen/documents/_tbox/._card-preview.html → scripts/lib/._card-registry.test.mjs} +0 -0
  156. /package/apps/client/{.tbox-gen/entries/._card-preview.tsx → scripts/lib/._evidence-inputs.mjs} +0 -0
  157. /package/apps/client/{.tbox-gen/entries/._index.tsx → scripts/lib/._evidence-inputs.test.mjs} +0 -0
  158. /package/{profiles/mall/config/._llm_provider.json → apps/client/scripts/lib/._static-render.mjs} +0 -0
  159. /package/{profiles/mall/config/._plugins.json → apps/client/scripts/lib/._static-render.test.mjs} +0 -0
  160. /package/{scripts/._compat-probe.mjs → packages/agent-ui-kit/src/._preview-provider.tsx} +0 -0
  161. /package/{scripts/._gen-tailwind-sources.mjs → packages/agent-ui-kit/src/._surface.test.tsx} +0 -0
@@ -0,0 +1,66 @@
1
+ /**
2
+ * 色值字面量扫描:谁在卡片/组件里写死了颜色、重复了多少次、最像哪个令牌。
3
+ *
4
+ * 判据一条:style.md 说「同一色值出现三处以上就该进契约」。门禁(style.color-repeat)
5
+ * 与 build-lab 的 adoption(hexColors / colorRepeatGroups)用同一份扫描,避免两套口径各说各话。
6
+ */
7
+ import { readFileSync } from 'node:fs';
8
+
9
+ /** Tailwind 任意值里的 hex(bg-[#173F33])、裸 hex、rgb()/rgba()。 */
10
+ const PATTERNS = [
11
+ { re: /\[(#[0-9a-fA-F]{3,8})\]/g, group: 1 }, // Tailwind 任意值:bg-[#173F33]
12
+ { re: /(^|[^\w[-])(#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3})\b/g, group: 2 }, // 裸 hex(排除 bg-[#...] 已被上一条收走)
13
+ { re: /rgba?\(\s*[\d.]+[\s,]+[\d.]+[\s,]+[\d.]+(?:[\s,/]+[\d.]+%?)?\s*\)/g, group: 0 },
14
+ ];
15
+
16
+ /** 归一:小写、3 位扩 6 位、rgba 转 8 位 hex。 */
17
+ export function normalizeHex(value) {
18
+ const text = value.trim().toLowerCase();
19
+ const rgb = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:[\s,/]+([\d.]+)(%?))?\s*\)$/.exec(text);
20
+ if (rgb) {
21
+ const part = (raw) => Math.max(0, Math.min(255, Math.round(Number(raw)))).toString(16).padStart(2, '0');
22
+ const alpha = rgb[4] === undefined ? 255 : rgb[5] === '%' ? Math.round((Number(rgb[4]) / 100) * 255) : Math.round(Number(rgb[4]) * 255);
23
+ return '#' + part(rgb[1]) + part(rgb[2]) + part(rgb[3]) + (alpha === 255 ? '' : part(alpha));
24
+ }
25
+ const hex = /^#([0-9a-f]{3,8})$/.exec(text);
26
+ if (!hex) return text;
27
+ const raw = hex[1];
28
+ if (raw.length === 3) return '#' + raw[0] + raw[0] + raw[1] + raw[1] + raw[2] + raw[2];
29
+ if (raw.length === 4) return '#' + raw[0] + raw[0] + raw[1] + raw[1] + raw[2] + raw[2] + raw[3] + raw[3];
30
+ return '#' + raw;
31
+ }
32
+
33
+ /** 单份文本里的字面量(保留出现位置,便于门禁给出「在哪个文件第几处」)。 */
34
+ export function findColorLiterals(text, file = '') {
35
+ const hits = [];
36
+ for (const { re, group } of PATTERNS) {
37
+ re.lastIndex = 0;
38
+ for (const match of text.matchAll(re)) {
39
+ const raw = match[group];
40
+ if (!raw) continue;
41
+ hits.push({ file, raw, hex: normalizeHex(raw) });
42
+ }
43
+ }
44
+ return hits;
45
+ }
46
+
47
+ /** 批量扫描 → Map<hex, { count, files: Set }>。 */
48
+ export function scanColorLiterals(files) {
49
+ const map = new Map();
50
+ for (const file of files) {
51
+ let text;
52
+ try {
53
+ text = typeof file === 'string' ? readFileSync(file, 'utf8') : String(file.text ?? '');
54
+ } catch {
55
+ continue;
56
+ }
57
+ const name = typeof file === 'string' ? file : String(file.name ?? '');
58
+ for (const hit of findColorLiterals(text, name)) {
59
+ const entry = map.get(hit.hex) ?? { count: 0, files: new Set() };
60
+ entry.count += 1;
61
+ entry.files.add(name);
62
+ map.set(hit.hex, entry);
63
+ }
64
+ }
65
+ return map;
66
+ }
@@ -0,0 +1,25 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { findColorLiterals, normalizeHex, scanColorLiterals } from './color-scan.mjs';
3
+
4
+ describe('色值扫描(T2.2)', () => {
5
+ it('归一:3 位扩 6 位、小写、rgba 转 8 位 hex', () => {
6
+ expect(normalizeHex('#FFF')).toBe('#ffffff');
7
+ expect(normalizeHex('rgba(23, 63, 51, 0.5)')).toBe('#173f3380');
8
+ expect(normalizeHex('rgb(23,63,51)')).toBe('#173f33');
9
+ });
10
+
11
+ it('三类写法都识别:Tailwind 任意值、裸 hex、rgb()', () => {
12
+ const hits = findColorLiterals("const a = 'bg-[#173F33]'; const b = '#c59a55'; const c = 'rgba(23,63,51,0.2)'; const d = 'bg-primary';");
13
+ expect(hits.map((hit) => hit.hex)).toEqual(['#173f33', '#c59a55', '#173f3333']);
14
+ });
15
+
16
+ it('按文件聚合并计数(同一色值出现三次以上才是信号)', () => {
17
+ const map = scanColorLiterals([
18
+ { name: 'a.tsx', text: 'bg-[#173F33] text-[#173f33] border-[#173f33]' },
19
+ { name: 'b.tsx', text: '#c59a55' },
20
+ ]);
21
+ expect(map.get('#173f33').count).toBe(3);
22
+ expect(map.get('#173f33').files.size).toBe(1);
23
+ expect(map.get('#c59a55').count).toBe(1);
24
+ });
25
+ });
@@ -0,0 +1,337 @@
1
+ /**
2
+ * 证据门禁的纯函数:内容哈希、验收漂移、覆盖集合、软闩判定、颜色对比。
3
+ *
4
+ * 从 check-evidence.mjs 抽出,便于用 vitest 直接测;脚本只做 IO 与编排。
5
+ */
6
+ import { createHash } from 'node:crypto';
7
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ export const HASH_SOURCE_DIRS = ['apps', 'packages', 'config', 'scenarios'];
11
+ export const HASH_SKIP = new Set(['node_modules', 'dist', 'dist-ssr', '.tbox-gen', '.tbox', '.git', '.vite']);
12
+
13
+ /** 交付内容哈希:路径 + 内容,同一文件改内容也能被软闩捕获。 */
14
+ export function hashSourceTree(root) {
15
+ const hash = createHash('sha256');
16
+ let files = 0;
17
+ const walk = (dir, rel) => {
18
+ let entries;
19
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
20
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
21
+ if (HASH_SKIP.has(entry.name) || entry.name.startsWith('._') || entry.name === '.DS_Store') continue;
22
+ const abs = path.join(dir, entry.name);
23
+ const next = rel + '/' + entry.name;
24
+ if (entry.isDirectory()) { walk(abs, next); continue; }
25
+ if (!entry.isFile()) continue;
26
+ try {
27
+ const stat = statSync(abs);
28
+ hash.update(next + '\0' + stat.size + '\0');
29
+ hash.update(readFileSync(abs));
30
+ files += 1;
31
+ } catch { /* 读失败的条目不影响其他内容 */ }
32
+ }
33
+ };
34
+ for (const name of HASH_SOURCE_DIRS) {
35
+ const abs = path.join(root, name);
36
+ if (existsSync(abs)) walk(abs, name);
37
+ }
38
+ for (const name of ['package.json', 'pnpm-lock.yaml']) {
39
+ const abs = path.join(root, name);
40
+ if (!existsSync(abs)) continue;
41
+ try { hash.update(name + '\0'); hash.update(readFileSync(abs)); files += 1; } catch { /* ignore */ }
42
+ }
43
+ return { hash: hash.digest('hex').slice(0, 16), files };
44
+ }
45
+
46
+ /**
47
+ * 故事板覆盖:界面上能看到的验收项,由帧证明「渲染出来了且没有几何错误」。
48
+ *
49
+ * 与场景覆盖分列:场景证明链路通,故事板只证明画面在 390/320 下没坏。任一匹配帧有 error 级
50
+ * 几何问题时该项不升格,按未覆盖处理;静态档位或没有故事板时回落 handoff,理由写明。
51
+ *
52
+ * @returns {{ covered: Set<string>, handoff: Map<string,string>, failed: Map<string,string> }}
53
+ */
54
+ export function storyboardCoverage(items, storyboard, policy) {
55
+ const covered = new Set();
56
+ const handoff = new Map();
57
+ const failed = new Map();
58
+ const frames = Array.isArray(storyboard?.frames) ? storyboard.frames : [];
59
+ const errorIds = new Set(['storyboard.render', 'card.overflow-x']);
60
+ for (const item of items) {
61
+ if (item.by !== 'storyboard' || item.lane) continue;
62
+ const id = String(item.id);
63
+ if (policy === 'static') {
64
+ handoff.set(id, 'static 档位不渲染故事板');
65
+ continue;
66
+ }
67
+ if (!storyboard || storyboard.status === 'not-run') {
68
+ handoff.set(id, '故事板未运行(pnpm storyboard / pnpm deliver)');
69
+ continue;
70
+ }
71
+ const patterns = Array.isArray(item.frames) && item.frames.length > 0 ? item.frames : ['*'];
72
+ const matched = frames.filter((frame) => patterns.some((pattern) => matchFrame(String(pattern), frame.id)));
73
+ if (matched.length === 0) {
74
+ handoff.set(id, '没有匹配的帧(frames: ' + patterns.join('、') + ')');
75
+ continue;
76
+ }
77
+ const broken = matched.filter((frame) => (frame.problems ?? []).some((problem) => errorIds.has(problem.id)));
78
+ if (broken.length > 0) {
79
+ failed.set(id, broken.length + ' 帧有几何错误:' + broken.slice(0, 2).map((frame) => frame.id).join('、'));
80
+ continue;
81
+ }
82
+ covered.add(id);
83
+ }
84
+ return { covered, handoff, failed };
85
+ }
86
+
87
+ /** 帧 id 通配:只支持结尾的 `*`(如 card:*@320、card:parking:*)。 */
88
+ export function matchFrame(pattern, id) {
89
+ if (pattern === '*') return true;
90
+ if (!pattern.includes('*')) return pattern === id;
91
+ const parts = pattern.split('*');
92
+ let rest = id;
93
+ for (const [index, part] of parts.entries()) {
94
+ if (index === 0) {
95
+ if (!rest.startsWith(part)) return false;
96
+ rest = rest.slice(part.length);
97
+ continue;
98
+ }
99
+ if (index === parts.length - 1) return rest.endsWith(part);
100
+ const at = rest.indexOf(part);
101
+ if (at < 0) return false;
102
+ rest = rest.slice(at + part.length);
103
+ }
104
+ return true;
105
+ }
106
+
107
+ /**
108
+ * 验收变更:把「验收文件哈希变了」升级成「哪一项、怎么变的」。
109
+ *
110
+ * 输入是每项的摘要(文本哈希、是否移交、被哪些场景覆盖);输出分类变更,并按 id 累计——
111
+ * 交付时列的是「自首次门禁以来弱化过什么」,不是只看最后一轮。不落锁文件、不加命令:
112
+ * 基线就是上一轮的 gate.json,确认的载体是会话本身。
113
+ */
114
+ export function acceptanceChangesOf(prevGate, digest) {
115
+ const previous = prevGate?.acceptanceDigest;
116
+ const current = digest ?? {};
117
+ if (!previous || typeof previous !== 'object') return { changes: [], cumulative: Array.isArray(prevGate?.acceptanceChanges) ? prevGate.acceptanceChanges : [] };
118
+ const changes = [];
119
+ const at = Date.now();
120
+ for (const [id, now] of Object.entries(current)) {
121
+ const before = previous[id];
122
+ if (!before) {
123
+ changes.push({ id, kind: 'item-added', weakening: false, firstSeenAt: at });
124
+ continue;
125
+ }
126
+ if (before.text !== now.text) {
127
+ changes.push({ id, kind: 'item-reworded', weakening: true, before: before.text, after: now.text, firstSeenAt: at });
128
+ }
129
+ const beforeCovers = Array.isArray(before.coveredBy) ? before.coveredBy.length : 0;
130
+ const nowCovers = Array.isArray(now.coveredBy) ? now.coveredBy.length : 0;
131
+ if (nowCovers < beforeCovers) {
132
+ changes.push({ id, kind: 'covers-shrunk', weakening: true, before: String(beforeCovers), after: String(nowCovers), firstSeenAt: at });
133
+ } else if (nowCovers > beforeCovers) {
134
+ changes.push({ id, kind: 'covers-grown', weakening: false, firstSeenAt: at });
135
+ }
136
+ if (!before.handoff && now.handoff) changes.push({ id, kind: 'handoff-added', weakening: true, firstSeenAt: at });
137
+ }
138
+ for (const id of Object.keys(previous)) {
139
+ if (!(id in current)) changes.push({ id, kind: 'item-removed', weakening: true, firstSeenAt: at });
140
+ }
141
+
142
+ // 累计:同 id 同 kind 只留最早一次;后来恢复原状的条目移除。
143
+ const cumulative = [...(Array.isArray(prevGate?.acceptanceChanges) ? prevGate.acceptanceChanges : [])];
144
+ for (const change of changes) {
145
+ if (cumulative.some((item) => item.id === change.id && item.kind === change.kind)) continue;
146
+ cumulative.push(change);
147
+ }
148
+ const recovered = (item) => {
149
+ const now = current[item.id];
150
+ if (!now) return false;
151
+ // 验收项被删后又加回来:这条账出账(继续报只会变成噪声)。
152
+ if (item.kind === 'item-removed') return true;
153
+ if (item.kind === 'item-reworded') return now.text === item.before;
154
+ if (item.kind === 'covers-shrunk') return (now.coveredBy?.length ?? 0) >= Number(item.before);
155
+ if (item.kind === 'handoff-added') return now.handoff === false;
156
+ return false;
157
+ };
158
+ // 累计只记弱化:加严不需要审计,恢复了就自动出账。
159
+ return { changes, cumulative: cumulative.filter((item) => item.weakening && !recovered(item)) };
160
+ }
161
+
162
+ /** 累计弱化的一行摘要(进告警与交付包);同一项的多处改动合成一句。 */
163
+ export function summarizeAcceptanceChanges(cumulative) {
164
+ const byId = new Map();
165
+ for (const item of cumulative ?? []) {
166
+ if (!item.weakening) continue;
167
+ const phrase = item.kind === 'covers-shrunk'
168
+ ? '覆盖 ' + item.before + '→' + item.after
169
+ : item.kind === 'item-removed'
170
+ ? '已删除'
171
+ : item.kind === 'handoff-added'
172
+ ? '改为移交'
173
+ : item.kind === 'item-reworded'
174
+ ? '文本改写'
175
+ : item.kind;
176
+ const list = byId.get(item.id) ?? [];
177
+ if (!list.includes(phrase)) list.push(phrase);
178
+ byId.set(item.id, list);
179
+ }
180
+ return [...byId.entries()].map(([id, phrases]) => id + ' ' + phrases.join('、'));
181
+ }
182
+
183
+ /**
184
+ * 出厂偏离面(D4):出厂快照与当前值的对比,按面登记。
185
+ *
186
+ * 加一个可偏离面 = 一行登记(快照文件 + 读取 + 差异函数);能力开关是第一面,
187
+ * 默认模块集是第二面——删掉出厂模块在会话与交付包里都看得见,不阻断。
188
+ */
189
+ export const DRIFT_SURFACES = {
190
+ 'chat.capabilities': { snapshot: '.tbox/factory/chat.json', change: 'user-intent' },
191
+ 'modules.default': { snapshot: '.tbox/factory/modules.json', change: 'declared' },
192
+ };
193
+
194
+ const packageNamesOf = (value) => {
195
+ const list = Array.isArray(value) ? value : Array.isArray(value?.modules) ? value.modules : [];
196
+ return list.map((item) => (typeof item === 'string' ? item : String(item?.package ?? ''))).filter(Boolean);
197
+ };
198
+
199
+ /** 出厂模块集 vs 当前 default-modules:少了的包就是一次偏离。 */
200
+ export function defaultModuleDrift({ factory, actual }) {
201
+ const before = packageNamesOf(factory);
202
+ const now = packageNamesOf(actual);
203
+ if (before.length === 0) return { skipped: true, reason: '出厂快照没有登记默认模块', items: [] };
204
+ const removed = before.filter((name) => !now.includes(name));
205
+ const added = now.filter((name) => !before.includes(name));
206
+ return {
207
+ skipped: false,
208
+ items: [
209
+ ...removed.map((name) => ({ key: name, kind: 'module-removed', factory: true, actual: false, change: 'declared' })),
210
+ ...added.map((name) => ({ key: name, kind: 'module-added', factory: false, actual: true, change: 'declared' })),
211
+ ],
212
+ };
213
+ }
214
+
215
+ export function acceptanceDrift(prevGate, acceptanceHash, acceptanceIds) {
216
+ if (!prevGate || !prevGate.acceptanceHash || !acceptanceHash || prevGate.acceptanceHash === acceptanceHash) {
217
+ return { added: [], removed: [], drift: [] };
218
+ }
219
+ const prevIds = Array.isArray(prevGate.acceptanceIds) ? prevGate.acceptanceIds : [];
220
+ const added = acceptanceIds.filter((id) => !prevIds.includes(id));
221
+ const removed = prevIds.filter((id) => !acceptanceIds.includes(id));
222
+ const detail = '验收文件哈希变化' + (added.length ? ';新增 ' + added.join('、') : '') + (removed.length ? ';删除 ' + removed.join('、') : '');
223
+ return { added, removed, drift: [{ kind: 'acceptance', detail }] };
224
+ }
225
+
226
+ export function shouldReopen(prevGate, verdict, contentHash) {
227
+ return Boolean(
228
+ verdict === 'deliverable' &&
229
+ prevGate &&
230
+ prevGate.verdict === 'deliverable' &&
231
+ prevGate.contentHash &&
232
+ contentHash &&
233
+ prevGate.contentHash !== contentHash,
234
+ );
235
+ }
236
+
237
+ export function coverageSets(scenarioResults, originByFile) {
238
+ const covered = new Set();
239
+ const declared = new Set();
240
+ for (const result of scenarioResults) {
241
+ if (!result.ok) continue;
242
+ for (const id of result.covers ?? []) {
243
+ declared.add(id);
244
+ if (originByFile.get(result.file) !== 'recorded') covered.add(id);
245
+ }
246
+ }
247
+ return { covered, declared };
248
+ }
249
+
250
+ /** 出厂能力表:键 → 偏离条件(与 SDK chatCapabilities 同形;app 侧不 import SDK,避免启动链耦合)。 */
251
+ export const CAPABILITY_CHANGE = {
252
+ enableVoiceInput: 'user-intent',
253
+ enableImageUpload: 'declared',
254
+ enableVideoUpload: 'declared',
255
+ enableTTS: 'declared',
256
+ };
257
+
258
+ /**
259
+ * 能力偏离:与 create 落盘的出厂基线比。
260
+ * - 无快照(旧应用)→ skipped,不误报;
261
+ * - user-intent 类偏离只告警;
262
+ * - declared 类只进交付包,不告警。
263
+ */
264
+ export function capabilityDrift({ factory, actual, change = CAPABILITY_CHANGE }) {
265
+ if (!factory || typeof factory !== 'object') {
266
+ return { skipped: true, reason: '缺出厂基线快照(.tbox/factory/chat.json)', items: [] };
267
+ }
268
+ const items = [];
269
+ for (const [key, mode] of Object.entries(change)) {
270
+ if (!(key in factory)) continue;
271
+ // 键缺席 = 沿用出厂默认,不算偏离(新模板出厂文件不再列出能力键)。
272
+ const current = actual && key in actual ? actual[key] : factory[key];
273
+ if (factory[key] === current) continue;
274
+ items.push({ key, factory: factory[key], actual: current, change: mode, severity: mode === 'user-intent' ? 'warn' : 'info' });
275
+ }
276
+ return { skipped: false, items };
277
+ }
278
+
279
+ /**
280
+ * 档位解析:平台注入优先;应用声明只有在写明理由时才算用户意图;否则回落缺省。
281
+ * 缺省 = visual(standard 档:静态 + 布局车道),不再默认 static。
282
+ */
283
+ export function resolvePolicy({ platformPolicy, docPolicy, docPolicyReason, fallback = 'visual' } = {}) {
284
+ const valid = ['static', 'visual', 'flow'];
285
+ if (valid.includes(platformPolicy)) return { policy: platformPolicy, source: 'platform', downgradeIgnored: false };
286
+ if (!valid.includes(docPolicy)) return { policy: fallback, source: 'default', downgradeIgnored: false };
287
+ if (docPolicy === 'flow' || docPolicy === 'visual') return { policy: docPolicy, source: 'app', downgradeIgnored: false };
288
+ if (docPolicyReason) return { policy: docPolicy, source: 'app-reasoned', downgradeIgnored: false };
289
+ return { policy: fallback, source: 'default', downgradeIgnored: true };
290
+ }
291
+
292
+ /** 场景删除漂移:上次记录的场景文件在本轮消失。 */
293
+ export function scenarioDrift(prevGate, scenarioHashes) {
294
+ const prev = prevGate?.scenarioHashes;
295
+ if (!prev || typeof prev !== 'object') return [];
296
+ return Object.keys(prev).filter((file) => !(file in (scenarioHashes ?? {}))).map((file) => ({
297
+ kind: 'scenario-removed',
298
+ detail: '场景被删除:' + file,
299
+ }));
300
+ }
301
+
302
+ /** 版本比较(since 过滤用):核心版本逐段数值比较;同核心时按 prerelease 段比较。 */
303
+ export function versionAtLeast(actual, required) {
304
+ const core = (value) => String(value).replace(/^v/, '').split('-')[0].split('.').map((part) => Number(part) || 0);
305
+ const pre = (value) => {
306
+ const match = /-([0-9A-Za-z.-]+)$/.exec(String(value));
307
+ return match ? match[1].split('.') : [];
308
+ };
309
+ const a = core(actual);
310
+ const b = core(required);
311
+ for (let index = 0; index < 3; index += 1) {
312
+ if ((a[index] ?? 0) !== (b[index] ?? 0)) return (a[index] ?? 0) > (b[index] ?? 0);
313
+ }
314
+ const ap = pre(actual);
315
+ const bp = pre(required);
316
+ // 无 prerelease 的正式版高于同核心的 prerelease。
317
+ if (ap.length === 0 && bp.length === 0) return true;
318
+ if (ap.length === 0) return true;
319
+ if (bp.length === 0) return false;
320
+ for (let index = 0; index < Math.max(ap.length, bp.length); index += 1) {
321
+ if (ap[index] === undefined) return false;
322
+ if (bp[index] === undefined) return true;
323
+ if (ap[index] === bp[index]) continue;
324
+ const an = Number(ap[index]);
325
+ const bn = Number(bp[index]);
326
+ if (Number.isFinite(an) && Number.isFinite(bn)) return an > bn;
327
+ return String(ap[index]) > String(bp[index]);
328
+ }
329
+ return true;
330
+ }
331
+
332
+ export function scenarioKey(appDir, file) {
333
+ return path.relative(appDir, file);
334
+ }
335
+
336
+ // 颜色解析与对比度只有一份实现(apps/client/scripts/theme-kernel.mjs),门禁与 theme 命令共用。
337
+ export { parseColor, contrastRatio } from './theme-kernel.mjs';
@@ -0,0 +1,135 @@
1
+ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import path from 'node:path';
4
+ import { afterEach, describe, expect, it } from 'vitest';
5
+ import {
6
+ acceptanceDrift,
7
+ capabilityDrift,
8
+ contrastRatio,
9
+ coverageSets,
10
+ hashSourceTree,
11
+ parseColor,
12
+ resolvePolicy,
13
+ scenarioDrift,
14
+ versionAtLeast,
15
+ shouldReopen,
16
+ } from './evidence-gate.mjs';
17
+
18
+ let root = '';
19
+
20
+ afterEach(() => {
21
+ if (root) rmSync(root, { recursive: true, force: true });
22
+ root = '';
23
+ });
24
+
25
+ describe('hashSourceTree', () => {
26
+ it('同一路径改内容会改变哈希,跳过 node_modules / .tbox', () => {
27
+ root = mkdtempSync(path.join(tmpdir(), 'tbox-hash-'));
28
+ mkdirSync(path.join(root, 'apps'), { recursive: true });
29
+ writeFileSync(path.join(root, 'apps/a.ts'), '// a\n');
30
+ const first = hashSourceTree(root);
31
+ writeFileSync(path.join(root, 'apps/a.ts'), '// b\n');
32
+ const second = hashSourceTree(root);
33
+ expect(second.hash).not.toBe(first.hash);
34
+ expect(second.files).toBe(first.files);
35
+
36
+ mkdirSync(path.join(root, 'node_modules/x'), { recursive: true });
37
+ mkdirSync(path.join(root, '.tbox'), { recursive: true });
38
+ writeFileSync(path.join(root, 'node_modules/x/a.ts'), 'changed\n');
39
+ writeFileSync(path.join(root, '.tbox/a.ts'), 'changed\n');
40
+ expect(hashSourceTree(root).hash).toBe(second.hash);
41
+ });
42
+ });
43
+
44
+ describe('acceptanceDrift / shouldReopen', () => {
45
+ it('列出新增与删除的验收项', () => {
46
+ const prev = { acceptanceHash: 'old', acceptanceIds: ['a', 'b'] };
47
+ const result = acceptanceDrift(prev, 'new', ['a', 'c']);
48
+ expect(result.added).toEqual(['c']);
49
+ expect(result.removed).toEqual(['b']);
50
+ expect(result.drift[0].kind).toBe('acceptance');
51
+ expect(acceptanceDrift(prev, 'old', ['a', 'b']).drift).toEqual([]);
52
+ });
53
+
54
+ it('只有交付后内容变化才 reopen', () => {
55
+ const prev = { verdict: 'deliverable', contentHash: 'h1' };
56
+ expect(shouldReopen(prev, 'deliverable', 'h2')).toBe(true);
57
+ expect(shouldReopen(prev, 'deliverable', 'h1')).toBe(false);
58
+ expect(shouldReopen({ ...prev, verdict: 'reopened' }, 'deliverable', 'h2')).toBe(false);
59
+ expect(shouldReopen(prev, 'failing', 'h2')).toBe(false);
60
+ });
61
+ });
62
+
63
+ describe('coverageSets', () => {
64
+ it('recorded 场景只计入 declared,不覆盖验收', () => {
65
+ const spec = { ok: true, file: '/app/scenarios/spec.json', covers: ['a'] };
66
+ const recorded = { ok: true, file: '/app/scenarios/rec.json', covers: ['b'] };
67
+ const origins = new Map([[spec.file, 'spec'], [recorded.file, 'recorded']]);
68
+ const { covered, declared } = coverageSets([spec, recorded], origins);
69
+ expect([...covered]).toEqual(['a']);
70
+ expect([...declared].sort()).toEqual(['a', 'b']);
71
+ });
72
+ });
73
+
74
+ describe('能力偏离', () => {
75
+ it('无基线快照时跳过,不误报旧应用', () => {
76
+ expect(capabilityDrift({ factory: null, actual: { enableVoiceInput: false } }).skipped).toBe(true);
77
+ });
78
+
79
+ it('user-intent 偏离告警,declared 只记录', () => {
80
+ const result = capabilityDrift({
81
+ factory: { enableVoiceInput: true, enableImageUpload: true, enableTTS: true },
82
+ actual: { enableVoiceInput: false, enableImageUpload: false, enableTTS: true },
83
+ });
84
+ expect(result.items.map((item) => item.key).sort()).toEqual(['enableImageUpload', 'enableVoiceInput']);
85
+ expect(result.items.find((item) => item.key === 'enableVoiceInput').severity).toBe('warn');
86
+ expect(result.items.find((item) => item.key === 'enableImageUpload').severity).toBe('info');
87
+ });
88
+
89
+ it('画像覆盖已进快照:同值与出厂一致时不产生偏离', () => {
90
+ const result = capabilityDrift({ factory: { enableTTS: false }, actual: { enableTTS: false } });
91
+ expect(result.items).toEqual([]);
92
+ });
93
+ });
94
+
95
+ describe('档位解析', () => {
96
+ it('平台注入优先', () => {
97
+ expect(resolvePolicy({ platformPolicy: 'flow', docPolicy: 'static' }).policy).toBe('flow');
98
+ });
99
+
100
+ it('应用降档没有理由时忽略,回落 visual', () => {
101
+ const result = resolvePolicy({ docPolicy: 'static' });
102
+ expect(result.policy).toBe('visual');
103
+ expect(result.downgradeIgnored).toBe(true);
104
+ });
105
+
106
+ it('应用降档写了理由时采纳', () => {
107
+ expect(resolvePolicy({ docPolicy: 'static', docPolicyReason: '用户要求快速交付' }).policy).toBe('static');
108
+ });
109
+ });
110
+
111
+ describe('场景删除漂移', () => {
112
+ it('上次记录的场景消失时报告', () => {
113
+ const drift = scenarioDrift({ scenarioHashes: { 'scenarios/a.json': 'h1', 'scenarios/b.json': 'h2' } }, { 'scenarios/a.json': 'h1' });
114
+ expect(drift).toEqual([{ kind: 'scenario-removed', detail: '场景被删除:scenarios/b.json' }]);
115
+ });
116
+ });
117
+
118
+ describe('版本比较(since)', () => {
119
+ it('同版本与更高版本满足,低版本不满足', () => {
120
+ expect(versionAtLeast('1.0.0-alpha.8', '1.0.0-alpha.8')).toBe(true);
121
+ expect(versionAtLeast('1.0.0-alpha.9', '1.0.0-alpha.8')).toBe(true);
122
+ expect(versionAtLeast('1.0.0-alpha.7', '1.0.0-alpha.8')).toBe(false);
123
+ expect(versionAtLeast('1.0.0', '1.0.0-alpha.8')).toBe(true);
124
+ expect(versionAtLeast('1.0.0-alpha.8', '1.0.0')).toBe(false);
125
+ });
126
+ });
127
+
128
+ describe('对比度颜色(实现来自 theme-kernel)', () => {
129
+ it('解析 hex / rgb / oklch,并计算黑白对比', () => {
130
+ expect(parseColor('#fff')).toMatchObject({ r: 255, g: 255, b: 255 });
131
+ expect(parseColor('rgb(0, 0, 0)')).toMatchObject({ r: 0, g: 0, b: 0 });
132
+ expect(parseColor('oklch(0.62796 0.25768 29.23)')).toMatchObject({ r: 255, g: 0, b: 0 });
133
+ expect(contrastRatio(parseColor('#000'), parseColor('#fff'))).toBeCloseTo(21, 0);
134
+ });
135
+ });