reasonweave 1.4.4 → 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.
@@ -17,9 +17,15 @@ set -uo pipefail
17
17
 
18
18
  # 非交互 hook 可能没把 ~/.local/bin 放进 PATH
19
19
  export PATH="$HOME/.local/bin:$PATH"
20
- OG="${OPENGREP_BIN:-$HOME/.local/bin/opengrep}"
21
- if ! [ -x "$OG" ] && ! command -v "$OG" >/dev/null 2>&1; then
22
- OG=$(command -v opengrep || true)
20
+ OG="${OPENGREP_BIN:-__AUTO__}"
21
+ if [ "$OG" = "__AUTO__" ]; then
22
+ if [ -x "$HOME/.local/bin/opengrep" ]; then
23
+ OG="$HOME/.local/bin/opengrep"
24
+ else
25
+ OG=$(command -v opengrep || true)
26
+ fi
27
+ elif [ -n "$OG" ] && { [ ! -x "$OG" ] && ! command -v "$OG" >/dev/null 2>&1; }; then
28
+ OG=""
23
29
  fi
24
30
 
25
31
  USE_RUFF_FALLBACK=0
@@ -48,22 +54,33 @@ SCAN_EXTS="${SCAN_EXTS:-py kt kts java rs ts tsx go xml gradle toml}"
48
54
  EXT_RE="\.(${SCAN_EXTS// /|})$"
49
55
 
50
56
  # 只扫本次提交真正要落库的暂存代码文件
51
- FILES=()
57
+ STAGED_FILES=()
52
58
  while IFS= read -r f; do
53
- [ -n "$f" ] && FILES+=("$f")
59
+ [ -n "$f" ] && STAGED_FILES+=("$f")
54
60
  done < <(git -C "$REPO_ROOT" diff --cached --name-only --diff-filter=ACM | grep -E "$EXT_RE" || true)
55
61
 
62
+ if [ ${#STAGED_FILES[@]} -eq 0 ]; then
63
+ exit 0
64
+ fi
65
+
66
+ # 从 Git Index 中将暂存内容安全还原至独立临时目录进行扫描,确保真实扫描暂存快照
67
+ STAGED_DIR=$(mktemp -d /tmp/og-staged-XXXXXX)
68
+ TMP=$(mktemp /tmp/og-precommit-XXXXXX.json)
69
+ trap 'rm -rf "$STAGED_DIR" "$TMP"' EXIT
70
+
56
71
  EXISTING=()
57
- for f in "${FILES[@]:-}"; do
58
- [ -f "$REPO_ROOT/$f" ] && EXISTING+=("$REPO_ROOT/$f")
72
+ for f in "${STAGED_FILES[@]}"; do
73
+ dest="$STAGED_DIR/$f"
74
+ mkdir -p "$(dirname "$dest")"
75
+ if git -C "$REPO_ROOT" show ":$f" > "$dest" 2>/dev/null; then
76
+ EXISTING+=("$dest")
77
+ fi
59
78
  done
79
+
60
80
  if [ ${#EXISTING[@]} -eq 0 ]; then
61
81
  exit 0
62
82
  fi
63
83
 
64
- TMP=$(mktemp /tmp/og-precommit-XXXXXX.json)
65
- trap 'rm -f "$TMP"' EXIT
66
-
67
84
  cd "$REPO_ROOT"
68
85
 
69
86
  # 规则集 / 排除项与 scan.sh 同语义(按需用环境变量覆盖)
@@ -79,13 +96,14 @@ EXCLUDE_RULES=(
79
96
  )
80
97
  EXCLUDES=$(printf -- '--exclude-rule %s ' ${EXCLUDE_RULES[@]+"${EXCLUDE_RULES[@]}"})
81
98
 
99
+ SCAN_EXIT=0
82
100
  if [ "$USE_RUFF_FALLBACK" = "1" ]; then
83
101
  echo "🔍 Ruff Bandit fallback gate: scanning ${#EXISTING[@]} staged file(s)..."
84
- "$RUFF" check --select S --output-format json "${EXISTING[@]}" > "$TMP" 2>/dev/null || true
102
+ "$RUFF" check --select S --output-format json "${EXISTING[@]}" > "$TMP" 2>/dev/null || SCAN_EXIT=$?
85
103
  else
86
104
  echo "🔍 OpenGrep gate: scanning ${#EXISTING[@]} staged file(s)..."
87
105
  "$OG" scan ${CONFIG_ARGS[@]+"${CONFIG_ARGS[@]}"} --disable-version-check --timeout 60 ${EXCLUDES} \
88
- --json --output "$TMP" "${EXISTING[@]}" >/dev/null 2>&1 || true
106
+ --json --output "$TMP" "${EXISTING[@]}" >/dev/null 2>&1 || SCAN_EXIT=$?
89
107
  fi
90
108
 
91
109
  PY=$(command -v python3 || command -v python || true)
@@ -94,37 +112,69 @@ if [ -z "$PY" ]; then
94
112
  exit 0
95
113
  fi
96
114
 
97
- "$PY" - "$TMP" "$BASELINE" "$REPO_ROOT" <<'PYEOF'
98
- import json, sys
115
+ "$PY" - "$TMP" "$BASELINE" "$STAGED_DIR" "$USE_RUFF_FALLBACK" "$SCAN_EXIT" <<'PYEOF'
116
+ import json, sys, os
117
+
118
+ tmp_path = sys.argv[1]
119
+ base_path = sys.argv[2]
120
+ staged_dir = os.path.realpath(sys.argv[3]).rstrip("/") + "/"
121
+ is_ruff = sys.argv[4] == "1"
122
+ scan_exit = int(sys.argv[5])
99
123
 
100
- def load(p):
124
+ def load(p, is_ruff_output=False):
101
125
  try:
102
- return json.load(open(p)).get("results", [])
103
- except Exception:
104
- return []
126
+ with open(p, "r", encoding="utf-8") as f:
127
+ data = json.load(f)
128
+ except Exception as e:
129
+ print(f"❌ 门禁评估失败: 无法解析扫描报告 {p}: {e}", file=sys.stderr)
130
+ sys.exit(2)
131
+
132
+ if isinstance(data, list):
133
+ if is_ruff_output:
134
+ return [
135
+ {
136
+ "check_id": item.get("code") or item.get("check_id"),
137
+ "path": item.get("filename") or item.get("path"),
138
+ "start": {"line": (item.get("location") or {}).get("row")},
139
+ "extra": {"severity": "WARNING", "message": item.get("message", "")}
140
+ }
141
+ for item in data
142
+ if isinstance(item, dict)
143
+ ]
144
+ return data
145
+ elif isinstance(data, dict):
146
+ return data.get("results", [])
147
+ return []
148
+
149
+ cur = load(tmp_path, is_ruff_output=is_ruff)
150
+ base = load(base_path, is_ruff_output=False)
105
151
 
106
- # opengrep 对绝对路径入参会回写绝对 path,而基线多为相对根路径 → 归一化为相对仓库根再比对
107
- REPO = sys.argv[3].rstrip("/") + "/"
108
152
  def norm(p):
109
- p = str(p)
110
- if p.startswith(REPO):
111
- p = p[len(REPO):]
112
- return p
113
-
114
- cur = load(sys.argv[1])
115
- base = load(sys.argv[2])
116
- base_keys = {(r["check_id"], norm(r["path"])) for r in base if "check_id" in r and "path" in r}
117
- new = [r for r in cur if ("check_id" in r and "path" in r)
118
- and (r["check_id"], norm(r["path"])) not in base_keys]
153
+ if not p:
154
+ return ""
155
+ p_real = os.path.realpath(str(p))
156
+ if p_real.startswith(staged_dir):
157
+ return p_real[len(staged_dir):]
158
+ p_str = str(p)
159
+ if p_str.startswith(sys.argv[3].rstrip("/") + "/"):
160
+ return p_str[len(sys.argv[3].rstrip("/") + "/"):]
161
+ return p_str
162
+
163
+ base_keys = {(r.get("check_id"), norm(r.get("path"))) for r in base if "check_id" in r and "path" in r}
164
+ new = [
165
+ r for r in cur
166
+ if ("check_id" in r and "path" in r) and (r.get("check_id"), norm(r.get("path"))) not in base_keys
167
+ ]
119
168
 
120
169
  if new:
121
- print("❌ OpenGrep gate: %d new finding(s) beyond accepted baseline:" % len(new))
170
+ gate_name = "Ruff Bandit" if is_ruff else "OpenGrep"
171
+ print(f"❌ {gate_name} gate: {len(new)} new finding(s) beyond accepted baseline:")
122
172
  for r in new:
123
173
  e = r.get("extra", {})
124
174
  line = r.get("start", {}).get("line", "?")
125
- print(" - [%s] %s:%s (%s)" % (r["check_id"], norm(r["path"]), line, e.get("severity", "?")))
126
- print("\n Fix the issue, or re-baseline: RULESETS=... bash scan.sh %s" % sys.argv[2])
175
+ print(f" - [{r.get('check_id')}] {norm(r.get('path'))}:{line} ({e.get('severity', '?')})")
176
+ print(f"\n Fix the issue, or re-baseline: RULESETS=... bash scan.sh {sys.argv[2]}")
127
177
  sys.exit(1)
128
178
 
129
- print("✅ OpenGrep gate passed (no new findings vs %d accepted baseline)." % len(base))
179
+ print(f"✅ Static-analysis gate passed (no new findings vs {len(base)} accepted baseline).")
130
180
  PYEOF
@@ -136,8 +136,22 @@ else
136
136
  python3 -c '
137
137
  import sys, json
138
138
  findings = []
139
- try: findings = json.loads(sys.argv[1]) if sys.argv[1] else []
140
- except: pass
139
+ try:
140
+ raw = json.loads(sys.argv[1]) if sys.argv[1] else []
141
+ if isinstance(raw, list):
142
+ for f in raw:
143
+ if isinstance(f, dict):
144
+ loc = f.get("location") or {}
145
+ end_loc = f.get("end_location") or {}
146
+ findings.append({
147
+ "check_id": f.get("code"),
148
+ "path": f.get("filename"),
149
+ "start": { "line": loc.get("row"), "col": loc.get("column") },
150
+ "end": { "line": end_loc.get("row"), "col": end_loc.get("column") },
151
+ "extra": { "message": f.get("message", ""), "severity": "WARNING" }
152
+ })
153
+ except Exception as e:
154
+ sys.stderr.write(f"Ruff JSON parse warning: {e}\n")
141
155
  payload = {
142
156
  "engine": "fallback-ruff-bandit",
143
157
  "fallback": True,
@@ -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 {
@@ -176,6 +176,14 @@ export function runMutationTest(options = {}) {
176
176
  throw new Error(`Mutation runner target file not found: ${targetFile}`);
177
177
  }
178
178
 
179
+ // 严格安全边界检查:确保 targetFile 位于 repoRoot 内部
180
+ const realRepoRoot = fs.existsSync(repoRoot) ? fs.realpathSync(repoRoot) : path.resolve(repoRoot);
181
+ const realTargetFile = fs.existsSync(targetFile) ? fs.realpathSync(targetFile) : path.resolve(targetFile);
182
+ const relativeTarget = path.relative(realRepoRoot, realTargetFile);
183
+ if (relativeTarget.startsWith('..') || path.isAbsolute(relativeTarget)) {
184
+ throw new Error(`Mutation runner target file must be located inside repoRoot: ${targetFile}`);
185
+ }
186
+
179
187
  const cleanEnv = { ...process.env };
180
188
  delete cleanEnv.NODE_TEST_CONTEXT;
181
189
 
@@ -207,42 +215,62 @@ export function runMutationTest(options = {}) {
207
215
  }
208
216
 
209
217
  // 3. 逐个注入变异并验证测试套件敏感度
218
+ // 安全防护:在进程退出或意外中断时注册保护兜底
210
219
  let killedCount = 0;
211
220
  const survivedMutants = [];
212
221
 
213
- for (const mutant of mutants) {
214
- const mutatedContent =
215
- originalContent.slice(0, mutant.index) +
216
- mutant.replacement +
217
- originalContent.slice(mutant.index + mutant.original.length);
218
-
222
+ const cleanupHandler = () => {
219
223
  try {
220
- fs.writeFileSync(targetFile, mutatedContent, 'utf8');
224
+ if (fs.existsSync(targetFile)) {
225
+ fs.writeFileSync(targetFile, originalContent, 'utf8');
226
+ }
227
+ } catch {}
228
+ };
229
+
230
+ process.once('SIGINT', cleanupHandler);
231
+ process.once('SIGTERM', cleanupHandler);
232
+ process.once('exit', cleanupHandler);
233
+
234
+ try {
235
+ for (const mutant of mutants) {
236
+ const mutatedContent =
237
+ originalContent.slice(0, mutant.index) +
238
+ mutant.replacement +
239
+ originalContent.slice(mutant.index + mutant.original.length);
221
240
 
222
- let testPassedWithMutant = false;
223
241
  try {
224
- execSync(testCmd, { cwd: repoRoot, stdio: 'pipe', encoding: 'utf8', env: cleanEnv });
225
- testPassedWithMutant = true;
226
- } catch {
227
- // 测试报错 = 变异被消灭 (Killed)
228
- testPassedWithMutant = false;
229
- }
242
+ fs.writeFileSync(targetFile, mutatedContent, 'utf8');
230
243
 
231
- if (testPassedWithMutant) {
232
- // 变异体存活 = 假测试!
233
- survivedMutants.push(mutant);
234
- } else {
235
- killedCount++;
244
+ let testPassedWithMutant = false;
245
+ try {
246
+ execSync(testCmd, { cwd: repoRoot, stdio: 'pipe', encoding: 'utf8', env: cleanEnv });
247
+ testPassedWithMutant = true;
248
+ } catch {
249
+ // 测试报错 = 变异被消灭 (Killed)
250
+ testPassedWithMutant = false;
251
+ }
252
+
253
+ if (testPassedWithMutant) {
254
+ // 变异体存活 = 假测试!
255
+ survivedMutants.push(mutant);
256
+ } else {
257
+ killedCount++;
258
+ }
259
+ } finally {
260
+ // 必须立刻恢复原文件,保证工作区绝对干净零污染!
261
+ fs.writeFileSync(targetFile, originalContent, 'utf8');
236
262
  }
237
- } finally {
238
- // 必须立刻恢复原文件,保证工作区绝对干净零污染!
239
- fs.writeFileSync(targetFile, originalContent, 'utf8');
240
- }
241
263
 
242
- // 发现任何一个存活变异体,立即熔断报告
243
- if (survivedMutants.length > 0) {
244
- break;
264
+ // 发现任何一个存活变异体,立即熔断报告
265
+ if (survivedMutants.length > 0) {
266
+ break;
267
+ }
245
268
  }
269
+ } finally {
270
+ process.removeListener('SIGINT', cleanupHandler);
271
+ process.removeListener('SIGTERM', cleanupHandler);
272
+ process.removeListener('exit', cleanupHandler);
273
+ cleanupHandler();
246
274
  }
247
275
 
248
276
  if (survivedMutants.length > 0) {
@@ -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
 
@@ -478,6 +479,25 @@ assert.equal(ep, "/api/v1/device/interlock");
478
479
  }
479
480
  });
480
481
 
482
+ it('runMutationTest 边界防御:严禁变异 repoRoot 外部的文件', () => {
483
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'spec-guard-sec-'));
484
+ const outsideDir = fs.mkdtempSync(path.join(os.tmpdir(), 'spec-guard-out-'));
485
+ try {
486
+ const outsideFile = path.join(outsideDir, 'outside.mjs');
487
+ fs.writeFileSync(outsideFile, 'export const x = 1;');
488
+ assert.throws(() => {
489
+ runMutationTest({
490
+ repoRoot: tmpDir,
491
+ targetFile: outsideFile,
492
+ testCmd: 'node -e "process.exit(0)"',
493
+ });
494
+ }, /must be located inside repoRoot/);
495
+ } finally {
496
+ fs.rmSync(tmpDir, { recursive: true, force: true });
497
+ fs.rmSync(outsideDir, { recursive: true, force: true });
498
+ }
499
+ });
500
+
481
501
  it('orphan 单元联动测试:符号引用分类与倒排生产调用者检索', () => {
482
502
  assert.equal(Classifier.isTestPath('src/test/java/Test.kt'), true);
483
503
  assert.equal(Classifier.isTestPath('src/main/java/Main.kt'), false);
@@ -562,6 +582,49 @@ scope:
562
582
  assert.equal(parsed.hasImplementationStatus, true, '## 验证 应被识别为 implementation 节');
563
583
  });
564
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
+
565
628
  it('totalAdrs === 0 时必须报告 ZERO_COVERAGE,覆盖率严禁为 100%,strict 模式下 exit 1 阻断', () => {
566
629
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'spec-guard-zero-check-'));
567
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 = `