Skip to main content

Best practices for GitHub Copilot CLI

Learn how to get the most out of GitHub Copilot 命令行界面.

Introduction

GitHub Copilot 命令行界面 is a terminal-native AI coding assistant that brings agentic capabilities directly to your command line. Copilot 命令行界面(CLI) can operate like a chatbot, answering your questions, but its true power lies in its ability to work autonomously as your coding partner, allowing you to delegate tasks and oversee its work.

This article provides tips for getting the most out of Copilot 命令行界面(CLI), from using the various CLI commands effectively to managing the CLI's access to files. Consider these tips as starting points, then experiment to find out what works best for your workflows.

注意

GitHub Copilot 命令行界面 is continually evolving. Use the /help command to see the most up to date information.

1. Customize your environment

Use custom instructions files

Copilot 命令行界面(CLI) automatically reads instructions from multiple locations, allowing you to define organization-wide standards and repository-specific conventions.

Supported locations (in order of discovery):

LocationScope
~/.copilot/copilot-instructions.mdAll sessions (global)
.github/copilot-instructions.mdRepository
.github/instructions/**/*.instructions.mdRepository (modular)
AGENTS.md (in Git root or cwd)Repository
Copilot.md, GEMINI.md, CODEX.mdRepository

Best practice

Repository instructions always take precedence over global instructions. Use this to enforce team conventions. For example, this is a simple .github/copilot-instructions.md file.

## Build Commands
- `npm run build` - Build the project
- `npm run test` - Run all tests
- `npm run lint:fix` - Fix linting issues

## Code Style
- Use TypeScript strict mode
- Prefer functional components over class components
- Always add JSDoc comments for public APIs

## Workflow
- Run `npm run lint:fix && npm test` after making changes
- Commit messages follow conventional commits format
- Create feature branches from `main`

提示

Keep instructions concise and actionable. Lengthy instructions can dilute effectiveness.

For more information, see 关于自定义 GitHub Copilot 响应.

Configure allowed tools

Manage which tools Copilot can run without asking for permission. When Copilot requests permission for an action, you can choose to Allow once, or Always allow to add the tool to your allowlist for this and future sessions.

To reset previously approved tools, use:

/reset-allowed-tools

You can also preconfigure allowed tools via CLI flags:

copilot --allow-tool 'shell(git:*)' --deny-tool 'shell(git push)'

Common permission patterns:

  • shell(git:*) — Allow all Git commands
  • shell(npm run:*) — Allow all npm scripts
  • shell(npm run test:*) — Allow npm test commands
  • write — Allow file writes

Select your preferred model

Use /model to choose from available models based on your task complexity:

ModelBest ForTradeoffs
Claude Opus 4.5 (default)Complex architecture, difficult debugging, nuanced refactoringMost capable but uses more premium requests
Claude Sonnet 4.5Day-to-day coding, most routine tasksFast, cost-effective, handles most work well
GPT-5.2 CodexCode generation, code review, straightforward implementationsExcellent for reviewing code produced by other models

Recommendations:

  • Opus 4.5 is ideal for tasks requiring deep reasoning, complex system design, subtle bug investigation, or extensive context understanding.
  • Switch to Sonnet 4.5 for routine tasks where speed and cost efficiency matter—it handles the majority of everyday coding effectively.
  • Use Codex for high-volume code generation and as a second opinion for reviewing code produced by other models.

You can switch models mid-session with /model as task complexity changes.

2. Plan before you code

Plan mode

Models achieve higher success rates when given a concrete plan to follow. In plan mode, Copilot will create a structured implementation plan before any code is written.

Press Shift+Tab to toggle between normal mode and plan mode. In plan mode, all prompts you enter will trigger the plan workflow.

Alternatively, you can use the /plan command in normal mode to achieve the same effect.

Example prompt (from normal mode):

/plan Add OAuth2 authentication with Google and GitHub providers

What happens:

  • Copilot analyzes your request and codebase.
  • Asks clarifying questions to align on requirements and approach.
  • Creates a structured implementation plan with checkboxes.
  • Saves the plan to plan.md in your session folder.
  • Waits for your approval before implementing.

You can press Ctrl+y to view and edit the plan in your default editor for Markdown files.

Example plan output:

# Implementation Plan: OAuth2 Authentication

## Overview
Add social authentication using OAuth2 with Google and GitHub providers.

## Tasks
- [ ] Install dependencies (passport, passport-google-oauth20, passport-github2)
- [ ] Create authentication routes in `/api/auth`
- [ ] Implement passport strategies for each provider
- [ ] Add session management middleware
- [ ] Create login/logout UI components
- [ ] Add environment variables for OAuth credentials
- [ ] Write integration tests

## Detailed Steps
1. **Dependencies**: Add to package.json...
2. **Routes**: Create `/api/auth/google` and `/api/auth/github`...

When to use plan mode

ScenarioUse plan mode?
Complex multi-file changes
Refactoring with many touch points
New feature implementation
Quick bug fixes
Single file changes

The explore → plan → code → commit workflow

For best results on complex tasks:

  • Explore:

    Read the authentication files but don't write code yet

  • Plan:

    /plan Implement password reset flow

  • Review:

    Check the plan, suggest modifications

  • Implement:

    Proceed with the plan

  • Verify:

    Run the tests and fix any failures

  • Commit:

    Commit these changes with a descriptive message

3. Leverage infinite sessions

Automatic context window management

Copilot 命令行界面(CLI) features infinite sessions. You don't need to worry about running out of context. The system automatically manages context through intelligent compaction that summarizes conversation history while preserving essential information.

Session storage location:

~/.copilot/session-state/{session-id}/
├── events.jsonl      # Full session history
├── workspace.yaml    # Metadata
├── plan.md           # Implementation plan (if created)
├── checkpoints/      # Compaction history
└── files/            # Persistent artifacts

注意

If you ever need to manually trigger compaction, use /compact. This is rarely necessary since the system handles it automatically.

Session management commands

# View session info
/session

# View checkpoint history
/session checkpoints

# View files in session
/session files

# View current plan
/session plan

Best practice: Keep sessions focused

While infinite sessions allow long-running work, focused sessions produce better results:

  • Use /clear or /new between unrelated tasks.
  • This resets context and improves response quality.
  • Think of it like starting a fresh conversation with a colleague.

The /context command

Visualize your current context usage with /context. It shows a breakdown of:

  • System/tools tokens
  • Message history tokens
  • Available free space
  • Buffer allocation

4. Delegate work effectively

The /delegate command

Offload work to run in the cloud using Copilot 编码智能体. This is particularly powerful for:

  • Tasks that can run asynchronously.
  • Changes to other repositories.
  • Long-running operations you don't want to wait for.

Example prompt:

/delegate Add dark mode support to the settings page

What happens:

  • Your request is sent to Copilot 编码智能体.
  • The agent creates a pull request with the changes.
  • You can continue working locally while the cloud agent works.

When to use /delegate

Use /delegateWork locally
Tangential tasksCore feature work
Documentation updatesDebugging
Refactoring separate modulesInteractive exploration

5. Common workflows

Codebase onboarding

Use Copilot 命令行界面(CLI) as your pair programming partner when joining a new project. For example, you could ask Copilot:

  • How is logging configured in this project?
  • What's the pattern for adding a new API endpoint?
  • Explain the authentication flow
  • Where are the database migrations?

Test-driven development

Pair with Copilot 命令行界面(CLI) to develop tests.

  • Write failing tests for the user registration flow
  • Review and approve the tests.
  • Now implement code to make all tests pass
  • Review the implementation.
  • Commit with message "feat: add user registration"

Code review assistance

  • /review Use Opus 4.5 and Codex 5.2 to review the changes in my current branch against `main`. Focus on potential bugs and security issues.

Git operations

Copilot excels at Git workflows:

  • What changes went into version `2.3.0`?
  • Create a PR for this branch with a detailed description
  • Rebase this branch against `main`
  • Resolve the merge conflicts in `package.json`

Bug investigation

  • The `/api/users` endpoint returns 500 errors intermittently. Search the codebase and logs to identify the root cause.

Refactoring

  • /plan Migrate all class components to functional components with hooks

    Then answer the questions Copilot asks. Review the plan it creates, and ask Copilot to make changes if necessary. When you are happy with the plan you can prompt:

    Implement this plan

6. Advanced patterns

Work across multiple repositories

Copilot 命令行界面(CLI) provides flexible multi-repository workflows—a key differentiator for teams working on microservices, monorepos, or related projects.

Option 1: Run from a parent directory

# Navigate to a parent directory containing multiple repos
cd ~/projects
copilot

Copilot can now access and work across all child repositories simultaneously. This is ideal for:

  • Microservices architectures
  • Making coordinated changes across related repos
  • Refactoring shared patterns across projects

Option 2: Use /add-dir to expand access

# Start in one repo, then add others (requires full paths)
copilot
/add-dir /Users/me/projects/backend-service
/add-dir /Users/me/projects/shared-libs
/add-dir /Users/me/projects/documentation

View and manage allowed directories:

/list-dirs

Example workflow: coordinated API changes

I need to update the user authentication API. The changes span:

- @/Users/me/projects/api-gateway (routing changes)
- @/Users/me/projects/auth-service (core logic)
- @/Users/me/projects/frontend (client updates)

Start by showing me the current auth flow across all three repos.

This multi-repository capability enables:

  • Cross-cutting refactors (update a shared pattern everywhere)
  • API contract changes with client updates
  • Documentation that references multiple codebases
  • Dependency upgrades across a monorepo

Using images for UI work

Copilot can work with visual references. Simply drag and drop images directly into the CLI input, or reference image files:

Implement this design: @mockup.png
Match the layout and spacing exactly

Checklists for complex migrations

For large-scale changes:

Run the linter and write all errors to `migration-checklist.md` as a checklist.
Then fix each issue one by one, checking them off as you go.

7. Team guidelines

  • Create .github/copilot-instructions.md with:

    • Build and test commands
    • Code style guidelines
    • Required checks before commits
    • Architecture decisions
  • Establish conventions for:

    • When to use /plan (complex features, refactoring)
    • When to use /delegate (tangential work)
    • Code review processes with AI assistance

Security considerations

  • Copilot 命令行界面(CLI) requires explicit approval for potentially destructive operations.
  • Review all proposed changes before accepting.
  • Use permission allowlists judiciously.
  • Never commit secrets. Copilot is designed to avoid this, but always verify.

Measuring productivity

Track metrics like:

  • Time from issue to pull request
  • Number of iterations before merge
  • Code review feedback cycles
  • Test coverage improvements

Getting help

# In-CLI help
/help

# View usage statistics
/usage

# Submit feedback
/feedback

Further reading