@wwkit/harness 1.0.34 → 1.0.35

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.
@@ -0,0 +1,270 @@
1
+ ---
2
+ name: blame-agents
3
+ description: Use when auditing or scoring a project's AGENTS.md instruction file against the open AGENTS.md standard. Triggers on: AGENTS.md review, agents.md audit, project instruction file scoring, agent context budget check, monorepo nested rules check, nested AGENTS.md review. Produces a weighted score report with veto caps and ranked improvement priorities.
4
+ license: MIT
5
+ metadata:
6
+ workflow: sequential
7
+ ---
8
+
9
+ # blame-agents 技能(固定 Sprint 冲刺)
10
+
11
+ 自包含 AGENTS.md 审计评分器:输入工程路径,按 **7 类必检(满分 100)+ 红线封顶 + 可选模块加权** 评分,输出 Markdown 审计报告与改进优先级。全部评分条目来自 AGENTS.md 开放格式的公开规范与社区实践共识,逐条可溯源。
12
+
13
+ ## Overview
14
+
15
+ AGENTS.md 在会话开始时**全量进入上下文**,因此它不是"写得越多越好"的文档,而是一份**上下文预算**:每一行都要通过"删掉它会让 agent 犯错吗"这道检验。本 skill 只评可判定的客观属性(命令可否溯源、路径是否存在、行数、章节覆盖、指令具体性),不评文采与篇幅丰度。
16
+
17
+ 本 skill 的评分对象只有 AGENTS.md 这份文件本身——不涉及任何工具的实现差异,不评"某个 agent 加载得对不对"。
18
+
19
+ ## When to Use
20
+
21
+ - 需要在提交前把关某工程(或 monorepo 某个子包)的 AGENTS.md 质量
22
+ - 需要量化"这个 AGENTS.md 值多少分、瓶颈在哪"
23
+ - 需要判断文件是否过长、是否与 README / CI 配置重复
24
+ - 需要在重构目录结构后确认指令文件没有漂移
25
+
26
+ ## When NOT to Use
27
+
28
+ - **要写或改文件** → 用 better-agents(本 skill 只出报告,不改任何文件)
29
+ - **评的是 SKILL.md** → 用 blame-skill;**评的是 agent 定义** → 用 blame-sprint-agent
30
+ - 工程里根本没有 AGENTS.md → 本 skill 评分无意义(见「审计对象定位」短路规则),先跑 better-agents
31
+
32
+ ## Quick Reference
33
+
34
+ | Item | 做什么 | 关键命令 |
35
+ |---|---|---|
36
+ | 1 | 定位审计对象、读取规则与目标全文 | `read` 目标文件 + `references/scoring-rules.md` |
37
+ | 2 | 跑机械预检,完成 7 类必检逐项评分 | `node references/check-agents.js <path> --json` |
38
+ | 3 | 判定红线、评可选模块、按公式算最终分 | 红线逐条比对 + `min(公式值, cap)` |
39
+ | 4 | 输出 Markdown 审计报告与改进优先级 | 见「Sprint Review」报告模板 |
40
+
41
+ ## 运行环境
42
+
43
+ | 项 | 值 |
44
+ |---|---|
45
+ | 运行时 | Node.js >= 20 |
46
+ | 第三方依赖 | 无(只用内置 `node:fs` / `node:path`) |
47
+ | 安装 | 无需安装,随 skill 分发 |
48
+
49
+ - **执行**:`references/check-agents.js` —— 每次审计 Item 2 **必须执行**,产出机械数据(行数 / 章节 / 指令行统计 / 命令抽取 / 占位符 / 密钥)
50
+ - **读作参考**:`references/scoring-rules.md` —— 通过 `read` 加载,不执行
51
+
52
+ 脚本缺失视为 skill 安装损坏 → 向 stderr 报错结束,不降级为纯手工统计。
53
+
54
+ ## 输入参数
55
+
56
+ 入参为调用方传入的**原始任务消息**,可为 JSON 对象、key=value 或自然语言等任意形态,agent 依据字段语义自主提取:
57
+
58
+ | 字段 | 类型 | 必填 | 说明 |
59
+ |---|---|---|---|
60
+ | `project_dir` | string | 二选一 | 工程根目录;用于自动定位指令文件 |
61
+ | `agents_file` | string | 二选一 | 直接指定要评的指令文件路径 |
62
+ 两个路径字段至少提供一个,否则命中 Item 1 短路规则。报告格式固定 Markdown,不是入参。
63
+
64
+ ## 审计对象定位
65
+
66
+ 只审计名为 `AGENTS.md` 的文件。`agents_file` 存在时直接使用;`project_dir` 存在时按「审计对象决策表」确定要评哪些文件——一个 monorepo 会产出**多份报告**(根文件与每份嵌套文件各一份)。
67
+
68
+ ### 审计对象决策表
69
+
70
+ | 工程 AGENTS.md 状态 | 审计对象 | 处理方式 |
71
+ |---|---|---|
72
+ | 只有根 `AGENTS.md` | 根文件 | 出一份报告 |
73
+ | 根 + 多个嵌套 `AGENTS.md` | 根文件 + 每个嵌套文件 | 每份各出一份报告,标题带作用域 |
74
+ | 只有嵌套 `AGENTS.md`、根缺失 | 每个嵌套文件 | 每份各出一份报告,并在报告开头注明根文件缺失(属必检一/二的扣分项) |
75
+ | 完全没有 `AGENTS.md` | — | 短路:不评分,stderr 报错并提示改用 better-agents |
76
+
77
+ ## 评分模型速览
78
+
79
+ 必检 7 类的**名称**如下,权重、扣分口径、红线与可选模块清单全部定义在 `references/scoring-rules.md`,本节不复述(评分时以 references 为准):
80
+
81
+ | # | 维度 | 评什么 |
82
+ |---|---|---|
83
+ | 一 | 文件位置与命名 | 文件名精确性、落位是否为最近作用域边界、作用域标题 |
84
+ | 二 | 作用域与分层正确性 | 通用/专属分工、层间冲突、嵌套是否重述根 |
85
+ | 三 | 命令与验证门 | 命令可溯源、四类覆盖、顺序与通过条件、单条可跑、失败处理 |
86
+ | 四 | 架构与结构 | 目录职责、入口与数据流、依赖方向、命名与文件约定 |
87
+ | 五 | 指令具体性 | 原则替换为事实、无占位符、无过度指导、无模糊豁免 |
88
+ | 六 | 精简与上下文预算 | 行数预算、每行有收益、与 README 分工 |
89
+ | 七 | 单一数据源与一致性 | 不搬运 CI/lint 配置、术语一致、与既有文档对齐 |
90
+
91
+ 可选模块按**被审对象**匹配判定:
92
+
93
+ | 模块 | 适用条件(命中即评) |
94
+ |---|---|
95
+ | A. Monorepo 多层作用域 | 工程存在多个子项目标志文件(`package.json`/`pyproject.toml`/`go.mod`/`Cargo.toml`) |
96
+ | B. 约束强度分层 | 文件同时含硬性约束(必须/禁止)与经验性建议(惯例/偏好) |
97
+ | C. 自检门 | 仓库已存在针对 AGENTS.md 的机械校验(脚本、CI job、pre-commit hook) |
98
+ | D. 代码风格与测试风格约定 | 工程存在需靠 AGENTS.md 传递的风格事实:无 formatter/linter 兜底、与生态默认相反、或测试组织形态非默认。**含"工程需要但文件没写"的情形** |
99
+
100
+ ## 执行范式
101
+
102
+ 每次调用 = 一个固定 Sprint,三个事件:
103
+
104
+ 1. **Sprint Planning**:解析入参 → 定义 Sprint Goal → todowrite 落固定 4 项 Sprint Backlog(每项带 DoD)
105
+ 2. **Sprint Execution**:逐项执行,每项 = 标记 `in_progress` → 执行 → 验证 DoD → 立即 `completed`(即时更新,不攒批)
106
+ 3. **Sprint Review**:对照 Sprint Goal 验证 Increment(评分报告)及输出格式
107
+
108
+ **Sprint Goal** = `对目标 AGENTS.md 完成机械预检 + 7 类必检评分 + 红线判定 + 可选模块评分,输出可溯源的审计报告`。
109
+
110
+ ## 固定 Sprint Backlog(todowrite 落单,覆盖历史 todos)
111
+
112
+ 1. 定位审计对象 + 读取规则与目标全文 | DoD: 入参已按「审计对象决策表」解析、每个待评 `AGENTS.md` 的绝对路径已确定、`references/scoring-rules.md` 已读取、每个目标文件已读取全文(或命中短路并 stderr 报错结束)
113
+ 2. 机械预检 + 7 类必检逐项评分 | DoD: `check-agents.js --json` 已执行且每份文件的客观数据已记录、7 类维度逐项得分与扣分原因已记录、每条命令已标注工程内溯源出处或标记不可溯源
114
+ 3. 红线判定 + 可选模块评分 + 最终得分 | DoD: 5 条红线逐条判定结果(命中/未命中)与封顶值已记录、适用的可选模块逐项得分已记录、`final = min(公式值, cap)` 已计算、等级已判定
115
+ 4. 输出审计报告 | DoD: 每份待评文件一份 Markdown 报告、最终得分/等级/红线命中/必检分项/可选分项/未满足项/改进优先级完整、报告未复述 scoring-rules.md 的权重数值
116
+
117
+ ## Sprint Execution
118
+
119
+ 按固定 4 项逐项执行(勾单机制见执行范式)。
120
+
121
+ ### Item 1:定位审计对象 + 读取规则与目标全文
122
+
123
+ 1. 从原始任务消息提取 `project_dir` / `agents_file`
124
+ 2. **短路规则**(命中即结束):
125
+ - 两个路径字段均缺失 → stderr 报错结束
126
+ - 指定路径不存在或不是文件 → stderr 报错结束
127
+ - 按决策表判定为"完全没有 `AGENTS.md`" → stderr 报错结束,提示改用 better-agents
128
+
129
+ 短路命中时:不进入后续 Item,剩余 Backlog Item 全部标记 `cancelled`(不得残留 `in_progress`),直接进入 Sprint Review 输出已有结果。
130
+ 3. 未短路时:
131
+ - `read` `references/scoring-rules.md` 全文(取权重、红线、可选模块清单)
132
+ - 对每个待评文件 `read` 全文
133
+ - `bash ls` AGENTS.md 所在目录,确认有无同名 `README.md`(用于「与 README 分工」与红线 V4)
134
+
135
+ ### Item 2:机械预检 + 7 类必检逐项评分
136
+
137
+ 对每个待评文件:
138
+
139
+ 1. 执行 `node <skill 目录>/references/check-agents.js <文件绝对路径> --json`,记录行数、章节、指令行可执行/泛化统计、命令列表、findings
140
+ 2. 退出码 1 不代表审计中断——error 级 findings 是评分证据,逐条并入对应维度扣分
141
+ 3. 按 scoring-rules.md 的 7 类逐项评分,每项记录:得分、扣分原因、证据(行号 / 文件名 / 脚本输出)
142
+ 4. **命令溯源**:每条出现在文件里的命令都要指出工程内出处(`package.json` scripts / `Makefile` / `.github/workflows/*.yml` / `pyproject.toml`);指不出的按规则扣分并计入红线 V2 判定
143
+ 5. **逐行修剪检验**(「六」用):对「六、精简与上下文预算」的"每行有收益"逐行执行"删掉会让 agent 犯错吗",无收益的连续行数用于扣分
144
+
145
+ ### Item 3:红线判定 + 可选模块评分 + 最终得分
146
+
147
+ 1. 逐条判定 5 条红线(V1-V5,清单与封顶值见 scoring-rules.md),记录命中项与对应封顶值;多条命中取最低封顶
148
+ 2. 按「评分模型速览」的可选模块适用条件逐个判定,适用模块各评 100 分,不适用跳过。D 的判据含"工程需要声明但文件缺失"的情形,不得因文件没写而跳过
149
+ 3. 按 scoring-rules.md 的公式计算 `final = min(公式值, cap)`
150
+ 4. 按 scoring-rules.md 的分数段判定等级,并在报告中标注等级是否被红线压低
151
+
152
+ ### Item 4:输出审计报告
153
+
154
+ 按「Sprint Review」的报告模板输出,每份待评文件一份。
155
+
156
+ ## 禁止事项与借口表
157
+
158
+ | 借口 | 现实 |
159
+ |---|---|
160
+ | "README 写得很全,AGENTS.md 薄一点也行" | README 不进入 agent 上下文,且面向人类贡献者;命令与约定缺失会让 agent 反复追问 |
161
+ | "命令我是从文档里抄的,肯定对" | 未溯源的命令就是漂移源,命中红线 V2;正确性只能由工程内文件证明 |
162
+ | "行数超了,但每一行都重要" | 全量进入上下文,超预算必然让关键规则被稀释;先砍铺垫与重复 |
163
+ | "嵌套文件差不多等于根文件" | 嵌套文件只在自己的作用域内生效,整份复制即浪费,规则冲突即错误 |
164
+ | "先给个大概分,细节以后补" | 未记录的扣分原因会让报告不可复现,改进优先级也无法排序 |
165
+
166
+ **禁令**:
167
+
168
+ - 禁止编造未在工程中验证的命令、路径、行数或扣分证据
169
+ - 禁止在本 skill 内修改被评文件(改文件是 better-agents 的职责)
170
+ - 禁止使用 WebFetch 或任何网络请求补证
171
+
172
+ ## Red Flags(自检清单,提交报告前逐条过)
173
+
174
+ 1. 全文未检出任何命令 → 「三、命令与验证门」直接记 0,不得给高分
175
+ 2. 文件行数 > 500 → 必须命中红线 V3,报告要写明被封顶
176
+ 3. 泛化指令行占比 ≥ 50% → 必须命中红线 V5
177
+ 4. 根与嵌套文件对同一命令给出不同写法 → 「二」层间冲突扣分
178
+ 5. 报告里的维度满分与 `references/scoring-rules.md` 不一致 → 以 references 为准并修正报告
179
+ 6. 改进项写成"可考虑进一步优化"这类无动作表述 → 重写为具体到节与行的改法
180
+ 7. monorepo 只给根文件出报告 → 补齐每份嵌套文件的报告
181
+
182
+ ## Common Mistakes
183
+
184
+ | 错误 | 后果 | 修复 |
185
+ |---|---|---|
186
+ | 跳过 `check-agents.js` 直接凭印象打分 | 行数、泛化率、占位符靠肉眼,结论不可复现 | Item 2 第一步强制执行脚本,用其输出当客观数据 |
187
+ | 把"文采好、排版漂亮"记为加分 | 评分偏离本规则的可判定取向 | 只评命令溯源、路径存在性、行数、章节覆盖、指令具体性 |
188
+ | 命令没溯源却记「三」满分 | 掩盖漂移风险,红线 V1 也无法判定 | 逐条标注出处文件;标不出即扣分 |
189
+ | 红线命中后仍按公式原值输出 | 报告给出的分数高于实际风险 | `final` 必须取 `min(公式值, cap)` 并注明封顶来源 |
190
+ | 只评根文件 | monorepo 的子包规则问题全部漏检 | 按决策表对每份嵌套文件各出报告 |
191
+ | 把权重数值抄进报告 | 违反单一数据源,规则更新后报告口径即过期 | 报告只写维度名与得分,权重指向 `references/scoring-rules.md` |
192
+
193
+ ## Sprint Review
194
+
195
+ 本 skill 每次调用 = 无状态独立 Sprint,无跨轮次状态,故不进行 Retrospective。所有 Backlog Items 完成后:
196
+
197
+ - **对照 Sprint Goal 验证**:机械预检是否执行?7 类必检是否逐项打分?红线是否逐条判定?最终分是否取了 `min(公式值, cap)`?每份待评文件是否都有报告?
198
+ - **验证 Increment**:Increment = 每份待评文件一份 Markdown 评分报告;验证其已输出且分项、红线、改进优先级完整。
199
+ - **Red Flags 终检**:过一遍上方 7 条自检清单,不通过则修正报告后再交付。
200
+
201
+ 报告模板:
202
+
203
+ ```
204
+ ## AGENTS.md 审计报告:<作用域或文件路径>
205
+
206
+ ### 最终得分:XX / 100(等级:X)| 封顶:<cap 值或"未命中红线">
207
+
208
+ ### 红线判定
209
+
210
+ | 红线 | 结果 | 证据 |
211
+ |---|---|---|
212
+ | V1 命令不可验证 | 命中/未命中 | |
213
+ | V2 与工程漂移 | 命中/未命中 | |
214
+ | V3 预算失控 | 命中/未命中 | |
215
+ | V4 README 搬运 | 命中/未命中 | |
216
+ | V5 泛化指令主导 | 命中/未命中 | |
217
+
218
+ ### 必检模块得分(R = XX / 100)
219
+
220
+ 各维度满分见 references/scoring-rules.md,本表只记录得分。
221
+
222
+ | # | 维度 | 得分 | 主要扣分原因 |
223
+ |---|---|---|---|
224
+ | 一 | 文件位置与命名 | XX | |
225
+ | 二 | 作用域与分层正确性 | XX | |
226
+ | 三 | 命令与验证门 | XX | |
227
+ | 四 | 架构与结构 | XX | |
228
+ | 五 | 指令具体性 | XX | |
229
+ | 六 | 精简与上下文预算 | XX | |
230
+ | 七 | 单一数据源与一致性 | XX | |
231
+
232
+ ### 可选模块得分
233
+
234
+ | 模块 | 适用 | 得分 | 满分 |
235
+ |---|---|---|---|
236
+ | A. Monorepo 多层作用域 | 是/否 | XX | 100 |
237
+ | B. 约束强度分层 | 是/否 | XX | 100 |
238
+ | C. 自检门 | 是/否 | XX | 100 |
239
+ | D. 代码风格与测试风格约定 | 是/否 | XX | 100 |
240
+
241
+ ### 未满足项及改进建议
242
+
243
+ - [ ] **[维度] [具体问题]**(扣 X 分)
244
+ - 证据:<行号 / 文件名 / 脚本 finding>
245
+ - 现状:<当前写法>
246
+ - 改法:<改到哪一节、改成什么可判定的内容>
247
+
248
+ ### 改进优先级
249
+
250
+ 1. <最高分值扣分项>
251
+ 2. <次优先项>
252
+ 3. ...
253
+ ```
254
+
255
+ ## 约束
256
+
257
+ - 只处理已声明字段(`project_dir` / `agents_file`),忽略所有其他传入参数
258
+ - 禁止使用 WebFetch 或任何网络请求;证据只能来自本工程的文件与脚本输出
259
+ - 读文件用 `read`;列目录用 `bash ls`;机械预检的命令形式见「运行环境」
260
+ - 本 skill 只输出评分报告,**不提供改写服务**,也不修改任何被评文件
261
+ - 评分口径的唯一真源是 `references/scoring-rules.md`,本文件不复述其权重数值
262
+ - 改进建议应写成可交给 better-agents 直接执行的动作(改哪节、补什么证据),不含主观评价
263
+
264
+ ## references/ 目录结构
265
+
266
+ ```
267
+ references/
268
+ ├── scoring-rules.md # 读作参考:7 类必检权重与扣分口径、5 条红线、4 个可选模块、得分公式、评分依据出处
269
+ └── check-agents.js # 执行:零依赖 ESM 机械预检器,产出客观数据与 findings
270
+ ```
@@ -0,0 +1,364 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * AGENTS.md 机械预检器(零第三方依赖,ESM)
4
+ *
5
+ * 用法:
6
+ * node check-agents.js <AGENTS.md 路径> [--json] [--max-lines N]
7
+ *
8
+ * 产出客观数据供 blame-agents 评分使用:行数、检出章节、空章节、
9
+ * 可执行/泛化指令行统计、占位符、密钥模式、无语言标注代码块、命令抽取。
10
+ *
11
+ * 退出码:0 = 无 error 级问题;1 = 存在 error 级问题;2 = 路径不可读或缺参。
12
+ *
13
+ * 可执行指令行的判定口径(heuristic,评分规则「五、指令具体性」引用此定义):
14
+ * 形如列表项(- / * / 1.)的行,若包含以下任一元素即为可执行行——
15
+ * ① 含路径(含 `/` 且非纯 URL)② 含命令关键字 ③ 含行内代码 ④ 含规范性标记
16
+ * (必须 / 禁止 / 不得 / must / never / always 等)。否则计为泛化指令行。
17
+ */
18
+
19
+ import { readFileSync } from "node:fs";
20
+ import { basename } from "node:path";
21
+
22
+ export const DEFAULT_MAX_LINES = 200;
23
+ export const HARD_MAX_LINES = 500;
24
+
25
+ /** 章节识别表:key → 中英文别名(小写匹配) */
26
+ export const SECTION_PATTERNS = {
27
+ commands: ["command", "命令", "常用命令", "脚本", "shell"],
28
+ setup: ["setup", "install", "安装", "环境准备", "bootstrap", "quick start"],
29
+ build: ["build", "构建", "编译", "产出"],
30
+ test: ["test", "testing", "测试", "单测", "ut", "it"],
31
+ lint: ["lint", "typecheck", "type check", "静态检查", "类型检查", "代码规范"],
32
+ structure: ["structure", "layout", "目录", "结构", "布局", "组成"],
33
+ architecture: ["architecture", "架构", "data flow", "数据流"],
34
+ conventions: ["convention", "style", "conventions", "规范", "约定", "代码风格"],
35
+ security: ["security", "安全", "secret"],
36
+ delivery: ["pr", "commit", "pull request", "提交", "交付", "发布", "部署", "deployment"],
37
+ forbidden: ["do not", "never", "禁止", "不要", "必须", "must", "iron law", "红线"],
38
+ };
39
+
40
+ const PATH_RE = /(?:\.\/|\.\.\/|\bsrc\/|\btests\/|\bbin\/|\bcli\/|\bpackages\/|\bskills\/|\bdocs\/|\b[A-Za-z0-9_-]+\/)[A-Za-z0-9_.*/-]+/;
41
+ const URL_RE = /^\s*(?:https?:)?\/\//;
42
+ const CODE_RE = /`[^`]+`/;
43
+ const COMMAND_WORDS =
44
+ /\b(pnpm|npm|yarn|bun|node|deno|python3?|pytest|uv|ruff|mypy|make|cargo|go|git|bash|sh|zsh|docker|eslint|prettier|tsc|vitest|jest|opencode|jq|curl)\b/;
45
+ const NORMATIVE_RE = /(必须|禁止|不得|不要|务必|一律|永远|must\b|must not|never\b|always\b|required|only\b)/i;
46
+ const BULLET_RE = /^\s*(?:[-*+]\s+|\d+[.)]\s+)/;
47
+ const PLACEHOLDER_RE =
48
+ /\b(TODO|TBD|FIXME)\b|<(your[-_ ]?(project|package|app|name|module)|package_name|project_name|你的)>/;
49
+ const SECRET_RE =
50
+ /(sk-[A-Za-z0-9]{16,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,}|xox[baprs]-[A-Za-z0-9-]{10,}|(?:api[_-]?key|secret|token|password)\s*[:=]\s*["']?[A-Za-z0-9_\-]{16,})/i;
51
+ const WINDOWS_PATH_RE = /`[A-Za-z]:\\|\\\\[A-Za-z0-9_.-]+\\/;
52
+
53
+ function makeFinding(rule, severity, message, line) {
54
+ return { rule, severity, message, line: line ?? null };
55
+ }
56
+
57
+ /** 去掉围栏代码块内容,返回"代码块之外的行数组"(内容为 null) */
58
+ function maskCodeBlocks(lines) {
59
+ const masked = [];
60
+ let inFence = false;
61
+ for (const raw of lines) {
62
+ if (/^\s*```/.test(raw)) {
63
+ inFence = !inFence;
64
+ masked.push(null);
65
+ continue;
66
+ }
67
+ masked.push(inFence ? null : raw);
68
+ }
69
+ return masked;
70
+ }
71
+
72
+ /** 去掉行内代码片段,避免把"提到占位符/密钥"的说明文字误判成真占位符 */
73
+ function stripInlineCode(line) {
74
+ return line.replace(/`[^`]*`/g, "``");
75
+ }
76
+
77
+ /** 抽取文档中出现的命令(行内代码里像命令的片段 + 代码块内命令) */
78
+ export function extractCommands(text) {
79
+ const commands = new Set();
80
+ for (const line of text.split(/\r?\n/)) {
81
+ for (const m of line.matchAll(/`([^`\n]+)`/g)) {
82
+ const candidate = m[1].trim();
83
+ if (COMMAND_WORDS.test(candidate) && !/\s=\s*"|\.md`?$/.test(candidate)) commands.add(candidate);
84
+ }
85
+ }
86
+ const inFence = /```(?:bash|sh|shell|zsh|console)?\r?\n([\s\S]*?)```/g;
87
+ let block;
88
+ while ((block = inFence.exec(text)) !== null) {
89
+ for (const line of block[1].split(/\r?\n/)) {
90
+ const t = line.trim();
91
+ if (t && !t.startsWith("#")) commands.add(t);
92
+ }
93
+ }
94
+ return [...commands];
95
+ }
96
+
97
+ /** 统计可执行 / 泛化指令行(口径见文件头注释) */
98
+ export function classifyInstructionLines(text) {
99
+ const masked = maskCodeBlocks(text.split(/\r?\n/));
100
+ const executable = [];
101
+ const vague = [];
102
+ masked.forEach((raw, idx) => {
103
+ if (raw === null) return;
104
+ if (!BULLET_RE.test(raw)) return;
105
+ const body = raw.replace(BULLET_RE, "").trim();
106
+ if (!body || URL_RE.test(body)) return;
107
+ const hasPath = PATH_RE.test(body) && !URL_RE.test(body);
108
+ const hit =
109
+ hasPath || COMMAND_WORDS.test(body) || CODE_RE.test(body) || NORMATIVE_RE.test(body);
110
+ (hit ? executable : vague).push({ line: idx + 1, text: body });
111
+ });
112
+ const total = executable.length + vague.length;
113
+ return {
114
+ executable,
115
+ vague,
116
+ total,
117
+ vagueRatio: total === 0 ? 0 : Number((vague.length / total).toFixed(3)),
118
+ };
119
+ }
120
+
121
+ /** 检出章节:返回 { key: { heading, line } },同一 key 只记首次出现 */
122
+ export function detectSections(text) {
123
+ const lines = text.split(/\r?\n/);
124
+ const found = {};
125
+ lines.forEach((raw, idx) => {
126
+ const m = /^\s{0,3}#{1,6}\s+(.+?)\s*$/.exec(raw);
127
+ if (!m) return;
128
+ const heading = m[1].toLowerCase();
129
+ for (const [key, aliases] of Object.entries(SECTION_PATTERNS)) {
130
+ if (found[key]) continue;
131
+ if (aliases.some((a) => heading.includes(a))) found[key] = { heading: m[1], line: idx + 1 };
132
+ }
133
+ });
134
+ return found;
135
+ }
136
+
137
+ /** 找出空章节(标题后直接是下一个标题;一级标题是文档名,不参与判定) */
138
+ export function findEmptySections(text) {
139
+ const lines = maskCodeBlocks(text.split(/\r?\n/));
140
+ const empty = [];
141
+ for (let i = 0; i < lines.length; i += 1) {
142
+ const raw = lines[i];
143
+ if (raw === null) continue;
144
+ if (!/^\s{0,3}#{2,6}\s+\S/.test(raw)) continue;
145
+ let j = i + 1;
146
+ while (j < lines.length && (lines[j] === null || lines[j].trim() === "")) j += 1;
147
+ const next = j < lines.length ? lines[j] : null;
148
+ if (next === null || /^\s{0,3}#{1,6}\s+\S/.test(next)) {
149
+ empty.push({ heading: raw.trim(), line: i + 1 });
150
+ if (next === null) break;
151
+ }
152
+ }
153
+ return empty;
154
+ }
155
+
156
+ /** 找出未标注语言的代码块起始围栏(闭合围栏不算) */
157
+ export function findUnlabeledFences(text) {
158
+ const lines = text.split(/\r?\n/);
159
+ const hits = [];
160
+ let open = false;
161
+ lines.forEach((raw, idx) => {
162
+ const m = /^\s*```(.*)$/.exec(raw);
163
+ if (!m) return;
164
+ if (open) {
165
+ open = false;
166
+ return;
167
+ }
168
+ open = true;
169
+ if (m[1].trim() === "") hits.push(idx + 1);
170
+ });
171
+ return hits;
172
+ }
173
+
174
+ /**
175
+ * 核心分析函数(纯函数,便于单测)
176
+ * @param {string} text AGENTS.md 全文
177
+ * @param {{maxLines?: number, path?: string, readmeText?: string|null}} options
178
+ */
179
+ export function analyze(text, options = {}) {
180
+ const maxLines = Number.isFinite(options.maxLines) ? options.maxLines : DEFAULT_MAX_LINES;
181
+ const fileName = options.path ? basename(options.path) : "AGENTS.md";
182
+ const lines = text.split(/\r?\n/);
183
+ if (lines.length && lines[lines.length - 1] === "") lines.pop();
184
+ const lineCount = lines.length;
185
+ const masked = maskCodeBlocks(lines);
186
+ const findings = [];
187
+
188
+ const firstContent = masked.find((l) => l !== null && l.trim() !== "");
189
+ if (!firstContent || !/^\s{0,3}#\s+\S/.test(firstContent)) {
190
+ findings.push(
191
+ makeFinding("E_NO_TITLE", "error", "首个非空行不是 `# 标题`,agent 无法判断规则作用域", 1)
192
+ );
193
+ }
194
+
195
+ if (lineCount > HARD_MAX_LINES) {
196
+ findings.push(
197
+ makeFinding("E_LINE_BUDGET", "error", `行数 ${lineCount} > ${HARD_MAX_LINES},命中红线 V3`, lineCount)
198
+ );
199
+ } else if (lineCount > maxLines) {
200
+ findings.push(
201
+ makeFinding("W_LINE_BUDGET", "warn", `行数 ${lineCount} > 预算 ${maxLines}`, lineCount)
202
+ );
203
+ }
204
+
205
+ masked.forEach((raw, idx) => {
206
+ if (raw === null) return;
207
+ const prose = stripInlineCode(raw);
208
+ if (PLACEHOLDER_RE.test(prose)) {
209
+ findings.push(makeFinding("E_PLACEHOLDER", "error", "存在未替换的占位符", idx + 1));
210
+ }
211
+ if (SECRET_RE.test(prose)) {
212
+ findings.push(makeFinding("E_SECRET", "error", "疑似硬编码密钥/凭据", idx + 1));
213
+ }
214
+ if (WINDOWS_PATH_RE.test(raw)) {
215
+ findings.push(makeFinding("W_WINDOWS_PATH", "warn", "Windows 风格路径,跨平台 agent 不可用", idx + 1));
216
+ }
217
+ });
218
+
219
+ lines.forEach((raw, idx) => {
220
+ if (/^\s{0,3}#{1,6}\s+.*\b(TODO|TBD|FIXME)\b/i.test(raw)) {
221
+ findings.push(makeFinding("E_TODO_HEADING", "error", "章节标题仍是 TODO/TBD 占位", idx + 1));
222
+ }
223
+ });
224
+
225
+ const unlabeled = findUnlabeledFences(text);
226
+ for (const line of unlabeled) {
227
+ findings.push(makeFinding("W_FENCE_NO_LANG", "warn", "代码块未标注语言", line));
228
+ }
229
+
230
+ for (const s of findEmptySections(text)) {
231
+ findings.push(makeFinding("W_EMPTY_SECTION", "warn", `空章节「${s.heading}」`, s.line));
232
+ }
233
+
234
+ const sections = detectSections(text);
235
+ const hasAny = (...keys) => keys.some((k) => sections[k]);
236
+ const required = [
237
+ [hasAny("commands", "setup", "build", "test", "lint"), "命令 / Commands"],
238
+ [hasAny("structure", "architecture"), "结构 / Layout"],
239
+ [hasAny("conventions", "forbidden", "delivery", "security"), "约定 / 禁止 / 交付前检查"],
240
+ ];
241
+ for (const [ok, label] of required) {
242
+ if (!ok) findings.push(makeFinding("W_MISSING_SECTION", "warn", `未检出「${label}」类章节`));
243
+ }
244
+
245
+ const inst = classifyInstructionLines(text);
246
+ if (inst.total >= 5 && 1 - inst.vagueRatio < 0.5) {
247
+ findings.push(
248
+ makeFinding(
249
+ "E_VAGUE_MAJORITY",
250
+ "error",
251
+ `泛化指令行占比 ${(inst.vagueRatio * 100).toFixed(0)}%(${inst.vague.length}/${inst.total}),命中红线 V5`,
252
+ null
253
+ )
254
+ );
255
+ }
256
+
257
+ const commands = extractCommands(text);
258
+ if (commands.length === 0) {
259
+ findings.push(makeFinding("E_NO_COMMANDS", "error", "全文未检出任何可执行命令", null));
260
+ }
261
+
262
+ let readmeOverlap = 0;
263
+ if (options.readmeText) {
264
+ const docLines = new Set(
265
+ text
266
+ .split(/\r?\n/)
267
+ .map((l) => l.replace(/^[\s>*+-]+/, "").trim())
268
+ .filter((l) => l.length > 0)
269
+ );
270
+ readmeOverlap = options.readmeText
271
+ .split(/\r?\n/)
272
+ .map((l) => l.replace(/^[\s>*+-]+/, "").trim())
273
+ .filter((l) => l.length > 0 && docLines.has(l)).length;
274
+ if (readmeOverlap >= 30) {
275
+ findings.push(
276
+ makeFinding("E_README_OVERLAP", "error", `与 README 重复 ${readmeOverlap} 行,命中红线 V4`, null)
277
+ );
278
+ }
279
+ }
280
+
281
+ return {
282
+ path: options.path ?? null,
283
+ file: fileName,
284
+ lineCount,
285
+ maxLines,
286
+ sections,
287
+ instructionLines: {
288
+ total: inst.total,
289
+ executable: inst.executable.length,
290
+ vague: inst.vague.length,
291
+ vagueRatio: inst.vagueRatio,
292
+ vagueSamples: inst.vague.slice(0, 10),
293
+ },
294
+ commands,
295
+ findings,
296
+ errors: findings.filter((f) => f.severity === "error"),
297
+ };
298
+ }
299
+
300
+ /** 人类可读报告 */
301
+ export function formatReport(result) {
302
+ const out = [];
303
+ out.push(`AGENTS.md 机械预检:${result.file ?? "(stdin)"}`);
304
+ out.push(`行数:${result.lineCount}(预算 ${result.maxLines},硬上限 ${HARD_MAX_LINES})`);
305
+ out.push(
306
+ `指令行:${result.instructionLines.total}(可执行 ${result.instructionLines.executable} / 泛化 ${result.instructionLines.vague},泛化占比 ${(result.instructionLines.vagueRatio * 100).toFixed(0)}%)`
307
+ );
308
+ out.push(`检出章节:${Object.keys(result.sections).join(", ") || "无"}`);
309
+ out.push(`命令数:${result.commands.length}`);
310
+ if (result.findings.length === 0) {
311
+ out.push("问题:0 error / 0 warn");
312
+ } else {
313
+ out.push(`问题:${result.errors.length} error / ${result.findings.length - result.errors.length} warn`);
314
+ for (const f of result.findings) {
315
+ out.push(` - [${f.severity}] ${f.rule}${f.line ? ` (L${f.line})` : ""}: ${f.message}`);
316
+ }
317
+ }
318
+ return out.join("\n");
319
+ }
320
+
321
+ export function main(argv = process.argv.slice(2)) {
322
+ const args = argv.filter((a) => a !== "--json");
323
+ const asJson = argv.includes("--json");
324
+ const maxIdx = argv.indexOf("--max-lines");
325
+ let maxLines = DEFAULT_MAX_LINES;
326
+ if (maxIdx !== -1 && Number.isFinite(Number(argv[maxIdx + 1]))) {
327
+ maxLines = Number(argv[maxIdx + 1]);
328
+ } else if (maxIdx !== -1) {
329
+ process.stderr.write("错误:--max-lines 需要一个数字参数\n");
330
+ return 2;
331
+ }
332
+
333
+ const target = args[0];
334
+ if (!target) {
335
+ process.stderr.write("错误:缺少 AGENTS.md 路径。用法:node check-agents.js <path> [--json]\n");
336
+ return 2;
337
+ }
338
+
339
+ let text;
340
+ try {
341
+ text = readFileSync(target, "utf8");
342
+ } catch (err) {
343
+ process.stderr.write(`错误:无法读取 ${target}(${err.code ?? err.message})\n`);
344
+ return 2;
345
+ }
346
+
347
+ let readmeText = null;
348
+ try {
349
+ const dir = target.replace(/\/[^/]*$/, "");
350
+ readmeText = readFileSync(`${dir}/README.md`, "utf8");
351
+ } catch {
352
+ readmeText = null;
353
+ }
354
+
355
+ const result = analyze(text, { maxLines, path: target, readmeText });
356
+ process.stdout.write(`${asJson ? JSON.stringify(result, null, 2) : formatReport(result)}\n`);
357
+ return result.errors.length > 0 ? 1 : 0;
358
+ }
359
+
360
+ const invokedDirectly =
361
+ process.argv[1] && import.meta.url === `file://${process.argv[1]}`;
362
+ if (invokedDirectly) {
363
+ process.exitCode = main();
364
+ }