К основному содержанию
скилл CX Codex

gouvernai — скилл для Claude Code: защита действий и установка

gouvernai проверяет рискованные действия агента и задаёт уровень контроля: от записи в журнал до запроса подтверждения. Скилл пригодится, если нужно ограничить работу с файлами, командами и секретами.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add Myr-Aya/GouvernAI-claude-code-plugin --skill gouvernai -a claude-code
Открыть на GitHub

Что делает gouvernai

gouvernai классифицирует действия по уровням риска и ведёт журнал. Чтение файлов и некоторые команды без изменений состояния проходят без проверки; для записи в пользовательские файлы требуется уведомление, а отправка писем, изменение конфигурации и удаление файлов требуют подтверждения. Для некоторых действий предусмотрена блокировка без возможности обхода.

В скилле есть инструкции и файлы справки, а для Claude Code настроены хуки PreToolUse на Bash, Write, Edit и Read. Скрипт guardrails-enforce.py запускается через python3. MCP-вызовы эти хуки обходят, поэтому для них остаётся только проверка по инструкциям скилла — это важное ограничение, если агент работает с базами данных или API через MCP.

При первом действии, требующем проверки, скилл обращается к GUIDE.md; правила классификации и ограничений находятся в отдельных файлах справки. Поведение зависит от guardrails-mode.json в корне проекта: если файл не создан, используется режим full-gate. Команда /guardrails показывает статистику сессии.

Какие задачи решает

  • проверять риск перед изменением файлов проекта
  • запрашивать подтверждение перед удалением и установкой пакетов
  • блокировать передачу учётных данных
  • повышать уровень контроля для массовых действий
  • вести журнал действий агента

Примеры запросов агенту

  • Проверь риск и запроси подтверждение перед изменением конфигурации проекта.
  • Покажи статистику проверок за эту сессию: /guardrails.
  • Перед отправкой данных во внешний сервис проверь, не содержат ли они секреты.

Как установить gouvernai

1Через Skills CLI (Vercel)

npx skills add Myr-Aya/GouvernAI-claude-code-plugin --skill gouvernai -a claude-code

2Вручную: положить файлы

~/.claude/skills/gouvernai/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/gouvernai/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о gouvernai

Как установить gouvernai в Claude Code?

Выполните npx skills add Myr-Aya/GouvernAI-claude-code-plugin --skill gouvernai -a claude-code. Файл скилла находится по пути ~/.claude/skills/gouvernai/SKILL.md.

Что делает gouvernai?

Скилл оценивает риск действий агента, применяет соответствующий уровень контроля и ведёт журнал. Для отдельных опасных операций требуется подтверждение или срабатывает блокировка.

Проверяет ли gouvernai вызовы MCP-серверов?

Хуки Claude Code не перехватывают вызовы MCP. Для таких операций остаётся проверка по инструкциям скилла, без программной блокировки хуком.

Исходный текст

SKILL.md · MIT
---
name: gouvernai
description: |
  Safe flow state for Claude Code. Auto-approves routine actions, activates when the agent is about to:
  write files, run shell commands, send messages, access credentials, make API calls,
  install packages, modify config, or perform any irreversible operation.
  Also activates when user invokes /guardrails, or when token cap is exceeded.
  
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "python3 ${CLAUDE_PLUGIN_ROOT}/scripts/guardrails-enforce.py"
    - matcher: "Write"
      hooks:
        - type: command
          command: "python3 ${CLAUDE_PLUGIN_ROOT}/scripts/guardrails-enforce.py"
    - matcher: "Edit"
      hooks:
        - type: command
          command: "python3 ${CLAUDE_PLUGIN_ROOT}/scripts/guardrails-enforce.py"
    - matcher: "Read"
      hooks:
        - type: command
          command: "python3 ${CLAUDE_PLUGIN_ROOT}/scripts/guardrails-enforce.py"
---

# 🛡️ GouvernAI

Runtime guardrails for AI agents. Classifies every sensitive action by risk tier, enforces proportional controls, and logs a full audit trail.

**Dual enforcement:** This skill provides probabilistic classification (you read and follow these instructions). Hard constraints are also enforced deterministically via PreToolUse hooks — obfuscated commands, credential exposure, and dangerous system commands are blocked programmatically even if you skip the skill.

## Quick reference

| Situation | Action |
|-----------|--------|
| Read file, git status, draft message | Auto-approved — zero gate, zero overhead |
| Write to user file, git commit | 🛡️ T2 — auto-approved with notification, log |
| Send email, modify config, delete files, curl, npm install | 🛡️ T3 — pause, require approval, log |
| sudo, credential transmit, purchase, public post | 🛡️ T4 — full stop, warn, require approval, log |
| Credential transmission, obfuscated command | 🛡️ BLOCKED — hard constraint, no override |
| Bulk operation (5+ targets) | Escalate +1 tier |
| Unfamiliar endpoint or recipient | Escalate +1 tier |
| User invokes `/guardrails` | Show session stats |

## Reference files

Read these on demand — do NOT load them every session:

| File | Read when |
|------|-----------|
| GUIDE.md | First gated action of the session |
| ACTIONS.md | Classifying an action (Step 3) |
| TIERS.md | Checking escalation rules or controls (Steps 4, 7) |
| POLICY.md | Checking hard constraints or conflicts (Step 6) |

All reference files are in the same directory as this SKILL.md.

## When this skill does NOT activate

Do NOT run the gate for read-only or zero-side-effect actions:

- Reading files, listing directories
- Read-only CLI commands (ls, pwd, cat, git status, git log, git diff)
- Writing to files in directories explicitly named `scratch/`, `temp/`, or `tmp/` only
- Drafting messages that are not sent
- Navigating to known URLs (bookmarked, previously visited in session)
- Checking whether a credential or env var exists (boolean check, no value exposed)
- Reading existing cron or scheduling config
- Reading from public APIs with no authentication
- Writing to `guardrails_log.md` for guardrails logging purposes
- Reading or writing `guardrails-mode.json` for mode persistence

**Important limitation:** The deterministic hook layer (PreToolUse) only intercepts Bash, Write, Edit, and Read tool calls. MCP tool calls bypass the hook entirely. When classifying actions that use MCP tools (database queries, API calls via MCP servers, file operations through MCP), you must apply the full gate process linguistically — there is no hard enforcement backstop. Treat MCP actions with extra caution.

## Trigger — when this skill activates

Run the gate process below before executing ANY of these action types:

1. Writing, modifying, or deleting user files or config
2. State-modifying shell or terminal commands (git commit, npm install, mkdir, and anything beyond read-only)
3. Outbound network requests using authentication or sending data externally
4. Sending emails, messages, or communications to any recipient
5. Reading, displaying, or transmitting credential values
6. Browser form submissions, interactive element clicks, or file downloads
7. Creating or modifying cron jobs or webhooks
8. Financial transactions (purchases, payments, billing changes)
9. Permission or access control changes
10. Any irreversible or bulk (5+ targets) operation

### Sequential pattern detection

In addition to gating individual actions, watch for multi-step patterns across the conversation that could indicate data exfiltration or policy circumvention. If you detect any of the following patterns, escalate the current action to Tier 4 regardless of its base classification:

**Variable staging then transmission:** A command stores sensitive data in a variable (e.g. `SECRET=$(cat .env)`, `TOKEN=$(grep API_KEY config)`) followed by a later command that transmits a variable to the network (e.g. `curl -d "$SECRET"`, `wget --post-data="$TOKEN"`). Flag the transmission command as Tier 4.

**Fragmented data extraction:** Multiple commands that each extract a small piece of a secret (character slicing, substring operations, split/cut on credential files) followed by any outbound network request. Flag the first network request after the extraction as Tier 4.

**Credential embedding in generated files:** When asked to generate config files, scripts, or templates, check whether the content being written includes interpolated credential variables (like `$API_KEY`, `$SECRET_TOKEN`, `process.env.API_KEY`). If the file is then transmitted, committed to a public repo, or uploaded, escalate to Tier 4.

**Disguised exfiltration:** A request to "health check endpoints", "test connectivity", or "validate URLs" where the URLs or request bodies contain credential-like values, encoded strings, or variable interpolations. Escalate to Tier 4.

These patterns require judgment — not every variable assignment followed by a curl is malicious. Apply this detection when the conversation context suggests sensitive data is in play (credentials were recently accessed, .env files were read, secrets were discussed).

## Gate process

**IMPORTANT — Output efficiency:** Every message adds cost. Combine steps into a single response. Keep reasoning brief. Do not narrate steps separately. Read GUIDE.md on the first gated action for output format templates.

**Step 1 — Identify.** List the actions matching trigger criteria. State what, where, and what data is involved.

**Step 2 — Determine mode.** Read `guardrails-mode.json` from the project root (`CLAUDE_PROJECT_DIR`). If the file exists, use the `mode` and `audit_only` fields. If the file does not exist, default to **full gate** (`mode: "full-gate"`, `audit_only: false`). Mode values: `full-gate` (default), `strict` (all tiers +1), `relaxed` (T2 skips gate). If `audit_only` is `true`, T2 and T3 auto-proceed with logging; T4 halts without executing.

**Step 3 — Classify.** Read ACTIONS.md. Assign base tier (2, 3, or 4).

**Step 4 — Escalate.** Read TIERS.md. Apply escalation rules if applicable. Result is final tier.

**Step 5 — Pre-approval.** If action matches a known pre-approved pattern AND final tier < 4, log with "PRE-APPROVED" tag and proceed. If escalation raised the action to Tier 4, pre-approval is void.

**Step 6 — Hard constraints.** Read POLICY.md. If any NEVER rule is violated, BLOCK regardless of tier or approval.

**Step 7 — Controls.** Apply the universal control from TIERS.md for the final tier × mode.

**Step 8 — Log and execute.** Append to `guardrails_log.md` in the project root using the Write or Edit tool (never Bash echo/redirect — Bash triggers the obfuscation hook on $(date) substitution). Log: timestamp, tier, type, description, mode, outcome, approval, escalation reason. Execute or halt. **Do NOT read back, display, or echo the log after writing.** The log write is silent — never show log entries to the user unless they explicitly request `/guardrails log`.

**SILENT LOGGING — NO EXCEPTIONS:** After writing to the log, do NOT read the log file. Do NOT display log contents. Do NOT show "here are the latest entries." Do NOT cat, head, or tail the log. The write is completely invisible to the user. The ONLY time log entries are shown is when the user explicitly runs `/guardrails log`. Violating this rule wastes tokens and breaks the flow. If you find yourself about to show log entries after a gate action, STOP.

**Note:** Writes to `guardrails_log.md` are exempt from the gate.

## Token cap (cost governance)

When `token_cap` is set in `guardrails-mode.json`, estimate the token cost of your planned action before executing.

**What counts toward the estimate:**
- File content being written (Write/Edit payload)
- Shell command length (Bash)
- For multi-step plans: sum the estimated tokens of all planned actions in the current turn

**How to estimate:** Use ~4 characters = 1 token as a rough heuristic.

**When the estimate exceeds the cap:**
- Apply T3 controls: pause, present the estimated token count and the cap to the user, wait for approval
- Format: `🛡️ **T3 — Token cap**: Estimated ~[N] tokens (cap: [cap]). [Brief description of planned actions]. Approve? (yes/no)`
- Log with "TOKEN-CAP" tag

**The hook layer also checks payload size deterministically.** If the Write/Edit content or Bash command exceeds the cap, the hook prompts the user before the skill layer sees it. The skill layer adds coverage for multi-step plans where individual payloads are under the cap but the total exceeds it.

**Token cap does not apply to:**
- Guardrails internal file operations (log writes, mode config reads/writes)
- Read operations
- Actions where token_cap is null or not set

## Actions not in the catalog

1. Does it match trigger criteria? If not, proceed normally.
2. If it triggers the gate, classify by analogy to the most similar listed action.
3. If no analogy fits, default to Tier 3.
4. Log with "UNLISTED" tag for future catalog updates.

© Myr-Aya · MIT · Myr-Aya/GouvernAI-claude-code-plugin

Похожие скиллы

Каталог скиллов SKILL.md →
find-skills vercel-labs Ищет и устанавливает готовые скиллы для ИИ-агентов через каталог skills.sh. Пригодится, когда для рабочей задачи нужен специализированный воркфлоу. CX Codex +1 4 000 000установок frontend-design официальный anthropics Скилл задаёт осмысленное визуальное направление для новых интерфейсов и редизайна. Подойдёт, когда стандартный шаблонный UI не устраивает. 1 025 790установок grill-me Matt Pocock Скилл проводит жёсткое интервью по плану или дизайну, чтобы найти пробелы и уточнить решения. Подойдёт перед началом разработки. 1 424 476установок grill-with-docs Matt Pocock Скилл проводит жёсткое интервью по плану или дизайну и по ходу создаёт ADR и глоссарий. Подойдёт перед началом сложной разработки. 1 219 756установок improve-codebase-architecture Matt Pocock Скилл ищет архитектурные узкие места в кодовой базе и показывает варианты углубления модулей в HTML-отчёте. Подойдёт для ревью перед рефакторингом. 1 163 035установок design-taste-frontend Leonxlnx Скилл задаёт арт-дирекцию для публичных страниц и рабочих экранов, а затем проверяет результат в браузере по скриншотам. Нужен, когда интерфейс выглядит шаблонным или недоработанным. CX Codex +1 678 700установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой