icpg
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseiCPG Skill (Intent-Augmented Code Property Graph)
iCPG 技能(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 │
└────────────────────────────────────────────────────────────────┘用途: 在代码结构之上新增一层Reason Graph层,让每个函数、类和模块都可以追溯到创建它的目标、负责的Agent或人类,以及它是否仍然在完成预期的任务。
┌────────────────────────────────────────────────────────────────┐
│ 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
3种标准前置任务查询
Every agent MUST run these before writing code:
| # | Query | Command | What It Answers |
|---|---|---|---|
| 1 | search_prior_work | | Has this been attempted before? Prevents duplication. |
| 2 | get_constraints | | What invariants apply to files I'll touch? Prevents breakage. |
| 3 | get_risk_profile | | Is this symbol fragile? Drift history, ownership changes. |
所有Agent在编写代码前必须执行这些查询:
| # | 查询 | 命令 | 解答的问题 |
|---|---|---|---|
| 1 | search_prior_work | | 之前有没有人尝试过做这件事?避免重复开发。 |
| 2 | get_constraints | | 我要修改的文件需要遵守哪些不变量?避免破坏现有功能。 |
| 3 | get_risk_profile | | 这个符号是否脆弱?查看漂移历史、所有权变更记录。 |
ReasonNode — The Core Primitive
ReasonNode — 核心原语
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 afterDrift = 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.
每个ReasonNode都记录了明确的目标以及对应的正式契约:
id UUID
goal 自然语言描述:要实现的目标
decision_type business_goal | arch_decision | task | workaround | constraint | patch
scope 预期会修改的文件/模块
owner 负责的人类或Agent
status proposed | executing | fulfilled | drifted | abandoned
source manual | commit | inferred | agent-session
FORMAL CONTRACT (Design by Contract):
preconditions 意图执行前必须满足的条件
postconditions 意图完成后必须满足的条件
invariants 执行全程以及完成后都必须保持不变的条件漂移 = 谓词失败。 当符号当前的行为不再满足创建它的ReasonNode的后置条件,或者违反了不变量时,就说明该符号发生了漂移。
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)CREATES Reason → Symbol (该意图创建了这个函数)
MODIFIES Reason → Symbol (该意图修改了这个函数)
REQUIRES Reason → Reason (B依赖A先完成)
DUPLICATES Reason → Reason (这两个目标存在重叠)
VALIDATED_BY Reason → Test (这个测试证明意图已被满足)
DRIFTS_FROM Symbol → Reason (这个符号不再实现它原本的设计目标)6-Dimension Drift Model
6维度漂移模型
| 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 to scan all dimensions. Each produces a 0-1 severity score.
icpg drift check| 维度 | 含义 | 检测方式 |
|---|---|---|
| 规范漂移 | 符号校验和发生变更但没有对应MODIFIES边 | 对比存储的校验和与当前校验和 |
| 决策漂移 | 后置条件不再成立 | 基于代码库评估谓词 |
| 所有权漂移 | 出现超过3个不同所有者且没有统一 oversight | 统计边上的唯一所有者数量 |
| 测试漂移 | VALIDATED_BY对应的测试缺失或运行失败 | 检查测试文件是否存在并运行测试 |
| 使用漂移 | 符号被用于原始作用域之外的场景 | 搜索作用域之外的导入引用 |
| 依赖漂移 | 下游REQUIRES关联的意图发生了漂移 | 遍历REQUIRES边 |
运行 即可扫描所有维度,每个维度都会生成0-1的严重程度评分。
icpg drift checkCLI Reference
CLI 参考
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)bash
icpg init # 创建 .icpg/ 目录和数据库
icpg bootstrap --days 90 # 从git历史推断ReasonNode
icpg bootstrap --days 90 --no-llm # 不使用LLM(仅基于提交消息)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 modificationsbash
icpg create "Add JWT auth" --scope src/auth/ --owner feature-auth --type task
icpg record --reason <id> --base main # 从git diff记录关联的符号
icpg record --reason <id> --edge-type MODIFIES # 记录为修改操作Query (the 3 canonical queries)
查询(3种标准查询)
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 radiusbash
icpg query prior "user authentication" # 1. 重复开发检测
icpg query constraints src/auth/service.ts # 2. 查询文件的不变量
icpg query risk validateToken # 3. 查询符号的风险概况
icpg query context src/auth/service.ts # 查询文件关联的所有意图
icpg query blast <reason-id> # 查询全量影响范围Drift
漂移相关
bash
icpg drift check # Full scan across all dimensions
icpg drift resolve <id> # Mark drift event resolvedbash
icpg drift check # 全维度扫描
icpg drift resolve <id> # 标记漂移事件已解决Status
状态查询
bash
icpg status # Stats: reasons, symbols, edges, driftbash
icpg status # 统计数据:意图、符号、边、漂移数量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项目级存储,git忽略,无需额外基础设施:
.icpg/
reason.db SQLite 数据库(4张表:reasons, symbols, edges, drift_events)
.gitignore 内容:*
chroma/ ChromaDB 向量存储(如果安装了chromadb)
tfidf_cache.json TF-IDF 兜底缓存
.current-intent 活跃意图标记文件(供Stop hook使用)安装选项:
bash
pip install ./scripts/icpg # 核心版本(零依赖)
pip install "./scripts/icpg[vectors]" # + ChromaDB 用于重复检测
pip install "./scripts/icpg[all]" # + ChromaDB + scikit-learn + openaiWorkflow: 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, typecheckStep 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.
0. 明确意图 → icpg create(或找到现有意图)
1. 去重检查 → icpg query prior(检查是否有重复工作)
2. 确认约束 → icpg query constraints(了解不变量)
3. 风险评估 → icpg query risk(检查脆弱符号)
4. 定位代码 → search_graph 查找对应符号(代码图技能)
5. 修改代码 → 执行编辑(PreToolUse hook会展示上下文)
6. 记录关联 → icpg record(将符号关联到对应意图)
7. 漂移检查 → icpg drift check(确认没有非预期漂移)
8. 验证 → 运行测试、lint、类型检查对于自主Agent来说第0步是必须的。 所有修改都必须关联到明确的目标,没有意图就没有衡量漂移的基准。
Hook Integration
Hook 集成
PreToolUse Hook (automatic context injection)
PreToolUse Hook(自动注入上下文)
Add to :
.claude/settings.jsonjson
{
"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.
═══════════════════添加到 :
.claude/settings.jsonjson
{
"hooks": {
"PreToolUse": [{
"matcher": "Edit|Write",
"hooks": [{
"type": "command",
"command": "scripts/icpg-pre-edit.sh",
"timeout": 3,
"statusMessage": "Checking intent context..."
}]
}]
}
}每次编辑文件前,Agent都会看到:
═══ 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)
Stop Hook(自动记录符号关联)
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}
]
}]
}
}实现通过测试后,自动记录关联的符号:
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
Agent 团队集成
Updated Pipeline (agent-teams + iCPG)
升级后的流水线(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) 0. 明确意图 团队负责人基于功能需求创建ReasonNode
0b. 去重检查 icpg query prior — 检查是否有重复意图
1. 编写规格 功能Agent编写规格说明
2. 规格评审 质量Agent评审规格是否和意图对齐
3. 编写测试(红阶段) 功能Agent编写测试用例
4. 红阶段验证 质量Agent验证测试运行失败
5. 功能实现 功能Agent编写代码(PreEdit hook会展示上下文)
5b. 记录关联 自动记录符号→意图关联(Stop hook)
5c. 漂移检查 质量Agent验证没有出现范围漂移
6. 绿阶段验证 质量Agent验证测试通过+覆盖率达标
7. 校验 Lint + 类型检查 + 全量测试套件
8. 代码评审 评审Agent(可以看到每个文件关联的意图上下文)
9. 安全检查 安全Agent审核
10. 提交PR 合并Agent(PR包含意图追溯信息)Agent Responsibilities
Agent 职责
| Agent | iCPG Action |
|---|---|
| Team Lead | |
| Feature Agent | |
| Quality Agent | |
| Review Agent | Sees intent context via PreToolUse hook when reviewing files. |
| Merger Agent | Includes intent traceability in PR description. |
| Agent | iCPG 操作 |
|---|---|
| 团队负责人 | 创建任务链时执行 |
| 功能Agent | 实现前执行 |
| 质量Agent | 绿阶段验证时执行 |
| 评审Agent | 评审文件时通过PreToolUse hook查看意图上下文。 |
| 合并Agent | 在PR描述中包含意图追溯信息。 |
Bootstrapping from Git History
从Git历史初始化
For existing codebases, infer ReasonNodes from commit history:
bash
icpg bootstrap --days 90 --verboseThis will:
- Get commits from last 90 days
- Cluster by temporal proximity (2-hour window)
- Infer intent via LLM (Claude or OpenAI) or commit message parsing
- Create ReasonNodes with ,
source: "inferred"confidence: 0.6-0.8 - Extract symbols from changed files, create CREATES edges
- Run duplicate detection against existing ReasonNodes
Quality note: Inferred intents are marked low-confidence. Review and
promote high-value ones manually.
对于现有代码库,可以从提交历史推断ReasonNode:
bash
icpg bootstrap --days 90 --verbose这个命令会:
- 获取最近90天的提交
- 按时间 proximity 聚类(2小时窗口)
- 通过LLM(Claude或OpenAI)或提交消息解析推断意图
- 创建ReasonNode,标记 ,
source: "inferred"confidence: 0.6-0.8 - 从变更文件中提取符号,创建CREATES边
- 和现有ReasonNode对比做重复检测
质量提示: 推断的意图会标记为低置信度,建议手动审核并升级高价值的意图。
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)
谓词是针对代码库状态的结构化断言:
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>"契约可以是:
- 手动编写 用于高风险的ReasonNode
- LLM推断 通过 生成
icpg create --infer-contracts - 启发式生成 (作用域→file_exists,测试→test_exists)
Anti-Patterns
反模式
| Anti-Pattern | Do This Instead |
|---|---|
| Coding without stating intent | |
| Assuming your change is isolated | |
| Rebuilding what already exists | |
| Leaving intent in 'executing' forever | Update status to 'fulfilled' when done |
| Ignoring drift events | |
| Storing full source in symbols | Store signature + checksum only — read source from files |
| Skipping bootstrap on existing repos | |
| 反模式 | 推荐做法 |
|---|---|
| 不明确意图就写代码 | 所有非 trivial 修改前先执行 |
| 假设你的修改是隔离的 | 先执行 |
| 重复造轮子 | 执行 |
| 永远把意图标记为'executing' | 完成后更新状态为'fulfilled' |
| 忽略漂移事件 | 每周执行 |
| 在符号中存储完整源码 | 仅存储签名+校验和——从文件读取源码 |
| 现有仓库跳过初始化 | 执行 |