opción

gateguard

affaan-m/ECC affaan-m/ECC

Obliga a los agentes de IA a investigar antes de editar o ejecutar comandos destructivos, lo que mejora la calidad del código al exigir datos concretos, como importadores, esquemas de datos e instrucciones de los usuarios.

...Expandir todo
0
Tiempo actualizado 1 de octubre de 2026

GateGuard — Filtro previo a la acción que exige datos concretos

Un gancho de PreToolUse que obliga a Claude a investigar antes de editar. En lugar de una autoevaluación («¿estás seguro?»), exige hechos concretos. El acto de investigar genera una toma de conciencia que la autoevaluación nunca logró.

Cuándo activarlo

  • Al trabajar en cualquier código fuente en el que las modificaciones de los archivos afecten a varios módulos
  • Proyectos con archivos de datos que tienen esquemas o formatos de fecha específicos
  • Equipos en los que el código generado por IA debe ajustarse a patrones existentes
  • Cualquier flujo de trabajo en el que Claude tiende a adivinar en lugar de investigar

Concepto fundamental

La autoevaluación de los modelos de lenguaje grande (LLM) no funciona. Si se pregunta «¿has infringido alguna política?», la respuesta es siempre «no». Esto se ha comprobado experimentalmente.

Pero preguntar «enumera todos los archivos que importan este módulo» obliga al LLM a ejecutar Grep y Read. La propia investigación crea un contexto que modifica el resultado.

Barrera de tres etapas:

1. DENY  — block the first Edit/Write/Bash attempt
2. FORCE — tell the model exactly which facts to gather
3. ALLOW — permit retry after facts are presented

Ningún competidor cumple las tres. La mayoría se queda en la negación.

Pruebas

Dos pruebas A/B independientes, agentes idénticos, misma tarea:

Tarea Con filtro Sin restricción Brecha
Módulo de análisis 8,0/10 6,5/10 +1,5
Validador de webhooks 10,0/10 7,0/10 +3,0
Media 9,0 6,75 +2,25

Ambos agentes generan código que se ejecuta y supera las pruebas. La diferencia radica en la profundidad del diseño.

Tipos de compuertas

Compuerta de edición / MultiEdit (primera edición por archivo)

La puerta «MultiEdit» se gestiona de forma idéntica: cada archivo del lote se somete a la puerta de forma individual.

Before editing {file_path}, present these facts:

1. List ALL files that import/require this file (use Grep)
2. List the public functions/classes affected by this change
3. If this file reads/writes data files, show field names, structure,
   and date format (use redacted or synthetic values, not raw production data)
4. Quote the user's current instruction verbatim

Compuerta de escritura (primera creación de un nuevo archivo)

Before creating {file_path}, present these facts:

1. Name the file(s) and line(s) that will call this new file
2. Confirm no existing file serves the same purpose (use Glob)
3. If this file reads/writes data files, show field names, structure,
   and date format (use redacted or synthetic values, not raw production data)
4. Quote the user's current instruction verbatim

Puerta de Bash destructiva (cada comando destructivo)

Se activa en: rm -rf, git reset --hard, git push --force, drop table, etc.

1. List all files/data this command will modify or delete
2. Write a one-line rollback procedure
3. Quote the user's current instruction verbatim

Puerta de Bash de rutina (una vez por sesión)

1. The current user request in one sentence
2. What this specific command verifies or produces

Inicio rápido

Opción A: Utiliza el hook ECC (sin instalación)

El hook que se encuentra en scripts/hooks/gateguard-fact-force.js está incluido en este complemento. Actívalo a través de hooks.json.

Si GateGuard bloquea las tareas de configuración o reparación, inicia la sesión con ECC_GATEGUARD=off. Para controlar a nivel de gancho, sigue utilizando ECC_DISABLED_HOOKS con el ID del gancho «GateGuard».

En sesiones largas, solo las primeras GATEGUARD_FACT_FORCE_FULL_DENIALS denegaciones de «fact-force» (por defecto, 3) emiten el bloque completo de cuatro hechos; las denegaciones posteriores se condensan en una sola línea que contiene el número ordinal de la denegación, de modo que los bloques casi idénticos no puedan acumularse en la ventana de contexto y amplificar los bucles de repetición del modelo (#2142). Volver a intentar el mismo archivo o comando tras presentar hechos nunca vuelve a activar la puerta.

Opción B: Paquete completo con configuración

pip install gateguard-ai
gateguard init

Esto añade .gateguard.yml para la configuración por proyecto (mensajes personalizados, rutas que se deben ignorar, activación/desactivación de la puerta).

Antipatrones

  • No utilices la autoevaluación en su lugar. A la pregunta «¿Estás seguro?» siempre se responde «sí». Esto está verificado experimentalmente.
  • No te saltes la comprobación del esquema de datos. Ambos agentes de pruebas A/B asumieron fechas según la norma ISO-8601 cuando se utilizaron datos reales %Y/%m/%d %H:%M. Comprobar la estructura de los datos (con valores ocultos) evita toda esta clase de errores.
  • No controles cada comando de Bash individualmente. Los controles rutinarios de Bash se realizan una vez por sesión. Los controles destructivos de Bash se realizan en cada ocasión. Este equilibrio evita la ralentización al tiempo que detecta riesgos reales.

Buenas prácticas

  • Deja que el filtro se active de forma natural. No intentes responder por adelantado a las preguntas del filtro: la propia investigación es lo que mejora la calidad.
  • Personaliza los mensajes de los controles según tu ámbito. Si tu proyecto tiene convenciones específicas, añádelas a las indicaciones de los controles.
  • Utiliza .gateguard.yml para ignorar rutas como .venv/, node_modules/, .git/.

Habilidades relacionadas

  • safety-guard — Comprobaciones de seguridad en tiempo de ejecución (complementarias, sin solapamientos)
  • code-reviewer — Revisión posterior a la edición (la «GateGuard» es una investigación previa a la edición)
Ver en GitHub
---
name: gateguard
description: Forces AI agents to investigate before editing or running destructive commands, improving code quality by requiring concrete facts like importers, data schemas, and user instructions.
---

# GateGuard — Fact-Forcing Pre-Action Gate

A PreToolUse hook that forces Claude to investigate before editing. Instead of self-evaluation ("are you sure?"), it demands concrete facts. The act of investigation creates awareness that self-evaluation never did.

## When to Activate

- Working on any codebase where file edits affect multiple modules
- Projects with data files that have specific schemas or date formats
- Teams where AI-generated code must match existing patterns
- Any workflow where Claude tends to guess instead of investigating

## Core Concept

LLM self-evaluation doesn't work. Ask "did you violate any policies?" and the answer is always "no." This is verified experimentally.

But asking "list every file that imports this module" forces the LLM to run Grep and Read. The investigation itself creates context that changes the output.

**Three-stage gate:**

```
1. DENY  — block the first Edit/Write/Bash attempt
2. FORCE — tell the model exactly which facts to gather
3. ALLOW — permit retry after facts are presented
```

No competitor does all three. Most stop at deny.

## Evidence

Two independent A/B tests, identical agents, same task:

| Task | Gated | Ungated | Gap |
| --- | --- | --- | --- |
| Analytics module | 8.0/10 | 6.5/10 | +1.5 |
| Webhook validator | 10.0/10 | 7.0/10 | +3.0 |
| **Average** | **9.0** | **6.75** | **+2.25** |

Both agents produce code that runs and passes tests. The difference is design depth.

## Gate Types

### Edit / MultiEdit Gate (first edit per file)

MultiEdit is handled identically — each file in the batch is gated individually.

```
Before editing {file_path}, present these facts:

1. List ALL files that import/require this file (use Grep)
2. List the public functions/classes affected by this change
3. If this file reads/writes data files, show field names, structure,
   and date format (use redacted or synthetic values, not raw production data)
4. Quote the user's current instruction verbatim
```

### Write Gate (first new file creation)

```
Before creating {file_path}, present these facts:

1. Name the file(s) and line(s) that will call this new file
2. Confirm no existing file serves the same purpose (use Glob)
3. If this file reads/writes data files, show field names, structure,
   and date format (use redacted or synthetic values, not raw production data)
4. Quote the user's current instruction verbatim
```

### Destructive Bash Gate (every destructive command)

Triggers on: `rm -rf`, `git reset --hard`, `git push --force`, `drop table`, etc.

```
1. List all files/data this command will modify or delete
2. Write a one-line rollback procedure
3. Quote the user's current instruction verbatim
```

### Routine Bash Gate (once per session)

```
1. The current user request in one sentence
2. What this specific command verifies or produces
```

## Quick Start

### Option A: Use the ECC hook (zero install)

The hook at `scripts/hooks/gateguard-fact-force.js` is included in this plugin. Enable it via hooks.json.

If GateGuard blocks setup or repair work, start the session with
`ECC_GATEGUARD=off`. For hook-level control, keep using
`ECC_DISABLED_HOOKS` with the GateGuard hook ID.

In long sessions, only the first `GATEGUARD_FACT_FORCE_FULL_DENIALS`
fact-force denials (default 3) emit the full four-fact block; later
denials are condensed to a single line carrying the denial ordinal, so
near-identical blocks cannot accumulate in the context window and
amplify model repetition loops (#2142). Retrying the same file or
command after presenting facts never re-triggers the gate.

### Option B: Full package with config

```bash
pip install gateguard-ai
gateguard init
```

This adds `.gateguard.yml` for per-project configuration (custom messages, ignore paths, gate toggles).

## Anti-Patterns

- **Don't use self-evaluation instead.** "Are you sure?" always gets "yes." This is experimentally verified.
- **Don't skip the data schema check.** Both A/B test agents assumed ISO-8601 dates when real data used `%Y/%m/%d %H:%M`. Checking data structure (with redacted values) prevents this entire class of bugs.
- **Don't gate every single Bash command.** Routine bash gates once per session. Destructive bash gates every time. This balance avoids slowdown while catching real risks.

## Best Practices

- Let the gate fire naturally. Don't try to pre-answer the gate questions — the investigation itself is what improves quality.
- Customize gate messages for your domain. If your project has specific conventions, add them to the gate prompts.
- Use `.gateguard.yml` to ignore paths like `.venv/`, `node_modules/`, `.git/`.

## Related Skills

- `safety-guard` — Runtime safety checks (complementary, not overlapping)
- `code-reviewer` — Post-edit review (GateGuard is pre-edit investigation)

Todos los archivos

1 archivos

Instalar gateguard

Descarga y descomprime los archivos de habilidades en tu directorio .claude/skills/.

Descargar ZIP

Clona el repositorio y copia los archivos de la habilidad a tu proyecto.

git clone https://github.com/affaan-m/ECC/tree/main/skills/gateguard # Copy SKILL.md to your .claude/skills/ directory

Copiar Copiar
Configuración rápida: Copia la carpeta de la habilidad en .claude/skills/ Claude detectará y utilizará automáticamente la habilidad
Repositorio affaan-m/ECC

Habilidades relacionadas

algorithmic-art
Tiempo actualizado 27 de agosto de 2026
systematic-debugging
Tiempo actualizado 3 de septiembre de 2026
tech-debt-tracker
Tiempo actualizado 29 de agosto de 2026
continual-learning
Tiempo actualizado 10 de septiembre de 2026
OR