@boyingliu01/xp-gate 0.20.0 → 0.20.1

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 (34) hide show
  1. package/adapters/gate-8.sh +115 -73
  2. package/adapters/powershell.sh +60 -5
  3. package/adapters/python.sh +38 -4
  4. package/build-integrity/__tests__/import-resolver.test.ts +59 -0
  5. package/build-integrity/gate-10.ts +17 -2
  6. package/gate-8.sh +115 -73
  7. package/hooks/gate-8.sh +115 -73
  8. package/hooks/pre-commit +130 -27
  9. package/lib/mattpocock-license-verdict.json +1 -1
  10. package/mock-policy/AGENTS.md +4 -4
  11. package/mutation/AGENTS.md +4 -4
  12. package/package.json +2 -2
  13. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  14. package/plugins/claude-code/skills/delphi-review/AGENTS.md +4 -4
  15. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +4 -4
  16. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +4 -4
  17. package/plugins/dsh/package.json +1 -1
  18. package/plugins/dsh/skills/delphi-review/AGENTS.md +4 -4
  19. package/plugins/dsh/skills/sprint-flow/AGENTS.md +4 -4
  20. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +4 -4
  21. package/plugins/opencode/package.json +1 -1
  22. package/plugins/opencode/skills/delphi-review/AGENTS.md +4 -4
  23. package/plugins/opencode/skills/sprint-flow/AGENTS.md +4 -4
  24. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +4 -4
  25. package/plugins/qoder/plugin.json +1 -1
  26. package/plugins/qoder/skills/delphi-review/AGENTS.md +4 -4
  27. package/plugins/qoder/skills/sprint-flow/AGENTS.md +4 -4
  28. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +4 -4
  29. package/principles/AGENTS.md +4 -4
  30. package/principles/boy-scout.ts +36 -6
  31. package/scripts/sync-package-content.js +13 -6
  32. package/skills/delphi-review/AGENTS.md +4 -4
  33. package/skills/sprint-flow/AGENTS.md +4 -4
  34. package/skills/test-specification-alignment/AGENTS.md +4 -4
@@ -1,11 +1,14 @@
1
1
  # ============================================================================
2
- # GATE 8: Secret Scanning (gitleaks)
3
- # Detects secrets (API keys, passwords, tokens) in staged files
4
- # Tool: gitleaks -- https://github.com/gitleaks/gitleaks
2
+ # GATE 8: Secret Scanning (gitleaks + detect-secrets)
3
+ # Detects secrets (API keys, passwords, tokens) in staged files.
4
+ # Tools:
5
+ # gitleaks -- primary, fail-closed (missing or non-0/1 exit => BLOCK, #499)
6
+ # detect-secrets -- secondary, baseline-diff: only blocks on secrets NOT in
7
+ # .secrets.baseline; silently does nothing when unavailable
5
8
  # ============================================================================
6
9
 
7
10
  2>&1 echo ""
8
- 2>&1 echo "→ Gate 8: Secret scanning (gitleaks)..."
11
+ 2>&1 echo "→ Gate 8: Secret scanning (gitleaks + detect-secrets)..."
9
12
  GATE_8_START=$(gate_start_ms)
10
13
 
11
14
  # Gitleaks availability check
@@ -16,85 +19,124 @@ elif [ -f "$HOME/.local/bin/gitleaks" ]; then
16
19
  GITLEAKS_CMD="$HOME/.local/bin/gitleaks"
17
20
  fi
18
21
 
19
- if [ -n "$GITLEAKS_CMD" ]; then
20
- GITLEAKS_CONFIG=""
21
- if [ -f ".gitleaks.toml" ]; then
22
- # gitleaks is a native binary and may not understand MSYS paths, so pass an
23
- # absolute path in the host's own format when we can derive one (#449).
24
- if command -v cygpath >/dev/null 2>&1; then
25
- GITLEAKS_CONFIG="--config=$(cygpath -w "$(pwd)/.gitleaks.toml")"
26
- else
27
- GITLEAKS_CONFIG="--config=$(pwd)/.gitleaks.toml"
28
- fi
22
+ if [ -z "$GITLEAKS_CMD" ]; then
23
+ # fail-closed (#499): an uninstalled gitleaks used to SKIP the gate, so any
24
+ # contributor without it shipped commits with zero secret protection and no
25
+ # signal. A security gate that cannot run must not report success.
26
+ echo " ❌ BLOCKED - gitleaks not installed (fail-closed, #499)."
27
+ echo " Secret scanning is mandatory before commit. Install gitleaks then retry:"
28
+ echo " macOS: brew install gitleaks"
29
+ echo " Windows: winget install gitleaks"
30
+ echo " Linux: scripts/install-gitleaks.sh (or https://github.com/gitleaks/gitleaks)"
31
+ exit 1
32
+ fi
33
+
34
+ GITLEAKS_CONFIG=""
35
+ if [ -f ".gitleaks.toml" ]; then
36
+ # gitleaks is a native binary and may not understand MSYS paths, so pass an
37
+ # absolute path in the host's own format when we can derive one (#449).
38
+ if command -v cygpath >/dev/null 2>&1; then
39
+ GITLEAKS_CONFIG="--config=$(cygpath -w "$(pwd)/.gitleaks.toml")"
40
+ else
41
+ GITLEAKS_CONFIG="--config=$(pwd)/.gitleaks.toml"
29
42
  fi
43
+ fi
30
44
 
31
- # Scan the INDEX, not history. gitleaks 8.x `git --pre-commit` walks committed
32
- # revisions and reports "0 commits scanned" on a pre-commit run -- so a staged
33
- # secret was never seen and Gate 8 always passed. `git --staged` scans
34
- # `git diff --cached`, which is exactly the pre-commit payload (#449).
35
- GITLEAKS_REPORT="${TMPDIR:-/tmp}/gitleaks-report.json"
36
- rm -f "$GITLEAKS_REPORT"
37
- GITLEAKS_OUTPUT=$($GITLEAKS_CMD git --staged --redact --no-banner $GITLEAKS_CONFIG --report-format=json --report-path="$GITLEAKS_REPORT" 2>&1)
38
- GITLEAKS_EXIT=$?
45
+ # Scan the INDEX, not history. gitleaks 8.x `git --pre-commit` walks committed
46
+ # revisions and reports "0 commits scanned" on a pre-commit run -- so a staged
47
+ # secret was never seen and Gate 8 always passed. `git --staged` scans
48
+ # `git diff --cached`, which is exactly the pre-commit payload (#449).
49
+ GITLEAKS_REPORT="${TMPDIR:-/tmp}/gitleaks-report.json"
50
+ rm -f "$GITLEAKS_REPORT"
51
+ GITLEAKS_OUTPUT=$($GITLEAKS_CMD git --staged --redact --no-banner $GITLEAKS_CONFIG --report-format=json --report-path="$GITLEAKS_REPORT" 2>&1)
52
+ GITLEAKS_EXIT=$?
39
53
 
40
- if [ "$GITLEAKS_EXIT" -eq 0 ]; then
41
- # Decide SKIP from the REPORT ARTIFACT, not from log wording. Parsing stdout
42
- # meant a gitleaks message change would silently turn a no-evidence run into
43
- # a PASS -- the same fail-open class this gate just fixed (#449).
44
- # The report exists and is a JSON array of findings; `[]` == clean scan.
45
- GITLEAKS_FINDINGS="?"
46
- if [ -f "$GITLEAKS_REPORT" ]; then
47
- # A report that is not shaped like a JSON array is no evidence: leave the
48
- # '?' sentinel so the gate reports SKIP, never a PASS it cannot support
49
- # (the fail-closed-on-the-claim rule #449 established).
50
- if grep -q '^\[' "$GITLEAKS_REPORT" 2>/dev/null; then
51
- # Count occurrences, not matching lines: `grep -c` prints its own zero AND
52
- # exits 1 on a clean report, so the old `|| echo 0` handed the verdict table
53
- # $'0\n0' -- no branch matched and a clean scan was BLOCKED as if it leaked
54
- # (#493). wc -l emits exactly one value, and `|| true` keeps the assignment
55
- # errexit/pipefail-safe (#489).
56
- GITLEAKS_FINDINGS=$(grep -o '"RuleID"' "$GITLEAKS_REPORT" 2>/dev/null | wc -l | tr -d '[:space:]') || true
57
- fi
54
+ if [ "$GITLEAKS_EXIT" -eq 0 ]; then
55
+ # Decide SKIP from the REPORT ARTIFACT, not from log wording. Parsing stdout
56
+ # meant a gitleaks message change would silently turn a no-evidence run into
57
+ # a PASS -- the same fail-open class this gate just fixed (#449).
58
+ # The report exists and is a JSON array of findings; `[]` == clean scan.
59
+ GITLEAKS_FINDINGS="?"
60
+ if [ -f "$GITLEAKS_REPORT" ]; then
61
+ # A report that is not shaped like a JSON array is no evidence: leave the
62
+ # '?' sentinel so the gate reports SKIP, never a PASS it cannot support
63
+ # (the fail-closed-on-the-claim rule #449 established).
64
+ if grep -q '^\[' "$GITLEAKS_REPORT" 2>/dev/null; then
65
+ # Count occurrences, not matching lines: `grep -c` prints its own zero AND
66
+ # exits 1 on a clean report, so the old `|| echo 0` handed the verdict table
67
+ # $'0\n0' -- no branch matched and a clean scan was BLOCKED as if it leaked
68
+ # (#493). wc -l emits exactly one value, and `|| true` keeps the assignment
69
+ # errexit/pipefail-safe (#489).
70
+ GITLEAKS_FINDINGS=$(grep -o '"RuleID"' "$GITLEAKS_REPORT" 2>/dev/null | wc -l | tr -d '[:space:]') || true
58
71
  fi
72
+ fi
59
73
 
60
- if [ "$GITLEAKS_FINDINGS" = "0" ]; then
61
- echo " ✅ PASSED - No secrets detected."
62
- GATE_8_STATUS="PASS"
63
- elif [ "$GITLEAKS_FINDINGS" = "?" ]; then
64
- # Exit 0 but no readable report: we have no evidence the scan happened.
65
- # Fail closed on the *claim*: report SKIP, never PASS.
66
- echo " ⚠️ gitleaks exited 0 but produced no readable report"
67
- echo " ⏭️ SKIPPED - secret scanning produced no evidence (not a pass)"
68
- GATE_8_STATUS="SKIP"
69
- else
70
- echo " ❌ BLOCKED - gitleaks reported $GITLEAKS_FINDINGS finding(s)"
71
- echo "$GITLEAKS_OUTPUT"
72
- echo ""
73
- echo "Remediation: remove the secret, or allowlist a false positive in .gitleaks.toml."
74
- exit 1
75
- fi
76
- elif [ "$GITLEAKS_EXIT" -eq 1 ]; then
77
- # Secrets found — output details
74
+ if [ "$GITLEAKS_FINDINGS" = "0" ]; then
75
+ echo " ✅ PASSED - No secrets detected."
76
+ GATE_8_STATUS="PASS"
77
+ elif [ "$GITLEAKS_FINDINGS" = "?" ]; then
78
+ # Exit 0 but no readable report: we have no evidence the scan happened.
79
+ # Fail closed on the *claim*: report SKIP, never PASS.
80
+ echo " ⚠️ gitleaks exited 0 but produced no readable report"
81
+ echo " ⏭️ SKIPPED - secret scanning produced no evidence (not a pass)"
82
+ GATE_8_STATUS="SKIP"
83
+ else
84
+ echo " ❌ BLOCKED - gitleaks reported $GITLEAKS_FINDINGS finding(s)"
78
85
  echo "$GITLEAKS_OUTPUT"
79
86
  echo ""
80
- echo "❌ BLOCKED - Secrets detected in staged files."
81
- echo ""
82
- echo "Remediation options:"
83
- echo " 1. Remove the secret and use environment variables instead"
84
- echo " 2. Add a false positive to .gitleaks.toml allowlist"
85
- echo " 3. Use git secret or vault for sensitive data"
86
- echo ""
87
- echo "See: https://github.com/gitleaks/gitleaks"
87
+ echo "Remediation: remove the secret, or allowlist a false positive in .gitleaks.toml."
88
88
  exit 1
89
+ fi
90
+ elif [ "$GITLEAKS_EXIT" -eq 1 ]; then
91
+ # Secrets found — output details
92
+ echo "$GITLEAKS_OUTPUT"
93
+ echo ""
94
+ echo " ❌ BLOCKED - Secrets detected in staged files."
95
+ echo ""
96
+ echo "Remediation options:"
97
+ echo " 1. Remove the secret and use environment variables instead"
98
+ echo " 2. Add a false positive to .gitleaks.toml allowlist"
99
+ echo " 3. Use git secret or vault for sensitive data"
100
+ echo ""
101
+ echo "See: https://github.com/gitleaks/gitleaks"
102
+ exit 1
103
+ else
104
+ # fail-closed (#499): a non-0/1 exit (config error, crash) used to SKIP, which
105
+ # let a broken scanner wave every commit through without any scan.
106
+ echo " ❌ BLOCKED - gitleaks exited with code $GITLEAKS_EXIT (fail-closed, #499)."
107
+ echo "$GITLEAKS_OUTPUT"
108
+ echo " Secret scanning could not complete; fix the gitleaks error above and retry."
109
+ exit 1
110
+ fi
111
+
112
+ # ---- detect-secrets(次要防线,基线比对)----
113
+ # detect-secrets-hook comes from the project's Python dev extra; it blocks only
114
+ # on secrets NOT yet registered in .secrets.baseline, so test-fixture dummy keys
115
+ # recorded in the baseline never trip it.
116
+ #
117
+ # The file list is piped NUL-delimited STRAIGHT into xargs -0 — never through a
118
+ # command substitution. `var=$(cmd -z)` strips every NUL byte (bash cannot hold
119
+ # NULs in a variable), which concatenated all filenames into one giant
120
+ # nonexistent path and would have BLOCKED every commit once a project shipped
121
+ # both detect-secrets-hook and .secrets.baseline. The pipeline lives inside an
122
+ # if-condition (errexit-exempt); a non-zero hook exit lands in the else branch.
123
+ if command -v detect-secrets-hook >/dev/null 2>&1 && [ -f ".secrets.baseline" ]; then
124
+ DS_TMP="$(dirname "$(mktemp -u)")/ds-output.$$"
125
+ if git diff --cached --name-only --diff-filter=ACM -z \
126
+ | xargs -0 detect-secrets-hook --baseline .secrets.baseline > "$DS_TMP" 2>&1; then
127
+ echo " ✅ detect-secrets PASSED - no new secrets beyond baseline."
89
128
  else
90
- echo " ⚠️ gitleaks exited with code $GITLEAKS_EXIT - skipping gate"
91
- echo " ✅ Secret Scanning (SKIP, gitleaks error)"
92
- GATE_8_STATUS="SKIP"
129
+ cat "$DS_TMP"
130
+ echo ""
131
+ echo " ❌ BLOCKED - detect-secrets found secrets not in .secrets.baseline."
132
+ echo " If these are false positives, regenerate the baseline (cross-platform):"
133
+ echo " detect-secrets scan --update .secrets.baseline && git add .secrets.baseline"
134
+ rm -f "$DS_TMP"
135
+ exit 1
93
136
  fi
137
+ rm -f "$DS_TMP"
94
138
  else
95
- echo " ℹ️ gitleaks not installed — secret scanning unavailable"
96
- echo " Install: brew install gitleaks (macOS) | winget install gitleaks (Windows) | scripts/install-gitleaks.sh (Linux)"
97
- echo " ⏭️ SKIPPED - Secret scanning (gitleaks not installed)"
98
- GATE_8_STATUS="SKIP"
139
+ echo " ⚠️ detect-secrets-hook unavailable (install: pip install -e \".[dev]\") — gitleaks only."
99
140
  fi
141
+
100
142
  record_gate_audit "gate-8" "secret-scanning" "$GATE_8_STATUS" "0" "$GATE_8_START"
@@ -190,17 +190,72 @@ run_coverage() {
190
190
  source_files[${#source_files[@]}]="$path"
191
191
  done < "$discovery_file"
192
192
  rm -f "$discovery_file"
193
+
194
+ # Optional project-level exclusions. Some scripts cannot be instrumented or
195
+ # exercised by a unit-test runner at all (e.g. a bootstrap script whose Main
196
+ # ends in `exit`, which terminates the Pester host when invoked in-process).
197
+ # Counting them as 0% coverage permanently caps the achievable percentage and
198
+ # makes the threshold unsatisfiable no matter how good the suite is.
199
+ # Format: one glob per line in .xp-gate-powershell-coverage-ignore
200
+ local ignore_file=".xp-gate-powershell-coverage-ignore"
201
+ if [ -f "$ignore_file" ]; then
202
+ local filtered=()
203
+ local src
204
+ for src in "${source_files[@]}"; do
205
+ local skip=0
206
+ local pat
207
+ # Discovery yields paths like "./setup.ps1"; match the pattern against the
208
+ # raw path AND the "./"-stripped form so a plain "setup.ps1" glob works.
209
+ local src_norm="${src#./}"
210
+ while IFS= read -r pat; do
211
+ # skip blanks and comments
212
+ case "$pat" in ''|'#'*) continue ;; esac
213
+ local pat_norm="${pat#./}"
214
+ # shellcheck disable=SC2254
215
+ case "$src" in $pat|$pat_norm) skip=1; break ;; esac
216
+ # shellcheck disable=SC2254
217
+ case "$src_norm" in $pat_norm) skip=1; break ;; esac
218
+ done < "$ignore_file"
219
+ if [ "$skip" -eq 0 ]; then
220
+ filtered[${#filtered[@]}]="$src"
221
+ else
222
+ echo " ℹ️ Coverage exclusion matched: $src"
223
+ fi
224
+ done
225
+ # Assign back unconditionally: when EVERY source file matched an
226
+ # exclusion, `filtered` is empty and the check below must see 0 to skip
227
+ # coverage. Only assigning on >0 silently ignored a full exclusion.
228
+ # (Empty-array guards keep this bash-3.2 / `set -u` safe.)
229
+ if [ "${#filtered[@]}" -gt 0 ]; then
230
+ source_files=("${filtered[@]}")
231
+ else
232
+ source_files=()
233
+ fi
234
+ fi
235
+
236
+ if [ "${#source_files[@]}" -eq 0 ]; then
237
+ echo "No PowerShell source files left after exclusions, skipping coverage"
238
+ return 0
239
+ fi
240
+
193
241
  test_paths=$(_powershell_path_array "${test_files[@]}")
194
242
  coverage_paths=$(_powershell_path_array "${source_files[@]}")
195
243
  echo "Running Pester with code coverage..."
244
+ # Pester 5 requires the modern configuration object: `-Path ... -CodeCoverage ...`
245
+ # is the deprecated Pester 4 parameter set and fails outright on Pester 5.x
246
+ # ("cannot resolve parameter set"). Using it silently produced no coverage.xml,
247
+ # which the pre-commit hook then reported as an unparseable/zero result.
196
248
  _pester_timeout "$PWSH" "${POWERSHELL_ARGS[@]}" "
197
- \$results = Invoke-Pester -Path $test_paths -CodeCoverage $coverage_paths -PassThru
249
+ \$cfg = New-PesterConfiguration
250
+ \$cfg.Run.Path = $test_paths
251
+ \$cfg.CodeCoverage.Enabled = \$true
252
+ \$cfg.CodeCoverage.Path = $coverage_paths
253
+ \$cfg.CodeCoverage.OutputFormat = 'JaCoCo'
254
+ \$cfg.CodeCoverage.OutputPath = (Join-Path (Get-Location) 'coverage.xml')
255
+ \$cfg.Run.PassThru = \$true
256
+ \$results = Invoke-Pester -Configuration \$cfg
198
257
  \$pct = [math]::Round(\$results.CodeCoverage.CoveragePercent, 1)
199
258
  Write-Host \"Coverage: \$pct%\"
200
- if (\$pct -lt 80) {
201
- Write-Host \"WARNING: Coverage \$pct% is below 80% threshold\"
202
- exit 0
203
- }
204
259
  exit 0
205
260
  " 2>&1
206
261
  local cov_exit=$?
@@ -4,13 +4,33 @@
4
4
  # Tools: mypy, ruff/flake8, pytest, import-linter (architecture)
5
5
 
6
6
  SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
7
+ # SC1091:adapter-common.sh 由调用方按查找顺序提供,路径靠变量拼接,shellcheck 无法静态跟随。
8
+ # `source … || true` 是既有容错口径(仓库存档时该文件可能不在),不要改成硬依赖。
9
+ # shellcheck source=/dev/null
7
10
  source "$SCRIPT_DIR/../adapter-common.sh" 2>/dev/null || true
8
11
 
9
12
  run_static_analysis() {
10
13
  require_tool mypy "mypy" || return 1
11
14
 
15
+ # 口径 = CI type job(.github/workflows/ci.yml:43-45)的两条命令,逐字一致。
16
+ # 为什么不能写 `mypy .`:`.` 会递归扫到两类文件,而它们在仓库里从未被声明为
17
+ # 门禁面,CI 也从不检查:
18
+ # ① 根目录一次性调研/演示脚本(fetch_*.py、demo_*.py、validate_*.py 等)——
19
+ # `[tool.ruff] exclude`(pyproject.toml:217-238)已逐文件把它们列为"历史产物,
20
+ # 从未被 `ruff check src/ tests/` 覆盖",mypy 侧却没有对应排除;
21
+ # ② `tests/` —— CI 只跑 `mypy src/` 与 `mypy scripts/`,测试域的类型问题
22
+ # 没有任何门禁核对过。
23
+ # 两份清单不一致的后果是钩子恒红且与本仓任何真实缺陷无关:实测 `mypy .` 87 条
24
+ # error(本机),而 `mypy src/`(136 files)与 `mypy scripts/`(42 files)各自
25
+ # exit 0。即当时钩子会阻断**任何**提交,包括纯文档改动。
26
+ # 处置是让钩子对齐已声明的 CI 口径,而不是给那 87 处补注解——补注解既不在声明
27
+ # 口径内,又会顺手动几十个无关文件(含 tests/)。
28
+ # 口径一致性由仓库侧 BATS 测试双向锁住:
29
+ # githooks/__tests__/adapter-mypy-pester-scope.test.bats(含"适配器里不得再
30
+ # 出现裸 mypy ."),防止 `mypy .` 被写回来时无人报警。
12
31
  echo "Running Python static analysis (mypy)..."
13
- mypy .
32
+ mypy src/ || return 1
33
+ mypy scripts/
14
34
  return $?
15
35
  }
16
36
 
@@ -45,7 +65,8 @@ run_tests() {
45
65
  require_tool pytest "pytest" || return 1
46
66
 
47
67
  echo "Running Python tests..."
48
- PYTEST_OUTPUT=$(pytest --exitfirst --tb=short 2>&1)
68
+ # Skip e2e tests by default in pre-commit (require live API + network)
69
+ PYTEST_OUTPUT=$(pytest --exitfirst --tb=short -m "not e2e" 2>&1)
49
70
  PYTEST_EXIT=$?
50
71
 
51
72
  # Show the short summary tail — this is where FAILED/assert diagnostics live.
@@ -85,7 +106,10 @@ run_coverage() {
85
106
  require_tool pytest "pytest" || return 1
86
107
 
87
108
  echo "Running Python coverage..."
88
- PYTEST_OUTPUT=$(pytest --exitfirst --tb=short --cov=. --cov-fail-under=80 2>&1)
109
+ # 阈值不在此处硬编码:pytest-cov 自动读取 pyproject.toml 的
110
+ # [tool.coverage.report] fail_under(唯一事实源)。此前这里重复写了
111
+ # --cov-fail-under=79.9,改 pyproject 不会让门禁跟着变,属于假配置。
112
+ PYTEST_OUTPUT=$(pytest --exitfirst --tb=short --cov=src -m "not e2e" 2>&1)
89
113
  PYTEST_EXIT=$?
90
114
  echo "$PYTEST_OUTPUT" | grep -E "(FAILED|PASSED|passed|failed|error|ERROR|TOTAL|assert)" | tail -10
91
115
  echo "$PYTEST_OUTPUT" | tail -5
@@ -152,7 +176,17 @@ run_mutation() {
152
176
  local MUTATION_OUTPUT
153
177
  MUTATION_OUTPUT=$(mktemp)
154
178
 
155
- timeout "${timeout_s}s" mutmut run --paths-to-mutate $file_list > "$MUTATION_OUTPUT" 2>&1
179
+ local MUTMUT_CMD="mutmut"
180
+ if ! command -v mutmut >/dev/null 2>&1; then
181
+ MUTMUT_CMD="python3 -m mutmut"
182
+ fi
183
+
184
+ # SC2086:`$MUTMUT_CMD` 与 `$file_list` 都是**故意按空白分词**的——
185
+ # 前者可能是两个词(`python3 -m mutmut`),后者是空格分隔的多条路径,
186
+ # 加引号会把它们并成单个参数、直接让命令失败。故此处显式声明意图,
187
+ # 而不是改成引号(引号在这里不是修 bug,是造 bug)。
188
+ # shellcheck disable=SC2086
189
+ timeout "${timeout_s}s" $MUTMUT_CMD run --paths-to-mutate $file_list > "$MUTATION_OUTPUT" 2>&1
156
190
  local EXIT_CODE=$?
157
191
 
158
192
  cat "$MUTATION_OUTPUT"
@@ -12,6 +12,10 @@ import path from 'path';
12
12
  import os from 'os';
13
13
  import { extractImports, resolveImportPath, runImportCheck } from '../gate-10';
14
14
 
15
+ // Named timeout for the runImportCheck calls that assert verdicts; keeps the
16
+ // Boy Scout magic-number count from growing with each new test case.
17
+ const IMPORT_CHECK_TIMEOUT_MS = 30000;
18
+
15
19
  /**
16
20
  * ─── extractImports ────────────────────────────────────────────────────────────
17
21
  */
@@ -321,6 +325,61 @@ describe('runImportCheck', () => {
321
325
  expect(result.violations[0].reason).toMatch(/not found|does not exist|missing/i);
322
326
  });
323
327
 
328
+ it('passes when projectRoot spelling differs in drive case/slashes (Windows, #508)', async () => {
329
+ // git rev-parse --show-toplevel reports "D:/repo" while path.resolve of a
330
+ // repo-relative changed file inherits process.cwd()'s "d:\repo" drive case.
331
+ // The case-sensitive startsWith judged every import as boundary-escaping,
332
+ // blocking any TS-bearing push. The same root spelled the other way must
333
+ // pass on Windows; drive letters do not exist on POSIX so skip there.
334
+ if (process.platform !== 'win32') return;
335
+
336
+ let fooFile: string;
337
+ try {
338
+ const srcDir = path.join(tmpDir, 'src');
339
+ await fs.mkdir(srcDir);
340
+
341
+ const barFile = path.join(srcDir, 'bar.ts');
342
+ await fs.writeFile(barFile, 'export const x = 1;');
343
+
344
+ fooFile = path.join(srcDir, 'foo.ts');
345
+ await fs.writeFile(fooFile, `import { x } from './bar';\nconsole.log(x);\n`);
346
+ } catch (error) {
347
+ throw new Error(`Fixture setup failed: ${error}`);
348
+ }
349
+
350
+ const altRoot = tmpDir.replace(/\\/g, '/').replace(/^[a-zA-Z]:/, (m) => m.toLowerCase());
351
+ expect(altRoot).not.toBe(tmpDir);
352
+
353
+ const result = await runImportCheck([fooFile], altRoot, IMPORT_CHECK_TIMEOUT_MS);
354
+ expect(result.status).toBe('pass');
355
+ expect(result.violations).toEqual([]);
356
+ });
357
+
358
+ it('still fails a true boundary escape after case normalization (#508 follow-up)', async () => {
359
+ // Normalization must only absorb case/spelling differences, never widen the
360
+ // boundary: an import that genuinely leaves the project root keeps failing
361
+ // even when the root is spelled with a different drive-letter case.
362
+ if (process.platform !== 'win32') return;
363
+
364
+ let badFile: string;
365
+ try {
366
+ const nestedDir = path.join(tmpDir, 'pkg', 'dist', 'sub');
367
+ await fs.mkdir(nestedDir, { recursive: true });
368
+
369
+ badFile = path.join(nestedDir, 'file.ts');
370
+ await fs.writeFile(badFile, `import { x } from '../../../../outside';\n`);
371
+ } catch (error) {
372
+ throw new Error(`Fixture setup failed: ${error}`);
373
+ }
374
+
375
+ const altRoot = tmpDir.replace(/\\/g, '/').replace(/^[a-zA-Z]:/, (m) => m.toLowerCase());
376
+
377
+ const result = await runImportCheck([badFile], altRoot, IMPORT_CHECK_TIMEOUT_MS);
378
+ expect(result.status).toBe('fail');
379
+ expect(result.violations.length).toBeGreaterThan(0);
380
+ expect(result.violations[0].reason).toMatch(/escapes|outside|boundary/i);
381
+ });
382
+
324
383
  it('skips YAML files containing JavaScript-like require text', async () => {
325
384
  const workflowDir = path.join(tmpDir, '.github', 'workflows');
326
385
  await fs.mkdir(workflowDir, { recursive: true });
@@ -307,6 +307,8 @@ export async function runImportCheck(
307
307
 
308
308
  const fsSync = fsNative;
309
309
 
310
+ const normalizedRoot = path.resolve(projectRoot);
311
+
310
312
  for (const file of changedFiles) {
311
313
  if (!isSupportedModuleFile(file)) continue;
312
314
 
@@ -327,14 +329,27 @@ export async function runImportCheck(
327
329
  continue;
328
330
  }
329
331
 
332
+ // Windows paths are case-insensitive but the two sides of the boundary
333
+ // comparison get their case from different sources: path.resolve of a
334
+ // repo-relative file inherits process.cwd()'s drive-letter case (often
335
+ // lowercase), while projectRoot comes from `git rev-parse --show-toplevel`
336
+ // (uppercase drive). A case-sensitive startsWith then judged EVERY import
337
+ // as escaping the boundary — pre-push Gate 10 blocked any TS-bearing push
338
+ // from a shell whose drive-letter case disagreed with git's (#508).
339
+ const normalizeForBoundary = (p: string): string => {
340
+ const resolved = path.resolve(p);
341
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
342
+ };
343
+ const boundaryRoot = normalizeForBoundary(normalizedRoot);
344
+
330
345
  const imports = extractImports(content);
331
346
 
332
347
  for (const imp of imports) {
333
348
  const rawResolved = path.resolve(path.dirname(file), imp.path);
334
- const normalizedRoot = path.resolve(projectRoot);
349
+ const boundaryTarget = normalizeForBoundary(rawResolved);
335
350
 
336
351
  const escapesBoundary =
337
- !rawResolved.startsWith(normalizedRoot + path.sep) && rawResolved !== normalizedRoot;
352
+ !boundaryTarget.startsWith(boundaryRoot + path.sep) && boundaryTarget !== boundaryRoot;
338
353
 
339
354
  if (escapesBoundary) {
340
355
  violations.push({