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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/.gitignore +7 -0
  2. package/.tbox/app.json +1 -1
  3. package/.tbox/default-modules.json +1 -1
  4. package/.tbox/factory/chat.json +9 -0
  5. package/.tbox/miniapp-containers.json +1 -1
  6. package/AGENTS.md +4 -2
  7. package/apps/client/package.json +1 -0
  8. package/apps/client/scripts/._color-scan.test.mjs +0 -0
  9. package/apps/client/scripts/._experience-checks.mjs +0 -0
  10. package/apps/client/scripts/._geometry-kernel.test.mjs +0 -0
  11. package/apps/client/scripts/._in-process-checks.mjs +0 -0
  12. package/apps/client/scripts/._probe-checks.mjs +0 -0
  13. package/apps/client/scripts/._sample-entries.test.mjs +0 -0
  14. package/apps/client/scripts/._storyboard.test.mjs +0 -0
  15. package/apps/client/scripts/._theme-kernel.mjs +0 -0
  16. package/apps/client/scripts/._theme-kernel.test.mjs +0 -0
  17. package/apps/client/scripts/acceptance-changes.test.mjs +97 -0
  18. package/apps/client/scripts/check-evidence.mjs +361 -94
  19. package/apps/client/scripts/color-scan.mjs +66 -0
  20. package/apps/client/scripts/color-scan.test.mjs +25 -0
  21. package/apps/client/scripts/evidence-gate.mjs +248 -46
  22. package/apps/client/scripts/evidence-gate.test.mjs +63 -5
  23. package/apps/client/scripts/experience-checks.mjs +163 -0
  24. package/apps/client/scripts/geometry-kernel.test.mjs +92 -0
  25. package/apps/client/scripts/in-process-checks.mjs +51 -0
  26. package/apps/client/scripts/lib/._card-registry.mjs +0 -0
  27. package/apps/client/scripts/lib/._card-registry.test.mjs +0 -0
  28. package/apps/client/scripts/lib/._evidence-inputs.mjs +0 -0
  29. package/apps/client/scripts/lib/._evidence-inputs.test.mjs +0 -0
  30. package/apps/client/scripts/lib/._static-render.mjs +0 -0
  31. package/apps/client/scripts/lib/._static-render.test.mjs +0 -0
  32. package/apps/client/scripts/lib/card-registry.mjs +81 -0
  33. package/apps/client/scripts/lib/card-registry.test.mjs +59 -0
  34. package/apps/client/scripts/lib/evidence-inputs.mjs +91 -0
  35. package/apps/client/scripts/lib/evidence-inputs.test.mjs +27 -0
  36. package/apps/client/scripts/lib/static-render.mjs +35 -0
  37. package/apps/client/scripts/lib/static-render.test.mjs +21 -0
  38. package/apps/client/scripts/probe-checks.mjs +85 -0
  39. package/apps/client/scripts/render-card.mjs +76 -60
  40. package/apps/client/scripts/sample-entries.test.mjs +31 -0
  41. package/apps/client/scripts/storyboard.test.mjs +149 -0
  42. package/apps/client/scripts/surface-css.mjs +5 -2
  43. package/apps/client/scripts/theme-kernel.mjs +236 -0
  44. package/apps/client/scripts/theme-kernel.test.mjs +136 -0
  45. package/apps/client/src/styles/brand.css +11 -11
  46. package/apps/client/src/styles/tailwind.css +3 -4
  47. package/apps/client/vite.config.ts +2 -1
  48. package/apps/server/scripts/probe.mjs +6 -1
  49. package/apps/server/scripts/scenario-lib.mjs +54 -7
  50. package/apps/server/scripts/scenario.mjs +41 -7
  51. package/config/AGENTS.md +1 -0
  52. package/config/chat.json +21 -9
  53. package/docs/agent/card.md +1 -0
  54. package/docs/agent/kit.md +1 -1
  55. package/docs/agent/shell.md +1 -0
  56. package/docs/agent/style.md +3 -1
  57. package/docs/agent/verify.md +37 -8
  58. package/package.json +9 -6
  59. package/packages/agent-ui-kit/README.md +21 -1
  60. package/packages/agent-ui-kit/catalog.json +1 -1
  61. package/packages/agent-ui-kit/package.json +9 -1
  62. package/packages/agent-ui-kit/src/ChatPage.tsx +30 -1
  63. package/packages/agent-ui-kit/src/card/primitives.test.tsx +10 -0
  64. package/packages/agent-ui-kit/src/card/primitives.tsx +14 -10
  65. package/packages/agent-ui-kit/src/card/view-card.tsx +6 -1
  66. package/packages/agent-ui-kit/src/chat-config.ts +11 -7
  67. package/packages/agent-ui-kit/src/components/ActionBar/DebugButton.test.tsx +3 -0
  68. package/packages/agent-ui-kit/src/components/ActionBar/DebugButton.tsx +2 -7
  69. package/packages/agent-ui-kit/src/components/BottomSheet/._index.test.tsx +0 -0
  70. package/packages/agent-ui-kit/src/components/BottomSheet/._index.tsx +0 -0
  71. package/packages/agent-ui-kit/src/components/BottomSheet/index.test.tsx +90 -0
  72. package/packages/agent-ui-kit/src/components/BottomSheet/index.tsx +129 -0
  73. package/packages/agent-ui-kit/src/components/ChatInput/index.test.tsx +2 -2
  74. package/packages/agent-ui-kit/src/components/ChatInput/index.tsx +21 -16
  75. package/packages/agent-ui-kit/src/components/HistoryEntry/index.tsx +1 -0
  76. package/packages/agent-ui-kit/src/components/QuickCommands/index.tsx +2 -2
  77. package/packages/agent-ui-kit/src/components/ScrollToBottomButton/index.tsx +7 -3
  78. package/packages/agent-ui-kit/src/components/ToolCallBlock/index.tsx +4 -2
  79. package/packages/agent-ui-kit/src/index.ts +4 -0
  80. package/packages/agent-ui-kit/src/shell.contract.json +9 -0
  81. package/packages/agent-ui-kit/src/shell.test.ts +10 -0
  82. package/packages/agent-ui-kit/src/shell.ts +15 -0
  83. package/packages/agent-ui-kit/src/theme/contract.json +78 -1
  84. package/packages/agent-ui-kit/src/theme/theme-contract.test.ts +16 -0
  85. package/packages/agent-ui-kit/src/theme/tokens.css +1 -1
  86. package/pnpm-lock.template.yaml +97 -91
  87. package/pnpm-workspace.template.yaml +10 -10
  88. package/profiles/mall/._chat.overrides.json +0 -0
  89. package/profiles/mall/chat.overrides.json +12 -0
  90. package/profiles/mall/config/chat.json +14 -6
  91. package/profiles/mall.json +1 -1
  92. package/scripts/._deliver.mjs +0 -0
  93. package/scripts/._shell-probe.mjs +0 -0
  94. package/scripts/._storyboard.mjs +0 -0
  95. package/scripts/check-fast.mjs +1 -0
  96. package/scripts/checks.json +294 -17
  97. package/scripts/deliver.mjs +183 -0
  98. package/scripts/lib/._chrome-pipe.mjs +0 -0
  99. package/scripts/lib/._geometry-kernel.mjs +0 -0
  100. package/scripts/lib/chrome-pipe.mjs +95 -0
  101. package/scripts/lib/geometry-kernel.mjs +137 -0
  102. package/scripts/shell-probe.mjs +283 -0
  103. package/scripts/storyboard.mjs +350 -0
  104. package/profiles/mall/config/llm_provider.json +0 -5
  105. package/profiles/mall/config/plugins.json +0 -3
  106. package/scripts/gen-tailwind-sources.mjs +0 -55
  107. /package/{profiles/mall/config/._llm_provider.json → .tbox/factory/._chat.json} +0 -0
  108. /package/{profiles/mall/config/._plugins.json → apps/client/scripts/._acceptance-changes.test.mjs} +0 -0
  109. /package/{scripts/._gen-tailwind-sources.mjs → apps/client/scripts/._color-scan.mjs} +0 -0
@@ -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
+ });
@@ -43,6 +43,175 @@ export function hashSourceTree(root) {
43
43
  return { hash: hash.digest('hex').slice(0, 16), files };
44
44
  }
45
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
+
46
215
  export function acceptanceDrift(prevGate, acceptanceHash, acceptanceIds) {
47
216
  if (!prevGate || !prevGate.acceptanceHash || !acceptanceHash || prevGate.acceptanceHash === acceptanceHash) {
48
217
  return { added: [], removed: [], drift: [] };
@@ -78,58 +247,91 @@ export function coverageSets(scenarioResults, originByFile) {
78
247
  return { covered, declared };
79
248
  }
80
249
 
81
- export function scenarioKey(appDir, file) {
82
- return path.relative(appDir, file);
83
- }
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
+ };
84
257
 
85
- export function parseColor(value) {
86
- if (!value) return null;
87
- const oklch = /^oklch\(\s*([\d.]+)(%?)\s+([\d.]+)\s+([\d.]+)(?:deg|rad|grad|turn)?(?:\s*\/\s*[\d.]+%?)?\s*\)$/i.exec(value);
88
- if (oklch) {
89
- const lightness = Number(oklch[1]) / (oklch[2] === '%' ? 100 : 1);
90
- const chroma = Number(oklch[3]);
91
- const hue = (Number(oklch[4]) * Math.PI) / 180;
92
- const a = chroma * Math.cos(hue);
93
- const b = chroma * Math.sin(hue);
94
- const lRoot = lightness + 0.3963377774 * a + 0.2158037573 * b;
95
- const mRoot = lightness - 0.1055613458 * a - 0.0638541728 * b;
96
- const sRoot = lightness - 0.0894841775 * a - 1.291485548 * b;
97
- const l = lRoot ** 3;
98
- const m = mRoot ** 3;
99
- const sVal = sRoot ** 3;
100
- const linear = [
101
- 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * sVal,
102
- -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * sVal,
103
- -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * sVal,
104
- ];
105
- return linear.map((channel) => {
106
- const gamma = channel <= 0.0031308 ? 12.92 * channel : 1.055 * Math.pow(Math.max(channel, 0), 1 / 2.4) - 0.055;
107
- return Math.round(Math.min(1, Math.max(0, gamma)) * 255);
108
- });
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: [] };
109
267
  }
110
- const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(value);
111
- if (hex) {
112
- let h = hex[1];
113
- if (h.length === 3) h = h.split('').map((c) => c + c).join('');
114
- return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16));
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' });
115
275
  }
116
- const rgb = /^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(value);
117
- if (rgb) return [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])];
118
- return null;
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 };
119
290
  }
120
291
 
121
- export function luminance(rgb) {
122
- const channel = (c) => {
123
- const x = c / 255;
124
- return x <= 0.03928 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
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('.') : [];
125
308
  };
126
- return 0.2126 * channel(rgb[0]) + 0.7152 * channel(rgb[1]) + 0.0722 * channel(rgb[2]);
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;
127
330
  }
128
331
 
129
- export function contrastRatio(fg, bg) {
130
- const a = luminance(fg);
131
- const b = luminance(bg);
132
- const hi = Math.max(a, b);
133
- const lo = Math.min(a, b);
134
- return (hi + 0.05) / (lo + 0.05);
332
+ export function scenarioKey(appDir, file) {
333
+ return path.relative(appDir, file);
135
334
  }
335
+
336
+ // 颜色解析与对比度只有一份实现(apps/client/scripts/theme-kernel.mjs),门禁与 theme 命令共用。
337
+ export { parseColor, contrastRatio } from './theme-kernel.mjs';
@@ -4,10 +4,14 @@ import path from 'node:path';
4
4
  import { afterEach, describe, expect, it } from 'vitest';
5
5
  import {
6
6
  acceptanceDrift,
7
+ capabilityDrift,
7
8
  contrastRatio,
8
9
  coverageSets,
9
10
  hashSourceTree,
10
11
  parseColor,
12
+ resolvePolicy,
13
+ scenarioDrift,
14
+ versionAtLeast,
11
15
  shouldReopen,
12
16
  } from './evidence-gate.mjs';
13
17
 
@@ -67,11 +71,65 @@ describe('coverageSets', () => {
67
71
  });
68
72
  });
69
73
 
70
- describe('对比度颜色', () => {
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)', () => {
71
129
  it('解析 hex / rgb / oklch,并计算黑白对比', () => {
72
- expect(parseColor('#fff')).toEqual([255, 255, 255]);
73
- expect(parseColor('rgb(0, 0, 0)')).toEqual([0, 0, 0]);
74
- expect(parseColor('oklch(0.62796 0.25768 29.23)')).toEqual([255, 0, 0]);
75
- expect(contrastRatio([0, 0, 0], [255, 255, 255])).toBeCloseTo(21, 0);
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);
76
134
  });
77
135
  });
@@ -0,0 +1,163 @@
1
+ /**
2
+ * 静态体验检查执行器(checks.json 的 source=experience + phase=static)。
3
+ *
4
+ * 新增检查 = checks.json 一行 + STATIC_CHECKS 一段;门禁主流程不再改。
5
+ * 每条返回 { status, detail },lane 由 checks.json 决定。
6
+ */
7
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
8
+ import path from 'node:path';
9
+ import { scanColorLiterals } from './color-scan.mjs';
10
+ import { nearestToken, readTokens } from './theme-kernel.mjs';
11
+
12
+ export const STATIC_CHECKS = {
13
+ 'boot.inline-script': ({ clientDir }) => {
14
+ try {
15
+ const html = readFileSync(path.join(clientDir, 'index.html'), 'utf8');
16
+ const inline = [...html.matchAll(/<script\b([^>]*)>/gi)].filter((match) => !/\bsrc\s*=/.test(match[1]));
17
+ return { status: inline.length === 0 ? 'pass' : 'fail', detail: inline.length === 0 ? '入口零内联脚本' : '入口有 ' + inline.length + ' 段内联脚本' };
18
+ } catch (error) {
19
+ return { status: 'fail', detail: '读不到 apps/client/index.html:' + (error?.message ?? error) };
20
+ }
21
+ },
22
+
23
+ 'shell.identity': ({ appDir }) => {
24
+ try {
25
+ const source = readFileSync(path.join(appDir, 'packages/agent-ui-kit/src/components/MessageBubble/index.tsx'), 'utf8');
26
+ return { status: source.includes('identity?.name') ? 'pass' : 'fail', detail: '发送者名取 identity.name' };
27
+ } catch (error) {
28
+ return { status: 'deferred', detail: 'kit 副本不在预期位置:' + (error?.message ?? error) };
29
+ }
30
+ },
31
+
32
+ 'quick.label-query': ({ appDir }) => {
33
+ try {
34
+ const chat = JSON.parse(readFileSync(path.join(appDir, 'config/chat.json'), 'utf8'));
35
+ const bad = (Array.isArray(chat.quickCommands) ? chat.quickCommands : []).filter((command) =>
36
+ command && command.label && command.query && command.query !== command.label && !String(command.query).includes(command.label));
37
+ return {
38
+ status: bad.length > 0 ? 'fail' : 'pass',
39
+ detail: bad.length > 0 ? '文案不一致:' + bad.map((command) => command.label + '→' + command.query).join('、') : '快捷问题文案一致',
40
+ };
41
+ } catch {
42
+ return { status: 'deferred', detail: '读不到 config/chat.json' };
43
+ }
44
+ },
45
+
46
+ 'meta.brand': ({ appDir }) => {
47
+ try {
48
+ const chatPage = readFileSync(path.join(appDir, 'packages/agent-ui-kit/src/ChatPage.tsx'), 'utf8');
49
+ const ok = chatPage.includes('document.title') && chatPage.includes('theme-color');
50
+ return { status: ok ? 'pass' : 'fail', detail: ok ? '标题与主题色跟身份注入' : 'kit 未注入标题/主题色' };
51
+ } catch {
52
+ return { status: 'deferred', detail: 'kit 副本不在预期位置' };
53
+ }
54
+ },
55
+
56
+ 'style.url-quoted': ({ appDir }) => {
57
+ try {
58
+ const files = ['components/QuickCommands/index.tsx', 'components/ChatInput/index.tsx'];
59
+ const offenders = files.filter((file) => {
60
+ const full = path.join(appDir, 'packages/agent-ui-kit/src', file);
61
+ if (!existsSync(full)) return false;
62
+ return /url\(\$\{/.test(readFileSync(full, 'utf8'));
63
+ });
64
+ return {
65
+ status: offenders.length > 0 ? 'fail' : 'pass',
66
+ detail: offenders.length > 0 ? '未加引号的 url():' + offenders.join('、') : 'url() 均已加引号',
67
+ };
68
+ } catch {
69
+ return { status: 'deferred', detail: 'kit 源码不可读' };
70
+ }
71
+ },
72
+
73
+ 'kit.color-literal': ({ appDir }) => {
74
+ try {
75
+ const cardDir = path.join(appDir, 'packages/agent-ui-kit/src/card');
76
+ const sources = ['primitives.tsx', 'view-card.tsx']
77
+ .filter((file) => existsSync(path.join(cardDir, file)))
78
+ .map((file) => readFileSync(path.join(cardDir, file), 'utf8'))
79
+ .join('\n');
80
+ const literals = sources.match(/#[0-9a-fA-F]{3,8}\b|rgba?\(/g) ?? [];
81
+ return {
82
+ status: literals.length > 0 ? 'fail' : 'pass',
83
+ detail: literals.length > 0 ? '卡片基元里有 ' + literals.length + ' 处非令牌色值' : '卡片基元零色值字面量',
84
+ };
85
+ } catch {
86
+ return { status: 'deferred', detail: 'kit 卡片源码不可读' };
87
+ }
88
+ },
89
+
90
+ // 同一色值三处以上就该进契约(style.md 的规则由检查兜住);只提示不阻断。
91
+ 'style.color-repeat': ({ appDir }) => {
92
+ try {
93
+ const files = [];
94
+ // styles/ 是令牌的家(brand.css 与 tailwind.css 的 var(..., 兜底) 映射):那里不是「写死的色值」。
95
+ const stylesDir = path.join(appDir, 'apps/client/src/styles');
96
+ for (const dir of ['apps/client/src', 'apps/server/src/cards']) {
97
+ const root = path.join(appDir, dir);
98
+ if (!existsSync(root)) continue;
99
+ const walk = (current) => {
100
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
101
+ const full = path.join(current, entry.name);
102
+ if (entry.isDirectory()) walk(full);
103
+ else if (/\.(tsx?|css)$/.test(entry.name) && !full.startsWith(stylesDir)) files.push(full);
104
+ }
105
+ };
106
+ walk(root);
107
+ }
108
+ const tokens = readTokens([
109
+ path.join(appDir, 'packages/agent-ui-kit/src/theme/tokens.css'),
110
+ path.join(appDir, 'apps/client/src/styles/brand.css'),
111
+ ].filter((file) => existsSync(file)));
112
+ const groups = [...scanColorLiterals(files).entries()].filter(([, value]) => value.count >= 3).sort((left, right) => right[1].count - left[1].count);
113
+ if (groups.length === 0) return { status: 'pass', detail: '没有重复 3 次以上的色值字面量' };
114
+ const detail = groups.slice(0, 5).map(([hex, value]) => {
115
+ const near = nearestToken(hex, tokens);
116
+ return hex + ' ×' + value.count + (near ? ' → 最近令牌 ' + near.token + '(ΔE ' + near.delta + ')' : '');
117
+ }).join(';');
118
+ return { status: 'fail', detail: groups.length + ' 组重复色值:' + detail };
119
+ } catch (error) {
120
+ return { status: 'deferred', detail: '色值扫描不可用:' + (error instanceof Error ? error.message : String(error)) };
121
+ }
122
+ },
123
+
124
+ 'card.action-primary': ({ appDir }) => {
125
+ try {
126
+ const viewCard = readFileSync(path.join(appDir, 'packages/agent-ui-kit/src/card/view-card.tsx'), 'utf8');
127
+ const ok = viewCard.includes('index === 0') && viewCard.includes("'primary'") && viewCard.includes("'secondary'");
128
+ return { status: ok ? 'pass' : 'fail', detail: ok ? '首个动作为主按钮' : '视图卡未按序分主次' };
129
+ } catch {
130
+ return { status: 'deferred', detail: '视图卡源码不可读' };
131
+ }
132
+ },
133
+
134
+ 'shell.type-scale': ({ appDir, clientDir }) => {
135
+ const offScale = [];
136
+ for (const root of [path.join(clientDir, 'src'), path.join(appDir, 'packages/agent-ui-kit/src')]) {
137
+ if (!existsSync(root)) continue;
138
+ const walk = (dir) => {
139
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
140
+ const full = path.join(dir, entry.name);
141
+ if (entry.isDirectory()) walk(full);
142
+ else if (/\.(tsx?|css)$/.test(entry.name) && !entry.name.endsWith('.test.tsx')) {
143
+ if (/text-\[\d+(?:\.\d+)?px\]/.test(readFileSync(full, 'utf8'))) offScale.push(path.relative(appDir, full));
144
+ }
145
+ }
146
+ };
147
+ walk(root);
148
+ }
149
+ return {
150
+ status: offScale.length === 0 ? 'pass' : 'fail',
151
+ detail: offScale.length === 0 ? '档外字号 0 处' : '档外字号:' + offScale.slice(0, 5).join('、'),
152
+ };
153
+ },
154
+ };
155
+
156
+ /** 按 checks.json 的 phase=static 顺序执行;未知 id 明确失败,避免「登记了但静默没跑」。 */
157
+ export function runStaticChecks(context, ids) {
158
+ return ids.map((id) => {
159
+ const run = STATIC_CHECKS[id];
160
+ if (!run) return { id, status: 'fail', detail: '静态执行器没有实现(检查登记与 experience-checks.mjs 不一致)' };
161
+ return { id, ...run(context) };
162
+ });
163
+ }