AI 编程教程中文版
官方教程中文版上下文与定制

仓库自定义指令

说明 Copilot repository instructions、path-specific instructions、AGENTS.md 和 references 验证方式。

仓库自定义指令(repository custom instructions)是给 Copilot 的项目长期上下文。GitHub 官方文档说明,它用来告诉 Copilot 如何理解项目,以及如何构建(build)、测试(test)、验证(validate)它的改动。

它不应该写一次性任务,也不应该塞敏感信息。它应该像项目规范一样维护。

阅读目标:读完本章,你应该能创建 repository-wide、path-specific 和 agent instructions,并知道如何验证 Copilot 是否使用了它们。

1. 三类仓库指令

GitHub 官方文档列出三类 repository custom instructions:

  • Repository-wide instructions:适用于仓库上下文中的所有请求,文件是 .github/copilot-instructions.md
  • Path-specific instructions:只适用于匹配路径的文件,文件放在 .github/instructions/ 下,文件名以 .instructions.md 结尾。
  • Agent instructions:给 AI agents 使用,常见文件名是 AGENTS.mdCLAUDE.mdGEMINI.md
flowchart TD
    Request["Copilot request"] --> Repo[".github/copilot-instructions.md"]
    Request --> Path[".github/instructions/*.instructions.md"]
    Request --> Agent["AGENTS.md / CLAUDE.md / GEMINI.md"]
    Path --> Match{"路径匹配?"}
    Match -->|是| Combine["和仓库级规则一起使用"]
    Match -->|否| RepoOnly["只用仓库级规则"]
    Agent --> Nearest["nearest AGENTS.md takes precedence"]
    Combine --> Response["Copilot response"]
    RepoOnly --> Response
    Nearest --> Response

    style Repo fill:#dbeafe,stroke:#2563eb,stroke-width:2px
    style Path fill:#fef3c7,stroke:#d97706,stroke-width:2px
    style Response fill:#dcfce7,stroke:#16a34a,stroke-width:2px

2. 文件结构

推荐结构:

.github/
  copilot-instructions.md
  instructions/
    frontend.instructions.md
    backend.instructions.md
    tests.instructions.md
AGENTS.md

Path-specific instructions 需要 frontmatter,使用 applyTo 指定 glob:

---
applyTo: "src/**/*.ts"
---

Use the existing error type.
Do not throw raw strings.

3. 写什么

适合写:

  • 项目用途和核心架构。
  • 目录职责。
  • build、test、lint、typecheck 命令。
  • 代码风格、命名、错误处理。
  • 安全红线和不可改路径。
  • PR 和 review 标准。

不适合写:

  • 密钥、token、账号。
  • 临时 bug 处理方案。
  • 已经过期的迁移说明。
  • 个人偏好。
  • 空泛口号。

4. 如何验证生效

官方文档说明,custom instructions 会自动加入相关 Copilot 请求。它们通常不直接显示在 Chat view 或 inline chat 里,但可以从 response references 里验证。

检查方式:

  1. 发起一个和仓库有关的 Chat 请求。
  2. 展开 response 顶部或 References 列表。
  3. 查看是否出现 .github/copilot-instructions.md 或相关 instruction 文件。
  4. 如果没有出现,检查 feature 开关、文件路径和工具支持矩阵。

5. 支持边界

不同 Copilot 功能支持的 instruction 类型不同。GitHub 官方支持矩阵会变化,写教程时不能把某个 IDE 或功能支持状态永久写死。

稳定做法:

  • 文档内标注 verifiedAt
  • 需要功能支持时链接官方 support matrix。
  • 对团队只写“我们当前启用的入口”。
深读:为什么 path-specific instructions 能降低上下文污染

大型仓库里,前端、后端、测试、基础设施的规则不同。如果全部写进一个仓库级文件,Copilot 每次都要读大量无关规则,还可能把后端规则套到前端。

Path-specific instructions 让规则按文件匹配加载,信息更少、更准,也更容易维护。

本章自检

完成本章后,用这 4 个问题检查:

  1. 仓库级和路径级规则是否职责清楚?
  2. applyTo 是否准确匹配目标文件?
  3. 是否能在 References 里看到对应 instruction 文件?
  4. 文件里是否没有敏感信息和临时任务?

通过标准:新成员不需要口头同步,就能让 Copilot 遵守项目核心规则。

官方来源

接下来去哪

本页目录