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

langgraph-code-review — скилл для Claude Code: обзор и установка

Скилл проверяет код на базе LangGraph в Claude Code и других агентах. Он находит мутации состояния, пропущенные редьюсеры и ошибки в узлах графа.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add existential-birds/beagle --skill langgraph-code-review -a claude-code
Открыть на GitHub

Что делает langgraph-code-review

Скилл анализирует пайплайны на базе LangGraph перед запуском или деплоем. Проверка идёт поэтапно через пять строгих шагов: поиск графовых вызовов, разбор схемы состояния, проверка персистентности, сбор цитат с номерами строк и сверка с контрольным списком. Модель ищет мутации словаря состояния вместо возврата частичных обновлений, отсутствие add_messages или operator.add у списков, а также вызовы interrupt без настроенного чекпоинтера.

В скилл встроен нулевой рубеж защиты от галлюцинаций. Нейросети часто критикуют код по памяти или домысливают детали из контекста ветки. Поэтому ревьюер обязан сначала процитировать точный фрагмент file:line из свежепрочитанного файла, и только потом фиксировать проблему. Если цитаты нет, замечание считается недействительным.

Инструмент выявляет структурные поломки в StateGraph: забытый вход от START, недостижимые узлы и функции ветвления, где в add_conditional_edges пропущены возможные ветви. Для объектов Command проверяется наличие параметра destinations, иначе ломается визуализация графа.

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

  • найти прямые мутации состояния вместо возврата частичных обновлений
  • обнаружить пропущенные редьюсеры operator.add и add_messages в схемах
  • проверить передачу thread_id и настройку чекпоинтеров при вызовах interrupt
  • выявить висячие узлы и неполные ветки в add_conditional_edges

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

  • Проверь файл agent/graph.py на ошибки в логике LangGraph и схеме состояния.
  • Найди мутации словаря состояния и пропущенные редьюсеры в графе.
  • Проведи ревью графа: проверь чекпоинтеры, передачу thread_id и граничные пути.

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

1Через Skills CLI (Vercel)

npx skills add existential-birds/beagle --skill langgraph-code-review -a claude-code

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

~/.claude/skills/langgraph-code-review/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/langgraph-code-review/

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

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

react-flow Помогает ассистенту создавать интерактивные диаграммы и графы на базе @xyflow/react. Пригодится при настройке узлов, связей и управлении зумом. CX Codex +1 1 300установок python-code-review Скилл проверяет файлы Python на ошибки в типах, блокирующие вызовы в async-функциях и нарушение PEP8. Пригодится при подготовке пуллреквестов и чистке кодовой базы. CX Codex +1 920установок tailwind-v4 Скилл для ИИ-агента, который подсказывает, как настроить Tailwind CSS v4: тема в CSS, токены дизайна, цвета OKLCH и тёмная тема. CX Codex +1 812установок react-router-v7 Скилл с практиками React Router v7: подсказывает, когда брать loader, Form или fetcher, и как настраивать вложенные маршруты. CX Codex +1 572установок vitest-testing Скилл для ИИ-агента: подсказывает, как писать тесты на Vitest — ассерты, моки, асинхронность, конфиг. Пригодится, когда в проекте уже стоит Vitest. CX Codex +1 467установок shadcn-ui Подсказывает агенту, как собирать компоненты на shadcn/ui: Radix, Tailwind, CVA-варианты и data-slot. CX Codex +1 351установок react-flow-code-review Проверяет код на @xyflow/react по чек-листу: антипаттерны, лишние ре-рендеры, типы. Пригодится, когда граф тормозит или ноды пересоздаются. CX Codex +1 319установок

Похожие

langgraph-persistence langchain-ai Скилл по персистентности LangGraph: как подключить checkpointer, развести диалоги по thread_id и откатиться к прошлому состоянию графа. CX Codex +1 18 000установок langgraph-fundamentals langchain-ai Скилл для написания кода LangGraph на любой платформе. Охватывает StateGraph, схемы состояния, ноды, рёбра, Command, Send, invoke, потоковую передачу и обработку ошибок. CX Codex +1 18 000установок options-analytics-agent-langgraph reason-machines Собирает агента на LangGraph для разбора опционов: данные Polygon.io, кэш в ChromaDB, память между сессиями. Пригодится, если нужен свой торговый ассистент, а не готовый сервис. CX Codex +1 2 000установок langgraph sickn33 Скилл для построения продакшн-grade агентов с явной структурой. Помогает проектировать граф-топологию, управлять состоянием, добавлять циклы и ветвления, сохранять прогресс через checkpointer'ы и встраивать человека в цикл решений. CX Codex +1 1 300установок traiage-review NeoLabHQ Скилл расставляет приоритеты при ревью изменений в кодовой базе и отбирает файлы, на которые человеку стоит взглянуть в первую очередь. CX Codex +1 381установок django-perf-review getsentry Скилл проверяет Django-код на N+1 запросы, неограниченные queryset и отсутствующие индексы. Пригодится перед релизом или когда страница тормозит на больших таблицах. CX Codex +1 2 900установок

Рядом в теме «Код-ревью и рефакторинг»

Всё по теме «Код-ревью и рефакторинг» →

Вопросы о langgraph-code-review

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

Выполните команду npx skills add existential-birds/beagle --skill langgraph-code-review -a claude-code в терминале проекта. Скилл сохранится и станет доступен агенту.

Что делает langgraph-code-review?

Скилл пошагово проверяет код StateGraph на ошибки работы с памятью, отсутствие чекпоинтеров для interrupt, мутации словарей и разорванные связи между узлами.

Зачем в скилле нужен предварительный рубеж anti-confabulation?

Он запрещает агенту выставлять замечание без цитирования свежепрочитанного фрагмента с указанием file:line. Это страхует от выдуманных ошибок, когда модель критикует несуществующий в файле код.

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

SKILL.md · Apache-2.0
---
name: langgraph-code-review
description: Reviews LangGraph code for bugs, anti-patterns, and improvements. Use when reviewing code that uses StateGraph, nodes, edges, checkpointing, or other LangGraph features. Catches common mistakes in state management, graph structure, and async patterns.
---

# LangGraph Code Review

When reviewing LangGraph code, check for these categories of issues.

## Anti-confabulation (gate 0 — runs before every other gate)

Before issuing **any** finding — flag a bug, anti-pattern, or improvement — you MUST echo the exact artifact you are judging, quoted from a source you read in **this** turn:

- The code finding: its `file:line` plus the cited code, read freshly now.
- The graph/state code under review: the `StateGraph`, node, edge, or state-schema snippet your finding depends on, quoted from the file you just read.

> The artifact is the only source of truth. **Never** infer what you are reviewing from the branch name, the working directory, surrounding files, or recollection. If your mental model differs from the freshly read source, **the source wins.** A finding issued without a same-turn echo of its target is invalid — emit the echo first, or do not emit the finding.

This gate exists because an LLM under contextual priming will confidently flag code that is not in the file. It runs **before** the gates below.

## Review gates (sequenced)

Complete in order. Each step has an objective pass condition before moving on.

1. **Locate graph code** — Search the review scope for `StateGraph`, `compile(`, `invoke`, `ainvoke`, `add_node`, `add_edge`, `add_conditional_edges`. **Pass:** a short list of file paths (or explicit “none in scope” after searching).

2. **Map state schema** — For each graph state type (`TypedDict`, `BaseModel`, etc.), list fields that hold lists, dicts, or messages and whether `Annotated` + reducers (`add_messages`, `operator.add`, …) are present. **Pass:** every such field is either covered by a reducer pattern below or explicitly flagged as intentional overwrite.

3. **Trace persistence** — If interrupts, `thread_id`, or checkpoint APIs appear, follow them to `compile(..., checkpointer=...)` and invocation `config`. **Pass:** behavior matches the interrupt/checkpointer/thread_id guidance below—or you document a concrete mismatch with file:line.

4. **Report with evidence** — For each finding you will deliver, record **file path and line number(s)** (or a minimal quoted snippet). **Pass:** no critical or high-severity issue is stated without that citation.

5. **Run the checklist** — Use the checklist at the end of this skill; each item is **satisfied**, **not applicable** (with reason), or **open** with evidence. **Pass:** no item left silently unchecked.

## Critical Issues

### 1. State Mutation Instead of Return

```python
# BAD - mutates state directly
def my_node(state: State) -> None:
    state["messages"].append(new_message)  # Mutation!

# GOOD - returns partial update
def my_node(state: State) -> dict:
    return {"messages": [new_message]}  # Let reducer handle it
```

### 2. Missing Reducer for List Fields

```python
# BAD - no reducer, each node overwrites
class State(TypedDict):
    messages: list  # Will be overwritten, not appended!

# GOOD - reducer appends
class State(TypedDict):
    messages: Annotated[list, operator.add]
    # Or use add_messages for chat:
    messages: Annotated[list, add_messages]
```

### 3. Wrong Return Type from Conditional Edge

```python
# BAD - returns invalid node name
def router(state) -> str:
    return "nonexistent_node"  # Runtime error!

# GOOD - use Literal type hint for safety
def router(state) -> Literal["agent", "tools", "__end__"]:
    if condition:
        return "agent"
    return END  # Use constant, not string
```

### 4. Missing Checkpointer for Interrupts

```python
# BAD - interrupt without checkpointer
def my_node(state):
    answer = interrupt("question")  # Will fail!
    return {"answer": answer}

graph = builder.compile()  # No checkpointer!

# GOOD - checkpointer required for interrupts
graph = builder.compile(checkpointer=InMemorySaver())
```

### 5. Forgetting Thread ID with Checkpointer

```python
# BAD - no thread_id
graph.invoke({"messages": [...]})  # Error with checkpointer!

# GOOD - always provide thread_id
config = {"configurable": {"thread_id": "user-123"}}
graph.invoke({"messages": [...]}, config)
```

## State Schema Issues

### 6. Using add_messages Without Message Types

```python
# BAD - add_messages expects message-like objects
class State(TypedDict):
    messages: Annotated[list, add_messages]

def node(state):
    return {"messages": ["plain string"]}  # May fail!

# GOOD - use proper message types or tuples
def node(state):
    return {"messages": [("assistant", "response")]}
    # Or: [AIMessage(content="response")]
```

### 7. Returning Full State Instead of Partial

```python
# BAD - returns entire state (may reset other fields)
def my_node(state: State) -> State:
    return {
        "counter": state["counter"] + 1,
        "messages": state["messages"],  # Unnecessary!
        "other": state["other"]          # Unnecessary!
    }

# GOOD - return only changed fields
def my_node(state: State) -> dict:
    return {"counter": state["counter"] + 1}
```

### 8. Pydantic State Without Annotations

```python
# BAD - Pydantic model without reducer loses append behavior
class State(BaseModel):
    messages: list  # No reducer!

# GOOD - use Annotated even with Pydantic
class State(BaseModel):
    messages: Annotated[list, add_messages]
```

## Graph Structure Issues

### 9. Missing Entry Point

```python
# BAD - no edge from START
builder.add_node("process", process_fn)
builder.add_edge("process", END)
graph = builder.compile()  # Error: no entrypoint!

# GOOD - connect START
builder.add_edge(START, "process")
```

### 10. Unreachable Nodes

```python
# BAD - orphan node
builder.add_node("main", main_fn)
builder.add_node("orphan", orphan_fn)  # Never reached!
builder.add_edge(START, "main")
builder.add_edge("main", END)

# Check with visualization
print(graph.get_graph().draw_mermaid())
```

### 11. Conditional Edge Without All Paths

```python
# BAD - missing path in conditional
def router(state) -> Literal["a", "b", "c"]:
    ...

builder.add_conditional_edges("node", router, {"a": "a", "b": "b"})
# "c" path missing!

# GOOD - include all possible returns
builder.add_conditional_edges("node", router, {"a": "a", "b": "b", "c": "c"})
# Or omit path_map to use return values as node names
```

### 12. Command Without destinations

```python
# BAD - Command return without destinations (breaks visualization)
def dynamic(state) -> Command[Literal["next", "__end__"]]:
    return Command(goto="next")

builder.add_node("dynamic", dynamic)  # Graph viz won't show edges

# GOOD - declare destinations
builder.add_node("dynamic", dynamic, destinations=["next", END])
```

## Async Issues

### 13. Mixing Sync/Async Incorrectly

```python
# BAD - async node called with sync invoke
async def my_node(state):
    result = await async_operation()
    return {"result": result}

graph.invoke(input)  # May not await properly!

# GOOD - use ainvoke for async graphs
await graph.ainvoke(input)
# Or provide both sync and async versions
```

### 14. Blocking Calls in Async Context

```python
# BAD - blocking call in async node
async def my_node(state):
    result = requests.get(url)  # Blocks event loop!
    return {"result": result}

# GOOD - use async HTTP client
async def my_node(state):
    async with httpx.AsyncClient() as client:
        result = await client.get(url)
    return {"result": result}
```

## Tool Integration Issues

### 15. Tool Calls Without Corresponding ToolMessage

```python
# BAD - AI message with tool_calls but no tool execution
messages = [
    HumanMessage(content="search for X"),
    AIMessage(content="", tool_calls=[{"id": "1", "name": "search", ...}])
    # Missing ToolMessage! Next LLM call will fail
]

# GOOD - always pair tool_calls with ToolMessage
messages = [
    HumanMessage(content="search for X"),
    AIMessage(content="", tool_calls=[{"id": "1", "name": "search", ...}]),
    ToolMessage(content="results", tool_call_id="1")
]
```

### 16. Parallel Tool Calls Before Interrupt

```python
# BAD - model may call multiple tools including interrupt
model = ChatOpenAI().bind_tools([interrupt_tool, other_tool])
# If both called in parallel, interrupt behavior is undefined

# GOOD - disable parallel tool calls before interrupt
model = ChatOpenAI().bind_tools(
    [interrupt_tool, other_tool],
    parallel_tool_calls=False
)
```

## Checkpointing Issues

### 17. InMemorySaver in Production

```python
# BAD - in-memory checkpointer loses state on restart
graph = builder.compile(checkpointer=InMemorySaver())  # Testing only!

# GOOD - use persistent storage in production
from langgraph.checkpoint.postgres import PostgresSaver
checkpointer = PostgresSaver.from_conn_string(conn_string)
graph = builder.compile(checkpointer=checkpointer)
```

### 18. Subgraph Checkpointer Confusion

```python
# BAD - subgraph with explicit False prevents persistence
subgraph = sub_builder.compile(checkpointer=False)

# GOOD - use None to inherit parent's checkpointer
subgraph = sub_builder.compile(checkpointer=None)  # Inherits from parent
# Or True for independent checkpointing
subgraph = sub_builder.compile(checkpointer=True)
```

## Performance Issues

### 19. Large State in Every Update

```python
# BAD - returning large data in every node
def node(state):
    large_data = fetch_large_data()
    return {"large_field": large_data}  # Checkpointed every step!

# GOOD - use references or store
from langgraph.store.memory import InMemoryStore

def node(state, *, store: BaseStore):
    store.put(namespace, key, large_data)
    return {"data_ref": f"{namespace}/{key}"}
```

### 20. Missing Recursion Limit Handling

```python
# BAD - no protection against infinite loops
def router(state):
    return "agent"  # Always loops!

# GOOD - check remaining steps or use RemainingSteps
from langgraph.managed import RemainingSteps

class State(TypedDict):
    messages: Annotated[list, add_messages]
    remaining_steps: RemainingSteps

def check_limit(state):
    if state["remaining_steps"] < 2:
        return END
    return "continue"
```

## Code Review Checklist

1. [ ] State schema uses Annotated with reducers for collections
2. [ ] Nodes return partial state updates, not mutations
3. [ ] Conditional edges return valid node names or END
4. [ ] Graph has path from START to all nodes
5. [ ] Checkpointer provided if using interrupts
6. [ ] Thread ID provided in config when using checkpointer
7. [ ] Tool calls paired with ToolMessages
8. [ ] Async nodes use async operations
9. [ ] Production uses persistent checkpointer
10. [ ] Recursion limits considered for loops

© existential-birds · Apache-2.0 · existential-birds/beagle

Смотрите также

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

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