Doramagic 项目包 · 项目说明书
coding-ethos 项目
coding-ethos 是一个面向「工具连接与集成」的开源项目,重点覆盖 MCP 工具、工具接入扩展;Doramagic 已整理安装入口、说明书、上下文包和风险边界,方便先判断再试用。
项目概述
coding-ethos 是一个由 Blackcat Informatics® Inc. 开发和维护的开源项目,旨在为代码库生成和强制执行编码标准。该工具通过结构化的原则定义、策略表达和生成的代理文档,确保人类开发者和 AI 编码助手(Codex、Claude Code、 Gemini CLI)遵循一致的编码规范。
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
简介
coding-ethos 是一个由 Blackcat Informatics® Inc. 开发和维护的开源项目,旨在为代码库生成和强制执行编码标准。该工具通过结构化的原则定义、策略表达和生成的代理文档,确保人类开发者和 AI 编码助手(Codex、Claude Code、 Gemini CLI)遵循一致的编码规范。
项目的主要目标是解决 AI 辅助编程中的标准一致性问题。在没有统一标准的情况下,不同的 AI 模型或同一模型的不同会话可能会产生风格不一致的代码。coding-ethos 通过以下方式解决这一挑战:
- 将编码原则和最佳实践结构化存储在 YAML 配置文件中
- 自动生成针对特定 AI 代理的文档(AGENTS.md、CLAUDE.md、GEMINI.md)
- 提供策略执行机制(CEL 表达式、lint 规则、pre-commit hooks)
- 支持 SARIF 格式的代码扫描结果输出
资料来源:README.md
核心概念
Ethos Bundle(准则包)
Ethos Bundle 是项目的核心数据结构,包含以下组件:
| 组件 | 描述 | 数据类型 |
|---|---|---|
| title | 准则包标题 | str |
| overview | 总体概述 | str |
| principles | 原则列表 | list[Principle] |
| agent_profiles | 代理配置 | dict[str, AgentProfile] |
| skills | 技能定义 | list[EthosSkill] |
| repo | 仓库上下文 | RepoContext |
资料来源:coding_ethos/models.py:114-121
Principle(原则)
每个 Principle 代表一条编码原则,具有以下属性:
@dataclass(slots=True)
class Principle:
id: str # 唯一标识符
order: int # 排序顺序
title: str # 标题
summary: str # 摘要
body: str # 详细内容
sections: list[PrincipleSection] # 章节列表
axioms: list[PrincipleAxiom] # 公理
directive: str # 核心指令
quick_ref: list[str] # 快速参考
merge_topics: list[str] # 合并主题
tags: list[str] # 标签
related: list[str] # 相关原则
agent_hints: dict[str, str] # 代理提示
资料来源:coding_ethos/models.py:54-66
Section Kind(章节类型)
原则的详细内容支持多种章节类型,便于组织不同用途的信息:
| 类型 | 用途 | 关键词 |
|---|---|---|
| overview | 概述/总结 | overview, summary, core principle |
| rationale | 理由/动机 | why, rationale, reason, motivation |
| anti_patterns | 反模式 | anti pattern, bad way, what not to do |
| correct_way | 正确做法 | right way, correct way, preferred way |
| rule | 规则 | rule, rules, policy, non negotiable |
| workflow | 工作流程 | workflow, process, procedure, steps |
| examples | 示例 | example, examples |
| reference | 参考 | checklist, quick ref, reference |
资料来源:coding_ethos/markdown_seed.py:40-56
架构概览
graph TD
A[用户/AI代理] --> B[CLI / MCP Server]
B --> C[Loaders]
C --> D[EthosBundle]
D --> E[Renderers]
E --> F[AGENTS.md<br/>CLAUDE.md<br/>GEMINI.md<br/>ETHOS.md]
D --> G[Policy Engine]
G --> H[Pre-commit Hooks]
G --> I[SARIF Output]
J[repo_ethos.yml] --> C
K[coding_ethos.yml] --> C
L[Markdown Seed] --> C
M[CEL Expressions] --> G
N[Tool Config] --> G支持的 AI 代理
coding-ethos 当前支持三种主流 AI 编码代理:
| 代理 | 生成文件 | 导入其他文件 |
|---|---|---|
| codex | AGENTS.md | - |
| claude | CLAUDE.md | @AGENTS.md, @.claude/ethos/MEMORY.md |
| gemini | GEMINI.md | @AGENTS.md |
每个代理的根文件表面(AgentRootSurface)定义了其特有的渲染逻辑和合并主题:
资料来源:coding_ethos/renderers.py:145-178
包结构
coding_ethos/
├── __init__.py # 公共 API 导出
├── cli.py # 命令行入口
├── loaders.py # 加载和合并 ethos bundle
├── renderers.py # 渲染代理文档
├── merging.py # 合并引擎支持
├── models.py # 数据模型定义
├── markdown_seed.py # Markdown 转 YAML 工具
├── yaml_utils.py # YAML 工具函数
├── presets.py # 预设配置
├── resources.py # 资源路径管理
└── resources/ # 打包后的资源文件
公共 API
项目的公共 API 通过 coding_ethos/__init__.py 导出:
from coding_ethos import (
load_primary_bundle, # 加载主 bundle
merge_repo_ethos, # 合并仓库 ethos
render_agent_root_outputs, # 渲染代理根文件
parse_ethos_markdown, # 解析 ethos markdown
seed_primary_from_markdown, # 从 markdown 播种
SUPPORTED_MERGE_ENGINES, # 支持的合并引擎
resolve_merge_bin, # 解析合并二进制
)
资料来源:coding_ethos/__init__.py:18-40
配置系统
主配置文件 (coding_ethos.yml)
主配置文件定义了跨仓库共享的编码原则和策略:
| 配置项 | 描述 |
|---|---|
| principles | 核心原则定义列表 |
| agent_notes | 各代理的通用备注 |
| skills | 技能定义 |
| policies | CEL 策略表达式 |
| tool_config | 工具配置 |
仓库配置 (repo_ethos.yml)
repo_ethos.yml 用于覆盖或扩展主配置,添加仓库特定的设置:
repo:
name: Example Service
overview: 背景处理服务
commands:
install: [uv sync]
test: [uv run pytest]
paths:
source: src/
tests: tests/
principles:
overrides:
protocol-first-design:
directive: 在实现工作前先在 src/interfaces/ 定义接口
additional:
- id: migration-hygiene
order: 900
title: 迁移卫生
summary: 迁移是追加的,像代码一样审查
合并策略
合并过程支持多种策略模式:
| 策略 | 说明 |
|---|---|
| overrides | 完全覆盖主配置中的指定项 |
| append | 在主配置后追加内容 |
| additional | 添加主配置中不存在的新项 |
工作流程
生成工作流
graph LR
A[coding_ethos.yml] --> B[load_primary_bundle]
C[repo_ethos.yml] --> D[merge_repo_ethos]
B --> D
D --> E[EthosBundle]
E --> F[render_agent_root_outputs]
F --> G[AGENTS.md]
F --> H[CLAUDE.md]
F --> I[GEMINI.md]生成命令:
uv run python main.py --repo .
资料来源:repo_ethos.yml
策略执行工作流
graph TD
A[AI 代理执行操作] --> B{Pre-commit Hook 检查}
B -->|通过| C[操作执行]
B -->|失败| D[策略阻止]
D --> E[MCP lint_advice]
E --> F[获取修复建议]
F --> G[应用修复]
G --> B策略表达
CEL 表达式
coding-ethos 支持 Common Expression Language (CEL) 进行策略表达:
policies:
expressions:
- id: filesystem.generated_artifact_edit
scope: file
severity: block
mode: block
skill_id: agent-operating-discipline
lint_scopes:
- staged
tools:
- Write
- Edit
- MultiEdit
message: 生成的文件必须通过源输入修改
advice: >-
编辑 coding_ethos.yml、repo_ethos.yml 或渲染器代码,
然后重新生成并审查差异。
该策略禁止直接编辑 AGENTS.md、CLAUDE.md、GEMINI.md 等生成文件,强制用户通过源配置进行修改。
资料来源:repo_ethos.yml
策略阻止的工具
| 工具 | 说明 |
|---|---|
| Write | 写入新文件 |
| Edit | 编辑现有文件 |
| MultiEdit | 批量编辑 |
MCP 服务器集成
coding-ethos 提供 MCP (Model Context Protocol) 服务器,为 AI 代理提供上下文:
| MCP 工具 | 功能 |
|---|---|
| lint_check | 运行托管 lint 检查 |
| lint_advice | 获取 ETHOS 策略映射的修复建议 |
| sarif_remediation_advice | SARIF 结果到修复建议的转换 |
| tool_capabilities | 查询运行时工具能力 |
启动 MCP 服务器:
make build
bin/coding-ethos-run mcp
资料来源:examples/mcp-lint-advice/README.md
工具配置
coding-ethos 支持多种 lint 工具配置,包括:
| 工具 | 配置位置 | 说明 |
|---|---|---|
| ruff | tool.ruff | Python lint |
| mypy | tool.mypy | Python 类型检查 |
| pyright | pyrightconfig.json | Python 类型检查 |
| golangci-lint | .golangci.yml | Go lint |
| shellcheck | - | Shell 脚本检查 |
示例工具配置:
tool_config:
golangci_lint:
linters:
enable:
- name: ginkgolinter
rationale: 此仓库的 Go 测试套件使用 Ginkgo 标准
SARIF 集成
coding-ethos 支持 SARIF (Static Analysis Results Interchange Format) 输出,用于代码扫描结果集成:
graph LR
A[Lint 检查] --> B[SARIF 生成]
B --> C[GitHub Code Scanning]
B --> D[Artifact 上传]
C --> E[发现展示]
E --> F[代理修复流程]
F --> ACI 配置示例参考 ci/gitlab/coding-ethos-sarif.yml:
资料来源:ci/gitlab/coding-ethos-sarif.yml
快速开始
环境要求
| 要求 | 版本 |
|---|---|
| Python | 3.13+ |
| Git | 最新版 |
| uv | 最新版 |
安装
git clone https://github.com/paudley/coding-ethos.git
cd coding-ethos
make install
make doctor
生成文档
uv run python main.py --repo .
运行测试
uv run pytest
资料来源:CONTRIBUTING.md
版本信息
当前版本:0.2.1
资料来源:README.md
快速开始
本文档面向希望快速上手 coding-ethos 的开发者,介绍项目环境配置、工作流程以及核心操作命令。
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
前提条件
在开始之前,请确保本地环境满足以下要求:
| 工具 | 版本要求 | 用途 |
|---|---|---|
| Git | 最新稳定版 | 版本控制 |
| Python | 3.13+ | 运行时环境 |
| uv | 最新稳定版 | 包管理和项目工作流 |
本地环境配置
克隆仓库
git clone https://github.com/paudley/coding-ethos.git
cd coding-ethos
安装依赖
项目使用 uv 进行依赖管理和虚拟环境管理:
make install
此命令将:
- 创建或激活 Python 虚拟环境
- 安装项目依赖
- 安装开发组依赖
环境诊断
安装完成后,运行健康检查以验证环境配置:
make doctor
该命令检查:
- Python 版本是否满足要求
- 依赖包是否完整安装
- 必要的系统工具是否可用
查看可用命令
make help
显示所有可用的 Makefile 目标和快捷命令。
核心工作流程
生成与渲染流程
coding-ethos 的核心功能是将声明式的 coding_ethos.yml 和 repo_ethos.yml 配置转换为各代理平台可读的根文档文件。
graph TD
A[coding_ethos.yml] -->|加载| B[EthosBundle]
C[repo_ethos.yml] -->|合并| B
B --> D{渲染器}
D --> E[AGENTS.md]
D --> F[CLAUDE.md]
D --> G[GEMINI.md]
D --> H[ETHOS.md]资料来源:coding_ethos/__init__.py:10-25
仓库输出再生
当需要重新生成代理根文档时:
uv run python main.py --repo .
生成后,运行测试套件验证输出:
uv run pytest
资料来源:repo_ethos.yml:95-98
CLI 入口点
项目提供统一的命令行接口:
# 通用入口
python main.py [命令]
# 或通过包安装
coding-ethos [命令]
支持的命令模块包括:
| 命令 | 功能说明 |
|---|---|
mcp | 启动 MCP 服务器,提供 lint 检查和建议功能 |
ci-sarif | 生成 CI 环境下的 SARIF 报告 |
资料来源:coding_ethos/__init__.py:11
MCP 服务器快速使用
启动 MCP 服务器
make build
bin/coding-ethos-run mcp
服务器启动后,代理可通过 MCP 协议访问 lint 和策略上下文。
核心 MCP 工具
| 工具名称 | 功能 |
|---|---|
lint_check | 运行托管 lint 捕获或编译策略 lint |
lint_advice | 将诊断映射到 ETHOS 策略和技能指导 |
sarif_remediation_advice | 将 SARIF 证据转换为修复建议 |
sarif_risk_summary | 汇总严重性、文件、工具、策略和技能 |
tool_capabilities | 检查运行时能力 |
资料来源:examples/mcp-lint-advice/README.md:35-48
代理提示模式
使用以下提示模式将 lint 修复工作委托给代理:
Use the coding-ethos MCP server before running any raw linter command.
Call lint_check for the relevant scope, then use lint_advice or
sarif_remediation_advice for each actionable diagnostic.
资料来源:examples/mcp-lint-advice/README.md:56-60
CI SARIF 集成
GitHub Actions 工作流
启用 GitHub Actions SARIF 生成:
generated_config:
ci:
github_actions:
enabled: true
生成的 SARIF 工作流应:
- 运行编译的 coding-ethos 策略 lint 路径
- 即使策略违规也要写入 SARIF
- 上传到 GitHub 代码扫描
- 在配置时上传调试工件
- 上传后如果存在阻止性发现则失败作业
资料来源:examples/github-sarif-ci/README.md:13-32
代理修复工作流
当 CI 报告 coding-ethos SARIF 发现时:
- 检查 SARIF/代码扫描发现
- 使用 MCP
sarif_remediation_advice获取 ETHOS 修复上下文 - 修复结构性问题
- 重新运行本地托管检查
- 仅在本地证据干净后推送
资料来源:examples/github-sarif-ci/README.md:34-43
生成产物概览
根文档文件
| 文件 | 目标代理 | 说明 |
|---|---|---|
AGENTS.md | 所有代理 | 通用代理根文件 |
CLAUDE.md | Claude Code | Claude 专用根文件 |
GEMINI.md | Gemini CLI | Gemini 专用根文件 |
ETHOS.md | 人类开发者 | 人类可读的 ETHOS 文档 |
生成的工件约定
生成的工件必须通过源输入更改,不能直接编辑:
AGENTS.mdCLAUDE.mdGEMINI.mdETHOS.md.claude/ethos/MEMORY.md.agents/ethos/*.agent-context/prompt-addons/*
编辑 coding_ethos.yml、repo_ethos.yml 或渲染器代码,然后重新生成并审查差异。
资料来源:repo_ethos.yml:1-10
验证清单
完成快速开始后,确认以下项目正常工作:
- [ ]
make install成功完成 - [ ]
make doctor无错误 - [ ]
uv run python main.py --repo .生成根文档 - [ ]
uv run pytest所有测试通过 - [ ] MCP 服务器可启动(
bin/coding-ethos-run mcp)
下一步
- 阅读 CODING_ETHOS.md 了解包级工作流
- 查看 CONTRIBUTING.md 了解贡献指南
- 参考 MCP_SERVER.md 深入 MCP 集成
- 探索 examples/ 目录中的实际使用场景
系统架构
coding-ethos 是一个用于生成和执行编码规范(ETHOS)的开源工具项目。该系统采用多语言架构,核心逻辑使用 Python 实现,而生成的 enforcement 工具配置、CI 集成、提示词包等则由 Go 语言组件处理。
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
概述
coding-ethos 是一个用于生成和执行编码规范(ETHOS)的开源工具项目。该系统采用多语言架构,核心逻辑使用 Python 实现,而生成的 enforcement 工具配置、CI 集成、提示词包等则由 Go 语言组件处理。
系统的核心职责包括:
- 从 YAML 配置加载规范数据
- 将结构化数据渲染为 AI Agent 可读的 Markdown 文档
- 管理 pre-commit 钩子和策略执行
- 生成 SARIF 格式的扫描结果
- 提供 MCP 服务器接口供 AI Agent 调用
资料来源:coding_ethos/CODING_ETHOS.md:1-15
整体架构图
graph TB
subgraph "前端层"
CLI[CLI 入口<br/>bin/coding-ethos-run]
MCP[MCP 服务器]
end
subgraph "Python 核心包 coding_ethos"
CLI_PY[cli.py<br/>命令行解析]
LOADER[loaders.py<br/>YAML 加载与验证]
MODEL[models.py<br/>数据模型定义]
RENDER[renderers.py<br/>Markdown 渲染]
MERGE[merging.py<br/>合并策略]
MARKDOWN[markdown_seed.py<br/>Markdown 解析]
YAML_UTIL[yaml_utils.py<br/>YAML 工具]
end
subgraph "Go 组件 go/internal"
HOOK[hookrunnercli<br/>钩子运行器]
POLICY[policy<br/>策略引擎]
SARIF[SARIF 生成器]
CONFIG[配置生成器]
end
subgraph "输出产物"
AGENTS[AGENTS.md<br/>CLAUDE.md<br/>GEMINI.md]
HOOKS[pre-commit hooks]
SARIF_OUT[SARIF 文件]
end
CLI --> CLI_PY
MCP --> CLI_PY
CLI_PY --> LOADER
LOADER --> MODEL
CLI_PY --> RENDER
CLI_PY --> MERGE
CLI_PY --> MARKDOWN
CLI_PY --> YAML_UTIL
CLI_PY --> HOOK
HOOK --> POLICY
POLICY --> SARIF
POLICY --> HOOKS
RENDER --> AGENTS
MODEL --> AGENTS模块边界与职责
Python 包结构
coding_ethos/ 目录包含 Python 包的核心逻辑,采用清晰的模块边界设计:
| 模块 | 职责 | 公开 API |
|---|---|---|
cli.py | 解析参数、解析路径、协调顶层工作流 | main() |
loaders.py | 验证主规范 YAML、应用仓库覆盖、标准化数据 | load_primary_bundle() |
models.py | 定义 loaders 和 renderers 共享的 dataclass | 内部使用 |
renderers.py | 渲染 Agent 根文档、详情文档、内存文件、提示附加 | render_agent_root_outputs() |
markdown_seed.py | 将现有 Markdown 规范转换为结构化 YAML | parse_ethos_markdown() |
merging.py | 通过托管块或外部 LLM 命令保留现有根文件 | resolve_merge_bin() |
yaml_utils.py | 提供保留注释和折叠长段落的 YAML 格式化 | render_yaml() |
资料来源:coding_ethos/CODING_ETHOS.md:28-42
公共 API 导出
Python 包通过 coding_ethos/__init__.py 导出以下公开接口:
__all__ = [
"SUPPORTED_MERGE_ENGINES",
"UnsupportedMergeEngineError",
"__version__",
"format_yaml_file",
"load_primary_bundle",
"main",
"merge_repo_ethos",
"parse_ethos_markdown",
"render_agent_root_outputs",
"render_yaml",
"required_root_imports",
"resolve_merge_bin",
"root_merge_topics",
"seed_primary_from_markdown",
]
资料来源:coding_ethos/__init__.py:31-44
数据模型
核心数据结构
models.py 定义了系统内部使用的数据模型,采用 dataclass 和 slots 模式优化内存使用:
classDiagram
class EthosBundle {
+str title
+str overview
+list~Principle~ principles
+dict~str, AgentProfile~ agent_profiles
+list~EthosSkill~ skills
+RepoContext repo
+str source_markdown
}
class Principle {
+str id
+int order
+str title
+str summary
+str body
+list~PrincipleSection~ sections
+list~PrincipleAxiom~ axioms
+str directive
+list~str~ quick_ref
+list~str~ merge_topics
+list~str~ tags
+list~str~ related
+dict~str, str~ agent_hints
}
class PrincipleSection {
+str id
+str title
+str summary
+str body
+str kind
}
class AgentProfile {
+str name
+str root_file
+list~str~ supporting_files
+list~str~ notes
}
class EthosSkill {
+str id
+str title
+str description
+list~str~ principle_ids
+list~str~ trigger_terms
+str short_hint
+str focus
+list~str~ remediation_steps
}
class RepoContext {
+str name
+str overview
+dict~str, list~str~~ commands
+dict~str, str~ paths
+list~str~ notes
+dict~str, list~str~~ agent_notes
}
EthosBundle *-- Principle
EthosBundle *-- AgentProfile
EthosBundle *-- EthosSkill
EthosBundle *-- RepoContext
Principle *-- PrincipleSection
Principle *-- PrincipleAxiom资料来源:coding_ethos/models.py:1-95
支持的类型常量
| 常量 | 值 | 用途 |
|---|---|---|
SUPPORTED_AGENTS | ("codex", "claude", "gemini") | 支持的 AI Agent 类型 |
SECTION_KINDS | 包含 11 种类型 | Principle 章节类型分类 |
支持的 Section 类型包括:overview、guidance、rule、policy、workflow、anti_patterns、correct_way、rationale、examples、reference、repo_context
资料来源:coding_ethos/models.py:15-25
渲染器架构
Agent 根文件表面
renderers.py 定义了支持的 Agent 根文件表面:
| Agent | 根文件路径 | 导入声明 | 合并主题 |
|---|---|---|---|
| Codex | AGENTS.md | 无 | repo commands、key paths、repo operating notes |
| Claude | CLAUDE.md | @AGENTS.md、@.claude/ethos/MEMORY.md | Claude imports、memory links、Claude-specific workflow notes |
| Gemini | GEMINI.md | @AGENTS.md | Gemini root guidance、linked detail docs、repo operating notes |
_AGENT_ROOT_SURFACES: tuple[AgentRootSurface, ...] = (
AgentRootSurface(
agent="codex",
path="AGENTS.md",
render_root=render_agents_md,
render_addendum=render_agents_addendum,
merge_topics=("repo commands", "key paths", "repo operating notes"),
),
AgentRootSurface(
agent="claude",
path="CLAUDE.md",
render_root=_render_claude_root,
render_addendum=render_claude_addendum,
imports=("@AGENTS.md", "@.claude/ethos/MEMORY.md"),
merge_topics=(
"Claude imports",
"memory links",
"Claude-specific workflow notes",
),
),
AgentRootSurface(
agent="gemini",
path="GEMINI.md",
render_root=render_gemini_md,
render_addendum=render_gemini_addendum,
imports=("@AGENTS.md",),
merge_topics=(
"Gemini root guidance",
"linked detail docs",
"repo operating notes",
),
),
)
资料来源:coding_ethos/renderers.py:1-50
渲染工作流
graph LR
A[YAML 配置<br/>coding_ethos.yml] --> B[loaders.py<br/>加载与验证]
C[repo_ethos.yml<br/>仓库覆盖] --> B
B --> D[models.py<br/>标准化数据]
D --> E[renderers.py<br/>渲染]
E --> F[AGENTS.md]
E --> G[CLAUDE.md]
E --> G[GEMINI.md]
E --> H[ETHOS.md]
E --> I[.claude/ethos/MEMORY.md]资源路径管理
打包资源路径解析
resources.py 模块处理打包后的资源路径查找:
def resource_path(*parts: str) -> Path:
"""返回源码或打包的 coding-ethos 资源的文件系统路径。"""
source_root = Path(__file__).resolve().parent.parent
source_candidates: dict[tuple[str, ...], Path] = {
("coding_ethos.yml",): source_root / "coding_ethos.yml",
("config.yaml",): source_root / "config.yaml",
("repo_config.example.yaml",): source_root / "repo_config.example.yaml",
("repo_ethos.example.yml",): source_root / "repo_ethos.example.yml",
}
source_path = source_candidates.get(parts)
if source_path is not None and source_path.exists():
return source_path
return Path(__file__).resolve().parent.joinpath("resources", *parts)
该设计支持两种场景:
- 源码检出的开发环境:直接从仓库根目录读取配置文件
- PyPI 安装的包环境:从
coding_ethos/resources/子目录读取打包资源
Markdown 种子解析
解析流程
markdown_seed.py 实现了从 Markdown 规范文档到结构化 YAML 的转换:
graph TD
A[Markdown 规范文档] --> B[SECTION_RE<br/>匹配 H2 标题<br/>^## \*\*(\d+)\.\s*(.+?)\*\*$]
A --> C[SUBSECTION_RE<br/>匹配 H3 标题<br/>^###\s+(?:\*\*)?(.+?)(?:\*\*)?\s*$]
B --> D[_split_sections<br/>分割章节]
C --> D
D --> E[_infer_section_kind<br/>推断章节类型]
E --> F[Section Kind Markers<br/>关键词匹配]
F --> G[PrincipleSection<br/>列表]
A --> H[summarize_markdown<br/>提取摘要]
H --> I[Principle.summary]章节类型推断
系统通过关键词匹配自动推断章节类型:
| 类型 | 匹配关键词 |
|---|---|
overview | overview, summary, core principle, essence |
rationale | why, rationale, reason, motivation, importance |
anti_patterns | anti pattern, bad way, wrong way, what not to do, failure mode |
correct_way | right way, correct way, preferred way, good way |
rule | rule, policy, practical rule, non negotiable, contract |
workflow | workflow, process, procedure, steps, operational implication |
examples | example, examples |
reference | checklist, quick ref, reference |
资料来源:coding_ethos/markdown_seed.py:30-55
CLI 入口点
命令行入口架构
项目提供多层 CLI 入口:
| 入口 | 用途 |
|---|---|
python main.py | 仓库开发期间直接运行 |
uv run python main.py | 使用 uv 环境运行 |
bin/coding-ethos-run | Go 二进制程序入口 |
uv run coding-ethos | 安装后的包入口 |
graph TD
A[用户命令] --> B{入口类型}
B -->|bin/coding-ethos-run| C[Go CLI]
B -->|python main.py| D[Python CLI]
C --> E[hookrunnercli<br/>钩子运行]
C --> F[policy<br/>策略检查]
C --> G[mcp<br/>MCP 服务器]
D --> H[cli.main<br/>主函数]
H --> I[loaders.py<br/>加载配置]
H --> J[renderers.py<br/>渲染输出]
H --> K[merging.py<br/>合并文件]main.py 是一个轻量级封装,直接调用包的公共 API:
from coding_ethos import main
if __name__ == "__main__":
raise SystemExit(main())
资料来源:main.py:1-20
版本信息
| 组件 | 版本 |
|---|---|
Python 包 coding_ethos | 0.2.1 |
| Pre-commit Hooks | 0.2.0 |
资料来源:coding_ethos/__init__.py:47, pre-commit/hooks/coding_ethos_hooks/__init__.py:18
开发规则
根据项目架构设计原则:
cli.py应仅作为编排层,不包含业务逻辑- 验证逻辑 应放在
loaders.py - 输出格式化 应放在
renderers.py - 合并行为 应放在
merging.py - 生成的 enforcement 产物 应放在 Go 包
go/internal/下
当更改影响标志、输出布局、覆盖行为、生成配置内容、技能表面或提示包内容时,应在同一更改中更新 README 指导和相关测试。
核心组件
coding-ethos 是一个用于生成和执行编码规范(Ethos)的 Python 包。其核心组件体系围绕数据模型、渲染引擎、加载器和工具函数展开,共同支撑从 Markdown 源文档到多种 AI Agent 配置文件的生成流程。
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
组件架构总览
coding-ethos 的核心组件可分为四个层次:
graph TD
A["源文档层<br/>(Markdown/YAML)"] --> B["加载与解析层"]
B --> C["数据模型层"]
C --> D["渲染与输出层"]
D --> E["AGENTS.md<br/>CLAUDE.md<br/>GEMINI.md<br/>ETHOS.md"]
F["预设数据层<br/>(presets.py)"] --> B
F --> C
G["资源路径层<br/>(resources.py)"] -.-> A资料来源:coding_ethos/__init__.py:1-47
数据模型层
数据模型层定义了项目内部的核心数据结构,所有组件共享统一的类型定义。
EthosBundle
EthosBundle 是整个系统的核心数据结构,代表一个完整的规范化 ethos 载荷:
| 字段 | 类型 | 说明 |
|---|---|---|
title | str | Ethos 标题 |
overview | str | 总体概述 |
principles | list[Principle] | 原则列表 |
agent_profiles | dict[str, AgentProfile] | Agent 特定配置 |
skills | list[EthosSkill] | 生成的 Agent 技能 |
repo | RepoContext | 仓库上下文 |
source_markdown | str | 源 Markdown 内容 |
资料来源:coding_ethos/models.py:108-119
Principle(原则)
Principle 表示单个规范化 ethos 原则:
@dataclass(slots=True)
class Principle:
id: str
order: int
title: str
summary: str
body: str
sections: list[PrincipleSection] = field(default_factory=_empty_sections)
axioms: list[PrincipleAxiom] = field(default_factory=_empty_axioms)
directive: str = ""
quick_ref: list[str] = field(default_factory=_empty_str_list)
merge_topics: list[str] = field(default_factory=_empty_str_list)
tags: list[str] = field(default_factory=_empty_str_list)
related: list[str] = field(default_factory=_empty_str_list)
agent_hints: dict[str, str] = field(default_factory=_empty_str_map)
资料来源:coding_ethos/models.py:53-68
AgentProfile(Agent 配置文件)
AgentProfile 定义 Agent 特定的根文件和备注配置:
| 字段 | 类型 | 说明 |
|---|---|---|
name | str | Agent 名称 |
root_file | str | 根文件路径 |
supporting_files | list[str] | 支持文件列表 |
notes | list[str] | 备注信息 |
资料来源:coding_ethos/models.py:71-76
EthosSkill(Ethos 技能)
EthosSkill 表示从 ETHOS 原则生成的 Agent 技能:
| 字段 | 类型 | 说明 |
|---|---|---|
id | str | 技能标识符 |
title | str | 技能标题 |
description | str | 技能描述 |
principle_ids | list[str] | 关联的原则 ID |
trigger_terms | list[str] | 触发关键词 |
short_hint | str | 简短提示 |
focus | str | 关注点 |
remediation_steps | list[str] | 修复步骤 |
资料来源:coding_ethos/models.py:90-100
支持的 Section 类型
系统定义了以下标准化的 section 类型:
| 类型 | 标识符 |
|---|---|
| 概述 | overview |
| 指导 | guidance |
| 规则 | rule |
| 策略 | policy |
| 工作流 | workflow |
| 反模式 | anti_patterns |
| 正确方式 | correct_way |
| 理由 | rationale |
| 示例 | examples |
| 参考 | reference |
| 仓库上下文 | repo_context |
资料来源:coding_ethos/models.py:20-31
加载与解析层
加载与解析层负责从各种格式的源文档中提取和构建数据模型。
Markdown 种子模块
markdown_seed.py 提供了将 Markdown ethos 文档转换为结构化 YAML 数据的辅助函数:
| 函数 | 功能 |
|---|---|
parse_ethos_markdown() | 解析 Markdown 文件 |
seed_primary_from_markdown() | 从 Markdown 种子化主 bundle |
markdown_to_plain_text() | 去除 Markdown 标记 |
summarize_markdown() | 提取摘要 |
slugify() | 生成稳定的标识符 slug |
资料来源:coding_ethos/markdown_seed.py:1-100
Section 推断逻辑
模块使用正则表达式推断 section 的类型:
graph LR
A["Markdown 标题"] --> B{SECTION_RE 匹配<br/>## **序号. 标题**}
B --> C{SUBSECTION_RE 匹配<br/>### 标题}
C --> D{关键词匹配}
D -->|含 'why'/'rationale'| E["rationale"]
D -->|含 'anti pattern'| F["anti_patterns"]
D -->|含 'rule'/'policy'| G["rule/policy"]
D -->|含 'example'| H["examples"]
D -->|其他| I["guidance"]资料来源:coding_ethos/markdown_seed.py:35-70
Section 关键词标记
| Section 类型 | 匹配关键词 |
|---|---|
overview | overview, summary, core principle, essence |
rationale | why, rationale, reason, motivation, importance |
anti_patterns | anti pattern, bad way, wrong way, failure mode |
correct_way | right way, correct way, preferred way, good way |
rule | rule, policy, contract, non negotiable |
workflow | workflow, process, procedure, steps |
examples | example, examples |
reference | checklist, quick ref, reference |
资料来源:coding_ethos/markdown_seed.py:36-66
渲染层
渲染层负责将 EthosBundle 数据模型转换为各种 AI Agent 可读的根文件格式。
Agent 根表面定义
系统支持三种 AI Agent 的根文件表面:
| Agent | 根文件 | 导入文件 |
|---|---|---|
| Codex | AGENTS.md | - |
| Claude | CLAUDE.md | @AGENTS.md, @.claude/ethos/MEMORY.md |
| Gemini | GEMINI.md | @AGENTS.md |
资料来源:coding_ethos/renderers.py:80-105
AgentRootSurface 结构
@dataclass(slots=True)
class AgentRootSurface:
agent: str
path: str
render_root: Callable[[EthosBundle, Path], str]
render_addendum: Callable[[EthosBundle, Path], str]
imports: tuple[str, ...] = ()
merge_topics: tuple[str, ...] = ()
资料来源:coding_ethos/renderers.py:50-57
渲染器工作流程
graph TD
A["EthosBundle"] --> B["render_agent_root_outputs()"]
B --> C["遍历 _AGENT_ROOT_SURFACES"]
C --> D["调用 surface.render_root()"]
D --> E["生成 AGENTS.md"]
D --> F["生成 CLAUDE.md"]
D --> G["生成 GEMINI.md"]
E --> H["dict[str, str]<br/>{path: content}"]
F --> H
G --> H资料来源:coding_ethos/renderers.py:110-125
根合并主题
每个 Agent 表面定义了特定的合并主题:
| Agent 表面 | 合并主题 |
|---|---|
AGENTS.md | repo commands, key paths, repo operating notes |
CLAUDE.md | Claude imports, memory links, Claude-specific workflow notes |
GEMINI.md | Gemini root guidance, linked detail docs, repo operating notes |
资料来源:coding_ethos/renderers.py:81-104
预设数据层
presets.py 提供了共享的预设元数据和辅助构建器,保持 seeded 或手写 YAML 的紧凑性和一致性。
PRINCIPLE_PRESETS
预设数据包含以下核心原则的配置:
| 原则 ID | 指令 | 标签 |
|---|---|---|
solid-is-law | Enforce SOLID and simplicity | architecture, design |
fail-fast-fail-hard-overview | Crash early on ambiguous startup | startup, reliability |
no-conditional-imports | Treat required imports as hard dependencies | dependency, startup |
static-analysis-is-the-first-line-of-defense | Make ruff and mypy blocking gates | tooling, linting |
validation-at-the-gate | Validate during bootstrap | validation, configuration |
radical-visibility | Log decisions with context | observability, logging |
protocol-first-design | Define interfaces before implementations | architecture, interfaces |
linting-as-code-quality-enforcement | Resolve lint with structural fixes | linting, quality |
资料来源:coding_ethos/presets.py:20-90
辅助构建器函数
| 函数 | 功能 |
|---|---|
build_agent_hints() | 构建 Agent 特定提示 |
build_merge_topics() | 构建合并主题列表 |
build_quick_ref() | 构建快速参考内容 |
资料来源:coding_ethos/presets.py:1-15
资源路径层
resources.py 集中管理资源文件路径查找,支持源代码检出和打包安装两种场景。
resource_path() 函数
def resource_path(*parts: str) -> Path:
source_root = Path(__file__).resolve().parent.parent
source_candidates: dict[tuple[str, ...], Path] = {
("coding_ethos.yml",): source_root / "coding_ethos.yml",
("config.yaml",): source_root / "config.yaml",
("repo_config.example.yaml",): source_root / "repo_config.example.yaml",
("repo_ethos.example.yml",): source_root / "repo_ethos.example.yml",
}
source_path = source_candidates.get(parts)
if source_path is not None and source_path.exists():
return source_path
return Path(__file__).resolve().parent.joinpath("resources", *parts)
资料来源:coding_ethos/resources.py:17-30
路径解析逻辑
graph TD
A["resource_path() 调用"] --> B{"源码检出模式?"}
B -->|是<br/>source_candidates 匹配| C["返回源码根目录路径"]
B -->|否| D["返回打包资源路径<br/>coding_ethos/resources/*"]资料来源:coding_ethos/resources.py:1-30
公共 API 导出
coding_ethos/__init__.py 导出以下公共接口:
| 导出项 | 来源模块 | 说明 |
|---|---|---|
main | cli | CLI 入口点 |
load_primary_bundle | loaders | 加载主 bundle |
merge_repo_ethos | loaders | 合并仓库 ethos |
parse_ethos_markdown | markdown_seed | 解析 Markdown |
seed_primary_from_markdown | markdown_seed | 种子化主 bundle |
SUPPORTED_MERGE_ENGINES | merging | 支持的合并引擎 |
resolve_merge_bin | merging | 解析合并工具路径 |
render_agent_root_outputs | renderers | 渲染 Agent 根文件 |
required_root_imports | renderers | 必需的根文件导入 |
root_merge_topics | renderers | 根合并主题 |
format_yaml_file | yaml_utils | 格式化 YAML 文件 |
render_yaml | yaml_utils | 渲染 YAML |
资料来源:coding_ethos/__init__.py:20-45
版本信息
| 组件 | 版本 |
|---|---|
coding-ethos 包 | 0.2.1 |
coding-ethos-hooks | 0.2.0 |
资料来源:coding_ethos/__init__.py:47
组件交互关系
graph LR
A["coding_ethos.yml<br/>repo_ethos.yml"] --> B["loaders<br/>load_primary_bundle()"]
C["Markdown ethos"] --> D["markdown_seed<br/>parse_ethos_markdown()"]
B --> E["models<br/>EthosBundle"]
D --> E
F["presets<br/>PRINCIPLE_PRESETS"] --> E
E --> G["renderers<br/>render_agent_root_outputs()"]
G --> H["AGENTS.md"]
G --> I["CLAUDE.md"]
G --> J["GEMINI.md"]
E --> K["merging<br/>merge_repo_ethos()"]
K --> L["合并配置输出"]
E --> M["yaml_utils<br/>render_yaml()"]
M --> N["YAML 格式化输出"]支持的 AI Agent
系统当前支持以下 AI Agent:
| Agent | 支持状态 | 根文件 |
|---|---|---|
| Codex | 完整支持 | AGENTS.md |
| Claude | 完整支持 | CLAUDE.md |
| Gemini | 完整支持 | GEMINI.md |
资料来源:coding_ethos/models.py:12
总结
coding-ethos 的核心组件体系采用分层架构设计:
- 数据模型层 (
models.py) 定义了EthosBundle、Principle、AgentProfile等核心类型,所有组件共享统一的类型定义
- 加载与解析层 (
markdown_seed.py) 负责从 Markdown 源文档提取和构建数据模型,使用正则表达式推断 section 类型
- 渲染层 (
renderers.py) 将数据模型转换为 AI Agent 可读的根文件,支持 Codex、Claude 和 Gemini 三种 Agent
- 预设数据层 (
presets.py) 提供预设元数据,保持配置的一致性和紧凑性
- 资源路径层 (
resources.py) 统一管理源码和打包场景下的资源文件查找
策略引擎
策略引擎(Policy Engine)是 coding-ethos 项目的核心子系统,负责将抽象的编码规范(ETHOS)转化为可执行的策略规则,并通过 hooks、lint、SARIF 等渠道实施强制执行。策略引擎连接了声明式的规范定义与运行时策略评估,是实现 "ethos is the policy source, config is the enforcement pr...
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
策略引擎(Policy Engine)是 coding-ethos 项目的核心子系统,负责将抽象的编码规范(ETHOS)转化为可执行的策略规则,并通过 hooks、lint、SARIF 等渠道实施强制执行。策略引擎连接了声明式的规范定义与运行时策略评估,是实现 "ethos is the policy source, config is the enforcement projection" 这一核心理念的关键组件。
设计目标与核心职责
策略引擎的设计目标是在代码工作流的所有关键节点(编辑前、提交前、CI 运行时)建立统一的策略评估层。它需要满足以下几个核心需求:
单一事实来源原则:策略规则必须与其所属的 ETHOS 原则保持紧密关联。每个策略规则都应能追溯到具体的原则 ID,而非独立存在于配置文件中。资料来源:POLICY_COMPILER.md
证据映射机制:策略引擎不仅仅是执行规则,还要理解外部工具(如 linter)的输出如何映射到 ETHOS 问题。linter 代码本身并不自动构成 ETHOS 违规——需要手动审查和归类后才能建立映射关系。资料来源:POLICY_COMPILER.md
多运行时分发:编译后的策略包需要被多个运行时消费,包括 Go git hooks、Python MCP 服务器、预提交钩子、以及生成式 AI 代理的提示包。资料来源:POLICY_COMPILER.md
策略数据模型
策略引擎的核心数据模型定义在 coding_ethos/models.py 中。该文件使用 Python dataclass 定义了层次化的数据结构,从原则到具体规则形成完整的语义图。
原则(Principle)
原则是 ETHOS 规范的基本单元,包含以下关键属性:
| 属性 | 类型 | 说明 |
|---|---|---|
id | str | 原则唯一标识符,用于关联策略和原则 |
order | int | 原则在规范中的优先级顺序 |
title | str | 人类可读的原则标题 |
summary | str | 原则的一行摘要 |
body | str | 原则的完整正文内容 |
directive | str | 强制性指令,通常用于快速参考 |
quick_ref | list[str] | 快速参考要点列表 |
sections | list[PrincipleSection] | 原则的详细章节(overview、rationale、anti_patterns 等) |
axioms | list[PrincipleAxiom] | 简洁的提醒公理 |
tags | list[str] | 原则标签,用于分类和检索 |
agent_hints | dict[str, str] | 针对不同 AI 代理的提示(codex、claude、gemini) |
资料来源:coding_ethos/models.py:56-77
原则章节类型
原则的详细内容通过章节(Section)组织,支持的章节类型定义如下:
| 类型 | 关键词 | 用途 |
|---|---|---|
overview | overview, summary, core principle | 概述和摘要 |
rationale | why, rationale, reason, motivation | 设计理由 |
anti_patterns | anti pattern, bad way, wrong way | 错误示例 |
correct_way | right way, preferred way, good way | 正确做法 |
rule | rule, policy, non negotiable, contract | 强制规则 |
workflow | workflow, process, procedure, steps | 工作流程 |
examples | example, examples | 示例代码 |
reference | checklist, quick ref | 参考资料 |
资料来源:coding_ethos/models.py:19-38
策略表达式(CEL Policy)
策略规则通过 CEL(Common Expression Language)表达式定义。CEL 提供了声明式的条件评估能力,适合表达文件系统操作、工具调用等策略约束。
policies:
expressions:
- id: filesystem.large_files.no_growth
description: 大源文件禁止继续增长
event: PreToolUse
severity: block
expression: |
proposed_file_change.is_source
&& proposed_file_change.current_line_count >= 800
&& proposed_file_change.new_line_count > proposed_file_change.current_line_count
CEL 表达式中可用的上下文变量包括:
event.tool:当前工具名称(如Write、Edit、MultiEdit)proposed_file_change.*:提议的文件变更详情file_changes.exists(...):检查已变更文件列表list_contains(...):列表包含检查paths.exists(...):路径存在性检查any_glob_match(...):glob 模式匹配
资料来源:examples/cel-policy/README.md
ETHOS Bundle
EthosBundle 是完整的策略包数据结构,包含项目所有原则、技能、代理配置和仓库上下文:
@dataclass(slots=True)
class EthosBundle:
title: str # 包标题
overview: str # 概述
principles: list[Principle] # 原则列表
agent_profiles: dict[str, AgentProfile] # 代理配置
skills: list[EthosSkill] # 技能定义
repo: RepoContext # 仓库上下文
source_markdown: str = "" # 原始 Markdown
资料来源:coding_ethos/models.py:105-117
策略编译流程
策略编译是将声明式 ETHOS 规范转换为可执行策略包的过程。根据 POLICY_COMPILER.md 的规划,这一流程包含多个阶段。
编译输入
策略编译器接受两类输入源:
语义策略源:
coding_ethos.yml:主规范文件,定义团队的核心编码原则repo_ethos.yml:仓库级规范,定义特定项目的原则覆盖和追加
执行配置源:
config.yaml:主配置文件,定义工具链、钩子设置repo_config.yaml:仓库级配置
资料来源:POLICY_COMPILER.md
编译输出
编译后的策略包采用 JSON 格式存储于 .git/coding-ethos-hooks/policy/policy-bundle.json。JSON 格式的选择是因为它易于被 Go、Python、Node.js 和 shell 脚本等多种语言消费。
{
"version": 1,
"bundle_id": "example-policy-2026-04-24",
"generated_at": "2026-04-24T12:00:00Z",
"sources": {
"ethos": {
"primary": "coding_ethos.yml",
"repo": "repo_ethos.yml"
},
"enforcement": {
"primary": "config.yaml",
"repo": "repo_config.yaml"
}
},
"principles": {},
"policies": {},
"dispatch": {}
}
资料来源:POLICY_COMPILER.md
编译架构
graph TD
subgraph 编译输入
A[coding_ethos.yml]
B[repo_ethos.yml]
C[config.yaml]
D[repo_config.yaml]
end
subgraph 编译过程
E[策略编译器]
E --> F[语义策略图构建]
E --> G[运行时分发索引]
end
subgraph 编译产物
H[policy-bundle.json]
I[policy-summary.md]
J[policy-bundle.trig]
end
subgraph 运行时消费者
K[Go Git Hooks]
L[Python MCP Server]
M[Pre-commit Hooks]
N[Agent Prompt Packs]
end
A --> E
B --> E
C --> E
D --> E
H --> K
H --> L
H --> M
H --> N
J --> O[RDF查询工具]编译产物分发到多个运行时组件,每个组件负责特定场景的策略评估。
证据映射机制
策略引擎的一个关键设计是证据映射(Evidence Mapping)。这一机制建立了外部工具输出与 ETHOS 策略之间的关联。
证据映射工作流
graph LR
A[Linter 输出] --> B[追踪文件存储]
B --> C[归一化处理]
C --> D[定期审查]
D --> E{是否重复出现?}
E -->|是| F[建立证据映射]
E -->|否| G[常规工具诊断]
F --> H[策略包更新]
G --> I[显示工具原始输出]
H --> J[策略违规报告]原始 linter 追踪存储在 .coding-ethos/ 目录下,经过归一化处理后定期审查。审查通过的标准 linter 代码会被归类为策略证据,并在策略包中建立映射关系。
资料来源:POLICY_COMPILER.md
证据映射示例
principles:
- id: keep-files-focused
title: 保持文件专注
policies:
expressions:
- id: filesystem.large_files.no_growth
skill_id: file-focus-discipline
lint_scopes:
- staged
每个策略表达式都可以关联到具体的技能 ID(skill_id),用于在 MCP 服务器中提供修复建议。
策略评估
评估上下文
策略评估发生在特定的事件上下文中。以下是主要的评估事件类型:
| 事件类型 | 说明 | 典型使用场景 |
|---|---|---|
PreToolUse | 工具使用前 | 阻止不安全的文件编辑 |
PreCommit | 提交前 | 检查提交内容合规性 |
PostToolUse | 工具使用后 | 验证工具输出符合预期 |
评估结果
策略评估的结果包含以下关键信息:
- severity:违规严重程度(
block、warn、info) - skill_id:关联的修复技能 ID
- message:面向用户的消息
- advice:修复建议
- id: filesystem.generated_artifact_edit
severity: block
skill_id: agent-operating-discipline
message: 生成的文件必须通过源输入修改
advice: >-
编辑 coding_ethos.yml、repo_ethos.yml 或渲染器代码,
然后重新生成并审查差异。
资料来源:repo_ethos.yml
运行时分发
策略包被设计为分发到多个运行时环境,每个环境使用编译后的 JSON 包执行评估。
Go Git Hooks
Go 实现的 git hooks 是主要的策略执行点。hooks 在关键 Git 操作点(pre-commit、pre-push 等)注入策略评估逻辑。
Python MCP 服务器
Python MCP 服务器提供工具调用接口,允许 AI 代理通过 MCP 协议查询策略信息:
lint_check:运行托管的 lint 捕获或编译的策略 lintlint_advice:将诊断映射到 ETHOS 策略和技能指导sarif_remediation_advice:将 SARIF 证据转换为聚焦的修复建议sarif_risk_summary:汇总严重程度、文件、工具、策略和技能
资料来源:examples/mcp-lint-advice/README.md
预提交钩子
预提交钩子通过 pre-commit 框架集成,在代码提交前执行静态检查。
策略与原则的关联
策略引擎的一个核心设计原则是保持策略与原则的强关联。每个策略规则都必须归属于一个原则,并通过原则 ID 建立联系。
关联结构
Principle (keep-files-focused)
├── directive: "拆分大文件而非继续增长"
├── axioms:
│ └── "大文件隐藏多个变更原因"
├── policies:
│ └── expressions:
│ └── id: filesystem.large_files.no_growth
└── sections:
├── overview (概述)
├── rationale (理由)
└── examples (示例)
原则继承与覆盖
仓库级规范可以通过 repo_ethos.yml 覆盖和追加主规范的策略:
principles:
overrides:
protocol-first-design:
directive: 在 src/interfaces/ 中定义接口
quick_ref:
- 接口工作从 src/interfaces/ 开始
additional:
- id: migration-hygiene
order: 900
title: 迁移卫生
错误处理与降级
策略引擎在遇到错误时采用渐进式降级策略:
- 策略解析错误:记录错误但允许操作继续,同时报告违规
- 评估超时:跳过评估并记录性能问题
- 沙箱模式不可用:在
required模式下阻止操作,在optional模式下仅警告
相关文档
- CEL 策略示例
- MCP 服务器集成
- 策略编译器设计
- 预提交钩子
CEL策略表达式
CEL策略表达式(CEL Policy Expressions)是coding-ethos项目中用于定义可执行策略谓词的核心机制。CEL(Common Expression Language)是一种表达力强、安全性高的策略描述语言,coding-ethos将其集成到ETHOS原则的策略层,实现代码规范的可执行化。
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
继续阅读本节完整说明和来源证据。
概述
CEL策略表达式(CEL Policy Expressions)是coding-ethos项目中用于定义可执行策略谓词的核心机制。CEL(Common Expression Language)是一种表达力强、安全性高的策略描述语言,coding-ethos将其集成到ETHOS原则的策略层,实现代码规范的可执行化。
CEL策略表达式的设计目标是将抽象的编码原则转化为具体的、可被系统强制执行的规则。通过将策略表达式附加到ETHOS原则,开发者可以在单一源头定义规则的意图、上下文和执行逻辑,由系统自动调度至钩子(hooks)、lint检查、MCP服务和SARIF报告等各个执行路径。
资料来源:examples/cel-policy/README.md:1-10
架构设计
策略表达式在系统中的位置
CEL策略表达式位于coding-ethos架构的策略执行层,承上启下:
- 上游:ETHOS原则定义意图和上下文
- 执行层:CEL表达式提供可计算的谓词逻辑
- 下游:钩子、lint、MCP、SARIF消费同一策略ID
graph TD
A[ETHOS原则] --> B[CEL策略表达式]
B --> C[策略编译器]
C --> D[PreToolUse钩子]
C --> E[MCP lint_check]
C --> F[SARIF报告]
C --> G[CI/CD门控]资料来源:examples/cel-policy/README.md:10-20
策略表达式的数据模型
策略表达式在数据模型中的定义包含以下核心字段:
| 字段 | 类型 | 说明 |
|---|---|---|
id | string | 策略唯一标识符,格式为{category}.{rule_name} |
description | string | 策略的人类可读描述 |
event | string | 触发事件的类型,如PreToolUse |
severity | string | 严重程度:block、warn、info |
expression | string | CEL表达式谓词 |
scope | string | 作用范围:file、global |
mode | string | 执行模式:block、audit |
skill_id | string | 关联的修复技能ID |
lint_scopes | list | lint检查范围,如staged、committed |
tools | list | 适用的工具名称列表 |
message | string | 违规时显示的消息 |
advice | string | 修复建议 |
资料来源:repo_ethos.yml:1-35
CEL表达式语法
表达式结构
CEL表达式是一个返回布尔值的谓词,当结果为true时表示策略违规。表达式中可以访问系统提供的上下文变量。
proposed_file_change.is_source
&& proposed_file_change.current_line_count >= 800
&& proposed_file_change.new_line_count > proposed_file_change.current_line_count
此表达式检查:如果文件是源代码文件,且当前行数不少于800行,且修改后行数增加,则触发策略违规。
资料来源:examples/cel-policy/README.md:20-35
策略表达式示例
以下是一个完整的策略表达式配置示例,附加到ETHOS原则:
principles:
- id: keep-files-focused
title: Keep Files Focused
directive: Split large files into focused modules instead of growing them.
axioms:
- id: large-files-hide-design-problems
text: Large files hide multiple reasons to change.
policies:
expressions:
- id: filesystem.large_files.no_growth
description: Large source files must not keep growing.
event: PreToolUse
severity: block
expression: |
proposed_file_change.is_source
&& proposed_file_change.current_line_count >= 800
&& proposed_file_change.new_line_count > proposed_file_change.current_line_count
资料来源:examples/cel-policy/README.md:14-30
可用的上下文变量
文件变更上下文
proposed_file_change对象提供当前文件变更的上下文信息:
| 变量 | 类型 | 说明 |
|---|---|---|
is_source | bool | 是否为源代码文件 |
current_line_count | int | 变更前的行数 |
new_line_count | int | 变更后的行数 |
file_path | string | 文件路径 |
operation | string | 操作类型:Write、Edit、MultiEdit |
事件上下文
event对象提供触发策略检查的事件信息:
| 变量 | 类型 | 说明 |
|---|---|---|
tool | string | 被调用的工具名称 |
parameters | map | 工具参数字典 |
资料来源:examples/cel-policy/README.md:30-45
路径与匹配函数
CEL表达式支持以下内置函数用于路径匹配:
| 函数 | 说明 |
|---|---|
paths.exists(path, predicate) | 检查路径是否存在满足谓词的文件 |
any_glob_match(patterns, value) | 检查值是否匹配任一glob模式 |
list_contains(list, item) | 检查列表是否包含指定项 |
file_changes.exists(file, predicate) | 检查文件变更中是否存在满足谓词的文件 |
(
list_contains(["Write", "Edit", "MultiEdit"], event.tool) &&
paths.exists(path,
any_glob_match(
[
"AGENTS.md",
"CLAUDE.md",
"GEMINI.md",
"ETHOS.md"
],
path.file
)
)
)
资料来源:repo_ethos.yml:15-35
策略执行流程
触发与评估流程
sequenceDiagram
participant Agent as AI Agent
participant Hook as PreToolUse Hook
participant Compiler as 策略编译器
participant CEL as CEL运行时
participant Skill as 修复技能
Agent->>Hook: 执行工具操作
Hook->>Compiler: 查询适用策略
Compiler->>CEL: 评估表达式
CEL-->>Compiler: 评估结果
alt 违规
Compiler-->>Hook: 返回阻止/警告
Hook-->>Agent: 显示message和advice
Agent->>Skill: 加载skill_id
Skill-->>Agent: 返回修复步骤
Agent->>Agent: 执行修复
Agent->>Hook: 重试操作
else 合规
Compiler-->>Hook: 允许执行
Hook-->>Agent: 工具执行成功
endMCP服务集成
CEL策略表达式通过MCP服务器的lint_check和lint_advice工具暴露:
lint_check:运行托管的lint捕获或编译的策略lintlint_advice:将诊断结果映射到ETHOS策略和技能指导sarif_remediation_advice:将SARIF证据转换为聚焦的修复建议sarif_policy_feedback:识别未映射或噪音诊断
资料来源:examples/mcp-lint-advice/README.md:1-45
策略表达式的最佳实践
原则与策略的对应关系
每个策略表达式应该与其所属的ETHOS原则保持紧密对应:
- 原则说明意图:通过
title、directive、axioms描述规则的目的 - 策略提供执行:通过
policies.expressions提供可执行的谓词 - 两者共享ID体系:策略ID应能追溯到原则ID
principles:
- id: protocol-first-design
title: Protocol First Design
directive: Define interfaces before implementation.
policies:
expressions:
- id: filesystem.interface_edit
# 策略ID反映原则主题
资料来源:repo_ethos.example.yml:30-50
表达式的编写原则
- 保持表达式简洁:复杂的逻辑应拆分为多个策略或使用辅助函数
- 明确边界条件:使用精确的数值阈值和类型检查
- 提供有价值的advice:违规消息应包含具体的修复路径
- 设置合理的severity:
block用于必须遵守的规则,warn用于建议性规则
资料来源:examples/cel-policy/README.md:45-55
与SARIF的集成
CEL策略违规可以输出为SARIF格式,携带以下信息:
| SARIF字段 | 来源 |
|---|---|
ruleId | 策略表达式的id |
level | 基于severity映射 |
message | 策略的message字段 |
properties.skill_id | 关联的技能ID |
properties.principle | 所属ETHOS原则 |
通过SARIF输出,策略违规可以进入代码扫描工作流、编辑器和CI/CD门控。
资料来源:examples/cel-policy/README.md:55-65
总结
CEL策略表达式是coding-ethos实现可执行编码规范的核心机制。它通过:
- 声明式语法:使用CEL语言描述策略谓词
- 原则绑定:将策略附加到ETHOS原则,保持意图与执行的统一
- 多路径执行:通过钩子、MCP、SARIF等渠道统一执行
- 技能集成:策略违规关联修复技能,实现自动化修复指导
这一设计使得ETHOS原则既是人类可读的开发指南,也是机器可执行的策略规则,实现了编码规范从文档到实践的闭环。
失败模式与踩坑日记
保留 Doramagic 在发现、验证和编译中沉淀的项目专属风险,不把社区讨论只当作装饰信息。
Developers may fail before the first successful local run: Bundle or provision Bubblewrap as a required sandbox dependency
Developers may fail before the first successful local run: bug: commit amend is not blocked by git safety policy
可能增加新用户试用和生产接入成本。
可能阻塞安装或首次运行。
Pitfall Log / 踩坑日志
项目:paudley/coding-ethos
摘要:发现 24 个潜在踩坑项,其中 0 个为 high/blocking;最高优先级:安装坑 - 失败模式:installation: Bundle or provision Bubblewrap as a required sandbox dependency。
1. 安装坑 · 失败模式:installation: Bundle or provision Bubblewrap as a required sandbox dependency
- 严重度:medium
- 证据强度:source_linked
- 发现:Developers should check this installation risk before relying on the project: Bundle or provision Bubblewrap as a required sandbox dependency
- 对用户的影响:Developers may fail before the first successful local run: Bundle or provision Bubblewrap as a required sandbox dependency
- 证据:failure_mode_cluster:github_issue | https://github.com/paudley/coding-ethos/issues/132 | Bundle or provision Bubblewrap as a required sandbox dependency
2. 安装坑 · 失败模式:installation: bug: commit amend is not blocked by git safety policy
- 严重度:medium
- 证据强度:source_linked
- 发现:Developers should check this installation risk before relying on the project: bug: commit amend is not blocked by git safety policy
- 对用户的影响:Developers may fail before the first successful local run: bug: commit amend is not blocked by git safety policy
- 证据:failure_mode_cluster:github_issue | https://github.com/paudley/coding-ethos/issues/112 | bug: commit amend is not blocked by git safety policy
3. 安装坑 · 来源证据:Bundle or provision Bubblewrap as a required sandbox dependency
- 严重度:medium
- 证据强度:source_linked
- 发现:GitHub 社区证据显示该项目存在一个安装相关的待验证问题:Bundle or provision Bubblewrap as a required sandbox dependency
- 对用户的影响:可能增加新用户试用和生产接入成本。
- 证据:community_evidence:github | https://github.com/paudley/coding-ethos/issues/132 | 来源类型 github_issue 暴露的待验证使用条件。
4. 安装坑 · 来源证据:bug: commit amend is not blocked by git safety policy
- 严重度:medium
- 证据强度:source_linked
- 发现:GitHub 社区证据显示该项目存在一个安装相关的待验证问题:bug: commit amend is not blocked by git safety policy
- 对用户的影响:可能阻塞安装或首次运行。
- 证据:community_evidence:github | https://github.com/paudley/coding-ethos/issues/112 | 来源类型 github_issue 暴露的待验证使用条件。
5. 配置坑 · 失败模式:configuration: [feature] Agent Proxy: Pre-Flight File Indexing and AST Anatomy Mapping
- 严重度:medium
- 证据强度:source_linked
- 发现:Developers should check this configuration risk before relying on the project: [feature] Agent Proxy: Pre-Flight File Indexing and AST Anatomy Mapping
- 对用户的影响:Developers may misconfigure credentials, environment, or host setup: [feature] Agent Proxy: Pre-Flight File Indexing and AST Anatomy Mapping
- 证据:failure_mode_cluster:github_issue | https://github.com/paudley/coding-ethos/issues/54 | [feature] Agent Proxy: Pre-Flight File Indexing and AST Anatomy Mapping
6. 配置坑 · 失败模式:configuration: [test] Add sandbox workflow E2E coverage
- 严重度:medium
- 证据强度:source_linked
- 发现:Developers should check this configuration risk before relying on the project: [test] Add sandbox workflow E2E coverage
- 对用户的影响:Developers may misconfigure credentials, environment, or host setup: [test] Add sandbox workflow E2E coverage
- 证据:failure_mode_cluster:github_issue | https://github.com/paudley/coding-ethos/issues/129 | [test] Add sandbox workflow E2E coverage
7. 配置坑 · 来源证据:[test] Add real MCP stdio workflow coverage
- 严重度:medium
- 证据强度:source_linked
- 发现:GitHub 社区证据显示该项目存在一个配置相关的待验证问题:[test] Add real MCP stdio workflow coverage
- 对用户的影响:可能增加新用户试用和生产接入成本。
- 证据:community_evidence:github | https://github.com/paudley/coding-ethos/issues/114 | 来源类型 github_issue 暴露的待验证使用条件。
8. 能力坑 · 能力判断依赖假设
- 严重度:medium
- 证据强度:source_linked
- 发现:README/documentation is current enough for a first validation pass.
- 对用户的影响:假设不成立时,用户拿不到承诺的能力。
- 证据:capability.assumptions | github_repo:1214781313 | https://github.com/paudley/coding-ethos | README/documentation is current enough for a first validation pass.
9. 运行坑 · 失败模式:runtime: [feature] Agent Proxy: Tool Output Compression and Stack Trace Truncation
- 严重度:medium
- 证据强度:source_linked
- 发现:Developers should check this runtime risk before relying on the project: [feature] Agent Proxy: Tool Output Compression and Stack Trace Truncation
- 对用户的影响:Developers may hit a documented source-backed failure mode: [feature] Agent Proxy: Tool Output Compression and Stack Trace Truncation
- 证据:failure_mode_cluster:github_issue | https://github.com/paudley/coding-ethos/issues/55 | [feature] Agent Proxy: Tool Output Compression and Stack Trace Truncation
10. 维护坑 · 维护活跃度未知
- 严重度:medium
- 证据强度:source_linked
- 发现:未记录 last_activity_observed。
- 对用户的影响:新项目、停更项目和活跃项目会被混在一起,推荐信任度下降。
- 证据:evidence.maintainer_signals | github_repo:1214781313 | https://github.com/paudley/coding-ethos | last_activity_observed missing
- 严重度:medium
- 证据强度:source_linked
- 发现:no_demo
- 证据:downstream_validation.risk_items | github_repo:1214781313 | https://github.com/paudley/coding-ethos | no_demo; severity=medium
12. 安全/权限坑 · 存在评分风险
- 严重度:medium
- 证据强度:source_linked
- 发现:no_demo
- 对用户的影响:风险会影响是否适合普通用户安装。
- 证据:risks.scoring_risks | github_repo:1214781313 | https://github.com/paudley/coding-ethos | no_demo; severity=medium
13. 安全/权限坑 · 来源证据:[feature] Agent Proxy: Generate Global AST Repo Map on Session Start
- 严重度:medium
- 证据强度:source_linked
- 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:[feature] Agent Proxy: Generate Global AST Repo Map on Session Start
- 对用户的影响:可能影响授权、密钥配置或安全边界。
- 证据:community_evidence:github | https://github.com/paudley/coding-ethos/issues/59 | 来源类型 github_issue 暴露的待验证使用条件。
14. 安全/权限坑 · 来源证据:[feature] Agent Proxy: Implement Read Deduplication & Caching for File Access
- 严重度:medium
- 证据强度:source_linked
- 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:[feature] Agent Proxy: Implement Read Deduplication & Caching for File Access
- 对用户的影响:可能影响授权、密钥配置或安全边界。
- 证据:community_evidence:github | https://github.com/paudley/coding-ethos/issues/53 | 来源类型 github_issue 暴露的待验证使用条件。
15. 安全/权限坑 · 来源证据:[feature] Agent Proxy: Pre-Flight File Indexing and AST Anatomy Mapping
- 严重度:medium
- 证据强度:source_linked
- 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:[feature] Agent Proxy: Pre-Flight File Indexing and AST Anatomy Mapping
- 对用户的影响:可能影响授权、密钥配置或安全边界。
- 证据:community_evidence:github | https://github.com/paudley/coding-ethos/issues/54 | 来源类型 github_issue 暴露的待验证使用条件。
16. 安全/权限坑 · 来源证据:[feature] Agent Proxy: Tool Output Compression and Stack Trace Truncation
- 严重度:medium
- 证据强度:source_linked
- 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:[feature] Agent Proxy: Tool Output Compression and Stack Trace Truncation
- 对用户的影响:可能影响授权、密钥配置或安全边界。
- 证据:community_evidence:github | https://github.com/paudley/coding-ethos/issues/55 | 来源讨论提到 python 相关条件,需在安装/试用前复核。
17. 安全/权限坑 · 来源证据:[test] Add sandbox workflow E2E coverage
- 严重度:medium
- 证据强度:source_linked
- 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:[test] Add sandbox workflow E2E coverage
- 对用户的影响:可能阻塞安装或首次运行。
- 证据:community_evidence:github | https://github.com/paudley/coding-ethos/issues/129 | 来源类型 github_issue 暴露的待验证使用条件。
18. 能力坑 · 失败模式:capability: [feature] Agent Proxy: Implement Read Deduplication & Caching for File Access
- 严重度:low
- 证据强度:source_linked
- 发现:Developers should check this capability risk before relying on the project: [feature] Agent Proxy: Implement Read Deduplication & Caching for File Access
- 对用户的影响:Developers may hit a documented source-backed failure mode: [feature] Agent Proxy: Implement Read Deduplication & Caching for File Access
- 证据:failure_mode_cluster:github_issue | https://github.com/paudley/coding-ethos/issues/53 | [feature] Agent Proxy: Implement Read Deduplication & Caching for File Access
19. 能力坑 · 失败模式:capability: [test] Add real MCP stdio workflow coverage
- 严重度:low
- 证据强度:source_linked
- 发现:Developers should check this capability risk before relying on the project: [test] Add real MCP stdio workflow coverage
- 对用户的影响:Developers may hit a documented source-backed failure mode: [test] Add real MCP stdio workflow coverage
- 证据:failure_mode_cluster:github_issue | https://github.com/paudley/coding-ethos/issues/114 | [test] Add real MCP stdio workflow coverage
20. 能力坑 · 失败模式:conceptual: [feature] Agent Proxy: Generate Global AST Repo Map on Session Start
- 严重度:low
- 证据强度:source_linked
- 发现:Developers should check this conceptual risk before relying on the project: [feature] Agent Proxy: Generate Global AST Repo Map on Session Start
- 对用户的影响:Developers may hit a documented source-backed failure mode: [feature] Agent Proxy: Generate Global AST Repo Map on Session Start
- 证据:failure_mode_cluster:github_issue | https://github.com/paudley/coding-ethos/issues/59 | [feature] Agent Proxy: Generate Global AST Repo Map on Session Start
21. 维护坑 · issue/PR 响应质量未知
- 严重度:low
- 证据强度:source_linked
- 发现:issue_or_pr_quality=unknown。
- 对用户的影响:用户无法判断遇到问题后是否有人维护。
- 证据:evidence.maintainer_signals | github_repo:1214781313 | https://github.com/paudley/coding-ethos | issue_or_pr_quality=unknown
22. 维护坑 · 发布节奏不明确
- 严重度:low
- 证据强度:source_linked
- 发现:release_recency=unknown。
- 对用户的影响:安装命令和文档可能落后于代码,用户踩坑概率升高。
- 证据:evidence.maintainer_signals | github_repo:1214781313 | https://github.com/paudley/coding-ethos | release_recency=unknown
23. 维护坑 · 失败模式:maintenance: v0.2.0
- 严重度:low
- 证据强度:source_linked
- 发现:Developers should check this maintenance risk before relying on the project: v0.2.0
- 对用户的影响:Upgrade or migration may change expected behavior: v0.2.0
- 证据:failure_mode_cluster:github_release | https://github.com/paudley/coding-ethos/releases/tag/v0.2.0 | v0.2.0
24. 维护坑 · 失败模式:maintenance: v0.2.1
- 严重度:low
- 证据强度:source_linked
- 发现:Developers should check this maintenance risk before relying on the project: v0.2.1
- 对用户的影响:Upgrade or migration may change expected behavior: v0.2.1
- 证据:failure_mode_cluster:github_release | https://github.com/paudley/coding-ethos/releases/tag/v0.2.1 | v0.2.1
来源:Doramagic 发现、验证与编译记录