ztheme-cli 0.0.7 → 0.0.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.
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  > CLI 是本仓原创代码,与 upstream tweakcn 无关。
5
5
 
6
6
  不依赖 shadcn 的主题 CLI。只走 HTTP,不需要 shadcn CLI、不需要 MCP、不需要登录。
7
- 当前版本 **0.0.7**(`npm i -g ztheme-cli` 或 `npx ztheme-cli@0.0.7` 都行,下文统一写 `ztheme`)。
7
+ 当前版本 **0.0.9**(`npm i -g ztheme-cli` 或 `npx ztheme-cli@0.0.9` 都行,下文统一写 `ztheme`)。
8
8
 
9
9
  ## 前提:告诉它站点在哪
10
10
 
@@ -88,7 +88,7 @@ ztheme init modern-minimal --dir . # 显式指定项目根
88
88
  |---|---|
89
89
  | `ztheme/<slug>.css` | `:root` + `.dark` 两段 CSS 变量 |
90
90
  | `AGENTS.md` | 一个幂等标记块:令牌表 + 可判定断言 + 禁用组合 + **改完必须跑的那条命令** |
91
- | `.ztheme/theme-lock.json` | slug + 主题 digest + 阈值 + 断言 + 锁定时刻的判定结果 |
91
+ | `.ztheme/theme-lock.json` | slug + 主题 digest + 令牌快照 + 阈值 + 断言 + 锁定时刻的判定结果(与验证结论) |
92
92
 
93
93
  `AGENTS.md` 里写的是**相对项目根**的路径(`ztheme/<slug>.css`),可以直接提交进仓库。
94
94
  (0.0.4 曾把本机绝对路径写进去,换台机器就跑不了;0.0.5 修了,并有测试守着。)
@@ -103,10 +103,33 @@ ztheme check --lock --file ztheme/modern-minimal.css --strict
103
103
  报两类漂移:① 本地 CSS 比锁定版本变差;② 站点上那套主题的 digest 变了。
104
104
  正常时输出「无漂移:主题与锁定版本一致」;`--strict` 下有漂移即 exit 1。
105
105
 
106
+ 只想知道「上游改了什么、会不会把对比度弄坏」时,用 `upgrade --check`:
107
+
108
+ ```bash
109
+ ztheme upgrade --check # 读 .ztheme/theme-lock.json
110
+ ztheme upgrade --check --strict # 有漂移即 exit 1(CI 用)
111
+ ```
112
+
113
+ 它逐项列出 light / dark 的令牌增删改,并按**锁定时的断言**重判站点当前版本,
114
+ 报告新增问题、已修复、新增无法判定的数量。旧锁文件没有令牌快照时只报 digest 漂移,
115
+ 提示重跑 `init` 升级锁格式;不会拿 digest 反推内容,也不自动改写任何文件。
116
+
117
+ 确认要跟之后,用 `upgrade --pr` 生成本地分支:
118
+
119
+ ```bash
120
+ ztheme upgrade --pr # 默认 dry-run:只打印计划
121
+ ztheme upgrade --pr --write # 建分支 ztheme/upgrade-<slug>、重写 ztheme/<slug>.css、更新锁并提交
122
+ ```
123
+
124
+ 要求工作区干净(脏了会让「这次升级改了什么」混进无关改动),不会 push、不会合入;
125
+ 下一步由你 `git push -u origin <branch>` 后开 PR 人审。生成文件头写着「勿手改」,
126
+ 所以升级会整份重写;如果本地 CSS 与锁定令牌不一致(可能手改过),默认拒绝,
127
+ 确认要覆盖时加 `--force`。
128
+
106
129
  ## 7. CI 里最小接入
107
130
 
108
131
  ```yaml
109
- - run: npx ztheme-cli@0.0.7 check --file app/globals.css --rules 你的主题 --strict
132
+ - run: npx ztheme-cli@0.0.9 check --file app/globals.css --rules 你的主题 --strict
110
133
  env:
111
134
  ZTHEME_BASE: https://你的生产站点
112
135
  ```
@@ -180,6 +203,30 @@ JSON)会让 audit 以退出码 2 结束,而不是当作「没有规则」继
180
203
 
181
204
  > 阈值不自动从主题派生:「主题圆角 0.5rem」推不出「这个项目只准用这么大」,后者是团队的决定。
182
205
 
206
+ ### 自动修:`--fix`
207
+
208
+ ```bash
209
+ ztheme audit . --fix # 只打印 patch,不改任何文件
210
+ ztheme audit . --fix --write # 真正落盘,写完自动重扫并报告剩余
211
+ ztheme audit . --fix --json # fixes 数组 + diff,仍然不写盘
212
+ ```
213
+
214
+ 能自动修的三类:圆角/间距政策命中(换成规则允许的档位)、颜色命中(换成对应的 token 类,
215
+ 如 `bg-[#3b82f6]` → `bg-primary`)、行内纯颜色(换成 `var(--token)`)。`style` 里的
216
+ `boxShadow` 这类组合值不修——换掉整段会丢语义。`no-hardcoded-color` 永不自动修:
217
+ 在 TS 常量里塞 `var()` 是错的。
218
+
219
+ 每条修复带 `confidence`:
220
+
221
+ | 值 | 含义 | 处理建议 |
222
+ |---|---|---|
223
+ | `policy` | 违反了 `.ztheme/rules.json` 声明的上限 | 直接接受 |
224
+ | `exact` | 与某个 token 肉眼同色(ΔE < 2) | 直接接受 |
225
+ | `near` | 近似色或就近取整 | **先看**:dry-run 会把它们单独列出来 |
226
+
227
+ diff 是逐行的(`--- a/` / `+++ b/`),所有替换都不增删换行,所以行号与原文一一对应。
228
+ `--write` 只改命中的那几个字符,文件其余字节(包括 CRLF)不动。
229
+
183
230
  在 PR 里自动评论(复用 workflow,不单独装 App):
184
231
 
185
232
 
@@ -214,11 +261,14 @@ workflow 按 `<!-- ztheme-audit -->` 更新同一条评论,不刷屏;完整
214
261
  | `check --file <path> --rules <slug>` | 同时校验该主题的规则断言 |
215
262
  | `init <slug> [--dir .]` | 生成 CSS + `AGENTS.md` 片段 + 主题锁 |
216
263
  | `check --lock [--file <css>]` | 与锁文件比对,报漂移 |
264
+ | `upgrade --check [--lock <json>] [--strict]` | 与锁文件比对站点当前主题:令牌 diff + 对比度影响 |
265
+ | `upgrade --pr [--write]` | 生成本地升级分支:重写主题 CSS、更新锁并提交(默认 dry-run) |
217
266
  | `audit [path] [--json] [--theme <slug>] [--max-warnings n]` | 扫组件源码里的硬编码颜色与任意值 |
267
+ | `audit [path] --fix [--write]` | 打印可审阅的 patch;`--write` 才落盘 |
218
268
  | `--help` | 打印用法 |
219
269
 
220
270
  退出码:`0` 通过;`1` `--strict` 下出现「建议修」或「无法判定」,或有漂移,或 audit 有
221
- error / 超过 `--max-warnings`;`2` audit 的参数、配置或扫描错误。
271
+ error / 超过 `--max-warnings`;`2` audit 的参数、配置或扫描错误,或 upgrade 的参数 / 锁文件错误。
222
272
 
223
273
  ## 为什么这么小
224
274
 
@@ -230,6 +280,26 @@ error / 超过 `--max-warnings`;`2` audit 的参数、配置或扫描错误。
230
280
 
231
281
  ## 变更记录
232
282
 
283
+ ### 0.0.9
284
+
285
+ - 新增 `upgrade --check`:与锁文件比对站点当前主题,逐项列出 light / dark 令牌增删改,
286
+ 并按锁定时的断言重判对比度影响(新增问题 / 修复 / 新增无法判定分开报);`--strict` 判失败。
287
+ - 新增 `upgrade --pr`:默认 dry-run;`--write` 时要求工作区干净,建分支
288
+ `ztheme/upgrade-<slug>`、重写生成的 CSS、更新锁并提交,不 push、不自动合入。
289
+ 本地 CSS 与锁定令牌不一致时拒绝覆盖,`--force` 才继续。
290
+ - 锁文件增加 `tokens` 令牌快照;站点返回验证结论时记录 `verifiedOk` 与 `verifiedAt`。
291
+ 旧锁文件仍可读,只是没有令牌快照时无法逐项 diff。
292
+ - 新增 `cli/upgrade.mjs`(纯函数:`diffTokens` / `summarizeChanges` / `contrastImpact` / `localDrift`)。
293
+
294
+ ### 0.0.8
295
+
296
+ - 新增 `audit --fix`:把建议落成可审阅的逐行 patch,**默认不写盘**,`--write` 才落盘。
297
+ - 每条修复带 `confidence`(`policy` / `exact` / `near`);近似色与就近取整单列提示。
298
+ - 行内颜色只修纯颜色值(`color: "#666"` → `var(--muted-foreground)`),组合值不碰;
299
+ `no-hardcoded-color` 永不自动修。
300
+ - 修复顺带修正了行内颜色定位偏移:此前 `style` 的 `{{` 之后 8 个字符没算进列号。
301
+ - `--fix --json` 输出 `fixes` / `diff` / `written`,`schemaVersion` 仍为 1。
302
+
233
303
  ### 0.0.7
234
304
 
235
305
  - 新增项目规则 `.ztheme/rules.json`:`radius.maxRem` 与 `spacing.baseUnit` 两条可声明阈值,
@@ -268,6 +338,7 @@ error / 超过 `--max-warnings`;`2` audit 的参数、配置或扫描错误。
268
338
 
269
339
  ## 尚未做
270
340
 
341
+ - 锁文件 `schemaVersion`:目前靠字段存在与否兼容旧格式。
271
342
  - Tailwind v4 的 `@theme inline` 映射片段(当前给的是 `:root` / `.dark` 变量,
272
343
  v4 项目照 `docs/presets/README` 的 `@theme inline` 写法接一下即可)
273
344
 
package/audit.mjs CHANGED
@@ -206,7 +206,7 @@ function buildPalette(theme) {
206
206
  return palette;
207
207
  }
208
208
 
209
- function suggestColor(value, palette) {
209
+ function suggestColorMatch(value, palette) {
210
210
  if (!palette.size) return null;
211
211
  const parsed = parseColor(value) ?? parseColor(extractColor(value) ?? "");
212
212
  if (!parsed) return null;
@@ -216,7 +216,11 @@ function suggestColor(value, palette) {
216
216
  if (!best || distance < best.distance) best = { token, distance };
217
217
  }
218
218
  if (!best || best.distance >= 10) return null;
219
- return "--" + best.token;
219
+ return { suggestion: "--" + best.token, distance: best.distance };
220
+ }
221
+
222
+ function suggestColor(value, palette) {
223
+ return suggestColorMatch(value, palette)?.suggestion ?? null;
220
224
  }
221
225
 
222
226
  function ignoredLinesOf(lines) {
@@ -305,6 +309,9 @@ export async function auditProject(options) {
305
309
  policy: extra?.policy ?? null,
306
310
  expected: extra?.expected ?? null,
307
311
  actual: extra?.actual ?? null,
312
+ // fix 是「可直接落盘的替换」:绝对偏移 + 新文本;confidence 让 --fix 能区分
313
+ // 「可证明等价」(exact / policy)与「近似」(near),后者必须人先看一眼。
314
+ fix: extra?.fix ?? null,
308
315
  });
309
316
  };
310
317
 
@@ -342,7 +349,18 @@ export async function auditProject(options) {
342
349
  const value = match[1];
343
350
  if (!isColorValue(value) || value.includes("var(")) continue;
344
351
  if (isCommentLine(text, starts, match.index)) continue;
345
- const outcome = emit(match, "no-arbitrary-color", value, suggestColor(value, palette));
352
+ const detail = suggestColorMatch(value, palette);
353
+ let fix = null;
354
+ const bracket = match[0].indexOf("-[");
355
+ if (detail && bracket > 0) {
356
+ fix = {
357
+ start: match.index,
358
+ end: match.index + match[0].length,
359
+ text: match[0].slice(0, bracket) + "-" + detail.suggestion.slice(2),
360
+ confidence: detail.distance < 2 ? "exact" : "near",
361
+ };
362
+ }
363
+ const outcome = emit(match, "no-arbitrary-color", value, detail?.suggestion ?? null, { fix });
346
364
  if (outcome === "ignored") ignoredCount += 1;
347
365
  }
348
366
 
@@ -360,6 +378,14 @@ export async function auditProject(options) {
360
378
  policy: verdict.rule === RULE_RADIUS ? "radius" : "spacing",
361
379
  expected: verdict.expected,
362
380
  actual: verdict.actual,
381
+ fix: verdict.suggestion
382
+ ? {
383
+ start: match.index,
384
+ end: match.index + match[0].length,
385
+ text: verdict.suggestion,
386
+ confidence: "policy",
387
+ }
388
+ : null,
363
389
  });
364
390
  if (outcome === "ignored") ignoredCount += 1;
365
391
  }
@@ -374,14 +400,34 @@ export async function auditProject(options) {
374
400
  for (const block of text.matchAll(R_STYLE_BLOCK)) {
375
401
  const blockStart = block.index ?? 0;
376
402
  const body = block[1] ?? "";
403
+ // property.index 是相对 body 的;body 从 `{{` 之后开始。少加这段偏移会让
404
+ // 行内颜色的定位(以及 fix 区间)整体前移 8 个字符。
405
+ const bodyOffset = (block[0] ?? "").indexOf("{{") + 2;
377
406
  R_STYLE_COLOR.lastIndex = 0;
378
407
  for (const property of body.matchAll(R_STYLE_COLOR)) {
379
408
  const rawValue = property[3] ?? "";
380
409
  if (!isColorValue(rawValue) || rawValue.includes("var(")) continue;
381
410
  const value = extractColor(rawValue) ?? rawValue;
382
- const index = blockStart + (property.index ?? 0);
411
+ const index = blockStart + bodyOffset + (property.index ?? 0);
383
412
  const fakeMatch = { index, 0: property[0] };
384
- const outcome = emit(fakeMatch, "no-inline-color", value, suggestColor(value, palette));
413
+ const detail = suggestColorMatch(value, palette);
414
+ // 只修「整个值就是一个颜色」的属性。boxShadow 这类组合值换掉整段会丢语义,
415
+ // 宁可让人手工改。
416
+ let fix = null;
417
+ if (detail && isPureColorValue(rawValue)) {
418
+ const colon = property[0].indexOf(":");
419
+ const quoteAt = property[0].indexOf(property[2], colon + 1);
420
+ if (quoteAt >= 0) {
421
+ const start = index + quoteAt + 1;
422
+ fix = {
423
+ start,
424
+ end: start + rawValue.length,
425
+ text: "var(" + detail.suggestion + ")",
426
+ confidence: detail.distance < 2 ? "exact" : "near",
427
+ };
428
+ }
429
+ }
430
+ const outcome = emit(fakeMatch, "no-inline-color", value, detail?.suggestion ?? null, { fix });
385
431
  if (outcome === "ignored") ignoredCount += 1;
386
432
  }
387
433
  }
package/fix.mjs ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * 把 finding 上的 fix 区间落成文本,并打印可审阅的 patch。
3
+ *
4
+ * 所有可修命中都是「同一个 token 内的局部替换」,不会增删换行——因此 applyFixes
5
+ * 之后行数与原文一一对应,diff 只需要逐行比较,不必引入 LCS。
6
+ */
7
+
8
+ /**
9
+ * 应用修复。区间按位置排序后先筛重叠(位置靠前的优先),再从后往前替换,
10
+ * 这样前面区间的偏移不会被后面的长度变化挤走。
11
+ */
12
+ export function applyFixes(text, fixes) {
13
+ if (!Array.isArray(fixes) || fixes.length === 0) return text;
14
+
15
+ const ordered = [...fixes]
16
+ .filter((fix) => Number.isInteger(fix.start) && Number.isInteger(fix.end))
17
+ .filter((fix) => fix.start >= 0 && fix.end >= fix.start)
18
+ .sort((left, right) => left.start - right.start);
19
+
20
+ const accepted = [];
21
+ let end = -1;
22
+ for (const fix of ordered) {
23
+ if (fix.start < end) continue; // 与前一个已接受区间重叠:跳过,不制造坏代码
24
+ accepted.push(fix);
25
+ end = fix.end;
26
+ }
27
+
28
+ let output = text;
29
+ for (let index = accepted.length - 1; index >= 0; index--) {
30
+ const fix = accepted[index];
31
+ output = output.slice(0, fix.start) + fix.text + output.slice(fix.end);
32
+ }
33
+ return output;
34
+ }
35
+
36
+ function splitLines(text) {
37
+ const lines = text.split("\n");
38
+ if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
39
+ return lines;
40
+ }
41
+
42
+ const stripCr = (line) => (line.endsWith("\r") ? line.slice(0, -1) : line);
43
+
44
+ /**
45
+ * 逐行 diff。`context` 是改动行上下文行数;相邻 hunk 自动合并。
46
+ * 行数不变是 applyFixes 的保证,这里仍按两边的最大长度遍历,避免越界。
47
+ */
48
+ export function diffLines(file, before, after, context = 3) {
49
+ if (before === after) return "";
50
+
51
+ const oldLines = splitLines(before);
52
+ const newLines = splitLines(after);
53
+ const total = Math.max(oldLines.length, newLines.length);
54
+
55
+ const changed = [];
56
+ for (let index = 0; index < total; index++) {
57
+ if ((oldLines[index] ?? "") !== (newLines[index] ?? "")) changed.push(index);
58
+ }
59
+ if (changed.length === 0) return "";
60
+
61
+ const hunks = [];
62
+ for (const index of changed) {
63
+ const start = Math.max(0, index - context);
64
+ const end = Math.min(total - 1, index + context);
65
+ const last = hunks[hunks.length - 1];
66
+ if (last && start <= last.end + 1) last.end = Math.max(last.end, end);
67
+ else hunks.push({ start, end });
68
+ }
69
+
70
+ const output = ["--- a/" + file, "+++ b/" + file];
71
+ for (const hunk of hunks) {
72
+ const count = hunk.end - hunk.start + 1;
73
+ output.push(
74
+ "@@ -" + (hunk.start + 1) + "," + count + " +" + (hunk.start + 1) + "," + count + " @@"
75
+ );
76
+ for (let index = hunk.start; index <= hunk.end; index++) {
77
+ const oldLine = oldLines[index] ?? "";
78
+ const newLine = newLines[index] ?? "";
79
+ if (oldLine === newLine) {
80
+ output.push(" " + stripCr(oldLine));
81
+ } else {
82
+ output.push("-" + stripCr(oldLine));
83
+ output.push("+" + stripCr(newLine));
84
+ }
85
+ }
86
+ }
87
+ return output.join("\n");
88
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ztheme-cli",
3
- "version": "0.0.7",
3
+ "version": "0.0.9",
4
4
  "description": "Ztheme 主题 CLI:从站点拉取主题 CSS 变量,并在仓库里扫设计漂移",
5
5
  "type": "module",
6
6
  "bin": {
@@ -11,6 +11,8 @@
11
11
  "audit.mjs",
12
12
  "color.mjs",
13
13
  "rules.mjs",
14
+ "fix.mjs",
15
+ "upgrade.mjs",
14
16
  "README.md",
15
17
  "LICENSE"
16
18
  ],
package/upgrade.mjs ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * 主题锁升级的纯函数部分(批次 D)。
3
+ *
4
+ * 只做「比较」:把锁定时的令牌快照与站点当前令牌逐项对比,再把两次对比度
5
+ * 判定的结果差分。不做网络、不读文件——CLI 负责取数,这里负责给出可复核的事实。
6
+ */
7
+
8
+ /**
9
+ * 逐项比较 { light, dark } 两份令牌表。
10
+ * 返回按 (mode, token) 稳定排序的增删改;值相同的不出现。
11
+ */
12
+ export function diffTokens(before, after) {
13
+ const changes = [];
14
+ for (const mode of ["light", "dark"]) {
15
+ const a = before?.[mode] ?? {};
16
+ const b = after?.[mode] ?? {};
17
+ const tokens = new Set([...Object.keys(a), ...Object.keys(b)]);
18
+ for (const token of [...tokens].sort()) {
19
+ const had = Object.prototype.hasOwnProperty.call(a, token);
20
+ const has = Object.prototype.hasOwnProperty.call(b, token);
21
+ if (had && has && a[token] === b[token]) continue;
22
+ if (!had) {
23
+ changes.push({ mode, token, kind: "added", before: null, after: b[token] });
24
+ } else if (!has) {
25
+ changes.push({ mode, token, kind: "removed", before: a[token], after: null });
26
+ } else {
27
+ changes.push({ mode, token, kind: "changed", before: a[token], after: b[token] });
28
+ }
29
+ }
30
+ }
31
+ return changes;
32
+ }
33
+
34
+ export function summarizeChanges(changes) {
35
+ const count = (kind) => changes.filter((change) => change.kind === kind).length;
36
+ return {
37
+ added: count("added"),
38
+ removed: count("removed"),
39
+ changed: count("changed"),
40
+ total: changes.length,
41
+ };
42
+ }
43
+
44
+ /**
45
+ * 本地 CSS 与锁定令牌的差异(手改检测)。
46
+ *
47
+ * 生成文件头写着「勿手改」,但人总会改。升级前先比对本地当前值与锁定快照,
48
+ * 有差异就要求显式 --force,避免把本地调整一口吞掉。
49
+ */
50
+ export function localDrift(localVars, lockedTokens) {
51
+ const drift = [];
52
+ for (const mode of ["light", "dark"]) {
53
+ const local = localVars?.[mode] ?? {};
54
+ const locked = lockedTokens?.[mode] ?? {};
55
+ const tokens = new Set([...Object.keys(local), ...Object.keys(locked)]);
56
+ for (const token of [...tokens].sort()) {
57
+ if (local[token] === locked[token]) continue;
58
+ drift.push({
59
+ mode,
60
+ token,
61
+ local: local[token] ?? null,
62
+ locked: locked[token] ?? null,
63
+ });
64
+ }
65
+ }
66
+ return drift;
67
+ }
68
+
69
+ const listOf = (value) => (Array.isArray(value) ? value : []);
70
+
71
+ /** 对比度判定的差分:新出现的问题与已修复的问题分开列,不许混成净变化数。 */
72
+ export function contrastImpact(before = {}, after = {}) {
73
+ const added = (key) => listOf(after[key]).filter((item) => !listOf(before[key]).includes(item));
74
+ const resolved = (key) =>
75
+ listOf(before[key]).filter((item) => !listOf(after[key]).includes(item));
76
+ return {
77
+ newFails: added("fails"),
78
+ resolvedFails: resolved("fails"),
79
+ newWarns: added("warns"),
80
+ resolvedWarns: resolved("warns"),
81
+ newUnknown: added("unknown"),
82
+ resolvedUnknown: resolved("unknown"),
83
+ };
84
+ }
package/ztheme.mjs CHANGED
@@ -15,11 +15,14 @@
15
15
  * 默认站点取 ZTHEME_BASE 环境变量,否则 http://localhost:3001。
16
16
  */
17
17
  import { createHash } from "node:crypto";
18
+ import { execFileSync } from "node:child_process";
18
19
  import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
19
20
  import { join, resolve } from "node:path";
20
21
 
21
22
  import { auditProject, formatHuman, formatJson } from "./audit.mjs";
23
+ import { applyFixes, diffLines } from "./fix.mjs";
22
24
  import { validateRules } from "./rules.mjs";
25
+ import { contrastImpact, diffTokens, localDrift, summarizeChanges } from "./upgrade.mjs";
23
26
 
24
27
  const BASE = (process.env.ZTHEME_BASE ?? "http://localhost:3001").replace(/\/$/, "");
25
28
 
@@ -308,6 +311,102 @@ const loadAuditTheme = async (root, slug) => {
308
311
  return { slug, source: "none", tokens: undefined };
309
312
  };
310
313
 
314
+ /**
315
+ * 把 findings 上的 fix 区间按文件归组,算出改前/改后与 patch。
316
+ * 只读不写——落盘是调用方在 --write 时做的事。
317
+ */
318
+ const buildFixPlan = (root, result) => {
319
+ const byFile = new Map();
320
+ for (const finding of result.findings) {
321
+ if (!finding.fix) continue;
322
+ if (!byFile.has(finding.file)) byFile.set(finding.file, []);
323
+ byFile.get(finding.file).push(finding);
324
+ }
325
+
326
+ const files = [];
327
+ const fixes = [];
328
+ const patches = [];
329
+ for (const [file, findings] of byFile) {
330
+ const before = readFileSync(join(root, file), "utf8");
331
+ const after = applyFixes(
332
+ before,
333
+ findings.map((finding) => finding.fix)
334
+ );
335
+ const diff = diffLines(file, before, after);
336
+ files.push({ file, before, after, diff });
337
+ if (diff) patches.push(diff);
338
+ for (const finding of findings) {
339
+ fixes.push({
340
+ file: finding.file,
341
+ line: finding.line,
342
+ column: finding.column,
343
+ rule: finding.rule,
344
+ from: finding.evidence,
345
+ to: finding.fix.text,
346
+ confidence: finding.fix.confidence,
347
+ });
348
+ }
349
+ }
350
+
351
+ fixes.sort(
352
+ (left, right) =>
353
+ left.file.localeCompare(right.file) || left.line - right.line || left.column - right.column
354
+ );
355
+ return {
356
+ files,
357
+ fixes,
358
+ diff: patches.join("\n"),
359
+ near: fixes.filter((fix) => fix.confidence === "near"),
360
+ };
361
+ };
362
+
363
+ const formatFixHuman = (result, plan, options) => {
364
+ const manual = result.findings.length - plan.fixes.length;
365
+ const lines = [];
366
+
367
+ if (!plan.fixes.length) {
368
+ lines.push("没有可自动修的问题(" + manual + " 条需要人工处理)");
369
+ return lines.join("\n");
370
+ }
371
+
372
+ const near = plan.near.length;
373
+ if (options.write) {
374
+ lines.push(
375
+ "已写入 " +
376
+ plan.files.filter((entry) => entry.diff).length +
377
+ " 个文件 · " +
378
+ plan.fixes.length +
379
+ " 处" +
380
+ (near ? "(其中近似 " + near + " 处)" : "")
381
+ );
382
+ lines.push("剩余 " + result.summary.warnings + " 条告警 · " + result.summary.errors + " 条错误");
383
+ } else {
384
+ lines.push(
385
+ "可自动修 " +
386
+ plan.fixes.length +
387
+ " 处" +
388
+ (near ? "(其中近似 " + near + " 处)" : "") +
389
+ ",需人工 " +
390
+ manual +
391
+ " 处"
392
+ );
393
+ }
394
+
395
+ if (near) {
396
+ lines.push("");
397
+ lines.push("近似修复(不是同色,换的是最近的 token / 刻度)请先确认:");
398
+ for (const fix of plan.near.slice(0, 10)) {
399
+ lines.push(" " + fix.file + ":" + fix.line + " " + fix.from + " → " + fix.to);
400
+ }
401
+ }
402
+
403
+ if (plan.diff) {
404
+ lines.push("");
405
+ lines.push(plan.diff);
406
+ }
407
+ return lines.join("\n");
408
+ };
409
+
311
410
 
312
411
  const TOKENS = [
313
412
  "background", "foreground", "card", "card-foreground", "popover", "popover-foreground",
@@ -355,7 +454,12 @@ const main = async () => {
355
454
  ztheme init <slug> [--dir .] 生成 ztheme/<slug>.css + AGENTS.md 片段 + .ztheme/theme-lock.json
356
455
  ztheme check --lock [--file x.css]
357
456
  与锁文件比对:本地 CSS 变差、或站点主题已更新时报警(--strict 判失败)
457
+ ztheme upgrade --check [--lock x.json] [--strict]
458
+ 与锁文件比对站点当前主题:列出令牌增删改与对比度影响(--strict 判失败)
459
+ ztheme upgrade --pr [--write] [--force]
460
+ 按站点当前版本生成本地升级分支(默认 dry-run;不 push、不合入)
358
461
  ztheme audit [path] [--json] [--theme <slug>] [--max-warnings <n>] [--quiet]
462
+ ztheme audit [path] --fix [--write] 打印可审阅的 patch;--write 才落盘
359
463
  扫描 TSX/JSX/TS/JS 里的硬编码颜色与任意值;
360
464
  --json 只输出 JSON;默认只告警,不阻断
361
465
  环境变量:
@@ -509,6 +613,11 @@ const main = async () => {
509
613
  base: BASE,
510
614
  lockedAt: new Date().toISOString(),
511
615
  themeDigest: digestOf(item.cssVars),
616
+ // 批次 D:锁住令牌快照,upgrade --check 才能逐项 diff;站点返回验证结论时一并记录
617
+ tokens: { light: lightVars, dark: darkVars },
618
+ ...(rulesRes.verified
619
+ ? { verifiedOk: !!rulesRes.verified.ok, verifiedAt: new Date().toISOString() }
620
+ : {}),
512
621
  boundary: checks.boundary ?? 2.6,
513
622
  pairs: checks.pairs,
514
623
  assertions,
@@ -530,6 +639,169 @@ const main = async () => {
530
639
  return;
531
640
  }
532
641
 
642
+ if (cmd === "upgrade") {
643
+ const doCheck = flags.has("check");
644
+ const doPr = flags.has("pr");
645
+ if (!doCheck && !doPr) failWith("用法:ztheme upgrade --check 或 upgrade --pr [--write]", 2);
646
+ if (doCheck && doPr) failWith("--check 与 --pr 只能选一个", 2);
647
+
648
+ const lockPath = valueOf("lock") ?? LOCK_FILE;
649
+ if (!existsSync(lockPath)) {
650
+ failWith("找不到锁文件:" + lockPath + "(先跑 ztheme init <slug>)", 2);
651
+ }
652
+
653
+ let lock;
654
+ try {
655
+ lock = JSON.parse(readFileSync(lockPath, "utf8"));
656
+ } catch (error) {
657
+ failWith("无法解析锁文件 " + lockPath + ":" + (error?.message ?? error), 2);
658
+ }
659
+ if (!lock?.slug) failWith("锁文件缺少 slug:" + lockPath, 2);
660
+
661
+ const site = await getJson("/r/themes/" + lock.slug);
662
+ const siteVars = site.cssVars ?? {};
663
+ const siteDigest = digestOf(siteVars);
664
+
665
+ if (siteDigest === lock.themeDigest) {
666
+ console.log(
667
+ doPr
668
+ ? `无漂移,不需要升级:站点上的 ${lock.slug} 与锁定版本一致(digest ${siteDigest})`
669
+ : `无漂移:站点上的 ${lock.slug} 与锁定版本一致(digest ${siteDigest})`
670
+ );
671
+ return;
672
+ }
673
+
674
+ console.log(
675
+ `漂移:站点上的 ${lock.slug} 已更新(锁定 ${lock.themeDigest},当前 ${siteDigest})`
676
+ );
677
+
678
+ let now = null;
679
+ if (!lock.tokens) {
680
+ // 旧锁文件只存 digest,逐项 diff 需要令牌快照;不拿 digest 反推,也不假装能比
681
+ console.log(
682
+ ` 锁文件里没有令牌快照(旧格式),无法逐项列出改动;重跑 ztheme init ${lock.slug} 可升级锁格式。`
683
+ );
684
+ if (doPr) {
685
+ failWith("没有令牌快照就无法生成升级分支;先重跑 ztheme init " + lock.slug, 2);
686
+ }
687
+ } else {
688
+ const variables = { light: siteVars.light ?? {}, dark: siteVars.dark ?? {} };
689
+ const changes = diffTokens(lock.tokens, variables);
690
+ const summary = summarizeChanges(changes);
691
+ console.log(
692
+ ` 令牌变化:新增 ${summary.added} / 删除 ${summary.removed} / 修改 ${summary.changed}`
693
+ );
694
+ for (const change of changes) {
695
+ console.log(
696
+ ` · ${change.mode} --${change.token}:${change.before ?? "—"} → ${change.after ?? "—"}`
697
+ );
698
+ }
699
+
700
+ // 影响必须按「锁定时的断言」重判当前站点,而不是拿新主题自己跟自己比
701
+ now = await postCheck(variables, lock.assertions ?? []);
702
+ const impact = contrastImpact(lock.result ?? {}, now);
703
+ console.log(
704
+ ` 对比度影响:新增问题 ${impact.newFails.length}、修复 ${impact.resolvedFails.length}、新增无法判定 ${impact.newUnknown.length}`
705
+ );
706
+ for (const item of impact.newFails) console.log(" × " + item);
707
+ for (const item of impact.resolvedFails) console.log(" ✓ " + item);
708
+ for (const item of impact.newUnknown) console.log(" ? " + item);
709
+ }
710
+
711
+ if (doCheck) {
712
+ console.log(` 跟随更新:重跑 ztheme init ${lock.slug};保持现状:忽略此提示。`);
713
+ if (flags.has("strict")) process.exit(1);
714
+ return;
715
+ }
716
+
717
+ // ---- upgrade --pr ----
718
+ const cssFile = valueOf("file") ?? join("ztheme", lock.slug + ".css");
719
+ if (!existsSync(cssFile)) {
720
+ failWith("找不到生成的主题 CSS:" + cssFile + "(先跑 ztheme init " + lock.slug + ")", 2);
721
+ }
722
+
723
+ const localVars = parseCssVars(readFileSync(cssFile, "utf8"));
724
+ const drift = localDrift(localVars, lock.tokens);
725
+ if (drift.length && !flags.has("force")) {
726
+ console.log(`本地 CSS 与锁定令牌不一致(${drift.length} 处),可能手改过:`);
727
+ for (const item of drift.slice(0, 10)) {
728
+ console.log(
729
+ ` · ${item.mode} --${item.token}:本地 ${item.local ?? "—"},锁定 ${item.locked ?? "—"}`
730
+ );
731
+ }
732
+ if (drift.length > 10) console.log(` · …共 ${drift.length} 处`);
733
+ failWith("拒绝覆盖本地修改;确认要按站点当前版本重写,请加 --force", 2);
734
+ }
735
+ if (drift.length) {
736
+ console.log(`已加 --force:本地修改将被站点当前版本覆盖(${drift.length} 处)`);
737
+ }
738
+
739
+ const branch = "ztheme/upgrade-" + lock.slug;
740
+ if (!flags.has("write")) {
741
+ console.log(
742
+ `[dry-run] 将重写 ${cssFile}、更新 ${lockPath},并创建分支 ${branch};加 --write 执行。`
743
+ );
744
+ return;
745
+ }
746
+
747
+ let status = "";
748
+ try {
749
+ status = execFileSync("git", ["status", "--porcelain"], { encoding: "utf8" });
750
+ } catch {
751
+ failWith("当前目录不是 git 仓库:upgrade --pr --write 需要 git", 2);
752
+ }
753
+ if (status.trim()) {
754
+ failWith("工作区不干净:先提交或暂存现有改动,再跑 upgrade --pr --write", 2);
755
+ }
756
+
757
+ try {
758
+ execFileSync("git", ["switch", "-c", branch], { encoding: "utf8", stdio: "pipe" });
759
+ } catch {
760
+ failWith("创建分支失败:" + branch + "(可能已存在或工作区受限)", 2);
761
+ }
762
+
763
+ const rulesRes = await tryGetJson("/r/themes/" + lock.slug + "/rules");
764
+ const siteVerified = rulesRes?.verified ?? null;
765
+ const nextLock = {
766
+ ...lock,
767
+ tokens: { light: siteVars.light ?? {}, dark: siteVars.dark ?? {} },
768
+ themeDigest: siteDigest,
769
+ lockedAt: new Date().toISOString(),
770
+ result: {
771
+ fails: now.fails,
772
+ warns: now.warns,
773
+ unknown: now.unknown,
774
+ assertionFails: (now.assertionResults ?? []).filter((r) => !r.ok).map((r) => r.about),
775
+ },
776
+ ...(siteVerified
777
+ ? { verifiedOk: !!siteVerified.ok, verifiedAt: new Date().toISOString() }
778
+ : {}),
779
+ };
780
+
781
+ writeFileSync(cssFile, toCss(lock.slug, site));
782
+ writeFileSync(lockPath, JSON.stringify(nextLock, null, 2) + "\n");
783
+ execFileSync("git", ["add", cssFile, lockPath], { encoding: "utf8" });
784
+ execFileSync(
785
+ "git",
786
+ [
787
+ "commit",
788
+ "-m",
789
+ "chore(ztheme): 升级 " +
790
+ lock.slug +
791
+ "(" +
792
+ String(lock.themeDigest).slice(0, 8) +
793
+ " → " +
794
+ siteDigest.slice(0, 8) +
795
+ ")",
796
+ ],
797
+ { encoding: "utf8", stdio: "pipe" }
798
+ );
799
+ console.log(
800
+ `已创建分支 ${branch} 并提交。下一步:git push -u origin ${branch},然后开 PR 人审。`
801
+ );
802
+ return;
803
+ }
804
+
533
805
  if (cmd === "check") {
534
806
  const strict = flags.has("strict");
535
807
  const fileAt = argv.indexOf("--file");
@@ -698,8 +970,12 @@ const main = async () => {
698
970
  maxWarnings = parsed;
699
971
  }
700
972
 
973
+ const fixMode = flags.has("fix");
974
+ const writeMode = flags.has("write");
975
+ if (writeMode && !fixMode) failWith("--write 需要和 --fix 一起用", 2);
976
+
701
977
  const theme = slug ? await loadAuditTheme(root, slug) : null;
702
- const result = await auditProject({
978
+ const scanOptions = {
703
979
  root,
704
980
  include: config.include,
705
981
  exclude: config.exclude,
@@ -707,10 +983,31 @@ const main = async () => {
707
983
  ignore: config.ignore,
708
984
  rules,
709
985
  theme,
710
- });
711
-
712
- if (flags.has("json")) console.log(formatJson(result));
713
- else console.log(formatHuman(result, { quiet: flags.has("quiet") }));
986
+ };
987
+ let result = await auditProject(scanOptions);
988
+
989
+ if (fixMode) {
990
+ const plan = buildFixPlan(root, result);
991
+ if (writeMode) {
992
+ for (const entry of plan.files) {
993
+ if (!entry.diff) continue;
994
+ writeFileSync(join(root, entry.file), entry.after, "utf8");
995
+ }
996
+ // 写后重扫:报告的是「现在还剩什么」,不是「刚才修了什么」。
997
+ result = await auditProject(scanOptions);
998
+ }
999
+ if (flags.has("json")) {
1000
+ console.log(
1001
+ formatJson({ ...result, fixes: plan.fixes, diff: plan.diff, written: writeMode })
1002
+ );
1003
+ } else {
1004
+ console.log(formatFixHuman(result, plan, { write: writeMode }));
1005
+ }
1006
+ } else if (flags.has("json")) {
1007
+ console.log(formatJson(result));
1008
+ } else {
1009
+ console.log(formatHuman(result, { quiet: flags.has("quiet") }));
1010
+ }
714
1011
 
715
1012
  if (result.errors.length > 0) {
716
1013
  process.exitCode = 2;