reasonweave 1.4.5 → 1.4.6

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/AGENTS.md CHANGED
@@ -67,7 +67,7 @@ docs/ 辅助文档与待办 (docs/backlogs/)
67
67
 
68
68
  <!-- handoff-stub:v2.1 begin -->
69
69
  <!-- generated — do not edit -->
70
- <!-- stub:sha256:9a6076fc -->
70
+ <!-- stub:sha256:5090fcd4 -->
71
71
  ### Agent Baton (Handoff) 接入桩(轻量韧性版 · 细则以 $(lab path handoffs)/README.md 契约 v2.41.2 为准)
72
72
 
73
73
  **核心守卫与身份(强制)**
@@ -83,7 +83,7 @@ docs/ 辅助文档与待办 (docs/backlogs/)
83
83
  2. **读工单**:运行 `baton show <id>`,根据验收判据改动本 lane 范围代码并实测。
84
84
  3. **交付或退回(实测为唯一准绳)**:
85
85
  - **实测通过**:照抄 `$(lab path handoffs)/RESPONSE-TEMPLATE.md` 骨架 → 运行 `baton receipt <id> -n "<正文>" --deliver --as <本方 lane> --evidence-paths "<路径>"`(审计工单附 `--audit-nonce "<nonce>"` 或同工作区授权下使用 `--auto-nonce` 自动绑定最新令牌;红队用例严格遵循 NO_DISPATCH / NO_COMPLETE / COMPLETE 三态标准)。
86
- - **实测未过(NO-GO/受阻)**:享有安全下车通道,直接运行 `baton reject <id> -n "<理由/缺失条件>" --as <本方 lane>` 退回整改。
86
+ - **实测未过(NO-GO/受阻)**:审计方享有安全下车通道,运行 `baton reject <id> -n "<理由/差异在哪>" --as audit` 退回整改;普通执行方若受阻/缺失条件,登记受阻回执 `baton receipt <id> -n "<缺失条件/受阻理由>" --evidence-note "<说明>" --as <本方 lane>` 由发起方核实并处理。
87
87
  4. **收尾自检**:运行 `baton check [id]`(若有数据漂移可加 `--fix` 自动修复)。
88
88
  5. **入站回复收尾(简洁单行裁决 · 严禁角色漂移)**:接收方必须严格保持本方执行/审计角色,严禁切换为发起方角色;**严禁反向输出 `## 交接提示词` 卡片或调用 `baton close` 越权闭环**;最终回复人类的最末尾仅输出单行纯文本(无需标题,无需代码块,严禁多行出站卡片):
89
89
  - 审计驳回:`审计完成,裁决 NO-GO(工单已退回<发起方角色>进入 Round <N>)`
package/INSTALL.md CHANGED
@@ -69,7 +69,7 @@ npm link
69
69
 
70
70
  | CLI | 作用 |
71
71
  |---|---|
72
- | `reasonweave`(别名 `lab`, `rw`) | 能力库总管、`lab init` 全套一键初始化、路径动态解析、环境体检 (`lab doctor`)、ZSpec 脚手架、下游一键批量同步分发 (`sync-consumers`)、全量转发核心工具 (v1.4.5,支持 `--version`) |
72
+ | `reasonweave`(别名 `lab`, `rw`) | 能力库总管、`lab init` 全套一键初始化、路径动态解析、环境体检 (`lab doctor`)、ZSpec 脚手架、下游一键批量同步分发 (`sync-consumers`)、全量转发核心工具 (v1.4.6,支持 `--version`) |
73
73
  | `baton`(别名 `agent-baton` / `handoff`) | 跨仓 / 仓内任务交割中枢、统一会话ID、防跨会话硬门禁、会话锁、密码学防伪回执、事件驱动唤醒(v2.41.2) |
74
74
  | `baton-worktree` | 为工单分配 / 回收独立物理工作树(v0.1.1,支持 `--version`) |
75
75
  | `baton-audit-runner` | 无上下文独立进程重跑验收测试,真实 Exit 0 方可签发回执(v1.2.3,支持 `--version`) |
package/README.md CHANGED
@@ -246,7 +246,7 @@ ln -sf ~/dev-templates/hooks/pre-commit-miniprogram .git/hooks/pre-commit
246
246
 
247
247
  <!-- handoff-stub:v2.1 begin -->
248
248
  <!-- generated — do not edit -->
249
- <!-- stub:sha256:9a6076fc -->
249
+ <!-- stub:sha256:5090fcd4 -->
250
250
  ### Agent Baton (Handoff) 接入桩(轻量韧性版 · 细则以 $(lab path handoffs)/README.md 契约 v2.41.2 为准)
251
251
 
252
252
  **核心守卫与身份(强制)**
@@ -262,7 +262,7 @@ ln -sf ~/dev-templates/hooks/pre-commit-miniprogram .git/hooks/pre-commit
262
262
  2. **读工单**:运行 `baton show <id>`,根据验收判据改动本 lane 范围代码并实测。
263
263
  3. **交付或退回(实测为唯一准绳)**:
264
264
  - **实测通过**:照抄 `$(lab path handoffs)/RESPONSE-TEMPLATE.md` 骨架 → 运行 `baton receipt <id> -n "<正文>" --deliver --as <本方 lane> --evidence-paths "<路径>"`(审计工单附 `--audit-nonce "<nonce>"` 或同工作区授权下使用 `--auto-nonce` 自动绑定最新令牌;红队用例严格遵循 NO_DISPATCH / NO_COMPLETE / COMPLETE 三态标准)。
265
- - **实测未过(NO-GO/受阻)**:享有安全下车通道,直接运行 `baton reject <id> -n "<理由/缺失条件>" --as <本方 lane>` 退回整改。
265
+ - **实测未过(NO-GO/受阻)**:审计方享有安全下车通道,运行 `baton reject <id> -n "<理由/差异在哪>" --as audit` 退回整改;普通执行方若受阻/缺失条件,登记受阻回执 `baton receipt <id> -n "<缺失条件/受阻理由>" --evidence-note "<说明>" --as <本方 lane>` 由发起方核实并处理。
266
266
  4. **收尾自检**:运行 `baton check [id]`(若有数据漂移可加 `--fix` 自动修复)。
267
267
  5. **入站回复收尾(简洁单行裁决 · 严禁角色漂移)**:接收方必须严格保持本方执行/审计角色,严禁切换为发起方角色;**严禁反向输出 `## 交接提示词` 卡片或调用 `baton close` 越权闭环**;最终回复人类的最末尾仅输出单行纯文本(无需标题,无需代码块,严禁多行出站卡片):
268
268
  - 审计驳回:`审计完成,裁决 NO-GO(工单已退回<发起方角色>进入 Round <N>)`
package/bin/lab.mjs CHANGED
@@ -107,20 +107,22 @@ function doctor() {
107
107
  console.log(`\n🔍 正在检查环境依赖 (ReasonWeave v${LAB_VERSION}):\n`);
108
108
 
109
109
  const userHome = os.homedir();
110
+ const isWin = process.platform === 'win32';
111
+ const pathSep = path.delimiter;
112
+
110
113
  const extraPaths = [
111
114
  path.dirname(process.execPath),
112
115
  path.join(userHome, '.local', 'bin'),
113
- '/opt/homebrew/bin',
114
- '/usr/local/bin',
116
+ ...(!isWin ? ['/opt/homebrew/bin', '/usr/local/bin'] : []),
115
117
  ].filter(p => fs.existsSync(p));
116
118
 
117
119
  const envPath = process.env.PATH || '';
118
120
  const augmentedPath = [
119
121
  ...new Set([
120
- ...envPath.split(':').filter(Boolean),
122
+ ...envPath.split(pathSep).filter(Boolean),
121
123
  ...extraPaths,
122
124
  ])
123
- ].join(':');
125
+ ].join(pathSep);
124
126
 
125
127
  const runCmd = (cmd, env = {}) => {
126
128
  return execSync(cmd, {
@@ -130,6 +132,18 @@ function doctor() {
130
132
  }).toString().trim();
131
133
  };
132
134
 
135
+ const findExecutable = (binName) => {
136
+ try {
137
+ const probeCmd = isWin ? `where ${binName}` : `which ${binName}`;
138
+ const out = runCmd(probeCmd);
139
+ if (out) {
140
+ const firstLine = out.split(/\r?\n/).map(s => s.trim()).filter(Boolean)[0];
141
+ if (firstLine && fs.existsSync(firstLine)) return firstLine;
142
+ }
143
+ } catch {}
144
+ return null;
145
+ };
146
+
133
147
  // 1. Node.js (>=18)
134
148
  try {
135
149
  const nodeVer = process.version;
@@ -155,19 +169,15 @@ function doctor() {
155
169
  try {
156
170
  let ogBin = process.env.OPENGREP_BIN;
157
171
  if (!ogBin || !fs.existsSync(ogBin)) {
158
- try {
159
- const whichOut = runCmd('which opengrep');
160
- if (whichOut && fs.existsSync(whichOut)) ogBin = whichOut;
161
- } catch {}
172
+ ogBin = findExecutable('opengrep');
162
173
  }
163
174
  const searchDirs = [
164
175
  path.join(userHome, '.local', 'bin'),
165
- '/opt/homebrew/bin',
166
- '/usr/local/bin',
176
+ ...(!isWin ? ['/opt/homebrew/bin', '/usr/local/bin'] : []),
167
177
  ];
168
178
  if (!ogBin) {
169
179
  for (const d of searchDirs) {
170
- const cand = path.join(d, 'opengrep');
180
+ const cand = path.join(d, isWin ? 'opengrep.exe' : 'opengrep');
171
181
  if (fs.existsSync(cand)) {
172
182
  ogBin = cand;
173
183
  break;
@@ -177,16 +187,11 @@ function doctor() {
177
187
  // Fallback to semgrep
178
188
  let isSemgrepFallback = false;
179
189
  if (!ogBin) {
180
- try {
181
- const whichSemgrep = runCmd('which semgrep');
182
- if (whichSemgrep && fs.existsSync(whichSemgrep)) {
183
- ogBin = whichSemgrep;
184
- isSemgrepFallback = true;
185
- }
186
- } catch {}
190
+ ogBin = findExecutable('semgrep');
191
+ if (ogBin) isSemgrepFallback = true;
187
192
  if (!ogBin) {
188
193
  for (const d of searchDirs) {
189
- const cand = path.join(d, 'semgrep');
194
+ const cand = path.join(d, isWin ? 'semgrep.exe' : 'semgrep');
190
195
  if (fs.existsSync(cand)) {
191
196
  ogBin = cand;
192
197
  isSemgrepFallback = true;
@@ -207,7 +212,11 @@ function doctor() {
207
212
  } catch {
208
213
  verOut = '已就绪 (探针超时)';
209
214
  }
210
- const inOriginalPath = (process.env.PATH || '').split(':').some(p => ogBin.startsWith(p + '/'));
215
+ const inOriginalPath = (process.env.PATH || '').split(pathSep).some(p => {
216
+ const normP = path.normalize(p).toLowerCase();
217
+ const normBin = path.normalize(ogBin).toLowerCase();
218
+ return normBin.startsWith(normP);
219
+ });
211
220
  const note = inOriginalPath ? '' : ` (位于 ${ogBin},非默认 PATH)`;
212
221
  const label = isSemgrepFallback ? 'Semgrep (review-gate 兼容)' : 'OpenGrep (review-gate L1)';
213
222
  console.log(` ✅ \x1b[32m${label.padEnd(28)}\x1b[0m: ${verOut}${note}`);
@@ -220,10 +229,21 @@ function doctor() {
220
229
 
221
230
  // 4. Python 3 (review-gate L2 fallback & test tooling)
222
231
  try {
223
- const pyOut = runCmd('python3 --version');
224
- console.log(` ✅ \x1b[32m${'Python 3 (L2 fallback)'.padEnd(28)}\x1b[0m: ${pyOut}`);
232
+ let pyOut = '';
233
+ try {
234
+ pyOut = runCmd('python3 --version');
235
+ } catch {
236
+ try {
237
+ pyOut = runCmd('python --version');
238
+ } catch {}
239
+ }
240
+ if (pyOut) {
241
+ console.log(` ✅ \x1b[32m${'Python 3 (L2 fallback)'.padEnd(28)}\x1b[0m: ${pyOut}`);
242
+ } else {
243
+ console.log(` ⚠️ \x1b[33m${'Python 3 (L2 fallback)'.padEnd(28)}\x1b[0m: 未检测到 python3/python (可选)`);
244
+ }
225
245
  } catch {
226
- console.log(` ⚠️ \x1b[33m${'Python 3 (L2 fallback)'.padEnd(28)}\x1b[0m: 未检测到 python3 (可选)`);
246
+ console.log(` ⚠️ \x1b[33m${'Python 3 (L2 fallback)'.padEnd(28)}\x1b[0m: 未检测到 python3/python (可选)`);
227
247
  }
228
248
 
229
249
  // 5. 核心 Unit CLI 完备性检查
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "reasonweave",
3
- "version": "1.4.5",
3
+ "version": "1.4.6",
4
4
  "description": "Agent Engineering Framework (AEF) & Disciplines Toolkit for multi-agent software engineering",
5
5
  "type": "module",
6
6
  "main": "bin/lab.mjs",
@@ -33,7 +33,7 @@
33
33
  "scripts": {
34
34
  "sync:consumers": "node scripts/sync-all-consumers.mjs",
35
35
  "test": "node bin/lab.mjs doctor && node units/handoffs/handoff.mjs status && node units/worktree/worktree.mjs --help && node units/review-gate/clean-runner.mjs --help && node units/orphan/bin/lab-orphan.mjs test-solver && node --test units/orphan/tests/*.test.mjs && node --test units/spec-guard/tests/*.test.mjs && node --test units/handoffs/tests/*.test.mjs && node --test units/review-gate/tests/*.test.mjs && node --test units/worktree/tests/*.test.mjs && node --test units/skills/tests/*.test.mjs && node --test tests/*.test.mjs",
36
- "postinstall": "chmod +x bin/lab.mjs units/handoffs/handoff.mjs units/worktree/worktree.mjs units/review-gate/clean-runner.mjs units/orphan/bin/lab-orphan.mjs units/spec-guard/bin/spec-guard.mjs units/skills/skills.mjs units/skills/bin/*.mjs units/adr/scripts/adr-init.sh units/preflight/templates/preflight.sh units/preflight/templates/check.sh units/review-gate/templates/scan.sh scripts/sync-all-consumers.mjs 2>/dev/null || true"
36
+ "postinstall": "node scripts/postinstall.mjs"
37
37
  },
38
38
  "files": [
39
39
  "bin/",
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import process from 'node:process';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = path.dirname(__filename);
9
+ const repoRoot = path.resolve(__dirname, '..');
10
+
11
+ // 在 POSIX 平台(macOS / Linux)为 CLI 脚本与模板自适应赋予执行权限(chmod +x)
12
+ // Windows 平台跳过(不依赖 POSIX 权限位),彻底根除 Windows cmd.exe 下 chmod 与 true 不可识别导致的安装中断
13
+ if (process.platform !== 'win32') {
14
+ const targets = [
15
+ 'bin/lab.mjs',
16
+ 'units/handoffs/handoff.mjs',
17
+ 'units/worktree/worktree.mjs',
18
+ 'units/review-gate/clean-runner.mjs',
19
+ 'units/orphan/bin/lab-orphan.mjs',
20
+ 'units/spec-guard/bin/spec-guard.mjs',
21
+ 'units/skills/skills.mjs',
22
+ 'units/skills/bin/task-brief.mjs',
23
+ 'units/skills/bin/review-package.mjs',
24
+ 'units/adr/scripts/adr-init.sh',
25
+ 'units/preflight/templates/preflight.sh',
26
+ 'units/preflight/templates/check.sh',
27
+ 'units/review-gate/templates/scan.sh',
28
+ 'scripts/sync-all-consumers.mjs',
29
+ 'scripts/postinstall.mjs',
30
+ ];
31
+
32
+ for (const rel of targets) {
33
+ const fullPath = path.join(repoRoot, rel);
34
+ try {
35
+ if (fs.existsSync(fullPath)) {
36
+ const stat = fs.statSync(fullPath);
37
+ fs.chmodSync(fullPath, stat.mode | 0o111);
38
+ }
39
+ } catch {}
40
+ }
41
+ }
42
+ process.exit(0);
@@ -6,12 +6,15 @@
6
6
 
7
7
  ---
8
8
 
9
- > **v2.41.2 补丁(2026-11-26 · 双盲审计出站卡片独立沙箱角色锚定与防自证拒识死锁加固)**:动因——用户反馈在跨客户端(WorkBuddy → ChatGPT)派发双盲审计工单时,ChatGPT 新窗口因全局安装了以“双盲审计”为触发词的派发技能,误以为人类在要求发起 `/audit`,激活派单逻辑后触发内部“严禁当前窗口自行审计”守卫,将自身锁死在派发官角色并拒接审计。经排查,系提示词缺乏独立沙箱声明与技能触发词语义撞车导致。实施彻底根治:
9
+ > **v2.41.2 补丁(2026-11-26 · 双盲审计出站卡片独立沙箱角色锚定与防自证拒识死锁加固 & 接入桩受阻话术契约对齐)**:动因——用户反馈在跨客户端(WorkBuddy → ChatGPT)派发双盲审计工单时,ChatGPT 新窗口因全局安装了以“双盲审计”为触发词的派发技能,误以为人类在要求发起 `/audit`,激活派单逻辑后触发内部“严禁当前窗口自行审计”守卫,将自身锁死在派发官角色并拒接审计;同时消费方反馈接入桩在执行方受阻时误导普通 `impl` 运行 `baton reject` 导致被系统越界拦截。经排查,实施彻底根治:
10
10
  > 1. **出站提示词双盲审计角色锚定(Audit Role Anchor Invariant)**:
11
11
  > - `cmdPrompt`(仓内及跨仓)在判定 `to_lane=audit` 时,自动在出站交接提示词卡片中注入显式角色锚定行:
12
12
  > `[角色锚定] 本会话即为独立审计沙箱,请直接作为审计执行员进行独立测试与核验(切勿触发派单逻辑)`(英文对应注入 `[Role Anchor]`);
13
13
  > - 接收端 Agent(ChatGPT / Claude / Cursor 等)读取提示词瞬间强行覆写系统上下文,消除角色认知模糊,阻断模型误召回全局派单技能。
14
- > 2. **自主双盲审计分诊协议边界加固(Dispatcher vs Verifier Boundary)**:
14
+ > 2. **接入桩入站退回契约与话术对齐(Inbound Bailout Contract Alignment)**:
15
+ > - 接入桩清晰界定“审计方安全下车驳回”与“普通执行方受阻登记回执”;
16
+ > - 纠正接入桩将普通执行方受阻误写为 `baton reject` 的瑕疵,对齐 `reject` 专属于发起方与审计方的物理门禁约束,普通执行方受阻统一通过登记受阻回执交由发起方协调推进。
17
+ > 3. **自主双盲审计分诊协议边界加固(Dispatcher vs Verifier Boundary)**:
15
18
  > - 在 `AGENT-GUIDE.md` 明确划定 `自主双盲审计分诊协议` 仅限发起方(`from_lane`)交割时触发;
16
19
  > - 明确禁止接收方(`to_lane=audit`)以“当前窗口不能自行审计”为借口推诿拒单(该窗口即为合法独立审计沙箱),强制进入入站实测工作流。
17
20
  > 3. **全套单测与事实源同步对齐**:更新用例 30 断言 `to_lane=audit` 时必须包含角色锚定行;全仓文档与门禁对齐。
@@ -1895,7 +1895,7 @@ function cmdReject(args) {
1895
1895
  isFromLane = fromLanes.includes(cur);
1896
1896
  isAuditor = (cur === toLaneRaw && toLaneRaw === 'audit');
1897
1897
  if (!isFromLane && !isAuditor) {
1898
- console.error(`❌ 越界驳回:当前执行身份 lane=${cur} 既非发起方 from_lane=${fromLaneRaw},亦非审计方 to_lane=${toLaneRaw}。驳回仅允许由发起方或审计方执行。`);
1898
+ console.error(`❌ 越界驳回:当前执行身份 lane=${cur} 既非发起方 from_lane=${fromLaneRaw},亦非审计方 to_lane=${toLaneRaw}。驳回仅允许由发起方或审计方执行(普通执行方受阻请通过 baton receipt 登记受阻回执交由发起方协调)。`);
1899
1899
  process.exit(1);
1900
1900
  }
1901
1901
  } else {
@@ -3215,7 +3215,7 @@ const STUB_BODY_ZH = `### Agent Baton (Handoff) 接入桩(轻量韧性版 ·
3215
3215
  2. **读工单**:运行 \`baton show <id>\`,根据验收判据改动本 lane 范围代码并实测。
3216
3216
  3. **交付或退回(实测为唯一准绳)**:
3217
3217
  - **实测通过**:照抄 \`$(lab path handoffs)/RESPONSE-TEMPLATE.md\` 骨架 → 运行 \`baton receipt <id> -n "<正文>" --deliver --as <本方 lane> --evidence-paths "<路径>"\`(审计工单附 \`--audit-nonce "<nonce>"\` 或同工作区授权下使用 \`--auto-nonce\` 自动绑定最新令牌;红队用例严格遵循 NO_DISPATCH / NO_COMPLETE / COMPLETE 三态标准)。
3218
- - **实测未过(NO-GO/受阻)**:享有安全下车通道,直接运行 \`baton reject <id> -n "<理由/缺失条件>" --as <本方 lane>\` 退回整改。
3218
+ - **实测未过(NO-GO/受阻)**:审计方享有安全下车通道,运行 \`baton reject <id> -n "<理由/差异在哪>" --as audit\` 退回整改;普通执行方若受阻/缺失条件,登记受阻回执 \`baton receipt <id> -n "<缺失条件/受阻理由>" --evidence-note "<说明>" --as <本方 lane>\` 由发起方核实并处理。
3219
3219
  4. **收尾自检**:运行 \`baton check [id]\`(若有数据漂移可加 \`--fix\` 自动修复)。
3220
3220
  5. **入站回复收尾(简洁单行裁决 · 严禁角色漂移)**:接收方必须严格保持本方执行/审计角色,严禁切换为发起方角色;**严禁反向输出 \`## 交接提示词\` 卡片或调用 \`baton close\` 越权闭环**;最终回复人类的最末尾仅输出单行纯文本(无需标题,无需代码块,严禁多行出站卡片):
3221
3221
  - 审计驳回:\`审计完成,裁决 NO-GO(工单已退回<发起方角色>进入 Round <N>)\`
@@ -2,6 +2,11 @@
2
2
 
3
3
  ## [0.1.0] - 2026-11-23
4
4
 
5
+ ### 修复 (Fixed)
6
+ - **Windows 平台 CLI 入口静默退出 0 缺陷**:
7
+ - 修复 `skills.mjs`、`task-brief.mjs` 与 `review-package.mjs` 中使用 `new URL(import.meta.url).pathname` 与 `process.argv[1]` 比对时,因 Windows 盘符带有前导斜杠 `/C:/...` 导致路径比对恒为 `false` 的问题;
8
+ - 统一替换为标准跨平台 API `fileURLToPath(import.meta.url)`,彻底解决 Windows 环境下 `lab skills list` / `lab skills check` 无输出静默退出的阻断性问题。
9
+
5
10
  ### 新增 (Added)
6
11
  - **初始版本建立**:基于 ADR-0015 架构决策,正式立项 `units/skills` 微观工程原子技能库与分发引擎;
7
12
  - **官方原子技能目录 (`catalog/`)**:
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
4
5
  import { execFileSync } from 'node:child_process';
5
6
 
6
7
  function printUsage() {
@@ -94,6 +95,6 @@ export function run(args = process.argv.slice(2)) {
94
95
  }
95
96
  }
96
97
 
97
- if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(new URL(import.meta.url).pathname)) {
98
+ if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))) {
98
99
  run();
99
100
  }
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
4
5
 
5
6
  function printUsage() {
6
7
  console.error('用法: task-brief <plan_file> <task_id> [outfile]');
@@ -97,6 +98,6 @@ export function run(args = process.argv.slice(2)) {
97
98
  console.log(outPath);
98
99
  }
99
100
 
100
- if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(new URL(import.meta.url).pathname)) {
101
+ if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))) {
101
102
  run();
102
103
  }
@@ -176,6 +176,6 @@ function run(args = process.argv.slice(2)) {
176
176
  process.exit(1);
177
177
  }
178
178
 
179
- if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(new URL(import.meta.url).pathname)) {
179
+ if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(__filename)) {
180
180
  run();
181
181
  }
@@ -6,6 +6,15 @@
6
6
  - **CLI 版本号与帮助 Banner 动态对齐**:
7
7
  - `spec-guard` 帮助 banner 移除硬编码 `v2.0.0`,改为动态读取 `VERSION.md` 事实源;
8
8
  - 显式接线 `--version` / `-v` / `version` 命令行选项,避免下发 `--version` 时报错 `未知命令: --version` 且以 exit 1 退出。
9
+ - **ADR 状态 Markdown 粗体冒号解析与格式清理**:
10
+ - 修复 `**Status:** Accepted` / `**Status**: Accepted` 因冒号处于 Markdown 粗体内部被误截断为 `** Accepted` 进而导致全景表降级为 `Draft` 的解析缺陷;
11
+ - 提取后统一剔除多余 Markdown 格式符,全景表如实展示 `[Accepted]` / `[Proposed]` 等真实决策状态。
12
+ - **零不变量覆盖率空集假绿修复**:
13
+ - 修复当 ADR 未声明任何架构不变量(`totalInvariantsCount === 0`)时,三元表达式分母为 0 误报 `100%` 覆盖率的缺陷;改为空规约输出 `0%`(终端输出 `N/A (未声明架构不变量: 0/0)` 与 `NO_INVARIANTS` 提示)。
14
+ - **实测性能数据自述提取精度优化**:
15
+ - 上下文排除:将历史环境说明(如剩余磁盘 `~100GB`)、模型规模背景估计(`30–70GB`)、调度设计约束(超时阈值 `10s`)、二进制体积预估(`~2MB`)等非测量声明精准过滤,避免误当实测性能主张索要机器凭据;
16
+ - 约数估算识别:精准区分波浪号约数(`~100GB`)与数值范围(`410~460ms`);
17
+ - 精细化忽略粒度:优化 `ignore_patterns`,不再整行误杀,确保同一行中被忽略的阈值不连带屏蔽同行的实测性能指标。
9
18
 
10
19
  ## [2.2.0] - 2026-11-14
11
20
 
@@ -393,8 +393,11 @@ export function parseAdrContent(content, filePath = '', options = {}) {
393
393
  }
394
394
  // 匹配状态行,如: - **状态(Status)**:Proposed / 🔒 Frozen
395
395
  if (!frontmatter || !frontmatter.status) {
396
- if (/^\s*[-*]?\s*\**状态.*?\**\s*[::]/i.test(line) || /^\s*[-*]?\s*\**Status\**\s*[::]/i.test(line)) {
397
- status = line.replace(/^.*?[::]\s*/, '').trim();
396
+ if (/^\s*[-*]?\s*\**\s*(?:状态|Status).*?[::]/i.test(line)) {
397
+ status = line
398
+ .replace(/^\s*[-*]?\s*\**\s*(?:状态|Status).*?[::]\s*/i, '')
399
+ .replace(/[\*_]/g, '')
400
+ .trim();
398
401
  if (frozenStates.length > 0) {
399
402
  isFrozen = frozenStates.some((fs) => fs.toLowerCase() === status.toLowerCase() || (fs === '🔒' && status.includes('🔒')));
400
403
  } else {
@@ -213,11 +213,10 @@ export function buildAndCheckMatrix(repoRoot, options = {}) {
213
213
  }
214
214
 
215
215
  const isZeroCoverage = parsedAdrs.length === 0;
216
- const coveragePercent = isZeroCoverage
216
+ const hasNoInvariants = totalInvariantsCount === 0;
217
+ const coveragePercent = isZeroCoverage || hasNoInvariants
217
218
  ? 0
218
- : (totalInvariantsCount > 0
219
- ? Math.round(((verifiedCount + sandboxedCount) / totalInvariantsCount) * 100)
220
- : 100);
219
+ : Math.round(((verifiedCount + sandboxedCount) / totalInvariantsCount) * 100);
221
220
 
222
221
  return {
223
222
  repoRoot,
@@ -233,7 +232,8 @@ export function buildAndCheckMatrix(repoRoot, options = {}) {
233
232
  orphanAssertions,
234
233
  unwiredInvariants,
235
234
  zeroCoverage: isZeroCoverage,
236
- isHealthy: !isZeroCoverage && driftCount === 0 && orphanAssertions.length === 0 && (!options.checkCallers || unwiredInvariants.length === 0),
235
+ hasNoInvariants,
236
+ isHealthy: !isZeroCoverage && !hasNoInvariants && driftCount === 0 && orphanAssertions.length === 0 && (!options.checkCallers || unwiredInvariants.length === 0),
237
237
  };
238
238
  }
239
239
 
@@ -246,10 +246,15 @@ export function formatConsoleReport(matrixResult) {
246
246
  lines.push('═'.repeat(65));
247
247
  lines.push(`📁 扫描代码文件: ${matrixResult.scannedFilesCount} 个 | ADR 规约: ${matrixResult.adrsCount} 份`);
248
248
  lines.push(`📊 总不变量: ${matrixResult.totalInvariantsCount} | 已验证: \x1b[32m${matrixResult.verifiedCount}\x1b[0m | 沙箱隔离: \x1b[36m${matrixResult.sandboxedCount}\x1b[0m | 进行中: \x1b[33m${matrixResult.inProgressCount}\x1b[0m | 漂移: \x1b[31m${matrixResult.driftCount}\x1b[0m`);
249
- lines.push(`📈 规约断言有效覆盖率: \x1b[1m${matrixResult.coveragePercent}%\x1b[0m\n`);
249
+ const coverageDisplay = matrixResult.hasNoInvariants
250
+ ? 'N/A (未声明架构不变量: 0/0)'
251
+ : `${matrixResult.coveragePercent}%`;
252
+ lines.push(`📈 规约断言有效覆盖率: \x1b[1m${coverageDisplay}\x1b[0m\n`);
250
253
 
251
254
  if (matrixResult.zeroCoverage || matrixResult.adrsCount === 0) {
252
255
  lines.push(`\x1b[31m⚠️ ZERO_COVERAGE: 未扫描到任何有效 ADR 规约文件!零覆盖不可伪装为通过。\x1b[0m\n`);
256
+ } else if (matrixResult.hasNoInvariants) {
257
+ lines.push(`\x1b[33m⚠️ NO_INVARIANTS: 扫描到 ${matrixResult.adrsCount} 份 ADR 但未提取到任何有效架构不变量,覆盖率不计为 100%。\x1b[0m\n`);
253
258
  }
254
259
 
255
260
  for (const rep of matrixResult.adrReports) {
@@ -512,6 +517,7 @@ export function buildFullTriadMatrix(repoRoot, options = {}) {
512
517
  });
513
518
 
514
519
  const isZeroCoverage = totalAdrs === 0;
520
+ const hasNoInvariants = assertionMatrix.totalInvariantsCount === 0;
515
521
  const isHealthy = !isZeroCoverage && assertionDriftCount === 0 && telemetryDriftCount === 0 && orphanDecisionCount === 0;
516
522
 
517
523
  return {
@@ -525,8 +531,9 @@ export function buildFullTriadMatrix(repoRoot, options = {}) {
525
531
  assertionDriftCount,
526
532
  telemetryDriftCount,
527
533
  orphanDecisionCount,
528
- coveragePercent: isZeroCoverage ? 0 : assertionMatrix.coveragePercent,
534
+ coveragePercent: (isZeroCoverage || hasNoInvariants) ? 0 : assertionMatrix.coveragePercent,
529
535
  zeroCoverage: isZeroCoverage,
536
+ hasNoInvariants,
530
537
  isHealthy,
531
538
  };
532
539
  }
@@ -555,7 +562,10 @@ export function formatTriadHeatmap(triadResult) {
555
562
  lines.push('─'.repeat(96));
556
563
 
557
564
  for (const row of triadResult.triadRows) {
558
- const frozenTag = row.isFrozen ? '[🔒Frozen]' : '[Draft]';
565
+ const displayStatus = row.status || (row.isFrozen ? 'Frozen' : 'Draft');
566
+ const frozenTag = row.isFrozen
567
+ ? (displayStatus.includes('🔒') ? `[${displayStatus}]` : `[🔒${displayStatus}]`)
568
+ : `[${displayStatus}]`;
559
569
  const statusCol = frozenTag.padEnd(10);
560
570
  const adrCol = row.adrId.padEnd(10);
561
571
  const assCol = row.assertionSummary.padEnd(18);
@@ -577,6 +587,8 @@ export function formatTriadHeatmap(triadResult) {
577
587
  lines.push('═'.repeat(96));
578
588
  if (triadResult.totalAdrs === 0 || triadResult.zeroCoverage) {
579
589
  lines.push('\x1b[31m❌ [ZERO_COVERAGE] 门禁阻断:未发现任何有效 ADR 规约!零覆盖不可伪装为健康。\x1b[0m\n');
590
+ } else if (triadResult.hasNoInvariants) {
591
+ lines.push('\x1b[33m⚠️ [NO_INVARIANTS] 提示:ADR 规约未声明架构不变量(断言覆盖率 N/A)。\x1b[0m\n');
580
592
  } else if (triadResult.isHealthy) {
581
593
  lines.push('\x1b[32m✅ 全景三元对账检查通过!无断言漂移、无实测数据伪造、无孤儿冻结决策。\x1b[0m\n');
582
594
  } else {
@@ -22,7 +22,17 @@ export const QUANTITATIVE_METRICS_REGEX = /(?:\b\d+(?:\.\d+)?\s*(?:ms|MB|GB|FPS|
22
22
  /**
23
23
  * 实测基准上下文线索关键字(避免将背景设备参数如 4GB RAM 或章节序号误判为实测基准声明)
24
24
  */
25
- const MEASUREMENT_CONTEXT_REGEX = /(?:实测|基准|均值|P95|P99|INT8|冷启|推理|拟合斜率|准确率|Top-?1|ECE|Latency|Throughput|Tokens?\/s|FPS|耗时|执行时间|软拷贝|基线|Benchmark|Spike|采样|常驻|阈值)/i;
25
+ const MEASUREMENT_CONTEXT_REGEX = /(?:实测|基准|均值|P95|P99|INT8|冷启|推理|拟合斜率|准确率|Top-?1|ECE|Latency|Throughput|Tokens?\/s|FPS|软拷贝|基线|Benchmark|Spike|采样|常驻)/i;
26
+
27
+ /**
28
+ * 非实测声明关键字(背景规模估计、环境剩余空间、约数预估等)
29
+ */
30
+ const NON_MEASUREMENT_REGEX = /(?:预估|估算|估计|空间|剩余|磁盘|背景|约在|下载规模|大约|approx|\bestimate\b)/i;
31
+
32
+ /**
33
+ * 强实测断言关键字(若行内明确标明实测/Benchmark,即使含阈值也不整行丢弃)
34
+ */
35
+ const STRONG_MEASUREMENT_REGEX = /(?:实测|基准数据|Benchmark|压测结果|测试数据|真实测量)/i;
26
36
 
27
37
  /**
28
38
  * 实测基准章节标题正则
@@ -107,13 +117,20 @@ export function extractTelemetryMetrics(content, options = {}) {
107
117
  continue;
108
118
  }
109
119
 
110
- // 2. 检查整行是否匹配 ignore_patterns(约定阈值等)
120
+ // 若该行属于设计约束、背景说明或估计预估,且未附带强实测声明,则不作为实测性能指标提取
121
+ if (NON_MEASUREMENT_REGEX.test(line) && !STRONG_MEASUREMENT_REGEX.test(line)) {
122
+ continue;
123
+ }
124
+
125
+ // 2. 检查整行是否被行级正则模式显式忽略(如 ^...$)
111
126
  if (compiledIgnorePatterns.length > 0) {
112
- const lineIgnored = compiledIgnorePatterns.some((p) => {
113
- if (p instanceof RegExp) return p.test(line);
114
- return line.includes(p);
127
+ const wholeLineIgnored = compiledIgnorePatterns.some((p) => {
128
+ if (p instanceof RegExp && p.source.startsWith('^')) {
129
+ return p.test(line);
130
+ }
131
+ return p === line.trim();
115
132
  });
116
- if (lineIgnored) {
133
+ if (wholeLineIgnored) {
117
134
  continue;
118
135
  }
119
136
  }
@@ -123,11 +140,27 @@ export function extractTelemetryMetrics(content, options = {}) {
123
140
  while ((match = QUANTITATIVE_METRICS_REGEX.exec(line)) !== null) {
124
141
  const matchedText = match[0].trim();
125
142
 
126
- // 3. 检查具体提取出的 metric 是否命中 ignore_patterns
143
+ // 约数/估算数字过滤(如 ~100GB, ≈2MB,注意区别于 410~460ms 的数值范围)且当前行无强实测声明
144
+ const prevChar = match.index > 0 ? line[match.index - 1] : '';
145
+ const isApproxPrefix = (prevChar === '~' || prevChar === '≈') && (match.index < 2 || !/\d/.test(line[match.index - 2]));
146
+ if (isApproxPrefix && !STRONG_MEASUREMENT_REGEX.test(line)) {
147
+ continue;
148
+ }
149
+
150
+ // 3. 检查具体提取出的 metric 是否命中 ignore_patterns(单指标精细化过滤,不误杀同行动态指标)
127
151
  if (compiledIgnorePatterns.length > 0) {
128
152
  const metricIgnored = compiledIgnorePatterns.some((p) => {
129
- if (p instanceof RegExp) return p.test(matchedText);
130
- return matchedText === p;
153
+ if (p instanceof RegExp) {
154
+ return p.test(matchedText);
155
+ }
156
+ const strPat = String(p).trim();
157
+ if (matchedText === strPat) return true;
158
+ if (line.includes(strPat)) {
159
+ if (strPat.includes(matchedText) || matchedText.includes(strPat)) {
160
+ return true;
161
+ }
162
+ }
163
+ return false;
131
164
  });
132
165
  if (metricIgnored) {
133
166
  continue;
@@ -29,6 +29,7 @@ import {
29
29
  import {
30
30
  buildAndCheckMatrix,
31
31
  buildFullTriadMatrix,
32
+ formatTriadHeatmap,
32
33
  generateAdrAuditReport,
33
34
  } from '../core/matrix-checker.mjs';
34
35
 
@@ -581,6 +582,49 @@ scope:
581
582
  assert.equal(parsed.hasImplementationStatus, true, '## 验证 应被识别为 implementation 节');
582
583
  });
583
584
 
585
+ it('支持 **Status:** Accepted、**Status**: Accepted 及各种中英文状态行格式,剥离 Markdown 符号', () => {
586
+ const rawContent1 = `# ADR-008: 安装预检\n\n**Status:** Accepted\n\n## 2. Decision\n决策内容`;
587
+ const parsed1 = parseAdrContent(rawContent1, 'ADR-008.md');
588
+ assert.equal(parsed1.status, 'Accepted', '加粗内含冒号 **Status:** Accepted 应准确解析为 Accepted');
589
+
590
+ const rawContent2 = `# ADR-009: 调度约束\n\n- **Status**: Proposed\n\n## 2. Decision\n决策内容`;
591
+ const parsed2 = parseAdrContent(rawContent2, 'ADR-009.md');
592
+ assert.equal(parsed2.status, 'Proposed');
593
+
594
+ const rawContent3 = `# ADR-010: 历史决策\n\nStatus: Rejected\n\n## 2. Decision\n决策内容`;
595
+ const parsed3 = parseAdrContent(rawContent3, 'ADR-010.md');
596
+ assert.equal(parsed3.status, 'Rejected');
597
+ });
598
+
599
+ it('有 ADR 但总不变量为 0 时,覆盖率严禁误报为 100%', () => {
600
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'spec-guard-no-inv-'));
601
+ try {
602
+ const adrDir = path.join(tmp, 'group', 'architecture', 'adr');
603
+ fs.mkdirSync(adrDir, { recursive: true });
604
+ fs.writeFileSync(
605
+ path.join(adrDir, 'ADR-001.md'),
606
+ '# ADR-001: 基础规约\n\n**Status:** Accepted\n\n## 2. Decision\n内容\n'
607
+ );
608
+ const matrix = buildAndCheckMatrix(tmp);
609
+ assert.equal(matrix.adrsCount, 1);
610
+ assert.equal(matrix.totalInvariantsCount, 0);
611
+ assert.equal(matrix.coveragePercent, 0, '总不变量为 0 时覆盖率必须为 0%,严禁返回 100%');
612
+ assert.equal(matrix.hasNoInvariants, true);
613
+
614
+ const triad = buildFullTriadMatrix(tmp);
615
+ assert.equal(triad.totalAdrs, 1);
616
+ assert.equal(triad.coveragePercent, 0);
617
+ assert.equal(triad.hasNoInvariants, true);
618
+ assert.equal(triad.triadRows[0].status, 'Accepted');
619
+
620
+ const heatmap = formatTriadHeatmap(triad);
621
+ assert.ok(heatmap.includes('[Accepted]'), '热力表应当真实展现 [Accepted] 而非 [Draft]');
622
+ assert.ok(heatmap.includes('[NO_INVARIANTS]'));
623
+ } finally {
624
+ fs.rmSync(tmp, { recursive: true, force: true });
625
+ }
626
+ });
627
+
584
628
  it('totalAdrs === 0 时必须报告 ZERO_COVERAGE,覆盖率严禁为 100%,strict 模式下 exit 1 阻断', () => {
585
629
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'spec-guard-zero-check-'));
586
630
  try {
@@ -43,6 +43,28 @@ describe('spec-guard v2.0: 实测数据自述凭据与机器信任根验签 (Tel
43
43
  assert.ok(metricStrings.includes('96.43%'));
44
44
  });
45
45
 
46
+ it('区分背景估算、环境描述与实测性能声明:避免误伤 ~100GB、30-70GB、~2MB 等非测量说明', () => {
47
+ const text = `
48
+ ## 3. Implementation Status
49
+ - 历史开发机 C 盘剩余空间 ~100GB,用于方案比较
50
+ - ComfyUI 模型权重下载规模估计 30–70GB
51
+ - 硬件体检工具二进制体积预估 ~2MB
52
+ `;
53
+ const metrics = extractTelemetryMetrics(text);
54
+ assert.equal(metrics.length, 0, '估算与环境描述严禁提取为实测声明');
55
+ });
56
+
57
+ it('同行混合设计阈值与实测指标时:忽略阈值不应误杀同行实测指标', () => {
58
+ const text = `
59
+ | 压测项 | 状态 | 实测基准数据 |
60
+ | 吞吐 | ✅ | 实测 Redmi 12C:均值 39.42ms,超时阈值 100ms |
61
+ `;
62
+ const metrics = extractTelemetryMetrics(text, { ignorePatterns: ['100ms'] });
63
+ const metricStrings = metrics.map((m) => m.metric);
64
+ assert.ok(metricStrings.includes('39.42ms'), '实测均值 39.42ms 必须正常提取');
65
+ assert.ok(!metricStrings.includes('100ms'), '被忽略的 100ms 不应提取');
66
+ });
67
+
46
68
  // [必红守护 1]: 格式伪造拦截 (手写性能数字却无 evidence 引用)
47
69
  it('格式伪造拦截:ADR 声称性能指标却缺少机器信任根凭据,必须判定自述漂移并违规熔断', () => {
48
70
  const fakeAdrContent = `