Agent Dev 101

Модуль 06 · Урок 6.3

Урок 6.3. Как писать SKILL.md

На этой странице
  1. Зачем это нужно
  2. Основная идея
  3. Ключевые термины
  4. Анатомия skill directory
  5. Минимальный SKILL.md
  6. Frontmatter: только нужная metadata
  7. Почему description критичен
  8. Имена skills
  9. Базовая структура SKILL.md
  10. Как писать Purpose
  11. Inputs
  12. Preconditions
  13. Context To Read
  14. Procedure
  15. Степень свободы
  16. Constraints
  17. Verification
  18. Failure Handling
  19. Output
  20. Схема работы skill
  21. Когда нужен какой developer skill
  22. Prompts для использования skills
  23. Prompts для написания skills
  24. Пример 1: create-api-endpoint
  25. Пример 2: fix-bug-with-regression-test
  26. Пример 3: review-code-against-spec
  27. Пример 4: create-db-migration
  28. Что выносить в references
  29. Когда добавлять scripts
  30. Когда skill должен ссылаться на MCP или tools
  31. Как не раздуть SKILL.md
  32. Best practices по написанию SKILL.md
  33. Процесс создания skill
  34. Частые анти-паттерны
  35. Checklist качества SKILL.md
  36. Практика: написать create-api-endpoint skill
  37. Skill pack как инженерная библиотека
  38. Критерии готовности
  39. Краткое резюме
  40. Вопросы для самопроверки
  41. Что дальше

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

В предыдущих уроках мы договорились: skill - это не магическая кнопка и не длинный prompt на все случаи жизни. Skill хранит повторяемую процедуру, которую агент может применить, когда задача похожа на уже известный инженерный workflow.

Теперь нужно научиться писать главный файл skill - SKILL.md.

Плохой SKILL.md делает агента менее предсказуемым:

  • skill срабатывает не тогда, когда нужно;
  • агент читает много лишнего контекста;
  • процедура расплывчатая и каждый раз исполняется по-разному;
  • verification описан словами, но не превращается в действие;
  • skill смешивает project rules, product requirements, architecture docs и scripts.

Хороший SKILL.md делает обратное:

  • точно объясняет, когда skill нужен;
  • дает агенту короткую, но полную процедуру;
  • задает границы изменений;
  • говорит, что прочитать перед работой;
  • говорит, чем проверить результат;
  • заставляет агента остановиться, если входных данных недостаточно.

Главная цель урока - научиться писать SKILL.md как инженерный operational document: компактный, проверяемый, повторяемый и удобный для агента.

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

SKILL.md должен отвечать на один вопрос:

text
Как агенту надежно выполнять этот повторяемый тип работы?

Не "что такое REST API". Не "как устроен весь проект". Не "какие фичи нужны продукту". Не "что делать в любой ситуации".

Skill должен быть достаточно конкретным, чтобы снижать вариативность, но не настолько жестким, чтобы ломаться на каждом проекте.

Хорошая формула:

text
Skill = trigger + reusable procedure + context routing + constraints + verification + output contract

Где:

  • trigger помогает агенту понять, когда skill использовать;
  • procedure задает порядок действий;
  • context routing говорит, какие файлы читать и когда;
  • constraints защищают от лишних изменений;
  • verification превращает "проверь" в конкретные команды и критерии;
  • output contract делает итог работы понятным пользователю.

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

Термин Значение
SKILL.md Основной файл skill с metadata и инструкциями.
Frontmatter YAML-блок в начале файла. Обычно содержит name и description.
name Машиночитаемое имя skill. Лучше короткое, конкретное, в kebab-case.
description Главный trigger: агент использует его, чтобы понять, когда skill применять.
Body Markdown-инструкции, которые загружаются после выбора skill.
Procedure Пошаговый workflow для выполнения задачи.
Preconditions Что должно быть известно до начала работы.
Constraints Что агент не должен нарушать во время выполнения.
Verification Команды, тесты и проверки, подтверждающие результат.
Failure Handling Когда агент должен остановиться, запросить уточнение или выбрать безопасный fallback.
References Дополнительные документы, которые skill предлагает читать только при необходимости.
Scripts Исполняемые помощники для повторяемых или хрупких действий.
Assets Шаблоны, примеры, boilerplate, изображения или другие файлы, используемые в результате.

Анатомия skill directory

Минимальный skill:

text
skills/
└── create-api-endpoint/
    └── SKILL.md

Skill с дополнительными ресурсами:

text
skills/
└── create-api-endpoint/
    ├── SKILL.md
    ├── references/
    │   ├── api-style.md
    │   └── error-handling.md
    ├── scripts/
    │   └── verify-api-change.sh
    └── assets/
        └── endpoint-test.template.ts

Главный принцип: SKILL.md хранит только ядро процедуры. Все длинное, редкое, вариативное или детальное лучше вынести в дополнительные файлы.

Часть Когда нужна Что хранить
SKILL.md Всегда Trigger, core workflow, constraints, verification, stop conditions.
references/ Когда есть длинные project/domain docs API style guide, database schema notes, design examples, policy.
scripts/ Когда действие повторяемое или должно быть детерминированным Validation, generators, format converters, static checks.
assets/ Когда skill использует готовые файлы Templates, boilerplate, snippets, document templates, icons.

Если в проекте уже принято имя templates/, можно использовать его. Но для переносимости удобно считать templates частью assets/, например assets/templates/.

Минимальный SKILL.md

Минимальный файл выглядит так:

markdown
---
name: create-api-endpoint
description: Add or modify REST API endpoints in an existing backend project. Use when Codex needs to implement controller/route changes, request validation, service integration, API tests, or OpenAPI contract updates for a specific endpoint.
---

# Create API Endpoint

## Procedure

1. Read the feature specification and acceptance criteria.
2. Find the closest existing endpoint pattern in the repository.
3. Identify affected layers: route, controller, service, validation, persistence, tests, contract.
4. Add or update tests before implementation when practical.
5. Implement the smallest scoped change that satisfies the specification.
6. Run targeted tests and any contract checks available in the project.
7. Report changed files, verification commands, and acceptance criteria status.

Такой skill уже полезен, но для реального курса этого мало. В нем не хватает inputs, constraints, failure handling и output contract.

Frontmatter: только нужная metadata

В базовом переносимом варианте frontmatter skill должен быть минимальным:

markdown
---
name: create-api-endpoint
description: Add or modify REST API endpoints in an existing backend project. Use when Codex needs to implement controller/route changes, request validation, service integration, API tests, or OpenAPI contract updates for a specific endpoint.
---

Главные поля:

Поле Зачем нужно
name Стабильное имя skill. Используется в списках, prompts, каталогах и тестах.
description Основной механизм выбора skill. Должен объяснять, что skill делает и когда его использовать.

Не добавляйте в YAML случайные поля вроде version, owner, examples, tools, tags, если конкретная agent platform не требует их официально. Лишняя metadata часто создает ложное ощущение контроля: автор думает, что агент использует поле, хотя runtime может его просто игнорировать.

Если платформа поддерживает отдельную UI metadata, например файл рядом со skill, относитесь к нему как к адаптеру. Source of truth все равно должен оставаться в SKILL.md: имя, trigger description и operational procedure.

Почему description критичен

Во многих agent systems сначала доступна только metadata skill: name и description. Полный body загружается позже, когда агент уже решил, что skill подходит.

Следствие:

text
Если trigger conditions спрятаны внутри body, агент может не открыть skill вообще.

Поэтому description должен содержать:

  • что skill делает;
  • когда его использовать;
  • типы задач, для которых он подходит;
  • важные negative triggers, если skill легко спутать с другим.

Плохой пример:

markdown
---
name: api
description: Helps with API work.
---

Проблемы:

  • имя слишком широкое;
  • непонятно, REST это, GraphQL или external API client;
  • непонятно, skill для implementation, review или documentation;
  • агент может применить его почти ко всему.

Хороший пример:

markdown
---
name: create-api-endpoint
description: Add or modify REST API endpoints in an existing backend service. Use when a task requires route/controller changes, request validation, service-layer integration, API tests, OpenAPI updates, or endpoint-level acceptance criteria. Do not use for generic API design discussions or external API client troubleshooting.
---

Здесь есть:

  • действие: add or modify;
  • область: REST API endpoints;
  • контекст: existing backend service;
  • triggers: route/controller, validation, tests, OpenAPI;
  • negative trigger: не для generic design discussions.

Имена skills

Имя skill должно быть коротким и конкретным.

Рекомендуемый стиль:

text
verb-noun
verb-domain-noun
tool-action-object

Примеры:

Хорошее имя Почему хорошо
create-api-endpoint Действие и объект понятны.
fix-bug-with-regression-test В имени есть ключевой engineering principle.
review-code-against-spec Ясно, что review идет относительно specification.
create-db-migration Конкретный workflow.
update-openapi-contract Узкая повторяемая задача.
write-technical-lesson Понятный content workflow.

Слабые имена:

Слабое имя Проблема
backend Слишком широко.
api-helper Неясно, implementation это или review.
good-code Абстрактно.
project-workflow Слишком много всего.
super-dev-agent Не описывает задачу.

Практическое правило:

text
Если skill нельзя уверенно вызвать одной фразой "Use <name> to ...",
скорее всего имя слишком размытое.

Базовая структура SKILL.md

Для developer skills удобно использовать такой шаблон:

markdown
---
name: skill-name
description: One precise sentence about what the skill does. Use when Codex needs to ... Include concrete trigger contexts. Add negative trigger if confusion is likely.
---

# Skill Title

## Purpose

Explain the workflow this skill standardizes in 2-4 sentences.

## Inputs

- Required input 1.
- Required input 2.
- Optional input.

## Preconditions

- What must be known before editing.
- Which project files or specs should exist.
- Which permissions or tools may be needed.

## Context To Read

1. Read the task or feature specification.
2. Read the nearest existing implementation pattern.
3. Read linked references only when the task matches them.

## Procedure

1. Step one.
2. Step two.
3. Step three.

## Constraints

- Do not change unrelated modules.
- Do not introduce new dependencies unless the task explicitly requires it.
- Preserve public contracts unless the spec says otherwise.

## Verification

- Run the most targeted tests first.
- Run broader checks when the change touches shared behavior.
- If a check cannot be run, explain why and describe residual risk.

## Failure Handling

Stop and ask for clarification when:

- Required acceptance criteria are missing.
- The requested change conflicts with an existing contract.
- The safe implementation path requires destructive migration or production access.

## Output

Return:

- summary of changes;
- changed files;
- verification commands and results;
- acceptance criteria status;
- unresolved risks or follow-up tasks.

Не каждый skill обязан иметь все эти секции, но для курса этот шаблон хорош: он дисциплинирует автора и делает поведение агента проверяемым.

Как писать Purpose

Purpose отвечает на вопрос:

text
Какую повторяемую работу нормализует этот skill?

Хороший Purpose короткий. Он не повторяет весь description, а объясняет смысл процедуры.

Пример:

markdown
## Purpose

Use this skill to implement backend API endpoints with tests and contract checks. The goal is to keep endpoint work scoped, aligned with existing project architecture, and verifiable through targeted tests.

Плохой Purpose:

markdown
## Purpose

APIs are very important in modern software development. REST APIs allow clients and servers to communicate. This skill explains what APIs are, why validation matters, and how backend engineering works.

Проблема: это лекция, а не operational procedure. Агенту не нужно повторно читать вводный курс по API каждый раз, когда он добавляет endpoint.

Inputs

Inputs перечисляет, что нужно дать агенту для успешного выполнения workflow.

Для create-api-endpoint:

markdown
## Inputs

- Feature specification or issue with endpoint behavior.
- HTTP method and path, if already known.
- Request and response schema.
- Authentication and authorization expectations.
- Acceptance criteria.
- Existing API contract location, if the project has one.

Inputs помогают не только агенту, но и пользователю. Они превращают vague request:

text
Сделай endpoint для проектов.

в управляемый request:

text
Use `create-api-endpoint`.
Spec: specs/features/create-project.md.
Endpoint: POST /api/projects.
Add request validation, service test, API test, and OpenAPI update.
Do not change authorization rules outside this endpoint.

Preconditions

Preconditions описывает условия, без которых агент не должен уверенно начинать работу.

Примеры:

markdown
## Preconditions

- The repository has an existing API layer or routing convention.
- The requested endpoint behavior is specified through acceptance criteria.
- The target test framework can be discovered from existing tests.
- Authorization behavior is explicit in the spec or in an existing analogous endpoint.

Preconditions важны для предсказуемости. Они не дают агенту "додумать" critical requirements.

Типичные preconditions для developer skills:

Skill Preconditions
create-api-endpoint Есть spec, path/method или понятная product intent, найден похожий endpoint.
create-db-migration Ясна schema change, есть migration framework, понятны rollback или compatibility rules.
fix-bug-with-regression-test Есть bug description, reproduction path или failing scenario.
review-code-against-spec Есть diff и spec, с которым сравнивать поведение.
update-openapi-contract Есть endpoint behavior и место хранения contract.

Context To Read

Skill не должен говорить "прочитай весь проект". Он должен направлять агента к релевантному контексту.

Хороший context routing:

markdown
## Context To Read

1. Read the user task and linked feature specification first.
2. Find 1-2 closest existing endpoint implementations.
3. Read only the framework-specific reference if the project pattern is ambiguous:
   - `references/express.md` for Express projects.
   - `references/fastapi.md` for FastAPI projects.
   - `references/rails.md` for Rails projects.
4. Do not load all references by default.

Это пример progressive disclosure. SKILL.md остается коротким, а framework details лежат отдельно.

Плохой context routing:

markdown
Read the whole repository and all documentation before doing anything.

Проблема: дорого, медленно, шумно и не гарантирует качества.

Procedure

Procedure - сердце skill. Она должна быть пошаговой, но не механической до абсурда.

Для developer skills почти всегда полезен порядок:

  1. Понять задачу.
  2. Найти локальный pattern.
  3. Определить минимальный scope.
  4. Написать или обновить tests.
  5. Реализовать изменение.
  6. Запустить verification.
  7. Вернуть результат в понятном формате.

Пример:

markdown
## Procedure

1. Read the feature specification and extract acceptance criteria.
2. Locate the closest existing implementation pattern.
3. Identify affected files before editing.
4. Add or update the smallest useful test that would fail without the change.
5. Implement the minimal code change.
6. Update public contracts or documentation only when behavior changed.
7. Run targeted verification.
8. If targeted verification passes and the change touches shared code, run broader checks.
9. Report changed files, checks, and acceptance criteria status.

Хорошая procedure не должна говорить агенту "be careful" без объяснения, как именно проявляется carefulness.

Плохо:

markdown
Be careful and write high-quality code.

Лучше:

markdown
Before adding a new abstraction, search for an existing local pattern. Reuse the existing pattern unless it conflicts with the specification or introduces duplicated behavior.

Степень свободы

Skill должен задавать правильную степень свободы. Не все workflows нужно описывать одинаково жестко.

Степень свободы Когда использовать Пример
Высокая Много допустимых решений, важны эвристики Code review, архитектурный анализ, написание лекции.
Средняя Есть preferred pattern, но детали зависят от проекта API endpoint, frontend form, bug fix.
Низкая Действие хрупкое, повторяемое, должно быть одинаковым PDF transform, migration validation, schema diff, generated files.

Для высокой свободы пишите principles и review checklist.

Для средней свободы пишите procedure, examples и constraints.

Для низкой свободы добавляйте scripts или tools.

Пример решения:

Ситуация Что писать в skill
"Добавить endpoint в разных Node/FastAPI/Rails проектах" Core procedure + references per framework.
"Каждый раз генерировать одинаковый OpenAPI diff" Procedure + script.
"Обращаться к staging database" Skill + MCP/tool policy, не просто shell snippet.
"Соблюдать UTC timestamps" Не skill, а project rule.

Constraints

Constraints защищают проект от нежелательных изменений.

Для developer workflows полезны такие ограничения:

markdown
## Constraints

- Keep changes scoped to the requested behavior.
- Do not rewrite unrelated modules.
- Do not add dependencies unless the specification or existing project pattern requires them.
- Preserve backward-compatible API behavior unless the task explicitly changes the contract.
- Prefer existing local conventions over introducing a new architecture style.
- Do not modify generated files manually unless the project expects manual edits there.

Constraints должны быть проверяемыми. Слабое ограничение:

text
Make the code good.

Сильное ограничение:

text
Do not introduce a new service abstraction if an existing service layer already handles the same entity.

Verification

Verification - это разница между "агент вроде сделал" и "изменение можно принимать".

В SKILL.md нужно указывать:

  • какие проверки запускать;
  • в каком порядке;
  • что делать, если проверку нельзя запустить;
  • когда нужна более широкая проверка.

Пример:

markdown
## Verification

1. Run the most targeted unit or integration test for the changed behavior.
2. Run API contract validation if the endpoint contract changed.
3. Run lint/typecheck if the project has cheap commands for them.
4. Run broader tests when shared validation, authentication, or persistence code changed.
5. If a command cannot be run, report the command, the reason, and the residual risk.

Для skills со scripts:

markdown
## Verification

Use `scripts/verify-api-change.sh` when the project has Node dependencies installed. Pass the endpoint test path as the first argument.

If the script fails because dependencies are missing, do not install packages without user approval. Fall back to reading package scripts and report what could not be verified.

Verification не обязан быть одним набором команд для всех проектов. Но skill должен научить агента выбирать ближайшую надежную проверку.

Failure Handling

Failure Handling нужен, чтобы агент не продолжал работу на догадках.

Пример:

markdown
## Failure Handling

Stop and ask for clarification when:

- The endpoint changes authentication or authorization and the expected policy is not specified.
- The request or response schema is ambiguous.
- The task requires a destructive database migration.
- Existing tests contradict the feature specification.
- The safe path requires credentials, production access, or external service writes.

When blocked by missing dependencies or unavailable services, continue with static inspection only if it can still produce useful progress. Report the limitation clearly.

Хороший failure handling не делает агента пассивным. Он отделяет ситуации, где можно продолжать безопасно, от ситуаций, где нельзя придумывать requirements.

Output

Output определяет, что агент должен вернуть после выполнения.

Для coding skill удобно требовать:

markdown
## Output

Return:

- concise implementation summary;
- changed files;
- tests or checks run, with results;
- acceptance criteria status;
- known limitations or follow-up tasks.

Это особенно важно в курсе управляемой разработки. Пользователь должен видеть не только "готово", но и evidence.

Схема работы skill

flowchart TD A[User Task] --> B[Skill metadata: name + description] B --> C{Trigger match?} C -- No --> D[Use normal project context] C -- Yes --> E[Load SKILL.md body] E --> F[Read required task context] F --> G{Need extra resources?} G -- References --> H[Load selected reference files] G -- Scripts --> I[Run or inspect helper scripts] G -- Assets --> J[Use templates or boilerplate] H --> K[Execute procedure] I --> K J --> K F --> K K --> L[Run verification] L --> M[Return output contract]

Главный смысл схемы: skill не должен загружать весь мир сразу. Он должен давать agent runtime навигацию по нужному контексту.

Когда нужен какой developer skill

Ниже - практическая карта для software development проектов.

Кейс Нужен skill? Какой skill Почему
Добавить типовой REST endpoint Да create-api-endpoint Повторяемый workflow: spec, pattern, tests, contract.
Исправить bug Да, если команда требует regression-first подход fix-bug-with-regression-test Агент часто чинит symptom без теста, skill снижает риск.
Провести code review Да review-code-against-spec Review имеет стабильные steps и output format.
Добавить database migration Да create-db-migration Миграции хрупкие, важны backward compatibility и verification.
Обновить README один раз Обычно нет Prompt One-off задача без устойчивой процедуры.
Всегда использовать UTC Нет Project rule Это invariant, а не workflow.
Запустить npm test Нет Tool/script Это действие, а не процедура.
Проверить production database Skill может описать процесс, но доступ нужен через tool/MCP inspect-db-safely + MCP Нужны permission boundaries и auditability.
Сгенерировать changelog по release PRs Да write-release-notes Повторяемый content workflow с источниками и форматом.
Перенести React component на design system Да migrate-component-to-design-system Нужно читать patterns, менять UI, запускать visual checks.

Prompts для использования skills

Промпт для запуска skill не должен повторять весь SKILL.md. Он должен дать задачу, артефакты, ограничения и ожидаемые проверки.

API endpoint

text
Use the `create-api-endpoint` skill.

Task: implement POST /api/projects.
Spec: specs/features/project-create.md.
Acceptance criteria: validate name, create project for current user, return 201 with project id.
Constraints: do not change existing authorization middleware.
Verification: add or update API tests and run the targeted test command.

Bug fix with regression test

text
Use the `fix-bug-with-regression-test` skill.

Bug: password reset tokens can be reused after successful reset.
Reproduction: specs/bugs/reusable-reset-token.md.
Expected behavior: consumed token must be rejected.
Start with a failing regression test, then implement the smallest fix.

Code review against specification

text
Use the `review-code-against-spec` skill.

Review the current diff against specs/features/team-invitations.md.
Focus on behavioral mismatches, missing tests, authorization gaps, and compatibility risks.
Return findings first, ordered by severity, with file and line references.

Database migration

text
Use the `create-db-migration` skill.

Task: add `last_seen_at` to users.
Compatibility: existing rows must remain valid.
Runtime requirement: deployment should not require downtime.
Verification: run migration tests or the project's schema check if available.

Frontend form workflow

text
Use the `build-frontend-form-flow` skill.

Task: add the project creation form.
Spec: specs/features/project-create.md.
Requirements: validation errors, loading state, success navigation, keyboard-accessible controls.
Match existing design system patterns.
Run targeted UI/component tests if available.

Skill selection prompt

Когда неясно, какие skills нужны проекту, можно попросить агента сделать skill map:

text
Analyze the repository and the last 10 planned development tasks.
Propose 3-5 candidate skills that would reduce repeated prompting.
For each skill, include: name, trigger description, workflow it standardizes, required references/scripts/assets, and why it should not be a rule or tool.
Do not create files yet.

Prompts для написания skills

Эти prompts полезны, когда вы создаете сам skill.

1. Найти повторяемые workflows

text
Analyze the repository docs, task plan, and existing development patterns.
Find workflows that are repeated enough to become skills.
Return a table with candidate skill name, trigger, inputs, procedure outline, verification, and required supporting files.
Do not write the skills yet.

2. Написать черновик SKILL.md

text
Write `skills/create-api-endpoint/SKILL.md`.

The skill should help an AI coding agent add or modify REST endpoints in this repository.
Include frontmatter with `name` and `description`, then Purpose, Inputs, Preconditions, Context To Read, Procedure, Constraints, Verification, Failure Handling, and Output.
Keep the skill concise and operational. Do not include generic REST API theory.

3. Улучшить description

text
Review this skill description as a trigger.
Make it specific enough that an agent will use the skill for the right tasks and avoid it for unrelated tasks.
Include concrete use cases and negative triggers when helpful.
Do not change the body yet.

4. Разделить SKILL.md и references

text
Review this SKILL.md for context bloat.
Identify content that should stay in SKILL.md and content that should move to `references/`, `scripts/`, or `assets/`.
Return the proposed file structure and explain the routing rules the skill should include.

5. Добавить verification

text
Improve the Verification and Failure Handling sections of this developer skill.
Make verification command-oriented where possible, but keep it adaptable to different project test frameworks.
Specify what the agent should report when a check cannot be run.

6. Проверить skill на реалистичном сценарии

text
Use the skill at `skills/create-api-endpoint` to implement the scenario in `specs/features/project-create.md`.
Follow the skill exactly where applicable.
After finishing, report which parts of the skill were useful, ambiguous, missing, or too verbose.

Этот prompt хорош для forward-testing: он проверяет, работает ли skill на настоящей задаче, а не красиво ли он выглядит в вакууме.

Пример 1: create-api-endpoint

Ниже пример SKILL.md для backend developer workflow.

markdown
---
name: create-api-endpoint
description: Add or modify REST API endpoints in an existing backend service. Use when a task requires route/controller changes, request validation, service-layer integration, API tests, OpenAPI contract updates, or endpoint-level acceptance criteria. Do not use for generic API design discussions or external API client troubleshooting.
---

# Create API Endpoint

## Purpose

Use this skill to implement REST API endpoint changes in a controlled, testable way. The skill standardizes how to move from feature specification to code, tests, contract updates, and verification while preserving existing project architecture.

## Inputs

- Feature specification, issue, or task description.
- HTTP method and path, if known.
- Request and response schema, if known.
- Authentication and authorization expectations.
- Acceptance criteria.
- Existing API contract location, if the project has one.

## Preconditions

- A relevant backend API layer exists or the task explicitly asks to create one.
- Expected endpoint behavior is specified enough to test.
- Authorization behavior is explicit in the spec or inferable from a directly analogous endpoint.
- The project has discoverable test, lint, or typecheck commands.

## Context To Read

1. Read the task and linked specification first.
2. Find 1-2 closest existing endpoint implementations.
3. Inspect existing tests for the same API layer.
4. Read API style references only when local code does not answer the question:
   - `references/api-style.md` for response envelope, status codes, and error shape.
   - `references/error-handling.md` for validation and exception mapping.
5. Do not read unrelated modules or all reference files by default.

## Procedure

1. Extract endpoint behavior and acceptance criteria from the spec.
2. Identify affected layers: route, controller, validation, service, persistence, tests, contract.
3. Choose the nearest existing implementation pattern and reuse it.
4. Add or update the smallest meaningful test that would fail without the new behavior.
5. Implement the endpoint with minimal scoped changes.
6. Update API contract or generated types only when endpoint behavior changed.
7. Run targeted verification.
8. If shared validation, auth, or persistence code changed, run broader checks.
9. Compare the result against every acceptance criterion.

## Constraints

- Do not rewrite unrelated API modules.
- Do not introduce new dependencies unless the spec or existing project pattern requires them.
- Do not change authentication or authorization behavior without explicit requirements.
- Preserve existing response shapes unless the endpoint contract changes.
- Prefer existing local conventions over new abstractions.

## Verification

1. Run the targeted API or integration test for the endpoint.
2. Run contract validation if OpenAPI or generated API types changed.
3. Run lint/typecheck when cheap project commands exist.
4. If a check cannot be run, report the command, the reason, and the residual risk.

## Failure Handling

Stop and ask for clarification when:

- Request or response schema is ambiguous.
- Authorization requirements are missing.
- The spec conflicts with existing public API behavior.
- The change requires destructive migration or production credentials.

When tests cannot run because dependencies are missing, do not install packages unless the user approves. Continue with static inspection only if useful.

## Output

Return:

- concise summary of implementation;
- changed files;
- verification commands and results;
- acceptance criteria status;
- unresolved risks or follow-up tasks.

Что в этом skill хорошо:

  • description работает как trigger;
  • procedure начинается со spec, а не с кода;
  • есть поиск local pattern;
  • tests идут до или рядом с implementation;
  • constraints защищают от лишнего scope;
  • failure handling запрещает додумывать auth;
  • output дает пользователю evidence.

Пример 2: fix-bug-with-regression-test

Этот skill нужен, когда команда хочет, чтобы агент не просто "починил", а сначала зафиксировал bug test.

markdown
---
name: fix-bug-with-regression-test
description: Fix software bugs by reproducing the failure with a regression test before implementation. Use when a task describes incorrect behavior, a failing scenario, production bug, flaky edge case, or regression risk. Do not use for pure refactoring or feature work without a bug scenario.
---

# Fix Bug With Regression Test

## Purpose

Use this skill to turn a bug report into a verified fix. The workflow prioritizes reproducing the bug, writing a regression test, implementing the smallest fix, and proving the bug stays fixed.

## Inputs

- Bug description.
- Expected behavior.
- Actual behavior.
- Reproduction steps, logs, failing request, or affected test.
- Relevant issue, spec, or user report.

## Preconditions

- The bug can be described as observable behavior.
- There is enough context to create or identify a failing scenario.
- The project has a test layer suitable for regression coverage, or the absence of one can be reported.

## Context To Read

1. Read the bug report and expected behavior.
2. Find the code path that owns the incorrect behavior.
3. Find existing tests around that code path.
4. Read only relevant logs or fixtures needed to reproduce the bug.

## Procedure

1. Restate the bug as expected behavior versus actual behavior.
2. Identify the smallest observable failing scenario.
3. Add or update a regression test that fails without the fix.
4. Run the targeted test if practical and capture the failure.
5. Implement the smallest fix in the owning code path.
6. Run the regression test again.
7. Run nearby tests when shared behavior changed.
8. Check that the fix does not mask the symptom while leaving the cause.

## Constraints

- Do not rewrite broad modules while fixing a narrow bug.
- Do not delete or weaken existing tests to make the suite pass.
- Do not change public behavior beyond the expected fix unless the spec requires it.
- Prefer a focused regression test over only manual verification.

## Verification

- Targeted regression test passes.
- Nearby tests for the same module pass when available.
- The final report names the test that would fail without the fix.

## Failure Handling

Stop and ask for clarification when:

- Expected behavior is unclear.
- The bug requires production-only data that is not available.
- The reproduction steps contradict the specification.

If no test framework exists for the affected behavior, report that limitation and provide the closest available verification path.

## Output

Return:

- bug summary;
- regression test added or updated;
- implementation summary;
- verification results;
- remaining risk.

Этот skill особенно полезен для junior-friendly agent workflows. Он защищает от частой ошибки: агент правит код сразу, а потом объясняет, что "проверил логически".

Пример 3: review-code-against-spec

Этот skill нужен для review-агента или для одного агента, который сам себя проверяет отдельным проходом.

markdown
---
name: review-code-against-spec
description: Review code changes against a feature specification, task plan, or acceptance criteria. Use when Codex needs to inspect a diff for behavioral mismatches, missing tests, regressions, security-sensitive gaps, compatibility risks, or scope creep. Do not use for style-only proofreading.
---

# Review Code Against Spec

## Purpose

Use this skill to perform a behavior-focused engineering review. The review should prioritize correctness, regressions, missing tests, and mismatch with the specification over cosmetic feedback.

## Inputs

- Code diff or changed files.
- Feature specification, task description, or acceptance criteria.
- Relevant architecture constraints or ADRs.
- Test results, if available.

## Preconditions

- There is a concrete change to review.
- There is a spec, issue, task, or acceptance criteria to compare against.
- The reviewer can inspect changed files and relevant surrounding code.

## Context To Read

1. Read the spec or task first.
2. Inspect the diff and changed files.
3. Read surrounding code only when needed to confirm behavior.
4. Read tests related to the changed behavior.
5. Read ADRs or architecture constraints only when the change touches architecture boundaries.

## Procedure

1. Extract the intended behavior and acceptance criteria.
2. Map each acceptance criterion to changed code and tests.
3. Look for behavior that is missing, incorrectly implemented, or over-implemented.
4. Check error handling, boundary cases, authorization, data compatibility, and rollback risk where relevant.
5. Check whether tests would fail if the main behavior were broken.
6. Report findings first, ordered by severity.
7. Include file and line references for each finding when possible.
8. Keep summaries brief and secondary.

## Constraints

- Do not praise the code before listing findings.
- Do not report speculative issues without a concrete failure path.
- Do not require unrelated refactors.
- Do not treat style preferences as correctness findings.
- Do not rewrite the code during review unless explicitly asked.

## Verification

- Every finding should connect to spec mismatch, bug risk, missing test, compatibility issue, or security-sensitive behavior.
- If no issues are found, state that clearly and mention remaining test gaps or residual risk.

## Failure Handling

Ask for clarification when the diff or spec is missing. If only one is available, perform a limited review and label the limitation explicitly.

## Output

Return:

- findings first, ordered by severity;
- file and line references;
- open questions or assumptions;
- brief summary only after findings;
- test gaps or residual risk.

Этот skill показывает важную мысль: не все developer skills пишут код. Некоторые стабилизируют review, planning, debugging, release и verification.

Пример 4: create-db-migration

Для database migration skill часто нужна более низкая степень свободы, потому что ошибки могут повредить данные или сломать deployment.

markdown
---
name: create-db-migration
description: Create safe database schema migrations for an existing application. Use when a task requires adding, changing, backfilling, indexing, or removing database fields, tables, constraints, or schema-derived types. Do not use for ad hoc SQL analysis or production database inspection.
---

# Create DB Migration

## Purpose

Use this skill to implement database schema changes with compatibility and verification in mind. The workflow should protect existing data, deployment safety, and application code that depends on the schema.

## Inputs

- Requested schema change.
- Affected entity or table.
- Compatibility requirements.
- Backfill expectations, if any.
- Rollback expectations, if any.

## Context To Read

1. Read the feature or migration spec.
2. Inspect existing migration naming and ordering.
3. Inspect current schema definition and affected model/entity code.
4. Inspect tests or fixtures that depend on the schema.

## Procedure

1. Classify the migration as additive, destructive, backfill, index, constraint, or rename.
2. Prefer backward-compatible additive changes when possible.
3. Create migration using the project's existing migration tool and naming convention.
4. Update application code and schema-derived types only as required.
5. Add or update tests for behavior affected by the schema.
6. Run migration verification and targeted tests.
7. Report deployment or rollback risks.

## Constraints

- Do not write destructive migrations without explicit approval.
- Do not assume production data shape unless documented.
- Do not manually edit generated schema artifacts unless the project expects it.
- Do not combine unrelated schema changes in one migration.

## Verification

- Run the project's migration check or schema diff command when available.
- Run targeted tests for affected models/services.
- If database tooling is unavailable, inspect migration syntax and report the unverified command.

## Failure Handling

Stop and ask for clarification when:

- The migration is destructive.
- Backfill behavior is unspecified.
- Existing data may violate a new constraint.
- The migration requires production credentials or live database access.

## Output

Return changed files, migration name, verification results, compatibility notes, and rollback concerns.

Здесь видно, почему один и тот же формат SKILL.md может давать разные guardrails. Для API endpoint достаточно средней свободы, для migration нужны более жесткие stop conditions.

Что выносить в references

references/ нужны, когда подробная информация полезна не всегда.

Примеры:

text
skills/create-api-endpoint/
├── SKILL.md
└── references/
    ├── express.md
    ├── fastapi.md
    ├── rails.md
    └── api-style.md

В SKILL.md должно быть написано, когда читать каждый файл:

markdown
## Context To Read

Read `references/express.md` only for Express projects.
Read `references/fastapi.md` only for FastAPI projects.
Read `references/api-style.md` when local endpoint examples do not clarify response format.

Best practices для references:

  • не дублировать одно и то же в SKILL.md и reference;
  • не делать цепочки ссылок на 4 уровня;
  • держать reference файлы рядом с skill;
  • для длинных reference файлов добавлять table of contents;
  • писать routing instruction в SKILL.md, иначе агент может не узнать, что reference существует;
  • хранить в references schema notes, API conventions, domain policies, framework variants, examples.

Когда добавлять scripts

Scripts нужны, когда текстовая инструкция регулярно превращается в одинаковый код или команду.

Добавляйте scripts/, если:

  • действие повторяется часто;
  • ошибка в ручной реализации дорогая;
  • нужна deterministic validation;
  • agent каждый раз переписывает один и тот же helper;
  • формат файла сложный;
  • результат удобно проверять машинно.

Не добавляйте script, если:

  • задача хорошо решается одной существующей командой проекта;
  • script будет использоваться один раз;
  • script требует secrets или production access;
  • script скрывает важные решения, которые агент должен понимать;
  • script будет сложно поддерживать.

Пример:

text
skills/create-api-endpoint/
└── scripts/
    └── detect-api-test-command.sh

Фрагмент инструкции в SKILL.md:

markdown
## Verification Helpers

Use `scripts/detect-api-test-command.sh` to suggest a targeted API test command when the project has known package scripts. Inspect the suggested command before running it. If the script cannot identify a command, fall back to reading package scripts and nearby test files.

Важно: script внутри skill не дает агенту новых permissions. Он просто лежит рядом как bundled helper. Если capability требует внешнего доступа, authentication, scopes или auditability, лучше думать о tool/MCP.

Когда skill должен ссылаться на MCP или tools

Skill может описывать, как использовать tool, но tool должен быть предоставлен agent runtime отдельно.

Пример:

text
Skill: inspect-db-safely
Tool/MCP: query read-only staging database

В SKILL.md можно написать:

markdown
## Tool Usage

Use the read-only database query tool only after identifying the exact table and columns from the schema resource. Do not run write queries. If the tool is unavailable, continue with schema inspection and report that live data was not checked.

Когда нужен MCP:

  • external service или database;
  • authentication/scopes;
  • structured tool schema;
  • audit logs;
  • read-only resources;
  • несколько агентов используют одну capability;
  • важна permission boundary.

Когда достаточно script:

  • локальная проверка;
  • нет external auth;
  • команда живет в репозитории;
  • результат можно воспроизвести локально.

Как не раздуть SKILL.md

Контекст агента ограничен. Даже если лимит большой, лишний текст ухудшает внимание.

Практическое правило:

text
SKILL.md должен содержать essential workflow.
References должны содержать detailed knowledge.
Scripts должны содержать deterministic operations.
Assets должны содержать reusable files.

Если SKILL.md приближается к 500 строкам, проверьте:

  • можно ли вынести framework-specific details в references/;
  • можно ли заменить длинный пример шаблоном в assets/;
  • можно ли заменить повторяемый код script;
  • можно ли удалить общие объяснения, которые агент и так знает;
  • можно ли оставить один хороший пример вместо пяти слабых.

Skill - это onboarding guide для агента по конкретному workflow. Не учебник, не база знаний и не копия всей документации проекта.

Best practices по написанию SKILL.md

1. Начинайте с concrete examples

Перед написанием skill соберите 3-5 реальных задач, где он должен применяться.

Пример:

text
1. Add POST /api/projects.
2. Add PATCH /api/projects/:id.
3. Add GET /api/projects/:id/members.
4. Update endpoint validation after schema change.

По этим примерам видно, какие inputs повторяются, какие files нужно читать, какие tests запускать.

2. Пишите один skill на один workflow

create-api-endpoint лучше, чем backend-development.

fix-bug-with-regression-test лучше, чем make-code-better.

Чем шире skill, тем труднее:

  • определить trigger;
  • удержать body коротким;
  • проверить качество;
  • избежать конфликтов с другими skills.

3. Делайте description самостоятельным

description должен работать без body.

Проверка:

text
Если агент видит только name + description, сможет ли он понять,
когда использовать этот skill?

Если нет, перепишите description.

Процесс создания skill

Практичный skill редко получается с первой попытки. Его лучше создавать как маленький engineering artifact.

flowchart LR A[Concrete examples] --> B[Plan reusable resources] B --> C[Create skill folder] C --> D[Write SKILL.md] D --> E[Validate structure] E --> F[Use on realistic task] F --> G[Iterate]

Рекомендуемый процесс:

  1. Соберите concrete examples задач, где skill должен срабатывать.
  2. Определите reusable resources: нужны ли references/, scripts/, assets/.
  3. Создайте директорию skill. Если у вашей agent platform есть scaffold tool, используйте его, чтобы не ошибиться в структуре.
  4. Напишите сначала короткий SKILL.md: description, core procedure, constraints, verification.
  5. Проверьте структуру: YAML frontmatter, имя директории, обязательные поля, отсутствие placeholders.
  6. Примените skill на realistic task и доработайте по реальному поведению агента.

Если платформа предоставляет validator, запускайте его после существенных изменений. Для developer skills это так же нормально, как запускать tests после изменения кода.

4. Используйте imperative/infinitive style

Skill должен инструктировать агента.

Хорошо:

text
Read the feature specification first.
Find the closest existing implementation pattern.
Run targeted tests before broad tests.

Слабо:

text
The agent may want to think about the specification.
Usually tests are nice.
It is important to be careful.

5. Не объясняйте очевидное

Модель уже знает базовые вещи: что такое test, REST, React component, SQL migration. В skill нужно класть то, что важно именно для workflow.

Плохо:

text
REST stands for Representational State Transfer.

Хорошо:

text
Preserve the project's existing response envelope unless the specification explicitly changes it.

6. Сначала routing, потом action

Agent coding task почти всегда должен начинаться с чтения:

  • spec;
  • ближайшего existing pattern;
  • tests;
  • relevant architecture constraints.

Не начинайте procedure с "write code".

7. Указывайте stop conditions

Если agent должен остановиться, напишите это явно.

Типичные stop conditions:

  • destructive migration;
  • production access;
  • unclear authorization;
  • conflict между spec и existing behavior;
  • missing acceptance criteria для critical behavior;
  • требование установить dependency или изменить infrastructure.

8. Verification должен быть исполнимым

Плохо:

text
Verify everything works.

Хорошо:

text
Run the targeted test for the changed behavior. If shared validation or auth code changed, run broader tests. If a command cannot be run, report the command and reason.

9. Output должен быть стандартным

Стандартный output снижает cognitive load пользователя.

Для coding tasks:

text
Summary, changed files, checks run, acceptance criteria status, risks.

Для review tasks:

text
Findings first, severity, file/line references, open questions, test gaps.

Для planning tasks:

text
Decision, rationale, task breakdown, dependencies, verification plan.

10. Выносите details в references

Если skill поддерживает несколько frameworks, не держите все details в body.

Структура:

text
references/
├── node-express.md
├── python-fastapi.md
└── ruby-rails.md

В body:

text
Read only the framework reference that matches the current repository.

11. Scripts должны быть протестированы

Если skill содержит script, он становится частью engineering surface.

Для script нужно:

  • понятное имя;
  • help или usage;
  • предсказуемый exit code;
  • безопасные defaults;
  • тестовый запуск хотя бы на representative scenario;
  • инструкция в SKILL.md, когда его использовать.

12. Не создавайте лишние docs внутри skill

В skill directory обычно не нужны:

  • README.md;
  • INSTALLATION_GUIDE.md;
  • CHANGELOG.md;
  • QUICK_REFERENCE.md;
  • заметки о том, как вы придумывали skill.

Эти файлы засоряют пространство. Агенту нужен SKILL.md и только те resources, которые помогают выполнить workflow.

13. Не кладите secrets

В skill нельзя класть:

  • API keys;
  • passwords;
  • production credentials;
  • private tokens;
  • персональные данные без необходимости;
  • инструкции обходить approvals.

Если skill требует внешнего доступа, опишите permission boundary и используйте tool/MCP, где права можно контролировать.

14. Учитывайте overlap между skills

Если два skills могут сработать на одну задачу, уточните description.

Пример overlap:

text
create-api-endpoint
update-openapi-contract

Решение:

  • create-api-endpoint использовать для implementation endpoint;
  • update-openapi-contract использовать для contract-only changes или contract review;
  • в description добавить negative triggers.

15. Сохраняйте skill переносимым

Skill может быть project-specific, но не должен без нужды зависеть от одного абсолютного пути, одного разработчика или одной временной договоренности.

Лучше:

text
Find the project's package scripts before choosing test commands.

Хуже:

text
Always run `/home/alex/tmp/project-old/run-tests.sh`.

16. Сначала пишите маленький skill

Не пытайтесь сразу написать идеальный skill на 2000 строк.

Итерация:

  1. Минимальный SKILL.md.
  2. Использование на 2-3 задачах.
  3. Наблюдение, где агент ошибся.
  4. Добавление constraints, references или scripts.
  5. Повторная проверка.

17. Проверяйте skill на realistic tasks

Skill выглядит хорошо только до первого реального использования.

Проверяйте:

  • срабатывает ли description;
  • читает ли агент нужные references;
  • не пропускает ли verification;
  • не лезет ли в unrelated scope;
  • понятен ли final output;
  • есть ли ситуации, где нужно остановиться.

18. Не подменяйте skill specification

Skill говорит "как выполнять тип работы".

Spec говорит "что нужно построить сейчас".

Плохо:

text
The create-api-endpoint skill always creates a Project with name, description, owner, billing tier, and archived flag.

Это product requirement, а не skill.

Хорошо:

text
Read the feature specification to determine request and response fields.

19. Не подменяйте skill rule

Rule применяется всегда. Skill применяется по необходимости.

Плохо:

text
Every SKILL.md repeats: "Use UTC for all timestamps."

Лучше:

text
Project rule: server timestamps must use UTC.

Skill может ссылаться на rule, но не должен копировать все global rules.

20. Делайте skill наблюдаемым

В конце работы должно быть понятно:

  • какой workflow применялся;
  • какие checks были выполнены;
  • что осталось непроверенным;
  • где агент сделал assumption;
  • какие files изменены.

Это превращает agent work в управляемый engineering process.

21. Валидируйте skill как артефакт

Skill должен проходить хотя бы базовую проверку:

  • корректный YAML frontmatter;
  • name совпадает с именем директории или выбранным convention;
  • description не пустой и не слишком общий;
  • нет незаполненных маркеров и заглушек;
  • ссылки на references/, scripts/, assets/ существуют;
  • scripts запускаются или хотя бы имеют понятный documented usage;
  • examples не противоречат procedure.

Если runtime предлагает специальный validator или scaffold, используйте его. Это снижает количество мелких ошибок, из-за которых skill не сработает или будет срабатывать непредсказуемо.

Частые анти-паттерны

Анти-паттерн Как проявляется Как исправить
Giant skill SKILL.md на тысячи строк обо всем проекте Разделить на skills и references.
Vague description "Helps with backend" Описать trigger contexts и negative triggers.
Tutorial instead of procedure Лекция о REST вместо steps Оставить operational workflow.
No verification "Make sure it works" Указать targeted tests, lint/typecheck, fallback.
No stop conditions Агент додумывает auth или schema Добавить Failure Handling.
Script for everything Даже простая команда завернута в helper Оставить project command или tool.
Tool hidden as skill Skill обещает доступ к database Подключить tool/MCP и описать permissions.
Duplicated references Одинаковый guide в body и references Оставить одно source of truth.
Broad skill overlap 3 skills подходят к одной задаче Уточнить names/descriptions.
No examples Procedure слишком абстрактная Добавить 1 короткий developer example.

Checklist качества SKILL.md

Перед тем как считать skill готовым, проверьте:

  • name короткий, конкретный, в kebab-case;
  • description объясняет что skill делает и когда его использовать;
  • description содержит negative trigger, если skill легко перепутать;
  • body начинается с purpose, а не с длинной теории;
  • inputs помогают пользователю сформулировать задачу;
  • preconditions предотвращают опасные догадки;
  • procedure имеет порядок действий;
  • first steps направляют агента к spec и local patterns;
  • constraints защищают от scope creep;
  • verification содержит реальные проверки;
  • failure handling говорит, когда остановиться;
  • output contract стандартизирует final response;
  • references подключаются условно, а не всегда;
  • scripts нужны и протестированы;
  • assets действительно используются;
  • нет secrets;
  • нет unrelated docs;
  • нет product requirements, которые должны жить в spec;
  • нет global rules, которые должны жить в project instructions;
  • skill можно проверить на realistic task.

Практика: написать create-api-endpoint skill

Создайте черновик:

text
skills/create-api-endpoint/SKILL.md

Структура:

markdown
---
name: create-api-endpoint
description: ...
---

# Create API Endpoint

## Purpose
...

## Inputs
...

## Preconditions
...

## Context To Read
...

## Procedure
...

## Constraints
...

## Verification
...

## Failure Handling
...

## Output
...

Минимальные требования:

  1. description содержит 5-7 trigger contexts.
  2. Procedure начинается с чтения spec и поиска existing pattern.
  3. Есть минимум 5 constraints.
  4. Verification разделяет targeted и broader checks.
  5. Failure Handling содержит минимум 4 stop conditions.
  6. Output требует summary, changed files, checks и risks.

Дополнительное задание:

text
Добавьте `references/api-style.md` и напишите в `SKILL.md`,
когда агент должен читать этот reference.

Skill pack как инженерная библиотека

Отдельный skill полезен, но настоящая сила появляется, когда команда относится к skills как к маленькой engineering library. Внешние collections вроде Vercel Agent Skills хорошо показывают этот подход: в одном репозитории лежат независимые skills для performance review, UI/accessibility review, writing guidelines, deployment workflow и других повторяемых задач.

Из этого можно взять несколько практических принципов.

Принцип Как применять в developer skills
Skill решает один workflow Не смешивайте API endpoint, migration и release notes в одном SKILL.md.
Metadata важнее объема Агент часто видит сначала только name/description, поэтому trigger должен быть точным.
Scripts optional, но проверяемы Если skill запускает helper script, script должен быть маленьким, локальным и тестируемым.
References загружаются по необходимости Большие style guides и framework notes не должны всегда попадать в context.
Skills можно переиспользовать между проектами Избегайте project secrets и unstable product requirements внутри skill.
Skill должен иметь output contract Иначе разные runs вернут разные summaries и evidence.

Минимальная структура skill pack:

text
skills/
  create-api-endpoint/
    SKILL.md
    references/
      api-style.md
    scripts/
      check-openapi.sh
  review-backend-change/
    SKILL.md
    references/
      review-rubric.md
  write-release-notes/
    SKILL.md

Skill pack не должен превращаться в "папку промптов на все случаи". Это versioned process layer. Если команда меняет процесс review, TDD или release, изменение должно попадать в соответствующий skill и затем проверяться через skill evals.

Критерии готовности

После урока студент должен уметь:

  • объяснить назначение name и description;
  • написать description, которое работает как trigger;
  • собрать operational structure для developer skill;
  • выбрать, что оставить в SKILL.md, а что вынести в references/, scripts/, assets/;
  • написать prompts для запуска skill;
  • написать prompts для проектирования skill;
  • задать constraints, verification и failure handling;
  • отличить хороший skill от giant prompt.

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

SKILL.md - это компактная инструкция для повторяемого agent workflow. Его сила не в объеме, а в том, что он снижает вариативность там, где команда уже знает правильный процесс.

Самые важные части skill:

  • точный description;
  • конкретная procedure;
  • правильный context routing;
  • constraints против лишнего scope;
  • verification как evidence;
  • failure handling для опасных или неоднозначных ситуаций.

Developer skills особенно полезны для API work, bug fixing, migrations, code review, release notes, frontend flows и других повторяемых engineering tasks. Но skill не должен заменять specification, rule, tool или test. Он связывает их в процедуру.

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

  1. Почему trigger conditions нужно писать в description, а не только в body?
  2. Чем Purpose отличается от tutorial explanation?
  3. Какие признаки говорят, что часть SKILL.md нужно вынести в references/?
  4. Когда script внутри skill полезнее текстовой инструкции?
  5. Какие stop conditions вы добавили бы в skill для database migration?

Что дальше

В следующем уроке мы разберем обратную сторону: что нельзя класть в skill. Это важно, потому что skill легко превратить в свалку project knowledge, secrets, unstable requirements и unrelated rules. Хороший skill не только говорит агенту, что делать, но и аккуратно ограничивает то, что не должно попадать в его контекст.

Обновлено 03.10.2026