вариант

gateguard

affaan-m/ECC affaan-m/ECC

Обязывает агенты искусственного интеллекта проводить предварительное исследование перед редактированием или выполнением команд, которые могут привести к сбоям, что позволяет повысить качество кода за счет требования предоставлять конкретные сведения, такие как импортеры, схемы данных и инструкции пользователя.

...Расширить все
0
Обновлено время 1 октября 2026 г.

GateGuard — Контрольный этап перед действием, основанный на фактах

Хук PreToolUse, который заставляет Клода проводить расследование перед редактированием. Вместо самооценки («вы уверены?») он требует конкретных фактов. Сам процесс расследования формирует осознанность, которой самооценка никогда не могла обеспечить.

Когда активировать

  • При работе с любой кодовой базой, где редактирование файлов затрагивает несколько модулей
  • Проекты с файлами данных, имеющими определённые схемы или форматы даты
  • В командах, где код, сгенерированный ИИ, должен соответствовать существующим шаблонам
  • Любой рабочий процесс, в котором Claude склонен делать предположения вместо того, чтобы проводить проверку

Основная концепция

Самооценка LLM не работает. Спросите: «Нарушил ли ты какие-либо политики?», и ответ всегда будет «нет». Это подтверждено экспериментально.

Но вопрос «перечисли все файлы, которые импортируют этот модуль» заставляет LLM запустить Grep и Read. Само расследование создает контекст, который изменяет результат.

Трехступенчатый фильтр:

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

Ни один из конкурентов не выполняет все три этапа. Большинство останавливаются на этапе «отрицания».

Доказательства

Два независимых A/B-теста, идентичные агенты, одна и та же задача:

Задача С фильтрацией Без ограничений Разрыв
Модуль аналитики 8,0/10 6,5/10 +1,5
Валидатор веб-хуков 10,0/10 7,0/10 +3,0
Среднее 9,0 6,75 +2,25

Оба агента генерируют код, который работает и проходит тесты. Разница заключается в глубине проектирования.

Типы контрольных точек

Ворота «Edit» / «MultiEdit» (первое редактирование в каждом файле)

Обработка MultiEdit происходит аналогично — каждый файл в пакете проходит проверку отдельно.

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

Шлюз записи (создание первого нового файла)

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» (каждая разрушающая команда)

Срабатывает при: rm -rf, git reset --hard, git push --force, drop tableи т. д.

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

Обычное событие Bash (один раз за сеанс)

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

Быстрый старт

Вариант A: Использование хука ECC (без установки)

Хук, расположенный по адресу scripts/hooks/gateguard-fact-force.js входит в состав этого плагина. Включите его через файл hooks.json.

Если GateGuard блокирует работы по настройке или восстановлению, запускайте сессию с параметром ECC_GATEGUARD=off. Для управления на уровне хуков продолжайте использовать ECC_DISABLED_HOOKS с идентификатором хука GateGuard.

В длительных сессиях только первые GATEGUARD_FACT_FORCE_FULL_DENIALS отклонения с принудительным указанием фактов (по умолчанию 3) генерируют полный блок из четырёх фактов; последующие отклонения сжимаются до одной строки с порядковым номером отклонения, чтобы почти идентичные блоки не накапливались в окне контекста и не усиливали циклы повторения модели (#2142). Повторная попытка обработки того же файла или команды после представления фактов никогда не запускает шлюз заново.

Вариант B: Полный пакет с конфигурацией

pip install gateguard-ai
gateguard init

Это добавляет .gateguard.yml для настройки на уровне проекта (пользовательские сообщения, пути для игнорирования, переключение шлюзов).

Антипаттерны

  • Не используйте вместо этого самооценку. На вопрос «Вы уверены?» всегда следует ответ «да». Это подтверждено экспериментально.
  • Не пропускайте проверку схемы данных. Оба агента A/B-тестирования предполагали, что даты соответствуют стандарту ISO-8601, когда использовались реальные данные %Y/%m/%d %H:%M. Проверка структуры данных (с замазанными значениями) позволяет предотвратить весь этот класс ошибок.
  • Не проверяйте каждую отдельную команду Bash. Рутинные проверки Bash выполняются один раз за сеанс. Деструктивные проверки Bash — каждый раз. Такой баланс позволяет избежать замедления работы и при этом выявлять реальные риски.

Лучшие практики

  • Позвольте проверке срабатывать естественным образом. Не пытайтесь заранее ответить на вопросы проверки — именно процесс проверки сам по себе повышает качество.
  • Настройте сообщения проверки с учётом специфики вашей области. Если в вашем проекте существуют особые соглашения, добавьте их в подсказки проверки.
  • Используйте .gateguard.yml для игнорирования путей типа .venv/, node_modules/, .git/.

Связанные навыки

  • safety-guard — Проверки безопасности во время выполнения (дополняющие, не дублирующие друг друга)
  • code-reviewer — Проверка после редактирования (GateGuard — это проверка до редактирования)
Посмотреть на 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)

Все файлы

1 файлов

Установить gateguard

Скачайте файлы навыков и распакуйте их в каталог .claude/skills/.

Скачать ZIP

Клонируйте репозиторий и скопируйте файлы навыка в свой проект.

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

Копировать Копировать
Быстрая настройка: Скопируйте папку со скиллом в каталог .claude/skills/ Claude автоматически обнаружит и запустит этот скилл
Репозиторий affaan-m/ECC

Похожие навыки

algorithmic-art
Обновлено время 27 августа 2026 г.
systematic-debugging
Обновлено время 3 сентября 2026 г.
tech-debt-tracker
Обновлено время 29 августа 2026 г.
continual-learning
Обновлено время 10 сентября 2026 г.
OR