你好!今天我将分享一个关于如何为 GitHub Copilot 设置项目的快速指南。
GitHub Copilot AI 工作流:完整指南及示例
本指南将指导你如何利用代理原语和上下文工程,在你的代码库和 IDE/CLI 中创建可预测且可重现的 AI 工作流。你将找到文件结构、预制模板、安全规则和命令。
⚠️ 注意:IDE/CLI 中的提示文件和代理模式功能可能会发生变化——请根据你使用的 Copilot 和 VS Code 的具体版本调整本指南。
1) 概览:工作流的组成部分
主要目标是将代理(Agent)的工作分解为清晰、可控的步骤。为此,我们提供了以下工具:
- Custom Instructions (
.github/copilot-instructions.md) — 项目全局规则(如何构建、如何测试、代码风格、PR 策略)。 - Path-specific Instructions (
.github/instructions/*.instructions.md) — 针对特定路径的规则,通过applyTo(glob 模式)应用。 - Chat Modes (
.github/chatmodes/*.chatmode.md) — 专门的聊天模式(例如,Plan/Frontend/DBA),具有固定的工具和模型。 - Prompt Files (
.github/prompts/*.prompt.md) — 可重用的脚本/“程序”,用于典型任务(审查、重构、生成)。 - Context helpers (
docs/*.spec.md,docs/*.context.md,docs/*.memory.md) — 项目规范、上下文信息和记忆,用于提供精确的上下文。 - MCP servers (
.vscode/mcp.json或通过 UI) — 代理可以使用的工具和外部资源。
2) 项目文件结构
以下结构与上述工具相对应,有助于为代理构建完整的工作流。
1.github/
2 copilot-instructions.md
3 instructions/
4 backend.instructions.md
5 frontend.instructions.md
6 actions.instructions.md
7 prompts/
8 implement-from-spec.prompt.md
9 security-review.prompt.md
10 refactor-slice.prompt.md
11 test-gen.prompt.md
12 chatmodes/
13 plan.chatmode.md
14 frontend.chatmode.md
15.vscode/
16 mcp.json
17docs/
18 feature.spec.md
19 project.context.md
20 project.memory.md
3) 文件及其用途 — 技术解析
现在,让我们单独看看每个工具及其作用。下面将解释这些文件是如何工作的:它们是什么,为什么存在,它们如何影响代理对任务的理解,以及它们合并/覆盖的顺序。以下代码示例符合规范。
| 文件/文件夹 | 这是什么 | 用途 | 应用位置 |
|---|---|---|---|
.github/copilot-instructions.md | 项目全局规则 | 为所有响应提供统一标准 | 整个代码库 |
.github/instructions/*.instructions.md | 针对特定路径的指令 | 为 frontend/backend/CI 提供不同规则 | 仅适用于匹配 applyTo 的文件 |
.github/chatmodes/*.chatmode.md | 聊天模式的规则集 + 可用工具 | 分割工作阶段(规划/重构/DBA) | 选择了该聊天模式时 |
.github/prompts/*.prompt.md | 任务脚本(工作流) | 重复运行典型流程 | 通过 /name 或 CLI 调用时 |
docs/*.spec.md | 规范 | 精确的任务定义 | 在对话中通过 @ 提及时 |
docs/*.context.md | 稳定参考信息 | 减少聊天中的“噪音” | 通过链接 / @-提及 |
docs/*.memory.md | 项目记忆 | 记录决策以避免重复 | 通过链接 / @-提及 |
.vscode/mcp.json | MCP 服务器配置 | 访问 GitHub 和其他工具 | 当前工作区 |
规则和设置的合并顺序:Prompt Frontmatter → Chat Mode → Repo/Path Instructions → Default Values。
现在,让我们逐一分析每个工具。
3.1. 全局规则 — .github/copilot-instructions.md
这是什么: 一个 Markdown 文件,包含简短、可验证的规则:如何构建、如何测试、代码风格和 PR 策略。
用途: 确保所有响应都遵循一套统一的标准(避免在每个提示中重复)。
工作原理: 该文件会自动成为代码库内所有问题的系统上下文的一部分。它没有 applyTo(稍后讨论)——它在所有地方都适用。
最小示例:
1# Repository coding standards
2- Build: `npm ci && npm run build`
3- Tests: `npm run test` (coverage ≥ 80%)
4- Lint/Typecheck: `npm run lint && npm run typecheck`
5- Commits: Conventional Commits; keep PRs small and focused
6- Docs: update `CHANGELOG.md` in every release PR
提示。
- 保持条目简短。
- 避免使用模糊的短语。
- 只包含可能影响结果的内容(构建/测试/代码检查/类型检查/PR 策略)。
3.2. 特定路径指令 — .github/instructions/*.instructions.md
这是什么: 模块化规则,包含 YAML frontmatter applyTo——用于应用这些规则的文件 glob 模式。
用途: 区分不同领域(前端/后端/CI)的标准。允许根据任务类型控制上下文。
工作原理: 在处理任务时,Copilot 会查找所有 *.instructions.md 文件,其中 applyTo 与当前上下文(你正在讨论/编辑的文件)匹配。匹配的规则将添加到全局规则中。
示例:
1---
2applyTo: "apps/web/**/*.{ts,tsx},packages/ui/**/*.{ts,tsx}"
3---
4- React: function components and hooks
5- State: Zustand; data fetching with TanStack Query
6- Styling: Tailwind CSS; avoid inline styles except dynamic cases
7- Testing: Vitest + Testing Library; avoid unstable snapshots
注意。
- 避免重复已有的全局规则。
- 确保 glob 模式确实指向了正确的文件路径。
3.3. 聊天模式 — .github/chatmodes/*.chatmode.md
这是什么: 配置文件,定义了代理对话的工作模式:简短描述、模型(如有必要)以及允许的工具列表。
用途: 分割工作阶段(规划/前端/DBA/安全),并限制每个阶段的工具。这使得结果更加可预测。
文件结构:
1---
2description: "Plan - analyze code/specs and propose a plan; read-only tools"
3model: GPT-4o
4tools:[ "search/codebase"]
5---
6In this mode:
7- Produce a structured plan with risks and unknowns
8- Do not edit files; output a concise task list instead
工作原理:
- 聊天模式应用于 IDE 中的当前聊天。
- 如果你激活了一个提示文件,其 frontmatter 具有优先权(可以更改模型并限制
tools)。 - 有效的允许工具列表:聊天模式的工具,受提示文件工具和 CLI 标志
--allow/--deny的限制。
管理和切换:
- 在 IDE (VS Code) 中:
- 打开 Copilot Chat 面板。
- 在顶部的行中,从下拉列表中选择所需的聊天模式(列表由
.github/chatmodes/*.chatmode.md+ 内置模式构成)。 - 该模式仅适用于此对话分支。要切换,请选择另一个或创建一个带有所需模式的新分支。
- 在对话标题/面板中检查活动模式;在 References 中将看到
*.chatmode.md文件。
-
在 CLI 中:(稍微有点技巧性,最好通过提示文件)
- 通常没有用于切换模式的特定 CLI 标志;将所需的限制编码到提示文件的 frontmatter 中,或通过
--allow-tool/--deny-tool标志实现。 - 你可以在第一行写:“Use i18n chat mode.” — 如果你的版本支持,代理可能会切换;否则,提示文件的 frontmatter 仍然会应用工具限制。
- 通常没有用于切换模式的特定 CLI 标志;将所需的限制编码到提示文件的 frontmatter 中,或通过
-
不切换模式:运行带有所需
tools:的 frontmatter 的提示文件——这将独立于聊天模式限制工具。
诊断: 如果代理使用了“多余”的工具或看不到所需的工具,请检查:(1) 选择的聊天模式;(2) 提示文件的 frontmatter 中的 tools;(3) CLI 标志 --allow/--deny;(4) 回复中的 References(可见的 *.chatmode.md/*.prompt.md 文件)。
3.4. 提示文件 — .github/prompts/*.prompt.md
这是什么: 用于可重用任务的脚本文件。包含 YAML frontmatter(配置)和主体(说明/步骤/验收标准)。通过 /name 在聊天中调用,或通过 CLI 调用。
何时使用: 当需要可预测、可自动化的过程时:审查 PR、生成测试、根据规范实现功能等。
Frontmatter 结构
description— 脚本的简短目标。mode—ask(Q&A,不编辑文件) ·edit(本地编辑打开的文件) ·agent(多步骤过程,带工具)。model— 期望的模型配置文件。tools— 脚本允许的工具列表(即使聊天模式允许,这里也可以进一步限制)。
执行算法(顺序)
- 从何处启动:
- 在聊天中:在消息框中输入
/prompt-name和参数。 - 在 CLI 中:调用
copilot并传递字符串/prompt-name …(交互式或通过 heredoc /-p标志)。
-
上下文收集: Copilot 按以下顺序构建执行上下文:
repo-instructions→path-instructions (applyTo)→chat mode→frontmatter prompt(提示文件的 frontmatter 具有最高优先级,可以限制工具/更改模型)。 -
参数解析(何处以及如何):
- 在聊天中:参数与名称在同一消息中,例如:
/security-review prNumber=123 target=apps/web。 - 在 CLI 中:参数在同一行
/…中,或在 stdin,或在-p标志之后。 - 在提示文件内部,它们可以作为
${input:name}访问。如果缺少必需参数,提示可能会通过对话文本要求。
- 在聊天中:参数与名称在同一消息中,例如:
-
工具权限解析:
- 有效的允许工具列表:聊天模式的工具,受提示文件工具和 CLI 标志
--allow/--deny的限制。 - 如果工具被禁止,相应步骤将被跳过或需要确认/策略更改。
-
执行提示文件主体中的步骤: 代理严格按照步骤顺序执行,仅执行策略/工具允许的操作(在代码库中搜索、生成 diff、运行测试等)。对于潜在风险操作,它会请求确认。
-
Validation gates(验证门): 在最后,提示会执行检查(构建/测试/代码检查/类型检查、输出格式检查)。如果检查失败——代理会返回问题列表并提出下一步操作(不自动合并/保存更改)。
-
结果出现在哪里(可见什么):
- 主要回复——在聊天面板(IDE)或 stdout(CLI)中:表格、列表、文本报告、带
diff的代码块。 - 文件更改——在你的工作目录中:IDE 中显示 diff/建议的补丁;CLI 中本地文件会被修改(如果工具允许)。
- 附加工件——例如,PR 评论,如果 GitHub 工具可用且提示指定了此操作。
输出格式和检查(建议)
- 始终指定 输出格式(例如,“issue | file | line | severity | fix” 表格)。
- 添加 validation gates:构建/测试/代码检查/类型检查;要求为建议的更改提供 unified-diff;列出未解决问题的 TODO。
完整的提示文件示例
1---
2mode: 'agent'
3model: GPT-4o
4tools: ['search/codebase']
5description: 'Implement a feature from a spec'
6---
7Goal: Implement the feature described in @docs/feature.spec.md.
8
9Steps:
101) Read @docs/feature.spec.md and produce a short implementation plan (bullets)
112) List files to add/modify with paths
123) Propose code patches as unified diff; ask before installing new deps
134) Generate minimal tests and run them (report results)
14
15Validation gates:
16- Build, tests, lint/typecheck must pass
17- Output includes the final diff and a TODO list for anything deferred
18- If any gate fails, return a remediation plan instead of "done"
反模式(Antipatterns)
- 模糊的描述:将
description保持在 1-2 行。 - 缺乏输出格式。
- 过多的工具:只允许必要的 (
tools)。
快速入门
- 聊天:
/implement-from-spec - CLI:
copilot <<<'/implement-from-spec'或copilot -p "Run /implement-from-spec"
3.5. 上下文文件 — specs/context/memory
这是什么: 辅助 Markdown 文件(非特殊类型),你在对话/提示中通过 @ 提及它们。通常存储为文档。
docs/*.spec.md— 精确的任务定义(目标、验收标准、边缘情况、非目标)。docs/*.context.md— 简短的参考信息(API 策略、安全性、UI 风格指南、SLA)。docs/*.memory.md— “决策日志”,包含日期和理由,这样代理就不会反复纠结于早已解决的问题。
示例:
1# Feature: Export report to CSV
2Goal: Users can export the filtered table to CSV.
3Acceptance criteria:
4- "Export CSV" button on /reports
5- Server generates file ≤ 5s for 10k rows
6- Column order/headers match UI; locale-independent values
7Edge cases: empty values, large numbers, special characters
8Non-goals: XLSX, multi-column simultaneous filters
3.6. MCP — .vscode/mcp.json
这是什么: 模型上下文协议(Model Context Protocol)服务器(例如 GitHub MCP)的配置,这些服务器为代理提供工具。
用途: 使代理能够读取 PR/issue、运行测试、与数据库/浏览器交互——在允许的权限范围内。
示例:
1{
2 "servers": {
3 "github-mcp": {
4 "type": "http",
5 "url": "https://api.githubcopilot.com/mcp"
6 }
7 }
8}
安全。 只连接受信任的服务器;在提示/聊天模式/CLI 中使用允许/禁止列表。
3.7. 上下文合并顺序和优先级(规则 & 工具)
- Instructions:
copilot-instructions+ 所有*.instructions.md(其applyTo与当前路径匹配)。具体指令将添加到通用上下文中。 - Chat Mode:限制会话的工具集和(如有必要)模型。
- Prompt Frontmatter:具有最高优先级;可以限制工具并覆盖模型。
- Context:你通过
@提及的所有内容,模型都将可靠地考虑在内。
诊断。 检查回复中的 References 部分——它会显示哪些指令文件被考虑在内,以及运行了哪个提示。
3.8. 示例:使用 Goman MCP 的完整 i18n 周期(创建/更新/删除)
以下是实现以下目标的精确流程和模板:(a) 在创建 UI 组件时,在 Goman 中创建/更新本地化键;(b) 在删除组件时,可以检测到未使用的条目,并在(确认后)删除它们。
代码片段和 frontmatter 为英文。
3.8.1. MCP 配置 — 连接 Goman
/.vscode/mcp.json
1{
2 "servers": {
3 "goman-mcp": {
4 "type": "http",
5 "url": "https://mcp.goman.live/mcp",
6 "headers": {
7 "apiKey": "<YOUR_API_KEY>",
8 "applicationid": "<YOUR_APPLICATION_ID>"
9 }
10 }
11 }
12}
3.8.2. Repo/Path 规则 — 强制默认 i18n
/.github/instructions/frontend.instructions.md (补充)
1---
2applyTo: "apps/web/**/*.{ts,tsx}"
3---
4- All user-facing strings **must** use i18n keys (no hardcoded text in JSX/TSX)
5- Key naming: `<ui_component_area>.<n>` (e.g., `ui_button_primary.label`)
6- When creating components, run `/i18n-component-scaffold` and commit both code and created keys
7- When deleting components, run `/i18n-prune` and confirm removal of unused keys
3.8.3. 聊天模式 — 限制 i18n 工具
/.github/chatmodes/i18n.chatmode.md
1---
2description: "i18n - manage localization keys via Goman MCP; enforce no hardcoded strings"
3model: GPT-4o
4tools:
5 - "files"
6 - "goman-mcp:*"
7---
8In this mode, prefer:
9- Creating/updating keys in Goman before writing code
10- Checking for existing keys and reusing them
11- Producing a table of changes (created/updated/skipped)
3.8.4. 提示文件 — 组件脚手架 + Goman 键同步
/.github/prompts/i18n-component-scaffold.prompt.md
1---
2mode: 'agent'
3model: GPT-4o
4tools: ['files','goman-mcp:*']
5description: 'Scaffold a React component with i18n keys synced to Goman'
6---
7Inputs: componentName, namespace (e.g., `ui.button`), path (e.g., `apps/web/src/components`)
8
9Goal: Create a React component and ensure all user-visible strings use i18n keys stored in Goman.
10
11Steps:
121) Plan the component structure and list all user-visible strings
132) For each string, propose a key under `${namespace}`; reuse if it exists
143) Using Goman MCP, create/update translations for languages: en, be, ru (values may be placeholders)
154) Generate the component using `t('<key>')` and export it; add a basic test
165) Output a Markdown table: key | en | be | ru | action(created/updated/reused)
17
18Validation gates:
19- No hardcoded literals in the produced .tsx
20- Confirm Goman actions succeeded (report tool responses)
21- Tests and typecheck pass
组件代码示例:
1import { t } from '@/i18n';
2import React from 'react';
3
4type Props = { onClick?: () => void };
5
6export function PrimaryButton({ onClick }: Props) {
7 return (
8 <button aria-label={t('ui.button.primary.aria')} onClick={onClick}>
9 {t('ui.button.primary.label')}
10 </button>
11 );
12}
3.8.5. 提示文件 — 删除组件时清理未使用的键
/.github/prompts/i18n-prune.prompt.md
1---
2mode: 'agent'
3model: GPT-4o
4tools: ['files','goman-mcp:*']
5description: 'Find and prune unused localization keys in Goman after code deletions'
6---
7Inputs: pathOrDiff (e.g., a deleted component path or a PR number)
8
9Goal: Detect keys that are no longer referenced in the codebase and remove them from Goman after confirmation.
10
11Steps:
121) Compute the set of removed/renamed UI elements (scan git diff or provided paths)
132) Infer candidate keys by namespace (e.g., `ui.<component>.*`) and check code references
143) For keys with **zero** references, ask for confirmation and delete them via Goman MCP
154) Produce a Markdown table: key | status(kept/deleted) | reason | notes
16
17Validation gates:
18- Never delete keys that still have references
19- Require explicit confirmation before deletion
20- Provide a rollback list of deleted keys
3.8.6. 提示文件 — 同步和检查缺失的翻译(可选)
/.github/prompts/i18n-sync.prompt.md
1---
2mode: 'agent'
3model: GPT-4o
4tools: ['files','goman-mcp:*']
5description: 'Sync new/changed i18n keys and check for missing translations'
6---
7Goal: Compare code references vs Goman and fill gaps.
8
9Steps:
101) Scan code for `t('...')` keys under provided namespaces
112) For missing keys in Goman - create them (placeholder text ok)
123) For missing languages - create placeholders and report coverage
134) Output coverage table: key | en | be | de | missing
4) 如何使用(IDE 和 CLI)
4.1. 在 VS Code / 其他 IDE 中
- 打开 Copilot Chat — 从下拉列表中选择 Agent/Edit/Ask 模式。
- 对于提示文件,只需在输入框中输入
/file-name,无需扩展名(例如/security-review)。 - 通过
@提及文件和目录来添加上下文。 - 在更改任务类型时,切换聊天模式(Plan/Frontend/DBA)。
4.2. 在 Copilot CLI(终端)中
- 安装示例:
npm install -g @github/copilot→ 运行copilot。 - 交互式:
“Run /implement-from-spec” on [@docs](https://dev.to/docs)/feature.spec.md。 - 编程化 / CI 中:
copilot -p "Implement feature from @docs/feature.spec.md" --deny-tool shell("rm*")。 - 通过标志添加/限制工具:
--allow-all-tools,--allow-tool,--deny-tool(全局或按模式,例如shell(npm run test:*))。
4.3. CLI 命令的配方(聊天模式和提示文件)
以下是预制配方。所有命令都应从代码库根目录运行,并遵守你的 deny/allow 列表。
A. 在交互式会话中运行提示文件
1copilot
2# 在会话中(按原样输入字符串)
3/security-review prNumber=123
B. 在非交互式模式下运行提示文件(heredoc)
1copilot <<'EOF'
2/security-review prNumber=123
3EOF
C. 向提示文件传递参数
1copilot <<'EOF'
2/implement-from-spec path=@docs/feature.spec.md target=apps/web
3EOF
在提示文件内部,值可以读取为
${input:target}和${input:path}。
D. 以安全的工具权限运行提示
1copilot --allow-tool "shell(npm run test:*)" \
2 --deny-tool "shell(rm*)" \
3 <<'EOF'
4/security-review prNumber=123
5EOF
E. 在 CLI 中使用聊天模式(专用模式)
1copilot
2# 在会话中——请求切换到所需模式并运行提示
3Use the i18n chat mode.
4/i18n-component-scaffold componentName=PrimaryButton namespace=ui.button path=apps/web/src/components
如果你的客户端支持通过菜单选择模式——在运行提示之前选择 i18n。如果不支持——在提示的 frontmatter 中指定限制(
tools和提示体内的规则)。
F. 将文件/diff 链接作为上下文传递
1copilot <<'EOF'
2Please review these changes:
3@apps/web/src/components/PrimaryButton.tsx
4@docs/feature.spec.md
5/security-review prNumber=123
6EOF
G. 为特定运行更改模型
我们建议在提示的 frontmatter 中指定模型。如果支持,你也可以在运行时传递模型标志:
1copilot --model GPT-4o <<'EOF'
2/implement-from-spec
3EOF
H. Goman MCP i18n 周期(聊天)
在同一个聊天分支中按顺序运行:
1/i18n-component-scaffold componentName=PrimaryButton namespace=ui.button path=apps/web/src/components
2/i18n-prune pathOrDiff=@last-diff
3/i18n-sync namespace=ui.button
你将获得:
- 聊天面板中的最终表格/报告;
- 代码更改在你的工作目录中(IDE 显示 diff);
- 这里不需要运行 Goman MCP 的 CLI 命令。
5) 上下文工程:如何避免过多的上下文
- 按阶段划分会话:规划 → 实现 → 审查/测试。每个阶段都有自己的聊天模式。
- 仅附加必要的指令:使用特定路径的
*.instructions.md,而不是加载所有内容。 - 项目记忆:在
project.memory.md中记录简短的 ADR——这可以减少代理在任务之间“遗忘”的现象。 - 上下文助手:将频繁的参考信息(API/安全/UI)存储在
*.context.md中,并在提示文件中引用它们。 - 专注于任务:在提示文件中始终指定目标、步骤和输出格式(表格、diff、清单)。
6) 安全和工具管理
- 在运行命令/工具之前要求显式确认。在 CI 中,默认使用
--deny-tool,并添加本地允许列表。 - 权限模式:只允许必需的(
shell(npm run test:*),playwright:*),禁止危险的模式(shell(rm*))。 - 密钥:不要将密钥放入提示和指令中;使用 GitHub Environments 或本地密钥管理器和
.env(并添加到.gitignore)。 - 任何 MCP——只从受信任的来源;连接前请检查代码/配置。
- 补丁审查:在提示文件中要求 unified-diff 和解释——这简化了审查。
7) CI/CD 配方(可选示例)
确保“一切都能构建”: 在安全模式下运行 Copilot CLI 以生成 PR 评论。
1# .github/workflows/ai-review.yml
2name: AI Review (Copilot CLI)
3on:
4 pull_request:
5 types: [opened, synchronize, reopened]
6
7jobs:
8 ai_review:
9 runs-on: ubuntu-latest
10 permissions:
11 contents: read
12 pull-requests: write
13 steps:
14 - uses: actions/checkout@v4
15 - uses: actions/setup-node@v4
16 with:
17 node-version: 22
18 - name: Install Copilot CLI
19 run: npm install -g @github/copilot
20 - name: Run security review prompt (no dangerous tools)
21 env:
22 PR: ${{ github.event.pull_request.number }}
23 run: |
24 copilot -p "Run /security-review with prNumber=${PR}" \
25 --deny-tool shell("rm*") --deny-tool shell("curl*") \
26 --allow-tool shell("npm run test:*") \
27 --allow-tool "github:*" \
28 > ai-review.txt || true
29 - name: Comment PR with results
30 if: always()
31 run: |
32 gh pr comment ${{ github.event.pull_request.number }} --body-file ai-review.txt
提示:保持严格的 deny/allow 列表;不要在 CI 中给代理“完全自由”。
8) 小型脚本和有用技巧
- 从想法到 PR:
/plan— 讨论计划 —/implement-from-spec→ 本地测试 — PR —/security-review。 - 维护:
/refactor-slice用于在不更改行为的情况下进行局部改进。 - 测试:
/test-gen用于新模块 + 手动添加以处理边缘情况。 - 渐进式引入:从 1-2 个提示文件和一个聊天模式开始;稍后扩展。
9) 质量检查(Validation Gates)
在每个提示文件中固定“什么是完成”的标准:
- 输出格式:风险表格、unified-diff、清单。
- 自动检查:构建、单元/集成测试、代码检查/类型检查。
- 手动检查:“OK to merge?” 并附带理由和剩余风险。
10) 反模式和技巧
- 反模式:一个巨大的 instructions.md。优先使用多个带有
applyTo的*.instructions.md。 - 反模式:用模糊的语言代替规则。优先使用具体的命令/步骤。
- 反模式:在没有检查的情况下运行危险的 shell 命令。使用 deny/allow 和手动确认。
- 反模式:遗忘的规范/记忆。维护
feature.spec.md和project.memory.md。 - 反模式:在一个会话中混合任务。为每个阶段创建聊天模式。
11) 实现清单
- 添加
.github/copilot-instructions.md(至少 5-8 条关于构建/测试/样式的内容)。 - 创建 1-2 个
*.instructions.md并带有applyTo(frontend/backend 或 workflows)。 - 添加
plan.chatmode.md和一个提示文件(例如implement-from-spec.prompt.md)。 - 创建
docs/feature.spec.md和docs/project.memory.md。 - 连接 MCP(至少 GitHub MCP)通过
.vscode/mcp.json。 - 在 VS Code 中运行工作流:
/implement-from-spec— 检查 — PR。 - (可选)通过 Copilot CLI 在 CI 中添加简单的 AI 审查,并设置严格的 deny/allow 列表。
12) 问答(FAQ)
Q: 如何确保 Copilot “看到”我的指令? A: 检查回复中的 summary/References;同时保持规则简短具体。
Q: 是否可以将参数动态传递给提示文件?
A: 是的,通常通过占位符变量(如 ${prNumber})或在聊天中运行 /prompt 时通过文本请求。
Q: 应该在哪里存储 MCP 的密钥?
A: 在 GitHub Environments 或本地密钥管理器中;不要放在 .prompt.md/.instructions.md 中。
Q: 如何选择:聊天模式还是提示文件? A: 聊天模式定义了“框架”(模型/工具/角色)。提示文件是该框架内的“脚本”。
13) 后续步骤
- 为你最常用的手动流程添加第二个提示文件。
- 在所有架构决策之后,将
project.memory.md设置为必填项。 - 逐渐将集体知识迁移到
*.context.md并在提示文件中引用它们。
附录 A — 快速入门模板
所有键、路径和标志均符合文档(2025 年 10 月 28 日)。
/.github/copilot-instructions.md — 整个代码库的规则
1# Repository coding standards
2- Build: `npm ci && npm run build`
3- Tests: `npm run test` (coverage ≥ 80%)
4- Lint/Typecheck: `npm run lint && npm run typecheck`
5- Commits: Conventional Commits; keep PRs small and focused
6- Docs: update `CHANGELOG.md` in every release PR
/.github/instructions/frontend.instructions.md — 特定路径指令
1---
2applyTo: "apps/web/**/*.{ts,tsx},packages/ui/**/*.{ts,tsx}"
3---
4- React: function components and hooks
5- State: Zustand; data fetching with TanStack Query
6- Styling: Tailwind CSS; avoid inline styles except dynamic cases
7- Testing: Vitest + Testing Library; avoid unstable snapshots
/.github/instructions/backend.instructions.md — 特定路径指令
1---
2applyTo: "services/api/**/*.{ts,js},packages/server/**/*.{ts,js}"
3---
4- HTTP: Fastify; version APIs under `/v{N}`
5- DB access: Prisma; migrations via `prisma migrate`
6- Security: schema validation (Zod), rate limits, audit logs
7- Testing: integration tests via `vitest --config vitest.integration.ts`
/.github/instructions/actions.instructions.md — GitHub Actions
1---
2applyTo: ".github/workflows/**/*.yml"
3---
4- Keep jobs small; reuse via composite actions
5- Cache: `actions/setup-node` + built-in cache for npm/pnpm
6- Secrets: only through GitHub Environments; never hardcode
/.github/chatmodes/plan.chatmode.md — 自定义聊天模式
1---
2description: "Plan - analyze code/specs and propose a plan; read-only tools"
3model: GPT-4o
4tools:
5 - "search/codebase"
6---
7In this mode:
8- Produce a structured plan with risks and unknowns
9- Do not edit files; output a concise task list instead
/.github/prompts/security-review.prompt.md — 提示文件
1---
2mode: 'agent'
3model: GPT-4o
4tools: ['search/codebase']
5description: 'Perform a security review of a pull request'
6---
7Goal: Review PR ${input:prNumber} for common security issues.
8
9Checklist:
10- Authentication/authorization coverage
11- Input validation and output encoding (XSS/SQLi)
12- Secret management and configuration
13- Dependency versions and known CVEs
14
15Output:
16- A Markdown table: issue | file | line | severity | fix
17- If trivial, include a unified diff suggestion
/.github/prompts/implement-from-spec.prompt.md — 提示文件
1---
2mode: 'agent'
3model: GPT-4o
4tools: ['search/codebase']
5description: 'Implement a feature from a spec'
6---
7Your task is to implement the feature described in @docs/feature.spec.md.
8
9Steps:
101) Read @docs/feature.spec.md and summarize the plan
112) List files to add or modify
123) Propose code changes; ask before installing new dependencies
134) Generate minimal tests and run them
14
15Validation gates:
16- Build, tests, lint/typecheck must pass
17- Provide a TODO list for anything deferred
/.github/prompts/refactor-slice.prompt.md — 提示文件
1---
2mode: 'agent'
3model: GPT-4o
4description: 'Refactor a specific code slice without changing behavior'
5---
6Goal: Improve readability and reduce side effects in @src/feature/* while keeping behavior unchanged.
7Criteria: fewer side effects, clearer structure, all tests pass.
/.github/prompts/test-gen.prompt.md — 提示文件
1---
2mode: 'agent'
3model: GPT-4o-mini
4description: 'Generate tests for a given file/module'
5---
6Ask the user to @-mention the target file; generate unit/integration tests and edge cases.
/docs/feature.spec.md — 规范模板
1# Feature: Export report to CSV
2Goal: Users can export the filtered table to CSV.
3Acceptance criteria:
4- "Export CSV" button on /reports
5- Server generates file ≤ 5s for 10k rows
6- Column order/headers match UI; locale-independent values
7Edge cases: empty values, large numbers, special characters
8Non-goals: XLSX, multi-column simultaneous filters
/.vscode/mcp.json — 最小 MCP 配置
1{
2 "servers": {
3 "github-mcp": {
4 "type": "http",
5 "url": "https://api.githubcopilot.com/mcp"
6 }
7 }
8}
附录 B — 操作补充(CLI & CI 示例)
这些示例补充了附录 A;它们描述了在执行/自动化中的使用,并且不重复上述模板。
Copilot CLI — 安全的工具权限(交互式 / CI)
1# 在你的代码库中启动交互式会话
2copilot
3
4# 允许/禁止特定工具(精确标志遵循 GitHub 文档)
5copilot --allow-tool "shell(npm run test:*)" --deny-tool "shell(rm*)"
6
7# 在非交互式模式下运行提示文件(示例)
8copilot <<'EOF'
9/security-review prNumber=123
10EOF
GitHub Actions — 在 PR 中评论审查结果
1name: AI Security Review (Copilot CLI)
2on:
3 pull_request:
4 types: [opened, synchronize, reopened]
5
6jobs:
7 review:
8 runs-on: ubuntu-latest
9 permissions:
10 contents: read
11 pull-requests: write
12 steps:
13 - uses: actions/checkout@v4
14 - uses: actions/setup-node@v4
15 with:
16 node-version: 22
17 - name: Install Copilot CLI
18 run: npm install -g @github/copilot
19 - name: Run security review prompt
20 env:
21 PR: ${{ github.event.pull_request.number }}
22 run: |
23 copilot --allow-tool "shell(npm run test:*)" --deny-tool "shell(rm*)" <<'EOF'
24 /security-review prNumber=${PR}
25 EOF
26 - name: Post results
27 run: |
28 gh pr comment ${{ github.event.pull_request.number }} --body "Copilot review completed. See artifacts/logs for details."
14) 在现有项目上设置上下文
本节解决了具体问题:你选择一个已有的活跃项目,并在一轮操作中为其创建完整的上下文和 GitHub Copilot 指令。我们不凭空捏造——所有内容都来自代码中已有的信息。
每个步骤都是一个在 VS Code Agent 模式下运行的提示。每个后续步骤都依赖于前一个步骤的结果,因此顺序很重要。
14.1. 步骤 1 — 项目审计
目标: 获取客观的项目地图。没有它,后续一切都是猜测。
操作: 打开 Copilot Chat,选择 Agent 模式,通过 @ 附加根目录,然后运行:
1@/
2
3Analyze the structure of this project. Determine:
4
5- stack: language, frameworks, package manager
6- build, test, lint commands (exact ones, from package.json / pom.xml / Makefile etc.)
7- existing CI workflows (.github/workflows) — what runs there
8- main directories and their purpose
9- existing configurations: lint, prettier, typescript, and similar
10
11Return the result as a structured list.
12Do not invent anything — only what is actually visible in the files.
结果: 保存响应——它将在第 2 步中使用。这是“初始地图”,后续所有工作的质量都取决于它。
14.2. 步骤 2 — 生成全局指令
目标: 创建 .github/copilot-instructions.md——整个代码库的统一规则来源。
操作: 获取第 1 步的结果并运行:
1Based on this project audit:
2
3[paste the result from step 1]
4
5Create the file .github/copilot-instructions.md
6
7Requirements:
8- only facts from the audit, nothing invented
9- build, test, lint commands — exact, copied from configs
10- code style — only if prettier/eslint config exists, and only what's fixed there
11- commit-policy — only if commitlint or similar exists
12- 8–12 points maximum
13- each point — one specific line
结果: .github/copilot-instructions.md 文件已创建并保存在工作目录中。
14.3. 步骤 3 — 生成特定路径指令
目标: 为代码的不同区域创建单独的规则,这些规则通过路径模式自动附加。
何时需要: 如果项目中至少有两个逻辑上独立的区域——前端和后端,apps 和 packages,多个服务。如果项目是同质的——跳过此步骤。
操作: 对于每个区域,附加相应的文件夹并运行单独的提示。以下是前端的示例:
1@src/components/
2@src/pages/
3
4Analyze this part of the project and determine:
5
6- which framework is used and how components are written
7- state management patterns (if visible)
8- how tests are structured (if any)
9- import and file naming styles
10
11Create the file .github/instructions/frontend.instructions.md
12
13Requirements:
14- applyTo — exact glob covering only these folders
15- rules — only from what you see in the code
16- do not duplicate what's already in copilot-instructions.md
17- no more than 6–8 points
如果存在后端,则对后端运行类似的提示,并附带相应的文件夹在 @ 中。
结果: 每个区域的 .github/instructions/ 目录下的文件。
14.4. 步骤 4 — 生成项目参考
目标: 创建 docs/project.context.md——一个稳定的参考信息,可以减少聊天中的“噪音”,并且不需要在每次更改时都更新。
操作:
1@/
2@README.md
3@package.json
4
5Create the file docs/project.context.md —
6this is project context for the AI assistant.
7
8Include:
9- brief description: what the project does, for whom
10- key architectural patterns, if visible in folder structure and imports
11- external dependencies and their roles (why these specific ones, if clear from context)
12- what NOT to do: deprecated folders, outdated patterns, known limitations
13
14Limitations:
15- max 30–40 lines
16- only what is objectively visible in the project
17- no assumptions or recommendations
结果: docs/project.context.md 文件。
14.5. 步骤 5 — 生成项目记忆
目标: 记录已做出的决策,以便代理不再重复纠结于此。
操作:
1@/
2
3Look at the project and find decisions that have already been documented in the code:
4
5- library choices — if obvious alternatives are visible in lock files or comments
6- folder structure — if it's non-standard for this stack
7- any TODO or FIXME that has context explaining why
8- configurations with explanatory comments
9
10Create the file docs/project.memory.md in the format:
11
12## [date or "unknown"] | Decision | Why
13
14Each entry — max 2 lines.
15No more than 10–12 entries.
16Only what is actually visible.
结果: docs/project.memory.md 文件。
14.6. 步骤 6 — 第一个提示文件
目标: 为最常见的任务创建一个可用的提示。不必一次创建所有五个模板——从一个开始,然后根据需要添加。
何时使用哪个提示: 如果团队更常实现新功能,则使用 implement-from-spec。如果更常审查 PR,则使用 security-review。选择每天都用到的。
操作(以 implement-from-spec 为例):
1@.github/copilot-instructions.md
2
3Create the file .github/prompts/implement-from-spec.prompt.md
4for this project.
5
6Requirements:
7- mode: agent
8- tools: only search/codebase
9- steps should use build and test commands
10 from copilot-instructions.md
11- validation gates: build, tests, lint must pass
12- description — one line
结果: .github/prompts/implement-from-spec.prompt.md 文件,已根据项目特定堆栈进行了调整。
14.7. 总结和后续操作
在完成这六个步骤后,代码库中将包含:
1.github/
2 copilot-instructions.md ← global rules (step 2)
3 instructions/
4 frontend.instructions.md ← frontend rules (step 3)
5 backend.instructions.md ← backend rules (step 3)
6 prompts/
7 implement-from-spec.prompt.md ← first prompt (step 6)
8docs/
9 project.context.md ← project context (step 4)
10 project.memory.md ← decision memory (step 5)
这是一个最基本的可用设置。之后,可以进行迭代:
- 随着新的典型任务出现,添加提示文件。
- 在每个架构决策之后更新
project.memory.md。 - 当开始注意到不同工作阶段相互干扰时,添加聊天模式。
- 只有在基本上下文运行正常后,才连接 MCP。
以上所有内容都可以在一个工作会话中完成。每个提示都可以连续运行,无需手动切换文件——代理会自动在工作目录中创建文件。
来源
🙌 PS:
感谢您阅读到最后!如果您觉得本文有用,我们很乐意看到您的:
技术变得更容易理解。您已经迈出了重要的一步 💪