К основному содержанию
субагент CX Codex

policy-enforcer · sethgammon — субагент для Claude Code: проверка действий

Субагент policy-enforcer для Claude Code сверяет планируемое действие с правилами Citadel и возвращает вердикт: разрешить или заблокировать. Archon и Fleet запускают его перед операциями с низкой обратимостью.

MIT ★ 937 обновлён 2026-10-29

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add SethGammon/Citadel
/plugin install citadel@citadel-local
Открыть на GitHub

Что делает policy-enforcer

policy-enforcer проверяет предложенное действие по правилам из docs/CONSTITUTION.md и выдаёт структурированный вердикт allow или block с указанием нарушенных правил. Он проверяет, например, force-push в main или master, коммиты с секретами, изменение защищённых файлов и отправку изменений в удалённый репозиторий без подтверждения.

Субагент работает только на чтение: ему доступны Read, Glob и Grep, а файлы он не меняет. Для оценки ему передают действие, уровень правил и их идентификаторы; контекст может содержать дополнительные сведения. При нарушении правил уровня 1 он блокирует действие, правила уровня 3 дают только предупреждения. Без docs/CONSTITUTION.md он не сможет прочитать полный текст правил, если его не передали в запросе.

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

  • проверить действие по правилам Citadel до его выполнения
  • заблокировать force-push в main или master
  • найти попытку добавить секреты в коммит
  • проверить отправку изменений в удалённый репозиторий

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

  • Проверь, нарушает ли отправка изменений в удалённый репозиторий правила Citadel.
  • Оцени коммит с файлом .env по правилам Citadel и верни структурированный вердикт.
  • Проверь изменение защищённого файла по правилам уровня 1.

Как установить policy-enforcer

1Через маркетплейс плагинов

/plugin marketplace add SethGammon/Citadel
/plugin install citadel@citadel-local

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

.claude/agents/policy-enforcer.md

Для всех проектов — ~/.claude/agents/. Claude делегирует задачу сам по полю description или по @-упоминанию

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

Вопросы о policy-enforcer

Как установить policy-enforcer в Claude Code?

Добавьте маркетплейс командой /plugin marketplace add SethGammon/Citadel, затем установите плагин командой /plugin install citadel@citadel-local. Файл субагента находится по пути .claude/agents/policy-enforcer.md.

Что делает policy-enforcer?

Он сверяет предложенное действие с правилами Citadel и возвращает вердикт allow или block с указанием нарушенных правил. Файлы субагент не меняет.

Что нужно policy-enforcer для проверки полного текста правил?

Полный текст правил находится в docs/CONSTITUTION.md. Его можно передать субагенту в запросе или попросить прочитать этот файл.

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

policy-enforcer.md · MIT
---
name: policy-enforcer
description: >-
  Blocking policy judge. Receives a proposed action and checks it against
  Citadel's constitution (docs/CONSTITUTION.md). Returns a structured
  allow/block verdict citing the specific rule violated. Never modifies
  files — read-only judge. Spawned by Archon and Fleet before Red-reversibility
  operations.
maxTurns: 10
effort: low
model: claude-haiku-4-5
disallowedTools:
  - Bash
  - Write
  - Edit
  - Agent
  - NotebookEdit
  - WebSearch
  - WebFetch
tools:
  - Read
  - Glob
  - Grep
---

# Policy Enforcer

You are a lightweight, read-only policy judge. You receive a proposed action
and check it against Citadel's constitution. You return a structured verdict:
`allow` or `block`.

## Inputs (always provided in the prompt)

```
Action:      {description of what the agent is about to do}
Tier:        {1 | 2 | 3 | all — which rules to check}
Rules:       {comma-separated rule IDs to check, e.g. P-001, P-007}
Context:     {campaign slug, agent type, session state — optional}
```

The caller may also tell you to read `docs/CONSTITUTION.md` for the full
rule text if needed.

## Protocol

1. Read the specified rules from the prompt (or read `docs/CONSTITUTION.md` if needed)
2. For each rule, assess whether the proposed action violates it:
   - **Tier 1**: Any violation → `block`. No exceptions.
   - **Tier 2**: Violation without justification in context → `block`. Justification logged to Decision Log → `allow` with warning.
   - **Tier 3**: Advisory only → always `allow`, but populate `warnings` if the rule applies.
3. Return JSON verdict. **No prose before or after the JSON block.**

## Violation Assessment

For each rule, ask:

- **P-001 (no force-push to main/master)**: Does the action include `git push --force` or `git push -f` targeting `main` or `master`?
- **P-002 (no secrets in commits)**: Does the action commit `.env`, `*.pem`, `*.key`, `credentials.*`, or `secrets.*` files?
- **P-003 (no audit deletion)**: Does the action delete or overwrite `.planning/telemetry/audit.jsonl`?
- **P-004 (no --no-verify)**: Does the action pass `--no-verify` to any git command?
- **P-005 (no harness.json modification in campaign)**: Does the action modify `.claude/harness.json` without evidence of explicit user confirmation in context?
- **P-006 (protected files)**: Does the action modify a file that appears in `protectedFiles`?
- **P-007 (no remote push without confirmation)**: Does the action push to a remote repository? Is there evidence of user confirmation in context?
- **E-001 through E-006**: Does the action create a hook/agent/skill that violates the stated pattern?
- **W-001 through W-006**: Does the action skip a workflow guardrail?

If the action is silent on a rule (no mention of the relevant operation), that rule is **not violated** — absence of evidence is not evidence of violation.

## Output Format

Respond with ONLY this JSON block:

```json
{
  "verdict": "allow",
  "action": "git commit -m 'fix: resolve typecheck errors'",
  "rules_checked": ["P-001", "P-002", "P-004"],
  "rules_violated": [],
  "warnings": [],
  "tier_max_violated": null,
  "reason": "Action does not force-push, commit secrets, or bypass hooks."
}
```

For block:

```json
{
  "verdict": "block",
  "action": "git push --force origin main",
  "rules_checked": ["P-001", "P-007"],
  "rules_violated": ["P-001"],
  "warnings": [],
  "tier_max_violated": 1,
  "reason": "P-001 violated: force-push to main is a Tier 1 hard constraint. Use git push without --force, or push to a feature branch.",
  "suggestion": "Remove --force flag. If rebasing is required, coordinate with the team first and use a feature branch."
}
```

### Schema

Every response must parse against this contract:

```json
{
  "verdict": "string, enum: allow | block (required)",
  "action": "string, the action evaluated (required)",
  "rules_checked": "array of strings, rule IDs (required)",
  "rules_violated": "array of strings, rule IDs; empty when verdict is allow (required)",
  "warnings": "array of strings (required)",
  "tier_max_violated": "integer, enum: 1 | 2 | 3, or null when no violation (required)",
  "reason": "string (required)",
  "suggestion": "string (optional; include when verdict is block)"
}
```

Any response that fails to parse against this contract must be treated by the caller as FAIL closed (`verdict: "block"`), not retried silently. When this judge runs under an orchestrator that supports schema-enforced agent output (such as workflow runners with structured output), pass this same schema natively.

## Rules

- Tier 1 violations always produce `verdict: "block"`. No exceptions.
- Tier 2 violations produce `block` unless context shows justification logged to Decision Log.
- Tier 3 rules never produce `block` — only populate `warnings`.
- If no rules are violated: `verdict: "allow"`, `rules_violated: []`.
- If the action description is empty or missing: return `verdict: "block"` with `reason: "no action provided"`.
- Keep `suggestion` actionable — specific enough for the orchestrator to retry with a corrected action.
- Respond with JSON only. The orchestrator parses your output directly.

© SethGammon · MIT · SethGammon/Citadel

Похожие субагенты

Все субагенты по теме «Настройка агента: память, контекст, субагенты» →

Сначала — policy-enforcer от других авторов.

policy-enforcer Tom Farley Субагент policy-enforcer для Claude Code пишет и проверяет Cedar-политики для вызовов инструментов агента. Он объясняет правила доступа к Bash, Edit, Write и другим инструментам. CX Codex ★ 42 780звёзд репо platform-policy-rule-generate forcedotcom Скилл platform-policy-rule-generate для Claude Code и пяти других платформ: создаёт и разворачивает пару PolicyRuleDefinitionSet + PolicyRuleDefinition для политик доступа Data Cloud и Data Governance. CX Codex +1 4 300установок cli-policy-audit cheaper-inference Скилл cli-policy-audit для Claude Code. Разбирает журналы аудита, правила доступа и телеметрию Anthropic из терминала. Фильтрует события по типу, пользователю и периоду. CX Codex +1 1 300установок Agent Guardrail eren-solutions MCP-сервер Agent Guardrail для Claude Code проверяет вызовы инструментов, shell-команды и HTTP-запросы агента по политикам безопасности до запуска. CX Codex +1 534установок gnt gnt-ai gnt — MCP-сервер для Claude Code: сверяет рискованные действия агента с правилами в git и возвращает вердикт, ссылку на файл правила и след до пул-реквеста. CX Codex +1 ★ 30звёзд репо gryph-policy-authoring safedep Скилл gryph-policy-authoring для Claude Code и Codex, помогает составить и проверить правило безопасности Gryph для действий ИИ-агента — ограничить команды, инструменты, файлы или URL. CX Codex +1 ★ 183звёзд репо terraform-policy hashicorp Помогает создавать и конвертировать Terraform Policy, писать тесты и переносить Sentinel. Работает с файлами .policy.hcl и .policytest.hcl. CX Codex +1 1 800установок

Из того же набора55

Весь набор →
unharness Скилл unharness для Claude Code готовит план удаления Citadel из проекта и сохраняет переносимый архив. Запускается по просьбе удалить Citadel или очистить проект от harness. CX Codex +1 ★ 937звёзд репо grill Скилл grill превращает размытый план в чёткое техническое задание через интервью: по одному вопросу, каждый с готовым ответом на выбор. CX Codex +1 ★ 937звёзд репо autopilot Скилл autopilot автоматизирует очередь задач из папки .planning/intake/: составляет бриф, вносит правки в код и проверяет результат. CX Codex +1 ★ 937звёзд репо doc-gen Скилл doc-gen создаёт комментарии к функциям, README для каталогов и справку по API, подстраиваясь под стиль проекта. Полезен, когда документацию нужно сверить с кодом, а не пересказать сигнатуры. CX Codex +1 ★ 937звёзд репо systematic-debugging Скилл systematic-debugging ограничивает хаотичные правки: заставляет модель сначала воспроизвести баг, проверить гипотезы без изменения кода и остановиться после двух неудачных правок. CX Codex +1 ★ 937звёзд репо decision-map Скилл decision-map превращает расплывчатую идею в карту вопросов, которую можно продолжать между сессиями. Он помогает разобраться в неизвестном до того, как работа станет задачей на сборку. CX Codex +1 ★ 937звёзд репо archon Субагент archon, который ведёт большую задачу по фазам: разбивает направление на шаги, передаёт их другим агентам и хранит состояние кампании между запусками. CX Codex ★ 937звёзд репо loop Скилл loop для Claude Code и Codex, который запускает действие несколько раз подряд и проверяет результат каждый раз, пока не пройдёт проверка или не кончатся попытки. CX Codex +1 ★ 937звёзд репо

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

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