Agent Dev 101

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

Урок 6.5. Skill Discovery

На этой странице
  1. Зачем это нужно
  2. Основная идея
  3. Ключевые термины
  4. Как агент видит skills
  5. Почему description важнее body для discovery
  6. False Positive Activation
  7. False Negative Activation
  8. Anatomy хорошего description
  9. Формула description
  10. Плохие и хорошие descriptions
  11. Naming skills
  12. Trigger Surface
  13. Positive и Negative Triggers
  14. Granularity: размер skill
  15. Overlap между skills
  16. Skill collision
  17. Discovery taxonomy для developer skills
  18. Description templates
  19. Как писать description пошагово
  20. Приоритеты при выборе skill
  21. Явный вызов skill пользователем
  22. Prompt patterns для discovery
  23. Пример: улучшение API description
  24. Пример: review-code description
  25. Пример: migration description
  26. Пример: frontend form flow
  27. Skill catalog на уровне проекта
  28. Discovery для references
  29. Discovery для scripts
  30. Description и body должны совпадать
  31. Description не должен быть слишком длинным
  32. Language и vocabulary
  33. Metadata для UI и prompts
  34. Матрица discovery качества
  35. Практика: улучшить metadata для 3 skills
  36. Практика: классифицировать задачи
  37. Типичные ошибки
  38. Checklist для хорошего discovery
  39. Критерии готовности
  40. Краткое резюме
  41. Вопросы для самопроверки
  42. Что дальше

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

В уроке 6.4 мы очистили skill от лишнего: secrets, unstable requirements, истории проекта, случайных правил и больших справочников. Но даже чистый skill бесполезен, если агент не понимает, когда его применять.

Skill discovery - это момент выбора:

text
Нужен ли для текущей задачи какой-то skill?
Если да, какой именно?

В agentic development этот момент критичен. Агент может иметь десятки skills, но в начале задачи он обычно видит не полный текст каждого SKILL.md, а только краткую metadata: имя и описание. Если metadata плохая, агент:

  • не активирует нужный skill;
  • активирует лишний skill;
  • выбирает слишком широкий skill;
  • путает похожие skills;
  • пропускает важную procedure;
  • читает лишний контекст;
  • выполняет задачу как обычный chatbot, хотя для нее есть проверенный workflow.

Главная цель урока - научиться писать и проверять metadata skill так, чтобы агент выбирал правильную процедуру по короткому описанию.

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

Skill discovery строится на простом контракте:

text
Metadata должна быть достаточной, чтобы агент решил,
нужно ли загружать полный SKILL.md.

Это означает:

  • name должен быстро показывать область и действие;
  • description должен объяснять, когда skill использовать;
  • description должен содержать concrete trigger contexts;
  • description должен предупреждать о похожих, но неподходящих задачах;
  • body не должен быть единственным местом, где описаны условия вызова.

Плохой discovery выглядит так:

text
User task: "Добавь POST /api/projects"
Available skill: api
description: Helps with API stuff.
Agent: "Неясно, стоит ли использовать skill. Сделаю сам."

Хороший discovery:

text
User task: "Добавь POST /api/projects"
Available skill: 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 integration, API tests, or API contract updates. Do not use for database-only migrations, frontend-only work, deployment, or generic API theory.
Agent: "Это endpoint implementation task. Нужно загрузить skill."

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

Термин Значение
Skill Discovery Процесс выбора подходящего skill по задаче и metadata.
Metadata Краткие сведения о skill, прежде всего name и description.
Trigger Условие, при котором skill должен активироваться.
Positive Trigger Пример задачи, где skill нужно использовать.
Negative Trigger Пример задачи, где skill не нужно использовать, несмотря на похожие слова.
Activation Решение агента загрузить и применить skill.
False Positive Skill активировался, хотя не был нужен.
False Negative Skill не активировался, хотя был нужен.
Overlap Ситуация, когда несколько skills подходят к одной задаче.
Granularity Размер и ширина skill: от узкого workflow до слишком общего skill.
Progressive Disclosure Сначала загружается metadata, потом body, потом references/scripts/assets по необходимости.
Trigger Surface Набор слов, ситуаций и артефактов, по которым агент распознает skill.

Как агент видит skills

Упрощенная модель:

flowchart TD A[User task] --> B[Available skill metadata] B --> C[Compare task with names and descriptions] C --> D{Clear match?} D -- No --> E[Proceed without skill or ask for context] D -- One match --> F[Load SKILL.md body] D -- Multiple matches --> G[Resolve overlap] G --> F F --> H[Follow procedure] H --> I{Need extra resources?} I -- Yes --> J[Load selected references/scripts/assets] I -- No --> K[Execute task] J --> K K --> L[Verification and output]

Ключевой момент:

text
Description работает до чтения body.

Поэтому секция ## When To Use This Skill внутри body полезна только после активации. Она не заменяет хорошее description.

Почему description важнее body для discovery

Представьте skill:

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

# API Work

## When To Use This Skill

Use this skill when adding REST API endpoints with controller, validation, service, tests, and OpenAPI updates. Do not use for external API client bugs or generic API explanations.

В body написано хорошее условие вызова. Но агент может его не увидеть, если description слишком слабый.

Лучше:

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, or OpenAPI contract updates. Do not use for external API client bugs, deployment work, or generic API explanations.
---

В body можно повторить детали procedure, но все trigger conditions должны быть в description.

False Positive Activation

False positive - skill активировался, хотя не был нужен.

Пример:

text
Skill:
name: api
description: Helps with APIs.

User task:
"Объясни разницу между REST и GraphQL."

Problem:
Агент активирует implementation skill, хотя пользователь просит объяснение.

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

  • агент тратит контекст на лишнюю procedure;
  • начинает искать codebase, хотя нужно ответить концептуально;
  • может предложить code changes без запроса;
  • workflow становится тяжелее.

Как исправить:

markdown
description: Add or modify REST API endpoints in an existing backend service. Use for implementation tasks involving route/controller, validation, service integration, tests, or API contract updates. Do not use for conceptual explanations, API tutorials, external API troubleshooting, or documentation-only questions.

Negative trigger здесь защищает от ложной активации.

False Negative Activation

False negative - skill не активировался, хотя был нужен.

Пример:

text
Skill:
name: endpoint
description: Creates routes.

User task:
"Добавь POST /api/projects с валидацией, сервисом и тестом."

Problem:
Описание слишком узкое: "routes" не покрывает validation, service, tests.
Агент может решить, что skill касается только router file.

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

  • агент пропускает стандартную procedure;
  • забывает tests;
  • не обновляет contract;
  • не применяет constraints;
  • задача выполняется менее предсказуемо.

Как исправить:

markdown
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, persistence calls, API tests, endpoint acceptance criteria, or OpenAPI contract updates.

Positive triggers должны покрывать реальные формулировки задач.

Anatomy хорошего description

Хороший description обычно содержит 5 частей:

text
Action + object/domain + context + positive triggers + negative triggers

Пример:

yaml
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, endpoint acceptance criteria, or OpenAPI contract updates. Do not use for frontend-only work, database-only migrations, deployment, or generic API theory.

Разбор:

Часть Фрагмент
Action Add or modify
Object/domain REST API endpoints
Context existing backend service
Positive triggers route/controller, validation, service, tests, OpenAPI
Negative triggers frontend-only, database-only, deployment, generic theory

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

Формула description

Используйте шаблон:

text
<Verb phrase> for <domain/object>. Use when Codex needs to <concrete task contexts>. Do not use for <near misses>.

Пример для review:

yaml
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, authorization gaps, compatibility risks, or scope creep. Do not use for style-only proofreading or implementation tasks.

Пример для migration:

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

Пример для release notes:

yaml
description: Write release notes from completed changes, issues, commits, or pull requests. Use when Codex needs to summarize shipped user-facing changes, breaking changes, migrations, fixes, and known limitations for a release. Do not use for implementation planning or code review.

Плохие и хорошие descriptions

Плохо Почему плохо Лучше
API stuff Нет действия и границ Add or modify REST API endpoints...
Helps with code Подходит ко всему Fix bugs by reproducing failure with a regression test...
Review Неясно, что review и против чего Review code changes against a feature specification...
Database Query, migration, schema design или ops? Create safe database schema migrations...
Frontend Слишком широко Build or update frontend form flows with validation, loading, error, and success states...
Docs Любые docs? Write technical Markdown lessons from outlines or course plans...
Security Слишком чувствительно и широко Perform secure-by-default review for Python/JS/Go code changes...

Сильное description не пытается быть красивым. Оно должно быть полезным для routing.

Naming skills

name работает как короткий якорь. Хорошее имя помогает агенту и пользователю быстро понять intent.

Рекомендации:

  • используйте lowercase;
  • используйте hyphen-case;
  • выбирайте action-oriented имя;
  • держите имя коротким;
  • избегайте общих слов;
  • добавляйте namespace по tool/domain, если это снижает неоднозначность.

Хорошие имена:

Имя Почему хорошо
create-api-endpoint Action + object.
fix-bug-with-regression-test Workflow прямо в имени.
review-code-against-spec Ясен критерий review.
create-db-migration Узкая backend procedure.
update-openapi-contract Узкая contract task.
write-release-notes Понятный content workflow.
migrate-react-component-to-design-system Конкретный frontend migration workflow.

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

Имя Проблема
api Слишком широко.
backend Не workflow.
helper Не говорит ничего.
quality Абстрактно.
do-work Не имеет trigger surface.
project-agent Похоже на роль агента, а не skill.

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

text
Можно ли естественно написать prompt:
"Use the `<skill-name>` skill to ..."

Если фраза звучит бессмысленно, имя нужно переписать.

Trigger Surface

Trigger surface - это набор признаков задачи, по которым skill должен распознаваться.

Для create-api-endpoint trigger surface:

Тип признака Примеры
Действия add, implement, modify, create endpoint
Артефакты route, controller, validation, OpenAPI, API test
Форматы POST /api/projects, HTTP method/path
Границы backend service, endpoint-level behavior
Acceptance request schema, response schema, status code
Near misses API explanation, external client bug, deployment

Description должен покрывать эти признаки словами, которые пользователи реально используют.

Для русского курса можно писать skill descriptions на английском или русском. Важно, чтобы в них были стандартные technical terms и реальные формулировки задач. Для командной среды часто удобно использовать английские name и description, а тело skill писать на языке команды.

Пример bilingual-friendly description:

yaml
description: Add or modify REST API endpoints in backend services. Use for tasks phrased as "add endpoint", "реализуй API route", "добавь POST /api/...", request validation, controller/service changes, API tests, or OpenAPI updates. Do not use for conceptual API explanations or frontend-only work.

Positive и Negative Triggers

Positive triggers отвечают:

text
Когда skill точно нужен?

Negative triggers отвечают:

text
Когда skill похож, но не нужен?

Обе части важны.

Пример:

yaml
description: Fix software bugs by reproducing the failure with a regression test before implementation. Use for bug reports, incorrect behavior, failing scenarios, production regressions, or edge cases that should be covered by tests. Do not use for new feature work, pure refactoring, or style-only cleanup.

Positive triggers:

  • bug reports;
  • incorrect behavior;
  • failing scenarios;
  • production regressions;
  • edge cases.

Negative triggers:

  • new feature work;
  • pure refactoring;
  • style-only cleanup.

Без negative triggers fix-bug-with-regression-test может активироваться для любого "исправь код", даже если пользователь просит refactor.

Granularity: размер skill

Skill discovery зависит от granularity. Если skill слишком широкий, он будет часто активироваться ложноположительно. Если слишком узкий, агент будет его пропускать.

Granularity Пример Проблема
Слишком широкий backend-development Подходит почти ко всем backend задачам.
Хороший create-api-endpoint Узкий повторяемый workflow.
Слишком узкий create-post-projects-endpoint Одноразовая задача, не reusable skill.

Правило:

text
Skill должен описывать повторяемый workflow,
а не весь домен и не один конкретный ticket.

Хорошая granularity появляется, когда у skill есть:

  • 3-10 похожих реальных задач;
  • общая procedure;
  • общие constraints;
  • похожий verification pattern;
  • понятные negative triggers.

Overlap между skills

Overlap возникает, когда два или больше skills похожи.

Пример:

text
create-api-endpoint
update-openapi-contract
create-db-migration
build-frontend-form-flow

Task:

text
Добавь endpoint POST /api/projects, обнови OpenAPI и добавь поле в database.

Как решать overlap:

  1. Определить primary workflow.
  2. Использовать основной skill для orchestration.
  3. Подключить дополнительные skills только для явно отдельных частей.
  4. Уточнить description, если overlap повторяется часто.

Пример primary/secondary:

Task aspect Skill
Endpoint implementation create-api-endpoint
Database schema change create-db-migration
Contract-only update update-openapi-contract
UI form build-frontend-form-flow

Описание должно помогать выбрать:

yaml
name: update-openapi-contract
description: Update, review, or validate OpenAPI contracts for existing API behavior. Use for contract-only changes, API documentation alignment, generated client compatibility, or contract validation after implementation. Do not use as the primary skill for implementing backend endpoint logic.

Так update-openapi-contract не будет конкурировать с create-api-endpoint как основной workflow.

Skill collision

Collision - более жесткий случай overlap, когда два skills имеют почти одинаковые names/descriptions.

Плохо:

text
api-work: Helps with API changes.
api-endpoint: Helps with API endpoints.
backend-api: Helps with backend API work.

Агент не понимает, какой skill выбрать.

Решение:

text
create-api-endpoint: implementation workflow
update-openapi-contract: contract workflow
debug-external-api-client: client integration troubleshooting
review-api-change: review workflow

Каждый skill получает свой глагол, объект и границу.

Discovery taxonomy для developer skills

В команде удобно держать skills как набор workflow categories.

Категория Skill examples Typical trigger
Implementation create-api-endpoint, build-frontend-form-flow "добавь", "реализуй", "измени поведение"
Bug fixing fix-bug-with-regression-test "bug", "не работает", "регрессия", "repro"
Review review-code-against-spec, review-security-sensitive-change "review", "проверь diff", "найди риски"
Schema and data create-db-migration, update-data-contract "migration", "schema", "field", "index"
Contracts update-openapi-contract, validate-event-schema "OpenAPI", "contract", "generated client"
Release write-release-notes, prepare-release-checklist "release notes", "changelog", "breaking changes"
Documentation write-technical-lesson, update-runbook "напиши урок", "обнови runbook"
Tool-specific gh-address-pr-comments, linear-plan-issue "GitHub PR comments", "Linear issue"

Такой taxonomy помогает не создавать случайные skills, которые перекрывают друг друга.

Description templates

Implementation skill

yaml
description: Implement <kind of change> in <system context>. Use when a task requires <artifact 1>, <artifact 2>, <tests>, or <contract/update>. Do not use for <near miss 1>, <near miss 2>, or <conceptual discussion>.

Пример:

yaml
description: Implement frontend form flows in an existing web application. Use when a task requires form layout, validation, loading state, error display, submission behavior, accessibility checks, or component tests. Do not use for backend-only work, visual mockups without behavior, or generic design advice.

Review skill

yaml
description: Review <artifact> against <standard/spec>. Use when Codex needs to find <risk types>. Do not use for <non-review tasks>.

Пример:

yaml
description: Review code changes against a feature specification. Use when Codex needs to find behavioral mismatches, missing tests, regressions, authorization gaps, compatibility risks, or scope creep. Do not use for implementation, formatting-only review, or broad architecture brainstorming.

Debugging skill

yaml
description: Diagnose and fix <class of bug> by <method>. Use for <bug signals>. Do not use for <non-bug work>.

Пример:

yaml
description: Diagnose and fix backend bugs by reproducing the failure with a regression test before implementation. Use for incorrect behavior, failing scenarios, production regressions, flaky edge cases, or bug reports with expected versus actual behavior. Do not use for new feature work or pure refactoring.

Tool-specific skill

yaml
description: Use <tool/service> to <workflow>. Use when a task involves <specific artifacts>. Do not use when <tool is not involved> or <task is only conceptual>.

Пример:

yaml
description: Address GitHub pull request review comments using the repository's contribution workflow. Use when Codex needs to inspect PR comments, map comments to code changes, implement fixes, run checks, and summarize responses. Do not use for local code review without GitHub PR context.

Content skill

yaml
description: Write or expand <content type> from <inputs>. Use when Codex needs to create <formats/sections>. Do not use for <unrelated writing>.

Пример:

yaml
description: Write polished technical lectures in Markdown from outlines, lesson plans, rough notes, or existing course files. Use when Codex needs to create educational engineering lessons with definitions, examples, diagrams, summaries, and review questions. Do not use for marketing pages or code implementation tasks.

Как писать description пошагово

Процесс:

  1. Соберите 5 реальных user prompts, где skill нужен.
  2. Соберите 5 near-miss prompts, где skill не нужен.
  3. Выпишите повторяющиеся nouns, verbs и artifacts.
  4. Сформулируйте action + object.
  5. Добавьте "Use when..." с concrete triggers.
  6. Добавьте "Do not use..." для near misses.
  7. Сравните description с body: оно должно обещать только то, что skill реально делает.

Пример working notes:

text
Should trigger:
- "Добавь POST /api/projects"
- "Implement PATCH /api/users/:id validation"
- "Add API test for team invitations"
- "Update endpoint response schema"
- "Add OpenAPI docs for new endpoint"

Should not trigger:
- "Объясни REST"
- "Почини внешний Stripe API client"
- "Сделай frontend form"
- "Добавь database index only"
- "Deploy API to staging"

Итоговое description:

yaml
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, endpoint tests, response schema changes, or OpenAPI contract updates. Do not use for generic REST explanations, external API client troubleshooting, frontend-only work, database-only migrations, or deployment.

Приоритеты при выборе skill

Когда кажется, что подходят несколько skills, используйте порядок:

  1. Самый конкретный workflow.
  2. Skill, который владеет основным результатом задачи.
  3. Skill, у которого verification ближе к acceptance criteria.
  4. Skill с более точными negative triggers.
  5. Если все еще неясно, попросить уточнение или выбрать основной skill и явно назвать границы.

Пример:

text
Task:
"Добавь поле `last_seen_at` в users и покажи его в API response."

Возможные skills:

Skill Роль
create-db-migration Основной для schema change.
create-api-endpoint Вторичный, если endpoint behavior тоже меняется.
update-openapi-contract Вторичный, если contract должен обновиться.

Ответ агента может быть:

text
Основной workflow здесь database migration, потому что задача начинается со schema change.
Я применю `create-db-migration`, а затем использую endpoint/contract steps только для API response update.

Явный вызов skill пользователем

Иногда пользователь сам пишет:

text
Use `create-api-endpoint`.

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

Пример:

text
Use `create-api-endpoint`.
Объясни новичку, чем REST отличается от GraphQL.

Здесь лучше сказать:

text
Эта задача похожа на conceptual explanation, а `create-api-endpoint` предназначен для implementation endpoint. Я отвечу без этого skill.

Если пользователь явно просит применить неподходящий skill, агент должен мягко назвать mismatch и выбрать безопасный путь.

Prompt patterns для discovery

Попросить агента выбрать skill

text
Analyze this task and choose whether any available skill should be used.
Return the selected skill, why it matches, why near-miss skills do not match, and what context should be loaded next.

Task:
<task text>

Попросить улучшить description

text
Improve this skill metadata for discovery.

Current name:
api-helper

Current description:
Helps with APIs.

Skill body summary:
Adds or modifies REST API endpoints with controller, validation, service integration, tests, and OpenAPI updates.

Return:
- better name;
- better description;
- positive triggers;
- negative triggers;
- likely overlapping skills.

Попросить найти overlap

text
Review these skill names and descriptions for overlap.
Identify collisions, false-positive risks, false-negative risks, and suggested rewrites.
Do not rewrite the SKILL.md bodies yet.

Попросить составить trigger surface

text
For the `create-api-endpoint` skill, list:
- user phrases that should trigger it;
- artifacts that should trigger it;
- tasks that look similar but should not trigger it;
- related skills that may overlap.
Then propose a final description.

Пример: улучшение API description

Исходник:

yaml
name: api
description: API stuff

Проблемы:

  • имя слишком короткое и широкое;
  • нет глагола;
  • нет context;
  • нет trigger artifacts;
  • нет negative triggers;
  • непонятно, implementation это, review, docs или troubleshooting.

Улучшение:

yaml
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, endpoint tests, response schema changes, or OpenAPI contract updates. Do not use for generic REST explanations, external API client troubleshooting, frontend-only work, database-only migrations, or deployment.

Что изменилось:

Было Стало
api create-api-endpoint
API stuff Concrete implementation workflow
Нет triggers route/controller, validation, service, tests, OpenAPI
Нет negative triggers REST explanation, external API client, frontend, migration, deployment

Пример: review-code description

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

yaml
name: review
description: Reviews code.

Что неясно:

  • code review или prose review;
  • review against what;
  • что считать finding;
  • можно ли править код;
  • относится ли skill к security review.

Хороший вариант:

yaml
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, authorization gaps, compatibility risks, or scope creep. Do not use for implementation tasks, style-only proofreading, or security-only audits that require a dedicated security workflow.

Здесь skill discovery получает критерий: нужен diff и spec. Это резко снижает ложные активации.

Пример: migration description

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

yaml
name: database
description: Helps with database.

Проблема: database может означать query, schema design, migration, production debugging, analytics, ORM mapping.

Хороший вариант:

yaml
name: create-db-migration
description: Create safe database schema migrations for an existing application. Use when a task requires adding, changing, backfilling, indexing, renaming, or removing database fields, tables, constraints, or schema-derived types. Do not use for ad hoc SQL analysis, production data inspection, analytics queries, or ORM-only refactors without schema changes.

Negative triggers помогают не использовать migration skill для read-only analytics.

Пример: frontend form flow

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

yaml
name: frontend
description: Helps with frontend.

Хороший вариант:

yaml
name: build-frontend-form-flow
description: Build or update frontend form flows in an existing application. Use when a task requires form fields, validation, loading and error states, submit behavior, accessibility, design-system components, or component tests. Do not use for backend-only work, static landing pages, visual mockups without behavior, or generic CSS questions.

Такое description отделяет форму как workflow от любого frontend изменения.

Skill catalog на уровне проекта

Skills можно хранить как директории, но команде часто нужен проектный обзор.

Например:

text
skills/
├── create-api-endpoint/
├── create-db-migration/
├── fix-bug-with-regression-test/
├── review-code-against-spec/
└── write-release-notes/

Проектный catalog может быть в guide/skill_catalog.md или в разделе engineering docs. Он не заменяет metadata, но помогает людям понимать набор workflows.

Пример catalog:

Skill Primary use Should not use for
create-api-endpoint Endpoint implementation with tests/contracts API theory, deployment
create-db-migration Schema changes Analytics queries, production inspection
fix-bug-with-regression-test Bug fixes with regression coverage Feature work, refactor
review-code-against-spec Diff review against AC/spec Implementation
write-release-notes User-facing release summaries Code review

Важно: catalog не должен расходиться с description. Если меняется skill metadata, обновляйте catalog или не заводите его вообще.

Discovery для references

Skill discovery не заканчивается на выборе SKILL.md. После активации skill должен выбрать, какие references читать.

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

markdown
## Context

Read all files in `references/`.

Хороший вариант:

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.
Read `references/auth.md` only when the endpoint touches authentication or authorization.

Это второй уровень discovery:

text
Task -> skill metadata -> SKILL.md -> relevant reference

То же правило: описание должно помогать выбрать нужное, а не грузить все подряд.

Discovery для scripts

Scripts тоже нуждаются в discovery. Нельзя просто положить script в папку и надеяться, что агент догадается.

Плохо:

text
scripts/
└── check.sh

Без инструкции агент не знает:

  • когда запускать script;
  • какие аргументы передавать;
  • какие failure modes ожидать;
  • можно ли запускать script безопасно;
  • заменяет ли он project tests.

Хороший фрагмент:

markdown
## Verification Helpers

Use `scripts/check-openapi-contract.sh` only when the API contract changed. Pass the OpenAPI file path as the first argument. Treat a non-zero exit code as a contract mismatch, inspect the output, and fix either implementation or contract before reporting success.

Discovery относится не только к skills, но и к bundled resources.

Description и body должны совпадать

Одна из частых ошибок:

text
description обещает одно,
body делает другое.

Пример:

yaml
name: review-code-against-spec
description: Review code changes against feature specifications and report behavioral risks.

А body:

markdown
## Procedure

1. Rewrite the code.
2. Add features you think are missing.
3. Commit the changes.

Это broken contract. Агент активирует skill для review, а получает implementation procedure.

Проверка:

text
Каждое обещание description должно иметь поддержку в body.
Каждый крупный workflow в body должен быть отражен в description.

Description не должен быть слишком длинным

Слишком короткое description плохо. Но слишком длинное тоже плохо.

Плохо:

text
description: This skill is for APIs. It can be used for many things. APIs are important. Sometimes users ask for endpoints, sometimes they ask for validation, sometimes controllers, sometimes services, sometimes OpenAPI. In our project in 2022...

Проблемы:

  • metadata сама становится context bloat;
  • trigger signal размывается;
  • в description попадает история и теория;
  • сложнее сравнивать skills между собой.

Практический ориентир:

text
1-3 плотных предложения.
Действие, область, triggers, negative triggers.

Language и vocabulary

Skill discovery зависит от слов. Если команда формулирует задачи по-русски, а description только по-английски, некоторые триггеры могут быть слабее. Если весь tooling и codebase на английском, полностью русское description тоже может быть менее точным.

Рабочий вариант для русскоязычной команды:

  • name на английском в kebab-case;
  • description с английскими technical terms и иногда русскими trigger phrases;
  • body на русском или английском, по стандарту команды.

Пример:

yaml
name: fix-bug-with-regression-test
description: Fix bugs by reproducing the failure with a regression test before implementation. Use for "баг", "не работает", incorrect behavior, failing scenario, production regression, or edge case reports. Do not use for new feature work, pure refactoring, or style-only cleanup.

Главное не язык, а recognizability.

Metadata для UI и prompts

Некоторые agent platforms могут показывать skills в UI, chips, marketplace или internal selector. Там могут быть дополнительные user-facing поля: display name, short description, default prompt.

В курсе важно разделить:

Поле Роль
name Стабильный technical identifier.
description Основной routing trigger.
display_name Человеческое название в UI, если platform поддерживает.
short_description Короткая подсказка для списка skills.
default_prompt Пример prompt для запуска skill.

Если такие UI fields есть, они должны совпадать по смыслу с SKILL.md. Не допускайте, чтобы UI обещал "review", а description описывал implementation.

Матрица discovery качества

Оцените description по шкале:

Критерий 0 1 2
Action Нет действия Действие расплывчатое Действие конкретное
Domain Неясен Слишком широкий Ясен объект workflow
Positive triggers Нет 1-2 общих Несколько concrete contexts
Negative triggers Нет Есть, но слабые Закрывают near misses
Granularity Ticket или весь домен Почти подходит Повторяемый workflow
Body alignment Не совпадает Частично совпадает Полностью совпадает
Overlap control Конфликтует Требует догадки Отличается от соседних skills

Цель: не обязательно набрать идеальные 14 баллов, но description с оценкой ниже 9 почти всегда стоит переписать.

Практика: улучшить metadata для 3 skills

Skill 1

Исходник:

yaml
name: api
description: API stuff

Улучшенный вариант:

yaml
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, endpoint tests, response schema changes, or OpenAPI contract updates. Do not use for generic REST explanations, external API client troubleshooting, frontend-only work, database-only migrations, or deployment.

Skill 2

Исходник:

yaml
name: review
description: Reviews things.

Улучшенный вариант:

yaml
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, authorization gaps, compatibility risks, or scope creep. Do not use for implementation tasks, style-only proofreading, or broad architecture brainstorming.

Skill 3

Исходник:

yaml
name: db
description: Database helper.

Улучшенный вариант:

yaml
name: create-db-migration
description: Create safe database schema migrations for an existing application. Use when a task requires adding, changing, backfilling, indexing, renaming, or removing database fields, tables, constraints, or schema-derived types. Do not use for analytics queries, production data inspection, ORM-only refactors, or generic database design discussion.

Практика: классифицировать задачи

Для каждого prompt решите, какой skill должен активироваться.

Prompt Expected discovery
"Добавь POST /api/projects с validation и API test" create-api-endpoint
"Объясни, чем REST отличается от GraphQL" No skill или lecture/explanation skill, не API implementation
"Исправь баг: reset token можно использовать дважды" fix-bug-with-regression-test
"Проверь diff по spec team-invitations.md" review-code-against-spec
"Добавь index на users.email" create-db-migration
"Сделай форму создания проекта" build-frontend-form-flow
"Обнови только OpenAPI description для существующего endpoint" update-openapi-contract
"Напиши release notes по merged PRs" write-release-notes
"Запусти тесты" Tool/command, не skill
"Всегда используй UTC" Rule, не skill

Эта практика показывает, что discovery - это классификация intent, а не поиск ключевого слова.

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

Ошибка Симптом Исправление
Description слишком общий Skill срабатывает на все Добавить action, object, positive/negative triggers
Description слишком узкий Skill пропускает реальные задачи Добавить реальные trigger contexts
Trigger спрятан в body Skill не открывается Перенести "Use when..." в description
Нет negative triggers Много false positives Добавить near misses
Skills пересекаются Агент выбирает случайно Развести names/descriptions и primary workflow
Skill слишком широкий Body становится giant prompt Разделить на несколько skills
Skill слишком узкий Похож на один ticket Поднять на уровень повторяемого workflow
Name не содержит глагол Непонятен action Использовать verb-led name
Description не совпадает с body Агент получает не тот workflow Синхронизировать metadata и body
Не учитывается язык команды Пользовательские prompts не совпадают с metadata Добавить familiar trigger terms

Checklist для хорошего discovery

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

  • name короткий, action-oriented, в hyphen-case;
  • description можно понять без чтения body;
  • description начинается с того, что skill делает;
  • есть конкретные positive trigger contexts;
  • есть negative triggers для near-miss задач;
  • description не содержит историю проекта, secrets или длинную теорию;
  • description не обещает больше, чем body выполняет;
  • skill не конфликтует с соседними skills;
  • granularity соответствует повторяемому workflow;
  • language и vocabulary совпадают с реальными user prompts;
  • references/scripts имеют routing instructions внутри body;
  • пользователь может явно вызвать skill понятным prompt;
  • можно написать trigger tests для YES и NO случаев.

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

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

  • объяснить, почему skill discovery зависит от metadata;
  • отличить false positive от false negative activation;
  • написать сильное description;
  • добавить positive и negative triggers;
  • выбрать хорошее имя skill;
  • оценить granularity skill;
  • найти overlap между skills;
  • улучшить metadata для developer skills;
  • подготовить trigger cases для следующего урока.

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

Skill discovery - это не второстепенная деталь. Это входная дверь в skill. Если дверь плохо подписана, агент не попадет в нужную процедуру или зайдет не туда.

Сильное description должно быть коротким, но насыщенным:

text
action + object/domain + concrete triggers + negative triggers

Хорошая metadata снижает ложные активации, помогает progressive disclosure, защищает context window и делает skills тестируемыми. После очистки skill от лишнего нужно обязательно проверить, понятно ли по name и description, когда его применять.

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

  1. Почему секция "When to use" внутри body не заменяет хорошее description?
  2. Чем false positive activation отличается от false negative activation?
  3. Какие negative triggers вы добавили бы для create-api-endpoint?
  4. Почему backend-development обычно хуже, чем create-api-endpoint?
  5. Как понять, что два skills конфликтуют в discovery?

Что дальше

В следующем уроке мы будем тестировать skills как поведенческие артефакты. Для discovery это означает trigger tests: задачи, где skill должен активироваться, и задачи, где он должен остаться выключенным. Так metadata перестает быть субъективным текстом и становится проверяемой частью agent workflow.

Обновлено 03.10.2026