@boyingliu01/xp-gate 0.38.4 → 0.38.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/adapters/gate-10.sh +478 -0
  2. package/adapters/gate-12-file-hygiene.sh +315 -0
  3. package/adapters/gate-13-compiler-strictness.sh +1443 -0
  4. package/adapters/gate-6-layers.sh +375 -0
  5. package/adapters/gate-8.sh +13 -1
  6. package/adapters/iac.sh +60 -27
  7. package/adapters/shell.sh +50 -2
  8. package/build-integrity/gate-10.ts +44 -3
  9. package/gate-12-file-hygiene.sh +15 -7
  10. package/gate-8.sh +13 -1
  11. package/hooks/gate-12-file-hygiene.sh +15 -7
  12. package/hooks/gate-8.sh +13 -1
  13. package/hooks/gate-entries/gate-1-entry.sh +44 -3
  14. package/hooks/gate-entries/gate-5-entry.sh +8 -0
  15. package/hooks/post-commit +9 -0
  16. package/hooks/pre-push +11 -2
  17. package/lib/mattpocock-license-verdict.json +1 -1
  18. package/mock-policy/AGENTS.md +1 -1
  19. package/mutation/AGENTS.md +1 -1
  20. package/package.json +1 -1
  21. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  22. package/plugins/claude-code/bin/xp-gate-version-check.sh +6 -0
  23. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  24. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  25. package/plugins/claude-code/skills/sprint-flow/__tests__/verify-sprint-state.test.bats +23 -1
  26. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  27. package/plugins/dsh/package.json +1 -1
  28. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  29. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  30. package/plugins/dsh/skills/sprint-flow/__tests__/verify-sprint-state.test.bats +23 -1
  31. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  32. package/plugins/opencode/package.json +1 -1
  33. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  34. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  35. package/plugins/opencode/skills/sprint-flow/__tests__/verify-sprint-state.test.bats +23 -1
  36. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  37. package/plugins/qoder/plugin.json +1 -1
  38. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  39. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  40. package/plugins/qoder/skills/sprint-flow/__tests__/verify-sprint-state.test.bats +23 -1
  41. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  42. package/principles/AGENTS.md +1 -1
  43. package/skills/delphi-review/AGENTS.md +1 -1
  44. package/skills/sprint-flow/AGENTS.md +1 -1
  45. package/skills/sprint-flow/__tests__/verify-sprint-state.test.bats +23 -1
  46. package/skills/test-specification-alignment/AGENTS.md +1 -1
@@ -0,0 +1,1443 @@
1
+ #!/usr/bin/env bash
2
+ # ============================================================================
3
+ # GATE 13: Compiler Strictness Check
4
+ #
5
+ # The compiler is the first and cheapest static analysis tool for any compiled
6
+ # language, and XP-Gate historically never used it that way: `cpp.sh` only runs
7
+ # clang-tidy/cppcheck over the first 20 files, and Gate 9's build-integrity half
8
+ # is TypeScript-and-Maven only. A measured `g++ -Wall -Wextra` pass over an
9
+ # innocuous-looking translation unit reports -Wnon-virtual-dtor, -Wreorder,
10
+ # -Wparentheses, -Wclass-memaccess, -Wold-style-cast and -Wswitch-default —
11
+ # real defects no linter in the chain is positioned to see. Bare `javac`
12
+ # likewise reports NOTHING for raw types; `-Xlint:all` does, and an identical
13
+ # Java file went from "0 diagnostics" to a hard error under `-Werror`.
14
+ #
15
+ # Design: docs/plans/2026-10-26-gate-13-compiler-strictness-design.md
16
+ # Requirement rounds 1-3 (.sprint-state/) — review findings folded in below are
17
+ # tagged with their review id (CI-xx architecture, MC-xx technical, FC-xx
18
+ # feasibility).
19
+ #
20
+ # ── VERDICT CONTRACT ────────────────────────────────────────────────────────
21
+ # Inherited from pre-commit's established java.sh / powershell.sh protocol (#507):
22
+ # 0 = PASS every compiled file clean or within its baseline
23
+ # 1 = FAIL new warnings on changed files (a real finding) -> commit blocked
24
+ # 2 = BLOCK tool RAN but its output is untrustworthy (fail-closed)
25
+ # 3 = WARN compiler absent / cross-compiling / timeout / warn-only findings
26
+ # -> counted IN the scoring denominator, never PASS
27
+ #
28
+ # A TIMEOUT is always 3, never 2 (architecture MA-03): a timeout is incomplete
29
+ # coverage, not a wrong conclusion, and promoting it to BLOCK would turn machine
30
+ # load into a failed commit. 2 is reserved for the case where the tool finished
31
+ # but contradicted itself or emitted unparseable output.
32
+ #
33
+ # Reasons cross the command-substitution subshell as an `XP_G13_REASON: ...`
34
+ # stdout line — an `export` inside this file can NEVER reach the caller, whose
35
+ # `$(...)` discards the child environment.
36
+ # ============================================================================
37
+
38
+ # ── Verdict codes (pinned by the bats suite) ────────────────────────────────
39
+ # shellcheck disable=SC2034 # public contract: pre-commit reads these by name
40
+ GATE13_PASS=0
41
+ # shellcheck disable=SC2034 # emitted from SLICE-2 onward (C/C++ warning findings)
42
+ GATE13_FAIL=1
43
+ # shellcheck disable=SC2034 # public contract
44
+ GATE13_BLOCK=2
45
+ # shellcheck disable=SC2034 # public contract
46
+ GATE13_WARN=3
47
+
48
+ GATE13_DEFAULT_TIMEOUT=120
49
+
50
+ # ---------------------------------------------------------------------------
51
+ # Reason channel. Mirrors java.sh's XP_G1_REASON protocol so pre-commit can
52
+ # surface a SKIP/WARN cause without losing the verdict code.
53
+ #
54
+ # Written to stderr, NOT stdout: the helpers below are also called in command
55
+ # substitution (`budget=$(gate13_timeout_budget)`), and a stdout reason would be
56
+ # captured INTO the value — turning a valid budget into "XP_G13_REASON: ... 120"
57
+ # and breaking every numeric consumer. pre-commit reads the reason with 2>&1.
58
+ # ---------------------------------------------------------------------------
59
+ gate13_reason() {
60
+ printf 'XP_G13_REASON: %s\n' "$*" >&2
61
+ }
62
+
63
+ # ---------------------------------------------------------------------------
64
+ # AC-007-01 — timeout budget.
65
+ # Precedence (feasibility FC-02): XP_GATE_COMPILER_TIMEOUT > .xp-gate/compiler-gate-timeout
66
+ # > 120s. The env var wins so CI can raise the budget for a large changeset
67
+ # without editing a tracked file. An unreadable/invalid override WARNs and falls
68
+ # back — an unreadable override must never silently disable the budget.
69
+ # ---------------------------------------------------------------------------
70
+ gate13_timeout_budget() {
71
+ local file=".xp-gate/compiler-gate-timeout" val=""
72
+
73
+ if [ -n "${XP_GATE_COMPILER_TIMEOUT:-}" ]; then
74
+ val=$(printf '%s' "$XP_GATE_COMPILER_TIMEOUT" | tr -d '[:space:]')
75
+ case "$val" in
76
+ ''|*[!0-9]*|0)
77
+ gate13_reason "invalid XP_GATE_COMPILER_TIMEOUT='${XP_GATE_COMPILER_TIMEOUT}' (expected a positive integer), falling back to ${GATE13_DEFAULT_TIMEOUT}s"
78
+ echo "$GATE13_DEFAULT_TIMEOUT"
79
+ return 0
80
+ ;;
81
+ *) echo "$val"; return 0 ;;
82
+ esac
83
+ fi
84
+
85
+ if [ -f "$file" ]; then
86
+ val=$(tr -d '[:space:]' < "$file")
87
+ fi
88
+
89
+ case "$val" in
90
+ '')
91
+ echo "$GATE13_DEFAULT_TIMEOUT"
92
+ ;;
93
+ *[!0-9]*|0)
94
+ gate13_reason "invalid $file value '${val}' (expected a positive integer), falling back to ${GATE13_DEFAULT_TIMEOUT}s"
95
+ echo "$GATE13_DEFAULT_TIMEOUT"
96
+ ;;
97
+ *) echo "$val" ;;
98
+ esac
99
+ }
100
+
101
+ # ---------------------------------------------------------------------------
102
+ # AC-007-02 / AC-006-03 — timeout classification. Always WARN, and the output
103
+ # must be visually distinguishable from "clean" so a reader never mistakes
104
+ # incomplete coverage for a pass.
105
+ # ---------------------------------------------------------------------------
106
+ gate13_classify_timeout() {
107
+ echo "TIMEOUT — coverage incomplete (the compiler did not finish within the budget); verdict treated as WARN, not a finding"
108
+ return "$GATE13_WARN"
109
+ }
110
+
111
+ # ---------------------------------------------------------------------------
112
+ # AC-006-03 — the ONLY path that yields verdict 2. The tool ran, but produced
113
+ # output that contradicts itself or cannot be interpreted, so no conclusion can
114
+ # be drawn. Missing tools never come here (they are 3).
115
+ # ---------------------------------------------------------------------------
116
+ gate13_classify_unusable() {
117
+ echo "BLOCK (fail-closed) — the compiler ran but its output is untrustworthy; refusing to report success"
118
+ return "$GATE13_BLOCK"
119
+ }
120
+
121
+ # ---------------------------------------------------------------------------
122
+ # AC-001-03 — cross-compilation predicate. Pure: takes a compiler name/command,
123
+ # returns 0 (cross) or 1 (host). Three explicit conditions (architecture CI-01),
124
+ # each independently testable:
125
+ # 1. CROSS_COMPILE is non-empty
126
+ # 2. the basename matches ^(prefix-)?(gcc|g++|cc|c++|clang|clang++)(-ver)?$
127
+ # with a NON-EMPTY prefix (arm-linux-gnueabihf-g++, aarch64-none-elf-gcc)
128
+ # 3. the target triple differs from the host triple (needs -dumpmachine)
129
+ #
130
+ # Explicitly answered in review: an empty CROSS_COMPILE with
131
+ # CC=arm-linux-gnueabihf-gcc IS cross-compilation — condition 2 catches it.
132
+ # ---------------------------------------------------------------------------
133
+ gate13_is_cross_compiling() {
134
+ local cc="${1:-}"
135
+ local base prefix
136
+
137
+ if [ -n "${CROSS_COMPILE:-}" ]; then
138
+ return 0
139
+ fi
140
+
141
+ base=$(basename -- "$cc" 2>/dev/null || printf '%s' "$cc")
142
+ # Strip a trailing -<version> / -<major.minor> so g++-13 is host, not cross.
143
+ base=$(printf '%s' "$base" | sed -E 's/-[0-9]+(\.[0-9]+)*$//')
144
+
145
+ # prefix-<tool>. `gcc` itself has no prefix; `<prefix>-gcc` does.
146
+ if printf '%s' "$base" | grep -Eq '^(.+)-(gcc|g\+\+|cc|c\+\+|clang|clang\+\+)$'; then
147
+ prefix=$(printf '%s' "$base" | sed -E 's/^(.+)-(gcc|g\+\+|cc|c\+\+|clang|clang\+\+)$/\1/')
148
+ # A leading path component was already stripped by basename, so any prefix
149
+ # left here is a toolchain prefix.
150
+ if [ -n "$prefix" ]; then
151
+ return 0
152
+ fi
153
+ fi
154
+
155
+ # Known host-style names with no prefix at all.
156
+ case "$base" in
157
+ gcc|g++|cc|c++|clang|clang++) return 1 ;;
158
+ esac
159
+
160
+ # Anything else (e.g. an absolute path to a foreign toolchain) — cond 3.
161
+ if [ -x "$cc" ] && command -v "$cc" >/dev/null 2>&1; then
162
+ local target host
163
+ target=$("$cc" -dumpmachine 2>/dev/null)
164
+ host=$(uname -m 2>/dev/null)
165
+ if [ -n "$target" ] && [ -n "$host" ]; then
166
+ case "$target" in
167
+ "$host"*) return 1 ;;
168
+ *) return 0 ;;
169
+ esac
170
+ fi
171
+ fi
172
+
173
+ return 1
174
+ }
175
+
176
+ # ---------------------------------------------------------------------------
177
+ # Usability probe — `command -v` alone is NOT enough. A broken shim, a missing
178
+ # shared library, or a PATH entry for the wrong architecture all pass `command
179
+ # -v` and then fail at the first real invocation. Treating that as "compiler
180
+ # present" would route to the analysis stage and report a spurious failure (or,
181
+ # worse, no failure at all). Ask the compiler to identify itself; anything but
182
+ # a clean exit means "not usable".
183
+ # ---------------------------------------------------------------------------
184
+ gate13_compiler_usable() {
185
+ local cc="$1"
186
+ "$cc" --version >/dev/null 2>&1
187
+ }
188
+
189
+ # ---------------------------------------------------------------------------
190
+ # AC-001-01 / AC-001-04 — compiler selection.
191
+ # Order (REQ-001): $CXX > Makefile CXX := > PATH (g++ > clang++ > c++).
192
+ # A user-named compiler that cannot be used is REPORTED, never silently replaced
193
+ # (AC-001-04) — a silent swap would compile the wrong code with the wrong flags
194
+ # and still print PASS.
195
+ #
196
+ # Prints the selected compiler path on stdout and the selection basis on stderr
197
+ # so callers can capture the path without the narrative.
198
+ # ---------------------------------------------------------------------------
199
+ gate13_select_cxx() {
200
+ local cand=""
201
+
202
+ # 1. Environment — this is what make itself would use.
203
+ if [ -n "${CXX:-}" ]; then
204
+ if command -v "$CXX" >/dev/null 2>&1 && gate13_compiler_usable "$CXX"; then
205
+ echo "compiler selected: $CXX (basis: \$CXX environment variable)" >&2
206
+ printf '%s\n' "$CXX"
207
+ return 0
208
+ fi
209
+ gate13_reason "explicitly configured CXX='${CXX}' is not runnable; refusing to substitute a different compiler"
210
+ echo "compiler selected: none (basis: \$CXX='${CXX}' is unusable)" >&2
211
+ return 1
212
+ fi
213
+
214
+ # 2. Makefile assignment — the project's own declared compiler.
215
+ if [ -f "Makefile" ]; then
216
+ cand=$(sed -nE 's/^[[:space:]]*CXX[[:space:]]*[:?]?=[[:space:]]*([^[:space:]#]+).*/\1/p' Makefile 2>/dev/null | head -1)
217
+ if [ -n "$cand" ] && command -v "$cand" >/dev/null 2>&1 && gate13_compiler_usable "$cand"; then
218
+ echo "compiler selected: $cand (basis: Makefile CXX assignment)" >&2
219
+ printf '%s\n' "$cand"
220
+ return 0
221
+ fi
222
+ fi
223
+
224
+ # 3. PATH lookup, most standard first.
225
+ for cand in g++ clang++ c++; do
226
+ if command -v "$cand" >/dev/null 2>&1 && gate13_compiler_usable "$cand"; then
227
+ echo "compiler selected: $cand (basis: PATH lookup)" >&2
228
+ printf '%s\n' "$cand"
229
+ return 0
230
+ fi
231
+ done
232
+
233
+ echo "compiler selected: none (basis: no usable C++ compiler on PATH)" >&2
234
+ return 1
235
+ }
236
+
237
+ # Same order for C, so a pure-C project is not forced through a C++ driver.
238
+ gate13_select_cc() {
239
+ local cand=""
240
+
241
+ if [ -n "${CC:-}" ]; then
242
+ if command -v "$CC" >/dev/null 2>&1 && gate13_compiler_usable "$CC"; then
243
+ printf '%s\n' "$CC"
244
+ return 0
245
+ fi
246
+ gate13_reason "explicitly configured CC='${CC}' is not runnable; refusing to substitute a different compiler"
247
+ return 1
248
+ fi
249
+
250
+ if [ -f "Makefile" ]; then
251
+ cand=$(sed -nE 's/^[[:space:]]*CC[[:space:]]*[:?]?=[[:space:]]*([^[:space:]#]+).*/\1/p' Makefile 2>/dev/null | head -1)
252
+ if [ -n "$cand" ] && command -v "$cand" >/dev/null 2>&1 && gate13_compiler_usable "$cand"; then
253
+ printf '%s\n' "$cand"
254
+ return 0
255
+ fi
256
+ fi
257
+
258
+ for cand in gcc clang cc; do
259
+ if command -v "$cand" >/dev/null 2>&1 && gate13_compiler_usable "$cand"; then
260
+ printf '%s\n' "$cand"
261
+ return 0
262
+ fi
263
+ done
264
+
265
+ return 1
266
+ }
267
+
268
+ # ---------------------------------------------------------------------------
269
+ # AC-008-02 — emergency kill switch, orthogonal to the strictness tier
270
+ # (feasibility FC-03). A gate that cannot be disabled during a misreport storm
271
+ # gets disabled permanently by `--no-verify`, which the Code of Conduct forbids —
272
+ # so the sanctioned escape hatch is an explicit, audited SKIP.
273
+ # ---------------------------------------------------------------------------
274
+ gate13_is_disabled() {
275
+ [ "${XP_GATE_DISABLE_13:-}" = "1" ]
276
+ }
277
+
278
+ # ---------------------------------------------------------------------------
279
+ # AC-002-01 — strictness tier resolution.
280
+ # Values: strict | balanced (default) | warn-only. An unrecognised value WARNs
281
+ # and falls back to balanced rather than silently choosing a stricter or looser
282
+ # policy than the user asked for.
283
+ # ---------------------------------------------------------------------------
284
+ gate13_resolve_tier() {
285
+ local tier="${1:-${XP_GATE_COMPILER_STRICTNESS:-balanced}}"
286
+ case "$tier" in
287
+ strict|balanced|warn-only) printf '%s\n' "$tier" ;;
288
+ *)
289
+ gate13_reason "unknown XP_GATE_COMPILER_STRICTNESS='${tier}' (expected strict|balanced|warn-only), falling back to balanced"
290
+ printf 'balanced\n'
291
+ ;;
292
+ esac
293
+ }
294
+
295
+ # ---------------------------------------------------------------------------
296
+ # AC-002-01 — the flag set for a tier and language.
297
+ #
298
+ # balanced covers the highest-value real-bug classes from the GCC manual with a
299
+ # low false-positive cost. strict adds -Wconversion/-Wsign-conversion, which are
300
+ # very noisy in numeric code, hence opt-in. The C++-only flags are separated so a
301
+ # C translation unit is never handed -Wold-style-cast (a C++ diagnostic gcc would
302
+ # reject as unrecognised for C with -Werror).
303
+ # ---------------------------------------------------------------------------
304
+ gate13_cpp_flags() {
305
+ local tier lang base strict common
306
+ tier=$(gate13_resolve_tier "${1:-}")
307
+ lang="${2:-cpp}"
308
+
309
+ base="-Wall -Wextra"
310
+
311
+ if [ "$tier" = "balanced" ] || [ "$tier" = "warn-only" ]; then
312
+ printf '%s\n' "$base"
313
+ return 0
314
+ fi
315
+
316
+ # strict
317
+ common="-Wpedantic -Wshadow -Wformat=2 -Wcast-qual -Wcast-align -Wnull-dereference -Wswitch-enum"
318
+ if [ "$lang" = "c" ]; then
319
+ printf '%s %s\n' "$base" "$common"
320
+ else
321
+ printf '%s %s -Wconversion -Wsign-conversion -Wold-style-cast -Wuseless-cast -Wnon-virtual-dtor -Woverloaded-virtual\n' "$base" "$common"
322
+ fi
323
+ }
324
+
325
+ # ---------------------------------------------------------------------------
326
+ # AC-002-02 / AC-002-03 — capability probe.
327
+ #
328
+ # One clean throwaway translation unit, each candidate flag tried ALONE in the
329
+ # POSITIVE form. Measured: gcc reports `unrecognized command-line option '-Wfoo'`
330
+ # for an unknown positive flag, but accepts an unknown `-Wno-foo` silently (a
331
+ # `cc1plus: note:` appears only when other diagnostics exist). Probing the
332
+ # negative form would therefore "succeed" for every flag and the gate would claim
333
+ # checks it never ran.
334
+ #
335
+ # Caching (architecture MA-01): results live in GATE13_PROBE_CACHE for the
336
+ # lifetime of one hook run — a persisted cache would go stale on compiler upgrade.
337
+ # Emits the ACCEPTED flags on stdout (space separated) and `dropped flag:` lines
338
+ # on stderr.
339
+ # ---------------------------------------------------------------------------
340
+ gate13_flag_supported() {
341
+ local cc="$1" flag="$2" lang="${3:-cpp}" probe_tu out
342
+ # The cache key carries the language (walkthrough R2 MA-05): gcc accepts
343
+ # -Wold-style-cast for C++ and rejects it for C, so a key without the language
344
+ # would let a C probe inherit the C++ answer.
345
+ local key="${cc}|${lang}|${flag}"
346
+
347
+ # Two separate caches, checked separately. A single "seen this key" cache was
348
+ # wrong (walkthrough MA-02): once any flag was dropped, every cached key
349
+ # returned "supported", re-enabling flags the compiler had already rejected.
350
+ case " ${GATE13_PROBE_DROPPED:-} " in
351
+ *" ${key} "*) return 1 ;;
352
+ esac
353
+ case " ${GATE13_PROBE_CACHE:-} " in
354
+ *" ${key} "*) return 0 ;;
355
+ esac
356
+
357
+ probe_tu="${GATE13_PROBE_TU:-}"
358
+ if [ -z "$probe_tu" ] || [ ! -f "$probe_tu" ]; then
359
+ probe_tu="${TMPDIR:-/tmp}/gate13_probe_$$.cpp"
360
+ printf 'int main() { return 0; }\n' > "$probe_tu"
361
+ GATE13_PROBE_TU="$probe_tu"
362
+ fi
363
+
364
+ if out=$("$cc" -fsyntax-only "$flag" "$probe_tu" 2>&1); then
365
+ GATE13_PROBE_CACHE="${GATE13_PROBE_CACHE:-} ${key}"
366
+ return 0
367
+ fi
368
+
369
+ case "$out" in
370
+ *"unrecognized command-line option"*|*"unknown warning option"*|*"unknown argument"*)
371
+ GATE13_PROBE_DROPPED="${GATE13_PROBE_DROPPED:-} ${key}"
372
+ return 1
373
+ ;;
374
+ esac
375
+
376
+ # The flag compiled but failed for some other reason (bad probe TU, missing
377
+ # system headers). Assume support: dropping a working flag silently loses
378
+ # coverage, and a genuinely unsupported flag is caught by the pattern above.
379
+ GATE13_PROBE_CACHE="${GATE13_PROBE_CACHE:-} ${key}"
380
+ return 0
381
+ }
382
+
383
+ gate13_probe_flags() {
384
+ local cc="$1" lang="$2"
385
+ shift 2
386
+ local flag accepted="" dropped=""
387
+
388
+ for flag in "$@"; do
389
+ if gate13_flag_supported "$cc" "$flag" "$lang"; then
390
+ accepted="$accepted $flag"
391
+ else
392
+ dropped="$dropped $flag"
393
+ printf 'dropped flag: %s (unsupported by %s)\n' "$flag" "$(gate13_compiler_id "$cc")" >&2
394
+ fi
395
+ done
396
+
397
+ printf '%s\n' "$(printf '%s' "$accepted" | sed 's/^ *//')"
398
+ }
399
+
400
+ gate13_compiler_id() {
401
+ local cc="$1" v
402
+ v=$("$cc" --version 2>/dev/null | head -1)
403
+ printf '%s' "${v:-$cc}"
404
+ }
405
+
406
+ # ---------------------------------------------------------------------------
407
+ # AC-003-04 — the changed set. Staged files only, matching Gate 1/12.
408
+ # Deleted files are excluded: they cannot be compiled.
409
+ # ---------------------------------------------------------------------------
410
+ gate13_changed_cpp_files() {
411
+ git diff --cached --name-only --diff-filter=d -- '*.c' '*.cc' '*.cpp' '*.cxx' '*.C' 2>/dev/null
412
+ }
413
+
414
+ # Emits "<status>\t<file>" where status is A (added) or M (modified/other).
415
+ gate13_classify_changed() {
416
+ local f status
417
+ while IFS= read -r f; do
418
+ [ -n "$f" ] || continue
419
+ status=$(git diff --cached --name-status --diff-filter=ACMR -- "$f" 2>/dev/null | awk '{print $1}' | head -1)
420
+ case "$status" in
421
+ A) printf 'added\t%s\n' "$f" ;;
422
+ *) printf 'modified\t%s\n' "$f" ;;
423
+ esac
424
+ done <<EOF
425
+ $(gate13_changed_cpp_files)
426
+ EOF
427
+ }
428
+
429
+ # ---------------------------------------------------------------------------
430
+ # AC-003-02 — baseline storage. In-repo, mirroring Gate 6's .warnings-baseline.json
431
+ # precedent (technical CRITICAL-1 / feasibility FC-01). A local cache was
432
+ # rejected because it makes CI and developer verdicts diverge.
433
+ # The HOOK NEVER WRITES THIS FILE — that is the precise meaning of
434
+ # "baseline only grows" (architecture CI-03): a hook that silently rewrote the
435
+ # baseline could excuse its own regressions.
436
+ # ---------------------------------------------------------------------------
437
+ gate13_baseline_path() {
438
+ printf '%s\n' ".xp-gate/compiler-warnings-baseline.json"
439
+ }
440
+
441
+ # Prints the recorded warning count for a file, or empty when there is no
442
+ # baseline / no entry for that file.
443
+ gate13_baseline_count() {
444
+ local file="$1" path count
445
+ path=$(gate13_baseline_path)
446
+ [ -f "$path" ] || return 0
447
+
448
+ if command -v node >/dev/null 2>&1; then
449
+ count=$(node -e '
450
+ const fs = require("fs");
451
+ try {
452
+ const j = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
453
+ const e = (j.files || {})[process.argv[2]];
454
+ if (e && typeof e.count === "number") process.stdout.write(String(e.count));
455
+ } catch (_) { /* unreadable baseline == no baseline */ }
456
+ ' "$path" "$file" 2>/dev/null)
457
+ fi
458
+ printf '%s' "$count"
459
+ }
460
+
461
+ gate13_baseline_exists() {
462
+ [ -f "$(gate13_baseline_path)" ]
463
+ }
464
+
465
+ # ---------------------------------------------------------------------------
466
+ # Compile one translation unit and count its diagnostics.
467
+ # -fsyntax-only: no artifacts, measured to write nothing into the tree.
468
+ # Prints the diagnostics on stderr; the COUNT goes to stdout.
469
+ # ---------------------------------------------------------------------------
470
+ gate13_count_warnings() {
471
+ local cc="$1" flags="$2" file="$3" out
472
+ # shellcheck disable=SC2086 # flags is a deliberately word-split flag list
473
+ out=$("$cc" -fsyntax-only $flags "$file" 2>&1)
474
+ printf '%s\n' "$out" | grep -E 'warning:' | grep -vcE '^\s*$' || true
475
+ }
476
+
477
+ # ============================================================================
478
+ # JAVA PATH (REQ-004)
479
+ #
480
+ # Measured motivation: `List raw = l;` in a Java file produces ZERO diagnostics
481
+ # from bare javac, `[rawtypes]` under -Xlint:all, and a hard error under
482
+ # -Xlint:all -Werror. Gate 9's `mvn -q -DskipTests compile` suppresses the very
483
+ # warnings a strict gate exists to read.
484
+ # ============================================================================
485
+
486
+ # ---------------------------------------------------------------------------
487
+ # AC-004-01 — Maven arguments.
488
+ #
489
+ # `-B` (batch mode) NOT `-q`: -q suppresses non-error diagnostics, so "run mvn
490
+ # quietly" and "parse the warning lines" are mutually exclusive — a real
491
+ # self-contradiction caught in requirement round 2 (architecture CI-02).
492
+ # `-o` keeps a hook from reaching the network (REQ-007).
493
+ # `compilerArgument` is a SINGLE appended argument; -Xlint:all,-processing is
494
+ # one token precisely because of that (technical MC-01).
495
+ # ---------------------------------------------------------------------------
496
+ gate13_maven_args() {
497
+ printf '%s\n' "-B -o -DskipTests compile -Dmaven.compiler.showWarnings=true -Dmaven.compiler.showDeprecation=true -Dmaven.compiler.compilerArgument=-Xlint:all,-processing"
498
+ }
499
+
500
+ gate13_javac_args() {
501
+ printf '%s\n' "-Xlint:all,-processing -d"
502
+ }
503
+
504
+ # ---------------------------------------------------------------------------
505
+ # AC-670-34 / AC-670-35 (#659) — counting javac lint findings, locale-proof.
506
+ #
507
+ # The previous detector was an allow-list of English `[category]` names applied to
508
+ # `[WARNING]` lines. Two independent ways it returned 0 on defective code:
509
+ #
510
+ # 1. NOVELTY: a JDK adds a category the list does not name (`future-category`),
511
+ # or the fix relies on the list staying in sync with javac. A fixed allow-list
512
+ # over an open enum is a fail-OPEN design.
513
+ # 2. LOCALISATION: on a non-English build javac's own hint drifts, and the
514
+ # `[WARNING]` prefix may too. Measured on a zh_CN Maven build, the tell is
515
+ # "使用了未经检查或不安全的操作 ... 请使用 -Xlint:unchecked 重新编译" -- a message
516
+ # javac emits precisely when -Xlint was NOT in effect.
517
+ #
518
+ # Fail-closed policy (#499/#570) applied to text matching: count any bracketed
519
+ # lowercase category (whatever it is named), and treat javac's "you should have
520
+ # used -Xlint" hint as a finding too -- the code has an unchecked/unsafe operation
521
+ # whether or not the flag that would name it was on.
522
+ #
523
+ # Prints a single integer. Never fails (always exits 0).
524
+ # ---------------------------------------------------------------------------
525
+ gate13_count_lint_findings() {
526
+ local src="${1:-}"
527
+ [ -n "$src" ] || src=$(cat)
528
+ # (#701) Pin the locale to C for this awk, on purpose. In a UTF-8 locale gawk
529
+ # refuses to let `.` span bytes that are not valid UTF-8, and a Maven build on a
530
+ # zh_CN Windows box writes its reactor summary in GBK (stdout.encoding=GBK), so a
531
+ # module name such as "验证程序" arrives as d1 e9 d6 a4 b3 cc d0 f2 -- invalid
532
+ # UTF-8. The #673 exclusion rule (`/^\[INFO\].*\[jar\].../`) then fails to match
533
+ # and the line falls through to the open-category rule as a phantom finding.
534
+ # Measured (#701): the same input counts 0 under LC_ALL=C and 1 under
535
+ # LC_ALL=C.UTF-8, i.e. the verdict depended on the caller's environment rather
536
+ # than on the build. C locale makes `.` byte-oriented, so the match no longer
537
+ # depends on whether the module name happens to be ASCII.
538
+ #
539
+ # This costs nothing in matching power: every marker below (packaging types,
540
+ # `[category]`, `warning:`) is ASCII, and the localised unchecked/unsafe
541
+ # wordings are matched as byte sequences, which C locale handles exactly.
542
+ printf '%s\n' "$src" | LC_ALL=C awk '
543
+ BEGIN { n = 0 }
544
+ # (#673) Maven 3.9.7+ reactor summary appends the packaging type per module:
545
+ # [INFO] whaleaudit-core [jar]
546
+ # `[pom]`/`[jar]` match the open-category rule below, so a 3-module reactor
547
+ # reported 4 javac findings on code with ZERO warnings -- and got worse with
548
+ # every module added. The marker set is closed (packaging types are an enum in
549
+ # Maven itself), so excluding it does not reopen the #659 fail-open hole that
550
+ # the open-category rule was introduced to close.
551
+ #
552
+ # Scoped to `[INFO]` lines: a javac diagnostic is never prefixed with the
553
+ # Maven [INFO] banner, so this cannot mask a real finding even when a category
554
+ # name collides with a packaging type.
555
+ /^\[INFO\].*\[(pom|jar|war|ear|rar|ejb|maven-plugin|par|test-jar|java-source|javadoc|zip|tar\.gz|tar\.bz2)\][[:space:]]*$/ { next }
556
+ # Any bracketed lowercase category: covers the whole javac -Xlint enum and any
557
+ # later addition to it. Restricted to lowercase/digit/hyphen so a Maven
558
+ # `[WARNING]` with no category, or a `[INFO]` banner, is not counted.
559
+ /\[[a-z][a-z0-9-]*\]/ { n++; next }
560
+ # javac localised or English: "warning:" prefix at line start.
561
+ /^[[:space:]]*warning:/ { n++; next }
562
+ # Unchecked/unsafe operations reported from any locale. The English and Chinese
563
+ # wordings are both matched; anything else falls through to the category rule
564
+ # above, which is marker-based and therefore locale-independent.
565
+ /unchecked|unsafe|未经检查|不安全/ { n++; next }
566
+ END { print n + 0 }
567
+ '
568
+ return 0
569
+ }
570
+
571
+ # ---------------------------------------------------------------------------
572
+ # AC-670-32 (#659) — PROVE that -Xlint takes effect, do not assume it.
573
+ #
574
+ # "Can assemble the flag" is not "the flag works". `compilerArgument` is a single
575
+ # appended argument, so `-Xlint:all,-processing` (a comma list) is not reliably
576
+ # passed through -- measured on Maven 3.9.12 + JDK 21, where the injected run
577
+ # produced no `[category]` markers at all and javac printed its own
578
+ # "recompile with -Xlint:unchecked" hint instead.
579
+ #
580
+ # The only honest test is a probe: compile a source that is KNOWN to warn (a raw
581
+ # type is the canonical one -- measured to emit `[rawtypes]` under -Xlint:all and
582
+ # nothing otherwise) using the exact same command shape, and look for the marker.
583
+ #
584
+ # Returns 0 = injection proven effective, 1 = not proven (caller must degrade).
585
+ # ---------------------------------------------------------------------------
586
+ gate13_maven_lint_effective() {
587
+ local mvn_bin="${1:-mvn}"
588
+ local budget tmpd probe out rc
589
+ budget=$(gate13_timeout_budget)
590
+ tmpd="${TMPDIR:-/tmp}/gate13_probe_$$"
591
+ mkdir -p "$tmpd" || return 1
592
+
593
+ # Raw type on purpose: javac emits NOTHING for this without -Xlint:all, so a
594
+ # silent run proves the flag did not reach the compiler.
595
+ probe="$tmpd/Gate13Probe.java"
596
+ cat > "$probe" <<'PROBE'
597
+ import java.util.ArrayList;
598
+ import java.util.List;
599
+ public class Gate13Probe {
600
+ private List items = new ArrayList();
601
+ public void add(Object o) { items.add(o); }
602
+ }
603
+ PROBE
604
+
605
+ # Same argument shape as gate13_maven_args(), against the probe only. A single
606
+ # -Djavac directly is not what we are testing -- the whole point is whether the
607
+ # MAVEN injection path works.
608
+ if command -v timeout >/dev/null 2>&1; then
609
+ out=$(timeout "$budget" javac -Xlint:all -d "$tmpd" "$probe" 2>&1)
610
+ else
611
+ out=$(javac -Xlint:all -d "$tmpd" "$probe" 2>&1)
612
+ fi
613
+ rc=$?
614
+ rm -rf "$tmpd"
615
+
616
+ # If the DIRECT javac probe cannot even produce a rawtypes warning, the JDK
617
+ # itself is not behaving as measured, so nothing about the Maven path can be
618
+ # concluded -- report "not proven" rather than "effective".
619
+ if [ "$rc" -ne 0 ]; then
620
+ return 1
621
+ fi
622
+ printf '%s\n' "$out" | grep -q 'rawtypes'
623
+ }
624
+
625
+ # Is `-Xlint` reachable at all on this machine? The Maven probe only makes sense
626
+ # when a raw-type warning is obtainable; when javac cannot produce one, callers
627
+ # stay in degraded mode instead of claiming a clean lint.
628
+ gate13_maven_probe_available() {
629
+ command -v javac >/dev/null 2>&1
630
+ }
631
+
632
+ gate13_java_sources() {
633
+ git diff --cached --name-only --diff-filter=d -- '*.java' 2>/dev/null
634
+ }
635
+
636
+ # ---------------------------------------------------------------------------
637
+ # AC-004-02 — is the command-line Maven injection likely to take effect?
638
+ #
639
+ # Returns 0 = reliable, 1 = unreliable. Three known failure modes, each of which
640
+ # silently drops the lint flags rather than failing loudly:
641
+ # 1. the pom already declares <compilerArgs> — a CLI single-arg append is
642
+ # overridden by the explicit configuration (technical MC-01)
643
+ # 2. maven-compiler-plugin < 3.1 — compilerArgument semantics were not stable
644
+ # (feasibility FC-02)
645
+ # 3. no plugin version declared at all — the effective version is inherited or
646
+ # defaulted and cannot be verified, so do not assume it works
647
+ #
648
+ # On "unreliable" the gate degrades to warn-only with a loud banner. It never
649
+ # fakes a PASS and never emits an unpredictable BLOCK.
650
+ # ---------------------------------------------------------------------------
651
+ # shellcheck disable=SC2016 # this function matches LITERAL ${...} in a pom, not expansions
652
+ gate13_maven_injection_reliable() {
653
+ local pom="${1:-pom.xml}" ver
654
+
655
+ [ -f "$pom" ] || return 1
656
+
657
+ if grep -q '<compilerArgs>' "$pom" 2>/dev/null; then
658
+ printf 'pom already declares <compilerArgs>; a command-line -Dmaven.compiler.compilerArgument may be overridden\n' >&2
659
+ return 1
660
+ fi
661
+
662
+ # Extract the version belonging to the maven-compiler-plugin block.
663
+ # Walkthrough R2 MA-04: a range match to the first </plugin> could pick up a
664
+ # neighbouring plugin's version, and a strict numeric pattern missed
665
+ # `3.13.0-SNAPSHOT`. Anchor on the plugin's own artifactId, then take the FIRST
666
+ # <version> that follows it, and accept a qualifier suffix.
667
+ ver=$(awk '
668
+ /<artifactId>[[:space:]]*maven-compiler-plugin[[:space:]]*<\/artifactId>/ { found=1 }
669
+ found && /<version>/ {
670
+ line=$0
671
+ sub(/.*<version>[[:space:]]*/, "", line)
672
+ sub(/[[:space:]]*<\/version>.*/, "", line)
673
+ print line
674
+ exit
675
+ }
676
+ ' "$pom" 2>/dev/null)
677
+
678
+ if [ -z "$ver" ]; then
679
+ printf 'maven-compiler-plugin version is not declared; injection cannot be verified\n' >&2
680
+ return 1
681
+ fi
682
+
683
+ # A property placeholder cannot be resolved statically — treat as unverified
684
+ # rather than guessing (walkthrough R2 MA-04).
685
+ case "$ver" in
686
+ *'${'*)
687
+ printf 'maven-compiler-plugin version is a property reference (%s); cannot be verified statically\n' "$ver" >&2
688
+ return 1
689
+ ;;
690
+ esac
691
+
692
+ # Drop a qualifier suffix (3.13.0-SNAPSHOT -> 3.13.0) before comparing.
693
+ ver=${ver%%-*}
694
+
695
+ local major minor
696
+ major=${ver%%.*}
697
+ minor=${ver#*.}
698
+ minor=${minor%%.*}
699
+
700
+ if [ "$major" -lt 3 ] || { [ "$major" -eq 3 ] && [ "$minor" -lt 1 ]; }; then
701
+ printf 'maven-compiler-plugin %s predates stable compilerArgument support (needs >= 3.1)\n' "$ver" >&2
702
+ return 1
703
+ fi
704
+
705
+ # AC-670-33 (#659): every check above verifies that the arguments can be
706
+ # ASSEMBLED. None of them verifies that they take EFFECT, which is exactly how a
707
+ # pom declaring plugin 3.13.0 was declared "reliable" while Maven ran with no
708
+ # -Xlint at all and Gate 13 reported PASS on a file javac warned about 3 times.
709
+ #
710
+ # So prove it: one probe compile of a known-raw-type source through the same
711
+ # command shape. If the marker does not appear, injection did not happen and the
712
+ # caller must degrade -- "could not verify" is never "verified fine" (#499/#570).
713
+ if ! gate13_maven_probe_available; then
714
+ printf 'javac unavailable; -Xlint injection cannot be probed\n' >&2
715
+ return 1
716
+ fi
717
+ if ! gate13_maven_lint_effective "${MVN_BIN:-mvn}"; then
718
+ printf 'probe compile did not produce a [rawtypes] marker; -Xlint injection is NOT effective\n' >&2
719
+ return 1
720
+ fi
721
+
722
+ return 0
723
+ }
724
+
725
+ # ---------------------------------------------------------------------------
726
+ # AC-004-03 — count javac diagnostics for a file under the strict lint set.
727
+ # Verified by measurement: bare javac reports nothing for a raw type, this
728
+ # reports [rawtypes].
729
+ # ---------------------------------------------------------------------------
730
+ gate13_javac_warning_count() {
731
+ local file="$1" out tmpd rc=0 budget
732
+ command -v javac >/dev/null 2>&1 || { printf '0\n'; return 0; }
733
+
734
+ tmpd="${TMPDIR:-/tmp}/gate13_javac_$$"
735
+ mkdir -p "$tmpd"
736
+ budget=$(gate13_timeout_budget)
737
+
738
+ # Timeout-bounded (walkthrough MC-03): a pathological file can hang javac, and
739
+ # a pre-commit hook must never hang with it. `timeout` may be absent on some
740
+ # systems, in which case we run unbounded rather than skipping the check.
741
+ if command -v timeout >/dev/null 2>&1; then
742
+ out=$(timeout "$budget" javac -Xlint:all,-processing -d "$tmpd" "$file" 2>&1)
743
+ rc=$?
744
+ else
745
+ out=$(javac -Xlint:all,-processing -d "$tmpd" "$file" 2>&1)
746
+ rc=$?
747
+ fi
748
+ rm -rf "$tmpd"
749
+
750
+ # timeout(1) reports 124 when it fired. Returning 0 here would be
751
+ # indistinguishable from "compiled clean" (walkthrough round 2, CI-02), so
752
+ # signal incompleteness with a dedicated non-numeric marker the caller checks.
753
+ if [ "$rc" -eq 124 ]; then
754
+ printf 'TIMEOUT\n'
755
+ return 0
756
+ fi
757
+
758
+ # javac prefixes each warning with "warning:" (localised builds may differ), so
759
+ # also count the "[category]" marker lines that every -Xlint diagnostic emits.
760
+ printf '%s\n' "$out" | grep -cE 'warning:|\[(rawtypes|unchecked|deprecation|fallthrough|finally|cast|static|try|overrides|overloads|serial|synchronization)\]' || true
761
+ }
762
+
763
+ # ---------------------------------------------------------------------------
764
+ # Java analysis stage. Verdict semantics mirror the C/C++ stage:
765
+ # 0 PASS, 1 FAIL, 2 BLOCK(untrustworthy), 3 WARN (no toolchain / degraded).
766
+ # ---------------------------------------------------------------------------
767
+ gate13_run_java_analysis() {
768
+ local srcs had_tool=0 degraded=0 files f cnt total=0
769
+
770
+ if gate13_is_disabled; then
771
+ gate13_reason "Gate 13 disabled via XP_GATE_DISABLE_13=1"
772
+ echo "SKIPPED - compiler strictness check (XP_GATE_DISABLE_13=1)"
773
+ return "$GATE13_WARN"
774
+ fi
775
+
776
+ srcs=$(gate13_java_sources)
777
+ if [ -z "$srcs" ]; then
778
+ return "$GATE13_PASS"
779
+ fi
780
+
781
+ if [ "${GATE13_FORCE_NO_JAVA_TOOLCHAIN:-}" = "1" ]; then
782
+ echo "WARN - no usable Java toolchain (mvn / gradle / javac); Java compiler checks NOT performed."
783
+ return "$GATE13_WARN"
784
+ fi
785
+
786
+ # ── Maven path ────────────────────────────────────────────────────────────
787
+ if [ -f "pom.xml" ]; then
788
+ if [ -x "./mvnw" ]; then
789
+ had_tool=1
790
+ elif command -v mvn >/dev/null 2>&1; then
791
+ had_tool=1
792
+ fi
793
+
794
+ if [ "$had_tool" -eq 1 ]; then
795
+ local mvn_bin="mvn"
796
+ [ -x "./mvnw" ] && mvn_bin="./mvnw"
797
+
798
+ if ! gate13_maven_injection_reliable "pom.xml" 2>/dev/null; then
799
+ echo " ⚠️ DEGRADED - Maven compiler-arg injection unreliable (see reasons below);"
800
+ echo " Java lint findings are REPORT-ONLY for this run (this is a degraded mode, not a normal warn-only run)."
801
+ degraded=1
802
+ fi
803
+
804
+ local args budget rc mvn_out mvn_log mvn_findings
805
+ args=$(gate13_maven_args)
806
+ budget=$(gate13_timeout_budget)
807
+ mvn_log="${TMPDIR:-/tmp}/gate13_mvn_$$.log"
808
+
809
+ # Capture BOTH streams. This is the whole point of REQ-004: `mvn compile`
810
+ # EXITS 0 even when javac emitted warnings, so a verdict derived from the
811
+ # exit code alone can never see a -Xlint finding. (Walkthrough review CI-01
812
+ # caught exactly that: the first implementation redirected to /dev/null and
813
+ # printed PASSED no matter what javac said.)
814
+ if command -v timeout >/dev/null 2>&1; then
815
+ # shellcheck disable=SC2086
816
+ timeout "$budget" "$mvn_bin" $args >"$mvn_log" 2>&1
817
+ else
818
+ # shellcheck disable=SC2086
819
+ "$mvn_bin" $args >"$mvn_log" 2>&1
820
+ fi
821
+ rc=$?
822
+ mvn_out=$(cat "$mvn_log" 2>/dev/null)
823
+ rm -f "$mvn_log"
824
+
825
+ if [ "$rc" -eq 124 ]; then
826
+ gate13_classify_timeout
827
+ return "$GATE13_WARN"
828
+ fi
829
+ if [ "$rc" -ne 0 ]; then
830
+ if [ "$degraded" -eq 1 ]; then
831
+ # We already know the lint flags were not applied, so a build failure
832
+ # here says nothing about compiler strictness — it is usually missing
833
+ # offline dependencies. Reporting it as FAIL would blame this gate for
834
+ # a build-environment problem (and would be a lie: nothing was linted).
835
+ echo " ⚠️ Java build failed (mvn exit ${rc}) in degraded mode — not attributed to Gate 13"
836
+ return "$GATE13_WARN"
837
+ fi
838
+ # A non-zero exit in a run where the lint flags WERE applied means javac
839
+ # found something (with -Werror in a project config) or the code does not
840
+ # compile. Either way it is a real finding, not an environment problem.
841
+ echo " ❌ Java compilation failed (mvn exit ${rc})"
842
+ printf '%s\n' "$mvn_out" | grep -E 'ERROR|WARNING' | head -10 | sed 's/^/ /'
843
+ return "$GATE13_FAIL"
844
+ fi
845
+
846
+ if [ "$degraded" -eq 1 ]; then
847
+ echo " ⚠️ DEGRADED - Java compiled but lint enforcement was NOT applied; no conclusion drawn"
848
+ return "$GATE13_WARN"
849
+ fi
850
+
851
+ # Count javac's lint output. Maven prefixes it with "[WARNING] ".
852
+ #
853
+ # #659: this used to be an English `[WARNING]...[allow-listed-category]`
854
+ # regex. Applied to a localised build -- or to a JDK category the list does
855
+ # not name -- it returned 0 on code javac had warned about, and the gate then
856
+ # printed PASSED. The shared counter below is marker- and locale-proof and
857
+ # fails closed (#499/#570). It lives in one place so the Maven path and the
858
+ # direct-javac path can never disagree about what counts as a finding.
859
+ mvn_findings=$(gate13_count_lint_findings "$mvn_out")
860
+ mvn_findings=${mvn_findings:-0}
861
+ case "$mvn_findings" in ''|*[!0-9]*) mvn_findings=0 ;; esac
862
+
863
+ if [ "$mvn_findings" -gt 0 ]; then
864
+ printf '%s\n' "$mvn_out" \
865
+ | grep -E '\[[a-z][a-z0-9-]*\]|warning:' | head -10 | sed 's/^/ /'
866
+ echo " ❌ ${mvn_findings} javac -Xlint finding(s)"
867
+ return "$GATE13_FAIL"
868
+ fi
869
+
870
+ echo " ✅ PASSED - Java compiled with -Xlint:all,-processing (no findings)"
871
+ return "$GATE13_PASS"
872
+ fi
873
+ fi
874
+
875
+ # ── Gradle path ───────────────────────────────────────────────────────────
876
+ if [ -f "build.gradle" ] || [ -f "build.gradle.kts" ]; then
877
+ if [ -x "./gradlew" ] || command -v gradle >/dev/null 2>&1; then
878
+ local g_bin="gradle"
879
+ [ -x "./gradlew" ] && g_bin="./gradlew"
880
+ local budget g_log grc g_out g_findings
881
+ budget=$(gate13_timeout_budget)
882
+ g_log="${TMPDIR:-/tmp}/gate13_gradle_$$.log"
883
+
884
+ # Same reasoning as the Maven path: capture the output, because a
885
+ # successful `compileJava` still carries the javac warnings.
886
+ # NOTE: no -q here — it suppresses exactly the diagnostics we want, the
887
+ # same trap that made -q wrong for Maven.
888
+ if command -v timeout >/dev/null 2>&1; then
889
+ timeout "$budget" "$g_bin" compileJava --offline --warning-mode all >"$g_log" 2>&1
890
+ else
891
+ "$g_bin" compileJava --offline --warning-mode all >"$g_log" 2>&1
892
+ fi
893
+ grc=$?
894
+ g_out=$(cat "$g_log" 2>/dev/null)
895
+ rm -f "$g_log"
896
+
897
+ if [ "$grc" -eq 124 ]; then
898
+ gate13_classify_timeout
899
+ return "$GATE13_WARN"
900
+ fi
901
+ if [ "$grc" -ne 0 ]; then
902
+ echo " ❌ Java compilation failed (gradle exit ${grc})"
903
+ printf '%s\n' "$g_out" | grep -E 'error|warning' | head -10 | sed 's/^/ /'
904
+ return "$GATE13_FAIL"
905
+ fi
906
+
907
+ g_findings=$(printf '%s\n' "$g_out" \
908
+ | grep -cE '\[(rawtypes|unchecked|deprecation|fallthrough|cast|static|overrides|serial|synchronization)\]' \
909
+ | tr -d '[:space:]')
910
+ g_findings=${g_findings:-0}
911
+ if [ "$g_findings" -gt 0 ]; then
912
+ printf '%s\n' "$g_out" | grep -E 'warning:' | head -10 | sed 's/^/ /'
913
+ echo " ❌ ${g_findings} javac lint finding(s) (gradle compileJava)"
914
+ return "$GATE13_FAIL"
915
+ fi
916
+ echo " ✅ PASSED - Java compiled (gradle compileJava, no findings)"
917
+ return "$GATE13_PASS"
918
+ fi
919
+ fi
920
+
921
+ # ── Bare javac path ───────────────────────────────────────────────────────
922
+ if command -v javac >/dev/null 2>&1; then
923
+ local blocking=0 timed_out=0
924
+ while IFS= read -r f; do
925
+ [ -n "$f" ] || continue
926
+ cnt=$(gate13_javac_warning_count "$f")
927
+ # A timed-out file was NOT checked. Treating it as 0 warnings would report
928
+ # a pass for code nobody looked at (walkthrough R2 CI-02).
929
+ if [ "$cnt" = "TIMEOUT" ]; then
930
+ gate13_classify_timeout
931
+ echo " ⚠️ ${f}: javac timed out — not analysed"
932
+ timed_out=$((timed_out + 1))
933
+ continue
934
+ fi
935
+ cnt=${cnt:-0}
936
+ if [ "$cnt" -gt 0 ]; then
937
+ total=$((total + cnt))
938
+ echo " ❌ ${f}: ${cnt} javac -Xlint finding(s)"
939
+ blocking=$((blocking + 1))
940
+ fi
941
+ done <<EOF
942
+ $srcs
943
+ EOF
944
+ if [ "$blocking" -gt 0 ]; then
945
+ echo " ❌ BLOCKED - ${blocking} Java file(s) with -Xlint findings (${total} total)"
946
+ return "$GATE13_FAIL"
947
+ fi
948
+ if [ "$timed_out" -gt 0 ]; then
949
+ echo " ⚠️ WARN - ${timed_out} Java file(s) were not analysed (timeout); coverage incomplete"
950
+ return "$GATE13_WARN"
951
+ fi
952
+ echo " ✅ PASSED - Java compiler strictness (javac -Xlint:all,-processing)"
953
+ return "$GATE13_PASS"
954
+ fi
955
+
956
+ echo "WARN - no usable Java toolchain (mvn / gradle / javac); Java compiler checks NOT performed."
957
+ return "$GATE13_WARN"
958
+ }
959
+
960
+ # ============================================================================
961
+ # `-fanalyzer` PATH (REQ-005) — C files only, opt-in.
962
+ #
963
+ # Path-sensitive analysis that finds use-after-free / double-free / NULL
964
+ # dereference no warning flag reaches. OFF by default for three measured reasons:
965
+ # * speed — seconds per translation unit, not milliseconds
966
+ # * portability— GCC-only; clang errors on the flag
967
+ # * semantics — it emits NOTHING under -fsyntax-only (measured), because the
968
+ # analysis hangs off real optimisation passes. It therefore has
969
+ # to compile for real, which is why artifacts go to a temp dir
970
+ # with -c (never a linked binary, never the work tree).
971
+ # Requirement round 2 (feasibility FC-04) restricted it to .c files: C++ TUs
972
+ # through -fanalyzer are dramatically slower and noisier.
973
+ # ============================================================================
974
+
975
+ gate13_analyzer_enabled() {
976
+ [ "${XP_GATE_COMPILER_ANALYZER:-}" = "1" ]
977
+ }
978
+
979
+ # Print the staged C (not C++) files eligible for analysis.
980
+ gate13_analyzer_files() {
981
+ git diff --cached --name-only --diff-filter=d -- '*.c' 2>/dev/null
982
+ }
983
+
984
+ # Can this compiler do -fanalyzer at all?
985
+ gate13_analyzer_supported() {
986
+ local cc="$1" out tu
987
+ [ -n "$cc" ] || return 1
988
+ command -v "$cc" >/dev/null 2>&1 || return 1
989
+
990
+ tu="${GATE13_ANALYZER_TU:-}"
991
+ if [ -z "$tu" ] || [ ! -f "$tu" ]; then
992
+ tu="${TMPDIR:-/tmp}/gate13_analyzer_probe_$$.c"
993
+ printf 'int main(void) { return 0; }\n' > "$tu"
994
+ GATE13_ANALYZER_TU="$tu"
995
+ fi
996
+
997
+ out=$("$cc" -fanalyzer -fsyntax-only "$tu" 2>&1) && return 0
998
+ case "$out" in
999
+ *"unknown argument"*|*"unrecognized command-line option"*|*"unknown option"*|*"not supported"*)
1000
+ return 1
1001
+ ;;
1002
+ esac
1003
+ # It failed for another reason (e.g. no C frontend): treat as unsupported
1004
+ # rather than silently claiming the analysis ran.
1005
+ return 1
1006
+ }
1007
+
1008
+ gate13_run_analyzer() {
1009
+ local cc
1010
+ local files=""
1011
+ local f cnt total=0 blocking=0
1012
+ local workdir
1013
+
1014
+ gate13_analyzer_enabled || return 0
1015
+
1016
+ cc=$(gate13_select_cc)
1017
+ [ -n "$cc" ] || {
1018
+ echo " ⚠️ -fanalyzer requested but no C compiler is usable; analyzer stage skipped"
1019
+ return 0
1020
+ }
1021
+
1022
+ if ! gate13_analyzer_supported "$cc"; then
1023
+ echo " ℹ️ $(gate13_compiler_id "$cc") has no -fanalyzer support; analyzer stage skipped"
1024
+ return 0
1025
+ fi
1026
+
1027
+ files=$(gate13_analyzer_files)
1028
+ if [ -z "$files" ]; then
1029
+ echo " ℹ️ -fanalyzer: no staged .c files"
1030
+ return 0
1031
+ fi
1032
+
1033
+ workdir="${TMPDIR:-/tmp}/gate13_analyzer_$$"
1034
+ mkdir -p "$workdir"
1035
+
1036
+ while IFS= read -r f; do
1037
+ [ -n "$f" ] || continue
1038
+ cnt=$("$cc" -fanalyzer -c -o "$workdir/$(basename -- "$f").o" "$f" 2>&1 \
1039
+ | grep -cE 'warning:|\[-Wanalyzer' || true)
1040
+ cnt=${cnt:-0}
1041
+ if [ "$cnt" -gt 0 ]; then
1042
+ total=$((total + cnt))
1043
+ echo " ⚠️ ${f}: ${cnt} -fanalyzer finding(s)"
1044
+ blocking=$((blocking + 1))
1045
+ fi
1046
+ done <<EOF
1047
+ $files
1048
+ EOF
1049
+
1050
+ rm -rf "$workdir"
1051
+
1052
+ if [ "$total" -gt 0 ]; then
1053
+ echo " ℹ️ -fanalyzer: ${total} finding(s) across ${blocking} file(s) (advisory, opt-in stage)"
1054
+ else
1055
+ echo " ✅ -fanalyzer: clean"
1056
+ fi
1057
+ return 0
1058
+ }
1059
+
1060
+ # ---------------------------------------------------------------------------
1061
+ # AC-003-01/02/03/05 — the C/C++ analysis stage.
1062
+ #
1063
+ # Policy:
1064
+ # added file -> -Werror: ANY warning in the active tier blocks
1065
+ # modified file -> compare count to baseline; no baseline => report-only
1066
+ # untouched file -> never compiled
1067
+ # warn-only tier -> nothing blocks; findings surface as WARN
1068
+ # ---------------------------------------------------------------------------
1069
+ gate13_run_cpp_analysis() {
1070
+ local cxx budget tier flags
1071
+ local added_list="" modified_list=""
1072
+ local blocking=0 findings=0 baseline_seen=0
1073
+
1074
+ if gate13_is_disabled; then
1075
+ gate13_reason "Gate 13 disabled via XP_GATE_DISABLE_13=1"
1076
+ echo "SKIPPED - compiler strictness check (XP_GATE_DISABLE_13=1)"
1077
+ return "$GATE13_WARN"
1078
+ fi
1079
+
1080
+ budget=$(gate13_timeout_budget)
1081
+ cxx=$(gate13_select_cxx)
1082
+ local sel_rc=$?
1083
+ if [ "$sel_rc" -ne 0 ] || [ -z "$cxx" ]; then
1084
+ echo "WARN - no usable C/C++ compiler found; compiler checks NOT performed."
1085
+ echo " Install one of: g++ / clang++ (Debian: build-essential, macOS: xcode-select --install)"
1086
+ return "$GATE13_WARN"
1087
+ fi
1088
+
1089
+ if gate13_is_cross_compiling "$cxx"; then
1090
+ gate13_reason "cross-compilation detected (compiler: ${cxx}, CROSS_COMPILE=${CROSS_COMPILE:-<empty>}); skipping host-side compile checks"
1091
+ echo "WARN - cross-compilation detected: ${cxx}"
1092
+ echo " Target-architecture code is not compiled with a host compiler; compiler checks NOT performed."
1093
+ return "$GATE13_WARN"
1094
+ fi
1095
+
1096
+ tier=$(gate13_resolve_tier)
1097
+ flags=$(gate13_cpp_flags "$tier" cpp)
1098
+ local probed
1099
+ # shellcheck disable=SC2086 # $flags is a deliberately word-split flag list
1100
+ probed=$(gate13_probe_flags "$cxx" cpp $flags)
1101
+ [ -n "$probed" ] && flags="$probed"
1102
+
1103
+ echo "compiler: ${cxx} ($(gate13_compiler_id "$cxx"))"
1104
+ echo "strictness: ${tier} | flags: ${flags} | budget: ${budget}s"
1105
+
1106
+ local classified
1107
+ classified=$(gate13_classify_changed)
1108
+ if [ -z "$classified" ]; then
1109
+ echo " ℹ️ No staged C/C++ source files — nothing to compile"
1110
+ return "$GATE13_PASS"
1111
+ fi
1112
+
1113
+ if ! gate13_baseline_exists; then
1114
+ echo " ⚠️ baseline missing — run 'xp-gate compiler-baseline create' to enable enforcement on modified files"
1115
+ echo " (new files are still -Werror; modified files are report-only until then)"
1116
+ fi
1117
+
1118
+ local f kind cnt base
1119
+ while IFS=$'\t' read -r kind f; do
1120
+ [ -n "$f" ] || continue
1121
+
1122
+ if [ "$kind" = "added" ]; then
1123
+ # AC-003-01: an added file's baseline count is inherently zero, so it is
1124
+ # enforced even without a baseline file.
1125
+ cnt=$(gate13_count_warnings "$cxx" "$flags" "$f")
1126
+ cnt=${cnt:-0}
1127
+ if [ "$cnt" -gt 0 ]; then
1128
+ findings=$((findings + cnt))
1129
+ if [ "$tier" = "warn-only" ]; then
1130
+ echo " ⚠️ ${f}: ${cnt} warning(s) (warn-only tier, not blocking)"
1131
+ else
1132
+ echo " ❌ ${f}: ${cnt} warning(s) in a NEW file"
1133
+ blocking=$((blocking + 1))
1134
+ fi
1135
+ fi
1136
+ else
1137
+ # AC-003-02/03: modified file.
1138
+ base=$(gate13_baseline_count "$f")
1139
+ if [ -z "$base" ]; then
1140
+ baseline_seen=1
1141
+ cnt=$(gate13_count_warnings "$cxx" "$flags" "$f")
1142
+ echo " ℹ️ ${f}: ${cnt:-0} warning(s) (no baseline entry, report-only)"
1143
+ continue
1144
+ fi
1145
+ cnt=$(gate13_count_warnings "$cxx" "$flags" "$f")
1146
+ cnt=${cnt:-0}
1147
+ if [ "$cnt" -gt "$base" ]; then
1148
+ findings=$((findings + cnt))
1149
+ if [ "$tier" = "warn-only" ]; then
1150
+ echo " ⚠️ ${f}: ${base} -> ${cnt} warning(s) (warn-only tier, not blocking)"
1151
+ else
1152
+ echo " ❌ ${f}: warning count rose ${base} -> ${cnt} (baseline exceeded)"
1153
+ blocking=$((blocking + 1))
1154
+ fi
1155
+ fi
1156
+ fi
1157
+ done <<EOF
1158
+ $classified
1159
+ EOF
1160
+
1161
+ if [ "$tier" = "warn-only" ]; then
1162
+ if [ "$findings" -gt 0 ]; then
1163
+ echo " ⚠️ WARN - ${findings} C/C++ compiler finding(s) (warn-only tier)"
1164
+ fi
1165
+ return "$GATE13_WARN"
1166
+ fi
1167
+
1168
+ if [ "$blocking" -gt 0 ]; then
1169
+ echo " ❌ BLOCKED - ${blocking} file(s) with compiler findings (${findings} warning(s) total)"
1170
+ echo " Fix the warnings, or (for pre-existing code) record a baseline:"
1171
+ echo " xp-gate compiler-baseline create"
1172
+ return "$GATE13_FAIL"
1173
+ fi
1174
+
1175
+ echo " ✅ PASSED - C/C++ compiler strictness (${tier} tier)"
1176
+
1177
+ # NOTE: gate13_run_analyzer is deliberately NOT called here. pre-commit drives
1178
+ # the three stages separately and reduces their verdicts itself; calling it in
1179
+ # both places ran -fanalyzer twice (walkthrough MC-01), doubling the slowest
1180
+ # stage for no benefit.
1181
+ return "$GATE13_PASS"
1182
+ }
1183
+
1184
+ # ============================================================================
1185
+ # C# / .NET PATH (#717 / REQ-005)
1186
+ #
1187
+ # Measured motivation, same shape as the C/C++ and Java paths above: `dotnet
1188
+ # build` on a solution with default settings reports NOTHING for a converted
1189
+ # nullable warning or an obsolete API, because MSBuild's default
1190
+ # WarningLevel/TreatWarningsAsErrors is whatever the project happens to declare.
1191
+ # `-warnaserror -p:Nullable=enable` turns the same source into hard errors --
1192
+ # which is exactly what a *compiler strictness* gate is for, and what no other
1193
+ # gate in the chain does (Gate 1 runs `dotnet format`, which formats and runs
1194
+ # analyzers but does not fail on the full compiler warning set).
1195
+ #
1196
+ # Verdict codes follow the file-level contract: 0 PASS / 1 FAIL / 2 BLOCK (tool
1197
+ # ran but output untrustworthy) / 3 WARN (tool absent, timeout, or warn-only).
1198
+ #
1199
+ # Deliberately driven by the adapter's own toolchain discovery rather than a
1200
+ # second copy of it: two independent "where is dotnet" implementations is how
1201
+ # detection and gates drift apart.
1202
+ # ============================================================================
1203
+
1204
+ # The strictness flag set for C#, decided by tier.
1205
+ #
1206
+ # Why this exists: unlike the C/C++/Java paths, the C# path used to run a bare
1207
+ # `dotnet build`, which inherits whatever the project happens to declare. A
1208
+ # project with `<TreatWarningsAsErrors>false</TreatWarningsAsErrors>` -- or one
1209
+ # that simply never set it, which is the common case -- sailed through with real
1210
+ # warnings. Measured on a fixture holding an unused field and an instance method
1211
+ # that could be static: "1 warning, 0 errors, build succeeded". The gate saw a
1212
+ # warning it could not act on, because it decides BLOCK from the build's exit
1213
+ # code. A strictness gate that depends on the audited project having declared
1214
+ # strictness is not a gate; it is a mirror.
1215
+ #
1216
+ # Passing these on the command line overrides the project-level properties --
1217
+ # measured: a project declaring TreatWarningsAsErrors=false still failed the
1218
+ # build once -warnaserror was passed. So this does not force downstream projects
1219
+ # to edit their own files.
1220
+ #
1221
+ # DELIBERATELY NOT INCLUDED -- these change compilation semantics rather than
1222
+ # raising the bar on existing code, and the C/C++/Java paths have no equivalent:
1223
+ #
1224
+ # -p:Nullable=enable
1225
+ # Turns on nullable *reference type* analysis, i.e. it opts the project
1226
+ # into a language feature it never asked for. Measured: a project without
1227
+ # it reports CS8632 ("nullable reference types only inside #nullable
1228
+ # context"); with it, the same line becomes CS8603 (possible null return).
1229
+ # Gating a legacy codebase on warnings it cannot even parse today is
1230
+ # exactly the false-BLOCK this gate must not produce.
1231
+ #
1232
+ # -p:EnforceCodeStyleInBuild=true
1233
+ # Measured to emit ZERO IDE diagnostics on a project with no .editorconfig
1234
+ # and no explicit analyzer reference -- it only amplifies configuration the
1235
+ # project already has, so it contributes nothing for the projects that most
1236
+ # need the gate and is a no-op for the rest.
1237
+ #
1238
+ # Tiers mirror the C++/Java paths:
1239
+ # balanced (default) -- warnings are errors at the highest meaningful warning
1240
+ # level, with the recommended analyzer set.
1241
+ # strict -- balanced plus every rule that is only suggestion/hidden
1242
+ # by default promoted via AnalysisMode. Measured to add
1243
+ # CA1707 (identifier contains underscore), which balanced
1244
+ # does not report at all.
1245
+ # warn-only -- no promotion (the caller downgrades the verdict to WARN
1246
+ # on its own, so an empty flag set is correct here).
1247
+ #
1248
+ # ANALYSISLEVEL IS NOT REDUNDANT with -warnaserror: the latter only promotes
1249
+ # compiler diagnostics (CS*), while analyzer rules (CA*) take their severity from
1250
+ # AnalysisLevel. Measured on the fixture above: -warnaserror alone caught CS0414
1251
+ # only; adding AnalysisLevel also caught CA1822. Passing one without the other
1252
+ # blocks half of what this gate is for.
1253
+ #
1254
+ # WARNINGLEVEL=9999 is intentional and safe: csc accepts /warn:N for N > 4 --
1255
+ # measured /warn:4, /warn:9, /warn:100, /warn:9999 and /warn:999999 all compile
1256
+ # identically with no CS1900. Only /warn:0 suppresses; there is no upper bound.
1257
+ # 9999 is used instead of 4 so that any warning level a future SDK introduces is
1258
+ # covered without this file needing a change.
1259
+ gate13_csharp_flags() {
1260
+ local tier="${1:-balanced}"
1261
+
1262
+ if [ "$tier" = "warn-only" ]; then
1263
+ printf '%s\n' ""
1264
+ return 0
1265
+ fi
1266
+
1267
+ local base="-warnaserror -p:WarningLevel=9999 -p:AnalysisLevel=latest-recommended"
1268
+
1269
+ if [ "$tier" = "strict" ]; then
1270
+ printf '%s %s\n' "$base" "-p:AnalysisMode=AllEnabledByDefault"
1271
+ return 0
1272
+ fi
1273
+
1274
+ printf '%s\n' "$base"
1275
+ }
1276
+
1277
+ # Locate the .NET SDK exactly as adapters/csharp.sh does.
1278
+ gate13_csharp_dotnet() {
1279
+ local d
1280
+ d="${DOTNET_BIN:-}"
1281
+ if [ -z "$d" ]; then
1282
+ d=$(command -v dotnet 2>/dev/null) || d=""
1283
+ fi
1284
+ [ -n "$d" ] || return 1
1285
+ "$d" --version >/dev/null 2>&1 || return 1
1286
+ printf '%s\n' "$d"
1287
+ }
1288
+
1289
+ # Print the staged .cs files (not the whole build output) that Gate 13 judges.
1290
+ gate13_csharp_sources() {
1291
+ git diff --cached --name-only --diff-filter=d -- '*.cs' 2>/dev/null
1292
+ }
1293
+
1294
+ # Print the .NET entry point to build: a solution, else a project file.
1295
+ #
1296
+ # Bare `dotnet build` in the repo root fails with MSB1003 whenever the project
1297
+ # lives in a subdirectory -- the normal layout (src/App/App.csproj) and the one
1298
+ # every fixture here uses. Measured: bare build produced no diagnostics at all
1299
+ # while `dotnet build P/P.csproj` produced the two real warnings. Resolving the
1300
+ # entry point explicitly is what makes the gate see anything.
1301
+ gate13_csharp_entry_point() {
1302
+ local f
1303
+ # A .sln is the widest scope and builds every project in it.
1304
+ f=$(git ls-files '*.sln' 2>/dev/null | head -1)
1305
+ if [ -n "$f" ]; then printf '%s
1306
+ ' "$f"; return 0; fi
1307
+ f=$(git ls-files '*.??proj' 2>/dev/null | head -1)
1308
+ if [ -n "$f" ]; then printf '%s
1309
+ ' "$f"; return 0; fi
1310
+ # Fall back to the working tree for a not-yet-tracked project.
1311
+ for f in *.sln *.??proj; do
1312
+ [ -f "$f" ] && { printf '%s
1313
+ ' "$f"; return 0; }
1314
+ done
1315
+ return 1
1316
+ }
1317
+
1318
+ # Is there a buildable .NET entry point to compile at all?
1319
+ gate13_csharp_has_manifest() {
1320
+ local f
1321
+ for f in *.sln *.csproj Directory.Build.props global.json; do
1322
+ [ -f "$f" ] && return 0
1323
+ done
1324
+ # A nested layout is normal (src/App/App.csproj).
1325
+ [ -n "$(git ls-files '*.*proj' '*.sln' 2>/dev/null | head -1)" ] && return 0
1326
+ return 1
1327
+ }
1328
+
1329
+ # Count compiler warnings FROM CHANGED FILES only.
1330
+ #
1331
+ # `dotnet build` reports diagnostics for the whole project, so counting every
1332
+ # warning would make a one-line change inherit the project's entire back-catalog
1333
+ # and block on work the author never touched -- the false-BLOCK that Gate 13's
1334
+ # baseline mechanism exists to prevent. Only lines naming a file this commit
1335
+ # stages are counted; everything else is baseline territory.
1336
+ gate13_csharp_changed_warning_count() {
1337
+ local dotnet="$1" out entry stage_files
1338
+ stage_files=$(git diff --cached --name-only --diff-filter=d 2>/dev/null)
1339
+ [ -n "$stage_files" ] || return 1
1340
+
1341
+ # -clp:NoSummary keeps the summary table out of the parse; --nologo drops the
1342
+ # banner.
1343
+ #
1344
+ # --no-incremental is REQUIRED, not an optimisation tradeoff. MSBuild skips
1345
+ # compilation when its outputs are newer than the sources, and a skipped
1346
+ # compile emits no diagnostics -- measured: the same tree reported 2 warnings
1347
+ # from a clean build and 0 from an immediately following incremental one. A
1348
+ # strictness gate that only sees warnings the first time is a gate that
1349
+ # silently passes forever after, which is precisely the failure mode #717
1350
+ # exists to remove.
1351
+ #
1352
+ # The entry point is passed explicitly: bare `dotnet build` in the repo root
1353
+ # dies with MSB1003 whenever the project sits in a subdirectory, emitting no
1354
+ # diagnostics at all.
1355
+ entry=$(gate13_csharp_entry_point) || return 1
1356
+
1357
+ # Strictness flags come from OUTSIDE the project, so the gate does not depend
1358
+ # on the audited repository having declared them. Empty in the warn-only tier.
1359
+ local flags
1360
+ flags=$(gate13_csharp_flags "$(gate13_resolve_tier)")
1361
+
1362
+ # shellcheck disable=SC2086 # $flags is a deliberately word-split flag list
1363
+ out=$("$dotnet" build "$entry" --nologo --no-incremental -clp:NoSummary $flags 2>&1)
1364
+
1365
+ # Report distinct CHANGED FILES, not diagnostic instances: the caller speaks in
1366
+ # files ("N changed C# file(s) carry compiler warnings"), and one file with two
1367
+ # warnings is one file to fix.
1368
+ #
1369
+ # Two normalisations are needed and both were measured, not assumed:
1370
+ # - dotnet prints ABSOLUTE Windows paths while git reports repo-relative
1371
+ # ones, so a suffix match is what relates them;
1372
+ # - the separators differ, so the diagnostic path is folded to "/" first.
1373
+ # Comparing raw strings matched nothing and reported 0 warnings on a file that
1374
+ # has two.
1375
+ printf '%s\n' "$out" \
1376
+ | grep -E ': (warning|error) [A-Z]+[0-9]+' \
1377
+ | sed -n 's/^\(.*\)(.*$/\1/p' \
1378
+ | tr '\\' '/' \
1379
+ | sort -u \
1380
+ | while IFS= read -r f; do
1381
+ [ -n "$f" ] || continue
1382
+ while IFS= read -r s; do
1383
+ [ -n "$s" ] || continue
1384
+ case "$f" in
1385
+ *"$s") printf '%s\n' "$s"; break ;;
1386
+ esac
1387
+ done <<EOF3
1388
+ $stage_files
1389
+ EOF3
1390
+ done \
1391
+ | sort -u | wc -l | tr -d ' '
1392
+ }
1393
+
1394
+ gate13_run_csharp_analysis() {
1395
+ local dotnet sources tier changed_count base
1396
+
1397
+ # gate13_is_disabled takes no argument: it reads the single repo-wide
1398
+ # XP_GATE_DISABLE_13 switch, which disables every language path together.
1399
+ if gate13_is_disabled; then
1400
+ gate13_reason "compiler strictness disabled (XP_GATE_DISABLE_13=1)"
1401
+ return "$GATE13_PASS"
1402
+ fi
1403
+
1404
+ sources=$(gate13_csharp_sources)
1405
+ if [ -z "$sources" ]; then
1406
+ return "$GATE13_PASS"
1407
+ fi
1408
+
1409
+ if ! gate13_csharp_has_manifest; then
1410
+ # .cs files staged with no project to compile them into. Not a pass -- the
1411
+ # gate genuinely could not judge them -- but not a block either.
1412
+ gate13_reason "no .sln/.csproj found; C# sources not compiled"
1413
+ echo " ⏭️ SKIPPED - no .NET project to compile (.cs staged without a manifest)"
1414
+ return "$GATE13_WARN"
1415
+ fi
1416
+
1417
+ dotnet=$(gate13_csharp_dotnet) || {
1418
+ gate13_reason "dotnet SDK not found"
1419
+ echo " ⏭️ SKIPPED - dotnet SDK not installed"
1420
+ return "$GATE13_WARN"
1421
+ }
1422
+
1423
+ tier=$(gate13_resolve_tier)
1424
+ changed_count=$(gate13_csharp_changed_warning_count "$dotnet") || changed_count=0
1425
+ changed_count=${changed_count:-0}
1426
+
1427
+ if [ "$changed_count" -eq 0 ]; then
1428
+ echo " ✅ PASSED - C# compiler strictness (no warnings in changed files)"
1429
+ return "$GATE13_PASS"
1430
+ fi
1431
+
1432
+ echo " ℹ️ ${changed_count} changed C# file(s) carry compiler warnings"
1433
+
1434
+ if [ "$tier" = "warn-only" ]; then
1435
+ echo " ⚠️ WARN - ${changed_count} C# file(s) with compiler warnings (warn-only tier)"
1436
+ return "$GATE13_WARN"
1437
+ fi
1438
+
1439
+ echo " ❌ BLOCKED - ${changed_count} changed C# file(s) with compiler warnings"
1440
+ echo " Turn the warnings into zero, or record a baseline:"
1441
+ echo " xp-gate compiler-baseline create"
1442
+ return "$GATE13_FAIL"
1443
+ }