Зачем это нужно
В прошлом уроке мы разобрали hooks:
Event
-> Hook command
-> Result
-> Continue, fix, stop or ask approval
Hooks помогают запускать повторяемые проверки в нужный момент. Но hooks не отвечают на весь вопрос безопасности agent workflow.
Есть правила, которые нельзя оставлять только в prompt:
Не пушить напрямую в main.
Не deploy'ить без approval.
Не удалять production data.
Не менять billing settings.
Не расширять tool permissions без review.
Не мержить, если CI failed.
Не давать reviewer'у write tools.
Если это написано только в инструкции агенту, правило слабое.
Почему?
- агент может забыть;
- агент может неверно оценить риск;
- prompt может конфликтовать с другой инструкцией;
- user может попросить "сделай быстро, проверки потом";
- модель может уверенно объяснить, почему исключение допустимо;
- tool может позволять действие, которое процесс запрещает.
Guardrail нужен, чтобы критичное правило стало границей системы:
Agent may decide what to propose.
System decides what is allowed.
Главная мысль урока:
Критичные ограничения должны enforce'иться системой,
а не только существовать как просьба к LLM.
Основная идея
Guardrail - это ограничение, которое не просто просит агента вести себя правильно, а меняет среду так, чтобы опасное действие:
- было невозможно;
- было заблокировано;
- требовало approval;
- оставляло audit trail;
- попадало в review;
- не могло пройти merge/deploy gate.
Плохой вариант:
Prompt:
"Никогда не пушь напрямую в main."
Лучше:
Branch protection:
- direct push to main disabled;
- PR required;
- required CI checks;
- required reviewer approval.
Prompt все еще нужен. Он объясняет агенту expected behavior.
Но prompt не должен быть единственной защитой:
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 может принимать решения внутри задачи:
Какой файл прочитать?
Какую функцию изменить?
Какие tests запустить?
Как сформулировать diff summary?
Какой refactor предложить?
Но есть решения, которые лучше не оставлять на усмотрение агента:
Можно ли 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. |
Принцип:
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. |
Хороший процесс комбинирует уровни.
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
Эта схема показывает важную идею:
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. |
Пример связки:
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.
Правило:
Не пушить напрямую в main.
Как prompt:
Agent, never push directly to main.
Проблема:
- агент может забыть;
- human может ошибиться;
- tool может выполнить push;
- exception может стать привычкой;
- audit trail будет слабым.
Как guardrail:
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:
git push origin main
remote rejected.
Это и есть hard constraint.
Branch Protection В Agent Development
Для AI-assisted development branch protection особенно важен, потому что агент может быстро дойти до команды "commit/push/merge" без человеческой паузы.
Минимальная policy:
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.
Для учебного проекта это можно упростить:
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, который говорит:
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.
Важно:
CI should call the same repo-level verification entry point when practical.
Например:
Local:
./scripts/verify
CI:
./scripts/verify
Так agent, human и CI используют один contract.
CI as gate сильнее, чем локальный hook, потому что CI:
- работает в clean environment;
- не зависит от локального состояния агента;
- имеет central logs;
- виден reviewer'у;
- может быть required для merge.
Но CI не решает все:
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, он потенциально может его использовать.
Правило:
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 должен отвечать:
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. |
Принцип:
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.
Пример:
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:
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 не означает "нельзя менять". Он означает:
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:
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:
Можно продолжать?
Он не говорит, что человек разрешает.
Secrets Guardrails
Secrets - один из самых частых рисков в agent workflow.
Prompt rule:
Не коммить secrets.
Guardrails:
- secret scan in hook;
- secret scan in CI;
- masked logs;
.envexcluded 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.
Важно:
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:
User pastes production API key into prompt.
Agent writes it into config.
BeforeCommit does not scan secrets.
Хороший workflow:
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:
Не трогай 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.
Особенно важно:
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:
Не удаляй важные файлы.
Guardrails:
- destructive commands require approval;
rm -rfне выполняется без explicit permission;- protected paths cannot be deleted without review;
- database
DROP/DELETEmigrations require approval; - branch deletion disabled for protected branches;
- backups/rollback plan required before data deletion;
- diff review highlights deleted files.
Пример local policy:
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:
Не трать много денег.
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:
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:
Не добавляй новые зависимости без необходимости.
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 может говорить:
Allowed:
- use existing project dependencies.
Requires approval:
- adding runtime dependency;
- major upgrade;
- changing package manager;
- adding external service SDK.
Dependency guardrail защищает от scope creep:
Small feature should not silently become supply-chain decision.
Migration Guardrails
Database migrations требуют отдельного внимания.
Prompt rule:
Будь осторожен с миграциями.
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:
Migration:
Purpose:
Schema changes:
Data changes:
Backward compatibility:
Rollback or roll-forward:
Commands tested:
Risks:
Approval needed from:
Даже в 101 курсе важно дать студенту привычку:
Migration is not just another file edit.
Deploy Guardrails
Deploy - это переход из engineering world в user-facing world.
Prompt rule:
Не 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:
Before production deploy:
- commit is from protected branch;
- CI passed;
- migration status checked;
- smoke tests passed;
- owner approval recorded;
- rollback plan documented.
Deploy guardrails часто выходят за рамки локального курса, но принцип нужен уже здесь:
Agent can prepare release.
Agent should not silently release to users.
Reviewer Guardrails
В модуле 11 мы говорили, что reviewer должен быть independent.
Guardrail для reviewer:
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:
Reviewer, не исправляй код.
Guardrail:
Reviewer session has no write tools.
Review output must be findings, not patch.
Если reviewer должен сделать fix, workflow должен явно поменять state:
Review -> ChangesRequested -> Implementer Fix
или:
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.
Пример:
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
Главная практическая техника урока:
Take a prompt rule.
Ask how it can fail.
Move the rule into system boundary where practical.
Шаблон:
Prompt rule:
Failure mode:
Better guardrail:
Enforcement point:
Evidence:
Override policy:
Пример:
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.
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
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:
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:
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:
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:
Use the ticket tool carefully.
Guardrail:
Ticket creation tool requires:
- explicit user approval;
- target project allowlist;
- dry-run preview;
- idempotency key;
- audit log.
Это гораздо надежнее.
Guardrails Для File Scope
AI agent часто ошибается не в том, что "сломал все", а в том, что сделал слишком много.
Prompt rule:
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.
Пример:
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:
Не ослабляй тесты ради 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:
Tests changed:
- file:
- reason:
- new scenario:
- removed scenario:
- why removal is safe:
Если agent меняет tests and implementation in one diff, reviewer должен смотреть особенно внимательно:
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:
Не отключай проверки.
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:
Tests fail.
Agent edits CI to skip the failing job.
CI becomes green.
Guardrail:
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:
Be careful when using tools.
Guardrail:
The tool cannot execute write action without approval token.
Overrides
Иногда guardrail нужно обойти. Это должно быть редким и видимым.
Bad override:
CI failed, but probably unrelated. Merging anyway.
Good override:
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.
Правило:
Override is a controlled exception,
not a convenient shortcut.
Guardrails И User Requests
Иногда user прямо просит сделать risky action:
Сделай force push.
Удаляй старую директорию.
Задеплой сразу.
Отключи падающий тест.
Дай агенту доступ к billing.
Agent should not treat user request as automatic permission if project guardrail requires explicit approval or context.
Правильная реакция:
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 конкретным:
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 должен фиксировать:
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
Плохо:
Prompt says:
"Do not merge if tests fail."
Но branch protection не настроена, CI optional, reviewer не видит test result.
Лучше:
Merge blocked unless required CI checks pass.
Ошибка 2. Слишком Широкие Tool Permissions
Плохо:
Coding agent has deploy, billing, database write and GitHub admin permissions.
Лучше:
Implementer has scoped repo write and test commands.
Deploy/billing/database write require separate approved role.
Ошибка 3. Reviewer Имеет Те Же Права, Что Implementer
Плохо:
Reviewer gets full write tools and starts fixing the diff.
Лучше:
Reviewer is read-only by default and outputs findings.
Ошибка 4. CI Config Не Защищен
Плохо:
Agent fixes failing CI by disabling CI job.
Лучше:
CI config is protected path and requires maintainer review.
Ошибка 5. Approval Prompt Слишком Общий
Плохо:
Approve?
Лучше:
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 Не Версионируются
Если правила живут только в устной договоренности, агент их не увидит.
Лучше:
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.
Шаблон:
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:
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.
Минимальный результат:
[ ] У каждого 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:
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.
Короткая формула:
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.
Главный принцип:
Do not rely on agent memory for safety-critical rules.
Move critical rules into enforceable boundaries.
Итоговый artifact для модуля:
docs/development/guardrails.md
Он должен описывать, какие правила являются prompt-level, какие enforced, где стоят gates, кто owner и как работает override.
Вопросы для самопроверки
- Чем guardrail отличается от prompt rule и hook?
- Почему запрет "не пушить в main" лучше enforce'ить branch protection, а не только prompt'ом?
- Какие tool permissions нужны Planner, Implementer, Reviewer и Release Agent?
- Какие действия должны требовать human approval в AI-assisted development?
- Как перевести правило "не добавляй dependency без необходимости" в enforceable guardrail?
Что дальше
В следующем модуле мы перейдем к observability и evals. Hooks и guardrails делают workflow контролируемым, но затем нужно измерять, как он работает: какие agent runs успешны, где происходят failures, какие guardrails чаще всего срабатывают, сколько стоят retries и какие evals помогают ловить regression в agent process.