AI Pair Programming with GitHub Copilot
Copilot started the whole category — the autocomplete that made "AI pair programmer" a real phrase. It has since grown chat, an agent mode, and code review, all wired into GitHub. This chapter covers Copilot's surfaces, how to get good suggestions, and the model-choice and governance angles that come with the most widely deployed AI dev tool.
Learning objectives
- Use Copilot's surfaces: completions, chat, agent, review.
- Get better suggestions with context and comments.
- Choose models and use Copilot in the GitHub workflow.
- Govern Copilot across an org.
code/ad5-copilot/ in the course, with a README on how to run it. Read here, run there — no need to copy-paste.1 · The tool that started the category essential
Copilot began as the autocomplete that coined "AI pair programmer." It's now the most widely deployed AI dev tool, with completions, chat, an agent mode, and PR review — all wired into GitHub. Its reach and governance features are its distinguishing edge.
2 · The surfaces essential
| Surface | Use for |
|---|---|
| Ghost-text completions | inline next-line suggestions |
| Copilot Chat | ask about code, generate, explain |
| Agent mode | multi-step tasks in the IDE |
| PR review / summaries | review + describe pull requests |
3 · Intermediate — steering the suggestions intermediate
Copilot reads open files, nearby code, and your comments. Better inputs = better output: write a clear docstring/signature first, keep relevant files open, and describe intent in a comment right above where you want code.
steer.pydef parse_iso_duration(text: str) -> int:
"""Parse an ISO-8601 duration like 'PT1H30M' into total seconds.
Supports hours (H), minutes (M), seconds (S) after 'PT'. Raises ValueError."""
import re
m = re.fullmatch(r"PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?", text)
if not m or text == "PT":
raise ValueError(f"bad duration: {text}")
h, mi, s = (int(x) if x else 0 for x in m.groups())
return h*3600 + mi*60 + s
print(parse_iso_duration("PT1H30M")) # 5400
print(parse_iso_duration("PT45S")) # 45
5400
45
This lab shows the contract-first way to use Copilot. You don't write the logic yourself — you write a precise contract (the function name, its inputs and output type, and a docstring saying exactly what it should do), and Copilot fills in the body. Here the function turns an ISO-8601 duration like PT1H30M (1 hour 30 minutes) into a plain number of seconds.
def parse_iso_duration(text: str) -> int:is the signature — the contract's header. It says: give me one string calledtext, and I hand back anint. Those type hints (: str,-> int) tell both Copilot and a human reader what goes in and what comes out.- The triple-quoted
"""..."""lines are the docstring — a plain-English spec of the job: parse hours/minutes/seconds afterPT, and raise an error on bad input. This is the highest-signal prompt you can give Copilot; it turns "guess what I want" into "implement this." re.fullmatch(...)is a regular expression — a pattern that checks the whole string matches the shapePTthen optionalH/M/Sgroups. If it doesn't match (or the string is just"PT"), the coderaises aValueError— its way of saying "that input is invalid."h*3600 + mi*60 + sdoes the arithmetic: each hour is 3600 seconds, each minute is 60, plus the leftover seconds. The line above it turns each captured piece into a number, using0when a piece is missing.
What the output means: PT1H30M is 1 hour + 30 minutes = 3600 + 1800 = 5400 seconds, and PT45S is just 45 seconds — exactly the two lines printed.
Try this: Delete everything from import re down to the return, keep only the signature and docstring, and let Copilot re-suggest the body. Then tighten the docstring (say, "also support days (D)") and watch the suggestion change — the clearer the contract, the more often Copilot's first guess is right.
4 · Advanced — model choice & the GitHub workflow advanced
Copilot now lets you pick the underlying model (including Claude models) per task — reasoning models for hard problems, fast ones for completions. And it lives in the whole GitHub flow: issues → agent → PR → Copilot review, so AI spans the loop, not just the editor.
5 · Professional — trust but verify professional
Copilot suggestions can be subtly wrong, outdated, or insecure. Keep the same bar as human code: tests, review, and never accept security-relevant code on faith. Its ubiquity makes complacency the real risk — treat every suggestion as a draft.
6 · Tech-lead — org-wide governance tech-lead
At org scale a lead configures Copilot centrally: content exclusions (repos/paths the model never sees), a policy on public-code matching, seat management, and audit. Because Copilot is so widely used, getting these controls right is a compliance issue, not a preference — the governance surface is a big reason enterprises pick it.
Exercise AD5.1 — Contract-first suggestions
Context: Copilot is at its best when you give it a contract to satisfy. Writing precise signatures with docstrings and watching the first-suggestion hit rate rise shows directly how contract clarity drives quality.
Your task: Write three function signatures with precise docstrings, let Copilot fill the bodies, and note how contract clarity changes the hit rate.
Requirements:
- Write three function signatures each with a precise docstring (like
steer.py) - Let Copilot fill each body from the contract
- Note how often the first suggestion is correct
- Observe how the clarity of the contract changes the first-suggestion hit rate
💡 Hint: The precise signature + docstring is the highest-signal prompt — the clearer the contract, the more often the first suggestion is right.
🪜 Practice ladder beginner → industry
Six graded exercises, easy to real-world. Try each before opening its solution.
Context: Copilot started the category with inline completion and has grown into chat and GitHub-native features. Knowing which surface is best for which task is the foundation for using it well.
Your task: Name Copilot's main surfaces (inline completion, chat, PR/workflow features) and give the one task each is best at.
Requirements:
- Inline completion (ghost text): finishing the line/block you're already writing — instant, in-flow
- Copilot Chat: explaining code, scoped edits, generating a test or function on request
- GitHub workflow features: summarizing a diff, suggesting review comments, answering ‘what changed’
- Note Copilot began as inline completion and extended toward workflow assistance
💡 Hint: Map each surface to the size and stage of the task — a keystroke, a scoped request, or a whole PR.
Show solution
| Surface | Best at |
|---|---|
| Inline completion (ghost text) | Finishing the line/block you're already writing — instant, in-flow |
| Copilot Chat | Explaining code, scoped edits, generating a test or function on request |
| GitHub workflow (PR summaries, review, Copilot in the repo) | Summarizing a diff, suggesting review comments, answering ‘what changed’ |
Copilot started the category with inline completion; the chat and GitHub-native features extend it from ‘autocomplete’ toward workflow assistance.
Context: Copilot predicts from surrounding code, open files, and what you've typed — so you steer it by shaping that context, not by wishing harder. Two concrete moves do most of the work.
Your task: Show two concrete ways to steer Copilot toward the completion you want, given that its suggestions are driven by nearby context.
Requirements:
- Explain that Copilot predicts from surrounding code, open files, and typed text
- Move 1: write a precise signature + docstring first, then let it fill the body toward that contract
- Move 2: keep a relevant example / sibling function open nearby to bias it toward your conventions
- Conclude the lever is context: a clear name, types, docstring, and nearby example turn vague suggestions into on-target ones
💡 Hint: A typed signature plus a docstring is the highest-signal prompt you can give — it turns ‘guess what I want’ into ‘implement this spec.’
Show solution
Copilot predicts from the surrounding code, open files, and what you've typed — so you steer it by shaping that context, not by wishing harder.
- Write a precise signature + docstring first, then let it fill the body:
def parse_iso_timestamp(s: str) -> datetime: """Parse an ISO-8601 string; raise ValueError if invalid. Assume UTC if no tz.""" # Copilot now completes toward THIS contract - Keep a relevant example open / nearby — a sibling function in the same style biases completions toward your conventions. Open the file you want it to imitate.
The lever is context: a clear name, types, docstring, and a nearby example turn vague suggestions into on-target ones.
Context: Copilot now lets you pick among models and integrates at the PR level — both change how you work, but the PR features especially risk reviewers rubber-stamping an AI summary instead of reviewing.
Your task: Say when you'd switch Copilot models and how PR-level features change the review loop.
Requirements:
- Model choice: fast/cheap model for routine completion; stronger reasoning model for hard multi-step logic, tricky debugging, or architecture questions
- Match model to the difficulty and stakes of the task
- PR features (diff summaries, suggested review comments) speed a reviewer's first pass
- State the risk: reviewers rubber-stamping the AI summary; keep human sign-off on correctness and design
- Frame the summary as a starting point to orient, not the review itself
💡 Hint: Use the strong model where a wrong answer costs more than the extra latency, and let PR summaries orient you, not decide for you.
Show solution
Model choice: use a fast/cheap model for routine completion and boilerplate; switch to a stronger reasoning model for hard, multi-step logic, tricky debugging, or architecture questions where a wrong answer costs more than the extra latency. Match model to the difficulty and stakes of the task.
PR-level features change the loop: Copilot can summarize a diff and suggest review comments, which speeds a reviewer's first pass — but its summary is a starting point, not the review. The risk is reviewers rubber-stamping the AI summary. Keep human sign-off on correctness and design; use the summary to orient, not to decide.
Context: Inline completion is fast but subtly degrades quality over time: it suggests the statistically likely next code, nudging you toward conventional — and sometimes subtly wrong — patterns, and it amplifies existing mistakes in nearby code.
Your task: Describe a subtle way inline completion degrades code quality over time and the habit that counters it.
Requirements:
- Name the degradation: convergence to the plausible-average (common-but-wrong patterns that look right)
- Note the second effect: it completes toward nearby code, propagating an existing mistake into new functions
- Explain the shift from actively designing to ratifying suggestions
- Give the counter-habit: treat each accepted suggestion as a diff to review, pausing to ask ‘is this correct, or just likely?’
- Add: fix bad nearby patterns quickly because Copilot amplifies them
💡 Hint: The danger is accepting the flow — pause on anything non-trivial and ask whether it's correct or merely the most likely next tokens.
Show solution
Subtle degradation: convergence to the plausible-average. Completion suggests the most statistically likely next code, which nudges you toward conventional patterns — including subtly wrong ones (off-by-one, wrong default, deprecated idiom) that look right because they're common. Accepting the flow repeatedly means you stop actively designing and start ratifying.
A second effect: it completes toward the shape of nearby code, so an existing mistake gets propagated into every new function.
Counter-habit: treat each accepted suggestion as a diff to review, not typing to approve — pause on anything non-trivial and ask ‘is this correct, or just likely?’ And fix bad nearby patterns quickly, because Copilot will amplify them.
Context: Copilot's speed of authoring is real; the professional discipline is a ‘trust but verify’ checklist applied before the suggestion becomes your commit — because you sign the commit, not Copilot.
Your task: Write the ‘trust but verify’ checklist a professional applies to Copilot output before committing.
Requirements:
- Correctness: does it handle edge cases (empty, null, boundary, error paths) or only the happy path it pattern-matched?
- Security: no hard-coded secrets, no injection-prone string-building, no insecure default
- Provenance/licensing: be wary of a large verbatim block; use duplication detection
- Fit: does it use our utilities and conventions or reinvent them?
- Tests: is the behavior pinned by a test, especially for generated branches?
- State the framing: trust the authoring speed, verify correctness/security/fit — you sign the commit
💡 Hint: Verify the dimensions tests can't see — security, provenance, and fit — not just whether it runs.
Show solution
- Correctness: does it handle the edge cases (empty, null, boundary, error paths), or only the happy path it pattern-matched?
- Security: no hard-coded secrets, no injection-prone string-building, no insecure default it copied.
- Provenance/licensing: for a large verbatim block, be wary of copied licensed code; use the org's duplication-detection setting.
- Fit: does it use our utilities and conventions, or reinvent them?
- Tests: is the behavior pinned by a test, especially for the branches it generated?
Trust the speed of authoring; verify the correctness, security, and fit before it becomes your commit — you sign the commit, not Copilot.
Context: Because Copilot is the most widely deployed AI dev tool, complacency is the real enterprise risk. Governance is about controlling data flow and preserving review discipline while capturing the velocity — and measuring both sides.
Your task: Design the governance to roll Copilot out across an enterprise with security and compliance obligations: policy, controls, and metrics.
Requirements:
- Data/IP controls: duplication filtering, configure what code context may be sent, confirm enterprise data-handling terms meet policy
- Secrets: secret-scanning in CI as a hard gate; never rely on the model to avoid leaking
- Review: AI-authored code reviewed like any code, author accountable, PR summaries orient but don't replace review
- Access: scope which repos/teams have it; keep sensitive repos opted out if required
- Pilot + written acceptable-use policy before broad enablement; review settings quarterly
- Measure both velocity (PR throughput, time-to-first-commit) and quality (defect/incident rate, security findings) to catch a bad trade
💡 Hint: The failure mode is enabling it as a checkbox and measuring only speed — watch data flow, review discipline, and quality signals too.
Show solution
| Area | Control |
|---|---|
| Data / IP | Enable duplication filtering; configure what code context may be sent; confirm the enterprise data-handling terms meet policy |
| Secrets | Secret-scanning in CI as a hard gate; never rely on the model to avoid leaking |
| Review | AI-authored code reviewed like any code; author accountable; PR summaries orient reviewers but don't replace review |
| Access | Scope which repos/teams have it; keep sensitive repos opted out if required |
| Training | Teach steering + verify habits, not just install it |
- Pilot & policy first: a written acceptable-use policy (verification required, no unowned code) before broad enablement.
- Measure both sides: velocity (PR throughput, time-to-first-commit) and quality (defect rate, security findings, incident rate) so you catch a speed-for-quality trade early.
- Review quarterly: models and features change fast; revisit settings and policy.
Lesson: enterprise governance is about controlling data flow and preserving review discipline while capturing the velocity — the failure mode is enabling it as a checkbox and measuring only speed.
✓ Checkpoint — you can move on when you can…
- Use completions/chat/agent/review appropriately.
- Steer with contracts + context.
- Choose models; use the full GitHub loop.
- Verify every suggestion; govern Copilot org-wide.
Knowledge check check yourself
The parse_iso_duration lab demonstrates "contract-first" use of Copilot. Why is a precise signature plus docstring called the highest-signal prompt you can give it?
Show answer
Copilot is described as the most widely deployed AI dev tool, and the lesson says its ubiquity makes complacency the real risk. How does that reframe an org lead's governance job?