mcpField
I
icpg

icpg

github.com/alinaqiAgent 工作流711149 次安装2 周前更新
代码仓库

关于 icpg

iCPG 是将代码元素关联到其目标、约束、负责人和测试的技能与命令行工具。它帮助编码 Agent 和开发者在修改前检查既有工作与风险,并记录意图、检测偏移。

主要功能

  1. 01将意图记录关联到代码符号
  2. 02查询既有工作、约束与风险
  3. 03检查六个维度的代码偏移
  4. 04从 Git 历史建立意图记录
  5. 05通过钩子注入上下文并记录

适用场景

  1. 01实现前检查是否有重复工作
  2. 02审查待修改文件的约束与风险
  3. 03追踪代码是否仍符合原定目标

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/alinaqi/maggy --skill icpg

安装后在 Claude Code 中输入/icpg确认已加载。

详细介绍

iCPG 技能(意图增强型代码属性图)

用途: 在代码结构之上添加原因图层,使每个函数、类和模块都能追溯到创建它的目标、负责它的 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 │
└────────────────────────────────────────────────────────────────┘

核心原则

意图优先,代码其次。 在编写或修改代码之前,先查询原因图,了解现有代码为何编写、必须保留哪些约束,以及你的更改是否会重复已有工作。


3 个标准的任务前查询

每个 Agent 都必须在编写代码前运行以下查询:

#查询命令解答的问题
1search_prior_workicpg query prior "<goal>"之前尝试过这项工作吗?防止重复。
2get_constraintsicpg query constraints <file>我将修改的文件适用哪些不变量?防止破坏代码。
3get_risk_profileicpg query risk <symbol>这个符号是否脆弱?查看漂移历史和所有权变更。

ReasonNode — 核心原语

每个 ReasonNode 都会通过正式契约记录明确声明的用途:

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

漂移 = 谓词失效。 当符号当前的行为不再满足创建它的 ReasonNode 的后置条件,或违反不变量时,该符号就发生了漂移。


六种边类型

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)

六维漂移模型

维度含义检测方式
规范漂移符号校验和发生变化,但没有 MODIFIES 边比较存储的校验和与当前校验和
决策漂移后置条件不再成立根据代码库评估谓词
所有权漂移出现超过 3 个不同负责人,且缺乏一致的监督统计边上的不同负责人数量
测试漂移VALIDATED_BY 测试缺失或未通过检查测试文件是否存在并运行测试
使用漂移符号在原始范围之外被使用搜索范围以外的导入
依赖漂移下游 REQUIRES 原因已发生漂移遍历 REQUIRES 边

运行 icpg drift check 扫描所有维度。每个维度都会生成一个 0–1 的严重性分数。


CLI 参考

设置
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)
创建与记录
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
查询(3 个标准查询)
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
漂移
icpg drift check          # Full scan across all dimensions
icpg drift resolve <id>   # Mark drift event resolved
状态
icpg status               # Stats: reasons, symbols, edges, drift

存储

按项目存储、由 gitignore 忽略、无需基础设施:

.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)

安装选项:

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

工作流:任何代码更改之前

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

对于自主 Agent,第 0 步不可妥协。 每项更改都必须关联到明确声明的用途。没有意图,就没有衡量漂移的依据。


Hook 集成

PreToolUse Hook(自动注入上下文)

添加到 .claude/settings.json:

{
  "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(自动记录符号)

实现通过测试后,自动记录符号:

{
  "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 集成

更新后的流水线(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 职责
AgentiCPG 操作
Team Lead创建任务链时运行 icpg create。运行 icpg query prior 检查重复。
Feature Agent实现前运行 icpg query constraints。写入 .icpg/.current-intent 以便自动记录。
Quality Agent在 GREEN 验证期间运行 icpg drift check。验证范围是否一致。
Review Agent审查文件时通过 PreToolUse hook 查看意图上下文。
Merger Agent在 PR 描述中包含意图可追溯性。

从 Git 历史记录引导初始化

对于现有代码库,可根据提交历史推断 ReasonNodes:

icpg bootstrap --days 90 --verbose

这将:

  1. 获取过去 90 天的提交
  2. 按时间接近程度聚类(2 小时窗口)
  3. 通过大模型(Claude 或 OpenAI)推断意图,或解析提交消息
  4. 创建 source: "inferred"、confidence: 0.6-0.8 的 ReasonNodes
  5. 从变更文件中提取符号,并创建 CREATES 边
  6. 与现有 ReasonNodes 进行重复项检测

质量提示: 推断出的意图会标记为低置信度。请手动审查并提升有价值的意图。


契约谓词

谓词是对代码库状态的结构化断言:

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>"

契约可以是:

  • 手动编写,用于高风险 ReasonNodes
  • 由大模型推断,通过 icpg create --infer-contracts
  • 启发式推断(scope → file_exists,test → test_exists)

反模式

反模式应改为
编码时不说明意图每次进行非平凡变更前运行 icpg create
假设变更不会影响其他部分先运行 icpg query constraints + icpg query risk
重做已有内容运行 icpg query prior 检查是否已有相关工作
让意图永远停留在“执行中”完成后将状态更新为“已履行”
忽略漂移事件每周运行 icpg drift check,解决问题或创建新意图
在符号中存储完整源代码只存储签名 + 校验和;从文件中读取源代码
在现有仓库中跳过引导初始化运行 icpg bootstrap --days 90 构建初始图谱

评论

支持 Markdown