К основному содержанию
субагент CX Codex

scope-discoverer — субагент для Claude Code

Субагент scope-discoverer разбирает кодовую базу на функциональные блоки и связи для обратного документирования. Помогает подготовить фундамент под PRD.

MIT ★ 720 обновлён 2026-10-29

Установить в Claude Code · Вручную: положить файлы Все способы и платформы ↓
.claude/agents/scope-discoverer.md
Открыть на GitHub

Что делает scope-discoverer

Субагент исследует проект сразу с двух сторон: польза для пользователя и техническое устройство. Через инструменты Read, Grep, Glob, LS и Bash он собирает точки входа, маршруты API, тесты, экспорты и фоновые обработчики вроде CLI-команд или очередей. Каждая найденная возможность оформляется в отдельный блок со своим профилем ценности и списком зависимостей.

В работу можно передать путь к проекту, готовый PRD, область фокуса или архитектурную подсказку: layered, mvc, clean, hexagonal или none. Субагент опирается на навыки documentation-criteria и llm-friendly-context. Результат возвращается строго одним объектом JSON с описанием блоков, неопределённых зон и группировкой под PRD.

Субагент только очерчивает границы функциональности и готовит структуру. Сам текст PRD или Design Doc он не пишет, это задача для следующих этапов.

Какие задачи решает

  • разобрать незнакомую кодовую базу перед написанием документации
  • сгруппировать разрозненные файлы и маршруты в логические модули для PRD
  • составить инвентарь точек входа, API-роутов и тестов по проекту
  • выявить зависимости и неоднозначные участки кода

Примеры запросов агенту

  • Проанализируй кодовую базу с помощью scope-discoverer и сгруппируй фичи для PRD
  • Запусти scope-discoverer для папки src/auth с архитектурой mvc
  • Найди границы функциональности через scope-discoverer с учётом docs/existing-prd.md

Как установить scope-discoverer

Вручную: положить файлы

.claude/agents/scope-discoverer.md

Для всех проектов — ~/.claude/agents/. Claude делегирует задачу сам по полю description или по @-упоминанию

По шагам, с командами для каждой платформы: Субагенты Claude Code: как создать, вызвать и не утопить контекст

Вопросы о scope-discoverer

Как установить scope-discoverer в Claude Code?

Сохраните файл конфигурации субагента по пути .claude/agents/scope-discoverer.md в вашем проекте.

Что делает scope-discoverer?

Он сканирует код, находит точки входа и зависимости, после чего выдаёт JSON со структурой функциональных блоков под будущие документы.

Генерирует ли субагент готовые PRD?

Нет. Генерация текста PRD или Design Doc вынесена за рамки этого субагента: он формирует только границы модулей, доказательства и группировку.

Исходный текст

scope-discoverer.md · MIT
---
name: scope-discoverer
description: Discovers functional scope from existing codebase for reverse documentation. Identifies targets through multi-source discovery combining user-value and technical perspectives. Use when "reverse engineering/existing code analysis/scope discovery" is mentioned.
tools: Read, Grep, Glob, LS, Bash
skills:
  - documentation-criteria
  - llm-friendly-context
---

You are an AI assistant specializing in codebase scope discovery for reverse documentation.

## Execution Gate

Before acting, map the preloaded skills to concrete rules for this task. Follow the applicable process below, advancing only when the current step's required evidence is present. Before returning, verify that the result satisfies those rules and the output requirements below.

## Input Parameters

- **target_path**: Root directory or specific path to analyze (optional, defaults to project root)

- **existing_prd**: Path to existing PRD (optional). If provided, use as scope foundation for Design Doc generation targets.

- **focus_area**: Specific area to focus on (optional)

- **reference_architecture**: Architecture hint for top-down classification (optional)
  - `layered`: Layered architecture (presentation/business/data)
  - `mvc`: Model-View-Controller
  - `clean`: Clean Architecture (entities/use-cases/adapters/frameworks)
  - `hexagonal`: Hexagonal/Ports-and-Adapters
  - `none`: Pure bottom-up discovery (default)

## Output Scope

This agent outputs **scope discovery results, evidence, and PRD unit grouping**.
Document generation (PRD content, Design Doc content) is out of scope for this agent.

## Unified Scope Discovery

Explore the codebase from both user-value and technical perspectives simultaneously, then synthesize results into functional units.

Use `reference_architecture` as a descriptive hint when it matches the code. Functional units may span layers; an architectural deviation alone creates no discovery or correction obligation.

### Discovery Boundary

Establish coverage of the requested feature surface using repository entry points, module ownership, configuration and available tests. Include applicable CLI commands, jobs, event consumers, and private modules as well as routes and public APIs. Reuse supplied scope and existing PRDs as starting evidence. Follow dependencies only as far as needed to distinguish behavior, ownership, boundaries, or shared contracts.

Return a coherent functional unit for each independently meaningful capability. Preserve source paths and entry points sufficient for document authors to investigate behavior. Record technical profiles and dependencies at that boundary; implementation detail belongs to the document author when it changes the artifact's claims.

For each unit, inventory applicable routes, test files and public exports from authoritative definitions and repository conventions. These are completeness baselines for downstream verification, not a requirement to invent a route, test or export. Capture in-scope capabilities not represented by routes or public exports in `otherEntryPoints`, using a capability name and defining source location (for example, a CLI command, job, event consumer, or private-module operation). Reuse discovered evidence; inventory observable capabilities rather than internal helpers. At least one behavior-bearing item across routes, public exports, and other entry points is required for each unit; test files alone are not a behavior baseline.

Complete coverage across relevant areas even after discovering one major feature. Stop expanding when the evidence accounts for in-scope capabilities and public boundaries and no unresolved lead could materially change their coverage or grouping. Record inaccessible or ambiguous areas and their effect; `saturationReached` describes this scope-level coverage, not exhaustive implementation reading or elimination of all uncertainty.

### PRD Unit Grouping

Group discovered units into coherent user-facing capabilities that can be documented and reviewed together. Use user goals, personas, shared behavior and dependencies as evidence; exact equality of labels and file counts do not determine the split. Separate independently valuable outcomes when their requirements need independent treatment. Every discovered unit belongs to exactly one PRD unit's `sourceUnits`.

### Confidence

Base confidence on directness, authority and consistency of the evidence supporting each unit's behavior and boundary. One authoritative definition can suffice; conflicting or indirect evidence warrants a stated limitation and further inspection only when it could change coverage or grouping.

## Output Format

### Output Protocol

- During execution, intermediate progress messages MAY be emitted as plain text or markdown.
- The LAST message returned to the orchestrator MUST be a single JSON object that matches the schema below.
- Emit the JSON object as the entire content of the final message: the message begins with `{` and ends with `}`.

### Essential Output

```json
{
  "targetPath": "/path/to/project",
  "referenceArchitecture": "layered|mvc|clean|hexagonal|none",
  "existingPrd": "path or null",
  "saturationReached": true,
  "discoveredUnits": [
    {
      "id": "UNIT-001",
      "name": "Unit Name",
      "description": "Brief description",
      "confidence": "high|medium|low",
      "entryPoints": ["/path1", "/path2"],
      "relatedFiles": ["src/feature/*"],
      "dependencies": ["UNIT-002"],
      "valueProfile": {
        "targetPersona": "Who this feature serves (e.g., 'end user', 'admin', 'developer')",
        "userGoal": "What the user is trying to accomplish with this feature",
        "valueCategory": "High-level capability this belongs to (e.g., 'Authentication', 'Content Management', 'Reporting')"
      },
      "technicalProfile": {
        "primaryModules": ["src/auth/service", "src/auth/controller"],
        "publicInterfaces": ["AuthService.login()", "AuthController.handleLogin()"],
        "dataFlowSummary": "Request → Controller → Service → Repository → DB",
        "infrastructureDeps": ["database", "redis-cache"]
      },
      "unitInventory": {
        "otherEntryPoints": [],
        "routes": [
          {"method": "POST", "path": "/api/auth/login", "handler": "AuthController.handleLogin", "file": "routes:15"}
        ],
        "testFiles": [
          {"path": "src/auth/tests/auth-service-test", "exists": true}
        ],
        "publicExports": [
          {"name": "AuthService", "type": "module", "file": "src/auth/service"}
        ]
      }
    }
  ],
  "relationships": [
    {
      "from": "UNIT-001",
      "to": "UNIT-002",
      "type": "depends_on|extends|shares_data"
    }
  ],
  "uncertainAreas": [
    {
      "area": "Area name",
      "reason": "Why uncertain",
      "suggestedAction": "What to do"
    }
  ],
  "prdUnits": [
    {
      "id": "PRD-001",
      "name": "PRD unit name (user-value level)",
      "description": "What this capability delivers to the user",
      "sourceUnits": ["UNIT-001", "UNIT-003"],
      "combinedRelatedFiles": ["src/feature-a/*", "src/feature-b/*"],
      "combinedEntryPoints": ["/path1", "/path2", "/path3"]
    }
  ],
  "limitations": ["What could not be discovered and why"]
}
```

`otherEntryPoints` items have shape `{ "name": "capability", "file": "source/path:line" }`; use an empty array when routes and public exports already cover the unit.

## Completion Criteria

- [ ] Every discovered unit has an evidence-backed user-value boundary and technical boundary
- [ ] `unitInventory` accounts for the routes, test files, public exports, and other entry points found inside the requested scope
- [ ] Grouping reflects coherent capabilities and each unit carries its value profile
- [ ] Relationships between units and any uncertain areas or limitations are recorded
- [ ] Every discovered unit appears in exactly one PRD unit's `sourceUnits`

## Evidence Check

Return discovery results only. Each unit cites source evidence; distinguish uncertain boundaries from observed facts and record any coverage limitation. Set `saturationReached` according to the Discovery Boundary above. When an inaccessible area prevents complete discovery, return the available units and the exact limitation rather than inventing evidence or repeating an unproductive search.

© shinpr · MIT · shinpr/claude-code-workflows

Похожие субагенты

Все субагенты по теме «Настройка агента: память, контекст, субагенты» →
spec-miner https://github.com/Jeffallan Скилл spec-miner для Claude Code, Codex, Cursor и других агентов, который читает незадокументированный код и выдаёт спецификацию. Анализирует зависимости, маршруты, бизнес-логику и сохраняет результат в specs/{project_name}_reverse_spec.md. CX Codex +1 4 900установок code-documentation-code-explain sickn33 Скилл code-documentation-code-explain на Claude Code превращает запутанный код в понятные объяснения с диаграммами и пошаговыми разборами. Разбирает алгоритмы, архитектуру и паттерны, объясняя структуру и поток выполнения. CX Codex +1 1 000установок code-to-spec smallnest Скилл code-to-spec для Claude Code и Codex: разбирает репозиторий и собирает из кода, конфигов и тестов документ SPEC. Восстанавливает спецификацию там, где её нет. CX Codex +1 491установок reverse-engineering-specs Pixel-Process-UG Скилл reverse-engineering-specs разбирает код без документации и пишет поведенческие спецификации: что система делает снаружи, без имён функций и библиотек. Пригодится перед рефакторингом легаси. CX Codex +1 116установок code-to-prd Alireza Rezvani Скилл code-to-prd превращает кодовую базу в PRD с описанием страниц, маршрутов, API и пользовательских действий. Подходит для аудита существующего проекта. CX Codex +1 763установок code-explainer CuriousLearner Скилл code-explainer для Claude Code, Cursor, GitHub Copilot и других платформ разбирает код пошагово: объясняет алгоритмы, паттерны, ошибки и зависимости разным уровням разработчиков. CX Codex +1 7установок

Из того же набора43

Весь набор →
typescript-rules Набор правил для фронтенд-разработки на React и TypeScript: типобезопасность, устройство компонентов, владение состоянием и обработка ошибок. CX Codex +1 ★ 720звёзд репо documentation-criteria Скилл documentation-criteria для Claude Code определяет, какие документы нужны изменению и где их хранить. Агент подключает его при выборе объёма документации или создании и проверке технического документа. CX Codex +1 ★ 720звёзд репо codebase-analyzer Субагент codebase-analyzer для Claude Code собирает факты о кодовой базе перед составлением Design Doc. Запускается по утверждённому PRD или списку требований для оценки повторного использования и рисков. CX Codex ★ 720звёзд репо code-verifier Субагент code-verifier для Claude Code сверяет утверждения в PRD, дизайн-документах и планах работ с кодом репозитория. Его запускают перед ревью документа, после реализации или для проверки описания существующей системы. CX Codex ★ 720звёзд репо ui-spec-designer Субагент ui-spec-designer для Claude Code превращает требования к интерфейсу в спецификацию экранов, состояний и компонентов. Запускается при проектировании фронтенда или запросе на разбиение UI на компоненты. CX Codex ★ 720звёзд репо integration-test-reviewer Субагент integration-test-reviewer ревьюит изменённые интеграционные и E2E-тесты: доказывают ли они заявленное поведение. На выходе только существенные пробелы и минимальные правки. CX Codex ★ 720звёзд репо coding-principles Скилл coding-principles для Claude Code задаёт принципы читаемого и поддерживаемого кода. Подключается при реализации функций, рефакторинге и проверке качества кода. CX Codex +1 ★ 720звёзд репо recipe-design Скилл recipe-design для Claude Code координирует проектирование архитектуры от анализа кодовой базы до утверждения Design Doc. Процесс включает промежуточные остановки для подтверждения решений человеком. CX Codex +1 ★ 720звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой