官方更新 Claude Blog 2026-07-08T12:00 正文 ok 1709 words

掌控 Claude Code:CLAUDE.md 文件、技能、钩子、规则、子智能体等

英文标题:Steering Claude Code: CLAUDE.md files, skills, hooks, rules, subagents and more

本文系统介绍了在 Claude Code 中自定义和控制助手行为的多种机制:规则(Rules)可按路径范围加载以节省令牌;技能(Skills)用于按需触发工作流;子智能体(Subagents)在独立上下文中执行子任务,避免干扰主会话;钩子(Hooks)提供确定性的生命周期事件响应;输出样式(Output styles)和追加系统提示等方法可影响回复风格。文章为开发者提供了清晰的选择指南,指出何时应使用钩子实现强制约束、何时将流程放入技能、以及如何避免上下文浪费,帮助团队更精准地驾驭 Claude Code。
打开原文相关 3.6 · 机会 1
media9.5 KB media99.6 KB media403 B media564.8 KB media108.6 KB media112.7 KB media27.9 KB media13.6 KB media8.1 KB media11.7 KB

中文

规则

规则 是 .claude/rules/ 目录下的 Markdown 文件,用于向 Claude 提供特定的约束或约定。

未限定范围的规则的行为与 CLAUDE.md 类似,它们始终在会话启动时加载,并在压缩时重新注入。即使对于当前任务并不相关,这也会消耗令牌,造成上下文浪费。

路径范围规则允许你通过添加 paths 字段来控制规则指令的加载时机,仅在相关时加载。

例如:范围限定为 src/api/** 的规则在仅处理文档的会话中不会进入上下文。只有当 Claude 读取 src/api/ 目录中的文件时,该规则才会被加载。

示例如下:

---
paths:
  - "src/api/**"
  - "**/*.handler.ts"
---
All API handlers must validate input with Zod before processing.

提示:像“迁移仅允许追加”这样针对特定文件的约束,最适合作为 规则 放在路径 frontmatter 中。当指令涉及跨切面关注点或出现在代码库的多个(但并非所有)角落的文件时,应优先使用路径范围规则,而非嵌套的 CLAUDE.md 文件。

技能

技能 位于 .claude/skills/ 中,是以文件夹形式组织的指令、脚本和资源,Claude 可动态加载。每个技能都有一个 SKILL.md 文件,包含名称、描述和正文。

只有名称和描述会在会话启动时加载;完整正文在 Claude 通过斜杠命令(如 /code-review)或自动匹配任务来调用该技能时才加载。

技能通过系统提示触发。

例如,/code-review 是一个内置技能,它会审查当前差异并报告发现的问题,而不编辑文件。该技能定义了操作手册,使得 Claude 每次调用时都遵循相同的结构化方法。

在压缩时,Claude Code 会重新注入已调用的技能,直到所有已调用技能的总预算用尽。如果你在一个会话中调用了许多技能,最旧的技能会最先被丢弃。

提示: 具有流程性质的指令,如部署工作流、发布检查清单或审查流程,应放入技能而非 CLAUDE.md 中。

Claude Code 内置了一些技能,但你也可以编写自己的自定义技能。我们的 构建 Claude 技能完整指南 会向你展示如何操作。

子智能体

子智能体 是 .claude/agents/ 中的 Markdown 文件,用于定义针对特定辅助任务的隔离助手。每个文件使用 YAML frontmatter(名称、描述、以及可选的模型和工具访问字段),后跟成为该子智能体系统提示的正文。

子智能体与技能类似,名称、描述和工具列表在会话启动时加载,但智能体正文中的更大上下文不会自动调用。Claude 通过 Agent 工具调用它们,并传入一个提示字符串。

Claude Code 的上下文窗口保存了 Claude 对你的会话所知的一切。此处的交互式时间线 逐步展示了加载的内容和时机。

子智能体正文中较大的指令上下文不仅不会自动调用,它也根本不会进入父对话。

子智能体随后在其自己的全新上下文窗口中运行,唯一返回到主会话的是子智能体的最终消息(通常是许多子任务的聚合结果)以及元数据。

这一模式可扩展:子智能体最多可以嵌套五层,并且 动态工作流 可以编排数十甚至数百个后台智能体,而无需你指定子智能体架构的每个细节。编排计划和中间结果存在于脚本变量中,而非 Claude 的上下文窗口中,这能在不丢失指令保真度的情况下实现扩展。

提示: 这种隔离性就是选择子智能体而非技能的主要原因之一。当诸如深度搜索、日志分析或依赖审计等辅助任务会因中间结果而搅乱主对话,且你不会再次引用这些结果时,应使用子智能体。当你想让流程在主线程中展开,以便你能查看和引导每一步时,则应使用技能。

钩子

钩子 是用户定义的命令、HTTP 端点或 LLM 提示,通过在 Claude 生命周期的特定事件(如文件编辑、工具调用或会话启动)触发,为 Claude 的行为提供更具确定性的控制。

下图展示了钩子可在 Claude Code 会话中触发的事件映射。

你在 settings.json、受管理的策略设置或技能/智能体的 frontmatter 中注册钩子。

钩子有多种类型:命令、HTTP、mcp_tool、提示和智能体。所有钩子都是确定性地触发的。前三种是确定性地执行,而后两种(提示和智能体)则借助 Claude 的判断而非一组规则来确定输出。

钩子的上下文成本很低,因为配置或指令存在于主上下文窗口之外。钩子运行器根据钩子类型运行处理程序(命令、http、mcp_tool)或使用独立窗口进行模型调用(提示、智能体)。

某些钩子的输出可能会保存到主上下文窗口中。例如,阻塞型钩子的标准错误会保存在上下文中,以便 Claude 知晓调用为何被拒绝。

但大多数钩子的输出不会保存到主窗口,除非配置明确要求返回。如果你使用 PreCompact 事件在压缩前将聊天历史备份到另一个文件以供稍后参考,Claude 并不知道哪个文件保存了聊天历史。

这使得这些钩子类型与 CLAUDE.md、规则和技能有着根本的不同。你可以在我们的文章 如何配置钩子 中了解更多。

提示: 对于任何应该确定性发生的事情,都应使用钩子:例如在编辑后运行 linter、在完成时向 Slack 推送消息,或在执行前阻止特定命令。PreToolUse 钩子可以检查任何工具调用,并以退出码 2 拒绝它。

它们上下文成本低,因为它们是运行器执行的代码,而不是加载到上下文中的对 Claude 的指令。

输出样式

输出样式 是 .claude/output-styles/ 中的文件,用于向系统提示注入指令。它们永远不会被压缩,每次会话启动时加载,并在会话中第一次请求后被缓存,这意味着它们具有中等的上下文成本。

由于它们位于系统提示中,输出样式在我们目前介绍的所有方法中具有最高的指令遵循权重,应谨慎使用。

更改输出样式将替换默认的输出样式(除非在样式的 frontmatter 中设置 keep-coding-instructions: true)。

在 Claude Code 中,这将移除那些告知 Claude 它正在帮助用户完成软件工程任务的指令,以及其他关键的默认指令,例如:

  • 如何控制变更范围;
  • 何时添加或省略代码注释;
  • 如何处理安全问题;以及
  • 验证习惯,如在声明工作完成前运行测试。

默认情况下,自定义的输出样式会丢弃所有这些内容,Claude Code 将变得更像一个通用助手,而非软件工程助手。

提示:在编写自定义输出样式之前,请先检查内置样式。主动式、解释式 和 学习式 覆盖了最常见的需求(自主模式、教学模式、协作编码),无需你维护样式文件。

追加系统提示

修改输出样式的一个替代方案是 append-system-prompt 标志。修改输出样式文件可能会对 Claude 的行为产生大量意外更改,而追加标志仅是对原始系统提示的补充。它不会修改 Claude 的角色;只是向默认角色添加指令。

它也是在调用时传入的,仅适用于该次调用,而非作为文件跨会话持久保留。

与其他传递指令的方法相比,追加系统提示可能具有更高的上下文成本。它增加了输入令牌,尽管在会话中的第一次请求后,提示缓存会降低这一成本。指示 Claude 使用更冗长或更长的风格也会增加输出令牌。

提示: 追加系统提示最适合添加特定的编码标准、输出格式或领域特定知识。请注意,使用追加系统提示对指令遵循度的回报是递减的。一般来说,你使用此方法提供的指令越多,Claude 对它们的遵循就越不严格,尤其是在指令相互矛盾时。

Claude Code 自定义之快速提示

如果你发现自己在做以下事情,可能需要考虑换一种放置指令的方式:

在 CLAUDE.md 中写“每次发生 X,总是做 Y”。如果该行为应该可靠地发生,如每次编辑后运行 prettier 或在完成时向 Slack 推送消息,请改用 settings.json 中的钩子。模型选择运行格式化工具与自动运行格式化工具是不同的。

在 CLAUDE.md 中写“绝不这样做”。当某件事绝对不能发生时,指令是错误工具。Claude 在大多数时候会遵循指令,但在压力下、长时间会话、模糊情形下,或由于任务涉及的文件中存在提示注入时,模型可能无法遵循提示的规则。真正的护栏需要是确定性的,而实施方法就是 钩子 和 权限。PreToolUse 钩子可以检查调用并以退出码 2 阻止它。托管设置 更进一步:它们由管理员部署,不能被用户的本地配置覆盖,是实现确定性、组织级护栏的唯一途径。

在 CLAUDE.md 中放入 30 行的流程。流程应放在技能中。CLAUDE.md 用于存放 Claude 应始终掌握的事实:构建命令、单体仓库布局、团队约定。部署操作手册或安全审查清单应位于 .claude/skills/ 中,仅在调用时加载正文。

未限定路径的 API 特定规则。如果某规则仅适用于 src/api/**,用 paths: 限定范围可以使其在不相关的工作中不进入上下文。未限定范围的规则在机制上与将内容放入 CLAUDE.md 相同:始终加载,始终消耗令牌。

将个人偏好写入项目级 CLAUDE.md 文件。所有基于文件的方法都有对应的用户级版本,无论你处于哪个代码仓库,Claude Code 会话都会加载它们。使用本地文件存放个人偏好(如始终使用语义化提交消息)。将项目级文件留给团队级但与特定代码库相关的偏好。

开始使用

你可以在 Claude Code 最佳实践 文档中找到更多从配置环境到跨并行会话扩展的技巧和模式,以充分发挥 Claude Code 的潜力。

一旦你让其中几项投入运作,就可以将许多内容(技能、子智能体、钩子、输出样式)打包为 插件,在团队成员或项目间共享一套连贯的设置。

English / 原文

Rules

Rules are markdown files in .claude/rules/ that give Claude specific constraints or conventions.

Unscoped rules behave like CLAUDE.md in that they are always loaded at session start and get re-injected on compaction. This can waste tokens by loading context even when it's not relevant for the task at hand.

Path-scoped rules allow you to load rule instructions only when they are relevant by adding a paths field that controls when they load.

For example: a rule scoped to src/api/** stays out of context during a docs-only session. It would only be loaded whenever Claude reads files within that src/api/ directory.

Here’s what that looks like:

---
paths:
  - "src/api/**"
  - "**/*.handler.ts"
---
All API handlers must validate input with Zod before processing.

Tip : A file-specific constraint, like "migrations are append-only," fits best as a rule placed in your paths: frontmatter. Reach for a path scoped rule over a nested CLAUDE.md file when the instruction regards a cross-cutting concern or file that appears in multiple (but not all) corners of the codebase.

Skills

Skills live in .claude/skills/ as folders of instructions, scripts, and resources that Claude loads dynamically. Each skill has a SKILL.md file with a name, description, and body.

Only the name and description load at session start; the full body loads when Claude invokes the skill, either through a slash command (/code-review) or by auto-matching the task.

Skills are triggered via your system prompt.

For example, /code-review is a built-in skill that reviews your current diff and reports its findings without editing files. The skill defines the playbook so Claude follows the same structured approach every time you invoke it.

On compaction, Claude Code re-injects invoked skills up to a total budget across all invoked skills. If you’ve invoked many skills during a session, the oldest ones drop first.

Tip: Instructions that are procedural, like deploy workflows, release checklists, or review processes, belong in a skill rather than in CLAUDE.md.

Claude Code ships with skills, but you can also write your own custom skills. Our complete guide to building skills for Claude shows you how.

Subagents

Subagents are markdown files in .claude/agents/ that define isolated assistants for specific side tasks. Each file uses YAML frontmatter (name, description, plus optional fields for model and tool access) followed by a body that becomes that subagent's system prompt.

Subagents are similar to skills in that the name, description, and tool list load at session start, but the larger context within the body of the agent doesn’t auto-invoke. Claude calls them via the Agent tool, passing in a prompt string.

Claude Code’s context window holds everything Claude knows about your session. The interactive timeline here walks through what loads and when.

Not only does the larger instructional context within the body of the subagent not auto-invoke, it never enters the parent conversation at all.

The subagent then runs in its own fresh context window, and the only thing that returns to your main session is the subagent’s final message (often the aggregated result of many subtasks) plus metadata.

This pattern scales: subagents can nest up to five levels deep, and dynamic workflows orchestrate tens to hundreds of background agents without requiring you to specify each detail of the subagent architecture. The orchestration plan and intermediate results live in script variables rather than in Claude’s context window, which enables scale without losing instructional fidelity.

Tip: That isolation is one of the main reasons to reach for a subagent instead of a skill. Use a subagent when a side task like deep search, a log analysis pass, or a dependency audit would clutter your main conversation with intermediate results you won't reference again. Use a skill when you want the procedure to play out inside the main thread so you can see and steer each step.

Hooks

Hooks are user-defined commands, HTTP endpoints, or LLM prompts that provide more deterministic control over Claude’s behavior by firing on specific events in Claude’s lifecycle like file edits, tool calls, or session start.

A map of events in a Claude Code session when a hook can fire.

You register hooks in settings.json, managed policy settings, or skill/agent frontmatter.

There are several types of hooks: command, HTTP, mcp_tool, prompt, and agent. All hooks are deterministically triggered. The first three execute deterministically while the latter two, prompt and agent, use Claude’s judgment rather than a set of rules to determine the output.

Hooks have low context costs because the configuration or instruction lives outside the main context window. The harness runs the handler (command, http, mcp_tool) or makes model calls with separate windows (prompt, agent) depending on the hook type.

Some hooks may have the output saved to the main context window. For example, a blocking hook's standard error is saved within context so Claude knows why the call was denied.

But most hooks won’t have the output saved to the main window unless the configuration explicitly returns it. If you backed up your chat history into another file for later reference before compaction using the PreCompact event, Claude wouldn’t know which file had the chat history saved.

This makes these hook types fundamentally different from CLAUDE.md, rules, and skills. You can learn more in our post****how to configure hooks.

Tip: Use hooks for anything that should happen deterministically: running linters after edits, posting to Slack on completion, or blocking specific commands before they execute. A PreToolUse hook can inspect any tool call and exit code 2 to deny it.

They have low context cost because they are code that the harness runs rather than instructions to Claude that get loaded into context.

Output styles

Output styles are files in .claude/output-styles/ that inject instructions into the system prompt. They never get compacted, load at the start of every session, and are cached after the first request within a session, meaning they have a moderate context cost.

Because they sit in the system prompt, output styles carry the highest instruction-following weight of any method that we've covered so far and should be used judiciously.

Changes to the output style will replace the default output style (unless you set keep-coding-instructions: true in the style's frontmatter).

In Claude Code, this would remove instructions that tell Claude it is helping users with software engineering tasks and contains other critical default instructions such as:

  • How to scope changes;
  • When to add or omit code comments;
  • What to do about security concerns; and
  • Verification habits like running tests before declaring work complete.

By default, a custom output style drops all of this and Claude Code becomes more of a general assistant than a software engineer assistant.

Tip : Before writing a custom output style, check the built-in styles. Proactive , Explanatory , and Learning cover the most common needs (autonomy, teaching mode, collaborative coding) without you having to maintain a style file.

Appending the system prompt

An alternative to modifying output styles is the append-system-prompt flag. Whereas modifying output style files can have large, unintended changes to Claude’s behavior, the append flag is only additive to the original system prompt. It doesn’t modify Claude’s role; it just adds instructions to its default role.

It is also passed at invocation time, and only applies to that invocation, rather than persisted as a file across sessions.

Appending the system prompt can have a higher context cost compared to other methods of passing instructions. It increases input tokens, though prompt caching reduces this cost after the first request in a session. Instructing Claude to use a more verbose or longer style also increases output tokens.

Tip: Appending the system prompt is best for adding specific coding standards, output formatting, or domain-specific knowledge. Keep in mind that appending the system prompt has diminishing returns for adherence. Generally, the more instructions you provide using this method, the less strictly Claude will follow them, particularly if any contradict.

Quick tips for Claude Code customization

If you find yourself doing one of the following, you may want to consider an alternative location for your instructions:

"Every time X, always do Y" in CLAUDE.md. If the behavior should happen reliably, like running prettier after every edit or posting to Slack on completion, use a hook in settings.json instead. The model choosing to run a formatter is different from the formatter running automatically.

“Never do this” in CLAUDE.md. When there's something that absolutely must not happen, an instruction is the wrong tool. Claude will follow the instruction most of the time, but when under pressure, in a long session or an ambiguous situation, or due to a prompt injection in a file accessed as part of the task, the model can fail to follow a prompted rule. A real guardrail needs to be deterministic, and the enforcement methods are hooks and permissions. A PreToolUse hook can inspect a call and exit with code 2 to block it. Managed settings**** go further: they are admin-deployed, cannot be overridden by a user's local config, and are the only way to enforce a deterministic, organization-wide guardrail.

A 30-line procedure in CLAUDE.md. Procedures belong in skills. CLAUDE.md is for facts Claude should hold all the time: build commands, monorepo layout, team conventions. A deployment runbook or a security review checklist should live in .claude/skills/, where the body loads only when invoked.

An API-specific rule without paths. If a rule only applies to src/api/**, scoping it with paths: keeps it out of context during unrelated work. An unscoped rule is mechanically identical to putting the content in CLAUDE.md: always loaded, always costing tokens.

Writing personal preferences to a project-level CLAUDE.md file. All file-based methods have a user-level counterpart loaded for every Claude Code session regardless of which repo you’re in. Use local files for personal preferences (always use semantic commit messages). Keep project-level files for preferences that are team-wide but specific to a given codebase.

Getting started

You can find more tips and patterns for getting the most out of Claude Code, from configuring your environment to scaling across parallel sessions, in our best practices for Claude Code documentation.

Once you have a few of these working, you can bundle many of them (skills, subagents, hooks, output styles) as a plugin to share a coherent setup across teammates or projects.