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

icpg — скилл для Claude Code: граф причин кода с контрактами

Скилл icpg отслеживает, ПОЧЕМУ существует каждая функция и модуль, через граф причин (ReasonNodes) с формальными контрактами.

MIT 156 установок ★ 713 обновлён 2026-10-13

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

Что делает icpg

iCPG добавляет слой причин поверх структуры кода. Каждый ReasonNode хранит цель, тип решения (бизнес-задача, архитектурное решение, патч), предусловия и постусловия в виде контрактов Design by Contract. Граф связывает причины с символами кода через шесть типов рёбер: CREATES, MODIFIES, REQUIRES, DUPLICATES, VALIDATED_BY и DRIFTS_FROM.

Скилл отслеживает шесть измерений дрейфа: изменение контрольной суммы без MODIFIES, нарушение постусловий, смены владельца, отсутствие тестов, использование вне исходной области и дрейф зависимостей. Перед любым изменением код запускает три канонических запроса: поиск предыдущей работы (дедупликация), получение ограничений для файла и профиль риска символа.

Хранилище — SQLite база в .icpg/reason.db на машине, в .gitignore. Установка требует Python и pip install ./scripts/icpg с опциональными зависимостями для векторизации (ChromaDB). Скилл не пользовательский — вызывается автоматически через PreToolUse хук перед любой правкой кода.

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

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

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

  • Перед тем как добавить новый метод аутентификации, запроси: icpg query prior "аутентификация JWT"
  • Узнай ограничения для файла: icpg query constraints src/auth/service.ts
  • Проверь профиль риска функции: icpg query risk validateToken

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

1Через Skills CLI (Vercel)

npx skills add alinaqi/maggy --skill icpg -a claude-code

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

~/.claude/skills/icpg/SKILL.md

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

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

Вопросы об icpg

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

Запусти npx skills add alinaqi/maggy --skill icpg -a claude-code, потом проверь ~/.claude/skills/icpg/SKILL.md.

Что делает icpg?

Строит граф причин кода: каждой функции или модулю сопоставляет цель, контракт (предусловия и постусловия) и отслеживает шесть видов дрейфа — когда код перестаёт соответствовать своему замыслу.

Нужны ли зависимости для работы?

Базовая версия работает с нулевыми зависимостями. Для векторной дедупликации установи pip install "./scripts/icpg[vectors]" с ChromaDB.

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

SKILL.md · MIT
---
name: icpg
description: Intent-Augmented Code Property Graph — tracks WHY code exists via ReasonNodes with formal contracts, 6-dimension drift detection, and 3 canonical pre-task queries for autonomous development
when-to-use: "Before any code change — query the reason graph for intent, constraints, and risk"
user-invocable: false
effort: high
---

# iCPG Skill (Intent-Augmented Code Property Graph)


**Purpose:** Add a Reason Graph layer on top of code structure so every
function, class, and module is traceable to the goal that created it,
the agent or human that owns it, and whether it's still doing what it
was supposed to do.

```
┌────────────────────────────────────────────────────────────────┐
│  iCPG = AST + CFG + PDG + RG (Reason Graph)                    │
│  ─────────────────────────────────────────────────────────────│
│  AST  = Abstract Syntax Tree (structure)      ← existing       │
│  CFG  = Control Flow Graph (execution paths)  ← existing       │
│  PDG  = Program Dependency Graph              ← existing       │
│  RG   = Reason Graph (WHY layer)              ← THIS SKILL     │
│                                                                │
│  The RG stores ReasonNodes (goals/tasks), links them to code   │
│  symbols via typed edges, enforces contracts (DbC), and        │
│  detects when code drifts from its original purpose.           │
│                                                                │
│  Storage: .icpg/reason.db (SQLite, per-project, gitignored)   │
│  CLI: icpg init | create | record | query | drift | bootstrap │
└────────────────────────────────────────────────────────────────┘
```

---

## Core Principle

**Intent first, code second.** Before writing or modifying code, query
the reason graph to understand WHY existing code was written, WHAT
constraints it must preserve, and WHETHER your change duplicates prior
work.

---

## The 3 Canonical Pre-Task Queries

**Every agent MUST run these before writing code:**

| # | Query | Command | What It Answers |
|---|-------|---------|-----------------|
| 1 | **search_prior_work** | `icpg query prior "<goal>"` | Has this been attempted before? Prevents duplication. |
| 2 | **get_constraints** | `icpg query constraints <file>` | What invariants apply to files I'll touch? Prevents breakage. |
| 3 | **get_risk_profile** | `icpg query risk <symbol>` | Is this symbol fragile? Drift history, ownership changes. |

---

## ReasonNode — The Core Primitive

Each ReasonNode captures a stated purpose with a formal contract:

```
id              UUID
goal            Natural language: what is this trying to achieve
decision_type   business_goal | arch_decision | task | workaround | constraint | patch
scope           Files/modules expected to be touched
owner           Human or agent accountable
status          proposed | executing | fulfilled | drifted | abandoned
source          manual | commit | inferred | agent-session

FORMAL CONTRACT (Design by Contract):
  preconditions    What must be true before this intent executes
  postconditions   What must be true when fulfilled
  invariants       What must remain true throughout and after
```

**Drift = predicate failure.** A symbol has drifted when its current
behavior no longer satisfies the postconditions of the ReasonNode that
created it, or when an invariant is violated.

---

## Six Edge Types

```
CREATES      Reason  → Symbol   (this intent created this function)
MODIFIES     Reason  → Symbol   (this intent changed this function)
REQUIRES     Reason  → Reason   (B depends on A being done first)
DUPLICATES   Reason  → Reason   (these two goals overlap)
VALIDATED_BY Reason  → Test     (this test proves the intent was satisfied)
DRIFTS_FROM  Symbol  → Reason   (this symbol no longer does what it was made for)
```

---

## 6-Dimension Drift Model

| Dimension | What It Means | Detection |
|-----------|--------------|-----------|
| **Spec drift** | Symbol checksum changed without a MODIFIES edge | Compare stored vs current checksum |
| **Decision drift** | Postconditions no longer hold | Evaluate predicates against codebase |
| **Ownership drift** | >3 different owners without coherent oversight | Count unique owners on edges |
| **Test drift** | VALIDATED_BY tests missing or failing | Check test file existence + run |
| **Usage drift** | Symbol used outside original scope | Grep for imports beyond scope |
| **Dependency drift** | Downstream REQUIRES reasons have drifted | Traverse REQUIRES edges |

Run `icpg drift check` to scan all dimensions. Each produces a 0-1 severity score.

---

## CLI Reference

### Setup
```bash
icpg init                          # Create .icpg/ and database
icpg bootstrap --days 90           # Infer ReasonNodes from git history
icpg bootstrap --days 90 --no-llm  # Without LLM (commit-message only)
```

### Create & Record
```bash
icpg create "Add JWT auth" --scope src/auth/ --owner feature-auth --type task
icpg record --reason <id> --base main         # Record symbols from git diff
icpg record --reason <id> --edge-type MODIFIES # Record as modifications
```

### Query (the 3 canonical queries)
```bash
icpg query prior "user authentication"     # 1. Duplicate detection
icpg query constraints src/auth/service.ts  # 2. Invariants for file
icpg query risk validateToken              # 3. Symbol risk profile
icpg query context src/auth/service.ts     # All intents for a file
icpg query blast <reason-id>               # Full blast radius
```

### Drift
```bash
icpg drift check          # Full scan across all dimensions
icpg drift resolve <id>   # Mark drift event resolved
```

### Status
```bash
icpg status               # Stats: reasons, symbols, edges, drift
```

---

## Storage

Per-project, gitignored, zero infrastructure:

```
.icpg/
  reason.db       SQLite database (4 tables: reasons, symbols, edges, drift_events)
  .gitignore      Contains: *
  chroma/         ChromaDB vectors (if chromadb installed)
  tfidf_cache.json  TF-IDF fallback cache
  .current-intent   Marker file for active intent (used by Stop hook)
```

Install options:
```bash
pip install ./scripts/icpg            # Core (zero deps)
pip install "./scripts/icpg[vectors]"  # + ChromaDB for duplicate detection
pip install "./scripts/icpg[all]"      # + ChromaDB + scikit-learn + openai
```

---

## Workflow: Before Any Code Change

```
0. INTENT       → icpg create (or identify existing intent)
1. DEDUP        → icpg query prior (check for duplicate work)
2. CONSTRAINTS  → icpg query constraints (understand invariants)
3. RISK         → icpg query risk (check fragile symbols)
4. LOCATE       → search_graph to find symbols (code-graph skill)
5. CHANGE       → Make the edit (PreToolUse hook shows context)
6. RECORD       → icpg record (link symbols to intent)
7. DRIFT CHECK  → icpg drift check (verify no unintended drift)
8. VERIFY       → Run tests, lint, typecheck
```

**Step 0 is non-negotiable for autonomous agents.** Every change must
be linked to a stated purpose. Without an intent, there's nothing to
measure drift against.

---

## Hook Integration

### PreToolUse Hook (automatic context injection)

Add to `.claude/settings.json`:
```json
{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Edit|Write",
      "hooks": [{
        "type": "command",
        "command": "scripts/icpg-pre-edit.sh",
        "timeout": 3,
        "statusMessage": "Checking intent context..."
      }]
    }]
  }
}
```

Before every file edit, agents see:
```
═══ iCPG CONTEXT ═══
INTENTS for src/auth/service.ts:
  [>] a1b2c3d4 — User authentication with JWT tokens
      Owner: feature-auth | Status: executing
      Invariants: 2
CONSTRAINTS for src/auth/service.ts:
  From intent: User authentication with JWT tokens
    INV: file_exists("src/auth/middleware.ts")
    POST: test_exists("src/auth/__tests__/service.test.ts")
PRESERVE function signatures unless your task requires changing them.
═══════════════════
```

### Stop Hook (automatic symbol recording)

After implementation passes tests, auto-records symbols:
```json
{
  "hooks": {
    "Stop": [{
      "hooks": [
        {"type": "command", "command": "scripts/tdd-loop-check.sh", "timeout": 60},
        {"type": "command", "command": "scripts/icpg-stop-record.sh", "timeout": 5}
      ]
    }]
  }
}
```

---

## Agent Teams Integration

### Updated Pipeline (agent-teams + iCPG)

```
 0. INTENT       Team lead creates ReasonNode from feature spec
 0b. DEDUP       icpg query prior — check for duplicate intents
 1. SPEC         Feature agent writes spec
 2. SPEC-REVIEW  Quality agent reviews spec + intent alignment
 3. TESTS (RED)  Feature agent writes tests
 4. RED-VERIFY   Quality agent verifies tests fail
 5. IMPLEMENT    Feature agent codes (PreEdit hook shows context)
 5b. RECORD      Auto-record symbols → intent (Stop hook)
 5c. DRIFT-CHECK Quality agent verifies no scope drift
 6. GREEN-VERIFY Quality agent verifies tests pass + coverage
 7. VALIDATE     Lint + typecheck + full suite
 8. CODE-REVIEW  Review agent (sees intent context per file)
 9. SECURITY     Security agent
10. BRANCH-PR    Merger agent (PR includes intent traceability)
```

### Agent Responsibilities

| Agent | iCPG Action |
|-------|-------------|
| **Team Lead** | `icpg create` when creating task chains. `icpg query prior` to check duplicates. |
| **Feature Agent** | `icpg query constraints` before implementing. Writes `.icpg/.current-intent` for auto-recording. |
| **Quality Agent** | `icpg drift check` during GREEN verify. Verifies scope alignment. |
| **Review Agent** | Sees intent context via PreToolUse hook when reviewing files. |
| **Merger Agent** | Includes intent traceability in PR description. |

---

## Bootstrapping from Git History

For existing codebases, infer ReasonNodes from commit history:

```bash
icpg bootstrap --days 90 --verbose
```

This will:
1. Get commits from last 90 days
2. Cluster by temporal proximity (2-hour window)
3. Infer intent via LLM (Claude or OpenAI) or commit message parsing
4. Create ReasonNodes with `source: "inferred"`, `confidence: 0.6-0.8`
5. Extract symbols from changed files, create CREATES edges
6. Run duplicate detection against existing ReasonNodes

**Quality note:** Inferred intents are marked low-confidence. Review and
promote high-value ones manually.

---

## Contract Predicates

Predicates are structured assertions over codebase state:

```
file_exists("src/auth/middleware.ts")
test_exists("src/auth/__tests__/service.test.ts")
symbol_count("src/auth/") <= 15
function_signature("validateToken") == "(token: string) => Promise<User>"
```

Contracts can be:
- **Hand-authored** for high-risk ReasonNodes
- **LLM-inferred** via `icpg create --infer-contracts`
- **Heuristic** (scope → file_exists, test → test_exists)

---

## Anti-Patterns

| Anti-Pattern | Do This Instead |
|-------------|-----------------|
| Coding without stating intent | `icpg create` before every non-trivial change |
| Assuming your change is isolated | `icpg query constraints` + `icpg query risk` first |
| Rebuilding what already exists | `icpg query prior` to check for prior work |
| Leaving intent in 'executing' forever | Update status to 'fulfilled' when done |
| Ignoring drift events | `icpg drift check` weekly, resolve or create new intents |
| Storing full source in symbols | Store signature + checksum only — read source from files |
| Skipping bootstrap on existing repos | `icpg bootstrap --days 90` to build initial graph |

© alinaqi · MIT · alinaqi/maggy

Похожие скиллы

Все скиллы по теме «Настройка агента: память, контекст, субагенты» →
validate Rudolf S. Скилл validate запускает проверку спецификаций, кода, расхождений с реализацией и правил конституции проекта через специализированных субагентов. CX Codex +1 ★ 587звёзд репо agency-codebase-archaeologist huytran1120 Скилл agency-codebase-archaeologist для Claude Code ищет расхождения в коде, который меняли разные ИИ-инструменты и сессии. Он выявляет несовпадения логики, мёртвый код и расхождения документации с реализацией. CX Codex +1 ★ 85звёзд репо check JuliusBrussee Скилл check читает SPEC.md и сравнивает его с кодом. Ничего не пишет, только сообщает о расхождениях по степеням важности. CX Codex +1 2 700установок egm-drift-report официальный google Скилл egm-drift-report для Claude Code сверяет дизайн-документы и README с кодом. Запускается по явному запросу на поиск расхождений или проверку согласованности файлов в каталоге. CX Codex +1 583установок analyze-project lllllllama Скилл analyze-project читает репозиторий с обучением моделей и выдаёт карту структуры, точек входа и подозрительных мест. Ничего не меняет и не запускает тяжёлые задачи. CX Codex +1 363 500установок draft-nda phuryn Скилл draft-nda помогает составить детальное соглашение о неразглашении (NDA) между двумя сторонами с учётом типов информации, юрисдикции и пометками разделов для проверки юристом. CX Codex +1 2 800установок

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

Весь набор →
shopify-apps Скилл shopify-apps помогает собирать приложения Shopify на Remix, работать с Admin GraphQL API и создавать checkout-расширения. Пригодится при разработке приложения или расширения для магазина. CX Codex +1 273установок azure-cosmosdb Скилл Claude Code разбирает partition keys, консистентность, change feed и паттерны SDK для Azure Cosmos DB; содержит примеры CRUD, иерархических ключей и cross-partition запросов. CX Codex +1 269установок workspace Скилл workspace анализирует архитектуру монорепозиториев и связанных проектов. Находит общие контракты API и типы, чтобы агент не ломал связи между сервисами. CX Codex +1 198установок cpg-analysis Скилл cpg-analysis для Claude Code анализирует потоки управления и данных через Joern CPG и CodeQL. Применяется при сложном рефакторинге и аудите безопасности. CX Codex +1 175установок mnemos Скилл mnemos, который предотвращает потерю важной информации при компакции контекста. Структурирует рабочую память как типизированный граф, где решения и цели никогда не теряются, а менее важные данные сжимаются по правилам. CX Codex +1 134установок maggy Скилл maggy для Claude Code собирает тикеты GitHub Issues и Asana в один инбокс, запускает TDD-прогон из тикета и готовит ежедневную сводку по конкурентам. CX Codex +1 131установок cross-agent-delegation Скилл cross-agent-delegation маршрутизирует задачи между Claude, Kimi и Codex на основе оценки сложности, чекпоинтов Mnemos и графа iCPG. CX Codex +1 122установок polyphony Скилл polyphony запускает каждого ИИ-агента в отдельном Docker-контейнере со своей git-веткой, чтобы параллельные агенты не конфликтовали друг с другом. CX Codex +1 116установок

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

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