hookPreToolUse[Bash]configurable
antipattern-guard
Detectar anti-patrones .NET en archivos staged
Qué comprueba
La cabecera del fichero no describe el comportamiento (la higiene de fuentes lo señala).
Códigos de salida
| Exit | Significado |
|---|---|
1 | AVISO informativo (no bloquea commit) |
0 | sin hallazgos |
Política
WARN-first: avisa (exit 1) por defecto y bloquea (exit 2) solo si la organización lo pone en hooks.blockList o sube hooks.policy a block.
| Clave | Tipo | Default | Qué hace |
|---|---|---|---|
hooks.policy | string | "warn" | WARN-first por defecto (avisan sin bloquear); 'block' eleva todos los hooks defensivos a bloqueo. Los hooks intrinsecamente BLOCK (bash-guard, protect-files certs/keys, hilo-json-guard) no se degradan nunca. |
hooks.blockList | array | [] | Hooks concretos elevados a BLOCK aunque policy=warn (ej. ['secret-scanner']). |
Código fuente
antipattern-guard.js · 151 líneas
// antipattern-guard.js - Detectar anti-patrones .NET en archivos staged
// Evento: PreToolUse[Bash] (cuando el comando es git commit)
// Exit 1 = AVISO informativo (no bloquea commit), Exit 0 = sin hallazgos.
// Historial del original (condensado):
// v2.0.0: politica WARN-first — todos los ERROR pasan a AVISO/exit 1; mensajes via
// stderr (Write-Host no surfaceaba en Claude Code); escanea contenido COMPLETO de staged, no solo diff.
// v1.0.1: GIT_OPTIONAL_LOCKS=0 (colisiones index.lock con IDE). v1.0.0: 7 antipatrones .NET.
// Detecta: DateTime.Now, new HttpClient(), async void, .Result, sync-over-async,
// catch generico, string interpolation en logs, connection strings hardcoded.
//
// Politica: WARN-first configurable — resolvePolicy(cfg, 'antipattern-guard');
// exit 2 (prefijo BLOQUEADO) solo si hooks.policy='block' o hooks.blockList lo incluye.
'use strict';
const fs = require('fs');
const h = require('./lib/helpers');
const config = require('./lib/config');
try {
const hookData = h.readHookInput();
const command = h.getToolInput(hookData);
if (!command) process.exit(0);
// Solo actuar cuando el comando es git commit
if (!/git\s+commit/i.test(command)) process.exit(0);
// Obtener archivos .cs en staging (GIT_OPTIONAL_LOCKS=0 via gitReadOnly: sin lock,
// no colisiona con VS Code/IDE)
const diff = h.gitReadOnly(['diff', '--cached', '--name-only', '--diff-filter=ACM']);
if (diff.exitCode !== 0) process.exit(0);
const stagedFiles = diff.stdOut.split(/\r?\n/).filter(Boolean).filter((f) => /\.cs$/i.test(f));
if (stagedFiles.length === 0) process.exit(0);
const mode = config.resolvePolicy(config.load(), 'antipattern-guard'); // WARN-first (default 'warn')
const prefijo = mode === 'block' ? 'BLOQUEADO' : 'AVISO';
// Helper: emitir aviso por stderr (visible para Claude Code)
const aviso = (msg) => console.error(msg);
aviso(h.txt(`Verificando ${stagedFiles.length} archivo(s) C# en staging...`,
`Checking ${stagedFiles.length} staged C# file(s)...`));
let warnings = 0;
for (const file of stagedFiles) {
if (!fs.existsSync(file)) continue;
let content = null;
try {
content = fs.readFileSync(file, 'utf8');
} catch {
continue;
}
if (!content) continue;
const lines = content.split(/\r?\n/);
let lineNum = 0;
for (const line of lines) {
lineNum++;
// AP001: async void (excepto event handlers)
if (/async\s+void/i.test(line) && !/EventArgs/i.test(line)) {
aviso(h.txt(`${prefijo} ${file}:${lineNum} - async void detectado. Recomendado: async Task.`,
`${prefijo} ${file}:${lineNum} - async void found. Prefer async Task.`));
warnings++;
}
// AP002: .Result o .GetAwaiter().GetResult() (sync-over-async)
if (/\.Result\b/i.test(line) || /\.GetAwaiter\(\)\.GetResult\(\)/i.test(line)) {
aviso(h.txt(`${prefijo} ${file}:${lineNum} - sync-over-async (.Result / .GetAwaiter().GetResult())`,
`${prefijo} ${file}:${lineNum} - sync-over-async (.Result / .GetAwaiter().GetResult())`));
warnings++;
}
// AP003: new HttpClient() (socket exhaustion)
if (/new\s+HttpClient\s*\(/i.test(line)) {
aviso(h.txt(`${prefijo} ${file}:${lineNum} - new HttpClient(). Recomendado: IHttpClientFactory.`,
`${prefijo} ${file}:${lineNum} - new HttpClient(). Prefer IHttpClientFactory.`));
warnings++;
}
// AP004: DateTime.Now / DateTime.UtcNow (untestable)
if (/DateTime\.(Now|UtcNow)/i.test(line)) {
aviso(h.txt(`${prefijo} ${file}:${lineNum} - DateTime.Now/UtcNow. Recomendado: TimeProvider.`,
`${prefijo} ${file}:${lineNum} - DateTime.Now/UtcNow. Prefer TimeProvider.`));
warnings++;
}
// AP005: catch(Exception) broad catch
if (/catch\s*\(\s*Exception\s*\)/i.test(line) || /catch\s*\(\s*Exception\s+\w+\s*\)/i.test(line)) {
aviso(h.txt(`${prefijo} ${file}:${lineNum} - catch(Exception) generico. Recomendado: capturar excepciones especificas.`,
`${prefijo} ${file}:${lineNum} - generic catch(Exception). Prefer catching specific exceptions.`));
warnings++;
}
// AP006: String interpolation en logging
if (/Log(Information|Warning|Error|Debug|Critical)\s*\(\s*\$"/i.test(line)) {
aviso(h.txt(`${prefijo} ${file}:${lineNum} - Interpolacion en log. Recomendado: template "Msg {Param}", value`,
`${prefijo} ${file}:${lineNum} - interpolation in a log call. Prefer a template: "Msg {Param}", value`));
warnings++;
}
// AP007 (ADR-024): captura de datos sensibles en telemetria/logging sin guarda de entorno
if (/(SetDbStatementForText|SetDbStatementForStoredProcedure|EnableSensitiveDataLogging)\s*=?\s*\(?\s*true/i.test(line)) {
aviso(h.txt(`${prefijo} ${file}:${lineNum} - ${line.trim().slice(0, 60)} captura SQL o datos sensibles siempre. Recomendado: builder.Environment.IsDevelopment().`,
`${prefijo} ${file}:${lineNum} - ${line.trim().slice(0, 60)} always captures SQL or sensitive data. Guard it with builder.Environment.IsDevelopment().`));
warnings++;
}
// COMILLAS: Connection string hardcoded
if (/(Server|Data Source|Initial Catalog|Password)\s*=/i.test(line) &&
!/(appsettings|configuration|IOptions|GetConnectionString)/i.test(line)) {
if (/"[^"]*Server\s*=/i.test(line)) {
aviso(h.txt(`${prefijo} ${file}:${lineNum} - Connection string hardcoded. Recomendado: appsettings + Key Vault.`,
`${prefijo} ${file}:${lineNum} - hardcoded connection string. Prefer appsettings plus a secrets vault.`));
warnings++;
}
}
}
}
if (warnings > 0) {
aviso('');
aviso(h.txt(`Se encontraron ${warnings} posible(s) antipatron(es) en archivos staged. Politica de la organización:`,
`Found ${warnings} possible anti-pattern(s) in staged files. Organization policy:`));
aviso(h.txt(' - Entorno seguro y deuda tecnica progresiva - NO bloqueante actualmente',
' - Safe environment, technical debt paid down over time - NOT blocking today'));
aviso(h.txt(' - El hook escanea contenido completo del archivo, no solo el diff.',
' - The hook scans the whole file, not just the diff.'));
aviso(h.txt(' Un refactor sobre archivo con .Result/DateTime.Now/etc legacy lo dispara.',
' Refactoring a file with legacy .Result/DateTime.Now/... will trigger it.'));
aviso(h.txt(' - Si el antipatron es NUEVO (introducido por este commit): corregirlo.',
' - If the anti-pattern is NEW (introduced by this commit): fix it.'));
aviso(h.txt(' - Si es legacy preexistente: documentar en _hilo/DEUDA_TECNICA.md como DT-XXX.',
' - If it is pre-existing legacy: record it in _hilo/DEUDA_TECNICA.md as DT-XXX.'));
aviso(h.txt(' - Si el equipo de infraestructura decide enforcement: el hook pasa a exit 2',
' - If the infrastructure team decides to enforce it: the hook becomes exit 2'));
process.exit(mode === 'block' ? 2 : 1); // exit 1 = AVISO informativo, patron WARN-first
}
aviso(h.txt('OK: Verificacion de anti-patrones completada (0 hallazgos).',
'OK: anti-pattern check complete (0 findings).'));
process.exit(0);
} catch (e) {
// Error inesperado: permitir operacion en lugar de romper el flujo.
console.error(h.txt(`antipattern-guard.js: error inesperado, permitiendo operacion. Detalle: ${e && e.message ? e.message : e}`,
`antipattern-guard.js: unexpected error, allowing the operation. Detail: ${e && e.message ? e.message : e}`));
process.exit(0);
}
Historial
6 cambios · 2026-09-07 → 2026-09-22. Último cambio: fix(higiene): lo que nadie mira no esta bien (ADR-076).
Notas de versiones anteriores
- v2.0.0: politica WARN-first — todos los ERROR pasan a AVISO/exit 1; mensajes via
- stderr (Write-Host no surfaceaba en Claude Code); escanea contenido COMPLETO de staged, no solo diff.
- v1.0.1: GIT_OPTIONAL_LOCKS=0 (colisiones index.lock con IDE). v1.0.0: 7 antipatrones .NET.
- Detecta: DateTime.Now, new HttpClient(), async void, .Result, sync-over-async,
- catch generico, string interpolation en logs, connection strings hardcoded.
- Politica: WARN-first configurable — resolvePolicy(cfg, 'antipattern-guard');
- exit 2 (prefijo BLOQUEADO) solo si hooks.policy='block' o hooks.blockList lo incluye.