Git Hour 3: Towards a Hosted Platform (Azure Repos vs. GitHub)

From "knowing how to use Git locally" to "collaborating securely on the platform": protocols, certification, branch protection, PR, CODEOWNERS, fork, debugging and migration
Git 2.56GCM 3.0.2Azure DevOps ServicesGitHub.comVerified according to official documents · 2026-11
overall learning objectives
  • Explain what is passed between Git and the hosting platform:Smart HTTP and SSH transfer、git-upload-pack / git-receive-pack, after the server receives the pushquarantine → pre-receive rule evaluation → update referenceProcess, and can choose GitHub / Azure Repos / GitLab / CodeCommit / Bitbucket accordingly.
  • Configure correct authentication for both platforms:SSH key(GitHub uses ed25519, Azure DevOps currentlyOnly supports RSA)、HTTPS + Git Credential Manager(GCM 3.x uses Entra OAuth tokens by default for Azure Repos),PAT(GitHub fine-grained PAT, Azure DevOps organization-wide PAT, and global PAT retirement).
  • in Azure ReposCreate/import the repository, configure the branch strategy (minimum reviewers, associated work items, comment resolution, build verification, merge type restrictions, automatically include reviewers) and useaz reposPR completed.
  • in GitHubChinese userulesetsProtect branches, understand its overlay relationship with traditional branch protection, merge queues, and useghComplete the entire PR process.
  • use CODEOWNERS(GitHub) withAutomatically include reviewers + path filtering(Azure Repos) Implement mandatory review by directory and configure required status checks.
  • Can distinguish the usage scenarios of fork, template repository, and Inner Source; can quickly locate 403 / Authentication failed / rule rejection / host key / large file / TLS proxy problem from the original error message.
  • use git clone --mirror + git push --mirrorBetween Azure Repos and GitHubWith full history and tagsMigration and be able to estimate costs for both platforms.

1-hour time allocation table

#timemodulecore contentanimation/interactionexperiment
0before classWarm-up and platform account preparationGitHub account, Azure DevOps organization and project,gh/azInstallation and reuse~/git-lab/myappAccount and tool self-checkgh auth status、az devops project list
100–05Hosting platform selection and Git service architectureComparison of five platforms; smart HTTP and SSH; protocol v2; server receive-pack and pre-receiveThe protocol messages of a clone/push are played back step by stepuse GIT_TRACE_PACKETObserve real messages
205–13Authentication: SSH, HTTPS, GCMed25519 and RSA, ssh-agent, multiple accounts~/.ssh/config;GCM Credential Assistant Protocol;PAT Scope and Expiration;Entracore animation: HTTPS + GCM authentication → push to protected branch → pre-receive rule rejectionConfiguring SSH and GCM for both platforms
313–22Azure ReposCreate/import repository; branch strategy family bucket; PR completion options; bypass permissions;az reposPR policy evaluator (which policy is blocking completion)Use CLI to build repository + strategy + PR
422–31GitHubRepository settings; rule sets vs branch protection; push rule sets; PR; merge queue;ghMulti-rule set stacking calculator (the strictest takes effect)Create rulesets and validate rejections with REST API
531–38CODEOWNERS, required reviews and status checksCODEOWNERS syntax and "last match takes effect"; Azure automatically includes reviewers; status check naming and path filtering trapsCODEOWNERS matcher (enter the path to see the person in charge)Two platforms implement the same set of directory managers
638–45fork, template repository and Inner Sourcefork network and synchronization; template repository (new history); Inner Source governanceclone / fork / template historical relationship demonstrationfork → synchronize upstream → cross-repository PR
745–54Practical troubleshooting on the platform side403/Authentication failed, rule denied, GCM cached bad credentials, host key, large file, TLS/proxyError report original text classifier +interactive troubleshooting treeDeliberately create 4 glitches and fix them
854–60Migration, costs and self-testingmirror migration, hidden references, LFS, verification; platform import tool; cost comparisonMigration Verification Simulation + Cost CalculatorAzure Repos → GitHub full migration
—After classcheat sheet · Comprehensive experimentBoth platforms have equal protection + PR merge + image migration + cleanupFinal exam (12 questions)Comprehensive experiment

Knowledge Coverage Matrix Knowledge Coverage Matrix

target skillM1M2M3M4M5M6M7M8key commandsexperiment
Smart HTTP/SSH transport explained with receive-pack✓✓····✓·GIT_TRACE_PACKET、GIT_CURL_VERBOSEM1 message observation
Platform selection✓····✓·✓—cost calculator
SSH keys and multiple accounts·✓····✓·ssh-keygen、ssh -T、ssh-addM2 Experiment
HTTPS + GCM, PAT life cycle·✓✓✓··✓·git credential、git credential-managerM2/M7 Experiment
Azure Repos branch strategies and PRs··✓·✓·✓·az repos policy、az repos prM3 Experiment
GitHub rulesets, merge queues, and PRs···✓✓·✓·gh api …/rulesets、gh pr、gh rulesetM4 Experiment
CODEOWNERS / Required Review / Status Check··✓✓✓✓··.github/CODEOWNERS、required-reviewerM5 Experiment
fork / template / Inner Source·····✓··gh repo fork、gh repo sync、--templateM6 Experiment
Platform side troubleshooting✓✓✓✓··✓✓GIT_TRACE=1、ssh -vTM7 troubleshooting drill
Migration with history and tags··✓✓···✓clone --mirror、push --mirror、for-each-refM8 / Comprehensive Experiment

What this lesson doesn’t cover (and where to learn it)

TopicWhy not in this lessonwhere to study
Protected branches/approval rules/push rules for AWS CodeCommit, GitLabThis lesson only deals with model selection and comparison.Lesson 4
GitHub Actions / Azure Pipelines Pipeline writing, OIDC, shallow cloning and change detectionThis lesson only treats the pipeline as the "source of status checks"Lesson 5; and subsequent stand-alone GitHub/Azure DevOps Platform lessons
Branch strategy (GitFlow/trunk-based), monorepo, partial cloning and sparse checkoutBelongs to the topic of architectureLesson 6
History rewritten to clear secrets (git filter-repo), reflog recoveryIn-depth debuggingLesson 7 (this lesson M7 only talks about platform side rejection and authentication)
GitHub Advanced Security / GHAS for Azure DevOps (confidential scanning, push protection, code scanning)Safe product beyond 1 hourGitHub Code Security Documentation、GHAzDO Documentation
Azure DevOps Server / GitHub Enterprise Server self-hosted operationsThis course is based on cloud servicesDocumentation for each product administrator

How to use this courseware

10 tabs per module
Principles · Diagrams · Animations · Commands · Experiments · Production Examples · Troubleshooting · Tests · Voice · Videos. Let’s first look at the “principles” and “animation”, and then do the “experiments” on the two platforms.
learning progress
A test score ≥ 70% or clicking "Mark this module completed" will be counted as progress and saved in this browser (cleared after refreshing when local storage is disabled).
Chinese voice
The "Voice" tab uses the browser's built-in Web Speech API (zh-CN) to read the explanation script; if there is no Chinese voice package, the explanation script can still be read or handed over to the TTS tool.
Version and platform instructionsBaseline for this lesson: Git 2.56 (2026-09), Git Credential Manager3.0.2(2026-10-26; Starting from 3.0 for .NET 10, Azure Repos returns Microsoft OAuth tokens instead of PAT by default, and Identity Broker is enabled by default on Windows), GitHub CLI 2.x, Azure CLI +azure-devopsExtension. The platform interface and package functions change frequently. This lesson will be verified against learn.microsoft.com and docs.github.com on 2026-11-15; the button names you see may be slightly different, please refer to the official documents.
Safety reminderThis lesson creates PAT, SSH keys, and a test repository. The final step of the comprehensive experiment includes a completeclean list(Delete the test repository, revoke PAT, delete the SSH public key on the platform, clear the local cache credentials), please be sure to execute it.

Module 0 · Warm-up and platform account preparation (completed before class)

Prepare a GitHub account and Azure DevOps organization, install gh/az, and reuse the ~/git-lab/myapp practice repository from the first two lessons
Before class ≈ 15 minutesThe free tiers of both platforms are sufficient
Prerequisites
  • CompletedLesson 1withLesson 2: This machine has a practice repository~/git-lab/myapp(By Lesson 1’sbootstrap-git-lab.shgenerate, includingmain、feature/*branches, tagsv0.1.0etc.).
  • Working machine: Ubuntu 24.04 (Azure VM or WSL) / macOS / Windows (Git for Windows + Git Bash).git --version≥ 2.46 (GCM 3's credential capability negotiation requires 2.46+, recommends 2.56).
  • One browser can log inGitHub personal account, one can log inAzure DevOpsMicrosoft account or Entra account.

Accounts, permissions and fees (read first before taking action)

PlatformThis lesson requiresIs the free tier enough?Note
GitHub.comPersonal account; optionally create a free organization<you>-gitlab-lab(Fork/template experiment of M6)enough. Please build the experimental repositorypublic:GitHub FreeprivateThe repository does not provide branch protection, rulesets, required reviewers, and CODEOWNERS enforcement (requires Pro/Team). Public repositories have these features available on Free.The merge queue is only inPublic repository owned by the organizationOr available in a private repository on GitHub Enterprise Cloud; pushing rule sets requires a private/internal repository on Team and above. This lesson only demonstrates these two items.
Azure DevOps Servicesan organizationhttps://dev.azure.com/<ORG>, a private projectgit-lab;You need to be a Project Administrator (the creator is the default)enough. Basic access level is free for the first 5 users and unlimited private Git repositories per organization.Approximately $6/user/month after more than 5 Basic users (2026-11 official website price). Stakeholder is free butCan't access Azure Repos。
real riskPlease do not put company code or any real secrets in the test repository. Lesson 1 Practice in the repositoryFAKE_SECRET=...Is a false value, but when pushing to a GitHub public repositoryMay trigger confidential scanning/push protection(Depending on whether the format looks like a real token). If intercepted, just learn how to handle it at M7; don't bypass protection just to push up.

Step 1: Confirm the practice repository (or quickly rebuild)

cd ~/git-lab/myapp && git status -sb && git branch -a && git tag && git log --oneline -5
## main
* main
  feature/healthz
  feature/redis-timeout
v0.1.0
v0.2.0
a3f9c21 (HEAD -> main, tag: v0.2.0) Add Redis timeout config
...

If the directory has been deleted, rerun Lesson 1, Module 0bootstrap-git-lab.sh. If you just want to catch up quickly with this lesson, you can also use the following minimal version (without "Dangerous History"):

mkdir -p ~/git-lab/myapp && cd ~/git-lab/myapp
git init -b main
mkdir -p app docs infra .github
printf 'from flask import Flask\napp = Flask(__name__)\n\n@app.get("/healthz")\ndef healthz():\n return "ok"\n' > app/main.py
printf 'flask==3.1.*\ngunicorn==23.*\nredis==5.*\n' > requirements.txt
printf '# myapp\nFlask + gunicorn + Redis example\n' > README.md
printf 'FROM python:3.13-slim\nWORKDIR /app\nCOPY . .\nRUN pip install -r requirements.txt\nCMD ["gunicorn","-b","0.0.0.0:8000","app.main:app"]\n' > Dockerfile
git add . && git commit -m "Initial myapp"
git tag -a v0.1.0 -m "first release"
git switch -c feature/healthz && echo "# health docs" > docs/health.md && git add . && git commit -m "Add health docs" && git switch main

Step 2: Install and log in to the GitHub CLI

# Ubuntu (official apt source, see cli.github.com) / macOS: brew install gh / Windows: winget install --id GitHub.cli
gh --version
gh auth login --hostname github.com --git-protocol https --web
gh auth status
github.com
  ✓ Logged in to github.com account octo-learner (keyring)
  - Active account: true
  - Git operations protocol: https
  - Token: gho_************************************
  - Token scopes: 'gist', 'read:org', 'repo', 'workflow'

gh auth loginThe OAuth device/browser process is followed, and the token is saved in the system keychain. In this lesson, M2 will clearly explain its relationship with GCM (just choose one of the two to be the Git Credential Assistant). Deleting a repository requires additionaldelete_repoRange, reuse when cleaninggh auth refresh -s delete_repoApply.

Step 3: Install the Azure CLI and azure-devops extension

# Ubuntu: curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
az version
az extension add --name azure-devops # If already installed, use az extension update --name azure-devops
az login # Browser login; Entra token is also used for az devops / az repos
export ADO_ORG=https://dev.azure.com/< your organization >
az devops project create --name git-lab --visibility private --org $ADO_ORG
az devops configure --defaults organization=$ADO_ORG project=git-lab
az devops project list -o table
ID                                    Name     State
------------------------------------  -------  ----------
5d1c9e0b-0c7e-4a36-9b7a-6a2f8b0d1e11  git-lab  wellFormed
Descriptionaz devopsThe command is inaz loginUse the Entra token directly afterwards, no PAT required. Only used in environments where Entra cannot be used (e.g. certain automation)az devops loginEnter PAT. By default, a new project will generate an empty repository with the same name as the projectgit-lab, this lesson will be created separatelymyapprepository.

Step 4: Set up the variables used in this lesson

cat >> ~/.gitlab-p3.env <<'EOF'
export GH_OWNER=octo-learner # Your GitHub username
export ADO_ORG_NAME=contoso-lab # Your Azure DevOps organization name
export ADO_ORG=https://dev.azure.com/$ADO_ORG_NAME
export ADO_PROJECT=git-lab
EOF
source ~/.gitlab-p3.env && echo "$GH_OWNER $ADO_ORG $ADO_PROJECT"

Warm-up: Answer from memory (30 seconds)

git pushWhat does local Git actually send to the remote end?

Two things: a set of "reference update commands" (Old SHA New SHA refs/heads/main) and a containing only objects missing from the remotepackfile. The remote end first receives the object and then decides whether to update the reference - the rule rejection occurs between these two steps, which is the main thread of this lesson.

Lesson 2git push --force-with-leaseWhat problem is solved? Who else will be stopped on the platform?

It checks locally that the remote reference is still the value you last saw to avoid overwriting other people's commits; but the rule set/branch policy on the platform (forcing forced push, direct push is prohibited) is executed on the server side,--force-with-leaseIt will also be rejected.

Environmental self-check list

Module 1 · Hosting platform selection and Git service architecture

00:00 – 05:00 · All platforms talk about the same Git protocol, and the difference lies in the "authentication, rule evaluation and collaboration functions" layer
5 minutesProtocol v2 is the default since Git 2.26★★★★
learning objectives
  • Can compare the differences in certification, branch protection, review, CI integration and cost between GitHub, Azure Repos, GitLab, AWS CodeCommit, and Bitbucket Cloud, and give reasons for selection.
  • Explain clearly the two endpoints of smart HTTP (/info/refs?service=… with POST /git-upload-pack|git-receive-pack) and SSH transfer (ssh git@host git-receive-pack 'path') difference.
  • Describe the order in which the server handles push: receive packfile toquarantine → pre-receive(Platform rules engine evaluates here) → Quote by quoteupdate→ Atomic update of references →post-receive(trigger webhook/CI).
Prerequisite knowledge:Object model for Lesson 1 (blob/tree/commit, references).Importance:★★★★ (After understanding this level, you can understand all the "rejections" that follow)

What: What does the hosting platform add to Git?

Git itself is distributed, and the "remote" is just another repository. Hosting platforms do four things that Git does not:Identity authentication(Who is pushing),Authorize(Whether you have write permission),strategic assessment(Whether this reference update complies with the branch protection/rule set),collaboration layer(Pull Request, Review, Issue/Work Item, Webhook, CI). The first three things all happen on the server-side processing path of push, and the fourth thing is around references (refs/pull/*etc.).

Why: Why should we first understand the service architecture?

The platform error reports seem to be varied (403、Authentication failed、GH013、TF402455、remote rejected), but they respectively correspond to different levels on the same pipeline: transport layer (TLS/proxy/SSH host key) → authentication → authorization → rule evaluation → storage limit. Once you know which level you are stuck at, all you have to do to troubleshoot is checking the configuration of that level.

How: Two transmission protocols

smart HTTP(S)SSH
URL examplehttps://github.com/OWNER/REPO.git
https://dev.azure.com/ORG/PROJ/_git/REPO
git@github.com:OWNER/REPO.git
git@ssh.dev.azure.com:v3/ORG/PROJ/REPO
discovery phaseGET /info/refs?service=git-upload-pack(fetch) or…service=git-receive-pack(push); the server returns the reference list (ref advertisement) and capabilitiesClient executionssh git@host "git-upload-pack 'OWNER/REPO.git'", the server program directly outputs the reference list in the SSH channel
data stagePOST /git-upload-pack(want/have to download the pack after negotiation)
POST /git-receive-pack(upload command + pack)
Continue bidirectional exchange within the same SSH session
CertificationHTTP 401 + WWW-Authenticate→ Git callCredential AssistantGet username/token →AuthorizationHead to retrySSH public key authentication (the server finds the user by public key), no credential assistant required
Firewall/Proxy443, naturally passes through the enterprise agent (http.proxy)22 Often blocked; provided by GitHubssh.github.com:443, Azure DevOps only has 22
suitable forEnterprise network, Windows + GCM, SSO/Conditional Access requiredLinux/macOS developers, long-term keys, multiple accounts

Protocol version:Git 2.26 onwardsprotocol.version=2By default, the client sends it first when fetch/clonels-refsOnly the required reference prefixes are requested, and the reference list of a large repository is no longer issued in full at once.push still uses the v0/v1 process of receive-pack(The server lists all references at once).

How: After the server receives the push

  1. Authentication and Authorization:HTTPS ViewAuthorizationToken/OAuth in the header; SSH looks at the public key. When there is no write permission, GitHub returns403(Permission to OWNER/REPO.git denied to USER)。
  2. Receive object:git-receive-packRead command list (<old-oid> <new-oid> <ref>) and packfile, put the object intoQuarantine (quarantine, Git 2.11+, environment variablesGIT_QUARANTINE_PATH), the object is not visible to other readers at this time.
  3. pre-receive: Get all reference updates (read from standard input) at once, and any non-zero exit willoverall rejection, the quarantine is discarded. The platform's rule sets, branching policies, file sizes, and confidential push protection are all evaluated in this step (or equivalent internal services).
  4. update: Called once for each reference, only one reference can be rejected (another reference may still succeed unless the client uses--atomic)。
  5. Migrate objects + update references: After passing, the object is moved from the quarantine area to the formal object library, and the reference is updated atomically.
  6. post-receive: Can no longer be rejected, used to trigger webhook, CI, PR updates, notifications.
  7. report-status: Server-side reply by referenceok refs/heads/xorng refs/heads/main <reason>;The client prints accordingly! [remote rejected] main -> main (reason). The description text output by the server through the sideband channel is displayed in your terminal asremote:Beginning.
Key pointsHosting platform is averageDo not allow users to install custom pre-receive hooks: GitHub.com and Azure DevOps Services use built-in rule sets/policies instead; only self-hosted products such as GitHub Enterprise Server, GitLab self-hosting (server hooks), and Bitbucket Data Center allow administrators to hang custom server hooks.

When: Platform selection comparison (2026-11)

GitHubAzure ReposGitLabAWS CodeCommitBitbucket Cloud
PositioningThe largest open source and enterprise code platform, ecosystem (Actions, Marketplace, Copilot)Part of the Azure DevOps suite, tightly coupled with Boards / Pipelines / Test PlansSingle application covering SCM + CI/CD + security, SaaS and self-hostedManaged Git within AWS, native IAM integrationAtlassian Ecosystem (Jira/Confluence)
Git certificationSSH (ed25519/ECDSA/RSA), HTTPS + OAuth/GCM, fine-grained PAT, GitHub AppHTTPS + Entra (GCM 3 default OAuth), organization-wide PAT, SSH (RSA only)SSH, HTTPS + PAT/OAuth, deployment tokenHTTPS (git-remote-codecommit / IAM credentials), SSH public key binding IAM userSSH, HTTPS + API token / App password (the latter is being phased out, subject to the official version)
branch protectionRule Set + Traditional Branch ProtectionBranch policy + branch security permissionsProtected branches + push rules + approval rulesIAM policy conditions + approval rule templatesBranch limits + merge checks
Responsible person by pathCODEOWNERS FileAutomatically include reviewers + path filtering (no CODEOWNERS file)CODEOWNERS(Supports sectioning)Approval rules (by branch, not by path)Subject to official documents
Free Tier HighlightsNo limit to repositorys; the protection function of private repositorys requires Pro/TeamFree for first 5 Basic usersThe Free layer private namespace has a limit on the number of users (subject to the official version)We will stop accepting new customers starting from 2024-07.2025-11 Resumption of GA;Based on active users (see Lesson 4 for details)Small team free tier (subject to official version)
Typical reasons for selectionOpen source, developer experience, Actions ecosystem, GHASUsed Azure Boards/Pipelines, Entra Unified Identity, Government/Compliance RegionWant integration and self-hostingCode must remain within the AWS accountHeavy Jira users
Common misunderstandings① "SSH is more secure than HTTPS" - both are encrypted; HTTPS + short-term OAuth token + conditional access are often more controllable in the enterprise, and the SSH private key is valid for a long time and will have a greater impact if leaked. ② "403It’s just that the password is wrong”——403usually meansAuthentication successful but no permissions(or the token range is not enough), the password error is usually401 → Authentication failed. ③ "Rejection of the rule means that the object was not uploaded" - the object has been transferred to the quarantine area and was just discarded; therefore, the rejection of a large push will also consume bandwidth and time, so check it locally first.

Architecture diagram: components passed by an HTTPS push

Developer work machine git push origin main git-remote-https (libcurl) credential.helper=manager GIT_TRACE_CURL Observable TLS 443 Frontend/Load Balancing TLS terminationCurrent limiting (429)Corporate agents are on the left Authentication/Authorization OAuth / PAT / Entra401 → Credential Assistant403 → No write permissionSSO/Conditional Access Git storage service (receive-pack) ① Read command old new ref② pack → quarantine③ Rules/policy engine (pre-receive)④ Update reference ⑤ report-status rejectng refs/heads/mainQuarantine discardremote: GH013 / TF402455 PassObject storage + reference updatepost-receivewebhook/CI/PR refresh The level corresponding to the error report SSL certificate problem / Proxy CONNECT → Transport layer | Authentication failed / 401 → Authentication 403 Permission denied → Authorization | GH013 / GH006 / TF402455 → Rule evaluation GH001 Large files / pack limit → Storage limit
Figure 1-1 The platform adds authentication, authorization and rule evaluation to the Git protocol; different error reports correspond to different levels

Sequence diagram: message sequence of smart HTTP push

git clientCredential Assistant (GCM)Platform GET /info/refs?service=git-receive-pack (no authentication) 401 Unauthorized + WWW-Authenticate: Basic git credential fill(protocol/host) username + password(=OAuth token) GET /info/refs + Authorization header 200: Reference list + capabilities (report-status, side-band-64k, atomic…) git credential approve (save) POST /git-receive-pack:old new refs/heads/main + PACK unpack ok + ng refs/heads/main …(or ok) Note: Credentials are approved after "reference list returns successfully"; subsequent rule rejections have nothing to do with credentials
Figure 1-2 smart HTTP push timing: authentication and rule evaluation are two independent stages

Protocol replay: what happens on the wire during a clone / push

Select the transfer method and operation, then play it step by step. Each step shows the participating components and what you useGIT_TRACE_PACKET=1 GIT_TRACE_CURL=1Real messages that can be seen on the terminal (simplified).

Select a combination and click play.
$ git clone https://github.com/octo-learner/myapp.git

Observe protocols and remote commands

commandfunctionKey parameters/description
git ls-remote <url>Only do the "discovery" phase and list remote references--heads、--tags、--refs; The fastest way to verify authentication and network
GIT_TRACE_PACKET=1Print pkt-line messagecan seels-refs、want/have、report-status
GIT_TRACE_CURL=1 / GIT_CURL_VERBOSE=1Print HTTP request/response headersGit will automatically hideAuthorizationheader value (unless setGIT_TRACE_REDACT=0,don't do this)
GIT_SSH_COMMAND="ssh -v"Print SSH handshake and keys used-vvvMore details
git remote -v / git remote set-urlView/modify remote URLHTTPS ↔ SSH switch
git push --atomicMultiple references are either updated all or none at allRequires server supportatomic Ability
git config protocol.versionView/set protocol versionThe default is 2 (2.26+); you can temporarily set it to 0 when troubleshooting old servers.
cd ~/git-lab
GIT_TRACE_PACKET=1 git ls-remote https://github.com/git/git.git 2>&1 | head -20
packet:          git> command=ls-refs
packet:          git> agent=git/2.56.0
packet:          git> 0001
packet:          git> peel
packet:          git> symrefs
packet:          git> unborn
packet:          git> ref-prefix HEAD
packet:          git> ref-prefix refs/heads/
packet:          git> ref-prefix refs/tags/
packet:          git> 0000
packet:          git< 5d9a… HEAD symref-target:refs/heads/master
...

How to verify:seecommand=ls-refsNote that protocol v2 is used.Common mistakes:put GIT_TRACE_CURLPaste the output into a work order or chat - although the authentication header is coded, cookies and internal host names may still be leaked, check before pasting.Production use:Determine whether the problem is in the "discovery phase" (authentication/network) or the "data phase" (rules/size).

# Report-status when pushing (push a temporary branch and delete it after completion)
cd ~/git-lab/myapp
GIT_TRACE_PACKET=1 git push origin HEAD:refs/heads/trace-test 2>&1 | grep -E "receive-pack|report-status|unpack|ok refs|ng refs"
git push origin --delete trace-test
packet:          push< 0000… capabilities^{}\0report-status report-status-v2 delete-refs side-band-64k quiet atomic ofs-delta push-options object-format=sha1 agent=github/…
packet:          push> 0000000000000000000000000000000000000000 a3f9c21… refs/heads/trace-test\0 report-status-v2 side-band-64k quiet object-format=sha1 agent=git/2.56.0
packet:     sideband< unpack ok
packet:     sideband< ok refs/heads/trace-test

Commands executed by the server during SSH transfer

GIT_SSH_COMMAND="ssh -v" git ls-remote git@github.com:git/git.git 2>&1 | grep -E "Authenticated|Sending command|Offering public key"
debug1: Offering public key: /home/me/.ssh/id_ed25519 ED25519 SHA256:3q…
debug1: Authenticated to github.com ([140.82.112.3]:22) using "publickey".
debug1: Sending command: git-upload-pack 'git/git.git'

Lab 1: See the Discovery and Data Phases firsthand (~4 minutes)

Observe clone negotiations using a public repository(no authentication required):
cd /tmp && rm -rf hello
GIT_TRACE_PACKET=1 git clone --depth 1 https://github.com/octocat/Hello-World.git hello 2>&1 | grep -E "command=|want |done|shallow" | head
packet:        clone> command=ls-refs
packet:        clone> command=fetch
packet:        clone> want 7fd1a60b01f91b314f59955a4e4d4e80d8edf11d
packet:        clone> deepen 1
packet:        clone> done
packet:        clone< shallow-info
Observe the unauthenticated push discovery phase(For any repository you don't have write access to):
GIT_TRACE_CURL=1 git -C hello push https://github.com/octocat/Hello-World.git HEAD:refs/heads/x 2>&1 | grep -E "^.*(GET|POST|HTTP/2|www-authenticate)" | head
=> Send header: GET /octocat/Hello-World.git/info/refs?service=git-receive-pack HTTP/2
<= Recv header: HTTP/2 401
<= Recv header: www-authenticate: Basic realm="GitHub"

Next Git calls the credential helper. If the login window pops up, just cancel it (you will seeAuthentication failedor403). This is the first step in M2 Core Animation.

Compare SSH(If GitHub SSH key is configured, otherwise come back after M2):
GIT_SSH_COMMAND="ssh -v" git ls-remote git@github.com:octocat/Hello-World.git 2>&1 | grep -E "Sending command|Authenticated"
clean up:
rm -rf /tmp/hello

Case 1: Choosing to migrate from Bitbucket Server to GitHub or Azure Repos

Question:A company that already uses Entra ID, Azure Subscriptions, and Azure Boards wants to replace self-hosted Bitbucket Server.Method:Score by "Identity → Planning Tools → CI → Compliance": Code and work items require two-way tracking, auditing requires conditional access → Azure Repos; there are also open source components and teams that require Copilot/GHAS → GitHub Enterprise Cloud and through Entra SSO/EMU. In the end, both coexist: internal business systems are in Azure Repos, open source and platform tools are in GitHub, and M8's mirroring method is used to synchronize a small number of shared repositorys.Limitations:The branch protection rules of the two platforms need to be maintained separately (the corresponding relationships are given in M3/M4/M5 in this lesson).

Case 2: Enterprise proxy causes all SSH failures

Question:The office network has blocked port 22, and the new employee’s clone is stuck untilConnection timed out。Method:GitHub users change toHost github.com → HostName ssh.github.com, Port 443;Azure Repos does not have a 443 SSH endpoint, and has been changed to HTTPS + GCM (which also meets conditional access).Configuration:See M2's~/.ssh/config。Limitations:Some proxies will perform TLS inspection and need to add the enterprise root certificate to Git's CA (M7).

Case 3: Fetch of large single repository becomes slow

Question:The repository has 200,000 tags and CI-generated citations,git fetchJust referencing the list takes several seconds.Method:Confirm client protocol v2 (ls-refsFilter by prefix), clean up useless branches/tags on the platform, CI usage--no-tagswith exact refspec.Limitations:Push is still a v0-style full reference declaration, and the number of references itself still needs to be managed (the repository architecture will be discussed in Lesson 6).

Common errors and solutions

fatal: unable to access 'https://…': Failed to connect to github.com port 443 after 21000 ms: Couldn't connect to server

Reason:Transport layer issues, not yet certified: DNS, firewall, proxy required.

curl -sSI https://github.com | head -1
git config --show-origin --get-regexp '^https?\.'
env | grep -i _proxy

Fix:Configure proxygit config --global http.proxy http://proxy.corp:8080(or only for a certain hosthttp.https://dev.azure.com.proxy), see M7 for details.

fatal: protocol error: bad line length character: Welc

Reason:Remote shell or~/.bashrcThe welcome text (on a self-hosted server) is output, polluting the Git protocol flow; it is also possible that the URL points to a normal SSH host instead of the Git service.

Fix:Confirm that the URL points togit@github.com / git@ssh.dev.azure.com;Have non-interactive shells print nothing on self-hosted servers.

error: RPC failed; HTTP 413 curl 22 The requested URL returned error: 413

Reason:The request body exceeds the size allowed by the reverse proxy or platform (for self-hosted nginxclient_max_body_sizeThe most common); usually manifested as push size limits on cloud platforms (GitHub single push 2 GiB, Azure Repos 5 GB).

Fix:Push in batches (by commit rangegit push origin <sha>:refs/heads/main), use Git LFS for large files;Don'tBlindly turn it uphttp.postBuffer- It only affects buffering when chunked transfers are not used, and is rarely the root cause.

! [remote rejected] main -> main (pre-receive hook declined)

Reason:Server-side pre-receive rejection (custom hook for self-hosted GitLab/GHES, or a generic representation of the platform's built-in rules). The specific reasons are aboveremote:In the line.

Fix:Read firstremote:OK; the GitHub rule set isGH013, the traditional branch protection isGH006, Azure Repos isTF402455etc. (M7 detailed explanation).

Command line operation questions
1. Without cloning, just use one command to verify that you can read the remote repository and list all tags.
git ls-remote --tags https://github.com/OWNER/REPO.git
2. Print the HTTP request header of fetch to confirm which URL the request went to and what status code was returned.
GIT_TRACE_CURL=1 git fetch origin 2>&1 | grep -E "Send header: (GET|POST)|Recv header: HTTP"
Scenario analysis questions
Same developer:git fetchnormal,git pushReturn403. What does it mean? How to check in order?

A successful fetch indicates that the transport layer and authentication are normal (the credentials are valid and at least have read permission). Push 403 occurs at the authorization level: ① The account only has read permissions on the repository (Azure Repos's Contribute permission / GitHub's Write role); ② The token scope is not enough (GitHub fine-grained PAT only has Contents: Read; Azure PAT only has Code (Read)); ③ The organization has enabled SAML SSO, and the token does not authorize the organization; ④GCM What is cached is the credentials of another account (M7). useGIT_TRACE_CURL=1To see which user it is, usegh auth statusOr check the scope on the platform's "Personal access tokens" page.

Verified instructional videos

▶
How Git Works: Explained in 4 Minutes — ByteByteGo
English · Use animation to talk about local repository, remote end and object transmission, suitable as an introduction to this module
▶
Tech Talk: Linus Torvalds on git — Google
English · 2007 · Git author talks about distributed design concepts: why "the remote end is just another repository"

Official documentation

Video storyboard (approximately 90 seconds)

This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–15s
Screen: Laptop on the left, five platform icons on the right, and a pipe with "Git protocol" written in the middle.
Narrator: No matter which hosting platform you use, the same Git protocol runs on the line.
Shot 2 · 15–40s
Picture: There are four cards in the HTTPS channel: GET info/refs, 401, retry with token, and 200 reference list; there are only "public key authentication" and "git-upload-pack" in the SSH channel.
Narrator: HTTPS is rejected once, and then the token is provided by the credential assistant; SSH uses the public key to complete authentication during the handshake.
Shot 3 · 40–70s
Screen: packfile enters a dotted box "quarantine", a gate with "Rule Engine" written on it falls, and a red light appears; the quarantine area is cleared.
Narrator: The push object enters the quarantine area first, and the reference will be updated only if the rule engine passes the evaluation; otherwise, it will be discarded entirely.
Shot 4 · 70–90s
Screen: Five levels are arranged in order: transmission, authentication, authorization, rules, and storage. Typical error reports are hung below each level.
Narrator: Remember these five levels. When you see any error, first determine which level it is stuck at.
or score ≥ 70% on the Quiz

Module 2 · Authentication: SSH, HTTPS, Git Credential Manager

05:00 – 13:00 · Choose the right credential type, store it securely in the right place, and know when it expires
8 minutesGCM 3.0.2 · Fine-grained PAT GA (2025-03)Azure DevOps global PAT is being retired★★★★★
learning objectives
  • Generate ed25519 keys for GitHub, RSA (3072-bit) keys for Azure DevOps, use ssh-agent, and use~/.ssh/configHost alias management for multiple accounts/multiple organizations.
  • Explaining the Git Credential Assistant protocol (git credential fill / approve / reject), will install, configure, and diagnose GCM until GCM 3 returns Entra OAuth tokens to Azure Repos by default.
  • Create PAT with least privileges: GitHub fine-grained PAT (single resource owner, specified repository, Contents read and write) and Azure DevOps organization-wide PAT (Code Read & write), aware of expiration, automatic revocation, and global PAT retirement.
  • Can understand Core Animation: After HTTPS + GCM authentication is successful, push to the protected branch is rejected by the rules in the pre-receive stage - andCredentials should not be cleared at this time。
Prerequisite knowledge:Smart HTTP timing for module 1.Importance:★★★★★ (Authentication issues are the number one platform ticket)

What: Four types of credentials

CredentialstransmissionIssued/saved bylifespanTypical uses
SSH key pairSSHYou generate it locally; the public key is uploaded to the personal settings of the platformDoes not expire by default (Azure DevOps organizations can force SSH key expiration, and the "Verify SSH key expiration" policy is enabled by default)Developer's daily life, Linux/macOS
OAuth/Entra tokenHTTPSIssued by platform/Entra after browser login, GCM orghSave to system keychainShort term + refresh tokenDeveloper daily (recommended), subject to conditional access and SSO
PAT (Personal Access Token)HTTPS (as password)/REST APIYou create it manually in the platform personal settingsExpiration date of your choice; can be restricted by administrator policyTools and temporary scripts that do not support OAuth
Application identity(GitHub App, Entra Service Principal/Managed Identity, Deployment Key)HTTPS / SSHPlatform or EntraShort-lived installation token/federated credentialsAutomation and CI (Lesson 5)

Why: Why not use a password?

GitHub will no longer accept account passwords for Git operations starting from 2021-08-13 (error reportingremote: Support for password authentication was removed on August 13, 2021.). Azure DevOps uses Entra identity, supports MFA and conditional access, and passwords cannot be used with Git. The benefit of tokens isCan be limited in scope, set to expire, and can be revoked individually, the impact after the leak can be controlled.

How(1): SSH Key

  • GitHub: Recommendedssh-keygen -t ed25519;Also supports ECDSA, RSA, and hardware security keys (ed25519-sk/ecdsa-sk). The same public key can also be registered as a "signing key" for SSH commit signing (Lesson 7).
  • Azure DevOps: The official document (2026-11) clearly states "Azure DevOps supports RSA keys", which is used for authentication.rsa-sha2-256/512Signature algorithm;ed25519 not supported. oldssh-rsa(SHA-1) signatures are deprecated, seessh-rsa is about to be deprecatedshould be deleted~/.ssh/configinsideHostkeyAlgorithms +ssh-rsaDowngrade configuration. Azure DevOps only accepts client-providedfirst oneKeys will not be tried one by one, so multiple keys must be usedIdentitiesOnly yes。
  • ssh-agentCache the decrypted private key to avoid repeatedly entering the password; Windows 10 1809+ comes with the OpenSSH agent service, and Git Bash also comes with it.
  • Host key verification: The first connection will prompt the server fingerprint, which must be consistent with the official one. GitHub Ed25519:SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU;Azure DevOps(RSA):SHA256:ohD8VZEXGWo6Ez8GSEJQ9WpafgLFsOfLOtGGQCQo6Og(Also shown on the Azure DevOps SSH public keys page).
  • SSH keys for Azure DevOps require youComplete a full web login regularly(The official writes "Usually once every 30 days, depending on Entra configuration"), otherwise the key will suddenly "expire". Azure DevOps does not support Git LFS over SSH.

How(2): HTTPS and Credential Assistant Protocol

Git does not store passwords itself. encounter401when it pressescredential.helperConfigure call helper, exchange stdin/stdoutkey=valueLine:

actionwhen to callinput → output
get(git credential fill)When credentials are requiredprotocol=https、host=github.com(EnableuseHttpPathSometimes there arepath)→ username=…、password=…(Can be attachedpassword_expiry_utc)
store(approve)After the credentials are accepted by the serverThe helper writes it to storage
erase(reject)Server returns401(Invalid credentials)The assistant deletes this credential and will prompt again next time.

GCM(Git Credential Manager)It is a cross-platform credential assistant: GitHub uses OAuth (browser or device code), Azure Repos uses Microsoft Identity Platform (Entra / MSA), and also supports Bitbucket and GitLab.GCM 3.0(2026-09)Changes: For .NET 10, the Windows version no longer relies on the .NET Framework;Azure Repos returns Microsoft OAuth token instead of PAT by default(requires old behavior settingcredential.azreposCredentialType=pat); on supported systemsIdentity broker enabled by default(WAM on Windows,credential.msauthUseBroker=falsecan be turned off); Azure Repos login uses GCM's own Entra application instead; the embedded login web view is removed; the credential capability negotiation of Git 2.46 is supported. The latest patch is3.0.2(2026-10-26)。

Where do the credentials live:Windows Credential Manager (entry name looks likegit:https://github.com), macOS keychain; Linux does not have a unified default and must be setcredential.credentialStore:secretservice(Desktop GNOME Keyring/KWallet),gpg(Cooperate withpass, suitable for servers without desktops),cache(memory, default 900 seconds),plaintext(not recommended).

How(3): Scope and expiration of PAT

GitHub fine-grained PAT (recommended)GitHub Classic PATAzure DevOps PAT
Scopesingle resource owner(a user or an organization); you can select only some repositorysyou can accessallrepositorysingle organization(Organization level); Global PAT is being retired
Permission granularitySegmented by resource: Contents, Pull requests, Administration... (Metadata read-only is required)Coarse-grained scope:repo、workflow、admin:org…By service: Code (Read / Read & write / Full), Build, Work Items…
ExpiredOptional 1–366 days or no expiration (organization/enterprise can set maximum life policy)Default or custom dateThe date you set (the maximum lifespan for the UI is 1 year, the administrator can set a shorter maximum lifespan)
governanceOrganizations may requireApprovalto access organization resources; GitHub deletes PATs that have not been used for one yearOrganizations can ban classic PATTenant administrators can limit global/wide PAT, set maximum lifespan,Automatically revoke PATs leaked to public GitHub repositories;Organization owners can restrict the creation of
Known limitationsYou cannot contribute to public repositories that you are not a member of, external collaborator scenarios, one token to access multiple organizations, Packages, Checks API, etc.—In organizations supported by Entra, PAT must be used within 90 days or become inactive; format is 84 characters, including fixedAZDOSignatures facilitate confidential scanning
Azure DevOps current recommendations (verified 2026-11)The official PAT document states at the beginning: Avoid PAT when more secure methods can be used; application and automation useMicrosoft Entra token, managed identity, or service principal; Developer Git useGCM(3.x defaults to OAuth); only used when the tool does not support EntraOrganizational level, minimum scope, shortest lifeof PAT.Global PAT is being retired: The sprint 270 release notes (2026-03) say 2026-12-01 and all stopped working. The top of the 2026-11 version of the PAT document says 2027-01-27 (the best practices section on the same page still says 2026-12-01) - no matter which day it is,Migrate now。

When:How to choose

  • Windows / Corporate Network / Conditional Access Required:HTTPS + GCM(Azure Repos preferred, Microsoft documentation's SSH page also says "Use GCM instead of SSH on Windows").
  • Linux/macOS developers, multiple accounts:SSH(GitHub ed25519;Azure DevOps RSA 3072+)。
  • The script temporarily calls the REST API: short-term fine-grained PAT / organization-level PAT, saves the keystore, and revokes it after use.
  • CI/CD: Instead of using personal credentials, use GitHub App / OIDC / Managed Identity (Lesson 5).
Common misunderstandings① "The push was rejected, delete your credentials and try logging in again" - ifremote:OKGH013/TF402455This type of rule rejects, and the credentials are completely fine. Deleting them will only result in one more login. ② "It is convenient to write PAT into the URL"——https://user:TOKEN@…Will enter clearly.git/config, shell history and CI logs. ③ "Azure DevOps can also be used ed25519" - As of 2026-11, the official documentation only supports RSA. ④ "gh auth loginBoth GCM and GCM must be installed" - just choose one of the two to be GitHub's credential assistant (gh auth setup-gitwillghSet as the assistant of github.com), when configuring both at the same time, usegit config --show-origin --get-all credential.helperThe order in will prevail.

Component diagram: Where do credentials come from and where are they stored?

gitgit-remote-httpscredential.helper= manager stdin/stdout GCM 3.0.2Select provider by hostGitHub / Azure Repos /Bitbucket / GitLab / Generic Credential storageWindows Credential ManagermacOS keychainLinux: secretservice / gpg / cache OAuth github.comBrowser/device code authorization→ gho_ OAuth token MSAL Microsoft Entra IDbroker (WAM) / browserMFA · Conditional Access→ Azure DevOps access token Platform verificationIs the token valid? (401)Do you have write permission? (403)SSO authorized?PAT scope/policyIP allow listThen it comes to rule evaluation SSH route (without assistant)~/.ssh/configssh-agent holds the private keyThe platform finds the user by public key
Figure 2-1 HTTPS route: git → GCM → Identity Provider → Storage; SSH route does not go through Credential Assistant

Decision chart: Which credentials to use

Who is using this credential? People (Developers)interactive Program (CI/Script)non-interactive Enterprise Network / Windows / Azure→ HTTPS + GCM(OAuth) Linux/macOS, multiple accounts→ SSH(GH ed25519 / ADO RSA) GitHub App / OIDC / Managed Identity Not supported by tool → Minimum range short-term PAT neverToken written into URL/codeShare personal PAT to CI
Figure 2-2 Credential selection: OAuth or SSH for humans, Application Identity for programs, PAT as a last resort

Core Animation: HTTPS + GCM authentication → push to protected branch → rule denial

Play step by step after selecting a scene. The highlighted box is the currently working component; the terminal below is the real message, assistant protocol or command output corresponding to this step (the token has been coded). Compare the four scenarios and gain key insights:Authentication failure (401) will triggererase;Authorization failure (403) and rule rejection both occur after successful authentication and the credentials have beenapproveSave.

git pushgit-remote-https GCMcredential helper Credential storageKeychain/Credential Manager identity providerGitHub OAuth / Entra Platform authentication/authorization401 / 403 / 200 receive-packquarantine → rule report-status → client outputremote: … / ! [remote rejected]
After selecting the scene, click Play.
$ git push origin main

Authentication related commands

commandfunctionKey parameters/description
ssh-keygen -t ed25519 -C "mailbox" -f ~/.ssh/id_ed25519_ghGenerate a key for GitHubSet password;-fSpecify filename to facilitate multiple keys
ssh-keygen -t rsa -b 3072 -f ~/.ssh/id_rsa_azdoGenerate RSA keys for Azure DevOpsAzure DevOps only supports RSA
ssh-add / ssh-add -lAdd private key to agent / list loaded keysmacOS:--apple-use-keychain
ssh -T git@github.com / ssh -T git@ssh.dev.azure.comTest SSH authentication-vSee which key is provided
gh ssh-key add/list/deleteManage SSH public keys on GitHub with the CLI--type signingRegister signing key
git credential-manager configure / diagnoseWrite GCM to global Git configuration/generate diagnostic reportStarting from 3.0diagnose --strictFails even with warnings
git credential-manager github list|login|logoutManage GitHub accounts saved by GCMUsed when using multiple accountsloginPre-login
git credential-manager azure-repos list|bind|unbind|clear-cacheAzure Repos account binding and token cachingBind an organization to a specified Entra account
git credential fill|approve|rejectDirectly call the assistant protocol (debugging artifact)rejectDelete cached bad credentials
gh auth login|status|setup-git|token|refreshGitHub CLI certificationrefresh -s delete_repoadditional range

GitHub:ed25519 + agent

ssh-keygen -t ed25519 -C "you@example.com" -f ~/.ssh/id_ed25519_gh
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519_gh
gh ssh-key add ~/.ssh/id_ed25519_gh.pub --title "git-lab $(hostname)"
ssh -T git@github.com
The authenticity of host 'github.com (140.82.112.3)' can't be established.
ED25519 key fingerprint is SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Hi octo-learner! You've successfully authenticated, but GitHub does not provide shell access.

How to verify:The fingerprint must be consistent with the docs.github.com "GitHub's SSH key fingerprints" page (you can also pre-write the official known_hosts line~/.ssh/known_hosts)。Common mistakes:Key file permissions are too wide (chmod 600 ~/.ssh/id_*、chmod 700 ~/.ssh)。

Azure DevOps:RSA

ssh-keygen -t rsa -b 3072 -C "you@example.com" -f ~/.ssh/id_rsa_azdo
cat ~/.ssh/id_rsa_azdo.pub # Copy to User settings → SSH public keys → + New Key
ssh -T git@ssh.dev.azure.com
RSA key fingerprint is SHA256:ohD8VZEXGWo6Ez8GSEJQ9WpafgLFsOfLOtGGQCQo6Og.
Warning: Permanently added 'ssh.dev.azure.com' (RSA) to the list of known hosts.
remote: Shell access is not supported.
shell request failed on channel 0

The successful output of Azure DevOps isShell access is not supported(Certification passed). None at the momentazThe command to upload the SSH public key needs to be completed on the web page.

Multiple accounts/multiple organizations:~/.ssh/config

# Personal GitHub
Hostgithub.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519_gh
  IdentitiesOnly yes
  AddKeysToAgent yes

# Company GitHub account: remote is written as git@github-work:corp/repo.git
Host github-work
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519_work
  IdentitiesOnly yes

# When port 22 is blocked: GitHub provides SSH on port 443
Host github-443
  HostName ssh.github.com
  Port 443
  User git
  IdentityFile ~/.ssh/id_ed25519_gh
  IdentitiesOnly yes

# Azure DevOps: Only first key accepted, must be IdentitiesOnly
Host ssh.dev.azure.com
  User git
  IdentityFile ~/.ssh/id_rsa_azdo
  IdentitiesOnly yes

# Second Azure DevOps organization with another identity: git@devops_contoso:v3/Contoso/Proj/repo
Host devops_contoso
  HostName ssh.dev.azure.com
  User git
  IdentityFile ~/.ssh/id_rsa_contoso
  IdentitiesOnly yes
chmod 600 ~/.ssh/config
ssh -T git@github-work # The company account name should be displayed
git remote set-url origin git@github-work:corp/repo.git

HTTPS + GCM

# Windows: Git for Windows has built-in GCM; macOS: brew install --cask git-credential-manager
# Linux: Download the .deb or tarball of 3.0.2 from github.com/git-ecosystem/git-credential-manager/releases
git-credential-manager --version
git credential-manager configure
git config --global credential.credentialStore secretservice #Linux desktop; use gpg or cache for server
git config --global --get-all credential.helper
git config --global --get-regexp 'credential\.'
3.0.2+…
Configuring component 'Git Credential Manager'...
Configuring component 'Azure Repos provider'...
/usr/local/bin/git-credential-manager
credential.helper /usr/local/bin/git-credential-manager
credential.https://dev.azure.com.usehttppath true
credential.credentialstore secretservice

credential.https://dev.azure.com.useHttpPath=trueLet Git pass the repository path (including the organization name) to the assistant as well, so that different Azure DevOps organizations can use different accounts.

Direct dialogue with Credential Assistant (extremely useful when troubleshooting)

# See who the assistant will return to github.com (the token will be displayed, only execute it in your own terminal, do not take screenshots)
printf 'protocol=https\nhost=github.com\n\n' | git credential fill | sed 's/^password=.*/password=***redacted***/'
# Delete an incorrect cached credential
printf 'protocol=https\nhost=github.com\n\n' | git credential reject

Azure DevOps: One-time Git operations with Entra tokens (no PAT)

TOKEN=$(az account get-access-token --resource 499b84ac-1321-427f-aa17-267ca6975798 --query accessToken -o tsv)
git -c http.extraHeader="Authorization: Bearer $TOKEN" ls-remote "$ADO_ORG/$ADO_PROJECT/_git/myapp"
unset TOKEN

499b84ac-1321-427f-aa17-267ca6975798Is the resource (application) ID of Azure DevOps in Entra. The token expires in approximately 1 hour and is suitable for temporary use by scripts; use Service Connection/Hosted Identity in CI (Lesson 5).

Lab 2: Configuring SSH and GCM for both platforms and verifying where credentials go (~8 minutes)

GitHub SSH:Page generation by "command"id_ed25519_gh, join agent,gh ssh-key add, executessh -T git@github.comseeHi < username >!。
Azure DevOps SSH: Generateid_rsa_azdo, add it in User settings → SSH public keys on the web page, check the server fingerprint displayed on the page and then executessh -T git@ssh.dev.azure.com。
ssh-keygen -l -E sha256 -f ~/.ssh/id_rsa_azdo.pub # Compare with the public key fingerprint displayed on the web page
write~/.ssh/config(Copy the configuration of the "Command" page, including at least the github.com and ssh.dev.azure.com sections), and then verify that Azure only provides the correct key:
ssh -vT git@ssh.dev.azure.com 2>&1 | grep -E "Offering public key|Authenticated"
debug1: Offering public key: /home/me/.ssh/id_rsa_azdo RSA SHA256:Fk… explicit
debug1: Authenticated to ssh.dev.azure.com ([20.37.158.0]:22) using "publickey".
HTTPS + GCM login to Azure Repos(Project default repositorygit-labalready exists):
cd /tmp && git clone "$ADO_ORG/$ADO_PROJECT/_git/$ADO_PROJECT" ado-default
# Browser or WAM pops up Entra login; clone continues after completion (empty repository will prompt You appear to have cloned an empty repository)
git credential-manager azure-repos list
contoso-lab:
  (global) -> you@contoso.com
Confirm credential type: GCM 3 saves OAuth access tokens (JWT, ending witheyJ) instead of the 84-character PAT:
printf 'protocol=https\nhost=dev.azure.com\npath=%s/%s/_git/%s\n\n' "$ADO_ORG_NAME" "$ADO_PROJECT" "$ADO_PROJECT" \
  | git credential fill | awk -F= '/^password=/{print "token prefix:", substr($2,1,3), "length:", length($2)} /^username=/{print}'
username=you@contoso.com
token prefix: eyJ length: 2214
Create a minimal-privilege GitHub fine-grained PAT (for M4's REST experiment, optional): Web page Settings → Developer settings → Personal access tokens → Fine-grained tokens → Generate new token: Choose yourself as Resource owner, choose “Only select repositories” for Repository access (edit and select after M4 creates myapp), Permissions: Contents Read and write, Pull requests Read and write, Administration Read and write (required for management rule set), expires in 7 days. Keep tokens only in a password manager.
clean up:rm -rf /tmp/ado-default. The SSH public key and PAT will be retained until the comprehensive experiment is completed and revoked (see p-final cleanup list).

Case 1: The developer has both personal and company GitHub accounts, and the commit was pushed with the wrong identity.

Question:The push to the company repository used the OAuth token of the personal account and was rejected by the organization's SAML SSO (403)。Method:Company repositories use SSH host aliases uniformlygithub-work;For HTTPS scenarioscredential.https://github.com.useHttpPath=trueHave GCM distinguish accounts by path, andgit credential-manager github loginTwo accounts. Also used in the company repository directoryincludeIf "gitdir:~/work/"Set up a company email (committing the author and verifying the identity are two different things).Limitations:SSH keys must also be organized on GitHub for SSO "Configure SSO → Authorize".

Case 2: Azure DevOps global PAT retirement causes nightly scripts to fail

Question:The "All accessible organizations" PAT created many years ago is used to back up the repositories of all organizations. After decommissioning, the script reports401。Method:Change the backup job to run with a managed identity in Azure, add the managed identity as a user for each organization (Basic), useaz account get-access-token --resource 499b84ac-…Get token; manual script uses organization-level PAT instead and enrolls inventory (owner, purpose, scope, expiration).Limitations:Service principals/managed identities also account for user licenses and need to be factored into the cost.

Case 3: PAT is committed to a public GitHub repository

Question:Developers use Azure DevOps PAT.envPush to personal public repository.Method:Azure DevOps scanned the public GitHub repository and discovered this PAT, when tenant policy allowed itautomatic revocationand record audit eventsToken.PatPublicDiscoveryEvent; security team notifies users, rotates relevant credentials, and clears them from history (Lesson 7git filter-repo)。Limitations:The audit log is only retained for 90 days and does not record token usage events, so it is impossible to determine whether it has been used.

Common errors and solutions

remote: Support for password authentication was removed on August 13, 2021. fatal: Authentication failed for 'https://github.com/…'

Reason:The Credential Assistant (or you enter it manually) provides the GitHub account password.

git config --show-origin --get-all credential.helper
printf 'protocol=https\nhost=github.com\n\n' | git credential reject

Fix:Install/enable GCM or executegh auth setup-git;Paste PAT at the password when entering manually.

git@github.com: Permission denied (publickey).

Reason:The key is not loaded, the wrong key is provided, the public key is not registered in the account, or the private key permissions are too wide and are ignored by ssh.

ssh -vT git@github.com 2>&1 | grep -E "identity file|Offering|Authenticated|denied"
ssh-add -l
ls -l ~/.ssh

Fix:ssh-addcorrect key or in~/.ssh/configwriteIdentityFile;gh ssh-key listConfirm registration;chmod 600。

remote: Public key authentication failed. fatal: Could not read from remote repository.(Azure DevOps)

Reason:Azure DevOps only accepts client-providedfirst oneKey: The agent has GitHub's ed25519 key ranked first; or you have uploaded the ed25519 public key (not supported); or the key has expired (organizational policy); or the web page login has not been completed for more than 30 days.

ssh -vT git@ssh.dev.azure.com 2>&1 | grep Offering

Fix:forssh.dev.azure.com Configuration IdentityFile ~/.ssh/id_rsa_azdo + IdentitiesOnly yes; Use RSA; regenerate upload when expired; log in to the web page once.

You’re using ssh-rsa that is about to be deprecated and your request has been blocked intentionally.

Reason:Client uses SHA-1ssh-rsasignature (usually~/.ssh/configThere isHostkeyAlgorithms +ssh-rsaorPubkeyAcceptedAlgorithms +ssh-rsalegacy, or very old SSH client).

Fix:Remove these downgrade configurations, upgrade OpenSSH, and let clients negotiatersa-sha2-256/512。

fatal: Authentication failed for 'https://dev.azure.com/contoso-lab/git-lab/_git/myapp/'

Reason:PAT expired/revoked/insufficient scope, PAT belongs to another organization (organization-level PAT), global PAT is deactivated, conditional access requires a new login, or GCM is bound to the wrong Entra account.

git credential-manager azure-repos list
GCM_TRACE=1 git ls-remote "$ADO_ORG/$ADO_PROJECT/_git/myapp" 2>&1 | tail -20

Fix:git credential-manager azure-repos clear-cacheRetry later;azure-repos bind <org> <user>Bind the correct account; if using PAT in the script, check the expiration date and "Code (Read & write)" range.

Command line operation questions
1. Without opening any GUI, delete the credentials cached by Git for github.com so that you will be prompted to log in again the next time you push.
printf 'protocol=https\nhost=github.com\n\n' | git credential reject
2. let~/work/Repository access undergithub.comused when~/.ssh/id_ed25519_work, without affecting the personal repository.
# Method 1: Host alias (see github-work in the "Command" page), use git@github-work:corp/repo.git for remote
#Method 2: Overwrite ssh commands by directory
git config --global includeIf.gitdir:~/work/.path ~/.gitconfig-work
printf '[core]\n sshCommand = ssh -i ~/.ssh/id_ed25519_work -o IdentitiesOnly=yes\n[user]\n email = me@corp.example\n' > ~/.gitconfig-work
Scenario analysis questions
A colleague said: "My push main was rejected, so I deleted the GitHub credentials in the credential manager. After logging in again, it was still rejected." His output includedGH013: Repository rule violations found. How do you explain that?

This is a rejection during the rule evaluation phase: the credential has already been authenticated and authorized (otherwise it would not have entered receive-pack's rule evaluation), and there is no point in deleting the credential. You should instead push the feature branch and create a PR (git push origin HEAD:feature/x → gh pr create), or ask your administrator to confirm if it should be in the ruleset's bypass list - it usually shouldn't be. Availablegh ruleset check mainSee which rules apply to main.

Verified instructional videos

No verified videos found specifically on GCM 3 / Azure DevOps SSH. The following generic videos have been verified by YouTube oEmbed as a background review (recorded prior to GCM 3 and fine-grained PAT GA, details are subject to this lesson).

▶
Git and GitHub for Beginners - Crash Course — freeCodeCamp.org
English · Complete demo with SSH key generation and pushing to GitHub
▶
Git & GitHub Crash Course For Beginners — Traversy Media
English · Early recording, suitable for reviewing the basic process of remote and push

Official documentation

Video storyboard (about 100 seconds)

This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Screen: Enter git push in the terminal, and the server on the right responds with a red 401 envelope.
Narrator: The first step of an HTTPS push is always rejected once, the server is telling Git: please show your credentials.
Shot 2 · 20–45s
Screen: Git hands GCM a card with protocol equal to https and host equal to github.com; GCM opens the browser, the user clicks "Authorize", and the keychain icon lights up.
Narrator: Git asks GCM for credentials through the credential assistant protocol. GCM uses OAuth to log in to get the token and store it in the system keychain.
Shot 3 · 45–75s
Screen: The request with the token passes the authentication gate (green light), the packfile enters the quarantine area, the rule engine lights up red, and GH013 and remote rejected appear on the terminal.
Narrator: The authentication passed, but the ruleset required all modifications to go through a Pull Request, so the push was rejected in the pre-receive stage.
Shot 4 · 75–100s
Screen: Two comparison cards: "401 → Delete Credentials" on the left, "GH013 → Open a branch and commit a PR" on the right.
Narrator: Only 401 indicates that there is a problem with the credentials; when the rule rejects it, the credentials are good, and the correct approach is to push the branch and open a PR.
or score ≥ 70% on the Quiz

Module 3 · Azure Repos: Repositories, Branching Strategies and PRs

13:00 – 22:00 · Turn main into a branch that can only be modified by PRs that have been reviewed, built, and associated with work items.
9 minutesAzure DevOps Services · azure-devops CLI extension★★★★★
learning objectives
  • Use web pages withaz repos create / az repos import createCreate or import a repository and push all branches and tags of the local myapp to it.
  • Configure branch strategy: minimum reviewers (including "disable recent pusher approval" and "reset voting on new push"), associated work items, comment resolution, merge type restrictions, build verification (including expiration settings), status check, automatic inclusion of reviewers + path filtering.
  • Understand how the strategy is executed:Branches with any "required" policy prohibit direct push(TF402455); "Bypass policy" are two independent permissions.
  • Master PR completion options (merge type, complete associated work items, delete source branch, custom merge commit message, autocomplete) and useaz repos prComplete the entire process.
Prerequisite knowledge:GCM login for Module 2; merge/squash/rebase for Lesson 2.Importance:★★★★★

What: Object hierarchy for Azure Repos

organization → project → repository. Permissions can be set at three levels: "all repositorys", a single repository, and a single branch at the project level. The inheritance relationship is from top to bottom. Branch protection consists of two parts:

  • branch policies: Rules for PR completion conditions (review, work item, comment, build, status check, merge type). "Cross-repository policy" can be set on a single branch, or at the project level by branch name/prefix (e.g.release/*) unified settings.
  • branch security: Git permissions, such as Contribute, Force push (rewrite history, delete branches and tags), Create branch, Manage permissions,Bypass policies when completing pull requests、Bypass policies when pushing。

In addition there areRepository level strategy(Repos → Settings → Policies): Commit author email verification, file path verification, case enforcement, reserved names, maximum path length, maximum file size, etc., which are checked by the server when pushing (not just for PR). Hard limits of the platform: the repository should be no larger than 250 GB (recommended to be within 10 GB), a single push can be up to 5 GB (more than that must be imported from a web page), the file is recommended to be no larger than 100 MB, and the total path length is 32,766 characters.

Why: Why use strategy instead of "convention"

This verbal agreement of “everyone PR’s” is bound to be broken when working on a deadline. The strategy is executed by the server: as long as there is anyRequiredPolicy, people without bypass permissions cannot push directly and can only be modified through PR; PR must meet all required policies to be completed. This also satisfies auditing (who approved what, corresponding to which work item, which build).

How: The semantics of each policy

StrategyKey optionsNote
Require a minimum number of reviewersMinimum number of people; Allow requestors to approve their own changes;Prohibit the most recent pusher from approving their own changes;Allow completion even if some reviewers vote to wait or reject;When new changes are pushed:Require at least one approval on every iteration / on the last iteration、Reset all approval votes、Reset all code reviewer votes"Author self-approval" is not counted by default; "Prohibit recent pushers from self-approval" is used for separation of duties (you approve a commit after someone else has pushed it)
Check for linked work itemsRequired / OptionalConnected with Azure Boards; when completing the PR, the work item can be turned into completed
Check for comment resolutionRequired / OptionalAll comment threads must be Resolved / Won't fix / Closed
Limit merge typesBasic merge (no fast-forward)、Squash merge、Rebase and fast-forward、Rebase with merge commitDetermining the historical shape of main (Lesson 6 discusses trade-offs)
Build validationSelect pipeline; Trigger automatic/manual; Policy requirement Required/Optional; Build expiration: Immediately when main is updated / After n hours if main has been updated / Never; Path filterThe build is run with PRMerge preview commit(refs/pull/<id>/merge), not the source branch itself
Status checksExternal services publish status (genre/name) through PR Status API; Authorized identity, reset conditions, applicability, path filteringSuitable for third-party scanning, external CI
Automatically included reviewersUser/Group; Required/Optional; Path filtering (supported*、?、!exclude,;Separated, the path must be separated by/or wildcard); allows requesters to self-approveAzure Repos does not have a CODEOWNERS file, this is its counterpart (M5)

PR completion options

  • Merge type: One of four types subject to "Limit merge types".
  • Complete associated work items after merging、Delete <source> after merging、Customize merge commit message。
  • Set auto-complete: Automatically completed after all policies are met (from 2026-03, you can set "New PR to enable automatic completion by default" in the repository/project).
  • Draft(Draft PRs will not be notified to required reviewers and cannot be completed),Abandon、Reactivate。
  • People with Bypass permissions will seeOverride branch policies and enable merge, reasons must be filled in and audit records left.
  • 2026-03 Added new repository setting: whether the commit message generated when the PR is completed is automatically prefixed with the PR number (retained by default).

When: Recommended main baseline

  • Minimum 1–2 reviewers,not allowedAuthor self-approval, enable "Prohibit recent pushers from self-approval", reset the approval ticket when new push is made.
  • Associated Work Items (Required), Comment Resolution (Required), Merge Type only allows Squash (or Rebase and fast-forward).
  • Build Validation Required, expires "immediately when main is updated" or "n hours later".
  • Automatically include reviewers by category (/infra/*→ platform group), unified cross-repository strategymain with release/*。
  • Bypass permissions are only given to a very small number of emergency accounts and are audited regularly.
Common misunderstandings① "Set the policy to Optional can also prevent direct push" - only if there isRequiredOnly branches of the policy are prohibited from direct push. ② "People with Bypass permissions cannot see the policy failure" - the policy will always be evaluated, and it is only a "suggestive" display to them. ③ "The 'Allow self-criticism' that automatically includes reviewers will make the minimum reviewer policy also allow self-criticism" - the two policies are set independently. ④ "The build verification runs on my branch" - it runs on the preview commit after the PR is merged into the target branch.

Architecture diagram: Protection layers of Azure Repos

Organization contoso-lab (Entra Tenant · PAT/SSH Policy · Accounting) Project git-lab (project-level Git permissions · cross-repository branch strategy main, release/* · repository default settings) Repository myapp Repository policy: Maximum file size · Path length · Reserved name · Author email Repository permissions: Contribute · Create branch · Create tag branch main Branching strategy: reviewer · work item · comment · merge type · build Branch security: Force push ✗ · Bypass (emergency account only) Automatically include reviewers: /infra/* → Platform team The fate of pushing main directly at once 1. Entra / PAT / SSH authentication → Passed 2. Contribute permission → Pass 3. Repository policy (file size, etc.) → Pass 4. main has the Required branch policy and no Bypass permissions → TF402455: Pushes to this branch are not permitted; you must use a pull request to update this branch. 5. Correct path: push feature/* → Create PR
Figure 3-1 Organization → Project → Repository → Branch, permissions and policies are superimposed layer by layer

Flow chart: PR from creation to completion

pushfeature/healthz Create a PRrefs/pull/7/merge Build verification (merge preview commits) Review voting / Automatically include reviewers Work item association · Comment resolution Status check (external service) All Required Passedor auto-complete trigger Completed (server-side merge)Generate commits by allowed merge typesComplete the work item · Delete the source branchNew push → Reset voting, build expired
Figure 3-2 Before the PR is completed, all necessary strategies are evaluated in parallel; when there is a new push to the source branch, it is reset according to the configuration

Interaction Simulator: Can this PR be completed now?

Configure the branch strategy of main on the left, and adjust the current status of PR on the right. The simulator evaluates each policy against the rules of Azure Repos and gives the status you would see on the PR page.az repos pr policy listoutput. Try a combination of "author self-approval", "recent pusher" and "reset vote after new push".

Branch strategy (main)
PR #7 Current status
After adjusting the left and right sides, click Evaluate.
$ az repos pr policy list --id 7 -o table

az reposCommon commands

commandfunctionKey parameters
az repos create --name myappCreate repositoryReturnremoteUrl、sshUrl、id
az repos list -o table / az repos show -r myappList/view repositories--query id -o tsvGet repository ID
az repos import createImport the external Git repository intoExisting empty repository--git-source-url、--repository、--requires-authorization、--user-name(Password/PAT is placed in the environment variableAZURE_DEVOPS_EXT_GIT_SOURCE_PASSWORD_OR_PAT)
az repos policy approver-count createMinimum reviewers--minimum-approver-count、--creator-vote-counts、--allow-downvotes、--reset-on-source-push、--blocking
az repos policy work-item-linking createAssociated work items--blocking true
az repos policy comment-required createComment solution--blocking true
az repos policy merge-strategy createLimit merge types--allow-squash、--allow-no-fast-forward、--allow-rebase、--allow-rebase-merge(--use-squash-mergeDeprecated)
az repos policy build createBuild verification--build-definition-id、--queue-on-source-update-only、--manual-queue-only、--valid-duration(minutes, 0 = not expire),--path-filter
az repos policy required-reviewer createAutomatically include reviewers--required-reviewer-ids(email;separated),--path-filter、--message
az repos policy list --repository-id … --branch mainView policies on a branch-o table
az repos pr createCreate a PR--source-branch、--target-branch、--work-items、--reviewers、--auto-complete、--squash、--delete-source-branch、--transition-work-items、--draft
az repos pr set-vote / pr policy list / pr updateVote / View Strategy Review / Complete or Abandon--vote approve|reject|wait-for-author;--status completed|abandoned;--bypass-policy --bypass-policy-reason

Create a repository and push all branches and tags

source ~/.gitlab-p3.env
az repos create --name myapp --query "{id:id, https:remoteUrl, ssh:sshUrl}" -o json
cd ~/git-lab/myapp
git remote add azure "$ADO_ORG/$ADO_PROJECT/_git/myapp" # or SSH: git@ssh.dev.azure.com:v3/$ADO_ORG_NAME/$ADO_PROJECT/myapp
git push -u azure --all
git push azure --tags
git ls-remote --heads --tags azure
{
  "https": "https://contoso-lab@dev.azure.com/contoso-lab/git-lab/_git/myapp",
  "id": "d28cd374-e7f0-4b1f-ad60-f349f155d47c",
  "ssh": "git@ssh.dev.azure.com:v3/contoso-lab/git-lab/myapp"
}
...
a3f9c21…        refs/heads/main
7be41d0…        refs/heads/feature/healthz
1c2d3e4…        refs/tags/v0.1.0

remoteUrlinsidecontoso-lab@It is a username prompt and can be removed. If the repository has a default README commit for the first push, it will be rejected as non-fast forward - the repository created with the CLI is empty and this problem will not occur.

Import (server pull, suitable for large repositorys)

az repos create --name myapp-imported
az repos import create --git-source-url https://github.com/octocat/Hello-World.git --repository myapp-imported
# Private source: export AZURE_DEVOPS_EXT_GIT_SOURCE_PASSWORD_OR_PAT=< read-only token >, plus --requires-authorization --user-name x
{
  "detailedStatus": { "currentStep": 1, "allSteps": ["Processing request", "Analyzing repository objects", "Storing objects", "Storing index file", "Updating references", "Import completed successfully"] },
  "status": "queued",
  ...
}

Configure policy for main (CLI)

REPO_ID=$(az repos show -r myapp --query id -o tsv)
COMMON="--repository-id $REPO_ID --branch main --blocking true --enabled true"
az repos policy approver-count create $COMMON --minimum-approver-count 1 \
  --creator-vote-counts false --allow-downvotes false --reset-on-source-push true
az repos policy work-item-linking create $COMMON
az repos policy comment-required create $COMMON
az repos policy merge-strategy create $COMMON --allow-squash true
az repos policy required-reviewer create $COMMON --path-filter "/infra/*" \
  --required-reviewer-ids "you@contoso.com" --message "infra changes require platform group review"
az repos policy list --repository-id $REPO_ID --branch main --query "[].{id:id,type:type.displayName,blocking:isBlocking}" -o table
Id    Type                              Blocking
----  --------------------------------  ----------
2     Minimum number of reviewers       True
3     Work item linking                 True
4     Comment requirements              True
5     Require a merge strategy          True
6     Required reviewers                True

How to verify:directgit push azure mainshould be receivedTF402455。Common mistakes:"Disable approval by recent pushers" currently does not have a corresponding switch in the CLI parameters, and needs to be checked in the Minimum number of reviewers policy on the web page.Production use:Put these commands into the repository creation script to ensure that the baseline of each new repository is consistent; use the project-level cross-repository strategy when batch unification is required.

Build verification (optional: requires a pipeline definition)

az pipelines create --name myapp-ci --repository myapp --repository-type tfsgit \
  --branch main --yml-path azure-pipelines.yml --skip-first-run true --query id -o tsv
az repos policy build create $COMMON --build-definition-id < Previous step ID> --display-name "ci" \
  --manual-queue-only false --queue-on-source-update-only false --valid-duration 720

Pipeline YAML itself is shown in Lesson 5; new organizations using the Microsoft Hosted Agent require available parallel job credits (free credits for new organizations may need to be applied for, subject to official approval).--valid-duration 720Indicates that the build results expire 12 hours after main is updated.

Lab 3: Complete PR process on Azure Repos (~9 minutes)

Create a repository and push: Execute "Create a repository and push all branches and tags" in the "Command" tab. On the web page Repos → Files confirm that the branches and tags are there.
Configure policy: Execute "Configure policy for main (CLI)". Then check the box on the webpage Repos → Branches → main → Branch policiesProhibit the most recent pusher from approving their own changes。
Verify that direct push is rejected:
cd ~/git-lab/myapp
echo "direct" >> README.md && git commit -am "Direct change to main"
git push azure main
To https://dev.azure.com/contoso-lab/git-lab/_git/myapp
 ! [remote rejected] main -> main (TF402455: Pushes to this branch are not permitted; you must use a pull request to update this branch.)
error: failed to push some refs to 'https://dev.azure.com/contoso-lab/git-lab/_git/myapp'
git reset --hard HEAD~1 # Undo this local commit and use the branch below
Work item + branch + PR:
WI=$(az boards work-item create --title "Add /healthz docs" --type Task --query id -o tsv); echo "work item $WI"
git switch feature/healthz
echo "GET /healthz returns ok" >> docs/health.md && git commit -am "Document healthz endpoint (AB#$WI)"
git push -u azure feature/healthz
PR=$(az repos pr create --repository myapp --source-branch feature/healthz --target-branch main \
  --title "Document /healthz" --description "Adds health docs" --work-items $WI \
  --squash true --delete-source-branch true --transition-work-items true --query pullRequestId -o tsv)
echo "PR $PR"; az repos pr policy list --id $PR --query "[].{policy:configuration.type.displayName,status:status}" -o table
work item 12
PR 7
Policy                         Status
-----------------------------  --------
Minimum number of reviewers    queued
Work item linking              approved
Comment requirements           approved
Require a merge strategy       approved

in the commit messageAB#12Is the commit association syntax for Azure Boards that also links commits to work items. Not here/infra/changes, so the "Required reviewers" policy does not apply and does not appear in the list.

Review and Completion: When you have only one account, your votes will not be counted (the author’s self-approval is not allowed). Please invite a second account (Basic is free for 5) to approve it on the web page, or temporarily use it in the experiment.--creator-vote-countsChange to true (change back after experimenting):
# Execute with the second account (or click Approve on the web page)
az repos pr set-vote --id $PR --vote approve
az repos pr update --id $PR --status completed --squash true --delete-source-branch true
az repos pr show --id $PR --query "{status:status, mergeStatus:mergeStatus, commit:lastMergeCommit.commitId}" -o json
{
  "commit": "9e1f0a7c…",
  "mergeStatus": "succeeded",
  "status": "completed"
}
Sync local and check historical shapes:
git switch main && git pull azure main
git log --oneline --graph -3
az boards work-item show --id $WI --query "fields.\"System.State\"" -o tsv
* 9e1f0a7 (HEAD -> main, azure/main) Merged PR 7: Document /healthz
* a3f9c21 (tag: v0.2.0) Add Redis timeout config
...
Done
ReserveRepositorys and strategies, M5, M8 and comprehensive experiments will continue to be used. Delete the imported demo repository:az repos delete --id $(az repos show -r myapp-imported --query id -o tsv) --yes。

Case 1: “Four Eyes Principle” for regulated industries

Question:The audit requires the approval of at least one non-author for each production change, and no additional commits can be made secretly after approval.Method:Minimum number of reviewers: 1. Authors do not count votes,Disable recent pushers from approving, reset approval ticket when new push, associate work item (change order), build verification Required; Bypass permission is only given to the "break-glass" group and access to the audit flow.Configuration:Project-level cross-repository policies act onmain with release/*。Limitations:New commits can be pushed by others after reviewers approve them - this is exactly what the "Recent Pushers" option is meant to solve.

Case 2: A large number of PRs queued in the build queue

Question:main merges 80 PRs every day, and the build verification setting "expires immediately when main is updated" causes the build to be repeatedly rerun for each PR.Method:Change it to "After 12 hours if main has been updated", and set path filtering for the PR in the docs directory to skip building; key service reservations expire immediately.Limitations:The longer the expiration window, the greater the probability of "combined failure" in main after the merger, which requires CI on main to take measures and quickly roll back.

Case 3: Import from TFVC migrated repository

Question:History repository exceeds 5 GB, command linegit pushReport push size limit.Method:Use the web page/CLI according to official recommendationsImport repository(Import is not subject to the 5 GB single push limit), large files are first migrated using Git LFS.Limitations:Azure DevOps Services does not support LFS transfer over SSH, you need to use HTTPS.

Common errors and solutions

! [remote rejected] main -> main (TF402455: Pushes to this branch are not permitted; you must use a pull request to update this branch.)

Reason:There is a Required branch policy on main and you don't have "Bypass policies when pushing" permission. This isnormal protection, not an authentication issue.

Fix:git push azure HEAD:refs/heads/feature/x → az repos pr create. If the local main already has more commits:git branch feature/x && git reset --hard azure/main。

! [remote rejected] main -> main (TF401027: You need the Git 'ForcePush' permission to perform this action.)

Reason:Non-fast forward push (--force/--force-with-lease) or delete a branch, Force push permission is required.

Fix:Pushing should not be forced on protected branches; use it when you need to undo a commitgit revertAnd walk PR. When a personal feature branch is blocked, check whether Force push permissions have been tightened at the project level.

TF401019: The Git repository with name or identifier myapp does not exist or you do not have permissions for the operation you are attempting.

Reason:The organization/project/repository name in the URL is incorrect, or the account does not have Read permission for the repository (Azure DevOps deliberately does not distinguish between "does not exist" and "no permission"). It is also common when GCM is bound to another tenant's account.

az repos list --query "[].name" -o tsv
git credential-manager azure-repos list
PR keeps showing “Required reviewers: 1 of 1 approvals required”, but I have already approved it

Reason:You are the author and have not allowed self-approval; or you are the most recent pusher; or there is a new push after you approved it, causing the ticket to be reset.

Fix:Ask another reviewer for approval; see instructions in the PR's Overview → policies details.

az repos policy … : ERROR: --repository-id is required when --branch is specified (or Policy configuration with same settings already exists)

Reason:The branch-level policy must also specify the repository ID; it should be used when the same type of policy already existsupdate --id。

az repos policy list --repository-id $REPO_ID --branch main -o table
az repos policy approver-count update --id 2 --minimum-approver-count 2
Command line operation questions
1. Use CLI to set "at least 2 reviewers, author does not count votes, new push resets votes" for myapp's main.
az repos policy approver-count create --repository-id $REPO_ID --branch main --blocking true --enabled true \
  --minimum-approver-count 2 --creator-vote-counts false --allow-downvotes false --reset-on-source-push true
2. Create a PR set to autocomplete, Squash merge, delete the source branch when complete, and close work item 12.
az repos pr create -r myapp -s feature/x -t main --title "X" --work-items 12 \
  --auto-complete true --squash true --delete-source-branch true --transition-work-items true
Scenario analysis questions
The team complained: "main is locked by the policy during hotfix, and production accidents can only wait for review." How will you design the emergency channel without destroying the audit?

Don't relax main's policy; create a "break-glass" security group that only grantsBypass policies when completing pull requests(Not granted when pushing, PR must still be taken and PR record retained). When using, the bypass reason must be filled in. The audit log is exported to SIEM and an alarm is triggered; post-event review (such as post-voting on PR or establishing a review work item). You can also go for hotfixrelease/*Branch and configure a lighter strategy, fix it and merge back into main.

Verified instructional videos

No verified Azure Repos branch strategy video was found (the search results were mostly reprints from unverifiable channels). Please use the official documentation and storyboard below.

Official documentation

Video storyboard (approximately 90 seconds)

This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Picture: Organization, project, repository, branch are nested in four layers of boxes, with a lock hanging on the main branch.
Narrator: In Azure Repos, permissions and policies stack up from organization, project, repository all the way to branches.
Shot 2 · 20–45s
Picture: terminal git push main, returns TF402455 red text; then changes to push feature branch and creates PR.
Narrator: As long as there is a required policy on main, direct push will be rejected, and modifications can only be made through Pull Request.
Shot 3 · 45–75s
Screen: The five strategy cards on the right side of the PR page turn green in sequence: Reviewer, Work Item, Comment, Build, and Merge Type.
Narrator: Reviews, Work Items, Comments, Build Verification Parallel Evaluation, when all are met, the autocomplete merges according to the allowed merge types.
Shot 4 · 75–90s
Screen: A "break-glass" key icon next to an audit log entry.
Narrator: The bypass strategy is two independent permissions, only given to a very small number of emergency accounts, and a reason is left for each use.
or score ≥ 70% on the Quiz

Module 4 · GitHub: Repositories, Rule Sets, and PRs

22:00 – 31:00 · Rule sets can be stacked, can be batched, and can be “evaluated” before taking effect – this is why it replaces traditional branch protection
9 minutesRulesets GA · Push rulesets GA(2024-09)Merge Queue: Organization Public Repository / GHEC★★★★★
learning objectives
  • Configure key collaboration settings for GitHub repositories: roles (Read/Triage/Write/Maintain/Admin), merge button options, automatic merging, and automatic deletion of branches after merging.
  • understandrulesetswithTraditional branch protection rulesThe difference: multiple rule sets take effect at the same time, rulesAggregate and get the most stringent, can switch the enabled status, set bypass by role/team/App, and anyone with read permission can view it.
  • Use the REST API (gh api)Create a branching rule set and verifyGH013Deny; Learn about tag rule sets versus push rule sets.
  • use gh prComplete creation, inspection, review, and automatic merging; understand the merge queuemerge_groupEvents and temporary branches.
Prerequisite knowledge:Module 1 pre-receive; Module 3 strategic concepts.Importance:★★★★★

What: GitHub repository protection methods

  • role: Read, Triage, Write, Maintain, Admin (customizable roles for organizations). Write to push to the unprotected branch.
  • Traditional branch protection rules: Set according to branch name mode, each branchonly oneThe rules take effect; repository administrator permissions are required to view them.
  • rulesets: Category three——branch rule set(Pressfnmatchmode or~DEFAULT_BRANCH/~ALLSelect branch),Label rule set(Who can create/delete/modifyv*label),Push ruleset(Block pushes by file path, path length, extension, file size, works on private/internal repositories and their entire fork network). Maximum of 75 rule sets per repository, plus organization-level rule sets.
  • secret scanning push protection: Detect tokens in known formats and block when pushing (free for public repositories).

Why: Why use a rule set?

Traditional branch protectionruleset
Quantity on the same branchOnly one takes effectMultiple effective at the same time, rule aggregation; when the same rule is configured differentlyTake the strictest
overlay with anotherRule sets and branch protection rules will also be aggregated when they exist at the same time (the most stringent one is chosen)
Start and stopcan only be deletedActive / Disabled switch, no need to delete; Enterprise also hasEvaluateMode (only record without blocking, use "Rule insights" to observe the impact)
bypass“Do not allow bypassing the above settings”/AdminBypass list: repository role, team, GitHub App, deployment key, etc.; can be set to "always" or "bypass only via PR"
visibilityAdministrators onlyAnyone with read accessYou can view the effective rule set (convenient for developers to check themselves)
batchEach repository is configured individuallyOrganization-level rule sets are delivered in batches by repository name/custom attributes (Enterprise)
Unique abilityLock branch, restrict who can pushTag rule set, push rule set, commit metadata rule (Enterprise), required workflow/code scan results

How: Common branching rules

Rules (RESTtype)function
Restrict deletions(deletion)Disable branch deletion
Block force pushes(non_fast_forward)Disable non-fast-forward updates
Require a pull request before merging(pull_request)Parameters:required_approving_review_count、dismiss_stale_reviews_on_push、require_code_owner_review、require_last_push_approval(The latest push must be approved by others, corresponding to Azure's "Disable approval by the latest pusher"),required_review_thread_resolution、allowed_merge_methods
Require status checks to pass(required_status_checks)Specify the check name;strict_required_status_checks_policy= Require branches and targets to be kept up to date
Require linear history(required_linear_history)Disable merge commit
Require signed commits(required_signatures)Lesson 7 about signatures
Require merge queue(merge_queue)Merge must go through queue
Restrict creations / updates(creation / update)Only people in the bypass list can create/update matching references (forrelease/*)
Require deployments / code scanning resultsIt is required to deploy to a certain environment first, and code scanning shows no high-risk alarms.

merge queue

Multiple PRs "each pass through CI" may be broken together. The merge queue superimposes the queued PRs onto the target branch in turn, generating the followinggh-readonly-queue/{base_branch}Prefix the temporary branch and run the required checks on it, and merge them in FIFO order after passing; failed PRs are removed, and the rest are rebuilt. GitHub Actions workflow must listenmerge_groupEvents that would otherwise require a check would never be reported. Settings: merge method, build concurrency (1–100merge_groupwebhook), min/max packet size, check timeout.Available in: Public repositories owned by your organization, or private repositories in your GitHub Enterprise Cloud organization。

Packages and Availability (2026-11)

  • Public repositories: Branch protection and rulesets are available on all plans.
  • Private repository: branch protection, required reviewers, CODEOWNERS requiredPro / Team / Enterprise; GitHub Free private repositories are not available.
  • Push rule sets: Private/internal repositories for Team and above; Organization-level rule sets, Evaluate mode, commit metadata rules: Enterprise.

When: Recommended main baseline (corresponding to M3)

targetAzure Repos branching strategyGitHub ruleset
Direct push is prohibitedAny Required policypull_request rules
Approved by at least 1 other personMinimum reviewer 1, authors do not count votesrequired_approving_review_count: 1(GitHub does not allow authors to approve their own PRs)
Pushing after approval requires re-approvalReset voting + disable recent pushers from approvingdismiss_stale_reviews_on_push + require_last_push_approval
Comments must be addressedCheck for comment resolutionrequired_review_thread_resolution
Only squash is allowedLimit merge types: Squashallowed_merge_methods: ["squash"](Or the repository settings only enable squash)
CI must passBuild validationrequired_status_checks
Responsible person by directoryAutomatically include reviewer + pathCODEOWNERS + require_code_owner_review
Associated work itemsCheck for linked work itemsNo built-in equivalent (available status check/Action validation PR body, or Enterprise's metadata rules)
No push/deletion allowedForce push permissionnon_fast_forward + deletion
Common misunderstandings① "I am Admin, the rule set cannot stop me" - the default rule setAlso effective for administrators, unless the repository administrator role is added to the bypass list. ② "If the rule set is Disabled, it means there is no protection" - if there is a traditional branch protection rule, it will still take effect (the two are aggregated). ③ "Evaluate mode will prevent illegal pushes" - No, it only records and is only available in Enterprise. ④ "When the merge queue is turned on, CI will run automatically" - the workflow must be addedon: merge_group。

Rule aggregation graph: multiple sources, choose the strictest

Organization ruleset org-baseline (Enterprise)~DEFAULT_BRANCH: Prohibit push and deletionbypass: none Repository ruleset protect-mainRequires PR, 1 approval, CODEOWNERSbypass: Repository admin (PR only) Traditional branch protection mainRequires 2 approvals, status check test(Historical legacy) Aggregation (no priority)The same rule takes the strictestbypass only exemptthe rule set it is in Valid rules for main No forced promotion or deletion is allowedMust pass PRNumber of approvals = max(1, 2) = 2CODEOWNERS ReviewStatus check test passedgh ruleset check main can be viewed
Figure 4-1 The rule set and branch protection rules are aggregated. The same rule is the most stringent; bypass is effective according to the rule set.

Flow chart: PR and merge queue

PR #12pull_request CI ✓ Review ✓ Thread ✓Add to merge queue Merge Queue (FIFO) gh-readonly-queue/main/pr-11-… = main + #11 gh-readonly-queue/main/pr-12-… = main + #11 + #12 Each temporary branch triggers the merge_group event and must be checked when running The losers are removed and the rest is rebuilt. main fast forward toVerified commit CI is not listeningmerge_group → timeout
Figure 4-2 The merged queue is verified on the "superimposed result" to avoid combinatorial failures.

Interactive Calculator: What will happen to this operation when multiple rule sets are stacked?

Configure three rule sources (enablement status, number of approvals, whether to prohibit forced push, whether to require status check, bypass), and select the operator and operation. The calculator first eliminates unenabled rule sets and rule sets that you can bypass, then selects the most stringent rules for the remaining rules, and outputs the results that GitHub will return.

After configuration, click Calculate.
$ gh ruleset check main

ghCommon commands with REST

commandfunctionKey parameters
gh repo createCreate repository--public/--private、--source .、--remote github、--push、--template
gh repo editModify repository settings--enable-squash-merge、--enable-merge-commit=false、--enable-rebase-merge=false、--enable-auto-merge、--delete-branch-on-merge、--default-branch
gh api repos/{owner}/{repo}/rulesetsList/Create Rule Sets (REST)-X POST --input ruleset.json;updatePUT …/rulesets/ID
gh ruleset list|view|checkView the ruleset;checkDisplay all rules that apply to a branchgh ruleset check main、view --web
gh pr createCreate a PR--base、--head、--title、--body、--reviewer、--draft、--fill
gh pr checks / gh pr viewView inspections and status--watch;--json reviewDecision,mergeStateStatus,statusCheckRollup
gh pr reviewReview--approve、--request-changes、--comment -b(Cannot approve your own PR)
gh pr mergeMerge/Auto-merge/Enter merge queue--squash|--merge|--rebase、--auto、--delete-branch、--admin(use bypass)

Create a public repository and push all branches and tags

source ~/.gitlab-p3.env
cd ~/git-lab/myapp
gh repo create "$GH_OWNER/myapp" --public --source . --remote github --description "git-lab part3"
git push -u github --all
git push github --tags
gh repo edit "$GH_OWNER/myapp" --enable-squash-merge --enable-merge-commit=false --enable-rebase-merge=false \
  --enable-auto-merge --delete-branch-on-merge
gh repo view "$GH_OWNER/myapp" --json visibility,defaultBranchRef,squashMergeAllowed,mergeCommitAllowed,deleteBranchOnMerge
✓ Created repository octo-learner/myapp on GitHub
✓ Added remote https://github.com/octo-learner/myapp.git
...
{"defaultBranchRef":{"name":"main"},"deleteBranchOnMerge":true,"mergeCommitAllowed":false,"squashMergeAllowed":true,"visibility":"PUBLIC"}

Create a ruleset with REST

{
  "name": "protect-main",
  "target": "branch",
  "enforcement": "active",
  "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
  "bypass_actors": [],
  "rules": [
    { "type": "deletion" },
    { "type": "non_fast_forward" },
    { "type": "pull_request",
      "parameters": {
        "required_approving_review_count": 0,
        "dismiss_stale_reviews_on_push": true,
        "require_code_owner_review": false,
        "require_last_push_approval": false,
        "required_review_thread_resolution": true,
        "allowed_merge_methods": ["squash"]
      } }
  ]
}
gh api -X POST "repos/$GH_OWNER/myapp/rulesets" --input ruleset-protect-main.json --jq '{id, name, enforcement}'
gh ruleset list -R "$GH_OWNER/myapp"
gh ruleset check main -R "$GH_OWNER/myapp"
{"enforcement":"active","id":4211873,"name":"protect-main"}

Showing 1 of 1 rulesets in octo-learner/myapp
ID       NAME          SOURCE                 STATUS  RULES
4211873  protect-main  octo-learner/myapp (repo)  active  3

3 rules apply to branch main in repo octo-learner/myapp
- deletion
- non_fast_forward
- pull_request: [allowed_merge_methods: [squash]] [required_approving_review_count: 0] …

Why the approval count is 0:GitHub does not allow authors to approve their own PRs, and an approval count of 1 for a solo experiment will result in it never being merged. Even if it is 0,pull_requestThe rules remainDirect push is prohibited, ask for PR. When you have a second account (add as a collaborator, Write), please change it to 1 and enable it.require_last_push_approval, equivalent to the configuration of Azure Repos.Required token permissions:gh auth loginThe default OAuth token is sufficient; fine-grained PAT requires Administration: Read and write.

PR whole process

git switch -c feature/redis-docs
echo "REDIS_URL defaults to redis://redis:6379/0" > docs/redis.md
git add docs/redis.md && git commit -m "Document REDIS_URL"
git push -u github feature/redis-docs
gh pr create --base main --head feature/redis-docs --title "Document REDIS_URL" --body "Adds Redis docs"
gh pr view --json number,reviewDecision,mergeStateStatus
gh pr merge --squash --delete-branch # Available when conditions are not met --auto, merge automatically after conditions are met
https://github.com/octo-learner/myapp/pull/1
{"mergeStateStatus":"CLEAN","number":1,"reviewDecision":""}
✓ Squashed and merged pull request octo-learner/myapp#1 (Document REDIS_URL)
✓ Deleted local branch feature/redis-docs and switched to branch main
✓ Deleted remote branch feature/redis-docs

Workflow triggers required for merge queues (demo)

name: ci
on:
  pull_request:
  merge_group: # The merge queue must
jobs:
  test: # The name of the required status check is the job name "test"
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: python -m py_compile app/main.py

Lab 4: GitHub ruleset + rejected direct push + PR merge (~9 minutes)

Create a public repository and push it: Execute the first paragraph of the "Command" page. On the web page Settings → General → Pull Requests confirm that only squash is allowed.
Create ruleset:Saveruleset-protect-main.jsonand executegh api -X POST …. View protect-main on the web page Settings → Rules → Rulesets and pay attention to Enforcement status in the upper right corner.
Verify direct push rejected (real version of Core Animation scene A):
git switch main && git pull github main
echo "direct" >> README.md && git commit -am "Direct change"
git push github main
remote: error: GH013: Repository rule violations found for refs/heads/main.
remote: Review all repository rules at https://github.com/octo-learner/myapp/rules?ref=refs%2Fheads%2Fmain
remote:
remote: - Changes must be made through a pull request.
remote:
To https://github.com/octo-learner/myapp.git
 ! [remote rejected] main -> main (push declined due to repository rule violations)
error: failed to push some refs to 'https://github.com/octo-learner/myapp.git'
git branch feature/direct-change && git reset --hard github/main # Move the commit to the branch
Verification force push was also rejected:
git push --force-with-lease github HEAD~1:main 2>&1 | grep -E "GH013|rejected|non_fast|force"

Expect to see GH013 with "Cannot force-push to this branch".

Merge via PR:
git switch feature/direct-change
git push -u github feature/direct-change
gh pr create --fill --base main
gh pr merge --squash --delete-branch
git switch main && git pull github main && git log --oneline -2
(optional, with a second account)Change the number of approvals to 1 and turn it onrequire_last_push_approval:
RS=$(gh api "repos/$GH_OWNER/myapp/rulesets" --jq '.[] | select(.name=="protect-main") | .id')
jq '.rules |= map(if .type=="pull_request" then .parameters.required_approving_review_count=1 | .parameters.require_last_push_approval=true else . end)' \
  ruleset-protect-main.json > rs2.json
gh api -X PUT "repos/$GH_OWNER/myapp/rulesets/$RS" --input rs2.json --jq '.rules[] | select(.type=="pull_request") | .parameters'
ReserveRepository and rule sets for M5, M6, M8 and comprehensive experiments.

Case 1: Migrating from branch protection to rulesets without interruption

Question:200 repositorys each maintain branch protection rules, and the configuration drifts seriously.Method:Enterprise organizations start by creating an organization-level rule set (target: Custom Attributestier=prodrepository), the status is set toEvaluateFor two weeks, use Rule insights to observe the pushes that will be intercepted; correct the false positives and switch to Active, and then gradually delete the traditional branch protection of each repository (the most stringent one will be used during the aggregation period, so that there will be no protection window).Limitations:Enterprise is required for Evaluate and organization-level rule sets; Team organizations can only configure rule sets on a per-repository basis (scriptable + REST batch available).

Case 2: Posting tag deleted by mistake

Question:When someone cleans up locallygit push origin --delete v2.3.0, leading to broken product traceability.Method:Label Rule Set: Targetv*, the rules Restrict deletions, Restrict updates, Restrict creations, bypass are only for GitHub App for publishing.Limitations:Deleted tags need to be restored from local clones or artifact metadata (git push origin v2.3.0, executed by the bypass account).

Case 3: main turns red frequently after merging

Question:In high-frequency repositorys, each PR passes CI independently, but the combination fails after concurrent merging; "requiring branches to stay up to date" causes developers to constantly rebase.Method:Enable merge queue (Organization Public Repository or GHEC), turn off strict latest requirement, increase workflowmerge_group, maximum grouping 5, concurrency 3.Limitations:Third-party CI needs to monitorgh-readonly-queue/*branch push.

Common errors and solutions

remote: error: GH013: Repository rule violations found for refs/heads/main. … - Changes must be made through a pull request.

Reason:rule setpull_requestrules. Normal protection.

gh ruleset check main

Fix:Push branch + PR. When an emergency bypass is really needed, it is performed by the bypass role (and a record is left) instead of temporarily disabling the rule set.

remote: error: GH006: Protected branch update failed for refs/heads/main. remote: error: Changes must be made through a pull request.

Reason:Traditional branch protection rules deny (GH006 corresponds to branch protection, GH013 corresponds to the rule set).

Fix:Same as above; view the rules in Settings → Branches. This error code will change to GH013 after migrating to the ruleset.

X Pull request octo-learner/myapp#3 is not mergeable: the base branch policy prohibits the merge.

Reason:gh pr mergeConditions are not met: insufficient number of approvals, required checks not completed, thread unresolved, CODEOWNERS approval required, merge method not allowed.

gh pr view 3 --json reviewDecision,mergeStateStatus,statusCheckRollup --jq '.'
gh pr checks 3

Fix:meet the conditions, or usegh pr merge --autoWait; when you have bypass--adminwill be bypassed (visible in audit).

Required status check "test" is expected — Waiting for status to be reported

Reason:The required check name is inconsistent with the actual reported name (the job is renamed in the workflow, the matrix job name istest (3.13)), or the workflow haspathsFiltering results in no triggering at all, or the merge queue is not monitored.merge_group。

Fix:Modify the rules based on the actual check name that appears on the PR page; for workflows skipped by path filtering, use the mode of "always run and determine whether to skip within the job" (M5 detailed explanation).

gh: Resource not accessible by personal access token (HTTP 403) (when creating a rule set)

Reason:Fine-grained PAT lacks Administration write permissions, or the repository is not selected; the organization requires PAT approval and the token is pending.

Fix:Edit token permissions/repository scope; or use insteadgh auth loginOAuth token.

Command line operation questions
1. List all rules on myapp that apply to main (including those from the organization's rule set).
gh ruleset check main -R OWNER/myapp
2. Set PR #5 to automatically squash merge and delete the branch after merging.
gh pr merge 5 --auto --squash --delete-branch
Scenario analysis questions
The repository has one traditional branch protection (2 approvals) and one rule set (1 approval, admin bypassable). For administratorsgh pr merge --adminMerged only 1 approved PR and still failed. Why?

bypass only exempts the rule set it is in; traditional branch protection requires 2 approvals to still be valid (and the rule does not allow administrators to bypass or "Do not allow bypassing" is turned on). The combination of the two is the most stringent. Solution: Migrate the protection to the rule set, delete the legacy branch protection rules, and then use the bypass list of the rule set to uniformly manage exceptions.

Verified instructional videos

No video dedicated to the GitHub Rules Set was found with a video ID that could be verified by oEmbed (the official GitHub "15 Minutes to Merge" show has a related episode, but the link could not be verified). The following generic videos have been verified:

▶
Git for Professionals Tutorial - Tools & Concepts for Mastering Version Control with Git — freeCodeCamp.org
English · Includes explanation of PR workflow, branch strategy and merge vs rebase

Official documentation

Video storyboard (approximately 90 seconds)

This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Image: Three transparencies (Organization Rule Set, Repository Rule Set, Old Branch Protection) stacked on the main branch.
Narrator: GitHub allows multiple rule sets to act on a branch at the same time. All rules are superimposed, and the strictest is used in case of conflict.
Shot 2 · 20–45s
Screen: Terminal git push main → GH013 → remote rejected; open the rules link in the browser next to it.
Narrator: When a direct push is rejected, the link in the message will show you which rule it is.
Shot 3 · 45–70s
Screen: There is only one robot icon in the bypass list; the administrator's avatar is blocked from the door.
Narrator: The rule set also applies to administrators by default, and exceptions must be explicitly added to the bypass list.
Shot 4 · 70–90s
Screen: The merge queue is like a conveyor belt, with three PRs stacked one after another and the green light turning on.
Narrator: The merge queue runs checks on the stacked results to avoid passing them individually and failing together.
or score ≥ 70% on the Quiz

Module 5 · CODEOWNERS, Required Reviews and Status Checks

31:00 – 38:00 · Let “who must see this code” and “what checks must pass” be enforced by the platform rather than by memory
7 minutesGitHub CODEOWNERS · Azure automatically includes reviewers★★★★
learning objectives
  • Writing GitHubCODEOWNERS: Position and search order, gitignore style syntax and three exceptions,Last match takes effect, the owner must have write permission, the file is taken from PRtarget branch。
  • Implement the same directory owner in Azure Repos with "Auto-include reviewers + path filtering" and understand the path filtering!Exclude and order from left to right.
  • Configure required status checks (GitHub check name/Azure build verification and status checks) to avoid the path filtering trap of "checks are never reported".
Prerequisite knowledge:Strategies and rule sets for M3 and M4.Importance:★★★★

What: Two implementations of "owner by path"

GitHub CODEOWNERSAzure Repos automatically include reviewers
Where is the configurationFiles in the repository:.github/CODEOWNERS, root directoryCODEOWNERS、docs/CODEOWNERS(Look in this order, use the first one found)branching strategy (web oraz repos policy required-reviewer), not in the code
Matching rulesgitignore style;When multiple matches occur, the last one takes effect.; not supported!Negation, character range[a-z], starting with escape#; Lines with syntax errors are skippedEach strategy is evaluated independently,Multiple strategies can require different reviewers at the same time;The path must be/or wildcard character; supported!Exclude, left to right; case insensitive
Forced methodRule set/branch protection turned on “Require review from Code Owners”Policy set to Required
Owner requirementsThe user/team needs to have knowledge about the repositoryExplicit write permission, the team must be visibleAny user or group with permission; any member of the group can approve
VersioningWith code review and traceability; what takes effect is the file on the PR target branchPolicy changes are recorded in the audit log
size/limitFile must be less than 3 MB—

Why

"At least 1 reviewer" only guarantees that someone has viewed it, not a guaranteePeople who understandSaw it.infra/Terraform,.github/workflows/(Confidential pipelines can be obtained) and database migration scripts should be compulsorily approved by the corresponding team. Set CODEOWNERS itself to be the responsibility of the platform team to prevent someone from bypassing it by modifying CODEOWNERS.

How: GitHub CODEOWNERS Example

# Default person in charge (must be placed at the front, subsequent rules override it)
* @octo-learner
# Documentation
/docs/ @octo-learner/docs-team
# Infrastructure and pipeline
/infra/ @octo-learner/platform
/.github/workflows/ @octo-learner/platform
# Dockerfile at any location
Dockerfile @octo-learner/platform
# CODEOWNERS itself
/.github/CODEOWNERS @octo-learner/platform

Teams cannot be used in personal account repositorys (@org/teamOnly applicable to organizations); in this lesson’s personal repository experiment, the owner is written as your username or collaborator’s username.

How: status check

  • GitHub:Required check match by name - GitHub Actions for<job name>, the reusable workflow is<job name > / < is called job name >, the others are check names; no distinction is made between workflow, matrix or trigger events. BepathsFilter skipped workflowsWill not report, PR will always display “Expected — Waiting for status to be reported”.
  • Azure Repos: When building a verification strategy, you can set up path filtering - when there is no matchPolicy does not apply(will not get stuck); external services are published using the PR Status APIgenre/namestatus, and then use the "Status checks" policy to set it to required.

When

Enable when there are more than 2 teams, the repository contains infrastructure or pipeline code, or there are compliance requirements. At very large scale CODEOWNERS should be kept coarse-grained (directory level) to avoid pulling in a dozen reviewers per PR.

Common misunderstandings① "If you write it in CODEOWNERS, it will be forced" - onlyautomatic requestReview must be turned on "Require review from Code Owners" in the ruleset to be mandatory. ② "You can add permissions to yourself by changing CODEOWNERS in the function branch" - the files on the target branch will take effect. ③ "!"Subdirectories can be excluded" - GitHub does not support it; override it with more specific rules later (you can write a rule without an owner to mean "no responsible person"). ④ "Azure path filtering"infra/*can also match" - not/Or the path starting with a wildcard character is invalid.

For the same PR, reviewer calculations on both platforms

PR change filedocs/redis.mdinfra/main.tfapp/Dockerfile GitHub: Get the last match for each file docs/redis.md → /docs/ → docs-teaminfra/main.tf → /infra/ → platformapp/Dockerfile → Dockerfile → platform Azure: Each policy is independently judged as to whether it is applicable. Policy A /docs/* → docs group (applies)Policy B /infra/*;*/Dockerfile → platform group (applicable)Policy C /db/* → DBA (not applicable, does not appear) Requires: docs-team + platformAt least one person from each group approves(When Code Owners review is turned on) Required: docs group + platform group+ Minimum reviewer strategy(Each strategy is satisfied separately)
Figure 5-1 GitHub “last match takes effect” on a file basis; Azure determines whether it is applicable on a policy basis

The "ghost wait" of status checks

PR only changed docs/The rule requires checking test ci.yml: paths: app/**Workflow does not trigger test always ExpectedPR cannot be merged RepairThe workflow is always triggered,Quickly succeed after judging changes within the job(Azure: Path filtering makes the policy not applicable)
Figure 5-2 GitHub required check + workflow path filtering = wait forever

CODEOWNERS matcher: enter the path and see who is responsible

Edit CODEOWNERS on the left (supports*、**、?, beginning/anchor, ending/directory), with one change file per line on the right. The matcher scans line by line and gives the responsible person according to "last match takes effect", while marking the ignored unsupported syntax (!、[ ]). The equivalent Azure Repos path filtering is shown below.

Click Match.

command

commandfunctionDescription
gh api repos/{owner}/{repo}/codeowners/errorsList CODEOWNERS syntax/owner errorsCheck in CI before merging
gh pr view --json reviewRequests,reviewDecisionView automatically requested reviewers and review conclusionsREVIEW_REQUIRED / APPROVED
az repos policy required-reviewer create --path-filterAzure required reviewers by path;separate multiple paths,!exclude
az repos policy build create --path-filterBuild is only required when the relevant paths changePolicy does not apply when there is no match
gh api …/rulesets(required_status_checks)Set up GitHub required checkscontext= check name
cd ~/git-lab/myapp && git switch main && git pull github main
git switch -c chore/codeowners
mkdir -p .github infra && echo 'terraform {}' > infra/main.tf
cat > .github/CODEOWNERS <<EOF
*                    @$GH_OWNER
/infra/              @$GH_OWNER
/.github/CODEOWNERS  @$GH_OWNER
EOF
git add . && git commit -m "Add CODEOWNERS and infra skeleton"
git push -u github chore/codeowners && gh pr create --fill --base main
gh api "repos/$GH_OWNER/myapp/codeowners/errors" --jq '.errors'
https://github.com/octo-learner/myapp/pull/3
[]
# Azure equivalent configuration: /infra/ Reviewers equivalent to CODEOWNERS (the /infra/* policy has been created in M3, append the Dockerfile here)
az repos policy required-reviewer create --repository-id $REPO_ID --branch main --blocking true --enabled true \
  --path-filter "/infra/*;*/Dockerfile;!/infra/README.md" --required-reviewer-ids "you@contoso.com" \
  --message "The platform group is responsible for infra and Dockerfile"

How to verify:The "Code owner" mark appears in the Reviewers column of GitHub PR; the corresponding group appears in the Required reviewers of Azure PR.Common mistakes:A user without write permission is written in CODEOWNERS.codeowners/errorsWill return "Unknown owner".

Experiment 5: Two platforms implement the same set of directory managers (about 7 minutes)

GitHub: Execute the first paragraph of "command" paging and merge the PR (gh pr merge --squash --delete-branch)。
Enable Code Owners enforcement(The actual effect only works when you have a second account; when you are single, you are the owner and the author, and cannot self-publish):
RS=$(gh api "repos/$GH_OWNER/myapp/rulesets" --jq '.[] | select(.name=="protect-main") | .id')
gh api "repos/$GH_OWNER/myapp/rulesets/$RS" | jq '{name,target,enforcement,conditions,bypass_actors,rules} | .rules |= map(if .type=="pull_request" then .parameters.require_code_owner_review=true else . end)' > rs3.json
gh api -X PUT "repos/$GH_OWNER/myapp/rulesets/$RS" --input rs3.json --jq '.rules[]|select(.type=="pull_request")|.parameters.require_code_owner_review'
Azure Repos: Execute the second paragraph of "Command" paging; then create a modificationinfra/main.tfFor a PR, check that “Required reviewers” appears in the policy list:
git switch -c infra/tweak azure/main 2>/dev/null || git switch -c infra/tweak
mkdir -p infra && echo '# tweak' >> infra/main.tf && git add infra && git commit -m "Tweak infra"
git push -u azure infra/tweak
PR2=$(az repos pr create -r myapp -s infra/tweak -t main --title "Tweak infra" --query pullRequestId -o tsv)
az repos pr policy list --id $PR2 --query "[].configuration.type.displayName" -o tsv
Minimum number of reviewers
Work item linking
Comment requirements
Require a merge strategy
Required reviewers
Clean up this PR:az repos pr update --id $PR2 --status abandoned;git switch main。

Case 1: Someone modified the CI workflow to steal secrets

Question:Modifications in PR by external contributors.github/workflows/, trying to print secrets in the deployment task.Method:CODEOWNERS/.github/workflows/ with /.github/CODEOWNERSHanded over to the platform team, the rule set requires Code Owners review; the workflow of the fork PR does not have access to the repository secret (Lesson 5).Limitations:CODEOWNERS only merges, regardless of the workflow running on the PR, and needs to cooperate with "Require approval for fork workflows".

Case 2: monorepo pulls 15 reviewers per PR

Question:CODEOWNERS is written to the file level, and PRs for cross-module refactoring require approval by more than a dozen teams.Method:Change to directory-level coarse-graining, and set up a "any core maintainer" team for the shared directory; large refactorings are split into multiple PRs.Limitations:The coarser the granularity, the fuzzier the responsibilities and the need for modularization (Lesson 6).

Case 3: Lost path reviews for Azure after migrating to GitHub

Question:GEI migrates branching policies, but Azure's "Automatically include reviewers + paths" requires CODEOWNERS file expressions on GitHub.Method:Used before migrationaz repos policy listExport all required-reviewer policies and scripts into CODEOWNERS lines (note the order: more specific ones come last) as part of the migration PR.Limitations:Azure!Exclusions need to be rewritten into more specific coverage rules.

Common errors and solutions

CODEOWNERS: Unknown owner on line 3: make sure @org/platform exists and has write access to the repository

Reason:The team does not exist, is not visible, or does not have explicit write permission (even if individual members have permission).

Fix:Settings → Collaborators and teams Write to the team;gh api repos/O/R/codeowners/errorsReview.

PR does not automatically request code owner review

Reason:CODEOWNERS is not on the target branch; the file exceeds 3 MB; it is placed in the fourth location (only recognizes.github/, root,docs/); matches are overridden by subsequent rules for others.

Fix:Merge CODEOWNERS into main first, then open a new PR; use this module's "animation" matcher to check the order.

Review required: At least 1 approving review is required by reviewers with write access. Waiting on code owner review from platform.

Reason:Code Owners review is turned on and the owner has not approved it; the author himself is never satisfied when he is the sole owner.

Fix:Configure a team of at least two people as owners for the critical path.

Azure: Required reviewers policy does not take effect (PR only changed infra/main.tf)

Reason:Path filtering is written asinfra/*(Not with/begins, ignored), or excluded!Putting it at the front causes nothing to match.

Fix:Change to/infra/*;Include first, exclude later.

Command line operation questions
1. Use a command to check CODEOWNERS for errors.
gh api repos/OWNER/REPO/codeowners/errors --jq '.errors[] | "\(.line): \(.message)"'
2. Request platform group review in Azure Repos/infra/Download all files except README.
az repos policy required-reviewer create --repository-id $REPO_ID --branch main --blocking true --enabled true \
  --path-filter "/infra/*;!/infra/README.md" --required-reviewer-ids "platform@contoso.com"
Scenario analysis questions
The first line of CODEOWNERS is written/infra/ @platform, the last line is written* @everyone-team. Why does infra’s PR no longer request platform?

The last match takes effect:*Matches all files, overwriting the previous ones/infra/. Default rules must be placed first, with more specific rules placed later.

Verified instructional videos

No verified CODEOWNERS/Azure automatically includes reviewer feature video found, please use official documentation and storyboards.

Official documentation

Video storyboard (approx. 75 seconds)

This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Screen: Repository directory tree, with team avatars attached to the three folders infra, docs, and workflows respectively.
Narrator: CODEOWNERS maps catalogs to responsible persons and automatically requests their review as soon as a PR is opened.
Shot 2 · 20–45s
Screen: The CODEOWNERS file is scanned from top to bottom, and the last matching line is highlighted.
Narrator: When multiple rules match the same file, the last one takes effect, so the default rule should be written first.
Shot 3 · 45–75s
Screen: "Required reviewers: platform group" appears on the Azure PR page; "Waiting on code owner review" appears on GitHub PR.
Narrator: Azure achieves the same effect with automatic inclusion of reviewers plus path filtering; both sides have to make it required to actually prevent the merge.
or score ≥ 70% on the Quiz

Module 6 · Fork, Template Repository and Inner Source

38:00 – 45:00 · When to copy history, when to copy only the starting point, and when not to copy at all
7 minutesGitHub fork / template · Azure Repos fork★★★
learning objectives
  • Distinguish between clone, fork, template repository, and mirror: who owns the new repository, whether the history is the same, and whether the relationship with the upstream is maintained.
  • use gh repo fork / gh repo sync / upstreamComplete "fork → synchronize upstream → cross-repository PR" remotely; understand the fork of Azure Repos in the same organization.
  • Use a template repository to provide a standard starting point for new services (CODEOWNERS, rule descriptions, CI, PR templates); understand the governance elements of Inner Source.
Importance:★★★

What: Four kinds of "copying"

cloneforkTemplate repository generationmirror(M8)
where is the resultyour local machineA new repository belonging to you/your organization on the platformNew repository on the platformAnother platform/repository
historyexactly the sameIdentical (Shared Object Network)A new history(Single initial commit), with only the default branch by default, optionally including all branchesIdentical, including all references
Relationship with upstreamorigin remoteThe platform records the fork relationship, can send PR to the upstream, and synchronize with one clickNo relationship (only "generated from" is displayed)No platform relationship, needs regular synchronization
Permissions—Fork owner control; private repository forks inherit upstream access controlNew repository owner controlstarget platform control
Typical scenarioDaily developmentOpen source contribution; contribute to internal repository without write accessNew service scaffoldingMigration, disaster recovery, cross-platform synchronization

Why

Within the company,If you have write permission, use the branch instead of forking.: Fork will generate a large number of repository copies, and CI, secrets, and rule sets must be configured repeatedly. fork suitableContributor does not have write permission(Open source, cross-sector Inner Source). The template repository solves the problem of "each new repository must re-configure CODEOWNERS, PR templates, and CI", but subsequent updates to the templateNoAutomatically spread.

How: platform details

  • GitHub fork: Anyone can fork a public repository; forks in private/internal repositories are controlled by organizational policies (can be prohibited), and access to private forks is inherited from the upstream; when the upstream private repository is deleted, its private fork is also deleted. Push rule sets apply to the entire fork network. The workflow in fork PR cannot get upstream secrets by default.
  • sync: webpage "Sync fork", orgh repo sync OWNER/FORK(sync default branch), or localgit fetch upstream && git rebase upstream/main。
  • Azure Repos fork: Can be forked tosame organizationAny project within; send a PR from the fork to the upstream; synchronization requires adding the upstream remote pull locally and then pushing it to the fork.
  • Template repository: Check “Template repository” in GitHub repository settings (gh repo edit --template), aftergh repo create NEW --template OWNER/TPL. Azure Repos does not have a template repository function, usually script +az repos importOr a cookiecutter tool.

When: Inner Source (internal open source)

  • Visibility: GitHub EnterpriseinternalVisibility makes it readable and forkable by all members of the enterprise; Azure DevOps can give read permission to everyone in the organization.
  • Entry file:README.md、CONTRIBUTING.md(How to commit PR, local development, review SLA),CODEOWNERS, Issue/PR template (.github/pull_request_template.md, Azure.azuredevops/pull_request_template.md)。
  • Role: Trusted committers are responsible for review and merging; contributors commit through forks or restricted branches.
  • Metrics: Number of external PRs, first response time, merge cycle.
Common misunderstandings① "Fork is an independent copy, it doesn't matter if you delete the upstream." - The fork of a private repository depends on the upstream. ② "After the template is updated, the generated repository will be synchronized" - No, template generation is one-time. ③ "It is safer for everyone in the company to fork and commit PR" - with write permissions, this will only increase maintenance costs, and the rule set can already protect main. ④ "The fork's PR can be deployed using the upstream secrets" - it cannot be used by default.

fork triangle workflow

upstream upstreamorg/myapp (rule set protects main) fork originyou/myapp (you have write permission) local cloneremotes: origin + upstream ① fork (platform side copy) ③ git fetch upstream ④ git push origin feature/x ⑤ PR:you:feature/x → org:main ② git clone origin
Figure 6-1 fork workflow: clone from fork, push to fork, send PR to upstream, synchronize from upstream fetch

Historical relationship: fork vs template

template tplA → B → C forkA → B → C → D (share the same SHA and can be directly PRed back to the upstream) Template generationX (single "Initial commit", content = tree of C, but different SHA, no common ancestor with tpl) Therefore: the repository generated by the template cannot send PR to the template, nor can it git merge subsequent updates of the template (refuse to merge unrelated histories will be reported)
Figure 6-2 Fork retains history and relationships; the template generates a new history with no common ancestors

Demonstration: Comparison of results of four replication methods

Choose an operation and play: observe which repositorys appear on the platform, whether the committed SHA is the same, how the remote end is configured, and whether it can send a PR to the upstream later.

Play after selecting the action.

command

commandfunctionKey parameters
gh repo fork OWNER/REPO --clone --remotefork and clone, automatically setupstream--orgfork to organization;--fork-name
gh repo sync OWNER/FORKThe platform side synchronizes the fork default branch with the upstream--branch、--force(Discard forked commits on fork)
git remote add upstream URL + git fetch upstreamLocal sync upstreamgit rebase upstream/main
gh pr create --repo UPSTREAM --head you:branchSend PR from fork to upstreamBy default, the target repository will be asked
gh repo edit --templateSet repository as template—
gh repo create NEW --template OWNER/TPLGenerate from template--include-all-branches、--clone
# Set myapp as a template and generate a new service repository
gh repo edit "$GH_OWNER/myapp" --template
gh repo create "$GH_OWNER/orders-svc" --template "$GH_OWNER/myapp" --public --clone
cd orders-svc && git log --oneline
✓ Created repository octo-learner/orders-svc on GitHub
1f0e2d3 (HEAD -> main, origin/main) Initial commit
# Azure Repos: On the web page Repos → … → Fork, select the target project and name; then
git clone "$ADO_ORG/$ADO_PROJECT/_git/myapp-fork" && cd myapp-fork
git remote add upstream "$ADO_ORG/$ADO_PROJECT/_git/myapp"
git fetch upstream && git rebase upstream/main && git push origin main

Experiment 6: fork → synchronize upstream → cross-repository PR (about 7 minutes)

Fork requires "another owner": fork myapp into the free org you created in module 0<you>-gitlab-lab(Or conversely, put upstream in the organization).

fork and clone:
export LAB_ORG=octo-learner-gitlab-lab
cd /tmp && gh repo fork "$GH_OWNER/myapp" --org "$LAB_ORG" --clone --remote --fork-name myapp
cd myapp && git remote -v
origin    https://github.com/octo-learner-gitlab-lab/myapp.git (fetch)
origin    https://github.com/octo-learner-gitlab-lab/myapp.git (push)
upstream  https://github.com/octo-learner/myapp.git (fetch)
upstream  https://github.com/octo-learner/myapp.git (push)
Go one step upstream and then synchronize the fork:
(cd ~/git-lab/myapp && git switch -c docs/contrib && printf '# Contributing\nPlease commit via PR.\n' > CONTRIBUTING.md && git add . && git commit -m "Add CONTRIBUTING" && git push -u github docs/contrib && gh pr create --fill --base main && gh pr merge --squash --delete-branch)
gh repo sync "$LAB_ORG/myapp"
git pull origin main && git log --oneline -1
Send PR from fork to upstream:
git switch -c feature/contrib-typo
echo "Contributions welcome." >> CONTRIBUTING.md && git commit -am "Improve CONTRIBUTING"
git push -u origin feature/contrib-typo
gh pr create --repo "$GH_OWNER/myapp" --head "$LAB_ORG:feature/contrib-typo" --base main --fill

You can see "wants to merge 1 commit into octo-learner:main from octo-learner-gitlab-lab:feature/contrib-typo" on the upstream PR page. Can be merged or closed.

clean up:gh repo delete "$LAB_ORG/myapp" --yes、gh repo delete "$GH_OWNER/orders-svc" --yes(need firstgh auth refresh -s delete_repo);rm -rf /tmp/myapp。

Case 1: Inner Source of Internal Platform Library

Question:The platform team's shared log library has only three maintainers, and each business team queues up other functions.Method:The repository is changed to internal and visible, CONTRIBUTING and PR templates are written, CODEOWNERS specifies the trusted committer team, and the business team forks and then commits PR; the rule set requires Code Owners review and CI.Limitations:SLAs need to be clearly reviewed, otherwise external PR backlogs will dampen willingness to contribute.

Case 2: Microservice scaffolding drift

Question:40 services were generated from the same template. The template later fixed the Dockerfile security issue, but no one followed up on the old services.Method:The template only contains the "starting point", and the evolving parts are extracted into reusable workflows/basic images/shared CI templates (Lesson 5), and updates are pushed by Dependabot/Renovate.Limitations:The template generation repository and the template have no common ancestor, and template updates cannot be merged.

Case 3: Forks in Azure Repos are abused

Question:Developers are used to forking and then committing PRs, resulting in hundreds of fork repositories in the project, and permissions must be configured for each one.Method:Members with Contribute permissions use branches instead; branch-level permissions restrict only creationusers/<name>/* with feature/*; fork is reserved only for cross-project contributions.Limitations:Forks of Azure Repos are limited to the same organization.

Common errors and solutions

fatal: refusing to merge unrelated histories

Reason:Attempts to merge updates from the template repository into the repository generated by the template (which has no common ancestor).

Fix:Do not merge history; migrate manually orgit cherry-pick;When it is really necessary to merge--allow-unrelated-histories(It will create a lot of conflicts and is not recommended).

! [rejected] main -> main (fetch first) (when pushing to its own fork)

Reason:The fork's main has advanced through web Sync, and the local one has fallen behind.

git pull --rebase origin main && git push origin main
gh repo sync: can't sync because there are diverging changes

Reason:The default branch of the fork has commits that are not available upstream.

Fix:Move these commits behind the feature branchgh repo sync --force;Do not commit directly on the fork's main in the future.

The Fork button is gray: Forking is disabled for this repository

Reason:The organization prohibits forking of private/internal repositories.

Fix:Request write permission and use the fork, or ask an administrator to allow forking in the organization settings.

Command line operation questions
1. You have a local clone of the fork, but no upstream remote. How to synchronize the updates of upstream main to fork?
git remote add upstream https://github.com/ORG/REPO.git
git fetch upstream && git switch main && git merge --ff-only upstream/main && git push origin main
2. Generate a private repository from the template that contains all branches of the template.
gh repo create ORG/new-svc --template ORG/tpl --private --include-all-branches
Scenario analysis questions
The outsourcing team needs to contribute code to the internal repository, but cannot see other repositorys and cannot directly change main. Do you recommend forking or branching?

If you give the outsourcing account the Write permission of a single repository, use branch + rule set (requires review by PR and Code Owners), which is the simplest management. If it can only be read (or if you want contributions to be completely isolated), use the fork workflow: outsource development in the fork and issue a PR to the upstream; note that the organization must allow fork private repositorys, the fork inherits upstream access control, and the workflow of the fork PR cannot obtain confidentiality.

Verified instructional videos

▶
Git Tutorial for Beginners: Learn Git in 1 Hour — Programming with Mosh
English · Review the concepts of remote, clone and branch (fork/template shall be subject to this lesson)

Official documentation

Video storyboard (about 70 seconds)

This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Screen: The three nodes of the upstream repository, fork, and local form a triangle, and the arrows light up in sequence.
Narrator: The fork workflow is a triangle: clone from the fork, push to the fork, and then send a Pull Request to the upstream.
Shot 2 · 20–45s
Screen: The template repository is stamped to generate a new repository, and the new repository has only one initial commit.
Narrator: The template only copies the starting point, not the history. After that, both sides go their separate ways.
Shot 3 · 45–70s
Screen: Developers with write permissions within the company branch, and external contributors fork.
Narrator: Use branches if you have write permissions; use forks only when you don’t have write permissions and need to be isolated.
or score ≥ 70% on the Quiz

Module 7 · Practical troubleshooting on the platform side

45:00 – 54:00 · First check which level the error report belongs to, and then check which level - don’t delete credentials or turn off SSL verification right away.
9 minutesGIT_TRACE / GCM_TRACE / ssh -v★★★★★
learning objectives
  • Common platform errors are classified into five levels: transmission (DNS/proxy/TLS/SSH host key) → authentication (401) → authorization (403/SSO) → rule evaluation (GH013/GH006/TF402455/push protection) → storage limit (large file/push size/path length).
  • Proficient in using diagnostic switches:GIT_TRACE=1、GIT_TRACE_CURL=1、GCM_TRACE=1、GIT_SSH_COMMAND="ssh -vT"、git credential fill。
  • Correct handling of: GCM caching bad credentials, host key changes, large file rejections (LFS), push protection hit secrets, enterprise TLS inspection and proxies.
Importance:★★★★★

What: Five levels and corresponding symptoms

levelTypical error report (original text)First diagnostic command
Transport: DNS/NetworkCould not resolve host: github.com、Failed to connect … port 443、Connection timed out(SSH 22)curl -sSI https://github.com、nslookup
transport:proxyReceived HTTP code 407 from proxy after CONNECTgit config --get-regexp 'http.*proxy'、env | grep -i proxy
Transport: TLSSSL certificate problem: unable to get local issuer certificate、self-signed certificate in certificate chainGIT_TRACE_CURL=1 git ls-remote …、openssl s_client -connect github.com:443 -showcerts
Transport: SSH host keyWARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!、Host key verification failed.ssh-keygen -F github.com、ssh-keygen -lf ~/.ssh/known_hosts
Certificationfatal: Authentication failed for …、Permission denied (publickey)、Support for password authentication was removedgit credential fill、ssh -vT
Authorizeremote: Permission to O/R.git denied to USER. + 403;has enabled or enforced SAML SSO;TF401019;Repository not found(GitHub also returns 404 for private repositories without permission)gh auth status、GIT_TRACE_CURL=1Look at users
Rule evaluationGH013、GH006、TF402455、TF401027, push protectionPush cannot contain secretsgh ruleset check BRANCH、az repos policy list
storage limitGH001: Large files detected、this exceeds GitHub's file size limit of 100.00 MB、VS403729(path too long), Azure push exceeds 5 GBgit rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectsize) %(rest)' | sort -k2 -n | tail

Why: The most common incorrect operations

  • Delete credentials when rule rejects: Invalid (see M2 Core Animation).
  • git config --global http.sslVerify false: Turn off all HTTPS verification, which is equivalent to allowing man-in-the-middle attacks. The correct approach is to add the enterprise root CA to the trust (http.sslCAInfo, or on Windowshttp.sslBackend schannelusing the system certificate store).
  • Delete it directly when the host key is changedknown_hosts: The official fingerprint should be checked first (GitHub changed the RSA host key on 2023-03-24, and that warning was normal; other times it may be an attack).
  • Commit a "delete large file" commit after the large file is rejected: The large file is still in the history, the push is still rejected, and the unpushed history must be rewritten.

How: GCM cached bad credentials

Symptoms: Always use old account/revoked token,403or401Appears repeatedly and does not log in. Reason: GCM only returns on server401timeerase;If the token is valid but belongs to the wrong account, the server returns403, GCM will not delete it. Fix:git credential reject(orgit credential-manager github logout USER、azure-repos clear-cache, Windows Credential Manager removalgit:https://github.com), then useuseHttpPathDifferentiate between multiple accounts.

When: Troubleshooting order

  1. read fullremote:line and lastfatal:/!OK.
  2. git ls-remoteCan it succeed? Can → Problem with authorization/rules/size; Cannot → Transport/Authentication.
  3. Open the corresponding trace and only look at that level.
  4. After repair, verify with minimal operations (ls-remote/ push the temporary branch).
Common misunderstandings① "404 Repository not found = The repository was deleted" - GitHub returns 404 for unauthorized access to private repositories, often because the account is incorrect. ② "Enlargehttp.postBuffer"solves all push failures" - almost never the root cause. ③ "The push protection is blocked, I just click bypass on the webpage" - Fake secrets are OK, but real secrets should be unrotated and deleted from history.

Troubleshooting funnel: locating checkpoints from error reports

Is git ls-remote successful? No → Transport/Authentication | Yes → Authorization/Rules/Storage Transport: DNS · Proxy 407 · TLS Certificate · SSH 22 Blocked · Host Key Authentication 401: Bad/Expired Token · Password · SSH Public Key Not Enrolled · Azure First Key Authorization 403/404: No write permission · Token scope · SAML SSO · Bad account Rules: GH013 · GH006 · TF402455 · Push Protection Storage: GH001 Large files · push size · path length
Figure 7-1 Exclude layer by layer from outside to inside

Large files rejected: why deleting commits is not enough

A (existing at the remote end) B add big.bin 150MB C Delete big.bin push A..C's pack still contains B's blob → GH001 rejected Fix: git rebase -i A, drop/modify B (or git lfs migrate import) History pushed to remote → Lesson 7 git filter-repo pre-receive checks all objects introduced by this push, not just the latest tree
Figure 7-2 The rule checks objects within the entire push range

Error original text classifier

Paste the error report in the terminal (or click on the example), the classifier will judge which level it belongs to based on the characteristics of the real error report, and give the first diagnostic command and repair direction. Rules are only matched locally in the browser and nothing is sent.

Waiting for input.

Diagnosis and repair commands

commandfunction
GIT_TRACE=1 GIT_TRACE_CURL=1 git ls-remote URLLook at the HTTP status code and which credential helper was called
GCM_TRACE=1 git fetch / git credential-manager diagnoseGCM detailed log/environment diagnostic report (network, agent, storage)
git config --show-origin --get-all credential.helperWhich assistants and from which configuration file (system-level Git for Windows will also be configured)
ssh-keygen -R github.comDelete old host keys in known_hosts (check official fingerprint first)
git config --global http.sslCAInfo /path/corp-ca.pemTrust enterprise root certificate (append to CA bundle)
git config --global http.sslBackend schannelWindows: Use the system certificate store
git config --global http.https://dev.azure.com.proxy http://proxy:8080Set proxy by host
git lfs migrate import --include="*.bin" --include-ref=refs/heads/featureConvert large files in unpushed history to LFS pointers
# 1) Host key change: update after verification
ssh-keygen -R github.com
curl -fsSL https://api.github.com/meta | jq -r '.ssh_keys[]' | sed 's/^/github.com /' >> ~/.ssh/known_hosts
ssh-keygen -lf ~/.ssh/known_hosts | grep github.com
256 SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU github.com (ED25519)
256 SHA256:p2QAMXNIC1TJYWeIOttrVc98/R1BUFWu3/LiyKgUfQM github.com (ECDSA)
3072 SHA256:uNiVztksCsDhcc0u9e8BujQXVUpKZIDTMczCvj3tD2s github.com (RSA)
# 2) Find the largest object within the push range
git rev-list --objects github/main..HEAD | git cat-file --batch-check='%(objecttype) %(objectsize) %(rest)' \
  | awk '$1=="blob"{printf "%.1f MB %s\n", $2/1048576, $3}' | sort -n | tail -5
# 3) Enterprise TLS check: Confirm who issued the certificate
openssl s_client -connect github.com:443 -servername github.com </dev/null 2>/dev/null | openssl x509 -noout -issuer -subject
issuer=CN = Contoso Corp TLS Inspection CA
subject=CN = github.com

Experiment 7: Deliberately create 4 glitches and fix them (about 9 minutes)

Failure 1: GCM cached incorrect credentials——Manually save a fake credential and automatically erase it after observing 401:
printf 'protocol=https\nhost=github.com\nusername=x\npassword=ghp_invalidtoken000000000000000000000000\n\n' | git credential approve
cd ~/git-lab/myapp && GIT_TRACE=1 git ls-remote github 2>&1 | grep -E "credential|401|Authentication" | head

Expectation: See first401,Git callcredential reject(erase), then GCM pops up the login or reportAuthentication failed. Restore after logging in again.

Fault 2: Host key mismatch(simulation):
cp ~/.ssh/known_hosts ~/.ssh/known_hosts.bak
sed -i 's/^github.com ssh-ed25519 .*/github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFakeFakeFakeFakeFakeFakeFakeFakeFakeFakeFake/' ~/.ssh/known_hosts
ssh -T git@github.com 2>&1 | head -3
mv ~/.ssh/known_hosts.bak ~/.ssh/known_hosts && ssh -T git@github.com
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Failure 3: Large files rejected(On the feature branch, does not affect main):
git switch -c test/bigfile github/main
head -c 110M /dev/urandom > big.bin && git add big.bin && git commit -m "Add big file"
git push github test/bigfile 2>&1 | grep -E "GH001|exceeds|rejected"
remote: error: File big.bin is 110.00 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
 ! [remote rejected] test/bigfile -> test/bigfile (pre-receive hook declined)
git reset --hard HEAD~1 && git switch main && git branch -D test/bigfile # Fix: Remove from unpushed history
# If you really need versioning: git lfs install && git lfs track "*.bin" and then commit
Fault 4: Rule Deny vs Authentication: Repeat step 3 of the M4 experiment to get GH013, and then executeprintf 'protocol=https\nhost=github.com\n\n' | git credential fill | grep username, confirm that the credentials are intact - do not delete them.
interactive troubleshooting tree: Go to the "Troubleshooting" page and use the troubleshooting tree to go through the above four scenarios to see if they are consistent with your judgment.

Case 1: A sudden SSL certificate problem occurred across the company

Question:Security team launches TLS inspection proxy for all developersgit fetchnewspaperunable to get local issuer certificate, someone recommended it on wikisslVerify false。Method:Windows Unificationhttp.sslBackend schannel(The enterprise root certificate has been issued through group policy); Linux/macOS adds the root certificate to the system CA and updates the packages used by Git; and negotiates with the security team to exempt github.com / dev.azure.com from inspection.Limitations:TLS inspection can break GCM's OAuth flow and certificate pinning tools.

Case 2: The token of the resigned employee is still on CI

Question:After an employee resigned, his PAT expired, and more than a dozen assembly lines401。Method:Short-term switch to service accounts/GitHub App tokens; long-term switch to OIDC vs. Managed Identity (Lesson 5); inventory all where personal credentials are used for automation.Limitations:Azure DevOps audit logs do not record token usage and need to be inventoried from the pipeline configuration side.

Case 3: Push protection blocked the “token” in the test data

Question:There is a string that looks like an AWS key in the unit test fixture, and push isGH013 … Push cannot contain secretsRefuse.Method:After confirming that the data is false, follow the prompts on the web page and select "It's used in tests" to bypass (leave auditing) and instead dynamically generate false values during the test; if it is truly confidential, immediately cancel it and rewrite history according to Lesson 7.

Interactive troubleshooting tree: push/clone failed

Supplement: Common mistakes

fatal: unable to access 'https://github.com/…': Received HTTP code 407 from proxy after CONNECT

Reason:Agents require certification.

Fix:Use a proxy configuration that supports integrated authentication, orhttp.proxyAuthMethod;Do not write the proxy password in clear text into the global configuration; GCM also followshttp.proxy。

remote: The 'contoso' organization has enabled or enforced SAML SSO. To access this repository, you must use the HTTPS remote with a personal access token or SSH with an SSH key and passphrase that has been authorized for this organization.

Reason:The token/SSH key is not authorized for SSO to this organization.

Fix:GitHub → Settings → SSH keys / Tokens → Configure SSO → Authorize; orgh auth refreshThen complete SSO in the browser.

Host key verification failed. (SSH clone in CI)

Reason:The non-interactive environment does not have known_hosts and cannot confirm the fingerprint.

Fix:Preset official known_hosts (available on GitHub fromapi.github.com/metaget),Don'tuse StrictHostKeyChecking=no。

remote: error: GH013: … - GITHUB PUSH PROTECTION … Push cannot contain secrets

Reason:Push protection detected a token of a known format in the commit of this push.

Fix:True Secret: Undo → Remove from unpushed history (git rebase -i / commit --amend) → Re-push; Fake data: Press the link in the message to select the reason to bypass.

Command line operation questions
1. One command to see which credential helpers are actually used by Git and the configuration source.
git config --show-origin --get-all credential.helper
2. List files larger than 50 MB in local commits that have not yet been pushed.
git rev-list --objects @{u}..HEAD | git cat-file --batch-check='%(objecttype) %(objectsize) %(rest)' | awk '$1=="blob" && $2>52428800 {print $2, $3}'
Scenario analysis questions
Windows users: personal project push is normal on the same computer, and the repository organized by the company's GitHub403, the login popup never pops up. What is your order of investigation?

①GIT_TRACE_CURL=1Confirm that it is 403 (Authorization) rather than 401; ②git credential fillLook at the username returned by GCM - most of them are personal accounts; ③GCM will not delete credentials due to 403, so there will be no pop-up window; ④git credential-manager github loginLog in to your company account and set upcredential.https://github.com.useHttpPath trueDistinguish by path; ⑤ If the company organization enables SAML SSO, complete SSO authorization in the browser.

Verified instructional videos

▶
13 Advanced (but useful) Git Techniques and Shortcuts — Fireship
English · Involves amend, interactive rebase and other techniques for repairing unpush history (the platform error reporting section shall be subject to this lesson)

Official documentation

Video storyboard (about 80 seconds)

This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Screen: Five-layer funnel, error cards fall from above and fall into the corresponding layer.
Narrator: Every error report belongs to a certain layer in transport, authentication, authorization, rules, or storage.
Shot 2 · 20–50s
Screen: Terminal 401 → Credentials erased; 403 → Credentials retained, GCM does not pop up.
Narrator: 401 will cause Git to erase the credentials, but 403 will not; so you need to manually clear the credentials for the wrong account.
Shot 3 · 50–80s
Screen: The red "sslVerify false" is crossed out and replaced with "Add Enterprise Root Certificate".
Narrator: When you encounter a certificate error, trust the correct root certificate instead of turning off verification.
or score ≥ 70% on the Quiz

Module 8 · Migration, Costs and Self-Testing

54:00 – 60:00 · History and tags cannot be missing; branch protection, PR and pipeline must be moved separately
6 minutesclone --mirror / push --mirrorGEI:ADO → GHEC★★★★
learning objectives
  • use git clone --mirror+ Explicit refspec push, migrate between Azure Repos ↔ GitHubAll branches and tags, to avoid platform hidden references (refs/pull/*); migrate LFS objects.
  • use git for-each-refCompare the references on both sides to prove that the migration is complete.
  • Know what Git won't move: PRs and comments, branch policies/rule sets, work items, pipelines, webhooks, permissions - and what the platform import tools (Azure Import repository, GitHub Importer, GitHub Enterprise Importer) can move.
  • Estimate the cost of both platforms and determine whether the free tier is sufficient.
Importance:★★★★

What: Three layers of migration

layercontentTools
Git dataAll commits, branches, tags (including note tag objects), notesgit clone --mirror + git push;Azure “Import repository”;GitHub Importer (web, Git sources only)
large filesLFS object (not in Git object library)git lfs fetch --all + git lfs push --all
Platform metadataPRs and comments, branching policies/rule sets, work item links, permissions, webhooks, pipelinesGitHub Enterprise Importer(GEI): Azure DevOps Services → GitHub Enterprise Cloud, which can migrate Git sources, PRs (including user history, work item links, attachments) and repository branch policies (excluding user-level and cross-repository policies),Pipeline and LFS objects are not migrated; 40 GiB limit for repository (public preview), 400 MiB per file during migration, 2 GiB per push; does not support Azure DevOps Server. The rest can only be rebuilt using scripts or manually.

Why: Why not use ordinary clone

Ordinarygit cloneOnly build the default branch locally, other branches arerefs/remotes/origin/*;git pushBy default, only the current branch is pushed.--mirrorClone into a bare repository and putAll remote referencesmapped to local(+refs/*:refs/*), sopush --mirrorCan push all branches and tags at once - and willDeleteA reference that is not local to the target.

How: Hide reference traps

  • from GitHubmirror clone will getrefs/pull/*/head(and possiblymerge). Pushing to GitHub will be rejected:! [remote rejected] refs/pull/1/head -> refs/pull/1/head (deny updating a hidden ref); Pushed to Azure Repos, it will become a bunch of ordinary references.
  • from Azure ReposMirror clone may be obtainedrefs/pull/*/mergeand other platform references.
  • Therefore production migration is recommendedPush only branches and tags:git push TARGET 'refs/heads/*:refs/heads/*' 'refs/tags/*:refs/tags/*';or delete firstrefs/pull/*Againpush --mirror。
  • The target repository must beEmpty repository(do not check the Initialize README), and rulesets/policies on the target may deny push during migration (e.g. disallow creationrelease/*, file size rules)—migrate first, then configure protection.
  • Azure Repos has a single push limit of 5 GB, which can be exceeded by importing it through a web page; GitHub has a hard limit of 100 MiB for a single file. If there are large files in the history, you must firstgit lfs migrate(SHA will be rewritten, and all employees need to clone again).

When: Switching steps

  1. Freeze window: The source repository is set to read-only (Azure: disable repository or retract Contribute; GitHub: archive).
  2. The last mirror synchronization + verification.
  3. Rebuild protection (M3/M4/M5 comparison table), webhooks, pipelines, permissions on target.
  4. Developer git remote set-url origin NEW。
  5. The source repository remains read-only for a period of time and then deleted.

Cost (2026-11, subject to the official website)

free tierPayExperiment in this lesson
GitHubFree: Not limited to public/private repositorys; private repositorys have no branch protection/rule set/CODEOWNERS enforcement; Actions public repositorys are freePro (individual), Team, and Enterprise are billed by user/month (long-term price is about $4 / $4 / $21, subject to github.com/pricing)Free + public repository is enough
Azure DevOpsFree for the first 5 Basic users; free for Stakeholders but cannot access Repos; unlimited private repositories$6/Basic user/month beyond that; GHAzDO, parallel jobs additionalfree
Common misunderstandings① “push --mirror"It's very safe" - it will delete redundant references on the target, and pointing to the wrong target will erase other people's branches. ② "After the migration, the PR history is also there" - Git does not contain PR; only GEI (and only ADO Services → GHEC) can take away PR. ③ "Push the tag once--tagsJust fine" - make sure both the annotated tag object and the lightweight tag are present, and compare the SHAs.

Migrate data flow

Azure Repos myapprefs/heads/*refs/tags/*refs/pull/* (platform)PR · Strategy · Work Item clone --mirror Local bare repository myapp.gitfetch = +refs/*:refs/*Delete refs/pull/*git lfs fetch --allfor-each-ref snapshot push heads+tags GitHub myapp-migrated (empty)Branch and tag SHA are the samegit lfs push --allAfter: Rule Sets · CODEOWNERSActions · Webhooks · Permissions Verification: After sorting git ls-remote --heads --tags on both sides, the diff is empty
Figure 8-1 Mirror migration: only branches and tags are moved, and platform metadata is rebuilt separately.

Reverse synchronization and double-write risk

Source (read-only frozen) target (only write point) Scheduled fetch --prune + push heads/tags (one-way) Both sides can write at the same time + two-way synchronization = reference conflicts and lost commits; there can only be one writing point at any time
Figure 8-2 Maintaining a single write point during migration

Migration Verification Simulation + Cost Calculator

Migration simulation:Select the push method and compare the source and target reference lists after playback.

Play after selection.

cost calculator(Based on the 2026-11 official website pricing: GitHub Team $4, Enterprise $21/user/month; Azure DevOps first 5 Basics free, then $6/user/month; does not include Actions/Pipelines minutes, GHAS/GHAzDO and storage)

Migration command

commandfunction
git clone --mirror SRC myapp.gitBare repository, mapping all references
git for-each-ref --format='%(refname)' refs/pull | xargs -r -n1 git update-ref -dRemove platform PR reference
git push DST 'refs/heads/*:refs/heads/*' 'refs/tags/*:refs/tags/*'Only push branches and tags (recommended)
git push --mirror DSTPush all refs and delete redundant refs to target (cautionary)
git lfs fetch --all / git lfs push --all DSTMigrate LFS objects
git ls-remote --heads --tags URL | sort -k2Reference snapshot for comparison
gh repo archive/Azure:Repository settings Disable repositoryFreeze source repository
source ~/.gitlab-p3.env
SRC="$ADO_ORG/$ADO_PROJECT/_git/myapp"
gh repo create "$GH_OWNER/myapp-migrated" --public --description "migrated from Azure Repos"
DST="https://github.com/$GH_OWNER/myapp-migrated.git"

cd /tmp && rm -rf myapp.git && git clone --mirror "$SRC" myapp.git && cd myapp.git
git for-each-ref --format='%(refname)' | sed 's#/[^/]*$##' | sort | uniq -c
git for-each-ref --format='%(refname)' refs/pull | xargs -r -n1 git update-ref -d
git push "$DST" 'refs/heads/*:refs/heads/*' 'refs/tags/*:refs/tags/*'
git lfs ls-files --all 2>/dev/null | head -1 && { git lfs fetch --all; git lfs push --all "$DST"; } || echo "no LFS objects"
      3 refs/heads
      2 refs/heads/feature
      1 refs/pull/7
      2 refs/tags
...
To https://github.com/octo-learner/myapp-migrated.git
 * [new branch]      feature/healthz -> feature/healthz
 * [new branch]      main -> main
 * [new tag]         v0.1.0 -> v0.1.0
 * [new tag]         v0.2.0 -> v0.2.0
no LFS objects
# Verification: The references on both sides are completely consistent (diff passes if there is no output)
diff <(git ls-remote --heads --tags "$SRC" | sort -k2) <(git ls-remote --heads --tags "$DST" | sort -k2) && echo "REFS IDENTICAL"
git rev-list --all --count
REFS IDENTICAL
14

The reverse direction (GitHub → Azure Repos) is exactly the same, except that the source will bringrefs/pull/*/head;Target firstaz repos create --name myapp-from-gh。

Lab 8: Azure Repos → GitHub full migration and rebuild protection (~6 minutes)

Migrate: Execute the migration and verification sections of the "Command" page, seeREFS IDENTICAL。
Check the Notes tab:
git clone -q "$DST" /tmp/mig && git -C /tmp/mig cat-file -t v0.1.0 && git -C /tmp/mig show -s --format='%H %s' v0.1.0^{commit}
tag
1c2d3e4… Initial myapp
reconstruction protection: Execute the M4 rule set creation command for myapp-migrated (replace the repository name with myapp-migrated), and confirm that the CODEOWNERS files have been migrated with history:git -C /tmp/mig ls-files .github。
(optional) reverse:az repos create --name myapp-from-gh, return from GitHub mirror to Azure Repos, be careful to deleterefs/pull/*。
clean up:rm -rf /tmp/myapp.git /tmp/mig. myapp-migrated will be deleted at the end of the comprehensive experiment.

Case 1: 300 repositories moved from Azure Repos to GitHub Enterprise Cloud

Question:PR discussions need to be kept for audit purposes.Method:Use GEI (gh(ado2gh extension, install according to official documentation) Git source, PR and branch strategy are migrated in batches; Azure Pipelines is temporarily retained and continued to be built through GitHub connection, and then gradually rewritten into Actions; LFS objects are pushed separately after migration.Limitations:User-level/cross-repository branch policies are not migrated and need to be rebuilt using organizational rule sets on GitHub; repositorys exceeding 40 GiB need to be slimmed down first.

Case 2: After migration, developers push to the old repository

Question:After the switch, there are still people pushing to Azure Repos, and the commit is "lost".Method:Disable the source repository (Disable repository) on the day of the switch, and put a migration announcement in the README and PR templates; usegit ls-remoteCompare the two sides every day, and cherry-pick new commits from the old repository to the new repository when differences are found.

Case 3: Disaster recovery mirror

Question:Compliance requires that the core code have a read-only copy on the second platform.Method:Timed job one-waygit fetch --prune+ Explicit refspec push to Azure Repos read-only repository (service principal only has Contribute permissions for this repository), disable PR and policy on the target to avoid rejecting the push.Limitations:Bidirectional synchronization is not possible.

Common errors and solutions

! [remote rejected] refs/pull/1/head -> refs/pull/1/head (deny updating a hidden ref)

Reason:push --mirrorPush the PR reference to GitHub as well.

Fix:Delete refs/pull/*Retry later, or use an explicit refspec instead. Branching and tagging is usually successful and there is no need to start over.

! [rejected] main -> main (fetch first) / updates were rejected because the remote contains work that you do not have

Reason:The target repository is not empty (README was initialized when created).

Fix:Delete and rebuild the empty repository; do not use--forceCover work that others may have already done.

remote: error: GH013: Repository rule violations found for refs/heads/release/1.0 … Cannot create ref due to creations being restricted.

Reason:The destination has organizational rule sets configured before migration.

Fix:Migrate the account to temporarily join bypass, or migrate first and then enable the rule set.

Git LFS: (0 of 25 files) … Smudge error: Error downloading object: … 404

Reason:Only Git pointers are migrated, not LFS objects.

Fix:in mirror repositorygit lfs fetch --all SRCaftergit lfs push --all DST。

Command line operation questions
1. Write the command to push all branches and tags in the bare repository (without other references) to DST.
git push DST 'refs/heads/*:refs/heads/*' 'refs/tags/*:refs/tags/*'
2. Prove that the two remote branches are completely consistent with the labels.
diff <(git ls-remote --heads --tags SRC | sort -k2) <(git ls-remote --heads --tags DST | sort -k2) && echo identical
Scenario analysis questions
The boss asked: "There are four of us, the code is private and requires mandatory review. Is it more economical to use GitHub or Azure Repos?"

Azure DevOps is free for the first 5 Basic users, private repository branching policy available - $0. GitHub Free private repositories cannot use branch protection/rule sets and require Team (approximately $4 per person per month, subject to the official website). If the team needs the GitHub ecosystem (Actions Market, Copilot, open source collaboration), this fee can be accepted; Azure Repos is more cost-effective for small teams that are purely internal and have already used Azure.

Verified instructional videos

▶
Git Explained in 100 Seconds — Fireship
English · Quickly review "repository = object + reference" and understand why mirror can be completely migrated

No verified mirror migration/GEI feature videos found.

Official documentation

Video storyboard (about 70 seconds)

This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Screen: All references to the source repository are copied to the bare repository like a bunch of keys.
Narrator: Mirror clone copies all references, including branches, tags, and the platform's own PR references.
Shot 2 · 20–45s
Image: refs/pull Keys are picked out and thrown away, leaving heads and tags pushed to new platforms.
Narrator: Push only branches and tags to avoid the problem of hidden ref rejections.
Shot 3 · 45–70s
Picture: two reference lists side by side, the diff result is empty, and a green check appears; "PR, strategy, pipeline" listed next to it needs to be rebuilt.
Narrator: Use reference comparison to prove that the migration is complete, and then rebuild the protection rules and pipeline on the new platform.
or score ≥ 70% on the Quiz

Command cheat sheet

Protocol Observation · Certification · Azure Repos · GitHub · CODEOWNERS · Fork · Troubleshooting · Migration

Protocols and Diagnostics

git ls-remote --heads --tags URL
GIT_TRACE_PACKET=1 git ls-remote URL
GIT_TRACE=1 GIT_TRACE_CURL=1 git fetch
GIT_SSH_COMMAND="ssh -vT" git fetch
GCM_TRACE=1 git push
git credential-manager diagnose

SSH

ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_gh # GitHub
ssh-keygen -t rsa -b 3072 -f ~/.ssh/id_rsa_azdo # Azure DevOps (RSA only)
ssh-add ~/.ssh/id_ed25519_gh; ssh-add -l
gh ssh-key add ~/.ssh/id_ed25519_gh.pub --title lab
ssh -T git@github.com; ssh -T git@ssh.dev.azure.com
ssh-keygen -R github.com

HTTPS credentials

git config --show-origin --get-all credential.helper
git credential-manager configure
git config --global credential.credentialStore secretservice
printf 'protocol=https\nhost=github.com\n\n' | git credential reject
git credential-manager github login|list|logout
git credential-manager azure-repos list|clear-cache
gh auth login|status|setup-git|refresh -s delete_repo

Azure Repos

az devops configure --defaults organization=$ADO_ORG project=$ADO_PROJECT
az repos create --name myapp
az repos import create --git-source-url URL -r myapp
az repos policy approver-count create --repository-id $REPO_ID --branch main \
  --blocking true --enabled true --minimum-approver-count 1 \
  --creator-vote-counts false --allow-downvotes false --reset-on-source-push true
az repos policy merge-strategy create ... --allow-squash true
az repos pr create -r myapp -s feature/x -t main --work-items 12 --auto-complete true --squash true
az repos pr set-vote --id 7 --vote approve
az repos pr update --id 7 --status completed

GitHub

gh repo create OWNER/myapp --public --source . --remote github
gh repo edit OWNER/myapp --enable-squash-merge --enable-merge-commit=false --delete-branch-on-merge
gh api -X POST repos/OWNER/myapp/rulesets --input ruleset.json
gh ruleset list; gh ruleset check main
gh pr create --fill --base main
gh pr checks --watch; gh pr merge --squash --auto --delete-branch

CODEOWNERS / fork / template

gh api repos/OWNER/REPO/codeowners/errors
gh repo fork OWNER/REPO --clone --remote
gh repo sync YOU/REPO
gh pr create --repo OWNER/REPO --head YOU:branch
gh repo edit OWNER/tpl --template
gh repo create OWNER/new --template OWNER/tpl --public

Migrate

git clone --mirror SRC repo.git && cd repo.git
git for-each-ref --format='%(refname)' refs/pull | xargs -r -n1 git update-ref -d
git push DST 'refs/heads/*:refs/heads/*' 'refs/tags/*:refs/tags/*'
git lfs fetch --all && git lfs push --all DST
diff <(git ls-remote --heads --tags SRC|sort -k2) <(git ls-remote --heads --tags DST|sort -k2)

Large Files/TLS/Proxy

git rev-list --objects @{u}..HEAD | git cat-file --batch-check='%(objecttype) %(objectsize) %(rest)' | sort -k2 -n | tail
git lfs migrate import --include="*.bin" --include-ref=refs/heads/feature
git config --global http.sslCAInfo /path/corp-ca.pem
git config --global http.sslBackend schannel          # Windows
git config --global http.https://github.com.proxy http://proxy:8080

Quick troubleshooting table

error keywordlevelProcess
Could not resolve host / Failed to connecttransmissionDNS, firewall, proxy
407 from proxytransmissionAgency certification
SSL certificate problemtransmissionTrust the enterprise CA and don’t turn off verification
REMOTE HOST IDENTIFICATION HAS CHANGEDtransmissionAfter checking official fingerprintsssh-keygen -R
Authentication failed / 401CertificationToken expiration/revocation;git credential reject
Permission denied (publickey) / Public key authentication failedCertificationIdentityFile + IdentitiesOnly;Azure using RSA
403 / denied to USER / SAML SSO / TF401019AuthorizePermissions, token scope, SSO authorization, wrong account
GH013 / GH006 / TF402455 / TF401027rulesPush branch + PR; don’t delete credentials
Push cannot contain secretsrulesRevoke True Secret + Rewrite Unpush History
GH001 / exceeds … 100.00 MB / VS403729storageRemove large files or LFS; shorten paths
deny updating a hidden refMigrateDelete refs/pull/*

Both platforms are equally protected (recommended configuration snippet)

Minimum reviewers 1 · Authors do not count votes · Disable recent pushers from approving
New push resets approval ticket · Associated work item Required · Comment resolved Required
Merge Type: Squash only · Build Verification Required (expires 12h after main update)
Automatically include reviewers /infra/*;*/Dockerfile → platform group
Force push: reject · Bypass: break-glass group only
target ~DEFAULT_BRANCH · enforcement active
deletion · non_fast_forward
pull_request: approvals 1, dismiss_stale, last_push_approval,
  code_owner_review, thread_resolution, allowed [squash]
required_status_checks: test (strict false)
bypass_actors: [] (or publish App)

Comprehensive experiment + final exam

Build repositorys on each of the two platforms, configure equal protection rules, complete a PR merge and image migration, and finally clean it up thoroughly
After class ≈ 40 minutesFree tier for both platforms
sceneThe team plans to host myapp on both Azure Repos (internal master repository) and GitHub (public read-only copy). Requirements: Both mains can only be modified through PR, require non-author approval (when there is a second account), only squash and infra directories are allowed and need to be reviewed by the platform manager; complete a PR merge in Azure Repos; mirror all branches and tags of Azure Repos to GitHub and prove consistency; finally clean up all test resources and credentials.
Free tier descriptionAzure DevOps: Free for the first 5 Basic users, 0 fee for this lab. GitHub: usepublicRepository, Free can use the rule set and CODEOWNERS; if you use a private repository, Pro/Team is required. "Non-author approval" cannot be satisfied when using a single account: Azure temporary settings--creator-vote-counts true, the GitHub approval number is set to 0 (direct push is still prohibited); when there is a second account, press 1 to configure it.
Prepare(Module 0):
source ~/.gitlab-p3.env
gh auth status && az devops project show --project $ADO_PROJECT --query name -o tsv
cd ~/git-lab/myapp && git switch main
Build repositorys on each of the two platforms(M3、M4):
az repos create --name myapp-final --query remoteUrl -o tsv
git remote add ado-final "$ADO_ORG/$ADO_PROJECT/_git/myapp-final"
git push ado-final --all && git push ado-final --tags
gh repo create "$GH_OWNER/myapp-final" --public --description "mirror of Azure Repos myapp-final"
GH_FINAL="https://github.com/$GH_OWNER/myapp-final.git"
Azure side protection(M3、M5):
REPO_ID=$(az repos show -r myapp-final --query id -o tsv)
C="--repository-id $REPO_ID --branch main --blocking true --enabled true"
az repos policy approver-count create $C --minimum-approver-count 1 --creator-vote-counts true --allow-downvotes false --reset-on-source-push true
az repos policy comment-required create $C
az repos policy merge-strategy create $C --allow-squash true
az repos policy required-reviewer create $C --path-filter "/infra/*" --required-reviewer-ids "$(az account show --query user.name -o tsv)"
az repos policy list --repository-id $REPO_ID --branch main --query "[].type.displayName" -o tsv

Single account in experiment--creator-vote-counts trueMake your approvals count; change to false if you have a second account.

Azure side PR merge(real version of M2 Core Animation Scene B):
echo x >> README.md && git commit -am "Direct change" && git push ado-final main # Expected TF402455
git branch feature/final && git reset --hard ado-final/main && git switch feature/final
git push -u ado-final feature/final
PR=$(az repos pr create -r myapp-final -s feature/final -t main --title "Final lab change" --squash true --delete-source-branch true --query pullRequestId -o tsv)
az repos pr set-vote --id $PR --vote approve
az repos pr update --id $PR --status completed --squash true --delete-source-branch true --query status -o tsv
git switch main && git pull ado-final main
 ! [remote rejected] main -> main (TF402455: Pushes to this branch are not permitted; you must use a pull request to update this branch.)
...
completed
Mirror migration to GitHub(M8)——Migrate first, then add the rule set:
cd /tmp && rm -rf final.git && git clone --mirror "$ADO_ORG/$ADO_PROJECT/_git/myapp-final" final.git && cd final.git
git for-each-ref --format='%(refname)' refs/pull | xargs -r -n1 git update-ref -d
git push "$GH_FINAL" 'refs/heads/*:refs/heads/*' 'refs/tags/*:refs/tags/*'
diff <(git ls-remote --heads --tags "$ADO_ORG/$ADO_PROJECT/_git/myapp-final" | sort -k2) <(git ls-remote --heads --tags "$GH_FINAL" | sort -k2) && echo "REFS IDENTICAL"
Equal protection on GitHub side(M4、M5):
cd ~/git-lab/myapp
cp ruleset-protect-main.json rs-final.json # Change required_approving_review_count to 1 when you have a second account
gh api -X POST "repos/$GH_OWNER/myapp-final/rulesets" --input rs-final.json --jq .id
gh ruleset check main -R "$GH_OWNER/myapp-final"
git clone -q "$GH_FINAL" /tmp/ghf && cd /tmp/ghf && echo y >> README.md && git commit -qam "direct" && git push origin main 2>&1 | grep -E "GH013|rejected"

CODEOWNERS has been migrated with history (committed in M5 is obsolete); if not, add a PR and open it in the rule setrequire_code_owner_review。

Clean up (must be done):
# GitHub test repository
gh auth refresh -h github.com -s delete_repo
for r in myapp myapp-final myapp-migrated orders-svc; do gh repo delete "$GH_OWNER/$r" --yes 2>/dev/null; done
# Azure DevOps: Delete test repository or entire project
az repos delete --id $(az repos show -r myapp-final --query id -o tsv) --yes
az devops project delete --id $(az devops project show --project $ADO_PROJECT --query id -o tsv) --yes # Delete the entire git-lab project
# SSH public key
gh ssh-key list; gh ssh-key delete <ID> --yes
# Azure DevOps: User settings → SSH public keys → Delete git-lab key (web)
# PAT: GitHub Settings → Developer settings → Fine-grained tokens → Delete; Azure User settings → Personal access tokens → Revoke
# Natively cache credentials
printf 'protocol=https\nhost=github.com\n\n' | git credential reject
git credential-manager azure-repos clear-cache
rm -rf /tmp/final.git /tmp/ghf ~/.ssh/id_rsa_azdo* ~/.ssh/id_ed25519_gh* # Only if these keys are only used for this lesson
gh auth logout -h github.com # optional
Acceptance Checklist

Open-ended self-assessment (answer yourself first, then expand for reference answers)

1.Draw the complete link for a rejected HTTPS push to the protected branch, and indicate at which step the credentials were saved.

GET info/refs → 401 → git credential fill → GCM (storage hit or OAuth/Entra login) → Retry with Authorization → 200 Reference list →credential approve (save)→ POST git-receive-pack (command + pack) → quarantine → pre-receive rule evaluation → ng → client prints remote: with the same reason as [remote rejected].

2.Why do I have to write IdentitiesOnly when using multiple SSH keys in Azure DevOps?

Azure DevOps only accepts the first key provided by the client. If it is invalid, it fails directly without trying the next one. The ssh.dev.azure.com host name is shared by all organizations and needs to be specified with host alias + IdentityFile + IdentitiesOnly.

3.Three key advantages of GitHub rulesets over traditional branch protection?

Multiple rule sets can be used simultaneously and aggregated to obtain the most stringent one; the enabled status can be switched (Enterprise and Evaluate); anyone with read permission can view it; the bypass list is as detailed as role/team/App; it supports label and push rule sets, and organization-level batches.

4.Azure Repos does not have CODEOWNERS, how to implement directory owner? What is the difference between the two matching semantics?

"Automatically include reviewers" policy + path filtering (Required). GitHub takes the last match into effect in file units and does not support !; Azure each policy independently determines whether it is applicable, supports ! exclusion and from left to right, the path must start with / or a wildcard character.

5.Why is hidden ref reported when using push --mirror to migrate GitHub → GitHub? How to migrate safely?

The mirror clone brings up refs/pull/*, and GitHub refuses to write these hidden references. Delete refs/pull/* or just use explicit refspec push of heads/tags, and then use ls-remote to compare and verify.

6.What is Azure DevOps' current official recommendation for PAT?

Avoid PAT when it can be used: developers use GCM (3.x default OAuth), and automation uses Entra tokens/managed identities/service principals; when it must be used, only use organization-level, minimum scope, and shortest life PAT, save the keystore and rotate; global PAT is being retired (the document gives two dates of 2026-12-01 / 2027-01-27).

Final exam (12 questions, covering all modules)

Sources and imprints

Verification basis for the technical facts of this lesson (verification date: 2026-11-15)
TopicVerify conclusionSource (Accessed on 2026-11-15)
Git Credential ManagerLatest 3.0.2 (2026-10-26), 3.0.1 (10-06), 3.0.0 (09-24). 3.0: For .NET 10, Windows no longer uses .NET Framework, abandons Win7/8; Azure Repos default OAuth token (credential.azreposCredentialType=patRestore old behavior); broker is enabled by default (credential.msauthUseBroker); new Entra application; removal of embedded web views; support for Git 2.46 credential capability negotiationGCM releases
Azure DevOps SSHOnly supports RSA (rsa-sha2-256/512), ssh-rsa SHA-1 is deprecated; hostssh.dev.azure.com, RSA fingerprintSHA256:ohD8VZEXGWo6Ez8GSEJQ9WpafgLFsOfLOtGGQCQo6Og;Only the first key is accepted; SSH does not support LFS; Regular web logins are required; Organizations can force key expirationUse SSH key authentication (version 2026-06-17)
Azure DevOps PATPriority Entra/Managed Identity/Service Principal; Organization-level PAT; Global PAT retired (top of page 2027-01-27, Best Practices section with sprint 270 release notes 2026-12-01); 90 days inactive; 84 characters with AZDO signature; Breach automatically revoked; Audited for 90 daysUse personal access tokens (version 2026-09-21) · Sprint 270(2026-03)
Azure Repos branch strategy and CLIEach policy option, four merge types, build expiration, path filtering syntax, two Bypass permissions, Required policy prohibits direct push;az repos policy *、az repos pr create/update/set-vote、az repos import createparametersBranch policies (version 2026-11-08) · az repos pr · az repos import
Azure Repos limitsRepository ≤250 GB (<10 GB recommended), push ≤5 GB (import exception), file recommendation ≤100 MB, path 32,766 / component 4,096 (VS403729)Git limits
Azure DevOps pricingThe first 5 Basics are free, then $6/user/month; Stakeholder is free but no Repos; no limit to private repositoriesAzure DevOps Services pricing
GitHub rulesetAggregation of multiple rule sets is the most stringent and aggregated with branch protection; Active/Disabled; bypass; read permission visible; 75 per repository; branch/tag/push rule set; push rule set 2024-09 GA (Team private/internal repository, acting on the fork network)About rulesets · Push rules GA(2024-09-10)
GitHub PlanFree private repository unprotected branch/required review/CODEOWNERS; Pro/Team hasGitHub’s plans
merge queuemerge_groupevents,gh-readonly-queue/{base}, concurrency 1–100, grouping and timeout; can be used to organize public repositorys and GHEC private repositorysManaging a merge queue · Merging with a merge queue
GitHub PATFine-grained PAT 2025-03-18 GA; single resource owner, 1–366 days or no expiration (can be limited by policy), organization approval, known limitations; automatic deletion if not used for one yearManaging PATs · GA Announcements
GitHub SSH fingerprint / large filesEd25519 SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqUetc; >50 MiB warning, >100 MiB block, browser 25 MiB, repository recommendation <1 GBSSH key fingerprints · About large files
CODEOWNERSPosition order .github/ → root → docs/; <3 MB; the last match takes effect; does not support !, character range, escape #; must explicitly write; get the target branch file; errors APIAbout code owners
GEI(ADO → GHEC)Migrate Git sources, PRs, work item links, attachments, branch policies (excluding user-level/cross-repository); do not migrate pipeline and LFS objects; 40 GiB, 400 MiB, 2 GiB limits; no support for Azure DevOps ServerAbout migrations from Azure DevOps
gh rulesetSubcommand list / view / checkgh ruleset manual
Git protocolsmart HTTP endpoint, protocol v2 (default since 2.26), receive-pack quarantine, pre-receive/update/post-receivegitprotocol-http · gitprotocol-v2 · githooks

Video verification instructions

The titles and channels of the following videos have been verified by the YouTube oEmbed interface (2026-11-15): Fireship "Git Explained in 100 Seconds" (hwP7WQkmECE), "13 Advanced (but useful) Git Techniques and Shortcuts" (ecK3EnyGD8o); freeCodeCamp.org "Git and GitHub for Beginners - Crash Course" (RGOj5yH7evk), "Git for Professionals Tutorial - Tools & Concepts for Mastering Version Control with Git" (Uszj_k0DGsg); Programming with Mosh "Git Tutorial for Beginners: Learn Git in 1 Hour" (8JJ101D3knE); ByteByteGo "How Git Works: Explained in 4 Minutes" (e9lnsKot_SQ); Google "Tech Talk: Linus Torvalds on git" (4XpnKHJAok8); Traversy Media "Git & GitHub Crash Course For Beginners" (SWYqp7iY_Tc). oEmbed does not return the duration and date, and the card does not write the specific duration. GCM 3, Azure Repos Branching Policy, GitHub Rule Sets, CODEOWNERS, GEI Migration No verifiable feature video found, storyboards provided. All videos are in English, and platform details are subject to this course and official documents.

Audio explanation

The "Voice" tab uses the browser Web Speech API (zh-CN) to read the explanation text in real time. English terms are pronounced in en-US. The effect depends on the voice installed on the system. The production environment cannot call the TTS service, so there is no embedded MP3; when audio is needed, the transcript can be handed over to services such as Azure AI Speech.

Known limitations

  • The SHA, repository ID, PR number, IP, token length, and time in "Expected Output" are all sample values; the commands of this courseware were not executed on the real account when generated, and the platform interface text may change with updates.
  • GitHubGH013/GH006/GH001With AzureTF402455/TF401027/TF401019The original text of the error report is organized according to common output. The official document does not list it verbatim, and the details may be slightly different.
  • There are two dates for the Azure DevOps global PAT retirement date on the official page (2026-12-01 and 2027-01-27), whichever is the latest release note.
  • GitHub prices (Team/Enterprise per user per month) are long-term prices. This lesson cannot verify the numbers on the docs.github.com package page. Please refer to github.com/pricing; details of the free tiers of GitLab, Bitbucket, and CodeCommit can be found in Lesson 4 or official documentation.
  • Animations and simulators (policy evaluation, rule set overlay, CODEOWNERS matching, error classification) are simplified models implemented as per the official documentation rules and do not cover all edge cases (e.g. full glob details of CODEOWNERS, target conditions of organization-level rule sets).
  • OAuth token length saved by GCM on Azure Repos,credential.https://dev.azure.com.useHttpPathbyconfigureDetails such as writing are subject to GCM documentation.