@boyingliu01/xp-gate 0.38.18 → 0.38.20

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.
@@ -91,6 +91,125 @@ case "${XP_GATE_SASTD:-direct}" in
91
91
  ;;
92
92
  esac
93
93
 
94
+ # ============================================================================
95
+ # SEMGREP RULESET CACHE
96
+ #
97
+ # `--config=p/security-audit` is a REGISTRY name: semgrep fetches the ruleset
98
+ # from semgrep.dev on every invocation. Nothing local is reused (~/.semgrep is
99
+ # settings only), so the gate waits on the network on every commit.
100
+ #
101
+ # Measured over the 420 gate-10 rows in .xp-gate/audit.jsonl:
102
+ # p10 314 ms | p50 10231 ms | p90 180118 ms | mean 43620 ms
103
+ # 243 runs <= 15 s, but 106 over 60 s and 42 at the 180 s timeout.
104
+ # The distribution is bimodal and the long half is not analysis. ABBA on this
105
+ # machine, one small file, alternating arms:
106
+ # A registry, network up : 5498 ms / 5370 ms (spread 2.4%)
107
+ # B registry, network DOWN : 108926 ms / 108791 ms (spread 0.1%)
108
+ # A 20x effect with near-zero within-arm spread. The 109 s is urllib3 retry
109
+ # backoff (MaxRetryError) against semgrep.dev, not scanning.
110
+ #
111
+ # Fetching the ruleset ONCE and passing the FILE removes the network entirely:
112
+ # local file, network up : 5578 ms
113
+ # local file, network DOWN : 5754 ms
114
+ # So the offline case drops 109 s -> 5.8 s, the online case is unchanged within
115
+ # noise, and verdicts are identical (a command-injection file reports 1 finding
116
+ # either way).
117
+ #
118
+ # The ruleset is a plain YAML document served at https://semgrep.dev/c/<name>
119
+ # (measured: 492566 bytes for p/security-audit).
120
+ #
121
+ # STALENESS IS THE RISK, and it is handled explicitly rather than ignored:
122
+ # - a cache younger than XP_GATE_SEMGREP_RULES_TTL_H (default 168 = 7 days) is
123
+ # used as-is;
124
+ # - an older cache is refreshed, and if the refresh fails the stale copy is
125
+ # still used BUT the gate announces it, because "checked with week-old rules"
126
+ # and "checked with current rules" are different claims and the operator has
127
+ # to be able to tell them apart;
128
+ # - no cache and no network falls back to the registry NAME so semgrep fails on
129
+ # its own terms and the existing runtime-error arm reports SKIP. A gate that
130
+ # cannot load rules must never PASS.
131
+ #
132
+ # The cache only ever holds a fetched document. It is not a place to hand-edit a
133
+ # ruleset and then be graded against it.
134
+ # @@RULES-RESOLVER-START@@
135
+ gate10_rules_cache_dir() {
136
+ printf '%s' "${XP_GATE_SEMGREP_RULES_DIR:-${XDG_CACHE_HOME:-$HOME/.cache}/xp-gate/semgrep-rules}"
137
+ }
138
+
139
+ # Download one registry ruleset to a file. Returns non-zero on any failure so the
140
+ # caller can decide, rather than leaving a truncated file behind that semgrep
141
+ # would reject as an unparseable config.
142
+ gate10_download() {
143
+ local ruleset="$1" dest="$2" url tmp
144
+ # p/security-audit -> https://semgrep.dev/c/p/security-audit
145
+ url="https://semgrep.dev/c/${ruleset}"
146
+ tmp="${dest}.part.$$"
147
+ if command -v curl >/dev/null 2>&1; then
148
+ # --fail so an HTTP error is a non-zero exit instead of an HTML body written
149
+ # to a file named .yml. Bounded timeouts: an unreachable registry must cost
150
+ # seconds, not the 109 s urllib3 backoff this whole block exists to avoid.
151
+ curl -fsS --max-time 30 --connect-timeout 10 -o "$tmp" "$url" 2>/dev/null || { rm -f "$tmp"; return 1; }
152
+ elif command -v wget >/dev/null 2>&1; then
153
+ wget -q -T 30 -O "$tmp" "$url" 2>/dev/null || { rm -f "$tmp"; return 1; }
154
+ else
155
+ return 1
156
+ fi
157
+ # A ruleset is a YAML document whose top level is a `rules:` list. Validate
158
+ # before installing, so a captive-portal page can never become the ruleset.
159
+ if [ ! -s "$tmp" ] || ! grep -q '^rules:' "$tmp" 2>/dev/null; then
160
+ rm -f "$tmp"
161
+ return 1
162
+ fi
163
+ mv -f "$tmp" "$dest" 2>/dev/null || { rm -f "$tmp"; return 1; }
164
+ return 0
165
+ }
166
+
167
+ # Resolve a registry name to a local file when possible.
168
+ #
169
+ # Prints the path to use for --config. Falls back to the registry name itself
170
+ # when no usable cache exists, which keeps semgrep's own diagnostics intact.
171
+ gate10_resolve_ruleset() {
172
+ local ruleset="$1" dir file ttl now age_days
173
+ dir=$(gate10_rules_cache_dir)
174
+ # Registry names contain '/', so flatten them: p/security-audit ->
175
+ # p__security-audit.yml. A flat name keeps the cache portable and greppable.
176
+ file="$dir/$(printf '%s' "$ruleset" | tr '/' '_').yml"
177
+ ttl="${XP_GATE_SEMGREP_RULES_TTL_H:-168}"
178
+
179
+ if [ -f "$file" ]; then
180
+ now=$(date +%s)
181
+ local mtime
182
+ mtime=$(stat -c %Y "$file" 2>/dev/null || stat -f %m "$file" 2>/dev/null || echo 0)
183
+ age_days=$(( (now - mtime) / 86400 ))
184
+ if [ "$mtime" -gt 0 ] && [ "$age_days" -lt "$ttl" ]; then
185
+ printf '%s' "$file"
186
+ return 0
187
+ fi
188
+ # Stale: try to refresh, and fall back to the stale copy with a warning.
189
+ if gate10_download "$ruleset" "$file" 2>/dev/null; then
190
+ printf '%s' "$file"
191
+ return 0
192
+ fi
193
+ echo " ⚠️ semgrep ruleset cache is ${age_days}d old and could not be refreshed;" >&2
194
+ echo " scanning with the cached ruleset (${file##*/})." >&2
195
+ printf '%s' "$file"
196
+ return 0
197
+ fi
198
+
199
+ # No cache: fetch once. This is the only path that pays a network round trip,
200
+ # and it happens once per TTL rather than once per commit.
201
+ if mkdir -p "$dir" 2>/dev/null && gate10_download "$ruleset" "$file" 2>/dev/null; then
202
+ printf '%s' "$file"
203
+ return 0
204
+ fi
205
+
206
+ # Nothing local and nothing fetchable: hand the registry name back so semgrep
207
+ # fails visibly and the runtime-error arm reports SKIP with its own output.
208
+ printf '%s' "$ruleset"
209
+ return 0
210
+ }
211
+ # @@RULES-RESOLVER-END@@
212
+
94
213
  # Semgrep availability check
95
214
  SEMGREP_CMD=""
96
215
  if command -v semgrep >/dev/null 2>&1; then
@@ -241,10 +360,13 @@ EOF
241
360
  # identical "filter looks like coverage" defect this issue removed from
242
361
  # Gate 4. p/csharp is loaded IN ADDITION so the security-audit rules still
243
362
  # cover the other languages in a mixed commit.
244
- SEMGREP_RULES=(--config=p/security-audit)
363
+ # Resolved through the cache above: a local FILE when one is available, else
364
+ # the registry name so semgrep fails on its own terms. Measured effect on the
365
+ # unreachable-registry case is 109 s -> 5.8 s.
366
+ SEMGREP_RULES=(--config="$(gate10_resolve_ruleset "p/security-audit")")
245
367
  if printf '%s
246
368
  ' "$SEMGREP_FILES" | grep -qE ".cs$"; then
247
- SEMGREP_RULES+=(--config=p/csharp)
369
+ SEMGREP_RULES+=(--config="$(gate10_resolve_ruleset "p/csharp")")
248
370
  fi
249
371
  SEMGREP_TIMEOUT_S="${XP_GATE_SEMGREP_TIMEOUT:-180}"
250
372
  SEMGREP_TIMED_OUT=false
@@ -424,6 +546,51 @@ console.log("");});
424
546
  # shellcheck disable=SC2034
425
547
  GATE_10_REASON="output_unparseable"
426
548
  fi
549
+ elif [ "${V_RESULTS:-0}" -eq 0 ] && printf '%s\n' "${SEMGREP_OUTPUT:-}" | grep -qi 'No code rules to run'; then
550
+ # A scan that loaded NO RULES reports results:[] and errors:[] -- a legal,
551
+ # successful, empty report, which is exactly what the PASS arm below is
552
+ # meant for. semgrep says so on stderr, and it is the only signal that
553
+ # separates this from a real clean scan:
554
+ #
555
+ # rules: [] -> "No code rules to run."
556
+ # p/security-audit -> "with 225 Code rules:"
557
+ #
558
+ # TWO EARLIER DRAFTS OF THIS CHECK WERE WRONG, and both are recorded
559
+ # because each one looked reasonable:
560
+ #
561
+ # 1. time.rules. That is semgrep's per-rule PROFILING list, empty on every
562
+ # healthy run -- a 225-rule scan reports time.rules:[]. Guarding on it
563
+ # would have turned every good scan into a SKIP.
564
+ # 2. paths.scanned == 0. Right for the empty-ruleset case, but it ALSO
565
+ # fires when the changed files are deliberately suppressed through
566
+ # .semgrepignore: measured, AC-543-02 went red because a legitimate
567
+ # "this file is ignored" result was reported as "nothing was examined".
568
+ # Deliberate suppression is a decision, not a failure.
569
+ #
570
+ # The stderr message has neither problem: it reports the rule count, which
571
+ # is the thing that actually distinguishes "could not load a ruleset" from
572
+ # "loaded a ruleset and it had nothing to say".
573
+ #
574
+ # Findings take precedence (V_RESULTS -eq 0 is required). If semgrep DID
575
+ # report something, it obviously ran, and the blocking arm must see it.
576
+ #
577
+ # #717 already found this shape once, in one language: p/security-audit
578
+ # carries no C# rules, so a .cs file with a textbook SQL injection scored 0.
579
+ # That was fixed by adding a second --config; the SHAPE -- clean because
580
+ # nothing was loaded -- stayed reachable for every other cause (registry
581
+ # unreachable mid-scan, an empty cached ruleset, a bad --config path).
582
+ #
583
+ # A security gate reporting "clean" because it loaded nothing is the
584
+ # failure the fail-closed convention exists to prevent, so this SKIPs with
585
+ # its own reason rather than folding into the clean-scan PASS.
586
+ echo " ⚠️ semgrep loaded no code rules — nothing was checked, so this is not a clean result"
587
+ echo " The ruleset was empty or could not be resolved. Try:"
588
+ echo " semgrep --config=p/security-audit <file>"
589
+ echo " ⏭️ SKIPPED - SAST (no rules loaded, nothing verified)"
590
+ GATE_10_STATUS="SKIP"
591
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
592
+ # shellcheck disable=SC2034
593
+ GATE_10_REASON="zero_rules"
427
594
  elif [ "$V_RESULTS" -eq 0 ] && { [ "$V_ERRORS" -gt 0 ] || [ "$SEMGREP_EXIT" -ne 0 ]; }; then
428
595
  # Nothing was scanned to a verdict: semgrep either failed outright
429
596
  # (nonzero exit) or completed but reported scan errors for every input
@@ -547,6 +547,19 @@ CC_POP_EOF
547
547
  RATCHET_VERDICT=$(printf '%s\n' "$CC_CSV" | evaluate_ccn_ratchet ".ccn-baseline.json")
548
548
  CC_VIOLATIONS=$(printf '%s\n' "$RATCHET_VERDICT" | grep -c '^BLOCK ' || true)
549
549
  CC_LOWER=$(printf '%s\n' "$RATCHET_VERDICT" | grep -c '^LOWER ' || true)
550
+ # #683 landed on the flat-threshold arm below and not here. The library
551
+ # emits a third kind of line -- UNVERIFIED -- for "no parsable CCN row at
552
+ # all", and this arm counted only BLOCK lines. An UNVERIFIED verdict
553
+ # therefore arrived as CC_VIOLATIONS=0 and took the PASS branch:
554
+ #
555
+ # UNVERIFIED no parsable CCN row (lizard produced no measurable function)
556
+ # ✅ PASSED - Complexity within ratchet baseline.
557
+ #
558
+ # Measured live in this repo: both lines came from one run, with
559
+ # issues_found=0 in the journal. The library's own comment states the
560
+ # rule this branch was breaking -- "'unverified' means never 'clean'".
561
+ # The ratchet cannot claim a verdict over rows it could not read.
562
+ CC_UNVERIFIED=$(printf '%s\n' "$RATCHET_VERDICT" | grep -c '^UNVERIFIED' || true)
550
563
  printf '%s\n' "$RATCHET_VERDICT" | grep -v '^OK ' || true
551
564
  if [ "${CC_LOWER:-0}" -gt 0 ]; then
552
565
  echo "ℹ️ $CC_LOWER function(s) improved below baseline — refresh with: node scripts/ccn-report.cjs --write-baseline"
@@ -557,6 +570,17 @@ CC_POP_EOF
557
570
  echo "❌ BLOCKED - $CC_VIOLATIONS function(s) violate the complexity ratchet (.ccn-baseline.json)."
558
571
  echo "Revert the increase, or refactor; refresh the baseline only via ccn-baseline-refresh commits."
559
572
  exit 1
573
+ elif [ "${CC_UNVERIFIED:-0}" -gt 0 ]; then
574
+ # WARN, not BLOCK: a tool that could not answer is an environment
575
+ # fault, and the convention for a missing tool is SKIP/WARN. What it
576
+ # must not be is a pass.
577
+ echo "⚠️ WARN - complexity ratchet could not grade the change set; nothing was verified."
578
+ echo " Run 'npx lizard --csv <files>' by hand to see why the rows are missing."
579
+ GATE_3_STATUS="WARN"
580
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
581
+ # shellcheck disable=SC2034
582
+ GATE_3_REASON="ratchet_no_parsable_rows"
583
+ GATE_3_DETAIL="mode=ratchet unverified=1"
560
584
  else
561
585
  echo "✅ PASSED - Complexity within ratchet baseline."
562
586
  GATE_3_STATUS="PASS"
@@ -15,6 +15,9 @@ IAC_FILES=$(git diff --cached --name-only --diff-filter=ACM 2>/dev/null | grep -
15
15
  # Consumed by the sourcing parent, not here (see #548).
16
16
  # shellcheck disable=SC2034
17
17
  GATE_7_SCANNED_FILES=0
18
+ # Initialised here, not only inside the adapter branch: the journal line at the
19
+ # bottom runs on EVERY path, and an unset variable there is an error under set -u.
20
+ IAC_ISSUE_COUNT=0
18
21
  if [ -z "$IAC_FILES" ]; then
19
22
  # #800: "nothing to scan" must never be rendered as "scanned and clean".
20
23
  # This branch used to print PASSED and set GATE_7_STATUS=PASS, while the report
@@ -59,13 +62,27 @@ else
59
62
  if [ $IAC_EXIT -eq 0 ]; then
60
63
  echo "✅ PASSED - IaC security scan."
61
64
  GATE_7_STATUS="PASS"
65
+ IAC_ISSUE_COUNT=0
62
66
  else
63
67
  echo ""
64
68
  echo "❌ BLOCKED - IaC security issues detected"
65
69
  echo "Fix the security issues above before committing."
66
70
  echo "Tip: Install checkov for comprehensive IaC scanning: pip install checkov"
67
71
  GATE_7_STATUS="FAIL"
68
- exit 1
72
+ # Counted from the adapter's own output instead of the hardcoded 0 this
73
+ # gate used to journal on every path, including the blocked one.
74
+ IAC_ISSUE_COUNT=$(printf '%s\n' "$IAC_OUTPUT" | grep -cE '^[[:space:]]*(❌|FAIL|ERROR|Critical|HIGH)' || true)
75
+ # The journal line must be reached ON THIS PATH, and the single call site at
76
+ # the bottom of the file is not reached: sourcing this file means `return 1`
77
+ # leaves before the bottom. The earlier `exit 1` had the same effect for a
78
+ # different reason. Measured by driving the arm with a stubbed recorder and
79
+ # a failing adapter: no AUDIT row at all, on the one outcome an operator
80
+ # most needs to find in the journal.
81
+ #
82
+ # So record here, then `return` -- not `exit` -- so the driver keeps its
83
+ # single exit point and the EXIT trap fires with the same status.
84
+ record_gate_audit "gate-7" "iac-security" "$GATE_7_STATUS" "${IAC_ISSUE_COUNT:-0}" "$GATE_7_START"
85
+ return 1
69
86
  fi
70
87
  else
71
88
  echo "ℹ️ SKIP - IaC adapter not found"
@@ -73,4 +90,6 @@ else
73
90
  GATE_7_STATUS="SKIP"
74
91
  fi
75
92
  fi
76
- record_gate_audit "gate-7" "iac-security" "$GATE_7_STATUS" "0" "$GATE_7_START"
93
+ # The single exit point for the journal, reached on every path now that the
94
+ # blocked arm returns instead of exiting.
95
+ record_gate_audit "gate-7" "iac-security" "$GATE_7_STATUS" "${IAC_ISSUE_COUNT:-0}" "$GATE_7_START"
package/gate-10.sh CHANGED
@@ -91,6 +91,125 @@ case "${XP_GATE_SASTD:-direct}" in
91
91
  ;;
92
92
  esac
93
93
 
94
+ # ============================================================================
95
+ # SEMGREP RULESET CACHE
96
+ #
97
+ # `--config=p/security-audit` is a REGISTRY name: semgrep fetches the ruleset
98
+ # from semgrep.dev on every invocation. Nothing local is reused (~/.semgrep is
99
+ # settings only), so the gate waits on the network on every commit.
100
+ #
101
+ # Measured over the 420 gate-10 rows in .xp-gate/audit.jsonl:
102
+ # p10 314 ms | p50 10231 ms | p90 180118 ms | mean 43620 ms
103
+ # 243 runs <= 15 s, but 106 over 60 s and 42 at the 180 s timeout.
104
+ # The distribution is bimodal and the long half is not analysis. ABBA on this
105
+ # machine, one small file, alternating arms:
106
+ # A registry, network up : 5498 ms / 5370 ms (spread 2.4%)
107
+ # B registry, network DOWN : 108926 ms / 108791 ms (spread 0.1%)
108
+ # A 20x effect with near-zero within-arm spread. The 109 s is urllib3 retry
109
+ # backoff (MaxRetryError) against semgrep.dev, not scanning.
110
+ #
111
+ # Fetching the ruleset ONCE and passing the FILE removes the network entirely:
112
+ # local file, network up : 5578 ms
113
+ # local file, network DOWN : 5754 ms
114
+ # So the offline case drops 109 s -> 5.8 s, the online case is unchanged within
115
+ # noise, and verdicts are identical (a command-injection file reports 1 finding
116
+ # either way).
117
+ #
118
+ # The ruleset is a plain YAML document served at https://semgrep.dev/c/<name>
119
+ # (measured: 492566 bytes for p/security-audit).
120
+ #
121
+ # STALENESS IS THE RISK, and it is handled explicitly rather than ignored:
122
+ # - a cache younger than XP_GATE_SEMGREP_RULES_TTL_H (default 168 = 7 days) is
123
+ # used as-is;
124
+ # - an older cache is refreshed, and if the refresh fails the stale copy is
125
+ # still used BUT the gate announces it, because "checked with week-old rules"
126
+ # and "checked with current rules" are different claims and the operator has
127
+ # to be able to tell them apart;
128
+ # - no cache and no network falls back to the registry NAME so semgrep fails on
129
+ # its own terms and the existing runtime-error arm reports SKIP. A gate that
130
+ # cannot load rules must never PASS.
131
+ #
132
+ # The cache only ever holds a fetched document. It is not a place to hand-edit a
133
+ # ruleset and then be graded against it.
134
+ # @@RULES-RESOLVER-START@@
135
+ gate10_rules_cache_dir() {
136
+ printf '%s' "${XP_GATE_SEMGREP_RULES_DIR:-${XDG_CACHE_HOME:-$HOME/.cache}/xp-gate/semgrep-rules}"
137
+ }
138
+
139
+ # Download one registry ruleset to a file. Returns non-zero on any failure so the
140
+ # caller can decide, rather than leaving a truncated file behind that semgrep
141
+ # would reject as an unparseable config.
142
+ gate10_download() {
143
+ local ruleset="$1" dest="$2" url tmp
144
+ # p/security-audit -> https://semgrep.dev/c/p/security-audit
145
+ url="https://semgrep.dev/c/${ruleset}"
146
+ tmp="${dest}.part.$$"
147
+ if command -v curl >/dev/null 2>&1; then
148
+ # --fail so an HTTP error is a non-zero exit instead of an HTML body written
149
+ # to a file named .yml. Bounded timeouts: an unreachable registry must cost
150
+ # seconds, not the 109 s urllib3 backoff this whole block exists to avoid.
151
+ curl -fsS --max-time 30 --connect-timeout 10 -o "$tmp" "$url" 2>/dev/null || { rm -f "$tmp"; return 1; }
152
+ elif command -v wget >/dev/null 2>&1; then
153
+ wget -q -T 30 -O "$tmp" "$url" 2>/dev/null || { rm -f "$tmp"; return 1; }
154
+ else
155
+ return 1
156
+ fi
157
+ # A ruleset is a YAML document whose top level is a `rules:` list. Validate
158
+ # before installing, so a captive-portal page can never become the ruleset.
159
+ if [ ! -s "$tmp" ] || ! grep -q '^rules:' "$tmp" 2>/dev/null; then
160
+ rm -f "$tmp"
161
+ return 1
162
+ fi
163
+ mv -f "$tmp" "$dest" 2>/dev/null || { rm -f "$tmp"; return 1; }
164
+ return 0
165
+ }
166
+
167
+ # Resolve a registry name to a local file when possible.
168
+ #
169
+ # Prints the path to use for --config. Falls back to the registry name itself
170
+ # when no usable cache exists, which keeps semgrep's own diagnostics intact.
171
+ gate10_resolve_ruleset() {
172
+ local ruleset="$1" dir file ttl now age_days
173
+ dir=$(gate10_rules_cache_dir)
174
+ # Registry names contain '/', so flatten them: p/security-audit ->
175
+ # p__security-audit.yml. A flat name keeps the cache portable and greppable.
176
+ file="$dir/$(printf '%s' "$ruleset" | tr '/' '_').yml"
177
+ ttl="${XP_GATE_SEMGREP_RULES_TTL_H:-168}"
178
+
179
+ if [ -f "$file" ]; then
180
+ now=$(date +%s)
181
+ local mtime
182
+ mtime=$(stat -c %Y "$file" 2>/dev/null || stat -f %m "$file" 2>/dev/null || echo 0)
183
+ age_days=$(( (now - mtime) / 86400 ))
184
+ if [ "$mtime" -gt 0 ] && [ "$age_days" -lt "$ttl" ]; then
185
+ printf '%s' "$file"
186
+ return 0
187
+ fi
188
+ # Stale: try to refresh, and fall back to the stale copy with a warning.
189
+ if gate10_download "$ruleset" "$file" 2>/dev/null; then
190
+ printf '%s' "$file"
191
+ return 0
192
+ fi
193
+ echo " ⚠️ semgrep ruleset cache is ${age_days}d old and could not be refreshed;" >&2
194
+ echo " scanning with the cached ruleset (${file##*/})." >&2
195
+ printf '%s' "$file"
196
+ return 0
197
+ fi
198
+
199
+ # No cache: fetch once. This is the only path that pays a network round trip,
200
+ # and it happens once per TTL rather than once per commit.
201
+ if mkdir -p "$dir" 2>/dev/null && gate10_download "$ruleset" "$file" 2>/dev/null; then
202
+ printf '%s' "$file"
203
+ return 0
204
+ fi
205
+
206
+ # Nothing local and nothing fetchable: hand the registry name back so semgrep
207
+ # fails visibly and the runtime-error arm reports SKIP with its own output.
208
+ printf '%s' "$ruleset"
209
+ return 0
210
+ }
211
+ # @@RULES-RESOLVER-END@@
212
+
94
213
  # Semgrep availability check
95
214
  SEMGREP_CMD=""
96
215
  if command -v semgrep >/dev/null 2>&1; then
@@ -241,10 +360,13 @@ EOF
241
360
  # identical "filter looks like coverage" defect this issue removed from
242
361
  # Gate 4. p/csharp is loaded IN ADDITION so the security-audit rules still
243
362
  # cover the other languages in a mixed commit.
244
- SEMGREP_RULES=(--config=p/security-audit)
363
+ # Resolved through the cache above: a local FILE when one is available, else
364
+ # the registry name so semgrep fails on its own terms. Measured effect on the
365
+ # unreachable-registry case is 109 s -> 5.8 s.
366
+ SEMGREP_RULES=(--config="$(gate10_resolve_ruleset "p/security-audit")")
245
367
  if printf '%s
246
368
  ' "$SEMGREP_FILES" | grep -qE ".cs$"; then
247
- SEMGREP_RULES+=(--config=p/csharp)
369
+ SEMGREP_RULES+=(--config="$(gate10_resolve_ruleset "p/csharp")")
248
370
  fi
249
371
  SEMGREP_TIMEOUT_S="${XP_GATE_SEMGREP_TIMEOUT:-180}"
250
372
  SEMGREP_TIMED_OUT=false
package/hooks/gate-10.sh CHANGED
@@ -91,6 +91,125 @@ case "${XP_GATE_SASTD:-direct}" in
91
91
  ;;
92
92
  esac
93
93
 
94
+ # ============================================================================
95
+ # SEMGREP RULESET CACHE
96
+ #
97
+ # `--config=p/security-audit` is a REGISTRY name: semgrep fetches the ruleset
98
+ # from semgrep.dev on every invocation. Nothing local is reused (~/.semgrep is
99
+ # settings only), so the gate waits on the network on every commit.
100
+ #
101
+ # Measured over the 420 gate-10 rows in .xp-gate/audit.jsonl:
102
+ # p10 314 ms | p50 10231 ms | p90 180118 ms | mean 43620 ms
103
+ # 243 runs <= 15 s, but 106 over 60 s and 42 at the 180 s timeout.
104
+ # The distribution is bimodal and the long half is not analysis. ABBA on this
105
+ # machine, one small file, alternating arms:
106
+ # A registry, network up : 5498 ms / 5370 ms (spread 2.4%)
107
+ # B registry, network DOWN : 108926 ms / 108791 ms (spread 0.1%)
108
+ # A 20x effect with near-zero within-arm spread. The 109 s is urllib3 retry
109
+ # backoff (MaxRetryError) against semgrep.dev, not scanning.
110
+ #
111
+ # Fetching the ruleset ONCE and passing the FILE removes the network entirely:
112
+ # local file, network up : 5578 ms
113
+ # local file, network DOWN : 5754 ms
114
+ # So the offline case drops 109 s -> 5.8 s, the online case is unchanged within
115
+ # noise, and verdicts are identical (a command-injection file reports 1 finding
116
+ # either way).
117
+ #
118
+ # The ruleset is a plain YAML document served at https://semgrep.dev/c/<name>
119
+ # (measured: 492566 bytes for p/security-audit).
120
+ #
121
+ # STALENESS IS THE RISK, and it is handled explicitly rather than ignored:
122
+ # - a cache younger than XP_GATE_SEMGREP_RULES_TTL_H (default 168 = 7 days) is
123
+ # used as-is;
124
+ # - an older cache is refreshed, and if the refresh fails the stale copy is
125
+ # still used BUT the gate announces it, because "checked with week-old rules"
126
+ # and "checked with current rules" are different claims and the operator has
127
+ # to be able to tell them apart;
128
+ # - no cache and no network falls back to the registry NAME so semgrep fails on
129
+ # its own terms and the existing runtime-error arm reports SKIP. A gate that
130
+ # cannot load rules must never PASS.
131
+ #
132
+ # The cache only ever holds a fetched document. It is not a place to hand-edit a
133
+ # ruleset and then be graded against it.
134
+ # @@RULES-RESOLVER-START@@
135
+ gate10_rules_cache_dir() {
136
+ printf '%s' "${XP_GATE_SEMGREP_RULES_DIR:-${XDG_CACHE_HOME:-$HOME/.cache}/xp-gate/semgrep-rules}"
137
+ }
138
+
139
+ # Download one registry ruleset to a file. Returns non-zero on any failure so the
140
+ # caller can decide, rather than leaving a truncated file behind that semgrep
141
+ # would reject as an unparseable config.
142
+ gate10_download() {
143
+ local ruleset="$1" dest="$2" url tmp
144
+ # p/security-audit -> https://semgrep.dev/c/p/security-audit
145
+ url="https://semgrep.dev/c/${ruleset}"
146
+ tmp="${dest}.part.$$"
147
+ if command -v curl >/dev/null 2>&1; then
148
+ # --fail so an HTTP error is a non-zero exit instead of an HTML body written
149
+ # to a file named .yml. Bounded timeouts: an unreachable registry must cost
150
+ # seconds, not the 109 s urllib3 backoff this whole block exists to avoid.
151
+ curl -fsS --max-time 30 --connect-timeout 10 -o "$tmp" "$url" 2>/dev/null || { rm -f "$tmp"; return 1; }
152
+ elif command -v wget >/dev/null 2>&1; then
153
+ wget -q -T 30 -O "$tmp" "$url" 2>/dev/null || { rm -f "$tmp"; return 1; }
154
+ else
155
+ return 1
156
+ fi
157
+ # A ruleset is a YAML document whose top level is a `rules:` list. Validate
158
+ # before installing, so a captive-portal page can never become the ruleset.
159
+ if [ ! -s "$tmp" ] || ! grep -q '^rules:' "$tmp" 2>/dev/null; then
160
+ rm -f "$tmp"
161
+ return 1
162
+ fi
163
+ mv -f "$tmp" "$dest" 2>/dev/null || { rm -f "$tmp"; return 1; }
164
+ return 0
165
+ }
166
+
167
+ # Resolve a registry name to a local file when possible.
168
+ #
169
+ # Prints the path to use for --config. Falls back to the registry name itself
170
+ # when no usable cache exists, which keeps semgrep's own diagnostics intact.
171
+ gate10_resolve_ruleset() {
172
+ local ruleset="$1" dir file ttl now age_days
173
+ dir=$(gate10_rules_cache_dir)
174
+ # Registry names contain '/', so flatten them: p/security-audit ->
175
+ # p__security-audit.yml. A flat name keeps the cache portable and greppable.
176
+ file="$dir/$(printf '%s' "$ruleset" | tr '/' '_').yml"
177
+ ttl="${XP_GATE_SEMGREP_RULES_TTL_H:-168}"
178
+
179
+ if [ -f "$file" ]; then
180
+ now=$(date +%s)
181
+ local mtime
182
+ mtime=$(stat -c %Y "$file" 2>/dev/null || stat -f %m "$file" 2>/dev/null || echo 0)
183
+ age_days=$(( (now - mtime) / 86400 ))
184
+ if [ "$mtime" -gt 0 ] && [ "$age_days" -lt "$ttl" ]; then
185
+ printf '%s' "$file"
186
+ return 0
187
+ fi
188
+ # Stale: try to refresh, and fall back to the stale copy with a warning.
189
+ if gate10_download "$ruleset" "$file" 2>/dev/null; then
190
+ printf '%s' "$file"
191
+ return 0
192
+ fi
193
+ echo " ⚠️ semgrep ruleset cache is ${age_days}d old and could not be refreshed;" >&2
194
+ echo " scanning with the cached ruleset (${file##*/})." >&2
195
+ printf '%s' "$file"
196
+ return 0
197
+ fi
198
+
199
+ # No cache: fetch once. This is the only path that pays a network round trip,
200
+ # and it happens once per TTL rather than once per commit.
201
+ if mkdir -p "$dir" 2>/dev/null && gate10_download "$ruleset" "$file" 2>/dev/null; then
202
+ printf '%s' "$file"
203
+ return 0
204
+ fi
205
+
206
+ # Nothing local and nothing fetchable: hand the registry name back so semgrep
207
+ # fails visibly and the runtime-error arm reports SKIP with its own output.
208
+ printf '%s' "$ruleset"
209
+ return 0
210
+ }
211
+ # @@RULES-RESOLVER-END@@
212
+
94
213
  # Semgrep availability check
95
214
  SEMGREP_CMD=""
96
215
  if command -v semgrep >/dev/null 2>&1; then
@@ -241,10 +360,13 @@ EOF
241
360
  # identical "filter looks like coverage" defect this issue removed from
242
361
  # Gate 4. p/csharp is loaded IN ADDITION so the security-audit rules still
243
362
  # cover the other languages in a mixed commit.
244
- SEMGREP_RULES=(--config=p/security-audit)
363
+ # Resolved through the cache above: a local FILE when one is available, else
364
+ # the registry name so semgrep fails on its own terms. Measured effect on the
365
+ # unreachable-registry case is 109 s -> 5.8 s.
366
+ SEMGREP_RULES=(--config="$(gate10_resolve_ruleset "p/security-audit")")
245
367
  if printf '%s
246
368
  ' "$SEMGREP_FILES" | grep -qE ".cs$"; then
247
- SEMGREP_RULES+=(--config=p/csharp)
369
+ SEMGREP_RULES+=(--config="$(gate10_resolve_ruleset "p/csharp")")
248
370
  fi
249
371
  SEMGREP_TIMEOUT_S="${XP_GATE_SEMGREP_TIMEOUT:-180}"
250
372
  SEMGREP_TIMED_OUT=false
@@ -2,6 +2,6 @@
2
2
  "verdict": "PASS",
3
3
  "license_type": "MIT",
4
4
  "sha256": "0e7ac423bf2c6e223b7c5b156f8cf72da49d748e56a1641402c31f22ad07dbb5",
5
- "checked_at": "2026-11-18T13:52:47.564Z",
5
+ "checked_at": "2026-11-18T16:06:37.893Z",
6
6
  "source": "network"
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boyingliu01/xp-gate",
3
- "version": "0.38.18",
3
+ "version": "0.38.20",
4
4
  "description": "AI-driven development workflow: 6 quality gates + Delphi review + Sprint Flow",
5
5
  "bin": {
6
6
  "xp-gate": "bin/xp-gate.js"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xp-gate",
3
- "version": "0.38.18",
3
+ "version": "0.38.20",
4
4
  "displayName": "XP-Gate",
5
5
  "description": "Extreme Programming quality gates + AI workflow skills for Claude Code. Includes 12 pre-commit gates (Gate 0-11), 8 pre-push gates, Sprint Flow (6 phases), and Delphi multi-expert review (>=90% consensus).",
6
6
  "author": {
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.18.0
6
+ **Version:** 0.38.20.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Delphi Consensus Review — multi-round anonymous expert review (≥90% threshold, exactly 3 experts with distinct executable model IDs). Supports design, requirements, and code-walkthrough modes.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.18.0
6
+ **Version:** 0.38.20.0
7
7
 
8
8
  ## OVERVIEW
9
9
  **6-phase** development pipeline (v2.0 compact redesign, Issue #290): PREP → DESIGN → BUILD → VERIFY → SHIP → CLOSE. Phase 3/6 BUILD default build mode is **ralph-loop** (REQ-level iteration; each REQ starts from a clean context instead of accumulating one across REQs). HARD-GATE between DESIGN (2/6) and BUILD (3/6): design must pass Delphi review (≥90% consensus) before any coding.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.18.0
6
+ **Version:** 0.38.20.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Test-Specification Alignment Engine — two-stage validation ensuring tests accurately reflect requirements and design specs.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.18.0
6
+ **Version:** 0.38.20.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Delphi Consensus Review — multi-round anonymous expert review (≥90% threshold, exactly 3 experts with distinct executable model IDs). Supports design, requirements, and code-walkthrough modes.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.18.0
6
+ **Version:** 0.38.20.0
7
7
 
8
8
  ## OVERVIEW
9
9
  **6-phase** development pipeline (v2.0 compact redesign, Issue #290): PREP → DESIGN → BUILD → VERIFY → SHIP → CLOSE. Phase 3/6 BUILD default build mode is **ralph-loop** (REQ-level iteration; each REQ starts from a clean context instead of accumulating one across REQs). HARD-GATE between DESIGN (2/6) and BUILD (3/6): design must pass Delphi review (≥90% consensus) before any coding.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.18.0
6
+ **Version:** 0.38.20.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Test-Specification Alignment Engine — two-stage validation ensuring tests accurately reflect requirements and design specs.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boyingliu01/opencode-plugin",
3
- "version": "0.38.18",
3
+ "version": "0.38.20",
4
4
  "type": "module",
5
5
  "main": "index.ts",
6
6
  "description": "XP-Gate quality gates + AI workflow skills for OpenCode",
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.18.0
6
+ **Version:** 0.38.20.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Delphi Consensus Review — multi-round anonymous expert review (≥90% threshold, exactly 3 experts with distinct executable model IDs). Supports design, requirements, and code-walkthrough modes.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.18.0
6
+ **Version:** 0.38.20.0
7
7
 
8
8
  ## OVERVIEW
9
9
  **6-phase** development pipeline (v2.0 compact redesign, Issue #290): PREP → DESIGN → BUILD → VERIFY → SHIP → CLOSE. Phase 3/6 BUILD default build mode is **ralph-loop** (REQ-level iteration; each REQ starts from a clean context instead of accumulating one across REQs). HARD-GATE between DESIGN (2/6) and BUILD (3/6): design must pass Delphi review (≥90% consensus) before any coding.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.18.0
6
+ **Version:** 0.38.20.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Test-Specification Alignment Engine — two-stage validation ensuring tests accurately reflect requirements and design specs.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.18.0
6
+ **Version:** 0.38.20.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Delphi Consensus Review — multi-round anonymous expert review (≥90% threshold, exactly 3 experts with distinct executable model IDs). Supports design, requirements, and code-walkthrough modes.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.18.0
6
+ **Version:** 0.38.20.0
7
7
 
8
8
  ## OVERVIEW
9
9
  **6-phase** development pipeline (v2.0 compact redesign, Issue #290): PREP → DESIGN → BUILD → VERIFY → SHIP → CLOSE. Phase 3/6 BUILD default build mode is **ralph-loop** (REQ-level iteration; each REQ starts from a clean context instead of accumulating one across REQs). HARD-GATE between DESIGN (2/6) and BUILD (3/6): design must pass Delphi review (≥90% consensus) before any coding.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.18.0
6
+ **Version:** 0.38.20.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Test-Specification Alignment Engine — two-stage validation ensuring tests accurately reflect requirements and design specs.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.18.0
6
+ **Version:** 0.38.20.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Delphi Consensus Review — multi-round anonymous expert review (≥90% threshold, exactly 3 experts with distinct executable model IDs). Supports design, requirements, and code-walkthrough modes.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.18.0
6
+ **Version:** 0.38.20.0
7
7
 
8
8
  ## OVERVIEW
9
9
  **6-phase** development pipeline (v2.0 compact redesign, Issue #290): PREP → DESIGN → BUILD → VERIFY → SHIP → CLOSE. Phase 3/6 BUILD default build mode is **ralph-loop** (REQ-level iteration; each REQ starts from a clean context instead of accumulating one across REQs). HARD-GATE between DESIGN (2/6) and BUILD (3/6): design must pass Delphi review (≥90% consensus) before any coding.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.18.0
6
+ **Version:** 0.38.20.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Test-Specification Alignment Engine — two-stage validation ensuring tests accurately reflect requirements and design specs.