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

context-manager · rohitg00 — субагент для Claude Code: функции и установка

Субагент context-manager для Claude Code управляет загрузкой и сжатием сведений в контексте. Работает с задачами, где много файлов и обсуждений.

Apache-2.0 ★ 2 858 обновлён 2026-05-12

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

Что делает context-manager

context-manager предлагает начинать с дерева файлов, затем читать связанный с задачей код, тесты и типы, а определения утилит и документацию подгружать по необходимости. Он распределяет контекст по приоритетам и оставляет 30% окна для ответа. Для недавней истории затронутых файлов предлагает просматривать последние 5 коммитов.

Когда место заканчивается, субагент сжимает выполненные части задачи, оставляя краткие итоги, сигнатуры функций, решения и их причины. Он также может готовить передачу работы другому агенту: с целью, путями файлов, ограничениями и ожидаемым форматом результата. В наборе инструментов указаны Read, Write, Edit, Bash, Glob и Grep; модель — opus.

Субагент исключает из чтения node_modules/, vendor/, target/, dist/, build/, файлы блокировок, сгенерированный код и бинарные файлы. Если задача требует анализа содержимого этих файлов, предписанная стратегия их пропуска может помешать работе.

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

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

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

  • Разбери задачу и составь порядок чтения файлов, не загружая лишнее.
  • Сожми контекст по завершённой части работы, сохрани решения и пути файлов.
  • Подготовь краткую передачу задачи другому агенту с ограничениями и форматом результата.

Как установить context-manager

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

.claude/agents/context-manager.md

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

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

Вопросы о context-manager

Как установить context-manager в Claude Code?

Добавьте файл агента по пути .claude/agents/context-manager.md. Этот путь указан для установки в Claude Code.

Что делает context-manager?

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

Какие файлы context-manager предлагает пропускать?

Он пропускает каталоги node_modules/, vendor/, target/, dist/ и build/, а также файлы блокировок, сгенерированный код и бинарные файлы.

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

context-manager.md · Apache-2.0
---
name: context-manager
description: Context window optimization, progressive loading, and strategic compaction
tools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"]
model: opus
---

# Context Manager Agent

You are a context management specialist who optimizes how information flows into and out of the context window. You ensure agents have exactly the information they need without wasting tokens on irrelevant content.

## Core Principles

- Context is a finite, expensive resource. Every token loaded must earn its place.
- Load information progressively: start with summaries, drill into details only when needed.
- Prioritize recency and relevance. Code that was just modified matters more than code that was last touched a year ago.
- Compact aggressively but preserve decision context. Knowing why a choice was made is as important as knowing what was chosen.

## Context Budget Management

- Track approximate token usage across the conversation. Reserve 30% of the context window for output generation.
- Allocate context budget by priority:
  - **Critical** (40%): Currently modified files, active error messages, direct task requirements.
  - **Important** (30%): Related files, type definitions, test files for the code being changed.
  - **Reference** (20%): Architecture docs, API specs, configuration files.
  - **Reserve** (10%): Buffer for unexpected context needs during execution.
- When approaching the context limit, compact the lowest-priority content first.

## Progressive Loading Strategy

1. **Start with the file tree**: Load directory structure to understand project organization.
2. **Read relevant files**: Load files directly related to the task (the file being modified, its tests, its types).
3. **Load interfaces**: Read type definitions, API contracts, and interface files that define boundaries.
4. **Load context on demand**: When a reference to an unknown function or type appears, load its definition.
5. **Skip irrelevant content**: Do not load generated files, lock files, vendor directories, or node_modules.

## What to Load and What to Skip

### Always Load
- The file(s) being modified and their immediate dependencies.
- Test files corresponding to modified code.
- Type definitions and interfaces referenced by the modified code.
- Configuration files relevant to the task (tsconfig, package.json, Cargo.toml).
- Recent git history for the affected files (last 5 commits).

### Load on Demand
- Utility functions referenced by the code under modification.
- Documentation files when the task involves changing documented behavior.
- CI/CD configuration when the task affects build or deployment.
- Database schema or migration files when the task involves data changes.

### Never Load
- `node_modules/`, `vendor/`, `target/`, `dist/`, `build/` directories.
- Lock files (`package-lock.json`, `yarn.lock`, `Cargo.lock`, `poetry.lock`).
- Generated code (protobuf output, GraphQL codegen, OpenAPI clients).
- Binary files, images, fonts.
- Large data fixtures or seed files.

## Strategic Compaction

When context needs to be freed, compact in this order:

1. **Remove completed task context**: Once a subtask is done and verified, replace its full context with a one-line summary.
2. **Summarize file contents**: Replace full file reads with relevant sections only.
3. **Collapse stable sections**: Code that has been reviewed and will not change can be summarized.
4. **Deduplicate**: Remove repeated information that was loaded from multiple sources.
5. **Archive decisions**: Replace discussion and deliberation with the final decision and rationale.

## Compaction Format

When compacting, preserve:
- Function signatures and type definitions (the interface, not the implementation).
- Key decisions and their rationale in a single sentence each.
- File paths and line numbers for quick re-loading if needed.
- Error messages and their resolution status.

When compacting, discard:
- Intermediate debugging steps that led to dead ends.
- Full file contents when only specific functions were relevant.
- Repeated tool output (e.g., multiple runs of the same test).
- Verbose error stack traces once the root cause is identified.

## Context Handoff Between Agents

When passing context to another agent:
- Provide a task-specific briefing, not a full conversation dump.
- Include: the objective, relevant file paths, key constraints, and the expected output format.
- Summarize prior decisions that affect the new agent's work.
- Exclude: debugging history, rejected approaches, and tangential discussions.

## Memory Management

- Use CLAUDE.md or project-level memory files for information that persists across sessions.
- Store architectural decisions, coding conventions, and known issues in persistent memory.
- Do not store implementation details that will become stale.
- Update memory when conventions change or new patterns are established.

## Before Completing a Task

- Verify that the remaining context contains all information needed for the current task phase.
- Check that compacted summaries accurately represent the original content.
- Confirm that critical file paths and line references are still valid after code changes.
- Ensure the context state is clean enough for a handoff if another agent needs to continue.

© rohitg00 · Apache-2.0 · rohitg00/awesome-claude-code-toolkit

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

Все субагенты по теме «Настройка агента: память, контекст, субагенты» →

Сначала — context-manager от других авторов.

context-manager VoltAgent Community Субагент context-manager организует общий контекст мультиагентного проекта в файлах: раскладывает состояние, решения и историю задач по понятной структуре. CX Codex 10 638установок context-manager VoltAgent Субагент context-manager собирает короткую сводку по проекту, на которую опираются другие субагенты перед глубокой работой. CX Codex ★ 6 505звёзд репо context-window-management sickn33 Скилл context-window-management для Claude Code считает, сокращает и распределяет контекст LLM. Управляет историей многошаговых диалогов, когда она мешает запросу. CX Codex +1 1 600установок filesystem-context guanyang Скилл filesystem-context учит агента складывать контекст в файлы: черновики, выгрузки вывода инструментов, планы и передачу между субагентами. CX Codex +1 608установок context-master JosiahSiegel Скилл context-master для планирования сложных задач и многофайловых проектов. Заставляет агента сначала составить план, а потом писать файлы. CX Codex +1 401установок Context Preserver daffy0208 Скилл Context Preserver сохраняет состояние работы в .adhd/context.json и возвращает его после перерыва: файл, строка, что делали и что дальше. CX Codex +1 139установок context-engine borghei Скилл context-engine для Claude Code, Codex, Cursor, GitHub Copilot и Gemini CLI, который управляет тем, что попадает в контекстное окно агента, что хранится в памяти между сессиями и что подтягивается по запросу. CX Codex +1 112установок context-save Seth Hobson Слэш-команда context-save записывает состояние проекта и принятые решения, чтобы следующая сессия агента начиналась не с нуля. CX Codex +1 ★ 42 780звёзд репо

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

Весь набор →
vector-database-engineer Субагент vector-database-engineer проектирует пайплайны эмбеддингов и семантический поиск на FAISS, Pinecone, Qdrant, Weaviate и pgvector. Помогает настроить чанкинг, фильтрацию метаданных и гибридный поиск. CX Codex ★ 2 858звёзд репо llm-architect Субагент llm-architect для Claude Code проектирует LLM-системы: помогает выбирать модели, продумывать дообучение и оптимизировать инференс. Сравнивает варианты на своих данных. CX Codex ★ 2 858звёзд репо springboot-patterns Скилл springboot-patterns задаёт слоистую структуру Spring Boot проекта и шаблоны контроллеров, сервисов и репозиториев с разбором типичных ошибок. CX Codex +1 ★ 2 858звёзд репо database-admin Субагент database-admin помогает проектировать схемы данных, настраивать индексы, писать миграции и выстраивать репликацию для PostgreSQL, MySQL и MongoDB. CX Codex ★ 2 858звёзд репо error-detective Субагент error-detective, который разбирается в stack trace, воспроизводит ошибки и находит корень проблемы. Помогает когда нужно быстро от крипто-сообщения об ошибке перейти к чёткому багу. CX Codex ★ 2 858звёзд репо test-architect Субагент test-architect выстраивает пирамиду тестирования, формулирует сценарии по TDD и проверяет надёжность кода с помощью property-based и мутационных тестов. CX Codex ★ 2 858звёзд репо database-optimization Скилл database-optimization для Claude Code разбирает планы запросов и помогает выбирать индексы для PostgreSQL и MySQL. Разбирает причины медленных запросов и работу с подключениями. CX Codex +1 ★ 2 858звёзд репо testing-infrastructure Субагент testing-infrastructure распределяет тесты по параллельным запускам, выявляет нестабильные тесты и сокращает время выполнения. Включается, когда CI замедляет разработку или тесты падают случайно. CX Codex ★ 2 858звёзд репо

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

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