flow-comet 1.6.1 → 1.6.3

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 (51) hide show
  1. package/.flow-comet/skills/flow-comet/INSTALLED_VERSION +1 -1
  2. package/.flow-comet/skills/flow-comet/SKILL.md +94 -46
  3. package/.flow-comet/skills/flow-comet/reference/KNOWN-ISSUES-template.md +1 -1
  4. package/.flow-comet/skills/flow-comet/reference/commit-discipline.md +32 -0
  5. package/.flow-comet/skills/flow-comet/reference/dirty-worktree.md +1 -1
  6. package/.flow-comet/skills/flow-comet/{GUIDANCE.md → reference/entry-detail.md} +22 -30
  7. package/.flow-comet/skills/flow-comet/reference/fix-loop.md +57 -0
  8. package/.flow-comet/skills/flow-comet/reference/platform-facts.md +58 -0
  9. package/.flow-comet/skills/flow-comet/reference/replan.md +23 -0
  10. package/.flow-comet/skills/flow-comet/reference/workflow-protocol.json +1 -1
  11. package/.flow-comet/skills/flow-comet/scripts/comet-check.mjs +5 -4
  12. package/.flow-comet/skills/flow-comet/scripts/comet-hook-guard.mjs +260 -17
  13. package/.flow-comet/skills/flow-comet/scripts/context-init.mjs +129 -3
  14. package/.flow-comet/skills/flow-comet/scripts/context-scan.mjs +396 -0
  15. package/.flow-comet/skills/flow-comet/scripts/evolve.mjs +778 -0
  16. package/.flow-comet/skills/flow-comet/scripts/guard-self-test.mjs +5432 -194
  17. package/.flow-comet/skills/flow-comet/scripts/health.mjs +664 -0
  18. package/.flow-comet/skills/flow-comet/scripts/route-node.mjs +51 -4
  19. package/.flow-comet/skills/flow-comet/scripts/state-schema.mjs +68 -0
  20. package/.flow-comet/skills/flow-comet/scripts/system-test.mjs +1479 -11
  21. package/.flow-comet/skills/flow-comet/scripts/time-utils.mjs +133 -0
  22. package/.flow-comet/skills/flow-comet/scripts/workflow-guard.mjs +197 -5
  23. package/.flow-comet/skills/flow-comet/scripts/workflow-handoff.mjs +115 -6
  24. package/.flow-comet/skills/flow-comet/scripts/workflow-state.mjs +261 -29
  25. package/.flow-comet/skills/flow-comet-archive/SKILL.md +10 -19
  26. package/.flow-comet/skills/flow-comet-change/SKILL.md +10 -1
  27. package/.flow-comet/skills/flow-comet-compose/SKILL.md +1 -1
  28. package/.flow-comet/skills/flow-comet-design/SKILL.md +8 -6
  29. package/.flow-comet/skills/flow-comet-evolve/SKILL.md +46 -11
  30. package/.flow-comet/skills/flow-comet-execute/SKILL.md +58 -16
  31. package/.flow-comet/skills/flow-comet-health/SKILL.md +57 -16
  32. package/.flow-comet/skills/flow-comet-integration/SKILL.md +8 -5
  33. package/.flow-comet/skills/flow-comet-open/SKILL.md +5 -1
  34. package/.flow-comet/skills/flow-comet-plan/GUIDANCE.md +1 -1
  35. package/.flow-comet/skills/flow-comet-plan/SKILL.md +8 -8
  36. package/.flow-comet/skills/flow-comet-review/SKILL.md +9 -12
  37. package/.flow-comet/skills/flow-comet-subagent-execute/SKILL.md +59 -16
  38. package/.flow-comet/skills/flow-comet-task/SKILL.md +3 -2
  39. package/.flow-comet/skills/flow-comet-ui-design/SKILL.md +29 -4
  40. package/.flow-comet/skills/flow-comet-verify/SKILL.md +8 -17
  41. package/README.md +5 -5
  42. package/package.json +1 -1
  43. package/scripts/dsh-bridge.mjs +59 -26
  44. package/scripts/prepare-env.mjs +165 -1
  45. package/.flow-comet/skills/flow-comet/reference/TEST-MATRIX.md +0 -116
  46. package/.flow-comet/skills/flow-comet/reference/composition-report.md +0 -65
  47. package/.flow-comet/skills/flow-comet/reference/dsh-platform.md +0 -184
  48. package/.flow-comet/skills/flow-comet/reference/resolved-skills.json +0 -661
  49. package/.flow-comet/skills/flow-comet/reference/skill-review.md +0 -13
  50. package/.flow-comet/skills/flow-comet/reference/subagents/script-author.md +0 -7
  51. package/.flow-comet/skills/flow-comet/reference/worktree-notes.md +0 -70
@@ -0,0 +1,664 @@
1
+ #!/usr/bin/env node
2
+ // health.mjs — 横向命令 health(技能 flow-comet-health)的确定性收集器
3
+ //
4
+ // 报告分层:
5
+ // · 确定性层:文件 / 结构可判项——项目上下文段与格式、经验条目编号连续性、技术债表项数、
6
+ // 可选工具在场判定、版本历史统计。每项都带计数与判据;同一冻结树两次运行逐字节一致。
7
+ // · 增补层:代码体检工具(brooks-lint)在场时,由 agent 执行其 4 维体检并把结果并入同一份
8
+ // 报告、标注来源;脚本不执行 agent 技能,缺省保留占位而不伪造结论。
9
+ // · 降级声明:可选外部工具不在场时显式声明原因。判据只锚「确定性层完整 + 降级声明可见」——
10
+ // 环境缺可选工具不构成失败(这些工具是可选项,不是依赖)。
11
+ //
12
+ // 只读边界:
13
+ // · 读:.specs/CONTEXT.md、.specs/LESSONS.md、.specs/health/*.md(基线)、git 历史、
14
+ // 可选工具的在场探测(文件 / 路径判定);
15
+ // · 写:仅一份报告 .specs/health/<日期>-HEALTH.md;`--stdout` 时把报告正文原样打到标准输出;
16
+ // · 标准输出另**恒**输出 `HEALTH:` 审计行(报告路径 / 日期 / 增补层在场 / 基线)——不带
17
+ // `--stdout` 时只有审计行(报告正文不回流);
18
+ // · 不写运行状态(不触碰 .flow-comet/flow-comet-state.json,不新增任何状态字段);
19
+ // · 时间与**基线报告名的日期判据**一律走 time-utils.mjs 单一来源(本地时间 + 显式偏移;日期前缀
20
+ // 的形态与日历自洽由同一实现判定),不在本文件内联第二份格式化 / 第二份前缀正则——同一判据
21
+ // 两份实现必然分叉:自写前缀正则会把 `2026-02-30-HEALTH.md` 一类日历不自洽的名字采作基线。
22
+ //
23
+ // 复现性纪律:报告中的「机器可判项」必须可逐字节复现;两次运行允许不同的行由报告末尾的
24
+ // 「易变行声明」逐条列出(差异集合显式标注,不靠口头约定)。基线对比取「最近一份**日期不同**的
25
+ // 历史报告」——同日重跑不与自己对比,否则报告自我污染、复现性判据失效。
26
+ //
27
+ // 读数快照的**键形态单一来源**:字段表(SNAPSHOT_FIELDS)是键名与取值的唯一表达处,写方
28
+ // (buildSnapshot)与读方(parseSnapshot / 基线对比)都从它派生——读方不再自行表达键形态。
29
+ // 两侧各写一份表达的后果实测过:写方发含大写字母的键、读方的键形态正则只认全小写,4 个键的
30
+ // 基线对比恒输出「(基线无此读数)」——逐键趋势静默失效且不报错(假绿形态)。
31
+ //
32
+ // 可选工具的超时预算:单次调用上限 60s(与巡检预算一致)。超时与运行失败同走「降级原因」可见
33
+ // 路径(原因里回显本次预算),不中断报告、不冒充成功读数。
34
+
35
+ import { execFileSync } from 'child_process';
36
+ import { existsSync, promises as fs } from 'fs';
37
+ import os from 'os';
38
+ import path from 'path';
39
+ import { fileURLToPath } from 'url';
40
+ import { validateContext } from './context-init.mjs';
41
+ import { parseSideCommandArgs, relativeLabel } from './evolve.mjs';
42
+ import { archiveDateFromName, formatLocalDate, formatLocalTimestamp } from './time-utils.mjs';
43
+
44
+ const SELF_FILE = fileURLToPath(import.meta.url);
45
+ const SELF_DIR = path.dirname(SELF_FILE);
46
+
47
+ const CONTEXT_DISPLAY = '.specs/CONTEXT.md';
48
+ const LESSONS_DISPLAY = '.specs/LESSONS.md';
49
+ const HEALTH_DIR_DISPLAY = '.specs/health';
50
+ const REPORT_SUFFIX = '-HEALTH.md';
51
+
52
+ const GIT_TIMEOUT_MS = 20000;
53
+ // 可选工具(冗余扫描)的单次调用上限:60s 预算内——超出预算的等待不算「巡检」,超时与非零
54
+ // 退出同走 runJscpd 的降级路径(原因可见,报告不中断)。
55
+ const TOOL_TIMEOUT_MS = 60000;
56
+
57
+ // 条目编号标题:`### L-<三位数字>`(后接非数字 / 非字母,避免吞掉更长编号)
58
+ const LESSON_HEADING = /^### L-(\d{3})(?![\dA-Za-z])/;
59
+ // 技术债段标题(层级放宽到二~四级,容忍项目侧标题层级差异)
60
+ const DEBT_HEADING = /^#{2,4}[ \t]*技术债/;
61
+ // 表格分隔行(`|---|---|`):表项计数须排除它,否则每张表多算一行
62
+ const TABLE_SEPARATOR = /^\|[\s:|-]+\|$/;
63
+ // 提交主题的约定式类型前缀(`type(scope): subject` / `type!: subject`)
64
+ const COMMIT_KIND = /^([a-z][a-z-]*)(?:\([^)]*\))?!?:/;
65
+ // 快照行(`key=value`):读方**不表达键形态**——键身份由 SNAPSHOT_FIELDS 判定(两侧同源),
66
+ // 此处只做「首个 `=` 之前是非空白串」的通用切分。
67
+ const SNAPSHOT_LINE = /^([^=\s]+)=(.*)$/;
68
+
69
+ const DEBT_ITEM_LIMIT = 20;
70
+ const KIND_ITEM_LIMIT = 12;
71
+
72
+ // 冗余工具探面(顺序固定:报告行序与快照判定随之稳定)。主语言首选项可执行,其余登记在场状态。
73
+ const REDUNDANCY_TOOLS = [
74
+ { name: 'jscpd', dimension: '字面重复块(全语言)', runnable: true },
75
+ { name: 'knip', dimension: '未用导出 / 孤立文件(JS / TS)', runnable: false },
76
+ { name: 'ts-prune', dimension: '未用导出(TS)', runnable: false },
77
+ { name: 'depcheck', dimension: '未用依赖(JS / TS)', runnable: false },
78
+ { name: 'vulture', dimension: '死代码 / 未用导出(Python)', runnable: false },
79
+ ];
80
+ const REDUNDANCY_TARGET_DIRS = ['src', 'lib', 'app', 'packages', 'scripts'];
81
+ const TOOL_PROBE_NOTE = '探面:`node_modules/.bin/` 与 `PATH`';
82
+
83
+ // 代码体检工具(brooks-lint)探测面:用户级缓存 / 用户技能目录 + 项目内三平台技能目录 + 可执行文件。
84
+ // 逐项判定并全部写进报告——「不在场」的结论必须能看到探测面,不能只给一句断言。
85
+ const BROOKS_SKILL = 'brooks-health';
86
+
87
+ function usage() {
88
+ return [
89
+ '用法: node health.mjs [--root <项目根>] [--stdout] [--help]',
90
+ ' --root <路径> 项目根(缺省 = 当前目录;`--root=<路径>` 等号形等价)',
91
+ ' --stdout 报告正文原样写到标准输出(与落盘逐字节相同;摘要行追加在其后)',
92
+ ' --help, -h 打印本用法后退出(不产报告)',
93
+ '说明: 只写 .specs/health/<日期>-HEALTH.md;不写运行状态、不改代码。',
94
+ ].join('\n');
95
+ }
96
+
97
+ // 参数解析走侧命令共用的单一实现(evolve.mjs 导出的 parseSideCommandArgs):`--root` 两种形态 /
98
+ // `--stdout` / `--help` / 未知参数各只在一处表达,三条横向命令的 CLI 契约因此同形。
99
+ // rootDisplay = 调用方原样给出的 --root 取值(报告里按人读形态回显与复现命令用)。
100
+ function parseArgs(argv) {
101
+ const options = parseSideCommandArgs(argv, { usage: usage() });
102
+ options.rootDisplay = options.rootArg ?? '.';
103
+ return options;
104
+ }
105
+
106
+ async function fileExists(file) {
107
+ if (!file) return false;
108
+ try { await fs.access(file); return true; } catch { return false; }
109
+ }
110
+
111
+ async function readTextIfExists(file) {
112
+ try { return await fs.readFile(file, 'utf8'); } catch { return null; }
113
+ }
114
+
115
+ // 报告内路径显示:项目根内用相对路径(跨机器稳定),用户主目录内用 `~` 简写,其余原样(正斜杠)。
116
+ function displayPath(runRoot, target) {
117
+ const rel = path.relative(runRoot, target);
118
+ if (rel === '') return '.';
119
+ if (!rel.startsWith('..') && !path.isAbsolute(rel)) return './' + rel.split(path.sep).join('/');
120
+ const homeRel = path.relative(os.homedir(), target);
121
+ if (homeRel && !homeRel.startsWith('..') && !path.isAbsolute(homeRel)) return '~/' + homeRel.split(path.sep).join('/');
122
+ return target.split(path.sep).join('/');
123
+ }
124
+
125
+ // ---------- 确定性层 1:项目上下文(CONTEXT.md)一致性 ----------
126
+ // 段清单与格式检查复用 context-init.mjs 的 validateContext(单一实现,不复制第二份判据)。
127
+ async function collectContext(runRoot) {
128
+ const text = await readTextIfExists(path.join(runRoot, '.specs', 'CONTEXT.md'));
129
+ const { missingSections, formatIssues } = await validateContext(runRoot);
130
+ return {
131
+ exists: text !== null,
132
+ lineCount: text === null ? 0 : text.split('\n').length,
133
+ missingSections: [...missingSections],
134
+ formatIssues: [...formatIssues],
135
+ };
136
+ }
137
+
138
+ // ---------- 确定性层 2:经验条目(LESSONS.md)编号连续性 ----------
139
+ function collectLessons(text) {
140
+ const empty = { exists: text !== null, entries: 0, min: null, max: null, missing: [], duplicates: [] };
141
+ if (text === null) return empty;
142
+ const numbers = [];
143
+ for (const line of text.split('\n')) {
144
+ const m = LESSON_HEADING.exec(line);
145
+ if (m) numbers.push(Number(m[1]));
146
+ }
147
+ if (numbers.length === 0) return empty;
148
+ const seen = new Set(numbers);
149
+ const duplicates = [...new Set(numbers.filter((n) => numbers.indexOf(n) !== numbers.lastIndexOf(n)))].sort((a, b) => a - b);
150
+ const min = Math.min(...numbers);
151
+ const max = Math.max(...numbers);
152
+ const missing = [];
153
+ for (let n = min; n <= max; n += 1) if (!seen.has(n)) missing.push(n);
154
+ return { exists: true, entries: numbers.length, min, max, missing, duplicates };
155
+ }
156
+
157
+ function formatLessonId(n) {
158
+ return 'L-' + String(n).padStart(3, '0');
159
+ }
160
+
161
+ // 编号压缩:连续段写 `L-aaa~L-bbb`,单点写 `L-aaa`(长缺失清单也能一行读完)
162
+ function compressRanges(numbers) {
163
+ if (numbers.length === 0) return '无';
164
+ const parts = [];
165
+ let start = numbers[0];
166
+ let previous = numbers[0];
167
+ for (let i = 1; i < numbers.length; i += 1) {
168
+ const current = numbers[i];
169
+ if (current === previous + 1) { previous = current; continue; }
170
+ parts.push(start === previous ? formatLessonId(start) : formatLessonId(start) + '~' + formatLessonId(previous));
171
+ start = current;
172
+ previous = current;
173
+ }
174
+ parts.push(start === previous ? formatLessonId(start) : formatLessonId(start) + '~' + formatLessonId(previous));
175
+ return parts.join(', ');
176
+ }
177
+
178
+ // ---------- 确定性层 3:技术债表项数 ----------
179
+ function collectDebt(text) {
180
+ if (text === null) return { exists: false, rows: 0, items: [], level: null };
181
+ const lines = text.split('\n');
182
+ const start = lines.findIndex((line) => DEBT_HEADING.test(line));
183
+ if (start === -1) return { exists: false, rows: 0, items: [], level: null };
184
+ // 段标题的**实际层级**随读数一起回传:复现命令的段级必须取自这里——判据的层级区间是二~四级,
185
+ // 命令若硬编码 H3,`## 技术债` 的项目照抄命令就复现不出本报告的读数(命令与判据各说一套)。
186
+ const level = (lines[start].match(/^#+/) ?? [''])[0].length;
187
+ const body = [];
188
+ for (let i = start + 1; i < lines.length; i += 1) {
189
+ const line = lines[i];
190
+ // 段边界 = 下一个**同级或更高级**标题,或分隔线。层级必须与段标题自身比较:按「任意 H1~H4
191
+ // 标题」截断会把段内子标题之后的表格整段丢掉——`## 技术债` + `### 明细` 与 `### 技术债` +
192
+ // `#### 明细` 都被读成 0 表项(深于段标题的子标题属于段内,不是段边界)。
193
+ const heading = /^(#{1,6})[ \t]/.exec(line);
194
+ if ((heading !== null && heading[1].length <= level) || /^-{3,}[ \t]*$/.test(line)) break;
195
+ body.push(line);
196
+ }
197
+ const tableRows = body.map((line) => line.trim()).filter((line) => line.startsWith('|'));
198
+ const contentRows = tableRows.filter((line) => !TABLE_SEPARATOR.test(line));
199
+ const dataRows = contentRows.slice(1); // 首行 = 表头
200
+ const items = dataRows
201
+ .map((line) => (line.split('|')[1] ?? '').trim().replaceAll('`', ''))
202
+ .filter((item) => item.length > 0);
203
+ return { exists: true, rows: dataRows.length, items, level };
204
+ }
205
+
206
+ // ---------- 确定性层 4:冗余工具在场判定(+ 首选项在场则跑) ----------
207
+ function findOnPath(name) {
208
+ const dirs = (process.env.PATH ?? '').split(path.delimiter).filter((dir) => dir.length > 0);
209
+ const extensions = process.platform === 'win32' ? ['', '.cmd', '.exe', '.bat'] : [''];
210
+ for (const dir of dirs) {
211
+ for (const extension of extensions) {
212
+ const candidate = path.join(dir, name + extension);
213
+ if (existsSync(candidate)) return candidate;
214
+ }
215
+ }
216
+ return null;
217
+ }
218
+
219
+ async function probeTool(runRoot, name) {
220
+ const localNames = process.platform === 'win32' ? [name + '.cmd', name + '.exe', name] : [name];
221
+ for (const localName of localNames) {
222
+ const candidate = path.join(runRoot, 'node_modules', '.bin', localName);
223
+ if (await fileExists(candidate)) return candidate;
224
+ }
225
+ return findOnPath(name);
226
+ }
227
+
228
+ async function collectRedundancy(runRoot) {
229
+ const targets = [];
230
+ for (const dir of REDUNDANCY_TARGET_DIRS) {
231
+ if (await fileExists(path.join(runRoot, dir))) targets.push(dir);
232
+ }
233
+ const tools = [];
234
+ for (const tool of REDUNDANCY_TOOLS) {
235
+ tools.push({ ...tool, path: await probeTool(runRoot, tool.name), reading: null, reason: null });
236
+ }
237
+ const primary = tools.find((tool) => tool.runnable && tool.path);
238
+ if (!primary) return { targets, tools, run: null };
239
+ if (targets.length === 0) {
240
+ return { targets, tools, run: { status: 'degraded', reason: '无可扫源码目录(探面:' + REDUNDANCY_TARGET_DIRS.join(' / ') + ')' } };
241
+ }
242
+ return { targets, tools, run: await runJscpd(runRoot, primary.path, targets) };
243
+ }
244
+
245
+ // 首选工具(全语言 · 字面重复块)在场才跑;输出目录落在系统临时区并在结束时清理,不在项目内留产物。
246
+ // 跑不起来(版本差异 / 平台包装器限制 / 超时)→ 记降级原因,不中断报告。
247
+ async function runJscpd(runRoot, toolPath, targets) {
248
+ const outDir = await fs.mkdtemp(path.join(os.tmpdir(), 'flow-comet-health-'));
249
+ try {
250
+ execFileSync(toolPath, [
251
+ ...targets,
252
+ '--min-lines', '5',
253
+ '--min-tokens', '50',
254
+ '--reporters', 'json',
255
+ '--output', outDir,
256
+ '--silent',
257
+ ], { cwd: runRoot, timeout: TOOL_TIMEOUT_MS, stdio: ['ignore', 'ignore', 'pipe'] });
258
+ const raw = await fs.readFile(path.join(outDir, 'jscpd-report.json'), 'utf8');
259
+ const total = JSON.parse(raw)?.statistics?.total ?? {};
260
+ return {
261
+ status: 'ok',
262
+ clones: Number(total.clones ?? 0),
263
+ duplicatedLines: Number(total.duplicatedLines ?? 0),
264
+ percentage: Number(total.percentage ?? 0),
265
+ targets,
266
+ };
267
+ } catch (error) {
268
+ // 失败原因可见且自证:回显本次超时预算,便于区分「超时」与「工具自身报错」;读数不落 `ok`。
269
+ return { status: 'degraded', reason: '工具在场但运行未完成(超时预算 ' + TOOL_TIMEOUT_MS + ' ms;' + String(error.message).split('\n')[0] + ')' };
270
+ } finally {
271
+ try { await fs.rm(outDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 150 }); } catch { /* 临时区清理失败不影响报告 */ }
272
+ }
273
+ }
274
+
275
+ // ---------- 确定性层 5:版本历史统计(git) ----------
276
+ function runGit(runRoot, args) {
277
+ try {
278
+ return execFileSync('git', args, { cwd: runRoot, encoding: 'utf8', timeout: GIT_TIMEOUT_MS, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
279
+ } catch {
280
+ return null;
281
+ }
282
+ }
283
+
284
+ function collectGit(runRoot) {
285
+ if (runGit(runRoot, ['rev-parse', '--is-inside-work-tree']) !== 'true') {
286
+ return { isRepo: false, commits: null, head: null, headDate: null, kinds: [], recent: null };
287
+ }
288
+ const commits = runGit(runRoot, ['rev-list', '--count', 'HEAD']);
289
+ const headLine = runGit(runRoot, ['log', '-1', '--pretty=%h|%cI']);
290
+ const subjects = runGit(runRoot, ['log', '--pretty=%s']);
291
+ const recent = runGit(runRoot, ['rev-list', '--count', '--since=30.days.ago', 'HEAD']);
292
+ const counts = new Map();
293
+ for (const subject of (subjects ?? '').split('\n')) {
294
+ const m = COMMIT_KIND.exec(subject.trim());
295
+ const kind = m ? m[1] : '(其它)';
296
+ counts.set(kind, (counts.get(kind) ?? 0) + 1);
297
+ }
298
+ const kinds = [...counts.entries()]
299
+ .map(([kind, count]) => ({ kind, count }))
300
+ .sort((a, b) => (b.count - a.count) || (a.kind < b.kind ? -1 : a.kind > b.kind ? 1 : 0));
301
+ const [head, headDate] = (headLine ?? '').split('|');
302
+ return {
303
+ isRepo: true,
304
+ commits: commits === null ? null : Number(commits),
305
+ head: head || null,
306
+ headDate: headDate || null,
307
+ kinds,
308
+ recent: recent === null ? null : Number(recent),
309
+ };
310
+ }
311
+
312
+ // ---------- 增补层:代码体检工具在场探测 ----------
313
+ async function collectBrooks(runRoot) {
314
+ const probes = [
315
+ { label: 'Claude Code 插件缓存(用户级)', target: path.join(os.homedir(), '.claude', 'plugins', 'cache', 'brooks-lint-marketplace') },
316
+ { label: 'Codex 用户技能目录', target: path.join(os.homedir(), '.codex', 'skills', BROOKS_SKILL) },
317
+ { label: '项目技能目录(Claude Code)', target: path.join(runRoot, '.claude', 'skills', BROOKS_SKILL) },
318
+ { label: '项目技能目录(Codex)', target: path.join(runRoot, '.agents', 'skills', BROOKS_SKILL) },
319
+ { label: '项目技能目录(dsh)', target: path.join(runRoot, '.dsh', 'skills', BROOKS_SKILL) },
320
+ { label: '可执行文件(PATH)', target: findOnPath(BROOKS_SKILL) },
321
+ ];
322
+ const resolved = [];
323
+ for (const probe of probes) {
324
+ resolved.push({ label: probe.label, display: probe.target ? displayPath(runRoot, probe.target) : null, hit: await fileExists(probe.target) });
325
+ }
326
+ return { present: resolved.some((probe) => probe.hit), probes: resolved };
327
+ }
328
+
329
+ // ---------- 基线:最近一份「日期不同」的历史报告 + 其读数快照 ----------
330
+ // 报告文件名约定(日期前缀 + 固定后缀)只在本函数里表达一次,避免与写盘路径各写一份字面量;
331
+ // 日期前缀的**形态与日历自洽**判定复用 time-utils 的同一实现(归档日期判据的单一权威)——
332
+ // 本文件不另写前缀正则:两份判据必然分叉,而日历不自洽的名字(`2026-02-30-HEALTH.md`)会让
333
+ // 基线对比输出看似有据的 ↑/↓ 趋势。
334
+ function reportDateOf(name) {
335
+ if (!name.endsWith(REPORT_SUFFIX)) return null;
336
+ return archiveDateFromName(name);
337
+ }
338
+
339
+ async function readBaseline(runRoot, currentDate) {
340
+ const dir = path.join(runRoot, '.specs', 'health');
341
+ let names;
342
+ try { names = await fs.readdir(dir); } catch { return null; }
343
+ const candidates = names
344
+ .map((name) => ({ name, date: reportDateOf(name) }))
345
+ .filter((entry) => entry.date !== null && entry.date !== currentDate)
346
+ .map((entry) => entry.name)
347
+ .sort();
348
+ if (candidates.length === 0) return null;
349
+ const name = candidates[candidates.length - 1];
350
+ const text = await readTextIfExists(path.join(dir, name));
351
+ if (text === null) return null;
352
+ return { name, snapshot: parseSnapshot(text) };
353
+ }
354
+
355
+ function parseSnapshot(text) {
356
+ const lines = text.split('\n');
357
+ const start = lines.findIndex((line) => line.startsWith('## 读数快照'));
358
+ if (start === -1) return {};
359
+ const values = {};
360
+ let fenced = false;
361
+ for (let i = start + 1; i < lines.length; i += 1) {
362
+ const line = lines[i].trim();
363
+ if (/^## /.test(line)) break;
364
+ if (/^```/.test(line)) { fenced = !fenced; continue; }
365
+ if (!fenced) continue;
366
+ const m = SNAPSHOT_LINE.exec(line);
367
+ // 键身份由字段表判定:表外的键(旧版本残留 / 形态不符)不属于本版本的读数面,不冒充读数。
368
+ if (m && SNAPSHOT_KEYS.has(m[1])) values[m[1]] = m[2];
369
+ }
370
+ return values;
371
+ }
372
+
373
+ // ---------- 报告 ----------
374
+ // 报告按「一段一函数」拼装:每个渲染器只读自己那一段的读数并向输出追加行,
375
+ // 段落增删互不影响(也避免出现跨越整份报告的单一长函数)。
376
+ function renderHeader(push, input) {
377
+ const { options, selfDisplay, date, timestamp } = input;
378
+ push('# 健康巡检 · ' + date, '');
379
+ push('- **报告文件**:`' + HEALTH_DIR_DISPLAY + '/' + date + REPORT_SUFFIX + '`');
380
+ push('- **生成时间**:' + timestamp + '(易变行 · 见「易变行声明」)');
381
+ push('- **扫描根**:`' + options.rootDisplay + '`');
382
+ push('- **复现命令**:`node ' + selfDisplay + ' --root ' + options.rootDisplay + ' --stdout`');
383
+ push('- **写入边界**:只写本报告文件;不改代码、不写运行状态文件(本命令不新增任何状态字段)');
384
+ push('- **报告分层**:确定性层(机器可判 · 逐项带计数与判据)|增补层(代码体检工具 4 维结果 · 可选)|降级声明');
385
+ push('- **判据**:只锚「确定性层完整 + 降级声明可见」——环境缺可选外部工具不构成失败', '');
386
+
387
+ push('## 确定性层(机器可判)', '');
388
+ }
389
+
390
+ function renderContextSection(push, context, selfDirDisplay) {
391
+ push('### 1 · 项目上下文一致性', '');
392
+ push('- 文件:`' + CONTEXT_DISPLAY + '`(' + (context.exists ? '在场' : '缺失') + ')');
393
+ push('- 文件行数:' + context.lineCount);
394
+ push('- 缺失段(' + context.missingSections.length + '):' + (context.missingSections.length === 0 ? '无' : context.missingSections.join(' · ')));
395
+ push('- 格式问题(' + context.formatIssues.length + '):' + (context.formatIssues.length === 0 ? '无' : context.formatIssues.join(' · ')));
396
+ push('- 判据:段清单与格式检查复用 `context-init.mjs` 的校验导出(单一实现);段清单由 `flow-kit/templates/CONTEXT.md` 派生,模板缺席时用内置七段基准');
397
+ push('- 复现命令:`node --input-type=module -e "import {validateContext} from \'' + selfDirDisplay + '/context-init.mjs\'; const r=await validateContext(process.cwd()); console.log(JSON.stringify({missingSections:r.missingSections,formatIssues:r.formatIssues}))"`', '');
398
+ }
399
+
400
+ function renderLessonsSection(push, lessons) {
401
+ push('### 2 · 经验条目编号连续性', '');
402
+ push('- 文件:`' + LESSONS_DISPLAY + '`(' + (lessons.exists ? '在场' : '缺失') + ')');
403
+ push('- 条目数:' + lessons.entries);
404
+ push('- 编号区间:' + (lessons.min === null ? '无条目' : formatLessonId(lessons.min) + '~' + formatLessonId(lessons.max)));
405
+ push('- 缺失编号(' + lessons.missing.length + '):' + compressRanges(lessons.missing));
406
+ push('- 重复编号(' + lessons.duplicates.length + '):' + (lessons.duplicates.length === 0 ? '无' : lessons.duplicates.map(formatLessonId).join(', ')));
407
+ push('- 判据:条目 = 行首 `### L-<三位数字>`(后接非数字 / 非字母);缺失 = 区间内未出现的编号(压缩为区间写法)');
408
+ push('- 复现命令:`grep -cE \'^### L-[0-9]{3}([^0-9A-Za-z]|$)\' ' + LESSONS_DISPLAY + '`', '');
409
+ }
410
+
411
+ function renderDebtSection(push, debt) {
412
+ push('### 3 · 技术债表项数', '');
413
+ push('- 段:`' + CONTEXT_DISPLAY + '` 的技术债段(' + (debt.exists ? '在场' : '缺失') + ')');
414
+ push('- 表项数:' + debt.rows);
415
+ if (debt.items.length > 0) {
416
+ for (const item of debt.items.slice(0, DEBT_ITEM_LIMIT)) push(' - ' + item);
417
+ if (debt.items.length > DEBT_ITEM_LIMIT) push(' - ……(仅列前 ' + DEBT_ITEM_LIMIT + ' 项,共 ' + debt.items.length + ' 项)');
418
+ }
419
+ push('- 判据:段内表格数据行计数(排除表头与分隔行);段边界 = 下一个同级或更高级标题,或分隔线');
420
+ // 复现命令的段级与段终点都**按判据动态取**:段级 = 文档里真实命中的标题层级(判据的层级区间是
421
+ // 二~四级);段终点 = 同级或更高级标题,或分隔线。此前用 `sed` 的单终点 `/^---/` 表达不了「同级或
422
+ // 更高级标题」——段以标题(而非分隔线)收尾时会把下一段的表格一并数进来,命令与判据各说一套。
423
+ // 段缺席 = 没有可取的层级,退回该区间的上界。两种情况都给出能复现本次读数的命令。
424
+ const bound = debt.exists ? String(debt.level) : '4';
425
+ push('- 复现命令:`awk \'f&&(/^#{1,' + bound + '}[[:space:]]/||/^-{3,}[[:space:]]*$/){exit} '
426
+ + '/^#{2,4}[[:space:]]*技术债/{f=1} f\' ' + CONTEXT_DISPLAY + ' | grep -c \'^|\'`(含表头与分隔行,减去 2 即表项数)', '');
427
+ }
428
+
429
+ function renderRedundancySection(push, redundancy, options, selfDisplay) {
430
+ push('### 4 · 冗余扫描(可选工具 · 在场则跑)', '');
431
+ push('- 源码目录探面:' + REDUNDANCY_TARGET_DIRS.map((dir) => '`' + dir + '`').join(' / ') + '(存在者才纳入扫描:' + (redundancy.targets.length === 0 ? '无' : redundancy.targets.map((dir) => '`' + dir + '`').join(' · ')) + ')');
432
+ push('- 工具在场判定(' + TOOL_PROBE_NOTE + '):', '');
433
+ push('| 工具 | 维度 | 在场 | 读数 / 降级原因 |');
434
+ push('|---|---|---|---|');
435
+ for (const tool of redundancy.tools) {
436
+ const reading = tool.runnable && tool.path && redundancy.run
437
+ ? (redundancy.run.status === 'ok'
438
+ ? '克隆块 ' + redundancy.run.clones + ' · 重复行 ' + redundancy.run.duplicatedLines + ' · 重复率 ' + redundancy.run.percentage + '%(目标:' + redundancy.run.targets.join(' ') + ')'
439
+ : '未采集——' + redundancy.run.reason)
440
+ : null;
441
+ const cell = tool.path
442
+ ? (reading ?? '在场但本次未采集(无稳定机读输出契约——由技能侧人工并入增补层)')
443
+ : '未采集——' + TOOL_PROBE_NOTE + ' 均未命中';
444
+ push('| `' + tool.name + '` | ' + tool.dimension + ' | ' + (tool.path ? '在场:`' + displayPath(options.root, tool.path) + '`' : '不在场') + ' | ' + cell + ' |');
445
+ }
446
+ push('');
447
+ push('- 判据:在场判定 = 文件 / 路径可判(确定性);读数由工具输出承担,未在场即记降级原因');
448
+ push('- 复现命令:`node ' + selfDisplay + ' --root ' + options.rootDisplay + ' --stdout`(在场判定随环境变化,同一环境内可复现)', '');
449
+ }
450
+
451
+ function renderGitSection(push, git) {
452
+ push('### 5 · 版本历史统计(git)', '');
453
+ if (!git.isRepo) {
454
+ push('- git 仓库:否——历史统计缺省(显式声明,不静默省略)');
455
+ // 本项在「不在仓库内」态同样要带复现命令:确定性层的每项都是机器可判的承诺,复现命令是它的
456
+ // 兑现方式——缺一项,该层就有一格不可复核(与在场态的两条命令对称)。
457
+ push('- 复现命令:`git rev-parse --is-inside-work-tree`(输出非 `true` / 退出码非 0 即不在仓库内)');
458
+ } else {
459
+ push('- git 仓库:是');
460
+ push('- 提交总数:' + (git.commits === null ? '不可判(HEAD 无法解析)' : git.commits));
461
+ push('- 当前提交:' + (git.head ? '`' + git.head + '`(提交时间 ' + git.headDate + ')' : '不可判'));
462
+ const kinds = git.kinds.slice(0, KIND_ITEM_LIMIT).map((entry) => entry.kind + ' ' + entry.count).join(' · ');
463
+ push('- 提交类型分布:' + (kinds || '不可判') + (git.kinds.length > KIND_ITEM_LIMIT ? ' · ……(共 ' + git.kinds.length + ' 类)' : ''));
464
+ push('- 最近 30 天提交数:' + (git.recent === null ? '不可判' : git.recent) + '(易变行 · 见「易变行声明」)');
465
+ push('- 判据:类型前缀取提交主题的 `type(scope):` 形态,其余归「(其它)」;计数降序、同数按名称升序');
466
+ push('- 复现命令:`git rev-list --count HEAD` · `git log --pretty=%s`');
467
+ }
468
+ push('');
469
+ }
470
+
471
+ function renderSupplementSection(push, brooks) {
472
+ push('## 增补层(代码体检工具的 4 维结果 · 可选)', '');
473
+ push('- **在场判定**:' + (brooks.present ? '在场' : '不在场——下列探测面逐项未命中(未安装 / 未加载)'));
474
+ push('- **探测面(固定清单 · 逐项判定)**:');
475
+ for (const probe of brooks.probes) {
476
+ push(' - ' + (probe.hit ? '在场' : '不在场') + ' · ' + probe.label + ':' + (probe.display ? '`' + probe.display + '`' : '(未命中)'));
477
+ }
478
+ if (brooks.present) {
479
+ push('- **取用方式**:agent 执行 `' + BROOKS_SKILL + '` 技能后,把 4 维结果**并入本段**(同一份报告,不另开文件)');
480
+ push('- **来源标注(必填)**:`来源:' + BROOKS_SKILL + '(brooks-lint · <命中落点>)`');
481
+ } else {
482
+ push('- **降级**:4 维结果缺省;报告只由确定性层构成(判据不因缺可选工具而失败)');
483
+ }
484
+ push('- **4 维结果槽**(脚本不执行 agent 技能;未填充时保留占位,不伪造结论):');
485
+ push(' - 代码质量(生产代码风险分布):');
486
+ push(' - 架构(分层 / 依赖):');
487
+ push(' - 技术债(Pain × Spread 优先级):');
488
+ push(' - 测试质量:');
489
+ push('');
490
+ }
491
+
492
+ function renderDegradationSection(push, redundancy, brooks) {
493
+ const brooksLine = brooks.present
494
+ ? '- **brooks-lint**:在场(见增补层探测面)——4 维结果由 agent 执行 `' + BROOKS_SKILL + '` 后并入并标注来源;未并入时本报告只含确定性层'
495
+ : '- **brooks-lint**:不可用——探测面逐项未命中(未安装 / 未加载);降级为内置确定性子集,4 维结果缺省';
496
+ const jscpdTool = redundancy.tools.find((tool) => tool.name === 'jscpd');
497
+ const jscpdLine = jscpdTool.path
498
+ ? '- **jscpd**:在场——字面重复块读数见「冗余扫描」段'
499
+ : '- **jscpd**:不在场(' + TOOL_PROBE_NOTE + ')——字面重复块未采集;建议 `npx jscpd <源码目录> --min-lines 5 --min-tokens 50` 后人工并入增补层';
500
+ const others = redundancy.tools.filter((tool) => tool.name !== 'jscpd' && !tool.path).map((tool) => tool.name);
501
+ push('## 降级声明', '');
502
+ push(brooksLine);
503
+ push(jscpdLine);
504
+ if (others.length > 0) {
505
+ push('- **' + others.join(' / ') + '**:不在场——未用导出 / 未用依赖 / 死代码维度未采集(按主语言选装其一即可)');
506
+ }
507
+ push('- **判据**:只锚「确定性层完整 + 降级声明可见」;上述工具均为**可选外部工具**(不构成依赖),缺席不影响本命令成功(退出码 0)');
508
+ push('');
509
+ }
510
+
511
+ function renderSnapshotSection(push, snapshot) {
512
+ push('## 读数快照(机器可读 · 供下次报告对比)', '');
513
+ push('```text');
514
+ for (const entry of snapshot) push(entry.key + '=' + entry.value);
515
+ push('```', '');
516
+ }
517
+
518
+ function renderBaselineSection(push, baseline, snapshot) {
519
+ push('## 与上次对比', '');
520
+ if (!baseline) {
521
+ push('- 基线:无(`' + HEALTH_DIR_DISPLAY + '` 下无日期不同的历史报告)——本次为该域首份报告,显式声明「无差异可比」,不静默省略');
522
+ } else {
523
+ push('- 基线:`' + HEALTH_DIR_DISPLAY + '/' + baseline.name + '`(取最近一份**日期不同**的历史报告——同日重跑不与自己对比,否则报告自我污染)');
524
+ for (const entry of snapshot) {
525
+ const previous = baseline.snapshot[entry.key];
526
+ if (previous === undefined) { push('- `' + entry.key + '`:' + entry.value + '(基线无此读数)'); continue; }
527
+ if (previous === entry.value) { push('- `' + entry.key + '`:' + previous + ' → ' + entry.value + '(无变化)'); continue; }
528
+ const before = Number(previous);
529
+ const after = Number(entry.value);
530
+ const trend = Number.isFinite(before) && Number.isFinite(after)
531
+ ? (after > before ? '(↑ ' + (after - before) + ')' : '(↓ ' + (before - after) + ')')
532
+ : '(已变更)';
533
+ push('- `' + entry.key + '`:' + previous + ' → ' + entry.value + trend);
534
+ }
535
+ }
536
+ push('');
537
+ }
538
+
539
+ function renderVolatilitySection(push, selfDisplay, options) {
540
+ push('## 易变行声明(两次运行的允许差异集合)', '');
541
+ push('同一冻结树连续两次运行,除下列差异集合外,其余行(即全部机器可判项)逐字节一致:');
542
+ push('1. 以 `- **生成时间**:` 开头的行(时刻本身)');
543
+ push('2. 以 `- 最近 30 天提交数:` 开头的行(相对当前时刻滑动的统计窗口)');
544
+ push('3. 报告文件名中的日期分量与「与上次对比」的基线选择(跨日运行时才会变化)');
545
+ push('');
546
+ push('验证方式:`node ' + selfDisplay + ' --root ' + options.rootDisplay + ' --stdout` 连续两次的差异应仅落在上述集合内。');
547
+ }
548
+
549
+ function renderReport(input) {
550
+ const lines = [];
551
+ const push = (...texts) => lines.push(...texts);
552
+ renderHeader(push, input);
553
+ renderContextSection(push, input.context, input.selfDirDisplay);
554
+ renderLessonsSection(push, input.lessons);
555
+ renderDebtSection(push, input.debt);
556
+ renderRedundancySection(push, input.redundancy, input.options, input.selfDisplay);
557
+ renderGitSection(push, input.git);
558
+ renderSupplementSection(push, input.brooks);
559
+ renderDegradationSection(push, input.redundancy, input.brooks);
560
+ renderSnapshotSection(push, input.snapshot);
561
+ renderBaselineSection(push, input.baseline, input.snapshot);
562
+ renderVolatilitySection(push, input.selfDisplay, input.options);
563
+ return lines.join('\n') + '\n';
564
+ }
565
+
566
+ // 读数快照字段表(**键形态的单一来源**):键名与取值只在本表表达一次——写方 buildSnapshot 与
567
+ // 读方 parseSnapshot / 基线对比都从本表派生,任一侧不再自持第二份键名或键形态。字段顺序 =
568
+ // 报告里快照块的书写顺序(同一冻结树两次运行逐字节一致的前提)。
569
+ function jscpdOf(readings) {
570
+ return readings.redundancy.tools.find((tool) => tool.name === 'jscpd') ?? null;
571
+ }
572
+
573
+ const SNAPSHOT_FIELDS = [
574
+ { key: 'context.exists', value: (r) => String(r.context.exists) },
575
+ { key: 'context.lineCount', value: (r) => String(r.context.lineCount) },
576
+ { key: 'context.missingSections', value: (r) => String(r.context.missingSections.length) },
577
+ { key: 'context.formatIssues', value: (r) => String(r.context.formatIssues.length) },
578
+ { key: 'lessons.exists', value: (r) => String(r.lessons.exists) },
579
+ { key: 'lessons.entries', value: (r) => String(r.lessons.entries) },
580
+ { key: 'lessons.min', value: (r) => (r.lessons.min === null ? 'none' : String(r.lessons.min)) },
581
+ { key: 'lessons.max', value: (r) => (r.lessons.max === null ? 'none' : String(r.lessons.max)) },
582
+ { key: 'lessons.missing', value: (r) => String(r.lessons.missing.length) },
583
+ { key: 'lessons.duplicates', value: (r) => String(r.lessons.duplicates.length) },
584
+ { key: 'debt.exists', value: (r) => String(r.debt.exists) },
585
+ { key: 'debt.rows', value: (r) => String(r.debt.rows) },
586
+ { key: 'redundancy.targets', value: (r) => (r.redundancy.targets.length === 0 ? 'none' : r.redundancy.targets.join(',')) },
587
+ { key: 'redundancy.jscpd', value: (r) => (jscpdOf(r)?.path ? (r.redundancy.run && r.redundancy.run.status === 'ok' ? 'ok' : 'present') : 'absent') },
588
+ { key: 'git.isRepo', value: (r) => String(r.git.isRepo) },
589
+ { key: 'git.commits', value: (r) => (r.git.commits === null ? 'none' : String(r.git.commits)) },
590
+ { key: 'git.head', value: (r) => r.git.head ?? 'none' },
591
+ { key: 'brooks.present', value: (r) => String(r.brooks.present) },
592
+ ];
593
+ // 键身份集合由字段表派生(读方判定「这一行是不是本版本的读数」)。
594
+ const SNAPSHOT_KEYS = new Set(SNAPSHOT_FIELDS.map((field) => field.key));
595
+
596
+ function buildSnapshot(readings) {
597
+ return SNAPSHOT_FIELDS.map((field) => ({ key: field.key, value: field.value(readings) }));
598
+ }
599
+
600
+ // 结果摘要(前缀行供机检检索):审计行与**报告落盘路径恒输出**(不带 `--stdout` 亦然)——
601
+ // 报告是唯一写入面,调用方至少要能从标准输出确认「跑没跑、落在哪、基线是谁、增补层在不在场」。
602
+ // `--stdout` 时报告正文原样在前(与落盘逐字节一致),审计行追加在后且不混进报告字节。
603
+ // 审计行内容当日确定(日期 / 在场判定 / 基线)——不引入新的易变行。
604
+ function printResult({ stdout, root, reportText, reportPath, date, baseline, brooks }) {
605
+ const output = [];
606
+ if (stdout) output.push(reportText, '');
607
+ output.push('HEALTH: 报告 `' + relativeLabel(root, reportPath) + '`');
608
+ output.push('HEALTH: 日期 ' + date + ' · 增补层 ' + (brooks.present ? '在场' : '不在场')
609
+ + ' · 基线 ' + (baseline
610
+ ? '`' + relativeLabel(root, path.join(root, '.specs', 'health', baseline.name)) + '`'
611
+ : '无(本次为基线,无差异可比)'));
612
+ output.push('HEALTH-DONE');
613
+ console.log(output.join('\n'));
614
+ }
615
+
616
+ async function main(argv) {
617
+ const options = parseArgs(argv);
618
+ if (options.help) { console.log(usage()); return 0; }
619
+ const stat = await fs.stat(options.root).catch(() => null);
620
+ if (!stat || !stat.isDirectory()) throw new Error('项目根不可用(不是目录): ' + options.root);
621
+
622
+ const date = formatLocalDate();
623
+ const timestamp = formatLocalTimestamp();
624
+ const contextText = await readTextIfExists(path.join(options.root, '.specs', 'CONTEXT.md'));
625
+ const lessonsText = await readTextIfExists(path.join(options.root, '.specs', 'LESSONS.md'));
626
+
627
+ const context = await collectContext(options.root);
628
+ const lessons = collectLessons(lessonsText);
629
+ const debt = collectDebt(contextText);
630
+ const redundancy = await collectRedundancy(options.root);
631
+ const git = collectGit(options.root);
632
+ const brooks = await collectBrooks(options.root);
633
+ const baseline = await readBaseline(options.root, date);
634
+ const snapshot = buildSnapshot({ context, lessons, debt, redundancy, git, brooks });
635
+
636
+ const report = renderReport({
637
+ options,
638
+ selfDisplay: displayPath(options.root, SELF_FILE),
639
+ selfDirDisplay: displayPath(options.root, SELF_DIR),
640
+ date,
641
+ timestamp,
642
+ context,
643
+ lessons,
644
+ debt,
645
+ redundancy,
646
+ git,
647
+ brooks,
648
+ baseline,
649
+ snapshot,
650
+ });
651
+
652
+ const reportPath = path.join(options.root, '.specs', 'health', date + REPORT_SUFFIX);
653
+ await fs.mkdir(path.dirname(reportPath), { recursive: true });
654
+ await fs.writeFile(reportPath, report, 'utf8');
655
+ printResult({ stdout: options.stdout, root: options.root, reportText: report, reportPath, date, baseline, brooks });
656
+ return 0;
657
+ }
658
+
659
+ main(process.argv.slice(2))
660
+ .then((code) => { process.exitCode = code; })
661
+ .catch((error) => {
662
+ console.error('health: ' + (error && error.message ? error.message : String(error)));
663
+ process.exitCode = 1;
664
+ });