opção

gateguard

affaan-m/ECC affaan-m/ECC

Obriga os agentes de IA a investigar antes de editar ou executar comandos destrutivos, melhorando a qualidade do código ao exigir fatos concretos, como importadores, esquemas de dados e instruções do usuário.

...Expandir tudo
0
Tempo atualizado 1 de Outubro de 2026

GateGuard — Etapa pré-ação de verificação de fatos

Um gancho do PreToolUse que obriga Claude a investigar antes de editar. Em vez de uma autoavaliação (“tem certeza?”), ele exige fatos concretos. O ato de investigar gera uma consciência que a autoavaliação nunca conseguiu.

Quando ativar

  • Ao trabalhar em qualquer base de código em que as edições de arquivos afetem vários módulos
  • Projetos com arquivos de dados que possuem esquemas ou formatos de data específicos
  • Equipes nas quais o código gerado por IA deve corresponder a padrões existentes
  • Qualquer fluxo de trabalho em que o Claude tende a adivinhar em vez de investigar

Conceito central

A autoavaliação do LLM não funciona. Pergunte “você violou alguma política?” e a resposta será sempre “não”. Isso foi comprovado experimentalmente.

Mas perguntar “liste todos os arquivos que importam este módulo” força o LLM a executar o Grep e o Read. A própria investigação cria um contexto que altera o resultado.

Porta de três estágios:

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

Nenhum concorrente faz todas as três etapas. A maioria para na negação.

Evidências

Dois testes A/B independentes, agentes idênticos, mesma tarefa:

Tarefa Com etapas Sem restrição Lacuna
Módulo de análise 8,0/10 6,5/10 +1,5
Validador de webhooks 10,0/10 7,0/10 +3,0
Média 9,0 6,75 +2,25

Ambos os agentes produzem código que é executado e é aprovado nos testes. A diferença está na profundidade do projeto.

Tipos de gate

Porta de edição / MultiEdit (primeira edição por arquivo)

A MultiEdit é tratada da mesma forma — cada arquivo no lote é submetido à verificação individualmente.

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

Porta de gravação (primeira criação de novo arquivo)

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

Porta de Bash destrutiva (a cada comando destrutivo)

Acionado por: 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

Porta de rotina do Bash (uma vez por sessão)

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

Início rápido

Opção A: Use o gancho ECC (sem instalação)

O hook em scripts/hooks/gateguard-fact-force.js está incluído neste plug-in. Ative-o por meio do arquivo hooks.json.

Se o `GateGuard` bloquear a configuração ou o reparo, inicie a sessão com ECC_GATEGUARD=off. Para controle no nível do hook, continue usando ECC_DISABLED_HOOKS com o ID do gancho GateGuard.

Em sessões longas, apenas as primeiras GATEGUARD_FACT_FORCE_FULL_DENIALS recusas de “fact-force” (padrão: 3) emitem o bloco completo de quatro fatos; as recusas posteriores são condensadas em uma única linha contendo o número ordinal da recusa, para que blocos quase idênticos não se acumulem na janela de contexto e ampliem os loops de repetição do modelo (#2142). Tentar novamente o mesmo arquivo ou comando após a apresentação dos fatos nunca reativa o gate.

Opção B: Pacote completo com configuração

pip install gateguard-ai
gateguard init

Isso adiciona .gateguard.yml para configuração por projeto (mensagens personalizadas, caminhos a serem ignorados, ativação/desativação de gate).

Antipadrões

  • Não use a autoavaliação como alternativa. “Tem certeza?” sempre recebe “sim”. Isso foi comprovado experimentalmente.
  • Não pule a verificação do esquema de dados. Ambos os agentes de teste A/B presumiram datas no formato ISO-8601 quando os dados reais usados %Y/%m/%d %H:%M. Verificar a estrutura dos dados (com valores ocultos) evita toda essa classe de bugs.
  • Não aplique gate a cada comando Bash. Gates de rotina no Bash ocorrem uma vez por sessão. Gates destrutivos no Bash ocorrem sempre. Esse equilíbrio evita lentidão ao mesmo tempo em que detecta riscos reais.

Melhores práticas

  • Deixe a verificação ser acionada naturalmente. Não tente responder antecipadamente às perguntas da verificação — é a própria investigação que melhora a qualidade.
  • Personalize as mensagens do gate para o seu domínio. Se o seu projeto tiver convenções específicas, adicione-as aos prompts do gate.
  • Use .gateguard.yml para ignorar caminhos como .venv/, node_modules/, .git/.

Habilidades relacionadas

  • safety-guard — Verificações de segurança em tempo de execução (complementares, sem sobreposição)
  • code-reviewer — Revisão pós-edição (a investigação pré-edição é feita por GateGuard)
Ver no 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 os arquivos

1 arquivos

Instalar gateguard

Baixe e descompacte os arquivos de habilidades no diretório .claude/skills/.

Baixar ZIP

Clone o repositório e copie os arquivos da habilidade para o seu projeto.

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

Copiar Copiar
Configuração rápida: Copie a pasta da habilidade para .claude/skills/ O Claude detectará e utilizará automaticamente a habilidade
Repositório affaan-m/ECC

Habilidades relacionadas

algorithmic-art
Tempo atualizado 27 de Agosto de 2026
systematic-debugging
Tempo atualizado 3 de Setembro de 2026
tech-debt-tracker
Tempo atualizado 29 de Agosto de 2026
continual-learning
Tempo atualizado 10 de Setembro de 2026
OR