@boyingliu01/xp-gate 0.37.2 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/adapter-common.sh +12 -2
  2. package/adapters/csharp.sh +73 -2
  3. package/adapters/dart.sh +13 -0
  4. package/adapters/go.sh +5 -0
  5. package/adapters/iac.sh +46 -3
  6. package/adapters/java.sh +6 -0
  7. package/adapters/kotlin.sh +6 -0
  8. package/adapters/shell.sh +119 -34
  9. package/adapters/swift.sh +6 -0
  10. package/adapters/typescript.sh +98 -34
  11. package/bin/xp-gate.js +48 -2
  12. package/gate-10.sh +99 -26
  13. package/gate-12-file-hygiene.sh +13 -1
  14. package/gate-registry.sh +197 -0
  15. package/gates/common-process.ts +36 -7
  16. package/gates/gate-9.ts +17 -8
  17. package/gates/python-health.ts +215 -24
  18. package/hooks/adapter-common.sh +12 -2
  19. package/hooks/deploy-manifest.sh +100 -0
  20. package/hooks/gate-10.sh +99 -26
  21. package/hooks/gate-12-file-hygiene.sh +13 -1
  22. package/hooks/gate-driver.sh +120 -0
  23. package/hooks/gate-entries/gate-0-entry.sh +825 -0
  24. package/hooks/gate-entries/gate-1-entry.sh +767 -0
  25. package/hooks/gate-entries/gate-10-entry.sh +52 -0
  26. package/hooks/gate-entries/gate-11-entry.sh +120 -0
  27. package/hooks/gate-entries/gate-12-entry.sh +44 -0
  28. package/hooks/gate-entries/gate-12b-entry.sh +178 -0
  29. package/hooks/gate-entries/gate-12c-entry.sh +80 -0
  30. package/hooks/gate-entries/gate-13-entry.sh +584 -0
  31. package/hooks/gate-entries/gate-2-entry.sh +199 -0
  32. package/hooks/gate-entries/gate-3-entry.sh +53 -0
  33. package/hooks/gate-entries/gate-4-entry.sh +46 -0
  34. package/hooks/gate-entries/gate-5-entry.sh +1729 -0
  35. package/hooks/gate-entries/gate-6-entry.sh +658 -0
  36. package/hooks/gate-entries/gate-7-entry.sh +41 -0
  37. package/hooks/gate-entries/gate-8-entry.sh +33 -0
  38. package/hooks/gate-entries/gate-9-entry.sh +307 -0
  39. package/hooks/gate-entries/subdir-restore.sh +27 -0
  40. package/hooks/gate-registry.sh +51 -15
  41. package/hooks/hook-module-resolution.sh +73 -0
  42. package/hooks/install.sh +135 -0
  43. package/hooks/lib/now-ms.sh +55 -19
  44. package/hooks/lib/toolchain-path.sh +50 -6
  45. package/hooks/pre-commit +256 -5091
  46. package/hooks/pre-push +212 -25
  47. package/lib/__tests__/arch-config-template.test.js +190 -0
  48. package/lib/__tests__/baseline-shell-scope.test.js +60 -0
  49. package/lib/__tests__/crap-cli.test.js +14 -3
  50. package/lib/__tests__/deploy-manifest-check-wired.test.js +138 -0
  51. package/lib/__tests__/deploy-manifest-completeness.test.js +151 -0
  52. package/lib/__tests__/deploy-manifest-consumers-adapter-uninstall.test.js +40 -0
  53. package/lib/__tests__/deploy-manifest-consumers-no-private-lists.test.js +74 -0
  54. package/lib/__tests__/deploy-manifest-projection.test.js +66 -0
  55. package/lib/__tests__/deploy-manifest-shell-parity.test.js +108 -0
  56. package/lib/__tests__/deploy-manifest.test.js +97 -0
  57. package/lib/__tests__/doctor.test.js +51 -7
  58. package/lib/__tests__/gate-coverage.test.js +79 -12
  59. package/lib/__tests__/gate-numbering.test.js +28 -1
  60. package/lib/__tests__/install-sh-deploy-manifest.test.js +80 -0
  61. package/lib/__tests__/mirror-sync.test.js +45 -3
  62. package/lib/__tests__/npm-package.test.js +10 -7
  63. package/lib/__tests__/sastd-client.test.js +452 -0
  64. package/lib/__tests__/shared-utils-copyHooks-manifest.test.js +69 -0
  65. package/lib/__tests__/sprint-status-rework.test.js +1 -0
  66. package/lib/arch-config-template.js +87 -0
  67. package/lib/baseline.js +54 -2
  68. package/lib/deploy-manifest.js +174 -0
  69. package/lib/doctor.js +46 -14
  70. package/lib/gate-capability.js +291 -0
  71. package/lib/gate-coverage.js +194 -74
  72. package/lib/gate-identity.js +349 -0
  73. package/lib/gate-runner.js +11 -1
  74. package/lib/hook-module-resolution.js +27 -0
  75. package/lib/init.js +72 -5
  76. package/lib/mattpocock-license-verdict.json +1 -1
  77. package/lib/sastd-client.js +534 -0
  78. package/lib/shared-utils.js +31 -9
  79. package/lib/uninstall.js +10 -7
  80. package/lib/update-hooks.js +27 -18
  81. package/mock-policy/AGENTS.md +1 -1
  82. package/mutation/AGENTS.md +1 -1
  83. package/package.json +3 -1
  84. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  85. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  86. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  87. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +2 -2
  88. package/plugins/dsh/package.json +1 -1
  89. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  90. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  91. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +2 -2
  92. package/plugins/opencode/package.json +1 -1
  93. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  94. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  95. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +2 -2
  96. package/plugins/qoder/plugin.json +1 -1
  97. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  98. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  99. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +2 -2
  100. package/principles/AGENTS.md +1 -1
  101. package/principles/__tests__/analyzer.test.ts +2 -1
  102. package/principles/__tests__/config-enforcement.test.ts +1 -0
  103. package/principles/__tests__/types.test.ts +1 -0
  104. package/principles/adapters/base.ts +14 -1
  105. package/principles/adapters/duplication.ts +134 -0
  106. package/principles/rules/__tests__/clean-code/large-file.test.ts +2 -1
  107. package/principles/rules/clean-code/code-duplication.ts +75 -9
  108. package/principles/types.ts +39 -0
  109. package/scripts/__tests__/check-mattpocock-license.test.js +36 -3
  110. package/scripts/__tests__/sync-package-content.test.js +12 -2
  111. package/scripts/generate-mirrors.cjs +125 -0
  112. package/scripts/sync-package-content.js +64 -20
  113. package/skills/delphi-review/AGENTS.md +1 -1
  114. package/skills/sprint-flow/AGENTS.md +1 -1
  115. package/skills/test-specification-alignment/AGENTS.md +2 -2
  116. package/adapters/gate-9.sh +0 -245
  117. package/gate-9.sh +0 -245
  118. package/hooks/gate-9.sh +0 -245
package/bin/xp-gate.js CHANGED
@@ -384,6 +384,47 @@ const COMMANDS = {
384
384
  },
385
385
  usage: 'xp-gate gate-coverage [--json] [--debt] [--strict] [--branch <name>]'
386
386
  },
387
+ 'gate-capability': {
388
+ description: 'Publish which execution path can run which gate, derived from the registry (REQ-D2)',
389
+ run: subargs => {
390
+ const { capabilityMatrix } = require('../lib/gate-capability.js');
391
+ const matrix = capabilityMatrix();
392
+
393
+ if (subargs.includes('--json')) {
394
+ process.stdout.write(`${JSON.stringify(matrix, null, 2)}\n`);
395
+ return;
396
+ }
397
+
398
+ // Rendered as a table with the reason spelled out. The point of this
399
+ // command is that "cannot run here" stops being a footnote: a reader sees
400
+ // WHY each gate is unavailable instead of inferring it from silence.
401
+ const width = Math.max(...matrix.gates.map(gate => String(gate.gate).length));
402
+
403
+ // Drift first. If the two sources disagree the labels below are not
404
+ // trustworthy, so saying that comes before showing them.
405
+ if (matrix.drift.length > 0) {
406
+ process.stdout.write('\n⚠️ SOURCE DRIFT — these labels are not trustworthy:\n');
407
+ for (const problem of matrix.drift) {
408
+ process.stdout.write(` gate ${problem.gate} (${problem.slug}): ${problem.problem}\n`);
409
+ }
410
+ }
411
+
412
+ process.stdout.write('\n━━━ GATE CAPABILITY ━━━\n\n');
413
+ process.stdout.write(` ${matrix.summary.runnable} runnable / ${matrix.summary.commitOnly} commit-only`);
414
+ process.stdout.write(` / ${matrix.summary.pushOnly} push-only / ${matrix.summary.unreachable} unreachable`);
415
+ process.stdout.write(` of ${matrix.summary.total}\n\n`);
416
+ process.stdout.write(' commit-only = needs the git-staged set, which exists only during git commit\n');
417
+ process.stdout.write(' push-only = runs on git push; no xp-gate subcommand is registered\n\n');
418
+ for (const gate of matrix.gates) {
419
+ const id = String(gate.gate).padStart(width);
420
+ process.stdout.write(` ${id} ${gate.capability.padEnd(12)} ${gate.slug}\n`);
421
+ if (gate.reason) process.stdout.write(` ${' '.repeat(width)} ${' '.repeat(12)} └─ ${gate.reason}\n`);
422
+ }
423
+ process.stdout.write(`\n registry: ${matrix.registry}\n`);
424
+ process.stdout.write(' runnability: gate-runner GATE_REGISTRY.preCommitOnly\n\n');
425
+ },
426
+ usage: 'xp-gate gate-capability [--json]'
427
+ },
387
428
  'gate-rules': {
388
429
  description: 'Print the gate limits that can block a commit, generated from the files that define them (#652)',
389
430
  run: subargs => {
@@ -512,8 +553,13 @@ const COMMANDS = {
512
553
  }
513
554
  };
514
555
 
515
- for (let i = 0; i <= 11; i++) {
516
- const gateId = String(i);
556
+ // Numbered gate subcommands are DERIVED from gateRunner.GATE_REGISTRY, which
557
+ // builds its metadata from githooks/gate-registry.sh. This loop used to be
558
+ // `for (let i = 0; i <= 11; i++)`, a hardcoded ceiling that silently excluded
559
+ // gate-12 (file hygiene) and gate-13 (compiler strictness) — both had scripts
560
+ // and hook coverage but no way to run them from the CLI (#783). Adding a row to
561
+ // the registry now yields a subcommand; nothing here needs editing.
562
+ for (const { id: gateId } of gateRunner.getAllGates().filter((gate) => /^\d+$/.test(gate.id))) {
517
563
  const gateInfo = gateRunner.GATE_REGISTRY[gateId];
518
564
  COMMANDS[`gate-${gateId}`] = {
519
565
  description: `Run Gate ${gateId}: ${gateInfo?.name || 'Unknown'}`,
package/gate-10.sh CHANGED
@@ -40,10 +40,11 @@ GATE_10_SCANNED_FILES=0
40
40
  # GATE_10_SEMGREP_PATH records what actually happened, so a reader of the report
41
41
  # can tell a fast run from a degraded one without timing it.
42
42
  #
43
- # The daemon does not exist yet (that is E2/E3). Until it does, EVERY value of
44
- # XP_GATE_SASTD resolves to "direct", which is what makes shipping E1 a no-op:
45
- # the switch, the degrade flag and the tests land first so the fast path is added
46
- # onto a base that is already proven to behave exactly as today.
43
+ # The daemon exists but is NOT the default. It is opt-in via XP_GATE_SASTD=on,
44
+ # and `auto` resolves to direct on purpose -- see the `auto` case below, which
45
+ # records the measurement that made the default a direct scan. Everything here is
46
+ # a switch plus a report field; with the default settings the gate behaves exactly
47
+ # as it did before the daemon was written.
47
48
  # ---------------------------------------------------------------------------
48
49
  # Consumed by the sourcing parent (pre-commit report JSON), not here.
49
50
  # shellcheck disable=SC2034
@@ -62,28 +63,24 @@ case "${XP_GATE_SASTD:-direct}" in
62
63
  GATE_10_SEMGREP_PATH="direct"
63
64
  ;;
64
65
  auto)
65
- # "Use the daemon if one is available, otherwise just scan." Absence of a
66
- # daemon is the normal state for most users, not a fault, so `auto` does NOT
67
- # set the degraded flag -- marking it would make every ordinary run look
68
- # degraded the moment E2 lands and train readers to ignore the flag.
69
- # E2 MUST add a probe INSIDE this branch rather than flipping the value:
70
- # a daemon that is ABSENT keeps degraded=0 (normal), but a daemon that is
71
- # PRESENT BUT UNUSABLE must set degraded=1 -- otherwise `auto` silently
72
- # swallows the same failure `on` reports. Get that distinction right here;
73
- # it is the whole reason the two branches are separate.
66
+ # `auto` deliberately does NOT select the daemon. It was meant to mean "use one
67
+ # if available", but measurement killed that default: with Gate 10's real
68
+ # ruleset (p/security-audit, 225 rules) the daemon saves ~20% in steady state
69
+ # (6.6-6.9s -> 5.2-5.4s) and is SLOWER end to end (10.5s -> 14.6s), because each
70
+ # gate run is a fresh process that pays the daemon's own startup without
71
+ # amortising it over a second call. Making that the automatic choice would tax
72
+ # every user for a benefit most of them never see.
73
+ #
74
+ # `auto` therefore behaves as "off" but says so through the `path` field, and it
75
+ # never sets degraded -- a plain direct run is not a degraded run.
74
76
  GATE_10_SEMGREP_PATH="direct"
75
77
  ;;
76
78
  on|1|true)
77
- # The user asserted a daemon SHOULD be here. If it is not, that is a
78
- # degradation worth reporting: their configuration is not being honoured.
79
+ # Opt-in only. The user asserted a daemon SHOULD be here; whether one actually
80
+ # answers can only be known after the probe, so the degrade flag is set there.
81
+ # Setting it at parse time would report a failure before anything has failed.
79
82
  # This is the branch that must never become "skip the scan and call it a pass".
80
- GATE_10_SEMGREP_PATH="direct"
81
- GATE_10_SASTD_DEGRADED=1
82
- # stderr, not stdout: this file is SOURCED by pre-commit, so stdout belongs to
83
- # the parent's report stream. A notice written there would land inside output
84
- # that another consumer may parse. stderr still reaches the developer's
85
- # terminal, which is the only audience a notice needs.
86
- echo " ℹ️ sastd requested but not available — using direct semgrep (degraded)" >&2
83
+ GATE_10_SEMGREP_PATH="daemon"
87
84
  ;;
88
85
  *)
89
86
  # An unrecognised value is a configuration mistake, not a reason to scan
@@ -251,8 +248,85 @@ EOF
251
248
  fi
252
249
  SEMGREP_TIMEOUT_S="${XP_GATE_SEMGREP_TIMEOUT:-180}"
253
250
  SEMGREP_TIMED_OUT=false
254
- if command -v timeout >/dev/null 2>&1; then
255
- SEMGREP_STDOUT_FILE=$(mktemp)
251
+ SEMGREP_STDOUT_FILE=$(mktemp)
252
+ SEMGREP_EXIT=0
253
+ SEMGREP_OUTPUT=""
254
+
255
+ # Daemon path (E3). One long-lived semgrep process, so its ~2.5s import tax is
256
+ # paid once per machine instead of once per gate run: direct 3.8-4.0s vs daemon
257
+ # hot 2.1-2.3s measured on this repo.
258
+ #
259
+ # A SWITCHED path, never a replacement: every failure below falls through to
260
+ # the direct scan. The daemon may make this gate SLOWER; it must never make it
261
+ # greener (#518/#559).
262
+ if [ "$GATE_10_SEMGREP_PATH" = "daemon" ] && command -v node >/dev/null 2>&1; then
263
+ # The protocol carries exactly ONE config. Counting rather than overwriting
264
+ # matters: the previous loop kept only the last --config, so a repo with two
265
+ # would have been scanned with one and reported on as if fully checked.
266
+ rules_for_daemon=""
267
+ config_count=0
268
+ for _arg in "${SEMGREP_RULES[@]}"; do
269
+ case "$_arg" in
270
+ --config=*)
271
+ rules_for_daemon="${_arg#--config=}"
272
+ config_count=$((config_count + 1))
273
+ ;;
274
+ esac
275
+ done
276
+ # Anything the protocol cannot express exactly is left to the direct path
277
+ # rather than approximated:
278
+ # - more than one config (nothing would report the dropped one);
279
+ # - p/csharp (Gate 10 adds it for C# repos);
280
+ # - "auto" (semgrep's own rule selection, not a spec we can pass through);
281
+ # - anything with a comma, which is semgrep's multi-config shorthand;
282
+ # - a remote URL, which the daemon would resolve against its own cwd and
283
+ # registry cache instead of the one the CLI would have used.
284
+ if [ "$config_count" -ne 1 ]; then
285
+ rules_for_daemon=""
286
+ fi
287
+ case "$rules_for_daemon" in
288
+ *p/csharp*|*","*|*"://"*|auto|"") rules_for_daemon="" ;;
289
+ esac
290
+ if [ -n "$rules_for_daemon" ]; then
291
+ daemon_roots=$(printf '%s\n' "${SEMGREP_ARGS[@]}" | grep -v '^--include=' || true)
292
+ # ARGV TRAP: under `node -e` there is NO script path in argv, so the first
293
+ # user argument is argv[1]. Indexing it as argv[2] passes undefined as the
294
+ # config, semgrep raises a python TypeError, and the gate "degrades" for a
295
+ # reason unrelated to the daemon -- which is how this looked like a flaky
296
+ # integration instead of an off-by-one.
297
+ # shellcheck disable=SC2086 # one argv entry per scanning root: word splitting is intended
298
+ if DAEMON_JSON=$(XP_GATE_SASTD=on node -e 'const NL = String.fromCharCode(10);
299
+ const { requestScan } = require(process.argv[1]);
300
+ requestScan({ config: process.argv[2], roots: process.argv.slice(3) }).then((r) => {
301
+ if (!r.ok) { process.stderr.write("SASTD_UNAVAILABLE: " + r.error + NL); process.exit(3); }
302
+ process.stdout.write(JSON.stringify(r.payload));
303
+ }).catch((e) => { process.stderr.write("SASTD_UNAVAILABLE: " + e.message + NL); process.exit(3); });' "$(cd "$GATE_DIR/../src/npm-package/lib" 2>/dev/null && pwd -W)/sastd-client.js" "$rules_for_daemon" $daemon_roots 2>"$SEMGREP_STDOUT_FILE.stderr"); then
304
+ printf '%s' "$DAEMON_JSON" > "$SEMGREP_STDOUT_FILE"
305
+ SEMGREP_OUTPUT=$(cat "$SEMGREP_STDOUT_FILE.stderr" 2>/dev/null || true)
306
+ rm -f "$SEMGREP_STDOUT_FILE.stderr"
307
+ else
308
+ SEMGREP_EXIT=$?
309
+ rm -f "$SEMGREP_STDOUT_FILE.stderr"
310
+ : > "$SEMGREP_STDOUT_FILE"
311
+ case "${XP_GATE_SASTD:-direct}" in
312
+ on|1|true)
313
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
314
+ # shellcheck disable=SC2034
315
+ GATE_10_SASTD_DEGRADED=1
316
+ echo " ⚠️ sastd requested but unavailable — using direct semgrep (degraded)" >&2
317
+ ;;
318
+ *)
319
+ echo " ℹ️ sastd unavailable — using direct semgrep" >&2
320
+ ;;
321
+ esac
322
+ GATE_10_SEMGREP_PATH="direct"
323
+ fi
324
+ else
325
+ GATE_10_SEMGREP_PATH="direct"
326
+ fi
327
+ fi
328
+
329
+ if [ "$GATE_10_SEMGREP_PATH" = "direct" ] && command -v timeout >/dev/null 2>&1; then
256
330
  SEMGREP_OUTPUT=$(timeout -k 10 "$SEMGREP_TIMEOUT_S" \
257
331
  "$SEMGREP_CMD" scan "${SEMGREP_RULES[@]}" --json --disable-version-check \
258
332
  "${SEMGREP_ARGS[@]}" 2>&1 >"$SEMGREP_STDOUT_FILE")
@@ -266,13 +340,12 @@ EOF
266
340
  case "$SEMGREP_EXIT" in
267
341
  124|137) SEMGREP_TIMED_OUT=true ;;
268
342
  esac
269
- else
343
+ elif [ "$GATE_10_SEMGREP_PATH" = "direct" ]; then
270
344
  # No `timeout` on this platform (stock macOS). Say so: an unbounded run
271
345
  # nobody mentioned is exactly how #559 stayed invisible for a whole
272
346
  # release. The scan still runs -- refusing to scan would be a worse
273
347
  # trade -- but the unbounded window is now stated.
274
348
  echo " ⚠️ 'timeout' command not available — semgrep runs UNBOUNDED (install coreutils or set up gtimeout)"
275
- SEMGREP_STDOUT_FILE=$(mktemp)
276
349
  SEMGREP_OUTPUT=$("$SEMGREP_CMD" scan "${SEMGREP_RULES[@]}" --json --disable-version-check \
277
350
  "${SEMGREP_ARGS[@]}" 2>&1 >"$SEMGREP_STDOUT_FILE")
278
351
  SEMGREP_EXIT=$?
@@ -15,7 +15,19 @@ GATE_12_START=$(gate_start_ms)
15
15
  MAX_FILE_SIZE_BYTES="${XP_GATE_MAX_FILE_SIZE:-1048576}" # 1MB default
16
16
 
17
17
  # Get list of staged files (excluding deleted files)
18
- STAGED_FILES=$(git diff --cached --name-only --diff-filter=d 2>/dev/null)
18
+ #
19
+ # Third-party trees are excluded. In a fresh `git init` fixture the CI's
20
+ # "First Commit Gates" job does `git add -A` before committing, so every
21
+ # node_modules/ file becomes staged — and third-party packages legitimately
22
+ # CONTAIN `<<<<<<<` text as documentation (semver/README.md, various NOTICE.txt).
23
+ # Gate 12 then reported "merge conflict markers detected" for files no author
24
+ # wrote, blocking the fixture commit, on every commit for months. A hygiene check
25
+ # that reads vendored documentation as a conflict is not finding anything.
26
+ #
27
+ # This is the same class as the __pycache__ filter in check-hook-mirror.sh (#587):
28
+ # build/dependency artefacts are not project source and must not be judged as it.
29
+ STAGED_FILES=$(git diff --cached --name-only --diff-filter=d 2>/dev/null \
30
+ | grep -vE '(^|/)(node_modules|\.stryker-tmp|vendor)/' || true)
19
31
 
20
32
  if [ -z "$STAGED_FILES" ]; then
21
33
  echo " ℹ️ No staged files — skipping"
@@ -0,0 +1,197 @@
1
+ #!/usr/bin/env bash
2
+ # ============================================================================
3
+ # GATE REGISTRY — the single source of truth for "which gate is which"
4
+ # ============================================================================
5
+ #
6
+ # WHY THIS FILE EXISTS
7
+ #
8
+ # Gate numbers alone are not self-describing, and the numbers are not stable
9
+ # facts about the repository — they are labels. Three sources disagreed about
10
+ # what "Gate 9" is:
11
+ #
12
+ # root AGENTS.md -> Semgrep SAST (WRONG)
13
+ # githooks/AGENTS.md -> Build Integrity (right)
14
+ # pre-commit actual -> Build Integrity (right)
15
+ #
16
+ # In issue #717 a C# SAST fix was written into githooks/gate-9.sh, because the
17
+ # root document said Gate 9 was SAST. SAST is gate 10. gate-9.sh is not sourced
18
+ # by any hook and never executes, so the fix changed nothing while appearing to
19
+ # land. The defect was not "the number was hard to remember" — it was that
20
+ # nothing connected a gate's NAME to the FILE that runs it.
21
+ #
22
+ # This registry makes that connection explicit and testable. The drift test
23
+ # (githooks/__tests__/gate-registry.test.bats) asserts every `impl` below
24
+ # against the code, so a document that disagrees with reality, or a fix that
25
+ # lands in a file nobody sources, fails immediately.
26
+ #
27
+ # COLUMNS
28
+ # name stable semantic id — use this in prose, commits, and tests
29
+ # number display label only. Mirrors the report key (gateN_*) for backward
30
+ # compatibility; do NOT treat it as the identity of the gate.
31
+ # impl where the gate actually runs. One of:
32
+ # <script>.sh a file sourced/executed by pre-commit
33
+ # inline implemented inside pre-commit itself
34
+ # blocks YES the gate can reject a commit
35
+ # NO the gate reports but cannot reject
36
+ #
37
+ # USAGE
38
+ # source githooks/gate-registry.sh
39
+ # gate_name_for_file gate-10.sh # -> sast
40
+ # gate_impl sast # -> gate-10.sh
41
+ # gate_number sast # -> 10
42
+ # gate_can_block sast # -> YES
43
+ # gate_registry_dump # -> one line per gate
44
+ #
45
+ # ⚠️ Adding a gate: add a row here AND update the drift test's expectations.
46
+ # A gate that exists only in pre-commit and not here is a gate nobody can
47
+ # look up by name — which is how #717's wrong-file patch happened.
48
+ # ============================================================================
49
+
50
+ # name|number|impl|blocks|hook
51
+ #
52
+ # The `hook` field is LAST so a 4-field reader (any consumer installed from an
53
+ # older package) keeps working: appending a field does not move the ones it
54
+ # already reads.
55
+ #
56
+ # Numbers are POSITIONAL LABELS, never identities, and nothing here orders them
57
+ # numerically — pre-push numbers are strings (M, M2, ML, UI, MW, S). Do not add
58
+ # `-gt`/`-lt`/`$((` logic against this field;
59
+ # scripts/__tests__/gate-identity-cross-surface.test.cjs greps for it.
60
+ #
61
+ # `impl` names the file that DECIDES the gate. Where a gate is an inline block
62
+ # plus a helper that renders the verdict, name the helper: `impl` answers "which
63
+ # file do I edit to change this gate", and `inline` answered that wrongly for
64
+ # gate 6 (#715) — the layer verdict comes from gate-6-layers.sh.
65
+ GATE_REGISTRY_ROWS=(
66
+ "version-consistency|0|inline|YES|pre-commit"
67
+ "code-quality|1|inline|YES|pre-commit"
68
+ "duplicate-code|2|inline|NO|pre-commit"
69
+ "complexity|3|gate-3.sh|YES|pre-commit"
70
+ "principles|4|gate-4.sh|YES|pre-commit"
71
+ "tests-coverage|5|inline|YES|pre-commit"
72
+ "architecture|6|gate-6-layers.sh|YES|pre-commit"
73
+ "iac-security|7|gate-7.sh|YES|pre-commit"
74
+ "secret-scanning|8|gate-8.sh|YES|pre-commit"
75
+ "build-integrity|9|inline|YES|pre-commit"
76
+ "sast|10|gate-10.sh|YES|pre-commit"
77
+ "sprint-flow|11|sprint-gate.sh|YES|pre-commit"
78
+ "file-hygiene|12|gate-12-file-hygiene.sh|NO|pre-commit"
79
+ "compiler-strictness|13|gate-13-compiler-strictness.sh|YES|pre-commit"
80
+ # pre-push. Registering these is identity bookkeeping only — pre-push keeps
81
+ # deciding its own execution order and skip semantics. Before this the
82
+ # registry knew nothing about half the gates this project runs (#769).
83
+ "mutation|M|inline|YES|pre-push"
84
+ "mock-density|M2|inline|NO|pre-push"
85
+ "mock-layering|ML|inline|YES|pre-push"
86
+ "ui-sprint|UI|inline|YES|pre-push"
87
+ "code-walkthrough|MW|inline|YES|pre-push"
88
+ "prepush-sprint|S|sprint-gate.sh|YES|pre-push"
89
+ )
90
+
91
+ # Report-key overrides for rows whose historical artifact key is not derivable
92
+ # as gate{number}_{name}. ONE entry today. Kept beside the rows so a second
93
+ # mapping cannot appear next to the comparison logic where it would be invisible.
94
+ # Compare on NAME, never on these keys: an override must not excuse a mismatch.
95
+ #
96
+ # Not read by any shell code here -- it exists for the Node reader in
97
+ # src/npm-package/lib/gate-identity.js, which parses this block directly. Some
98
+ # shells do not inherit unexported array variables across a `source`, so it is
99
+ # exported rather than left dangling (which also keeps shellcheck honest).
100
+ export GATE_REPORT_KEY_OVERRIDES=(
101
+ "code-quality|gate1_static_analysis"
102
+ )
103
+
104
+ # Human-readable title for each name. Kept separate from the row above so the
105
+ # title can change without touching the lookup keys.
106
+ _gate_title() {
107
+ case "$1" in
108
+ version-consistency) echo "Version Consistency" ;;
109
+ code-quality) echo "Code Quality (Static + Lint)" ;;
110
+ duplicate-code) echo "Duplicate Code" ;;
111
+ complexity) echo "Cyclomatic Complexity" ;;
112
+ principles) echo "Clean Code + SOLID" ;;
113
+ tests-coverage) echo "Tests + Coverage" ;;
114
+ architecture) echo "Architecture + Boy Scout Rule" ;;
115
+ iac-security) echo "IaC Security Scanning" ;;
116
+ secret-scanning) echo "Secret Scanning" ;;
117
+ build-integrity) echo "Build Integrity" ;;
118
+ sast) echo "SAST Security Scan" ;;
119
+ sprint-flow) echo "Sprint Flow Enforcement" ;;
120
+ file-hygiene) echo "File Hygiene Check" ;;
121
+ compiler-strictness) echo "Compiler Strictness" ;;
122
+ *) return 1 ;;
123
+ esac
124
+ }
125
+
126
+ # ---------------------------------------------------------------------------
127
+ # Lookups. Each returns non-zero when the name is unknown, so a typo fails
128
+ # loudly instead of silently matching nothing.
129
+ # ---------------------------------------------------------------------------
130
+
131
+ # gate_row <name> -> echoes the raw row, or returns 1.
132
+ gate_row() {
133
+ local want="$1" row
134
+ for row in "${GATE_REGISTRY_ROWS[@]}"; do
135
+ case "$row" in
136
+ "$want"\|*) printf '%s\n' "$row"; return 0 ;;
137
+ esac
138
+ done
139
+ return 1
140
+ }
141
+
142
+ # _gate_field <name> <1-based field index>
143
+ _gate_field() {
144
+ local row
145
+ row=$(gate_row "$1") || return 1
146
+ printf '%s\n' "$row" | cut -d'|' -f"$2"
147
+ }
148
+
149
+ gate_number() { _gate_field "$1" 2; }
150
+ gate_impl() { _gate_field "$1" 3; }
151
+ gate_blocks() { _gate_field "$1" 4; }
152
+ gate_can_block() { [ "$(gate_blocks "$1")" = "YES" ] && echo YES || echo NO; }
153
+ gate_title() { _gate_title "$1"; }
154
+
155
+ # gate_name_for_number <N> -> echoes the semantic name.
156
+ gate_name_for_number() {
157
+ local want="$1" row
158
+ for row in "${GATE_REGISTRY_ROWS[@]}"; do
159
+ case "$row" in
160
+ *\|"$want"\|*) printf '%s\n' "${row%%|*}"; return 0 ;;
161
+ esac
162
+ done
163
+ return 1
164
+ }
165
+
166
+ # gate_name_for_file <file> -> semantic name of the gate implemented by <file>.
167
+ # Returns 1 for `inline` gates and unknown files. This is the lookup that would
168
+ # have caught #717: gate-9.sh resolves to build-integrity, not sast.
169
+ gate_name_for_file() {
170
+ local want="$1" row impl name
171
+ for row in "${GATE_REGISTRY_ROWS[@]}"; do
172
+ name="${row%%|*}"
173
+ impl=$(printf '%s\n' "$row" | cut -d'|' -f3)
174
+ [ "$impl" = "$want" ] && { printf '%s\n' "$name"; return 0; }
175
+ done
176
+ return 1
177
+ }
178
+
179
+ # List every script the registry claims the hook runs.
180
+ gate_all_impls() {
181
+ local row impl
182
+ for row in "${GATE_REGISTRY_ROWS[@]}"; do
183
+ impl=$(printf '%s\n' "$row" | cut -d'|' -f3)
184
+ [ "$impl" != "inline" ] && printf '%s\n' "$impl"
185
+ done
186
+ }
187
+
188
+ gate_registry_dump() {
189
+ local row name num impl blocks
190
+ for row in "${GATE_REGISTRY_ROWS[@]}"; do
191
+ name="${row%%|*}"
192
+ num=$(printf '%s\n' "$row" | cut -d'|' -f2)
193
+ impl=$(printf '%s\n' "$row" | cut -d'|' -f3)
194
+ blocks=$(printf '%s\n' "$row" | cut -d'|' -f4)
195
+ printf '%-3s %-22s %-34s %-6s %s\n' "$num" "$name" "$(_gate_title "$name")" "$blocks" "$impl"
196
+ done
197
+ }
@@ -29,12 +29,6 @@ export interface PowerShellInfo {
29
29
 
30
30
  // ── Tool Detection ──
31
31
 
32
- /**
33
- * Cross-platform tool detection with 3-tier fallback:
34
- * 1. PATH lookup (command -v equivalent)
35
- * 2. npx fallback (for npm-installed tools)
36
- * 3. Custom path (~/.local/bin/ on Unix)
37
- */
38
32
  /** Tier 1: PATH lookup. */
39
33
  function probeToolPath(tool: string): ToolAvailability {
40
34
  const whichCmd = process.platform === 'win32' ? 'where' : 'which';
@@ -47,8 +41,34 @@ function probeToolPath(tool: string): ToolAvailability {
47
41
  return { available: false, path: '', via: 'none' };
48
42
  }
49
43
 
50
- /** Tier 2: npx fallback (check if tool is available via npx). */
44
+ /**
45
+ * Is the npx fallback probe enabled?
46
+ *
47
+ * `probeToolNpx` answers "is this tool installed?" by running
48
+ * `npx --yes <tool> --version`. `--yes` means "do not ask, just download and
49
+ * install it" — so to answer a question about the LOCAL environment, XP-Gate
50
+ * could reach the npm registry, download a whole package, and execute it. On
51
+ * this machine that costs 4-6 s per tool, hangs for the full 15 s timeout when
52
+ * offline, and installs packages on someone else's machine without asking.
53
+ *
54
+ * That is the wrong default for a quality gate, so it is OFF unless explicitly
55
+ * requested. Measured on this machine (2026-11-09): the probe is the single
56
+ * largest avoidable per-tool cost, and every tool this repo's gates use
57
+ * (semgrep, lizard, gitleaks, mypy, ruff) is normally on PATH anyway.
58
+ *
59
+ * Setting `XP_GATE_NPX_PROBE=1` restores the old behaviour for projects that
60
+ * deliberately rely on npx-provided tooling (typically CI).
61
+ */
62
+ function npxProbeEnabled(): boolean {
63
+ const raw = process.env.XP_GATE_NPX_PROBE;
64
+ if (raw === undefined) return false;
65
+ const v = raw.trim().toLowerCase();
66
+ return v === '1' || v === 'true' || v === 'yes';
67
+ }
68
+
69
+ /** Tier 2: npx fallback. No-op unless `XP_GATE_NPX_PROBE=1` (see npxProbeEnabled). */
51
70
  function probeToolNpx(tool: string, cwd?: string): ToolAvailability {
71
+ if (!npxProbeEnabled()) return { available: false, path: '', via: 'none' };
52
72
  try {
53
73
  const npxCheck = spawnSync('npx', ['--yes', tool, '--version'], {
54
74
  encoding: 'utf-8',
@@ -63,6 +83,15 @@ function probeToolNpx(tool: string, cwd?: string): ToolAvailability {
63
83
  return { available: false, path: '', via: 'none' };
64
84
  }
65
85
 
86
+ /**
87
+ * Cross-platform tool detection with 3-tier fallback:
88
+ * 1. PATH lookup (command -v equivalent)
89
+ * 2. npx fallback (for npm-installed tools) — OPT-IN, see npxProbeEnabled()
90
+ * 3. Custom path (~/.local/bin/ on Unix)
91
+ *
92
+ * Tier 2 is skipped unless `XP_GATE_NPX_PROBE=1`, because it installs packages
93
+ * to answer a question about the local environment.
94
+ */
66
95
  export function isToolAvailable(tool: string, cwd?: string): ToolAvailability {
67
96
  // Tier 1: PATH lookup
68
97
  const pathProbe = probeToolPath(tool);
package/gates/gate-9.ts CHANGED
@@ -3,6 +3,13 @@
3
3
  * Detects security vulnerabilities in staged files.
4
4
  * For PowerShell projects: uses PSScriptAnalyzer security rules as alternative.
5
5
  * TypeScript rewrite of githooks/adapters/gate-9.sh for cross-platform Node.js CLI.
6
+ *
7
+ * Ordering (#782, P0-A): the change set is filtered to semgrep-supported files
8
+ * BEFORE the tool is probed. The reverse order made a change set with nothing to
9
+ * scan pay for `isToolAvailable('semgrep')` first — and with the old npx fallback
10
+ * that probe could reach the registry and download semgrep — purely to then decide
11
+ * there was no input. Measured 2026-11-09, no-input fixture: 789 ms -> 624 ms
12
+ * (-21.0%, 12-round load-valid ABBA).
6
13
  */
7
14
  import {
8
15
  GateInput, GateOutput, isToolAvailable, runTool, recordAudit,
@@ -43,6 +50,16 @@ export function runGate9(input: GateInput): GateOutput {
43
50
  return runPowerShellSAST(input, startMs, messages);
44
51
  }
45
52
 
53
+ // Filter to semgrep-supported language files FIRST (#782, P0-A). The input
54
+ // question is free; the tool question is not, so it must be asked second.
55
+ // See the module header for the measurement behind this ordering.
56
+ const semgrepFiles = filterSemgrepFiles(input.changedFiles);
57
+ if (semgrepFiles.length === 0) {
58
+ messages.push(' ⏭️ SKIPPED - SAST (no supported language files changed)');
59
+ recordAudit('gate-9', 'sast-security', 'SKIP', 0, startMs);
60
+ return { status: 'SKIP', messages, exitCode: 0 };
61
+ }
62
+
46
63
  // Standard path: semgrep
47
64
  const tool = isToolAvailable('semgrep', input.cwd);
48
65
  if (!tool.available) {
@@ -57,14 +74,6 @@ export function runGate9(input: GateInput): GateOutput {
57
74
  const semgrepCmd = tool.via === 'npx' ? 'npx' : tool.path;
58
75
  const semgrepArgs = tool.via === 'npx' ? ['-y', 'semgrep'] : [];
59
76
 
60
- // Filter to semgrep-supported language files
61
- const semgrepFiles = filterSemgrepFiles(input.changedFiles);
62
- if (semgrepFiles.length === 0) {
63
- messages.push(' ⏭️ SKIPPED - SAST (no supported language files changed)');
64
- recordAudit('gate-9', 'sast-security', 'SKIP', 0, startMs);
65
- return { status: 'SKIP', messages, exitCode: 0 };
66
- }
67
-
68
77
  // Run semgrep with JSON output. Fixed overhead per run is the point of #640 --
69
78
  // see SEMGREP_EXTRA_ARGS.
70
79
  semgrepArgs.push('scan', `--config=${SEMGREP_RULESET}`, '--json', ...SEMGREP_EXTRA_ARGS, ...semgrepFiles);