# GitHub Repository Management Create, clone, fork, configure, and manage GitHub repositories. Each section shows `gh` first, then the `git` + `curl` fallback. ## Prerequisites - Authenticated with GitHub (see `github-auth` skill) ### Setup ```bash if command -v gh &>/dev/null && gh auth status &>/dev/null; then AUTH="gh" else AUTH="git" if [ -z "$GITHUB_TOKEN" ]; then if _hermes_env="${HERMES_HOME:-$HOME/.hermes}/.env"; [ -f "$_hermes_env" ] && grep -q "^GITHUB_TOKEN=" "$_hermes_env"; then GITHUB_TOKEN=$(grep "^GITHUB_TOKEN=" "$_hermes_env" | head -1 | cut -d= -f2 | tr -d '\n\r') elif grep -q "github.com" ~/.git-credentials 2>/dev/null; then GITHUB_TOKEN=$(uv run python "${HERMES_HOME:-$HOME/.hermes}/skills/github/github-auth/scripts/git-credential-token.py") fi fi fi # Get your GitHub username (needed for several operations) if [ "$AUTH" = "gh" ]; then GH_USER=$(gh api user --jq '.login') else GH_USER=$(curl -s -H "Authorization: token $GITHUB_TOKEN" https://api.github.com/user | python -c "import sys,json; print(json.load(sys.stdin)['login'])") fi ``` If you're inside a repo already: ```bash REMOTE_URL=$(git remote get-url origin) OWNER_REPO=$(echo "$REMOTE_URL" | sed -E 's|.*github\.com[:/]||; s|\.git$||') OWNER=$(echo "$OWNER_REPO" | cut -d/ -f1) REPO=$(echo "$OWNER_REPO" | cut -d/ -f2) ``` --- ## 1. Cloning Repositories Cloning is pure `git` — works identically either way: ```bash # Clone via HTTPS (works with credential helper or token-embedded URL) git clone https://github.com/owner/repo-name.git # Clone into a specific directory git clone https://github.com/owner/repo-name.git ./my-local-dir # Shallow clone (faster for large repos) git clone --depth 1 https://github.com/owner/repo-name.git # Clone a specific branch git clone --branch develop https://github.com/owner/repo-name.git # Clone via SSH (if SSH is configured) git clone git@github.com:owner/repo-name.git ``` **With gh (shorthand):** ```bash gh repo clone owner/repo-name gh repo clone owner/repo-name -- --depth 1 ``` ## 2. Creating Repositories **With gh:** ```bash # Create a public repo and clone it gh repo create my-new-project --public --clone # Private, with description and license gh repo create my-new-project --private --description "A useful tool" --license MIT --clone # Under an organization gh repo create my-org/my-new-project --public --clone # From existing local directory cd /path/to/existing/project gh repo create my-project --source . --public --push ``` **With git + curl:** ```bash # Create the remote repo via API curl -s -X POST \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/user/repos \ -d '{ "name": "my-new-project", "description": "A useful tool", "private": false, "auto_init": true, "license_template": "mit" }' # Clone it git clone https://github.com/$GH_USER/my-new-project.git cd my-new-project # -- OR -- push an existing local directory to the new repo cd /path/to/existing/project git init git add . git commit -m "Initial commit" git remote add origin https://github.com/$GH_USER/my-new-project.git git push -u origin main ``` To create under an organization: ```bash curl -s -X POST \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/orgs/my-org/repos \ -d '{"name": "my-new-project", "private": false}' ``` ### From a Template **With gh:** ```bash gh repo create my-new-app --template owner/template-repo --public --clone ``` **With curl:** ```bash curl -s -X POST \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/repos/owner/template-repo/generate \ -d '{"owner": "'"$GH_USER"'", "name": "my-new-app", "private": false}' ``` ## 3. Forking Repositories **With gh:** ```bash gh repo fork owner/repo-name --clone ``` **With git + curl:** ```bash # Create the fork via API curl -s -X POST \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/repos/owner/repo-name/forks # Wait a moment for GitHub to create it, then clone sleep 3 git clone https://github.com/$GH_USER/repo-name.git cd repo-name # Add the original repo as "upstream" remote git remote add upstream https://github.com/owner/repo-name.git ``` ### Keeping a Fork in Sync ```bash # Pure git — works everywhere git fetch upstream git checkout main git merge upstream/main git push origin main ``` **With gh (shortcut):** ```bash gh repo sync $GH_USER/repo-name ``` ## 4. Repository Information **With gh:** ```bash gh repo view owner/repo-name gh repo list --limit 20 gh search repos "machine learning" --language python --sort stars ``` **With curl:** ```bash # View repo details curl -s \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/repos/$OWNER/$REPO \ | python -c " import sys, json r = json.load(sys.stdin) print(f\"Name: {r['full_name']}\") print(f\"Description: {r['description']}\") print(f\"Stars: {r['stargazers_count']} Forks: {r['forks_count']}\") print(f\"Default branch: {r['default_branch']}\") print(f\"Language: {r['language']}\")" # List your repos curl -s \ -H "Authorization: token $GITHUB_TOKEN" \ "https://api.github.com/user/repos?per_page=20&sort=updated" \ | python -c " import sys, json for r in json.load(sys.stdin): vis = 'private' if r['private'] else 'public' print(f\" {r['full_name']:40} {vis:8} {r.get('language', ''):10} ★{r['stargazers_count']}\")" # Search repos curl -s \ "https://api.github.com/search/repositories?q=machine+learning+language:python&sort=stars&per_page=10" \ | python -c " import sys, json for r in json.load(sys.stdin)['items']: print(f\" {r['full_name']:40} ★{r['stargazers_count']:6} {r['description'][:60] if r['description'] else ''}\")" ``` ## 5. Repository Settings **With gh:** ```bash gh repo edit --description "Updated description" --visibility public gh repo edit --enable-wiki=false --enable-issues=true gh repo edit --default-branch main gh repo edit --add-topic "machine-learning,python" gh repo edit --enable-auto-merge ``` **With curl:** ```bash curl -s -X PATCH \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/repos/$OWNER/$REPO \ -d '{ "description": "Updated description", "has_wiki": false, "has_issues": true, "allow_auto_merge": true }' # Update topics curl -s -X PUT \ -H "Authorization: token $GITHUB_TOKEN" \ -H "Accept: application/vnd.github.mercy-preview+json" \ https://api.github.com/repos/$OWNER/$REPO/topics \ -d '{"names": ["machine-learning", "python", "automation"]}' ``` ## 6. Branch Protection ```bash # View current protection curl -s \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/repos/$OWNER/$REPO/branches/main/protection # Set up branch protection curl -s -X PUT \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/repos/$OWNER/$REPO/branches/main/protection \ -d '{ "required_status_checks": { "strict": true, "contexts": ["ci/test", "ci/lint"] }, "enforce_admins": false, "required_pull_request_reviews": { "required_approving_review_count": 1 }, "restrictions": null }' ``` ## 7. Secrets Management (GitHub Actions) **With gh:** ```bash gh secret set API_KEY --body "your-secret-value" gh secret set SSH_KEY < ~/.ssh/id_rsa gh secret list gh secret delete API_KEY ``` **With curl:** Secrets require encryption with the repo's public key — more involved via API: ```bash # Get the repo's public key for encrypting secrets curl -s \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/repos/$OWNER/$REPO/actions/secrets/public-key # Encrypt and set (requires Python with PyNaCl) python -c " from base64 import b64encode from nacl import encoding, public import json, sys # Get the public key key_id = '' public_key = '' # Encrypt sealed = public.SealedBox( public.PublicKey(public_key.encode('utf-8'), encoding.Base64Encoder) ).encrypt('your-secret-value'.encode('utf-8')) print(json.dumps({ 'encrypted_value': b64encode(sealed).decode('utf-8'), 'key_id': key_id }))" # Then PUT the encrypted secret curl -s -X PUT \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/repos/$OWNER/$REPO/actions/secrets/API_KEY \ -d '' # List secrets (names only, values hidden) curl -s \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/repos/$OWNER/$REPO/actions/secrets \ | python -c " import sys, json for s in json.load(sys.stdin)['secrets']: print(f\" {s['name']:30} updated: {s['updated_at']}\")" ``` Note: For secrets, `gh secret set` is dramatically simpler. If setting secrets is needed and `gh` isn't available, recommend installing it for just that operation. ## 8. Releases **With gh:** ```bash gh release create v1.0.0 --title "v1.0.0" --generate-notes gh release create v2.0.0-rc1 --draft --prerelease --generate-notes gh release create v1.0.0 ./dist/binary --title "v1.0.0" --notes "Release notes" gh release list gh release download v1.0.0 --dir ./downloads ``` **With curl:** ```bash # Create a release curl -s -X POST \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/repos/$OWNER/$REPO/releases \ -d '{ "tag_name": "v1.0.0", "name": "v1.0.0", "body": "## Changelog\n- Feature A\n- Bug fix B", "draft": false, "prerelease": false, "generate_release_notes": true }' # List releases curl -s \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/repos/$OWNER/$REPO/releases \ | python -c " import sys, json for r in json.load(sys.stdin): tag = r.get('tag_name', 'no tag') print(f\" {tag:15} {r['name']:30} {'draft' if r['draft'] else 'published'}\")" # Upload a release asset (binary file) RELEASE_ID= curl -s -X POST \ -H "Authorization: token $GITHUB_TOKEN" \ -H "Content-Type: application/octet-stream" \ "https://uploads.github.com/repos/$OWNER/$REPO/releases/$RELEASE_ID/assets?name=binary-amd64" \ --data-binary @./dist/binary-amd64 ``` ## 9. GitHub Actions Workflows **With gh:** ```bash gh workflow list gh run list --limit 10 gh run view gh run view --log-failed gh run rerun gh run rerun --failed gh workflow run ci.yml --ref main gh workflow run deploy.yml -f environment=staging ``` **With curl:** ```bash # List workflows curl -s \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/repos/$OWNER/$REPO/actions/workflows \ | python -c " import sys, json for w in json.load(sys.stdin)['workflows']: print(f\" {w['id']:10} {w['name']:30} {w['state']}\")" # List recent runs curl -s \ -H "Authorization: token $GITHUB_TOKEN" \ "https://api.github.com/repos/$OWNER/$REPO/actions/runs?per_page=10" \ | python -c " import sys, json for r in json.load(sys.stdin)['workflow_runs']: print(f\" Run {r['id']} {r['name']:30} {r['conclusion'] or r['status']}\")" # Download failed run logs RUN_ID= curl -s -L \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/repos/$OWNER/$REPO/actions/runs/$RUN_ID/logs \ -o ~/.hermes/cache/scratch/ci-logs.zip cd ~/.hermes/cache/scratch && unzip -o ci-logs.zip -d ci-logs # Re-run a failed workflow curl -s -X POST \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/repos/$OWNER/$REPO/actions/runs/$RUN_ID/rerun # Re-run only failed jobs curl -s -X POST \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/repos/$OWNER/$REPO/actions/runs/$RUN_ID/rerun-failed-jobs # Trigger a workflow manually (workflow_dispatch) WORKFLOW_ID= curl -s -X POST \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/repos/$OWNER/$REPO/actions/workflows/$WORKFLOW_ID/dispatches \ -d '{"ref": "main", "inputs": {"environment": "staging"}}' ``` ## 10. Gists **With gh:** ```bash gh gist create script.py --public --desc "Useful script" gh gist list ``` **With curl:** ```bash # Create a gist curl -s -X POST \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/gists \ -d '{ "description": "Useful script", "public": true, "files": { "script.py": {"content": "print(\"hello\")"} } }' # List your gists curl -s \ -H "Authorization: token $GITHUB_TOKEN" \ https://api.github.com/gists \ | python -c " import sys, json for g in json.load(sys.stdin): files = ', '.join(g['files'].keys()) print(f\" {g['id']} {g['description'] or '(no desc)':40} {files}\")" ``` ## 11. GitHub Pages (static site, custom domain) **Before wiring up a custom subdomain for a product's site, check whether its existing default `.github.io//` URL already works and is reachable with zero DNS/cert setup.** A custom domain only buys a nicer-looking URL; it costs a DNS record, a certificate-provisioning wait, and an extra moving part to maintain — not worth it unless there's a concrete reason (the product needs to look/feel fully independent, or it must share the parent domain's trust/cookies). One repo can register exactly ONE custom domain via Pages — this is the real, technical reason a product that would otherwise share a repo with another already-domain-bound site (e.g. the main portfolio site) needs its OWN separate repo to get its own subdomain at all. If a product already has its own repo and you're only adding a subdomain for cosmetic reasons, say so and let the user decide rather than defaulting straight to DNS instructions. For a Vite/React/static-build site deployed via a GitHub Actions workflow (`build_type: workflow`, not the legacy "deploy from a branch" mode): ```bash # Check current Pages config (cname null = no custom domain set yet) gh api repos/$OWNER/$REPO/pages ``` **A repo that has NEVER had Pages turned on returns a plain 404 (`"message": "Not Found"`) from the check above — a green, successful deploy-workflow run does NOT fix this on its own, and the site stays unreachable (404 on the public URL) even though `gh run watch` shows every step succeeding.** The `actions/deploy-pages` step needs an actual Pages site to publish into; create one explicitly, once, before or right after the first workflow run: ```bash gh api repos/$OWNER/$REPO/pages -X POST -f build_type=workflow # html_url in the response (https://.github.io//) is the live URL once the workflow has deployed ``` Do this check (`gh api repos/$OWNER/$REPO/pages`, look for 404 vs a real object) as a standard step whenever wiring up Pages for a repo for the first time, before trusting a green CI run as proof the site is live — then verify the actual URL with a real `curl -s -o /dev/null -w "%{http_code}"` against the public html_url, not just the API response. **Gotcha: a `CNAME` file in the built output does NOT auto-register the custom domain under Actions-based deployment.** The classic "deploy from a branch" Pages mode auto-detects a `CNAME` file and sets the domain for you; the newer Actions/workflow mode does not pick it up from the uploaded artifact. You need BOTH: 1. A `public/CNAME` file (or equivalent for the build tool) containing just the domain, so it ships inside the built site and GitHub serves it as the requested Host. 2. An explicit API call to actually register the domain on the Pages config: ```bash gh api -X PUT repos/$OWNER/$REPO/pages -f cname=example.com # then verify: gh api repos/$OWNER/$REPO/pages # cname should now show the domain, html_url updates ``` Skipping step 2 leaves `cname: null` forever even though the workflow runs green and the CNAME file is clearly in the deployed artifact. **DNS records needed at the registrar** (give these to the user, you cannot configure their registrar): - Apex/root domain: 4 **A** records to GitHub Pages' IPs — `185.199.108.153`, `185.199.109.153`, `185.199.110.153`, `185.199.111.153`. - `www` subdomain (optional but recommended): **CNAME** → `.github.io`. - Check the existing record list for a leftover **default-parking A record** from the registrar (an IP that is NOT one of the four above) — an extra 5th A record causes browsers to round-robin into a blank parking page some of the time; tell the user to delete it. - `https_enforced` stays `false` until DNS actually propagates and GitHub auto-provisions the certificate; re-check `gh api repos/$OWNER/$REPO/pages` after a few hours and enable it then if still false (`gh api -X PUT repos/$OWNER/$REPO/pages -f https_enforced=true`). **Cert provisioning stuck even though DNS is verified clean** (checked from multiple resolvers — the domain's own nameservers, 8.8.8.8, 1.1.1.1 — all return exactly the 4 GitHub IPs, no CAA record blocking Let's Encrypt): this is a documented GitHub-side "stuck in new" provisioning-queue bug, not a DNS problem on your end. The official, single-use fix is to remove and re-add the custom domain, which restarts the certificate request: ```bash gh api -X PUT repos/$OWNER/$REPO/pages -F cname='' # clear it sleep 180 # wait a few minutes gh api -X PUT repos/$OWNER/$REPO/pages -f cname=example.com # re-add ``` Do this ONCE and then wait (minutes to a couple of hours, rarely up to 24–48h) — repeated remove/re-add cycles restart Let's Encrypt's internal queue each time and can trip its per-domain rate limit, making the problem worse, not better. If it is still stuck after 24–48h with DNS verified clean throughout, the remaining path is a GitHub Support ticket, not another local toggle. If the site uses a `BASE_PATH`-style build variable to serve correctly from `.github.io//` before a custom domain exists, remember to flip it to `/` once the domain is live, or every asset URL will carry the now-wrong repo-name prefix. ## 12. Preparing a private repo to go public Before flipping `visibility: private` -> `public` (`gh repo edit --visibility public`), run this checklist — a repo is not a secret store and a private-dev-notes assumption tends to leak once public: 1. **Scrub public-facing surfaces of internal framing**, not just secrets: an "inspired by / port of X" credit line, an "this is an internal system test" README/AGENTS.md note, or a hardcoded path to the maintainer's own personal notes vault reads very differently once visible to strangers than it did as a private dev note. Check the repo's description (`gh repo view --json description`), its root `AGENTS.md`/`CLAUDE.md`/README, and any `website/`-style public page for this kind of internal framing and rewrite it in public-facing terms (what the project does, not how it originated). 2. **Verify the claimed LICENSE file actually exists.** A README/site footer claiming "MIT licensed" with no `LICENSE` file at repo root is a real, common gap in a project that grew privately — add the actual license text before going public, don't just leave the claim unbacked. 3. **Audit for secrets/PII across the FULL git history, not just the current HEAD.** A file removed from the latest commit is still present in every earlier commit that touched it, and a public repo exposes all of history by default. Run a real secret scanner across all history (`gitleaks git --log-opts=--all`, or extract every blob and `gitleaks dir` on the extraction) rather than relying only on grep for known key patterns. Separately, grep every blob (`git log -p` / `git log -S` across `--all`, or extract blobs and ripgrep them) for the maintainer's own absolute home directory paths, personal network addresses (Tailscale/VPN IPs, MagicDNS names), phone/email, and real account content (session/chat titles, cost or usage figures) that a QA screenshot may have captured. **Screenshots need OCR, not just filename judgment** — a PNG/JPG with real personal content in it is invisible to text-based grep; run every image in history through `tesseract` and apply the same keyword/pattern scan to the extracted text, then eyeball the highest-risk hits directly. For anything non-trivial, delegate this specific audit to a security- focused worker forced onto a strong model/reasoning level (see coding-agent-orchestration's model- override pattern) with an explicit brief that it may NOT change visibility or rewrite history itself — it reports findings with file+line+commit hash, you decide the remediation. 4. **Current tracked files (HEAD) are a separate cleanup pass from history — squashing history does NOT touch them.** Old QA/evidence files that are still tracked today (real session screenshots, usage-cost dashboards, device logcats with real paths) ship into a public repo even after a clean squash, because a squash only discards old COMMITS, not files currently in the tree. Delete or redact these from HEAD as their own step, verified with a fresh `git status`/`find` pass, before the squash or the final push. 5. **When the audit finds non-trivial leaks spread across many commits/branches (dozens of commits, several branches touching the same sensitive file), prefer squashing to a single fresh commit over a targeted `git filter-repo --replace-text` rewrite** — selective history surgery is more complex and risk-prone (missed branches, missed blob, broken worktree refs) than starting a clean public history from the current, now-scrubbed tree. This is safe only when nothing external already depends on existing history (no open PRs, no released tags, no forks, no other clone relying on the old commit graph — check `gh pr list --state all`, `gh release list`, fork count before doing this). Confirm this trade-off with the user rather than picking it unilaterally; losing commit history is a one-way choice they may not want even when it is the lower-risk path. 6. Only flip visibility after (1)-(5) are addressed or explicitly accepted as low-risk by the user; going public, getting forked/cached, then re-privatizing does not retract what already copied out. | Action | gh | git + curl | |--------|-----|-----------| | Clone | `gh repo clone o/r` | `git clone https://github.com/o/r.git` | | Create repo | `gh repo create name --public` | `curl POST /user/repos` | | Fork | `gh repo fork o/r --clone` | `curl POST /repos/o/r/forks` + `git clone` | | Repo info | `gh repo view o/r` | `curl GET /repos/o/r` | | Edit settings | `gh repo edit --...` | `curl PATCH /repos/o/r` | | Create release | `gh release create v1.0` | `curl POST /repos/o/r/releases` | | List workflows | `gh workflow list` | `curl GET /repos/o/r/actions/workflows` | | Rerun CI | `gh run rerun ID` | `curl POST /repos/o/r/actions/runs/ID/rerun` | | Set secret | `gh secret set KEY` | `curl PUT /repos/o/r/actions/secrets/KEY` (+ encryption) | ## 13. Routine repo hygiene sweep (already-public repos, not just the going-public moment) A "check my GitHub projects for junk" request is a recurring class of work, not a one-off audit — development naturally leaks scratch/internal content into a repo between pushes, and it keeps happening after the repo already went public. Sweep EVERY repo on a fixed checklist rather than eyeballing the file tree: 1. **Biggest tracked files**: `git ls-files -z | xargs -0 du -h | sort -rh | head -20` — surfaces oversized assets fast (duplicate/forgotten screenshots, unused icon-concept exports, a stray multi-MB "proof" PNG) without having to browse the tree by eye. 2. **Dot-prefixed scratch files at repo root**: `git ls-files | grep -E '^\.[a-z]+-task-'` (and similar: `.-task-*.md`, `.design-proof/`) — these are internal agent-dispatch briefs, not project docs; they routinely carry the maintainer's own absolute home-directory paths and old/renamed project codenames. `git rm --cached` + add the pattern to `.gitignore` (keep the file locally if still useful, just stop tracking it) rather than leaving them in future pushes. 3. **Accidentally tracked build output**: `git ls-files | grep -c '^node_modules/'` (same idea for `dist/`, `build/`, `.venv/`, `__pycache__/`) — a non-zero count means a `.gitignore` was added too late; `git rm -r --cached ` then commit the `.gitignore` entry. Harmless to remove since these regenerate from `npm install`/the build step. 4. **Unused generated asset variants**: when a design process generates N options and only ONE ships (e.g. several icon "concept" folders, only one wired into the actual build/installer), the others are dead weight — but confirm which one is actually referenced (`grep -rn '' --include='*.py' --include='*.yml' .`) before deleting any; do not guess which variant is "the real one" from naming alone. 5. **Screenshots/docs referenced nowhere**: `grep -rl '' README.md docs/*.md` — a QA/mockup image not linked from any doc is almost always safe dead weight; confirm the negative (grep returns nothing) before removing, don't assume. 6. **A `git rm --cached` + `.gitignore` pass only cleans the current tip.** It does not remove the blob from history; say this plainly when reporting the cleanup rather than implying the content is fully gone. A full history scrub (`git filter-repo`) is a much heavier, separate operation — only do it on explicit request (see §12 for the going-public version of this trade-off). 7. **Before cleaning a branch, confirm it was ever actually pushed**: `git ls-remote origin | grep ` — a repo that looks like it has sensitive/old content "on GitHub" may only have that content on a local-only branch that was never pushed; don't do remote remediation (history rewrite, force-push) for content that was never remote to begin with, and say so explicitly rather than assuming every local branch is live. Always rebuild and re-push after cleanup on a repo with a build step (`npm run build` / equivalent) to confirm nothing load-bearing was removed — a QA-looking folder can occasionally be referenced by a build script even when it looks like dead evidence.