@boyingliu01/xp-gate 0.38.16 → 0.38.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/gate-10.sh CHANGED
@@ -424,6 +424,51 @@ console.log("");});
424
424
  # shellcheck disable=SC2034
425
425
  GATE_10_REASON="output_unparseable"
426
426
  fi
427
+ elif [ "${V_RESULTS:-0}" -eq 0 ] && printf '%s\n' "${SEMGREP_OUTPUT:-}" | grep -qi 'No code rules to run'; then
428
+ # A scan that loaded NO RULES reports results:[] and errors:[] -- a legal,
429
+ # successful, empty report, which is exactly what the PASS arm below is
430
+ # meant for. semgrep says so on stderr, and it is the only signal that
431
+ # separates this from a real clean scan:
432
+ #
433
+ # rules: [] -> "No code rules to run."
434
+ # p/security-audit -> "with 225 Code rules:"
435
+ #
436
+ # TWO EARLIER DRAFTS OF THIS CHECK WERE WRONG, and both are recorded
437
+ # because each one looked reasonable:
438
+ #
439
+ # 1. time.rules. That is semgrep's per-rule PROFILING list, empty on every
440
+ # healthy run -- a 225-rule scan reports time.rules:[]. Guarding on it
441
+ # would have turned every good scan into a SKIP.
442
+ # 2. paths.scanned == 0. Right for the empty-ruleset case, but it ALSO
443
+ # fires when the changed files are deliberately suppressed through
444
+ # .semgrepignore: measured, AC-543-02 went red because a legitimate
445
+ # "this file is ignored" result was reported as "nothing was examined".
446
+ # Deliberate suppression is a decision, not a failure.
447
+ #
448
+ # The stderr message has neither problem: it reports the rule count, which
449
+ # is the thing that actually distinguishes "could not load a ruleset" from
450
+ # "loaded a ruleset and it had nothing to say".
451
+ #
452
+ # Findings take precedence (V_RESULTS -eq 0 is required). If semgrep DID
453
+ # report something, it obviously ran, and the blocking arm must see it.
454
+ #
455
+ # #717 already found this shape once, in one language: p/security-audit
456
+ # carries no C# rules, so a .cs file with a textbook SQL injection scored 0.
457
+ # That was fixed by adding a second --config; the SHAPE -- clean because
458
+ # nothing was loaded -- stayed reachable for every other cause (registry
459
+ # unreachable mid-scan, an empty cached ruleset, a bad --config path).
460
+ #
461
+ # A security gate reporting "clean" because it loaded nothing is the
462
+ # failure the fail-closed convention exists to prevent, so this SKIPs with
463
+ # its own reason rather than folding into the clean-scan PASS.
464
+ echo " ⚠️ semgrep loaded no code rules — nothing was checked, so this is not a clean result"
465
+ echo " The ruleset was empty or could not be resolved. Try:"
466
+ echo " semgrep --config=p/security-audit <file>"
467
+ echo " ⏭️ SKIPPED - SAST (no rules loaded, nothing verified)"
468
+ GATE_10_STATUS="SKIP"
469
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
470
+ # shellcheck disable=SC2034
471
+ GATE_10_REASON="zero_rules"
427
472
  elif [ "$V_RESULTS" -eq 0 ] && { [ "$V_ERRORS" -gt 0 ] || [ "$SEMGREP_EXIT" -ne 0 ]; }; then
428
473
  # Nothing was scanned to a verdict: semgrep either failed outright
429
474
  # (nonzero exit) or completed but reported scan errors for every input
package/gate-7.sh CHANGED
@@ -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/hooks/gate-10.sh CHANGED
@@ -424,6 +424,51 @@ console.log("");});
424
424
  # shellcheck disable=SC2034
425
425
  GATE_10_REASON="output_unparseable"
426
426
  fi
427
+ elif [ "${V_RESULTS:-0}" -eq 0 ] && printf '%s\n' "${SEMGREP_OUTPUT:-}" | grep -qi 'No code rules to run'; then
428
+ # A scan that loaded NO RULES reports results:[] and errors:[] -- a legal,
429
+ # successful, empty report, which is exactly what the PASS arm below is
430
+ # meant for. semgrep says so on stderr, and it is the only signal that
431
+ # separates this from a real clean scan:
432
+ #
433
+ # rules: [] -> "No code rules to run."
434
+ # p/security-audit -> "with 225 Code rules:"
435
+ #
436
+ # TWO EARLIER DRAFTS OF THIS CHECK WERE WRONG, and both are recorded
437
+ # because each one looked reasonable:
438
+ #
439
+ # 1. time.rules. That is semgrep's per-rule PROFILING list, empty on every
440
+ # healthy run -- a 225-rule scan reports time.rules:[]. Guarding on it
441
+ # would have turned every good scan into a SKIP.
442
+ # 2. paths.scanned == 0. Right for the empty-ruleset case, but it ALSO
443
+ # fires when the changed files are deliberately suppressed through
444
+ # .semgrepignore: measured, AC-543-02 went red because a legitimate
445
+ # "this file is ignored" result was reported as "nothing was examined".
446
+ # Deliberate suppression is a decision, not a failure.
447
+ #
448
+ # The stderr message has neither problem: it reports the rule count, which
449
+ # is the thing that actually distinguishes "could not load a ruleset" from
450
+ # "loaded a ruleset and it had nothing to say".
451
+ #
452
+ # Findings take precedence (V_RESULTS -eq 0 is required). If semgrep DID
453
+ # report something, it obviously ran, and the blocking arm must see it.
454
+ #
455
+ # #717 already found this shape once, in one language: p/security-audit
456
+ # carries no C# rules, so a .cs file with a textbook SQL injection scored 0.
457
+ # That was fixed by adding a second --config; the SHAPE -- clean because
458
+ # nothing was loaded -- stayed reachable for every other cause (registry
459
+ # unreachable mid-scan, an empty cached ruleset, a bad --config path).
460
+ #
461
+ # A security gate reporting "clean" because it loaded nothing is the
462
+ # failure the fail-closed convention exists to prevent, so this SKIPs with
463
+ # its own reason rather than folding into the clean-scan PASS.
464
+ echo " ⚠️ semgrep loaded no code rules — nothing was checked, so this is not a clean result"
465
+ echo " The ruleset was empty or could not be resolved. Try:"
466
+ echo " semgrep --config=p/security-audit <file>"
467
+ echo " ⏭️ SKIPPED - SAST (no rules loaded, nothing verified)"
468
+ GATE_10_STATUS="SKIP"
469
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
470
+ # shellcheck disable=SC2034
471
+ GATE_10_REASON="zero_rules"
427
472
  elif [ "$V_RESULTS" -eq 0 ] && { [ "$V_ERRORS" -gt 0 ] || [ "$SEMGREP_EXIT" -ne 0 ]; }; then
428
473
  # Nothing was scanned to a verdict: semgrep either failed outright
429
474
  # (nonzero exit) or completed but reported scan errors for every input
package/hooks/gate-7.sh CHANGED
@@ -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"
@@ -159,13 +159,44 @@ PYLINT_LIST
159
159
  fi
160
160
 
161
161
  echo "Running jscpd for Go duplicate code detection..."
162
- FILES_TO_CHECK=$(echo "$CHANGED_FILES" | grep "\.go$" | head -20)
163
- if [ -n "$FILES_TO_CHECK" ]; then
162
+ # Reading one path per line into an ARRAY fixes two defects that shared this
163
+ # one line:
164
+ # - `head -20` silently dropped every .go file past the twentieth. Measured
165
+ # in a 30-file fixture: jscpd was handed 20 paths and the other 10 were
166
+ # never scanned, with no message saying so. A scan that quietly covers part
167
+ # of the change set is the same lie as one that covers none of it.
168
+ # - unquoted `$FILES_TO_CHECK` relied on word splitting, which also splits a
169
+ # path containing a space -- handing jscpd two bogus paths (#457 class,
170
+ # same fix gate 3's lizard call already carries).
171
+ # Chunked rather than one argv for the whole list: Windows caps a command line
172
+ # at 32,767 characters, and an oversized argv fails without scanning anything.
173
+ GO_JSCPD_FILES=()
174
+ while IFS= read -r _gof; do
175
+ [ -n "$_gof" ] || continue
176
+ GO_JSCPD_FILES+=("$_gof")
177
+ done <<GO_LIST
178
+ $(echo "$CHANGED_FILES" | grep "\.go$" || true)
179
+ GO_LIST
180
+ if [ "${#GO_JSCPD_FILES[@]}" -gt 0 ]; then
164
181
  # #392-#9: capture jscpd's real exit code via temp file instead of piping
165
182
  # through head (which would swallow the exit status under pipefail analysis).
166
183
  GO_JSCPD_TMP=$(mktemp)
167
- jscpd $FILES_TO_CHECK > "$GO_JSCPD_TMP" 2>&1
168
- JSCPD_GO_EXIT=$?
184
+ JSCPD_GO_EXIT=0
185
+ GO_ARGV_BUDGET="${XP_GATE_JSCPD_ARGV_BUDGET:-8000}"
186
+ GO_BATCH=()
187
+ GO_SIZE=0
188
+ for _gof in "${GO_JSCPD_FILES[@]}"; do
189
+ if [ "${#GO_BATCH[@]}" -gt 0 ] && [ $((GO_SIZE + ${#_gof} + 1)) -gt "$GO_ARGV_BUDGET" ]; then
190
+ jscpd "${GO_BATCH[@]}" >> "$GO_JSCPD_TMP" 2>&1 || JSCPD_GO_EXIT=$?
191
+ GO_BATCH=()
192
+ GO_SIZE=0
193
+ fi
194
+ GO_BATCH+=("$_gof")
195
+ GO_SIZE=$((GO_SIZE + ${#_gof} + 1))
196
+ done
197
+ if [ "${#GO_BATCH[@]}" -gt 0 ]; then
198
+ jscpd "${GO_BATCH[@]}" >> "$GO_JSCPD_TMP" 2>&1 || JSCPD_GO_EXIT=$?
199
+ fi
169
200
  head -10 "$GO_JSCPD_TMP"
170
201
  rm -f "$GO_JSCPD_TMP"
171
202
  if [ "$JSCPD_GO_EXIT" -ne 0 ]; then
@@ -191,11 +222,20 @@ PYLINT_LIST
191
222
  powershell)
192
223
  echo "ℹ️ No PowerShell-native duplicate detector (jscpd does not support .ps1)"
193
224
  echo "⏭️ SKIPPED - Duplicate code (no tool for PowerShell)"
225
+ # These two arms printed SKIP prose and set nothing. GATE_2_STATUS kept its
226
+ # initial "PASS", so the journal recorded a pass for a language that was never
227
+ # scanned -- the same defect the TypeScript/Go/generic arms just had removed,
228
+ # surviving here because these arms never claimed to have scanned anything.
229
+ # They still do not claim it; but "no verdict" was being recorded as "passed".
230
+ GATE_2_STATUS="SKIP"
231
+ GATE_2_DETAIL="no_tool_for_powershell"
194
232
  ;;
195
233
 
196
234
  shell)
197
235
  echo "ℹ️ Duplicate detection not typically used for shell scripts"
198
236
  echo "⏭️ SKIPPED - Duplicate code (no tool for shell scripts)"
237
+ GATE_2_STATUS="SKIP"
238
+ GATE_2_DETAIL="no_tool_for_shell"
199
239
  ;;
200
240
 
201
241
  *)
package/hooks/pre-commit CHANGED
@@ -987,10 +987,27 @@ record_gate_audit() {
987
987
  esac
988
988
 
989
989
  # Determine gate result: PASS or FAIL based on status variable
990
+ #
991
+ # `gate_result` answers "did this gate block?", which is the question the retry
992
+ # streak asks (it greps the journal for "passed":false). SKIP therefore stays
993
+ # "true" -- changing it would make every skip inflate the attempt index and
994
+ # rewrite every historical metric.
995
+ #
996
+ # But that leaves PASS and SKIP byte-identical in the journal, and pass_pct is
997
+ # computed as passed/total -- so a gate that skipped on every run reported a
998
+ # 100% pass rate while never having evaluated anything. The verdict the gate
999
+ # actually reached is recorded separately as gate_status, so a consumer can
1000
+ # tell the three states apart without moving the numbers that already exist.
990
1001
  local gate_result="true"
991
1002
  if [ "$passed" != "PASS" ] && [ "$passed" != "SKIP" ]; then
992
1003
  gate_result="false"
993
1004
  fi
1005
+ # Only forward a status the caller actually named; an empty/unknown value is
1006
+ # omitted rather than recorded as a guess.
1007
+ local gate_status_arg=""
1008
+ case "$passed" in
1009
+ PASS|SKIP|WARN|BLOCK) gate_status_arg="--gate-status $passed" ;;
1010
+ esac
994
1011
 
995
1012
  # Fire-and-forget: audit must never block the commit
996
1013
  #
@@ -1026,6 +1043,7 @@ record_gate_audit() {
1026
1043
  --trigger commit \
1027
1044
  ${_XP_GATE_ATTEMPT:+--attempt "$_XP_GATE_ATTEMPT"} \
1028
1045
  ${detail:+--detail "$detail"} \
1046
+ $gate_status_arg \
1029
1047
  2>/dev/null
1030
1048
  } &
1031
1049
  disown 2>/dev/null || true
@@ -1057,7 +1075,12 @@ _record_blocking_exit() {
1057
1075
  # the one that actually called exit.
1058
1076
  local _bg_id="" _bg_name="" _bg_status="" _bg_detail=""
1059
1077
  local _i _st_var _st
1060
- for _i in 0 1 2 3 4 5 6 7 8 9 10 11 12 13; do
1078
+ # Every gate key, not every NUMBER. 12b and 12c were missing from this list,
1079
+ # so a block raised by either one left _bg_id empty and the journal recorded
1080
+ # gate "unknown" with no reason -- the one case where knowing WHICH gate
1081
+ # stopped the commit matters most. The keys are strings here on purpose: they
1082
+ # match the registry and the GATE_N_STATUS variable names, not ordinals.
1083
+ for _i in 0 1 2 3 4 5 6 7 8 9 10 11 12 12b 12c 13; do
1061
1084
  _st_var="GATE_${_i}_STATUS"
1062
1085
  _st="${!_st_var:-}"
1063
1086
  case "$_st" in
@@ -1086,6 +1109,8 @@ _record_blocking_exit() {
1086
1109
  10) _bg_name="SAST Security" ;;
1087
1110
  11) _bg_name="Sprint Flow" ;;
1088
1111
  12) _bg_name="File Hygiene" ;;
1112
+ 12b) _bg_name="Mirror Parity" ;;
1113
+ 12c) _bg_name="Probe Discipline" ;;
1089
1114
  13) _bg_name="Compiler Strictness" ;;
1090
1115
  *) _bg_name="unknown" ;;
1091
1116
  esac
@@ -0,0 +1,81 @@
1
+ /**
2
+ * @test REQ-AUDIT-SKIP-DISTINGUISHABLE
3
+ * @intent The audit journal could not tell PASS from SKIP, and both counted as
4
+ * a pass.
5
+ *
6
+ * record_gate_audit received the gate's real status as its third
7
+ * argument and threw it away:
8
+ *
9
+ * local gate_result="true"
10
+ * if [ "$passed" != "PASS" ] && [ "$passed" != "SKIP" ]; then
11
+ * gate_result="false"
12
+ * fi
13
+ *
14
+ * So every SKIP row was written as passed=true. aggregateByGate then
15
+ * computes pass_pct as passed/total, which means a gate that skipped
16
+ * every single time reported a 100% pass rate while never having checked
17
+ * anything.
18
+ *
19
+ * Measured: a deselected gate-11 wrote `"passed":true` with nothing else
20
+ * distinguishing it from a real pass.
21
+ *
22
+ * The fix keeps `passed` exactly as it was — it answers "did this gate
23
+ * block?", which is still the right question for the retry streak, whose
24
+ * awk reads `"passed":false`. What is added is the status the gate
25
+ * actually reached, so a consumer can tell the three states apart.
26
+ *
27
+ * @covers AC-AUDIT-SKIP-01 AC-AUDIT-SKIP-02
28
+ */
29
+
30
+ import { describe, it, expect } from 'vitest';
31
+ import { aggregateByGate } from '../gate-audit.js';
32
+ import type { GateAuditEntry } from '../gate-audit.js';
33
+
34
+ function entry(over: Partial<GateAuditEntry>): GateAuditEntry {
35
+ return {
36
+ timestamp: '2026-11-18T00:00:00.000Z',
37
+ gate_id: 'gate-1',
38
+ gate_name: 'lint',
39
+ passed: true,
40
+ issues_found: 0,
41
+ duration_ms: 10,
42
+ trigger: 'commit',
43
+ repo_path: '/repo',
44
+ commit_hash: 'abc',
45
+ ...over,
46
+ } as GateAuditEntry;
47
+ }
48
+
49
+ describe('REQ-AUDIT-SKIP-DISTINGUISHABLE', () => {
50
+ it('AC-AUDIT-SKIP-01: a SKIP row is distinguishable from a PASS row', () => {
51
+ // Both rows have passed=true -- that is the existing, deliberate schema.
52
+ const rows: GateAuditEntry[] = [
53
+ entry({ gate_status: 'PASS' }),
54
+ entry({ gate_status: 'SKIP' }),
55
+ ];
56
+
57
+ const buckets = aggregateByGate(rows);
58
+ const b = buckets.get('gate-1');
59
+ expect(b).toBeDefined();
60
+ // The status must survive into the aggregate; without it these two rows are
61
+ // byte-identical as far as any consumer is concerned.
62
+ expect(b?.skipped).toBe(1);
63
+ expect(b?.verified).toBe(1);
64
+ });
65
+
66
+ it('AC-AUDIT-SKIP-02: a gate that only ever skips does not look like a gate that passes', () => {
67
+ const rows: GateAuditEntry[] = [
68
+ entry({ gate_id: 'gate-11', gate_status: 'SKIP' }),
69
+ entry({ gate_id: 'gate-11', gate_status: 'SKIP' }),
70
+ entry({ gate_id: 'gate-11', gate_status: 'SKIP' }),
71
+ ];
72
+
73
+ const b = aggregateByGate(rows).get('gate-11');
74
+ // verified counts only rows where something was actually evaluated.
75
+ expect(b?.verified).toBe(0);
76
+ expect(b?.skipped).toBe(3);
77
+ // The old metric must still read 100% -- it answers a different question,
78
+ // and changing it here would silently move every historical number.
79
+ expect(b?.passed).toBe(3);
80
+ });
81
+ });
package/lib/gate-audit.ts CHANGED
@@ -58,6 +58,19 @@ export interface GateAuditEntry {
58
58
  attempt?: number;
59
59
  /** True when this row describes a test that is quarantined as flaky (#603). */
60
60
  quarantined?: boolean;
61
+ /**
62
+ * The verdict the gate actually reached: PASS / WARN / SKIP / BLOCK.
63
+ *
64
+ * `passed` answers "did this gate block?" and is deliberately kept -- the
65
+ * retry streak reads `"passed":false` from the journal and every historical
66
+ * metric is defined on it. But it cannot separate a real pass from a skip,
67
+ * because both are `passed: true`. A gate that skipped on every run therefore
68
+ * reported a 100% pass rate while never having evaluated anything.
69
+ *
70
+ * Absent on rows written before this field existed. Consumers must treat
71
+ * "absent" as unknown, never as a pass.
72
+ */
73
+ gate_status?: string;
61
74
  }
62
75
 
63
76
  // ── Public API ───────────────────────────────────────────────────────────────
@@ -236,16 +249,40 @@ function parseAuditEntries(logPath: string): GateAuditEntry[] {
236
249
  /**
237
250
  * Aggregate audit entries by gate_id, computing sums for passed/ms/issues.
238
251
  */
239
- function aggregateByGate(entries: GateAuditEntry[]): Map<string, { total: number; passed: number; ms: number; issues: number; anomaly_count: number }> {
240
- const buckets = new Map<string, { total: number; passed: number; ms: number; issues: number; anomaly_count: number }>();
252
+ interface GateBucket {
253
+ total: number;
254
+ passed: number;
255
+ ms: number;
256
+ issues: number;
257
+ anomaly_count: number;
258
+ /** Rows whose gate_status was SKIP -- nothing was evaluated. */
259
+ skipped: number;
260
+ /** Rows whose gate_status says something really was evaluated. */
261
+ verified: number;
262
+ }
263
+
264
+ export function aggregateByGate(entries: GateAuditEntry[]): Map<string, GateBucket> {
265
+ const buckets = new Map<string, GateBucket>();
241
266
 
242
267
  for (const e of entries) {
243
268
  // Tolerate malformed/legacy rows: a missing gate_id would otherwise create
244
269
  // an `undefined` bucket key (and crash the sort comparing it to a string).
245
270
  const gateId = typeof e.gate_id === 'string' && e.gate_id ? e.gate_id : 'unknown';
246
- const b = buckets.get(gateId) ?? { total: 0, passed: 0, ms: 0, issues: 0, anomaly_count: 0 };
271
+ const b = buckets.get(gateId) ?? { total: 0, passed: 0, ms: 0, issues: 0, anomaly_count: 0, skipped: 0, verified: 0 };
247
272
  b.total += 1;
248
273
  if (e.passed) b.passed += 1;
274
+ // `passed` cannot tell a pass from a skip (both are true). Count the real
275
+ // verdict alongside it rather than redefining `passed`, which the retry
276
+ // streak and every historical metric already depend on.
277
+ //
278
+ // Absent status is UNKNOWN, not verified. Legacy rows predate the field;
279
+ // counting them as verified would reproduce the defect this field exists to
280
+ // fix, just in the other direction.
281
+ if (e.gate_status === 'SKIP') {
282
+ b.skipped += 1;
283
+ } else if (e.gate_status === 'PASS' || e.gate_status === 'WARN') {
284
+ b.verified += 1;
285
+ }
249
286
  // Issue #370: exclude anomalous durations from ms aggregation. REQ-B: a
250
287
  // null duration is the honest sibling of that flag — deliberately not
251
288
  // measurable, so it stays out of the sums (and out of the denominator).
@@ -438,6 +475,10 @@ function runCli(): void {
438
475
  // to what earlier versions wrote.
439
476
  ...(opts['attempt'] ? { attempt: Number.parseInt(String(opts['attempt']), 10) || 1 } : {}),
440
477
  ...(opts['quarantined'] === 'true' ? { quarantined: true } : {}),
478
+ // Only set when provided, so records from callers that do not supply it
479
+ // stay byte-identical. `passed` cannot separate a pass from a skip; this
480
+ // carries the verdict the gate actually reached.
481
+ ...(opts['gate-status'] ? { gate_status: String(opts['gate-status']).slice(0, 20) } : {}),
441
482
  };
442
483
  // Pre-commit (trigger=commit) is staging for a commit that does not exist
443
484
  // yet: park it in the pending sidecar so post-commit can stamp the real
@@ -2,6 +2,6 @@
2
2
  "verdict": "PASS",
3
3
  "license_type": "MIT",
4
4
  "sha256": "0e7ac423bf2c6e223b7c5b156f8cf72da49d748e56a1641402c31f22ad07dbb5",
5
- "checked_at": "2026-11-18T11:27:48.544Z",
5
+ "checked_at": "2026-11-18T13:52:47.564Z",
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.16",
3
+ "version": "0.38.18",
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.16",
3
+ "version": "0.38.18",
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.16.0
6
+ **Version:** 0.38.18.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.16.0
6
+ **Version:** 0.38.18.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.16.0
6
+ **Version:** 0.38.18.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.16.0
6
+ **Version:** 0.38.18.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.16.0
6
+ **Version:** 0.38.18.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.16.0
6
+ **Version:** 0.38.18.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.16",
3
+ "version": "0.38.18",
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.16.0
6
+ **Version:** 0.38.18.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.16.0
6
+ **Version:** 0.38.18.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.16.0
6
+ **Version:** 0.38.18.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.16.0
6
+ **Version:** 0.38.18.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.16.0
6
+ **Version:** 0.38.18.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.16.0
6
+ **Version:** 0.38.18.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Test-Specification Alignment Engine — two-stage validation ensuring tests accurately reflect requirements and design specs.
@@ -0,0 +1,540 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * CI driver for the BATS hook-behaviour contracts.
4
+ *
5
+ * @test REQ-CI-BATS-01
6
+ * @intent Run the SAME contracts Gate 5b used to run, in a fraction of the
7
+ * wall-clock, without weakening a single assertion.
8
+ * @covers AC-CI-BATS-01-01 (every .bats file is assigned to exactly one shard)
9
+ * @covers AC-CI-BATS-01-02 (shards are balanced by measured cost, not file count)
10
+ * @covers AC-CI-BATS-01-03 (a shard that runs nothing is a FAILURE, not a pass)
11
+ * @covers AC-CI-BATS-01-04 (the suite still runs as ONE blocking gate)
12
+ *
13
+ * WHY THIS EXISTS
14
+ * `npx bats githooks/__tests__/` was a single serial step: measured 18m47s of
15
+ * a 22m24s Gate Checks job on 2026-11-12 — 81% of the whole pipeline — and it
16
+ * had to be made non-blocking just to keep the pipeline usable.
17
+ *
18
+ * Nothing about that cost was intrinsic to the assertions. Two levers, both
19
+ * measured rather than assumed:
20
+ *
21
+ * 1. THE FILES ARE INDEPENDENT PROCESSES, SO THEY CAN RUN SIDE BY SIDE.
22
+ * Every suite builds its own fixture in `mktemp -d` and runs the hook from
23
+ * there; the only cross-file resource is the checkout itself, which they
24
+ * read (and the hook cases run their own copy, never this one). Bats
25
+ * supports `-j N` natively, but each worker costs one npm-registry call
26
+ * because `npx <tool>` inside a fixture installs the tool, so the inside-
27
+ * the-runner parallelism is an AND with tool resolution, not a substitute
28
+ * for it (see the eslint/biome fix that ships with this driver).
29
+ *
30
+ * 2. THE RUNNERS ARE SEPARATE MACHINES. A matrix shard gets its own CPU, its
31
+ * own filesystem and its own npm cache. This is the lever that does not
32
+ * depend on any fixture damage being repaired first.
33
+ *
34
+ * This driver owns (1) the shard split so it is testable and reviewable, and
35
+ * leaves (2) to the workflow matrix.
36
+ *
37
+ * THE SPLIT IS BY MEASURED COST, NOT BY FILE COUNT
38
+ * A plain round-robin split is a lie about cost: `gate-8-layers.test.bats` (8
39
+ * cases of pure grep) and `gate-8-architecture.test.bats` (20 cases that each
40
+ * run the real hook) are one file each. The table below is the per-file
41
+ * wall-clock measured on a 4-core Linux runner, and it ships WITH the split so
42
+ * the split cannot silently become "alphabetical". Unlisted files take the
43
+ * median weight, and the driver prints whenever that happens — a new suite no
44
+ * one weighed is visible in the CI log instead of quietly unbalancing a shard.
45
+ *
46
+ * The weights were measured at N; they are a starting point, not a constant.
47
+ * `--print-shards` shows the resulting split and `--report-only` writes a
48
+ * machine-readable summary so an operator can re-measure from a real run
49
+ * instead of trusting this table forever.
50
+ *
51
+ * USAGE
52
+ * node scripts/run-bats-ci.cjs --shard 1/3
53
+ * node scripts/run-bats-ci.cjs --shard 1/3 --jobs 4 --print-only
54
+ * node scripts/run-bats-ci.cjs --all --print-shards
55
+ *
56
+ * EXIT CODES
57
+ * 0 every assigned suite passed
58
+ * 1 at least one suite failed (or the runner could not start)
59
+ * 2 the shard was starved: zero files matched, or a file matched by no shard
60
+ * at all. "Ran nothing" must never read as "passed" (#636's rule, and the
61
+ * 6ebbd5a failure mode #484 was created for).
62
+ */
63
+
64
+ 'use strict';
65
+
66
+ const fs = require('node:fs');
67
+ const path = require('node:path');
68
+ const { spawnSync } = require('node:child_process');
69
+
70
+ const ROOT = path.resolve(__dirname, '..');
71
+ const BATS_DIR = path.join(ROOT, 'githooks', '__tests__');
72
+
73
+ /**
74
+ * Per-file wall-clock, milliseconds.
75
+ *
76
+ * MEASURED on a 4-core Linux box (WSL2, 2026-11-12) by running every suite on
77
+ * its own with a 45 s budget. Do not re-invent these numbers by reading the
78
+ * files: a suite's cost is the number of PROCESSES it spawns, which is
79
+ * unrelated to its line count. Two facts decided the table:
80
+ *
81
+ * 1. Suites that never finished inside 45 s during the profile are recorded
82
+ * as 50000. Measured: 13 of them, all reaching a `npx <tool>` that tries to
83
+ * INSTALL the tool on a machine without the dependency (see
84
+ * docs/plans/2026-11-12-ci-bats-runtime-optimization.md §1). That install
85
+ * trap is now fixed for the Biome and ESLint arms, which took three of the
86
+ * thirteen from "killed at 45 s" to under a second each (gate-1-linter-
87
+ * missing 45 000 ms -> 863 ms, gate-1-biome-noop -> 438 ms, adapter-
88
+ * typescript-biome-exit -> 274 ms), but the remaining sites (`npx tsc`,
89
+ * real `mvn`) still pay it on a machine without those tools, so 50000 stays
90
+ * an honest over-estimate for them. Over-estimating errs toward spreading
91
+ * heavy suites across different shards — the safe direction.
92
+ * 2. Everything under 3000 ms is not listed and takes DEFAULT_MS. Listing 175
93
+ * numbers of ±300 ms noise would make the table look precise without making
94
+ * the split better.
95
+ *
96
+ * Suites with no entry use DEFAULT_MS, which is the measured MEDIAN of this
97
+ * table's entries — not a guess. The driver prints how many suites fall back, so
98
+ * a large fallback population is visible in the CI log.
99
+ */
100
+ const MEASURED_MS = {
101
+ 'gate-1-tsc-test-files.test.bats': 50000,
102
+ 'gate-5a-block.test.bats': 50000,
103
+ 'gate9-architecture.bats': 50000,
104
+ 'gate-cjs-source-detection.test.bats': 50000,
105
+ 'gate-m2-threshold.test.bats': 50000,
106
+ 'issue-450-gate0-bypass-enforcement.test.bats': 50000,
107
+ 'issue-551-stale-sprint.test.bats': 50000,
108
+ 'issue-554c-gate5-no-source-skip.test.bats': 50000,
109
+ 'issue-776-adapter-verdicts-and-csharp.test.bats': 50000,
110
+ 'java-gate.test.bats': 50000,
111
+ 'multilang-subdir-gate5a.test.bats': 50000,
112
+ 'tag-push-gate-mw.test.bats': 50000,
113
+ 'typecheck-local-tsc.test.bats': 50000,
114
+ 'gate-13-slice-2.test.bats': 16100,
115
+ 'issue-649-changed-files-scan-scope.test.bats': 15300,
116
+ 'gate-13-slice-3.test.bats': 13000,
117
+ 'issue-706-kotlin-static-analysis.test.bats': 12000,
118
+ 'gate-mw-evidence.test.bats': 11800,
119
+ 'issue-577-prepush-score-majority.test.bats': 11500,
120
+ 'issue-550-staged-semantics.test.bats': 11300,
121
+ 'gate-13-walkthrough-round2.test.bats': 10800,
122
+ 'issue-599-install-hook-resolution.test.bats': 10500,
123
+ 'gate-13-compiler-strictness.test.bats': 9300,
124
+ 'issue-569-prepush-summary-counts.test.bats': 9000,
125
+ 'gate-3.test.bats': 8100,
126
+ 'gate-registry.test.bats': 6700,
127
+ 'gate-activation.test.bats': 6400,
128
+ 'gate-10-verdict.test.bats': 6000,
129
+ 'install-hooks-lib.test.bats': 5900,
130
+ 'issue-798-gate-order.bats': 5400,
131
+ 'gate-6-layers.test.bats': 5000,
132
+ 'issue-548-vendored-hook-modules-shellcheck.test.bats': 4600,
133
+ 'issue-404-gate-m-journal.test.bats': 4200,
134
+ 'issue-580-prepush-score.test.bats': 4100,
135
+ 'issue-634-pytest-test-path-exclusion.test.bats': 3900,
136
+ 'issue-604-model-input-safety.test.bats': 3800,
137
+ 'issue-668-pre-existing-assertions.test.bats': 3800,
138
+ 'powershell-stage2-coverage.test.bats': 3600,
139
+ 'adapter-common.test.bats': 3500,
140
+ 'cpp-gate.test.bats': 3400,
141
+ 'issue-523-python-coverage-parse.test.bats': 3300,
142
+ 'issue-564-score-denominator.test.bats': 3300,
143
+ 'issue-570-coverage-fail-closed.test.bats': 3300,
144
+ 'java-stage2-coverage.test.bats': 3300,
145
+ 'issue-399-python-test-selection.test.bats': 3200,
146
+ 'issue-511-gitleaks-migration.test.bats': 3000,
147
+ };
148
+
149
+ /**
150
+ * Everything not in MEASURED_MS: the measured median of the listed suites.
151
+ * Raising or lowering it changes only how optimistically unweighed suites are
152
+ * treated; it cannot move a suite between shards, only their balance.
153
+ */
154
+ const DEFAULT_MS = 3000;
155
+
156
+ /**
157
+ * Suite names, WITH the directory they live in.
158
+ *
159
+ * Returning bare names broke CI on the first real run: bats is spawned with
160
+ * `cwd: ROOT`, so `adapter-shell-scope.test.bats` resolved to the repository
161
+ * root and every shard died on
162
+ * ERROR: Test file ".../xp-gate/adapter-shell-scope.test.bats" does not exist.
163
+ * shard 1..4, all four, in one second. The shard unit tests did not catch it
164
+ * because they only asserted the `.bats` suffix, which a bare name satisfies.
165
+ *
166
+ * The name stays relative to ROOT rather than absolute so the printed plan reads
167
+ * the same on a developer's machine and on a runner, and so it can be pasted
168
+ * into a local command unchanged.
169
+ */
170
+ function listSuites(dir = BATS_DIR) {
171
+ return fs
172
+ .readdirSync(dir)
173
+ .filter((f) => f.endsWith('.bats'))
174
+ .sort()
175
+ .map((f) => path.relative(ROOT, path.join(dir, f)).split(path.sep).join('/'));
176
+ }
177
+
178
+ /**
179
+ * Measured cost of one suite.
180
+ *
181
+ * The table is keyed by BASENAME (`gate-5a-block.test.bats`) because that is how
182
+ * the timings were recorded, and a whole directory rename should not silently
183
+ * throw away every measurement. The planner, meanwhile, has to hand bats paths
184
+ * that resolve from ROOT. Looking up by basename bridges the two, and using the
185
+ * `in` check rather than `||` keeps a legitimate 0 out of the fallback.
186
+ */
187
+ function suiteCost(file) {
188
+ const base = path.basename(file);
189
+ return base in MEASURED_MS ? MEASURED_MS[base] : DEFAULT_MS;
190
+ }
191
+
192
+ /** Sum of the measured cost of the files in `files`. */
193
+ function shardCost(files) {
194
+ return files.reduce((sum, f) => sum + suiteCost(f), 0);
195
+ }
196
+
197
+ /** True when this suite carries a real measurement rather than the fallback. */
198
+ function isWeighed(file) {
199
+ return path.basename(file) in MEASURED_MS;
200
+ }
201
+
202
+ /**
203
+ * Longest-processing-time-first split over measured cost.
204
+ *
205
+ * Assigning the most expensive remaining file to the currently-cheapest shard
206
+ * is the standard greedy for this problem, and it beats round-robin by a wide
207
+ * margin on a list with a 30x spread — which this one has (17500 vs ~150).
208
+ *
209
+ * Deterministic by construction: files are sorted by weight then name, so two
210
+ * runs with the same table produce the same split, and a shard's contents can
211
+ * be reproduced from this file alone.
212
+ */
213
+ function planShards(files, shardCount) {
214
+ if (!Number.isInteger(shardCount) || shardCount < 1) {
215
+ throw new Error(`shardCount must be a positive integer, got ${shardCount}`);
216
+ }
217
+ const shards = Array.from({ length: shardCount }, () => ({ files: [], cost: 0 }));
218
+ const ordered = [...files].sort((a, b) => {
219
+ const d = suiteCost(b) - suiteCost(a);
220
+ return d !== 0 ? d : a.localeCompare(b);
221
+ });
222
+ for (const file of ordered) {
223
+ // Cheapest shard wins; ties go to the lowest index so the plan is stable.
224
+ let target = shards[0];
225
+ for (const shard of shards) {
226
+ if (shard.cost < target.cost) target = shard;
227
+ }
228
+ target.files.push(file);
229
+ target.cost += suiteCost(file);
230
+ }
231
+ for (const shard of shards) shard.files.sort();
232
+ return shards;
233
+ }
234
+
235
+ /** Parse `--shard <index>/<total>` (1-based index, as GitHub matrix reads it). */
236
+ function parseShard(spec, suiteCount) {
237
+ const match = /^(\d+)\/(\d+)$/.exec(String(spec));
238
+ if (!match) {
239
+ throw new Error(`--shard expects <index>/<total> (e.g. 1/3), got "${spec}"`);
240
+ }
241
+ const index = Number(match[1]);
242
+ const total = Number(match[2]);
243
+ if (total < 1 || index < 1 || index > total) {
244
+ throw new Error(`--shard ${spec} is out of range: index must be 1..${total}`);
245
+ }
246
+ return { index, total, suiteCount };
247
+ }
248
+
249
+ function findBatsBin() {
250
+ // The repo-local runner is the pinned devDependency. `npx bats` is NOT used:
251
+ // npx installs bats when it is missing, so a broken install would answer
252
+ // "yes, I have a runner" by downloading one — the exact probe-vs-install
253
+ // confusion AGENTS.md forbids.
254
+ const bin = path.join(ROOT, 'node_modules', 'bats', 'bin', 'bats');
255
+ if (!fs.existsSync(bin)) {
256
+ return null;
257
+ }
258
+ return bin;
259
+ }
260
+
261
+ /**
262
+ * Can `bats --jobs N` actually parallelize here?
263
+ *
264
+ * bats delegates intra-file parallelism to an external helper and aborts the
265
+ * whole run (not just the parallel part) when none is found. The four names
266
+ * below are the ones bats 1.x will use. Windows has none of them by default,
267
+ * which is why this check exists rather than trusting the `--jobs` request.
268
+ */
269
+ function hasParallelRunner() {
270
+ for (const tool of ['parallel', 'rush', 'semaphore', 'shlock', 'flock']) {
271
+ const probe = spawnSync(process.platform === 'win32' ? 'where' : 'command',
272
+ process.platform === 'win32' ? [tool] : ['-v', tool],
273
+ { cwd: ROOT, stdio: 'ignore', shell: process.platform !== 'win32' });
274
+ if (probe.status === 0) {
275
+ return true;
276
+ }
277
+ }
278
+ return false;
279
+ }
280
+
281
+ function runShard(files, jobs) {
282
+ const bin = findBatsBin();
283
+ if (!bin) {
284
+ console.error('❌ node_modules/bats/bin/bats is missing.');
285
+ console.error(' The suite must run on the pinned devDependency; run `npm ci` first.');
286
+ return 1;
287
+ }
288
+ const args = [bin];
289
+ // -j needs GNU parallel or rush INSIDE the runner. When neither is present
290
+ // bats errors out, so the flag is only added when the operator asks AND the
291
+ // runner exists; otherwise the shard still runs, serially, which is correct
292
+ // if slower. `--print-output-on-failure` is kept from the original step: it
293
+ // is what made a red build diagnosable (#591).
294
+ //
295
+ // The "runner exists" half of that sentence was documented but never coded:
296
+ // `--jobs N` was passed on the operator's word alone, so on Windows --
297
+ // where none of the four (parallel/rush/semaphore/shlock) is installed --
298
+ // bats aborted the whole shard with
299
+ // ERROR: flock/shlock is required for parallelization within files!
300
+ // and printed no test results at all. Asking for parallelism is a request,
301
+ // not a guarantee; falling back to serial is the documented behaviour, and
302
+ // now it is the actual one.
303
+ const effectiveJobs = jobs > 1 && hasParallelRunner() ? jobs : 1;
304
+ if (jobs > 1 && effectiveJobs === 1) {
305
+ console.warn(
306
+ `⚠️ --jobs ${jobs} ignored: no parallel runner (GNU parallel / rush / ` +
307
+ `semaphore / shlock) on PATH. Running serially.`
308
+ );
309
+ }
310
+ if (effectiveJobs > 1) {
311
+ args.push('--jobs', String(effectiveJobs));
312
+ }
313
+ args.push('--print-output-on-failure', ...files);
314
+
315
+ console.log(
316
+ `Running ${files.length} suite(s)` +
317
+ `${effectiveJobs > 1 ? ` with --jobs ${effectiveJobs}` : ' serially'}:`
318
+ );
319
+ for (const f of files) console.log(` - ${f}`);
320
+
321
+ // No timeout was passed here for a long time, so a suite that hung blocked CI
322
+ // until the platform killed the whole job -- and the operator saw a job that
323
+ // never finished rather than a suite that never returned.
324
+ //
325
+ // The budget is derived from measurement, not taste. This is ONE spawnSync for
326
+ // the whole shard (bats gets every file at once), so the unit is the shard:
327
+ //
328
+ // slowest known suite : 880 s (gate-5a-block, 16 cases, measured in full)
329
+ // a 1/4 shard holds : ~4x that worst case in the pathological case
330
+ //
331
+ // A per-shard budget cannot be both tight and safe, because shards are
332
+ // unbalanced by size. The default is therefore generous -- it exists to turn
333
+ // "hangs forever" into "fails after 45 minutes with a message naming the
334
+ // suite" -- and is overridable for a genuinely larger shard.
335
+ //
336
+ // Per-suite granularity is deliberately NOT implemented here: bats handles
337
+ // --jobs internally on platforms that have a parallel runner, and splitting
338
+ // this call per file would duplicate that and serialise CI on Windows, where
339
+ // no parallel runner exists (measured: 18m47s of a 22m24s job is serial bats).
340
+ const timeoutMs = Number(process.env.XP_GATE_BATS_TIMEOUT_MS) > 0
341
+ ? Number(process.env.XP_GATE_BATS_TIMEOUT_MS)
342
+ : 45 * 60 * 1000;
343
+
344
+ const result = spawnSync('bash', args, {
345
+ cwd: ROOT,
346
+ stdio: 'inherit',
347
+ timeout: timeoutMs,
348
+ });
349
+ // A timeout surfaces in TWO different shapes depending on the platform and on
350
+ // whether a signal or the exit status is observed first, and the splitting
351
+ // was measured, not assumed: on Windows this run reports
352
+ // result.error.code === 'ETIMEDOUT', error.message 'spawnSync bash ETIMEDOUT'
353
+ // while other paths set signal='SIGTERM' with a null status. Checking only
354
+ // the signal would have reported the Windows case as "could not start the
355
+ // runner" -- the opposite of what happened.
356
+ const timedOut =
357
+ result.error?.code === 'ETIMEDOUT' ||
358
+ (result.signal === 'SIGTERM' && (result.status === null || result.status !== 0));
359
+ if (timedOut) {
360
+ const budget = Math.round(timeoutMs / 1000);
361
+ console.error(
362
+ `❌ bats did not finish within ${budget}s (XP_GATE_BATS_TIMEOUT_MS). ` +
363
+ `A suite is hung rather than slow: the slowest measured suite takes 880s. ` +
364
+ `Re-run the shard with --print-only to see which files it contains, then ` +
365
+ `run them one at a time.`
366
+ );
367
+ return 1;
368
+ }
369
+ if (result.error) {
370
+ console.error(`❌ could not start the bats runner: ${result.error.message}`);
371
+ return 1;
372
+ }
373
+ return result.status === 0 ? 0 : 1;
374
+ }
375
+
376
+ /**
377
+ * Parse argv into an options object.
378
+ *
379
+ * Split out of main() because the flag loop alone pushed main's cyclomatic
380
+ * complexity to 27 against a block threshold of 10 -- Gate 3 caught it on CI
381
+ * with "BLOCK scripts/run-bats-ci.cjs:290 main CCN=27". Each branch here is an
382
+ * independent decision, which is exactly what the metric is counting; keeping
383
+ * them in one dispatcher conflated parsing, planning and execution.
384
+ *
385
+ * Returns { opts } or { error } -- never throws, so the caller keeps one exit path.
386
+ */
387
+ function parseArgs(argv) {
388
+ const opts = { shard: null, jobs: 1, printOnly: false, printShards: false, all: false, help: false };
389
+ // Table-driven on purpose. Every flag is an independent decision, and written
390
+ // as a chain of `else if` each one adds a branch to the same function: the
391
+ // gate blocked the previous version at CCN=15. A lookup table states the same
392
+ // mapping without turning "how many flags exist" into "how complex is the
393
+ // parser". `takesValue` says whether the next argv element is its argument.
394
+ const FLAGS = {
395
+ '--shard': { key: 'shard', takesValue: true },
396
+ '--jobs': { key: 'jobs', takesValue: true, coerce: Number },
397
+ '--print-only': { key: 'printOnly', value: true },
398
+ '--print-shards': { key: 'printShards', value: true },
399
+ '--all': { key: 'all', value: true },
400
+ '--help': { key: 'help', value: true },
401
+ '-h': { key: 'help', value: true },
402
+ };
403
+ for (let i = 0; i < argv.length; i += 1) {
404
+ const arg = argv[i];
405
+ const flag = FLAGS[arg];
406
+ if (!flag) return { error: `Unknown argument: ${arg}` };
407
+ if (!flag.takesValue) {
408
+ opts[flag.key] = flag.value;
409
+ continue;
410
+ }
411
+ const raw = argv[++i];
412
+ opts[flag.key] = flag.coerce ? flag.coerce(raw) : raw;
413
+ }
414
+ return { opts };
415
+ }
416
+
417
+ /**
418
+ * The shard this invocation is responsible for, validated against the whole
419
+ * suite. Returns { files, index, total, cost } or { error, code }.
420
+ *
421
+ * Every rejection here is the same principle from a different angle: something
422
+ * that did not run must not read as passed (#636 / 6ebbd5a). A starved shard, a
423
+ * plan that omits a suite or repeats one, and an out-of-range index are all
424
+ * "this matrix entry verified nothing", and each exits 2 rather than 0.
425
+ */
426
+ function resolveShard(suites, spec) {
427
+ let spec_ = null;
428
+ try {
429
+ spec_ = parseShard(spec, suites.length);
430
+ } catch (error) {
431
+ return { error: error.message, code: 1 };
432
+ }
433
+ const { index, total } = spec_;
434
+ const shards = planShards(suites, total);
435
+ const mine = shards[index - 1];
436
+
437
+ if (mine.files.length === 0) {
438
+ return {
439
+ error:
440
+ `shard ${index}/${total} was assigned zero suites. ` +
441
+ 'The split is starved -- fix --shard/suite count, do not merge a green shard.',
442
+ code: 2,
443
+ };
444
+ }
445
+
446
+ const assigned = shards.flatMap((s) => s.files);
447
+ const missing = suites.filter((f) => !assigned.includes(f));
448
+ const duped = assigned.filter((f, i) => assigned.indexOf(f) !== i);
449
+ if (missing.length || duped.length) {
450
+ return {
451
+ error:
452
+ `shard plan is not a partition (missing: ${missing.join(', ') || 'none'})
453
+ ` +
454
+ ` duplicated: ${duped.join(', ') || 'none'}`,
455
+ code: 2,
456
+ };
457
+ }
458
+
459
+ return { files: mine.files, index, total, cost: mine.cost };
460
+ }
461
+
462
+ /** Report the unweighed-suite count. Silence here would hide a partial measurement. */
463
+ function reportUnweighed(suites) {
464
+ const unweighed = suites.filter((f) => !isWeighed(f));
465
+ if (!unweighed.length) return;
466
+ console.log(
467
+ `ℹ️ ${unweighed.length}/${suites.length} suite(s) have no measured weight and use ${DEFAULT_MS} ms; shard balance is approximate until they are weighed.`,
468
+ );
469
+ }
470
+
471
+ function printShards(suites, shardSpec) {
472
+ const total = shardSpec ? parseShard(shardSpec, suites.length).total : 1;
473
+ const shards = planShards(suites, total);
474
+ shards.forEach((s, i) => {
475
+ console.log(`
476
+ Shard ${i + 1}/${total} — ${s.files.length} file(s), ~${s.cost} ms`);
477
+ for (const f of s.files) console.log(` ${f}`);
478
+ });
479
+ return 0;
480
+ }
481
+
482
+ function main(argv) {
483
+ const parsed = parseArgs(argv);
484
+ if (parsed.error) {
485
+ console.error(parsed.error);
486
+ return 1;
487
+ }
488
+ const opts = parsed.opts;
489
+ if (opts.help) {
490
+ console.log('usage: node scripts/run-bats-ci.cjs --shard 1/3 [--jobs N] [--print-only]');
491
+ return 0;
492
+ }
493
+
494
+ if (!fs.existsSync(BATS_DIR)) {
495
+ console.error(`❌ no suite directory at ${BATS_DIR}`);
496
+ return 1;
497
+ }
498
+ const suites = listSuites();
499
+ if (suites.length === 0) {
500
+ // A green run over zero suites is the 6ebbd5a failure mode. Fail loudly.
501
+ console.error(`❌ no .bats suites in ${BATS_DIR} — refusing to report PASS`);
502
+ return 2;
503
+ }
504
+
505
+ reportUnweighed(suites);
506
+
507
+ if (opts.printShards) return printShards(suites, opts.shard);
508
+ if (opts.all) return runShard(suites, opts.jobs);
509
+
510
+ if (!opts.shard) {
511
+ console.error('Pass --shard <index>/<total>, or --all to run every suite serially.');
512
+ return 1;
513
+ }
514
+
515
+ const shard = resolveShard(suites, opts.shard);
516
+ if (shard.error) {
517
+ console.error(`❌ ${shard.error}`);
518
+ return shard.code;
519
+ }
520
+
521
+ if (opts.printOnly) {
522
+ console.log(`Shard ${shard.index}/${shard.total}: ${shard.files.join(' ')}`);
523
+ return 0;
524
+ }
525
+
526
+ console.log(`
527
+ === BATS shard ${shard.index}/${shard.total} (~${shard.cost} ms of measured cost) ===`);
528
+ return runShard(shard.files, opts.jobs);
529
+ }
530
+
531
+ if (require.main === module) {
532
+ try {
533
+ process.exit(main(process.argv.slice(2)));
534
+ } catch (error) {
535
+ console.error(`❌ ${error.message}`);
536
+ process.exit(1);
537
+ }
538
+ }
539
+
540
+ module.exports = { listSuites, planShards, shardCost, parseShard, MEASURED_MS, DEFAULT_MS };
@@ -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.16.0
6
+ **Version:** 0.38.18.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.16.0
6
+ **Version:** 0.38.18.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.16.0
6
+ **Version:** 0.38.18.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Test-Specification Alignment Engine — two-stage validation ensuring tests accurately reflect requirements and design specs.