diff --git a/website/astro.config.mjs b/website/astro.config.mjs index 87c9e4e6..34ac6f16 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -7,6 +7,9 @@ export default defineConfig({ base: "/awesome-copilot/", output: "static", integrations: [sitemap()], + redirects: { + "/samples/": "/learning-hub/cookbook/", + }, build: { assets: "assets", }, diff --git a/website/public/styles/global.css b/website/public/styles/global.css index 5a5d4a64..3029280b 100644 --- a/website/public/styles/global.css +++ b/website/public/styles/global.css @@ -1587,3 +1587,326 @@ a:hover { background-color: rgba(210, 153, 34, 0.2); color: var(--color-warning); } + +/* Learning Hub - Sidebar Layout */ +.learning-hub-layout { + display: grid; + grid-template-columns: 240px 1fr; + gap: 48px; + align-items: start; +} + +.learning-hub-sidebar { + position: sticky; + top: calc(var(--header-height) + 24px); + max-height: calc(100vh - 48px); + overflow-y: auto; +} + +.sidebar-section { + margin-bottom: 24px; +} + +.sidebar-section h3 { + font-size: 11px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--color-text-muted); + margin-bottom: 8px; + padding: 0 12px; +} + +.sidebar-nav-list { + list-style: none; + padding: 0; + margin: 0; +} + +.sidebar-nav-list li { + margin: 0; +} + +.sidebar-nav-list a { + display: block; + padding: 6px 12px; + font-size: 13px; + line-height: 1.4; + color: var(--color-text-muted); + text-decoration: none; + border-radius: 6px; + border-left: 2px solid transparent; + transition: color 0.15s, background-color 0.15s, border-color 0.15s; +} + +.sidebar-nav-list a:hover { + color: var(--color-text); + background-color: var(--color-glass); +} + +.sidebar-nav-list a.active { + color: var(--color-text-emphasis); + background-color: var(--color-glass); + border-left-color: var(--color-accent); + font-weight: 600; +} + +@media (max-width: 900px) { + .learning-hub-layout { + grid-template-columns: 1fr; + gap: 0; + } + + .learning-hub-sidebar { + position: static; + max-height: none; + border-bottom: 1px solid var(--color-border); + padding-bottom: 20px; + margin-bottom: 32px; + } +} + +/* Learning Hub - Article Styles */ +.breadcrumb { + margin-bottom: 16px; +} + +.breadcrumb a { + color: var(--color-link); + text-decoration: none; + font-size: 14px; +} + +.breadcrumb a:hover { + color: var(--color-link-hover); + text-decoration: underline; +} + +.article-meta { + display: flex; + gap: 16px; + margin-top: 12px; + flex-wrap: wrap; +} + +.meta-item { + font-size: 14px; + color: var(--color-text-muted); +} + +.article-tags { + display: flex; + gap: 8px; + margin-top: 12px; + flex-wrap: wrap; +} + +.tag { + font-size: 12px; + padding: 4px 10px; + border-radius: 12px; + background-color: var(--color-glass); + border: 1px solid var(--color-glass-border); + color: var(--color-text-muted); +} + +/* Article prose content */ +.article-content { + max-width: 780px; + line-height: 1.75; + font-size: 16px; + color: var(--color-text); +} + +.article-content h2 { + font-size: 24px; + font-weight: 700; + margin-top: 48px; + margin-bottom: 16px; + color: var(--color-text-emphasis); + border-bottom: 1px solid var(--color-border); + padding-bottom: 8px; +} + +.article-content h3 { + font-size: 20px; + font-weight: 600; + margin-top: 32px; + margin-bottom: 12px; + color: var(--color-text-emphasis); +} + +.article-content h4 { + font-size: 16px; + font-weight: 600; + margin-top: 24px; + margin-bottom: 8px; + color: var(--color-text-emphasis); +} + +.article-content p { + margin-bottom: 16px; +} + +.article-content a { + color: var(--color-link); + text-decoration: none; +} + +.article-content a:hover { + color: var(--color-link-hover); + text-decoration: underline; +} + +.article-content ul, +.article-content ol { + margin-bottom: 16px; + padding-left: 24px; +} + +.article-content li { + margin-bottom: 6px; +} + +.article-content code { + font-size: 14px; + padding: 2px 6px; + border-radius: 4px; + background-color: var(--color-bg-tertiary); + border: 1px solid var(--color-border); + font-family: 'Monaspace Argon NF', monospace; +} + +.article-content pre { + margin-bottom: 16px; + padding: 16px; + border-radius: 8px; + background-color: var(--color-bg-secondary); + border: 1px solid var(--color-border); + overflow-x: auto; +} + +.article-content pre code { + padding: 0; + border: none; + background: none; + font-size: 14px; + line-height: 1.6; +} + +.article-content blockquote { + margin: 16px 0; + padding: 12px 20px; + border-left: 4px solid var(--color-accent); + background-color: var(--color-glass); + border-radius: 0 8px 8px 0; + color: var(--color-text-muted); +} + +.article-content blockquote p { + margin-bottom: 0; +} + +.article-content hr { + margin: 32px 0; + border: none; + border-top: 1px solid var(--color-border); +} + +.article-content strong { + color: var(--color-text-emphasis); +} + +.article-content table { + width: 100%; + border-collapse: collapse; + margin: 16px 0; + font-size: 14px; +} + +.article-content th, +.article-content td { + padding: 10px 14px; + text-align: left; + border: 1px solid var(--color-border); +} + +.article-content th { + font-weight: 600; + color: var(--color-text-emphasis); + background-color: var(--color-glass); +} + +.article-content tr:hover { + background-color: var(--color-glass); +} + +/* Learning Hub - Index Page */ +.learning-hub-section h2 { + font-size: 24px; + font-weight: 700; + margin-bottom: 8px; + color: var(--color-text-emphasis); +} + +.section-description { + font-size: 16px; + color: var(--color-text-muted); + margin-bottom: 24px; +} + +.article-list { + display: flex; + flex-direction: column; + gap: 16px; +} + +.article-card { + display: flex; + gap: 20px; + padding: 20px; + border-radius: 12px; + background-color: var(--color-card-bg); + border: 1px solid var(--color-glass-border); + text-decoration: none; + color: var(--color-text); + transition: background-color 0.2s, border-color 0.2s; +} + +.article-card:hover { + background-color: var(--color-card-hover); + border-color: var(--color-accent); +} + +.article-number { + display: flex; + align-items: center; + justify-content: center; + width: 40px; + height: 40px; + border-radius: 50%; + background: var(--gradient-accent); + color: #fff; + font-weight: 700; + font-size: 16px; + flex-shrink: 0; +} + +.article-info { + flex: 1; + min-width: 0; +} + +.article-info h3 { + font-size: 18px; + font-weight: 600; + margin-bottom: 6px; + color: var(--color-text-emphasis); +} + +.article-info p { + font-size: 14px; + color: var(--color-text-muted); + margin-bottom: 8px; + line-height: 1.5; +} diff --git a/website/src/config/learning-hub.ts b/website/src/config/learning-hub.ts new file mode 100644 index 00000000..0fbe9dc2 --- /dev/null +++ b/website/src/config/learning-hub.ts @@ -0,0 +1,20 @@ +// Shared article ordering for the Learning Hub. +// Used by both the index page and the article sidebar layout. + +export const fundamentalsOrder = [ + 'what-are-agents-skills-instructions', + 'understanding-copilot-context', + 'copilot-configuration-basics', + 'defining-custom-instructions', + 'creating-effective-skills', + 'building-custom-agents', + 'understanding-mcp-servers', + 'automating-with-hooks', + 'using-copilot-coding-agent', + 'installing-and-using-plugins', + 'before-after-customization-examples', +]; + +export const referenceOrder = [ + 'github-copilot-terminology-glossary', +]; diff --git a/website/src/content.config.ts b/website/src/content.config.ts new file mode 100644 index 00000000..78738c96 --- /dev/null +++ b/website/src/content.config.ts @@ -0,0 +1,20 @@ +import { defineCollection, z } from "astro:content"; +import { glob } from "astro/loaders"; + +const learningHub = defineCollection({ + loader: glob({ pattern: "**/*.md", base: "./src/content/learning-hub" }), + schema: z.object({ + title: z.string(), + description: z.string(), + authors: z.array(z.string()).optional(), + lastUpdated: z.string().optional(), + estimatedReadingTime: z.string().optional(), + tags: z.array(z.string()).optional(), + relatedArticles: z.array(z.string()).optional(), + prerequisites: z.array(z.string()).optional(), + }), +}); + +export const collections = { + "learning-hub": learningHub, +}; diff --git a/website/src/content/learning-hub/automating-with-hooks.md b/website/src/content/learning-hub/automating-with-hooks.md new file mode 100644 index 00000000..79be9dd0 --- /dev/null +++ b/website/src/content/learning-hub/automating-with-hooks.md @@ -0,0 +1,354 @@ +--- +title: 'Automating with Hooks' +description: 'Learn how to use hooks to automate lifecycle events like formatting, linting, and governance checks during Copilot agent sessions.' +authors: + - GitHub Copilot Learning Hub Team +lastUpdated: '2026-02-26' +estimatedReadingTime: '8 minutes' +tags: + - hooks + - automation + - fundamentals +relatedArticles: + - ./building-custom-agents.md + - ./what-are-agents-skills-instructions.md +prerequisites: + - Basic understanding of GitHub Copilot agents +--- + +Hooks let you run automated scripts at key moments during a Copilot agent session — when a session starts or ends, when the user submits a prompt, or before and after the agent uses a tool. They're the glue between Copilot's AI capabilities and your team's existing tooling: linters, formatters, governance scanners, and notification systems. + +This article explains how hooks work, how to configure them, and practical patterns for common automation needs. + +## What Are Hooks? + +Hooks are shell commands or scripts that run automatically in response to lifecycle events during a Copilot agent session. They execute outside the AI model, they're deterministic, repeatable, and under your full control. + +**Key characteristics**: +- Hooks run as shell commands on the user's machine +- They execute synchronously—the agent waits for them to complete +- They can block actions (e.g., prevent commits that fail linting) +- They're defined in JSON files stored at `.github/hooks/*.json` in your repository +- They receive detailed context via JSON input, enabling context-aware automation +- They can include bundled scripts for complex logic + +### When to Use Hooks vs Other Customizations + +| Use Case | Best Tool | +|----------|-----------| +| Run a linter after every code change | **Hook** | +| Teach Copilot your coding standards | **Instruction** | +| Automate a multi-step workflow | **Skill** or **Agent** | +| Scan prompts for sensitive data | **Hook** | +| Format code before committing | **Hook** | +| Generate tests for new code | **Skill** | + +Hooks are ideal for **deterministic automation** that must happen reliably—things you don't want to depend on the AI remembering to do. + +## Anatomy of a Hook + +Each hook in this repository is a folder containing: + +``` +hooks/ +└── my-hook/ + ├── README.md # Documentation with frontmatter + ├── hooks.json # Hook configuration + └── scripts/ # Optional bundled scripts + └── check.sh +``` + +> Note: Not all of these files are required for a generalised hook implementation. In your own repository, hooks are stored as JSON files in `.github/hooks/` (e.g., `.github/hooks/my-hook.json`). The folder structure above with README.md is specific to the Awesome Copilot repository for documentation purposes. + + +### hooks.json + +The configuration defines which events trigger which commands: + +```json +{ + "version": 1, + "hooks": { + "postToolUse": [ + { + "type": "command", + "bash": "npx prettier --write .", + "cwd": ".", + "timeoutSec": 30 + } + ] + } +} +``` + +## Hook Events + +Hooks can trigger on several lifecycle events: + +| Event | When It Fires | Common Use Cases | +|-------|---------------|------------------| +| `sessionStart` | Agent session begins or resumes | Initialize environments, log session starts, validate project state | +| `sessionEnd` | Agent session completes or is terminated | Clean up temp files, generate reports, send notifications | +| `userPromptSubmitted` | User submits a prompt | Log requests for auditing and compliance | +| `preToolUse` | Before the agent uses any tool (e.g., `bash`, `edit`) | **Approve or deny** tool executions, block dangerous commands, enforce security policies | +| `postToolUse` | After a tool completes execution | Log results, track usage, format code after edits, send failure alerts | +| `agentStop` | Main agent finishes responding to a prompt | Run final linters/formatters, validate complete changes | +| `subagentStop` | A subagent completes before returning results | Audit subagent outputs, log subagent activity | +| `errorOccurred` | An error occurs during agent execution | Log errors for debugging, send notifications, track error patterns | + +> **Key insight**: The `preToolUse` hook is the most powerful — it can **approve or deny** individual tool executions. This enables fine-grained security policies like blocking specific shell commands or requiring approval for sensitive file operations. + +### Event Configuration + +Each hook entry supports these fields: + +```json +{ + "type": "command", + "bash": "./scripts/my-check.sh", + "powershell": "./scripts/my-check.ps1", + "cwd": ".", + "timeoutSec": 10, + "env": { + "CUSTOM_VAR": "value" + } +} +``` + +**type**: Always `"command"` for shell-based hooks. + +**bash**: The command or script to execute on Unix systems. Can be inline or reference a script file. + +**powershell**: The command or script to execute on Windows systems. Either `bash` or `powershell` (or both) must be provided. + +**cwd**: Working directory for the command (relative to repository root). + +**timeoutSec**: Maximum execution time in seconds (default: 30). The hook is killed if it exceeds this limit. + +**env**: Additional environment variables merged with the existing environment. + +### README.md + +The README provides metadata and documentation for the Awesome Copilot repository. While not required in your own implementation, it serves as a useful way to document them for your team. + +```markdown +--- +name: 'Auto Format' +description: 'Automatically formats code using project formatters before commits' +tags: ['formatting', 'code-quality'] +--- + +# Auto Format + +Runs your project's configured formatter (Prettier, Black, gofmt, etc.) +automatically before the agent commits changes. + +## Setup + +1. Ensure your formatter is installed and configured +2. Copy the hooks.json to your `.github/hooks/` directory +3. Adjust the formatter command for your project +``` + +## Practical Examples + +### Auto-Format After Edits + +Ensure all code is formatted after the agent edits files: + +```json +{ + "version": 1, + "hooks": { + "postToolUse": [ + { + "type": "command", + "bash": "npx prettier --write . && git add -A", + "cwd": ".", + "timeoutSec": 30 + } + ] + } +} +``` + +### Lint Check When Agent Completes + +Run ESLint after the agent finishes responding and block if there are errors: + +```json +{ + "version": 1, + "hooks": { + "agentStop": [ + { + "type": "command", + "bash": "npx eslint . --max-warnings 0", + "cwd": ".", + "timeoutSec": 60 + } + ] + } +} +``` + +If the lint command exits with a non-zero status, the action is blocked. + +### Security Gating with preToolUse + +Block dangerous commands before they execute: + +```json +{ + "version": 1, + "hooks": { + "preToolUse": [ + { + "type": "command", + "bash": "./scripts/security-check.sh", + "cwd": ".", + "timeoutSec": 15 + } + ] + } +} +``` + +The `preToolUse` hook receives JSON input with details about the tool being called. Your script can inspect this input and exit with a non-zero code to **deny** the tool execution, or exit with zero to **approve** it. + +### Governance Audit + +Scan user prompts for potential security threats and log session activity: + +```json +{ + "version": 1, + "hooks": { + "sessionStart": [ + { + "type": "command", + "bash": ".github/hooks/governance-audit/audit-session-start.sh", + "cwd": ".", + "timeoutSec": 5 + } + ], + "userPromptSubmitted": [ + { + "type": "command", + "bash": ".github/hooks/governance-audit/audit-prompt.sh", + "cwd": ".", + "env": { + "GOVERNANCE_LEVEL": "standard", + "BLOCK_ON_THREAT": "false" + }, + "timeoutSec": 10 + } + ], + "sessionEnd": [ + { + "type": "command", + "bash": ".github/hooks/governance-audit/audit-session-end.sh", + "cwd": ".", + "timeoutSec": 5 + } + ] + } +} +``` + +This pattern is useful for enterprise environments that need to audit AI interactions for compliance. + +### Notification on Session End + +Send a Slack or Teams notification when an agent session completes: + +```json +{ + "version": 1, + "hooks": { + "sessionEnd": [ + { + "type": "command", + "bash": "curl -X POST \"$SLACK_WEBHOOK_URL\" -H 'Content-Type: application/json' -d '{\"text\": \"Copilot agent session completed\"}'", + "cwd": ".", + "env": { + "SLACK_WEBHOOK_URL": "${input:slackWebhook}" + }, + "timeoutSec": 5 + } + ] + } +} +``` + +## Writing Hook Scripts + +For complex logic, use bundled scripts instead of inline bash commands: + +```bash +#!/usr/bin/env bash +# scripts/pre-commit-check.sh +set -euo pipefail + +echo "Running pre-commit checks..." + +# Format code +npx prettier --write . + +# Run linter +npx eslint . --fix + +# Run type checker +npx tsc --noEmit + +# Stage any formatting changes +git add -A + +echo "Pre-commit checks passed ✅" +``` + +**Tips for hook scripts**: +- Use `set -euo pipefail` to fail fast on errors +- Keep scripts focused—one responsibility per script +- Make scripts executable: `chmod +x scripts/pre-commit-check.sh` +- Test scripts manually before adding them to hooks.json +- Use reasonable timeouts—formatting a large codebase may need 30+ seconds + +## Best Practices + +- **Keep hooks fast**: Hooks run synchronously, so slow hooks delay the agent. Set tight timeouts and optimize scripts. +- **Use non-zero exit codes to block**: If a hook exits with a non-zero code, the triggering action is blocked. Use this for must-pass checks. +- **Bundle scripts in the hook folder**: Keep related scripts alongside the hooks.json for portability. +- **Document setup requirements**: If hooks depend on tools being installed (Prettier, ESLint), document this in the README. +- **Test locally first**: Run hook scripts manually before relying on them in agent sessions. +- **Layer hooks, don't overload**: Use multiple hook entries for independent checks rather than one monolithic script. + +## Common Questions + +**Q: Where do I put hooks configuration files?** + +A: Place them in the `.github/hooks/` directory in your repository (e.g., `.github/hooks/my-hook.json`). You can have multiple hook files — all are loaded automatically. This makes hooks available to all team members. + +**Q: Can hooks access the user's prompt text?** + +A: Yes, for `userPromptSubmitted` events the prompt content is available via JSON input to the hook script. Other hooks like `preToolUse` and `postToolUse` receive context about the tool being called. See the [GitHub Copilot hooks documentation](https://docs.github.com/en/copilot/concepts/agents/coding-agent/about-hooks) for details. + +**Q: What happens if a hook times out?** + +A: The hook is terminated and the agent continues. Set `timeoutSec` appropriately for your scripts. + +**Q: Can I have multiple hooks for the same event?** + +A: Yes. Hooks for the same event run in the order they appear in the array. If any hook fails (non-zero exit), subsequent hooks for that event may be skipped. + +**Q: Do hooks work with the Copilot coding agent?** + +A: Yes. Hooks are especially valuable with the coding agent because they provide deterministic guardrails for autonomous operations. See [Using the Copilot Coding Agent](../using-copilot-coding-agent/) for details. + +## Next Steps + +- **Explore Examples**: Browse the [Hooks Directory](../../hooks/) for ready-to-use hook configurations +- **Build Agents**: [Building Custom Agents](../building-custom-agents/) — Create agents that complement hooks +- **Automate Further**: [Using the Copilot Coding Agent](../using-copilot-coding-agent/) — Run hooks in autonomous agent sessions + +--- diff --git a/website/src/content/learning-hub/before-after-customization-examples.md b/website/src/content/learning-hub/before-after-customization-examples.md new file mode 100644 index 00000000..e514b524 --- /dev/null +++ b/website/src/content/learning-hub/before-after-customization-examples.md @@ -0,0 +1,595 @@ +--- +title: 'Before/After Customization Examples' +description: 'See real-world transformations showing how custom agents, skills, and instructions dramatically improve GitHub Copilot effectiveness.' +authors: + - GitHub Copilot Learning Hub Team +lastUpdated: '2025-12-12' +estimatedReadingTime: '12 minutes' +tags: + - customization + - examples + - fundamentals + - best-practices +relatedArticles: + - ./what-are-agents-skills-instructions.md + - ./creating-effective-skills.md + - ./defining-custom-instructions.md +--- + +The power of GitHub Copilot customization becomes clear when you see concrete examples of how agents, skills, and instructions transform everyday development workflows. This article presents real-world scenarios showing the dramatic difference between default Copilot behavior and customized experiences that align with your team's standards, tools, and practices. + +> Note: The following examples illustrate typical before-and-after scenarios. The actual before and after code may vary depending on the model used and any other context present at generation time. + +## Example 1: API Client Code Generation + +### Before: Generic API Code + +Without customization, GitHub Copilot generates generic HTTP request code that may not follow your team's patterns: + +```typescript +// user-api.ts +async function getUser(userId: string) { + // Default Copilot suggestion + const response = await fetch(`https://api.example.com/users/${userId}`); + const data = await response.json(); + return data; +} +``` + +**Problems**: +- No error handling or retry logic +- Doesn't use existing HTTP client utilities +- Missing type safety +- No logging or telemetry +- Hardcoded base URL + +### After: With Custom Instructions + +Create `.github/instructions/typescript-api.md`: + +````markdown +--- +description: 'API client patterns for our application' +applyTo: '**/*-api.ts, **/services/**/*.ts' +--- + +When generating API client code: +- Always use the HttpClient class from `@/lib/http-client` +- Include proper TypeScript types for request/response +- Add structured error handling with our ApiError class +- Include retry logic for transient failures +- Use environment-based configuration for base URLs +- Add telemetry using our logger utility +- Never hardcode API endpoints + +Example pattern: +```typescript +import { httpClient } from '@/lib/http-client'; +import { ApiError } from '@/lib/errors'; +import { logger } from '@/lib/logger'; + +async function fetchResource(endpoint: string): Promise { + try { + const response = await httpClient.get(endpoint); + logger.debug('API call successful', { endpoint }); + return response.data; + } catch (error) { + logger.error('API call failed', { endpoint, error }); + throw new ApiError('Failed to fetch resource', error); + } +} +``` +```` + +Now Copilot generates code aligned with your team's patterns: + +```typescript +// user-api.ts +import { httpClient } from '@/lib/http-client'; +import { ApiError } from '@/lib/errors'; +import { logger } from '@/lib/logger'; + +interface User { + id: string; + name: string; + email: string; +} + +async function getUser(userId: string): Promise { + try { + const response = await httpClient.get(`/users/${userId}`); + logger.debug('User fetched successfully', { userId }); + return response.data; + } catch (error) { + logger.error('Failed to fetch user', { userId, error }); + throw new ApiError('Unable to retrieve user data', error); + } +} +``` + +**Benefits**: +- Automatically uses your team's HTTP client +- Includes proper error handling and logging +- Type-safe with your interfaces +- Follows team conventions consistently +- No manual corrections needed + +## Example 2: Test Generation + +### Before: Basic Test Structure + +Default Copilot test suggestions are often generic and miss project-specific patterns: + +```typescript +// user-service.test.ts +import { UserService } from './user-service'; + +describe('UserService', () => { + it('should get user by id', async () => { + const service = new UserService(); + const user = await service.getUserById('123'); + expect(user).toBeDefined(); + }); +}); +``` + +**Problems**: +- No test fixtures or factories +- Missing setup/teardown +- Doesn't use testing utilities +- No mocking strategy +- Incomplete assertions + +### After: With Custom Testing Skill + +Create a skill folder `.github/skills/generate-tests/` with a `SKILL.md`: + +````markdown +--- +name: generate-tests +description: 'Generate comprehensive test suites using our testing patterns, including fixtures, setup/teardown, and thorough assertions' +--- + +# generate-tests + +Generate a comprehensive test suite for the selected code following these patterns: + +**Setup Requirements**: +- Use our test factory functions from `@/test/factories` +- Set up database transactions with `setupTestDb()` and `cleanupTestDb()` +- Mock external services using our mock utilities from `@/test/mocks` + +**Test Structure**: +- Group related tests in `describe` blocks +- Use descriptive test names that explain behavior: "should [action] when [condition]" +- Include setup/teardown in `beforeEach`/`afterEach` +- Test happy path, edge cases, and error scenarios + +**Assertions**: +- Use specific assertions, not just `.toBeDefined()` +- Verify all relevant properties of returned objects +- Check error messages and types for failure cases +- Assert side effects (database changes, API calls, events) + +See [references/test-patterns.md](references/test-patterns.md) for standard patterns and [templates/test-template.ts](templates/test-template.ts) for a starter structure. + +**Example Pattern**: +```typescript +import { setupTestDb, cleanupTestDb } from '@/test/setup'; +import { createUser, createPost } from '@/test/factories'; +import { mockApiClient } from '@/test/mocks'; + +describe('UserService', () => { + beforeEach(async () => { + await setupTestDb(); + }); + + afterEach(async () => { + await cleanupTestDb(); + }); + + describe('getUserById', () => { + it('should return user when found', async () => { + const user = await createUser({ name: 'Alice' }); + const service = new UserService(); + + const result = await service.getUserById(user.id); + + expect(result).toEqual({ + id: user.id, + name: 'Alice', + email: expect.any(String) + }); + }); + + it('should throw NotFoundError when user does not exist', async () => { + const service = new UserService(); + + await expect(service.getUserById('nonexistent')) + .rejects.toThrow(NotFoundError); + }); + }); +}); +``` + +Generate tests following this pattern for the selected code. +```` + +Now when you select code and use `/generate-tests`, or when an agent detects a testing need, Copilot produces comprehensive test suites: + +```typescript +// user-service.test.ts +import { setupTestDb, cleanupTestDb } from '@/test/setup'; +import { createUser, createPost } from '@/test/factories'; +import { mockApiClient } from '@/test/mocks'; +import { UserService } from './user-service'; +import { NotFoundError } from '@/lib/errors'; + +describe('UserService', () => { + let service: UserService; + + beforeEach(async () => { + await setupTestDb(); + service = new UserService(); + }); + + afterEach(async () => { + await cleanupTestDb(); + }); + + describe('getUserById', () => { + it('should return user with all properties when found', async () => { + const user = await createUser({ + name: 'Alice Johnson', + email: 'alice@example.com' + }); + + const result = await service.getUserById(user.id); + + expect(result).toEqual({ + id: user.id, + name: 'Alice Johnson', + email: 'alice@example.com', + createdAt: expect.any(Date) + }); + }); + + it('should throw NotFoundError when user does not exist', async () => { + await expect(service.getUserById('nonexistent-id')) + .rejects.toThrow(NotFoundError); + }); + + it('should throw NotFoundError with correct message', async () => { + await expect(service.getUserById('invalid')) + .rejects.toThrow('User not found'); + }); + }); + + describe('getUserPosts', () => { + it('should return all posts for a user', async () => { + const user = await createUser(); + const post1 = await createPost({ userId: user.id, title: 'First Post' }); + const post2 = await createPost({ userId: user.id, title: 'Second Post' }); + + const result = await service.getUserPosts(user.id); + + expect(result).toHaveLength(2); + expect(result[0]).toMatchObject({ title: 'First Post' }); + expect(result[1]).toMatchObject({ title: 'Second Post' }); + }); + + it('should return empty array when user has no posts', async () => { + const user = await createUser(); + + const result = await service.getUserPosts(user.id); + + expect(result).toEqual([]); + }); + }); +}); +``` + +**Benefits**: +- Richer test coverage including edge cases +- Uses team's testing utilities and patterns +- Proper setup/teardown +- Comprehensive assertions +- Ready to run without modifications + +## Example 3: Infrastructure as Code with Terraform + +### Before: Basic Terraform Resources + +Default suggestions lack organization, security best practices, and team conventions: + +```hcl +# main.tf +resource "azurerm_resource_group" "rg" { + name = "my-rg" + location = "eastus" +} + +resource "azurerm_storage_account" "data" { + name = "mystorage" + resource_group_name = azurerm_resource_group.rg.name + location = azurerm_resource_group.rg.location + account_tier = "Standard" + account_replication_type = "LRS" + # Defaults used; public network access allowed +} +``` + +**Problems**: +- No consistent naming aligned to Azure conventions +- Missing tags +- Public network access not blocked; no private endpoint or network rules +- No diagnostic settings for auditing +- Hardcoded values without variables + +### After: With Terraform Custom Agent + +Use a custom agent from the repository [`agents/terraform-azure-implement.agent.md`](https://github.com/github/awesome-copilot/blob/main/agents/terraform-azure-implement.agent.md) (click through to see full definition). + +Now Copilot has access to a custom agent that enforces your organization's Terraform best practices for Azure. + +```hcl +# storage.tf +# Azure Storage Account for application data with secure networking and diagnostics + +locals { + storage_account_name = lower(replace("${var.environment}-${var.project_name}-st-app-data", "-", "")) + + common_tags = { + Environment = var.environment + Project = var.project_name + ManagedBy = "Terraform" + Owner = var.owner_team + CostCenter = var.cost_center + } +} + +resource "azurerm_resource_group" "rg" { + name = "${var.environment}-${var.project_name}-rg" + location = var.location + + tags = merge(local.common_tags, { Name = "${var.environment}-${var.project_name}-rg" }) +} + +resource "azurerm_storage_account" "app_data" { + name = local.storage_account_name + resource_group_name = azurerm_resource_group.rg.name + location = azurerm_resource_group.rg.location + account_tier = "Standard" + account_replication_type = "ZRS" + min_tls_version = "TLS1_2" + public_network_access_enabled = false + + tags = merge(local.common_tags, { + Name = local.storage_account_name + Description = "Application data storage account" + }) +} + +resource "azurerm_log_analytics_workspace" "law" { + name = "${var.environment}-${var.project_name}-law" + location = azurerm_resource_group.rg.location + resource_group_name = azurerm_resource_group.rg.name + sku = "PerGB2018" + retention_in_days = 30 + + tags = local.common_tags +} + +resource "azurerm_monitor_diagnostic_setting" "sa_diagnostics" { + name = "${local.storage_account_name}-diag" + target_resource_id = azurerm_storage_account.app_data.id + log_analytics_workspace_id = azurerm_log_analytics_workspace.law.id + + enabled_log { + category = "StorageRead" + } + + enabled_log { + category = "StorageWrite" + } + + enabled_log { + category = "StorageDelete" + } + + metric { + category = "AllMetrics" + enabled = true + } +} + +output "storage_account_name" { + description = "Name of the application data Storage Account" + value = azurerm_storage_account.app_data.name +} + +output "storage_account_id" { + description = "ID of the application data Storage Account" + value = azurerm_storage_account.app_data.id +} +``` + +**Benefits**: +- Secure-by-default configuration (encryption at rest, TLS 1.2+) +- Follows Azure naming and tagging conventions +- Public access blocked with diagnostics enabled +- Clean separation of resources and outputs +- Ready to extend with private endpoints and CMK if required + +## Example 4: Code Review Comments + +### Before: Manual Review Process + +Developers manually review pull requests and write comments, which can be time-consuming and inconsistent: + +**Manual Process**: +1. Read through code changes +2. Think about potential issues +3. Write detailed feedback +4. Format code suggestions +5. Ensure constructive tone + +Time investment: 20-30 minutes per PR + +### After: With Code Review Skill + +Create a skill folder `skills/review-pr/` with a `SKILL.md`: + +````markdown +--- +name: review-pr +description: 'Generate comprehensive code review with actionable feedback, covering correctness, security, performance, and maintainability' +--- + +# review-pr + +Analyze the current git diff and provide a structured code review with: + +**Structure**: +1. **Summary**: Brief overview of changes +2. **Positive Feedback**: What's done well +3. **Issues Found**: Problems categorized by severity (Critical/Major/Minor) +4. **Suggestions**: Specific improvements with code examples +5. **Questions**: Clarifications needed + +**Review Focus**: +- Code correctness and logic errors +- Security vulnerabilities +- Performance implications +- Test coverage +- Code style and maintainability +- Error handling +- Documentation needs + +**Tone**: +- Be constructive and helpful +- Explain the "why" behind suggestions +- Offer specific fixes, not just critique +- Acknowledge good patterns + +**Format**: +Use markdown with code blocks for suggestions. For each issue, provide: +- Clear description of the problem +- Why it matters +- Suggested fix with code example + +See [references/review-checklist.md](references/review-checklist.md) for the standard review checklist. + +Example format: +## 🔴 Critical Issues + +### Missing Input Validation +**Problem**: The `processUser` function doesn't validate the email format. +**Impact**: Could lead to invalid data in the database. +**Fix**: +```typescript +function processUser(user: User) { + if (!isValidEmail(user.email)) { + throw new ValidationError('Invalid email format'); + } + // ... rest of function +} +``` +```` + +Using this skill on a PR (via `/review-pr` or agent invocation) generates structured, actionable feedback: + +````markdown +## Summary +This PR adds user authentication with JWT tokens. The implementation includes login, token generation, and middleware for protected routes. + +## 🎉 Positive Feedback +- Good separation of concerns with separate auth service and middleware +- Comprehensive error handling in the login flow +- Clear function naming that makes the code self-documenting + +## 🔴 Critical Issues + +### 1. Hardcoded Secret Key +**Problem**: The JWT secret is hardcoded in `auth.service.ts`: +```typescript +const secret = 'my-secret-key'; // ❌ Hardcoded +``` +**Impact**: Security vulnerability - secrets should never be in source code. +**Fix**: +```typescript +const secret = process.env.JWT_SECRET; +if (!secret) { + throw new Error('JWT_SECRET environment variable is required'); +} +``` + +### 2. Missing Password Hashing Salt Rounds +**Problem**: Password hashing uses default bcrypt rounds which may be too low. +**Impact**: Weak password protection if defaults are insufficient. +**Fix**: +```typescript +const SALT_ROUNDS = 12; // Explicit configuration +const hashedPassword = await bcrypt.hash(password, SALT_ROUNDS); +``` + +## ⚠️ Major Issues + +### 3. No Token Expiration Validation +**Problem**: The auth middleware doesn't check token expiration explicitly. +**Impact**: Expired tokens might be accepted if JWT library doesn't verify. +**Fix**: Add explicit expiration check in the middleware. + +## 💡 Suggestions + +### 4. Consider Adding Refresh Tokens +The current implementation uses only access tokens. Consider implementing refresh tokens for better security and user experience: +- Short-lived access tokens (15 minutes) +- Longer-lived refresh tokens (7 days) +- Token rotation on refresh + +### 5. Add Rate Limiting +The login endpoint should have rate limiting to prevent brute force attacks: +```typescript +import rateLimit from 'express-rate-limit'; + +const loginLimiter = rateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 5, // 5 attempts + message: 'Too many login attempts, please try again later' +}); + +app.post('/login', loginLimiter, authController.login); +``` + +## ❓ Questions +1. What's the intended token expiration time for production? +2. Should we implement token revocation for logout functionality? +3. Are there plans for multi-factor authentication in the future? +```` + +**Benefits**: +- Consistent review quality +- Faster review process (5-10 minutes) +- Structured, actionable feedback +- Includes code examples for fixes +- Identifies security issues systematically +- Maintains constructive tone + +## Key Takeaways + +These examples demonstrate how customization transforms GitHub Copilot from a general-purpose assistant into a team-specific expert: + +1. **Instructions** embed your team's patterns into every suggestion automatically +2. **Skills** standardize workflows with bundled resources and enable agent discovery +3. **Agents** bring specialized expertise for complex domains +4. **Combination** of all three creates a comprehensive development assistant + +The investment in creating customizations pays dividends through: +- Faster development with fewer manual corrections +- Consistent code quality across the team +- Automatic adherence to best practices +- Reduced onboarding time for new team members +- Better security and maintainability + + diff --git a/website/src/content/learning-hub/building-custom-agents.md b/website/src/content/learning-hub/building-custom-agents.md new file mode 100644 index 00000000..077bace0 --- /dev/null +++ b/website/src/content/learning-hub/building-custom-agents.md @@ -0,0 +1,303 @@ +--- +title: 'Building Custom Agents' +description: 'Learn how to create specialized GitHub Copilot agents with custom personas, tool integrations, and domain expertise.' +authors: + - GitHub Copilot Learning Hub Team +lastUpdated: '2026-02-26' +estimatedReadingTime: '10 minutes' +tags: + - agents + - customization + - fundamentals +relatedArticles: + - ./what-are-agents-skills-instructions.md + - ./creating-effective-skills.md + - ./understanding-mcp-servers.md +prerequisites: + - Basic understanding of GitHub Copilot chat + - Familiarity with agents, skills, and instructions +--- + +Custom agents are specialized assistants that give GitHub Copilot a focused persona, specific tool access, and domain expertise. Unlike instructions (which apply passively) or skills (which handle individual tasks), agents define a complete working style—they shape how Copilot thinks, what tools it reaches for, and how it communicates throughout an entire session. + +This article shows you how to design, structure, and deploy effective agents for your team's workflows. + +## What Are Custom Agents? + +Custom agents are Markdown files (`*.agent.md`) that configure GitHub Copilot with: + +- **A persona**: The expertise, tone, and working style the agent adopts +- **Tool access**: Which built-in tools and MCP servers the agent can use +- **Guardrails**: Boundaries and conventions the agent follows +- **A model preference**: Which AI model powers the agent (optional but recommended) + +When a user selects a custom agent in VS Code or assigns it to an issue via the Copilot coding agent, the agent's configuration shapes the entire interaction. + +**Key Points**: +- Agents persist across a conversation—they maintain their persona and context +- Agents can invoke tools, run commands, search codebases, and interact with MCP servers +- Multiple agents can coexist in a repository, each serving different workflows +- Agents are stored in `.github/agents/` and are shared with the entire team + +### How Agents Differ from Other Customizations + +**Agents vs Instructions**: +- Agents are explicitly selected; instructions apply automatically to matching files +- Agents define a complete persona; instructions provide passive background context +- Use agents for interactive workflows; use instructions for coding standards + +**Agents vs Skills**: +- Agents are persistent personas; skills are single-task capabilities +- Agents can invoke skills during a conversation +- Use agents for complex multi-step workflows; use skills for focused, repeatable tasks + +## Anatomy of an Agent + +Every agent file has two parts: YAML frontmatter and Markdown instructions. + +### Frontmatter Fields + +```yaml +--- +name: 'Security Reviewer' +description: 'Expert security auditor that reviews code for OWASP vulnerabilities, authentication flaws, and supply chain risks' +model: Claude Sonnet 4 +tools: ['codebase', 'terminal', 'github'] +--- +``` + +**name** (recommended): A human-readable display name for the agent. + +**description** (required): A clear summary of what the agent does. This is shown in the agent picker and helps users find the right agent. + +**model** (recommended): The AI model that powers the agent. Choose based on the complexity of the task—use more capable models for nuanced reasoning. + +**tools** (recommended): An array of built-in tools and MCP servers the agent can access. Common tools include: + +| Tool | Purpose | +|------|---------| +| `codebase` | Search and analyze code across the repository | +| `terminal` | Run shell commands | +| `github` | Interact with GitHub APIs (issues, PRs, etc.) | +| `fetch` | Make HTTP requests to external APIs | +| `edit` | Modify files in the workspace | + +For MCP server tools, reference them by server name (e.g., `postgres`, `docker`). See [Understanding MCP Servers](../understanding-mcp-servers/) for details. + +### Agent Instructions + +After the frontmatter, write Markdown instructions that define the agent's behavior. Structure these clearly: + +````markdown +--- +name: 'API Design Reviewer' +description: 'Reviews API designs for consistency, RESTful patterns, and team conventions' +model: Claude Sonnet 4 +tools: ['codebase', 'github'] +--- + +# API Design Reviewer + +You are an expert API designer who reviews endpoints, schemas, and contracts for consistency and best practices. + +## Your Expertise + +- RESTful API design patterns +- OpenAPI/Swagger specification +- Versioning strategies +- Error response standards +- Pagination and filtering patterns + +## Review Checklist + +When reviewing API changes: + +1. **Naming**: Verify endpoints use plural nouns, consistent casing +2. **HTTP Methods**: Confirm correct verb usage (GET for reads, POST for creates) +3. **Status Codes**: Check appropriate codes (201 for creation, 404 for not found) +4. **Error Responses**: Ensure structured error objects with codes and messages +5. **Pagination**: Verify cursor-based pagination for list endpoints +6. **Versioning**: Confirm API version is specified in the path or header + +## Output Format + +Present findings as: +- 🔴 **Breaking**: Changes that break existing clients +- 🟡 **Warning**: Patterns that should be improved +- 🟢 **Good**: Patterns that follow our conventions +```` + +## Design Patterns + +### The Domain Expert + +Create agents with deep knowledge of a specific technology: + +```markdown +--- +name: 'Terraform Expert' +description: 'Infrastructure-as-code specialist for Terraform on Azure with security-first defaults' +model: Claude Sonnet 4 +tools: ['codebase', 'terminal'] +--- + +You are an expert in Terraform and Azure infrastructure. + +## Principles + +- Security-first: always enable encryption, disable public access by default +- Use variables for all configurable values—never hardcode +- Apply consistent tagging strategy across all resources +- Follow Azure naming conventions: {env}-{project}-{resource-type} +- Include diagnostic settings for all resources that support them +``` + +### The Workflow Automator + +Create agents that execute multi-step processes: + +```markdown +--- +name: 'Release Manager' +description: 'Automates release preparation including changelog generation, version bumping, and tag creation' +model: Claude Sonnet 4 +tools: ['codebase', 'terminal', 'github'] +--- + +You are a release manager who automates the release process. + +## Workflow + +1. Analyze commits since last release using conventional commit format +2. Determine version bump (major/minor/patch) based on commit types +3. Generate changelog from commit messages +4. Update version in package.json / pyproject.toml +5. Create a release summary for the PR description + +## Rules + +- Never skip the changelog step +- Always verify the test suite passes before proceeding +- Ask for confirmation before creating tags or releases +``` + +### The Quality Gate + +Create agents that enforce standards: + +```markdown +--- +name: 'Accessibility Auditor' +description: 'Reviews UI components for WCAG 2.1 AA compliance and accessibility best practices' +model: Claude Sonnet 4 +tools: ['codebase'] +--- + +You are an accessibility expert who reviews UI components for WCAG compliance. + +## Audit Areas + +- Semantic HTML structure +- ARIA attributes and roles +- Keyboard navigation support +- Color contrast ratios (minimum 4.5:1 for text) +- Screen reader compatibility +- Focus management in dynamic content + +## When Reviewing + +- Check every interactive element has an accessible name +- Verify form inputs have associated labels +- Ensure images have meaningful alt text (or empty alt for decorative) +- Test that all functionality is keyboard-accessible +``` + +## Connecting Agents to MCP Servers + +Agents become significantly more powerful when connected to external tools via MCP servers. Reference MCP tools in the `tools` array: + +```yaml +--- +name: 'Database Administrator' +description: 'Expert DBA for PostgreSQL performance tuning, query optimization, and schema design' +tools: ['codebase', 'terminal', 'postgres-mcp'] +--- +``` + +The agent can then query your database, analyze query plans, and suggest optimizations—all within the conversation. For setup details, see [Understanding MCP Servers](../understanding-mcp-servers/). + +## Best Practices + +### Writing Effective Agent Personas + +- **Be specific about expertise**: "Expert in React 18+ with TypeScript" beats "Frontend developer" +- **Define the working style**: Should the agent ask clarifying questions or make assumptions? Should it be concise or thorough? +- **Include guardrails**: What should the agent never do? ("Never modify production configuration files directly") +- **Provide examples**: Show the output format you expect (review comments, code patterns, etc.) + +### Choosing the Right Model + +| Scenario | Recommended Model | +|----------|-------------------| +| Complex reasoning, security review | Claude Sonnet 4 or higher | +| Code generation, refactoring | GPT-4.1 | +| Quick analysis, simple tasks | Claude Haiku or GPT-4.1-mini | +| Large codebase understanding | Models with larger context windows | + +### Organizing Agents in Your Repository + +``` +.github/ +└── agents/ + ├── security-reviewer.agent.md + ├── api-designer.agent.md + ├── terraform-expert.agent.md + └── release-manager.agent.md +``` + +Keep agents focused—one persona per file. If you find an agent trying to do too many things, split it into multiple agents or extract common tasks into skills that agents can invoke. + +## Common Questions + +**Q: How do I select a custom agent?** + +A: In VS Code, open Copilot Chat and use the agent picker dropdown at the top of the chat panel. Your custom agents appear alongside built-in options. You can also `@mention` an agent by name. + +**Q: Can agents use skills?** + +A: Yes. Agents can discover and invoke skills during a conversation based on the user's intent. Skills extend what an agent can do without bloating the agent's own instructions. + +**Q: How many agents should a repository have?** + +A: Start with 2–3 agents for your most common workflows. Add more as patterns emerge. Typical teams have 3–8 agents covering areas like code review, infrastructure, testing, and documentation. + +**Q: Can I use an agent with the Copilot coding agent?** + +A: Yes. When you assign an issue to Copilot, you can specify which agent should handle it. The agent's persona and tool access apply to the autonomous coding session. See [Using the Copilot Coding Agent](../using-copilot-coding-agent/) for details. + +**Q: Should agents include code examples?** + +A: Yes, when defining output format or coding patterns. Show what you expect the agent to produce—review formats, code structure, commit message style, etc. + +## Common Pitfalls + +- ❌ **Too broad**: "You are a software engineer" — no focus or guardrails + ✅ **Instead**: Define specific expertise, review criteria, and output format + +- ❌ **No tools specified**: Agent can't search code or run commands + ✅ **Instead**: Declare the tools the agent needs in frontmatter + +- ❌ **Conflicting with instructions**: Agent says "use tabs" but instructions say "use spaces" + ✅ **Instead**: Agents should complement instructions, not contradict them + +- ❌ **Monolithic agent**: One agent that handles security, testing, docs, and deployment + ✅ **Instead**: Create focused agents and let them invoke shared skills + +## Next Steps + +- **Explore Repository Examples**: Browse the [Agents Directory](../../agents/) for production agent definitions +- **Connect External Tools**: [Understanding MCP Servers](../understanding-mcp-servers/) — Give agents access to databases, APIs, and more +- **Automate with Coding Agent**: [Using the Copilot Coding Agent](../using-copilot-coding-agent/) — Run agents autonomously on issues +- **Add Reusable Tasks**: [Creating Effective Skills](../creating-effective-skills/) — Build tasks agents can discover and invoke + +--- diff --git a/website/src/content/learning-hub/copilot-configuration-basics.md b/website/src/content/learning-hub/copilot-configuration-basics.md new file mode 100644 index 00000000..6b15ac1c --- /dev/null +++ b/website/src/content/learning-hub/copilot-configuration-basics.md @@ -0,0 +1,385 @@ +--- +title: 'Copilot Configuration Basics' +description: 'Learn how to configure GitHub Copilot at user, workspace, and repository levels to optimize your AI-assisted development experience.' +authors: + - GitHub Copilot Learning Hub Team +lastUpdated: '2025-11-28' +estimatedReadingTime: '10 minutes' +tags: + - configuration + - setup + - fundamentals +relatedArticles: + - ./what-are-agents-skills-instructions.md + - ./understanding-copilot-context.md +prerequisites: + - Basic familiarity with GitHub Copilot +--- + +GitHub Copilot offers extensive configuration options that let you tailor its behavior to your personal preferences, project requirements, and team standards. Understanding these configuration layers helps you maximize productivity while maintaining consistency across teams. This article explains the configuration hierarchy, key settings, and how to set up repository-level customizations that benefit your entire team. + +## Configuration Levels + +GitHub Copilot uses a hierarchical configuration system where settings at different levels can override each other. Understanding this hierarchy helps you apply the right configuration at the right level. + +### User Settings + +User settings apply globally across all your projects and represent your personal preferences. These are stored in your IDE's user configuration and travel with your IDE profile. + +**Common user-level settings**: +- Enable/disable inline suggestions globally +- Commit message style preferences +- Default language preferences + +**When to use**: For personal preferences that should apply everywhere you work, like keyboard shortcuts or whether you prefer inline suggestions vs chat. + +### Repository Settings + +Repository settings live in your codebase (typically in `.github/` although some editors allow customising the paths that Copilot will use) and are shared with everyone working on the project. These provide the highest level of customization and override both user and workspace settings. + +**Common repository-level customizations**: +- Custom instructions for coding conventions +- Reusable skills for common tasks +- Specialized agents for project workflows +- Custom agents for domain expertise + +**When to use**: For repository-wide standards, project-specific best practices, and reusable customizations that should be version-controlled and shared. + +### Organisation Settings (GitHub.com only) + +Organisation settings allow administrators to enforce Copilot policies across all repositories within an organization. These settings can include defining custom agents, creating globally applied instructions, enabling or disabling Copilot, managing billing, and setting usage limits. These policies may not be enforced in the IDE, depending on the IDE's support for organization-level settings, but will apply to Copilot usage on GitHub.com. + +**When to use**: For enforcing organization-wide policies, ensuring compliance, and providing shared resources across multiple repositories. + +### Configuration Precedence + +When multiple configuration levels define the same setting, GitHub Copilot applies them in this order (highest precedence first): + +1. **Organisation settings** (if applicable) +1. **Repository settings** (`.github/`) +1. **User settings** (IDE global preferences) + +**Example**: If your user settings disable Copilot for `.test.ts` files, but repository settings enable custom instructions for test files, the repository settings take precedence and Copilot remains active with the custom instructions applied. + +## Key Configuration Options + +These settings control GitHub Copilot's core behavior across all IDEs: + +### Inline Suggestions + +Control whether Copilot automatically suggests code completions as you type. + +**VS Code example**: +```json +{ + "github.copilot.enable": { + "*": true, + "plaintext": false, + "markdown": false + } +} +``` + +**Why it matters**: Some developers prefer to invoke Copilot explicitly rather than seeing automatic suggestions. You can also enable it only for specific languages. + +### Chat Availability + +Control access to GitHub Copilot Chat in your IDE. + +**VS Code example**: +```json +{ + "github.copilot.chat.enabled": true +} +``` + +**Why it matters**: Chat provides a conversational interface for asking questions and getting explanations, complementing inline suggestions. + +### Suggestion Trigger Behavior + +Configure how and when Copilot generates suggestions. + +**VS Code example**: +```json +{ + "editor.inlineSuggest.enabled": true, + "github.copilot.editor.enableAutoCompletions": true +} +``` + +**Why it matters**: Control whether suggestions appear automatically or only when explicitly requested, balancing helpfulness with potential distraction. + +### Language-Specific Settings + +Enable or disable Copilot for specific programming languages. + +**VS Code example**: +```json +{ + "github.copilot.enable": { + "typescript": true, + "javascript": true, + "python": true, + "markdown": false + } +} +``` + +**Why it matters**: You may want Copilot active for code files but not for documentation or configuration files. + +### Excluded Files and Directories + +Prevent Copilot from accessing specific files or directories. + +**VS Code example**: +```json +{ + "github.copilot.advanced": { + "debug.filterLogCategories": [], + "excludedFiles": [ + "**/secrets/**", + "**/*.env", + "**/node_modules/**" + ] + } +} +``` + +**Why it matters**: Exclude sensitive files, generated code, or dependencies from Copilot's context to improve suggestion relevance and protect confidential information. + +## Repository-Level Configuration + +The `.github/` directory in your repository enables team-wide customizations that are version-controlled and shared across all contributors. + +### Directory Structure + +A well-organized Copilot configuration directory looks like this: + +``` +.github/ +├── agents/ +│ ├── terraform-expert.agent.md +│ └── api-reviewer.agent.md +├── skills/ +│ ├── generate-tests/ +│ │ └── SKILL.md +│ └── refactor-component/ +│ └── SKILL.md +└── instructions/ + ├── typescript-conventions.instructions.md + └── api-design.instructions.md +``` + +### Custom Agents + +Agents are specialized assistants for specific workflows. Place agent definition files in `.github/agents/`. + +**Example agent** (`terraform-expert.agent.md`): +```markdown +--- +description: 'Terraform infrastructure-as-code specialist' +tools: ['filesystem', 'terminal'] +name: 'Terraform Expert' +--- + +You are an expert in Terraform and cloud infrastructure. +Guide users through creating, reviewing, and deploying infrastructure code. +``` + +**When to use**: Create agents for domain-specific tasks like infrastructure management, API design, or security reviews. + +### Reusable Skills + +Skills are self-contained folders that package reusable capabilities. Store them in `.github/skills/`. + +**Example skill** (`generate-tests/SKILL.md`): +```markdown +--- +name: generate-tests +description: 'Generate comprehensive unit tests for a component, covering happy path, edge cases, and error conditions' +--- + +# generate-tests + +Generate unit tests for the selected code that: +- Cover all public methods and edge cases +- Use our testing conventions from @testing-utils.ts +- Include descriptive test names + +See [references/test-patterns.md](references/test-patterns.md) for standard patterns. +``` + +Skills can also bundle reference files, templates, and scripts in their folder, giving the AI richer context than a single file can provide. Unlike the older prompt format, skills can be discovered and invoked by agents automatically. + +**When to use**: For repetitive tasks your team performs regularly, like generating tests, creating documentation, or refactoring patterns. + +### Instructions Files + +Instructions provide persistent context that applies automatically when working in specific files or directories. Store them in `.github/instructions/`. + +**Example instruction** (`typescript-conventions.instructions.md`): +```markdown +--- +description: 'TypeScript coding conventions for this project' +applyTo: '**.ts, **.tsx' +--- + +When writing TypeScript code: +- Use strict type checking +- Prefer interfaces over type aliases for object types +- Always handle null/undefined with optional chaining +- Use async/await instead of raw promises +``` + +**When to use**: For project-wide coding standards, architectural patterns, or technology-specific conventions that should influence all suggestions. + +## Setting Up Team Configuration + +Follow these steps to establish effective team-wide Copilot configuration: + +### 1. Create the Configuration Structure + +Start by creating the `.github/` directory in your repository root: + +```bash +mkdir -p .github/{agents,skills,instructions} +``` + +### 2. Document Your Conventions + +Create instructions that capture your team's coding standards: + +```markdown + +--- +description: 'Team coding conventions and best practices' +applyTo: '**' +--- + +Our team follows these practices: +- Write self-documenting code with clear names +- Add comments only for complex logic +- Prefer composition over inheritance +- Keep functions small and focused +``` + +### 3. Build Reusable Skills + +Identify repetitive tasks and create skills for them: + +```markdown + +--- +name: add-error-handling +description: 'Add comprehensive error handling to existing code following team patterns' +--- + +# add-error-handling + +Add error handling to the selected code: +- Catch and handle potential errors +- Log errors with context +- Provide meaningful error messages +- Follow our error handling patterns from @error-utils.ts +``` + +### 4. Version Control Best Practices + +- **Commit all `.github/` files** to your repository +- **Use descriptive commit messages** when adding or updating customizations +- **Review changes** to ensure they align with team standards +- **Document** each customization with clear descriptions and examples + +### 5. Onboard New Team Members + +Make Copilot configuration part of your onboarding process: + +1. Point new members to your `.github/` directory +2. Explain which agents and skills exist and when to use them +3. Encourage exploration and contributions +4. Include example usage in your project README + +## IDE-Specific Configuration + +While repository-level customizations work across all IDEs, you may also need IDE-specific settings: + +### VS Code + +Settings file: `.vscode/settings.json` or global user settings + +```json +{ + "github.copilot.enable": { + "*": true + }, + "github.copilot.chat.enabled": true, + "editor.inlineSuggest.enabled": true +} +``` + +### Visual Studio + +Settings: Tools → Options → GitHub Copilot + +- Configure inline suggestions +- Set keyboard shortcuts +- Manage language-specific enablement + +### JetBrains IDEs + +Settings: File → Settings → Tools → GitHub Copilot + +- Enable/disable for specific file types +- Configure suggestion behavior +- Customize keyboard shortcuts + +### GitHub Copilot CLI + +Configuration file: `~/.copilot-cli/config.json` + +```json +{ + "editor": "vim", + "suggestions": true +} +``` + +## Common Questions + +**Q: How do I disable Copilot for specific files?** + +A: Use the `excludedFiles` setting in your IDE configuration or create a workspace setting that disables Copilot for specific patterns: + +```json +{ + "github.copilot.advanced": { + "excludedFiles": [ + "**/secrets/**", + "**/*.env", + "**/test/fixtures/**" + ] + } +} +``` + +**Q: Can I have different settings per project?** + +A: Yes! Use workspace settings (`.vscode/settings.json`) for project-specific preferences that don't need to be shared, or use repository settings (for example, files in `.github/agents/`, `.github/skills/`, `.github/instructions/`, and `.github/copilot-instructions.md`) for team-wide customizations that should be version-controlled. + +**Q: How do team settings override personal settings?** + +A: Repository-level Copilot configuration (such as `.github/agents/`, `.github/skills/`, `.github/instructions/`, and `.github/copilot-instructions.md`) has the highest precedence, followed by workspace settings, then user settings. This means team-defined instructions and agents will apply even if your personal settings differ, ensuring consistency across the team. + +**Q: Where should I put customizations that apply to all my projects?** + +A: Use user-level settings in your IDE for personal preferences that should apply everywhere. For customizations specific to a technology or framework (like React conventions), consider creating a collection in the awesome-copilot-hub repository that you can reference across multiple projects. + +## Next Steps + +Now that you understand Copilot configuration, explore how to create powerful customizations: + +- **[What are Agents, Skills, and Instructions](../what-are-agents-skills-instructions/)** - Understand the customization types you can configure +- **[Understanding Copilot Context](../understanding-copilot-context/)** - Learn how configuration affects context usage +- **[Defining Custom Instructions](../defining-custom-instructions/)** - Create persistent context for your projects +- **[Creating Effective Skills](../creating-effective-skills/)** - Build reusable task folders with bundled assets +- **[Building Custom Agents](../building-custom-agents/)** - Develop specialized assistants diff --git a/website/src/content/learning-hub/creating-effective-skills.md b/website/src/content/learning-hub/creating-effective-skills.md new file mode 100644 index 00000000..2c047702 --- /dev/null +++ b/website/src/content/learning-hub/creating-effective-skills.md @@ -0,0 +1,403 @@ +--- +title: 'Creating Effective Skills' +description: 'Master the art of writing reusable, shareable skill folders that deliver consistent results across your team.' +authors: + - GitHub Copilot Learning Hub Team +lastUpdated: '2026-02-26' +estimatedReadingTime: '9 minutes' +tags: + - skills + - customization + - fundamentals +relatedArticles: + - ./what-are-agents-skills-instructions.md + - ./defining-custom-instructions.md +prerequisites: + - Basic understanding of GitHub Copilot chat +--- + +Skills are self-contained folders that package reusable capabilities—instructions, reference files, templates, and scripts—into a single unit that agents can discover automatically and users can invoke via slash commands. They enable teams to standardize common workflows like generating tests, reviewing code, or creating documentation, ensuring consistent, high-quality results across all team members. + +This article shows you how to design, structure, and optimize skills that solve real development challenges. + +## What Are Skills? + +Skills are folders containing a `SKILL.md` file and optional bundled assets. The `SKILL.md` defines: + +- **Name**: A kebab-case identifier that doubles as the `/command` users invoke (e.g., `/generate-tests`) +- **Description**: What the skill accomplishes and when it should be triggered +- **Instructions**: The detailed workflow Copilot executes +- **Asset references**: Links to bundled templates, scripts, schemas, and reference documents + +**Key advantages over the older prompt file format**: +- Skills support extended frontmatter for **agent discovery**—agents can find and invoke skills automatically, while prompts required manual slash-command invocation +- Skills can **bundle additional files** (reference docs, templates, scripts) alongside their instructions, giving the AI richer context +- Skills are **more normalised across coding agent systems** via the open [Agent Skills specification](https://agentskills.io/home) +- Skills still support **slash-command invocation** just like prompts did + +### How Skills Differ from Other Customizations + +**Skills vs Instructions**: +- Skills are invoked explicitly (by agents or users); instructions apply automatically +- Skills drive specific tasks with bundled resources; instructions provide ongoing context +- Use skills for workflows you trigger on demand; use instructions for standards that always apply + +**Skills vs Agents**: +- Skills are task-focused capabilities; agents are specialized personas +- Skills work with standard Copilot tools and bundle their own assets; agents may require MCP servers or custom integrations +- Use skills for repeatable tasks; use agents for complex multi-step workflows that need persistent state + +## Anatomy of a Skill + +Every effective skill has two parts: a `SKILL.md` file with frontmatter and instructions, plus optional bundled assets. + +### SKILL.md Structure + +**Example - Simple Skill** (`skills/generate-tests/SKILL.md`): + +```markdown +--- +name: generate-tests +description: 'Generate comprehensive unit tests for the selected code, covering happy path, edge cases, and error conditions' +--- + +# generate-tests + +Generate comprehensive unit tests for the selected code. + +## When to Use This Skill + +Use this skill when you need to create or expand test coverage for existing code. + +## Requirements + +- Cover happy path, edge cases, and error conditions +- Use the testing framework already present in the codebase +- Follow existing test file naming conventions +- Include descriptive test names explaining what is being tested +- Add assertions for all expected behaviors +``` + +**Why This Works**: +- Clear `name` field provides the slash-command identifier +- Rich `description` tells agents when to invoke this skill +- Structured instructions provide specific, actionable guidance +- Generic enough to work across different projects + +### Adding Bundled Assets + +Skills can include reference files, templates, and scripts that enrich the AI's context: + +``` +skills/ +└── generate-tests/ + ├── SKILL.md + ├── references/ + │ └── testing-patterns.md # Common testing patterns + ├── templates/ + │ └── test-template.ts # Starter test file + └── scripts/ + └── setup-test-env.sh # Environment setup +``` + +Reference these assets in your SKILL.md instructions: + +```markdown +## Testing Patterns + +Follow the patterns documented in [references/testing-patterns.md](references/testing-patterns.md). + +Use [templates/test-template.ts](templates/test-template.ts) as a starting structure. +``` + +## Frontmatter Configuration + +The YAML frontmatter controls how Copilot discovers and executes your skill. + +### Required Fields + +**name**: Kebab-case identifier matching the folder name +```yaml +name: generate-tests +``` + +**description**: Brief summary of what the skill does and when to use it (10–1024 characters, wrapped in single quotes) +```yaml +description: 'Generate comprehensive unit tests for a component, covering happy path, edge cases, and error conditions' +``` + +### Description Best Practices + +The `description` field is critical for agent discovery. Write it so that agents understand **when** to invoke the skill: + +✅ **Good**: `'Generate conventional commit messages by analyzing staged git changes and applying the Conventional Commits specification'` + +❌ **Poor**: `'Commit helper'` + +Include trigger keywords and contextual cues that help agents match the skill to user intent. + +## Real Examples from the Repository + +The awesome-copilot repository includes skill folders demonstrating production patterns. + +### Conventional Commits + +See [`skills/conventional-commit/SKILL.md`](https://github.com/github/awesome-copilot/tree/main/skills/conventional-commit) for automating commit messages: + +```markdown +--- +name: conventional-commit +description: 'Generate conventional commit messages from staged changes following the Conventional Commits specification' +--- + +# conventional-commit + +## Workflow + +Follow these steps: + +1. Run `git status` to review changed files +2. Run `git diff --cached` to inspect changes +3. Construct commit message using Conventional Commits format +4. Execute commit command automatically + +## Commit Message Structure + +(scope): description + +Types: feat|fix|docs|style|refactor|perf|test|build|ci|chore + +## Examples + +- feat(parser): add ability to parse arrays +- fix(ui): correct button alignment +- docs: update README with usage instructions +``` + +This skill automates a repetitive task (writing commit messages) with a proven template that agents can discover and invoke automatically. + +### Diagram Generation with Bundled Assets + +See [`skills/excalidraw-diagram-generator/`](https://github.com/github/awesome-copilot/tree/main/skills/excalidraw-diagram-generator) for a skill with rich bundled resources: + +``` +excalidraw-diagram-generator/ +├── SKILL.md +├── references/ +│ ├── excalidraw-schema.md +│ └── element-types.md +├── templates/ +│ ├── flowchart-template.json +│ └── relationship-template.json +└── scripts/ + └── split-excalidraw-library.py +``` + +This skill packages schema documentation, starter templates, and utility scripts so the AI has everything it needs to generate valid diagrams without hallucinating the format. + +## Writing Effective Skill Instructions + +### Structure Your Skills + +**1. Start with clear objectives**: +```markdown +# skill-name + +Your goal is to [specific task] for [specific target]. +``` + +**2. Add "When to Use" guidance** (helps agent discovery): +```markdown +## When to Use This Skill + +Use this skill when: +- A user asks to [trigger phrase 1] +- You need to [trigger phrase 2] +- Keywords: [keyword1], [keyword2], [keyword3] +``` + +**3. Define requirements explicitly**: +```markdown +## Requirements + +- Must follow [standard/pattern] +- Should include [specific element] +- Avoid [anti-pattern] +``` + +**4. Reference bundled assets**: +```markdown +## References + +- Follow patterns in [references/patterns.md](references/patterns.md) +- Use template from [templates/starter.json](templates/starter.json) +``` + +**5. Provide examples**: +```markdown +### Good Example +[Show desired output] + +### What to Avoid +[Show problematic patterns] +``` + +## Best Practices + +- **One purpose per skill**: Focus on a single task or workflow +- **Write for discovery**: Craft descriptions with trigger keywords so agents find the right skill +- **Bundle what matters**: Include templates, schemas, and reference docs that reduce hallucination +- **Make it generic**: Write skills that work across different projects +- **Be explicit**: Avoid ambiguous language; specify exact requirements +- **Name descriptively**: Use clear, action-oriented names: `generate-tests`, not `helper` +- **Keep assets lean**: Bundled files should be under 5 MB each +- **Test thoroughly**: Verify skills work with different inputs and codebases + +### Writing Style Guidelines + +**Use imperative mood**: +- ✅ "Generate unit tests for the selected function" +- ❌ "You should generate some tests" + +**Be specific about requirements**: +- ✅ "Use Jest with React Testing Library" +- ❌ "Use whatever testing framework" + +**Provide guardrails**: +- ✅ "Do not modify existing test files; create new ones" +- ❌ "Update tests as needed" + +**Structure complex skills**: +```markdown +## Step 1: Analysis +[Analyze requirements] + +## Step 2: Generation +[Generate code] + +## Step 3: Validation +[Check output] +``` + +## Common Patterns + +### Multi-Step Workflow with References + +```markdown +--- +name: scaffold-feature +description: 'Scaffold a new feature with implementation, tests, and documentation following project conventions' +--- + +# scaffold-feature + +Create a complete feature implementation: + +1. **Analyze**: Review existing patterns in codebase +2. **Generate**: Create implementation files following project structure +3. **Test**: Generate comprehensive test coverage using [references/test-patterns.md](references/test-patterns.md) +4. **Document**: Add inline comments and update relevant docs +5. **Validate**: Check for common issues and anti-patterns + +Use the existing code style and conventions found in the codebase. +``` + +### Quick Analysis Skill + +```markdown +--- +name: explain-architecture +description: 'Analyze and explain code architecture, design patterns, and data flow for selected code' +--- + +# explain-architecture + +Analyze the selected code and explain: + +1. Overall architecture and design patterns used +2. Key components and their responsibilities +3. Data flow and dependencies +4. Potential improvements or concerns + +Keep explanations concise and developer-focused. +``` + +### Skill with Script Assets + +```markdown +--- +name: run-test-suite +description: 'Execute the project test suite, parse failures, and suggest fixes for failing tests' +--- + +# run-test-suite + +Execute the project's test suite: + +1. Identify the test command from package.json or build files +2. Run tests in the integrated terminal +3. Parse test output for failures +4. Summarize failed tests with relevant file locations +5. Suggest potential fixes based on error messages + +Use [scripts/parse-test-output.sh](scripts/parse-test-output.sh) to extract structured failure data. +``` + +## Common Questions + +**Q: How do I invoke a skill?** + +A: Skills can be invoked in two ways. Users can type the skill name as a `/command` in VS Code Chat (e.g., `/generate-tests`). Agents can also discover and invoke skills automatically based on the skill's description and the user's intent. + +**Q: How are skills different from prompts?** + +A: Skills replace the older prompt file (`*.prompt.md`) format. Skills offer agent discovery (prompts were manual-only), bundled assets (prompts were single files), and cross-platform portability via the Agent Skills specification. If you have existing prompts, consider migrating them to skills. + +**Q: Can skills include multiple files?** + +A: Yes! Skills are folders, not single files. You can bundle reference documents, templates, scripts, and any other resources the AI needs. Keep individual assets under 5 MB. + +**Q: How do I share skills with my team?** + +A: Store skill folders in your repository's `.github/skills/` directory. They're automatically available to all team members with Copilot access when working in that repository. + +**Q: Can agents chain multiple skills?** + +A: Agents can discover and invoke multiple skills during a conversation based on user intent. Each skill invocation is independent, but agents maintain conversation context across invocations. + +**Q: Should skills include code examples?** + +A: Yes, for clarity. Show examples of desired output format, patterns to follow, or anti-patterns to avoid. For complex schemas or formats, consider bundling them as reference files rather than inline examples. + +## Common Pitfalls to Avoid + +- ❌ **Vague description**: "Code helper" doesn't help agents discover the skill + ✅ **Instead**: Write descriptions with trigger keywords: "Generate comprehensive unit tests covering happy path, edge cases, and error conditions" + +- ❌ **Missing bundled resources**: Expecting the AI to know your test patterns or schemas + ✅ **Instead**: Bundle reference docs and templates in the skill folder + +- ❌ **Too many responsibilities**: A skill that generates, tests, documents, and deploys + ✅ **Instead**: Create focused skills for each concern + +- ❌ **Hardcoded paths**: Referencing specific project file paths in skill instructions + ✅ **Instead**: Write generic instructions that work across projects + +- ❌ **No examples**: Abstract requirements without concrete guidance + ✅ **Instead**: Include "Good Example" and "What to Avoid" sections, or bundle templates + +## Next Steps + +Now that you understand effective skills, you can: + +- **Explore Repository Examples**: Browse the [Skills Directory](../../skills/) for production skills covering diverse workflows +- **Learn About Agents**: [Building Custom Agents](../building-custom-agents/) — When to upgrade from skills to full agents +- **Understand Instructions**: [Defining Custom Instructions](../defining-custom-instructions/) — Complement skills with automatic context +- **Decision Framework**: Choosing the Right Customization _(coming soon)_ — When to use skills vs other types + +**Suggested Reading Order**: +1. This article (creating effective skills) +2. [Building Custom Agents](../building-custom-agents/) — More sophisticated workflows +3. Choosing the Right Customization _(coming soon)_ — Decision guidance + +--- diff --git a/website/src/content/learning-hub/defining-custom-instructions.md b/website/src/content/learning-hub/defining-custom-instructions.md new file mode 100644 index 00000000..6b4465f2 --- /dev/null +++ b/website/src/content/learning-hub/defining-custom-instructions.md @@ -0,0 +1,317 @@ +--- +title: 'Defining Custom Instructions' +description: 'Learn how to create persistent, context-aware instructions that guide GitHub Copilot automatically across your codebase.' +authors: + - GitHub Copilot Learning Hub Team +lastUpdated: '2025-12-02' +estimatedReadingTime: '8 minutes' +tags: + - instructions + - customization + - fundamentals +relatedArticles: + - ./what-are-agents-skills-instructions.md + - ./creating-effective-skills.md + - ./copilot-configuration-basics.md +prerequisites: + - Basic understanding of GitHub Copilot features +--- + +Custom instructions are persistent configuration files that automatically guide GitHub Copilot's behavior when working with specific files or directories in your codebase. Unlike skills that require explicit invocation (by a user or an agent), instructions work silently in the background, ensuring Copilot consistently follows your team's standards, conventions, and architectural decisions. + +This article explains how to create effective custom instructions, when to use them, and how they integrate with your development workflow. + +## What Are Custom Instructions? + +Custom instructions are markdown files (`.instructions.md`) that contain: + +- **Coding standards**: Naming conventions, formatting rules, style guidelines +- **Framework-specific guidance**: Best practices for your tech stack +- **Architecture decisions**: Project structure, design patterns, conventions +- **Compliance requirements**: Security policies, regulatory constraints + +**Key Points**: +- Instructions apply automatically when Copilot works on matching files +- They persist across all chat sessions and inline completions +- They can be scoped globally, per language, or per directory using glob patterns +- They help Copilot understand your codebase's unique context without manual prompting + +### How Instructions Differ from Other Customizations + +**Instructions vs Skills**: +- Instructions are always active for matching files; skills require explicit invocation (by users or agents) +- Instructions provide passive context; skills drive specific tasks with bundled resources +- Use instructions for standards that apply repeatedly; use skills for on-demand operations + +**Instructions vs Agents**: +- Instructions are lightweight context; agents are specialized personas with tool access +- Instructions work with any Copilot interaction; agents require explicit selection +- Use instructions for coding standards; use agents for complex workflows with tooling needs + +## Creating Your First Custom Instruction + +Custom instructions follow a simple structure with YAML frontmatter and markdown content. + +**Example**: + +````markdown +--- +description: 'TypeScript coding standards for React components' +applyTo: '**/*.tsx, **/*.ts' +--- + +# TypeScript React Development + +Use functional components with TypeScript interfaces for all props. + +## Naming Conventions + +- Component files: PascalCase (e.g., `UserProfile.tsx`) +- Hook files: camelCase with `use` prefix (e.g., `useAuth.ts`) +- Type files: PascalCase with descriptive names (e.g., `UserTypes.ts`) + +## Component Structure + +Always define prop interfaces explicitly: + +```typescript +interface UserProfileProps { + userId: string; + onUpdate: (user: User) => void; +} + +export function UserProfile({ userId, onUpdate }: UserProfileProps) { + // Implementation +} +``` +```` + +## Best Practices + +- Export types separately for reuse across components +- Use React.FC only when children typing is needed +- Prefer named exports over default exports + +**Why This Works**: +- The `applyTo` glob pattern targets TypeScript/TSX files specifically +- Copilot reads these instructions whenever it generates or suggests code for matching files +- Standards are enforced consistently without developers needing to remember every rule +- New team members benefit from institutional knowledge automatically + +## Scoping Instructions Effectively + +The `applyTo` field determines which files receive the instruction's guidance. + +### Common Scoping Patterns + +**All TypeScript files**: +```yaml +applyTo: '**/*.ts, **/*.tsx' +``` + +**Specific directory**: +```yaml +applyTo: 'src/components/**/*.tsx' +``` + +**Test files only**: +```yaml +applyTo: '**/*.test.ts, **/*.spec.ts' +``` + +**Single technology**: +```yaml +applyTo: '**/*.py' +``` + +**Entire project**: +```yaml +applyTo: '**' +``` + +**Expected Result**: +When you work on a file matching the pattern, Copilot incorporates that instruction's context into suggestions and chat responses automatically. + +## Real Examples from the Repository + +The awesome-copilot-hub repository includes over 120 instruction files demonstrating real-world patterns. + +### Security Standards + +See [security-and-owasp.instructions.md](https://github.com/github/awesome-copilot/blob/main/instructions/security-and-owasp.instructions.md) for comprehensive security guidance: + +```markdown +--- +description: 'OWASP Top 10 security practices for all code' +applyTo: '**' +--- + +# Security and OWASP Best Practices + +Always validate and sanitize user input before processing. + +## Input Validation + +- Whitelist acceptable input patterns +- Reject unexpected formats early +- Never trust client-side validation alone +- Use parameterized queries for database operations +``` + +This instruction applies to all files (`applyTo: '**'`), ensuring security awareness in every suggestion. + +### Framework-Specific Guidance + +See [reactjs.instructions.md](https://github.com/github/awesome-copilot/blob/main/instructions/reactjs.instructions.md) for React-specific patterns: + +```markdown +--- +description: 'React development best practices and patterns' +applyTo: '**/*.jsx, **/*.tsx' +--- + +# React Development Guidelines + +Use functional components with hooks for all new components. + +## State Management + +- Use `useState` for local component state +- Use `useContext` for shared state across components +- Consider Redux only for complex global state +- Avoid prop drilling beyond 2-3 levels +``` + +This instruction targets only React component files, providing context-specific guidance. + +### Testing Standards + +See [playwright-typescript.instructions.md](https://github.com/github/awesome-copilot/blob/main/instructions/playwright-typescript.instructions.md) for test automation patterns: + +````markdown +--- +description: 'Playwright test automation with TypeScript' +applyTo: '**/*.spec.ts, **/tests/**/*.ts' +--- + +# Playwright Testing Standards + +Write descriptive test names that explain the expected behavior. + +## Test Structure + +```typescript +test('should display error message when login fails', async ({ page }) => { + await page.goto('/login'); + await page.fill('#username', 'invalid'); + await page.fill('#password', 'invalid'); + await page.click('#submit'); + + await expect(page.locator('.error')).toBeVisible(); +}); +``` +```` + +This instruction applies only to test files, ensuring test-specific context. + +## Structuring Instruction Content + +### Effective Organization + +A well-structured instruction file includes: + +1. **Clear title and overview**: What this instruction covers +2. **Specific guidelines**: Actionable rules, not vague suggestions +3. **Code examples**: Working snippets showing correct patterns +4. **Explanations**: Why certain approaches are preferred + +### Writing Style Best Practices + +- **Be specific**: "Use PascalCase for component names" instead of "name components well" +- **Show examples**: Include working code snippets demonstrating patterns +- **Explain reasoning**: Brief context helps Copilot understand intent +- **Stay concise**: Focus on what matters most; avoid exhaustive documentation + +**Example - Vague vs Specific**: + +❌ **Vague**: "Handle errors properly" + +✅ **Specific**: +````markdown +## Error Handling + +Wrap async operations in try-catch blocks and log errors: + +```typescript +try { + const data = await fetchUser(userId); + return data; +} catch (error) { + logger.error('Failed to fetch user', { userId, error }); + throw new UserNotFoundError(userId); +} +``` +```` + +## Common Questions + +**Q: How many instructions should I create?** + +A: Start with 3-5 core instructions covering your most important standards (naming, structure, security). Add more as patterns emerge. Having 10-20 instructions for a medium-sized project is reasonable. Awesome Copilot repository contains over 120 to demonstrate the range of possibilities. + +**Q: Do instructions slow down Copilot?** + +A: No. Instructions are processed efficiently as part of Copilot's context window. Keep individual files focused (under 500 lines) for best results, and ensure that they are scoped appropriately. + +**Q: Can instructions contradict each other?** + +A: If multiple instructions apply to the same file, Copilot considers all of them. Avoid contradictions by keeping instructions focused and using specific `applyTo` patterns. More specific patterns take precedence mentally, but it's best to design complementary instructions. + +**Q: How do I know if my instructions are working?** + +A: Test by asking Copilot to generate code matching your patterns. If it follows your standards without explicit prompting, the instructions are effective. You can also reference the instruction explicitly in chat: "Following the TypeScript standards in my instructions, create a user component." + +**Q: Should I document everything in instructions?** + +A: No. Instructions are for persistent standards that apply repeatedly. Document one-off decisions in code comments. Use instructions for patterns you want Copilot to follow automatically. + +## Best Practices + +- **One purpose per file**: Create separate instructions for different concerns (security, testing, styling) +- **Use clear naming**: Name files descriptively: `react-component-standards.instructions.md`, not `rules.instructions.md` +- **Include examples**: Every guideline should have at least one code example +- **Keep it current**: Review instructions when dependencies or frameworks update +- **Test your instructions**: Generate code and verify Copilot follows the patterns +- **Link to documentation**: Reference official docs for detailed explanations +- **Use tables for rules**: Tabular format works well for naming conventions and comparisons + +## Common Pitfalls to Avoid + +- ❌ **Too generic**: "Write clean code" doesn't give Copilot actionable guidance + ✅ **Instead**: Provide specific patterns: "Extract functions longer than 20 lines into smaller, named functions" + +- ❌ **Too verbose**: Including entire documentation pages overwhelms the context window + ✅ **Instead**: Distill key patterns and link to full documentation + +- ❌ **Contradictory rules**: Different instructions suggesting opposite approaches + ✅ **Instead**: Design complementary instructions with clear scopes + +- ❌ **Outdated patterns**: Instructions referencing deprecated APIs or old versions + ✅ **Instead**: Review and update instructions when dependencies change + +- ❌ **Missing scope**: Using `applyTo: '**'` for language-specific guidelines + ✅ **Instead**: Scope to relevant files: `applyTo: '**/*.py'` for Python-specific rules + +## Next Steps + +Now that you understand custom instructions, you can: + +- **Explore Repository Examples**: Browse [Instructions Directory](../../instructions/) - Over 120 real-world examples covering frameworks, languages, and domains +- **Learn About Skills**: [Creating Effective Skills](../creating-effective-skills/) - Discover when to use skills instead of instructions +- **Understand Agents**: [Building Custom Agents](../building-custom-agents/) - See how agents complement instructions for complex workflows +- **Configuration Basics**: [Copilot Configuration Basics](../copilot-configuration-basics/) - Learn how to organize and manage your customizations + +**Suggested Reading Order**: +1. This article (defining custom instructions) +2. [Creating Effective Skills](../creating-effective-skills/) - Learn complementary customization type +3. [Building Custom Agents](../building-custom-agents/) - Decision framework for when to use each type diff --git a/website/src/content/learning-hub/github-copilot-terminology-glossary.md b/website/src/content/learning-hub/github-copilot-terminology-glossary.md new file mode 100644 index 00000000..0caa5722 --- /dev/null +++ b/website/src/content/learning-hub/github-copilot-terminology-glossary.md @@ -0,0 +1,248 @@ +--- +title: 'GitHub Copilot Terminology Glossary' +description: 'A quick reference guide defining common GitHub Copilot and platform-specific terms.' +authors: + - GitHub Copilot Learning Hub Team +lastUpdated: '2025-12-15' +estimatedReadingTime: '8 minutes' +tags: + - glossary + - terminology + - reference +relatedArticles: + - ./what-are-agents-skills-instructions.md + - ./copilot-configuration-basics.md +--- + +New to GitHub Copilot customization? This glossary defines common terms you'll encounter while exploring agents, skills, instructions, and related concepts in the Awesome GitHub Copilot ecosystem. + +Use this page as a quick reference when reading articles in the Learning Hub or browsing the repository. + +--- + +## Core Concepts + +### Agent + +A specialized configuration file (`*.agent.md`) that defines a GitHub Copilot persona or assistant with specific expertise, tools, and behavior patterns. Agents integrate with MCP servers to provide enhanced capabilities for particular workflows (e.g., "Terraform Expert" or "Security Auditor"). + +**When to use**: For recurring workflows that benefit from deep tooling integrations and persistent conversational context. + +**Learn more**: [What are Agents, Skills, and Instructions](../what-are-agents-skills-instructions/) + +--- + +### Built-in Tool + +A native capability provided by GitHub Copilot without requiring additional configuration or MCP servers. Examples include code search, file editing, terminal command execution, and web search. Built-in tools are always available and don't require installation. + +**Related terms**: [Tools](#tools), [MCP](#mcp-model-context-protocol) + +--- + +### Chat Mode + +**Deprecated terminology** - This term is no longer used. Use [Agent](#agent) instead. + +Previously, "chat mode" was an alternative term for [Agent](#agent) that described how GitHub Copilot Chat could be transformed into domain-specific assistants. The ecosystem has standardized on "Agent" as the preferred terminology. + +**See**: [Agent](#agent) + +--- + +### Collection + +**Note**: Collections are a concept specific to the Awesome GitHub Copilot repository and are not part of standard GitHub Copilot terminology. + +A curated grouping of related skills, instructions, and agents organized around a specific theme or workflow. Collections are defined in YAML files (`*.collection.yml`) in the `collections/` directory and help users discover related customizations together. + +**Example**: The "Awesome Copilot" collection bundles meta-skills for discovering and generating GitHub Copilot customizations. + +**Learn more**: [What are Agents, Skills, and Instructions](../what-are-agents-skills-instructions/) + +--- + +### Custom Agent + +See [Agent](#agent). The term "custom" emphasizes that these are user-defined configurations rather than GitHub Copilot's default behavior. Custom agents can be created by anyone and shared via repositories like Awesome GitHub Copilot. + +--- + +### Custom Instruction + +See [Instruction](#instruction). The term "custom" emphasizes that these are user-defined rules rather than GitHub Copilot's built-in understanding. Custom instructions are particularly useful for codifying team-specific standards and architectural decisions. + +--- + +## Configuration & Metadata + +### Front Matter + +YAML metadata placed at the beginning of Markdown files (between `---` delimiters) that provides structured information about the file and controls its behavior. In this repository, front matter typically includes fields like `name`, `description`, `mode`, `model`, `tools`, and `applyTo`. + +The front matter is what controls: +- **Tool access**: Which built-in and MCP tools the customization can use +- **Model selection**: Which AI model powers the customization +- **Scope**: Where the customization applies (e.g., `applyTo` patterns for instructions) + +**Note**: Not all fields are common across all customization types. Refer to the specific documentation for agents, skills, or instructions to see which fields apply to each type. + +**Example**: +```yaml +--- +name: 'React Component Generator' +description: 'Generate modern React components with TypeScript' +mode: 'agent' +tools: ['codebase'] +--- +``` + +**Used in**: Skills, agents, instructions, and Learning Hub articles. + +--- + +### AGENTS.md + +An emerging industry standard file format for defining portable AI coding instructions that work across different AI coding tools (GitHub Copilot, Claude, Codex, and others). The `AGENTS.md` file, typically placed in a repository root or `.github/` directory, contains instructions for how AI assistants should interact with your codebase. + +Unlike tool-specific customization files (`.agent.md`, `.prompt.md`, `.instructions.md`), `AGENTS.md` aims to provide a standardized, platform-agnostic way to define AI behavior that can be consumed by multiple tools. + +**Key characteristics**: +- Platform-agnostic format for cross-tool compatibility +- Typically contains project context, coding standards, and architectural guidelines +- Located at repository root or in `.github/` directory + +**Learn more**: [AGENTS.md Specification](https://agents.md/) + +**Related terms**: [Instruction](#instruction), [Front Matter](#front-matter) + +--- + +### Instruction + +A configuration file (`*.instructions.md`) that provides persistent background context and coding standards that GitHub Copilot reads whenever working on matching files. Instructions contain style guides, framework-specific hints, and repository rules that help Copilot align with your engineering practices automatically. + +**When to use**: For long-lived guidance that applies across many sessions, like coding standards or compliance requirements. + +**Learn more**: [What are Agents, Skills, and Instructions](../what-are-agents-skills-instructions/), [Defining Custom Instructions](../defining-custom-instructions/) + +--- + +## Skills & Interactions + +### Persona + +The identity, tone, and behavioral characteristics defined for an [Agent](#agent). A well-crafted persona helps GitHub Copilot respond consistently and appropriately for specific domains or expertise areas. + +**Example**: A "Database Performance Expert" persona might prioritize query optimization and explain concepts using database-specific terminology. + +**Related terms**: [Agent](#agent) + +--- + +### Prompt + +**Deprecated** — Prompts (`*.prompt.md`) were reusable chat templates that captured specific tasks or workflows, invoked using the `/` command in GitHub Copilot Chat. Prompts have been superseded by [Skills](#skill), which offer the same slash-command invocation plus agent discovery, bundled assets, and cross-platform portability. + +If you have existing prompts, consider migrating them to skills. See [Creating Effective Skills](../creating-effective-skills/) for guidance. + +**See**: [Skill](#skill) + +--- + +### Skill + +A self-contained folder containing a `SKILL.md` file and optional bundled assets (reference documents, templates, scripts) that packages a reusable capability for GitHub Copilot. Skills follow the open [Agent Skills specification](https://agentskills.io/home) and can be invoked by users via `/command` or discovered and invoked by agents automatically. + +**Key advantages**: +- **Agent discovery**: Extended frontmatter lets agents find and invoke skills automatically +- **Bundled assets**: Reference files, templates, and scripts provide richer context +- **Cross-platform**: Portable across coding agent systems via the Agent Skills specification + +**Example**: A `/generate-tests` skill might include a `SKILL.md` with testing instructions, a `references/test-patterns.md` with common patterns, and a `templates/test-template.ts` starter file. + +**When to use**: For standardizing how Copilot responds to recurring tasks, especially when bundled resources improve quality. + +**Learn more**: [What are Agents, Skills, and Instructions](../what-are-agents-skills-instructions/), [Creating Effective Skills](../creating-effective-skills/) + +--- + +## Platform & Integration + +### MCP (Model Context Protocol) + +A standardized protocol for connecting AI assistants like GitHub Copilot to external data sources, tools, and services. MCP servers act as bridges, allowing Copilot to interact with APIs, databases, file systems, and other resources beyond its built-in capabilities. + +**Example**: An MCP server might provide access to your company's internal documentation, AWS resources, or a specific database system. + +**Learn more**: [Model Context Protocol](https://modelcontextprotocol.io/) | [MCP Specification](https://spec.modelcontextprotocol.io/) | [Understanding MCP Servers](../understanding-mcp-servers/) + +**Related terms**: [Tools](#tools), [Built-in Tool](#built-in-tool) + +--- + +### Hook + +A shell command or script that runs automatically in response to lifecycle events during a Copilot agent session. Hooks are stored as JSON files in `.github/hooks/` and can trigger on events like session start/end, prompt submission, before/after tool use, and when errors occur. They provide deterministic automation—linting, formatting, governance scanning—that doesn't depend on the AI remembering to do it. + +**Example**: A `postToolUse` hook that runs Prettier after the agent edits files, or a `preToolUse` hook that blocks dangerous shell commands. + +**When to use**: For deterministic automation that must happen reliably, like formatting code, running linters, or auditing prompts for compliance. + +**Learn more**: [Automating with Hooks](../automating-with-hooks/) + +**Related terms**: [Agent](#agent), [Coding Agent](#coding-agent) + +--- + +### Coding Agent + +The autonomous GitHub Copilot agent that works on issues in a cloud environment without continuous human guidance. You assign an issue to Copilot, it spins up a dev environment, implements a solution, runs tests, and opens a pull request for review. + +**Key characteristics**: +- Runs in an isolated cloud environment +- Uses your repository's instructions, agents, skills, and hooks +- Always produces a PR—it can't merge or deploy +- Supports iteration via PR comments + +**When to use**: For well-defined tasks with clear acceptance criteria that can be completed autonomously. + +**Learn more**: [Using the Copilot Coding Agent](../using-copilot-coding-agent/) + +**Related terms**: [Agent](#agent), [Hook](#hook) + +--- + +### Plugin + +An installable package that extends GitHub Copilot CLI with a bundled set of agents, skills, hooks, MCP server configurations, and LSP integrations. Plugins provide a way to distribute and share custom capabilities across projects and teams, with versioning, discovery, and one-command installation via marketplaces. + +**Example**: Installing `database-data-management@awesome-copilot` to get a database specialist agent, migration skills, and schema validation hooks in a single command. + +**When to use**: When you want to share a curated set of Copilot capabilities across multiple projects or team members, or when you want to install community-contributed tooling without manually copying files. + +**Learn more**: [Installing and Using Plugins](../installing-and-using-plugins/) + +**Related terms**: [Agent](#agent), [Skill](#skill), [Hook](#hook) + +--- + +### Tools + +Capabilities that GitHub Copilot can invoke to perform actions or retrieve information. Tools fall into two categories: + +1. **Built-in tools**: Native capabilities like `codebase` (code search), `terminalCommand` (running commands), and `web` (web search) +2. **MCP tools**: External integrations provided by MCP servers (e.g., database queries, cloud resource management, or API calls) + +Agents and skills can specify which tools they require or recommend in their front matter. + +**Example front matter**: +```yaml +tools: ['codebase', 'terminalCommand', 'github'] +``` + +**Related terms**: [MCP](#mcp-model-context-protocol), [Built-in Tool](#built-in-tool), [Agent](#agent) + +--- + +**Have a term you'd like to see added?** Contributions are welcome! See our [Contributing Guidelines](https://github.com/github/awesome-copilot/blob/main/CONTRIBUTING.md) for how to suggest additions to this glossary. diff --git a/website/src/content/learning-hub/installing-and-using-plugins.md b/website/src/content/learning-hub/installing-and-using-plugins.md new file mode 100644 index 00000000..d66b2682 --- /dev/null +++ b/website/src/content/learning-hub/installing-and-using-plugins.md @@ -0,0 +1,249 @@ +--- +title: 'Installing and Using Plugins' +description: 'Learn how to find, install, and manage plugins that extend GitHub Copilot CLI with reusable agents, skills, hooks, and integrations.' +authors: + - GitHub Copilot Learning Hub Team +lastUpdated: '2026-02-26' +estimatedReadingTime: '8 minutes' +tags: + - plugins + - copilot-cli + - fundamentals +relatedArticles: + - ./building-custom-agents.md + - ./creating-effective-skills.md + - ./automating-with-hooks.md +prerequisites: + - GitHub Copilot CLI installed + - Basic understanding of agents, skills, and hooks +--- + +Plugins are installable packages that extend GitHub Copilot CLI with reusable agents, skills, hooks, and servers, all bundled into a single unit you can install with one command. Instead of manually copying agent files and configuring MCP servers across every project, plugins let you install a curated set of capabilities and share them with your team. + +This article explains what plugins contain, how to find and install them, and how to manage your plugin library. + +## What's Inside a Plugin? + +A plugin bundles one or more of the following components: + +| Component | What It Does | File Location | +|-----------|-------------|---------------| +| **Custom Agents** | Specialized AI assistants with tailored expertise | `agents/*.agent.md` | +| **Skills** | Discrete callable capabilities with bundled resources | `skills/*/SKILL.md` | +| **Hooks** | Event handlers that intercept agent behavior | `hooks.json` or `hooks/` | +| **MCP Servers** | Model Context Protocol integrations for external tools | `.mcp.json` or `.github/mcp.json` | +| **LSP Servers** | Language Server Protocol integrations | `lsp.json` or `.github/lsp.json` | + +A plugin might include all of these or just one — for example, a plugin could provide a single specialized agent, or an entire development toolkit with multiple agents, skills, hooks, and MCP server configurations working together. + +### Example: What a Plugin Looks Like + +Here's the structure of a typical plugin: + +``` +my-plugin/ +├── .github/ +│ └── plugin/ +│ └── plugin.json # Plugin manifest (name, description, version) +├── agents/ +│ ├── api-architect.agent.md +│ └── test-specialist.agent.md +├── skills/ +│ └── database-migrations/ +│ ├── SKILL.md +│ └── scripts/migrate.sh +├── hooks.json +└── README.md +``` + +The `plugin.json` manifest declares what the plugin contains: + +```json +{ + "name": "my-plugin", + "description": "API development toolkit with specialized agents and migration skills", + "version": "1.0.0", + "agents": [ + "./agents/api-architect.md", + "./agents/test-specialist.md" + ], + "skills": [ + "./skills/database-migrations/" + ] +} +``` + +## Why Use Plugins? + +You might wonder: why not just copy agent files into your project manually? Plugins provide several advantages: + +| Feature | Manual Configuration | Plugin | +|---------|---------------------|--------| +| **Scope** | Single repository | Any project | +| **Sharing** | Manual copy/paste | `copilot plugin install` command | +| **Versioning** | Git history | Marketplace versions | +| **Discovery** | Searching repositories | Marketplace browsing | +| **Updates** | Manual tracking | `copilot plugin update` | + +Plugins are especially valuable when you want to: + +- **Standardize across a team** — Everyone installs the same plugin for consistent tooling +- **Share domain expertise** — Package a Rails expert, Kubernetes specialist, or security reviewer as an installable unit +- **Encapsulate complex setups** — Bundle MCP server configurations that would otherwise require manual setup +- **Reuse across projects** — Install the same capabilities in every project without duplicating files + +## Finding Plugins + +Plugins are collected in **marketplaces** — registries you can browse and install from. Copilot CLI comes with two marketplaces registered by default: + +- **`copilot-plugins`** — Official GitHub Copilot plugins +- **`awesome-copilot`** — Community-contributed plugins from this repository + +### Browsing a Marketplace + +List your registered marketplaces: + +```bash +copilot plugin marketplace list +``` + +Browse plugins in a specific marketplace: + +```bash +copilot plugin marketplace browse awesome-copilot +``` + +Or from within an interactive Copilot session: + +``` +/plugin marketplace browse awesome-copilot +``` + +> **Tip**: You can also browse plugins on this site's [Plugins Directory](../../plugins/) to see descriptions, included agents, and skills before installing. + +### Adding More Marketplaces + +Register additional marketplaces from GitHub repositories: + +```bash +copilot plugin marketplace add anthropics/claude-code +``` + +Or from a local path: + +```bash +copilot plugin marketplace add /path/to/local-marketplace +``` + +## Installing Plugins + +### From a Registered Marketplace + +The most common way to install a plugin — reference it by name and marketplace: + +```bash +copilot plugin install database-data-management@awesome-copilot +``` + +Or from an interactive session: + +``` +/plugin install database-data-management@awesome-copilot +``` + +## Managing Plugins + +Once installed, plugins are managed with a few simple commands: + +```bash +# List all installed plugins +copilot plugin list + +# Update a plugin to the latest version +copilot plugin update my-plugin + +# Remove a plugin +copilot plugin uninstall my-plugin +``` + +### Where Plugins Are Stored + +- **Marketplace plugins**: `~/.copilot/installed-plugins/MARKETPLACE/PLUGIN-NAME/` +- **Direct installs**: `~/.copilot/installed-plugins/_direct/PLUGIN-NAME/` + +## How Plugins Work at Runtime + +When you install a plugin, its components become available to Copilot CLI automatically: + +- **Agents** appear in your agent selection (use with `/agent` or the agents dropdown) +- **Skills** are loaded automatically when relevant to your current task +- **Hooks** run at the configured lifecycle events during agent sessions +- **MCP servers** extend the tools available to agents + +You don't need to do any additional configuration after installing — the plugin's components integrate seamlessly into your workflow. + +## Plugins from This Repository + +This repository (`awesome-copilot`) serves as both a collection of individual resources _and_ a plugin marketplace. You can use it in two ways: + +### Install Individual Plugins + +Browse the [Plugins Directory](../../plugins/) and install specific plugins: + +```bash +copilot plugin install context-engineering@awesome-copilot +copilot plugin install azure-cloud-development@awesome-copilot +copilot plugin install frontend-web-dev@awesome-copilot +``` + +Each plugin bundles related agents and skills around a specific theme or technology. + +### Use Individual Resources Without Plugins + +If you only need a single agent or skill (rather than a full plugin), you can still copy individual files from this repo directly into your project: + +- Copy an `.agent.md` file into `.github/agents/` +- Copy a skill folder into `.github/skills/` +- Copy a hook configuration into `.github/hooks/` + +See [Using the Copilot Coding Agent](../using-copilot-coding-agent/) for details on this approach. + +## Best Practices + +- **Start with a marketplace plugin** before building your own — there may already be one that fits your needs +- **Keep plugins focused** — a plugin for "Rails development" is better than a plugin for "everything" +- **Check for updates regularly** — run `copilot plugin update` to get the latest improvements +- **Review what you install** — plugins run code on your machine, so inspect unfamiliar plugins before installing +- **Use plugins for team standards** — publish an internal plugin to ensure every team member has the same agents, skills, and hooks +- **Remove unused plugins** — declutter with `copilot plugin uninstall` to keep your environment clean + +## Common Questions + +**Q: Do plugins work with the coding agent on GitHub.com?** + +A: Plugins are specific to GitHub Copilot CLI and the VS Code extension (currently Insiders). For the coding agent on GitHub.com, add agents, skills, and hooks directly to your repository (via a plugin if you prefer!). See [Using the Copilot Coding Agent](../using-copilot-coding-agent/) for details. + +**Q: Can I use plugins and repository-level configuration together?** + +A: Yes. Plugin components are merged with your repository's local agents, skills, and hooks. Local configuration takes precedence if there are conflicts. + +**Q: How do I create my own plugin?** + +A: Create a directory with a `plugin.json` manifest and your agents/skills/hooks. See the [GitHub docs on creating plugins](https://docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/plugins-creating) for a step-by-step guide. + +**Q: Can I share plugins within my organization?** + +A: Yes. You can create a private plugin marketplace in an internal GitHub repository, then have team members register it with `copilot plugin marketplace add org/internal-plugins`. + +**Q: What happens if I uninstall a plugin?** + +A: The plugin's agents, skills, and hooks are removed from Copilot. Any work already done with those tools is unaffected — only future sessions lose access. + +## Next Steps + +- **Browse Plugins**: Explore the [Plugins Directory](../../plugins/) for installable plugin packages +- **Create Skills**: [Creating Effective Skills](../creating-effective-skills/) — Build skills that can be included in plugins +- **Build Agents**: [Building Custom Agents](../building-custom-agents/) — Create agents to package in plugins +- **Add Hooks**: [Automating with Hooks](../automating-with-hooks/) — Configure hooks for plugin automation + +--- diff --git a/website/src/content/learning-hub/understanding-copilot-context.md b/website/src/content/learning-hub/understanding-copilot-context.md new file mode 100644 index 00000000..067bee56 --- /dev/null +++ b/website/src/content/learning-hub/understanding-copilot-context.md @@ -0,0 +1,172 @@ +--- +title: 'Understanding Copilot Context' +description: 'Learn how GitHub Copilot uses context from your code, workspace, and conversation to generate relevant suggestions.' +authors: + - GitHub Copilot Learning Hub Team +lastUpdated: '2025-11-28' +estimatedReadingTime: '8 minutes' +tags: + - context + - fundamentals + - how-it-works +relatedArticles: + - ./what-are-agents-skills-instructions.md +--- + +Context is the foundation of how GitHub Copilot generates relevant, accurate suggestions. Understanding what Copilot "sees" and how it uses that information helps you write better prompts, get higher-quality completions, and work more effectively with AI assistance. This article explains the types of context Copilot uses and how to optimize your development environment for better results. + +## What Copilot Sees + +When GitHub Copilot generates a suggestion or responds to a chat message, it analyzes multiple sources of information from your development environment: + +**Open Files**: Copilot can access content from files currently open in your editor. Having relevant files visible gives Copilot important context about your codebase structure, naming conventions, and coding patterns. + +**Current Cursor Position**: The exact location of your cursor matters. Copilot considers the surrounding code—what comes before and after—to understand your current intent and generate contextually appropriate suggestions. + +**Related Files**: Through imports, references, and dependencies, Copilot identifies files related to your current work. For example, if you're editing a component that imports a utility function, Copilot may reference that utility file to understand available functionality. + +**Chat Conversation History**: In GitHub Copilot Chat, previous messages in your conversation provide context for follow-up questions. This allows for natural, iterative problem-solving where each response builds on earlier exchanges. + +**Workspace Structure**: The organization of your project—directory structure, configuration files, and patterns—helps Copilot understand the type of project you're working on and follow appropriate conventions. + +## Types of Context + +GitHub Copilot leverages four distinct types of context to inform its suggestions: + +### Editor Context + +Editor context includes the active files displayed in your editor and the specific code visible on screen. When you have multiple files open in tabs or split views, Copilot can reference all of them to provide more informed suggestions. + +**Example**: If you're writing a function that calls methods from a class defined in another open file, Copilot can suggest the correct method names and parameter types by referencing that class definition. + +### Semantic Context + +Semantic context goes beyond raw text to understand the meaning and relationships in your code. This includes function signatures, type definitions, interface contracts, class hierarchies, and inline comments that explain complex logic. + +**Example**: When you're implementing an interface, Copilot uses the interface definition as semantic context to suggest correct method signatures with appropriate parameter types and return values. + +### Conversation Context + +In GitHub Copilot Chat, conversation context includes all previous messages, questions, and responses in the current chat session. This enables contextual follow-ups where you can ask "What about error handling?" and Copilot understands you're referring to the code discussed earlier. + +**Example**: After asking Copilot to generate a database query function, you can follow up with "Add error handling and logging" without repeating the full context—Copilot remembers the previous exchange. + +### Workspace Context + +Workspace context includes project-level information like your directory structure, configuration files (`.gitignore`, `package.json`, `tsconfig.json`), and overall repository organization. This helps Copilot understand your project type, dependencies, and conventions. + +**Example**: If your workspace contains a `package.json` with TypeScript and React dependencies, Copilot recognizes this is a TypeScript React project and generates suggestions using appropriate patterns and types. + +## How Context Influences Suggestions + +Context directly impacts the relevance, accuracy, and usefulness of GitHub Copilot's suggestions. More context generally leads to better suggestions. + +### Example: Code Completion with Context + +**Without Context** (only the current file open): + +```typescript +// user.ts +function getUserById(id: string) { + // Copilot might suggest generic database code + const user = db.query('SELECT * FROM users WHERE id = ?', [id]); + return user; +} +``` + +**With Context** (database utility file also open): + +```typescript +// database.ts (open in another tab) +export async function queryOne(sql: string, params: any[]): Promise { + // ... implementation +} + +// user.ts (current file) +function getUserById(id: string) { + // Copilot now suggests using the existing utility + return queryOne('SELECT * FROM users WHERE id = ?', [id]); +} +``` + +By having the `database.ts` file open, Copilot recognizes the existing utility function and suggests using it instead of generating generic database code. + +### Example: Chat with File References + +**Without @-mention**: + +``` +You: How do I handle validation? + +Copilot: Here's a general approach to validation... +[provides generic validation code] +``` + +**With #-mention**: + +``` +You: How do I handle validation in #user-service.ts? + +Copilot: Based on your UserService class, you can add validation like this... +[provides code specific to your UserService implementation] +``` + +Using `#` to reference specific files gives Copilot precise context about which code you're asking about. + +### Token Limits and Context Prioritization + +GitHub Copilot has a maximum token limit for how much context it can process at once. When you have many files open or a long chat history, Copilot prioritizes: + +1. **Closest proximity**: Code immediately surrounding your cursor +2. **Explicitly referenced files**: Files you @-mention in chat for CLI, and #-mention for IDEs (VS Code, Visual Studio, JetBrains, etc.) +3. **Recently modified files**: Files you've edited recently +4. **Direct dependencies**: Files imported by your current file + +Understanding this prioritization helps you optimize which files to keep open and when to use explicit references. + +## Context Best Practices + +Maximize GitHub Copilot's effectiveness by providing clear, relevant context: + +**Keep related files open**: If you're working on a component, keep its test file, related utilities, and type definitions open in tabs or split views. + +**Use descriptive names**: Choose clear variable names, function names, and class names that convey intent. `getUserProfile()` provides more context than `getData()`. + +**Add clarifying comments**: For complex algorithms or business logic, write comments explaining the "why" behind the code. Copilot uses these to understand your intent. + +**Structure your workspace logically**: Organize files in meaningful directories that reflect your application architecture. Clear structure helps Copilot understand relationships between components. + +**Use #-mentions in chat**: When asking questions, explicitly reference files with `#filename` to ensure Copilot analyzes the exact code you're discussing. + +**Provide examples in prompts**: When asking Copilot to generate code, include examples of your existing patterns and conventions. + +## Common Questions + +**Q: Does Copilot see my entire repository?** + +A: No, Copilot doesn't automatically analyze all files in your repository. It focuses on open files, recently modified files, and files directly referenced by your current work. For large codebases, this selective approach ensures fast response times while still providing relevant context. + +**Q: How do I know what context Copilot is using?** + +A: In GitHub Copilot Chat, you can see which files are being referenced in responses. When Copilot generates suggestions, it's primarily using your currently open files and the code immediately surrounding your cursor. Using `#workspace` in chat explicitly searches across your entire repository. + +**Q: Can I control what context is included?** + +A: Yes, you have several ways to control context: +- Open/close files to change what's available to Copilot +- Use `#` mentions to explicitly reference specific files, symbols or functions +- Configure `.gitignore` to exclude files from workspace context +- Use instructions and skills to provide persistent context for specific scenarios + +**Q: Does closing a file remove it from context?** + +A: Yes, closing a file can remove it from Copilot's active context. However, files you've recently worked with may still influence suggestions briefly. For a clean context reset, you can restart your editor or start a new chat session. + +## Next Steps + +Now that you understand how context works in GitHub Copilot, explore these related topics: + +- **[What are Agents, Skills, and Instructions](../what-are-agents-skills-instructions/)** - Learn about customization types that provide persistent context +- **[Copilot Configuration Basics](../copilot-configuration-basics/)** - Configure settings to optimize context usage +- **[Creating Effective Skills](../creating-effective-skills/)** - Use context effectively in your skills +- **Common Pitfalls and Solutions** _(coming soon)_ - Avoid context-related mistakes diff --git a/website/src/content/learning-hub/understanding-mcp-servers.md b/website/src/content/learning-hub/understanding-mcp-servers.md new file mode 100644 index 00000000..ef4b0277 --- /dev/null +++ b/website/src/content/learning-hub/understanding-mcp-servers.md @@ -0,0 +1,223 @@ +--- +title: 'Understanding MCP Servers' +description: 'Learn how Model Context Protocol servers extend GitHub Copilot with access to external tools, databases, and APIs.' +authors: + - GitHub Copilot Learning Hub Team +lastUpdated: '2026-02-26' +estimatedReadingTime: '8 minutes' +tags: + - mcp + - tools + - fundamentals +relatedArticles: + - ./building-custom-agents.md + - ./what-are-agents-skills-instructions.md +prerequisites: + - Basic understanding of GitHub Copilot agents +--- + +GitHub Copilot's built-in tools—code search, file editing, terminal access—cover a wide range of tasks. But real-world workflows often need access to external systems: databases, cloud APIs, monitoring dashboards, or internal services. That's where MCP servers come in. + +This article explains what MCP is, how to configure servers, and how agents use them to accomplish tasks that would otherwise require context-switching. + +## What Is MCP? + +The **Model Context Protocol (MCP)** is an open standard for connecting AI assistants to external data sources and tools. An MCP server is a lightweight process that exposes capabilities—called **tools**—that Copilot can invoke during a conversation. + +Think of MCP servers as bridges: + +``` +GitHub Copilot ←→ MCP Server ←→ External System + (bridge) (database, API, etc.) +``` + +**Key characteristics**: +- MCP is an open protocol, not specific to GitHub Copilot—it works across AI tools +- Servers run locally on your machine or in a container +- Each server exposes one or more tools with defined inputs and outputs +- Agents and users can invoke MCP tools naturally during conversation + +### Built-in vs MCP Tools + +GitHub Copilot provides several **built-in tools** that are always available: + +| Built-in Tool | What It Does | +|--------------|--------------| +| `codebase` | Search and analyze code across the repository | +| `terminal` | Run shell commands in the integrated terminal | +| `edit` | Create and modify files in the workspace | +| `fetch` | Make HTTP requests to URLs | +| `search` | Search across workspace files | +| `github` | Interact with GitHub APIs | + +**MCP tools** extend this with external capabilities: + +| MCP Server Example | What It Adds | +|-------------------|--------------| +| PostgreSQL server | Query databases, inspect schemas, analyze query plans | +| Docker server | Manage containers, inspect logs, deploy services | +| Sentry server | Fetch error reports, analyze crash data | +| Figma server | Read design tokens, component specs | + +## Configuring MCP Servers + +MCP servers are configured per-workspace in `.vscode/mcp.json`: + +```json +{ + "servers": { + "postgres": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-postgres"], + "env": { + "DATABASE_URL": "postgresql://user:pass@localhost:5432/mydb" + } + }, + "filesystem": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem", "./docs"] + } + } +} +``` + +### Configuration Fields + +**command**: The executable to run the MCP server (e.g., `npx`, `python`, `docker`). + +**args**: Arguments passed to the command. Most MCP servers are distributed as npm packages and can be run with `npx -y`. + +**env**: Environment variables passed to the server process. Use these for connection strings, API keys, and configuration—never hardcode secrets in the JSON file. + +### Common MCP Server Configurations + +**PostgreSQL** — Query databases and inspect schemas: +```json +{ + "postgres": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-postgres"], + "env": { + "DATABASE_URL": "${input:databaseUrl}" + } + } +} +``` + +**GitHub** — Extended GitHub API access: +```json +{ + "github": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-github"], + "env": { + "GITHUB_TOKEN": "${input:githubToken}" + } + } +} +``` + +**Filesystem** — Controlled access to specific directories: +```json +{ + "filesystem": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem", "./data", "./config"] + } +} +``` + +> **Security tip**: Use `${input:variableName}` for sensitive values. VS Code will prompt for these at runtime rather than storing them in the file. + +## How Agents Use MCP Tools + +When an agent declares an MCP server in its `tools` array, Copilot can invoke that server's capabilities during conversation: + +```yaml +--- +name: 'Database Administrator' +description: 'Expert DBA for PostgreSQL performance tuning and schema design' +tools: ['codebase', 'terminal', 'postgres'] +--- +``` + +With this configuration, the agent can: +- Run SQL queries to inspect table structures +- Analyze query execution plans +- Suggest index optimizations based on actual data +- Compare schema changes against the live database + +### Example Conversation + +``` +User: The users page is loading slowly. Can you figure out why? + +Agent: Let me check the query that powers the users page. +[Searches codebase for user listing query] +[Runs EXPLAIN ANALYZE via postgres MCP server] + +I found the issue. The query on user_profiles is doing a sequential scan +on 2.4M rows. Here's what I recommend: + +CREATE INDEX idx_user_profiles_active ON user_profiles (is_active) + WHERE is_active = true; + +This should reduce the query time from ~3.2s to ~15ms based on the +current data distribution. +``` + +Without the MCP server, the agent would have to guess at database structure and performance characteristics. With it, the agent works with real data. + +## Finding MCP Servers + +The MCP ecosystem is growing rapidly. Here are key resources: + +- **[Official MCP Servers](https://github.com/modelcontextprotocol/servers)**: Reference implementations for common services (PostgreSQL, Slack, Google Drive, etc.) +- **[MCP Specification](https://spec.modelcontextprotocol.io/)**: The protocol specification for building your own servers +- **[Awesome MCP Servers](https://github.com/punkpeye/awesome-mcp-servers)**: Community-curated list of MCP servers + +### Building Your Own MCP Server + +If your team has internal tools or proprietary APIs, you can build custom MCP servers. The protocol supports three main capability types: + +| Capability | Description | Example | +|-----------|-------------|---------| +| **Tools** | Functions the AI can invoke | `query_database`, `deploy_service` | +| **Resources** | Data the AI can read | Database schemas, API docs | +| **Prompts** | Pre-built conversation templates | Common troubleshooting flows | + +MCP server SDKs are available in [Python](https://github.com/modelcontextprotocol/python-sdk), [TypeScript](https://github.com/modelcontextprotocol/typescript-sdk), and other languages. Browse the [Agents Directory](../../agents/) for examples of agents built around MCP server expertise. + +## Best Practices + +- **Principle of least privilege**: Only give MCP servers the minimum access they need. Use read-only database connections for analysis agents. +- **Keep secrets out of config files**: Use `${input:variableName}` for API keys and connection strings, or load from environment variables. +- **Document your servers**: Add comments or a README explaining which MCP servers your project uses and why. +- **Version control carefully**: Commit `.vscode/mcp.json` for shared server configurations, but use `.gitignore` for any files containing credentials. +- **Test server connectivity**: Verify MCP servers start correctly before relying on them in agent workflows. + +## Common Questions + +**Q: Do MCP servers run in the cloud?** + +A: No, MCP servers typically run locally on your machine as child processes. They're started automatically when needed and stopped when the session ends. + +**Q: Can I use MCP servers without custom agents?** + +A: Yes. Once configured in `.vscode/mcp.json`, MCP tools are available in any Copilot Chat session. Custom agents simply make it easier to pre-select the right tools for a workflow. + +**Q: Are MCP servers secure?** + +A: MCP servers run with the same permissions as your user account. Follow least-privilege principles: use read-only database connections, scope API tokens narrowly, and review server code before trusting it. + +**Q: How many MCP servers can I configure?** + +A: There's no hard limit, but each server is a running process. Configure only the servers you actively use. Most projects use 1–3 servers. + +## Next Steps + +- **Build Agents**: [Building Custom Agents](../building-custom-agents/) — Create agents that leverage MCP tools +- **Explore Examples**: Browse the [Agents Directory](../../agents/) for agents built around MCP server integrations +- **Protocol Deep Dive**: [MCP Specification](https://spec.modelcontextprotocol.io/) — Learn the protocol details for building your own servers + +--- diff --git a/website/src/content/learning-hub/using-copilot-coding-agent.md b/website/src/content/learning-hub/using-copilot-coding-agent.md new file mode 100644 index 00000000..4a4f467a --- /dev/null +++ b/website/src/content/learning-hub/using-copilot-coding-agent.md @@ -0,0 +1,413 @@ +--- +title: 'Using the Copilot Coding Agent' +description: 'Learn how to use GitHub Copilot coding agent to autonomously work on issues, generate pull requests, and automate development tasks.' +authors: + - GitHub Copilot Learning Hub Team +lastUpdated: '2026-02-26' +estimatedReadingTime: '12 minutes' +tags: + - coding-agent + - automation + - agentic +relatedArticles: + - ./building-custom-agents.md + - ./automating-with-hooks.md + - ./creating-effective-skills.md +prerequisites: + - Understanding of GitHub Copilot agents + - Repository with GitHub Copilot enabled +--- + +The Copilot coding agent is an autonomous agent that can work on GitHub issues without continuous human guidance. You assign it an issue, it spins up a cloud environment, writes code, runs tests, and opens a pull request—all while you focus on other work. Think of it as a junior developer who never sleeps, handles the well-defined tasks, and always asks for review. + +This article explains how the coding agent works, how to set it up, and best practices for getting the most out of autonomous coding sessions. + +## How It Works + +The coding agent follows a straightforward workflow: + +``` +1. You assign an issue to Copilot (or @mention it) + ↓ +2. Copilot spins up a cloud dev environment + ↓ +3. It reads the issue, your instructions, and codebase + ↓ +4. It plans and implements a solution + ↓ +5. It runs tests and validates the changes + ↓ +6. It opens a pull request for your review +``` + +The agent works in its own branch, in an isolated environment. It can't merge code or deploy—it always produces a PR that a human must review and approve. + +**Key characteristics**: +- Runs in a secure, sandboxed cloud environment +- Uses your repository's instructions, agents, and skills for context +- Executes hooks (linting, formatting) automatically +- Creates a PR with a summary of what it did and why +- Supports iterating—you can comment on the PR and the agent will refine + +## Setting Up the Environment + +The coding agent needs to know how to set up your project. Define this in `.github/copilot-setup-steps.yml`: + +```yaml +# .github/copilot-setup-steps.yml +steps: + - name: Install dependencies + run: npm ci + + - name: Build the project + run: npm run build + + - name: Verify tests pass + run: npm test +``` + +### What to Include + +Think of this file as bootstrapping instructions for a new developer joining the project: + +**Language runtimes**: If your project needs a specific Node.js, Python, or Go version, install it here. + +**Dependencies**: Install all project dependencies (`npm ci`, `pip install -r requirements.txt`, `bundle install`). + +**Build step**: Compile the project if needed, so the agent can verify its changes build successfully. + +**Test command**: Run the test suite so the agent can validate its changes don't break existing functionality. + +**Example for a Python project**: +```yaml +steps: + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: Install dependencies + run: pip install -r requirements.txt + + - name: Run tests + run: pytest +``` + +**Example for a multi-language project**: +```yaml +steps: + - name: Install Node.js dependencies + run: npm ci + + - name: Install Python dependencies + run: pip install -r requirements.txt + + - name: Build frontend + run: npm run build + + - name: Run all tests + run: npm test && pytest +``` + +## Assigning Work to the Coding Agent + +There are several ways to trigger the coding agent: + +### From a GitHub Issue + +1. Create a well-described issue with clear acceptance criteria +2. Assign the issue to **Copilot** (it appears as an assignee option) +3. The agent starts working within minutes + +### From a Comment + +On any issue, comment: +``` +@copilot work on this +``` + +Or provide more specific direction: +``` +@copilot implement the user avatar upload feature described above. +Use the existing FileUpload component and S3 service. +``` + +### Using Custom Agents + +Custom agents let you give the coding agent a specialized persona, toolset, and instructions for specific types of work. Instead of relying on generic behavior, you can point the coding agent at an agent profile tailored for your task. + +**Where custom agents live**: Agent profiles are stored as `.agent.md` files in `.github/agents/` in your repository. For organization-wide agents, place them in the root `agents/` directory. + +``` +.github/ +└── agents/ + ├── api-architect.agent.md + ├── test-specialist.agent.md + └── security-reviewer.agent.md +``` + +**Selecting an agent on GitHub.com**: When prompting the coding agent or assigning it to an issue, use the dropdown menu in the agents panel to select your custom agent instead of the default. + +**Selecting an agent via comment**: On any issue, mention the agent by name: + +``` +@copilot use the api-architect agent to implement this API endpoint +``` + +The agent will adopt the persona, tools, and guardrails defined in that agent file. + +**What goes in an agent profile**: An `.agent.md` file is a Markdown file with YAML frontmatter defining the agent's name, description, available tools, and optionally MCP server configurations. The Markdown body contains the agent's behavioral instructions (up to 30,000 characters). + +```markdown +--- +name: test-specialist +description: Focuses on test coverage, quality, and testing best practices +tools: ["read", "edit", "search", "bash"] +--- + +You are a testing specialist. Analyze existing tests, identify coverage gaps, +and write comprehensive unit and integration tests. Follow best practices for +the language and framework. Never modify production code unless asked. +``` + +> **Tip**: Browse the [Agents Directory](../../agents/) on this site for ready-to-use agent profiles you can add to your repository. + +## Writing Effective Issues for the Coding Agent + +The coding agent is only as good as the issue it receives. Well-structured issues lead to better results. + +### Good Issue Structure + +```markdown +## Summary +Add a rate limiter to the /api/login endpoint to prevent brute force attacks. + +## Requirements +- Limit to 5 attempts per IP address per 15-minute window +- Return HTTP 429 with a Retry-After header when limit is exceeded +- Use the existing Redis cache for rate tracking +- Log rate limit violations to our security audit log + +## Acceptance Criteria +- [ ] Rate limiter middleware is applied to POST /api/login +- [ ] Tests cover: normal login, rate limit hit, rate limit reset +- [ ] Existing login tests continue to pass + +## Context +- Rate limiter utility exists at src/middleware/rate-limiter.ts +- Redis client is configured in src/config/redis.ts +- Security audit logger is at src/utils/security-logger.ts +``` + +### Tips for Better Results + +- **Be specific**: "Add input validation" is vague. "Validate email format and password length (8+ chars) on the registration endpoint" is actionable. +- **Point to existing code**: Reference files, utilities, and patterns the agent should use. +- **Define done**: List acceptance criteria or test cases that verify the work is complete. +- **Scope appropriately**: Single-feature issues work best. Break large features into smaller issues. +- **Include constraints**: If there are things the agent should NOT do ("don't modify the database schema"), say so explicitly. + +## Working with the Pull Request + +When the coding agent finishes, it opens a PR with: + +- A description of changes and the reasoning behind them +- File-by-file summaries of what changed +- References back to the original issue + +### Reviewing the PR + +Review coding agent PRs like any other: + +1. **Read the summary**: Understand what the agent did and why +2. **Check the diff**: Verify the implementation matches your expectations +3. **Run tests locally**: Confirm tests pass in your environment +4. **Leave comments**: If something needs to change, comment on the PR + +### Iterating with Comments + +If the PR needs adjustments, comment directly: + +``` +@copilot the rate limiter should use a sliding window, not a fixed window. +Also, add a test for the Retry-After header value. +``` + +The agent will read your feedback, make changes, and push new commits to the same PR. + +## Agent Skills and the Coding Agent + +Agent skills are folders of instructions, scripts, and resources that the coding agent can automatically load when relevant to a task. While custom agents define _who_ does the work, skills define _how_ to do specific types of work. + +### How Skills Work with the Coding Agent + +When the coding agent works on a task, it reads the `description` field in each skill's `SKILL.md` and decides whether that skill is relevant. If so, the skill's instructions are injected into the agent's context — giving it access to specialized guidance, scripts, and examples without you needing to specify anything. + +This means you can add skills to your repository and the coding agent will **automatically** leverage them when appropriate. + +### Where Skills Live + +Skills are stored in a `skills/` subdirectory, with each skill in its own folder: + +**Project skills** (specific to one repository): +``` +.github/ +└── skills/ + ├── github-actions-debugging/ + │ └── SKILL.md + ├── database-migrations/ + │ ├── SKILL.md + │ └── scripts/ + │ └── migrate.sh + └── api-testing/ + ├── SKILL.md + └── references/ + └── test-template.ts +``` + +**Personal skills** (shared across all your projects): +``` +~/.copilot/ +└── skills/ + └── code-review-checklist/ + └── SKILL.md +``` + +### What Makes Skills Powerful + +Unlike simple instructions, skills can bundle additional resources: + +- **Scripts** that the agent can execute (e.g., a migration script, a code generator) +- **Templates** and examples the agent can reference +- **Data files** and reference material for specialized domains +- **Supplementary Markdown** files with detailed guidance + +The `SKILL.md` file tells the agent when and how to use these resources: + +```markdown +--- +name: database-migrations +description: 'Guide for creating safe database migrations. Use when asked to modify database schema or create migrations.' +--- + +When creating database migrations, follow this process: + +1. Run `./scripts/check-schema.sh` to validate current state +2. Create a new migration file following the naming convention: `YYYYMMDD_description.sql` +3. Always include a rollback section +4. Test the migration against a local database before committing +``` + +### Skills vs Instructions vs Agents + +| Feature | Instructions | Skills | Custom Agents | +|---------|-------------|--------|---------------| +| When loaded | Always (matching file patterns) | Automatically when relevant | When explicitly selected | +| Best for | Coding standards, style guides | Specialized task guidance | Role-based personas | +| Can include scripts | No | Yes | No (but can reference skills) | +| Scope | File-pattern based | Task-based | Session-wide | + +> **Tip**: Browse the [Skills Directory](../../skills/) for ready-to-use skills you can add to your repository. Each skill includes a `SKILL.md` and any bundled assets needed. + +## Leveraging Community Resources + +This repository provides a curated collection of agents, skills, and hooks designed for the coding agent. Here's how to use them: + +### Adding Agents from This Repo + +1. Browse the [Agents Directory](../../agents/) for agents matching your needs +2. Copy the `.agent.md` file into your repository's `.github/agents/` directory +3. The agent will be available in the dropdown when assigning work to the coding agent + +### Adding Skills from This Repo + +1. Browse the [Skills Directory](../../skills/) for specialized skills +2. Copy the entire skill folder into your repository's `.github/skills/` directory +3. The coding agent will automatically use the skill when it's relevant to a task + +### Adding Hooks from This Repo + +1. Browse the [Hooks Directory](../../hooks/) for automation hooks +2. Copy the `hooks.json` content into a file in `.github/hooks/` in your repository +3. Copy any referenced scripts alongside it +4. The hooks will run automatically during coding agent sessions + +> **Example workflow**: Combine a `test-specialist` agent with a `database-migrations` skill and a linting hook. Assign an issue to the coding agent using the test-specialist agent — it will automatically pick up the migrations skill when relevant, and the hook ensures all code is formatted before completion. + +## Hooks and the Coding Agent + +Hooks are especially valuable with the coding agent because they provide deterministic guardrails for autonomous work: + +- **`preToolUse`**: Approve or deny tool executions — block dangerous commands and enforce security policies +- **`postToolUse`**: Format code, run linters, and validate changes after edits +- **`agentStop`**: Run final checks (e.g., full lint pass) when the agent finishes responding +- **`sessionStart`**: Log the start of autonomous sessions for governance +- **`sessionEnd`**: Send notifications when the agent finishes + +See [Automating with Hooks](../automating-with-hooks/) for configuration details. + +## Best Practices + +### Setting Up for Success + +- **Invest in `copilot-setup-steps.yml`**: A reliable setup means the agent can build and test confidently. If tests are flaky, the agent will struggle. +- **Add comprehensive instructions**: The agent reads your `.github/instructions/` files. The more context you provide about patterns and conventions, the better the output. +- **Create skills for repeatable tasks**: If your team frequently does a specific type of work (migrations, API endpoints, test suites), create a skill with step-by-step guidance the agent can follow automatically. +- **Use custom agents for specialized roles**: Create focused agent profiles for different types of work — a security reviewer, a test specialist, or an infrastructure expert. +- **Define hooks for formatting**: Hooks ensure the agent's code meets your style requirements automatically, reducing review friction. + +### Choosing the Right Tasks + +The coding agent excels at: +- ✅ Well-defined feature implementations with clear acceptance criteria +- ✅ Bug fixes with reproducible steps +- ✅ Adding tests to existing code +- ✅ Refactoring with specific goals (extract function, rename, etc.) +- ✅ Documentation updates based on code changes + +It's less suited for: +- ❌ Ambiguous design decisions that need team discussion +- ❌ Large architectural changes spanning many files +- ❌ Tasks requiring access to external systems not in the dev environment +- ❌ Performance optimization without clear metrics + +### Security Considerations + +- The coding agent works in an isolated environment—it can't access your local machine +- It can only modify code in its branch—it can't push to main or deploy +- All changes go through PR review before merging +- Use hooks to enforce security scanning on every commit +- Scope repository permissions appropriately + +## Common Questions + +**Q: How long does the coding agent take?** + +A: Typically 5–30 minutes depending on the complexity of the task and the size of the codebase. You'll receive a notification when the PR is ready. + +**Q: Can I use the coding agent with private repositories?** + +A: Yes. The coding agent works with both public and private repositories where GitHub Copilot is enabled. + +**Q: What if the agent gets stuck?** + +A: The agent has built-in timeouts. If it can't make progress, it will open a PR with what it has and explain what it couldn't resolve. You can then comment with guidance or take over manually. + +**Q: Can I assign multiple issues at once?** + +A: Yes. The coding agent can work on multiple issues in parallel, each in its own branch. Use Mission Control on GitHub.com to track all active agent sessions. + +**Q: Does the coding agent use my custom agents and skills?** + +A: Yes. You can specify which agent to use when assigning work — the coding agent adopts that agent's persona, tools, and guardrails. Skills are loaded automatically when the agent determines they're relevant to the task, based on the skill's description. + +## Next Steps + +- **Set Up Your Environment**: Create `.github/copilot-setup-steps.yml` for your project +- **Create Skills**: [Creating Effective Skills](../creating-effective-skills/) — Build skills the coding agent can use automatically +- **Add Guardrails**: [Automating with Hooks](../automating-with-hooks/) — Ensure code quality in autonomous sessions +- **Build Custom Agents**: [Building Custom Agents](../building-custom-agents/) — Create specialized agents for the coding agent to use +- **Explore Configuration**: [Copilot Configuration Basics](../copilot-configuration-basics/) — Set up repository-level customizations +- **Browse Community Resources**: Explore the [Agents](../../agents/), [Skills](../../skills/), and [Hooks](../../hooks/) directories for ready-to-use resources + +--- diff --git a/website/src/content/learning-hub/what-are-agents-skills-instructions.md b/website/src/content/learning-hub/what-are-agents-skills-instructions.md new file mode 100644 index 00000000..a5a70e01 --- /dev/null +++ b/website/src/content/learning-hub/what-are-agents-skills-instructions.md @@ -0,0 +1,93 @@ +--- +title: 'What are Agents, Skills, and Instructions' +description: 'Understand the primary customization primitives that extend GitHub Copilot for specific workflows.' +authors: + - GitHub Copilot Learning Hub Team +lastUpdated: '2026-02-26' +estimatedReadingTime: '7 minutes' +--- + +Building great experiences with GitHub Copilot starts with understanding the core primitives that shape how Copilot behaves in different contexts. This article clarifies what each artifact does, how it is packaged inside this repository, and when to use it. + +## Agents + +Agents are configuration files (`*.agent.md`) that describe: + +- The tasks they specialize in (for example, "Terraform Expert" or "LaunchDarkly Flag Manager"). +- Which tools or MCP servers they can invoke. +- Optional instructions that guide the conversation style or guardrails. + +When you assign an issue to Copilot or open the **Agents** panel in VS Code, these configurations let you swap in a specialized assistant. Each agent in this repo lives under `agents/` and includes metadata about the tools it depends on. + +### When to reach for an agent + +- You have a recurring workflow that benefits from deep tooling integrations. +- You want Copilot to proactively execute commands or fetch context via MCP. +- You need persona-level guardrails that persist throughout a coding session. + +## Skills + +Skills are self-contained folders that package reusable capabilities for GitHub Copilot. Each skill lives in its own directory and contains a `SKILL.md` file along with optional bundled assets such as reference documents, templates, and scripts. + +A `SKILL.md` defines: + +- A **name** (used as a `/command` in VS Code Chat and for agent discovery). +- A **description** that tells agents and users when the skill is relevant. +- Detailed instructions for how the skill should be executed. +- References to any bundled assets the skill needs. + +Skills follow the open [Agent Skills specification](https://agentskills.io/home), making them portable across coding agent systems beyond GitHub Copilot. + +### Why skills over prompts + +Skills replace the earlier prompt file (`*.prompt.md`) pattern and offer several advantages: + +- **Agent discovery**: Skills include extended frontmatter that lets agents find and invoke them automatically—prompts could only be triggered manually via a slash command. +- **Richer context**: Skills can bundle reference files, scripts, templates, and other assets alongside their instructions, giving the AI much more to work with. +- **Cross-platform portability**: The Agent Skills specification is supported across multiple coding agent systems, so your investment travels with you. +- **Slash command support**: Like prompts, skills can still be invoked via `/command` in VS Code Chat. + +### When to reach for a skill + +- You want to standardize how Copilot responds to a recurring task. +- You need bundled resources (templates, schemas, scripts) to complete the task. +- You want agents to discover and invoke the capability automatically. +- You prefer to drive the conversation, but with guardrails and rich context. + +## Instructions + +Instructions (`*.instructions.md`) provide background context that Copilot reads whenever it works on matching files. They often contain: + +- Coding standards or style guides (naming conventions, testing strategy). +- Framework-specific hints (Angular best practices, .NET analyzers to suppress). +- Repository-specific rules ("never commit secrets", "feature flags must live in `flags/`"). + +Instructions sit under `instructions/` and can be scoped globally, per language, or per directory using glob patterns. They help Copilot align with your engineering playbook automatically. + +### When to reach for instructions + +- You need persistent guidance that applies across many sessions. +- You are codifying architecture decisions or compliance requirements. +- You want Copilot to understand patterns without manually pasting context. + +## How the artifacts work together + +Think of these artifacts as complementary layers: + +1. **Instructions** lay the groundwork with long-lived guardrails. +2. **Skills** let you trigger rich, reusable workflows on demand—and let agents discover those workflows automatically. +3. **Agents** bring the most opinionated behavior, bundling tools and instructions into a single persona. + +By combining all three, teams can achieve: + +- Consistent onboarding for new developers. +- Repeatable operations tasks with reduced context switching. +- Tailored experiences for specialized domains (security, infrastructure, data science, etc.). + +## Next steps + +- Explore the rest of the **Fundamentals** track for deeper dives on chat modes, collections, and MCP servers. +- Browse the [Awesome Agents](../../agents/), [Skills](../../skills/), and [Instructions](../../instructions/) directories for inspiration. +- Try generating your own artifacts, then add them to the repo to keep the Learning Hub evolving. + +--- diff --git a/website/src/layouts/ArticleLayout.astro b/website/src/layouts/ArticleLayout.astro new file mode 100644 index 00000000..9eb2dc48 --- /dev/null +++ b/website/src/layouts/ArticleLayout.astro @@ -0,0 +1,132 @@ +--- +import BaseLayout from './BaseLayout.astro'; +import { getCollection } from 'astro:content'; +import { fundamentalsOrder, referenceOrder } from '../config/learning-hub'; + +interface Props { + title: string; + description?: string; + estimatedReadingTime?: string; + lastUpdated?: string; + tags?: string[]; +} + +const { title, description, estimatedReadingTime, lastUpdated, tags } = Astro.props; +const base = import.meta.env.BASE_URL; + +const createOrderIndexMap = (order: string[]) => { + const map = new Map(); + for (let i = 0; i < order.length; i += 1) { + map.set(order[i], i); + } + return map; +}; + +const articles = await getCollection('learning-hub'); + +const fundamentalsOrderIndex = createOrderIndexMap(fundamentalsOrder); +const referenceOrderIndex = createOrderIndexMap(referenceOrder); + +const fundamentals = articles + .filter((a) => fundamentalsOrderIndex.has(a.id)) + .sort( + (a, b) => + (fundamentalsOrderIndex.get(a.id) ?? 0) - (fundamentalsOrderIndex.get(b.id) ?? 0), + ); + +const reference = articles + .filter((a) => referenceOrderIndex.has(a.id)) + .sort( + (a, b) => + (referenceOrderIndex.get(a.id) ?? 0) - (referenceOrderIndex.get(b.id) ?? 0), + ); + +const currentSlug = Astro.url.pathname.replace(/\/$/, '').split('/').pop(); +--- + + +
+ + +
+
+
+ +
+ +
+
+
+
+
+
diff --git a/website/src/layouts/BaseLayout.astro b/website/src/layouts/BaseLayout.astro index c28eb7a8..9f36f048 100644 --- a/website/src/layouts/BaseLayout.astro +++ b/website/src/layouts/BaseLayout.astro @@ -106,8 +106,8 @@ try { class:list={[{ active: activeNav === "tools" }]}>Tools SamplesLearning Hub
diff --git a/website/src/pages/index.astro b/website/src/pages/index.astro index 4a66b8e6..bcfcab4f 100644 --- a/website/src/pages/index.astro +++ b/website/src/pages/index.astro @@ -81,6 +81,13 @@ const base = import.meta.env.BASE_URL;
-
+ + +
+

Learning Hub

+

Articles and guides to master GitHub Copilot

+
+
diff --git a/website/src/pages/learning-hub/[slug].astro b/website/src/pages/learning-hub/[slug].astro new file mode 100644 index 00000000..689431d4 --- /dev/null +++ b/website/src/pages/learning-hub/[slug].astro @@ -0,0 +1,25 @@ +--- +import ArticleLayout from '../../layouts/ArticleLayout.astro'; +import { getCollection, render } from 'astro:content'; + +export async function getStaticPaths() { + const articles = await getCollection('learning-hub'); + return articles.map((article) => ({ + params: { slug: article.id }, + props: { article }, + })); +} + +const { article } = Astro.props; +const { Content } = await render(article); +--- + + + + diff --git a/website/src/pages/samples.astro b/website/src/pages/learning-hub/cookbook/index.astro similarity index 92% rename from website/src/pages/samples.astro rename to website/src/pages/learning-hub/cookbook/index.astro index 7cd17618..34e1ba3c 100644 --- a/website/src/pages/samples.astro +++ b/website/src/pages/learning-hub/cookbook/index.astro @@ -1,15 +1,18 @@ --- -import BaseLayout from '../layouts/BaseLayout.astro'; -import Modal from '../components/Modal.astro'; +import BaseLayout from '../../../layouts/BaseLayout.astro'; +import Modal from '../../../components/Modal.astro'; const base = import.meta.env.BASE_URL; --- - +
@@ -243,6 +246,6 @@ const base = import.meta.env.BASE_URL; diff --git a/website/src/pages/learning-hub/index.astro b/website/src/pages/learning-hub/index.astro new file mode 100644 index 00000000..b350c4a1 --- /dev/null +++ b/website/src/pages/learning-hub/index.astro @@ -0,0 +1,158 @@ +--- +import BaseLayout from '../../layouts/BaseLayout.astro'; +import { getCollection } from 'astro:content'; +import { fundamentalsOrder, referenceOrder } from '../../config/learning-hub'; + +const base = import.meta.env.BASE_URL; +const articles = await getCollection('learning-hub'); + +const createOrderIndexMap = (order) => { + const map = new Map(); + order.forEach((id, index) => { + map.set(id, index); + }); + return map; +}; + +const fundamentalsOrderIndex = createOrderIndexMap(fundamentalsOrder); +const referenceOrderIndex = createOrderIndexMap(referenceOrder); + +const fundamentals = articles + .filter((a) => fundamentalsOrder.includes(a.id)) + .sort((a, b) => fundamentalsOrderIndex.get(a.id) - fundamentalsOrderIndex.get(b.id)); + +const reference = articles + .filter((a) => referenceOrder.includes(a.id)) + .sort((a, b) => referenceOrderIndex.get(a.id) - referenceOrderIndex.get(b.id)); +--- + + +
+ + +
+
+
+ + + +
+
+
+
+