@boyingliu01/xp-gate 0.37.3 → 0.38.1

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 (116) 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/python-health.ts +67 -29
  16. package/hooks/adapter-common.sh +12 -2
  17. package/hooks/deploy-manifest.sh +100 -0
  18. package/hooks/gate-10.sh +99 -26
  19. package/hooks/gate-12-file-hygiene.sh +13 -1
  20. package/hooks/gate-driver.sh +120 -0
  21. package/hooks/gate-entries/gate-0-entry.sh +825 -0
  22. package/hooks/gate-entries/gate-1-entry.sh +767 -0
  23. package/hooks/gate-entries/gate-10-entry.sh +52 -0
  24. package/hooks/gate-entries/gate-11-entry.sh +120 -0
  25. package/hooks/gate-entries/gate-12-entry.sh +44 -0
  26. package/hooks/gate-entries/gate-12b-entry.sh +178 -0
  27. package/hooks/gate-entries/gate-12c-entry.sh +80 -0
  28. package/hooks/gate-entries/gate-13-entry.sh +584 -0
  29. package/hooks/gate-entries/gate-2-entry.sh +199 -0
  30. package/hooks/gate-entries/gate-3-entry.sh +53 -0
  31. package/hooks/gate-entries/gate-4-entry.sh +46 -0
  32. package/hooks/gate-entries/gate-5-entry.sh +1729 -0
  33. package/hooks/gate-entries/gate-6-entry.sh +658 -0
  34. package/hooks/gate-entries/gate-7-entry.sh +41 -0
  35. package/hooks/gate-entries/gate-8-entry.sh +33 -0
  36. package/hooks/gate-entries/gate-9-entry.sh +307 -0
  37. package/hooks/gate-entries/subdir-restore.sh +27 -0
  38. package/hooks/gate-registry.sh +51 -15
  39. package/hooks/hook-module-resolution.sh +73 -0
  40. package/hooks/install.sh +135 -0
  41. package/hooks/lib/now-ms.sh +55 -19
  42. package/hooks/lib/toolchain-path.sh +50 -6
  43. package/hooks/pre-commit +256 -5091
  44. package/hooks/pre-push +212 -25
  45. package/lib/__tests__/arch-config-template.test.js +190 -0
  46. package/lib/__tests__/baseline-shell-scope.test.js +60 -0
  47. package/lib/__tests__/crap-cli.test.js +14 -3
  48. package/lib/__tests__/deploy-manifest-check-wired.test.js +138 -0
  49. package/lib/__tests__/deploy-manifest-completeness.test.js +151 -0
  50. package/lib/__tests__/deploy-manifest-consumers-adapter-uninstall.test.js +40 -0
  51. package/lib/__tests__/deploy-manifest-consumers-no-private-lists.test.js +74 -0
  52. package/lib/__tests__/deploy-manifest-projection.test.js +66 -0
  53. package/lib/__tests__/deploy-manifest-shell-parity.test.js +108 -0
  54. package/lib/__tests__/deploy-manifest.test.js +97 -0
  55. package/lib/__tests__/doctor.test.js +51 -7
  56. package/lib/__tests__/gate-coverage.test.js +79 -12
  57. package/lib/__tests__/gate-numbering.test.js +28 -1
  58. package/lib/__tests__/install-sh-deploy-manifest.test.js +80 -0
  59. package/lib/__tests__/mirror-sync.test.js +45 -3
  60. package/lib/__tests__/npm-package.test.js +10 -7
  61. package/lib/__tests__/sastd-client.test.js +514 -0
  62. package/lib/__tests__/shared-utils-copyHooks-manifest.test.js +69 -0
  63. package/lib/__tests__/sprint-status-rework.test.js +1 -0
  64. package/lib/arch-config-template.js +87 -0
  65. package/lib/baseline.js +54 -2
  66. package/lib/deploy-manifest.js +174 -0
  67. package/lib/doctor.js +46 -14
  68. package/lib/gate-capability.js +291 -0
  69. package/lib/gate-coverage.js +194 -74
  70. package/lib/gate-identity.js +349 -0
  71. package/lib/gate-runner.js +11 -1
  72. package/lib/hook-module-resolution.js +27 -0
  73. package/lib/init.js +72 -5
  74. package/lib/mattpocock-license-verdict.json +1 -1
  75. package/lib/sastd-client.js +572 -0
  76. package/lib/shared-utils.js +31 -9
  77. package/lib/uninstall.js +10 -7
  78. package/lib/update-hooks.js +27 -18
  79. package/mock-policy/AGENTS.md +1 -1
  80. package/mutation/AGENTS.md +1 -1
  81. package/package.json +3 -1
  82. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  83. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  84. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  85. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  86. package/plugins/dsh/package.json +1 -1
  87. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  88. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  89. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  90. package/plugins/opencode/package.json +1 -1
  91. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  92. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  93. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  94. package/plugins/qoder/plugin.json +1 -1
  95. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  96. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  97. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  98. package/principles/AGENTS.md +1 -1
  99. package/principles/__tests__/analyzer.test.ts +2 -1
  100. package/principles/__tests__/config-enforcement.test.ts +1 -0
  101. package/principles/__tests__/types.test.ts +1 -0
  102. package/principles/adapters/base.ts +14 -1
  103. package/principles/adapters/duplication.ts +134 -0
  104. package/principles/rules/__tests__/clean-code/large-file.test.ts +2 -1
  105. package/principles/rules/clean-code/code-duplication.ts +75 -9
  106. package/principles/types.ts +39 -0
  107. package/scripts/__tests__/check-mattpocock-license.test.js +36 -3
  108. package/scripts/__tests__/sync-package-content.test.js +12 -2
  109. package/scripts/generate-mirrors.cjs +125 -0
  110. package/scripts/sync-package-content.js +64 -20
  111. package/skills/delphi-review/AGENTS.md +1 -1
  112. package/skills/sprint-flow/AGENTS.md +1 -1
  113. package/skills/test-specification-alignment/AGENTS.md +1 -1
  114. package/adapters/gate-9.sh +0 -245
  115. package/gate-9.sh +0 -245
  116. 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
+ }
@@ -60,6 +60,12 @@ const SIGNAL_SKIP_DIRS = new Set([
60
60
  const SIGNAL_MAX_DEPTH = 4;
61
61
  const SIGNAL_MAX_ENTRIES = 5000;
62
62
 
63
+ /**
64
+ * Virtualenv directory names. Their presence alone is a Python signal even with
65
+ * no marker file, common for `python -m venv .venv`-only setups.
66
+ */
67
+ const VENV_DIR_NAMES = ['.venv', 'venv'];
68
+
63
69
  /**
64
70
  * Does this project show any sign of being Python at all?
65
71
  *
@@ -86,43 +92,75 @@ const SIGNAL_MAX_ENTRIES = 5000;
86
92
  */
87
93
  export function hasPythonSignal(cwd?: string): boolean {
88
94
  const root = cwd || process.cwd();
95
+ return hasMarkerFile(root) || hasVenvDir(root) || containsPythonFile(root);
96
+ }
89
97
 
90
- for (const marker of PYTHON_MARKER_FILES) {
91
- try {
92
- if (fs.existsSync(path.join(root, marker))) return true;
93
- } catch { /* unreadable root → fall through to the walk */ }
94
- }
95
-
96
- // Virtualenv directories are themselves a Python project signal even with no
97
- // marker file (common for `python -m venv .venv`-only setups).
98
- for (const venv of ['.venv', 'venv']) {
99
- try {
100
- if (fs.existsSync(path.join(root, venv))) return true;
101
- } catch { /* ignore */ }
102
- }
103
-
104
- let seen = 0;
105
- const walk = (dir: string, depth: number): boolean => {
106
- if (depth > SIGNAL_MAX_DEPTH || seen > SIGNAL_MAX_ENTRIES) return false;
107
- let entries: import('fs').Dirent[];
98
+ /** Is any marker file present? An unreadable root is not evidence either way. */
99
+ function hasMarkerFile(root: string): boolean {
100
+ return PYTHON_MARKER_FILES.some((marker) => {
108
101
  try {
109
- entries = fs.readdirSync(dir, { withFileTypes: true });
102
+ return fs.existsSync(path.join(root, marker));
110
103
  } catch {
111
104
  return false;
112
105
  }
113
- for (const entry of entries) {
114
- if (seen++ > SIGNAL_MAX_ENTRIES) return false;
115
- if (entry.isDirectory()) {
116
- if (SIGNAL_SKIP_DIRS.has(entry.name) || entry.name.startsWith('.')) continue;
117
- if (walk(path.join(dir, entry.name), depth + 1)) return true;
118
- } else if (entry.name.endsWith('.py')) {
119
- return true;
120
- }
106
+ });
107
+ }
108
+
109
+ /**
110
+ * Is a virtualenv directory present? Only the signal matters here, so an
111
+ * unreadable root still counts as a hit rather than being silently skipped.
112
+ */
113
+ function hasVenvDir(root: string): boolean {
114
+ return VENV_DIR_NAMES.some((venv) => {
115
+ try {
116
+ return fs.existsSync(path.join(root, venv));
117
+ } catch {
118
+ return true;
121
119
  }
120
+ });
121
+ }
122
+
123
+ /** Should this directory be skipped during the .py walk? */
124
+ function shouldSkipDir(entry: import('fs').Dirent): boolean {
125
+ return SIGNAL_SKIP_DIRS.has(entry.name) || entry.name.startsWith('.');
126
+ }
127
+
128
+ /** A non-directory entry is a hit only if it is a .py file. */
129
+ function isPythonFileEntry(entry: import('fs').Dirent): boolean {
130
+ return !entry.isDirectory() && entry.name.endsWith('.py');
131
+ }
132
+
133
+ /**
134
+ * One directory level: does this directory or any descendant hold a .py file?
135
+ * Split from containsPythonFile so the bounds and the traversal stay separately
136
+ * readable, and bounded by depth and entry count so a pathological tree cannot
137
+ * make a gate hang.
138
+ */
139
+ function walkForPythonFile(dir: string, depth: number, counter: { seen: number }): boolean {
140
+ if (depth > SIGNAL_MAX_DEPTH || counter.seen > SIGNAL_MAX_ENTRIES) return false;
141
+ let entries: import('fs').Dirent[];
142
+ try {
143
+ entries = fs.readdirSync(dir, { withFileTypes: true });
144
+ } catch {
122
145
  return false;
123
- };
146
+ }
147
+ for (const entry of entries) {
148
+ counter.seen += 1;
149
+ if (counter.seen > SIGNAL_MAX_ENTRIES) return false;
150
+ if (isPythonFileEntry(entry)) return true;
151
+ if (entry.isDirectory() && !shouldSkipDir(entry) && walkForPythonFile(path.join(dir, entry.name), depth + 1, counter)) {
152
+ return true;
153
+ }
154
+ }
155
+ return false;
156
+ }
124
157
 
125
- return walk(root, 0);
158
+ /**
159
+ * Look for any .py file under root. Returns false on a read error: "could not
160
+ * look" must never be reported as "definitely not Python".
161
+ */
162
+ function containsPythonFile(root: string): boolean {
163
+ return walkForPythonFile(root, 0, { seen: 0 });
126
164
  }
127
165
 
128
166
  // ── Python Detection ──
@@ -225,7 +225,15 @@ require_tool() {
225
225
  return 0
226
226
  fi
227
227
 
228
- if command -v npx >/dev/null 2>&1 && npx --no-install "$tool_name" --version >/dev/null 2>&1; then
228
+ # Project-local node_modules/.bin. This replaces an `npx --no-install <tool>
229
+ # --version` probe: `--no-install` does prevent the package from being
230
+ # INSTALLED, but it still asks the registry every time (measured: 697 ms on a
231
+ # cache miss, 105 ms revalidating on a hit), inside a pre-commit hook. And once
232
+ # any earlier misuse populates the npx cache the same probe returns rc=0 for a
233
+ # tool the project never depended on, so the answer can be corrupted, not just
234
+ # slow. Checking the directory the tool would actually live in is both cheaper
235
+ # and honest. See docs/incidents/2026-11-09-command-could-not-run-*.
236
+ if [ -x "node_modules/.bin/$tool_name" ]; then
229
237
  return 0
230
238
  fi
231
239
 
@@ -289,7 +297,9 @@ detect_mutation_testable() {
289
297
  if [ -f "package.json" ] && grep -qE '"@stryker-mutator[^"]*"' package.json 2>/dev/null; then
290
298
  return 0
291
299
  fi
292
- if command -v npx >/dev/null 2>&1 && npx --no-install stryker --version >/dev/null 2>&1; then
300
+ # Project-local install. Replaces `npx --no-install stryker --version`, which
301
+ # still queried the registry on every call (see require_tool above).
302
+ if [ -x "node_modules/.bin/stryker" ]; then
293
303
  return 0
294
304
  fi
295
305
  # Legacy config files (backwards compatibility — deprecated)