@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,478 @@
1
+ # shellcheck shell=bash
2
+ # ============================================================================
3
+ # GATE 10: Semgrep SAST Security Scan
4
+ # Detects security vulnerabilities (SQL injection, XSS, etc.) in staged files
5
+ # Tool: semgrep -- https://semgrep.dev
6
+ # ============================================================================
7
+
8
+ 2>&1 echo ""
9
+ 2>&1 echo "→ Gate 10: Semgrep SAST Security Scan..."
10
+ GATE_10_START=$(gate_start_ms)
11
+
12
+ GATE_10_STATUS=""
13
+ # #536: audit trail for "did this commit actually get scanned?". The report
14
+ # surfaces reason + scanned_files so a non-scan never reads as a clean PASS.
15
+ #
16
+ # GATE_10_REASON and GATE_10_SCANNED_FILES are consumed by the sourcing parent
17
+ # (pre-commit builds its report JSON from them after `source gate-10.sh`), not
18
+ # inside this file. The linter checks one file at a time and cannot see the
19
+ # consumer, so each assignment is flagged SC2034 "appears unused" -- which
20
+ # blocks Gate 1 for any repo that vendors this adapter, because that repo's own
21
+ # lint pass runs over the vendored copy (#548). Each assignment carries a
22
+ # scoped directive with that reason stated at the site.
23
+ #
24
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
25
+ # shellcheck disable=SC2034
26
+ GATE_10_REASON=""
27
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
28
+ # shellcheck disable=SC2034
29
+ GATE_10_SCANNED_FILES=0
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Which path runs semgrep: the sastd daemon (fast) or a direct invocation.
33
+ #
34
+ # A direct `semgrep scan` costs ~9s on Windows, and the bill is almost entirely
35
+ # Python import tax: `--version` alone takes 4-5s because semgrep's CLI eagerly
36
+ # imports commands.ci -> app.auth -> telemetry -> opentelemetry -> requests ->
37
+ # urllib3. Paying that once per machine in a resident process is the point of
38
+ # sastd (measured: a second in-process import costs 0ms).
39
+ #
40
+ # GATE_10_SEMGREP_PATH records what actually happened, so a reader of the report
41
+ # can tell a fast run from a degraded one without timing it.
42
+ #
43
+ # The daemon exists but is NOT the default. It is opt-in via XP_GATE_SASTD=on,
44
+ # and `auto` resolves to direct on purpose -- see the `auto` case below, which
45
+ # records the measurement that made the default a direct scan. Everything here is
46
+ # a switch plus a report field; with the default settings the gate behaves exactly
47
+ # as it did before the daemon was written.
48
+ # ---------------------------------------------------------------------------
49
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
50
+ # shellcheck disable=SC2034
51
+ GATE_10_SEMGREP_PATH="direct"
52
+ # Set to 1 when sastd was requested but unusable, so "we fell back" is a fact in
53
+ # the report rather than an inference from a missing log line. Never set when the
54
+ # daemon was not requested at all -- a plain direct run is not a degraded run.
55
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
56
+ # shellcheck disable=SC2034
57
+ GATE_10_SASTD_DEGRADED=0
58
+
59
+ # shellcheck disable=SC2034
60
+ case "${XP_GATE_SASTD:-direct}" in
61
+ off|direct|0|false|"")
62
+ # Explicitly or implicitly off: the direct path. Not a degradation.
63
+ GATE_10_SEMGREP_PATH="direct"
64
+ ;;
65
+ auto)
66
+ # `auto` deliberately does NOT select the daemon. It was meant to mean "use one
67
+ # if available", but measurement killed that default: with Gate 10's real
68
+ # ruleset (p/security-audit, 225 rules) the daemon saves ~20% in steady state
69
+ # (6.6-6.9s -> 5.2-5.4s) and is SLOWER end to end (10.5s -> 14.6s), because each
70
+ # gate run is a fresh process that pays the daemon's own startup without
71
+ # amortising it over a second call. Making that the automatic choice would tax
72
+ # every user for a benefit most of them never see.
73
+ #
74
+ # `auto` therefore behaves as "off" but says so through the `path` field, and it
75
+ # never sets degraded -- a plain direct run is not a degraded run.
76
+ GATE_10_SEMGREP_PATH="direct"
77
+ ;;
78
+ on|1|true)
79
+ # Opt-in only. The user asserted a daemon SHOULD be here; whether one actually
80
+ # answers can only be known after the probe, so the degrade flag is set there.
81
+ # Setting it at parse time would report a failure before anything has failed.
82
+ # This is the branch that must never become "skip the scan and call it a pass".
83
+ GATE_10_SEMGREP_PATH="daemon"
84
+ ;;
85
+ *)
86
+ # An unrecognised value is a configuration mistake, not a reason to scan
87
+ # less. Use the direct path and name the value so it can be fixed.
88
+ GATE_10_SEMGREP_PATH="direct"
89
+ GATE_10_SASTD_DEGRADED=1
90
+ echo " ⚠️ XP_GATE_SASTD='${XP_GATE_SASTD}' is not recognised (expected off|auto|on) — using direct semgrep" >&2
91
+ ;;
92
+ esac
93
+
94
+ # Semgrep availability check
95
+ SEMGREP_CMD=""
96
+ if command -v semgrep >/dev/null 2>&1; then
97
+ SEMGREP_CMD="semgrep"
98
+ elif [ -f "$HOME/.local/bin/semgrep" ]; then
99
+ SEMGREP_CMD="$HOME/.local/bin/semgrep"
100
+ else
101
+ # #572: Windows pip --user installs land in
102
+ # %APPDATA%\Python\<ver>\Scripts\semgrep.exe, which git-bash does NOT inherit
103
+ # on PATH -- so a working, installed semgrep read as "not installed" and this
104
+ # SAST gate degraded to WARN on the platform the project is developed on.
105
+ # The glob is expanded by the shell (one candidate per Python version) and
106
+ # probed by EXIT CODE, never by parsing `semgrep --version` output: a broken
107
+ # install can still print a plausible version string, and the probe must
108
+ # distinguish "runnable" from "present".
109
+ for candidate in "$HOME"/AppData/Roaming/Python/*/Scripts/semgrep.exe; do
110
+ [ -f "$candidate" ] || continue
111
+ if "$candidate" --version >/dev/null 2>&1; then
112
+ SEMGREP_CMD="$candidate"
113
+ break
114
+ fi
115
+ done
116
+ fi
117
+
118
+ if [ -z "$SEMGREP_CMD" ]; then
119
+ echo " ⚠️ WARN - semgrep not installed — SAST scanning unavailable"
120
+ echo " Install: brew install semgrep (macOS) | pip install semgrep (Linux) | pip install semgrep (Windows)"
121
+ echo " Pre-cache rules: semgrep --config=p/security-audit"
122
+ echo " Gate 10: SAST Security (WARN, semgrep not installed)"
123
+ GATE_10_STATUS="WARN"
124
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
125
+ # shellcheck disable=SC2034
126
+ GATE_10_REASON="tool_not_installed"
127
+ else
128
+ # Get staged files filtered to Semgrep-supported languages.
129
+ # #547 finding 3: ps1|psm1 were missing, so a PowerShell-only commit never
130
+ # reached semgrep even when Gate 10 ran -- the SAST gate was simply absent
131
+ # for that language.
132
+ SEMGREP_FILES=$(git diff --cached --name-only --diff-filter=ACM 2>/dev/null | grep -E '\.(ts|tsx|js|jsx|py|go|java|c|cpp|cs|rb|php|scala|swift|ps1|psm1)$' || true)
133
+
134
+ if [ -z "$SEMGREP_FILES" ]; then
135
+ echo " ⏭️ SKIPPED - SAST (no supported language files changed)"
136
+ GATE_10_STATUS="SKIP"
137
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
138
+ # shellcheck disable=SC2034
139
+ GATE_10_REASON="no_supported_files"
140
+ else
141
+ # One path per line into an array. Quoting the newline-joined list would hand
142
+ # semgrep ONE argument containing newlines -> "Invalid scanning root" once
143
+ # >=2 files are staged (#490). Same defect class as the Gate 4 --files fix
144
+ # (#457): an array is the only form that keeps spaces intact AND splits files.
145
+ #
146
+ # Each element gets a ./ prefix: a tracked path may legitimately start with
147
+ # '-' (`git add -- ./-o.ts`), and bare in argv that element reads as an option
148
+ # and rewrites the scan it was meant to constrain. ./ is a path to every
149
+ # argument parser.
150
+ #
151
+ # The unquoted heredoc below expands $SEMGREP_FILES once, then feeds literal
152
+ # lines to `read`; bash never rescans the result for separators. Its correct
153
+ # reading rests on one property of the producer above, not of the loop:
154
+ # `git diff --cached --name-only` terminates paths with LF and quotes control
155
+ # by AC-490-04.
156
+ #
157
+ # #543: semgrep 1.171 ignores .semgrepignore ENTIRELY when files are passed
158
+ # as explicit targets (measured: file target -> an ignored finding survives
159
+ # every suppression form — ignore patterns, --exclude, --exclude-rule,
160
+ # --project-root; directory target + --include -> the ignore file is honored,
161
+ # proven fail-closed by removing it and watching the findings return). The
162
+ # gate therefore passes each staged file's DIRECTORY as a target plus one
163
+ # --include per staged basename. Coverage stays exact for the staged set
164
+ # (verified: scanned == staged); the only widening is same-basename siblings
165
+ # outside the staged set, which scan too — scanning MORE is the safe side.
166
+ SEMGREP_ARGS=()
167
+ SEMGREP_FILE_COUNT=0
168
+ SEMGREP_DIRS_SEEN=$'\n'
169
+ while IFS= read -r _semgrep_file; do
170
+ [ -n "$_semgrep_file" ] || continue
171
+ SEMGREP_FILE_COUNT=$((SEMGREP_FILE_COUNT + 1))
172
+ SEMGREP_ARGS+=("--include=${_semgrep_file##*/}")
173
+ # A repo-root file has no slash at all, so "%/*" returns it unchanged and
174
+ # the old comment's assumption (`"./x.ts" strips to "./"`) never held:
175
+ # the target became the FILE path dressed as a directory ("./x.ts").
176
+ # Strip only when a slash is present; otherwise the target is the repo
177
+ # root, spelled ".". Scanning "." widens the scan to the whole tree, which
178
+ # is the safe side (see the note above) and is what a root-level staged
179
+ # file requires in order to be analysed at all.
180
+ case "$_semgrep_file" in
181
+ */*) _semgrep_dir="./${_semgrep_file%/*}" ;;
182
+ *) _semgrep_dir="." ;;
183
+ esac
184
+ # #558: dedup must match WHOLE lines. The previous `case "$SEEN" in
185
+ # *"$_semgrep_dir"*)` was an unanchored substring test: once
186
+ # ./fastdl/tests was recorded, the parent ./fastdl matched it and was
187
+ # never added as a target, so a staged fastdl/a.py contributed an
188
+ # --include= with no directory to scan it in. Nothing errored and nothing
189
+ # was reported -- the file was simply not analysed, which for a security
190
+ # gate is the worst outcome: a silent net loss that looks like a pass.
191
+ # Sibling prefixes (src/api vs src/app) collapsed the same way.
192
+ case "$SEMGREP_DIRS_SEEN" in
193
+ *$'\n'"$_semgrep_dir"$'\n'*) : ;;
194
+ *) SEMGREP_ARGS+=("$_semgrep_dir"); SEMGREP_DIRS_SEEN="$SEMGREP_DIRS_SEEN$_semgrep_dir"$'\n' ;;
195
+ esac
196
+ done <<EOF
197
+ $SEMGREP_FILES
198
+ EOF
199
+
200
+ # The verdict is parsed from the JSON with node (see below), so node is a
201
+ # hard dependency of this gate — check it BEFORE spending a semgrep run
202
+ # (#518 R2): without it we would silently SKIP every finding as
203
+ # "unparseable" and lose the whole security net on minimal CI images.
204
+ if ! command -v node >/dev/null 2>&1; then
205
+ echo " ⚠️ WARN - node is not installed — Gate 10 needs it to parse semgrep's JSON verdict"
206
+ echo " Install node (https://nodejs.org); without it SAST findings cannot be classified"
207
+ echo " ⏭️ SKIPPED - SAST (node not installed)"
208
+ GATE_10_STATUS="SKIP"
209
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
210
+ # shellcheck disable=SC2034
211
+ GATE_10_REASON="tool_not_installed"
212
+ else
213
+
214
+ # Run semgrep with JSON output. stdout and stderr are captured SEPARATELY:
215
+ # --json writes findings to stdout, progress/summary lines to stderr, and the
216
+ # old `2>&1` merge poisoned the very JSON the verdict now depends on (#518).
217
+ # SEMGREP_OUTPUT keeps its name and role — what the tool said, printed on the
218
+ # SKIP path (AC-475-04).
219
+ #
220
+ # #518: the exit code does NOT carry the verdict. semgrep exits 0 even with
221
+ # ERROR-severity findings, and its exit-code semantics have drifted across
222
+ # versions and platforms (upstream currently reports findings WITH --error
223
+ # as exit 1 and failures as 2, but that mapping is not something a gate
224
+ # should bet on). The JSON carries what the exit code never could —
225
+ # per-severity counts — so the verdict is read from the JSON and the exit
226
+ # code is demoted to "did the tool itself run". --error stays OFF: it would
227
+ # add nothing the JSON does not already provide, and keeping it off leaves
228
+ # failure exit codes unambiguous for the #475 diagnostics path.
229
+ # #559: bound the run. Without a timeout, a wedged semgrep blocks the
230
+ # invocation for as long as its process lives; the fail-closed verdict logic
231
+ # below is correct but unreachable, so the hook hangs instead of judging.
232
+ # A gate that can wedge an interactive `git commit` gets bypassed with
233
+ # --no-verify, which is worse than any verdict it could have produced.
234
+ # `-k` after the primary signal: pysemgrep spinning in a syscall ignores
235
+ # SIGTERM, and the shipped 0.29 code used the same `-k 10` shape.
236
+ # #717: p/security-audit carries NO C# rules. Measured on a .cs file with
237
+ # a textbook SQL injection (string-concatenated SqlCommand) plus a
238
+ # Process.Start command injection: p/security-audit 0 findings, p/csharp 1
239
+ # ERROR (csharp-sqli). Line 69 has listed `cs` in the filter all along, so
240
+ # .cs was accepted and then scanned by a ruleset that cannot see C# -- the
241
+ # identical "filter looks like coverage" defect this issue removed from
242
+ # Gate 4. p/csharp is loaded IN ADDITION so the security-audit rules still
243
+ # cover the other languages in a mixed commit.
244
+ SEMGREP_RULES=(--config=p/security-audit)
245
+ if printf '%s
246
+ ' "$SEMGREP_FILES" | grep -qE ".cs$"; then
247
+ SEMGREP_RULES+=(--config=p/csharp)
248
+ fi
249
+ SEMGREP_TIMEOUT_S="${XP_GATE_SEMGREP_TIMEOUT:-180}"
250
+ SEMGREP_TIMED_OUT=false
251
+ SEMGREP_STDOUT_FILE=$(mktemp)
252
+ SEMGREP_EXIT=0
253
+ SEMGREP_OUTPUT=""
254
+
255
+ # Daemon path (E3). One long-lived semgrep process, so its ~2.5s import tax is
256
+ # paid once per machine instead of once per gate run: direct 3.8-4.0s vs daemon
257
+ # hot 2.1-2.3s measured on this repo.
258
+ #
259
+ # A SWITCHED path, never a replacement: every failure below falls through to
260
+ # the direct scan. The daemon may make this gate SLOWER; it must never make it
261
+ # greener (#518/#559).
262
+ if [ "$GATE_10_SEMGREP_PATH" = "daemon" ] && command -v node >/dev/null 2>&1; then
263
+ # The protocol carries exactly ONE config. Counting rather than overwriting
264
+ # matters: the previous loop kept only the last --config, so a repo with two
265
+ # would have been scanned with one and reported on as if fully checked.
266
+ rules_for_daemon=""
267
+ config_count=0
268
+ for _arg in "${SEMGREP_RULES[@]}"; do
269
+ case "$_arg" in
270
+ --config=*)
271
+ rules_for_daemon="${_arg#--config=}"
272
+ config_count=$((config_count + 1))
273
+ ;;
274
+ esac
275
+ done
276
+ # Anything the protocol cannot express exactly is left to the direct path
277
+ # rather than approximated:
278
+ # - more than one config (nothing would report the dropped one);
279
+ # - p/csharp (Gate 10 adds it for C# repos);
280
+ # - "auto" (semgrep's own rule selection, not a spec we can pass through);
281
+ # - anything with a comma, which is semgrep's multi-config shorthand;
282
+ # - a remote URL, which the daemon would resolve against its own cwd and
283
+ # registry cache instead of the one the CLI would have used.
284
+ if [ "$config_count" -ne 1 ]; then
285
+ rules_for_daemon=""
286
+ fi
287
+ case "$rules_for_daemon" in
288
+ *p/csharp*|*","*|*"://"*|auto|"") rules_for_daemon="" ;;
289
+ esac
290
+ if [ -n "$rules_for_daemon" ]; then
291
+ daemon_roots=$(printf '%s\n' "${SEMGREP_ARGS[@]}" | grep -v '^--include=' || true)
292
+ # ARGV TRAP: under `node -e` there is NO script path in argv, so the first
293
+ # user argument is argv[1]. Indexing it as argv[2] passes undefined as the
294
+ # config, semgrep raises a python TypeError, and the gate "degrades" for a
295
+ # reason unrelated to the daemon -- which is how this looked like a flaky
296
+ # integration instead of an off-by-one.
297
+ # shellcheck disable=SC2086 # one argv entry per scanning root: word splitting is intended
298
+ if DAEMON_JSON=$(XP_GATE_SASTD=on node -e 'const NL = String.fromCharCode(10);
299
+ const { requestScan } = require(process.argv[1]);
300
+ requestScan({ config: process.argv[2], roots: process.argv.slice(3) }).then((r) => {
301
+ if (!r.ok) { process.stderr.write("SASTD_UNAVAILABLE: " + r.error + NL); process.exit(3); }
302
+ process.stdout.write(JSON.stringify(r.payload));
303
+ }).catch((e) => { process.stderr.write("SASTD_UNAVAILABLE: " + e.message + NL); process.exit(3); });' "$(cd "$GATE_DIR/../src/npm-package/lib" 2>/dev/null && pwd -W)/sastd-client.js" "$rules_for_daemon" $daemon_roots 2>"$SEMGREP_STDOUT_FILE.stderr"); then
304
+ printf '%s' "$DAEMON_JSON" > "$SEMGREP_STDOUT_FILE"
305
+ SEMGREP_OUTPUT=$(cat "$SEMGREP_STDOUT_FILE.stderr" 2>/dev/null || true)
306
+ rm -f "$SEMGREP_STDOUT_FILE.stderr"
307
+ else
308
+ SEMGREP_EXIT=$?
309
+ rm -f "$SEMGREP_STDOUT_FILE.stderr"
310
+ : > "$SEMGREP_STDOUT_FILE"
311
+ case "${XP_GATE_SASTD:-direct}" in
312
+ on|1|true)
313
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
314
+ # shellcheck disable=SC2034
315
+ GATE_10_SASTD_DEGRADED=1
316
+ echo " ⚠️ sastd requested but unavailable — using direct semgrep (degraded)" >&2
317
+ ;;
318
+ *)
319
+ echo " ℹ️ sastd unavailable — using direct semgrep" >&2
320
+ ;;
321
+ esac
322
+ GATE_10_SEMGREP_PATH="direct"
323
+ fi
324
+ else
325
+ GATE_10_SEMGREP_PATH="direct"
326
+ fi
327
+ fi
328
+
329
+ if [ "$GATE_10_SEMGREP_PATH" = "direct" ] && command -v timeout >/dev/null 2>&1; then
330
+ SEMGREP_OUTPUT=$(timeout -k 10 "$SEMGREP_TIMEOUT_S" \
331
+ "$SEMGREP_CMD" scan "${SEMGREP_RULES[@]}" --json --disable-version-check \
332
+ "${SEMGREP_ARGS[@]}" 2>&1 >"$SEMGREP_STDOUT_FILE")
333
+ SEMGREP_EXIT=$?
334
+ # 124 = timeout's own "I gave up" code. 137 = 128+SIGKILL, which is what
335
+ # `timeout -k` returns when the child ignored SIGTERM and had to be
336
+ # killed -- measured with a semgrep stand-in that traps TERM. Both mean
337
+ # "bounded, no verdict", so both must be reported as a timeout; checking
338
+ # only 124 told the user their semgrep was unparseable when in fact the
339
+ # scan had been cut off.
340
+ case "$SEMGREP_EXIT" in
341
+ 124|137) SEMGREP_TIMED_OUT=true ;;
342
+ esac
343
+ elif [ "$GATE_10_SEMGREP_PATH" = "direct" ]; then
344
+ # No `timeout` on this platform (stock macOS). Say so: an unbounded run
345
+ # nobody mentioned is exactly how #559 stayed invisible for a whole
346
+ # release. The scan still runs -- refusing to scan would be a worse
347
+ # trade -- but the unbounded window is now stated.
348
+ echo " ⚠️ 'timeout' command not available — semgrep runs UNBOUNDED (install coreutils or set up gtimeout)"
349
+ SEMGREP_OUTPUT=$("$SEMGREP_CMD" scan "${SEMGREP_RULES[@]}" --json --disable-version-check \
350
+ "${SEMGREP_ARGS[@]}" 2>&1 >"$SEMGREP_STDOUT_FILE")
351
+ SEMGREP_EXIT=$?
352
+ fi
353
+
354
+ # One node pass over the JSON: first line = verdict counts, remaining lines =
355
+ # finding details. The severity vocabulary is the UNION of the two scales
356
+ # (#518): semgrep's own ERROR is its most severe tier (it maps to the old
357
+ # CRITICAL/HIGH → BLOCK intent), its WARNING/INFO align with the old
358
+ # MEDIUM/LOW → warnings-only tier. Anything OUTSIDE both lists (missing,
359
+ # empty, or a future/new tier) counts as BLOCKING — a security gate must
360
+ # fail closed on severities it does not recognize (#518 R2). Parsing
361
+ # failure degrades to PARSE=FAIL — a fail-closed SKIP below, never a PASS.
362
+ SEMGREP_VERDICT=$(node -e '
363
+ let d="";process.stdin.on("data",c=>d+=c);process.stdin.on("end",()=>{
364
+ let data;try{data=JSON.parse(d);}catch(e){console.log("PARSE=FAIL RESULTS=0 ERRORS=0 BLOCKING=0 WARNINGS=0");return;}
365
+ const results=data.results||[];const errors=data.errors||[];
366
+ const sev=r=>((r.extra&&r.extra.severity)||"").toUpperCase();
367
+ const WARNV=["WARNING","INFO","MEDIUM","LOW"];
368
+ let b=0,w=0;results.forEach(r=>{if(WARNV.indexOf(sev(r))>=0)w++;else b++;});
369
+ console.log("PARSE=OK RESULTS="+results.length+" ERRORS="+errors.length+" BLOCKING="+b+" WARNINGS="+w);
370
+ results.slice(0,5).forEach(r=>{const extra=r.extra||{};const s=sev(r)||"UNKNOWN";
371
+ console.log(" ["+s+"] "+(r.check_id||"unknown"));
372
+ console.log(" "+(r.path||"unknown")+":"+((r.start&&r.start.line)||"?")+" → "+(extra.message||"").slice(0,80));
373
+ console.log("");});
374
+ });' < "$SEMGREP_STDOUT_FILE") || SEMGREP_VERDICT="PARSE=FAIL RESULTS=0 ERRORS=0 BLOCKING=0 WARNINGS=0"
375
+
376
+ PARSE_LINE=$(printf '%s\n' "$SEMGREP_VERDICT" | sed -n '1p')
377
+ FINDING_DETAILS=$(printf '%s\n' "$SEMGREP_VERDICT" | sed -n '2,$p')
378
+ V_PARSE=$(printf '%s\n' "$PARSE_LINE" | sed -n 's/^PARSE=\([A-Z]*\) .*/\1/p')
379
+ V_RESULTS=$(printf '%s\n' "$PARSE_LINE" | sed -n 's/.* RESULTS=\([0-9]*\) .*/\1/p')
380
+ V_ERRORS=$(printf '%s\n' "$PARSE_LINE" | sed -n 's/.* ERRORS=\([0-9]*\) .*/\1/p')
381
+ V_BLOCKING=$(printf '%s\n' "$PARSE_LINE" | sed -n 's/.* BLOCKING=\([0-9]*\) .*/\1/p')
382
+ V_WARNINGS=$(printf '%s\n' "$PARSE_LINE" | sed -n 's/.* WARNINGS=\([0-9]*\)$/\1/p')
383
+ # Keep the raw stdout tail for the unparseable branch's diagnostics BEFORE
384
+ # the temp file goes away (#518 R2: stderr alone often says nothing there).
385
+ SEMGREP_STDOUT_TAIL=$(tail -5 "$SEMGREP_STDOUT_FILE" 2>/dev/null)
386
+ rm -f "$SEMGREP_STDOUT_FILE"
387
+
388
+ # Fail closed: an unparseable payload OR an OK parse with any missing count
389
+ # field (verdict-line format drift) must SKIP, never silently degrade to
390
+ # PASS (#518).
391
+ if [ "$V_PARSE" != "OK" ] || [ -z "$V_RESULTS" ] || [ -z "$V_ERRORS" ] || [ -z "$V_BLOCKING" ] || [ -z "$V_WARNINGS" ]; then
392
+ # Unparseable output: nothing the exit code claims can be trusted (#518).
393
+ # Fail closed — SKIP with diagnostics, never a PASS.
394
+ #
395
+ # #559: name a timeout as a timeout. The generic "unparseable" message
396
+ # would be true but useless here -- it points at the JSON parser when the
397
+ # real problem is that the scan was cut off. Same verdict (SKIP), but a
398
+ # diagnosis the reader can act on.
399
+ if [ "$SEMGREP_TIMED_OUT" = true ]; then
400
+ echo " ⏱️ semgrep exceeded ${SEMGREP_TIMEOUT_S}s and was killed — no verdict is possible"
401
+ echo " This is NOT a finding and NOT a clean scan. Raise XP_GATE_SEMGREP_TIMEOUT"
402
+ echo " if the repo legitimately takes longer; investigate if semgrep itself is wedged."
403
+ else
404
+ echo " ⚠️ semgrep output unparseable or verdict fields missing (exit code ${SEMGREP_EXIT}) — cannot determine verdict"
405
+ fi
406
+ if [ -n "$SEMGREP_OUTPUT" ]; then
407
+ echo " ── what semgrep reported on stderr ──"
408
+ printf '%s\n' "$SEMGREP_OUTPUT" | tail -10 | sed 's/^/ /'
409
+ fi
410
+ if [ -n "$SEMGREP_STDOUT_TAIL" ]; then
411
+ echo " ── what semgrep wrote to stdout (tail) ──"
412
+ printf '%s\n' "$SEMGREP_STDOUT_TAIL" | sed 's/^/ /'
413
+ fi
414
+ if [ "$SEMGREP_TIMED_OUT" = true ]; then
415
+ echo " ⏭️ SKIPPED - SAST (semgrep timed out after ${SEMGREP_TIMEOUT_S}s)"
416
+ GATE_10_STATUS="SKIP"
417
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
418
+ # shellcheck disable=SC2034
419
+ GATE_10_REASON="semgrep_timeout"
420
+ else
421
+ echo " ⏭️ SKIPPED - SAST (semgrep output unparseable)"
422
+ GATE_10_STATUS="SKIP"
423
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
424
+ # shellcheck disable=SC2034
425
+ GATE_10_REASON="output_unparseable"
426
+ fi
427
+ elif [ "$V_RESULTS" -eq 0 ] && { [ "$V_ERRORS" -gt 0 ] || [ "$SEMGREP_EXIT" -ne 0 ]; }; then
428
+ # Nothing was scanned to a verdict: semgrep either failed outright
429
+ # (nonzero exit) or completed but reported scan errors for every input
430
+ # (#518 R2: exit 0 + results:[] + errors:[{...}] used to fall through to
431
+ # PASS). An operational failure must neither block nor claim a pass
432
+ # (#475 kept).
433
+ echo " ⚠️ semgrep exit=${SEMGREP_EXIT}, scan errors=${V_ERRORS}, findings=${V_RESULTS} — nothing to judge"
434
+ if [ -n "$SEMGREP_OUTPUT" ]; then
435
+ echo " ── what semgrep reported ──"
436
+ printf '%s\n' "$SEMGREP_OUTPUT" | tail -10 | sed 's/^/ /'
437
+ fi
438
+ echo " ⏭️ SKIPPED - SAST (semgrep runtime error)"
439
+ GATE_10_STATUS="SKIP"
440
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
441
+ # shellcheck disable=SC2034
442
+ GATE_10_REASON="semgrep_runtime_error"
443
+ elif [ "$V_BLOCKING" -gt 0 ]; then
444
+ echo ""
445
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
446
+ echo " GATE 10: Semgrep Security Gate"
447
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
448
+ echo " CRITICAL/HIGH/ERROR: ${V_BLOCKING} ❌ BLOCKED"
449
+ echo " MEDIUM/LOW/WARNING/INFO: ${V_WARNINGS} ⚠️ warning"
450
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
451
+ echo " ❌ BLOCKED — blocking-severity vulnerability found"
452
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
453
+ echo "$FINDING_DETAILS"
454
+ # #717: a C# finding comes from p/csharp; naming only security-audit
455
+ # would send the author to a ruleset that reproduces zero hits.
456
+ echo " Run 'semgrep scan --config=p/security-audit --config=p/csharp' to review all findings."
457
+ GATE_10_STATUS="FAIL"
458
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
459
+ # shellcheck disable=SC2034
460
+ GATE_10_SCANNED_FILES=$SEMGREP_FILE_COUNT
461
+ exit 1
462
+ else
463
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
464
+ # shellcheck disable=SC2034
465
+ GATE_10_SCANNED_FILES=$SEMGREP_FILE_COUNT
466
+ echo ""
467
+ echo " ✅ PASSED - No blocking vulnerabilities (files scanned: $SEMGREP_FILE_COUNT)"
468
+ if [ "$V_WARNINGS" -gt 0 ]; then
469
+ echo " ⚠️ ${V_WARNINGS} non-blocking findings (warnings only)"
470
+ echo "$FINDING_DETAILS"
471
+ fi
472
+ GATE_10_STATUS="PASS"
473
+ fi
474
+
475
+ fi # node available
476
+ fi
477
+ fi
478
+ record_gate_audit "gate-10" "sast-security" "$GATE_10_STATUS" "0" "$GATE_10_START"