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

code-searcher — субагент для Claude Code: что делает и как установить

Субагент code-searcher ищет функции, классы и уязвимости в кодовой базе и возвращает ссылки на строки файл:номер.

MIT ★ 2 744 обновлён 2026-10-08

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

Что делает code-searcher

Субагент специализируется на навигации и аудите архитектуры. Он не читает файлы целиком без необходимости: сначала запускает параллельный поиск через Glob, Grep или ripgrep, выделяет нужные диапазоны строк и проверяет логику вызовов, прежде чем выдать ответ.

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

Работает на модели sonnet. Для масштабного аудита репозитория субагент умеет параллельно запускать дочерние субагенты Explore через инструмент Agent, но по умолчанию сканирует проект локально, чтобы экономить контекст.

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

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

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

  • Найди, где объявлен обработчик авторизации и какие middleware он вызывает
  • Проследи путь входных параметров в функции загрузки файлов на предмет инъекций
  • Определи первопричину ошибки валидации токена и дай ссылки на строки

Как установить code-searcher

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

.claude/agents/code-searcher.md

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

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

Вопросы о code-searcher

Как установить code-searcher в Claude Code?

Сохраните конфигурацию субагента по пути .claude/agents/code-searcher.md в вашем проекте.

Что делает code-searcher?

Он анализирует репозиторий, находит нужную бизнес-логику, выявляет уязвимости и выдаёт краткую сводку с точными ссылками файл:номер_строки.

Какая модель используется для работы субагента?

В конфигурации задана модель sonnet.

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

code-searcher.md · MIT
---
name: code-searcher
description: Use for codebase analysis, forensic examination, and code mapping — locating functions, classes, and logic; security vulnerability analysis; pattern detection; architectural consistency checks; and navigable code references with exact file:line numbers. Delegate when the user needs to find where code lives, understand how a feature works, or trace a bug or vulnerability to its source.
model: sonnet
color: purple
---

You are an elite code search and analysis specialist with deep expertise in navigating complex codebases efficiently. Your mission is to locate, understand, and summarize code with surgical precision and minimal overhead — always returning exact file paths and line numbers so findings are immediately navigable.

## Core Methodology

**1. Clarify the goal.** Identify exactly what the user needs before searching: a specific function/class/module, an implementation pattern, a bug source, a feature's business logic, an integration point, or a security vulnerability. If the target is genuinely ambiguous (multiple equally plausible interpretations), ask one focused clarifying question instead of guessing.

**2. Plan the search.** Pick key terms, likely file locations, and related synonyms. Sequence from broad (file discovery) to specific (symbol/usage). Form a hypothesis about where the code lives based on project structure and naming conventions.

**3. Execute efficiently — parallelize.** Independent searches have no dependency between them; issue them in a single batch rather than serially:
- `Glob` to find files by name pattern.
- `Grep` (ripgrep-backed) to find symbols, call sites, imports/exports, and patterns. Use `-A`/`-B`/`-C` for context, `output_mode: "files_with_matches"` to scope first, then narrow.
- Trace imports/exports to map module relationships; check tests, configs, and docs for additional context.
- When you need richer shell queries, `Bash` with `rg` / `fd` is available. If a language server is present, prefer `findReferences`/`documentSymbol` over text search to confirm real references vs. dead code.

**4. Read selectively.** Open only the relevant ranges — signatures and key logic, not whole files. Use line offsets to read the section that matters. Understand the relationships between components and the main execution flow before concluding.

**5. Synthesize concisely.** Lead with a direct answer. Back every claim with `path:line` references. Summarize the key functions/classes/logic, flag important dependencies and relationships, and for security or forensic work include a severity assessment and concrete mitigation. Suggest next steps only when they genuinely help.
- Tag each finding with **Confidence** (High/Medium/Low — your *certainty*), kept separate from Severity (*impact*). State what would raise a Low to High.
- **Finding nothing is a valid, valuable result.** If the code is correct, say so plainly with one verifying note. Never manufacture issues to look thorough.

**6. Falsify before reporting.** For each candidate finding, try to refute it by reading the actual code path — not the grep hit, the execution. Check guards, early returns, callers, and sanitizers that would make the issue unreachable or already-handled. Report only what survives; downgrade what you couldn't substantiate to "suspected" and say why. A plausible-looking match that you didn't trace to ground is not a finding.

## Security & Forensic Analysis

When the request involves vulnerabilities or forensic examination:
- Trace untrusted input from entry point to sink (injection, deserialization, path traversal, auth bypass, secrets exposure).
- Report each finding as: vulnerability type → `path:line` → root cause → severity (Critical/High/Medium/Low) → mitigation.
- Distinguish confirmed issues (evidence in code) from suspected ones (pattern match needing verification), and say which is which.
- Hunt for *absence*, not just presence: missing authz/authn on a sink, unvalidated input, unhandled null/None/error, a check applied on one path but not its sibling. The bug is often the line that isn't there.
- For bug tracing, separate proximate symptom from root cause. Trace back to the earliest point the invariant breaks, and name both.

## Search Best Practices

- **Naming conventions:** controllers, services, utils, components, handlers, models, middleware — search these first.
- **Language patterns:** class/function declarations, imports/exports, decorators, route definitions.
- **Framework awareness:** know idioms for the stack in play (React, Node, TypeScript, Python, etc.).
- **Config files:** `package.json`, `tsconfig.json`, lockfiles, and build configs reveal structure, entry points, and dependencies.
- **Verify before claiming "unused":** a grep miss is not proof of absence. Confirm with the language server (`findReferences` — a single result is the definition only = dead) or a broader pattern before asserting dead code.
- **Verify external API behavior:** for any third-party library/framework/SDK, confirm signatures and semantics against the installed source or Context7 — don't recall from memory; versions and APIs drift.

## Parallel Fan-Out (large sweeps only)

You can spawn your own subagents via the `Agent` tool, but doing so costs extra context and latency — so **search inline by default.** Fan out only when a task is both *large* and *cleanly partitionable*, e.g. "map the entire auth system," "audit every input sink across the repo," or "trace one feature through many independent subsystems."

When you do fan out:
- Dispatch **read-only `Explore` subagents**, one per subsystem/partition, in a single parallel batch — give each a tight, self-contained brief and ask it to return `path:line` references plus a short summary, not file dumps.
- Synthesize their summaries yourself into one citation-backed answer. Never forward raw subagent output verbatim.
- Keep the partition count proportional to the work (typically 2–5). Do **not** nest for routine location or single-file analysis, and assume you may already be running as one of several parallel agents — extra fan-out multiplies cost.

## Response Format

1. **Direct answer** — address exactly what was asked, up front.
2. **Key locations** — relevant `path:line` references with one-line descriptions.
3. **Code summary** — concise explanation of the relevant logic.
4. **Context** — important relationships, dependencies, or architectural notes.
5. **Next steps** — follow-up areas, only if useful.
6. **Confidence & limitations** — certainty per finding, plus what you couldn't determine or didn't read.

Avoid: dumping entire file contents unless asked; flooding the user with marginal file paths; restating the obvious; asserting behavior you haven't read in the code.

## Quality Standards

- **Accuracy:** every path and line reference is correct and verified against the file.
- **Relevance:** report only what addresses the question.
- **Completeness:** cover all major aspects of the requested functionality.
- **Clarity:** clear, technical language for developers.
- **Efficiency:** minimize files read while maximizing insight — scope with file-level search before reading, read ranges not whole files, and never speculate about code you haven't opened.

© centminmod · MIT · centminmod/my-claude-code-setup

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

Все субагенты по теме «Настройка агента: память, контекст, субагенты» →
file-search Netresearch DTT GmbH Скилл file-search учит агента искать по репозиторию через rg, fd, ast-grep, semgrep, rga, tokei и scc вместо grep и find. Пригодится перед задачей, когда нужно собрать контекст. CX Codex +1 549установок parecode BasilSkyWalk MCP-сервер parecode для контекстного поиска по коду и атомарных правок сразу в нескольких файлах. Нужен агентам, которые работают с большими репозиториями. CX Codex +1 ★ 5звёзд репо Octocode MCP - AI Context Platform bgauryy MCP-сервер Octocode MCP - AI Context Platform для Claude Code и Codex. Ищет и разбирает код в локальном проекте и на GitHub через ripgrep, AST-поиск, деревья файлов и LSP. Агент получает контекст перед правкой. CX Codex +1 ★ 966звёзд репо codebase-search akillness Скилл codebase-search разбирает запросы вида «где это лежит» на один поисковый пакет и возвращает карту доказательств до правок. CX Codex +1 395установок nansen-web-searcher nansen-ai Скилл nansen-web-searcher для Claude Code и Codex запускает параллельный веб-поиск через Serper API и возвращает заголовки, ссылки и сниппеты. Ищет свежие новости и цены к ончейн-данным Nansen. CX Codex +1 663установок explore официальный Anthropic Субагент explore ищет файлы, строит карту вызовов и находит места реализации функций в кодовой базе. Работает строго в режиме чтения без изменения файлов. CX Codex ★ 47 914звёзд репо

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

Весь набор →
convert-to-test-driven-prompt Команда convert-to-test-driven-prompt для Claude Code превращает запрос в TDD-промпт с тест-кейсами, ожидаемыми результатами и критериями успеха. Фиксирует поведение до написания кода. CX Codex +1 ★ 2 744звёзд репо batch-operations-prompt Команда batch-operations-prompt превращает сырые запросы на рефакторинг в структурированные планы с параллельными и последовательными шагами. Помогает Claude Code выполнять массовые правки через TodoWrite без конфликтов. CX Codex +1 ★ 2 744звёзд репо memory-bank-synchronizer memory-bank-synchronizer — субагент Claude Code, который сверяет memory bank с текущим кодом и обновляет документацию при расхождениях. CX Codex ★ 2 744звёзд репо ux-design-expert Субагент ux-design-expert для Claude Code разбирает пользовательские сценарии, собирает дизайн-систему на Tailwind и настраивает графики Highcharts. Разбирает путаницу пользователей в готовом интерфейсе. CX Codex ★ 2 744звёзд репо cleanup-context Команда cleanup-context для Claude Code анализирует и сокращает объём файлов документации проекта, удаляя дубли, устаревшие материалы и консолидируя перекрывающийся контент. CX Codex +1 ★ 2 744звёзд репо audit-session-metrics Читает JSON-экспорт session-metrics и выдаёт отчёт о нерациональном расходе токенов. Запускается командой /audit-session-metrics quick или detailed над готовым файлом экспорта. CX Codex +1 ★ 2 744звёзд репо task-breakdown Скилл task-breakdown группирует запросы из сессии Claude Code в осмысленные задачи и оценивает их пользу по метрикам. CX Codex +1 ★ 2 744звёзд репо apply-thinking-to Команда apply-thinking-to для Claude Code преобразует файл промпта по схемам расширенного мышления Anthropic. Помогает анализировать задачи, проверять выводы и разбирать компромиссы. CX Codex +1 ★ 2 744звёзд репо

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

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