00.4 GitHub and Collaboration

FoundationsLesson 4 of 915,446 words9 parts
Module 00 · 0 of 9 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9

Lesson 00.3 taught you git: commits, branches, merges and the daily loop, all on your own machine. This lesson is about the other half of the story — GitHub, the place where almost every professional software project lives. You will learn what GitHub actually is (and how it differs from git itself and from competitors like GitLab and Bitbucket), how to create and secure an account, how to push your ai-path workspace to a remote repository, how to authenticate with SSH keys, the GitHub CLI and personal access tokens, the full pull-request workflow from fork to merge, how issues and GitHub-flavoured Markdown work, the collaboration files and branch protections real teams use, a working overview of GitHub Actions, the security features that watch your repository for leaked secrets and vulnerable dependencies, and how to turn your GitHub profile into the portfolio Module 14B builds on. Nearly everything can be practised offline; the parts that need a free GitHub account are clearly marked.

What you'll learn

  • The difference between git (the tool), GitHub (the host plus collaboration layer) and alternatives like GitLab and Bitbucket — and what GitHub adds on top of a bare remote
  • Creating and securing a GitHub account: profile, two-factor authentication, recovery codes, and what the Free, Pro, Team and Enterprise plans actually include as of November 2026
  • Public vs private repositories, READMEs, .gitignore templates, and how to choose a licence (MIT, Apache-2.0, GPL and friends)
  • Remotes in depth: origin, fetch vs pull vs push, upstream tracking, and a complete offline simulation of a hosted remote using git init --bare
  • Authentication: HTTPS with the GitHub CLI credential helper vs SSH keys (Ed25519 end to end), classic vs fine-grained personal access tokens, and the rules for never letting a token into a URL, a commit or a log
  • The GitHub CLI (gh): installing it on macOS, Windows and Linux, and the commands that replace most website clicking — repos, pull requests, issues, releases, workflow runs
  • The pull-request workflow end to end: fork vs branch, writing PRs reviewers can actually review, draft PRs, requesting reviewers, review comments and suggestions, addressing feedback, force-push etiquette, the three merge strategies, and deleting branches
  • Code review as a skill, including how to review code an AI assistant wrote for you
  • Issues, projects and discussions: bug-report and feature-request templates, labels, milestones, linking PRs to issues, and the GitHub-flavoured Markdown that makes all of it readable (task lists, alerts, mentions, collapsible sections, Mermaid diagrams)
  • Collaboration files and norms: CONTRIBUTING.md, CODE_OF_CONDUCT.md, SECURITY.md, CODEOWNERS, templates, branch protection and rulesets, semantic versioning, releases and changelogs, trunk-based development vs Git Flow, and monorepos vs polyrepos
  • GitHub Actions in one lesson: what CI is, the anatomy of a workflow file (on, jobs, steps, uses, run, secrets, matrix), a minimal Python test workflow, secrets vs variables, why you pin third-party actions, and what Pages and Codespaces are
  • Security on GitHub: secret scanning and push protection, Dependabot alerts and updates, dependency review, private vulnerability reporting, signed commits, and exactly what to do when a key leaks anyway
  • Your portfolio on GitHub: profile READMEs, pinned repositories and what makes a README good — the preview of Module 14B

What you don't need

  • Any API key or paid plan. A free GitHub account unlocks the online exercises; everything else runs offline with git alone.
  • Deep git knowledge — lesson 00.3 owns commits, branches, merges and conflict resolution. This lesson uses those skills constantly but explains them only as far as collaboration needs.
  • Experience with YAML, though Part 7 introduces the small subset GitHub Actions needs.

Setup

You need git (installed and configured in 00.3), a text editor, and — for the online parts — a free account at github.com. The GitHub CLI is optional but strongly recommended; install it with the official instructions for your system (verified as of November 2026, from the GitHub CLI repository):

bash
# macOS (Homebrew — installed in 00.1)
brew install gh

# Windows (in PowerShell; open a NEW terminal window afterwards so PATH refreshes)
winget install --id GitHub.cli --source winget

# Debian/Ubuntu (WSL or Linux) — official apt repository
(type -p wget >/dev/null || (sudo apt update && sudo apt install wget -y)) \
  && sudo mkdir -p -m 755 /etc/apt/keyrings \
  && out=$(mktemp) && wget -nv -O$out https://cli.github.com/packages/githubcli-archive-keyring.gpg \
  && cat $out | sudo tee /etc/apt/keyrings/githubcli-archive-keyring.gpg > /dev/null \
  && sudo chmod go+r /etc/apt/keyrings/githubcli-archive-keyring.gpg \
  && sudo mkdir -p -m 755 /etc/apt/sources.list.d \
  && echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" \
     | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null \
  && sudo apt update && sudo apt install gh -y

# Fedora/RHEL family — gh lives in the official gh-cli repo, which must be
# added first (DNF5 form shown; on DNF4 use --add-repo instead of addrepo --from-repofile)
sudo dnf config-manager addrepo --from-repofile=https://cli.github.com/packages/rpm/gh-cli.repo
sudo dnf install gh

Verify with gh --version. Then gh auth login walks you through signing in (Part 3.5 covers it). No API key needed anywhere in this lesson — gh uses its own sign-in, not a provider key.


What you must be able to do after this lesson#

  • Explain the difference between git and GitHub
  • Create a GitHub account and secure it with two-factor authentication
  • Connect to GitHub with SSH or HTTPS and never put a token in a URL
  • Open a pull request and respond to review comments
  • Review a pull request, including code written by an AI assistant
  • Keep tokens and secrets out of a repository

Why this matters for an AI engineer#

Git and GitHub are the plumbing under everything else in this path. Every later module assumes you can keep a project under version control, keep secrets out of it, and collaborate on it without losing work.

You'll hear... You'll understand it after...
"Just open a PR against main." Part 4: The pull-request workflow
"Can you review this before I merge?" 4.7 Code review as a skill
"Push your branch and I'll take a look." 3.1 What a remote is
"Set up SSH so you don't paste tokens." 3.4 SSH keys end to end
"Use a fine-grained token with only Contents read." 3.6 Personal access tokens
"CI is red on your PR." Part 7: GitHub Actions
"Dependabot opened a bump PR." 8.2 Dependabot and dependency review
"Did you enable push protection?" 8.1 Secret scanning and push protection
"Tag v1.2.0 and write release notes." 6.3 Releases and versioning
"Fork it and send me a PR." 4.2 Fork vs branch
"Your profile README is empty." Part 9: Your portfolio on GitHub
"Never commit .env — it's in .gitignore, right?" 2.4 .gitignore and templates and 8.6 A local secret scanner

Part 1: Git vs GitHub vs the alternatives#

1.1 The mental model: three different things#

People say "git" and "GitHub" interchangeably, but they're three separate layers:

Layer What it is Analogy
git A program on your computer that versions files. Works with no network, no account, no company. The engine of a car
A git host A server that stores git repositories and adds collaboration features around them The car itself, plus the dealership
GitHub The most popular git host, owned by Microsoft, plus a huge ecosystem of apps, Actions, Packages, Codespaces and Pages The dealership and the parts market, service network and road rules

A repository (often shortened to repo) is the unit everything hangs off: one project, one folder of history plus the hosting features attached to it. When you git clone from GitHub, you're downloading a copy of the repository — after that, git works exactly as it did in 00.3, on your machine, offline. GitHub only enters the picture when you push, pull, open a pull request, or use its website and API.

1.2 What a host adds that git alone can't#

Git itself has no concept of users, permissions, pull requests, issues or CI. Those are all hosting features. The table below maps the thing you'll actually do to the layer that provides it.

Thing you do Provided by
git commit, git merge, git rebase git (local)
Store a backup copy of the repo off your laptop Any git host (GitHub, GitLab, Bitbucket, or even a bare repo on a USB stick)
Let a teammate see your work before it lands on main The host's pull request feature
Track bugs and feature requests The host's issues
Run tests automatically on every push The host's CI (GitHub Actions, GitLab CI, etc.)
Control who can push, merge or change settings The host's permissions and branch protection
Publish a static site GitHub Pages, GitLab Pages, Netlify, ...
Package management, code search, a project board Host-specific extras

This is why "I use git" and "I use GitHub" are different claims: the first is a skill, the second is an ecosystem. The skills transfer — GitLab and Bitbucket repos speak the same git protocol — but the features and the UI don't.

1.3 GitLab and Bitbucket#

GitHub GitLab Bitbucket
Owner Microsoft (acquired 2018) GitLab Inc. (public company) Atlassian
Strongest at Community, open source, Actions ecosystem, Copilot/AI tooling Integrated DevOps platform (CI, registry, wiki in one product), self-managed option Tight Jira/Confluence integration for Atlassian shops
CI product GitHub Actions GitLab CI/CD Bitbucket Pipelines
Free tier Generous for public repos; limited private-repo features Similar shape; self-hosted Community Edition is free Smaller free tier; popular in Java/Atlassian environments
Market share Dominant for open source and most new projects Strong in enterprises and regulated industries Niche but entrenched in Atlassian-centric companies

The concepts in this lesson — remotes, pull requests, issues, CI pipelines, branch protection — exist on all three with different names and screens. If you learn them on GitHub, you can transfer; if your employer uses GitLab, the mental model carries over even where the buttons don't.

1.4 Self-hosting and "just a bare repo"#

Nothing forces you to use a hosted service. A bare repository — a git repo with no working tree, just the object store and refs — on any machine that both you and a teammate can reach (a server, a NAS, a shared drive) is a valid remote. Part 3.2 builds one on your own laptop to prove the point: every git command in this lesson works identically whether the remote is GitHub or a directory called origin.git. The host is where the collaboration features live; git itself doesn't care.

flowchart LR
    subgraph laptop ["Your laptop"]
        WT["working tree<br/>(files you edit)"] -->|git add| ST["staging area"]
        ST -->|git commit| LOCAL["local repo<br/>(full history)"]
    end
    LOCAL -->|"git push (SSH/HTTPS)"| GH["GitHub repo<br/>+ PRs, issues,<br/>Actions, Pages…"]
    GH -->|"git fetch / pull"| LOCAL
    LOCAL -->|"git clone"| OTHER["teammate's laptop"]

Part 2: Your account, plans and repositories#

2.1 Creating the account and profile#

Sign up at github.com with a professional email — the one you'll keep for years, because your commit history and account notifications live there. Pick a username deliberately: it appears in every clone URL (github.com/yourname/...), every @mention, and — as Part 9 shows — potentially in job applications. Avoid your real name plus birth year; a neutral handle ages better.

Your profile is the public face: avatar, display name, bio, links, and pinned repositories. Fill in the profile README in Part 9 when you have projects worth showing.

2.2 Two-factor authentication: non-negotiable#

GitHub holds the keys to your code, your Actions minutes and — through connected apps — sometimes deploy access. A leaked password must not be enough. Enable two-factor authentication (2FA) immediately:

  1. Settings → Password and authentication → Enable two-factor authentication.
  2. Choose an authenticator app (the recommended option: it generates a fresh code every 30 seconds) or a security key / passkey if you have one. SMS is offered as a fallback but is the weakest option — SIM-swapping attacks exist.
  3. Save the recovery codes somewhere offline (a password manager, printed paper). They are the only way back in if you lose your phone. GitHub shows them once.

GitHub has been tightening 2FA for years — as of November 2026, accounts without it face increasing restrictions, and organisations can require it for every member. Treat it as table stakes, not an option.

2.3 Plans: what Free actually gives you#

GitHub's plans change; the table below reflects the official plan documentation as of November 2026 — check GitHub's plans page for current numbers before relying on them.

Feature GitHub Free (personal) GitHub Pro GitHub Team (orgs)
Public repositories Unlimited, full feature set Same Same
Private repositories Unlimited, limited feature set Full feature set Full feature set
Collaborators Unlimited Unlimited Unlimited
Actions compute included $12/month of usage $18/month $18/month per user pool
Actions on public repos Free (standard runners) Free Free
Codespaces 120 core-hours + 15 GB storage/month 180 core-hours + 20 GB Not included for orgs
Packages / Actions artifact storage (shared) 500 MB 1–2 GB (see note) 2 GB
Dependabot alerts ✅ ✅ ✅
Secret scanning / push protection Public repos only (see Part 8) Same Private repos need Secret Protection add-on
Pages Public repos only Public and private repos Same as Pro
Advanced private-repo tools (required reviewers, protected branches, code owners, auto-linked references, wikis, insights) ❌ ✅ ✅
Support Community Email Email

Note: GitHub's plans page lists 2 GB of Packages storage for Pro, while the Actions billing page (which says artifact storage is shared with Packages) lists 1 GB — the two pages disagree as of November 2026, so read the billing page for the number that is actually metered. Actions compute is expressed as a dollar amount, not a fixed number of minutes (Actions billing).

Two consequences worth internalising:

  • For learning and portfolio work, Free is genuinely enough. Your ai-path repo, your exercise repos, even a public open-source contribution — all free. You only hit the private-repo limits if you want protected branches or private Pages on a personal account.
  • Public repos get the security features free. Secret scanning, push protection, code scanning, dependency review and Dependabot all run free on public repositories. Keeping learning repos public is both a portfolio win and a security win — with the caveat that everything in a public repo is world-readable, so secrets must never be there (Part 8 exists because this is the #1 beginner leak).

2.4 .gitignore and templates#

Every repository should start with a sensible .gitignore. GitHub offers templates when you create a repo (the "Add .gitignore" dropdown), and languages have canonical ones — for Python the github/gitignore repo's Python.gitignore covers .venv/, __pycache__/, .env-adjacent files and more. The ai-path .gitignore from 00.3 already covers the essentials:

gitignore
# .gitignore
.env
__pycache__/
.venv/
*.pyc
.DS_Store

Two rules that never change:

  1. .env and anything holding secrets is ignored from the first commit, not added later. 03.1 §3.4 covers the .env/.env.example pattern in depth; the habit starts here.
  2. .gitignore only affects untracked files. If a file was committed before you added its pattern, git keeps tracking it. The fix is git rm --cached .env (untrack but keep the local file) — covered in 00.3. You can verify ignore rules with git check-ignore -v .env, which prints the matching rule:
console
$ git check-ignore -v .env
.gitignore:1:.env	.env

2.5 Licences: what they mean and how to choose#

A licence is the legal answer to "what may someone do with this code?" Without one, copyright law defaults to "all rights reserved" — people can look but not legally copy, modify or redistribute. For portfolio and learning repos the stakes are low, but the habit matters because employers and open-source communities read it.

Licence What it allows What it requires Choose it when
MIT Anyone can use, copy, modify, sell, sublicense Keep the copyright + licence notice You want maximum adoption with minimal friction: libraries, examples, portfolio pieces
Apache-2.0 Same as MIT, plus an explicit patent grant Keep notices; state changes; include the NOTICE file if present Companies that care about patents; widely used by Google-originated projects
GPL-3.0 (and AGPL) Anyone can use/modify, but derivative works must also be GPL ("copyleft") Distribute source of derivatives under GPL; AGPL also covers network use You want to force derivatives to stay open — strong for community projects, a deterrent for commercial adoption
BSD-2/3-Clause Like MIT, with a "no endorsement" clause Keep notices Academic/traditional settings
Unlicense / CC0 Public-domain dedication Nothing You want zero restrictions
No licence Nobody may legally reuse the code — Private/commercial code where reuse is unwanted

For ai-path and your exercise repos, MIT is the sensible default: it's what most learners' portfolios use, it's two sentences long, and it signals "look, learn, reuse with attribution". Copy the canonical text from choosealicense.com or the licence's official page — never paraphrase legal text. Name the file LICENSE (or LICENSE.md) in the repo root so GitHub detects and displays it.

2.6 Creating the ai-path repository on GitHub#

The running thread of this module is ~/code/ai-path/, created in 00.1 and turned into a git repo in 00.3. Now it gets a home on GitHub. Two routes:

Route A — the website. github.com → New → name it ai-path → choose Private (it's your coursework; make it public later if you want it in your portfolio — Part 9) → check "Add a README" off (you already have one locally — adding one creates a merge you don't need) → Create repository. GitHub shows you the exact git remote add / git push commands for your case.

Route B — the CLI (recommended; Part 3.3 covers gh properly):

bash
cd ~/code/ai-path
gh repo create ai-path --private --source . --remote origin --push

That one command creates the repo under your account, adds origin as the remote, and pushes your current branch — exactly what the manual steps do, minus the copy-pasting. We'll unpack every flag in Part 3.


Part 3: Remotes and authentication#

3.1 What a remote is#

In 00.3 every command worked on your laptop alone. A remote is a second copy of the repository that git knows how to talk to — usually over the network, but it can equally be a directory on the same machine. The remote you clone from is conventionally named origin (you can name remotes anything; upstream is the conventional second name, explained in 4.2).

The four commands that move data:

Command Direction What it does
git push local → remote Sends your commits and branch pointers to the remote
git fetch remote → local Downloads new commits into remote-tracking branches (origin/main) without touching your working files
git pull remote → local fetch + merge (or rebase) into your current branch — updates your working files
git remote -v — Lists configured remotes and their fetch/push URLs

Two pieces of vocabulary that confuse everyone at first:

  • Remote-tracking branches like origin/main are local bookmarks recording where the remote's main was at your last fetch/pull. They're read-only — you never commit to them directly. git status -sb shows how your branch relates: ## main...origin/main [ahead 2] means you have 2 unpushed commits; [behind 1] means the remote has 1 you don't; [ahead 1, behind 2] means you've diverged.
  • Upstream tracking is the link between a local branch and its remote counterpart, set by git push -u or git branch --set-upstream-to. Once set, plain git push/git pull on that branch know where to go — no arguments needed.

3.2 Try it: a "remote" with no GitHub at all#

Everything in Parts 3–4 can be practised offline by standing up a bare repository — a repo with no working tree, just the object store — and treating it as the remote. This is also a genuinely useful trick for backups and for testing CI scripts locally.

bash
# In a scratch folder (e.g. mktemp -d), with a throw-away git identity:
export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null
export GIT_AUTHOR_NAME="Learner" GIT_AUTHOR_EMAIL="learner@example.com"
export GIT_COMMITTER_NAME="Learner" GIT_COMMITTER_EMAIL="learner@example.com"
export GIT_AUTHOR_DATE="2026-11-01T09:00:00+00:00"
export GIT_COMMITTER_DATE="2026-11-01T09:00:00+00:00"
export TZ=UTC

git init --bare -b main origin.git          # the "server": bare repo, main as default
git clone origin.git ai-path                 # your working copy
cd ai-path
Example output · illustrative4 lines
Initialized empty Git repository in /Users/you/scratch/origin.git/
Cloning into 'ai-path'...
warning: You appear to have cloned an empty repository.
done.

Now make commits and push — note -u sets upstream tracking on first push. Two commits here: the scaffold, then notes/api-facts.md, which is the file the teammate edits below. (Re-exporting the dates before each commit keeps every SHA reproducible.)

bash
cat > README.md <<'EOF'
# ai-path

My workspace for the AI engineer learning path.
EOF
cat > .gitignore <<'EOF'
.env
__pycache__/
.venv/
EOF
mkdir -p notes
git add README.md .gitignore
git commit -m "feat: scaffold ai-path workspace"

export GIT_AUTHOR_DATE="2026-11-01T09:05:00+00:00"
export GIT_COMMITTER_DATE="2026-11-01T09:05:00+00:00"
cat > notes/api-facts.md <<'EOF'
# API facts verified

- Responses API is OpenAI's primary API.
- Anthropic Messages API requires anthropic-version header.
EOF
git add notes/api-facts.md
git commit -m "docs: add verified API facts notes"
git log --oneline
git push -u origin main
git status -sb
Output13 lines
[main (root-commit) f704e4c] feat: scaffold ai-path workspace
 2 files changed, 6 insertions(+)
 create mode 100644 .gitignore
 create mode 100644 README.md
[main eba7e92] docs: add verified API facts notes
 1 file changed, 4 insertions(+)
 create mode 100644 notes/api-facts.md
eba7e92 docs: add verified API facts notes
f704e4c feat: scaffold ai-path workspace
To /path/to/origin.git
 * [new branch]      main -> main
branch 'main' set up to track 'origin/main'.
## main...origin/main

(The commit SHAs are reproducible: with the fixed dates, name and email above, the same content produces the same hash on any machine — that's what makes commit SHAs trustworthy identifiers.)

A teammate is just a second clone. Have them commit and push, then come back and see how fetch/pull behave:

bash
cd ..
git clone origin.git teammate
cd teammate
export GIT_AUTHOR_DATE="2026-11-02T10:00:00+00:00"
export GIT_COMMITTER_DATE="2026-11-02T10:00:00+00:00"
cat >> notes/api-facts.md <<'EOF'
- Gemini generateContent takes the model in the URL path.
EOF
git add notes/api-facts.md
git commit -m "fix: correct Gemini endpoint note"
git push origin main

cd ../ai-path
git fetch origin
git status -sb        # ## main...origin/main [behind 1]
git pull --ff-only    # fast-forward: no merge commit needed
git log --oneline -3
Output16 lines
Cloning into 'teammate'...
done.
[main 614f453] fix: correct Gemini endpoint note
 1 file changed, 1 insertion(+)
To /path/to/origin.git
   eba7e92..614f453  main -> main
From /path/to/origin
   eba7e92..614f453  main       -> origin/main
## main...origin/main [behind 1]
Updating eba7e92..614f453
Fast-forward
 notes/api-facts.md | 1 +
 1 file changed, 1 insertion(+)
614f453 fix: correct Gemini endpoint note
eba7e92 docs: add verified API facts notes
f704e4c feat: scaffold ai-path workspace

Read that status line carefully: after fetch, git knew the remote had moved ([behind 1]) but your files were untouched until pull ran. That separation is the whole point of fetch.

The full worked script — including a simulated pull-request merge and ls-remote — is in the lesson's exercise solutions; the commands above are the complete mental model. Everything you just did maps 1:1 onto GitHub: origin.git ↔ github.com/you/ai-path.git, the second clone ↔ a teammate's laptop, git push origin --delete <branch> ↔ clicking "Delete branch" after a merge.

3.3 HTTPS vs SSH: the decision#

Git needs to authenticate to the remote on every push/pull. Two transports exist:

HTTPS SSH
URL looks like https://github.com/you/ai-path.git git@github.com:you/ai-path.git
Authenticates with A token (PAT or gh credential) sent on each operation An SSH key pair: private key stays on your machine, public key on GitHub
Works through Proxies, firewalls, corporate networks — almost everywhere Sometimes blocked by restrictive proxies/firewalls
Setup effort Lower — gh auth login handles it One-time key generation + adding the public key
Common failure Token expired/revoked → 403 or auth prompt loop Key not loaded in agent, wrong key offered → Permission denied (publickey)
Best for Most people, most machines, CI systems Developers who prefer key-based auth, machines that push often

The honest recommendation: pick HTTPS + gh auth login for your first setup — it's the path of least resistance and gh manages the credential for you. Add an SSH key too if you like (it's the more "professional" default on Unix machines and required for some workflows like git@github.com: remotes in CI). Both can coexist on the same repo — the remote URL just decides which is used.

3.4 SSH keys end to end#

An SSH key pair is two files: a private key (~/.ssh/id_ed25519, never leaves your machine, never shared) and a public key (id_ed25519.pub, safe to paste anywhere). GitHub stores the public key; when you connect, your machine proves it holds the private key — no password or token travels.

Step 1 — check for existing keys (don't overwrite someone's key):

bash
ls -la ~/.ssh/    # look for id_ed25519, id_ed25519.pub, id_rsa, ...

If id_ed25519 and id_ed25519.pub both exist, skip to step 3.

Step 2 — generate an Ed25519 key (the modern default; GitHub has recommended it for years):

bash
ssh-keygen -t ed25519 -C "you@example.com"
  • -t ed25519 — the algorithm. Ed25519 is fast, secure and short. (GitHub dropped DSA support in March 2022; RSA keys generated after November 2021 must use SHA-2 signatures — Ed25519 avoids all of that.)
  • -C "you@example.com" — a comment label, conventionally your email. It's stored inside the public key; GitHub displays it so you can tell keys apart.

When prompted Enter a file in which to save the key, press Enter for the default ~/.ssh/id_ed25519. For the passphrase: use one. A passphrase encrypts the private key at rest, so a stolen laptop doesn't hand over your GitHub access. The ssh-agent (next step) means you type it once per session, not per push.

Example output · illustrative7 lines
Generating public/private ed25519 key pair.
Enter file in which to save the key (/Users/you/.ssh/id_ed25519):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/you/.ssh/id_ed25519
Your public key has been saved in /Users/you/.ssh/id_ed25519.pub
The key fingerprint is: SHA256:abc123... you@example.com

Step 3 — load the key into ssh-agent so you don't retype the passphrase:

bash
# macOS
ssh-add --apple-use-keychain ~/.ssh/id_ed25519     # --apple-use-keychain stores passphrase in Keychain
# Linux
eval "$(ssh-agent -s)" && ssh-add ~/.ssh/id_ed25519
# Windows PowerShell: OpenSSH agent service + ssh-add (see GitHub docs)

Step 4 — copy the public key to your clipboard (macOS: pbcopy < ~/.ssh/id_ed25519.pub; Windows PowerShell: Get-Content ~\.ssh\id_ed25519.pub | Set-Clipboard; Linux: xclip/wl-copy or just cat and copy).

Step 5 — add it to GitHub: Settings → SSH and GPG keys → New SSH key → paste → Add SSH key. Title it something useful ("MacBook Pro", "work desktop") — you'll thank yourself when you have three keys later. With gh installed you can also do gh ssh-key add ~/.ssh/id_ed25519.pub --title "MacBook Pro".

Step 6 — test it:

bash
ssh -T git@github.com
Example output · illustrative1 line
Hi yourusername! You've successfully authenticated, but GitHub does not provide shell access.

That "does not provide shell access" is correct and expected — SSH here is only for git operations, not a remote terminal. (For actual shell access to servers you'd use plain SSH to those machines; different thing.)

Step 7 — use it. Either clone with the SSH URL (git clone git@github.com:you/ai-path.git) or switch an existing HTTPS remote:

bash
git remote set-url origin git@github.com:you/ai-path.git
git remote -v    # confirm both fetch and push show the SSH URL
sshconfig
# ~/.ssh/config
Host github.com-personal
    HostName github.com
    IdentityFile ~/.ssh/id_ed25519_personal
Host github.com-work
    HostName github.com
    IdentityFile ~/.ssh/id_ed25519_work

Then clone via the alias — git clone git@github.com-work:you/ai-path.git — and the github.com-work host picks the work key while plain github.com remotes keep using your default key. The GitHub account that owns each public key decides which identity the push authenticates as.

3.5 HTTPS with the GitHub CLI#

If you chose HTTPS, gh is the cleanest authenticator. gh auth login is interactive — run it in your terminal:

bash
gh auth login

It asks a short series of questions (verified flow as of November 2026):

  1. GitHub.com or an Enterprise host? → GitHub.com (Enterprise is for companies running their own instance).
  2. Preferred protocol for Git operations? → HTTPS or SSH — this decides the remote URLs gh configures.
  3. Authenticate Git with your GitHub credentials? → Yes — this is the important one: it registers gh as git's credential helper, so git push over HTTPS silently asks gh for a token instead of prompting you.
  4. How to authenticate gh itself? → Login with a web browser (easiest: it shows a one-time code, you paste it into github.com) or Paste an authentication token (for headless machines/CI — that's the PAT route, 3.6).

Behind the scenes gh stores a token in your system credential store (macOS Keychain, Windows Credential Manager, or ~/.config/gh/hosts.yml as fallback) and keeps it fresh. gh auth status shows what's stored and which account/host it belongs to; gh auth logout removes it; gh auth setup-git re-runs just the credential-helper step if you skipped it.

If you'd rather not install gh at all, plain git over HTTPS can still get the browser sign-in through a credential helper. Git Credential Manager (GCM) is the standard one — bundled with Git for Windows and installable on macOS (brew install --cask git-credential-manager) — which pops an OAuth browser flow and stores the result in the OS keychain, so your password never touches the terminal. GitHub's own docs recommend gh or GCM for exactly this reason; without either, git falls back to prompting for a username and password (or token) on every operation — which is why HTTPS pushes used to demand a PAT.

3.6 Personal access tokens#

A personal access token (PAT) is a string that acts as your password for API/git-over-HTTPS operations — revocable, scopable, and (unlike your password) usable in automation. Two generations exist:

Classic PAT Fine-grained PAT
Prefix ghp_ github_pat_
Scopes Broad named scopes (repo, read:org, gist, workflow...) Granular permissions per resource (e.g. "Contents: Read and write", "Pull requests: Read")
Repository access All repos (or selected via OAuth app settings) Only the repos you choose, for a single user or org
Limit Effectively unlimited 50 tokens max per account (as of November 2026)
Expiry Optional, can be infinite You choose an expiry when you create it; an infinite lifetime is allowed unless an organisation or enterprise owner sets a maximum-lifetime policy that blocks it
Best for gh auth login --with-token, simple scripts Least-privilege automation, anything touching a real org

Create them at Settings → Developer settings → Personal access tokens. For a token that only needs to clone/push ai-path over HTTPS, a fine-grained token with Contents: Read and write on just that repository, expiring in 90 days, is the disciplined choice — if it leaks, the blast radius is one repo for three months. Classic repo-scope tokens are broader and fine for personal learning.

3.7 Pushing ai-path for real#

Putting it together — the complete first-push flow:

bash
cd ~/code/ai-path

# 1. Confirm remotes (empty until you add one)
git remote -v

# 2. Either: gh creates the repo AND wires the remote AND pushes
gh repo create ai-path --private --source . --remote origin --push

#   --private        visibility choice
#   --source .       "this local directory is the repo"
#   --remote origin  name the remote 'origin'
#   --push           push the current branch and set tracking

# 3. Or manually, if you made the repo on the website:
git remote add origin git@github.com:you/ai-path.git   # SSH form
git push -u origin main

After either route, git status -sb shows ## main...origin/main with no ahead/behind — you're in sync. From now on the loop is the 00.3 loop plus push/pull: commit locally, git push, and on other machines git pull.

3.8 The gh commands you'll actually use#

gh covers the whole GitHub API from the terminal. The daily-driver set:

Task Command
Create + push a repo gh repo create ai-path --private --source . --remote origin --push
Clone / view a repo gh repo clone owner/repo · gh repo view (opens in browser with --web)
New branch workflow gh pr checkout 42 — checks out someone else's PR locally
Open a PR gh pr create (--fill, --draft, --web, --reviewer username)
Request / remove reviewers gh pr edit 42 --add-reviewer username · --remove-reviewer username
Submit a review gh pr review 42 --approve · --request-changes -b "..." · --comment
PR status at a glance gh pr status · gh pr checks 42 (CI results!) · gh pr view --web
Merge gh pr merge 42 --squash --delete-branch
Issues gh issue create · gh issue list · gh issue view 42
CI runs gh run list · gh run watch · gh run view --log
Releases gh release create v1.0.0 --generate-notes
Escape hatch gh api repos/{owner}/{repo} — any REST endpoint, for when no subcommand exists

The pattern to internalise: gh for GitHub-side state, git for repository content. gh never commits your files; git never opens PRs. gh browse opens the current repo's page; gh alias set saves your own shortcuts; gh extension installs community add-ons.


Part 4: The pull-request workflow#

4.1 Why pull requests exist#

On a solo repo you can push straight to main — and for ai-path early on, you will. But the moment anyone else (a teammate, a reviewer, a future employer looking at your work) might read or depend on the code, the question changes from "is it committed?" to "should this change land?" A pull request (PR) is GitHub's answer: a proposal to merge one branch into another, wrapped in a discussion thread, a diff view, CI results and review tooling.

Think of it as a code review packet: here's the branch, here's what changed and why, here are the checks, here are the comments — approve or request changes, then merge. PRs are the heartbeat of professional software; learning to write and review them well is arguably the highest-leverage skill in this lesson.

flowchart LR
    A["feature branch<br/>your commits"] --> B["push branch<br/>to GitHub"]
    B --> C["open PR:<br/>base main ← head feature"]
    C --> D["CI checks run<br/>(Actions)"]
    C --> E["reviewers comment<br/>/ request changes"]
    E --> F["author pushes fixes"]
    F --> C
    D --> G{"approved +<br/>checks green?"}
    G -->|yes| H["merge:<br/>merge / squash / rebase"]
    G -->|no| E
    H --> I["delete branch"]

4.2 Fork vs branch#

Two ways to contribute to a repo you don't own:

Branch + PR (same repo) Fork + PR (your own copy)
Who can do it Anyone with write access (collaborators, org members) Anyone, on any public repo
Where commits live Branches inside the original repo Your fork (you/repo), PR'd back upstream:main
Typical for Teams, shared projects, ai-path with yourself Open-source contributions, repos you don't control
Extra setup None gh repo fork adds an upstream remote; keep it synced
Permission risk You can push branches (still can't merge without review if protected) None beyond your fork

Rule of thumb: own repo or collaborator → branch; stranger's public repo → fork. For your own ai-path, always branch — forking your own repo is pointless ceremony.

bash
# Contributing to someone else's repo:
gh repo fork owner/repo --clone   # creates you/repo on GitHub and clones it into ./repo,
                                  # wiring origin → your fork + upstream → the original repo
cd repo
git remote -v                    # confirm both remotes are there
git fetch upstream               # keep your fork in sync later:
git switch main && git merge upstream/main && git push origin main

Two details that bite people: --clone is required for a non-interactive clone (without it gh only creates the fork on GitHub and asks whether to clone), and gh's clone already configures both remotes — origin pointing at your fork and upstream at the original — so don't git remote add upstream again (it fails with "remote upstream already exists"). If git remote -v shows upstream missing anyway, add it by hand: git remote add upstream git@github.com:owner/repo.git.

4.3 Anatomy of a good pull request#

A PR has four parts, and reviewers read them in this order:

  1. Title — one line, imperative mood, specific: fix: stop retrying 4xx errors not updates or fix stuff. If the repo uses Conventional Commits (many do), match the style — your squash-merged commit will inherit it.
  2. Description — what changed and why, not how (the diff shows how). A good template:
markdown
## What
- Add retry-with-backoff to the ticket export job
- Cap retries at 3 with jittered delays

## Why
Exports were failing silently on transient 503s from the warehouse API;
three support tickets this week traced to it.

## How I tested
- `pytest tests/test_export.py` — 14 passed
- Replayed the failing request against staging; now succeeds on attempt 2

Fixes #42
  1. The diff — keep PRs small. A 40-line PR gets reviewed in minutes; a 4,000-line PR gets "LGTM" without reading or sits for a week. If a feature is big, stack PRs (Part 4.5 touches this).
  2. Checks and review state — CI results and reviewer comments live on the PR itself.

Open one with gh:

bash
git switch -c fix/export-retries
git push -u origin fix/export-retries
gh pr create --title "fix: retry export job on transient 5xx" --body-file pr-body.md
# or interactively: gh pr create  (prompts for title/body/base)
# or quickly: gh pr create --fill   (uses commit messages as the body)

Add --draft while work is incomplete — draft PRs signal "not ready for review" but still run CI and let you share progress. Mark ready with gh pr ready or the website button.

Requesting reviewers is how work finds its reviewer. On the PR page, the right-hand Reviewers panel lists people and teams you can request; from the CLI, gh pr create --reviewer teammate-login sets them at creation (plain logins, or org/team-name for a team — no @) and gh pr edit --add-reviewer teammate-login adds or re-requests later (--remove-reviewer takes them off — see the gh table in 3.8). If the repo has a CODEOWNERS file (6.1), GitHub requests the owners of the paths you changed automatically — manual requests are for everyone else, and on a PR to yourself there's nobody to request, which is fine for practice.

4.4 Reviewing and being reviewed#

As a reviewer, GitHub gives you three comment granularities: comment on the whole PR (general discussion), comment on a specific line ("this off-by-one looks wrong"), or a suggestion — a fenced diff block the author can apply with one click:

suggestion
max_retries = 3  # was: infinite loop on persistent 503

Review verbs: Comment (neutral), Approve (good to merge), Request changes (blocking — must be addressed or dismissed). Be specific and kind: "this will throw KeyError when meta is absent — see line 12" beats "this is wrong". Review the code, not the person; ask questions ("what happens if the list is empty?") as often as you assert.

As an author, address feedback by pushing new commits to the same branch — the PR updates automatically. Never rewrite pushed history on a shared branch just to make comments "disappear"; discuss instead. When feedback is wrong or you disagree, reply explaining why — reviewers appreciate pushback with reasoning.

4.5 Updating a PR: commits, amends and force-push etiquette#

After review feedback you'll usually add commits:

bash
git add -A && git commit -m "fix: cap retries and add jitter per review"
git push            # PR updates; reviewers see the new commit

Sometimes you want to rewrite — squash five "fix typo" commits into one clean commit. That's git commit --amend or interactive rebase (00.3) followed by git push --force-with-lease — never plain --force on a shared branch. --force-with-lease fails if someone else pushed since your last fetch, protecting you from silently erasing a teammate's work. The etiquette rule: force-push only your own feature branches, only before merge, and always --force-with-lease. Never force-push main or a branch others have checked out.

For truly large features, stacked PRs keep reviews sane: PR1 adds the data layer, PR2 (based on PR1's branch) adds the API, PR3 adds the UI — each reviewable in isolation, merged in order.

4.6 Merging: three strategies#

When checks pass and review is approved, merge. GitHub offers three methods (repository settings decide which are enabled — as of November 2026 all three are available on Free for public repos):

Strategy Result in history Choose when
Merge commit All branch commits preserved + an explicit merge commit (--no-ff) You want the full story: feature-branch workflow, audit trails
Squash and merge All commits combined into one commit on the base The PR is one logical change with messy WIP commits — the most common choice; gives a clean linear-ish history
Rebase and merge Each commit replayed onto base, no merge commit — perfectly linear Small, well-organised commits you want to keep individually; rewrites SHAs

Practical defaults: squash for most PRs (clean main, one commit per feature, easy revert), merge commit when the individual commits matter (long-lived features, pair programming sessions). Whatever the repo's convention, match it — check recent merges with git log --oneline --graph after pulling.

After merging, delete the branch (GitHub offers a button; gh pr merge --delete-branch does it in one step). Merged branches are cheap to keep but they clutter the branch list and confuse git branch -a; git keeps the commits reachable through the merge regardless.

bash
gh pr merge 42 --squash --delete-branch     # merge PR #42, delete its branch
# or interactively: gh pr merge

4.7 Code review as a skill#

Reviewing is a learnable discipline, and it's how you level up fastest as an engineer — you read more code in a month of reviewing than in a month of writing. What good reviewers actually check:

  • Correctness: does it do what the PR claims? Edge cases (empty input, null, huge lists)?
  • Fit: does it match the codebase's conventions, error handling, naming?
  • Tests: is the new behaviour covered? Do the tests test behaviour, not implementation?
  • Security: secrets, injection, unsafe deserialisation, authz gaps (Part 8 mindset)
  • Clarity: would a stranger understand this in six months?
  • Scope: does the PR do one thing? Unrelated changes belong in another PR

Part 5: Issues, projects, discussions and GitHub Markdown#

Deep-dive

5.1 Issues: the work queue#

An issue is a unit of work or a bug report — the shared to-do list of a repo. Good issues are reproducible: a stranger can understand and ideally reproduce the problem. GitHub supports issue templates (.github/ISSUE_TEMPLATE/) so reports arrive structured — bug reports ask for steps-to-reproduce, expected vs actual, environment; feature requests ask for the problem, proposed solution, alternatives. Templates come in two shapes: markdown templates (.md files — a skeleton the reporter fills in) and issue forms (.yml files in the same folder, written in GitHub's form schema — dropdowns, checkboxes, required fields, even file uploads; the form's answers are converted into the issue body as markdown, so you get structure without trusting free text).

Two issue types you'll write constantly:

  • Bug report: what happened, what you expected, steps to reproduce, environment (OS, versions), logs/screenshots, severity.
  • Feature request: the problem it solves (not just the solution), proposed behaviour, alternatives considered, willingness to implement.

5.2 A worked bug report#

Weak: "export is broken". Strong:

markdown
## Bug: CSV export truncates rows after 10,000

**What happened:** Exporting the tickets list as CSV produces a file with
only the first 10,000 rows; the UI says "export complete".

**Expected:** All matching rows exported (dataset has ~47k tickets).

**Steps to reproduce:**
1. Open /tickets, clear filters
2. Click Export → CSV
3. Open the downloaded file: 10,000 data rows + header

**Environment:** ai-path v0.4, Chrome 141, Windows 11 / Firefox 144 (same).

**Logs:** none — no error surfaced. Suspect an undocumented API cap.

That report is actionable: a maintainer can reproduce it in five minutes and knows where to look. Write issues for your future self too — six months from now you'll have forgotten the context.

5.3 Labels, milestones, linking#

  • Labels categorise (bug, enhancement, documentation, good first issue, priority: high). Consistent labels make the issue list searchable; don't invent synonyms (defect vs bug).
  • Milestones group issues toward a release or date — the lightweight project-management layer.
  • Assignees say who's on it; projects (the kanban boards under the repo/org) give the fuller planning view.
  • Linking: Fixes #42 / Closes #42 / Resolves #42 in a PR description or commit message auto-closes the issue on merge; plain #42 just references it. gh issue create, gh issue list, gh issue view 42 cover the CLI side.

5.4 Discussions#

GitHub Discussions are forum-style threads attached to a repo — for questions, ideas and show-and-tell that aren't issues (a bug is work to do; a question is conversation). Enable them in repo Settings if you want them; many projects use them instead of Stack Overflow for community Q&A.

5.5 GitHub-flavoured Markdown: the features plain Markdown lacks#

Everything you've written in README.md so far is GFM — GitHub Flavoured Markdown, CommonMark plus GitHub extensions. The extensions that matter daily:

Feature Syntax Renders as
Fenced code a code fence tagged with a language, e.g. python Syntax-highlighted block with a copy button — always tag the language
Task list - [x] done / - [ ] todo Checkbox (clickable on GitHub!)
Alert box > [!NOTE] > [!TIP] > [!IMPORTANT] > [!WARNING] > [!CAUTION] Coloured callout — the marker must be alone on the first blockquote line
Mention @username, @org/team Notification + link
Issue/PR ref #42, owner/repo#42 Link to the item
Commit ref `abc1234` (7+ hex chars) Link to the commit
Collapse <details><summary>Title</summary> ... </details> Expandable section — used for long logs, solutions
Mermaid a code fence tagged mermaid Rendered diagram (Part 1's flowchart works in READMEs, issues, PRs, wikis)
Table | a | b | pipes Table (GFM extension, not in base Markdown)
Footnote [^1] + [^1]: text Numbered footnote
File link Markdown link with a relative target (e.g. ./docs/guide.md), or a blob URL with line anchor #L10-L20 Link that survives renames better than absolute URLs

Two practical notes: alerts render only on GitHub (VS Code's preview won't show them — your lesson callouts > 🎓 are plain blockquotes and render everywhere); and you can check what a file looks like rendered exactly as GitHub sees it via gh api -X POST /markdown — overkill for daily use, useful when debugging weird rendering.

5.6 A README that works#

The ai-path README (and every project README you'll write) should answer, in order: what is this, how do I run it, how is it tested, what's the status. Skeleton:

markdown
# ai-path

Workspace for the AI engineer learning path: tickets.db, notes/, exercises.

## Quickstart
```bash
python3 make_tickets_db.py       # creates tickets.db (script from lesson 00.7)
sqlite3 tickets.db               # or: python3 -m sqlite3 tickets.db (Python 3.12+)
```

## Layout
- `make_tickets_db.py` — builds the SQLite support-ticket database (see 00.7)
- `tickets.db` — the generated database (rebuildable, so optional to commit)
- `notes/` — verified API facts, one file per provider

## Status
Exercises through lesson 00.9. No API keys required.

Part 6: Collaboration at team scale#

Deep-dive

Solo repos need none of this; real teams need all of it. You'll meet every file below in open-source and company repos.

6.1 The governance files#

File Location Purpose
CONTRIBUTING.md root or docs/ How to contribute: setup steps, coding standards, commit/PR conventions, what gets reviewed. The first file a new contributor reads
CODE_OF_CONDUCT.md root Community behaviour rules — most projects adopt the Contributor Covenant verbatim
SECURITY.md root How to privately report vulnerabilities (links to private vulnerability reporting or a security contact). Distinct from "how to use securely" docs
CODEOWNERS root, docs/, or .github/ Maps paths/globs to owners: *.py @your-username means changes to Python files request your review. Powers auto-review-request and (on paid private repos) required reviews
Issue/PR templates .github/ISSUE_TEMPLATE/*.md, .github/PULL_REQUEST_TEMPLATE.md Structured forms for reports and PRs (Part 5.1)
FUNDING.yml .github/ Donation/sponsorship links (GitHub Sponsors, Open Collective) — awareness only
SUPPORT.md root Where users get help — awareness only

You don't need all of these on ai-path, but writing a minimal CONTRIBUTING.md once teaches you what belongs in one: environment setup, how to run tests, commit message style, PR checklist, and "what we won't accept".

6.2 Branch protection and rulesets#

Branch protection rules (and the newer rulesets, which generalise them) control what can happen to main: require pull requests, require N approving reviews, require status checks to pass, require linear history, require signed commits, restrict who can push, prevent force-pushes and deletions. They're the mechanism that makes "everyone works on main" safe — without them, one bad push can rewrite shared history.

Availability (verified as of November 2026): on public repositories these features are free on every plan; on private repos they need GitHub Pro (personal) or Team (org). For your learning repos, making them public gets you the full feature set for free.

A sensible protection set for a course/team repo:

  • Require a pull request before merging
  • Require 1 approving review (solo repos: 0 is fine)
  • Require status checks — once Part 7's workflow exists, "tests pass" becomes a merge gate
  • Require branches to be up to date before merging
  • Do not allow force pushes or deletions on main

6.3 Releases and versioning#

Professional repos mark stable points with tags and releases:

  • Semantic versioning (MAJOR.MINOR.PATCH, e.g. 1.4.2): bump MAJOR for breaking changes, MINOR for backwards-compatible features, PATCH for fixes. semver.org is the spec; it's a social contract — state it in your README if you follow it.
  • git tag -a v1.4.0 -m "Release 1.4.0" && git push origin v1.4.0 — annotated tags are the norm for releases.
  • GitHub Releases (Tags → Draft a new release) attach notes and binaries to the tag; the release notes page auto-generates from merged PRs, or you write them by hand.
  • Changelog: a CHANGELOG.md (the Keep a Changelog format is the de-facto standard) or release notes per tag. For AI-path projects, generating notes from Conventional Commits is a solved problem — the whats_changed.py script in exercise 15 does exactly that: it reads git log, groups commit subjects by conventional-commit type into Markdown sections, and can be limited to a range like v0.1.0..HEAD.

6.4 Workflow models: honest comparison#

Model Shape Best for
Trunk-based development Everyone commits/pushes small changes to main (often via short-lived branches + PRs); deploy continuously Teams with strong CI, small changes, fast iteration — the modern default at most product companies
GitHub Flow main is always deployable; feature branches + PRs; merge when reviewed The simple version of trunk-based — what this lesson teaches; perfect for small teams and portfolio repos
Git Flow main (releases) + develop (integration) + feature/release/hotfix branches Scheduled releases, multiple supported versions in the wild — heavier; common in older enterprises
Forking workflow Contributors fork, maintainers merge PRs from forks Large open-source projects with untrusted contributors

Pick the lightest model your team can keep honest: for ai-path and most learning/portfolio work, GitHub Flow (feature branch → PR → squash-merge → delete branch) is the answer. Trunk-based is where most industry teams actually live now; Git Flow survives where release trains matter.

6.5 Monorepo vs polyrepo#

  • Monorepo: everything in one repo (e.g. Google's approach). Atomic cross-package changes, shared tooling, one CI config — at the cost of repo size and access granularity.
  • Polyrepo ("multi-repo"): one repo per project/service. Simpler permissions, independent versioning, clearer boundaries — at the cost of cross-repo changes needing multiple PRs.

For this path: ai-path is a monorepo by design — it's a learning workspace, not a deployed system, and keeping notes/, tickets.db scripts and exercises together is the point. Real AI products usually end up polyrepo-ish (service repos) or monorepo-with-packages (pnpm/turbo style) — you'll meet both in Module 11C.

6.6 Using other people's code: licences and provenance#

Three habits keep you out of trouble:

  1. Read the licence before copying. MIT/Apache/BSD code can be reused with attribution; GPL code infects your project if you distribute derivatives; "no licence" means no legal right to copy even if it's public. When you do reuse, keep the copyright notice and say where it came from (a comment or NOTICE file).
  2. Attribute AI-generated code honestly. Tools' licences vary — some grant broad rights to output, some don't; GitHub's Copilot terms and individual tool terms differ, and case law is still forming. Don't assume "the AI wrote it" means "it's public domain". 12.7 covers provenance properly.
  3. Check what you actually downloaded. git clone, pip install, npm install all fetch code you'll run — the supply-chain lessons in 12.7 apply to dependencies the same way they apply to model weights.

Part 7: GitHub Actions in one lesson#

Deep-dive

7.1 What CI is, and why it matters here#

Continuous Integration (CI) is the practice of automatically building and testing every change. "It works on my machine" dies the moment CI runs the same steps on a clean machine for every push and every PR. For AI work specifically, CI is where your tests, linting, schema checks and — later — eval suites run automatically (11C.2 is the full LLM-grade treatment; this section is the GitHub mechanics).

GitHub Actions is GitHub's CI/CD platform: you commit YAML files describing workflows; GitHub runs them on its hosted machines (called runners) triggered by events like pushes and PRs.

7.2 Anatomy of a workflow file#

Workflows live in .github/workflows/*.yml. A minimal one:

yaml
# .github/workflows/tests.yml
name: tests                        # display name in the Actions tab

"on":                              # triggers — quoted because YAML 1.1 reads a bare
  push:                            # 'on' as boolean true (GitHub accepts both;
    branches: [main]               # quoting is the safe habit)
  pull_request:                     # runs on every PR targeting any branch

jobs:                               # a workflow = many jobs; jobs run in parallel by default
  pytest:
    runs-on: ubuntu-latest           # GitHub-hosted runner image
    steps:
      - uses: actions/checkout@v7   # download the repo (official action)
      - uses: astral-sh/setup-uv@v10.3.3 # install uv — exact tag, no floating major
      - run: uv sync                # install locked dependencies
      - run: uv run pytest          # run the tests

The moving parts:

Key Meaning
on Trigger events: push, pull_request, schedule (cron), workflow_dispatch (manual button), release, etc. Quote it ("on") — YAML 1.1 parsers read a bare on as boolean true; GitHub's own parser accepts both
jobs.<id> A job = a runner + a sequence of steps. Jobs run in parallel unless needs: chains them
steps Ordered commands inside a job
uses: Run a prebuilt action (owner/repo@ref) — actions/checkout fetches your code, actions/setup-python installs Python
run: Run a shell command on the runner
needs: Job dependency: deploy: needs: [test, lint]
if: Conditional step/job (if: github.event_name == 'push')
env: / secrets.X Environment variables and repository secrets
matrix: Run the same job across combinations (Python 3.11/3.12/3.13, OS matrix)
permissions: GITHUB_TOKEN scopes for the run — least privilege
concurrency: Cancel superseded runs on the same branch

Context variables like ${{ github.sha }}, ${{ github.ref }}, ${{ secrets.MY_KEY }} inject run metadata — ${{ secrets.* }} is the only way secrets reach workflows.

7.3 A minimal Python CI workflow (illustrative)#

For a uv-based Python project the realistic starter tests on three versions and lints:

yaml
# .github/workflows/ci.yml  — illustrative example for a uv project
name: ci
"on":
  push:
    branches: [main]
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python: ["3.11", "3.12", "3.13"]
    steps:
      - uses: actions/checkout@v7
      - uses: astral-sh/setup-uv@v10.3.3
        with:
          python-version: ${{ matrix.python }}
      - run: uv sync --locked
      - run: uv run ruff check .
      - run: uv run pytest -q

Example output (illustrative — Actions UI varies): the run shows a matrix of three jobs, each green when tests pass; a failing test marks the check ✗ and (once required, 6.2) blocks merge.

Two details worth copying verbatim: pin actions to a release tag — a floating major like actions/checkout@v7 where the action publishes one, or an exact version like astral-sh/setup-uv@v10.3.3 where it doesn't (setup-uv ships no v10 major tag) — and check each action's releases page, because majors move faster than most teams expect (11C.2 makes the same point with the same pins); and uv sync --locked/--frozen so CI installs exactly your lockfile, not whatever resolves that day.

7.4 Secrets vs variables, and pinning actions#

  • Secrets (Settings → Secrets and variables → Actions): encrypted, masked in logs (GitHub replaces the value with *** if a step tries to print it), available to workflows as ${{ secrets.NAME }}. Variables are the non-secret counterpart — config like PYTHON_VERSION or a feature flag.
  • Never echo secrets: don't echo ${{ secrets.X }}, don't env | grep, don't write them to files that get uploaded as artifacts. Masking is a safety net, not a licence — a determined leak (base64, split strings) bypasses it.
  • ${{ github.token }} is an automatic per-run token for the workflow itself (checkout, commenting on PRs) — scoped by the permissions: key. Set permissions: contents: read at workflow level unless you need more.
  • Untrusted PRs and pull_request_target: a workflow triggered by pull_request from a fork runs with a read-only token and no access to your secrets, which is the safe default. The pull_request_target trigger instead runs in the context of your base branch with secrets and a write-capable token, so checking out and running the fork's code there hands an anonymous contributor your credentials. Treat it as dangerous: use plain pull_request unless you fully understand why you need the other (GitHub's Actions security guide covers it, and recommends avoiding pull_request_target unless the workflow truly needs a privileged context).
  • Pinning: uses: actions/checkout@v7 trusts the moving v7 tag; uses: actions/checkout@<40-character-commit-sha> # v7.0.1 pins the exact commit — the supply-chain-hardened choice for third-party actions (12.7 covers why this matters). The SHA is the commit the tag currently points at (shown as a placeholder here because you should look it up yourself rather than copy one from a lesson): get it from the action's releases page or with git ls-remote https://github.com/actions/checkout refs/tags/v7.0.1. Prefer the commit SHA of a release tag you have checked, and let Dependabot (8.2) propose bumps.

7.5 Checks on pull requests#

Once a workflow runs on pull_request, its result appears as a check on the PR: green ✓, red ✗, or pending. Making a check required (branch protection → "Require status checks") turns CI into a merge gate — no green, no merge. That's the mechanism behind "CI is red on your PR".

7.6 Pages and Codespaces: awareness#

  • GitHub Pages: free static-site hosting from a repo — push an index.html (or a docs folder, or a Jekyll/Hugo site) and it serves at you.github.io/repo. On the Free plan the source repo must be public (verified; Pro allows private sources). Perfect for project docs and portfolios.
  • GitHub Codespaces: a full dev environment in the browser — VS Code + terminal + your repo, on Microsoft's machines. Free tier: 120 core-hours + 15 GB storage/month (verified as of November 2026). Invaluable when your laptop can't run the stack, and a fine fallback if your OS setup fights you.
  • GitHub Packages (500 MB free) and GitHub Sponsors exist too — know they're there; you won't need them in this path.

7.7 The same thing elsewhere#

GitLab calls it GitLab CI (.gitlab-ci.yml), Bitbucket Pipelines (bitbucket-pipelines.yml), CircleCI/GitHub-Actions-lookalikes abound. The concepts — trigger, job, step, runner, secrets, artifacts — are identical; only the YAML dialect changes. If you learn Actions, you can read any CI file.


Part 8: Security on GitHub#

8.1 Secret scanning and push protection#

Secret scanning is GitHub's detector: it continuously scans your repo's git history, issues, PRs, wikis and gists for known credential shapes (API keys, tokens, private keys) and raises an alert on the Security tab. Push protection goes further — it blocks the push when the commit contains a recognised secret, before it ever reaches the repo.

Availability (verified as of November 2026): free and automatic on public repositories; on private repos it requires GitHub Secret Protection, part of GitHub Code Security/Advanced Security, which needs a Team or Enterprise Cloud plan. There's also a personal "Push protection for users" setting that guards you when pushing secrets to public repos you don't own.

The workflow when an alert fires: rotate the credential first (assume it's compromised — history is public to anyone who cloned), then remove it from the code and, if the repo is public or widely cloned, consider rewriting history (00.3 covers the safe undo path; git filter-repo for history surgery). For provider API keys specifically, 03.1 §3.7 is the hour-by-hour playbook.

8.2 Dependabot and dependency review#

Dependabot is GitHub's dependency robot, in three flavours:

  • Dependabot alerts — warns when a dependency you use has a known vulnerability (sourced from the GitHub Advisory Database). Free on all plans.
  • Dependabot security updates — opens PRs that bump vulnerable dependencies to fixed versions.
  • Dependabot version updates — opens PRs keeping dependencies current (configured via dependabot.yml in .github/).

It runs on GitHub Actions runners under the hood. For Python projects it reads pyproject.toml/uv.lock and proposes bumps exactly like a human would — review them like any PR (check the changelog, run tests).

Dependency review comments on PRs that add or change dependencies, flagging known-vulnerable versions before merge — free on public repos, part of Code Security for private. It's the diff-level complement to Dependabot's repo-level alerts.

8.3 Private vulnerability reporting and SECURITY.md#

Owners of public repos can enable private vulnerability reporting: a "Report a vulnerability" button that lets researchers disclose bugs privately (draft security advisories) instead of public issues. Pair it with a SECURITY.md telling reporters where and how to report — the coordinated-disclosure pattern every mature project uses. On private repos the feature doesn't apply (you're already private).

8.4 Signed commits#

A signed commit is cryptographically proven to come from the key holder — GitHub shows a "Verified" badge. Signing uses your SSH key (the same one from 3.4, added with type "signing") or a GPG key. It defends against impersonation — someone pushing commits as you — and is increasingly expected in security-sensitive repos. Setup: git config --global gpg.format ssh, user.signingkey, commit.gpgsign true, plus gpg.ssh.allowedSignersFile for local verification; GitHub's docs walk through it. Awareness level is enough for now — know the badge exists and what it means.

8.5 When a secret leaks anyway#

The order is always: rotate → remove → assess → clean history (maybe).

  1. Rotate immediately. Revoke/regenerate the credential at the provider first — a dead key in public history is harmless; a live one is an open door. 03.1 §3.7 has the provider-specific first hour.
  2. Remove it going forward (.env, .gitignore, untrack if committed).
  3. Assess exposure: was the repo public? For how long? Was it forked/cloned? Private repos that never left your machine are lower risk — still rotate, because "private" isn't "safe" (collaborators, backups, support staff all saw it).
  4. History rewrite is optional and disruptive: git filter-repo can purge the secret from all history, but it rewrites every SHA — anyone with a clone must re-clone, open PRs break, and it only helps after rotation (the old commits still exist in caches/forks). Most teams rotate and move on.

8.6 A local secret scanner you can run today#

GitHub's scanner needs a GitHub repo; here's a stdlib-only miniature that works on any local git repo — it scans every tracked file for common credential shapes and, deliberately, never prints the secret itself (a scanner that echoes credentials into your terminal is itself a leak).

First, a scratch repo seeded with planted fake secrets. The fakes are assembled at runtime with printf tricks, so no real-looking credential ever sits in this script or on disk:

bash
# seed_secret_demo.sh — build a scratch repo with planted fake secrets.
set -euo pipefail
WORK="${1:-$(mktemp -d)}"        # or pass your own scratch dir
mkdir -p "$WORK" && cd "$WORK"

# Throw-away identity: the machine's real git config is never read.
export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null
export GIT_AUTHOR_NAME="Learner" GIT_AUTHOR_EMAIL="learner@example.com"
export GIT_COMMITTER_NAME="Learner" GIT_COMMITTER_EMAIL="learner@example.com"
export GIT_AUTHOR_DATE="2026-11-04T09:00:00+00:00"
export GIT_COMMITTER_DATE="2026-11-04T09:00:00+00:00"
export TZ=UTC

git init -b main demo-repo >/dev/null
cd demo-repo

# Fake secrets, built at runtime — none of this is a usable credential.
ghp="$(printf 'ghp_%s' "$(printf 'a%.0s' $(seq 36))")"
pat="$(printf 'github_pat_%s' "$(printf 'B%.0s' $(seq 22))_11AA")"
sk="$(printf 'sk-proj-%s' "$(printf 'x%.0s' $(seq 30))")"
akia="$(printf 'AKIA%s' "$(printf 'Z9%.0s' $(seq 8))")"
gkey="$(printf 'AIza%s' "$(printf 'Gg7%.0s' $(seq 12))")"

mkdir -p app deploy notes keys

cat > README.md <<'EOF'
# demo-repo

Set OPENAI_API_KEY=sk-... in your .env (see .env.example).
EOF

cat > .env.example <<'EOF'
# Copy to .env and fill in real values. Never commit .env.
OPENAI_API_KEY=sk-...
GITHUB_TOKEN=ghp_...
EOF

cat > app/settings.py <<EOF
# settings.py — where the leak lives
OPENAI_API_KEY = "$sk"
GITHUB_TOKEN = "$ghp"
EOF

cat > deploy/aws.env <<EOF
AWS_ACCESS_KEY_ID=$akia
AWS_SECRET_ACCESS_KEY=$(printf 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY')
DATABASE_URL=postgres://appuser:$(printf 's3cr3t-pass')@db.internal:5432/app
EOF

cat > notes/provider-keys.txt <<EOF
Backup of keys (DO NOT SHARE):
OPENAI_API_KEY=$sk
GOOGLE_API_KEY=$gkey
GITHUB_TOKEN=$pat
MAILGUN_API_KEY=$(printf 'key-%s' "$(printf 'm%.0s' $(seq 24))")
EOF

cat > keys/server.pem <<'EOF'
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
-----END OPENSSH PRIVATE KEY-----
EOF

# .gitignore lists .env — but .env was committed before the rule existed,
# so git still tracks it (the "ignored but still committed" trap from 00.3).
cat > .gitignore <<'EOF'
.env
__pycache__/
EOF
cat > .env <<EOF
OPENAI_API_KEY=$sk
EOF
git add -f .env
git add -A
git commit -m "chore: initial import (with secrets, unfortunately)" >/dev/null

echo "Demo repo ready at $PWD"
echo "Save the scanner below as secret_scan_local.py in $WORK, then run:"
echo "  cd $PWD && python3 ../secret_scan_local.py"

The scanner itself — complete, standard library only:

python
#!/usr/bin/env python3
"""secret_scan_local.py — scan git-tracked files for common secret patterns.

A miniature version of what GitHub's secret scanning does, runnable fully
offline with the standard library. It scans the *working-tree* contents of
every file `git ls-files` reports (i.e. files git would commit), prints
file:line and the *kind* of secret found, and — deliberately — never prints
the secret itself: a scanner that echoes credentials into your terminal or
CI log is itself a leak.

Usage:  python3 secret_scan_local.py [--repo PATH]
Exit code 0 = clean, 1 = findings.
"""

import re
import subprocess
import sys
from pathlib import Path

# Obvious placeholders are not secrets: ..., YOUR_API_KEY, "example", etc.
PLACEHOLDER = re.compile(
    r"(\.\.\.|your[_-]|example|changeme|change[_-]?me|xxx+|<|>|redacted|"
    r"dummy|fake|placeholder|todo|insert|replace|sample)",
    re.IGNORECASE,
)

PATTERNS = [
    ("GitHub token (classic)", re.compile(r"ghp_[A-Za-z0-9]{20,}")),
    ("GitHub fine-grained PAT", re.compile(r"github_pat_[A-Za-z0-9_]{20,}")),
    ("OpenAI-style API key", re.compile(r"sk-(?:ant-|proj-|svcacct-)?[A-Za-z0-9_-]{20,}")),
    ("AWS access key ID", re.compile(r"\bAKIA[0-9A-Z]{16}\b")),
    ("Google API key", re.compile(r"\bAIza[0-9A-Za-z_-]{30,}")),
    ("Private key block", re.compile(r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----")),
    (
        "Credential in URL",
        re.compile(r"\b([a-z][a-z0-9+.-]*)://[^/\s:@]+:[^@\s/]+@([^/\s:]+)", re.IGNORECASE),
    ),
    (
        "Secret-looking assignment",
        # NAME may carry a prefix (AWS_, DB_, OPENAI_); the sensitive word must
        # appear as api_key/secret/token/password/access_key, so "monkey" is safe.
        re.compile(
            r"(?i)\b\w*(?:secret|token|password|passwd|api[_-]?key|access[_-]?key)\w*"
            r"\s*[:=]\s*[\"']?([^\s\"']{8,})"
        ),
    ),
]

BINARY_SNIFF = 8192
GENERIC = "Secret-looking assignment"
URL_KIND = "Credential in URL"


def repo_root(start: Path) -> Path:
    out = subprocess.run(
        ["git", "rev-parse", "--show-toplevel"],
        cwd=start,
        capture_output=True,
        text=True,
        check=True,
    )
    return Path(out.stdout.strip())


def tracked_files(root: Path) -> list[str]:
    out = subprocess.run(
        ["git", "ls-files", "-z"],
        cwd=root,
        capture_output=True,
        check=True,
    )
    return [p for p in out.stdout.decode().split("\0") if p]


def looks_binary(data: bytes) -> bool:
    return b"\0" in data[:BINARY_SNIFF]


def redact(kind: str, match: re.Match) -> str:
    """A safe one-line hint about what was found — never the secret value."""
    if kind == URL_KIND:
        return f"{match.group(1)}://<user>:<redacted>@{match.group(2)}"
    if kind == GENERIC:
        # Show only the variable name, never its value.
        head = match.group(0).split("=", 1)[0].split(":", 1)[0].strip()
        return f"{head}=<redacted>"
    return match.group(0)[:4] + "…"


def scan_file(root: Path, rel: str) -> list[tuple[int, str, str]]:
    """Return (lineno, pattern-name, redacted-snippet) findings."""
    path = root / rel
    try:
        data = path.read_bytes()
    except OSError:
        return []
    if looks_binary(data):
        return []
    findings = []
    for lineno, line in enumerate(data.decode("utf-8", "replace").splitlines(), 1):
        for name, pattern in PATTERNS:
            m = pattern.search(line)
            if not m:
                continue
            if name == GENERIC and PLACEHOLDER.search(m.group(1)):
                continue
            findings.append((lineno, name, redact(name, m)))
            break  # one finding per line is enough
    return findings


def main() -> int:
    args = [a for a in sys.argv[1:] if not a.startswith("--")]
    start = Path(args[0]) if args else Path.cwd()
    root = repo_root(start)

    files = tracked_files(root)
    total = 0
    for rel in files:
        for lineno, name, snippet in scan_file(root, rel):
            total += 1
            print(f"{rel}:{lineno}  [{name}]  {snippet}")

    print(f"\nScanned {len(files)} tracked files: {total} finding(s).")
    if total:
        print("Rotate anything real, then remove it from history "
              "(lesson 00.3 covers the safe undo path; lesson 03.1 §3.7 "
              "covers the first hour after a provider-key leak).")
        return 1
    print("Clean.")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Save both scripts in the same scratch folder and run bash seed_secret_demo.sh . — it builds demo-repo/ beside them — then cd demo-repo && python3 ../secret_scan_local.py. Against that demo it printed (exit code 1 — findings present):

text
.env:1  [OpenAI-style API key]  sk-p…
app/settings.py:2  [OpenAI-style API key]  sk-p…
app/settings.py:3  [GitHub token (classic)]  ghp_…
deploy/aws.env:1  [AWS access key ID]  AKIA…
deploy/aws.env:3  [Credential in URL]  postgres://<user>:<redacted>@db.internal
keys/server.pem:1  [Private key block]  ----…
notes/provider-keys.txt:2  [OpenAI-style API key]  sk-p…
notes/provider-keys.txt:3  [Google API key]  AIza…
notes/provider-keys.txt:4  [GitHub fine-grained PAT]  gith…
notes/provider-keys.txt:5  [Secret-looking assignment]  MAILGUN_API_KEY=<redacted>

Scanned 8 tracked files: 10 finding(s).
Rotate anything real, then remove it from history (lesson 00.3 covers the safe undo path; lesson 03.1 §3.7 covers the first hour after a provider-key leak).

Three lessons fall out: .env was flagged even though .gitignore listed it — because it had been git add -f'd before the ignore rule (the 00.3 trap, now with consequences); DATABASE_URL with an inline password got caught by the URL rule, not the assignment rule — credentials hide in URLs; and .env.example with sk-... placeholders stayed clean — the allowlist works. Run it on ai-path after every module: python3 secret_scan_local.py.


Part 9: Your portfolio on GitHub#

Deep-dive

For freshers and career-switchers, GitHub doubles as a portfolio: employers and recruiters routinely check it, and Module 14B builds the career strategy around it. Three surfaces matter:

9.1 The profile README#

Create a public repository named exactly your username (e.g. yourname/yourname) — GitHub renders its README.md at the top of your profile. It's the highest-visibility real estate you have: who you are, what you're building, how to reach you. Keep it honest and useful — a short bio, what you're learning, links to your best repos, contact. No fake metrics, no engagement-bait badges you didn't earn.

9.2 Pinned repositories#

Your profile shows a Pinned section — up to six repositories and gists combined (verified as of November 2026). Pin your best work: the ai-path capstone, a project with a real README and real tests, something that shows range. Pinned repos display live star/fork counts and language bars — another reason READMEs and tests matter.

9.3 What makes a README good#

Employers skim. A good project README answers in 30 seconds: what it does, a screenshot or example output if visual, how to run it, how it's tested, and what state it's in. The ai-path repos you'll build through this path are portfolio pieces — write their READMEs like they matter, because they do. The checklist:

  • One-paragraph "what and why"
  • Quickstart that actually works on a clean machine
  • Links to the interesting parts (architecture note, key module)
  • Honest status ("exercises through 00.9", "capstone in progress")
  • Licence file
  • No secrets, no .env, no giant data dumps — git status clean, secret_scan_local.py clean

Symptom Almost always means First move
Permission denied (publickey) on push SSH key not on the account, not loaded in agent, or wrong key offered ssh -T git@github.com, ssh-add -l, re-add pubkey in Settings
remote: Repository not found on HTTPS Auth worked but repo doesn't exist for that account — private repo you can't see, or typo in URL Check URL + gh auth status; private repos 404 rather than 403 by design
Password prompt loops forever on HTTPS Using account password instead of a token (post-2FA) gh auth login / credential helper; never paste password
! [rejected] main -> main (non-fast-forward) Remote has commits you don't (someone pushed, or you created repo with README) git fetch, inspect, git pull --rebase or merge
PR shows "This branch has conflicts" Base moved since you branched git switch <branch> && git pull --rebase origin main, resolve, push
Checks stuck "Expected — waiting for status" Required check name in branch protection doesn't match the workflow's job name Align names; check .github/workflows/ name:/job ids
Actions log shows *** where a value should be That's secret masking working — the value was printed Stop printing it; rotate if it was real
Dependabot PR fails CI The bump broke tests or needs a code change Read the changelog; fix or close with explanation
Secret scanning alert on old commit Credential in history, possibly long rotated Rotate now if not already; then decide on history rewrite
gh: command not found after install PATH not refreshed (Windows especially) New terminal window; gh --version to confirm
Everything works locally, CI fails CI runs clean Linux; your machine isn't — line endings, case-sensitivity, missing lockfile entry Reproduce in a clean env; check .gitattributes, uv sync --locked

Common misconceptions#

Misconception Reality
"Git and GitHub are the same thing." Git is the local version-control tool; GitHub is a host plus collaboration features (PRs, issues, Actions). Git works fine with no GitHub at all — Part 3.2 proved it.
"I need to pay for GitHub." Free covers unlimited public repos with full features and unlimited private repos with a limited set — enough for learning and portfolio work.
"git pull is always safe." pull = fetch + merge/rebase and changes your working tree. fetch first when you want to look before leaping.
"HTTPS needs my GitHub password." Since 2FA, git-over-HTTPS uses a token — gh auth login manages it for you. Your password is for the website only.
"A token in the remote URL is convenient." It lands in .git/config, shell history and logs — and any git remote -v prints it. Never.
".gitignore removes files from git." It only affects untracked files. Already-committed files need git rm --cached.
"Deleting a branch loses the work." After a merge (especially squash), the commits live on in main's history; the branch is just a label. Delete freely after merge.
"Squash merge loses history." It consolidates the PR's commits into one — deliberate, for clean history. The original commits remain reachable via the PR's reflog/patch if truly needed.
"Force-push is always forbidden." It's fine on your own unmerged feature branch with --force-with-lease; never on shared/main branches.
"Private repo = secrets are safe." Private repos still leak via collaborators, forks-internal visibility, backups and support access — and secret scanning is paid there. Rotate anyway.
"CI secrets can't leak because they're masked." Masking catches literal prints only; encoding or splitting bypasses it. Treat secrets as write-only.
"More stars = better portfolio." Recruiters read READMEs and commit quality, not star counts. Honest small projects win.
"Code review is for seniors checking juniors." Everyone reviews everyone; it's how teams share knowledge and how you get better fastest.

Key takeaways#

  • git ≠ GitHub ≠ GitLab/Bitbucket. Git versions files locally; a host adds remotes, PRs, issues, CI and permissions. The concepts transfer across hosts; the buttons don't.
  • Free is enough for learning and portfolio work: unlimited public repos (full features) and private repos (limited set), Dependabot alerts, $12/month Actions compute, 120 Codespaces hours, Pages on public repos — as of November 2026.
  • 2FA on, recovery codes saved, professional email — the account is the root of trust for everything else.
  • Remotes: origin is the conventional name; fetch updates knowledge safely, pull changes files, push -u sets tracking. A bare repo (git init --bare) is a complete offline remote — every command in this lesson works against it.
  • HTTPS + gh auth login (or Git Credential Manager for plain git) is the easiest auth; SSH keys (Ed25519, passphrase, ssh-agent, public key to GitHub) are the classic professional setup. Tokens are for HTTPS/API: fine-grained github_pat_ beats classic ghp_ for least privilege; never in URLs, commits or logs; GitHub Apps beat both for org automation.
  • Pull requests are the unit of review: small diffs, title + why-focused description, draft until ready, review comments/suggestions, address feedback with new commits, merge with the repo's convention (squash is the common default), delete the branch.
  • Issues are the work queue: reproducible bug reports, feature requests with the problem first, labels/milestones, Fixes #N linking. GFM adds task lists, alerts, mentions, refs, collapsible sections and Mermaid to plain Markdown.
  • Team files: CONTRIBUTING.md, CODE_OF_CONDUCT.md, SECURITY.md, CODEOWNERS, templates. Branch protection (free on public repos) makes main safe: required reviews, required checks, no force-push.
  • Releases: semver tags, GitHub Releases, changelog — generate notes from Conventional Commits.
  • GitHub Actions: .github/workflows/*.yml, on/jobs/steps/uses/run/secrets/matrix; secrets are write-only; pin actions (SHA for sensitive ones); checks become merge gates.
  • Security: secret scanning + push protection free on public repos (paid for private); Dependabot alerts/updates; private vulnerability reporting; rotate-first response to leaks; signed commits show "Verified".
  • Portfolio: username/username README repo, ≤6 pinned items, READMEs that answer what/how/tested/status in 30 seconds.

Terms introduced in this lesson#

Term One-line definition
Git host A service storing git repositories plus collaboration features (GitHub, GitLab, Bitbucket)
Repository (repo) One project's full git history plus its hosting features
Remote Another copy of a repository git can push to/fetch from
origin / upstream Conventional remote names: the repo you cloned from / the original repo behind your fork
Remote-tracking branch Local bookmark like origin/main recording the remote's state at last fetch
Upstream tracking The link letting plain git push/git pull know the remote counterpart
Bare repository A git repo with no working tree — just objects and refs; used as a remote or backup
Fork Your own copy of someone else's repo, used to contribute back via PR
Pull request (PR) A proposal to merge a branch, with diff, discussion, checks and review
Draft PR A PR marked not-ready-for-review that still runs CI
Review comment / suggestion Line-anchored feedback; a suggestion is an applyable diff block
Force-push (--force-with-lease) Rewriting remote history on your own branch; --force-with-lease is the safe form
Merge commit / squash / rebase merge The three PR merge strategies GitHub offers
Issue A tracked bug report or feature request in a repo
Label / milestone / assignee Issue metadata: category, release grouping, ownership
GitHub Discussions Forum-style Q&A threads attached to a repo
GFM (GitHub Flavoured Markdown) Markdown plus GitHub extensions: task lists, alerts, mentions, Mermaid
Alert ([!NOTE] etc.) GFM coloured callout box in blockquotes
CONTRIBUTING.md File telling contributors how to set up, code and submit
CODEOWNERS File mapping paths to required reviewers
SECURITY.md File explaining how to privately report vulnerabilities
Branch protection / ruleset Rules controlling pushes, merges, reviews and checks on a branch
Required status check A CI check that must pass before merge is allowed
Semantic versioning (semver) MAJOR.MINOR.PATCH versioning contract for releases
GitHub Release A named snapshot (tag + notes + binaries) of a repo
Changelog Human-readable list of changes per release
Trunk-based / GitHub Flow / Git Flow The three common branching workflow models
Monorepo / polyrepo One repo for everything / one repo per project
GitHub Actions GitHub's CI/CD platform: YAML workflows on hosted runners
Workflow / job / step An Actions file / a runner + ordered steps / one command or action
uses: / run: In a step: invoke a prebuilt action / run a shell command
Runner The machine executing an Actions job (ubuntu-latest etc.)
${{ secrets.X }} / ${{ vars.X }} Workflow access to encrypted secrets / plain variables
Matrix Running one job across combinations (Python versions, OSes)
GITHUB_TOKEN Automatic per-run token scoped by permissions:
Dependabot GitHub's dependency-update bot: alerts, security updates, version updates
Dependency review PR-time check flagging newly added vulnerable dependencies
Private vulnerability reporting Structured private channel for security researchers on public repos
Secret scanning / push protection Detection of leaked credentials / blocking pushes containing them
Signed commit Commit cryptographically proven to come from a key holder ("Verified" badge)
Personal access token (PAT) Token authenticating API/git-over-HTTPS; classic (ghp_) vs fine-grained (github_pat_)
SSH key pair Private key (yours) + public key (on GitHub) for passwordless git auth
ssh-agent Helper holding decrypted SSH keys so you type the passphrase once
Git Credential Manager (GCM) Credential helper giving plain git HTTPS the same browser sign-in gh provides
GitHub App Bot identity with fine-grained permissions for org/long-lived automation — GitHub's recommended alternative to PATs there
Issue form .yml template in ISSUE_TEMPLATE/ rendering structured web-form fields instead of free text
Profile README README.md in a username/username repo rendered on your profile
Pinned repositories Up to six repos/gists chosen for your profile's Pinned section

All terms are also collected in the glossary.


Exercises#

  1. Offline remote (3.2): in a mktemp -d scratch folder, repeat the bare-remote demo: init origin.git, clone ai-path, two commits, push -u, a teammate clone that pushes a third commit, then fetch + status -sb + pull --ff-only. Paste your git log --oneline --graph --all.
  2. Simulate a PR merge (4.6): on the scratch repo, create docs/notes branch, commit, push, git switch main, git merge --no-ff docs/notes -m "Merge branch 'docs/notes'", push, delete the branch locally and on the remote. Compare git log --graph before and after. Online version (free account): push ai-path to GitHub as in 3.7, then git switch -c docs/notes, commit, git push -u origin docs/notes, gh pr create --fill, gh pr merge --squash --delete-branch, and paste your gh pr status output — the real PR-to-yourself loop from Part 4.
  3. HTTPS vs SSH (3.3): your work machine is behind a corporate proxy that blocks port 22; your home laptop isn't. Which transport for each, and what changes?
  4. Token scopes (3.6): a teammate needs CI to read ai-path's contents and open PRs, nothing else. Write the fine-grained PAT configuration (resource owner, repos, permissions, expiry) you'd give them, and justify each choice.
  5. Write the PR (4.3): given this diff summary — "adds rate_limit.py with token-bucket limiter; wires it into client.py; 6 new tests" — write a PR title and description using the template in 4.3.
  6. Review catch (4.7): this PR snippet has three planted problems — find them:
    python
    def get_user(user_id):
        return db.query("SELECT * FROM users WHERE id = " + user_id)
    python
    for i in range(len(items)):
        process(items[i])
    python
    try:
        risky()
    except:
        pass
  7. Issue report (5.2): write a bug report for "the app sometimes logs me out" using the template — include steps, expected/actual, environment fields.
  8. GFM rendering (5.5): write a README section containing a task list, a > [!WARNING] alert, a collapsible <details> block with a log, and a small mermaid flowchart. Push it (or preview via gh api) and confirm each renders.
  9. Local secret scan (8.6): save secret_scan_local.py from 8.6 and run it inside ai-path after adding a .env with OPENAI_API_KEY=sk-.... Then fix the repo so a second run is clean — and explain why .gitignore alone didn't do it.
  10. Merge strategy (4.6): for each scenario pick merge/squash/rebase and justify: (a) a 2-commit typo fix, (b) a 30-commit feature branch where each commit is meaningful, (c) a PR from a first-time contributor with 12 "fix" commits.
  11. CONTRIBUTING.md (6.1): draft a 15-line CONTRIBUTING.md for ai-path: setup, test command, commit style, PR checklist.
  12. Workflow YAML (7.3): write .github/workflows/tests.yml for a uv project that runs ruff and pytest on pushes to main and all PRs. Then add a matrix over Python 3.11–3.13.
  13. Leak response (8.5): order these actions correctly and justify the order: delete the file, rotate the key, rewrite history, open an incident note, add .env to .gitignore, notify collaborators.
  14. Portfolio (9): audit your GitHub profile against the 9.3 checklist; write the profile README for username/username and pick your six pins.
  15. Release notes from commits (6.3): save whats_changed.py from the solution below into ai-path, run python3 whats_changed.py, make one feat: commit and one fix: commit, run it again, then git tag -a v0.1.0 -m "Release 0.1.0" and run python3 whats_changed.py v0.1.0..HEAD to see range filtering.
Solutions
  1. Offline remote: save this as bare_remote_demo.sh and run bash bare_remote_demo.sh "$(mktemp -d)/demo" — it performs the whole exercise: init bare origin.git, clone ai-path, two commits on main, push -u, a teammate clone that commits and pushes, then fetch/status -sb/pull --ff-only, a simulated PR merge with --no-ff, branch deletion and ls-remote. The throw-away identity and fixed dates make the SHAs reproducible (f704e4c → eba7e92 → 614f453, merge 93c1e5b).
bash
#!/usr/bin/env bash
# bare_remote_demo.sh — offline simulation of the GitHub "remote" workflow.
#
# Teaches: git init --bare, clone, push -u, branch + push, a simulated
# pull-request merge, fetch vs pull, ls-remote, branch -vv tracking.
#
# Usage: bash bare_remote_demo.sh <workdir>
# Everything runs with a throw-away identity and fixed dates so the
# commit SHAs in the output are reproducible on any machine.

set -euo pipefail

WORK="$1"
mkdir -p "$WORK"
cd "$WORK"

# Throw-away identity and clock: the machine's real git config is never read.
export GIT_CONFIG_GLOBAL=/dev/null
export GIT_CONFIG_SYSTEM=/dev/null
export GIT_AUTHOR_NAME="Learner"
export GIT_AUTHOR_EMAIL="learner@example.com"
export GIT_COMMITTER_NAME="Learner"
export GIT_COMMITTER_EMAIL="learner@example.com"
export TZ=UTC
export GIT_AUTHOR_DATE="2026-11-01T09:00:00+00:00"
export GIT_COMMITTER_DATE="2026-11-01T09:00:00+00:00"

say() { printf '\n===== %s =====\n' "$1"; }

say "1. Create the 'remote': a bare repository (what GitHub hosts for you)"
git init --bare -b main origin.git

say "2. Clone it (empty for now) and check the remote"
git clone origin.git ai-path
cd ai-path
git remote -v

say "3. First commits on main"
cat > README.md <<'EOF'
# ai-path

My workspace for the AI engineer learning path.
EOF
cat > .gitignore <<'EOF'
.env
__pycache__/
.venv/
EOF
mkdir -p notes
git add README.md .gitignore
git commit -m "feat: scaffold ai-path workspace"

export GIT_AUTHOR_DATE="2026-11-01T09:05:00+00:00"
export GIT_COMMITTER_DATE="2026-11-01T09:05:00+00:00"
cat > notes/api-facts.md <<'EOF'
# API facts verified

- Responses API is OpenAI's primary API.
- Anthropic Messages API requires anthropic-version header.
EOF
git add notes/api-facts.md
git commit -m "docs: add verified API facts notes"
git log --oneline

say "4. Push main to the remote for the first time (-u sets tracking)"
git push -u origin main
git status -sb

say "5. A teammate (a second clone) commits and pushes"
cd "$WORK"
git clone origin.git teammate
cd teammate
export GIT_AUTHOR_DATE="2026-11-02T10:00:00+00:00"
export GIT_COMMITTER_DATE="2026-11-02T10:00:00+00:00"
cat >> notes/api-facts.md <<'EOF'
- Gemini generateContent takes the model in the URL path.
EOF
git add notes/api-facts.md
git commit -m "fix: correct Gemini endpoint note"
git push origin main

say "6. Back in ai-path: fetch shows the remote moved; pull fast-forwards"
cd "$WORK/ai-path"
git fetch origin
git status -sb
git pull --ff-only
git log --oneline -3

say "7. Feature branch + 'pull request' simulated by a local merge"
export GIT_AUTHOR_DATE="2026-11-03T11:00:00+00:00"
export GIT_COMMITTER_DATE="2026-11-03T11:00:00+00:00"
git switch -c docs/fix-readme-typo
cat >> README.md <<'EOF'

Built while following the AI engineer learning path.
EOF
git add README.md
git commit -m "docs: expand README with course context"
git push -u origin docs/fix-readme-typo
git switch main
git merge --no-ff docs/fix-readme-typo -m "Merge branch 'docs/fix-readme-typo'"
git push origin main
git branch -d docs/fix-readme-typo
git push origin --delete docs/fix-readme-typo

say "8. Final state: remotes, branches, graph"
git remote -v
git branch -vv
git ls-remote origin
git log --oneline --graph --all

Key checks: git remote -v shows origin → origin.git; after the teammate push, status -sb shows [behind 1]; pull --ff-only fast-forwards; git ls-remote origin lists HEAD and refs/heads/main with the same SHA; git branch -vv shows the tracking info. 2. PR merge: git log --oneline --graph shows a merge bubble (* with two parents) after --no-ff; git branch -a no longer lists docs/notes; git ls-remote origin lacks refs/heads/docs/notes after the remote delete. Online version: gh pr status shows the PR state; after gh pr merge --squash --delete-branch, gh pr list --state merged shows it merged and the branch is gone locally and on the remote. 3. Transport: work machine → HTTPS (port 443 survives proxies); home laptop → either, SSH preferred. No config change needed per-machine beyond the remote URL; gh auth login on the work machine, SSH key on the laptop. 4. Token: fine-grained PAT, resource owner = your account, repository access = only ai-path, permissions = Contents: Read and write (push/clone) + Pull requests: Read and write (open PRs via API) — nothing else; expiry 90 days; name "ai-path-ci". Justification: least privilege, single repo, auto-expiry bounds the leak window. 5. PR: title feat: add token-bucket rate limiter to API client; body: What (limiter + wiring + tests), Why (provider 429s under burst; ticket #7), How tested (pytest tests/test_rate_limit.py, manual burst replay). Link Fixes #7 if the issue exists. 6. Review catches: (a) SQL injection — string-concatenated query, use parameterised queries; (b) needless index loop — for item in items: is idiomatic and avoids the index bookkeeping; (c) bare except: pass — swallows everything including KeyboardInterrupt, hides bugs; catch specific exceptions and log. 7. Bug report: title "Intermittent logout ~hourly"; steps: log in, leave tab idle 60 min, observe redirect to login; expected: session persists per config (8h); actual: logged out; environment: browser+version, OS, ai-path version; note whether it correlates with deploys or token refresh. 8. GFM: verify each element renders — task lists become checkboxes, the alert becomes a coloured box, <details> collapses, the mermaid fence draws the diagram. If a fence shows as code, check the language tag spelling. 9. Secret scan: after git add -f .env && git commit, the scanner flags .env:1. .gitignore doesn't untrack — fix is git rm --cached .env (keep local file), commit, re-scan → clean. If it was pushed, rotate the key (03.1 §3.7). 10. Merge strategy: (a) squash — two commits are noise, one clean commit suffices; (b) rebase or merge commit — meaningful individual commits deserve preserving (rebase for linear, merge commit to keep branch context); (c) squash — twelve "fix" commits are WIP noise; squash into one well-described commit, keep the PR description as the narrative. 11. CONTRIBUTING.md: setup (uv sync, .env from .env.example), test (uv run pytest), style (ruff clean, Conventional Commits, small PRs), checklist (tests pass, README updated, no secrets — run secret_scan_local.py), review expectations. 12. Workflow: the 7.3 example is the answer; matrix adds strategy.matrix.python: ["3.11","3.12","3.13"] and with: python-version: ${{ matrix.python }} on setup-uv (or setup-python). 13. Order: rotate key first (dead key = harmless history) → remove from code + .gitignore → git rm --cached if tracked → assess exposure → then decide on history rewrite (disruptive, needs force-push coordination) → notify collaborators last with what was done. 14. Portfolio: profile README with bio + learning focus + links; pins = capstone, best project repo, ai-path, a tool/script repo, a write-up repo, one wildcard. README per 9.3 checklist; verify no .env in history (git log --all -- .env empty, scanner clean).

  1. Release notes: save this as whats_changed.py and run it inside the exercise-1 demo repo (or any repo with Conventional Commits). python3 whats_changed.py groups git log --no-merges --format=%s subjects by type into Markdown sections; pass a range like v0.1.0..HEAD to limit it. Non-conventional subjects — and conventional types with no section of their own, like wip: — land under "Other", and type!:/type(scope)!: marks the entry BREAKING. On the demo repo it printed:
python
#!/usr/bin/env python3
"""whats_changed.py — draft release notes from Conventional Commits.

Reads `git log --no-merges --format=%s` (optionally limited to a range such
as `v1.2.0..HEAD`) and groups commit subjects into Markdown sections by
their conventional-commit type. Standard library only; deterministic output. Subjects that aren't
conventional — and conventional types with no section above (e.g. `wip:`) —
land under "Other".

Usage:  python3 whats_changed.py [git-range]
Example: python3 whats_changed.py v1.4.0..HEAD
"""

import re
import subprocess
import sys
from collections import OrderedDict

# Section order mirrors keep-a-changelog-ish priorities: what users get
# first, chores last.
SECTIONS = [
    ("feat", "Features"),
    ("fix", "Bug fixes"),
    ("perf", "Performance"),
    ("refactor", "Refactoring"),
    ("docs", "Documentation"),
    ("style", "Style"),
    ("test", "Tests"),
    ("build", "Build and dependencies"),
    ("ci", "CI"),
    ("chore", "Chores"),
    ("revert", "Reverts"),
]

CONVENTIONAL = re.compile(r"^(\w+)(?:\([^)]*\))?(!)?:\s*(.+)$")


def commit_subjects(git_range: str | None) -> list[str]:
    cmd = ["git", "log", "--no-merges", "--format=%s"]
    if git_range:
        cmd.append(git_range)
    out = subprocess.run(cmd, capture_output=True, text=True, check=True)
    return [line for line in out.stdout.splitlines() if line.strip()]


def classify(subject: str) -> tuple[str, str, bool]:
    """Return (section-key, bullet-text, breaking?)."""
    m = CONVENTIONAL.match(subject)
    if not m:
        return ("other", subject, False)
    kind, bang, rest = m.group(1).lower(), m.group(2), m.group(3).strip()
    breaking = bool(bang)
    return (kind, rest, breaking)


def main() -> int:
    git_range = sys.argv[1] if len(sys.argv) > 1 else None
    subjects = commit_subjects(git_range)
    if not subjects:
        print("No commits in range.")
        return 0

    grouped: "OrderedDict[str, list[str]]" = OrderedDict(
        (key, []) for key, _ in SECTIONS
    )
    grouped["other"] = []
    titles = dict(SECTIONS)
    titles["other"] = "Other"

    for subject in subjects:
        key, text, breaking = classify(subject)
        if key not in grouped:
            key = "other"  # valid conventional format, but a type with no section
        if breaking:
            text = f"**BREAKING** {text}"
        grouped[key].append(f"- {text}")

    print(f"## Release notes{f' ({git_range})' if git_range else ''}\n")
    wrote = False
    for key, _title in SECTIONS + [("other", "Other")]:
        bullets = grouped[key]
        if not bullets:
            continue
        wrote = True
        print(f"### {titles[key]}\n")
        print("\n".join(bullets))
        print()

    if not wrote:
        print("(range contains only merge commits)")
    return 0


if __name__ == "__main__":
    sys.exit(main())
text
Output:
## Release notes

### Features

- scaffold ai-path workspace

### Bug fixes

- correct Gemini endpoint note

### Documentation

- expand README with course context
- add verified API facts notes

Where you'll use this in the AI path#

Skill from this lesson Where it shows up next
Keeping secrets out of git; .env discipline 03.1 Part 3: Accounts, keys and secrets — provider keys live in .env, never in commits
Responding to a leaked provider key 03.1 §3.7: When a key leaks — the hour-by-hour playbook this lesson previews
PR workflow, Conventional Commits, small reviewable changes Every project in Modules 04–12 is built this way; prompt changes get PRs too — 04.10 versions prompts like code
CI checks on every push 11C.2 §2.1: What belongs in ci.yml — the deterministic-checks spine; eval gates layer on top
Dependency and supply-chain hygiene 12.7 §3.2: Prevention — Dependabot, pinning, secret scanning in the AI threat model
Release tagging and versioned artefacts 04.10 §4.1: Versions and 11C.1 deployment
Portfolio and profile Module 14B: Career Appendix — the capstone and job-search material build directly on this
Asking for help, debugging together 00.9: Working Like an Engineer — issues and PRs are also how you ask strangers for help well

Check yourself#

  1. Name the three layers "git", "a git host" and "GitHub" and one thing each provides that the others don't.
  2. What's the difference between git fetch and git pull, and why is fetch the safer habit?
  3. Your git status -sb shows ## main...origin/main [ahead 2, behind 1]. What does that mean, and what's your safest next step?
  4. Why does git push over HTTPS fail or prompt after you enable 2FA — and what does gh auth login change?
  5. What's the difference between a classic PAT and a fine-grained PAT, and which should a CI job that only reads one repo use?
  6. Why is putting a token in the remote URL (https://TOKEN@github.com/...) a bad idea?
  7. When do you fork vs branch-and-PR?
  8. What's the difference between a PR comment, a line comment and a suggestion?
  9. When is git push --force-with-lease acceptable, and when is it dangerous?
  10. Which merge strategy keeps every commit, which makes one commit, and which gives a linear history?
  11. What does Fixes #42 in a PR description do?
  12. Name four files a well-run repo has at its root and what each is for.
  13. What's the difference between a repository secret and a variable in Actions, and why must you never echo a secret?
  14. Why is secret scanning free on public repos but paid on private ones — and what does that imply for where you keep learning repos?
  15. You committed .env with a live API key and pushed to a private repo. List the first three things you do, in order.

Further resources#


← 00.3 — Git Fundamentals | Module 00 overview | 00.5 — How Web Apps Work: Client, Server and Database →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close