Agent Dev 101

Модуль 12 · Урок 12.2

Урок 12.2. Guardrails

На этой странице
  1. Зачем это нужно
  2. Основная идея
  3. Ключевые термины
  4. Agent Decision Vs Hard Constraint
  5. Уровни Ограничений
  6. Схема Guardrails В Agent Workflow
  7. Guardrail Vs Hook
  8. Branch Protection
  9. Branch Protection В Agent Development
  10. CI As Gate
  11. Tool Permissions
  12. Типы Guardrails Для LLM-Агента
  13. Risk Rating Для Tools
  14. Permissions В Локальной Среде Codex/Claude Code
  15. Protected Paths
  16. Approval Gates
  17. Secrets Guardrails
  18. Production Data Guardrails
  19. Deletion Guardrails
  20. Billing И Cost Guardrails
  21. Dependency Guardrails
  22. Migration Guardrails
  23. Deploy Guardrails
  24. Reviewer Guardrails
  25. Multi-Agent Guardrails
  26. Prompt Rules -> Guardrails
  27. Примеры Перевода Правил
  28. Guardrails Matrix
  29. Template: docs/development/guardrails.md
  30. Example: Password Reset Feature
  31. Example: AI Agent Workflow Feature
  32. Guardrails Для File Scope
  33. Guardrails Для Tests
  34. Guardrails Для CI Config
  35. Guardrails Для External Tools
  36. Overrides
  37. Guardrails И User Requests
  38. Observability Начинается С Guardrails
  39. Типичные Ошибки
  40. Практика
  41. Мини-Лаборатория: Guardrails Для Course Repo
  42. Критерии Хороших Guardrails
  43. Краткое резюме
  44. Вопросы для самопроверки
  45. Что дальше

Зачем это нужно

В прошлом уроке мы разобрали hooks:

text
Event
-> Hook command
-> Result
-> Continue, fix, stop or ask approval

Hooks помогают запускать повторяемые проверки в нужный момент. Но hooks не отвечают на весь вопрос безопасности agent workflow.

Есть правила, которые нельзя оставлять только в prompt:

text
Не пушить напрямую в main.
Не deploy'ить без approval.
Не удалять production data.
Не менять billing settings.
Не расширять tool permissions без review.
Не мержить, если CI failed.
Не давать reviewer'у write tools.

Если это написано только в инструкции агенту, правило слабое.

Почему?

  • агент может забыть;
  • агент может неверно оценить риск;
  • prompt может конфликтовать с другой инструкцией;
  • user может попросить "сделай быстро, проверки потом";
  • модель может уверенно объяснить, почему исключение допустимо;
  • tool может позволять действие, которое процесс запрещает.

Guardrail нужен, чтобы критичное правило стало границей системы:

text
Agent may decide what to propose.
System decides what is allowed.

Главная мысль урока:

text
Критичные ограничения должны enforce'иться системой,
а не только существовать как просьба к LLM.

Основная идея

Guardrail - это ограничение, которое не просто просит агента вести себя правильно, а меняет среду так, чтобы опасное действие:

  • было невозможно;
  • было заблокировано;
  • требовало approval;
  • оставляло audit trail;
  • попадало в review;
  • не могло пройти merge/deploy gate.

Плохой вариант:

text
Prompt:
"Никогда не пушь напрямую в main."

Лучше:

text
Branch protection:
- direct push to main disabled;
- PR required;
- required CI checks;
- required reviewer approval.

Prompt все еще нужен. Он объясняет агенту expected behavior.

Но prompt не должен быть единственной защитой:

text
Prompt explains the rule.
Guardrail enforces the boundary.

Ключевые термины

Термин Значение
Guardrail Ограничение вокруг workflow, которое предотвращает, блокирует или требует approval для рискованного действия.
Hard constraint Правило, enforce'ящееся системой: permission, branch protection, required CI, blocked command.
Soft rule Инструкция в prompt или docs. Полезна, но не является enforced boundary.
Approval gate Точка, где действие не продолжается без явного human approval.
Branch protection Настройки репозитория, которые ограничивают push/merge в защищенные ветки.
Tool permission Разрешение или запрет на использование конкретного tool, команды, API или scope.
Least privilege Агент получает минимальные права, достаточные для текущей роли и задачи.
CI gate Required check, без которого change не может быть merged/deployed.
Protected path Файл или директория, изменения в которых требуют extra review или approval.
Policy Явное правило процесса: что разрешено, что запрещено, где нужен gate.
Override Осознанное исключение из правила с owner, reason и evidence.
Audit trail Следы принятого решения: кто разрешил, что было выполнено, какие checks passed/failed.
Blast radius Максимальный ущерб, который может причинить ошибка агента с текущими permissions.

Agent Decision Vs Hard Constraint

AI agent может принимать решения внутри задачи:

text
Какой файл прочитать?
Какую функцию изменить?
Какие tests запустить?
Как сформулировать diff summary?
Какой refactor предложить?

Но есть решения, которые лучше не оставлять на усмотрение агента:

text
Можно ли push в main?
Можно ли удалить database table?
Можно ли deploy'ить в production?
Можно ли дать tool доступ к billing?
Можно ли игнорировать failed security check?
Можно ли расширить scope задачи?

Разница:

Тип решения Кто может решать Пример
Local implementation decision Agent within task scope Выбрать helper function.
Design decision Agent proposes, human/reviewer approves if important Изменить API contract.
Verification decision Hook/CI provides evidence, agent reacts Tests failed, нужно fix.
Risk decision Human or policy gate Deploy with known issue.
Permission decision System/admin/project owner Разрешить external write tool.
Merge decision Branch protection + reviewer + CI PR can merge only when gates pass.

Принцип:

text
Agent can propose risky action.
Agent should not be the final authority for risky action.

Уровни Ограничений

Не все правила сразу становятся hard guardrails. Есть уровни.

Уровень Пример Сила
Prompt rule "Не меняй unrelated files." Слабая, зависит от поведения агента.
Checklist Перед финалом проверить diff. Лучше, но все еще ручная дисциплина.
Hook BeforeCommit запускает scripts/verify. Enforced на событии, если hook нельзя обойти.
CI gate Required checks before merge. Сильнее, проверяет clean environment.
Branch protection Direct push disabled, PR required. Hard repository boundary.
Tool permission Agent не имеет destructive tool. Hard execution boundary.
Approval gate Deploy/deletion requires human approval. Human-controlled boundary.
Environment isolation Agent cannot access production secrets/data. Hard blast-radius boundary.

Хороший процесс комбинирует уровни.

text
Prompt tells the agent what good behavior is.
Hooks automate repeatable checks.
CI verifies in shared environment.
Permissions limit possible actions.
Approvals handle risky exceptions.
Branch protection blocks unsafe merge paths.

Схема Guardrails В Agent Workflow

flowchart TD A[Agent proposes action] --> B{Tool permission allows?} B -- no --> X[Blocked: insufficient permission] B -- yes --> C{Protected path or risky action?} C -- yes --> D[Approval gate / reviewer gate] C -- no --> E[Execute action] D --> F{Approved?} F -- no --> Y[Blocked or redesign] F -- yes --> E E --> G[Hooks / local checks] G --> H{Checks pass?} H -- no --> Z[Fix or block] H -- yes --> I[PR / Integration] I --> J[CI gate] J --> K{CI green and review approved?} K -- no --> Z K -- yes --> L[Merge / Deploy gate]

Эта схема показывает важную идею:

text
Guardrails are checked before, during and after action.

До действия:

  • permissions;
  • protected paths;
  • approval gates;
  • scope constraints.

Во время действия:

  • sandbox;
  • command approval;
  • read/write boundaries;
  • rate limits;
  • environment separation.

После действия:

  • hooks;
  • CI;
  • review;
  • audit logs;
  • deployment gates.

Guardrail Vs Hook

Hook запускает automation.

Guardrail задает boundary.

Вопрос Hook Guardrail
Что делает? Запускает команду при событии. Ограничивает действие или требует gate.
Пример BeforeCommit runs scripts/verify. Merge blocked unless CI passes.
Может ли быть частью другого? Да, hook может реализовать часть guardrail. Да, guardrail может требовать hook/CI result.
Основной риск Hook можно обойти или он шумит. Guardrail может быть слишком широким или неудобным.
Хороший output Pass/fail evidence. Allowed/blocked/approval required.

Пример связки:

text
Prompt rule:
Run tests before commit.

Hook:
BeforeCommit runs tests.

Guardrail:
Protected branch requires CI tests before merge.

Hook помогает локально. Guardrail не дает непроверенному change попасть в protected branch.

Branch Protection

Branch protection - один из самых простых и полезных guardrails.

Правило:

text
Не пушить напрямую в main.

Как prompt:

text
Agent, never push directly to main.

Проблема:

  • агент может забыть;
  • human может ошибиться;
  • tool может выполнить push;
  • exception может стать привычкой;
  • audit trail будет слабым.

Как guardrail:

text
main branch:
- direct push disabled;
- pull request required;
- required CI checks;
- required review;
- stale approvals dismissed after new commits;
- force push disabled;
- deletion disabled.

Даже если агент попробует push:

text
git push origin main

remote rejected.

Это и есть hard constraint.

Branch Protection В Agent Development

Для AI-assisted development branch protection особенно важен, потому что агент может быстро дойти до команды "commit/push/merge" без человеческой паузы.

Минимальная policy:

text
Protected branches:
- main
- release/*

Rules:
- no direct push;
- no force push;
- pull request required;
- required status checks;
- independent review for non-trivial changes;
- CODEOWNERS or path owners for protected areas;
- conversation/finding resolution before merge.

Для учебного проекта это можно упростить:

text
No direct edits to main for capstone feature.
Every feature gets a task branch.
Before merge:
- scripts/verify passed;
- diff reviewed;
- unrelated changes separated;
- human approval for high-risk changes.

Даже если нет GitHub/GitLab settings, правило можно имитировать локально:

  • работать через branches;
  • не делать git add . без review;
  • не merge'ить без verification report;
  • использовать git diff main...HEAD;
  • держать final approval как отдельный step.

Но в настоящей командной среде лучше enforce'ить это на стороне remote.

CI As Gate

CI gate - это guardrail, который говорит:

text
Change cannot merge unless required checks pass.

CI может запускать:

  • format check;
  • lint;
  • typecheck;
  • unit tests;
  • integration tests;
  • docs build;
  • security scan;
  • secret scan;
  • migration check;
  • eval smoke suite;
  • ./scripts/verify.

Важно:

text
CI should call the same repo-level verification entry point when practical.

Например:

text
Local:
./scripts/verify

CI:
./scripts/verify

Так agent, human и CI используют один contract.

CI as gate сильнее, чем локальный hook, потому что CI:

  • работает в clean environment;
  • не зависит от локального состояния агента;
  • имеет central logs;
  • виден reviewer'у;
  • может быть required для merge.

Но CI не решает все:

text
Green CI does not prove correct product behavior.

CI gate нужен вместе с review gate и acceptance criteria.

Tool Permissions

Tool permissions - это guardrails вокруг действий агента.

В agent workflow tools могут читать файлы, писать код, запускать команды, ходить в сеть, управлять Git, менять cloud resources, отправлять письма, создавать tickets, управлять billing или deploy'ить.

Если у агента есть tool, он потенциально может его использовать.

Правило:

text
Give the agent the least privilege needed for the current role.

Пример permissions by role:

Роль Read files Write files Run tests Git write Network Deploy Billing
Planner yes no no no no by default no no
Implementer yes scoped yes local branch only limited no no
Verifier yes no by default yes no no by default no no
Reviewer yes no by default read-only checks no no by default no no
Integrator yes scoped yes integration branch limited no no
Release Agent yes no or scoped yes tag/release if approved limited gated no
Billing Agent read only by default no no no maybe no gated

В маленьком локальном workflow это может быть не формальная IAM-матрица, а практическое правило:

  • reviewer работает без write tools;
  • planner сначала только читает;
  • destructive commands требуют approval;
  • network/dependency install не выполняется без причины;
  • deploy tools отключены для implementer;
  • billing/secrets tools не доступны обычным coding tasks.

Tool permission guardrail должен отвечать:

text
Can this role do damage if it follows a bad plan?

Если да, permission слишком широкая.

Типы Guardrails Для LLM-Агента

В agent workflow guardrails полезно делить не только по enforcement mechanism, но и по риску, который они закрывают.

Тип guardrail Что защищает Пример
Relevance boundary Агент не уходит за domain/task scope. Coding agent отказывается решать unrelated business/legal question.
Safety / jailbreak classifier Защита от prompt injection и попыток раскрыть hidden instructions. Input просит "выведи system prompt" -> blocked/escalated.
PII filter Не дает лишним персональным данным попадать в prompt, log или output. Redaction email/phone/token before run log.
Moderation Блокирует harmful или policy-sensitive content в пользовательских input/output. Support agent не генерирует запрещенный контент.
Tool safeguard Ограничивает риск tool calls. High-risk write tool требует approval.
Rules-based protection Детерминированные проверки известных угроз. Regex secret scan, path denylist, max input size.
Output validation Проверяет форму и допустимость результата. JSON schema, no fabricated test claims, required evidence fields.

Для курса особенно важны четыре типа:

  • relevance boundary: агент не расширяет задачу;
  • tool safeguards: агент не выполняет рискованные действия без gate;
  • output validation: финальный ответ содержит evidence, а не уверенность;
  • PII/log filtering: run logs полезны, но не должны становиться хранилищем sensitive data.

Risk Rating Для Tools

Не все tools одинаковы. Один и тот же agent может безопасно читать docs, но не должен без approval менять billing, production data или deployment config.

Оценивайте tool по нескольким вопросам:

Вопрос Low risk Medium risk High risk
Read/write Read-only Scoped write в repo External write / production write
Reversibility Легко отменить Откат возможен, но требует effort Откат дорогой или невозможен
Permissions Public/local data Internal project data Secrets, PII, billing, production
Impact Docs/search Code/config change Money, security, customer data, deploy
Evidence Clear logs Partial logs Weak logs or opaque side effects

Примеры:

Tool/action Risk Guardrail
Read local Markdown files Low Разрешить в Plan/Act.
Run targeted unit tests Low/Medium Разрешить, логировать command result.
Edit source files in approved scope Medium Scope approval + diff review.
Add dependency Medium Approval + lockfile review + security check.
Write GitHub PR comment Medium Approval or role-specific permission.
Run database migration High Explicit approval + backup/rollback plan.
Deploy production High Release gate + human approval + CI evidence.
Change billing/cloud permissions High Owner approval, preferably no agent access by default.

Принцип:

text
Tool risk determines the gate.
Low risk can be automated.
Medium risk needs scope and evidence.
High risk needs explicit human approval or should be unavailable.

Permissions В Локальной Среде Codex/Claude Code

Даже локальный coding agent имеет guardrails:

  • filesystem sandbox;
  • writable roots;
  • approval для escalated commands;
  • command allow/deny policies;
  • network restrictions;
  • distinction between read and write operations;
  • approval for destructive actions;
  • user-visible diffs.

Это не просто техническая деталь. Это часть design of agent workflow.

Пример:

text
Task:
Update one lesson file.

Allowed:
- read course files;
- edit target Markdown file;
- run local verification commands.

Not allowed without approval:
- delete directories;
- reset git history;
- install packages;
- push to remote;
- deploy site;
- write outside repo.

Такое ограничение снижает blast radius. Даже если агент неправильно понял задачу, он не должен иметь возможность повредить unrelated environment.

Protected Paths

Некоторые файлы и директории требуют особого контроля.

Примеры:

  • database migrations;
  • auth/permissions code;
  • payment/billing code;
  • deployment config;
  • infrastructure scripts;
  • secrets/config templates;
  • agent tool permission config;
  • prompts/skills that affect production agent behavior;
  • CI workflow files;
  • package manager lockfiles;
  • public API schemas.

Policy:

text
If protected path changes,
require extra review or approval.

Пример:

Path Guardrail
db/migrations/** Require migration review + rollback plan.
auth/** Require security-sensitive review.
.github/workflows/** Require maintainer review.
skills/**/SKILL.md Require skill validation and reviewer.
agent/tools/** Require permission diff review.
billing/** Require owner approval.
infra/** Require deploy/ops approval.

Protected path не означает "нельзя менять". Он означает:

text
Change is allowed only through the right gate.

Approval Gates

Approval gate нужен там, где система не может сама решить risk.

Типовые high-risk actions:

Action Почему нужен approval
Deploy to production Влияет на пользователей.
Delete files/data Может быть необратимо.
Database migration Риск data loss, downtime, compatibility.
Change auth/permissions Security-sensitive behavior.
Add dependency Supply chain, license, size, maintenance.
Change billing settings Финансовый риск.
Access external service Privacy, cost, rate limits.
Use production data Privacy/compliance risk.
Override failed CI/security check Осознанное принятие risk.
Expand tool permissions Увеличивает blast radius.

Хороший approval request:

text
Approval needed:
Run database migration that adds `password_reset_tokens`.

Why:
Required for password reset feature.

Evidence:
- migration file:
- rollback plan:
- tests:
- local verification:

Risk:
- new table only, no existing data mutation;
- deploy order must run migration before enabling endpoint.

Decision options:
1. approve migration;
2. request safer migration plan;
3. split migration into separate task;
4. reject for current scope.

Плохой approval request:

text
Можно продолжать?

Он не говорит, что человек разрешает.

Secrets Guardrails

Secrets - один из самых частых рисков в agent workflow.

Prompt rule:

text
Не коммить secrets.

Guardrails:

  • secret scan in hook;
  • secret scan in CI;
  • masked logs;
  • .env excluded from Git;
  • example env files use placeholders;
  • production secrets unavailable to coding agent;
  • tools do not print secret values;
  • approvals for secret rotation or access;
  • revoke/rotate procedure if secret appears in diff.

Важно:

text
Agent should not need production secrets to write normal code.

Если task требует secret, сначала нужно спросить:

  • можно ли использовать local dummy value;
  • можно ли использовать test environment;
  • можно ли вызвать service through controlled tool;
  • нужен ли human approval;
  • будет ли secret visible in logs.

Плохой workflow:

text
User pastes production API key into prompt.
Agent writes it into config.
BeforeCommit does not scan secrets.

Хороший workflow:

text
Agent asks for non-secret config name or test credential.
Real secret stays in secret manager.
Secret scan blocks accidental commit.
Logs mask sensitive values.

Production Data Guardrails

Coding agent не должен свободно работать с production data.

Prompt rule:

text
Не трогай production data.

Guardrails:

  • no production database credentials in local environment;
  • read-only credentials for analysis tasks;
  • write access only through approved migration/deploy process;
  • data export disabled by default;
  • PII redaction before logs/prompts;
  • approval for any production data access;
  • audit log for access;
  • synthetic fixtures for tests.

Особенно важно:

text
Do not put production data into model context unless policy explicitly allows it.

Для учебного курса достаточно принципа:

  • используем fixtures;
  • используем test database;
  • не даем агенту production credentials;
  • не вставляем real user data в prompt;
  • не просим агента "посмотреть таблицу пользователей" без approved process.

Deletion Guardrails

Удаление опасно, потому что часто необратимо или трудно заметно.

Prompt rule:

text
Не удаляй важные файлы.

Guardrails:

  • destructive commands require approval;
  • rm -rf не выполняется без explicit permission;
  • protected paths cannot be deleted without review;
  • database DROP/DELETE migrations require approval;
  • branch deletion disabled for protected branches;
  • backups/rollback plan required before data deletion;
  • diff review highlights deleted files.

Пример local policy:

text
Agent may delete generated files in scoped task if regeneration is documented.
Agent must ask approval before deleting source files, migrations, docs, tests or directories.

Deletion guardrail должен различать:

Deletion type Policy
Delete unused local generated file May be allowed with evidence.
Delete source file Requires review.
Delete test Requires explanation and reviewer approval.
Delete migration Requires database owner approval.
Delete production data Requires formal approval and rollback/backup plan.
Delete protected branch Disallowed or admin-only.

Billing И Cost Guardrails

AI agents могут вызывать paid APIs, запускать cloud resources, отправлять много tokens, создавать jobs или менять billing settings.

Prompt rule:

text
Не трать много денег.

Guardrails:

  • no billing write permissions by default;
  • read-only billing access for reporting;
  • budget limits;
  • rate limits;
  • quota per task;
  • approval before paid external API use;
  • approval before launching cloud resources;
  • cost logging;
  • kill switch for runaway jobs.

Для AI development особенно важно:

  • eval regression suite может быть expensive;
  • multi-agent runs can multiply token cost;
  • external tools may bill per call;
  • retries can hide cost growth.

Практичная policy:

text
Agent can run local tests freely.
Agent needs approval for paid external service calls.
Agent needs approval for large eval suite if cost exceeds threshold.
Billing settings are read-only unless explicitly approved.

Dependency Guardrails

Добавить dependency легко. Поддерживать ее потом сложнее.

Prompt rule:

text
Не добавляй новые зависимости без необходимости.

Guardrails:

  • dependency changes require approval or review;
  • lockfile diff must be inspected;
  • license/security scan for new packages;
  • prefer existing libraries in repo;
  • no install from unknown source without approval;
  • no auto-upgrade as side effect of unrelated task;
  • CI verifies lockfile consistency.

Agent task brief может говорить:

text
Allowed:
- use existing project dependencies.

Requires approval:
- adding runtime dependency;
- major upgrade;
- changing package manager;
- adding external service SDK.

Dependency guardrail защищает от scope creep:

text
Small feature should not silently become supply-chain decision.

Migration Guardrails

Database migrations требуют отдельного внимания.

Prompt rule:

text
Будь осторожен с миграциями.

Guardrails:

  • migration files are protected path;
  • migration requires task brief and acceptance criteria;
  • backward compatibility review for zero-downtime systems;
  • rollback plan or roll-forward plan;
  • local migration test;
  • CI migration check;
  • approval before production migration;
  • no destructive migration without explicit approval;
  • deploy order documented.

Migration approval packet:

text
Migration:

Purpose:

Schema changes:

Data changes:

Backward compatibility:

Rollback or roll-forward:

Commands tested:

Risks:

Approval needed from:

Даже в 101 курсе важно дать студенту привычку:

text
Migration is not just another file edit.

Deploy Guardrails

Deploy - это переход из engineering world в user-facing world.

Prompt rule:

text
Не deploy без проверки.

Guardrails:

  • deploy only from protected branch or approved release branch;
  • deploy only if CI green;
  • staging smoke tests before production;
  • human approval for production;
  • rollback plan visible;
  • deploy logs saved;
  • secrets/config validation;
  • no deploy from dirty worktree;
  • no deploy with uncommitted local changes;
  • no deploy by normal implementer role.

Хороший deploy gate:

text
Before production deploy:
- commit is from protected branch;
- CI passed;
- migration status checked;
- smoke tests passed;
- owner approval recorded;
- rollback plan documented.

Deploy guardrails часто выходят за рамки локального курса, но принцип нужен уже здесь:

text
Agent can prepare release.
Agent should not silently release to users.

Reviewer Guardrails

В модуле 11 мы говорили, что reviewer должен быть independent.

Guardrail для reviewer:

text
Reviewer should not have write permission by default.

Почему?

Если reviewer может сразу исправлять код, он легко превращается во второго implementer'а. Это не всегда плохо, но это меняет роль.

Policy:

Роль Default permission
Reviewer Read diff, inspect relevant files, run read-only checks.
Reviewer with fix permission Allowed only after explicit routing decision.
Implementer Fixes findings in scoped branch.
Integrator Resolves conflicts and compatibility fixes.

Prompt rule:

text
Reviewer, не исправляй код.

Guardrail:

text
Reviewer session has no write tools.
Review output must be findings, not patch.

Если reviewer должен сделать fix, workflow должен явно поменять state:

text
Review -> ChangesRequested -> Implementer Fix

или:

text
Review -> Approved Small Reviewer Fix -> Verification -> Review update

Но это не должно происходить молча.

Multi-Agent Guardrails

Для multi-agent workflow нужны дополнительные guardrails:

  • agents do not share the same writable worktree by default;
  • each branch has a task brief;
  • each role has permissions;
  • integration is a separate stage;
  • reviewer uses fresh context;
  • branch packets include evidence;
  • no agent merges its own branch without review;
  • coordinator cannot silently override failed gates;
  • high-risk branches require human approval.

Пример:

text
Backend Agent:
- write access only to backend branch/worktree;
- no deploy tools;
- no billing tools;
- cannot change frontend contract without approval.

Frontend Agent:
- write access only to UI branch/worktree;
- cannot change API behavior;
- must report UI verification evidence.

Test Agent:
- can add tests;
- cannot weaken acceptance criteria;
- test deletion requires reviewer approval.

Reviewer:
- read-only;
- fresh context;
- no write tools by default.

Guardrails делают role separation реальной, а не декоративной.

Prompt Rules -> Guardrails

Главная практическая техника урока:

text
Take a prompt rule.
Ask how it can fail.
Move the rule into system boundary where practical.

Шаблон:

text
Prompt rule:

Failure mode:

Better guardrail:

Enforcement point:

Evidence:

Override policy:

Пример:

text
Prompt rule:
Do not push directly to main.

Failure mode:
Agent or human runs `git push origin main`.

Better guardrail:
Remote branch protection rejects direct push.

Enforcement point:
Git provider.

Evidence:
PR merge history + CI status.

Override policy:
Admin-only emergency process.

Примеры Перевода Правил

Prompt rule Failure mode Guardrail
"Не пушь в main." Agent runs direct push. Branch protection rejects direct push.
"Запускай tests перед merge." Agent forgets or claims without running. Required CI checks.
"Не коммить secrets." Secret попадает в diff. Secret scan hook + CI scan + masked logs.
"Не удаляй важные файлы." Source/test file deleted accidentally. Protected paths + approval for deletion.
"Не deploy без разрешения." Agent runs deploy command. Deploy permission disabled + approval gate.
"Не меняй billing." Agent uses billing API. Billing tool read-only or unavailable.
"Reviewer не чинит код." Reviewer writes patch during review. Reviewer context has read-only permissions.
"Не добавляй dependency." Agent installs package to solve local issue. Dependency changes require approval + lockfile review.
"Не ослабляй tests." Agent edits tests for green build. Test diff review + protected test paths for critical cases.
"Не меняй CI без review." Agent disables failing check. CI config protected path + CODEOWNER review.

Не каждое правило можно сделать fully hard. Но почти каждое critical rule можно усилить:

  • permission;
  • branch rule;
  • required check;
  • approval;
  • protected path;
  • audit log;
  • review packet requirement.

Guardrails Matrix

Для проекта полезно иметь таблицу guardrails.

text
docs/development/guardrails.md

Пример:

Risk Prompt rule Enforced guardrail Owner Override
Direct main push Do not push to main. Branch protection requires PR. Maintainer Admin emergency only.
Unverified merge Run tests before merge. Required CI checks. Maintainer Documented override.
Secret leak Never commit secrets. Secret scan hook + CI. Security/maintainer No override, rotate if leaked.
Risky migration Be careful with DB. Protected path + migration approval. Backend owner Approval required.
Tool overreach Use only needed tools. Least privilege permissions. Project owner Temporary scoped approval.
Test weakening Do not delete tests. Reviewer inspects test diff. Reviewer Requires reason.
Production deploy Do not deploy casually. Deploy approval gate. Release owner Emergency process.

Такой документ полезен не только людям, но и агентам. Он превращает security/process expectations в явный project context.

Template: docs/development/guardrails.md

text
Document:
docs/development/guardrails.md

Purpose:
Define enforceable constraints for human and AI-assisted development.

Protected Branches:
- `main`:
  - direct push:
  - required checks:
  - required review:
  - force push:

Required Verification:
- local:
- before commit:
- before PR:
- before merge:
- before deploy:

Tool Permissions:
| Role | Allowed | Requires Approval | Forbidden |
|---|---|---|---|
| Planner |  |  |  |
| Implementer |  |  |  |
| Verifier |  |  |  |
| Reviewer |  |  |  |
| Integrator |  |  |  |

Protected Paths:
| Path | Required Gate | Owner |
|---|---|---|
|  |  |  |

High-Risk Actions:
| Action | Gate | Evidence Required |
|---|---|---|
| Deploy to production |  |  |
| Database migration |  |  |
| Secret access |  |  |
| Dependency change |  |  |
| Billing change |  |  |
| Data deletion |  |  |

Override Policy:
Override requires:
- reason;
- owner approval;
- evidence;
- rollback plan when relevant;
- follow-up task if risk remains.

Agent Reporting:
Every agent final report must include:
- changed files;
- verification commands;
- pass/fail/not-run checks;
- guardrails triggered;
- approvals requested or received;
- residual risks.

Это не бюрократия ради бюрократии. Это executable memory проекта: что нельзя делать автоматически, где нужны gates, какие evidence считать достаточными.

Example: Password Reset Feature

Вернемся к capstone feature:

text
Password reset:
- request reset link;
- send email;
- validate token;
- set new password.

Риски:

  • account enumeration;
  • token leakage;
  • insecure token storage;
  • broken expiry;
  • migration risk;
  • email provider secrets;
  • auth code changes;
  • tests weakened by agent.

Guardrails:

Risk Guardrail
Account enumeration Acceptance criteria + reviewer security pass.
Token leakage Secret scan + review of logs/examples.
Insecure token storage Auth protected path review.
Migration risk Migration approval packet.
Email provider secret No real secret in prompt/repo, use env var placeholder.
Auth behavior change Protected path review for auth/**.
Tests weakened Test diff review, critical test deletion requires approval.
Unverified merge Required scripts/verify in CI.
Direct main update Branch protection.

Example task brief:

text
Allowed:
- implement password reset in feature branch;
- edit scoped auth files;
- add tests;
- use existing email abstraction.

Requires approval:
- add new email provider dependency;
- create database migration;
- change auth middleware;
- change CI config;
- access external email service;
- deploy.

Forbidden:
- commit real API keys;
- push directly to main;
- remove existing auth tests without approval;
- disable security checks.

Это guardrail thinking в действии: мы не просто говорим "будь аккуратен с auth", а задаем boundaries before work starts.

Example: AI Agent Workflow Feature

Task:

text
Add a new MCP tool that can create tickets in an external tracker.

Риски:

  • tool can create external side effects;
  • API token exposure;
  • spam/duplicate ticket creation;
  • billing/usage limits;
  • wrong project/workspace;
  • agent uses tool during review;
  • tests accidentally hit real API.

Guardrails:

Risk Guardrail
External side effect Tool disabled by default, approval required for write calls.
Token exposure Secret manager, masked logs, no token in prompt.
Duplicate tickets Idempotency key required.
Wrong workspace Allowlist project IDs.
Billing/usage Rate limit and quota.
Review misuse Reviewer gets read-only/mock tool.
Tests hit real API Tests use mock server by default.
Tool permission expansion Permission diff review.

Prompt rule:

text
Use the ticket tool carefully.

Guardrail:

text
Ticket creation tool requires:
- explicit user approval;
- target project allowlist;
- dry-run preview;
- idempotency key;
- audit log.

Это гораздо надежнее.

Guardrails Для File Scope

AI agent часто ошибается не в том, что "сломал все", а в том, что сделал слишком много.

Prompt rule:

text
Do not change unrelated files.

Guardrails:

  • task brief lists allowed paths;
  • agent final report includes changed files;
  • pre-commit warns on files outside allowed scope;
  • reviewer checks git diff --name-only;
  • protected paths require approval;
  • one task per branch;
  • generated files are labeled.

Пример:

text
Allowed paths:
- modules/module_12/lesson_12_02_guardrails.md

Requires approval:
- modules/module_12/README.md
- guide/content_plan.md
- scripts/**

Forbidden for this task:
- module_13/**
- package manager files
- CI config

Даже если это не fully enforceable локально, это делает scope visible. В зрелом repo это можно усилить path-based checks.

Guardrails Для Tests

Tests являются safety mechanism, но агент может сам изменить tests.

Prompt rule:

text
Не ослабляй тесты ради green.

Guardrails:

  • critical tests protected by reviewer approval;
  • test deletion requires explanation;
  • bug fix should include reproducing test when practical;
  • changed tests are highlighted in review packet;
  • CI compares coverage or key scenarios;
  • acceptance criteria remain source of truth;
  • failing tests cannot be removed silently.

Review packet should include:

text
Tests changed:
- file:
- reason:
- new scenario:
- removed scenario:
- why removal is safe:

Если agent меняет tests and implementation in one diff, reviewer должен смотреть особенно внимательно:

text
Did the test become more accurate,
or did it become easier for wrong code to pass?

Guardrails Для CI Config

CI config itself is high-risk.

Prompt rule:

text
Не отключай проверки.

Guardrails:

  • CI config protected path;
  • changes require maintainer review;
  • required checks cannot be removed by PR author alone;
  • branch protection configured outside repo file when possible;
  • CI changes require explanation in PR;
  • failed check override requires owner approval.

Плохой pattern:

text
Tests fail.
Agent edits CI to skip the failing job.
CI becomes green.

Guardrail:

text
Any change to `.github/workflows/**` or equivalent CI config requires reviewer approval.
Required checks are configured in repository settings, not only in editable workflow files.

Guardrails Для External Tools

External tools увеличивают blast radius.

Examples:

  • GitHub write API;
  • Slack posting;
  • Gmail sending;
  • calendar scheduling;
  • cloud deployment;
  • database writes;
  • billing API;
  • issue tracker writes;
  • analytics export;
  • customer support tools.

Guardrails:

  • read-only by default;
  • write calls require approval;
  • dry-run preview before side effect;
  • allowlist target workspace/project/channel;
  • idempotency key for create/update actions;
  • audit logs;
  • rate limits;
  • no tool access for roles that do not need it;
  • revoke permission after task.

Prompt:

text
Be careful when using tools.

Guardrail:

text
The tool cannot execute write action without approval token.

Overrides

Иногда guardrail нужно обойти. Это должно быть редким и видимым.

Bad override:

text
CI failed, but probably unrelated. Merging anyway.

Good override:

text
Override request:

Guardrail:
Required docs link check.

Failure:
External website temporarily unavailable.

Evidence:
- local docs build passed;
- failing link is external;
- no internal links broken.

Risk:
Released docs may contain one external broken link.

Owner approval:
Docs maintainer approved temporary override.

Follow-up:
Track link check issue.

Override policy:

  • owner approval required;
  • reason documented;
  • evidence included;
  • scope limited;
  • expiration/follow-up set;
  • never use override to hide unknown failure;
  • security/secrets/data deletion overrides are stricter.

Правило:

text
Override is a controlled exception,
not a convenient shortcut.

Guardrails И User Requests

Иногда user прямо просит сделать risky action:

text
Сделай force push.
Удаляй старую директорию.
Задеплой сразу.
Отключи падающий тест.
Дай агенту доступ к billing.

Agent should not treat user request as automatic permission if project guardrail requires explicit approval or context.

Правильная реакция:

text
This is a high-risk action.
I need explicit approval with scope and reason.
Here is what will happen, what can go wrong, and how to roll back.

В локальном workflow это особенно важно для destructive commands:

  • rm;
  • git reset --hard;
  • git clean;
  • force push;
  • database drop;
  • migration rollback;
  • deploy.

Guardrail делает conversation конкретным:

text
Do you approve deleting these files?
- file A
- file B

Reason:
Generated artifacts, can be recreated by command X.

Rollback:
Git restore from current branch.

Observability Начинается С Guardrails

Следующий модуль посвящен observability и evals. Guardrails готовят переход к нему.

Почему?

Потому что guardrail без logs трудно улучшать.

Нужно знать:

  • какие guardrails часто triggered;
  • какие hooks часто failed;
  • где agents запрашивают approval;
  • какие overrides были сделаны;
  • какие permissions были расширены;
  • какие CI checks чаще всего blocking;
  • какие tasks чаще всего выходят за scope.

Это уже вопрос наблюдаемости процесса.

Минимальный run log должен фиксировать:

text
Task:
Agent role:
Tools used:
Guardrails triggered:
Approvals requested:
Approvals received:
Checks passed:
Checks failed:
Overrides:
Final state:

Так guardrails становятся не только защитой, но и источником improvement data.

Типичные Ошибки

Ошибка 1. Guardrail Остается Prompt Rule

Плохо:

text
Prompt says:
"Do not merge if tests fail."

Но branch protection не настроена, CI optional, reviewer не видит test result.

Лучше:

text
Merge blocked unless required CI checks pass.

Ошибка 2. Слишком Широкие Tool Permissions

Плохо:

text
Coding agent has deploy, billing, database write and GitHub admin permissions.

Лучше:

text
Implementer has scoped repo write and test commands.
Deploy/billing/database write require separate approved role.

Ошибка 3. Reviewer Имеет Те Же Права, Что Implementer

Плохо:

text
Reviewer gets full write tools and starts fixing the diff.

Лучше:

text
Reviewer is read-only by default and outputs findings.

Ошибка 4. CI Config Не Защищен

Плохо:

text
Agent fixes failing CI by disabling CI job.

Лучше:

text
CI config is protected path and requires maintainer review.

Ошибка 5. Approval Prompt Слишком Общий

Плохо:

text
Approve?

Лучше:

text
Approve production deploy of commit X?
Evidence:
- CI passed;
- smoke tests passed;
- migration checked;
- rollback plan:

Ошибка 6. Guardrails Нельзя Обойти Даже Когда Нужно

Слишком жесткие guardrails могут заблокировать работу.

Нужен override process:

  • кто может approve;
  • в каких случаях;
  • какой evidence нужен;
  • где фиксируется reason;
  • какой follow-up нужен.

Иначе команда начнет искать неофициальные обходы.

Ошибка 7. Guardrail Слишком Шумный

Если guardrail срабатывает на каждую безопасную операцию, люди перестают ему доверять.

Лучше:

  • четко отделить warning от blocking;
  • сделать rules scoped;
  • убрать ложные positives;
  • назначить owner;
  • пересматривать guardrails по run logs.

Ошибка 8. Guardrails Не Версионируются

Если правила живут только в устной договоренности, агент их не увидит.

Лучше:

text
docs/development/guardrails.md
scripts/verify
CI required checks
branch protection settings
tool permission config

Часть guardrails живет в репозитории. Часть в platform settings. Но в docs должен быть map: где что enforce'ится.

Практика

Возьмите demo repo или capstone feature и переведите 5 prompt rules в enforceable guardrails.

Шаблон:

text
Rule 1:
Prompt rule:
Failure mode:
Guardrail:
Enforcement point:
Evidence:
Override policy:

Rule 2:
Prompt rule:
Failure mode:
Guardrail:
Enforcement point:
Evidence:
Override policy:

Rule 3:
Prompt rule:
Failure mode:
Guardrail:
Enforcement point:
Evidence:
Override policy:

Rule 4:
Prompt rule:
Failure mode:
Guardrail:
Enforcement point:
Evidence:
Override policy:

Rule 5:
Prompt rule:
Failure mode:
Guardrail:
Enforcement point:
Evidence:
Override policy:

Рекомендуемые rules:

text
1. Do not push directly to main.
2. Do not merge without tests.
3. Do not commit secrets.
4. Do not deploy without approval.
5. Do not add dependencies without review.

Минимальный результат:

text
[ ] У каждого rule есть failure mode.
[ ] У каждого rule есть enforcement point.
[ ] Есть хотя бы один branch protection guardrail.
[ ] Есть хотя бы один CI gate.
[ ] Есть хотя бы один tool permission guardrail.
[ ] Есть хотя бы один approval gate.
[ ] Есть override policy.
[ ] Есть agent reporting requirement.

Мини-Лаборатория: Guardrails Для Course Repo

Для репозитория курса можно предложить простые guardrails:

text
Protected branch:
- main accepts only reviewed changes.

Required verification:
- no unfinished draft markers;
- markdown code fences balanced;
- `git diff --check`;
- lesson has summary and self-check questions.

Protected paths:
- guide/content_plan.md requires course owner approval;
- req/** is source material, changes require approval;
- modules/module_12/** can be edited for current task.

Tool permissions:
- writing allowed only inside repo;
- destructive git commands require approval;
- dependency installation requires approval;
- no deploy tools for lecture writing task.

Approval gates:
- deleting lesson files;
- changing course structure;
- changing module plan;
- publishing/deploying course.

Это учебная версия guardrails. Она уже улучшает agent workflow: агент понимает не только "что написать", но и какие boundaries нельзя пересекать.

Критерии Хороших Guardrails

Хороший guardrail:

  • защищает реальный risk;
  • имеет clear enforcement point;
  • не зависит только от памяти агента;
  • дает понятный allowed/blocked result;
  • имеет owner;
  • имеет override policy;
  • не слишком шумный;
  • не ломает обычный workflow;
  • оставляет evidence;
  • ограничивает blast radius;
  • соответствует роли агента;
  • documented enough for humans and agents.

Плохой guardrail:

  • существует только в prompt;
  • блокирует слишком много безопасных действий;
  • не имеет owner;
  • его легко обойти;
  • непонятно, что делать при failure;
  • не оставляет logs;
  • требует broad permissions;
  • создает ложную безопасность;
  • делает risky action silently.

Короткая формула:

text
A guardrail should make the unsafe action difficult,
visible or impossible.

Краткое резюме

Guardrails - это hard constraints вокруг AI-assisted development. Они ограничивают действия агента, требуют gates для risky operations и не позволяют критичным правилам жить только в prompt.

Основные механизмы:

  • branch protection;
  • required CI checks;
  • tool permissions;
  • approval gates;
  • protected paths;
  • environment separation;
  • secret scanning;
  • deployment gates;
  • documented override policy.

Hooks запускают automation. Guardrails задают boundaries. CI подтверждает deterministic checks. Reviewer проверяет смысл и diff. Human approves risk.

Главный принцип:

text
Do not rely on agent memory for safety-critical rules.
Move critical rules into enforceable boundaries.

Итоговый artifact для модуля:

text
docs/development/guardrails.md

Он должен описывать, какие правила являются prompt-level, какие enforced, где стоят gates, кто owner и как работает override.

Вопросы для самопроверки

  1. Чем guardrail отличается от prompt rule и hook?
  2. Почему запрет "не пушить в main" лучше enforce'ить branch protection, а не только prompt'ом?
  3. Какие tool permissions нужны Planner, Implementer, Reviewer и Release Agent?
  4. Какие действия должны требовать human approval в AI-assisted development?
  5. Как перевести правило "не добавляй dependency без необходимости" в enforceable guardrail?

Что дальше

В следующем модуле мы перейдем к observability и evals. Hooks и guardrails делают workflow контролируемым, но затем нужно измерять, как он работает: какие agent runs успешны, где происходят failures, какие guardrails чаще всего срабатывают, сколько стоят retries и какие evals помогают ловить regression в agent process.

Обновлено 03.10.2026