← Back to dashboard

GitHub Developer Course

What is GitHub?

The real model

Commit DAG + PR-gated trunk; automate with Actions, secure with the built-in suite, drive from Claude Code.

Master is protected by a ruleset; work happens on branches merged via PRs that must pass review + required status checks. Choose your integration deliberately: merge (preserve shape), rebase (linear, local-only before pushing), squash (one tidy commit — codeAmani's default into master). Actions runs CI on `on: [push, pull_request]` with jobs/needs/matrix, least-privilege `permissions`, SHA-pinned (or `actions.lock`-locked) actions, and attestations for anything you ship. Turn on secret scanning + push protection so a leaked API key never lands, and verify every webhook's `X-Hub-Signature-256` before parsing. Claude Code drives PRs/issues/Actions via the GitHub MCP server (v2), and a push to master fires the Vercel deploy — so green CI + rulesets are what keep production safe.

Six things to master

From commits to CI to Claude Code. Tap a card for the commands + gotchas.

Branch & PR simulator — merge vs squash vs rebase

The concept new developers most often get wrong. Switch the integration strategy and watch the commit graph redraw — then walk a pull request from open to deployed, and toggle a failing check to see branch protection block the merge.

Integrate the feature branch with:
masterfeatureABCSDE
merge --squashD + E collapse into one commit S on master. The branch detail is discarded — master reads as one tidy commit per feature. codeAmani's default.
PR lifecycle
  1. 1Open
  2. 2Review
  3. 3CI checks
  4. 4Merged

Push a branch and `gh pr create`. The PR is a proposal — nothing has touched master yet.

Text
 ██████╗ ██╗████████╗██╗  ██╗██╗   ██╗██████╗
██╔════╝ ██║╚══██╔══╝██║  ██║██║   ██║██╔══██╗
██║  ███╗██║   ██║   ███████║██║   ██║██████╔╝
██║   ██║██║   ██║   ██╔══██║██║   ██║██╔══██╗
╚██████╔╝██║   ██║   ██║  ██║╚██████╔╝██████╔╝
 ╚═════╝ ╚═╝   ╚═╝   ╚═╝  ╚═╝ ╚═════╝ ╚═════╝

GitHub Developer Course

Focus: A hands-on path from git init to shipping with confidence: Git fundamentals, collaboration on GitHub, Actions/CI-CD, security and supply chain, the wider ecosystem, and driving it all from Claude Code. Grounded in docs.github.com, the GitHub changelog and the official release pages; reviewed 2026-10-20.

How this course works

Four levels, each ending with a ✅ capability checkpoint ("you can now…") and a 🛠 exercise. Work top-to-bottom the first time; use the command cheat-sheet and Table of Contents as reference after. The interactive learn module above this page (a branch & PR lifecycle simulator) is your illustration for Level 2; play with it before reading the merge/rebase section.

Table of Contents

Official Documentation

Verified versions (2026-10-20)

ThingVersionSource
actions/checkoutv7.0.1 (3d3c42e5aac5ba805825da76410c181273ba90b1)GitHub releases
actions/setup-nodev7.1.0 (949feb2413d6458794dcd2491c4babbbce0c15c1)GitHub releases
actions/cachev6.1.0GitHub releases
actions/upload-artifact / download-artifactv7.0.2 / v8.0.2GitHub releases
actions/attestv4.2.2 (1e69f48acb82d1966a394da916b4c1698aa569d6); attest-build-provenance v4.2.2 is now a thin wrapperGitHub releases
actions/create-github-app-tokenv3.3.0GitHub releases
actions/dependency-review-actionv5.0.0GitHub releases
github/codeql-actionv4.39.0 (use @v4)GitHub tags
actions/upload-pages-artifact / deploy-pagesv5.0.0 / v5.0.1GitHub releases
anthropics/claude-code-actionv1 → v1.0.254 (db77d4d3c98f3f6380e7cd45ffba2342a3dbde3c)GitHub tags
github/github-mcp-serverv2.0.2 (2026-10-08)GitHub releases
gh CLIv2.102.0cli/cli releases
@octokit/rest / octokit22.0.1 / 5.0.5 (ESM-only, Node ≥ 20)npm view
@octokit/webhooks-methods / @octokit/webhooks6.0.0 / 14.2.0npm view
@anthropic-ai/claude-code2.1.304npm view
REST API version2026-03-10 (newest); 2022-11-28 supported until 2028-03-10docs.github.com

Level 1 — Git fundamentals

Git vs GitHub

Git is the version-control tool that runs on your machine. It records snapshots (commits) of your files. GitHub is the hosted home for Git repositories that adds collaboration: pull requests, reviews, issues, CI/CD, security, and agents.

Text
   your machine (Git)                         GitHub (remote)
 ┌────────────────────┐    git push     ┌────────────────────┐
 │ working dir        │ ─────────────▶  │  origin/master     │
 │   └ staging (index)│                 │  PRs · Actions ·    │
 │       └ .git/ (commits, branches)    │  Issues · Security  │
 └────────────────────┘ ◀───────────── └────────────────────┘
                          git pull

A file moves through three states: working directory → staging area (git add) → committed history (git commit).

Setup & first-time config

Bash
# Install Git + the GitHub CLI
winget install Git.Git GitHub.cli     # Windows
brew install git gh                    # macOS
sudo apt install git gh               # Debian/Ubuntu (incl. WSL)

# One-time identity
git config --global user.name  "Your Name"
git config --global user.email "you@codeamani.com"
git config --global init.defaultBranch master   # codeAmani repos deploy from master
git config --global pull.rebase false            # merge on pull (or 'true' to rebase)

# Authenticate the CLI (browser flow; stores a token in the OS keychain)
gh auth login
gh --version   # expect 2.102.x or newer

The core loop

Bash
git init                      # start a repo here   (or: gh repo clone owner/name)
git status                    # what changed?
git add file.ts               # stage a change      (git add -A for everything)
git commit -m "feat: add login form"
git log --oneline --graph     # see history as a graph
git diff                      # unstaged changes    (git diff --staged for staged)

Write good commit messages: a short imperative summary (fix: handle null token), optionally a body explaining why. The codeAmani convention follows Conventional Commits (feat:, fix:, chore:, docs:).

Branches: the cheap pointer

A branch is just a movable pointer to a commit; creating one is instant and free. This is the mental model that makes everything else click.

Bash
git switch -c feature/mpesa-stk      # create + switch (old: git checkout -b)
git switch master                    # switch back
git branch                           # list local branches
git branch -d feature/mpesa-stk      # delete a merged branch

Remotes & pushing to GitHub

Bash
gh repo create codeAmani-Labs/my-app --private --source=. --push   # create + link + push
# …or link an existing remote
git remote add origin https://github.com/codeAmani-Labs/my-app.git
git push -u origin master            # -u sets the upstream once
git pull                             # fetch + merge remote changes
git fetch origin                     # download without merging
gitignore
# .gitignore — never track secrets or build junk
.env*
!.env.example
node_modules/
.next/
*.log

✅ Checkpoint: You can initialise a repo, stage and commit changes, branch, and push to GitHub. 🛠 Exercise: Create a repo with gh repo create, add a README.md, commit on a feature/readme branch, and push it.


Level 2 — Collaboration

Merge vs rebase vs squash

The three ways to integrate a branch, and the concept developers most often get wrong. Play with the simulator above to see the commit graph redraw for each.

StrategyWhat it doesHistoryUse when
MergeCreates a merge commit joining both linesPreserves true branch shapeShared/long-lived branches; you want the full record
RebaseReplays your commits on top of the targetLinear, no merge commitsCleaning up your local branch before a PR
SquashCombines all branch commits into oneOne tidy commit per featureMerging a PR into master (the codeAmani default)
Bash
git merge feature/x                  # merge feature/x into current branch
git rebase master                    # replay current branch on top of master
git rebase -i HEAD~3                  # interactively squash/reorder last 3 commits
# Golden rule: never rebase commits you've already pushed to a shared branch.

Pull requests: the unit of collaboration

A PR proposes merging one branch into another, gated by review + CI before it lands. Lifecycle: open → review → CI checks → approve → merge (or the merge queue on busy repos).

Bash
gh pr create --title "feat: Stripe checkout" --body "Adds Checkout Session + webhook"
gh pr create --fill                  # use branch name + last commit as title/body
gh pr list                           # open PRs
gh pr view 42 --web                  # open in browser
gh pr checks 42 --watch              # CI status for the PR, live
gh pr merge 42 --squash --delete-branch
gh pr merge 42 --squash --auto       # merge automatically once checks pass

Code review

Bash
gh pr diff 42                        # read the changes
gh pr review 42 --approve
gh pr review 42 --request-changes --body "Verify the Stripe signature before parsing"
gh pr review 42 --comment --body "Nice — one nit inline"

A good review checks correctness, security (no secrets, input validated, webhooks verified), tests, and clarity. Keep PRs small; they get reviewed faster and merge cleaner. AI reviewers (Copilot code review, the Claude Code Action) are a first pass, not a substitute for a human approval on master.

Resolving conflicts

Bash
git switch feature/x
git merge master                     # conflict markers appear in files
# Edit the <<<<<<< / ======= / >>>>>>> sections, choosing the right code, then:
git add resolved-file.ts
git commit                           # completes the merge

Undoing things safely

GoalCommandSafe on shared history?
Discard unstaged file changegit restore file✅
Unstage a filegit restore --staged file✅
Amend the last commitgit commit --amend❌ (rewrites)
Undo a commit, keep changesgit reset --soft HEAD~1❌
Revert a pushed commitgit revert <sha>✅ (new inverse commit)
Stash work-in-progressgit stash / git stash pop✅
Recover "lost" commitsgit reflog✅ (your safety net)

git revert is the safe public undo; git reset/--amend rewrite history (force-push territory). When in doubt, git reflog remembers where everything was.

Issues, labels & Projects

Bash
gh issue create --title "Bug: webhook times out" --label bug,priority:high
gh issue list --assignee @me
gh issue close 17 --comment "Fixed in #42"
gh project list --owner codeAmani-Labs     # Projects (v2) boards

Rulesets & branch protection

Protect master so nothing merges unreviewed or red. Repository rulesets (Settings → Rules → Rulesets) are the current mechanism: they stack, can target many branches by pattern, can be set at org level, and support bypass lists. Classic branch protection still works.

Bash
# Classic branch protection via the REST API (still supported)
gh api -X PUT repos/codeAmani-Labs/my-app/branches/master/protection \
  --input - <<'JSON'
{
  "required_status_checks": { "strict": true, "contexts": ["lint", "typecheck", "test"] },
  "enforce_admins": true,
  "required_pull_request_reviews": { "required_approving_review_count": 1 },
  "restrictions": null
}
JSON
# Rulesets: list what's applied to a repo
gh api repos/codeAmani-Labs/my-app/rulesets

✅ Checkpoint: You can open a PR, review it, resolve conflicts, undo mistakes safely, and protect a branch. 🛠 Exercise: Open a PR from your feature/readme branch, request a change on it, push a fix, then squash-merge it with --auto.


Level 3 — Automation, security & ecosystem

GitHub Actions (CI/CD)

Workflows are YAML in .github/workflows/. Structure: events (on) → jobs → steps. Jobs run in parallel unless chained with needs.

YAML
# .github/workflows/ci.yml — full file in github/examples/ci.yml
name: CI
on:
  push: { branches: [master] }
  pull_request: { branches: [master] }
  workflow_dispatch:           # manual "Run workflow" button

permissions:
  contents: read               # least privilege by default

concurrency:                   # cancel superseded runs of this workflow on the same ref
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  check:
    runs-on: ubuntu-latest
    timeout-minutes: 15        # default job cap is 6 h on GitHub-hosted runners
    strategy:
      fail-fast: false
      matrix:
        task: [lint, typecheck, test]
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with: { persist-credentials: false }
      - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
        with: { node-version: "24", cache: npm }
      - run: npm ci
      - run: npm run ${{ matrix.task }}

Key building blocks:

  • Triggers: push, pull_request, workflow_dispatch (manual), schedule (cron), workflow_call (reusable).
  • needs: declare job dependencies and pass outputs between jobs.
  • matrix: fan a job across tasks/versions/OSes.
  • permissions: scope the built-in GITHUB_TOKEN; start at contents: read, or {} and grant per job.
  • timeout-minutes: always set one. GitHub-hosted jobs otherwise run up to 6 hours (self-hosted: 5 days).
  • Caching: cache: npm on setup-node, or actions/cache@v6. Cache storage is 10 GB per repo included.
  • Secrets: ${{ secrets.NAME }}; prefer OIDC over long-lived cloud keys.
  • Node versions: Node 24 is Active LTS, Node 22 Maintenance LTS, Node 20 is EOL (2026-04-30). Matrix [22, 24] if you need both.
Bash
gh workflow list
gh workflow run ci.yml --ref master
gh run watch                   # live-stream the active run
gh run view 12345678 --log-failed

Workflow security rules that bite:

  • pull_request_target and workflow_run run with the base repo's privileges (secrets, write token, shared cache). Never check out and run fork PR code in them. Use pull_request for CI on untrusted code.
  • Never interpolate ${{ github.event.* }} text (PR titles, branch names, comment bodies) straight into run:; pass it through env: and quote it. That's script injection.
  • persist-credentials: false on actions/checkout unless a later step really needs to push.

Pinning actions: SHAs and the lockfile

A tag like @v7 is a movable pointer; if an action's repo is compromised the tag can be repointed. Two defences, strongest first:

  1. Workflow dependency lockfile (public preview). gh extension install github/gh-actions-lock, then run gh actions-lock at the repo root. It writes .github/workflows/actions.lock pinning every action (including transitive ones) to a commit and to the source repo's numeric owner/repo IDs, which Actions checks at run time. GitHub's docs say SHA pinning is no longer necessary in repos that adopt it. Dependabot regenerates lockfile entries when it bumps an onboarded workflow. Note: allowed-actions allowlists are then checked against the locked SHA, so tag-pinned allowlist entries stop matching.
  2. Full-length commit SHA in each uses: with the tag in a same-line comment: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1. Dependabot updates both the SHA and the comment.

Caveat: Dependabot alerts only fire for actions referenced by semver tag, not by SHA. Pinned repos rely on Dependabot version updates (package-ecosystem: github-actions) to stay patched.

OIDC: keyless cloud auth

With permissions: id-token: write, a job can mint a short-lived OIDC token (issuer https://token.actions.githubusercontent.com) and exchange it with a cloud provider (AWS, GCP, Azure, and now Anthropic's Workload Identity Federation) instead of storing a long-lived key. Scope the trust policy to repo:OWNER/REPO:ref:refs/heads/master or an environment, never just the org.

Artifact attestations & SLSA

Attestations are Sigstore-signed provenance claims (workflow, repo, commit SHA, trigger) that consumers check with gh attestation verify. Public repos sign with the Sigstore public-good instance (and a public transparency log); private repos use GitHub's own Sigstore instance.

YAML
permissions:
  contents: read
  id-token: write
  attestations: write
steps:
  # …build dist.tar.gz…
  - uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
    with:
      subject-path: dist.tar.gz          # or subject-name + subject-digest for images
Bash
gh attestation verify dist.tar.gz -R codeAmani-Labs/my-app
gh attestation verify oci://ghcr.io/codeamani-labs/app:1.2.0 -R codeAmani-Labs/my-app
SetupSLSA level (per GitHub docs)
actions/attest in the build jobBuild L2
Build + attest inside a shared reusable workflow, verified with --signer-workflowBuild L3
slsa-github-generator isolated buildersBuild L3 (codeAmani's documented default)

Only attest things people download and run (release tarballs, images, packages), not every test build. Full example: github/examples/release-attest.yml. Policy: see the Supply-Chain & Provenance section of CLAUDE.md and supply-chain/CLAUDE_CODE_INTEGRATION.md.

Actions pricing (2026)

Public repos on standard runners: free. Self-hosted runners: free (the announced $0.002/min self-hosted "cloud platform charge" for March 2026 was postponed in December 2025 and the billing docs still list self-hosted as free). Hosted-runner prices dropped by up to 39% on 2026-01-01. Private repos get a monthly quota, then pay per minute (rounded up per job):

RunnerSKU$/min
Linux 1-core x64actions_linux_slim0.002
Linux 2-core x64 (ubuntu-latest)actions_linux0.006
Linux 2-core arm64actions_linux_arm0.005
Windows 2-core x64 / arm64actions_windows / _arm0.010
macOS 3/4-coreactions_macos0.062
Linux 4 / 8 / 16-core (larger)linux_N_core0.012 / 0.022 / 0.042
PlanMinutes / monthArtifact + Packages storageCache / repo
Free (user or org)2,000500 MB10 GB
Pro3,0001 GB10 GB
Team3,0002 GB10 GB
Enterprise Cloud50,00050 GB10 GB

Overage storage: $0.25/GB-month (artifacts + Packages), $0.07/GB-month (cache above 10 GB). Larger runners are never free and can't use included minutes. Agents bill minutes too: Copilot code review, Copilot cloud agent and third-party agents (Claude, Codex) consume Actions minutes on private repos (plus Copilot AI credits). Set a budget under Billing → Budgets and alerts. Arm Linux (ubuntu-24.04-arm) is the cheapest 2-core option for Node builds.

Security suite (shift left)

FeatureWhere it comes fromPrivate repo needs
Dependency graph, Dependabot alerts + security updates + version updatesAll plansnothing extra
Secret scanning + push protection, AI-detected secrets, custom patterns, delegated bypassGitHub Secret Protection ($19 per active committer / month)Team or Enterprise plan
Code scanning (CodeQL), Copilot Autofix, dependency review, AI Scan, security campaignsGitHub Code Security ($30 per active committer / month)Team or Enterprise plan

Public repos get secret scanning, push protection and CodeQL code scanning free. Separately, push protection for users is on by default for every GitHub.com account and stops you pushing secrets to any public repo. Repository push protection is off by default; a repo admin or org owner enables it.

YAML
# .github/dependabot.yml (full file: github/examples/dependabot.yml)
version: 2
updates:
  - package-ecosystem: "npm"
    directory: "/"
    schedule: { interval: "weekly" }
    cooldown: { default-days: 5 }     # version updates default to a 3-day cooldown anyway
    groups:
      minor-and-patch: { update-types: ["minor", "patch"] }
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule: { interval: "weekly" }
YAML
# .github/workflows/codeql.yml — CodeQL code scanning (or use "default setup" in Settings)
name: CodeQL
on: { push: { branches: [master] }, pull_request: { branches: [master] } }
permissions: { contents: read }
jobs:
  analyze:
    runs-on: ubuntu-latest
    permissions: { security-events: write, contents: read }
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - uses: github/codeql-action/init@v4
        with: { languages: javascript-typescript }
      - uses: github/codeql-action/analyze@v4

Prefer code scanning default setup (Settings → Code security → CodeQL → Default) unless you need custom queries; it needs no workflow file. Add actions/dependency-review-action@v5 to PR CI to block PRs that introduce known-vulnerable dependencies (needs Code Security on private repos).

Tokens, PATs & GitHub Apps

CredentialUse it forNotes
GITHUB_TOKEN (Actions)Anything inside a workflow on the same repoAuto-injected, expires with the job, scoped by permissions:
GitHub App installation tokenBots, servers, cross-repo automation, webhooks1-hour tokens, scoped to installed repos + declared permissions, not tied to a person. Preferred for anything long-lived
Fine-grained PATPersonal scripts, local MCP, CLI on one ownerOne owner per token, per-repo selection, expiry (default 30 days, max 366 or none if policy allows), org approval; max 50 per user
Classic PATOnly where fine-grained can't (Packages, Checks API, multi-org, outside-collaborator writes)Broad repo/workflow scopes across every repo you can access. Avoid
OIDCKeyless cloud/vendor auth from ActionsNo stored secret at all
YAML
# Mint an App token inside a workflow (client ID in a repo VARIABLE, key in a SECRET)
- uses: actions/create-github-app-token@v3
  id: app-token
  with:
    client-id: ${{ vars.APP_CLIENT_ID }}
    private-key: ${{ secrets.APP_PRIVATE_KEY }}
- run: gh issue list
  env:
    GH_TOKEN: ${{ steps.app-token.outputs.token }}

Server-side App auth with Octokit lives in github/examples/github-app.ts (new App({ appId, privateKey }) → app.getInstallationOctokit(id)).

Webhooks: verify, then parse

GitHub signs the raw body with your webhook secret (HMAC-SHA256) and sends X-Hub-Signature-256: sha256=<hex>. Verify with a constant-time compare before JSON.parse, respond 2xx within 10 seconds (queue heavy work), and dedupe on X-GitHub-Delivery (redeliveries reuse it). X-Hub-Signature (SHA-1) is legacy only.

TypeScript
// app/api/webhooks/github/route.ts (full file: github/examples/webhook-route.ts)
import { verify } from "@octokit/webhooks-methods";

export async function POST(req: Request): Promise<Response> {
  const secret = process.env.GITHUB_WEBHOOK_SECRET;
  const signature = req.headers.get("x-hub-signature-256");
  if (!secret || !signature) return new Response("unauthorized", { status: 401 });
  const rawBody = await req.text();
  if (!(await verify(secret, rawBody, signature))) {
    return new Response("bad signature", { status: 401 });
  }
  const event = req.headers.get("x-github-event");
  // …dedupe on x-github-delivery, enqueue, then:
  return new Response(event === "ping" ? "pong" : null, { status: event === "ping" ? 200 : 202 });
}

Test vector from the docs: secret It's a Secret to Everybody, payload Hello, World! → sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17.

REST, GraphQL & Octokit

Bash
# REST — anything the API exposes
gh api repos/codeAmani-Labs/my-app/pulls --jq '.[].title'
gh api -X POST repos/codeAmani-Labs/my-app/issues -f title="From the CLI" -f body="…"
gh api --paginate repos/codeAmani-Labs/my-app/issues --jq '.[].number'
# GraphQL — precise, fewer round-trips
gh api graphql -f query='query { viewer { login } }'
# Pin the REST API version for stable scripts
gh api -H "X-GitHub-Api-Version: 2026-03-10" repos/codeAmani-Labs/my-app

The REST API is date-versioned. 2026-03-10 is the newest version; requests without X-GitHub-Api-Version still default to 2022-11-28, which is supported until 2028-03-10 (each version gets at least 24 months after its successor ships; a retired version returns 410 Gone, and Deprecation/Sunset headers warn you first). gh api itself sends 2022-11-28 unless you pass -H (checked with gh api --verbose). Send the header explicitly and read the breaking-changes page before bumping. GraphQL is a single evolving schema; watch its changelog.

TypeScript
// Octokit (TypeScript) — full file: github/examples/octokit.ts
import { Octokit } from "@octokit/rest";          // @octokit/rest 22.0.1, ESM-only

const octokit = new Octokit({
  auth: process.env.GITHUB_TOKEN,
  userAgent: "codeamani-scripts/1.0",
  headers: { "X-GitHub-Api-Version": "2026-03-10" },
});

const prs = await octokit.paginate(octokit.rest.pulls.list, {
  owner: "codeAmani-Labs", repo: "my-app", state: "open", per_page: 100,
});

Pick the package: @octokit/rest for REST-only scripts; octokit (5.x) when you also need GraphQL, Apps (App), OAuth apps, webhooks, retries and throttling in one import. Both are ESM-only and need Node ≥ 20.

Packages & Releases

Bash
gh release create v1.2.0 --generate-notes     # notes from merged PRs
gh release list
# GitHub Packages (npm): "publishConfig": { "registry": "https://npm.pkg.github.com" }, then npm publish
# Packages storage shares the Actions artifact allowance (see pricing table)

Codespaces

A cloud dev environment defined by devcontainer.json, for instant, reproducible onboarding.

JSON
// .devcontainer/devcontainer.json
{
  "image": "mcr.microsoft.com/devcontainers/javascript-node:24",
  "features": { "ghcr.io/devcontainers/features/github-cli:1": {} },
  "postCreateCommand": "npm ci",
  "customizations": { "vscode": { "extensions": ["dbaeumer.vscode-eslint"] } }
}
Bash
gh codespace create -R codeAmani-Labs/my-app
gh codespace code            # open in VS Code

GitHub Pages

Free static hosting from a repo (docs/landing pages). Standard runners are free for Pages builds. Enable under Settings → Pages, or deploy via Actions:

YAML
permissions: { contents: read, pages: write, id-token: write }
# … build, then:
- uses: actions/upload-pages-artifact@v5
  with: { path: dist }
- uses: actions/deploy-pages@v5

✅ Checkpoint: You can write a pinned, least-privilege CI workflow; attest a release; enable Dependabot + CodeQL + push protection; choose between GITHUB_TOKEN, an App and a fine-grained PAT; and verify a webhook signature. 🛠 Exercise: Add examples/ci.yml to a repo, run gh actions-lock, enable Dependabot for github-actions, and wire examples/webhook-route.ts to a test webhook (use the docs' test vector first).


Level 4 — GitHub + AI agents

The GitHub MCP server

The official github/github-mcp-server (v2.0.2, Oct 2026) lets Claude read and act on repos, issues, PRs, Actions, and security alerts in-session. v2.0 added typed tool output schemas for clients on MCP spec 2026-07-28+.

Remote (hosted by GitHub, recommended). Endpoint https://api.githubcopilot.com/mcp/. Auth with OAuth (host-dependent) or a PAT in an Authorization: Bearer header. Read-only: append /readonly. Single toolset: https://api.githubcopilot.com/mcp/x/<toolset> (also /x/all). Or use headers: X-MCP-Toolsets, X-MCP-Tools, X-MCP-Readonly, X-MCP-Lockdown, X-MCP-Insiders.

Bash
# Claude Code ≥ 2.1.1 (per the server's install guide)
claude mcp add-json github '{"type":"http","url":"https://api.githubcopilot.com/mcp","headers":{"Authorization":"Bearer YOUR_FINE_GRAINED_PAT"}}' --scope user
# If add-json returns "Invalid input" on Windows, use the older form:
claude mcp add --transport http github https://api.githubcopilot.com/mcp -H "Authorization: Bearer YOUR_FINE_GRAINED_PAT"
claude mcp list
JSON
// .mcp.json (project scope) — read-only remote server, token from the environment
{
  "mcpServers": {
    "github": {
      "type": "http",
      "url": "https://api.githubcopilot.com/mcp/readonly",
      "headers": { "Authorization": "Bearer ${GITHUB_PERSONAL_ACCESS_TOKEN}" }
    }
  }
}

Local (Docker image or release binary). The local server now does a browser OAuth login on github.com by default (token kept in memory), or takes GITHUB_PERSONAL_ACCESS_TOKEN (takes precedence). Needed for GitHub Enterprise Server (GITHUB_HOST).

Bash
# OAuth login (publish the fixed callback port)
claude mcp add github -e GITHUB_OAUTH_CALLBACK_PORT=8085 -- \
  docker run -i --rm -p 127.0.0.1:8085:8085 -e GITHUB_OAUTH_CALLBACK_PORT ghcr.io/github/github-mcp-server
# PAT + explicit toolsets + read-only + lockdown
claude mcp add github -e GITHUB_PERSONAL_ACCESS_TOKEN -e GITHUB_TOOLSETS=default,actions,code_security -e GITHUB_READ_ONLY=1 -e GITHUB_LOCKDOWN_MODE=1 -- \
  docker run -i --rm -e GITHUB_PERSONAL_ACCESS_TOKEN -e GITHUB_TOOLSETS -e GITHUB_READ_ONLY -e GITHUB_LOCKDOWN_MODE ghcr.io/github/github-mcp-server
ToolsetWhat it covers
context (default)Who am I / where am I. Strongly recommended
repos (default)Files, branches, commits, releases
issues (default)Create, comment, label, sub-issues
pull_requests (default)Create, review, merge, comment
users (default)User lookup
actionsWorkflows, runs, logs
code_security / secret_protection / dependabotCode-scanning, secret-scanning, Dependabot alerts
governanceRulesets and custom properties
copilotAssign work to Copilot cloud agent
otherscode_quality, discussions, gists, git, labels, notifications, orgs, projects, security_advisories, stargazers, copilot_issue_intents
remote-onlycopilot_spaces, github_support_docs_search

Lockdown mode filters content from public repos authored by people without push access, a best-effort guard against prompt injection via issues/PR comments. It is not an authorization boundary; the token's real permissions still apply. Turn it on for agents that read public issues.

The npm package @modelcontextprotocol/server-github is deprecated ("Package no longer supported"). Use the remote endpoint, the Docker image, or the release binary.

Claude Code GitHub Action

anthropics/claude-code-action@v1 runs Claude Code on your runner: mention @claude in an issue/PR, assign an issue, add a label, or run it with a prompt: on any event (scheduled audits, CI-failure fixes, PR review).

  • Setup: run /install-github-app inside claude (repo admin; direct Anthropic API only), or install the Claude GitHub App and add ANTHROPIC_API_KEY as a repo secret. Bedrock, Vertex and Microsoft Foundry are supported via OIDC (use_bedrock, use_vertex, use_foundry).
  • Keyless: Workload Identity Federation (anthropic_federation_rule_id + anthropic_organization_id, optional anthropic_service_account_id/anthropic_workspace_id, id-token: write) exchanges the job's GitHub OIDC token for a short-lived Anthropic token. No API-key secret to rotate.
  • Config: v1 unified everything into prompt and claude_args (CLI flags such as --max-turns, --model, --allowedTools). Other useful inputs: trigger_phrase, assignee_trigger, label_trigger, use_sticky_comment, track_progress, use_commit_signing, plugins, plugin_marketplaces.
  • Safety: allowed_bots and allowed_non_write_users are empty by default; keep them that way on public repos. Claude only triggers for users with write access.
  • Cost: Actions minutes (your runner) + Claude API tokens (your key).

Full workflow: github/examples/claude.yml.

YAML
- uses: anthropics/claude-code-action@v1
  with:
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
    prompt: "Review this PR for security issues: secrets, unverified webhooks, missing input validation."
    claude_args: --max-turns 8

Copilot cloud agent & Claude on Agent HQ

  • Copilot cloud agent (formerly "Copilot coding agent") researches, plans and edits in an ephemeral Actions-powered environment, then opens a PR. Start it from the Agents tab, an issue assignment, a PR comment, or the MCP copilot toolset. One repo, one branch, one PR per task.
  • Third-party agents (public preview, all paid Copilot plans): assign an issue to Claude (Anthropic's agent, built on the Claude Agent SDK) or Codex from the Assignees dropdown, mention @claude on a PR, or pick it in the Agents tab. Enable it in Copilot policies ("Allow Claude coding agent" installs the anthropic code agent app). Generated code is auto-checked with CodeQL, secret scanning and the Advisory Database. Usage consumes Actions minutes + GitHub AI credits.
  • Copilot plans (2026, AI-credit billing): Free; Student (free); Pro $10/mo (1,500 credits incl. flex); Pro+ $39/mo (7,000); Max $100/mo (20,000); Business $19/seat (1,900/user pooled); Enterprise $39/seat (3,900/user pooled). Overage $0.01 per credit; code completions don't consume credits on paid plans.

Which to use? For codeAmani: the Claude Code Action when you want Claude with your own API key, your own CLAUDE.md, plugins and tool allowlist. Claude on Agent HQ when a teammate already has Copilot and wants to hand off an issue from the GitHub UI. Either way, the output is a PR that goes through the same review + required checks.

Claude Code automations

Markdown
<!-- .claude/commands/review-pr.md -->
Review pull request #$ARGUMENTS.
1. Use the GitHub MCP to fetch the PR diff, description and existing comments.
2. Check for bugs, security issues (secrets, unverified webhooks, unvalidated input), missing tests, and convention drift.
3. Post a review: approve if safe, else request changes with specific line notes.

Usage: /review-pr 42

JavaScript
// scripts/auto-pr.mjs — open a PR after a feature branch is pushed (Stop hook)
import { execFileSync } from "node:child_process";   // execFileSync + arg arrays = no shell injection
const branch = execFileSync("git", ["branch", "--show-current"]).toString().trim();
if (branch === "main" || branch === "master") process.exit(0);
if (execFileSync("git", ["status", "--porcelain"]).toString()) process.exit(0);
try { execFileSync("gh", ["pr", "create", "--fill"], { stdio: "inherit" }); } catch { /* PR may already exist */ }

✅ Checkpoint: You can give Claude scoped, read-only GitHub access via MCP, run Claude in Actions without a stored key, and hand an issue to an agent knowing what it costs. 🛠 Exercise: Add examples/claude.yml to a sandbox repo, comment @claude explain the CI workflow on an issue, and check the run's minutes in the Actions usage view.


Environment variables

Real secrets (store them in the secrets vault / Vercel env / Actions secrets; placeholders only):

Bash
GITHUB_TOKEN=github_pat_...
GITHUB_WEBHOOK_SECRET=replace_with_random_32_byte_hex...
GITHUB_APP_PRIVATE_KEY=pem_contents_with_newlines_escaped_as_backslash_n...
ANTHROPIC_API_KEY=sk-ant-...

Non-secret settings (plain config or Actions variables, not secrets):

NameExampleUsed by
GITHUB_APP_ID / APP_CLIENT_ID123456 / Iv23li...Octokit App, create-github-app-token
GITHUB_APP_INSTALLATION_ID98765432getInstallationOctokit()
GITHUB_TOOLSETSdefault,actions,code_securitylocal MCP server
GITHUB_READ_ONLY / GITHUB_LOCKDOWN_MODE1local MCP server
GITHUB_HOSThttps://ghe.example.comMCP / gh against GHES or ghe.com
ANTHROPIC_FEDERATION_RULE_ID / ANTHROPIC_ORGANIZATION_IDfdrl_... / UUIDClaude Code Action WIF

gh reads GH_TOKEN (or GITHUB_TOKEN) from the environment; inside Actions pass GH_TOKEN: ${{ github.token }} via env:.

Command cheat-sheet

Bash
# Daily loop
git status / git add -A / git commit -m "…" / git push
git switch -c feature/x      # branch        git switch master
git pull --rebase            # update cleanly  git stash / git stash pop
# History
git log --oneline --graph --all
git revert <sha>             # safe undo of a pushed commit
git reflog                   # find lost commits
# GitHub via gh
gh pr create --fill / gh pr checks 42 --watch / gh pr merge 42 --squash --auto
gh issue create / gh run watch / gh run view --log-failed
gh release create vX --generate-notes
gh attestation verify dist.tar.gz -R OWNER/REPO
gh extension install github/gh-actions-lock && gh actions-lock
gh api repos/OWNER/REPO/... # raw REST/GraphQL

More: github/reference/gh-cli-cheatsheet.md.

Troubleshooting

IssueFix
gh: command not foundInstall via winget/brew/apt; gh --version should be 2.102+
401 on MCP HTTPToken expired or missing permission; regenerate the fine-grained PAT with the repos + permissions the toolsets need
claude mcp add-json → "Invalid input" (Windows)Use claude mcp add --transport http github <url> -H "Authorization: Bearer …"
Push rejected (non-fast-forward)git pull --rebase then push
Push blocked by push protectionA secret was detected: remove it, rotate it, recommit (bypass only for confirmed false positives)
Webhook signature never matchesVerify the raw body (no JSON re-serialise), use X-Hub-Signature-256, check the secret is set on the hook; a proxy may be rewriting the body
Webhook shows "timed out"Respond 2xx within 10 s; enqueue the work
Workflow didn't runCheck on: triggers + branch/path filters; workflows from forks need approval
Run fails after gh actions-lockAn allowlist entry is tag-pinned; switch it to a wildcard or full SHA
410 Gone from RESTYou pinned a retired API version; move to 2026-03-10
Unexpected Actions billAgents and Copilot code review consume minutes on private repos; add timeout-minutes, concurrency, and a budget
Accidentally committed a secretRotate it immediately; then history rewrite (git filter-repo) + force-push

codeAmani notes

  • master is the deploy trigger. A push to master fires the Vercel build, so master must always be green and reviewed. Enforce a ruleset (1 approval + required lint/typecheck/test checks) and merge via squash for a clean, revertable history. Vercel deploys through its GitHub integration; we don't deploy to Vercel from Actions.
  • Pin and lock. SHA-pin every third-party action (tag in a trailing comment) or onboard the repo to gh actions-lock; let Dependabot (github-actions ecosystem) bump them weekly.
  • Provenance per CLAUDE.md. Anything we ship as a downloadable artifact (npm package, CLI, MCP server, release tarball, image) targets SLSA Build L3. This KB and Vercel/Netlify apps are deploys, not artifacts: pin actions, document the build. actions/attest alone is L2; follow supply-chain/CLAUDE_CODE_INTEGRATION.md for the L3 builders.
  • Secrets never touch the repo. Keep them in .env.local (git-ignored) and the secrets vault; turn on secret scanning + push protection (free on public repos; Secret Protection on private ones) and run gitleaks/Infisical scan in CI as the backstop. If a secret lands, rotate first; scrubbing history is secondary.
  • Server-side only. PATs, App private keys and webhook secrets live in server env (route handlers, Actions secrets), never NEXT_PUBLIC_* and never in client bundles. Prefer a GitHub App over a PAT for any bot or server integration.
  • Webhooks: verify X-Hub-Signature-256 before parsing (same rule as Stripe signing-secret verification and Svix for Clerk), dedupe on X-GitHub-Delivery, reply within 10 s.
  • Payments context. GitHub itself is billed by card (USD). Product payments stay Stripe by default; M-Pesa/Daraja only for Kenya-targeted projects. Nothing in this guide changes that.
  • AI routing. Use the GitHub MCP (read-only + lockdown for public repos) for PR/issue/Actions work in-session; use the Claude Code Action (prefer WIF over a stored key) for CI review/auto-fix with our own CLAUDE.md. Claude on Agent HQ is fine for teammates already on Copilot. See anthropic for model/key setup.
  • Cost guardrails. Private-repo CI and every agent run burn Actions minutes: set timeout-minutes, concurrency with cancel-in-progress, short artifact retention-days, and an Actions budget. Arm Linux runners are the cheapest 2-core option.
  • African-market workflow (Kenya-targeted projects). CI runs on GitHub's hosted runners regardless of local bandwidth, so push small and let Actions do the heavy build/test. Pair with the vercel deploy and the chrome-devtools CI Lighthouse budget to guard 2G/3G performance on every PR. gh and the remote MCP server are light on bandwidth compared to the web UI.
  • Run it from WSL. Keep repos on the Linux filesystem for fast git, and let Git Credential Manager bridge your Windows auth.