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

arch — команда для Claude Code: карта архитектуры проекта

Команда для построения и проверки .arch/index.json — карты, которая связывает каждый компонент архитектуры с файлами, которые его реализуют. Находит, когда файлы и описание компонентов перестали совпадать.

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

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

Что делает arch

Команда arch решает две задачи: построить карту архитектуры с нуля или проверить, не разошлась ли она с реальным кодом. Работает через три подкоманды: build создаёт .arch/index.json по текущему состоянию репозитория, drift сравнивает существующую карту с деревом файлов и находит расхождения, check запускает валидатор без записи изменений.

Процесс состоит из четырёх слоёв. Первый — детерминированный, без агентов: команда проверяет экосистему, смотрит, не было ли слишком много изменений с момента последней привязки, и для неизменённых деревьев завершает работу сразу. Второй — агент-архитектор синтезирует индекс. Третий — две параллельные проверки: рецензент архитектуры смотрит на связность и ясность компонентов, эксперт домена проверяет, совпадает ли описание с кодом. Четвёртый — финальный агент применяет замечания и рисует диаграмму.

Каждый run привязан к коммиту через .arch/pinned-commit, и индекс обновляется только если все проверки пройдены. Результат пишется в .arch/index.json, доказательства валидации — в .arch/ARCH-EVIDENCE.md.

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

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

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

  • Какие файлы реализуют компонент 'api'?
  • /team arch drift
  • /team arch build --full

Как установить arch

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

.claude/commands/arch.md

Вызов — /arch. Для всех проектов — ~/.claude/commands/

Вопросы об arch

Как установить arch в Claude Code?

Скопируй файл .claude/commands/arch.md в репозиторий по пути .claude/commands/. Команда будет доступна через /team arch в Claude Code.

Что делает arch?

Команда создаёт и проверяет .arch/index.json — индекс, который показывает, какие файлы реализуют каждый компонент архитектуры. Также находит, когда файлы и описание компонентов расходятся.

Чем отличаются подкоманды build, drift и check?

build создаёт индекс с нуля, drift проверяет существующий индекс на расхождения с кодом и обновляет его, check запускает только валидацию без записи изменений.

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

arch.md · MIT
---
description: "Use when asked which files implement a component, to build or refresh .arch/index.json, or to check whether the architecture map drifted. Pins the index to a commit, validates every path, and writes ARCH-EVIDENCE.md."
---
# /team arch — Architecture Index Pipeline

> Called by team.md router when action is `arch`.
> Builds and validates `.arch/index.json`, the commit-pinned map from each
> architectural component to the real files that implement it, and detects when that
> map has stopped being true.
>
> Governed by `team:architecture.md`. **Paths or it does not exist.**

## Usage

```
/team arch [build|drift|check] [scope] [--full] [--roles <ids>]
```

Default subcommand: `drift` when `.arch/pinned-commit` exists, `build` when it does not.
Scope is optional; when given it narrows the analysis to a subtree.

| Subcommand | Purpose |
|---|---|
| `build` | Produce a fresh index from scratch |
| `drift` | Reconcile an existing index against the current tree |
| `check` | Run the validator alone and capture evidence. No model calls, no writes to `index.json`. |

## Role Selection Bias

| Layer | Preferred Roles | Count |
|-------|----------------|-------|
| L1 | technical-analyst; security-analyst if domain includes api/backend/infrastructure; repo-cartographer only on the fallback crawl | 0-2 |
| L2 | solution-architect | 1 |
| L3 | architecture-reviewer, domain-accuracy | 2 |
| L4 | principal-architect | 1 |

Layer 1 is **zero agents** when `.planning/codebase/` exists. That is the intended
common case, not a degradation.

## Pipeline Customization

### Stage 0: Deterministic gate — no agents, runs before pre-flight

This stage exists so that the most common invocation costs nothing.

1. Resolve the subcommand. Record `git rev-parse HEAD` as the pin candidate.
2. Detect the ecosystem from whichever manifest exists: `package.json`,
   `pyproject.toml`, `go.mod`, `Cargo.toml`, `pom.xml`, `Gemfile`, `*.csproj`.
3. Check for `.planning/codebase/` and for a gitnexus index.
4. For `drift`, run the scan and evaluate its gate:

```bash
python3 ~/.claude/skills/arch-index/scripts/arch_drift.py --repo-root .
```

| Gate | Action |
|---|---|
| `NONE` | Report `NO DRIFT — structural only`, write `.arch/ARCH-EVIDENCE.md`, and **end the run here**. No team is created, no agent is spawned. |
| `FULL_REBUILD` | Report that more than 300 files or 50,000 lines changed since the pin, so a rebuild is cheaper than a patch. Re-enter as `build`. |
| `INCREMENTAL` | Continue to pre-flight. |
| exit 2 | The scan could not run. Report why. This is **never** `NO DRIFT`. |

### Layer 1: Structural context (parallel, mode `default`)

**Skipped entirely when `.planning/codebase/` exists.** Read `ARCHITECTURE.md`,
`STRUCTURE.md`, `STACK.md`, and `INTEGRATIONS.md` from there directly and report the
skip. Spawning agents to re-derive a map that `gsd-map-codebase` already wrote is the
exact waste this action was built to remove.

Otherwise, if gitnexus is available, call `mcp__gitnexus__context` and
`mcp__gitnexus__group_list`. Record how many commits behind the index is in
`ecosystem.sourceCommitsBehind`. Stale grouping advice is tolerable here because every
path is checked against the working tree by the validator, so staleness can date the
decomposition but cannot introduce a path that does not exist.

Only if neither exists, spawn `repo-cartographer` under the three-phase read budget in
`skills/arch-index/references/tool-frugality.md`, writing `.arch/ANALYSIS.md` against the
seven-section skeleton in `references/analysis-taxonomy.md`.

Always run `python3 ~/.claude/skills/arch-index/scripts/repo_tree.py --repo-root .` for the
authoritative current tree. If it reports truncation, propagate that into
`ecosystem.treeTruncated` and **do not run `drift`** — reconciling against a partial
tree deletes components whose code is merely unseen.

### Layer 2: Synthesis (1 agent, `solution-architect`, mode `bypassPermissions`)

**Writes confined to `.arch/`.** This agent does not touch source files.

No tool use during synthesis. Read only the gathered summary plus the tree, and emit
`.arch/index.json` per `references/schema.md`, bound by `references/component-rules.md`.
Separating exploration from formatting is why the structured output stays in schema.

For `drift`, apply the `DRIFT.json` verdicts as settled fact: `REMOVE` deletes the
component and every connection to it, `PRUNE` drops the dead paths and keeps the
identifier, `KEEP` changes nothing. Preserve surviving identifiers. Then answer the one
open question the script cannot: do the unclaimed added files constitute a component
that should exist?

### Validation gate: deterministic, and a real BLOCK

```bash
python3 ~/.claude/skills/arch-index/scripts/validate_index.py .arch/index.json --repo-root .
```

Capture the command line, the exit code, and the per-check table into
`.arch/ARCH-EVIDENCE.md` per the template in `skills/arch-index/templates/`.

Exit 0 proceeds. Non-zero loops back to Layer 2 with the exact violation lines, bounded
to three rounds, then stops and reports what remains. **A validator that cannot be
executed is a BLOCK, not a pass.** There is deliberately no prose fallback here: a
fallback an agent can narrate is the failure mode this gate exists to remove. See
`team:architecture.md`.

### Layer 3: Review (parallel, read-only, mode `default`, 2 agents)

- **architecture-reviewer** — decomposition, coupling, boundary coherence, wishful
  components, vague titles, altitude drift.
- **domain-accuracy** — does each component's described capability match what the code
  at those paths actually does?

Findings use `CRITICAL | MAJOR | MINOR | SUGGESTION` with the component id and a quote,
compressed into `CRITIQUE-SUMMARY.md` at the standard 200-line cap. Any CRITICAL blocks
back to Layer 2.

Neither reviewer may treat a passing validator as evidence that the architecture is
sound. The validator proves the paths exist and the graph is well-formed, and nothing
more.

### Layer 4: Finalise (1 agent, `principal-architect`)

Apply the critique, re-run the validator, write `.arch/INDEX.md` from the template, and
emit the Mermaid `C4Container` source for rendering through `design:mermaid`
(beautiful-mermaid).

**Advance `.arch/pinned-commit` only after the validator exits 0.** A failed run leaves
the previous pin untouched, so a broken index can never present itself as current.

Emit feedback entries in the format at `_index.md`.

## Fast path

`build` is **not** fast-path eligible. An index that skips its review layer is worse
than no index, mirroring the evidence carve-out in the router.

`drift` is fast-path eligible in a stronger sense than any other action: Stage 0 can
complete the entire run with zero agents, and on an unchanged tree it always does.

## Artifacts

All of `.arch/` is committed except `DRIFT.json`, which is derived scratch and
gitignored. The index is only useful if it is diffable across runs and present in the
clean checkout that `team:ship.md` verifies from.

## Scope limit

This action detects **structural** drift: components whose code was deleted, moved, or
never claimed. It does not detect semantic drift, such as a component whose datastore
was swapped inside its own already-claimed directory. Every artifact it writes says so
in those words, and no consumer may drop them.

## GSD Integration

When `.planning/` exists, Layer 1 reads `.planning/codebase/` in preference to crawling,
and `plan.md` may use the index to populate the `files_modified` frontmatter field of
generated phase plans.

© coco-research · MIT · coco-research/coco

Похожие слэш-команды

Все слэш-команды по теме «Код-ревью и рефакторинг» →
arch-check codewithmukesh Скилл arch-check сверяет кодовую базу с заявленной архитектурой: направление зависимостей, нарушения слоёв, утечки между модулями и циклы. Пригодится перед релизом или после крупной фичи. CX Codex +1 3 900установок breakdown-epic-arch официальный github Скилл breakdown-epic-arch для GitHub Copilot превращает PRD Epic в высокоуровневую техническую архитектуру. Он формирует спецификацию с диаграммой системы и оценкой размера работы. CX Codex +1 9 000установок arch-diagram bassnova42 Скилл arch-diagram для Claude Code превращает исходный код, статьи или заметки в подробные архитектурные схемы. Он визуализирует структуру проекта в интерактивные HTML-страницы или диаграммы Mermaid. CX Codex +1 ★ 145звёзд репо arch-reviewer SethGammon Субагент arch-reviewer проверяет архитектурные границы слоёв, циклические импорты и правила проекта без изменения файлов. CX Codex ★ 937звёзд репо feature-arch PyModel Скилл feature-arch задаёт правила папок и границ модулей в React-проекте: 42 правила по 8 категориям, от структуры каталогов до имён файлов. CX Codex +1 609установок html-ppt-knowledge-arch-blueprint nexu-io Скилл html-ppt-knowledge-arch-blueprint для создания презентаций управленческого уровня в HTML — с раскладкой и визуальным языком шаблона knowledge-arch-blueprint. Подходит для ретро инцидентов, roadmap и архитектурных решений. CX Codex +1 184установок

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

Весь набор →
code-reviewer Субагент code-reviewer для ревью кода, архитектуры и безопасности. Проверяет SOLID, DDD, уязвимости, API-дизайн и производительность перед слиянием PR. CX Codex ★ 328звёзд репо coco-ads Превращает код готового проекта в короткое рекламное видео (15–25 секунд). Срабатывает на /coco-ads или фразу «сделай launch-видео». CX Codex +1 ★ 328звёзд репо mermaid Команда строит диаграммы Mermaid (блок-схемы, sequence, state, class, ER, XY-графики) в SVG, HTML или ASCII для терминала. CX Codex +1 ★ 328звёзд репо maker-mdap Скилл maker-mdap помогает проектировать длинные цепочки действий LLM через декомпозицию, голосование и отсев подозрительных ответов. CX Codex +1 ★ 328звёзд репо develop Команда develop запускает многоагентный пайплайн разработки и исправления кода с разделением файлов между агентами и обязательной проверкой регрессий. CX Codex +1 ★ 328звёзд репо data-specialist Субагент data-specialist для исследовательского анализа данных, машинного обучения и оптимизации SQL-запросов под PostgreSQL, MySQL, SQL Server и Oracle. CX Codex ★ 328звёзд репо media-use Скилл media-use собирает музыку, звуки, иконки и логотипы для проекта HyperFrames, озвучивает текст и правит кадры. CX Codex +1 ★ 328звёзд репо brain:init Скилл brain:init для Claude Code создаёт в каталоге проекта базу знаний project_brain.db и наполняет её данными из заметок, документации и истории решений. CX Codex +1 ★ 328звёзд репо

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

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