Python Junior a
Примеры правил AI
Ответы
Ниже — практические, “живые” примеры. Они написаны так, чтобы их можно было положить в репозиторий и реально использовать. Формат и содержание можно адаптировать под ваш стек (у вас часто FastAPI + SQLAlchemy + Alembic + Docker/Swarm). --- ## Пример `agents.md` ```md # agents.md — Team AI Orchestration Rules ## Goals - Keep architectural integrity: layering, boundaries, DB invariants. - Use Plan → Execute → Review for any non-trivial change. - Produce code that is testable, deployable, and migration-safe. ## Operating Mode (MANDATORY) ### 1) Plan Before writing code, provide: - Problem statement (1–2 sentences) - Proposed approach (bullets) - Alternatives considered (at least 1) - Risk list (data loss, race conditions, migrations, performance) - Execution steps (ordered checklist) - Test plan (unit/integration, edge cases) ### 2) Execute - Implement strictly per approved plan. - If a new assumption arises, stop and update the plan section first. - Keep diffs small and reviewable. ### 3) Review - Re-check against plan. - Verify invariants, transaction boundaries, idempotency. - Ensure observability: logs/metrics/alerts if relevant. ## Agent Roles ### Planner Responsibilities: - Produce Plan section. - Identify missing requirements and risks. Constraints: - No code beyond pseudocode. Output format: - Markdown with headings: Problem / Approach / Alternatives / Risks / Steps / Tests. ### Implementer Responsibilities: - Write code + tests per plan. Constraints: - No architectural changes without returning to Planner mode. - Must include error handling and logging conventions. Output format: - Provide a file list + code blocks per file. ### Reviewer Responsibilities: - Find correctness, security, performance, and maintenance issues. - Demand changes if plan is violated. Checklist: - SQL/ORM correctness, N+1, indexes - Migrations reversible, safe defaults - Backward compatibility for APIs - Idempotency for jobs/consumers - Secrets not logged ## Repo Conventions (Example) - Python: ruff + mypy (strict-ish) - DB: Alembic only; migrations must be reversible where possible - API: FastAPI; pydantic schemas; no business logic in routers - Logging: structured logs, correlation id from request headers ## Output Requirements - Always include: “Files changed” + “How to run tests” + “Rollback notes”. - If touching DB schema: include a migration plan + verification queries. ``` --- ## Пример `CLAUDE.md` (аналог “project constitution”) ```md # CLAUDE.md — Project Engineering Constitution ## Architecture - Layering: - app/api: HTTP layer only (routing, schemas, auth) - app/domain: business logic (pure functions/services) - app/infra: DB, external services, brokers - Domain must not import infra directly (use interfaces/ports). - Side effects only in infra layer. ## Database Rules (PostgreSQL) - Use SQLAlchemy ORM + Alembic migrations. - All schema changes must: - be backward compatible for at least 1 release when feasible - avoid table rewrites for large tables (prefer add nullable + backfill + set NOT NULL) - Always define indexes for: - FK columns used in joins - columns used in WHERE filters for hot paths - Avoid N+1 queries: use selectinload/joinedload explicitly. ## Transactions & Consistency - Transaction boundary: - request handler starts unit-of-work - domain service uses a session passed in - For multi-store (e.g., PostgreSQL + YDB): - do NOT attempt distributed transactions - use Outbox pattern (exactly-once effect via idempotency keys) ## Migrations Playbook - Prefer additive migrations: 1) add column nullable 2) backfill in batches (job or SQL) 3) add constraints (NOT NULL, FK) after verification - Every migration must include a downgrade unless explicitly prohibited. ## API Standards - REST-ish paths; consistent naming. - Error format: { "error": { "code": "...", "message": "...", "details": ... } } - Do not break response schema without versioning or compatibility layer. ## Observability - Log levels: debug for dev, info for business events, warning for recoverable issues, error for failures. - Never log secrets, tokens, or PII. ## Definition of Done - Tests added/updated - Migration safe + verified - Lint/format/mypy passes - Deployment notes included (rolling update constraints) ``` --- ## Пример кастомных skills/плагинов Здесь логика такая: вы делаете “инструменты” (скрипты/утилиты) и описываете их так, чтобы AI-агенты могли ими пользоваться в рамках процесса. Ниже — 3 реалистичных примера. ### 1) Skill: “DB Schema Guard” (проверка миграций на опасные операции) **`skills/db_schema_guard/README.md`** ```md # db_schema_guard Purpose: - Detect dangerous migration operations: - DROP COLUMN/TABLE without feature flag window - massive table rewrite patterns - missing indexes on new FK columns How to run: - python -m skills.db_schema_guard --path alembic/versions Outputs: - exit code 1 if risky operations detected ``` **`skills/db_schema_guard/__main__.py` (упрощённый пример)** ```python import argparse import re from pathlib import Path DANGEROUS = [ re.compile(r"\bop\.drop_table\("), re.compile(r"\bop\.drop_column\("), re.compile(r"\bALTER\s+TABLE\b.*\bDROP\b", re.I), ] def main() -> int: p = argparse.ArgumentParser() p.add_argument("--path", required=True) args = p.parse_args() risky = [] for f in Path(args.path).glob("*.py"): txt = f.read_text(encoding="utf-8") for pat in DANGEROUS: if pat.search(txt): risky.append((f.name, pat.pattern)) if risky: print("RISKY MIGRATIONS FOUND:") for name, pat in risky: print(f"- {name}: matched {pat}") return 1 print("OK: no risky migration patterns detected") return 0 if __name__ == "__main__": raise SystemExit(main()) ``` Как это используется агентами: * Implementer генерирует миграцию → Reviewer запускает guard → если red flag, возвращает задачу в Plan. --- ### 2) Skill: “OpenAPI Contract Linter” (соглашения API) **`skills/openapi_lint/README.md`** ```md # openapi_lint Checks: - all endpoints have tags - error responses contain standard schema - no breaking changes vs baseline (optional) Run: - python -m skills.openapi_lint --spec openapi.json ``` Идея: из FastAPI можно экспортировать OpenAPI JSON, прогнать линтер и заблокировать PR, если нарушены правила. --- ### 3) Skill: “Outbox Consistency Check” (для multi-store) **`skills/outbox_check/README.md`** ```md # outbox_check Goal: - Validate that any domain write touching "aggregate" tables also writes an outbox event in the same transaction. How: - grep-based heuristic + optional runtime tests Run: - python -m skills.outbox_check --src app/ ``` Да, это может быть эвристика (grep/AST), но для больших команд часто и это даёт пользу: ловит “забыли добавить outbox” на раннем этапе. --- ## Как это обычно собирают вместе Минимальный “командный пакет”: * `agents.md` — правила работы агентов и формат процесса * `CLAUDE.md` — архитектурная конституция (инварианты) * `skills/` — утилиты, которые: * проверяют миграции * валидируют API-контракт * enforce-ят паттерны (outbox, идемпотентность, индексы) --- Если хотите — могу сделать это “под вас” в более точном виде: под FastAPI/SQLAlchemy/Alembic + Docker Swarm (rolling update, migrate job, healthchecks) и добавить конкретные чек-листы (например, “как безопасно добавлять NOT NULL” или “как обновлять сервис без даунтайма”).