AI代理治理框架

P8是一个零信任治理框架,用于防止AI代理产生幻觉、破坏事物和绕过规则,适用于AI编码代理的严格管控。

  • by Aquifer-sea
  • Python
  • 本地部署
  • 44 星标
  • 更新于
在 GitHub 查看 Aquifer-sea/pattern8

使用说明

图案8(P8)

零信任治理框架,防止人工智能代理产生幻觉、破坏事物和绕过你的规则。

“你的提示只是一个建议。P8是法律。”

🇨🇳 简体中文 · Architecture (源码导读)


目录


混沌与法律

你是否厌倦了AI编码代理(Claude、Cursor、Devin)无视你的指令、删除错误的文件或在没有测试的情况下推送代码?

提示是不够的。 快速注射防御是不可能的。 为了真正控制代理,必须在操作系统和代码级别实施约束。

❌ 没有P8(混沌)

  • 代理人决定 跳过编写测试,因为它“太琐碎”。
  • 代理运行 rm -rf 在多步骤重构过程中出错。
  • 代理输出 一个从未写过设计文档的功能。
  • 代理忽略 您的5000字系统提示,因为其上下文窗口已满。

🛡️ P8(法律)

  • MCP保安 在操作系统级别拦截和阻止危险命令。
  • MCP审核人 如果输出不匹配,则强制代理进入严格的重试循环 template.yaml.
  • 预提交钩子 确保代理人自己没有篡改规则。
  • 反转模式 迫使代理人停下来问你澄清问题,而不是产生幻觉。

⚡ 30秒内从零到英雄

使用3个命令绝对控制您的代码库:

# 1. Install the enforcer (Python 3.8+)
pip install pattern8

# 2. Add handcuffs to your current project
p8 init

# 3. Done. Your Agents are now under control.
p8 list

💡 对于中文团队: p8 init --lang zh 生成所有带有中文注释的SKILL文件。


🏛️ 架构概述

P8是 非 AI代理框架。它不调用LLM或驱动管道。
P8是一个 治理层 --一组可执行的规则文件+一个约束的运行时执行引擎 怎么 任何AI代理都可以在您的项目上工作。

┌─────────────────────────────────────────────────────────────────────────┐
│                            YOUR PROJECT                                │
│                                                                        │
│  ┌──────────────────────────┐    ┌──────────────────────────────────┐  │
│  │    📜 LAW (Editable)      │    │    🚔 POLICE (Read-Only Engine)  │  │
│  │                          │    │                                  │  │
│  │  skills/                 │    │  src/p8/enforcement/             │  │
│  │  ├── prd/                │──→ │  ├── mcp_server.py    (Gateway) │  │
│  │  ├── bug_fix/            │    │  ├── security_guard.py (Block)  │  │
│  │  ├── code_review/        │    │  └── reviewer.py      (Audit)  │  │
│  │  ├── refactor/           │    │                                  │  │
│  │  └── feature_dev/        │    │  Runs as MCP stdio server       │  │
│  │                          │    │  Agent ↔ MCP ↔ Police           │  │
│  │  AGENTS.md               │    └──────────────────────────────────┘  │
│  │  .cursor/rules/*.mdc     │                                          │
│  └──────────────────────────┘    ┌──────────────────────────────────┐  │
│                                  │    🔗 HOOKS (Git-level)          │  │
│                                  │    hooks/pre-commit              │  │
│                                  └──────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────┘

关键洞察:代理人可以阅读 SKILL.md, checklist.yaml,以及 template.yaml (“法律”)。但它 不能 阅读 guidelines.yaml 或 security.yaml (“审计标准”)。这可以防止代理对审计进行游戏。


📂 项目结构

pattern8/
├── src/p8/                          # Python package (pip install pattern8)
│   ├── __init__.py                  #   Package metadata (version)
│   ├── cli.py                       #   CLI entry point (click-based)
│   └── enforcement/                 #   🚔 Enforcement engine
│       ├── __init__.py
│       ├── mcp_server.py            #     MCP protocol gateway (3 Resources + 2 Tools)
│       ├── security_guard.py        #     OS-level command blocker (regex blacklist)
│       └── reviewer.py              #     Static rule audit engine (format + rules)
│
├── skills/                          # 📜 Built-in SKILL rules (English)
│   ├── prd/                         #   Product Requirements Document
│   │   ├── SKILL.md                 #     Pipeline definition (frontmatter + steps)
│   │   ├── assets/
│   │   │   ├── checklist.yaml       #     Inversion: pre-flight questions
│   │   │   └── template.yaml        #     Generator: output format
│   │   └── references/
│   │       ├── guidelines.yaml      #     🔒 Reviewer audit rules (hidden from Agent)
│   │       └── security.yaml        #     🔒 SecurityGuard blacklist (hidden from Agent)
│   ├── bug_fix/                     #   Bug Fix (same structure)
│   ├── code_review/                 #   Code Review (same structure)
│   ├── feature_dev/                 #   Feature Development (same structure)
│   └── refactor/                    #   Refactoring (same structure)
│
├── skills_zh/                       # 📜 Built-in SKILL rules (Chinese)
│   └── (same structure as skills/)
│
├── hooks/
│   └── pre-commit                   # 🔗 Git hook: SKILL integrity + secret scan
│
├── AGENTS.md                        # Global agent behavior instructions
├── .cursor/rules/
│   └── p8-enforcement.mdc          # Cursor IDE injection rules
│
├── tests/
│   ├── test_p8.py                   # CLI + SKILL management tests
│   └── test_enforcement.py          # SecurityGuard + Reviewer + MCP tests
│
├── .github/workflows/
│   └── ci.yml                       # CI: pytest on Python 3.11-3.13 × Ubuntu/macOS
│
├── pyproject.toml                   # Build config (hatchling)
├── CONTRIBUTING.md                  # Contributor guide
├── CHANGELOG.md                     # Version history
└── LICENSE                          # MIT

🚔 工作原理:法律与警察

P8分离 法律 (可编辑规则)来自 警察 (只读执行引擎):

Developer-editable (Law)              Read-only Engine (Police)
┌──────────────────────┐          ┌──────────────────────────┐
│ SKILL.md             │          │ SecurityGuard            │
│ checklist.yaml       │  read →  │  ↳ regex blacklist       │
│ template.yaml        │          │  ↳ OS command hooks      │
│ guidelines.yaml  🔒  │          │ Reviewer                 │
│ security.yaml    🔒  │          │  ↳ static rule engine    │
│                      │          │  ↳ P8AuditError rollback │
│ "The Constitution"   │          │ "The Police"             │
└──────────────────────┘          └──────────────────────────┘
                ↕ Agent calls via MCP ↕

你写 法律 简单的Markdown和YAML。这 警察 引擎通过MCP(模型上下文协议)自动执行它们。标记为的文件🔒 故意对代理隐藏,因此代理无法读取用于审核它的安全参数。


🔐 五种执行模式

每一项技能都强制执行 5图案 按顺序。这些是P8治理理念的支柱:

# 模式 它做什么 由控制
1 管道 任务按照严格的顺序执行。不得跳过任何步骤。 SKILL.md
2 反转 在开始之前,代理必须验证所有先决条件。如果信息缺失 停下来问 --没有猜测。 assets/checklist.yaml
3 发电机 输出必须遵循严格的模板。每个部分都必须填写。没有自由泳。 assets/template.yaml
4 工具包装 在执行操作系统命令之前,代理必须通过安全检查点。被列入黑名单的操作将被拒绝。 references/security.yaml 🔒
5 审稿人 完成输出后,静态审计引擎对结果进行评分。不符合要求的输出会触发回滚+重试(最多3次)。 references/guidelines.yaml 🔒

为什么模式4和5被隐藏? 如果代理可以读取确切的审计标准,它可以通过产生技术上通过但语义上是垃圾的输出来玩弄系统。通过隐藏它们,审计保持了诚实。


🧬 技能剖析

每个SKILL都是一个自包含的目录,其中包含 4个YAML配置文件 和 1 Markdown管道定义:

skills/<skill_name>/
├── SKILL.md                    # Pipeline definition (YAML frontmatter + Markdown steps)
├── assets/
│   ├── checklist.yaml          # Pattern 2 — Inversion: pre-flight checklist
│   └── template.yaml           # Pattern 3 — Generator: output format template
└── references/
    ├── guidelines.yaml         # Pattern 5 — 🔒 Reviewer: audit rules
    └── security.yaml           # Pattern 4 — 🔒 SecurityGuard: command blacklist

SKILL.md --管道脚本

使用YAML frontmatter声明元数据+文件引用,然后使用Markdown定义每个管道步骤:

---
name: feature_dev
description: Constrains the Agent to follow structured feature development.
assets:
  checklist: assets/checklist.yaml
  template: assets/template.yaml
references:
  guidelines: references/guidelines.yaml
  security: references/security.yaml
---

步骤被包裹在 <PIPELINE> 标签,带 <HARD-GATE> 对于阻塞条件:

<PIPELINE>

## Step 1: Inversion (Requirements Alignment)
<HARD-GATE>
If the user has not provided acceptance criteria, you must block and ask.
</HARD-GATE>

## Step 2: Generator (Generate from Template)
Your output must strictly follow `assets/template.yaml`.

## Step 3: Tool Wrapper (Security Fence)
Commands must be checked against `references/security.yaml`.

## Step 4: Reviewer (Self-Audit Loop)
Audit against `references/guidelines.yaml`. Retry up to 3x if non-compliant.

</PIPELINE>

checklist.yaml --代理人必须验证什么

checklist:
  - "Feature requirements are clearly described with user stories"
  - "Technology stack and framework are specified"
  - "Acceptance criteria are defined"
  - "Edge cases and error scenarios are considered"

template.yaml --输出必须是什么样子

template: |
  # Feature Development Report
  ## 1. Requirement Understanding
  ## 2. Technical Design
  ## 3. Implementation
  ## 4. Tests
  ## 5. Integration Notes

security.yaml --什么是禁止的(🔒 对代理人隐藏)

tool_security:
  blacklist:
    - "rm -rf *"
    - "sudo *"
    - "curl * | sh"
  denied_paths:
    - "/etc"
    - "~/.ssh"
    - "~/.aws"
  max_shell_timeout: 30

guidelines.yaml --产出如何评分(🔒 对代理人隐藏)

支持4种静态分析规则类型:

规则类型 描述 示例
regex_match 必须与正则表达式模式匹配 代码块必须存在(\```)

💎 5种内置技能

P8配备了5种工业级开发技能。 不要只写代码。工程师。

📝 PRD(skills/prd/)

不要只是建造。先想想。
强制代理在编写单行逻辑之前收集需求并生成结构化的产品需求文档。

🐛 Bug修复(skills/bug_fix/)

找出根本原因,否则根本不解决。
强制代理通过严格的4步黄金路径:复制→ 根本原因分析→ Fix → 回归测试。

🔒 代码审查(skills/code_review/)

永远不要合并未经审查的AI垃圾。
代理人必须将其更改提交给 Reviewer 发动机。如果代码不符合安全性、性能或正确性准则,引擎将抛出 P8_AUDIT_FAILED 错误,迫使代理在向您呈现之前重试并修复自己的混乱(最多3次)。

🏗️ 重构(skills/refactor/)

改变结构,而不是行为。
强制代理在移动代码后保证功能等效测试通过。

🚀 功能开发(skills/feature_dev/)

端到端交付。 需求→ 技术设计→ 实施→ 单元测试。


🔌 MCP执法引擎深潜

执法引擎(src/p8/enforcement/)以a的形式运行 MCP stdio服务器当连接到IDE(Cursor、Windsurf、Claude Desktop)时,它会显示:

资源(认知基础——代理在启动时读取)

URI 描述 源文件
skill://index 列出所有可用的技能及其名称和描述 扫描 skills/*/SKILL.md
skill://{name}/skill_md 完整的SKILL.md管道定义 skills/{name}/SKILL.md
skill://{name}/checklist 倒置检查表项目 skills/{name}/assets/checklist.yaml
skill://{name}/template 输出模板 skills/{name}/assets/template.yaml

工具(强制检查点——代理必须调用这些工具)

execute_tool --操作系统命令沙盒

{
  "command": "npm install lodash",
  "path": "./src/",
  "operation": "write",
  "skill": "feature_dev"
}

内链 (代理人看不见):

  1. 负载 references/security.yaml 对于指定的技能
  2. SecurityGuard.check_command(command) --与正则表达式黑名单匹配
  3. SecurityGuard.check_path(path, operation) --验证路径是否允许
  4. 退货 {"allowed": true} 或 {"allowed": false, "action": "BLOCKED"}

submit_review --输出审核门

{
  "content": "# Feature Development Report\n## 1. Requirement Understanding\n...",
  "skill": "feature_dev"
}

内链 (代理人看不见):

  1. 负载 references/guidelines.yaml (隐藏审计规则)
  2. 负载 assets/template.yaml (格式参考)
  3. Reviewer.audit(content) 运行4种检查类型:
    • 格式验证:是否存在所有必需的Markdown标题?
    • 正则表达式匹配/排除:图案匹配/不匹配吗?
    • 长度限制:内容够长吗?
  4. 全部通过→ {"passed": true, "score": 100, "status": "APPROVED"}
  5. 任何失败→ 投掷 P8AuditError → 回报 P8_AUDIT_FAILED +违规清单

自我纠正循环

Agent completes work
        │
        ▼
  submit_review()
        │
    ┌───┴───┐
    │ PASS? │
    └───┬───┘
   Yes  │  No
    │   │   │
    ▼   │   ▼
 APPROVED  P8_AUDIT_FAILED
           + violation list
                │
                ▼
        Agent reads violations,
        fixes its output,
        resubmits (up to 3×)
                │
           ┌────┴────┐
           │ 3 fails │
           └────┬────┘
                ▼
        Agent reports failure
        to user with details

🔄 端到端数据流

以下是代理在P8管理的项目中处理任务时发生的情况:

Step 1: Agent reads skill://index          → Discovers available SKILLs
Step 2: Agent reads skill://X/checklist    → Gets pre-flight checklist
Step 3: Agent verifies checklist items     → ASKS user if anything missing (Inversion)
Step 4: Agent reads skill://X/template     → Learns required output format
Step 5: Agent starts working...
        └─ Before any OS command:
           execute_tool(command, skill)    → SecurityGuard checks regex blacklist
           ├─ allowed: true  → proceed
           └─ allowed: false → BLOCKED, Agent must stop
Step 6: Agent finishes output
        └─ submit_review(content, skill)   → Reviewer audits against hidden rules
           ├─ passed: true  → APPROVED, deliver to user
           └─ P8_AUDIT_FAILED → Agent self-corrects and resubmits (up to 3×)

🛠️ CLI参考

命令 描述
p8 init [target] 在项目中初始化P8并生成5个默认技能
p8 init --lang zh 使用中文SKILL文件初始化
p8 list 列出当前项目中所有可用的技能
p8 validate <skill_path> 验证SKILL文件完整性(编辑YAML后运行)
p8 new <skill_name> 为新的自定义技能创建脚手架
p8 serve 启动MCP执行服务器(stdio模式)
p8 mcp-config --client cursor 为Cursor IDE生成MCP配置JSON
p8 --version 显示已安装版本

🔌 IDE集成

光标/风帆/克劳德桌面

要打开活动的“警察”执法引擎,请安装MCP扩展:

# Full install with MCP server support
pip install 'pattern8[enforcement]'

# Generate MCP config for Cursor
p8 mcp-config --client cursor

将输出粘贴到 .cursor/mcp.json。现在,每当游标代理尝试运行命令或完成任务时,它 必须 穿过P8 execute_tool 和 submit_review 检查站。

游标规则的工作原理

P8还安装了 .cursor/rules/p8-enforcement.mdc 文件是 自动注入到每个代理对话中。此文件指示代理:

  1. 阅读 skill://index 在创业过程中发现技能
  2. 呼叫 execute_tool() 在运行任何操作系统命令之前
  3. 呼叫 submit_review() 完成SKILL流程后
  4. 从不阅读 guidelines.yaml 或 security.yaml 直接
  5. 从不修改 skills/ 或 AGENTS.md 没有明确的用户权限

代理商.md

这 AGENTS.md 项目根目录下的文件是由支持项目级配置(Cursor、Windsurf等)的代理读取的全局指令文件。它告诉代理人:

  • 检查 skills/ 用于在开始任何任务之前匹配技能
  • 严格遵循5模式管道
  • 将安全红线视为绝对的硬约束

🔗 预提交钩子

P8安装了一个Git预提交钩子,在每个 git commit:

# What the hook does:
1. Validates all SKILL file integrity (p8 validate)
2. Scans staged files for hardcoded secrets (API keys, passwords, tokens)
3. Blocks the commit if any issues are found

手动安装:

cp hooks/pre-commit .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit

或自动通过 p8 init.


🏗️ 创建自定义技能

# Scaffold a new SKILL
p8 new my_custom_skill

# This creates:
# skills/my_custom_skill/
# ├── SKILL.md              ← Edit pipeline steps
# ├── assets/
# │   ├── checklist.yaml    ← Edit pre-flight questions
# │   └── template.yaml     ← Edit required output format
# └── references/
#     ├── guidelines.yaml   ← Edit audit rules
#     └── security.yaml     ← Edit command blacklist

然后编辑每个文件以满足团队的治理需求。跑 p8 validate skills/my_custom_skill 检查完整性。


🧪 测试

# Install dev dependencies
pip install -e ".[dev]"

# Run all tests (59 tests, 100% coverage)
pytest tests/ -v

# Tests cover:
# - CLI commands (init, list, validate, new)
# - SecurityGuard (blacklist matching, path blocking)
# - Reviewer (format checking, rule auditing, P8AuditError)
# - MCP server (resource reading, tool routing)

CI在每次推送/PR时自动运行 main,测试:

  • python: 3.11, 3.12, 3.13
  • 操作系统:Ubuntu、macOS

🤝 贡献

我们欢迎全新的技能!看 贡献.md 了解架构细节以及如何打开PR。

对于希望深入了解源代码的中国开发人员,请参阅 建筑设计_zh-CN.md.

📄 许可证

麻省理工学院