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

diff-computation — правило для Claude Code: дифф перед ревью

Правило diff-computation задаёт порядок код-ревью: сначала вычисляет дифф, затем читает файлы. Находки ограничены изменёнными строками, большие патчи читаются порциями.

MIT ★ 1 627 обновлён 2026-10-25

Установить в GitHub Copilot · Вручную: положить файлы Все способы и платформы ↓
.github/instructions/diff-computation.instructions.md
Открыть на GitHub

Что делает diff-computation

Правило задаёт порядок: дифф получают до того, как агент откроет хоть один файл исходников. Сначала идут git branch --show-current и git status --short, дальше — дерево решений из пяти случаев: обзор ветки или PR, незакоммиченные правки на main, выделенный код, отдельный коммит и «ревьюить нечего». Для ветки вызывается скилл pr-reference: generate.sh --base-branch auto --merge-base --exclude-ext min.js,min.css,map --output .copilot-tracking/pr/pr-reference.xml, затем список изменённых файлов и чтение диффа порциями через read-diff.sh --chunk N.

Область проверки зафиксирована. Находки берутся только со строк, которые дифф добавляет или меняет, полные файлы читаются ради контекста, а старые проблемы в неизменённом коде уходят в отдельную таблицу и не влияют на вердикт. Крупные диффы разбираются по размеру: меньше 20 файлов целиком, от 20 до 50 по каталогам, больше 50 партиями по 5-10 файлов; если изменений больше 2000 строк или 500 в одном файле, правило советует смотреть коммиты по одному.

Из ревью выпадают lock-файлы, минифицированные бандлы, source maps, бинарники и каталоги сборки. Работает это на скриптах скилла pr-reference; когда их нет или они падают, дифф считается вручную через git merge-base и git diff. Сам файл в .claude/rules/ ничего не подключает: в code-review.agent.md правило попадает только через импорт #file:, иначе агент его не увидит.

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

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

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

  • Проверь ветку feature/login: сначала посчитай дифф по правилу diff-computation, потом читай файлы.
  • Сделай ревью незакоммиченных правок на main, неотслеживаемые файлы тоже включи.
  • Дифф большой — пройди его по частям через read-diff.sh --chunk N и пропусти lock-файлы.

Как установить diff-computation

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

.github/instructions/diff-computation.instructions.md

Поле applyTo задаёт, к каким файлам применять

По шагам, с командами для каждой платформы: AGENTS.md и CLAUDE.md: что это, кто читает и какой выбрать

Вопросы о diff-computation

Как установить diff-computation в Claude Code?

Скопировать файл по пути .claude/rules/diff-computation.md в проект. Чтобы правило срабатывало в ревью, добавьте импорт #file: в code-review.agent.md.

Что делает diff-computation?

Задаёт порядок получения диффа перед код-ревью: выбор ветки или коммита, фиксация области проверки, разбор больших диффов порциями и пропуск не-исходников.

Нужен ли для этого правила скилл pr-reference?

Для веток правило вызывает его скрипты generate.sh и list-changed-files.sh. Если их нет или они падают, дифф считается вручную через git merge-base и git diff.

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

diff-computation.instructions.md · MIT
---
description: "Code review diff computation: branch detection, scope locking, large-diff handling, and non-source filtering"
---

# Diff Computation Protocol

> Delivery: this file is delivered via the explicit `#file:` import in code-review.agent.md, not via `applyTo`. Plugin and extension distributions omit the repository artifact-root prefix, so a source-tree-qualified `applyTo` glob would match nothing once distributed. Future coding-standards agents or prompts that need this guidance must import it with `#file:` rather than relying on `applyTo`.

Obtain the diff before reading any source files. Use the decision tree below to determine the appropriate method, then apply scope rules and large diff handling.

## Decision Tree

Run `git branch --show-current` and `git status --short` to determine context. Match the first applicable case:

1. **Branch review** (user explicitly requests a specific branch or PR, or is on a feature branch that is not `main` and not detached HEAD): follow the Feature Branch Diff section. The pr-reference skill captures committed changes; a working-tree supplement captures staged, unstaged, and untracked changes. If the user says "review the PR" while on `main` or detached HEAD without naming a branch, PR, or commit, ask which branch or PR they want reviewed, then route to this case or to the Specific Commit section as appropriate.
2. **Local uncommitted changes on `main` or detached HEAD** (not on a feature branch, but edits exist that are not yet committed): follow the Uncommitted Changes section.
3. **Selected code or `#file` references** (user selects code in the editor or references `#file:path/to/file.ext`): follow the Selected Code section.
4. **Specific commit review** (user asks to review a particular commit): follow the Specific Commit section.
5. **No reviewable content**: inform the user that no diff could be determined and stop.

## Feature Branch Diff

Invoke the **pr-reference** skill to compute the diff. The skill handles branch detection, merge-base resolution, file listing, non-source exclusions, and large diff chunking.

1. Generate the structured diff to an explicit output path so that path is a single source of truth the review agent reuses for `diffPatchPath` (overridable, not implicitly coupled to the skill default):

   ```bash
   generate.sh --base-branch auto --merge-base --exclude-ext min.js,min.css,map --output .copilot-tracking/pr/pr-reference.xml
   ```

   ```powershell
   generate.ps1 -BaseBranch auto -MergeBase -ExcludeExt min.js,min.css,map -OutputPath .copilot-tracking/pr/pr-reference.xml
   ```

2. Get the changed file list:

   ```bash
   list-changed-files.sh --exclude-type deleted --format plain
   ```

   ```powershell
   list-changed-files.ps1 -ExcludeType Deleted -Format Plain
   ```

3. For large diffs, use chunk planning and batched analysis:

   ```bash
   read-diff.sh --info       # chunk count and size summary
   read-diff.sh --chunk N    # read chunk N
   ```

   ```powershell
   read-diff.ps1 -Info        # chunk count and size summary
   read-diff.ps1 -Chunk N     # read chunk N
   ```

If the changed-file list (`list-changed-files.sh` or `list-changed-files.ps1`) returns an empty list, stop and report "no reviewable content" per Decision Tree case 5.

Pass the diff output and file list as pre-computed input to the review agent so it skips its own scope detection.

## Uncommitted Changes

* Unstaged: `git diff HEAD`
* Staged: `git diff --cached`
* Untracked (new files not yet staged): enumerate with `git ls-files --others --exclude-standard`, then read the full content of each file as the review input.

## Selected Code

Use the provided code as the review input; no git diff is needed. Apply all loaded skills or review logic to the selected code. Skip artifact persistence since there is no branch context.

## Specific Commit

```bash
git diff <commit>^..<commit>
```

## Scope Rules

* Do not enumerate, list, or read source files before obtaining the diff or review input.
* Only lines present in the diff (added or modified lines) are in scope for findings.
* For selected code reviews (no diff context), all provided code lines are in scope.
* Read full file contents only for contextual understanding of diff lines, never as a source of findings.
* Pre-existing issues in unchanged code go in the **Out-of-scope Observations** table, clearly labelled and excluded from the verdict.

## Large Diff Handling

Use the `timeout` parameter on terminal commands to prevent hanging on large repositories.

| Changed Files | Strategy                                                       |
|---------------|----------------------------------------------------------------|
| Fewer than 20 | Analyze all files with full diffs.                             |
| 20 to 50      | Group files by directory and analyze each group.               |
| More than 50  | Progressive batched analysis, processing 5-10 files at a time. |

When a diff exceeds 2000 lines of combined changes or 500 lines in a single file, review the most recent commits individually using `git log --oneline` and `git show --stat`.

## Non-Source Artifact Skip List

Skip these artifacts when computing and analyzing diffs:

* Lock files: `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`
* Minified bundles: `.min.js`, `.min.css`
* Source maps: `.map`
* Binaries
* Build output directories: `/bin/`, `/obj/`, `/node_modules/`, `/dist/`, `/out/`, `/coverage/`

### Fallback (pr-reference skill unavailable)

If the pr-reference skill scripts are not found or fail, compute the diff manually:

1. Resolve the merge-base: `git merge-base origin/<default-branch> HEAD`
2. Generate the diff: `git diff <merge-base>...HEAD`
3. List changed files: `git diff <merge-base>...HEAD --name-only`
4. For uncommitted changes, supplement with `git diff HEAD`, `git diff --cached`, and `git ls-files --others --exclude-standard`

Apply the Non-Source Artifact Skip List and Large Diff Handling rules to the manual output.

© microsoft · MIT · microsoft/hve-core

Похожие правила IDE

Все правила IDE по теме «Код-ревью и рефакторинг» →
understand-diff Egonex-AI Скилл understand-diff сопоставляет изменения в Git с графом знаний проекта, чтобы оценить затронутые компоненты и радиус поломки. Пригодится перед ревью пуллреквестов. CX Codex +1 4 200установок diff-context Barnett-Studios Скилл diff-context собирает git-дифф вместе с контекстом зависимостей через утилиту cxpak. Он помогает ассистенту подготовить описание PR или провести ревью кода с учётом импортов и типов. CX Codex +1 ★ 34звёзд репо diff-analyze ruvnet Скилл diff-analyze анализирует git-дифф перед PR: оценивает риск, классифицирует изменения и предлагает роли ревьюеров. Нужен перед слиянием крупных правок. CX Codex +1 753установок diff-scanning-with-aws-security-agent aws Скилл diff-scanning-with-aws-security-agent для Claude Code и других ИИ-редакторов, запускает AWS Security Agent только на изменённом коде с указанного git-рефа. Срабатывает перед коммитом или PR. CX Codex +1 1 600установок security-diff-scan официальный OpenAI Скилл security-diff-scan для Codex проверяет пул-реквесты, коммиты и патчи на уязвимости. Агент анализирует изменённые файлы и связанные участки кода для выявления угроз. CX Codex GP ChatGPT +1 30установок explain-diff Nick Nisi Скилл explain-diff разбирает diff, PR, ветку или коммит и готовит HTML-документ с контекстом, схемами, разбором кода и тестом. Пригодится, чтобы понять изменение самому или объяснить его команде. CX Codex +1 ★ 114звёзд репо

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

Весь набор →
analysis-authoring Скилл analysis-authoring задаёт правила оформления EDA-ноутбуков и аналитических дашбордов: порядок разделов, выбор графиков и лимиты производительности. CX Codex +1 ★ 1 627звёзд репо RPI Reviewer Субагент RPI Reviewer для Claude Code разбирает назначенный фрагмент RPI-доказательств и возвращает кандидатов на находки с местами подтверждения. Используется в больших сравнениях. CX Codex +1 ★ 1 627звёзд репо rai-standards Скилл rai-standards для Claude Code собирает стандарты ответственного ИИ: NIST AI RMF 1.0, оверлей AI STRIDE и требования EU AI Act по этапам разработки. CX Codex +1 ★ 1 627звёзд репо data-catalog Скилл data-catalog помогает составить Markdown-каталог данных с сущностями и их связями. Он пригодится при инвентаризации данных и подготовке каталога к построению ERD. CX Codex +1 ★ 1 627звёзд репо Supply Chain Skill Assessor Субагент Supply Chain Skill Assessor оценивает supply-chain проекта по скиллу supply-chain-security и отдаёт таблицу находок: что закрыто, что частично, где дыра. Пригодится перед релизом или разбором CI. CX Codex +1 ★ 1 627звёзд репо privacy-standards Скилл privacy-standards для Claude Code содержит справочные материалы по конфиденциальности. Используется для анализа потоков данных, оценки порогов DPIA и сопоставления требований. CX Codex +1 ★ 1 627звёзд репо copilot-tracking Правило задаёт, как хранить промежуточные материалы RPI, HVE Builder и других рабочих процессов в .copilot-tracking/. Оно помогает агенту вести исследование, планы и ревью в согласованных файлах. CX Codex +1 ★ 1 627звёзд репо demo-video Скилл demo-video собирает демо-видео из упорядоченных кадров или клипов, WAV-озвучки и переходов через FFmpeg. Для первых прототипных роликов и туториалов. CX Codex +1 ★ 1 627звёзд репо

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

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