pravidhi-commit-protocol
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePravidhi Commit Protocol Skill
Pravidhi 提交协议技能
Overview
概述
This skill drives a complete, repeatable, and quality-enforced coding workflow inside any Git repository. Every major stage can pause and ask the user for input. The goal is clean atomic commits, zero leaked secrets, minimal diff noise, and a passing CI pipeline before a single line is pushed.
Formatting threshold (hardcoded default): If more than 10 files would be reformatted, stop and ask the user before applying formatting. Adjust per project if the user instructs you to.
本技能可为任意Git仓库提供一套完整、可复用、质量强管控的编码工作流,每个核心阶段都可以暂停并向用户请求输入。目标是在任何代码推送前实现清晰的原子提交、零密钥泄露、最小差异噪声以及CI流水线全量通过。
格式化阈值(硬编码默认值): 如果需要格式化的文件超过10个,应用格式化前需停止并询问用户。如果用户有明确指令,可按项目需求调整阈值。
Quick Reference
快速参考
| Stage | Key Actions |
|---|---|
| 1. Repo Hygiene | branch check, fetch, pull, porcelain status, .gitignore triage |
| 2. Dependency & Security | audit (npm/pip/cargo/etc.), known-vuln scan |
| 3. Pre-coding Quality | formatter dry-run, linter check-only |
| 4. CI/CD Pre-validation | detect & mirror local CI checks |
| 5. Refactor Safety Net | revert command, risks, rollback verification |
| 6. Implementation | scoped, convention-respecting code changes |
| 7. Post-coding Validation | format, lint, type-check, tests, coverage, build, hooks |
| 8. Secret Detection | scan staged files before commit |
| 9. CHANGELOG | detect & prompt update |
| 10. Commit & Push | atomic, high-quality commit message |
| 11. Pull Request | generate PR/MR via CLI or link |
| 阶段 | 核心操作 |
|---|---|
| 1. 仓库规范检查 | 分支检查、fetch拉取、pull同步、简洁状态检查、.gitignore分类处理 |
| 2. 依赖与安全审计 | 多生态审计(npm/pip/cargo等)、已知漏洞扫描 |
| 3. 编码前质量检查 | 格式化工具干跑、仅检查模式的linter校验 |
| 4. CI/CD 前置校验 | 识别并在本地镜像执行CI检查 |
| 5. 重构安全网 | 回滚命令、风险评估、回滚验证 |
| 6. 代码实现 | 范围可控、符合规范的代码变更 |
| 7. 编码后验证 | 格式化、lint检查、类型检查、测试、覆盖率、构建、钩子执行 |
| 8. 密钥检测 | 提交前扫描暂存文件 |
| 9. CHANGELOG 检查 | 识别变更并提示更新 |
| 10. 提交与推送 | 原子化、高质量的提交信息 |
| 11. 拉取请求 | 通过CLI或链接生成PR/MR |
Stage 1 — Repository Hygiene
阶段1 — 仓库规范检查
1.1 Branch Safety Check
1.1 分支安全校验
bash
git branch --show-current
Rules:
- If branch is ,
main,master, ordev: STOP. Ask user: "You are on a protected branch. Should I create a new feature branch namedproduction?"feature/<task-slug> - If branch is a feature branch: Proceed.
bash
git branch --show-current
规则:
- 如果当前分支是 、
main、master或dev:立即停止,询问用户:"您当前处于受保护分支,是否需要创建名为production的新功能分支?"feature/<任务标识> - 如果当前是功能分支:继续执行后续流程。
1.2 Sync with Remote
1.2 与远程仓库同步
bash
git fetch --all --prune
git pull --ff-only
If fails, stop and ask the user whether to rebase or merge.
--ff-onlybash
git fetch --all --prune
git pull --ff-only
如果 执行失败,停止并询问用户选择变基还是合并。
--ff-only1.3 Check for Uncommitted Changes
1.3 检查未提交变更
bash
git status --porcelain
- Empty output → repository is clean, continue.
- Non-empty output → inspect each entry:
| Prefix | Meaning | Action |
|---|---|---|
| Modified tracked file | Ask: stash, commit, or abort? |
| Staged new file | Ask: keep staged or unstage? |
| Untracked file | Evaluate for .gitignore (see 1.4) |
| Deleted file | Ask: intentional or restore? |
Present a clean summary to the user and ask how to proceed before continuing.
bash
git status --porcelain
- 输出为空 → 仓库干净,继续执行。
- 输出非空 → 逐一检查每个条目:
| 前缀 | 含义 | 操作 |
|---|---|---|
| 已修改的跟踪文件 | 询问:暂存、提交还是终止操作? |
| 已暂存的新文件 | 询问:保留暂存还是取消暂存? |
| 未跟踪文件 | 评估是否应该加入.gitignore(见1.4) |
| 已删除文件 | 询问:是 intentional 删除还是恢复文件? |
向用户展示清晰的汇总信息,询问下一步操作后再继续。
1.4 .gitignore Triage
1.4 .gitignore 分类处理
Scan untracked paths ( entries) and immediately add known suspects to without asking:
??.gitignoretext
undefined扫描未跟踪路径( 条目),无需询问直接将已知类型的无关文件加入 :
??.gitignoretext
undefinedBuild artifacts
构建产物
dist/ build/ out/ target/ .next/
pycache/ *.pyc *.pyo *.class *.o
dist/ build/ out/ target/ .next/
pycache/ *.pyc *.pyo *.class *.o
Logs & temp
日志与临时文件
*.log *.tmp .DS_Store Thumbs.db
*.log *.tmp .DS_Store Thumbs.db
Generated files
生成文件
coverage/ .nyc_output/ *.lcov htmlcov/
coverage/ .nyc_output/ *.lcov htmlcov/
Secrets & environment (NEVER commit these)
密钥与环境变量(绝对不能提交)
.env .env.* *.pem *.key *.p12
secrets/ credentials/ .aws/ .gcloud/
.env .env.* *.pem *.key *.p12
secrets/ credentials/ .aws/ .gcloud/
IDE / editor
IDE/编辑器配置
.idea/ .vscode/ *.swp *.swo
For **ambiguous** untracked paths (not obviously an artifact), ask the user before adding.
Stage and commit `.gitignore` changes as a standalone commit:
```text
chore: update .gitignore — exclude build artifacts and env files
.idea/ .vscode/ *.swp *.swo
对于**含义不明确**的未跟踪路径(明显不是构建产物的),加入.gitignore前先询问用户。
将.gitignore的变更作为独立提交暂存并提交:
```text
chore: update .gitignore — exclude build artifacts and env files
Stage 2 — Dependency & Security Audit
阶段2 — 依赖与安全审计
Run the appropriate audit for the detected ecosystem(s). Multiple ecosystems may be present in a monorepo.
针对识别到的技术生态执行对应的审计,单体仓库可能存在多个技术生态。
Detection
生态识别
bash
undefinedbash
undefinedDetect ecosystems
识别技术生态
ls package.json package-lock.json yarn.lock pnpm-lock.yaml # Node
ls requirements.txt Pipfile pyproject.toml setup.py # Python
ls Cargo.toml # Rust
ls go.sum # Go
ls Gemfile.lock # Ruby
ls composer.lock # PHP
undefinedls package.json package-lock.json yarn.lock pnpm-lock.yaml # Node
ls requirements.txt Pipfile pyproject.toml setup.py # Python
ls Cargo.toml # Rust
ls go.sum # Go
ls Gemfile.lock # Ruby
ls composer.lock # PHP
undefinedAudit Commands by Ecosystem
各生态审计命令
bash
undefinedbash
undefinedNode
Node
npm audit --audit-level=moderate # or: yarn audit / pnpm audit
npx audit-ci --moderate # CI-friendly exit code
npm audit --audit-level=moderate # 或: yarn audit / pnpm audit
npx audit-ci --moderate # 适配CI的退出码
Python
Python
pip-audit # pip install pip-audit
safety check --full-report # pip install safety
pip-audit # pip install pip-audit
safety check --full-report # pip install safety
Rust
Rust
cargo audit # cargo install cargo-audit
cargo audit # cargo install cargo-audit
Go
Go
govulncheck ./... # go install golang.org/x/vuln/cmd/govulncheck
govulncheck ./... # go install golang.org/x/vuln/cmd/govulncheck
Ruby
Ruby
bundle audit check --update # gem install bundler-audit
bundle audit check --update # gem install bundler-audit
PHP
PHP
composer audit
undefinedcomposer audit
undefinedDecision Logic
决策逻辑
| Severity Found | Action |
|---|---|
| Critical | Stop immediately. Do not proceed. Show findings. Ask: patch deps now or abort? |
| High | Stop. Ask: patch now (separate commit) or accept risk and continue? |
| Moderate | Warn. Ask: patch now or track in a follow-up ticket? |
| Low / Info | Note in output, continue automatically. |
If the user chooses to patch:
- Apply fixes (,
npm audit fix, etc.)pip install --upgrade <pkg> - Run audit again to confirm clean
- Commit as a standalone commit:
text
chore(deps): fix [critical|high] security vulnerabilities — <brief description>
| 发现的漏洞等级 | 操作 |
|---|---|
| 严重 | 立即停止,不继续执行后续流程。展示漏洞详情,询问:现在修复依赖还是终止操作? |
| 高危 | 停止,询问:现在修复(单独提交)还是接受风险继续执行? |
| 中危 | 发出警告,询问:现在修复还是在后续工单中跟踪处理? |
| 低危/提示 | 在输出中备注,自动继续执行。 |
如果用户选择修复:
- 应用修复(、
npm audit fix等)pip install --upgrade <包名> - 重新运行审计确认无漏洞
- 作为独立提交:
text
chore(deps): fix [critical|high] security vulnerabilities — <简要描述>
Stage 3 — Pre-coding Quality Checks
阶段3 — 编码前质量检查
3.1 Check Memory for User Preferences
3.1 检查用户偏好记忆
Before running any tools, check if there is a stored preference from previous sessions:
- → skip formatter dry-run
skip_pre_coding_format: true - → skip linter check-only pass
skip_pre_coding_lint: true - → override the default threshold of 10
format_commit_threshold: <N>
If no memory exists, proceed with defaults and store the user's decisions at the end of this stage (see Stage 6).
运行任何工具前,检查之前会话是否存储了用户偏好:
- → 跳过格式化工具干跑
skip_pre_coding_format: true - → 跳过仅检查模式的linter校验
skip_pre_coding_lint: true - → 覆盖默认的10个文件阈值
format_commit_threshold: <N>
如果没有记忆记录,使用默认值执行,并在本阶段结束时存储用户的决策(见阶段6)。
3.2 Formatter Dry-Run
3.2 格式化工具干跑
Detect the formatter from config files:
bash
undefined通过配置文件识别格式化工具:
bash
undefinedPrettier (JS/TS/CSS/HTML/JSON/YAML)
Prettier (JS/TS/CSS/HTML/JSON/YAML)
npx prettier --list-different "**/*.{js,ts,jsx,tsx,css,json,yaml,md}"
npx prettier --list-different "**/*.{js,ts,jsx,tsx,css,json,yaml,md}"
Black (Python)
Black (Python)
black --check --diff .
black --check --diff .
Rustfmt
Rustfmt
cargo fmt -- --check
cargo fmt -- --check
gofmt
gofmt
gofmt -l ./...
gofmt -l ./...
PHP CS Fixer
PHP CS Fixer
php-cs-fixer fix --dry-run --diff
php-cs-fixer fix --dry-run --diff
rubocop (Ruby)
rubocop (Ruby)
rubocop --auto-correct-all --dry-run
Count the number of files that would be reformatted.
**If count > threshold (default: 10):**
> 🛑 **Formatting check found N files that would be reformatted.**
> Creating a dedicated formatting commit before implementing your task has these benefits:
> * **Clean diffs** — reviewers see only your feature changes, not whitespace noise
> * **Clearer Git history** — formatting is a separate, revertable concern
> * **Easier code review** — no mixing of stylistic and semantic changes
> * **Reduced merge conflicts** — formatting is settled before feature branching
>
>
> **Would you like to:**
> 1. Apply formatting now in a dedicated commit, then proceed with your task
> 2. Skip formatting for now and proceed directly with the task
> 3. Apply formatting only to files touched by the task (post-coding)
>
>
Store the user's choice for future sessions.rubocop --auto-correct-all --dry-run
统计需要格式化的文件数量。
**如果数量 > 阈值(默认:10):**
> 🛑 **格式化检查发现N个文件需要格式化。**
> 在实现需求前创建独立的格式化提交有以下好处:
> * **清晰的差异** → 评审者只会看到你的功能变更,不会看到空格类噪声
> * **更清晰的Git历史** → 格式化是独立的、可回滚的操作
> * **更简单的代码评审** → 不会混合风格变更和语义变更
> * **减少合并冲突** → 功能分支创建前先解决格式化问题
>
>
> **您希望如何处理:**
> 1. 现在创建独立的格式化提交,再继续实现需求
> 2. 暂时跳过格式化,直接开始实现需求
> 3. 仅格式化本次任务修改的文件(编码后执行)
>
>
存储用户的选择供后续会话使用。3.3 Linter Check-Only
3.3 Linter仅检查模式
Detect and run:
bash
undefined识别并运行linter:
bash
undefinedESLint
ESLint
npx eslint . --format=compact 2>&1 | tail -1 # count violations
npx eslint . --format=compact 2>&1 | tail -1 # 统计违规数量
Pylint / Flake8 / Ruff
Pylint / Flake8 / Ruff
ruff check . --statistics
flake8 . --statistics --count
ruff check . --statistics
flake8 . --statistics --count
Clippy (Rust)
Clippy (Rust)
cargo clippy -- -D warnings 2>&1 | grep -c "^error"
cargo clippy -- -D warnings 2>&1 | grep -c "^error"
golint / staticcheck (Go)
golint / staticcheck (Go)
staticcheck ./...
staticcheck ./...
rubocop (Ruby)
rubocop (Ruby)
rubocop --format progress | tail -3
Classify output:
| Violation Count | Classification | Action |
| --- | --- | --- |
| 0–5 | Minor | Continue, note in output |
| 6–20 | Moderate | Stop, ask user (fix in dedicated commit or continue?) |
| 21+ | Extensive | Stop, strongly recommend dedicated lint fix commit |
If user chooses to fix lint:
1. Run auto-fix where safe: `npx eslint . --fix`, `ruff check . --fix`, `cargo clippy --fix`
2. Manually address remaining issues
3. Commit:
```text
chore(lint): resolve linting violations before feature work
rubocop --format progress | tail -3
对输出进行分类:
| 违规数量 | 分类 | 操作 |
| --- | --- | --- |
| 0–5 | 轻微 | 继续执行,在输出中备注 |
| 6–20 | 中等 | 停止,询问用户(创建独立提交修复还是继续执行?) |
| 21+ | 大量 | 停止,强烈建议创建独立的lint修复提交 |
如果用户选择修复lint问题:
1. 安全范围内运行自动修复:`npx eslint . --fix`、`ruff check . --fix`、`cargo clippy --fix`
2. 手动处理剩余问题
3. 提交:
```text
chore(lint): resolve linting violations before feature work
Stage 4 — CI/CD Pre-validation
阶段4 — CI/CD 前置校验
4.1 Detect CI Configuration
4.1 识别CI配置
bash
ls .github/workflows/ # GitHub Actions
ls .gitlab-ci.yml # GitLab CI
ls Jenkinsfile # Jenkins
ls .circleci/config.yml # CircleCI
ls .travis.yml # Travis CI
ls azure-pipelines.yml # Azure DevOps
ls bitbucket-pipelines.yml
ls .drone.yml
bash
ls .github/workflows/ # GitHub Actions
ls .gitlab-ci.yml # GitLab CI
ls Jenkinsfile # Jenkins
ls .circleci/config.yml # CircleCI
ls .travis.yml # Travis CI
ls azure-pipelines.yml # Azure DevOps
ls bitbucket-pipelines.yml
ls .drone.yml
4.2 Extract and Mirror CI Steps Locally
4.2 提取并在本地镜像执行CI步骤
Parse the CI config and identify steps that can be run locally. Common patterns to extract:
bash
undefined解析CI配置,识别可以在本地运行的步骤。常见提取模式:
bash
undefinedFrom GitHub Actions: find "run:" steps
从GitHub Actions中查找"run:"步骤
grep -A1 "run:" .github/workflows/*.yml
grep -A1 "run:" .github/workflows/*.yml
Run them in the same order as CI
按照CI中的顺序执行步骤
**Example mapping (GitHub Actions → local equivalents):**
```yaml
**示例映射(GitHub Actions → 本地等价命令):**
```yamlCI step: # Local equivalent:
CI步骤: # 本地等价命令:
npm ci → npm ci
npm run build → npm run build
npm test → npm test
npm run lint → npx eslint .
npm run type-check → npx tsc --noEmit
For each detected CI step, run it locally and capture exit codes. If any step fails:
> ⚠️ **CI pre-validation failure: `<step name>**`
> The following CI step failed locally: `<command>`
> Exit code: `<N>`
> Output: `<last 20 lines>`
> This will likely cause CI to fail after push.
> **Would you like to:**
> 1. Fix the issue now before implementing the task
> 2. Note it and proceed (I'll flag this again at post-coding validation)
> 3. Abort
>
>npm ci → npm ci
npm run build → npm run build
npm test → npm test
npm run lint → npx eslint .
npm run type-check → npx tsc --noEmit
对每个识别到的CI步骤,在本地运行并捕获退出码。如果任何步骤失败:
> ⚠️ **CI前置校验失败:`<步骤名>`**
> 以下CI步骤在本地运行失败:`<命令>`
> 退出码:`<N>`
> 输出:`<最后20行>`
> 这大概率会导致推送后CI运行失败。
> **您希望如何处理:**
> 1. 在实现需求前先修复这个问题
> 2. 备注该问题继续执行(我会在编码后验证阶段再次提示)
> 3. 终止操作
>
>4.3 Pre-commit / Pre-push Hook Detection
4.3 预提交/预推送钩子识别
bash
ls .git/hooks/pre-commit .git/hooks/pre-push
ls .husky/pre-commit .husky/pre-push # Husky
ls .lefthook.yml lefthook.yml # Lefthook
ls .pre-commit-config.yaml # pre-commit framework
If hooks exist, run them now as a pre-flight check:
bash
undefinedbash
ls .git/hooks/pre-commit .git/hooks/pre-push
ls .husky/pre-commit .husky/pre-push # Husky
ls .lefthook.yml lefthook.yml # Lefthook
ls .pre-commit-config.yaml # pre-commit 框架
如果存在钩子,现在作为预检项运行:
bash
undefinedNative hooks
原生钩子
bash .git/hooks/pre-commit
bash .git/hooks/pre-push
bash .git/hooks/pre-commit
bash .git/hooks/pre-push
Husky
Husky
npx husky run pre-commit
npx husky run pre-commit
pre-commit framework
pre-commit 框架
pre-commit run --all-files
pre-commit run --all-files
Lefthook
Lefthook
lefthook run pre-commit
If hooks fail, stop and report. Hooks represent the project's own quality gate — do not bypass them.
---lefthook run pre-commit
如果钩子运行失败,停止并报告。钩子是项目自身的质量门禁,不能绕过。
---Stage 5 — Refactor Safety Net (Major Refactors Only)
阶段5 — 重构安全网(仅大型重构时触发)
Trigger this stage if the task involves:
- Renaming or moving multiple files/modules
- Changing a public API or interface
- Modifying database schemas or migrations
- Restructuring directory layout
- Changing build configuration or dependency graph
当任务包含以下内容时触发本阶段:
- 重命名或移动多个文件/模块
- 修改公共API或接口
- 变更数据库 schema 或迁移脚本
- 调整目录结构
- 修改构建配置或依赖图谱
5.1 Document Before Touching Code
5.1 编写代码前先文档化
Before writing a single line, output and store:
markdown
undefined编写任何代码前,输出并存储:
markdown
undefinedRefactor Safety Net
重构安全网
Task: <description of refactor>
Date: <ISO timestamp>
任务: <重构描述>
日期: <ISO时间戳>
Revert Command
回滚命令
bash
git stash # if not yet committedbash
git stash # 如果还未提交OR
或
git revert <SHA> # if committed
git revert <SHA> # 如果已经提交
OR
或
git reset --hard <SHA-before-changes>
undefinedgit reset --hard <变更前的SHA>
undefinedKnown Risks
已知风险
- <Risk 1: e.g., "API consumers outside this repo may break">
- <Risk 2: e.g., "Database migration is irreversible without a down migration">
- <Risk 3: e.g., "Cache keys will be invalidated — plan for cold cache on deploy">
- <风险1:例如 "本仓库外的API消费者可能会中断">
- <风险2:例如 "数据库迁移没有回滚脚本,不可逆">
- <风险3:例如 "缓存键会失效,部署时需要准备冷缓存预案">
Rollback Verification Steps
回滚验证步骤
- Run:
<command to verify system is working post-rollback> - Check:
<what to look for in logs or UI> - Confirm:
<specific assertion that proves rollback succeeded>
Present this to the user and ask for confirmation before proceeding.- 运行:
<回滚后验证系统正常的命令> - 检查:
<需要在日志或UI中确认的内容> - 确认:
<证明回滚成功的具体断言>
向用户展示以上内容并请求确认后再继续。5.2 Create a Pre-refactor Tag
5.2 创建重构前标签
bash
git tag pre-refactor/<task-slug>-$(date +%Y%m%d)
git push origin pre-refactor/<task-slug>-$(date +%Y%m%d)
This gives a named rollback point that survives branch resets.
bash
git tag pre-refactor/<任务标识>-$(date +%Y%m%d)
git push origin pre-refactor/<任务标识>-$(date +%Y%m%d)
这会创建一个命名的回滚点,不会被分支重置操作清除。
Stage 6 — Implementation
阶段6 — 代码实现
6.1 Store User Preferences from Prior Stages
6.1 存储之前阶段的用户偏好
At this point, persist the following to memory for future workflow runs:
text
skip_pre_coding_format: <true|false>
skip_pre_coding_lint: <true|false>
format_commit_threshold: <N>
audit_severity_threshold: <critical|high|moderate>
此时,将以下配置持久化存储到内存,供后续工作流运行使用:
text
skip_pre_coding_format: <true|false>
skip_pre_coding_lint: <true|false>
format_commit_threshold: <N>
audit_severity_threshold: <critical|high|moderate>
6.2 Define Scope
6.2 定义范围
Before writing code, state clearly:
text
Task: <one-line description of what is being implemented>
Files: <exhaustive list of files to modify>
Scope: <what is explicitly OUT of scope for this change>
编写代码前,清晰说明:
text
任务: <实现内容的单行描述>
文件: <要修改的完整文件列表>
范围: <本次变更明确不涉及的内容>
6.3 Implementation Rules
6.3 实现规则
- Follow existing project architecture, patterns, and naming conventions
- Do not introduce formatting changes in files unrelated to the task
- Do not refactor code outside the defined scope
- Do not modify test fixtures, mocks, or test utilities unless the task requires it
- Preserve existing error handling patterns
- Keep new public APIs consistent with existing ones
- Do not stage any changes yet — post-coding validation comes first
- 遵循现有项目架构、模式和命名规范
- 不要在与任务无关的文件中引入格式化变更
- 不要重构定义范围外的代码
- 除非任务要求,不要修改测试夹具、mock或测试工具
- 保留现有错误处理模式
- 新的公共API要与现有API保持一致
- 暂不要暂存任何变更 — 先执行编码后验证
Stage 7 — Post-coding Validation
阶段7 — 编码后验证
Run every applicable tool against only the files that were changed. Fix issues that are safe and mechanical (e.g., trailing whitespace, import ordering). For anything requiring judgment, stop and ask the user.
Context Guard: When running linters, tests, or builds, DO NOT output the full log if it exceeds 50 lines. Useor pipe to a temporary file and| tail -n 50for "Error" or "Fail" to avoid crashing the agent context window.grep
仅对变更过的文件运行所有适用的工具。修复安全且机械性的问题(比如末尾空格、导入排序)。任何需要判断的问题,停止并询问用户。
上下文防护: 运行linter、测试或构建时,如果完整日志超过50行,不要输出全部内容。使用或者输出到临时文件后| tail -n 50查找 "Error" 或 "Fail",避免撑爆Agent上下文窗口。grep
7.1 Formatter (Write Mode)
7.1 格式化工具(写入模式)
bash
undefinedbash
undefinedOnly on changed files
仅针对变更文件
git diff --name-only | xargs npx prettier --write
git diff --name-only | xargs black
undefinedgit diff --name-only | xargs npx prettier --write
git diff --name-only | xargs black
undefined7.2 Linter
7.2 Linter
bash
git diff --name-only | xargs npx eslint --fix
git diff --name-only | xargs ruff check --fix
If unfixable violations remain after auto-fix, stop and report each one with file, line, and rule name. Ask: fix manually, suppress with justification, or abort?
bash
git diff --name-only | xargs npx eslint --fix
git diff --name-only | xargs ruff check --fix
如果自动修复后仍有无法修复的违规,停止并逐个报告文件、行号和规则名,询问:手动修复、添加理由禁用规则还是终止操作?
7.3 Type Checker
7.3 类型检查器
bash
npx tsc --noEmit # TypeScript
mypy <changed_files> # Python
cargo check # Rust
go vet ./... # Go
Type errors are blocking — do not proceed past this step with type errors.
bash
npx tsc --noEmit # TypeScript
mypy <changed_files> # Python
cargo check # Rust
go vet ./... # Go
类型错误是阻塞性问题 — 存在类型错误时不能继续后续步骤。
7.4 Tests & Coverage
7.4 测试与覆盖率
Detect Testing Framework
识别测试框架
bash
undefinedbash
undefinedNode
Node
ls jest.config.* vitest.config.* .mocharc.*
grep -E '"test":|"jest":|"vitest"' package.json
ls jest.config.* vitest.config.* .mocharc.*
grep -E '"test":|"jest":|"vitest"' package.json
Python
Python
ls pytest.ini setup.cfg pyproject.toml | xargs grep -l '[tool.pytest'
ls tests/ test_*.py *_test.py
ls pytest.ini setup.cfg pyproject.toml | xargs grep -l '[tool.pytest'
ls tests/ test_*.py *_test.py
Rust
Rust
grep '[dev-dependencies]' Cargo.toml
grep '[dev-dependencies]' Cargo.toml
Go — built-in
Go — 内置
ls *_test.go
ls *_test.go
Ruby
Ruby
ls spec/ test/
undefinedls spec/ test/
undefinedRun Tests
运行测试
bash
undefinedbash
undefinedRun full suite first (with context guard)
先运行完整测试套件(带上下文防护)
npm test 2>&1 | tail -n 50
pytest | tail -n 50
cargo test
go test ./...
bundle exec rspec
npm test 2>&1 | tail -n 50
pytest | tail -n 50
cargo test
go test ./...
bundle exec rspec
If full suite passes, run coverage for changed files
如果完整套件通过,运行变更文件的覆盖率
npx jest --coverage --collectCoverageFrom='<changed_files>'
pytest --cov=<module> --cov-report=term-missing <changed_files>
undefinednpx jest --coverage --collectCoverageFrom='<变更文件>'
pytest --cov=<模块> --cov-report=term-missing <变更文件>
undefinedCoverage Rules
覆盖率规则
| Scenario | Requirement |
|---|---|
| Project has established test suite (>0 tests exist) | Achieve complete coverage of changed files. If files are small (<200 LOC), target 100%. |
| Project has no tests | Write basic tests for every public function/method changed. Cover happy path + at least one error case per function. |
| Changed files are small (<100 LOC) | Target 100% coverage of those specific files. |
If coverage drops below the project's configured threshold (e.g., in jest.config), stop and ask whether to write additional tests or document the coverage gap.
coverageThreshold| 场景 | 要求 |
|---|---|
| 项目已有成熟测试套件(存在>0条测试) | 实现变更文件的全量覆盖。如果文件很小(<200行),目标100%覆盖率。 |
| 项目没有测试 | 为每个修改的公共函数/方法编写基础测试,覆盖正常路径+每个函数至少一个错误场景。 |
| 变更文件很小(<100行) | 目标是这些文件100%覆盖率。 |
如果覆盖率低于项目配置的阈值(比如jest.config中的),停止并询问是否补充测试或者记录覆盖率缺口。
coverageThresholdTest Failure Protocol
测试失败处理规则
- First failure: Attempt to fix
- Second consecutive failure on same test: Stop, show full output, ask user how to proceed
- 第一次失败:尝试修复
- 同一个测试连续第二次失败:停止,展示完整输出,询问用户如何处理
7.5 Build
7.5 构建
bash
npm run build
cargo build --release
go build ./...
python -m build
mvn package -q
Build failures are blocking.
bash
npm run build
cargo build --release
go build ./...
python -m build
mvn package -q
构建失败是阻塞性问题。
7.6 Pre-commit and Pre-push Hooks (Final Run)
7.6 预提交和预推送钩子(最终运行)
Run all detected hooks one final time against the actual changed files:
bash
pre-commit run --files $(git diff --name-only)
bash .git/hooks/pre-commit
If hooks fail here, the commit will fail anyway — fix issues before staging.
针对实际变更的文件最终运行所有识别到的钩子:
bash
pre-commit run --files $(git diff --name-only)
bash .git/hooks/pre-commit
如果此处钩子运行失败,提交也会失败 — 暂存前先修复问题。
Stage 8 — Secret Detection
阶段8 — 密钥检测
Always run before staging. Never skip.
bash
undefined暂存前必须运行,绝对不能跳过。
bash
undefinedgitleaks (recommended — install: brew install gitleaks / apt install gitleaks)
gitleaks(推荐 — 安装:brew install gitleaks / apt install gitleaks)
gitleaks detect --source . --no-git
gitleaks detect --source . --no-git
truffleHog
truffleHog
trufflehog filesystem .
trufflehog filesystem .
detect-secrets (Python)
detect-secrets (Python)
detect-secrets scan --baseline .secrets.baseline
detect-secrets scan --baseline .secrets.baseline
git-secrets (AWS focused)
git-secrets(聚焦AWS)
git secrets --scan
git secrets --scan
Fallback: manual pattern grep if no tool is available
降级方案:如果没有工具可用,手动正则匹配
grep -rE
'(AKIA[0-9A-Z]{16}|sk-[a-zA-Z0-9]{32,}|ghp_[a-zA-Z0-9]{36}|-----BEGIN (RSA|EC|OPENSSH) PRIVATE KEY|password\s*=\s*["\x27][^"\x27]{4,}["\x27])'
$(git diff --name-only)
'(AKIA[0-9A-Z]{16}|sk-[a-zA-Z0-9]{32,}|ghp_[a-zA-Z0-9]{36}|-----BEGIN (RSA|EC|OPENSSH) PRIVATE KEY|password\s*=\s*["\x27][^"\x27]{4,}["\x27])'
$(git diff --name-only)
undefinedgrep -rE
'(AKIA[0-9A-Z]{16}|sk-[a-zA-Z0-9]{32,}|ghp_[a-zA-Z0-9]{36}|-----BEGIN (RSA|EC|OPENSSH) PRIVATE KEY|password\s*=\s*["\x27][^"\x27]{4,}["\x27])'
$(git diff --name-only)
'(AKIA[0-9A-Z]{16}|sk-[a-zA-Z0-9]{32,}|ghp_[a-zA-Z0-9]{36}|-----BEGIN (RSA|EC|OPENSSH) PRIVATE KEY|password\s*=\s*["\x27][^"\x27]{4,}["\x27])'
$(git diff --name-only)
undefinedSecret Found Protocol
发现密钥处理规则
🚨 **Potential secret detected inat line<filename>Pattern matched:<N>**DO NOT COMMIT. Options:<redacted — show only type, not value>
Replace with environment variable reference and add to.env.example Move to a secrets manager (Vault, AWS Secrets Manager, etc.) Mark as false positive and add to.secrets.baseline
Do not proceed to staging until all findings are resolved.
🚨 在第<文件名>行检测到潜在密钥 匹配模式:<N>绝对不要提交。 可选方案:<脱敏处理 — 仅展示类型,不展示值>
替换为环境变量引用并加入.env.example 移动到密钥管理服务(Vault、AWS Secrets Manager等) 标记为误报并加入.secrets.baseline
所有问题解决前不要进入暂存阶段。
Stage 9 — CHANGELOG Check
阶段9 — CHANGELOG 检查
9.1 Detect CHANGELOG
9.1 识别CHANGELOG
bash
ls CHANGELOG.md CHANGELOG.rst CHANGELOG.txt CHANGES.md HISTORY.md RELEASES.md 2>/dev/null
bash
ls CHANGELOG.md CHANGELOG.rst CHANGELOG.txt CHANGES.md HISTORY.md RELEASES.md 2>/dev/null
9.2 Evaluation Rules
9.2 评估规则
| Condition | Action |
|---|---|
| CHANGELOG not found | Skip (note absence) |
| CHANGELOG found + task is a new feature | Stop, ask user to confirm CHANGELOG entry |
| CHANGELOG found + task is a bug fix | Stop, ask user to confirm CHANGELOG entry |
| CHANGELOG found + task is chore/refactor only | Ask but default to "skip" |
| 条件 | 操作 |
|---|---|
| 未找到CHANGELOG | 跳过(备注缺失) |
| 存在CHANGELOG + 任务是新功能 | 停止,询问用户确认是否添加CHANGELOG条目 |
| 存在CHANGELOG + 任务是bug修复 | 停止,询问用户确认是否添加CHANGELOG条目 |
| 存在CHANGELOG + 任务仅为chore/重构 | 询问但默认选择"跳过" |
9.3 CHANGELOG Entry Format
9.3 CHANGELOG 条目格式
Use the project's existing format. If none exists, default to Keep a Changelog:
markdown
undefined使用项目现有格式,如果没有默认使用 Keep a Changelog 规范:
markdown
undefined[Unreleased]
[Unreleased]
Added
Added
- <feature description> — <brief rationale>
- <功能描述> — <简要 rationale>
Fixed
Fixed
- <bug description> — fixes #<issue> if applicable
- <bug描述> — 修复 #<issue号>(如果适用)
Changed
Changed
- <what changed and why>
If user confirms an entry is needed, add it and stage `CHANGELOG.md` alongside the feature files in the same commit (not a separate commit — changelog belongs with the change).
---- <变更内容和原因>
如果用户确认需要添加条目,添加后将`CHANGELOG.md`和功能文件在同一个提交中暂存(不要单独提交 — CHANGELOG属于变更的一部分)。
---Stage 10 — Version Control & Commit
阶段10 — 版本控制与提交
10.1 Inspect Final Diff
10.1 检查最终差异
bash
git status
git diff --stat
Classify every modified file:
| Category | Disposition |
|---|---|
| Intentional (task-related) | Stage |
| Tool-generated (formatter/linter on task files) | Stage |
| CHANGELOG.md (if updated) | Stage |
| Tool-generated on unrelated files | Do NOT stage — ask user |
| Accidentally modified | Do NOT stage — restore with |
| New files not related to task | Do NOT stage — ask user |
bash
git status
git diff --stat
对每个修改文件分类:
| 分类 | 处理方式 |
|---|---|
| 有意修改(和任务相关) | 暂存 |
| 工具生成(任务相关文件的格式化/lint变更) | 暂存 |
| CHANGELOG.md(如果更新) | 暂存 |
| 无关文件的工具生成变更 | 不要暂存 — 询问用户 |
| 意外修改 | 不要暂存 — 用 |
| 和任务无关的新文件 | 不要暂存 — 询问用户 |
10.2 Final Secret Scan on Staged Files Only
10.2 仅对暂存文件做最终密钥扫描
bash
git stash # stash unstaged
git diff --cached | gitleaks detect --no-git --pipe
git stash pop # restore unstaged
bash
git stash # 暂存未暂存内容
git diff --cached | gitleaks detect --no-git --pipe
git stash pop # 恢复未暂存内容
10.3 Stage Files
10.3 暂存文件
bash
git add <file1> <file2> ... # Always stage explicitly, never `git add .`
git diff --cached --stat # Confirm staged set looks correct
bash
git add <文件1> <文件2> ... # 始终显式暂存,绝对不要用 `git add .`
git diff --cached --stat # 确认暂存集合正确
10.4 Commit Message
10.4 提交信息
Follow Conventional Commits format. Craft a commit that answers:
- What changed (summary line, imperative mood, ≤72 chars)
- Why it was changed (body)
- What problem it solves (body)
- Architectural/behavioral impact if any (body or footer)
- References — issue/PR numbers, related commits
text
<type>(<scope>): <short imperative summary>
<Paragraph explaining WHY the change was made and WHAT problem it solves.
Wrap at 72 characters. Use present tense. Be specific — avoid "fix bug".>
<Optional paragraph for architectural impact, migration steps, or
behavioral changes users/consumers should be aware of.>
Refs: #<issue>, #<pr>
Breaking-Change: <description if applicable>
Type vocabulary:
| Type | Use for |
|---|---|
| New feature |
| Bug fix |
| Code restructuring without behavior change |
| Adding or fixing tests |
| Build, deps, tooling, CI |
| Documentation only |
| Performance improvement |
| Formatting only (no logic change) |
| Reverting a prior commit |
遵循 Conventional Commits 格式。编写的提交信息要回答:
- 什么变更(摘要行,祈使语气,≤72字符)
- 为什么要变更(正文)
- 解决了什么问题(正文)
- 有没有架构/行为影响(正文或页脚)
- 参考信息 — issue/PR编号、相关提交
text
<type>(<scope>): <简短祈使式摘要>
<段落说明变更的原因和解决的问题,每行72字符换行,使用现在时,表述具体,不要写"fix bug"这类模糊内容。>
<可选段落说明架构影响、迁移步骤、用户/消费者需要注意的行为变更。>
Refs: #<issue号>, #<pr号>
Breaking-Change: <描述破坏性变更(如果有)>
类型词汇表:
| 类型 | 使用场景 |
|---|---|
| 新功能 |
| Bug修复 |
| 不改变行为的代码重构 |
| 添加或修复测试 |
| 构建、依赖、工具、CI相关变更 |
| 仅文档变更 |
| 性能优化 |
| 仅格式化变更(无逻辑变更) |
| 回滚之前的提交 |
10.5 Push
10.5 推送
bash
git push origin <branch>
If the push is rejected (non-fast-forward), stop and ask the user before force-pushing. Never force-push to , , or branches.
mainmasterproductionbash
git push origin <分支名>
如果推送被拒绝(非快进),强制推送前先停止并询问用户,绝对不要强制推送到、或分支。
mainmasterproductionStage 11 — Pull Request (Optional)
阶段11 — 拉取请求(可选)
If (GitHub) or (GitLab) CLI tools are installed and authenticated:
ghglab如果安装并认证了(GitHub)或(GitLab)CLI工具:
ghglabGitHub
GitHub
bash
gh pr create \
--title "<commit summary>" \
--body "<commit body>" \
--base main \
--head <current-branch> \
--draft # Ask user: Draft or Ready?
bash
gh pr create \
--title "<提交摘要>" \
--body "<提交正文>" \
--base main \
--head <当前分支> \
--draft # 询问用户:草稿还是就绪?
GitLab
GitLab
bash
glab mr create \
--title "<commit summary>" \
--description "<commit body>" \
--source-branch <current-branch>
If no CLI tool is found, generate the HTTPS link for the user to click to create the PR manually (e.g., ).
https://github.com/org/repo/compare/main...feature-branchbash
glab mr create \
--title "<提交摘要>" \
--description "<提交正文>" \
--source-branch <当前分支>
如果没有找到CLI工具,生成HTTPS链接供用户手动点击创建PR(例如 )。
https://github.com/org/repo/compare/main...feature-branchError Recovery Playbook
错误恢复手册
| Symptom | Recovery |
|---|---|
| |
| Formatter changes too many files | Create dedicated format commit first |
| Lint violations > 20 | Create dedicated lint commit first |
| Audit finds critical CVE | Patch deps, re-audit, commit before feature work |
| CI step fails locally | Fix before implementation or document as known issue |
| Test fails after repeated fix attempts | Stop, show full trace, ask user |
| Secret detected in staged files | Unstage, rotate credential, fix, re-scan |
| Build fails | Stop — do not push broken builds |
| Hook fails | Fix — hooks represent the project's own enforcement |
| Push rejected | Fetch, rebase, resolve conflicts — never force-push protected branches |
| 现象 | 恢复方案 |
|---|---|
| |
| 格式化工具修改了太多文件 | 先创建独立的格式化提交 |
| Lint违规>20条 | 先创建独立的lint修复提交 |
| 审计发现严重CVE | 修复依赖、重新审计、提交后再进行功能开发 |
| CI步骤本地运行失败 | 实现前修复或者记录为已知问题 |
| 多次尝试修复后测试仍失败 | 停止,展示完整 trace,询问用户 |
| 暂存文件中检测到密钥 | 取消暂存、轮换凭证、修复、重新扫描 |
| 构建失败 | 停止 — 不要推送破坏的构建 |
| 钩子运行失败 | 修复 — 钩子是项目自身的强制规则 |
| 推送被拒绝 | 拉取、变基、解决冲突 — 绝对不要强制推送受保护分支 |
Commit Sequence Summary
提交顺序汇总
A full workflow may produce multiple commits in this order:
text
1. chore: update .gitignore (if needed)
2. chore(deps): fix security vulnerabilities (if audit findings patched)
3. style: apply formatter to codebase (if user approved pre-coding format)
4. chore(lint): resolve linting violations (if user approved pre-coding lint)
5. feat/fix/refactor(<scope>): <main task> (the actual work + changelog + tests)
完整工作流可能按以下顺序生成多个提交:
text
1. chore: update .gitignore (如果需要)
2. chore(deps): fix security vulnerabilities (如果修复了审计发现的漏洞)
3. style: apply formatter to codebase (如果用户同意编码前格式化)
4. chore(lint): resolve linting violations (如果用户同意编码前修复lint)
5. feat/fix/refactor(<scope>): <主任务> (实际功能变更 + CHANGELOG + 测试)