Engineering teams adopting GitHub Copilot often face an early consistency hurdle: without shared guidelines, Copilot generates code based solely on generic training data and local file context. One engineer gets JavaScript-style callbacks in a TypeScript project, another receives deprecated ORM syntax, and a third sees architectural layering violated across pull requests.
GitHub Copilot solves this problem at scale through repository custom instructions. By placing version-controlled markdown files directly in the repository—primarily .github/copilot-instructions.md and scoped .github/instructions/**/*.instructions.md files—teams can inject architectural boundaries, linting preferences, security standards, and testing patterns straight into every Copilot interaction across the engineering organization.
This guide walks through how repository custom instructions work, how to configure repository-wide and path-scoped rules, how to activate automated enforcement in pull request code reviews, and the best practices engineering leads must follow to keep instructions effective without overloading context windows.
Where Custom Instructions Apply (and Where They Do Not)
Before writing rules, teams must understand how GitHub Copilot ingests custom instructions across different features.
Custom instructions are automatically prepended to the prompt payload sent to underlying LLMs during higher-level reasoning workflows:
- Copilot Chat in IDEs: VS Code, Visual Studio, JetBrains IDEs (IntelliJ IDEA, PyCharm, WebStorm), Xcode, and Eclipse.
- GitHub.com Surfaces: Copilot Chat on web repositories, Copilot cloud agent tasks, and automated pull request generation.
- Copilot Code Review: Automated pull request reviews on GitHub.com evaluate incoming diffs against your custom instructions.
- Copilot CLI: Terminal-based assistance in developer shell environments.
The Autocomplete (Ghost Text) Distinction
Custom instruction files do not reliably control millisecond-latency inline autocomplete (ghost text). Ghost text uses localized context—open editor tabs, neighboring files, and cursor proximity—to minimize latency. Custom instructions primarily govern Copilot Chat, inline refactoring prompts (/fix, /explain), autonomous agent sessions, and pull request reviews. For strict syntax formatting in inline autocomplete, pair Copilot with deterministic local linters and formatters (such as ESLint, Biome, or Prettier) rather than relying on natural language prompts alone.
Instruction Precedence Hierarchy
When multiple instruction layers exist, GitHub Copilot combines them using a defined order of precedence:
- Personal instructions: Individual user preferences set in Copilot Chat settings (highest precedence).
- Path-specific repository instructions: Rules defined in
.github/instructions/**/*.instructions.mdmatching active files via glob patterns. - Repository-wide custom instructions: The global
.github/copilot-instructions.mdfile. - Agent instructions: Instructions declared in
AGENTS.md,CLAUDE.md, orGEMINI.md. - Organization custom instructions: Policy-level instructions configured by GitHub organization administrators across all company repositories.
Step 1: Create Repository-Wide Instructions (.github/copilot-instructions.md)
The foundational configuration file lives at the root of your Git repository:
mkdir -p .github
touch .github/copilot-instructions.md
This file applies to every Copilot prompt submitted within the workspace. To maximize AI comprehension, structure the file with crisp markdown headings, bulleted technical constraints, and positive behavioral rules.
Essential Sections for Engineering Teams
- Project Overview & Architecture: State what the project does, the architectural pattern (e.g., Clean Architecture, Modular Monolith, Hexagonal), and directional boundary rules (e.g., "Domain layers must never import persistence or UI models").
- Language Versions & Key Tooling: Pin specific framework versions (e.g., "Node.js 22 LTS, TypeScript 5.5, Next.js 15 with App Router").
- Coding Standards & Patterns: State explicit naming conventions, error handling mechanisms (e.g., "Use Result types instead of throwing unhandled exceptions"), and immutability practices.
- Testing Expectations: Specify the test runner (e.g., Vitest, Jest, PyTest), testing philosophy (AAA pattern), and required test coverage for new business logic.
- Security & Input Validation: Mandate sanitization libraries (e.g., Zod, Pydantic), parameterized database queries, and credential handling policies.
Production-Ready Example: TypeScript & Next.js Service
# Repository Architecture and Coding Standards
## Project Overview
This repository contains the Core Billing Service, built as a modular Next.js and Node.js microservice communicating with PostgreSQL and Stripe.
## Architectural Boundaries
- Strict Layer Separation: UI Components (`/app`, `/components`) -> Application Services (`/src/services`) -> Domain Models (`/src/domain`) -> Data Repositories (`/src/infrastructure`).
- Domain logic must remain framework-agnostic. Never import `next/*` or database drivers inside `/src/domain`.
- All database queries must run through Prisma repositories located in `/src/infrastructure/repositories`. Direct SQL queries outside migration files are prohibited.
## TypeScript Standards
- TypeScript 5.x in strict mode. Never use `any`; use `unknown` with narrowing or explicit Zod schemas.
- Prefer `type` aliases for object definitions and unions; use `interface` only for extensible contracts.
- Always handle async errors with explicit `Result<T, E>` types or structured error objects. Do not allow uncaught Promise rejections.
- Use early returns and guard clauses to minimize nested conditional branching.
## State and Data Fetching
- For client-side fetching, use TanStack Query (`@tanstack/react-query`). Do not trigger unmemoized `useEffect` hooks for API calls.
- Server Actions must validate incoming payloads using Zod schemas before calling domain services.
## Testing Standards
- Test runner: Vitest with React Testing Library.
- Unit tests must be co-located with implementation files (`*.spec.ts` or `*.spec.tsx`).
- Arrange-Act-Assert (AAA) structure is required in every test suite.
- Mock network boundaries with Mock Service Worker (MSW); do not mock internal language utilities or utility classes.
## Commands Reference
- Run test suite: `pnpm test`
- Type checking: `pnpm typecheck`
- Linter and style check: `pnpm lint`
Step 2: Configure Path-Specific Custom Instructions (.github/instructions/)
In large monorepos or multi-tiered applications, a single global instruction file can dilute Copilot's attention or exceed token budgets. For instance, frontend React styling standards have no relevance when an engineer modifies a Go microservice or SQL database migration.
Path-specific instructions solve this by scoping rules to matching glob patterns.
Directory Structure
Store path-scoped instruction files in .github/instructions/:
.github/
├── copilot-instructions.md
└── instructions/
├── frontend.instructions.md
├── backend.instructions.md
└── migrations.instructions.md
File Syntax with Frontmatter
Every path-specific file must end with .instructions.md and include a YAML frontmatter block with the applyTo keyword:
---
applyTo: "apps/web/**/*.{ts,tsx}"
---
# Frontend Component Standards
- Components must be functional components with named exports.
- Use Tailwind CSS utility classes; avoid inline CSS style objects.
- Ensure all interactive elements include valid `aria-*` attributes and keyboard navigation.
- For icons, import exclusively from `lucide-react`.
Advanced Glob Scoping
**/*.py: Applies to all Python files in any directory.services/billing/**/*.go: Applies recursively to billing service Go code.**/*.test.ts,**/*.spec.ts: Applies to all TypeScript test files.
Excluding Specific Agents
If a rule set is intended solely for GitHub Cloud Agent workflows and should not trigger during automated code review (or vice versa), use excludeAgent:
---
applyTo: "**"
excludeAgent: "code-review"
---
# Autonomous Cloud Agent Build & Migration Runbook
- Run `pnpm db:migrate` before executing integration test suites.
- Check `.env.example` when scaffolding new configuration parameters.
Step 3: Enforce Instructions in GitHub Pull Request Code Reviews
Repository custom instructions do not stop at interactive development. Engineering leadership can enforce these standards automatically during code reviews performed by Copilot.
Enabling Code Review Integration
- On GitHub.com, navigate to your repository.
- Select Settings (under repository administration).
- In the left sidebar, navigate to Code, planning, and automation -> Copilot -> Code review.
- Enable the toggle for Use custom instructions when reviewing pull requests.
How Branch Evaluation Works
When reviewing a pull request, Copilot reads .github/copilot-instructions.md and relevant .instructions.md files from the head branch (the PR branch), not the base target branch (main).
This mechanism provides a crucial workflow advantage: when your platform team refines coding standards or adds architectural rules, you can create a pull request containing both the instruction file updates and the code changes adhering to them. Copilot immediately evaluates the PR diff against the updated rules before they are merged into main.
Step 4: Verify Custom Instructions in Developer Workspaces
To confirm that Copilot is reading repository custom instructions during daily development:
- Verify IDE Settings:
- In VS Code, open Settings (
Ctrl+,orCmd+,), search forinstruction file, and verify that Code Generation: Use Instruction Files is checked (enabled by default). - In JetBrains IDEs, open the Copilot Chat panel, click the settings gear icon, and select Customizations to view active instruction files.
- In VS Code, open Settings (
- Inspect the Chat References List:
- Submit a query in Copilot Chat (for example, "Create a customer verification service").
- Expand the References section at the top of Copilot's response.
- If configured correctly,
.github/copilot-instructions.md(and any matching.instructions.mdfile) appears with a file link, indicating that the AI conditioned its response on team standards.
Engineering Best Practices & Traps to Avoid
| Recommended Practice | High-Risk Mistake | Impact on Team Velocity |
|---|---|---|
| Focus on high-signal architectural constraints | Pasting 20-page employee style guides into markdown | Exhausts LLM context window; AI misses primary rules |
| Use clear, affirmative constraints ("Use Zod for input validation") | Vague or negative aphorisms ("Write clean, robust code") | Generates generic, inconsistent suggestions |
Segment monorepo domains with .instructions.md globs | Forcing frontend, mobile, and backend rules into a single global file | Contradictory rules confuse generation across languages |
| Pair instructions with deterministic CI linters and test suites | Relying on Copilot as the sole gatekeeper for project standards | Non-deterministic AI allows edge-case rule violations |
| Commit instructions to Git and review changes via PR | Treating instructions as local workstation scratchpads | Inconsistent developer environment configurations across teams |
Complementing with Prompt Files (.github/prompts/*.prompt.md)
While custom instructions define constant project constraints, engineering teams often have repeatable workflows—such as scaffolding a new API route, writing migration scripts, or generating unit test matrices.
For task-specific workflows, combine repository instructions with Copilot Prompt Files stored in .github/prompts/*.prompt.md. Prompt files allow developers to trigger pre-packaged, multi-step prompt templates inside Copilot Chat (via the paperclip context icon or slash commands), while the underlying .github/copilot-instructions.md ensures the generated output conforms to global team standards.
Summary Checklist for Engineering Leads
- Create
.github/copilot-instructions.mdcontaining core architecture, pinned dependency versions, and non-negotiable coding conventions. - Create
.github/instructions/**/*.instructions.mdfiles with frontmatterapplyToglobs for specialized subdirectories or language targets. - Turn on "Use custom instructions when reviewing pull requests" in GitHub Repository Settings.
- Verify references in Copilot Chat to ensure files are actively loaded.
- Review and update instruction files regularly alongside framework updates and architectural evolution.
References
- Adding repository custom instructions for GitHub Copilot - GitHub Docs
- Adding repository custom instructions for GitHub Copilot in your IDE - GitHub Docs
- Support for different types of custom instructions - GitHub Docs
- About customizing GitHub Copilot responses - GitHub Docs
- 5 tips for writing better custom instructions for Copilot - The GitHub Blog