@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
@@ -0,0 +1,767 @@
1
+ #!/usr/bin/env bash
2
+ # ============================================================================
3
+ # gate-1 entry — extracted from pre-commit by scripts/extract-gates.cjs
4
+ #
5
+ # WHY THIS FILE EXISTS (#798)
6
+ # The gate order used to BE the physical order of blocks in a 6341-line
7
+ # hook, so changing the order meant moving thousands of lines. An attempt at
8
+ # that also moved the hook epilogue, after which every gate past Gate 13
9
+ # silently stopped running while `bash -n`, a line count and five ordering
10
+ # tests all passed. Gate 5a stopped blocking and only a behavioural test
11
+ # noticed. With one file per gate, order is a list of names in
12
+ # pre-commit's GATE_ORDER and cannot detach a body from its position.
13
+ #
14
+ # THE BODY BELOW IS A BYTE-EXACT SLICE of the original block. It is wrapped
15
+ # in a function so the gate keeps its own variable scope, and is called from
16
+ # pre-commit at the point the driver reaches it. Edit the gate here from now
17
+ # on - there is no copy left in the hook.
18
+ # ============================================================================
19
+
20
+ # ============================================================================
21
+ # GATE 1: Code Quality (Static Analysis + Linting + Shell Check combined)
22
+ # Combination of: Old Gates 1 (Static), Gate 2 (Linting), Gate 5 (Shell Check)
23
+ # v0.14.3+ (Issue #312): Skip if no code files changed
24
+ # ============================================================================
25
+ # Gate body. `return` is used instead of `exit` so the driver decides to
26
+ # stop: see scripts/wrap-gate-entries.cjs for why the two are equivalent
27
+ # here, and why sub-shell exits are deliberately left as `exit`.
28
+ gate_1_run() {
29
+ 2>&1 echo ""
30
+ 2>&1 echo "→ Gate 1: Code Quality (static analysis + linting)..."
31
+ # REQ-B: the start stamp is taken OUTSIDE the branches below. It used to be
32
+ # assigned only on the lint path, so every skipped Gate 1 recorded an empty
33
+ # GATE_1_START -> duration_ms=null with reason=poisoned_start_ms. That null is
34
+ # honest but it answers the wrong question: those commits never ran the gate, so
35
+ # the log should say SKIP, not "measurement failed".
36
+ GATE_1_START=$(gate_start_ms)
37
+ GATE_1_STATUS="PASS"
38
+ GATE_1_DETAIL=""
39
+ if ! gate_enabled 1; then
40
+ echo "⏭️ SKIPPED - Gate 1: Code quality (not selected by XP_GATE_ONLY_GATE)"
41
+ GATE_1_STATUS="SKIP"
42
+ GATE_1_DETAIL="not_selected"
43
+ elif ! any_changed_files_match "\.(ts|tsx|js|jsx|py|go|java|kt|cpp|c|swift|m|mm|dart|sh|ps1|psm1|cs|csx|fs|vb|rs|php|rb|lua|pl)$" "\.ya?ml$" "\.json$" "Dockerfile" "\.tf$"; then
44
+ # #798: this branch did NOT run a lint check, so it must not report PASSED.
45
+ # "No code files changed" is a SKIP: the same wording Gate 3 already uses
46
+ # ("⏭️ SKIPPED - Complexity: no changed source files in this run"). Reporting
47
+ # ✅ PASSED here meant a project whose main language was missing from the
48
+ # extension list got a green Gate 1 on every single commit, having analysed
49
+ # nothing. C# was exactly that case before `.cs` was added below.
50
+ echo "⏭️ SKIPPED - Code quality: no changed code files in this run (scope: diff)."
51
+ GATE_1_STATUS="SKIP"
52
+ GATE_1_DETAIL="no_matching_files"
53
+ else
54
+ if [ "$PROJECT_LANG" = "documentation-only" ]; then
55
+ # Documentation-only project - skip static analysis
56
+ echo "⏭️ SKIPPED - Code quality (documentation project)."
57
+ GATE_1_STATUS="SKIP"
58
+ GATE_1_DETAIL="documentation_project"
59
+
60
+ else
61
+ for CURRENT_LANG in $PROJECT_LANGS; do
62
+ echo " ── Checking $CURRENT_LANG ──"
63
+ case "$CURRENT_LANG" in
64
+ typescript)
65
+ # TypeScript: static analysis + linting (eslint). The type-check decision lives
66
+ # in githooks/lib/typecheck.sh so a project's own checker (vue-tsc, svelte-check,
67
+ # a `typecheck` script) is used instead of a hardcoded tsc that cannot resolve
68
+ # single-file components (#436).
69
+ #
70
+ # Resolve the TS project directory first (#470). The probes below used to run
71
+ # against the repo root only; in multi-language monorepos (e.g. web/ +
72
+ # backend/, where the hook stays at the root — see the cd block above)
73
+ # tsconfig.json / biome.json live in the language subdirectory, so the whole
74
+ # TS half of Gate 1 silently SKIPped ("tsconfig.json not found") while a
75
+ # project config existed. Order: repo root first (unchanged behaviour for
76
+ # plain projects), then the detected language subdirectory, then a shallow
77
+ # search.
78
+ TS_PROJECT_DIR=""
79
+ for _ts_dir in "." "${PROJECT_SUBDIR:-}"; do
80
+ [ -z "$_ts_dir" ] && continue
81
+ if [ -f "$_ts_dir/tsconfig.json" ] || [ -f "$_ts_dir/biome.json" ] || [ -f "$_ts_dir/biome.jsonc" ] \
82
+ || [ -f "$_ts_dir/eslint.config.js" ] || [ -f "$_ts_dir/.eslintrc.json" ] \
83
+ || [ -f "$_ts_dir/.eslintrc.js" ] || [ -f "$_ts_dir/.eslintrc.cjs" ]; then
84
+ TS_PROJECT_DIR="$_ts_dir"
85
+ break
86
+ fi
87
+ done
88
+ if [ -z "$TS_PROJECT_DIR" ]; then
89
+ _TSCONFIG_CAND=$(find . -maxdepth 2 \( -name tsconfig.json -o -name biome.json -o -name biome.jsonc -o -name eslint.config.js -o -name .eslintrc.json -o -name .eslintrc.js -o -name .eslintrc.cjs \) -not -path './.git/*' -not -path './node_modules/*' 2>/dev/null | head -1)
90
+ if [ -n "$_TSCONFIG_CAND" ]; then
91
+ TS_PROJECT_DIR=$(dirname "$_TSCONFIG_CAND")
92
+ fi
93
+ fi
94
+ [ -z "$TS_PROJECT_DIR" ] && TS_PROJECT_DIR="."
95
+ if [ "$TS_PROJECT_DIR" != "." ]; then
96
+ echo " TypeScript project directory: $TS_PROJECT_DIR/"
97
+ # typecheck.sh is cwd-relative: run it from the TS project subdirectory in a
98
+ # subshell so the language loop's next iteration still starts at the root.
99
+ # Exit contract: 0 clean, 1 findings (block), 2 checker unavailable (skip).
100
+ # A cd/source infrastructure failure must NOT read as "type errors": map it
101
+ # to 2 (skip) so 1 stays reserved for real findings (#508 walkthrough).
102
+ ( cd "$TS_PROJECT_DIR" 2>/dev/null || exit 2 \
103
+ ; [ -r "${AUDIT_SCRIPT_DIR}/lib/typecheck.sh" ] || exit 2 \
104
+ ; source "${AUDIT_SCRIPT_DIR}/lib/typecheck.sh" && run_typescript_typecheck )
105
+ TS_CHECK_EXIT=$?
106
+ else
107
+ source_gate_lib "${AUDIT_SCRIPT_DIR}/lib/typecheck.sh"
108
+ run_typescript_typecheck
109
+ TS_CHECK_EXIT=$?
110
+ fi
111
+ if [ "$TS_CHECK_EXIT" -eq 1 ]; then
112
+ return 1
113
+ fi
114
+
115
+ # Run ESLint linting if config exists (root or TS project subdirectory)
116
+ if [ -f "$TS_PROJECT_DIR/.eslintrc.json" ] || [ -f "$TS_PROJECT_DIR/.eslintrc.js" ] || [ -f "$TS_PROJECT_DIR/.eslintrc.cjs" ] || [ -f "$TS_PROJECT_DIR/eslint.config.js" ]; then
117
+ echo "Running ESLint linting..."
118
+ # Filter to only TS/JS files - ESLint config ignores non-matching files
119
+ ESLINT_FILES=$(echo "$CHANGED_FILES" | grep -E '\.(ts|tsx|js|jsx)$' || true)
120
+ if [ -n "$ESLINT_FILES" ]; then
121
+ # File paths from git are repo-root relative, so they are correct from
122
+ # the root. Legacy .eslintrc.* configs are discovered by walking up from
123
+ # each linted file (found in the subdirectory automatically); flat
124
+ # configs are discovered from the CWD, so point at them explicitly.
125
+ if [ "$TS_PROJECT_DIR" != "." ] && [ -f "$TS_PROJECT_DIR/eslint.config.js" ]; then
126
+ ESLINT_OUTPUT=$(run_node_bin eslint eslint/bin/eslint.js --config "$TS_PROJECT_DIR/eslint.config.js" $ESLINT_FILES -f json --no-warn-ignored 2>&1)
127
+ else
128
+ ESLINT_OUTPUT=$(run_node_bin eslint eslint/bin/eslint.js $ESLINT_FILES -f json --no-warn-ignored 2>&1)
129
+ fi
130
+ ESLINT_EXIT=$?
131
+ if [ "$ESLINT_EXIT" -ne 0 ]; then
132
+ if [ -f ".xp-gate/lint-baseline.json" ] && command -v node &> /dev/null; then
133
+ # Compare against lint baseline
134
+ BASELINE_WARNINGS=$(echo "$ESLINT_FILES" | tr ' ' '\n' | node -e "
135
+ const fs=require('fs');const b=JSON.parse(fs.readFileSync('.xp-gate/lint-baseline.json','utf8'));
136
+ const stdin=require('fs').readFileSync(0,'utf8').trim();
137
+ const files=stdin?stdin.split('\n'):[];
138
+ let total=0;for(const f of files){if(b[f])total+=b[f].totalWarnings||0}
139
+ console.log(total);
140
+ ")
141
+ CURRENT_WARNINGS=$(echo "$ESLINT_OUTPUT" | node -e "
142
+ const d=JSON.parse(require('fs').readFileSync(0,'utf8'));
143
+ console.log(d.reduce((s,f)=>s+(f.warningCount||0)+(f.errorCount||0),0));
144
+ ")
145
+ if [ "$CURRENT_WARNINGS" -gt "$BASELINE_WARNINGS" ]; then
146
+ NEW_WARNINGS=$((CURRENT_WARNINGS - BASELINE_WARNINGS))
147
+ echo "$ESLINT_OUTPUT" | head -30
148
+ echo ""
149
+ echo "❌ BLOCKED - ${NEW_WARNINGS} NEW lint error(s) (baseline: ${BASELINE_WARNINGS}, current: ${CURRENT_WARNINGS})"
150
+ echo "Run 'xp-gate baseline reset' after fixing to update the baseline."
151
+ return 1
152
+ else
153
+ REDUCED=$((BASELINE_WARNINGS - CURRENT_WARNINGS))
154
+ if [ "$REDUCED" -gt 0 ]; then
155
+ echo "✅ PASSED - Lint debt reduced by ${REDUCED} (${BASELINE_WARNINGS} → ${CURRENT_WARNINGS})"
156
+ else
157
+ echo "✅ PASSED - No new lint errors (baseline: ${BASELINE_WARNINGS})"
158
+ fi
159
+ fi
160
+ else
161
+ echo "$ESLINT_OUTPUT" | head -30
162
+ echo ""
163
+ echo "❌ BLOCKED - LINT ERRORS detected"
164
+ echo "Fix the lint errors above before committing."
165
+ echo "Tip: Run 'xp-gate baseline create' to establish a lint baseline."
166
+ return 1
167
+ fi
168
+ else
169
+ echo "✅ PASSED - ESLint linting."
170
+ fi
171
+ else
172
+ echo "✅ PASSED - No staged TS/JS files to lint."
173
+ fi
174
+ else
175
+ echo "ℹ️ No ESLint configuration found - Skipping"
176
+ if [ -f "$TS_PROJECT_DIR/package.json" ] && command -v node &> /dev/null; then
177
+ HAS_ESLINT=$(node -e "try{const p=JSON.parse(require('fs').readFileSync('$TS_PROJECT_DIR/package.json','utf8'));const d=p.devDependencies||{};const deps=p.dependencies||{};console.log((d.eslint||deps.eslint)?'yes':'no')}catch{console.log('no')}") && true
178
+ if [ "$HAS_ESLINT" = "yes" ]; then
179
+ echo "⚠️ WARNING: eslint is installed in package.json but no eslint config found"
180
+ echo " Either create .eslintrc.* / eslint.config.* or remove eslint from dependencies"
181
+ echo " See: https://eslint.org/docs/latest/use/configure/configuration-files"
182
+ fi
183
+ fi
184
+ fi
185
+
186
+ # ── Biome lint/format check ──
187
+ # Default the project dir so this branch stays runnable standalone
188
+ # (the gate-1-biome-noop suite extracts it verbatim); a no-op inside the
189
+ # hook, where TS_PROJECT_DIR is resolved above.
190
+ TS_PROJECT_DIR="${TS_PROJECT_DIR:-.}"
191
+ if [ -f "$TS_PROJECT_DIR/biome.json" ] || [ -f "$TS_PROJECT_DIR/biome.jsonc" ]; then
192
+ echo "Running Biome lint/format check..."
193
+ # Run from the TS project directory so Biome auto-discovers its config and
194
+ # scopes --staged to that subdirectory (mirrors the single-language subdir
195
+ # mode, which executes after cd "$PROJECT_SUBDIR"). Empirically verified:
196
+ # `biome check --staged .` from the subdir checks the staged files under it.
197
+ BIOME_OUT=$(cd "$TS_PROJECT_DIR" && npx biome check --staged . 2>&1)
198
+ BIOME_STATUS=$?
199
+ if [ "$BIOME_STATUS" -ne 0 ]; then
200
+ # Biome exits 1 with `internalError/io - No files were processed` when the
201
+ # staged set yields nothing lintable (docs-only / config-only commit, or
202
+ # everything excluded by biome.json). That is "nothing to do", not a lint
203
+ # violation -- blocking on it makes documentation uncommittable (#458).
204
+ # This matches the hook's stated principle: tool available + check
205
+ # SUCCEEDS = PASS. Real violations still carry diagnostics, so they block.
206
+ if echo "$BIOME_OUT" | grep -qE 'internalError/io|No files were processed'; then
207
+ echo "$BIOME_OUT"
208
+ echo "✅ PASSED - Biome check (no lintable files staged)."
209
+ else
210
+ echo "$BIOME_OUT" | head -50
211
+ echo ""
212
+ echo "❌ BLOCKED - Biome check failed"
213
+ echo "Fix the errors above before committing."
214
+ echo "Tip: Run 'npx biome check --write .' to auto-fix formatting and safe lint issues."
215
+ echo " Run 'npx biome check --write --unsafe .' to also fix unsafe lint issues."
216
+ return 1
217
+ fi
218
+ else
219
+ echo "✅ PASSED - Biome check."
220
+ fi
221
+ else
222
+ if [ -f "$TS_PROJECT_DIR/package.json" ] && command -v node &> /dev/null; then
223
+ HAS_BIOME=$(node -e "try{const p=JSON.parse(require('fs').readFileSync('$TS_PROJECT_DIR/package.json','utf8'));const d=p.devDependencies||{};const deps=p.dependencies||{};console.log((d['@biomejs/biome']||deps['@biomejs/biome'])?'yes':'no')}catch{console.log('no')}") && true
224
+ if [ "$HAS_BIOME" = "yes" ]; then
225
+ echo ""
226
+ echo "⚠️ WARNING: @biomejs/biome is installed in package.json but no biome.json found"
227
+ echo " Create a biome.json configuration file to enable Biome linting."
228
+ echo " NOTE: useLiteralKeys conflicts with TypeScript TS4111 — see docs/biome-configuration.md"
229
+ echo " For quick setup: add '\"linter\":{\"rules\":{\"complexity\":{\"useLiteralKeys\":\"off\"}}}' to biome.json"
230
+ fi
231
+ fi
232
+ fi
233
+
234
+ # Debug statement detection (debugger statement in JS/TS)
235
+ #
236
+ # Dependencies and build output are filtered out first (#648). The list
237
+ # comes from `git diff --cached`, so a project (or a CI fixture) that
238
+ # vendors or commits its dependencies gets the dependency's OWN source
239
+ # scanned as if it were project code. TypeScript 7.x ships a bare
240
+ # `debugger;` in dist/internal/utils.js, which blocked commits that changed
241
+ # nothing of their own:
242
+ # ❌ BLOCKED - 'debugger' statements detected:
243
+ # node_modules/typescript/dist/internal/utils.js:18: debugger;
244
+ # Pinning the dependency's version only postpones that: any package may
245
+ # carry a debugger statement, and which one lands changes with every
246
+ # install. The rule the gate actually wants is "no debugger in OUR code",
247
+ # so the ignore set Gate 2 already uses decides what counts as ours — one
248
+ # notion of build output across the gates, overridable through the same
249
+ # XP_GATE_JSCPD_DEFAULT_IGNORE switch.
250
+ TS_DEBUG_FILES=$(echo "$CHANGED_FILES" | grep -E '\.(ts|tsx|js|jsx)$' | {
251
+ while IFS= read -r _df; do
252
+ [ -n "$_df" ] || continue
253
+ if ! jscpd_is_build_output "$_df"; then
254
+ printf '%s\n' "$_df"
255
+ fi
256
+ done
257
+ } || true)
258
+ if [ -n "$TS_DEBUG_FILES" ]; then
259
+ # NUL-separated so paths with spaces survive; a bare $VAR would word-split.
260
+ DEBUGGER_HITS=$(printf '%s\n' "$TS_DEBUG_FILES" | tr '\n' '\0' | xargs -0 grep -n '^\s*debugger\s*;\?\s*$' 2>/dev/null || true)
261
+ if [ -n "$DEBUGGER_HITS" ]; then
262
+ echo ""
263
+ echo "❌ BLOCKED - 'debugger' statements detected:"
264
+ echo "$DEBUGGER_HITS" | head -10
265
+ echo ""
266
+ echo "Remove debugger statements before committing."
267
+ return 1
268
+ fi
269
+ fi
270
+ ;;
271
+
272
+ python)
273
+ # Python: Ruff (includes syntax + linting) + mypy (optional typing)
274
+ if ! command -v ruff &> /dev/null; then
275
+ echo "ℹ️ ruff not available — skipping Python linting"
276
+ echo "⏭️ SKIPPED - Code quality (ruff not available, run: pip install ruff)"
277
+ else
278
+ # Run Ruff (includes syntax check, linting)
279
+ echo "Running Ruff linting (syntax + lint)..."
280
+ # Filter to *.py/*.pyi into a bash array so each staged path is passed as
281
+ # ONE argument even when it contains whitespace; skip ruff when no Python
282
+ # files are staged so yaml/.gitignore are never parsed.
283
+ RUFF_ARGS=()
284
+ while IFS= read -r staged_file; do
285
+ case "$staged_file" in
286
+ *.py|*.pyi) RUFF_ARGS+=("$staged_file") ;;
287
+ esac
288
+ done <<< "$CHANGED_FILES"
289
+ if [ "${#RUFF_ARGS[@]}" -eq 0 ]; then
290
+ RUFF_OUTPUT="[]"
291
+ RUFF_EXIT=0
292
+ else
293
+ RUFF_OUTPUT=$(ruff check "${RUFF_ARGS[@]}" --output-format json 2>&1)
294
+ RUFF_EXIT=$?
295
+ fi
296
+ if [ "$RUFF_EXIT" -ne 0 ]; then
297
+ if [ -f ".xp-gate/lint-baseline.json" ] && command -v node &> /dev/null; then
298
+ # Get baseline warnings for changed Python files
299
+ PY_FILES=$(echo "$CHANGED_FILES" | grep '\.py$' || true)
300
+ if [ -n "$PY_FILES" ]; then
301
+ BASELINE_WARNINGS=$(echo "$PY_FILES" | node -e "
302
+ const fs=require('fs');const b=JSON.parse(fs.readFileSync('.xp-gate/lint-baseline.json','utf8'));
303
+ const stdin=require('fs').readFileSync(0,'utf8').trim();
304
+ const files=stdin?stdin.split('\n'):[];
305
+ let total=0;for(const f of files){if(b[f])total+=b[f].totalWarnings||0}
306
+ console.log(total);
307
+ ")
308
+ CURRENT_WARNINGS=$(echo "$RUFF_OUTPUT" | node -e "
309
+ const d=JSON.parse(require('fs').readFileSync(0,'utf8'));
310
+ console.log(d.reduce((s,f)=>s+(f.messages?f.messages.length:0),0));
311
+ ")
312
+ if [ "$CURRENT_WARNINGS" -gt "$BASELINE_WARNINGS" ]; then
313
+ NEW_WARNINGS=$((CURRENT_WARNINGS - BASELINE_WARNINGS))
314
+ echo "$RUFF_OUTPUT" | node -e "
315
+ const d=JSON.parse(require('fs').readFileSync(0,'utf8'));
316
+ for(const f of d){for(const m of f.messages||[]){console.log(m.kind+': '+m.message)}}
317
+ " | head -30
318
+ echo ""
319
+ echo "❌ BLOCKED - ${NEW_WARNINGS} NEW lint error(s) (baseline: ${BASELINE_WARNINGS}, current: ${CURRENT_WARNINGS})"
320
+ echo "Run 'xp-gate baseline reset' after fixing to update the baseline."
321
+ return 1
322
+ else
323
+ REDUCED=$((BASELINE_WARNINGS - CURRENT_WARNINGS))
324
+ if [ "$REDUCED" -gt 0 ]; then
325
+ echo "✅ PASSED - Lint debt reduced by ${REDUCED} (${BASELINE_WARNINGS} → ${CURRENT_WARNINGS})"
326
+ else
327
+ echo "✅ PASSED - No new lint errors (baseline: ${BASELINE_WARNINGS})"
328
+ fi
329
+ fi
330
+ else
331
+ echo "✅ PASSED - Ruff linting (no Python files to check)."
332
+ fi
333
+ else
334
+ echo "$RUFF_OUTPUT" | node -e "
335
+ const d=JSON.parse(require('fs').readFileSync(0,'utf8'));
336
+ for(const f of d){for(const m of f.messages||[]){console.log(m.kind+': '+m.message)}}
337
+ " | head -30
338
+ echo ""
339
+ echo "❌ BLOCKED - RUFF ERRORS detected"
340
+ echo "Fix the lint errors above before committing."
341
+ echo "Tip: Run 'ruff check --fix' to auto-fix some issues."
342
+ echo "Tip: Run 'xp-gate baseline create' to establish a lint baseline."
343
+ return 1
344
+ fi
345
+ else
346
+ echo "✅ PASSED - Ruff linting."
347
+ fi
348
+
349
+ # Ruff format check (formatting gate)
350
+ if command -v ruff &> /dev/null; then
351
+ FMT_ARGS=()
352
+ while IFS= read -r staged_file; do
353
+ case "$staged_file" in
354
+ *.py|*.pyi) FMT_ARGS+=("$staged_file") ;;
355
+ esac
356
+ done <<< "$CHANGED_FILES"
357
+ if [ "${#FMT_ARGS[@]}" -gt 0 ]; then
358
+ RUFF_FMT_OUTPUT=$(ruff format --check "${FMT_ARGS[@]}" 2>&1)
359
+ RUFF_FMT_EXIT=$?
360
+ if [ "$RUFF_FMT_EXIT" -ne 0 ]; then
361
+ echo "$RUFF_FMT_OUTPUT" | head -20
362
+ echo ""
363
+ echo "❌ BLOCKED - Ruff format check failed"
364
+ echo "Fix formatting: run 'ruff format .' to auto-format."
365
+ return 1
366
+ fi
367
+ echo "✅ PASSED - Ruff format check."
368
+ fi
369
+ fi
370
+
371
+ # Debug statement detection (breakpoint/pdb/ipdb)
372
+ DEBUG_ARGS=()
373
+ while IFS= read -r staged_file; do
374
+ case "$staged_file" in
375
+ *.py|*.pyi) DEBUG_ARGS+=("$staged_file") ;;
376
+ esac
377
+ done <<< "$CHANGED_FILES"
378
+ if [ "${#DEBUG_ARGS[@]}" -gt 0 ]; then
379
+ DEBUG_HITS=$(grep -n 'breakpoint()\|pdb\.set_trace()\|ipdb\.set_trace()\|import pdb\|import ipdb' "${DEBUG_ARGS[@]}" 2>/dev/null || true)
380
+ if [ -n "$DEBUG_HITS" ]; then
381
+ echo ""
382
+ echo "❌ BLOCKED - Debug statements detected in Python files:"
383
+ echo "$DEBUG_HITS" | head -10
384
+ echo ""
385
+ echo "Remove breakpoint()/pdb.set_trace() before committing."
386
+ return 1
387
+ fi
388
+ fi
389
+
390
+ # Optional: Type checking with mypy — INCREMENTAL (fast, staged-only).
391
+ #
392
+ # Responsibility boundary (#534):
393
+ # * This branch (python case) runs mypy ONLY over the staged .py/.pyi
394
+ # files via python_typecheck_incremental — seconds, not a full inference
395
+ # pass. Uses --follow-imports=silent so a change to A.py that references
396
+ # an unchanged B.py does NOT surface B's pre-existing diagnostics; only
397
+ # caller-level signature errors still block. Its exit code is captured
398
+ # directly (temp file), which is deterministic and does not depend on
399
+ # set -o pipefail (the old `... | head | tail; rc=$?` worked only under
400
+ # pipefail and could drop mypy's status when the pattern is copied into
401
+ # a non-pipefail context).
402
+ # * The FULL mypy pass lives OUTSIDE this hook: run_static_analysis()
403
+ # (githooks/adapters/python.sh) is reachable via the adapter CLI and the
404
+ # general adapter route, and CI installs mypy (quality-gates.yml) for
405
+ # typed projects. NOTE: the pre-commit python case is fully inline and
406
+ # never routes to run_static_analysis — so the incremental blind spot
407
+ # (cross-module signature break on an unchanged file) is the accepted
408
+ # trade-off here, backstopped by full mypy wherever that surface runs.
409
+ # Both paths coexist: this one is the fast pre-commit pass.
410
+ if command -v mypy &> /dev/null; then
411
+ # Collect staged .py/.pyi via the helper (whitespace-safe, bash-3
412
+ # compatible — macOS default bash is 3.2, so avoid mapfile).
413
+ MYPY_ARGS=()
414
+ while IFS= read -r staged_file; do
415
+ MYPY_ARGS+=("$staged_file")
416
+ done < <(python_staged_py_files)
417
+ python_typecheck_incremental "${MYPY_ARGS[@]}"
418
+ MYPY_EXIT=$?
419
+ if [ "$MYPY_EXIT" -ne 0 ]; then
420
+ echo ""
421
+ echo "❌ BLOCKED - MYPY TYPE ERRORS detected"
422
+ echo "Fix the type errors above before committing."
423
+ return 1
424
+ fi
425
+ echo "✅ PASSED - mypy type checking."
426
+ else
427
+ echo "ℹ️ Mypy not available - Skipping optional type check"
428
+ fi
429
+ fi
430
+ ;;
431
+
432
+ go)
433
+ # Go: go vet + golangci-lint
434
+ if ! command -v golangci-lint &> /dev/null; then
435
+ echo "ℹ️ golangci-lint not available — skipping Go linting"
436
+ echo "⏭️ SKIPPED - Code quality (golangci-lint not available)"
437
+ else
438
+ # #534: run golangci-lint over ONLY the staged .go files (incremental),
439
+ # not the whole repo. `golangci-lint run` with no args scans every package
440
+ # and dominates pre-commit time on large Go repos. golangci-lint accepts
441
+ # explicit file targets. No staged .go files -> SKIP (nothing to lint).
442
+ GO_FILES=$(echo "$CHANGED_FILES" | grep '\.go$' || true)
443
+ if [ -z "$GO_FILES" ]; then
444
+ echo "✅ PASSED - No staged Go files to lint."
445
+ else
446
+ echo "Running golangci-lint (incremental, staged .go)..."
447
+ # #534: capture golangci-lint's REAL exit code via a temp file, not a
448
+ # pipe stage's (`... | head -30; rc=$?` would take head's status; it only
449
+ # works because of set -o pipefail, which is fragile and inconsistent with
450
+ # the python incremental helper's temp-file pattern).
451
+ GO_TMP=$(mktemp)
452
+ golangci-lint run $GO_FILES > "$GO_TMP" 2>&1
453
+ GOLANGCI_EXIT=$?
454
+ head -30 "$GO_TMP"
455
+ rm -f "$GO_TMP"
456
+ if [ "$GOLANGCI_EXIT" -ne 0 ]; then
457
+ echo ""
458
+ echo "❌ BLOCKED - GOLANGCI-LINT ERRORS detected"
459
+ echo "Fix the lint errors above before committing."
460
+ return 1
461
+ fi
462
+ echo "✅ PASSED - golangci-lint."
463
+ fi
464
+ fi
465
+ ;;
466
+
467
+ shell)
468
+ # Shell: check staged shell files only. Installed hook adapters are infrastructure,
469
+ # not project changes, and should not be linted on unrelated commits.
470
+ SHELL_FILES=$(echo "$CHANGED_FILES" | grep '\.sh$' || true)
471
+
472
+ if [ -z "$SHELL_FILES" ]; then
473
+ echo "✅ PASSED - No staged shell scripts to check."
474
+ elif command -v shellcheck &> /dev/null; then
475
+ echo "Running shellcheck on staged shell scripts..."
476
+ SHELLCHECK_OUTPUT=$(shellcheck -f json $SHELL_FILES 2>&1)
477
+ SHELLCHECK_EXIT=$?
478
+ if [ "$SHELLCHECK_EXIT" -ne 0 ]; then
479
+ if [ -f ".xp-gate/lint-baseline.json" ] && command -v node &> /dev/null; then
480
+ BASELINE_WARNINGS=$(echo "$SHELL_FILES" | node -e "
481
+ const fs=require('fs');const b=JSON.parse(fs.readFileSync('.xp-gate/lint-baseline.json','utf8'));
482
+ const stdin=require('fs').readFileSync(0,'utf8').trim();
483
+ const files=stdin?stdin.split('\n'):[];
484
+ let total=0;for(const f of files){if(b[f])total+=b[f].totalWarnings||0}
485
+ console.log(total);
486
+ ")
487
+ CURRENT_WARNINGS=$(echo "$SHELLCHECK_OUTPUT" | node -e "
488
+ const d=JSON.parse(require('fs').readFileSync(0,'utf8'));
489
+ console.log(d.length);
490
+ ")
491
+ if [ "$CURRENT_WARNINGS" -gt "$BASELINE_WARNINGS" ]; then
492
+ NEW_WARNINGS=$((CURRENT_WARNINGS - BASELINE_WARNINGS))
493
+ echo "$SHELLCHECK_OUTPUT" | node -e "
494
+ const d=JSON.parse(require('fs').readFileSync(0,'utf8'));
495
+ for(const i of d){console.log(i.file+':'+i.line+': '+i.level+': '+i.message)}
496
+ " | head -30
497
+ echo ""
498
+ echo "❌ BLOCKED - ${NEW_WARNINGS} NEW shellcheck issue(s) (baseline: ${BASELINE_WARNINGS}, current: ${CURRENT_WARNINGS})"
499
+ echo "Run 'xp-gate baseline reset' after fixing to update the baseline."
500
+ return 1
501
+ else
502
+ REDUCED=$((BASELINE_WARNINGS - CURRENT_WARNINGS))
503
+ if [ "$REDUCED" -gt 0 ]; then
504
+ echo "✅ PASSED - Shellcheck debt reduced by ${REDUCED} (${BASELINE_WARNINGS} → ${CURRENT_WARNINGS})"
505
+ else
506
+ echo "✅ PASSED - No new shellcheck issues (baseline: ${BASELINE_WARNINGS})"
507
+ fi
508
+ fi
509
+ else
510
+ echo "$SHELLCHECK_OUTPUT" | node -e "
511
+ const d=JSON.parse(require('fs').readFileSync(0,'utf8'));
512
+ for(const i of d){console.log(i.file+':'+i.line+': '+i.level+': '+i.message)}
513
+ " | head -30
514
+ echo ""
515
+ echo "❌ BLOCKED - SHELLCHECK ERRORS detected"
516
+ echo "Fix the shell script errors above."
517
+ echo "Tip: Run 'xp-gate baseline create' to establish a lint baseline."
518
+ return 1
519
+ fi
520
+ else
521
+ echo "✅ PASSED - Shellcheck completed."
522
+ fi
523
+ else
524
+ echo "ℹ️ shellcheck not available - Attempting basic syntax check"
525
+ # Basic check for staged shell script files
526
+ for sh_file in $SHELL_FILES; do
527
+ if [ -f "$sh_file" ]; then
528
+ bash -n "$sh_file"
529
+ if [ $? -ne 0 ]; then
530
+ echo "❌ BLOCKED - SYNTAX ERROR in $sh_file"
531
+ return 1
532
+ fi
533
+ fi
534
+ done
535
+ echo "✅ PASSED - Basic shell script syntax check."
536
+ fi
537
+ ;;
538
+
539
+ java)
540
+ # GATE 1 Java: wc-java-lint with fail-closed verdicts (#507 S1, DR-001).
541
+ # java.sh run_static_analysis verdict codes:
542
+ # 0=PASS 1=FAIL(violations) 2=BLOCK(execution error) 3=WARN(non-blocking).
543
+ # Every non-0/1/2 outcome is scored as WARN -- IN the denominator, so it
544
+ # forbids an overall PASS. Delphi round-2 A-MAJOR-1: these paths used to
545
+ # map to SKIP, which sits OUT of the denominator, letting a repo with no
546
+ # Java engine (or findings suppressed in report mode) report PASS/10.0
547
+ # while its Java quality was never verified.
548
+ # The adapter applies the XP_GATE_WC_JAVA_LINT=soft escape valve itself, so
549
+ # a 2 reaching this branch is hard: BLOCK the commit. Captured to a var
550
+ # (not piped) so the verdict code survives regardless of output length --
551
+ # `cmd | head` makes a long report die with SIGPIPE, which would turn a
552
+ # real verdict into an accident of line count.
553
+ ADAPTER_FILE=$(resolve_adapter_path "$CURRENT_LANG")
554
+ if [ -z "$ADAPTER_FILE" ] || ! source "$ADAPTER_FILE" 2>/dev/null; then
555
+ echo "⚠️ WARN - Java adapter not found (code quality NOT verified)"
556
+ GATE_1_STATUS="WARN"
557
+ GATE_1_DETAIL="java: adapter missing"
558
+ else
559
+ JAVA_G1_EXIT=0
560
+ # `|| JAVA_G1_EXIT=$?` (not a bare assignment): under a set -e consumer a
561
+ # non-zero verdict would abort the host hook before the mapping below.
562
+ JAVA_G1_OUTPUT=$(run_static_analysis 2>&1) || JAVA_G1_EXIT=$?
563
+ # SKIP/WARN reasons cross the command-substitution subshell as an
564
+ # `XP_G1_REASON: ...` stdout line -- an `export` inside the adapter can
565
+ # NEVER reach this process (#507 Delphi round-1 B-MAJOR-1: verified the
566
+ # subshell discards the child env). Parse, then strip from display.
567
+ JAVA_G1_REASON=$(printf '%s\n' "$JAVA_G1_OUTPUT" | sed -n 's/^XP_G1_REASON: //p' | head -1)
568
+ if [ -n "$JAVA_G1_REASON" ]; then
569
+ JAVA_G1_OUTPUT=$(printf '%s\n' "$JAVA_G1_OUTPUT" | grep -v '^XP_G1_REASON: ')
570
+ fi
571
+ [ -n "$JAVA_G1_OUTPUT" ] && echo "$JAVA_G1_OUTPUT" | head -40
572
+ case "$JAVA_G1_EXIT" in
573
+ 0)
574
+ echo "✅ PASSED - Java code quality (wc-java-lint)."
575
+ ;;
576
+ 1)
577
+ echo "❌ BLOCKED - Java static analysis violations (fix or add suppressions)"
578
+ return 1
579
+ ;;
580
+ 2)
581
+ echo "❌ BLOCKED - wc-java-lint unusable (fail-closed; unset XP_GATE_WC_JAVA_LINT=soft only if you accept the risk)"
582
+ return 1
583
+ ;;
584
+ 3)
585
+ echo "⚠️ WARN - Java code quality NOT verified (engine unavailable or downgraded)"
586
+ GATE_1_STATUS="WARN"
587
+ GATE_1_DETAIL="java: ${JAVA_G1_REASON:-unavailable (warn)}"
588
+ ;;
589
+ *)
590
+ echo "⚠️ WARN - Java code quality NOT verified (unexpected verdict $JAVA_G1_EXIT)"
591
+ GATE_1_STATUS="WARN"
592
+ GATE_1_DETAIL="java: unexpected verdict $JAVA_G1_EXIT"
593
+ ;;
594
+ esac
595
+ fi
596
+ ;;
597
+
598
+ powershell)
599
+ # #547 finding 2: PowerShell had no arm here, so it fell into the generic
600
+ # `*)` branch, where a non-zero analysis verdict printed a non-blocking
601
+ # line and GATE_1_STATUS stayed PASS. The java arm's XP_G1_REASON
602
+ # protocol applies verbatim: 0 = pass, 1 = block, 2 = unusable
603
+ # (fail-closed), 3 = WARN with a reason that STAYS in the scoring
604
+ # denominator so a skip is visible in retro instead of vanishing.
605
+ POWERSHELL_ADAPTER=$(resolve_adapter_path "powershell")
606
+ if [ -z "$POWERSHELL_ADAPTER" ]; then
607
+ echo "⚠️ WARN - PowerShell adapter not found (code quality NOT verified)"
608
+ GATE_1_STATUS="WARN"
609
+ GATE_1_DETAIL="powershell: adapter missing"
610
+ else
611
+ PS_G1_EXIT=0
612
+ # Subshell: reasons cross as `XP_G1_REASON: ...` stdout lines, exactly
613
+ # as in the java arm — an export inside the adapter cannot reach us.
614
+ PS_G1_OUTPUT=$(source "$POWERSHELL_ADAPTER" 2>/dev/null; run_static_analysis 2>&1) || PS_G1_EXIT=$?
615
+ PS_G1_REASON=$(printf '%s\n' "$PS_G1_OUTPUT" | sed -n 's/^XP_G1_REASON: //p' | head -1)
616
+ if [ -n "$PS_G1_REASON" ]; then
617
+ PS_G1_OUTPUT=$(printf '%s\n' "$PS_G1_OUTPUT" | grep -v '^XP_G1_REASON: ')
618
+ fi
619
+ [ -n "$PS_G1_OUTPUT" ] && printf '%s\n' "$PS_G1_OUTPUT" | head -40
620
+ case "$PS_G1_EXIT" in
621
+ 0)
622
+ echo "✅ PASSED - PowerShell code quality (PSScriptAnalyzer)."
623
+ ;;
624
+ 1)
625
+ echo "❌ BLOCKED - PSScriptAnalyzer violations (fix or add suppressions)"
626
+ GATE_1_STATUS="BLOCK"
627
+ GATE_1_DETAIL="powershell: PSScriptAnalyzer findings"
628
+ return 1
629
+ ;;
630
+ 2)
631
+ echo "❌ BLOCKED - PowerShell static analysis unusable (fail-closed): ${PS_G1_REASON:-unknown}"
632
+ GATE_1_STATUS="BLOCK"
633
+ GATE_1_DETAIL="powershell: ${PS_G1_REASON:-unusable}"
634
+ return 1
635
+ ;;
636
+ 3)
637
+ echo "⚠️ WARN - PowerShell code quality NOT verified: ${PS_G1_REASON:-engine unavailable}"
638
+ GATE_1_STATUS="WARN"
639
+ GATE_1_DETAIL="powershell: ${PS_G1_REASON:-engine unavailable}"
640
+ ;;
641
+ *)
642
+ echo "⚠️ WARN - PowerShell code quality NOT verified (unexpected verdict $PS_G1_EXIT)"
643
+ GATE_1_STATUS="WARN"
644
+ GATE_1_DETAIL="powershell: unexpected verdict $PS_G1_EXIT"
645
+ ;;
646
+ esac
647
+ fi
648
+ ;;
649
+
650
+ *)
651
+ # Route to appropriate adapter for other languages.
652
+ #
653
+ # #776: this arm used to PRINT findings and then leave GATE_1_STATUS
654
+ # untouched. An adapter returning 1 -- "I ran and found violations" -- got
655
+ # one cosmetic "may be non-blocking" line, then `⏭️ SKIPPED ... (tools
656
+ # unavailable or failed)`, and the gate ended PASS. Every language without
657
+ # its own arm above (C#, C/C++, Objective-C, Swift, Kotlin, Go, Python,
658
+ # Dart, Flutter) was therefore fail-open, and the java/powershell arms' one
659
+ # hard-won verdict protocol (#507 S1, #547, #717) was reachable by exactly
660
+ # two languages.
661
+ #
662
+ # Why that matters for adoption, measured in a real project: a net8.0
663
+ # project with TreatWarningsAsErrors=true + WarningLevel=9999 whose
664
+ # `dotnet format --verify-no-changes` FAILED produced the three lines above
665
+ # and a PASS. The project's own build.sh hard-failed on the identical tree,
666
+ # so the gate was strictly weaker than the compiler it was meant to
667
+ # institutionalise -- the exact opposite of the purpose of a shared gate.
668
+ #
669
+ # The protocol now applies here verbatim, per adapter verdict:
670
+ # 0 = PASS 1 = BLOCK (ran, found problems) 2 = BLOCK (could not
671
+ # execute, fail-closed) 3 = WARN (skipped for a stated reason, stays in
672
+ # the scoring denominator so an unmeasured language is visible).
673
+ #
674
+ # Two mechanics are load-bearing and copied together, because either one
675
+ # alone is a defect:
676
+ # - The verdict is captured into a variable, NOT read from `cmd | head`.
677
+ # #706 fixed `$?` becoming head's status; the java arm documents the
678
+ # remaining trap: a long report makes the writer die of SIGPIPE, so the
679
+ # verdict would depend on how much output happened to be produced. The
680
+ # `|| G1R_EXIT=$?` form (not a bare assignment) keeps a non-zero verdict
681
+ # from aborting the host hook under set -e before it is mapped.
682
+ # - Reasons cross the command-substitution subshell as `XP_G1_REASON:`
683
+ # stdout lines, since an `export` in the adapter can never reach this
684
+ # process (#507 Delphi round-1 B-MAJOR-1).
685
+ ADAPTER_FILE=$(resolve_adapter_path "$CURRENT_LANG")
686
+ if [ -n "$ADAPTER_FILE" ] && source "$ADAPTER_FILE" 2>/dev/null; then
687
+ echo "Running static analysis for $CURRENT_LANG..."
688
+ G1A_OUTPUT=""
689
+ G1A_EXIT=0
690
+ G1A_OUTPUT=$(run_static_analysis 2>&1) || G1A_EXIT=$?
691
+ G1A_REASON=$(printf '%s\n' "$G1A_OUTPUT" | sed -n 's/^XP_G1_REASON: //p' | head -1)
692
+ if [ -n "$G1A_REASON" ]; then
693
+ G1A_OUTPUT=$(printf '%s\n' "$G1A_OUTPUT" | grep -v '^XP_G1_REASON: ')
694
+ fi
695
+ [ -n "$G1A_OUTPUT" ] && printf '%s\n' "$G1A_OUTPUT" | head -30
696
+
697
+ echo "Running lint check for $CURRENT_LANG..."
698
+ G1L_OUTPUT=""
699
+ G1L_EXIT=0
700
+ G1L_OUTPUT=$(run_lint 2>&1) || G1L_EXIT=$?
701
+ [ -n "$G1L_OUTPUT" ] && printf '%s\n' "$G1L_OUTPUT" | head -30
702
+
703
+ # The stricter of the two verdicts wins. Note 3 (WARN) must not mask a 1
704
+ # or 2 from the other command: a clean formatter plus a failing analyzer
705
+ # is still a failing source tree.
706
+ case "${G1L_EXIT}" in
707
+ 1|2) G1_VERDICT="$G1L_EXIT" ;;
708
+ *) G1_VERDICT="$G1A_EXIT" ;;
709
+ esac
710
+
711
+ case "$G1_VERDICT" in
712
+ 0)
713
+ echo "✅ PASSED - Language-specific code quality checks."
714
+ ;;
715
+ 1)
716
+ echo "❌ BLOCKED - ${CURRENT_LANG} code quality violations (fix or add suppressions)"
717
+ GATE_1_STATUS="BLOCK"
718
+ GATE_1_DETAIL="${CURRENT_LANG}: analyzer findings"
719
+ return 1
720
+ ;;
721
+ 2)
722
+ # The substring "(… could not execute — NOT a pass)" is kept from the
723
+ # #717 wording: issue-717-mirror-parity.test.bats asserts that exact
724
+ # text in the npm mirror. An earlier draft of this rewrite dropped it
725
+ # and turned a green main red — the contract is the string, not the
726
+ # author's preference for how to phrase it.
727
+ echo "❌ BLOCKED - ${CURRENT_LANG} toolchain could not execute — NOT a pass (fail-closed): ${G1A_REASON:-unknown}"
728
+ echo " A tool that could not run is not a clean tree. Install the toolchain,"
729
+ echo " or set the adapter's documented escape valve if you accept the risk."
730
+ GATE_1_STATUS="BLOCK"
731
+ GATE_1_DETAIL="${CURRENT_LANG}: ${G1A_REASON:-unusable}"
732
+ return 1
733
+ ;;
734
+ 3)
735
+ echo "⚠️ WARN - ${CURRENT_LANG} code quality NOT verified: ${G1A_REASON:-adapter reported a non-blocking skip}"
736
+ GATE_1_STATUS="WARN"
737
+ GATE_1_DETAIL="${CURRENT_LANG}: ${G1A_REASON:-unavailable (warn)}"
738
+ ;;
739
+ *)
740
+ echo "⚠️ WARN - ${CURRENT_LANG} code quality NOT verified (unexpected verdict $G1_VERDICT)"
741
+ GATE_1_STATUS="WARN"
742
+ GATE_1_DETAIL="${CURRENT_LANG}: unexpected verdict $G1_VERDICT"
743
+ ;;
744
+ esac
745
+ else
746
+ # If no adapter exists for this language, skip
747
+ echo "ℹ️ No specific adapter for $CURRENT_LANG — using generic checks if any"
748
+ echo "⏭️ SKIPPED - Code quality (no specific checks for $CURRENT_LANG)"
749
+ fi
750
+ ;;
751
+ esac
752
+ done
753
+ fi
754
+ fi # End: if ! any_changed_files_match (Issue #312 skip)
755
+ GATE_1_STATUS="${GATE_1_STATUS:-SKIP}"
756
+ GATE_1_TOOL="${PROJECT_LANGS}"
757
+ # The java branch may set GATE_1_STATUS=WARN + a GATE_1_DETAIL warn reason
758
+ # (engine unavailable / soft or report downgrade); route it into the audit
759
+ # trail via the S2 detail plumbing so a WARN verdict is diagnosable, not
760
+ # silent. WARN stays IN the scoring denominator (Delphi round-2 A-MAJOR-1).
761
+ record_gate_audit "gate-1" "code-quality" "$GATE_1_STATUS" "0" "$GATE_1_START" "${GATE_1_DETAIL:-}"
762
+ return 0
763
+ }
764
+
765
+
766
+ # Called by pre-commit's ordered driver.
767
+