前往 WaytoAGI 飞书知识库 · 1 亿+ 次访问的开源 AI 知识库 →
通往 AGI 之路 WaytoAGI

知识库 · AI 编程

像 Boris Cherny 那样使用 Claude Code 的 10 个 Slash Commands

Claude Code 的 custom commands 可将重复的 10-15 行 prompt 固化为 Git 版本控制的 slash command,避免 prompt drift。Boris Cherny 风格的 10 个实用命令(含完整模板),在 ML 服务项目中演示 env-check、代码审查、测试生成等,提升团队一致性。

ClaudeAI工具Prompt工程开发效率Git

像 Boris Cherny 那样使用 Claude Code 的 10 个 Slash Commands

4月12日修改
原帖链接:https://x.com/_avichawla/status/2042929462908719352
文档图片

在终端里设置 shell aliases 已经自然到几乎成了每个开发者的肌肉记忆。某个命令只要你用得足够频繁,你就会给它起个 alias。
但在 Claude Code prompts 这件事上,开发者通常会完全跳过这一步,然后一遍又一遍地凭记忆重打同样的 10-15 行指令,比如他们的代码审查清单、测试生成约束、pre-commit 扫描……而且一个 session 接一个 session 地重复。
文档图片

真正的成本不只是你作为开发者不断重复输入,更在于 prompt drift。
每次你凭记忆重打一段 prompt,措辞都会轻微变化。比如你可能漏掉某个约束,或者用不同方式描述预期输出格式。
对于 shell commands 来说这无所谓,因为它们是确定性的;但对于 LLM 来说,措辞稍有不同,就可能产出明显不同的结果。
文档图片

Claude Code 的 custom commands 同时解决了这两个问题。
你只需要把一个 markdown 文件保存在 .claude/commands/ 里,它就会变成一个 slash command。之后每次调用,Claude 都会收到完全一致的指令。
这些 prompts 通过 Git 做版本控制,所以整个团队跑的是同样的 commands;一旦有人优化了 prompt,其他人下次 pull 后就都能获得更新。
这正是 Boris Cherny 在他关于 Claude Code workflows 的线程里描述的模式:凡是会重复发生的 workflow,他都会把它变成一个 command,检入 Git,并与团队共享:
文档图片

我们先走一遍它们的配置方式,然后再看这 10 个在我工作流里最有用的 commands。我会在一个真实的 ML inference service(FastAPI、scikit-learn、Alembic)上演示每一个命令,这样你能看到实际输出,而且我会把完整 prompt templates 一并给你,你可以直接放进自己的项目里。

自定义命令是什么

一个 custom command,本质上就是 .claude/commands/ 目录里的一个 markdown 文件。文件名就是命令名。
代码块
# Project-scoped(通过 Git 共享,在自动补全里显示为 "(project)"):
your-repo/.claude/commands/preflight.md  ->  /preflight

# User-scoped(个人级,对所有项目生效):
~/.claude/commands/orient.md  ->  /orient

# Subdirectories 会生成带前缀的命令:
.claude/commands/db/migrate.md  ->  /db:migrate
文件内容就是当你运行这个 command 时发给 Claude 的 prompt。你可以使用 $ARGUMENTS 作为占位符,承接命令名后面输入的任何内容。
例如,运行 "/dissect src/auth/session.ts" 时,$ARGUMENTS 会被替换成 "src/auth/session.ts"。
你还可以用 shell commands 动态注入上下文,方法是使用 !\command\`` 语法:
代码块
## Current state
- Branch: !`git branch --show-current`

- Staged changes: !`git diff --cached --stat`

- Last 3 commits: !`git log --oneline -3`
Claude 会在处理 prompt 之前先执行这些 shell commands,因此上下文始终是最新的。
最后,你还可以在文件顶部加一个可选的 YAML frontmatter,用来预先批准工具权限(这样 Claude 就不会每次调用 git 都重新问你)、设置模型覆盖项,或者添加说明:
代码块
---
description: Pre-commit check for debug artifacts and code smells
allowed-tools: Bash(git *), Bash(grep *), Read, Glob
---
整个系统就这些:一个 markdown 文件、一个可选 YAML 头部,以及 $ARGUMENTS 用来接收动态输入。
下面我会分享 10 个我在实际工作中最有用的命令。
文档图片

Command 1:/env-check

当你 clone 一个项目,或者隔了几周重新回到一个项目,第一件事就是确认你的本地环境到底能不能跑起来。可能 runtime 版本不对、环境变量缺失、migrations 没有应用。
这个命令会一次性校验整个本地开发环境。
代码块
---
description: Validate local development environment setup
allowed-tools: Bash(node *), Bash(npm *), Bash(python *), Bash(which *), Bash(cat *), Bash(docker *), Read, Glob
---

Check that this project's development environment is properly configured.

## Step 1: Read project requirements
Look for configuration files that specify requirements:
!`cat .node-version .nvmrc .python-version .tool-versions .env.example 2>/dev/null`
!`cat package.json | head -30 2>/dev/null`
!`cat docker-compose.yml 2>/dev/null | head -10`

## Step 2: Validate each requirement

**Runtime versions:**
- Check installed Node/Python/Ruby version against the project's required version
- Check package manager version (npm/yarn/pnpm/pip/poetry)

**Dependencies:**
- Are node_modules/venv/.venv installed and up to date?
- Are there any peer dependency warnings?

**Environment variables:**
- Compare .env.example (or .env.sample) against the actual .env file
- List any variables present in .example but missing from .env
- Do NOT print actual values of any env vars (security)

**Services:**
- If docker-compose.yml exists, are the required containers running?
- Check if common services (PostgreSQL, Redis, etc.) are accessible on expected ports

**Git hooks:**
- Are git hooks installed (husky, lefthook, pre-commit)?

## Output format
Print a checklist:
✅ Node v20.11.0 (matches .nvmrc)
❌ Missing env var: DATABASE_URL (required by .env.example)
⚠️ node_modules out of date (run npm install)

End with the exact commands needed to fix any ❌ items.
下面是 /env-check 在这个 ML inference service 上运行出来的效果:
00:00/00:21
1x
  • 2x
  • 1.5x
  • 1x
  • 0.75x
  • 0.5x
请试试刷新
00:21
OiVyoBEl52aFhk_2.mp4
OiVyoBEl52aFhk_2
这个命令一次就抓出了五类问题,包括 Python 3.12 与 3.11 的版本不匹配、没有 virtual environment(当前在用系统级 Anaconda)、缺少三个包(ruff、structlog、pytest-cov)、.env.example 里定义但 .env 里缺失的六个环境变量,以及一条未应用的 Alembic migration。
每个发现后面都附了精确的修复命令,所以开发者可以按顺序执行这些命令,从一个坏掉的本地环境直接走到可运行状态。

Command 2:/orient

环境跑起来之后,你接下来需要的是上下文,比如你当前在哪个分支、离开前在做什么等等。
这件事在执行过 /clear 之后尤其重要。你确实应该定期执行 /clear,避免上下文窗口退化。这个命令会读取未提交的改动、最近的提交,以及任何未完成的 TODO,一次性帮你重建工作状态。
代码块
---
description: Rebuild working context after /clear
allowed-tools: Bash(git *), Read, Glob
---

Load my current working state into this conversation. Read the following:

1. All uncommitted changes (staged and unstaged):
!`git diff HEAD`

2. The 5 most recent commits with full diffs:
!`git log --oneline -5`

3. Any TODO/FIXME markers in modified files:
!`git diff --name-only HEAD | head -20`

Read each modified file listed above. Identify any TODO, FIXME, or HACK comments in those files.

4. Current branch and its relationship to main:
!`git branch --show-current`
!`git log main..HEAD --oneline 2>/dev/null || echo "No commits ahead of main"`

After loading all of this, give me a brief summary:
- What I appear to be working on (inferred from changes)
- Key files modified
- Any TODOs or incomplete work flagged in the code
- How far ahead of main this branch is
最后这个 summary 很重要,因为它会强迫 Claude 真正去解析自己读进来的东西,而不是只是把它们被动塞进上下文窗口。
下面是 /orient 在 ML inference service 上、且发生在一次 /clear 之后的运行效果:
00:00/00:10
1x
  • 2x
  • 1.5x
  • 1x
  • 0.75x
  • 0.5x
请试试刷新
00:10
GEcMg_pSnxXf6PTs.mp4
GEcMg_pSnxXf6PTs
在完全没有上下文的冷启动状态下,这个命令识别出了项目类型(FastAPI ML inference service)、当前分支目的(为模型变体做 A/B test routing)、staged work 的精确状态(ab_router.py 中 87 行改动,核心逻辑已经完成),以及提交前必须解决的三个具体问题:debug artifacts(pdb.set_trace()、breakpoint())、一处日志规范违规(print 而不是 structlog),以及缺失的测试。
最后给出的 “most important next step” 非常关键,因为它让你不需要自己重新读完整个 diff,直接就能开始做下一步动作。

Command 3: /preflight

有了上下文、也做完了一些更新后,下一步自然就是检查你即将提交的代码到底干不干净。
这个命令就是给每一次 commit 前跑的。它会扫描 staged changes 中那些不该被提交出去的东西,比如残留的 debug statements、TODO 标记、被注释掉的代码块、硬编码 secrets、被跳过的测试和 debug flags。
这里有一个关键设计决策:如果它发现问题,它只会列出来然后停止。不会自动修。
我们现在不需要一个会偷偷改代码的 auto-fixer。
代码块
---
description: Pre-commit scan for debug artifacts and code smells
allowed-tools: Bash(git *), Bash(grep *), Read, Glob
---

Scan all staged changes for the following issues:

## What to scan
!`git diff --cached`

## Rules
Check for ALL of the following in the staged diff:
1. console.log, console.debug, console.warn statements (unless in a logger utility)
2. TODO, FIXME, HACK, XXX comments
3. Commented-out code blocks (3+ consecutive commented lines)
4. Hardcoded secrets: API keys, tokens, passwords, connection strings
5. .only or .skip in test files (jest, mocha, vitest)
6. Debug flags: debugger statements, #debug, verbose: true in config
7. Large binary files or data dumps added to the commit
8. Import statements for dev-only packages in production code paths

## Output format
If ALL checks pass: respond with "✅ Preflight clear. Staged changes look clean."

If ANY issues found: list every issue with its file path and line context.
Do NOT fix anything. Do NOT unstage anything. Report only.
下面是 /preflight 在 staged 的 A/B router 上抓到 debug artifacts 的例子:
00:00/00:17
1x
  • 2x
  • 1.5x
  • 1x
  • 0.75x
  • 0.5x
请试试刷新
00:17
KC3VUCOeL2RIzKJk.mp4
KC3VUCOeL2RIzKJk
它在 staged file 中抓到了四个 blockers:
一个被 # noqa 压着不报错、但其实已经是死代码的 pdb import
一个会让生产请求直接卡死的 breakpoint()
一个作用完全相同的 pdb.set_trace()
一个把用户 ID 打到 stdout 的 print 语句,违反了项目的 structlog 规范
它还顺手指出了两个它在扫描过程中发现的 unstaged issues:predict.py 里的一个 debug print,以及一个把 flaky test 藏起来的 pytest.mark.skip。
最后 summary table 里 “blocker (staged)” 和 “should-fix (unstaged)” 的区分非常有用,因为它明确告诉你哪些问题会直接污染这次提交,哪些问题则是应该另外处理的。

Command 4: /dissect

/preflight 抓的是明显问题。
而如果你想对某个特定文件做更深层的 review,/dissect 提供的是一种结构化分析方式,聚焦那些真正会引发线上事故的东西:错误处理缺口、竞态条件、遗漏的边界情况,以及静默失败。
它接收一个文件路径作为参数,所以你可以把它直接指向你最担心的那个模块。
代码块
---
description: Deep structural review of a file or module
allowed-tools: Read, Glob, Grep
argument-hint: <file-path-or-directory>
---

Perform a deep structural review of: $ARGUMENTS

## Review dimensions (check all of these)

**Error handling:**
- Are all error paths handled explicitly (no empty catch blocks)?
- Do async operations have proper error propagation?
- Are there any swallowed errors that would fail silently?

**Edge cases:**
- What happens with null/undefined/empty inputs?
- What happens at boundary values (0, -1, MAX_INT, empty arrays)?
- Are there implicit type coercions that could cause subtle bugs?

**Concurrency:**
- Could any state mutation cause race conditions if called concurrently?
- Are shared resources properly synchronized?
- What happens if this function is called twice before the first call completes?

**Dependencies:**
- Are imports used? Flag any unused imports.
- Are there circular dependency risks?
- Is the module tightly coupled to implementation details it shouldn't know about?

**Naming and structure:**
- Do function names accurately describe what they do (including side effects)?
- Are there functions doing more than one thing that should be split?

## Output format
For each finding, give:
- Severity: 🔴 Critical (will cause bugs) / 🟡 Warning (could cause issues) / 🔵 Note (improvement)
- The specific code location
- What could go wrong
- A suggested fix (code, not just description)
下面是 /dissect src/routes/predict.py 审查 prediction endpoint 的效果:
00:00/00:18
1x
  • 2x
  • 1.5x
  • 1x
  • 0.75x
  • 0.5x
请试试刷新
00:18
1oPBcAo2A6Kuc06z.mp4
1oPBcAo2A6Kuc06z
这次 review 把问题组织到了六个维度里,但最亮眼的是它抓到了一些普通 linter 根本抓不到的东西,比如:
一个损坏的 API contract:model_version 虽然出现在 request schema 中,但在两个 handlers 里都被悄悄忽略了
当模型没有加载时,接口返回的是 200 OK 加空数据;它本该返回 503
单条延迟被错误地记录成“总耗时的平均值”,而不是真正的单条测量值
它还交叉读了测试文件,并指出一个很关键的问题:现有测试居然把 “model-not-loaded 时返回 200” 这个错误行为本身写进了断言里。
最后的 “Top 3” 优先级列表也非常有价值,因为它直接给你一个适合单次 commit 的行动清单。

Command 5:/testmatch

上面的 review 已经指出了若干未覆盖的代码路径,这时候就轮到 /testmatch 了。
AI 生成测试的一大问题在于:它们几乎从来不会匹配你项目现有的测试风格。
断言库、命名风格、setup 模式,全都可能不一样。
这个命令会先读取你已有的测试,再生成“看起来像是你团队里某个人写出来”的新测试。
代码块
---
description: Generate tests that match existing project test patterns
allowed-tools: Read, Glob, Grep, Bash(npx *), Bash(npm test *)
argument-hint: <file-to-test>
---

Generate tests for: $ARGUMENTS

## Step 1: Learn the existing test patterns
Before writing anything, find and read 2-3 existing test files in this project:
!`find . -name "*.test.*" -o -name "*.spec.*" | head -5`

From those files, identify:
- Test framework (jest, vitest, mocha, pytest, etc.)
- Assertion style (expect/assert/should/chai)
- Naming convention for describe/it blocks
- Setup and teardown patterns (beforeEach, fixtures, factories)
- Mocking approach (jest.mock, sinon, manual mocks, dependency injection)
- File naming convention (*.test.ts, *.spec.ts, __tests__/*)

## Step 2: Read the target file
Read $ARGUMENTS completely. Understand every function, every branch, every error path.

## Step 3: Generate tests
Write tests that:
- Follow EXACTLY the patterns found in Step 1
- Cover every exported function/method
- Include happy path, error cases, and edge cases
- Test boundary values and null/undefined inputs
- Use the same mocking approach as existing tests
- Use the same file naming convention

Place the test file adjacent to the source file following the project's convention.

Do NOT use any test patterns, assertion libraries, or conventions that don't already exist in this project.
下面是 /testmatch src/services/prediction_logger.py 为 logging service 生成测试的结果:
00:00/00:15
1x
  • 2x
  • 1.5x
  • 1x
  • 0.75x
  • 0.5x
请试试刷新
00:15
7cbPLWRnLTJf75xp.mp4
7cbPLWRnLTJf75xp
它一共生成了 19 个测试,分布在三个 classes 中,每个公共函数一组,而且第一次运行就全部通过。
这些测试和现有项目约定完全一致:同样的 conftest.py fixtures、同样的 db_session 依赖注入、同样按 Test* class 分组、内部用扁平 methods 的结构。
最有意思的是它还主动解决了一个隐蔽问题。service functions 会调用 db.commit(),因此 conftest.py 里正常的 session.rollback() teardown 根本无法回滚已经提交的行。
它因此加了一个 clean_predictions 的 autouse fixture,在每个测试前删除所有 rows,强制保证隔离。
这种测试基础设施和应用代码之间的微妙耦合,通常需要开发者在 CI 里失败几轮后才会意识到。

Command 6: /explain-func

在 review 和 testing 的过程中,你迟早会碰到那些逻辑很密、但实现原因完全没写下来的函数。
这个命令会生成 inline documentation,而且有一条很重要的规则:它解释的是 “why”,不是 “what”。
因为代码自己已经说明了它在做什么;评论应该负责解释它为什么要这样做。
这些注释应该把那些非显而易见的决策和未来维护者必须守住的 invariants 记录下来。
代码块
---
description: Generate why-focused documentation for complex functions
allowed-tools: Read, Grep
argument-hint: <function-name-or-file:line>
---

Document the function or code block at: $ARGUMENTS

## Rules for documentation style
- Explain WHY, not WHAT. The code shows what it does. Comments explain why it does it that way.
- Document non-obvious decisions: "We use a Map instead of an object here because keys can be symbols"
- Document invariants: "This must be called after auth middleware has run"
- Document constraints: "Rate limited to 100 calls/min by the upstream API"
- Document gotchas: "Returns stale data if cache TTL hasn't expired, even after a write"
- DO NOT add comments that restate the code: "// increment counter" above counter++

## Output format
- Add a JSDoc/docstring header with: purpose (one line), parameters with types, return value, throws/errors, and a brief example if the usage isn't obvious
- Add inline comments only where the code makes non-obvious decisions
- Keep every comment under 100 characters per line

Output the function with documentation added. Do not modify the logic.
下面是 /explain-func src/preprocessing/pipeline.py 为 feature engineering functions 生成文档的效果:
00:00/00:23
1x
  • 2x
  • 1.5x
  • 1x
  • 0.75x
  • 0.5x
请试试刷新
00:23
v5vNrwgJp0JYJDzC.mp4
v5vNrwgJp0JYJDzC
这个命令为两个函数补上了文档。
对每个函数,它都解释了若干具体实现选择背后的原因:为什么要先去掉 URL 再处理标点(顺序反了会制造垃圾 token)、为什么 IDF 公式要在 log 外面再加一个 +1(避免把在所有文档中都出现的特征压成零)、为什么最后要做 L2 normalization(与训练好的模型保持 cosine-distance 兼容)。
它还指出了这个文件里最大的正确性风险:TF-IDF vocabulary 是根据当前 batch 建的,而不是根据训练语料建的,所以单文档推理得到的 IDF 值其实没有意义。
这种上下文对一个新加入团队的人来说,往往需要几周才能自己摸清。

Command 7: /refactor-safe

到这一步,你已经 review 了代码、补了测试、也加了文档。
如果 /dissect 报出了结构性问题,比如一个 45 行的 handler 同时做 validation、inference、logging 和 response formatting,这时候就该用这个命令修它了。
用 AI 做重构的风险在于 Claude 很容易“顺手优化”掉你根本没让它碰的东西。
这个命令最重要的约束就是:public API 绝不能变。
它只允许你改内部结构。
代码块
---
description: Refactor internals without changing public API
allowed-tools: Read, Grep, Glob
argument-hint: <file-or-function>
---

Refactor the internals of: $ARGUMENTS

## Hard constraints
- DO NOT change any exported function signatures
- DO NOT change any return types or shapes
- DO NOT rename any exported symbols
- DO NOT change the module's public interface in any way
- DO NOT add new dependencies
- Preserve all existing behavior, including edge cases and error messages

## What to improve (internal only)
- Extract repeated logic into private helper functions
- Simplify nested conditionals (early returns, guard clauses)
- Remove dead code paths that can never execute
- Replace magic numbers/strings with named constants
- Improve variable names within function bodies
- Reduce function length by extracting logical steps

## Verification
After refactoring, confirm:
1. Every exported function/type/constant still has the same name and signature
2. All existing tests would still pass without modification (don't run them, just verify compatibility)
3. No new imports were added

Present the refactored code with a brief summary of what changed and why.
下面是 /refactor-safe src/routes/predict.py 对 batch handler 做拆分的效果:
00:00/00:19
1x
  • 2x
  • 1.5x
  • 1x
  • 0.75x
  • 0.5x
请试试刷新
00:19
7ilYG7GvYHNgnfK7.mp4
7ilYG7GvYHNgnfK7
它从两个 route handlers 中提取出了 7 个私有 helpers:validation、inference、result building、DB logging,都各自拆成了独立函数。
batch handler 于是从一个 45 行 monolith,变成了只有五行的 helper 调用序列。它还把 print(f"DEBUG: ...") 替换成了 logger.debug(...),以符合项目的 structlog 规范。
还有一个关键点是,它在重构完成后运行了项目现有的 32 个测试,而且全部通过。
public API 完全没变:同样的 endpoints、同样的 request/response schemas、同样的 router export。这正是 prompt 里那些 hard constraints 的意义。

Command 8:/ship

代码已经 review、测试、文档化、也重构完了。
接下来就是开 PR,而写一份好的 PR description 是那种每次都要花 10 分钟、但结构其实永远差不多的工作:改了什么、为什么改、怎么验证、可能出什么风险。
这个命令会先跑测试套件,再根据真实 commits 和 diff 生成一份 PR description。整体思路和 /preflight 一样,先校验,再执行。
代码块
---
description: Validate and generate PR description from current branch
allowed-tools: Bash(git *), Bash(gh *), Bash(pytest *), Bash(npm test *), Read, Glob
---

Prepare a pull request for the current branch.

## Step 1: Pre-flight validation
Run the test suite before generating anything. If tests fail, stop and report the failures.
!`git diff --stat main..HEAD`

## Step 2: Assess the diff
!`git log main..HEAD --oneline`
!`git diff --stat main..HEAD`

Check:
- If the diff exceeds 500 lines changed, flag it as a large PR and suggest splitting
- If the branch has more than 15 commits, suggest squashing before opening

## Step 3: Generate PR description
Read the actual code changes (not just filenames) to understand what was built:
!`git diff main..HEAD`

Write a PR description with these sections:

**Summary** (2-3 sentences): What this PR does and why, written for someone who hasn't seen the code.

**Changes** (bullet list): Group related changes together. Reference specific files only when it adds clarity. Skip trivial changes like formatting and import reordering.

**How to test**: Step-by-step instructions a reviewer can follow to verify the changes work. Include specific commands to run, endpoints to hit, or behaviors to observe.

**Risk assessment**: What could go wrong with this change? Does it touch shared infrastructure, modify database schemas, change public APIs, or affect performance-sensitive paths? Be specific. "Low risk" is not useful. "Modifies the prediction endpoint response shape, which could break clients that destructure the old format" is useful.

**Related issues**: Scan commit messages for issue references (#123, JIRA-456) and list them.

## Step 4: Output
Print the PR description in markdown, ready to paste into GitHub.
Do NOT create the PR automatically. Output the description for review first.
下面是 /ship 为 A/B testing feature 生成 PR description 的效果:
00:00/00:23
1x
  • 2x
  • 1.5x
  • 1x
  • 0.75x
  • 0.5x
请试试刷新
00:23
doC3ISKbV1tF-jcM.mp4
doC3ISKbV1tF-jcM
它先跑了完整测试套件(50 passed,1 skipped),然后在真正生成 PR description 之前,先把 ab_router.py 里的四个 debug artifacts 标为 blockers。
PR description 本身则把 A/B router、migration、以及 predict route refactor 分成了几个清晰部分,并且附上了具体的 curl 命令作为验证方法。
risk assessment 里还有一个很不明显、但很重要的部署细节:router 虽然实现了,但还没有真正接进任何 route,因此在被接入 prediction flow 之前,A/B split 实际上并不会生效。
它最后还顺带提出可以当场修掉这些 debug artifacts,这和 /preflight 之前抓到的问题形成了一个闭环。

Command 9: /migrate-draft

代码功能做完之后,如果还需要 schema change,就该轮到数据库 migration 了。
而 migration 这件事必须格外谨慎,因为一旦上线,回滚成本通常非常高。
这个命令会生成一个包含 up 和 down 两部分 的 migration 文件,并附上安全检查清单。它还会像 /testmatch 学测试风格那样,先读取现有 migrations,推断项目正在使用的 ORM 和命名风格。
代码块
---
description: Draft a database migration with rollback plan
allowed-tools: Read, Glob, Grep
argument-hint: <description-of-schema-change>
---

Generate a database migration for: $ARGUMENTS

## Step 1: Identify the migration system
!`ls migrations/ db/migrate/ prisma/migrations/ drizzle/ alembic/versions/ 2>/dev/null | head -20`

Read 2-3 existing migration files to identify:
- ORM/tool (Prisma, Drizzle, Knex, TypeORM, Alembic, Rails, raw SQL)
- Naming convention (timestamp prefix, sequential numbering)
- Structure (up/down methods, SQL vs ORM DSL)

## Step 2: Generate the migration
Create the migration file following the exact conventions from Step 1.

Requirements:
- Include both UP and DOWN (rollback) logic
- The DOWN must perfectly reverse the UP
- For column additions: set a sensible DEFAULT if the column is NOT NULL
- For column removals in DOWN: document data loss warnings as comments
- For index changes: check that the index name follows the project's naming convention
- For table renames: handle foreign key references

## Step 3: Safety checklist
After the migration code, add a comment block with:
- [ ] Estimated row count for affected tables (check with: SELECT count(*) FROM table)
- [ ] Will this lock the table? (ALTER TABLE on large tables can lock for minutes)
- [ ] Is this backwards-compatible with the current application code?
- [ ] Can this be deployed independently of the application change?
- [ ] What happens if the migration fails halfway through?

Do NOT run the migration. Output the file content only.
下面是 /migrate-draft add-ab-test-assignments-table 为 A/B test tracking 生成 migration 的效果:
00:00/00:12
1x
  • 2x
  • 1.5x
  • 1x
  • 0.75x
  • 0.5x
请试试刷新
00:12
PXnbQBiNazt6qsQ1.mp4
PXnbQBiNazt6qsQ1
它先读取现有 migration 来匹配项目的 Alembic 约定,再读取 ab_router.py 来理解这张表到底需要哪些列。
最终生成的 migration 包含了若干直接从 router 逻辑里推导出的列,比如 user_id、variant、bucket(用于审计 assignment 公平性的确定性 hash 值)、指向 predictions 表的 prediction_id 外键,并设置为 ON DELETE SET NULL,以及一个带 server-side default 的 assigned_at。
它还为后续分析 variant performance 时最常过滤的三列加上了 indexes。也就是说,这份 migration 是被应用代码本身反向约束出来的。

Command 10: /debt-scan

最后一个“正式命令”是当你想退后一步,看整个项目健康状况时用的。
技术债往往是在不知不觉中积累起来的,直到哪天某个地方终于炸掉。
这个命令会在整个 codebase 里扫描常见的 debt patterns,并输出一个可以直接转成 tickets 的优先级列表:代码复杂度、依赖过期、测试覆盖缺口,以及架构异味。
代码块
---
description: Scan for technical debt patterns and prioritize remediation
allowed-tools: Bash(git *), Bash(npm *), Bash(npx *), Bash(wc *), Bash(find *), Read, Glob, Grep
---

Scan this project for technical debt and produce a prioritized remediation report.

## Scan dimensions

**Code complexity:**
- Find the 5 largest files by line count (often a sign of god objects/modules)
- Identify functions longer than 50 lines
- Flag files with more than 10 imports (high coupling)

**Dependency health:**
!`npm outdated 2>/dev/null || pip list --outdated 2>/dev/null | head -20`
- How many dependencies are more than 2 major versions behind?
- Are there any dependencies with known deprecation notices?

**Test coverage gaps:**
- Find source files that have no corresponding test file
- List them with file size (larger untested files = higher risk)

**Code smells:**
- grep for: any-type assertions (as any, type: any), eslint-disable without explanation, @ts-ignore without comment
- Find duplicated code blocks (same 10+ lines appearing in multiple files)
- Check for TODO/FIXME/HACK comments older than 30 days:
  use `git log` to find when each TODO was introduced

**Architectural smells:**
- Circular dependencies (if a tool like madge is available)
- Business logic in API route handlers (should be in service layer)
- Direct database queries outside of a repository/data-access layer

## Output format
Group findings by priority:
🔴 High: Likely to cause incidents or block feature work
🟡 Medium: Increasing maintenance cost over time
🔵 Low: Code quality improvements

For each finding, include:
- The specific file(s) and what's wrong
- Estimated effort to fix (small/medium/large)
- A one-line description suitable for a ticket title
下面是 /debt-scan 生成完整项目健康报告的效果:
00:00/00:18
1x
  • 2x
  • 1.5x
  • 1x
  • 0.75x
  • 0.5x
请试试刷新
00:18
Vlf4F7wsyISBBjTs.mp4
Vlf4F7wsyISBBjTs
它在整个 codebase 中找出了 20 个问题,每个都有 severity、文件位置、问题描述和预计修复时间。
高优先级发现包括一些 linter 根本抓不到的东西,比如:
用 assert 做输入校验,而 Python 在 -O 下会直接把它静默禁用
metrics service 里存在一个无上限 list,本质上就是内存泄漏
model loading 中已经有文档记录的 race condition,但没有任何测试覆盖
最后 “Recommended Fix Order” 还会按投入产出比排出前五项,从“两分钟删掉 debugger”一路排到“45 分钟补测试覆盖”。
你甚至可以直接把每一条都原样转成 Jira ticket。

[Bonus] Command 11: /changelog

功能做完了,migration 也起草好了。
现在你需要 release notes。
手写 changelog 很无聊,而直接从 commit messages 自动生成出来的 changelog 又通常完全没法看。
这个命令位于两者中间:它会读取最近的 commits,再逐个检查 diff 以理解“实际发生了什么改动”,然后产出一份人类可读、可编辑后发布的 changelog。
代码块
---
description: Generate a changelog entry from recent commits
allowed-tools: Bash(git *)
argument-hint: <since-tag-or-commit (optional)>
---

Generate a changelog entry for all commits since: $ARGUMENTS

If no argument provided, use the most recent git tag:
!`git describe --tags --abbrev=0 2>/dev/null || echo "No tags found, using last 20 commits"`

## Gather the raw data
!`git log $(git describe --tags --abbrev=0 2>/dev/null || echo "HEAD~20")..HEAD --pretty=format:"%h %s" --no-merges`

## Rules
- Group changes into: Added, Changed, Fixed, Removed, Security
- Write each entry as a single sentence describing the user-facing impact, not the code change
- BAD: "Refactored auth middleware to use async/await"
- GOOD: "Fixed session expiry not being enforced on API routes"
- Skip pure refactors, typo fixes, and CI config changes unless they affect behavior
- Include the commit hash in parentheses after each entry
- If a commit message is unclear, read the diff to understand the actual change:
  use `git show <hash> --stat` to check

## Output format
[version] - YYYY-MM-DD

Added
- Entry here (...)

Fixed
- Entry here (...)

Output the changelog in markdown. Do not commit or modify any files.
下面是 /changelog 从项目提交历史中生成 release notes 的效果:
00:00/00:09
1x
  • 2x
  • 1.5x
  • 1x
  • 0.75x
  • 0.5x
请试试刷新
00:09
J8s73Q4ibuJpNQ7P.mp4
J8s73Q4ibuJpNQ7P
它读了 11 个 commits,并逐个检查 diff 以理解“实际改了什么”,而不是照抄 commit message,然后把结果分进了 Added、Fixed 和 Infrastructure 这些类别里。
每个条目都描述的是 用户能感知到的影响,而不是代码改动本身。比如它会写 “Single prediction endpoint with request logging”,而不是 “add predict route and logger service”。
它还把 commit hashes 一并带上了,因此你可以随时回溯到具体 diff。
最后 summary 会把这些 commits 串成一条叙事链,说明目前到底已经做成了什么、还有哪些在进行中。

开始你的第一个命令

配置你的第一个 command,只需要三步:
在项目根目录创建目录:mkdir -p .claude/commands
创建一个带 prompt 的 markdown 文件:echo "Review the staged changes and suggest improvements.\n\n!\git diff --cached\`" > .claude/commands/review.md`
在 Claude Code 中运行它:/review
对于那些你希望跨所有项目复用的 commands(比如 orient 或 preflight),把它们放到 ~/.claude/commands/ 里,然后用 /command-name 调用。
另外,这篇文章中的 commands 是有意带着强烈主观偏好的。它们编码进去了特定的 code review priorities、test patterns、commit hygiene 和 documentation style。你完全可以 fork 它们,再根据自己的 use cases 做调整。
但真正的价值不在于这些 prompts 的字面内容,而在于这套模式本身:找出那些你反复重打的指令,把它们保存成文件,并不断迭代 prompt,直到输出稳定地接近你手工完成时的效果。
还有一点要注意:Anthropic 后来已经引入了 .claude/skills/ 作为新 command 的推荐目录。Skills 支持更多能力,比如打包附属文件、自动触发(Claude 识别到相关任务时会自动加载这个 skill),以及 subagent 执行。
这篇文章里使用的 .claude/commands/ 方式依然可用,而且作为起步方案会更简单。
👉 轮到你了:你现在在 Claude Code 里反复输入、但其实早该被做成 custom command 的 prompts,到底有哪些?
That's a wrap!
如果你喜欢这篇教程:
Find me →@_avichawla
我每天都会分享关于 DS、ML、LLMs 和 RAG 的教程与洞察。