@boyingliu01/xp-gate 0.37.3 → 0.38.0
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/adapter-common.sh +12 -2
- package/adapters/csharp.sh +73 -2
- package/adapters/dart.sh +13 -0
- package/adapters/go.sh +5 -0
- package/adapters/iac.sh +46 -3
- package/adapters/java.sh +6 -0
- package/adapters/kotlin.sh +6 -0
- package/adapters/shell.sh +119 -34
- package/adapters/swift.sh +6 -0
- package/adapters/typescript.sh +98 -34
- package/bin/xp-gate.js +48 -2
- package/gate-10.sh +99 -26
- package/gate-12-file-hygiene.sh +13 -1
- package/gate-registry.sh +197 -0
- package/gates/python-health.ts +67 -29
- package/hooks/adapter-common.sh +12 -2
- package/hooks/deploy-manifest.sh +100 -0
- package/hooks/gate-10.sh +99 -26
- package/hooks/gate-12-file-hygiene.sh +13 -1
- package/hooks/gate-driver.sh +120 -0
- package/hooks/gate-entries/gate-0-entry.sh +825 -0
- package/hooks/gate-entries/gate-1-entry.sh +767 -0
- package/hooks/gate-entries/gate-10-entry.sh +52 -0
- package/hooks/gate-entries/gate-11-entry.sh +120 -0
- package/hooks/gate-entries/gate-12-entry.sh +44 -0
- package/hooks/gate-entries/gate-12b-entry.sh +178 -0
- package/hooks/gate-entries/gate-12c-entry.sh +80 -0
- package/hooks/gate-entries/gate-13-entry.sh +584 -0
- package/hooks/gate-entries/gate-2-entry.sh +199 -0
- package/hooks/gate-entries/gate-3-entry.sh +53 -0
- package/hooks/gate-entries/gate-4-entry.sh +46 -0
- package/hooks/gate-entries/gate-5-entry.sh +1729 -0
- package/hooks/gate-entries/gate-6-entry.sh +658 -0
- package/hooks/gate-entries/gate-7-entry.sh +41 -0
- package/hooks/gate-entries/gate-8-entry.sh +33 -0
- package/hooks/gate-entries/gate-9-entry.sh +307 -0
- package/hooks/gate-entries/subdir-restore.sh +27 -0
- package/hooks/gate-registry.sh +51 -15
- package/hooks/hook-module-resolution.sh +73 -0
- package/hooks/install.sh +135 -0
- package/hooks/lib/now-ms.sh +55 -19
- package/hooks/lib/toolchain-path.sh +50 -6
- package/hooks/pre-commit +256 -5091
- package/hooks/pre-push +212 -25
- package/lib/__tests__/arch-config-template.test.js +190 -0
- package/lib/__tests__/baseline-shell-scope.test.js +60 -0
- package/lib/__tests__/crap-cli.test.js +14 -3
- package/lib/__tests__/deploy-manifest-check-wired.test.js +138 -0
- package/lib/__tests__/deploy-manifest-completeness.test.js +151 -0
- package/lib/__tests__/deploy-manifest-consumers-adapter-uninstall.test.js +40 -0
- package/lib/__tests__/deploy-manifest-consumers-no-private-lists.test.js +74 -0
- package/lib/__tests__/deploy-manifest-projection.test.js +66 -0
- package/lib/__tests__/deploy-manifest-shell-parity.test.js +108 -0
- package/lib/__tests__/deploy-manifest.test.js +97 -0
- package/lib/__tests__/doctor.test.js +51 -7
- package/lib/__tests__/gate-coverage.test.js +79 -12
- package/lib/__tests__/gate-numbering.test.js +28 -1
- package/lib/__tests__/install-sh-deploy-manifest.test.js +80 -0
- package/lib/__tests__/mirror-sync.test.js +45 -3
- package/lib/__tests__/npm-package.test.js +10 -7
- package/lib/__tests__/sastd-client.test.js +452 -0
- package/lib/__tests__/shared-utils-copyHooks-manifest.test.js +69 -0
- package/lib/__tests__/sprint-status-rework.test.js +1 -0
- package/lib/arch-config-template.js +87 -0
- package/lib/baseline.js +54 -2
- package/lib/deploy-manifest.js +174 -0
- package/lib/doctor.js +46 -14
- package/lib/gate-capability.js +291 -0
- package/lib/gate-coverage.js +194 -74
- package/lib/gate-identity.js +349 -0
- package/lib/gate-runner.js +11 -1
- package/lib/hook-module-resolution.js +27 -0
- package/lib/init.js +72 -5
- package/lib/mattpocock-license-verdict.json +1 -1
- package/lib/sastd-client.js +534 -0
- package/lib/shared-utils.js +31 -9
- package/lib/uninstall.js +10 -7
- package/lib/update-hooks.js +27 -18
- package/mock-policy/AGENTS.md +1 -1
- package/mutation/AGENTS.md +1 -1
- package/package.json +3 -1
- package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
- package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
- package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
- package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
- package/plugins/dsh/package.json +1 -1
- package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
- package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
- package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
- package/plugins/opencode/package.json +1 -1
- package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
- package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
- package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
- package/plugins/qoder/plugin.json +1 -1
- package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
- package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
- package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
- package/principles/AGENTS.md +1 -1
- package/principles/__tests__/analyzer.test.ts +2 -1
- package/principles/__tests__/config-enforcement.test.ts +1 -0
- package/principles/__tests__/types.test.ts +1 -0
- package/principles/adapters/base.ts +14 -1
- package/principles/adapters/duplication.ts +134 -0
- package/principles/rules/__tests__/clean-code/large-file.test.ts +2 -1
- package/principles/rules/clean-code/code-duplication.ts +75 -9
- package/principles/types.ts +39 -0
- package/scripts/__tests__/check-mattpocock-license.test.js +36 -3
- package/scripts/__tests__/sync-package-content.test.js +12 -2
- package/scripts/generate-mirrors.cjs +125 -0
- package/scripts/sync-package-content.js +64 -20
- package/skills/delphi-review/AGENTS.md +1 -1
- package/skills/sprint-flow/AGENTS.md +1 -1
- package/skills/test-specification-alignment/AGENTS.md +1 -1
- package/adapters/gate-9.sh +0 -245
- package/gate-9.sh +0 -245
- package/hooks/gate-9.sh +0 -245
|
@@ -0,0 +1,1729 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# ============================================================================
|
|
3
|
+
# gate-5 entry — extracted from pre-commit by scripts/extract-gates.cjs
|
|
4
|
+
#
|
|
5
|
+
# WHY THIS FILE EXISTS (#798)
|
|
6
|
+
# The gate order used to BE the physical order of blocks in a 6341-line
|
|
7
|
+
# hook, so changing the order meant moving thousands of lines. An attempt at
|
|
8
|
+
# that also moved the hook epilogue, after which every gate past Gate 13
|
|
9
|
+
# silently stopped running while `bash -n`, a line count and five ordering
|
|
10
|
+
# tests all passed. Gate 5a stopped blocking and only a behavioural test
|
|
11
|
+
# noticed. With one file per gate, order is a list of names in
|
|
12
|
+
# pre-commit's GATE_ORDER and cannot detach a body from its position.
|
|
13
|
+
#
|
|
14
|
+
# THE BODY BELOW IS A BYTE-EXACT SLICE of the original block. It is wrapped
|
|
15
|
+
# in a function so the gate keeps its own variable scope, and is called from
|
|
16
|
+
# pre-commit at the point the driver reaches it. Edit the gate here from now
|
|
17
|
+
# on - there is no copy left in the hook.
|
|
18
|
+
# ============================================================================
|
|
19
|
+
|
|
20
|
+
# ============================================================================
|
|
21
|
+
# Gate body. `return` is used instead of `exit` so the driver decides to
|
|
22
|
+
# stop: see scripts/wrap-gate-entries.cjs for why the two are equivalent
|
|
23
|
+
# here, and why sub-shell exits are deliberately left as `exit`.
|
|
24
|
+
gate_5_run() {
|
|
25
|
+
# GATE 5: Tests & Coverage Combined (Combines Old Gates 3 - Tests and 4 - Coverage)
|
|
26
|
+
# Uses adapter system to run tests + coverage for language
|
|
27
|
+
#
|
|
28
|
+
# v0.14.3+ (Issue #312): Skip test run when no code files changed.
|
|
29
|
+
# Code files = src/**/*.ts, plugins/**/*.ts, *.ts, *.tsx, etc. (language-aware).
|
|
30
|
+
# VERSION, CHANGELOG, docs, config-only changes → SKIP test run entirely.
|
|
31
|
+
# Gate 5a (new file pairing), 5b (mock density), and 5c (semantic annotation)
|
|
32
|
+
# are lightweight and still run even when no code files changed.
|
|
33
|
+
# Gate 5a (new file pairing) and Gate 5b (mock density) still run — they're lightweight.
|
|
34
|
+
# ============================================================================
|
|
35
|
+
2>&1 echo ""
|
|
36
|
+
2>&1 echo "→ Gate 5: Tests & coverage..."
|
|
37
|
+
GATE_5_START=$(gate_start_ms)
|
|
38
|
+
# #554 follow-up: explicit "nothing decided yet" sentinel. A branch inside the
|
|
39
|
+
# else-block may record its own verdict (the no-code early skip records SKIP);
|
|
40
|
+
# the epilogue must not overwrite it with PASS. Using "" rather than leaving the
|
|
41
|
+
# variable unset keeps the epilogue's decision readable, and keeps every render
|
|
42
|
+
# site's own default (`${GATE_5_STATUS:-SKIP}`) honest for the paths that never
|
|
43
|
+
# assign at all.
|
|
44
|
+
GATE_5_STATUS=""
|
|
45
|
+
|
|
46
|
+
if ! gate_enabled 5; then
|
|
47
|
+
echo "⏭️ SKIPPED - Gate 5: Tests & coverage (not selected by XP_GATE_ONLY_GATE)"
|
|
48
|
+
GATE_5_STATUS="SKIP"
|
|
49
|
+
GATE_5_DETAIL="not_selected"
|
|
50
|
+
|
|
51
|
+
elif [ "$PROJECT_LANG" = "documentation-only" ] || [ "$DOCS_ONLY_COMMIT" = true ]; then
|
|
52
|
+
echo "⏭️ SKIPPED - Tests & coverage (documentation-only commit — no code changed to test)."
|
|
53
|
+
GATE_5_STATUS="SKIP"
|
|
54
|
+
GATE_5_DETAIL="docs_only_change"
|
|
55
|
+
|
|
56
|
+
else
|
|
57
|
+
# ========================================================================
|
|
58
|
+
# Gate 5-FOCUS / Gate 5-DELETE (#602): the two quietest ways to "fix" a red
|
|
59
|
+
# build are to commit a `.only` (CI then runs one case and reports green) and
|
|
60
|
+
# to delete a test file with no replacement (the safety net vanishes with no
|
|
61
|
+
# signal). 指南 §9.5/§12 forbid both. Gate 5a guards the ADD side -- "a new
|
|
62
|
+
# source file must have a test" -- so guarding only that side left the
|
|
63
|
+
# constraint asymmetric: tests could be silently removed but never silently
|
|
64
|
+
# added, which is backwards from what protects the codebase.
|
|
65
|
+
#
|
|
66
|
+
# Runs before the expensive Gate 5a machinery so a `.only` commit fails in
|
|
67
|
+
# milliseconds instead of after a full test run.
|
|
68
|
+
# ========================================================================
|
|
69
|
+
GATE_5_FOCUS_BLOCKED=0
|
|
70
|
+
GATE_5_SKIP_COUNT=0
|
|
71
|
+
GATE_5_DELETED_TESTS=""
|
|
72
|
+
if declare -f classify_test_focus >/dev/null 2>&1; then
|
|
73
|
+
STAGED_TEST_FILES=$(printf '%s\n' "${XP_STAGED_ACM:-$(git diff --cached --name-only --diff-filter=ACM 2>/dev/null)}" \
|
|
74
|
+
| filter_project_paths | grep -E '\.(test|spec)\.(ts|tsx|js|jsx|mjs|cjs|py|go|java|kt|cs|scala|ps1)$|(^|/)(test_[^/]*\.py|[^/]*_test\.(py|go))$' || true)
|
|
75
|
+
if [ -n "$STAGED_TEST_FILES" ]; then
|
|
76
|
+
while IFS= read -r _tf; do
|
|
77
|
+
[ -n "$_tf" ] || continue
|
|
78
|
+
_tf_content=$(git show ":$tf" 2>/dev/null) || _tf_content=$(cat "$_tf" 2>/dev/null || true)
|
|
79
|
+
[ -n "$_tf_content" ] || continue
|
|
80
|
+
|
|
81
|
+
# --- focus markers: BLOCK ---
|
|
82
|
+
_focus_hits=$(printf '%s\n' "$_tf_content" | classify_test_focus || true)
|
|
83
|
+
if [ -n "$_focus_hits" ]; then
|
|
84
|
+
# XP_GATE_ALLOW_ONLY=1 is an explicit, audited override for the one
|
|
85
|
+
# legitimate case (debugging an unrelated failure mid-bisect). It is
|
|
86
|
+
# opt-in per run and printed, never silent.
|
|
87
|
+
if [ "${XP_GATE_ALLOW_ONLY:-0}" = "1" ]; then
|
|
88
|
+
echo "⚠️ WARN - focus marker in $_tf (allowed by XP_GATE_ALLOW_ONLY=1)"
|
|
89
|
+
record_gate_audit "gate-5-focus-override" "focus-override" "WARN" 1 "$GATE_5_START" "file=$_tf"
|
|
90
|
+
else
|
|
91
|
+
echo "❌ BLOCKED - focus marker(s) in $_tf:"
|
|
92
|
+
printf '%s\n' "$_focus_hits" | sed 's/^/ /'
|
|
93
|
+
GATE_5_FOCUS_BLOCKED=$((GATE_5_FOCUS_BLOCKED + 1))
|
|
94
|
+
fi
|
|
95
|
+
fi
|
|
96
|
+
|
|
97
|
+
# --- skip markers: WARN unless justified ---
|
|
98
|
+
_skip_hits=$(printf '%s\n' "$_tf_content" | classify_test_skip || true)
|
|
99
|
+
if [ -n "$_skip_hits" ]; then
|
|
100
|
+
if is_skip_justified "$_tf_content"; then
|
|
101
|
+
echo "ℹ️ Skipped case(s) in $_tf are justified via @skip-justified."
|
|
102
|
+
else
|
|
103
|
+
_skip_n=$(printf '%s\n' "$_skip_hits" | wc -l | tr -d ' ')
|
|
104
|
+
GATE_5_SKIP_COUNT=$((GATE_5_SKIP_COUNT + _skip_n))
|
|
105
|
+
echo "⚠️ WARN - $_skip_n skipped case(s) in $_tf without @skip-justified: <reason>"
|
|
106
|
+
fi
|
|
107
|
+
fi
|
|
108
|
+
# --- Gate 5d (#601): assertion quality ---
|
|
109
|
+
# 指南 §9.2 forbids six assertion anti-patterns, and until now nothing in
|
|
110
|
+
# XP-Gate looked at assertions at all: Gate M2/M3 examine how test doubles
|
|
111
|
+
# are built, never whether the test asserts anything. Tautologies and
|
|
112
|
+
# empty catches are BLOCK (certainly vacuous); weak-only / mock-echo /
|
|
113
|
+
# call-order shapes WARN, because each can be legitimate and blocking a
|
|
114
|
+
# legal style trains people to add justification annotations until the
|
|
115
|
+
# annotation stops meaning anything.
|
|
116
|
+
if declare -f classify_tautological_assertions >/dev/null 2>&1; then
|
|
117
|
+
if is_assertion_justified "$_tf_content"; then
|
|
118
|
+
echo "ℹ️ Assertion style in $_tf is justified via @assertion-justified."
|
|
119
|
+
else
|
|
120
|
+
_tauto=$(printf '%s\n' "$_tf_content" | classify_tautological_assertions || true)
|
|
121
|
+
_swallow=$(printf '%s\n' "$_tf_content" | classify_swallowed_errors || true)
|
|
122
|
+
_weak=$(printf '%s\n' "$_tf_content" | classify_weak_assertions || true)
|
|
123
|
+
# #668: split the findings into "added by this change" and
|
|
124
|
+
# "pre-existing". Gate 5d examines whole files, so editing a file
|
|
125
|
+
# anywhere re-examines all of its assertions; presenting standing debt
|
|
126
|
+
# under an unrelated commit is a false attribution, and false
|
|
127
|
+
# attribution is what drives people to @assertion-justified instead of
|
|
128
|
+
# a real fix.
|
|
129
|
+
_new_ranges=$(staged_added_line_ranges "$_tf" 2>/dev/null || true)
|
|
130
|
+
if [ -n "$_tauto" ]; then
|
|
131
|
+
_tauto_new=""
|
|
132
|
+
_tauto_old=""
|
|
133
|
+
while IFS= read -r _tline; do
|
|
134
|
+
[ -n "$_tline" ] || continue
|
|
135
|
+
_tnum="${_tline%%:*}"
|
|
136
|
+
if assertion_line_is_new "$_tf" "$_tnum" "$_new_ranges"; then
|
|
137
|
+
_tauto_new="${_tauto_new}${_tline}"$'\n'
|
|
138
|
+
else
|
|
139
|
+
_tauto_old="${_tauto_old}${_tline}"$'\n'
|
|
140
|
+
fi
|
|
141
|
+
done <<< "$_tauto"
|
|
142
|
+
if [ -n "$_tauto_new" ]; then
|
|
143
|
+
echo "❌ BLOCKED - tautological assertion(s) added by this change in $_tf (cannot fail):"
|
|
144
|
+
printf '%s' "$_tauto_new" | sed 's/^/ /'
|
|
145
|
+
echo " See skills/test-driven-development/testing-anti-patterns.md"
|
|
146
|
+
GATE_5_FOCUS_BLOCKED=$((GATE_5_FOCUS_BLOCKED + 1))
|
|
147
|
+
fi
|
|
148
|
+
if [ -n "$_tauto_old" ]; then
|
|
149
|
+
echo "⚠️ WARN - PRE-EXISTING tautological assertion(s) in $_tf (NOT introduced by this change):"
|
|
150
|
+
printf '%s' "$_tauto_old" | sed 's/^/ /'
|
|
151
|
+
echo " These predate this commit. Two options:"
|
|
152
|
+
echo " fix them now (see 'xp-gate audit assertions'), or"
|
|
153
|
+
echo " leave them - they are not blocking you."
|
|
154
|
+
fi
|
|
155
|
+
fi
|
|
156
|
+
if [ -n "$_swallow" ]; then
|
|
157
|
+
# Same #668 split as the tautology branch above.
|
|
158
|
+
_sw_new=""
|
|
159
|
+
_sw_old=""
|
|
160
|
+
while IFS= read -r _sline; do
|
|
161
|
+
[ -n "$_sline" ] || continue
|
|
162
|
+
_snum="${_sline%%:*}"
|
|
163
|
+
if assertion_line_is_new "$_tf" "$_snum" "$_new_ranges"; then
|
|
164
|
+
_sw_new="${_sw_new}${_sline}"$'\n'
|
|
165
|
+
else
|
|
166
|
+
_sw_old="${_sw_old}${_sline}"$'\n'
|
|
167
|
+
fi
|
|
168
|
+
done <<< "$_swallow"
|
|
169
|
+
if [ -n "$_sw_new" ]; then
|
|
170
|
+
echo "❌ BLOCKED - empty catch added by this change in $_tf swallows the failure it guards:"
|
|
171
|
+
printf '%s' "$_sw_new" | sed 's/^/ /'
|
|
172
|
+
echo " See skills/test-driven-development/testing-anti-patterns.md"
|
|
173
|
+
GATE_5_FOCUS_BLOCKED=$((GATE_5_FOCUS_BLOCKED + 1))
|
|
174
|
+
fi
|
|
175
|
+
if [ -n "$_sw_old" ]; then
|
|
176
|
+
echo "⚠️ WARN - PRE-EXISTING empty catch(es) in $_tf (NOT introduced by this change):"
|
|
177
|
+
printf '%s' "$_sw_old" | sed 's/^/ /'
|
|
178
|
+
echo " These predate this commit; see 'xp-gate audit assertions'."
|
|
179
|
+
fi
|
|
180
|
+
fi
|
|
181
|
+
if [ -n "$_weak" ]; then
|
|
182
|
+
echo "⚠️ WARN - test block(s) in $_tf assert only weak properties:"
|
|
183
|
+
printf '%s\n' "$_weak" | sed 's/^/ /'
|
|
184
|
+
echo " toBeDefined/toBeTruthy alone cannot detect a wrong value."
|
|
185
|
+
GATE_5_SKIP_COUNT=$((GATE_5_SKIP_COUNT + $(printf '%s\n' "$_weak" | wc -l | tr -d ' ')))
|
|
186
|
+
fi
|
|
187
|
+
fi
|
|
188
|
+
fi
|
|
189
|
+
done <<< "$STAGED_TEST_FILES"
|
|
190
|
+
|
|
191
|
+
# --- deleted test files: WARN ---
|
|
192
|
+
DELETED_LIST=$(mktemp 2>/dev/null || echo "${TMPDIR:-/tmp}/xp-deleted-$$")
|
|
193
|
+
ADDED_LIST=$(mktemp 2>/dev/null || echo "${TMPDIR:-/tmp}/xp-added-$$")
|
|
194
|
+
# Routed through the same filter as every other staged-file scan (#649):
|
|
195
|
+
# a deleted/added file under node_modules/ or vendor/ is not project code,
|
|
196
|
+
# and treating it as one reports deletions that mean nothing.
|
|
197
|
+
git diff --cached --name-only --diff-filter=D 2>/dev/null | filter_project_paths > "$DELETED_LIST" || true
|
|
198
|
+
git diff --cached --name-only --diff-filter=A 2>/dev/null | filter_project_paths > "$ADDED_LIST" || true
|
|
199
|
+
GATE_5_DELETED_TESTS=$(classify_deleted_tests "$DELETED_LIST" "$ADDED_LIST" || true)
|
|
200
|
+
rm -f "$DELETED_LIST" "$ADDED_LIST"
|
|
201
|
+
if [ -n "$GATE_5_DELETED_TESTS" ]; then
|
|
202
|
+
echo "⚠️ WARN - test file(s) deleted with no same-named replacement:"
|
|
203
|
+
printf '%s\n' "$GATE_5_DELETED_TESTS" | sed 's/^/ /'
|
|
204
|
+
echo " Deleting a test removes the safety net (指南 §9.5). If the code is"
|
|
205
|
+
echo " genuinely gone, say so in the commit body; otherwise restore it."
|
|
206
|
+
fi
|
|
207
|
+
fi
|
|
208
|
+
fi
|
|
209
|
+
|
|
210
|
+
if [ "$GATE_5_FOCUS_BLOCKED" -gt 0 ]; then
|
|
211
|
+
echo ""
|
|
212
|
+
echo "❌ BLOCKED - Gate 5: $GATE_5_FOCUS_BLOCKED test-hygiene violation(s) (see above)."
|
|
213
|
+
echo " Focus markers (.only/fit/fdescribe) make CI run one case and report green;"
|
|
214
|
+
echo " tautological assertions and empty catches verify nothing at all."
|
|
215
|
+
echo " See skills/test-driven-development/testing-anti-patterns.md"
|
|
216
|
+
echo " Remove them, or add '@assertion-justified: <reason>' for a reviewed exception."
|
|
217
|
+
record_gate_audit "gate-5-focus" "test-focus" "FAIL" "$GATE_5_FOCUS_BLOCKED" "$GATE_5_START" "blocked=1"
|
|
218
|
+
return 1
|
|
219
|
+
fi
|
|
220
|
+
|
|
221
|
+
# ========================================================================
|
|
222
|
+
# Gate 5a: Test-Source File Pairing Check
|
|
223
|
+
# New .ts/.tsx files: BLOCK (no corresponding test → commit rejected)
|
|
224
|
+
# Modified files (any lang): WARNING (backward compatible)
|
|
225
|
+
# New non-TS files: WARNING (unchanged)
|
|
226
|
+
# Escape valve: SKIP_GATE_5A_BLOCK=1 (non-main/master only, audit logged)
|
|
227
|
+
# Grace period: .tdd-adoption.yaml gracePeriod: N (first N commits = WARNING only)
|
|
228
|
+
# Checks coexistence, not temporal order. True "test-first" enforced by
|
|
229
|
+
# Agent skills (Layer 1 + Layer 4).
|
|
230
|
+
# ========================================================================
|
|
231
|
+
|
|
232
|
+
# --- Pre-checks: grace period + escape valve ---
|
|
233
|
+
TDD_GRACE=0
|
|
234
|
+
if [ -f ".tdd-adoption.yaml" ]; then
|
|
235
|
+
TDD_ENABLED=$(grep -E '^\s*enabled:' .tdd-adoption.yaml | awk '{print $2}' || echo "true")
|
|
236
|
+
if [ "$TDD_ENABLED" != "false" ]; then
|
|
237
|
+
TDD_GRACE=$(grep -E '^\s*gracePeriod:' .tdd-adoption.yaml | awk '{print $2}' || echo "0")
|
|
238
|
+
fi
|
|
239
|
+
fi
|
|
240
|
+
|
|
241
|
+
TDD_BLOCK_DOWNGRADE=false
|
|
242
|
+
if [ "$TDD_GRACE" -gt 0 ] 2>/dev/null; then
|
|
243
|
+
TDD_BLOCK_DOWNGRADE=true
|
|
244
|
+
fi
|
|
245
|
+
|
|
246
|
+
SKIP_5A_BLOCK=false
|
|
247
|
+
if [ "${SKIP_GATE_5A_BLOCK:-0}" = "1" ]; then
|
|
248
|
+
CURRENT_BRANCH=$(git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --abbrev-ref HEAD 2>/dev/null) || CURRENT_BRANCH=""
|
|
249
|
+
CURRENT_BRANCH=$(printf '%s' "$CURRENT_BRANCH" | tr -d '\r\n'); [ -n "$CURRENT_BRANCH" ] || CURRENT_BRANCH="HEAD"
|
|
250
|
+
if [ "$CURRENT_BRANCH" != "main" ] && [ "$CURRENT_BRANCH" != "master" ]; then
|
|
251
|
+
REASON="${SKIP_GATE_5A_BLOCK_REASON:-not specified}"
|
|
252
|
+
mkdir -p .xp-gate/reports
|
|
253
|
+
# Escape special characters in REASON for valid JSON
|
|
254
|
+
ESCAPED_REASON=$(printf '%s' "$REASON" | sed 's/\\/\\\\/g; s/"/\\"/g')
|
|
255
|
+
ESCAPED_USER=$(printf '%s' "$(git config user.name)" | sed 's/\\/\\\\/g; s/"/\\"/g')
|
|
256
|
+
echo "{\"timestamp\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",\"branch\":\"$CURRENT_BRANCH\",\"user\":\"$ESCAPED_USER\",\"reason\":\"$ESCAPED_REASON\",\"gate\":\"5a-block\"}" >> .xp-gate/reports/escape-valve-log.json
|
|
257
|
+
echo "⚠️ ESCAPE VALVE: SKIP_GATE_5A_BLOCK=1 on branch $CURRENT_BRANCH (reason: $REASON)"
|
|
258
|
+
echo " ⚠️ Post-mortem issue required within 24h"
|
|
259
|
+
SKIP_5A_BLOCK=true
|
|
260
|
+
else
|
|
261
|
+
echo "❌ ESCAPE VALVE BLOCKED: SKIP_GATE_5A_BLOCK not allowed on main/master branch"
|
|
262
|
+
return 1
|
|
263
|
+
fi
|
|
264
|
+
fi
|
|
265
|
+
|
|
266
|
+
# --- BLOCK path: New .ts/.tsx files without corresponding tests ---
|
|
267
|
+
# Exclusions come from filter_project_paths (#649). The hand-maintained list
|
|
268
|
+
# this replaced omitted vendor/target/coverage/out, so a staged vendor/x.ts
|
|
269
|
+
# was reported as new source with no test.
|
|
270
|
+
#
|
|
271
|
+
# Byte-identical mirrors under src/npm-package/ are excluded the same way
|
|
272
|
+
# lint (#494) and Boy Scout (#649) already exclude them. A mirror cannot
|
|
273
|
+
# carry its own test: the next resync overwrites the directory, so the
|
|
274
|
+
# requirement is structurally unsatisfiable and blocked every commit that
|
|
275
|
+
# added a file to a mirrored module. The canonical source keeps its test.
|
|
276
|
+
NEW_TS_FILES=$(git diff --cached --name-only --diff-filter=A | filter_project_paths | grep -Ev "$MIRROR_PATH_FILTER" | grep -E '\.(ts|tsx)$' | grep -v '\.d\.ts$' | grep -v '__tests__' | grep -v '\.test\.' | grep -v '\.spec\.' | grep -v '__snapshots__' | grep -Ev '(^|/)vitest\.config\.' | grep -Ev '(^|/)vite\.config\.' | grep -Ev '(^|/)jest\.config\.' | grep -Ev '(^|/)tsconfig\.' | grep -Ev '(^|/)eslint\.' | grep -Ev '(^|/)prettier\.' | grep -Ev '(^|/)tailwind\.' || true)
|
|
277
|
+
|
|
278
|
+
# Strip PROJECT_SUBDIR prefix from new-TS-file paths ONLY when the hook
|
|
279
|
+
# actually cd'd into the subdirectory (IN_PROJECT_SUBDIR=1; single-language
|
|
280
|
+
# subdirectory projects). git diff returns repo-root relative paths; after
|
|
281
|
+
# cd "$PROJECT_SUBDIR" the test-pairing [ -f ] checks below need
|
|
282
|
+
# subdirectory-relative paths. When the hook stays at the repo root
|
|
283
|
+
# (multi-language projects) the paths must KEEP their prefix or every
|
|
284
|
+
# [ -f ] lookup misses and paired files are falsely BLOCKED.
|
|
285
|
+
# (Mirrors the v0.14.31+ Gate 5b fix at lines 1603-1608; Gate 5a was missing it.)
|
|
286
|
+
if [ "$IN_PROJECT_SUBDIR" = "1" ] && [ -n "$NEW_TS_FILES" ]; then
|
|
287
|
+
NEW_TS_FILES=$(echo "$NEW_TS_FILES" | sed "s|^${PROJECT_SUBDIR}/||")
|
|
288
|
+
fi
|
|
289
|
+
|
|
290
|
+
if [ -n "$NEW_TS_FILES" ]; then
|
|
291
|
+
BLOCKED_TS_FILES=0
|
|
292
|
+
for src_file in $NEW_TS_FILES; do
|
|
293
|
+
base="${src_file%.*}"
|
|
294
|
+
ext="${src_file##*.}"
|
|
295
|
+
filename="${base##*/}"
|
|
296
|
+
dir="$(dirname "$src_file")"
|
|
297
|
+
|
|
298
|
+
# Skip excluded files: index/barrel, types, interfaces, constants, declarations
|
|
299
|
+
case "$filename" in
|
|
300
|
+
index|types|interfaces|constants|__init__) continue ;;
|
|
301
|
+
esac
|
|
302
|
+
case "$ext" in
|
|
303
|
+
d.ts|pyi) continue ;;
|
|
304
|
+
esac
|
|
305
|
+
# Skip files with @no-test-required (reason >= 10 chars) or legacy @no-test annotation
|
|
306
|
+
# Order matters: @no-test-required must be checked first — @no-test is a substring match
|
|
307
|
+
if grep -q '@no-test-required' "$src_file" 2>/dev/null; then
|
|
308
|
+
if grep -qE '@no-test-required\s*:\s*.{10,}' "$src_file" 2>/dev/null; then
|
|
309
|
+
continue
|
|
310
|
+
fi
|
|
311
|
+
# @no-test-required with short reason (< 10 chars) — fall through to BLOCK
|
|
312
|
+
elif grep -q '@no-test' "$src_file" 2>/dev/null; then
|
|
313
|
+
continue
|
|
314
|
+
fi
|
|
315
|
+
|
|
316
|
+
# Check common test file patterns for TypeScript
|
|
317
|
+
TEST_FOUND=false
|
|
318
|
+
patterns=(
|
|
319
|
+
"${base}.test.${ext}"
|
|
320
|
+
"${base}.spec.${ext}"
|
|
321
|
+
"${dir}/__tests__/${filename}.test.${ext}"
|
|
322
|
+
"${dir}/__tests__/${filename}.spec.${ext}"
|
|
323
|
+
"tests/${filename}.test.${ext}"
|
|
324
|
+
"tests/${filename}.spec.${ext}"
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
for pattern in "${patterns[@]}"; do
|
|
328
|
+
if [[ "$pattern" == *'*'* ]]; then
|
|
329
|
+
found=$(find . -path "*/${pattern}" -type f 2>/dev/null | head -1)
|
|
330
|
+
if [ -n "$found" ]; then TEST_FOUND=true; break; fi
|
|
331
|
+
elif [ -f "$pattern" ]; then
|
|
332
|
+
TEST_FOUND=true
|
|
333
|
+
break
|
|
334
|
+
fi
|
|
335
|
+
done
|
|
336
|
+
|
|
337
|
+
if [ "$TEST_FOUND" = false ]; then
|
|
338
|
+
if [ "$SKIP_5A_BLOCK" = true ] || [ "$TDD_BLOCK_DOWNGRADE" = true ]; then
|
|
339
|
+
echo "⚠️ TEST PAIRING WARNING (downgraded): New TypeScript file without test: $src_file"
|
|
340
|
+
echo " Expected: ${patterns[0]}, ${patterns[1]:-...}"
|
|
341
|
+
echo " Or: Add '// @no-test-required: <reason>' if this file doesn't need tests"
|
|
342
|
+
else
|
|
343
|
+
echo "❌ BLOCKED: $src_file — New TypeScript source file without corresponding test"
|
|
344
|
+
echo " Expected: ${patterns[0]}, ${patterns[1]:-...}"
|
|
345
|
+
echo " Add '// @no-test-required: <reason>' if this file doesn't need tests"
|
|
346
|
+
BLOCKED_TS_FILES=$((BLOCKED_TS_FILES + 1))
|
|
347
|
+
fi
|
|
348
|
+
fi
|
|
349
|
+
done
|
|
350
|
+
|
|
351
|
+
if [ "$BLOCKED_TS_FILES" -gt 0 ]; then
|
|
352
|
+
echo ""
|
|
353
|
+
echo "❌ $BLOCKED_TS_FILES new TypeScript file(s) without corresponding tests — commit BLOCKED"
|
|
354
|
+
echo " Add test files or '// @no-test-required: <reason>' annotation."
|
|
355
|
+
echo " Escape valve: SKIP_GATE_5A_BLOCK=1 (non-main/master only)"
|
|
356
|
+
return 1
|
|
357
|
+
fi
|
|
358
|
+
fi
|
|
359
|
+
|
|
360
|
+
# --- WARNING path: Modified files (any lang) + New non-TS files ---
|
|
361
|
+
# filter_project_paths strips dependencies and build output (#649); without
|
|
362
|
+
# it a staged vendor/ or target/ module is reported as source needing a test.
|
|
363
|
+
WARNING_SOURCE_FILES=$(
|
|
364
|
+
{
|
|
365
|
+
git diff --cached --name-only --diff-filter=M | filter_project_paths | grep -E '\.(ts|tsx|py|go|java|kt|kts|cpp|cc|cxx|c|swift|dart|rb|rs)$' | grep -v '__tests__' | grep -v '\.test\.' | grep -v '\.spec\.' | grep -v '__snapshots__'
|
|
366
|
+
git diff --cached --name-only --diff-filter=A | filter_project_paths | grep -E '\.(py|go|java|kt|kts|cpp|cc|cxx|c|swift|dart|rb|rs)$' | grep -v '__tests__' | grep -v '\.test\.' | grep -v '\.spec\.' | grep -v '__snapshots__'
|
|
367
|
+
} | sort -u || true
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
if [ -n "$WARNING_SOURCE_FILES" ]; then
|
|
371
|
+
PAIRING_WARNINGS=0
|
|
372
|
+
for src_file in $WARNING_SOURCE_FILES; do
|
|
373
|
+
base="${src_file%.*}"
|
|
374
|
+
ext="${src_file##*.}"
|
|
375
|
+
filename="${base##*/}"
|
|
376
|
+
dir="$(dirname "$src_file")"
|
|
377
|
+
|
|
378
|
+
# Skip excluded files: index/barrel, types, interfaces, constants, declarations
|
|
379
|
+
case "$filename" in
|
|
380
|
+
index|types|interfaces|constants|__init__) continue ;;
|
|
381
|
+
esac
|
|
382
|
+
case "$ext" in
|
|
383
|
+
d.ts|pyi) continue ;;
|
|
384
|
+
esac
|
|
385
|
+
# Skip files with @no-test-required (reason >= 10 chars) or legacy @no-test annotation
|
|
386
|
+
# Order matters: @no-test-required must be checked first — @no-test is a substring match
|
|
387
|
+
if grep -q '@no-test-required' "$src_file" 2>/dev/null; then
|
|
388
|
+
if grep -qE '@no-test-required\s*:\s*.{10,}' "$src_file" 2>/dev/null; then
|
|
389
|
+
continue
|
|
390
|
+
fi
|
|
391
|
+
# @no-test-required with short reason (< 10 chars) — fall through to BLOCK
|
|
392
|
+
elif grep -q '@no-test' "$src_file" 2>/dev/null; then
|
|
393
|
+
continue
|
|
394
|
+
fi
|
|
395
|
+
|
|
396
|
+
# Check common test file patterns (language-specific)
|
|
397
|
+
TEST_FOUND=false
|
|
398
|
+
case "$ext" in
|
|
399
|
+
ts|tsx|js|jsx)
|
|
400
|
+
patterns=(
|
|
401
|
+
"${base}.test.${ext}"
|
|
402
|
+
"${base}.spec.${ext}"
|
|
403
|
+
"${dir}/__tests__/${filename}.test.${ext}"
|
|
404
|
+
"${dir}/__tests__/${filename}.spec.${ext}"
|
|
405
|
+
"tests/${filename}.test.${ext}"
|
|
406
|
+
"tests/${filename}.spec.${ext}"
|
|
407
|
+
)
|
|
408
|
+
;;
|
|
409
|
+
py)
|
|
410
|
+
patterns=(
|
|
411
|
+
"tests/${filename}_test.py"
|
|
412
|
+
"tests/test_${filename}.py"
|
|
413
|
+
"${dir}/tests/test_${filename}.py"
|
|
414
|
+
"${base}_test.py"
|
|
415
|
+
)
|
|
416
|
+
;;
|
|
417
|
+
go)
|
|
418
|
+
patterns=(
|
|
419
|
+
"${base}_test.go"
|
|
420
|
+
"${dir}/${filename}_test.go"
|
|
421
|
+
)
|
|
422
|
+
;;
|
|
423
|
+
java|kt|kts)
|
|
424
|
+
patterns=(
|
|
425
|
+
"${base}Test.${ext}"
|
|
426
|
+
"src/test/java/**/${filename}Test.${ext}"
|
|
427
|
+
"src/test/kotlin/**/${filename}Test.${ext}"
|
|
428
|
+
)
|
|
429
|
+
;;
|
|
430
|
+
cpp|cc|cxx|c)
|
|
431
|
+
patterns=(
|
|
432
|
+
"${base}_test.${ext}"
|
|
433
|
+
"${base}Test.${ext}"
|
|
434
|
+
"${dir}/test_${filename}.${ext}"
|
|
435
|
+
)
|
|
436
|
+
;;
|
|
437
|
+
swift)
|
|
438
|
+
patterns=(
|
|
439
|
+
"${base}Tests.swift"
|
|
440
|
+
"${dir}/${filename}Tests.swift"
|
|
441
|
+
)
|
|
442
|
+
;;
|
|
443
|
+
dart)
|
|
444
|
+
patterns=("${base}_test.${ext}")
|
|
445
|
+
;;
|
|
446
|
+
rb)
|
|
447
|
+
patterns=(
|
|
448
|
+
"${dir}/test_${filename}.rb"
|
|
449
|
+
"${base}_test.rb"
|
|
450
|
+
)
|
|
451
|
+
;;
|
|
452
|
+
rs)
|
|
453
|
+
# Rust tests are typically inline with #[cfg(test)]
|
|
454
|
+
continue
|
|
455
|
+
;;
|
|
456
|
+
*) continue ;;
|
|
457
|
+
esac
|
|
458
|
+
|
|
459
|
+
for pattern in "${patterns[@]}"; do
|
|
460
|
+
if [[ "$pattern" == *'*'* ]]; then
|
|
461
|
+
found=$(find . -path "*/${pattern}" -type f 2>/dev/null | head -1)
|
|
462
|
+
if [ -n "$found" ]; then TEST_FOUND=true; break; fi
|
|
463
|
+
elif [ -f "$pattern" ]; then
|
|
464
|
+
TEST_FOUND=true
|
|
465
|
+
break
|
|
466
|
+
fi
|
|
467
|
+
done
|
|
468
|
+
|
|
469
|
+
if [ "$TEST_FOUND" = false ]; then
|
|
470
|
+
echo "⚠️ TEST PAIRING WARNING: Source file without corresponding test: $src_file"
|
|
471
|
+
echo " Expected patterns for .${ext}: ${patterns[0]}, ${patterns[1]:-...}"
|
|
472
|
+
echo " Or: Add '// @no-test-required: <reason>' annotation if this file doesn't need tests"
|
|
473
|
+
PAIRING_WARNINGS=$((PAIRING_WARNINGS + 1))
|
|
474
|
+
fi
|
|
475
|
+
done
|
|
476
|
+
|
|
477
|
+
if [ "$PAIRING_WARNINGS" -gt 0 ]; then
|
|
478
|
+
echo ""
|
|
479
|
+
echo "⚠️ $PAIRING_WARNINGS source file(s) without corresponding tests"
|
|
480
|
+
echo " This is a WARNING — commit proceeds. TDD order enforced by Agent skills."
|
|
481
|
+
echo " To suppress for specific files, add '// @no-test-required: <reason>' at the top."
|
|
482
|
+
fi
|
|
483
|
+
fi
|
|
484
|
+
|
|
485
|
+
# ========================================================================
|
|
486
|
+
# Gate 5b: Mock Density ADVISORY Scan (pure bash — no npx tsx overhead)
|
|
487
|
+
# 30% = ADVISORY, 50% = suggests @mock-justified. Does NOT block commit.
|
|
488
|
+
# ========================================================================
|
|
489
|
+
CHANGED_TEST_FILES=$(printf '%s\n' "${XP_STAGED_ACM:-$(git diff --cached --name-only --diff-filter=ACM)}" | filter_project_paths | grep -E '\.(test|spec)\.(ts|tsx|js|jsx|cjs|mjs|py|go)$' || true)
|
|
490
|
+
|
|
491
|
+
# Nested plugin sub-projects (plugins/<name>/) own their own vitest config and
|
|
492
|
+
# are excluded from the root suite (`vitest.config.ts` excludes `plugins/**`,
|
|
493
|
+
# because plugins/*/node_modules contains vendored tests). Feeding their test
|
|
494
|
+
# paths to the root vitest yields "No test files found" → false BLOCK, so drop
|
|
495
|
+
# them here and let the per-plugin suite cover them (CI runs `npm test` inside
|
|
496
|
+
# each plugin directory).
|
|
497
|
+
CHANGED_TEST_FILES=$(echo "$CHANGED_TEST_FILES" | grep -vE '^plugins/[^/]+/' || true)
|
|
498
|
+
|
|
499
|
+
# Strip PROJECT_SUBDIR prefix from test file paths ONLY when the hook
|
|
500
|
+
# actually cd'd into the subdirectory (IN_PROJECT_SUBDIR=1). git diff returns
|
|
501
|
+
# repo-root relative paths; after cd "$PROJECT_SUBDIR" vitest and [ -f ]
|
|
502
|
+
# checks need subdirectory-relative paths. At the repo root (multi-language
|
|
503
|
+
# projects) stripping would silently skip the mock-density scan and feed
|
|
504
|
+
# vitest paths that do not exist. (v0.14.31+ fix, gated on the cd in v0.19.x)
|
|
505
|
+
if [ "$IN_PROJECT_SUBDIR" = "1" ] && [ -n "$CHANGED_TEST_FILES" ]; then
|
|
506
|
+
CHANGED_TEST_FILES=$(echo "$CHANGED_TEST_FILES" | sed "s|^${PROJECT_SUBDIR}/||")
|
|
507
|
+
fi
|
|
508
|
+
|
|
509
|
+
if [ -n "$CHANGED_TEST_FILES" ]; then
|
|
510
|
+
echo "Checking mock density in test files..."
|
|
511
|
+
for test_file in $CHANGED_TEST_FILES; do
|
|
512
|
+
if [ -f "$test_file" ]; then
|
|
513
|
+
# Count mock keyword references (precise patterns only)
|
|
514
|
+
MOCK_COUNT=0
|
|
515
|
+
for kw in 'jest\.mock' 'vi\.mock' 'jest\.spyOn' 'vi\.spyOn' 'jest\.fn' 'vi\.fn' \
|
|
516
|
+
'mockResolvedValue' 'mockRejectedValue' 'mockReturnValue' 'mockImplementation' \
|
|
517
|
+
'createMock' 'mockReset' 'mockClear' 'mockRestore' 'MagicMock' 'unittest\.mock' \
|
|
518
|
+
'\.patch(' 'gomock' 'mockgen' '.EXPECT()'; do
|
|
519
|
+
# Use grep -o piped to wc -l for reliable single-number output (grep -c can emit
|
|
520
|
+
# multi-line output with filenames under some grep versions, causing bash arithmetic
|
|
521
|
+
# syntax errors). grep -o extracts each match on its own line, wc -l counts them.
|
|
522
|
+
c=$(grep -o "$kw" "$test_file" 2>/dev/null | wc -l || true)
|
|
523
|
+
c=${c//[^0-9]/}
|
|
524
|
+
c=${c:-0}
|
|
525
|
+
MOCK_COUNT=$((MOCK_COUNT + c))
|
|
526
|
+
done
|
|
527
|
+
|
|
528
|
+
# Count total non-empty, non-comment lines for density denominator
|
|
529
|
+
TOTAL_LINES=$(grep -v '^\s*$' "$test_file" | grep -v '^\s*//' | grep -v '^\s*\*' | grep -v '^\s*#' | wc -l | awk '{print $1}')
|
|
530
|
+
|
|
531
|
+
if [ "$TOTAL_LINES" -gt 0 ] 2>/dev/null; then
|
|
532
|
+
MOCK_DENSITY=$(awk "BEGIN {printf \"%.1f\", ($MOCK_COUNT / $TOTAL_LINES) * 100}")
|
|
533
|
+
else
|
|
534
|
+
MOCK_DENSITY="0"
|
|
535
|
+
fi
|
|
536
|
+
|
|
537
|
+
THRESHOLD_30=$(awk "BEGIN {print ($MOCK_DENSITY > 30) ? 1 : 0}")
|
|
538
|
+
THRESHOLD_50=$(awk "BEGIN {print ($MOCK_DENSITY > 50) ? 1 : 0}")
|
|
539
|
+
|
|
540
|
+
# Check for @mock-justified annotation with reason text (min 10 chars)
|
|
541
|
+
HAS_JUSTIFIED=$(grep -qE '@mock-justified\s*:\s*.{10,}' "$test_file" 2>/dev/null && echo "true" || echo "false")
|
|
542
|
+
|
|
543
|
+
if [ "$THRESHOLD_50" = "1" ]; then
|
|
544
|
+
if [ "$HAS_JUSTIFIED" = "false" ]; then
|
|
545
|
+
echo "⚠️ MOCK DENSITY: $test_file — ${MOCK_DENSITY}% (exceeds 50%)"
|
|
546
|
+
echo " Consider: integration test with real collaborators"
|
|
547
|
+
echo " Or: Add '// @mock-justified: <reason>' (min 10 char explanation)"
|
|
548
|
+
else
|
|
549
|
+
echo "📝 MOCK DENSITY: $test_file — ${MOCK_DENSITY}% (justified)"
|
|
550
|
+
fi
|
|
551
|
+
elif [ "$THRESHOLD_30" = "1" ]; then
|
|
552
|
+
echo "ℹ️ MOCK DENSITY ADVISORY: $test_file — ${MOCK_DENSITY}% (consider reducing mocks)"
|
|
553
|
+
fi
|
|
554
|
+
fi
|
|
555
|
+
done
|
|
556
|
+
fi
|
|
557
|
+
|
|
558
|
+
# ============================================================================
|
|
559
|
+
# ============================================================================
|
|
560
|
+
# Gate 5c: Semantic Annotation Check (#585)
|
|
561
|
+
#
|
|
562
|
+
# The check itself lives in lib/gate-5c-alignment.sh so its contract is
|
|
563
|
+
# unit-testable without executing the hook. Two defects it fixes, both of which
|
|
564
|
+
# made this gate a decoration:
|
|
565
|
+
# 1. The whole body sat inside `if [ -f req-ids.json ] && command -v jq`.
|
|
566
|
+
# .sprint-state/ is gitignored, so on a fresh clone the gate printed
|
|
567
|
+
# NOTHING — not PASS, not FAIL, not SKIP — and the report had no slot for
|
|
568
|
+
# it. Silence read as success, the same defect as #449/#499/#570.
|
|
569
|
+
# 2. Test discovery matched only JS/TS, so Pester's *.Tests.ps1, pytest's
|
|
570
|
+
# test_*.py, Go's *_test.go, Java's *Test.java and Kotlin's *Tests.kt found
|
|
571
|
+
# nothing and the gate reported a vacuous "0 annotated, 0 uncovered".
|
|
572
|
+
#
|
|
573
|
+
# GATE_5C_STATUS is now always PASS, SKIP or BLOCK — never empty.
|
|
574
|
+
# ============================================================================
|
|
575
|
+
GATE_5C_STATUS=""
|
|
576
|
+
gate_5c_alignment || return 1
|
|
577
|
+
|
|
578
|
+
# ============================================================================
|
|
579
|
+
# v0.14.3+ (Issue #312): Early skip when no code files changed.
|
|
580
|
+
# If the commit only touches VERSION, CHANGELOG, docs, config, .gitignore,
|
|
581
|
+
# or similar non-code files, skip the test run entirely.
|
|
582
|
+
# Gate 5a (new file pairing) and 5b (mock density) are cheap and still run.
|
|
583
|
+
# ============================================================================
|
|
584
|
+
# #763: `cs`/`csx` were missing from this list, so a commit touching ONLY C#
|
|
585
|
+
# files produced an empty CHANGED_CODE_FILES and took the "no code files
|
|
586
|
+
# changed" early skip below -- the full test suite never ran, and the absence
|
|
587
|
+
# of a test result was reported as the absence of a need for one. The
|
|
588
|
+
# Principles extensions list got `.cs` in ac214d38; this one was left behind,
|
|
589
|
+
# which is why the C# arm looked like it worked while Gate 5 stood down.
|
|
590
|
+
CODE_EXTENSIONS="\.(ts|tsx|js|jsx|mjs|cjs|py|go|java|kt|kts|cs|csx|cpp|cc|cxx|c|h|hpp|swift|m|mm|dart|sh|ps1)$"
|
|
591
|
+
CHANGED_CODE_FILES=$(echo "$CHANGED_FILES" | grep -E "$CODE_EXTENSIONS" || true)
|
|
592
|
+
if [ -z "$CHANGED_CODE_FILES" ]; then
|
|
593
|
+
# #554: this branch DID stand down deliberately, but "PASS" is a claim that
|
|
594
|
+
# a check ran and found nothing. Nothing ran here: no test executed, no
|
|
595
|
+
# coverage number exists. Recording PASS inflated the pass rate and made an
|
|
596
|
+
# unmeasured gate indistinguishable from a measured clean one -- the same
|
|
597
|
+
# defect #554 fixed on the docs-only branch, on the branch that fix did not
|
|
598
|
+
# cover (measured on the v0.31.2.0 release commit: journal said
|
|
599
|
+
# gate5_tests.status=PASS while the summary printed "coverage: N/A%").
|
|
600
|
+
echo "⏭️ SKIPPED - No code files changed (only docs/config/VERSION) — test run not needed."
|
|
601
|
+
echo " Changed files: $(echo "$CHANGED_FILES" | tr '\n' ' ')"
|
|
602
|
+
TESTS_EXIT_CODE=0
|
|
603
|
+
TESTS_SKIPPED=true
|
|
604
|
+
GATE_5_STATUS="SKIP"
|
|
605
|
+
GATE_5_DETAIL="no_code_files_changed"
|
|
606
|
+
GATE_5_END=$(gate_start_ms)
|
|
607
|
+
GATE_5_ELAPSED=$((GATE_5_END - GATE_5_START))
|
|
608
|
+
echo " ⏱️ Gate 5: ${GATE_5_ELAPSED}ms (skipped — no code changes)"
|
|
609
|
+
else
|
|
610
|
+
|
|
611
|
+
# ============================================================================
|
|
612
|
+
# Smart test selection (Issue #286): only run tests affected by changed files.
|
|
613
|
+
# Reuses CHANGED_TEST_FILES already computed in Gate 5b (line 1244).
|
|
614
|
+
# Full run fallback: >20 changed test files, or vitest not found.
|
|
615
|
+
# ============================================================================
|
|
616
|
+
echo "Running tests..."
|
|
617
|
+
|
|
618
|
+
# Route to appropriate test runner via adapter
|
|
619
|
+
for CURRENT_LANG in $PROJECT_LANGS; do
|
|
620
|
+
ADAPTER_FILE=$(resolve_adapter_path "$CURRENT_LANG")
|
|
621
|
+
if [ "${CURRENT_LANG}" != "unknown" ] && [ -n "$ADAPTER_FILE" ]; then
|
|
622
|
+
if source "$ADAPTER_FILE" 2>/dev/null; then
|
|
623
|
+
# TypeScript: vitest with smart test selection
|
|
624
|
+
if [ "$CURRENT_LANG" = "typescript" ] && { [ -f "package.json" ] || [ -f "$PROJECT_ROOT/package.json" ]; }; then
|
|
625
|
+
# `--probe`: answer "is vitest installed HERE?" without letting npx
|
|
626
|
+
# download it. A probe that installs what it is checking for always
|
|
627
|
+
# reports success, which is how repos with no vitest ended up blocking on
|
|
628
|
+
# a downloaded one's missing @vitest/coverage-v8 (#21, dsh-aot-runner).
|
|
629
|
+
if run_without_git_context run_node_bin --probe vitest vitest/vitest.mjs --version >/dev/null 2>&1; then
|
|
630
|
+
# Count changed test files to decide strategy. `grep -c '.'` prints its
|
|
631
|
+
# own zero AND exits 1 on an empty list, so `|| echo "0"` used to yield
|
|
632
|
+
# $'0\n0' -- the same two-value bug that false-blocked Gate 8 (#493).
|
|
633
|
+
# Bundled mirrors under src/npm-package/ are excluded from the root
|
|
634
|
+
# vitest project (vitest.config.ts, #418), so selecting them makes
|
|
635
|
+
# vitest exit 1 with "No test files found" and this gate reads that as
|
|
636
|
+
# failing tests: a false BLOCK for any commit that only touches mirrors
|
|
637
|
+
# (#494). Route both lists through the selector and announce it.
|
|
638
|
+
SELECTED_TEST_FILES=$(select_root_suite_targets "$CHANGED_TEST_FILES")
|
|
639
|
+
if [ "$SELECTED_TEST_FILES" != "$CHANGED_TEST_FILES" ]; then
|
|
640
|
+
echo " ↪ Selection adjusted for bundled mirrors (#494):"
|
|
641
|
+
echo " was: $(echo "$CHANGED_TEST_FILES" | tr '\n' ' ')"
|
|
642
|
+
echo " now: $(echo "$SELECTED_TEST_FILES" | tr '\n' ' ')"
|
|
643
|
+
fi
|
|
644
|
+
CHANGED_TEST_FILE_COUNT=$(echo "$SELECTED_TEST_FILES" | grep -c '.' || true)
|
|
645
|
+
|
|
646
|
+
# Also get changed source files (non-test) for related-test lookup
|
|
647
|
+
CHANGED_SRC_FILES=$(printf '%s\n' "${XP_STAGED_ACM:-$(git diff --cached --name-only --diff-filter=ACM)}" | filter_project_paths | grep -E '\.(ts|tsx|js|jsx)$' | grep -v '\.test\.' | grep -v '\.spec\.' | grep -v '__tests__' | grep -v '\.d\.ts$' | grep -v '__snapshots__' || true)
|
|
648
|
+
# Nested plugin sub-projects are excluded from the root suite; their
|
|
649
|
+
# sources must not drive root-vitest related-test lookup either (it
|
|
650
|
+
# would resolve to plugin-local paths vitest cannot collect).
|
|
651
|
+
CHANGED_SRC_FILES=$(echo "$CHANGED_SRC_FILES" | grep -vE '^plugins/[^/]+/' || true)
|
|
652
|
+
# Mirror handling is identical for source files: their test-adjacent
|
|
653
|
+
# paths must never reach vitest as root-project targets (#494).
|
|
654
|
+
# Selection runs on repo-root relative paths (git diff output), before
|
|
655
|
+
# any PROJECT_SUBDIR stripping, so the bundled-mirror prefixes match.
|
|
656
|
+
SELECTED_SRC_FILES=$(select_root_suite_targets "$CHANGED_SRC_FILES")
|
|
657
|
+
if [ "$SELECTED_SRC_FILES" != "$CHANGED_SRC_FILES" ]; then
|
|
658
|
+
echo " ↪ Source selection adjusted for bundled mirrors (#494):"
|
|
659
|
+
echo " was: $(echo "$CHANGED_SRC_FILES" | tr '\n' ' ')"
|
|
660
|
+
echo " now: $(echo "$SELECTED_SRC_FILES" | tr '\n' ' ')"
|
|
661
|
+
fi
|
|
662
|
+
# Strip PROJECT_SUBDIR prefix ONLY when the hook cd'd into the
|
|
663
|
+
# subdirectory (IN_PROJECT_SUBDIR=1; same gate as the CHANGED_TEST_FILES
|
|
664
|
+
# fix above — at the repo root the paths must stay root-relative or the
|
|
665
|
+
# related-test lookup and vitest targets resolve against the wrong dir,
|
|
666
|
+
# #470)
|
|
667
|
+
if [ "$IN_PROJECT_SUBDIR" = "1" ] && [ -n "$SELECTED_SRC_FILES" ]; then
|
|
668
|
+
SELECTED_SRC_FILES=$(echo "$SELECTED_SRC_FILES" | sed "s|^${PROJECT_SUBDIR}/||")
|
|
669
|
+
fi
|
|
670
|
+
CHANGED_SRC_COUNT=$(echo "$SELECTED_SRC_FILES" | grep -c '.' || true)
|
|
671
|
+
|
|
672
|
+
# Decide strategy
|
|
673
|
+
if [ "$CHANGED_TEST_FILE_COUNT" -gt 20 ] 2>/dev/null; then
|
|
674
|
+
# Too many test files changed → full run
|
|
675
|
+
echo "Too many test files changed ($CHANGED_TEST_FILE_COUNT), running full test suite..."
|
|
676
|
+
TESTS_OUTPUT=$(run_without_git_context run_node_bin vitest vitest/vitest.mjs run --coverage 2>&1)
|
|
677
|
+
TESTS_EXIT_CODE=$?
|
|
678
|
+
echo "$TESTS_OUTPUT" | head -60
|
|
679
|
+
if [ "$TESTS_EXIT_CODE" -ne 0 ]; then
|
|
680
|
+
handle_test_failure "$TESTS_OUTPUT" "full test suite" || return 1
|
|
681
|
+
else
|
|
682
|
+
echo "✅ PASSED - Full test suite passed (with coverage)."
|
|
683
|
+
TESTS_RAN_ANY=true
|
|
684
|
+
fi
|
|
685
|
+
elif [ "$CHANGED_TEST_FILE_COUNT" -gt 0 ] 2>/dev/null; then
|
|
686
|
+
# Run only changed test files with coverage
|
|
687
|
+
PARTIAL_TEST_RUN=true # Mark as partial run for coverage check
|
|
688
|
+
SMART_TARGETS=$(echo "$SELECTED_TEST_FILES" | tr '\n' ' ')
|
|
689
|
+
echo "Running ${CHANGED_TEST_FILE_COUNT} changed test file(s) with coverage..."
|
|
690
|
+
echo " Target(s): $(echo "$SELECTED_TEST_FILES" | tr '\n' ' ')"
|
|
691
|
+
TESTS_OUTPUT=$(run_without_git_context run_node_bin vitest vitest/vitest.mjs run --coverage $SMART_TARGETS 2>&1)
|
|
692
|
+
TESTS_EXIT_CODE=$?
|
|
693
|
+
echo "$TESTS_OUTPUT" | head -60
|
|
694
|
+
if [ "$TESTS_EXIT_CODE" -ne 0 ]; then
|
|
695
|
+
# Distinguish a real test failure from a runner infrastructure
|
|
696
|
+
# error -- see #454. handle_test_failure routes both cases and
|
|
697
|
+
# keeps the message consistent across every Gate 5 branch.
|
|
698
|
+
handle_test_failure "$TESTS_OUTPUT" "changed test files" || return 1
|
|
699
|
+
else
|
|
700
|
+
echo "✅ PASSED - Changed test files passed (with coverage)."
|
|
701
|
+
TESTS_RAN_ANY=true
|
|
702
|
+
fi
|
|
703
|
+
elif [ "$CHANGED_SRC_COUNT" -gt 0 ] 2>/dev/null; then
|
|
704
|
+
# Source files changed but no test files → find related tests or run full
|
|
705
|
+
echo "Source file(s) changed, finding related tests..."
|
|
706
|
+
RELATED_TESTS=""
|
|
707
|
+
for src_file in $SELECTED_SRC_FILES; do
|
|
708
|
+
base="${src_file%.*}"
|
|
709
|
+
filename="${base##*/}"
|
|
710
|
+
dir="$(dirname "$src_file")"
|
|
711
|
+
ext="${src_file##*.}"
|
|
712
|
+
# Try common test file patterns
|
|
713
|
+
for pattern in \
|
|
714
|
+
"${base}.test.${ext}" \
|
|
715
|
+
"${base}.spec.${ext}" \
|
|
716
|
+
"${dir}/__tests__/${filename}.test.${ext}" \
|
|
717
|
+
"${dir}/__tests__/${filename}.spec.${ext}" \
|
|
718
|
+
"tests/${filename}.test.${ext}" \
|
|
719
|
+
"tests/${filename}.spec.${ext}"; do
|
|
720
|
+
if [ -f "$pattern" ]; then
|
|
721
|
+
RELATED_TESTS="${RELATED_TESTS}${pattern} "
|
|
722
|
+
fi
|
|
723
|
+
done
|
|
724
|
+
# Glob fallback for __tests__ dir patterns
|
|
725
|
+
if [ -d "${dir}/__tests__" ]; then
|
|
726
|
+
found_glob=$(find "${dir}/__tests__" -maxdepth 1 -name "${filename}.test.*" -o -name "${filename}.spec.*" 2>/dev/null | tr '\n' ' ')
|
|
727
|
+
if [ -n "$found_glob" ]; then
|
|
728
|
+
for f in $found_glob; do
|
|
729
|
+
case " $RELATED_TESTS " in *" $f "*) ;; *) RELATED_TESTS="${RELATED_TESTS}${f} " ;; esac
|
|
730
|
+
done
|
|
731
|
+
fi
|
|
732
|
+
fi
|
|
733
|
+
done
|
|
734
|
+
if [ -n "$RELATED_TESTS" ]; then
|
|
735
|
+
echo " Found related test(s): $(echo "$RELATED_TESTS" | tr '\n' ' ')"
|
|
736
|
+
PARTIAL_TEST_RUN=true # Mark as partial run for coverage check
|
|
737
|
+
TESTS_OUTPUT=$(run_without_git_context run_node_bin vitest vitest/vitest.mjs run --coverage $RELATED_TESTS 2>&1)
|
|
738
|
+
TESTS_EXIT_CODE=$?
|
|
739
|
+
echo "$TESTS_OUTPUT" | head -60
|
|
740
|
+
if [ "$TESTS_EXIT_CODE" -ne 0 ]; then
|
|
741
|
+
handle_test_failure "$TESTS_OUTPUT" "related test files" || return 1
|
|
742
|
+
else
|
|
743
|
+
echo "✅ PASSED - Related test files passed (with coverage)."
|
|
744
|
+
TESTS_RAN_ANY=true
|
|
745
|
+
fi
|
|
746
|
+
else
|
|
747
|
+
# No related tests found → full run is safest
|
|
748
|
+
echo " No related test files found, running full test suite..."
|
|
749
|
+
TESTS_OUTPUT=$(run_without_git_context run_node_bin vitest vitest/vitest.mjs run --coverage 2>&1)
|
|
750
|
+
TESTS_EXIT_CODE=$?
|
|
751
|
+
echo "$TESTS_OUTPUT" | head -60
|
|
752
|
+
if [ "$TESTS_EXIT_CODE" -ne 0 ]; then
|
|
753
|
+
handle_test_failure "$TESTS_OUTPUT" "full test suite" || return 1
|
|
754
|
+
else
|
|
755
|
+
echo "✅ PASSED - Full test suite passed (with coverage)."
|
|
756
|
+
TESTS_RAN_ANY=true
|
|
757
|
+
fi
|
|
758
|
+
fi
|
|
759
|
+
else
|
|
760
|
+
# No test files AND no source files changed → skip
|
|
761
|
+
echo "✅ PASSED - No test or source files changed, skipping test run."
|
|
762
|
+
TESTS_EXIT_CODE=0
|
|
763
|
+
TESTS_SKIPPED=true
|
|
764
|
+
fi
|
|
765
|
+
else
|
|
766
|
+
# Fallback: run_tests without coverage
|
|
767
|
+
TESTS_OUTPUT=$(run_without_git_context run_tests 2>&1)
|
|
768
|
+
TESTS_EXIT_CODE=$?
|
|
769
|
+
echo "$TESTS_OUTPUT" | head -50
|
|
770
|
+
# No runner installed is a SKIP, not a pass. The adapter returns 0 in
|
|
771
|
+
# that case (it measured nothing), so the exit code alone cannot tell
|
|
772
|
+
# "all tests passed" from "no tests could run". Without this, the
|
|
773
|
+
# coverage arm further down finds no report and blocks with
|
|
774
|
+
# "coverage/coverage-summary.json not found" -- blaming a missing
|
|
775
|
+
# artifact for a runner that was never installed (dsh-aot-runner #21).
|
|
776
|
+
if [ "$TESTS_EXIT_CODE" -eq 0 ] && printf '%s' "$TESTS_OUTPUT" | grep -q "No test runner installed locally"; then
|
|
777
|
+
TESTS_SKIPPED=true
|
|
778
|
+
fi
|
|
779
|
+
if [ "$TESTS_EXIT_CODE" -ne 0 ]; then
|
|
780
|
+
# This branch is reached from the typescript adapter, so run_tests ran
|
|
781
|
+
# vitest (adapters/typescript.sh) and its output is vitest-shaped: the
|
|
782
|
+
# same three non-failure exits (#454 runner EPERM, #473 partial
|
|
783
|
+
# threshold, #498 no test files) apply here as in the four branches
|
|
784
|
+
# above. #454 left it unguarded because its own comment covers the
|
|
785
|
+
# NON-typescript fallback below, whose runner is pytest/go/jest; this
|
|
786
|
+
# one is not that branch.
|
|
787
|
+
handle_test_failure "$TESTS_OUTPUT" "typescript adapter fallback" || return 1
|
|
788
|
+
fi
|
|
789
|
+
fi
|
|
790
|
+
else
|
|
791
|
+
# Adapter test flow for everything the TypeScript branch above did not
|
|
792
|
+
# claim. The label this branch carried (#454) was "Non-TypeScript", which
|
|
793
|
+
# is not what reaches it: a TypeScript project without a package.json also
|
|
794
|
+
# lands here, and its adapter runs vitest — which is how a test-less TS
|
|
795
|
+
# repo got false-blocked on "No test files found" (#498).
|
|
796
|
+
#
|
|
797
|
+
# #798 / #794: whether the coverage section below will already run (and
|
|
798
|
+
# therefore validate) this suite is now an ADAPTER declaration, not a
|
|
799
|
+
# language name. The old code was:
|
|
800
|
+
#
|
|
801
|
+
# if [ "$CURRENT_LANG" = "python" ]; then ...defer...
|
|
802
|
+
#
|
|
803
|
+
# Python had been patched by hand once (#794's 2d23fe89) because its
|
|
804
|
+
# coverage run subsumes the test run; csharp/go/java/kotlin/dart/swift
|
|
805
|
+
# have exactly the same property and kept running the suite twice. The
|
|
806
|
+
# language-name check could only ever cover the languages someone
|
|
807
|
+
# remembered to add. `coverage_runs_tests` asks the adapter, which is the
|
|
808
|
+
# component that actually knows its toolchain.
|
|
809
|
+
#
|
|
810
|
+
# Default is deliberately the SAFE side: an adapter that does not
|
|
811
|
+
# declare it runs the tests here as well. Double-running costs time; not
|
|
812
|
+
# running them would cost verification, and #794's precedent is that the
|
|
813
|
+
# slower mistake is the acceptable one for an undeclared adapter.
|
|
814
|
+
if adapter_declares_coverage_runs_tests; then
|
|
815
|
+
echo "ℹ️ ${CURRENT_LANG}: coverage run includes the tests — deferring test execution to a single pass."
|
|
816
|
+
TESTS_DEFERRED=true
|
|
817
|
+
else
|
|
818
|
+
TESTS_OUTPUT=$(run_without_git_context run_tests 2>&1)
|
|
819
|
+
TESTS_EXIT_CODE=$?
|
|
820
|
+
echo "$TESTS_OUTPUT" | head -50
|
|
821
|
+
if [ "$TESTS_EXIT_CODE" -ne 0 ]; then
|
|
822
|
+
if [ "$CURRENT_LANG" = "typescript" ]; then
|
|
823
|
+
# vitest output, so the same three non-failure exits are judged
|
|
824
|
+
# here as in the branches above (#454, #473, #498).
|
|
825
|
+
handle_test_failure "$TESTS_OUTPUT" "typescript adapter (no package.json)" || return 1
|
|
826
|
+
else
|
|
827
|
+
# Genuinely non-vitest runners (pytest/go/jest/...): their output
|
|
828
|
+
# shape is not vitest's, so the guard could excuse a real failure.
|
|
829
|
+
# They keep blocking on any non-zero exit (#454).
|
|
830
|
+
echo ""
|
|
831
|
+
echo "❌ BLOCKED - Tests FAILED"
|
|
832
|
+
return 1
|
|
833
|
+
fi
|
|
834
|
+
else
|
|
835
|
+
# Same distinction as the branch above: the adapter returns 0 both for
|
|
836
|
+
# "tests passed" and for "no runner installed", so the output is the
|
|
837
|
+
# only evidence of which one happened. Setting TESTS_RAN_ANY here
|
|
838
|
+
# unconditionally would claim a measurement that never took place.
|
|
839
|
+
if printf '%s' "$TESTS_OUTPUT" | grep -q "No test runner installed locally"; then
|
|
840
|
+
TESTS_SKIPPED=true
|
|
841
|
+
else
|
|
842
|
+
echo "✅ PASSED - Unit tests passed."
|
|
843
|
+
# #760: a runner really executed for this language, so the coverage
|
|
844
|
+
# guard below must not treat this pass as "nothing was measured".
|
|
845
|
+
TESTS_RAN_ANY=true
|
|
846
|
+
fi
|
|
847
|
+
fi
|
|
848
|
+
fi
|
|
849
|
+
fi
|
|
850
|
+
else
|
|
851
|
+
echo "✅ PASSED - Could not source ${CURRENT_LANG} adapter for tests, assuming none to run."
|
|
852
|
+
fi
|
|
853
|
+
else
|
|
854
|
+
echo "✅ PASSED - No ${CURRENT_LANG} adapter found for tests, assuming none to run."
|
|
855
|
+
fi
|
|
856
|
+
done # end for CURRENT_LANG
|
|
857
|
+
|
|
858
|
+
fi # End: if [ -n "$CHANGED_CODE_FILES" ] (Issue #312 early skip)
|
|
859
|
+
|
|
860
|
+
# Next, run coverage check (skip if tests were skipped — Issue #312)
|
|
861
|
+
#
|
|
862
|
+
# #760: TESTS_SKIPPED is one global flag written inside the per-language test
|
|
863
|
+
# loop, but it is read HERE, outside that loop. A project that resolves to
|
|
864
|
+
# several languages therefore had its coverage check cancelled by whichever
|
|
865
|
+
# language stood down first -- and the loop order is the detection order, not
|
|
866
|
+
# a statement about which language matters.
|
|
867
|
+
#
|
|
868
|
+
# Measured on a real repo (.xp-gate-config.json -> typescript, shell, csharp):
|
|
869
|
+
# the typescript arm found no changed .ts file, set TESTS_SKIPPED=true, and the
|
|
870
|
+
# csharp arm's dotnet test result (139 passing, full coverage data present) was
|
|
871
|
+
# then discarded with "Test run was skipped — skipping coverage check". Gate 5
|
|
872
|
+
# reported a PASS on a coverage floor it never evaluated.
|
|
873
|
+
#
|
|
874
|
+
# The flag now only speaks for language selection that produced nothing at all:
|
|
875
|
+
# if any language actually RAN tests, coverage is evaluated for every language
|
|
876
|
+
# that has an adapter. Languages that ran nothing fall through to their own
|
|
877
|
+
# adapter's coverage branch, which already distinguishes "no evidence" (a
|
|
878
|
+
# documented failure) from "not applicable" (iac).
|
|
879
|
+
if [ "${TESTS_SKIPPED:-false}" = "true" ] && [ "${TESTS_RAN_ANY:-false}" != "true" ]; then
|
|
880
|
+
echo "ℹ️ Test run was skipped — skipping coverage check."
|
|
881
|
+
else
|
|
882
|
+
echo "Running coverage check..."
|
|
883
|
+
|
|
884
|
+
# Major-2 (Delphi): COV_EXIT aggregates coverage-run failures across ALL
|
|
885
|
+
# languages in Stage 1. It starts at 0 and each language branch ORs its own
|
|
886
|
+
# result in (`COV_EXIT=$((COV_EXIT || $?))`), so a later language's success
|
|
887
|
+
# can never mask an earlier language's subset-run failure. Previously every
|
|
888
|
+
# branch overwrote COV_EXIT and the last language's status won.
|
|
889
|
+
COV_EXIT=0
|
|
890
|
+
|
|
891
|
+
for CURRENT_LANG in $PROJECT_LANGS; do
|
|
892
|
+
ADAPTER_FILE=$(resolve_adapter_path "$CURRENT_LANG")
|
|
893
|
+
if [ "${CURRENT_LANG}" != "unknown" ] && [ -n "$ADAPTER_FILE" ]; then
|
|
894
|
+
if source "$ADAPTER_FILE" 2>/dev/null; then
|
|
895
|
+
case "$CURRENT_LANG" in
|
|
896
|
+
"typescript")
|
|
897
|
+
# Coverage collected during the test section above.
|
|
898
|
+
# Smart selection (Issue #286): only runs changed/related tests with --coverage,
|
|
899
|
+
# producing coverage/coverage-summary.json for the tested subset.
|
|
900
|
+
# Stage 2 enforcement reads global coverage from the subset run.
|
|
901
|
+
# #798: this used to echo "Test run was skipped — skipping coverage
|
|
902
|
+
# check." — the SAME sentence the outer guard above uses for the case
|
|
903
|
+
# where coverage really is skipped. Here nothing is skipped: this arm
|
|
904
|
+
# only records that there is no TypeScript coverage to evaluate, and
|
|
905
|
+
# the loop then continues to the next language (which is where
|
|
906
|
+
# #798's csharp run kept going and re-ran the suite for 28s after
|
|
907
|
+
# this line had already announced a skip). A message that describes
|
|
908
|
+
# the outer decision while sitting inside an inner branch is how the
|
|
909
|
+
# same output line appeared twice with two different meanings.
|
|
910
|
+
if [ "${TESTS_SKIPPED:-false}" = "true" ]; then
|
|
911
|
+
echo "ℹ️ No TypeScript tests were selected — no TS coverage to evaluate."
|
|
912
|
+
COV_EXIT=$((COV_EXIT || 0))
|
|
913
|
+
elif [ -f "coverage/coverage-summary.json" ]; then
|
|
914
|
+
echo "TypeScript coverage collected during test run."
|
|
915
|
+
COV_EXIT=$((COV_EXIT || 0))
|
|
916
|
+
else
|
|
917
|
+
echo "ℹ️ No coverage data produced — test run was skipped (no TS changes)."
|
|
918
|
+
COV_EXIT=$((COV_EXIT || 0))
|
|
919
|
+
fi
|
|
920
|
+
;;
|
|
921
|
+
"python")
|
|
922
|
+
if command -v pytest &> /dev/null && command -v coverage &> /dev/null; then
|
|
923
|
+
# Issue #45 (merged in #514, replacing a machine-side hotfix that
|
|
924
|
+
# kept drifting out of the repo — the exact class #514 exists to
|
|
925
|
+
# kill). BOTH the scope and the threshold must come from the
|
|
926
|
+
# target repo's pyproject.toml ([tool.coverage.run] source,
|
|
927
|
+
# [tool.coverage.report] fail_under — e.g. source=["src"],
|
|
928
|
+
# fail_under=82): a hardcoded `--cov=. --cov-fail-under=80` counts
|
|
929
|
+
# tests/ into the denominator and produced a measured 76.49%
|
|
930
|
+
# false-red BLOCKED. tomllib first; a repo declaring neither gets
|
|
931
|
+
# the historical `--cov=. --cov-fail-under=80` behavior verbatim.
|
|
932
|
+
PY_COV_SOURCE=$(python -c "import tomllib;print(' '.join('--cov='+s for s in tomllib.load(open('pyproject.toml','rb'))['tool']['coverage']['run'].get('source',[])))" 2>/dev/null || echo "")
|
|
933
|
+
PY_COV_FAIL_UNDER=$(python -c "import tomllib;print(tomllib.load(open('pyproject.toml','rb'))['tool']['coverage']['report']['fail_under'])" 2>/dev/null || echo "")
|
|
934
|
+
if [ -z "$PY_COV_FAIL_UNDER" ]; then
|
|
935
|
+
PY_COV_FAIL_UNDER=$(grep -oE 'fail_under *= *[0-9]+' pyproject.toml 2>/dev/null | grep -oE '[0-9]+' | head -1)
|
|
936
|
+
fi
|
|
937
|
+
[ -z "$PY_COV_SOURCE" ] && PY_COV_SOURCE="--cov=."
|
|
938
|
+
[ -z "$PY_COV_FAIL_UNDER" ] && PY_COV_FAIL_UNDER=80
|
|
939
|
+
|
|
940
|
+
# ── #399: smart test selection, the Python counterpart of #286 ──
|
|
941
|
+
# Three tiers (lib/python-test-selection.sh holds the pure
|
|
942
|
+
# decision logic + related-test lookup, unit-tested separately):
|
|
943
|
+
# changed-tests / related -> run ONLY those targets, with the
|
|
944
|
+
# repo's coverage SOURCE but WITHOUT the global fail_under
|
|
945
|
+
# (subset coverage is meaningless globally). The run is marked
|
|
946
|
+
# partial so Stage 2 warns instead of falsely blocking.
|
|
947
|
+
# full -> unchanged behavior: whole suite + real threshold.
|
|
948
|
+
# skip -> nothing test-relevant changed; no pytest at all.
|
|
949
|
+
PY_CHANGED_TEST_FILES=$(printf '%s\n' "${XP_STAGED_ACM:-$(git diff --cached --name-only --diff-filter=ACM 2>/dev/null)}" \
|
|
950
|
+
| filter_project_paths \
|
|
951
|
+
| grep -E '(^|/)test_[^/]*\.py$|_test\.py$' || true)
|
|
952
|
+
PY_CHANGED_SRC_FILES=$(printf '%s\n' "${XP_STAGED_ACM:-$(git diff --cached --name-only --diff-filter=ACM 2>/dev/null)}" \
|
|
953
|
+
| filter_project_paths \
|
|
954
|
+
| grep -E '\.py$' | grep -vE '(^|/)test_[^/]*\.py$|_test\.py$' || true)
|
|
955
|
+
# NOT filtered on purpose: this list answers "did a requirements
|
|
956
|
+
# file change", which is a property of the whole commit including
|
|
957
|
+
# paths under a vendor/ tree that filter_project_paths removes.
|
|
958
|
+
PY_CHANGED_ALL="${XP_STAGED_ACM:-$(git diff --cached --name-only --diff-filter=ACM 2>/dev/null || true)}"
|
|
959
|
+
# `grep -c '.'` prints its own zero AND exits 1 on an empty list
|
|
960
|
+
# (#493), so the count is derived with `|| true` + wc -l instead.
|
|
961
|
+
PY_TEST_COUNT=$(printf '%s\n' "$PY_CHANGED_TEST_FILES" | grep -c '.' || true)
|
|
962
|
+
PY_SRC_COUNT=$(printf '%s\n' "$PY_CHANGED_SRC_FILES" | grep -c '.' || true)
|
|
963
|
+
PY_DEPS_CHANGED=0
|
|
964
|
+
if python_dependency_changed $PY_CHANGED_ALL; then PY_DEPS_CHANGED=1; fi
|
|
965
|
+
PY_STRATEGY=$(select_python_test_strategy "$PY_TEST_COUNT" "$PY_SRC_COUNT" "$PY_DEPS_CHANGED")
|
|
966
|
+
|
|
967
|
+
# xdist parallel args (#516) — empty + warning when unavailable,
|
|
968
|
+
# never a BLOCK; unquoted expansion is the multi-word arg list.
|
|
969
|
+
PY_XDIST_ARGS=$(python_xdist_args 2>/dev/null || true)
|
|
970
|
+
|
|
971
|
+
if [ "$PY_STRATEGY" = "skip" ]; then
|
|
972
|
+
echo "ℹ️ Python: no test/source changes — skipping test run (#399)."
|
|
973
|
+
# Critical-1 (#399): mark the run skipped so Stage 2's
|
|
974
|
+
# enforce_python_coverage refuses to consume a stale .coverage
|
|
975
|
+
# left by a prior subset run. Without this flag the gate read the
|
|
976
|
+
# leftover low-% file and BLOCKED a docs-only commit that changed
|
|
977
|
+
# no Python. Mirrors the TS branch's TESTS_SKIPPED guard.
|
|
978
|
+
PY_TEST_SKIPPED=true
|
|
979
|
+
COV_EXIT=$((COV_EXIT || 0))
|
|
980
|
+
elif [ "$PY_STRATEGY" = "full" ]; then
|
|
981
|
+
if [ "$PY_DEPS_CHANGED" = "1" ]; then
|
|
982
|
+
echo "ℹ️ Python: dependency manifest changed — running FULL suite (#399)."
|
|
983
|
+
elif [ "$PY_TEST_COUNT" -gt 20 ] 2>/dev/null; then
|
|
984
|
+
echo "ℹ️ Python: $PY_TEST_COUNT changed test files (>20) — running FULL suite (#399)."
|
|
985
|
+
fi
|
|
986
|
+
# shellcheck disable=SC2086
|
|
987
|
+
pytest $PY_XDIST_ARGS $PY_COV_SOURCE --cov-fail-under="$PY_COV_FAIL_UNDER" --tb=short
|
|
988
|
+
COV_EXIT=$((COV_EXIT || $?))
|
|
989
|
+
else
|
|
990
|
+
# changed-tests | related → resolve the exact targets.
|
|
991
|
+
PY_TARGETS=""
|
|
992
|
+
if [ "$PY_STRATEGY" = "changed-tests" ]; then
|
|
993
|
+
PY_TARGETS="$PY_CHANGED_TEST_FILES"
|
|
994
|
+
else
|
|
995
|
+
for _py_src in $PY_CHANGED_SRC_FILES; do
|
|
996
|
+
_py_related=$(python_related_tests "$_py_src")
|
|
997
|
+
if [ -n "$_py_related" ]; then
|
|
998
|
+
PY_TARGETS="${PY_TARGETS}${_py_related}
|
|
999
|
+
"
|
|
1000
|
+
fi
|
|
1001
|
+
done
|
|
1002
|
+
PY_TARGETS=$(printf '%s\n' "$PY_TARGETS" | grep -v '^$' | sort -u)
|
|
1003
|
+
fi
|
|
1004
|
+
|
|
1005
|
+
if [ -z "$PY_TARGETS" ]; then
|
|
1006
|
+
# related lookup found nothing → tier 3 full run is safest.
|
|
1007
|
+
echo "ℹ️ Python: no related tests found for changed sources — running FULL suite (#399)."
|
|
1008
|
+
# shellcheck disable=SC2086
|
|
1009
|
+
pytest $PY_XDIST_ARGS $PY_COV_SOURCE --cov-fail-under="$PY_COV_FAIL_UNDER" --tb=short
|
|
1010
|
+
COV_EXIT=$((COV_EXIT || $?))
|
|
1011
|
+
else
|
|
1012
|
+
PY_TARGET_COUNT=$(printf '%s\n' "$PY_TARGETS" | grep -c '.' || true)
|
|
1013
|
+
echo "ℹ️ Python: selective run ($PY_STRATEGY) — $PY_TARGET_COUNT target(s):"
|
|
1014
|
+
printf '%s\n' "$PY_TARGETS" | sed 's/^/ /'
|
|
1015
|
+
# Subset run: keep --cov so data is collected, but the global
|
|
1016
|
+
# threshold must be actively DISABLED, not merely omitted.
|
|
1017
|
+
# Omitting --cov-fail-under does not work (#556): pytest-cov
|
|
1018
|
+
# reads fail_under from pyproject on its own, so the floor
|
|
1019
|
+
# stayed in force, a selective run at 23% exited 1, and the
|
|
1020
|
+
# exit was escalated to a hard BLOCK -- printing "Partial
|
|
1021
|
+
# coverage ... not full suite" immediately above "BLOCKED -
|
|
1022
|
+
# Coverage check FAILED". --cov-fail-under=0 is the documented
|
|
1023
|
+
# way to switch it off for one invocation.
|
|
1024
|
+
PARTIAL_TEST_RUN=true
|
|
1025
|
+
# shellcheck disable=SC2086
|
|
1026
|
+
pytest $PY_XDIST_ARGS $PY_COV_SOURCE --cov-fail-under=0 --tb=short $PY_TARGETS
|
|
1027
|
+
COV_EXIT=$((COV_EXIT || $?))
|
|
1028
|
+
fi
|
|
1029
|
+
fi
|
|
1030
|
+
else
|
|
1031
|
+
echo "pytest/coverage not available, running coverage via adapter..."
|
|
1032
|
+
run_coverage_output=$(run_coverage 2>&1)
|
|
1033
|
+
COV_EXIT=$((COV_EXIT || $?))
|
|
1034
|
+
echo "$run_coverage_output" | head -30
|
|
1035
|
+
fi
|
|
1036
|
+
;;
|
|
1037
|
+
"go")
|
|
1038
|
+
if command -v go &> /dev/null; then
|
|
1039
|
+
go test -coverprofile=coverage.out ./... 2>/dev/null
|
|
1040
|
+
TOTAL_COVERAGE=$(go tool cover -func=coverage.out 2>/dev/null | grep "^total:" | awk '{print substr($3, 1, length($3)-1)}')
|
|
1041
|
+
if [ -n "$TOTAL_COVERAGE" ] && (( $(echo "$TOTAL_COVERAGE < 80" | bc -l 2>/dev/null || echo "0") )); then
|
|
1042
|
+
echo "❌ BLOCKED - Go coverage $TOTAL_COVERAGE% below ${COVERAGE_THRESHOLD:-80}% threshold"
|
|
1043
|
+
return 1
|
|
1044
|
+
fi
|
|
1045
|
+
echo "Go coverage: $TOTAL_COVERAGE%"
|
|
1046
|
+
COV_EXIT=$((COV_EXIT || 0))
|
|
1047
|
+
fi
|
|
1048
|
+
;;
|
|
1049
|
+
"shell")
|
|
1050
|
+
shell_cov_output=$(run_coverage 2>&1)
|
|
1051
|
+
COV_EXIT=$((COV_EXIT || $?))
|
|
1052
|
+
echo "$shell_cov_output" | head -10
|
|
1053
|
+
echo "ℹ️ Shell coverage not typically measured"
|
|
1054
|
+
;;
|
|
1055
|
+
*)
|
|
1056
|
+
# #640: hand the staged set to the adapter. Java's run_coverage uses it
|
|
1057
|
+
# for three-tier smart selection (changed-tests -> related -> full);
|
|
1058
|
+
# without it the adapter deliberately runs the full suite rather than
|
|
1059
|
+
# guessing, so this export failing closed is safe.
|
|
1060
|
+
# Colon-separated: newlines do not survive every adapter's word
|
|
1061
|
+
# splitting, and paths with spaces stay intact inside the value.
|
|
1062
|
+
GATE_CHANGED_FILES=$(printf '%s' "$CHANGED_FILES" | tr '\n' ':')
|
|
1063
|
+
export GATE_CHANGED_FILES
|
|
1064
|
+
# The adapter runs inside $(...), so it cannot set PARTIAL_TEST_RUN
|
|
1065
|
+
# for us. It writes the chosen strategy to this file and we raise the
|
|
1066
|
+
# flag here, in the shell that later reads it. Without this a Java
|
|
1067
|
+
# subset run under 80% coverage would take the hard-BLOCK branch
|
|
1068
|
+
# instead of the WARN branch, exactly the bug #556 fixed for Python.
|
|
1069
|
+
_java_partial_file=$(mktemp 2>/dev/null || echo "")
|
|
1070
|
+
if [ -n "$_java_partial_file" ]; then
|
|
1071
|
+
export XP_GATE_PARTIAL_RUN_FILE="$_java_partial_file"
|
|
1072
|
+
fi
|
|
1073
|
+
default_cov_output=$(run_coverage 2>&1)
|
|
1074
|
+
COV_EXIT=$((COV_EXIT || $?))
|
|
1075
|
+
echo "$default_cov_output" | head -30
|
|
1076
|
+
unset XP_GATE_PARTIAL_RUN_FILE GATE_CHANGED_FILES
|
|
1077
|
+
if [ -n "$_java_partial_file" ]; then
|
|
1078
|
+
if [ -s "$_java_partial_file" ]; then
|
|
1079
|
+
PARTIAL_TEST_RUN=true
|
|
1080
|
+
fi
|
|
1081
|
+
rm -f "$_java_partial_file" 2>/dev/null || true
|
|
1082
|
+
fi
|
|
1083
|
+
;;
|
|
1084
|
+
esac
|
|
1085
|
+
else
|
|
1086
|
+
# Adapter source failed — warn and let Stage 2 attempt file-based enforcement
|
|
1087
|
+
echo "⚠️ Could not source ${CURRENT_LANG} adapter from ${ADAPTER_FILE}, will check coverage files directly..."
|
|
1088
|
+
COV_EXIT=$((COV_EXIT || 0))
|
|
1089
|
+
fi
|
|
1090
|
+
else
|
|
1091
|
+
# No adapter available — warn and let Stage 2 attempt file-based enforcement
|
|
1092
|
+
echo "⚠️ No adapter found for ${CURRENT_LANG} (searched: ${ADAPTER_DIR}/, ${ADAPTER_DIR}/adapters/, ${PROJECT_GITHOOKS}/adapters/, ${SCRIPT_DIR}/adapters/) — will check coverage files directly..."
|
|
1093
|
+
COV_EXIT=$((COV_EXIT || 0))
|
|
1094
|
+
fi
|
|
1095
|
+
done # end for CURRENT_LANG (Stage 1 coverage)
|
|
1096
|
+
|
|
1097
|
+
# ============================================================================
|
|
1098
|
+
# Stage 2: UNCONDITIONAL coverage percentage enforcement
|
|
1099
|
+
# Always attempt to parse coverage from available sources. If percentage
|
|
1100
|
+
# can be determined and is < 80% → BLOCK. If no data found → warn.
|
|
1101
|
+
#
|
|
1102
|
+
# NOTE: When only a subset of test files were run (smart selection, Issue #286),
|
|
1103
|
+
# coverage data reflects only the tested subset. In that case we warn but don't
|
|
1104
|
+
# block, because the full suite coverage may be ≥80% even though the subset
|
|
1105
|
+
# coverage is lower.
|
|
1106
|
+
# ============================================================================
|
|
1107
|
+
COVERAGE_ENFORCED=false
|
|
1108
|
+
|
|
1109
|
+
for CURRENT_LANG in $PROJECT_LANGS; do
|
|
1110
|
+
# #570: every comparison below reads $COVERAGE_THRESHOLD, and the messages
|
|
1111
|
+
# quote it. If it ever arrives empty (a helper called outside the hook, a test
|
|
1112
|
+
# harness that sources only the case block), `[ "$pct" -lt "" ]` is false and
|
|
1113
|
+
# `awk 'pct < thr'` with an empty thr is false too — the gate would PASS every
|
|
1114
|
+
# value, i.e. exactly the fail-open this issue is about. Fall back to the
|
|
1115
|
+
# historical default so an unset variable can never widen the gate.
|
|
1116
|
+
#
|
|
1117
|
+
# Kept INSIDE the loop (immediately before the case) so a harness that extracts
|
|
1118
|
+
# only `case ... esac` still gets the guarantee it depends on.
|
|
1119
|
+
if ! [[ "${COVERAGE_THRESHOLD:-}" =~ ^[0-9]+$ ]]; then
|
|
1120
|
+
COVERAGE_THRESHOLD=80
|
|
1121
|
+
COVERAGE_THRESHOLD_SOURCE="default (threshold was unset at Stage 2)"
|
|
1122
|
+
fi
|
|
1123
|
+
case "$CURRENT_LANG" in
|
|
1124
|
+
"typescript")
|
|
1125
|
+
COVERAGE_ENFORCED=true
|
|
1126
|
+
if [ "${TESTS_SKIPPED:-false}" = "true" ]; then
|
|
1127
|
+
echo "✅ PASSED - Coverage check skipped (no test/source files changed)."
|
|
1128
|
+
elif [ -f "coverage/coverage-summary.json" ]; then
|
|
1129
|
+
# #594: reject NaN at the SOURCE, not after the fact. Math.round() does
|
|
1130
|
+
# not fail on a non-numeric input -- it returns NaN and console.log prints
|
|
1131
|
+
# "NaN" -- so istanbul's "Unknown" (a file with no executable lines) sailed
|
|
1132
|
+
# past both the `!= "parse_error"` and `-n` guards. Emit `no_data`, which
|
|
1133
|
+
# the guard below already treats as "could not measure".
|
|
1134
|
+
COVERAGE_PERCENT=$(node -e "
|
|
1135
|
+
try {
|
|
1136
|
+
const fs = require('fs');
|
|
1137
|
+
const data = JSON.parse(fs.readFileSync('coverage/coverage-summary.json', 'utf8'));
|
|
1138
|
+
const pct = data && data.total && data.total.lines && data.total.lines.pct;
|
|
1139
|
+
console.log(Number.isFinite(pct) ? Math.round(pct) : 'no_data');
|
|
1140
|
+
} catch(e) { console.log('parse_error'); }
|
|
1141
|
+
" 2>/dev/null)
|
|
1142
|
+
# #594: `-n` was not enough. `[ "NaN" -lt 80 ]` is not false in bash -- it
|
|
1143
|
+
# is an ERROR (exit 2, "integer expression expected"), and an `if` only
|
|
1144
|
+
# tells zero from non-zero, so the error took the else branch: the PASS
|
|
1145
|
+
# branch. Require an actual integer before comparing anything.
|
|
1146
|
+
if [[ "$COVERAGE_PERCENT" =~ ^[0-9]+$ ]]; then
|
|
1147
|
+
# #570: default the threshold at the comparison site too — an empty
|
|
1148
|
+
# value makes test(1) fail, the branch is skipped, and low coverage is
|
|
1149
|
+
# reported as a pass.
|
|
1150
|
+
if [ "$COVERAGE_PERCENT" -lt "${COVERAGE_THRESHOLD:-80}" ]; then
|
|
1151
|
+
# Only a subset test run (smart selection) leaves partial coverage data;
|
|
1152
|
+
# a full suite run must block on <80% even when many test files changed.
|
|
1153
|
+
if [ "${PARTIAL_TEST_RUN:-false}" = "true" ]; then
|
|
1154
|
+
echo "⚠️ Partial coverage ${COVERAGE_PERCENT}% (subset test run, not full suite)."
|
|
1155
|
+
echo " Run 'npx vitest run --coverage' for full coverage check."
|
|
1156
|
+
else
|
|
1157
|
+
echo "❌ BLOCKED - TypeScript coverage ${COVERAGE_PERCENT}% below ${COVERAGE_THRESHOLD:-80}% threshold"
|
|
1158
|
+
return 1
|
|
1159
|
+
fi
|
|
1160
|
+
else
|
|
1161
|
+
echo "TypeScript coverage: ${COVERAGE_PERCENT}% ✅ (≥ ${COVERAGE_THRESHOLD:-80}%)"
|
|
1162
|
+
fi
|
|
1163
|
+
|
|
1164
|
+
# ---- Diff coverage (#600): 指南 §10.1/§10.3 ----
|
|
1165
|
+
# The block above measures the WHOLE repo. A commit that changes five
|
|
1166
|
+
# lines and tests none of them passes as long as the global average has
|
|
1167
|
+
# not dipped -- so the only thing that gate ever knew about THIS change
|
|
1168
|
+
# was the average of everything else. This block asks the narrower and
|
|
1169
|
+
# more useful question: of the lines this commit touches, how many did
|
|
1170
|
+
# the tests execute?
|
|
1171
|
+
#
|
|
1172
|
+
# Skipped on a subset run, like the global check above: a partial run
|
|
1173
|
+
# legitimately leaves most changed lines unexecuted because the tests
|
|
1174
|
+
# covering them were deselected, and reporting that as low coverage
|
|
1175
|
+
# would punish the smart-selection feature for working.
|
|
1176
|
+
if declare -f compute_diff_coverage >/dev/null 2>&1 \
|
|
1177
|
+
&& [ "${PARTIAL_TEST_RUN:-false}" != "true" ] \
|
|
1178
|
+
&& [ -f "coverage/coverage-final.json" ]; then
|
|
1179
|
+
DIFF_COV_RANGES=$(mktemp 2>/dev/null || echo "${TMPDIR:-/tmp}/diffcov-$$")
|
|
1180
|
+
DIFF_COV_LINE_T=$(diff_coverage_threshold diff_coverage_lines 90)
|
|
1181
|
+
DIFF_COV_BRANCH_T=$(diff_coverage_threshold diff_coverage_branches 85)
|
|
1182
|
+
staged_added_line_ranges > "$DIFF_COV_RANGES" 2>/dev/null || true
|
|
1183
|
+
if [ -s "$DIFF_COV_RANGES" ]; then
|
|
1184
|
+
DIFF_COV_OUT=$(compute_diff_coverage coverage/coverage-final.json \
|
|
1185
|
+
"$DIFF_COV_RANGES" "$DIFF_COV_LINE_T" "$DIFF_COV_BRANCH_T" 2>&1)
|
|
1186
|
+
DIFF_COV_RC=$?
|
|
1187
|
+
DIFF_COV_RESULT=$(printf '%s\n' "$DIFF_COV_OUT" | grep '^RESULT ' | head -1)
|
|
1188
|
+
DIFF_COV_BRANCH=$(printf '%s\n' "$DIFF_COV_OUT" | grep '^BRANCH ' | head -1)
|
|
1189
|
+
if [ "$DIFF_COV_RC" -eq 0 ]; then
|
|
1190
|
+
echo "Changed-line coverage: ${DIFF_COV_RESULT#RESULT }% ✅ (lines, ≥ ${DIFF_COV_LINE_T}%)"
|
|
1191
|
+
if printf '%s\n' "$DIFF_COV_OUT" | grep -q '^NA '; then
|
|
1192
|
+
printf '%s\n' "$DIFF_COV_OUT" | grep '^NA ' | sed 's/^NA / n\/a (no executable statements): /'
|
|
1193
|
+
fi
|
|
1194
|
+
elif [ "$DIFF_COV_RC" -eq 1 ]; then
|
|
1195
|
+
echo "❌ BLOCKED - Changed-line coverage below threshold (指南 §10.1)."
|
|
1196
|
+
echo " Lines: ${DIFF_COV_RESULT#RESULT } (need ≥ ${DIFF_COV_LINE_T}%)"
|
|
1197
|
+
echo " Branches: ${DIFF_COV_BRANCH#BRANCH } (need ≥ ${DIFF_COV_BRANCH_T}%)"
|
|
1198
|
+
printf '%s\n' "$DIFF_COV_OUT" | grep '^UNCOVERED ' | sed 's/^UNCOVERED / untested changed lines: /'
|
|
1199
|
+
printf '%s\n' "$DIFF_COV_OUT" | grep '^MISSING ' | sed 's/^MISSING / no coverage data for: /'
|
|
1200
|
+
echo " Add tests for the lines listed above, or set diff_coverage_lines in"
|
|
1201
|
+
echo " .xp-gate/test-profile.yaml if this file genuinely cannot be unit-tested."
|
|
1202
|
+
rm -f "$DIFF_COV_RANGES"
|
|
1203
|
+
return 1
|
|
1204
|
+
else
|
|
1205
|
+
# #570: not measurable is not a pass. (The global check above already
|
|
1206
|
+
# blocked on a missing/corrupt report; this arm covers the narrower
|
|
1207
|
+
# case where coverage-final.json itself is unreadable.)
|
|
1208
|
+
echo "⚠️ Changed-line coverage could not be measured (coverage-final.json unreadable)."
|
|
1209
|
+
echo " See: $(printf '%s\n' "$DIFF_COV_OUT" | grep '^ERROR ' | head -1)"
|
|
1210
|
+
fi
|
|
1211
|
+
fi
|
|
1212
|
+
rm -f "$DIFF_COV_RANGES"
|
|
1213
|
+
fi
|
|
1214
|
+
else
|
|
1215
|
+
# #570: an unparseable report is not a pass. Silently continuing here
|
|
1216
|
+
# meant a corrupt or unexpected-shape coverage-summary.json disabled the
|
|
1217
|
+
# TypeScript coverage gate while the run still looked clean.
|
|
1218
|
+
if [ "${PARTIAL_TEST_RUN:-false}" = "true" ]; then
|
|
1219
|
+
echo "⚠️ Could not parse TypeScript coverage from coverage/coverage-summary.json (subset test run) — not blocking."
|
|
1220
|
+
else
|
|
1221
|
+
echo "❌ BLOCKED - Could not parse TypeScript coverage from coverage/coverage-summary.json."
|
|
1222
|
+
echo " The report exists but carries no usable total.lines.pct, so the"
|
|
1223
|
+
echo " ${COVERAGE_THRESHOLD:-80}% floor could not be checked."
|
|
1224
|
+
return 1
|
|
1225
|
+
fi
|
|
1226
|
+
fi
|
|
1227
|
+
else
|
|
1228
|
+
# #570: the report file is absent, so nothing was measured. Warning and
|
|
1229
|
+
# continuing made "delete coverage/coverage-summary.json" an effective way
|
|
1230
|
+
# to switch this gate off.
|
|
1231
|
+
if [ "${PARTIAL_TEST_RUN:-false}" = "true" ]; then
|
|
1232
|
+
echo "⚠️ coverage/coverage-summary.json not found (subset test run) — not blocking."
|
|
1233
|
+
else
|
|
1234
|
+
echo "❌ BLOCKED - coverage/coverage-summary.json not found."
|
|
1235
|
+
echo " No coverage could be measured, so the ${COVERAGE_THRESHOLD:-80}% floor could not be"
|
|
1236
|
+
echo " checked. Run 'npx vitest run --coverage' before committing."
|
|
1237
|
+
return 1
|
|
1238
|
+
fi
|
|
1239
|
+
fi
|
|
1240
|
+
;;
|
|
1241
|
+
"python")
|
|
1242
|
+
COVERAGE_ENFORCED=true
|
|
1243
|
+
# Issue #523: parsing + threshold verdict live in lib/coverage-total.sh
|
|
1244
|
+
# (the old `grep -o '[0-9]*%'` never matched --format=total's bare
|
|
1245
|
+
# number, so this branch never reached the threshold). Returns 1 on
|
|
1246
|
+
# BLOCK after echoing the verdict.
|
|
1247
|
+
enforce_python_coverage || return 1
|
|
1248
|
+
;;
|
|
1249
|
+
"java")
|
|
1250
|
+
COVERAGE_ENFORCED=true
|
|
1251
|
+
# JaCoCo writes target/site/jacoco/ (Maven) or build/reports/jacoco/test/
|
|
1252
|
+
# (Gradle), i.e. neither path probed by the default branch below, so Java
|
|
1253
|
+
# needs its own branch to be measurable at all.
|
|
1254
|
+
#
|
|
1255
|
+
# #603: a MULTI-MODULE Maven repo writes one report per module --
|
|
1256
|
+
# whaleaudit-core/target/site/jacoco/jacoco.csv, whaleaudit-demo/... --
|
|
1257
|
+
# and nothing at the repo root. Probing only the root paths therefore
|
|
1258
|
+
# concluded "No JaCoCo report found, so the 80% floor cannot be verified"
|
|
1259
|
+
# and BLOCKED every Java commit of a project that had a complete report
|
|
1260
|
+
# sitting one directory down. A gate that cannot see the report is not
|
|
1261
|
+
# enforcing a floor, it is enforcing an accident of build layout.
|
|
1262
|
+
# Fix: probe the root paths first (single-module projects, and the
|
|
1263
|
+
# historical behaviour), then fall back to the module reports and
|
|
1264
|
+
# aggregate across them, so the floor covers every class that was built.
|
|
1265
|
+
jacoco_csv=""
|
|
1266
|
+
jacoco_all=""
|
|
1267
|
+
for jacoco_candidate in \
|
|
1268
|
+
"target/site/jacoco/jacoco.csv" \
|
|
1269
|
+
"build/reports/jacoco/test/jacocoTestReport.csv"; do
|
|
1270
|
+
[ -f "$jacoco_candidate" ] && { jacoco_csv="$jacoco_candidate"; break; }
|
|
1271
|
+
done
|
|
1272
|
+
if [ -z "$jacoco_csv" ]; then
|
|
1273
|
+
# Module reports. -mindepth-free walk so ./module/... is found; sorted
|
|
1274
|
+
# for a stable, reproducible aggregate order.
|
|
1275
|
+
jacoco_all=$(find . -path ./target -prune -o \
|
|
1276
|
+
-type f \( -name 'jacoco.csv' -path '*/target/site/jacoco/*' \) -print 2>/dev/null \
|
|
1277
|
+
| sort | tr '\n' ' ')
|
|
1278
|
+
# First module report doubles as the "report exists" witness for the
|
|
1279
|
+
# messages below; the aggregate sums over every one of them.
|
|
1280
|
+
jacoco_csv=$(echo "$jacoco_all" | awk '{print $1}')
|
|
1281
|
+
fi
|
|
1282
|
+
if [ -n "$jacoco_csv" ] && [ -n "$jacoco_all" ]; then
|
|
1283
|
+
_jc_n=$(echo "$jacoco_all" | awk '{print NF}')
|
|
1284
|
+
echo " ℹ️ Multi-module JaCoCo: aggregating $_jc_n module report(s)."
|
|
1285
|
+
fi
|
|
1286
|
+
|
|
1287
|
+
if [ -n "$jacoco_csv" ]; then
|
|
1288
|
+
# Aggregate INSTRUCTION_MISSED / INSTRUCTION_COVERED over every class row.
|
|
1289
|
+
# Columns are located by header name because their position is not part of
|
|
1290
|
+
# the CSV's stable contract.
|
|
1291
|
+
#
|
|
1292
|
+
# #603: with module reports, each file repeats the header row, so the
|
|
1293
|
+
# header detection is per-file (FNR == 1) rather than per-stream
|
|
1294
|
+
# (NR == 1). Otherwise module 2's header is summed as data, or worse,
|
|
1295
|
+
# the single header found in module 1 leaves the columns unset for it.
|
|
1296
|
+
_jc_inputs="$jacoco_csv"
|
|
1297
|
+
[ -n "$jacoco_all" ] && _jc_inputs="$jacoco_all"
|
|
1298
|
+
COVERAGE_PERCENT=$(awk -F, '
|
|
1299
|
+
FNR == 1 {
|
|
1300
|
+
missed_col = 0; covered_col = 0;
|
|
1301
|
+
for (i = 1; i <= NF; i++) {
|
|
1302
|
+
if ($i == "INSTRUCTION_MISSED") missed_col = i;
|
|
1303
|
+
if ($i == "INSTRUCTION_COVERED") covered_col = i;
|
|
1304
|
+
}
|
|
1305
|
+
next;
|
|
1306
|
+
}
|
|
1307
|
+
missed_col && covered_col {
|
|
1308
|
+
missed += $missed_col;
|
|
1309
|
+
covered += $covered_col;
|
|
1310
|
+
}
|
|
1311
|
+
END {
|
|
1312
|
+
total = missed + covered;
|
|
1313
|
+
if (total > 0) printf "%.2f", (covered / total) * 100;
|
|
1314
|
+
else print "";
|
|
1315
|
+
}
|
|
1316
|
+
' $_jc_inputs 2>/dev/null) || COVERAGE_PERCENT=""
|
|
1317
|
+
|
|
1318
|
+
if [ -n "$COVERAGE_PERCENT" ]; then
|
|
1319
|
+
# Compare on the unrounded value so 79.5% cannot pass as 80%.
|
|
1320
|
+
COVERAGE_ROUNDED=${COVERAGE_PERCENT%.*}
|
|
1321
|
+
if awk -v pct="$COVERAGE_PERCENT" -v thr="${COVERAGE_THRESHOLD:-80}" 'BEGIN { exit !(pct < thr) }'; then
|
|
1322
|
+
if [ "${PARTIAL_TEST_RUN:-false}" = "true" ]; then
|
|
1323
|
+
echo "⚠️ Partial coverage ${COVERAGE_ROUNDED}% (subset test run, not full suite)."
|
|
1324
|
+
echo " Run the full test suite for a complete Java coverage check."
|
|
1325
|
+
else
|
|
1326
|
+
echo "❌ BLOCKED - Java coverage ${COVERAGE_ROUNDED}% below ${COVERAGE_THRESHOLD:-80}% threshold"
|
|
1327
|
+
return 1
|
|
1328
|
+
fi
|
|
1329
|
+
else
|
|
1330
|
+
echo "Java coverage: ${COVERAGE_ROUNDED}% ✅ (≥ ${COVERAGE_THRESHOLD:-80}%)"
|
|
1331
|
+
fi
|
|
1332
|
+
else
|
|
1333
|
+
# #570: a JaCoCo report that yields no instruction data measured
|
|
1334
|
+
# nothing. Warning and continuing let the gate pass on no evidence.
|
|
1335
|
+
if [ "${PARTIAL_TEST_RUN:-false}" = "true" ]; then
|
|
1336
|
+
echo "⚠️ Could not parse Java coverage from ${jacoco_csv} (subset test run) — not blocking."
|
|
1337
|
+
else
|
|
1338
|
+
echo "❌ BLOCKED - Could not parse Java coverage from ${jacoco_csv} (no instruction data),"
|
|
1339
|
+
echo " so the ${COVERAGE_THRESHOLD:-80}% floor cannot be verified."
|
|
1340
|
+
return 1
|
|
1341
|
+
fi
|
|
1342
|
+
fi
|
|
1343
|
+
else
|
|
1344
|
+
# #570: no report at all is the fail-open path this issue was filed for.
|
|
1345
|
+
if [ "${PARTIAL_TEST_RUN:-false}" = "true" ]; then
|
|
1346
|
+
echo "⚠️ No JaCoCo report found (subset test run) — not blocking."
|
|
1347
|
+
else
|
|
1348
|
+
# (#703) Diagnose BEFORE advising. The old message sent every user to
|
|
1349
|
+
# `mvn verify`; on a build path containing non-ASCII characters that
|
|
1350
|
+
# command is a dead end. Measured on a zh_CN Windows box at
|
|
1351
|
+
# D:\projects\SQL审计工具: the JaCoCo agent never writes jacoco.exec, it
|
|
1352
|
+
# does not throw, and Maven reports BUILD SUCCESS with
|
|
1353
|
+
# [INFO] Skipping JaCoCo execution due to missing execution data file.
|
|
1354
|
+
# so `mvn verify` "fixes" nothing and the user loops. Splitting the
|
|
1355
|
+
# diagnosis out lets each case get an action that can actually work.
|
|
1356
|
+
echo "❌ BLOCKED - No JaCoCo report found, so the ${COVERAGE_THRESHOLD:-80}% Java coverage"
|
|
1357
|
+
echo " floor cannot be verified."
|
|
1358
|
+
# The distinguishing symptom is the jacoco.exec execution data file, not
|
|
1359
|
+
# a missing report: a report that failed to be GENERATED and an agent
|
|
1360
|
+
# that never WROTE are different problems with different fixes.
|
|
1361
|
+
echo " Likely cause: the JaCoCo agent did not write its execution data file"
|
|
1362
|
+
echo " (target/jacoco.exec), which is what 'Skipping JaCoCo execution due to"
|
|
1363
|
+
echo " missing execution data file' in the Maven log means."
|
|
1364
|
+
# A non-ASCII working directory is the one common cause where the usual
|
|
1365
|
+
# advice actively does not work, so it must be called out by name rather
|
|
1366
|
+
# than left for the user to discover by trying.
|
|
1367
|
+
case "$PWD" in
|
|
1368
|
+
*[!-~]*)
|
|
1369
|
+
echo " ⚠️ This build path contains non-ASCII characters: ${PWD}"
|
|
1370
|
+
echo " ⚠️ Re-running 'mvn verify' will NOT help on this path — JaCoCo"
|
|
1371
|
+
echo " silently skips writing execution data there. Build through an"
|
|
1372
|
+
echo " ASCII-only directory instead (e.g. a junction to the same tree,"
|
|
1373
|
+
echo " entered with cmd's 'pushd'/'cd /d' — Git Bash's cd resolves the"
|
|
1374
|
+
echo " junction back to the non-ASCII path, so it does not help)."
|
|
1375
|
+
;;
|
|
1376
|
+
*)
|
|
1377
|
+
echo " To produce it, run 'mvn verify' or 'gradle jacocoTestReport' so that"
|
|
1378
|
+
echo " target/site/jacoco/jacoco.csv exists (see also: JaCoCo detection"
|
|
1379
|
+
echo " in adapters/java.sh)."
|
|
1380
|
+
;;
|
|
1381
|
+
esac
|
|
1382
|
+
return 1
|
|
1383
|
+
fi
|
|
1384
|
+
fi
|
|
1385
|
+
;;
|
|
1386
|
+
"go")
|
|
1387
|
+
# Go enforcement already handled inline in Stage 1 (lines 933-942)
|
|
1388
|
+
;;
|
|
1389
|
+
"shell")
|
|
1390
|
+
# Shell coverage not typically measured
|
|
1391
|
+
;;
|
|
1392
|
+
"dart"|"flutter")
|
|
1393
|
+
COVERAGE_ENFORCED=true
|
|
1394
|
+
if [ -f "coverage/lcov.info" ]; then
|
|
1395
|
+
COVERAGE_PERCENT=$(parse_lcov_coverage "coverage/lcov.info" 2>/dev/null) || COVERAGE_PERCENT="0"
|
|
1396
|
+
# #570: `-ge 0`, not `!= "0"`. A measured 0% is DATA — the tool ran and
|
|
1397
|
+
# covered nothing — so it must reach the threshold comparison instead of
|
|
1398
|
+
# being folded into "could not determine".
|
|
1399
|
+
if [ -n "$COVERAGE_PERCENT" ] && [ "$COVERAGE_PERCENT" -ge 0 ] 2>/dev/null; then
|
|
1400
|
+
# #570: default at the comparison site; an empty threshold makes
|
|
1401
|
+
# test(1) fail and silently skips the BLOCK.
|
|
1402
|
+
if [ "$COVERAGE_PERCENT" -lt "${COVERAGE_THRESHOLD:-80}" ]; then
|
|
1403
|
+
if [ "${PARTIAL_TEST_RUN:-false}" = "true" ]; then
|
|
1404
|
+
echo "⚠️ Partial coverage ${COVERAGE_PERCENT}% (subset test run, not full suite)."
|
|
1405
|
+
echo " Run the full test suite for a complete Flutter/Dart coverage check."
|
|
1406
|
+
else
|
|
1407
|
+
echo "❌ BLOCKED - Flutter/Dart coverage ${COVERAGE_PERCENT}% below ${COVERAGE_THRESHOLD:-80}% threshold"
|
|
1408
|
+
return 1
|
|
1409
|
+
fi
|
|
1410
|
+
else
|
|
1411
|
+
echo "Flutter/Dart coverage: ${COVERAGE_PERCENT}% ✅ (≥ ${COVERAGE_THRESHOLD:-80}%)"
|
|
1412
|
+
fi
|
|
1413
|
+
else
|
|
1414
|
+
# #570: lcov.info exists but carries no usable hit/found pair.
|
|
1415
|
+
if [ "${PARTIAL_TEST_RUN:-false}" = "true" ]; then
|
|
1416
|
+
echo "⚠️ Could not determine Flutter/Dart coverage (subset test run) — not blocking."
|
|
1417
|
+
else
|
|
1418
|
+
echo "❌ BLOCKED - Could not determine Flutter/Dart coverage from coverage/lcov.info,"
|
|
1419
|
+
echo " so the ${COVERAGE_THRESHOLD:-80}% floor cannot be verified."
|
|
1420
|
+
return 1
|
|
1421
|
+
fi
|
|
1422
|
+
fi
|
|
1423
|
+
else
|
|
1424
|
+
# #570: the fail-open path. `dart test --coverage` not run means the gate
|
|
1425
|
+
# has no evidence, and no evidence is not a pass.
|
|
1426
|
+
if [ "${PARTIAL_TEST_RUN:-false}" = "true" ]; then
|
|
1427
|
+
echo "⚠️ coverage/lcov.info not found (subset test run) — not blocking."
|
|
1428
|
+
else
|
|
1429
|
+
echo "❌ BLOCKED - coverage/lcov.info not found, so the ${COVERAGE_THRESHOLD:-80}% Flutter/Dart"
|
|
1430
|
+
echo " coverage floor cannot be verified. Ensure 'dart test --coverage' was run."
|
|
1431
|
+
return 1
|
|
1432
|
+
fi
|
|
1433
|
+
fi
|
|
1434
|
+
;;
|
|
1435
|
+
"powershell")
|
|
1436
|
+
COVERAGE_ENFORCED=true
|
|
1437
|
+
if [ -f "coverage.xml" ]; then
|
|
1438
|
+
# The threshold is passed INTO node: the verdict used to be computed
|
|
1439
|
+
# against a hard-coded 80 inside the script, so a project that configured
|
|
1440
|
+
# a different floor got a verdict about a number it never set (#570).
|
|
1441
|
+
COVERAGE_RESULT=$(THRESHOLD="${COVERAGE_THRESHOLD:-80}" node -e "
|
|
1442
|
+
try {
|
|
1443
|
+
const fs = require('fs');
|
|
1444
|
+
const xml = fs.readFileSync('coverage.xml', 'utf8');
|
|
1445
|
+
const counters = [...xml.matchAll(/<counter\b([^>]*)\/?\s*>/gi)]
|
|
1446
|
+
.map((match) => Object.fromEntries(
|
|
1447
|
+
[...match[1].matchAll(/([\w:-]+)\s*=\s*(['\"])(.*?)\2/g)]
|
|
1448
|
+
.map((attribute) => [attribute[1].toUpperCase(), attribute[3]])
|
|
1449
|
+
))
|
|
1450
|
+
.filter((counter) => counter.TYPE === 'LINE');
|
|
1451
|
+
const reportCounter = counters.at(-1);
|
|
1452
|
+
const missed = Number(reportCounter?.MISSED);
|
|
1453
|
+
const covered = Number(reportCounter?.COVERED);
|
|
1454
|
+
const total = missed + covered;
|
|
1455
|
+
if (!Number.isFinite(missed) || !Number.isFinite(covered) || missed < 0 || covered < 0 || total <= 0) {
|
|
1456
|
+
throw new Error('invalid LINE counter');
|
|
1457
|
+
}
|
|
1458
|
+
const threshold = Number(process.env.THRESHOLD);
|
|
1459
|
+
// Number("") is 0, which would make every percentage "pass" — the
|
|
1460
|
+
// exact fail-open shape this fix is about. Refuse an unusable floor.
|
|
1461
|
+
if (!Number.isFinite(threshold) || threshold <= 0) {
|
|
1462
|
+
throw new Error('unusable THRESHOLD');
|
|
1463
|
+
}
|
|
1464
|
+
const percentage = (covered / total) * 100;
|
|
1465
|
+
console.log((percentage < threshold ? 'below' : 'pass') + '|' + Math.round(percentage));
|
|
1466
|
+
} catch (error) { console.log('parse_error'); }
|
|
1467
|
+
" 2>/dev/null) || COVERAGE_RESULT="parse_error"
|
|
1468
|
+
if [ "$COVERAGE_RESULT" != "parse_error" ] && [ -n "$COVERAGE_RESULT" ]; then
|
|
1469
|
+
COVERAGE_STATUS=${COVERAGE_RESULT%%|*}
|
|
1470
|
+
COVERAGE_PERCENT=${COVERAGE_RESULT#*|}
|
|
1471
|
+
if [ "$COVERAGE_STATUS" = "below" ]; then
|
|
1472
|
+
if [ "${PARTIAL_TEST_RUN:-false}" = "true" ]; then
|
|
1473
|
+
echo "⚠️ Partial coverage ${COVERAGE_PERCENT}% (subset test run, not full suite)."
|
|
1474
|
+
echo " Run the full Pester suite for a complete PowerShell coverage check."
|
|
1475
|
+
else
|
|
1476
|
+
echo "❌ BLOCKED - PowerShell coverage ${COVERAGE_PERCENT}% below ${COVERAGE_THRESHOLD:-80}% threshold"
|
|
1477
|
+
return 1
|
|
1478
|
+
fi
|
|
1479
|
+
else
|
|
1480
|
+
echo "PowerShell coverage: ${COVERAGE_PERCENT}% ✅ (≥ ${COVERAGE_THRESHOLD:-80}%)"
|
|
1481
|
+
fi
|
|
1482
|
+
else
|
|
1483
|
+
# #570: an unparseable coverage.xml is no evidence, not a pass.
|
|
1484
|
+
if [ "${PARTIAL_TEST_RUN:-false}" = "true" ]; then
|
|
1485
|
+
echo "⚠️ Could not parse PowerShell coverage from coverage.xml (subset test run) - not blocking."
|
|
1486
|
+
else
|
|
1487
|
+
echo "❌ BLOCKED - Could not parse PowerShell coverage from coverage.xml,"
|
|
1488
|
+
echo " so the ${COVERAGE_THRESHOLD:-80}% floor cannot be verified."
|
|
1489
|
+
return 1
|
|
1490
|
+
fi
|
|
1491
|
+
fi
|
|
1492
|
+
else
|
|
1493
|
+
# #570: Pester coverage not run means the gate has nothing to answer with.
|
|
1494
|
+
if [ "${PARTIAL_TEST_RUN:-false}" = "true" ]; then
|
|
1495
|
+
echo "⚠️ coverage.xml not found (subset test run) - not blocking."
|
|
1496
|
+
else
|
|
1497
|
+
echo "❌ BLOCKED - coverage.xml not found, so the ${COVERAGE_THRESHOLD:-80}% PowerShell"
|
|
1498
|
+
echo " coverage floor cannot be verified. Ensure Pester coverage was run."
|
|
1499
|
+
return 1
|
|
1500
|
+
fi
|
|
1501
|
+
fi
|
|
1502
|
+
;;
|
|
1503
|
+
"iac")
|
|
1504
|
+
# IaC has no coverage concept — must not borrow the TypeScript report
|
|
1505
|
+
# that Stage 1 leaves behind (same rule as the PowerShell branch).
|
|
1506
|
+
;;
|
|
1507
|
+
*)
|
|
1508
|
+
# Default: attempt to parse coverage from common formats regardless of language
|
|
1509
|
+
COVERAGE_ENFORCED=true
|
|
1510
|
+
COVERAGE_PERCENT=""
|
|
1511
|
+
if [ -f "coverage/coverage-summary.json" ]; then
|
|
1512
|
+
COVERAGE_PERCENT=$(node -e "
|
|
1513
|
+
try {
|
|
1514
|
+
const fs = require('fs');
|
|
1515
|
+
const data = JSON.parse(fs.readFileSync('coverage/coverage-summary.json', 'utf8'));
|
|
1516
|
+
console.log(Math.round(data.total.lines.pct));
|
|
1517
|
+
} catch(e) { console.log('parse_error'); }
|
|
1518
|
+
" 2>/dev/null) || COVERAGE_PERCENT=""
|
|
1519
|
+
elif [ -f "coverage/lcov.info" ]; then
|
|
1520
|
+
if command -v parse_lcov_coverage &> /dev/null; then
|
|
1521
|
+
COVERAGE_PERCENT=$(parse_lcov_coverage "coverage/lcov.info" 2>/dev/null) || COVERAGE_PERCENT=""
|
|
1522
|
+
else
|
|
1523
|
+
COVERAGE_PERCENT=$(grep -oP 'SF:.*' coverage/lcov.info 2>/dev/null | wc -l || echo "0")
|
|
1524
|
+
# Simple fallback: check lcov for coverage percentage
|
|
1525
|
+
COVERAGE_PERCENT=$(grep -oP 'coverage: \K[0-9]+%' coverage/lcov.info 2>/dev/null | head -1 | tr -d '%') || COVERAGE_PERCENT=""
|
|
1526
|
+
fi
|
|
1527
|
+
else
|
|
1528
|
+
# #768: Cobertura is what the .NET/C# and several JVM toolchains actually
|
|
1529
|
+
# emit -- `dotnet test --collect:"XPlat Code Coverage"` writes ONE
|
|
1530
|
+
# cobertura XML per test target under TestResults/<guid>/coverage.cobertura.xml,
|
|
1531
|
+
# never coverage-summary.json or lcov.info. This branch only knew the two
|
|
1532
|
+
# JS-oriented filenames, so a C# project with full coverage data fell into
|
|
1533
|
+
# "Could not determine coverage percentage" and was BLOCKED with an
|
|
1534
|
+
# instruction to "produce coverage data" it had already produced.
|
|
1535
|
+
#
|
|
1536
|
+
# Discovery order: the conventional root file first, then the newest
|
|
1537
|
+
# TestResults artifact, so both `coverlet`'s default layout and a
|
|
1538
|
+
# hand-placed report work. Newest-first matters because TestResults
|
|
1539
|
+
# accumulates one directory per run and an old report must not win.
|
|
1540
|
+
_cob_file=""
|
|
1541
|
+
for _candidate in coverage/cobertura.xml coverage.cobertura.xml coverage/coverage.cobertura.xml; do
|
|
1542
|
+
if [ -f "$_candidate" ]; then _cob_file="$_candidate"; break; fi
|
|
1543
|
+
done
|
|
1544
|
+
if [ -z "$_cob_file" ]; then
|
|
1545
|
+
_cob_file=$(find . -name 'coverage.cobertura.xml' \
|
|
1546
|
+
-path '*TestResults*' -not -path './.git/*' 2>/dev/null \
|
|
1547
|
+
| while IFS= read -r _f; do printf '%s\t%s\n' "$(stat -c %Y "$_f" 2>/dev/null || stat -f %m "$_f" 2>/dev/null || echo 0)" "$_f"; done \
|
|
1548
|
+
| sort -rn | head -1 | cut -f2-)
|
|
1549
|
+
fi
|
|
1550
|
+
if [ -n "$_cob_file" ] && [ -f "$_cob_file" ]; then
|
|
1551
|
+
# Cobertura's root <coverage line-rate="..."> is the fraction covered
|
|
1552
|
+
# (0..1) and is authoritative; summing per-class lines double-counts.
|
|
1553
|
+
# A report that exists but has no parseable line-rate is `parse_error`,
|
|
1554
|
+
# which the caller treats as "no evidence" rather than 0% -- 0% would
|
|
1555
|
+
# be a *measured* value and block with the wrong reason.
|
|
1556
|
+
COVERAGE_PERCENT=$(node -e "
|
|
1557
|
+
try {
|
|
1558
|
+
const fs = require('fs');
|
|
1559
|
+
const xml = fs.readFileSync(process.argv[1], 'utf8');
|
|
1560
|
+
const root = xml.match(/<coverage\b[^>]*>/);
|
|
1561
|
+
if (!root) { console.log('parse_error'); process.exit(0); }
|
|
1562
|
+
const rate = root[0].match(/line-rate\s*=\s*[\"']([0-9.]+)[\"']/);
|
|
1563
|
+
if (!rate) { console.log('parse_error'); process.exit(0); }
|
|
1564
|
+
const value = Number(rate[1]);
|
|
1565
|
+
if (!Number.isFinite(value) || value < 0 || value > 1) { console.log('parse_error'); process.exit(0); }
|
|
1566
|
+
console.log(Math.round(value * 100));
|
|
1567
|
+
} catch (e) { console.log('parse_error'); }
|
|
1568
|
+
" "$_cob_file" 2>/dev/null) || COVERAGE_PERCENT=""
|
|
1569
|
+
if [ -n "$COVERAGE_PERCENT" ] && [ "$COVERAGE_PERCENT" != "parse_error" ]; then
|
|
1570
|
+
echo " (coverage source: $_cob_file)"
|
|
1571
|
+
fi
|
|
1572
|
+
fi
|
|
1573
|
+
fi
|
|
1574
|
+
# #579: `-ge 0`, not `-gt 0`. A measured 0% is DATA -- coverage.py ran and
|
|
1575
|
+
# covered nothing -- not a missing value. Folding it into the
|
|
1576
|
+
# "could not determine" branch let a suite that tested nothing pass the
|
|
1577
|
+
# coverage gate with a WARNING. The two claims are different: 0% is
|
|
1578
|
+
# "executed, proved nothing"; undetermined is "no evidence produced".
|
|
1579
|
+
# #570: the threshold is defaulted HERE as well as quoted in the message.
|
|
1580
|
+
# A bare `[ "$COVERAGE_PERCENT" -lt "$COVERAGE_THRESHOLD" ]` with an empty
|
|
1581
|
+
# threshold makes test(1) fail with "integer expected", the condition is
|
|
1582
|
+
# false, and 16% coverage was reported as ✅ (the same fail-open shape this
|
|
1583
|
+
# issue is about, one line further down). `2>/dev/null` on the numeric test
|
|
1584
|
+
# keeps a non-numeric report on the "cannot determine" path instead of
|
|
1585
|
+
# dying.
|
|
1586
|
+
if [ -n "$COVERAGE_PERCENT" ] && [ "$COVERAGE_PERCENT" != "parse_error" ] \
|
|
1587
|
+
&& [ "$COVERAGE_PERCENT" -ge 0 ] 2>/dev/null; then
|
|
1588
|
+
if [ "$COVERAGE_PERCENT" -lt "${COVERAGE_THRESHOLD:-80}" ]; then
|
|
1589
|
+
# Only a subset test run (smart selection) warns — the full suite may
|
|
1590
|
+
# still reach ≥80%; a full suite run must block.
|
|
1591
|
+
if [ "${PARTIAL_TEST_RUN:-false}" = "true" ]; then
|
|
1592
|
+
echo "⚠️ Partial coverage ${COVERAGE_PERCENT}% (subset test run, not full suite)."
|
|
1593
|
+
echo " Run the full test suite for a complete ${CURRENT_LANG} coverage check."
|
|
1594
|
+
else
|
|
1595
|
+
echo "❌ BLOCKED - ${CURRENT_LANG} coverage ${COVERAGE_PERCENT}% below ${COVERAGE_THRESHOLD:-80}% threshold"
|
|
1596
|
+
return 1
|
|
1597
|
+
fi
|
|
1598
|
+
else
|
|
1599
|
+
echo "${CURRENT_LANG} coverage: ${COVERAGE_PERCENT}% ✅ (≥ ${COVERAGE_THRESHOLD:-80}%)"
|
|
1600
|
+
fi
|
|
1601
|
+
else
|
|
1602
|
+
# #570: "could not determine" is a FAILED answer to the gate's question
|
|
1603
|
+
# ("is coverage at or above the floor?"), not a lenient one. Warning and
|
|
1604
|
+
# falling through made the generic branch fail-open: a language that
|
|
1605
|
+
# produced no standard report file passed the coverage gate while the
|
|
1606
|
+
# summary still looked clean. The ONE exception is a subset run, where
|
|
1607
|
+
# the global percentage is meaningless by construction.
|
|
1608
|
+
if [ "${PARTIAL_TEST_RUN:-false}" = "true" ]; then
|
|
1609
|
+
echo "⚠️ Could not determine ${CURRENT_LANG} coverage percentage (subset test run) — not blocking."
|
|
1610
|
+
else
|
|
1611
|
+
echo "❌ BLOCKED - Could not determine ${CURRENT_LANG} coverage percentage."
|
|
1612
|
+
echo " No standard coverage report file was found, so the ${COVERAGE_THRESHOLD:-80}% floor"
|
|
1613
|
+
echo " could not be checked. Produce coverage data or run a subset test run."
|
|
1614
|
+
return 1
|
|
1615
|
+
fi
|
|
1616
|
+
fi
|
|
1617
|
+
;;
|
|
1618
|
+
esac
|
|
1619
|
+
|
|
1620
|
+
if [ "$COV_EXIT" -ne 0 ]; then
|
|
1621
|
+
echo ""
|
|
1622
|
+
echo "❌ BLOCKED - Coverage check FAILED"
|
|
1623
|
+
return 1
|
|
1624
|
+
fi
|
|
1625
|
+
if [ "$COVERAGE_ENFORCED" = false ]; then
|
|
1626
|
+
echo "ℹ️ Coverage enforcement not applicable for ${CURRENT_LANG}"
|
|
1627
|
+
fi
|
|
1628
|
+
echo "✅ PASSED - Coverage check completed."
|
|
1629
|
+
done # end for CURRENT_LANG (Stage 2 coverage)
|
|
1630
|
+
|
|
1631
|
+
fi # End: if [ "${TESTS_SKIPPED:-false}" != "true" ] (Issue #312 coverage skip)
|
|
1632
|
+
|
|
1633
|
+
# ============================================================================
|
|
1634
|
+
# Stage 3: Per-file coverage check for NEW files (Issue #103)
|
|
1635
|
+
# New files must have ≥80% coverage individually.
|
|
1636
|
+
# ============================================================================
|
|
1637
|
+
if has_project_lang "typescript" && [ -f "coverage/coverage-summary.json" ]; then
|
|
1638
|
+
NEW_SOURCE_FILES=$(git diff --cached --name-only --diff-filter=A | filter_project_paths | grep -E '\.(ts|tsx)$' | grep -v '__tests__' | grep -v '\.test\.' | grep -v '\.spec\.' | grep -v '__snapshots__' | grep -v '\.d\.ts$' || true)
|
|
1639
|
+
if [ -n "$NEW_SOURCE_FILES" ]; then
|
|
1640
|
+
echo ""
|
|
1641
|
+
echo " └─ Per-file coverage check for new files:"
|
|
1642
|
+
for new_file in $NEW_SOURCE_FILES; do
|
|
1643
|
+
# Normalize path for coverage-summary.json lookup
|
|
1644
|
+
NORMALIZED_PATH=$(echo "$new_file" | sed 's|^\./||')
|
|
1645
|
+
FILE_COV=$(node -e "
|
|
1646
|
+
try {
|
|
1647
|
+
const fs = require('fs');
|
|
1648
|
+
const data = JSON.parse(fs.readFileSync('coverage/coverage-summary.json', 'utf8'));
|
|
1649
|
+
const entry = data['$NORMALIZED_PATH'];
|
|
1650
|
+
if (entry && entry.lines) {
|
|
1651
|
+
console.log(Math.round(entry.lines.pct));
|
|
1652
|
+
} else {
|
|
1653
|
+
console.log('no_data');
|
|
1654
|
+
}
|
|
1655
|
+
} catch(e) { console.log('parse_error'); }
|
|
1656
|
+
" 2>/dev/null)
|
|
1657
|
+
# NOTE (#555): the 80 below is deliberately NOT $COVERAGE_THRESHOLD.
|
|
1658
|
+
# That one is the project-level floor a repo declares in fail_under;
|
|
1659
|
+
# this is the bar a single NEW file must clear to justify existing at
|
|
1660
|
+
# all. Tying them would mean a repo with fail_under=82 could not add a
|
|
1661
|
+
# file at 81% even while the project sits well above its floor.
|
|
1662
|
+
if [ "$FILE_COV" = "no_data" ] || [ "$FILE_COV" = "parse_error" ]; then
|
|
1663
|
+
echo " ⚠️ $new_file — no coverage data (file may be excluded or not exercised)"
|
|
1664
|
+
elif [ "$FILE_COV" -lt 80 ]; then
|
|
1665
|
+
echo " ❌ $new_file — ${FILE_COV}% coverage (below 80% per-new-file threshold)"
|
|
1666
|
+
NEW_FILE_COV_FAIL=true
|
|
1667
|
+
else
|
|
1668
|
+
echo " ✅ $new_file — ${FILE_COV}% coverage"
|
|
1669
|
+
fi
|
|
1670
|
+
done
|
|
1671
|
+
if [ "${NEW_FILE_COV_FAIL:-false}" = "true" ]; then
|
|
1672
|
+
echo ""
|
|
1673
|
+
echo "❌ BLOCKED - New file(s) below 80% coverage threshold"
|
|
1674
|
+
echo "Add tests to cover the new files before committing."
|
|
1675
|
+
return 1
|
|
1676
|
+
fi
|
|
1677
|
+
fi
|
|
1678
|
+
fi
|
|
1679
|
+
# Only reached on the non-docs-only path. Assigning PASS outside the if/else
|
|
1680
|
+
# overwrote the docs-only SKIP a few hundred lines above and reported
|
|
1681
|
+
# "Tests + Coverage: PASS (coverage: N/A)" for a commit where no test ran
|
|
1682
|
+
# (#554) -- a SKIP promoted to PASS inflates the pass rate and hides that the
|
|
1683
|
+
# gate never executed.
|
|
1684
|
+
#
|
|
1685
|
+
# #554 follow-up: the same promotion was still happening ONE LEVEL IN. The
|
|
1686
|
+
# early-skip branch above (no source extension among the changed files, e.g. a
|
|
1687
|
+
# version bump) sets GATE_5_STATUS="SKIP", and this unguarded assignment
|
|
1688
|
+
# overwrote it on the way out of the same else-block. A branch that records
|
|
1689
|
+
# its own verdict must not be re-decided by the block epilogue: default to
|
|
1690
|
+
# PASS only when the sentinel is still untouched.
|
|
1691
|
+
#
|
|
1692
|
+
# Not written as a `:-PASS` expansion: AC-599-03 forbids a PASS default in
|
|
1693
|
+
# any `GATE_N_STATUS:-DEFAULT` expansion, because that is how an unassigned
|
|
1694
|
+
# gate came to render as "passed". An explicit comparison keeps both rules.
|
|
1695
|
+
if [ -z "$GATE_5_STATUS" ]; then
|
|
1696
|
+
GATE_5_STATUS="PASS"
|
|
1697
|
+
fi
|
|
1698
|
+
fi
|
|
1699
|
+
|
|
1700
|
+
# #665: a subset run is exempt from the GLOBAL coverage floor by design (#473),
|
|
1701
|
+
# but the exemption was never published, so the persisted report showed
|
|
1702
|
+
# `actual.coverage = 29` beside `thresholds.lines = 82` with `status = PASS` and
|
|
1703
|
+
# `reason = ""`. The verdict was correct; the RECORD was unreadable, and a record
|
|
1704
|
+
# is all `xp-gate audit` and the tech-debt trackers (#636, #638) ever see. Two
|
|
1705
|
+
# opposite situations -- "coverage really was 29% and the gate passed it" and
|
|
1706
|
+
# "a subset run, global floor not applicable" -- rendered identically.
|
|
1707
|
+
#
|
|
1708
|
+
# Derived from PARTIAL_TEST_RUN at ONE place instead of being set by hand at each
|
|
1709
|
+
# of the six branches that mark a partial run: a reason written at one call site
|
|
1710
|
+
# and forgotten at another is the drift that produced the empty reason here.
|
|
1711
|
+
if [ "${PARTIAL_TEST_RUN:-false}" = "true" ]; then
|
|
1712
|
+
GATE_5_COVERAGE_APPLIES_TO="subset"
|
|
1713
|
+
# Never overwrite a reason the branch itself recorded (docs_only_change,
|
|
1714
|
+
# no_code_files_changed, ...) -- those explain a different verdict.
|
|
1715
|
+
if [ -z "${GATE_5_DETAIL:-}" ] && [ "$GATE_5_STATUS" = "PASS" ]; then
|
|
1716
|
+
GATE_5_DETAIL="partial_test_run_coverage_not_applicable"
|
|
1717
|
+
fi
|
|
1718
|
+
else
|
|
1719
|
+
GATE_5_COVERAGE_APPLIES_TO="project"
|
|
1720
|
+
fi
|
|
1721
|
+
|
|
1722
|
+
record_gate_audit "gate-5" "tests-coverage" "$GATE_5_STATUS" "0" "$GATE_5_START" "${GATE_5_DETAIL:-}"
|
|
1723
|
+
return 0
|
|
1724
|
+
}
|
|
1725
|
+
|
|
1726
|
+
|
|
1727
|
+
|
|
1728
|
+
# Called by pre-commit's ordered driver.
|
|
1729
|
+
|