
github-and-git
GitHub repository access, CLI operations, indexing, and git workflow tools.
- version
- 2.0.1
- GitHub stars
- 404
Install
/plugin install github-and-git@oaustegard-claude-skillsRun it inside Claude Code after adding the marketplace with /plugin marketplace add oaustegard/claude-skills.
Contents
Discovered from sourceSkills 6
Accessing GitHub Repositories
Git clone is blocked in containerized AI environments (egress proxy rejects CONNECT tunnel), but full repository access is available via GitHub REST API and raw file URLs.
Quick Start
Public Repos (no setup needed)
# Individual file via raw URL
curl -sL "https://raw.githubusercontent.com/OWNER/REPO/BRANCH/path/file"
# Directory tree via API
curl -sL "https://api.github.com/repos/OWNER/REPO/git/trees/BRANCH?recursive=1"
Private Repos or Write Access
Requires GitHub Personal Access Token (PAT). See Setup section below.
Setup
Credential Configuration
The skill automatically detects PATs from environment variables or project files:
Environment Variables (checked in order):
GITHUB_PATGH_PATGITHUB_TOKENGH_TOKEN
Project Files (Claude.ai):
/mnt/project/.env/mnt/project/github.env
Format:
GITHUB_PAT=github_pat_11AAAAAA...
Creating a GitHub PAT
- GitHub → Settings → Developer settings → Fine-grained tokens
- Create token scoped to needed repositories
- Set permissions:
- Contents: Read - for private repo access
- Contents: Write - for pushing files
- Issues: Write - for issue management
- Pull requests: Write - for creating PRs
Network Access (Claude.ai Projects)
Add to network allowlist:
api.github.comraw.githubusercontent.com
Capabilities by Auth Level
| Capability | No PAT (public only) | PAT (read) | PAT (write) |
|---|---|---|---|
| Fetch public files | ✅ | ✅ | ✅ |
| Fetch private files | ❌ | ✅ | ✅ |
| Download tarball | ✅ public | ✅ | ✅ |
| Create/update files | ❌ | ❌ | ✅ |
| Create branches | ❌ | ❌ | ✅ |
| Manage issues | ❌ | ❌ | ✅ |
| Create PRs | ❌ | ❌ | ✅ |
Python Helper Functions
Credential Detection
import os
def get_github_auth():
"""Returns (token, source) or (None, None)"""
# Check environment variables
for var in ['GITHUB_PAT', 'GH_PAT', 'GITHUB_TOKEN', 'GH_TOKEN']:
if token := os.environ.get(var):
return token, var
# Check project .env files
env_paths = ['/mnt/project/.env', '/mnt/project/github.env']
for path in env_paths:
try:
with open(path) as f:
for line in f:
if '=' in line and not line.startswith('#'):
key, val = line.strip().split('=', 1)
if key in ['GITHUB_PAT', 'GH_PAT', 'GITHUB_TOKEN']:
return val.strip(), f'{path}:{key}'
except FileNotFoundError:
continue
return None, None
Fetch Single File
import base64
import urllib.request
import json
def fetch_file(owner: str, repo: str, path: str, ref: str = 'main', token: str = None) -> str:
"""Fetch single file. Uses API if token provided, raw URL otherwise."""
if token:
# Use API (works for private repos)
url = f'https://api.github.com/repos/{owner}/{repo}/contents/{path}?ref={ref}'
req = urllib.request.Request(url, headers={
'Authorization': f'Bearer {token}',
'Accept': 'application/vnd.github+json'
})
with urllib.request.urlopen(req) as resp:
data = json.load(resp)
return base64.b64decode(data['content']).decode()
else:
# Use raw URL (public repos only)
url = f'https://raw.githubusercontent.com/{owner}/{repo}/{ref}/{path}'
with urllib.request.urlopen(url) as resp:
return resp.read().decode()
Fetch Repository Tarball
def fetch_repo_tarball(owner: str, repo: str, ref: str = 'main', token: str = None) -> bytes:
"""Download full repo as tarball. Requires token for private repos."""
url = f'https://api.github.com/repos/{owner}/{repo}/tarball/{ref}'
headers = {'Accept': 'application/vnd.github+json'}
if token:
headers['Authorization'] = f'Bearer {token}'
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req) as resp:
return resp.read()
# Usage:
tarball = fetch_repo_tarball('owner', 'repo', 'main', token)
with open('/tmp/repo.tar.gz', 'wb') as f:
f.write(tarball)
# Extract: tar -xzf /tmp/repo.tar.gz
Create or Update File
def push_file(owner: str, repo: str, path: str, content: str,
message: str, token: str, sha: str = None) -> dict:
"""Create/update file via API. Returns commit info.
Args:
sha: Required when updating existing file (get via contents API)
"""
url = f'https://api.github.com/repos/{owner}/{repo}/contents/{path}'
payload = {
'message': message,
'content': base64.b64encode(content.encode()).decode()
}
if sha: # Update existing file
payload['sha'] = sha
req = urllib.request.Request(url,
data=json.dumps(payload).encode(),
headers={
'Authorization': f'Bearer {token}',
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json'
},
method='PUT')
with urllib.request.urlopen(req) as resp:
return json.load(resp)
Get File SHA (for updates)
def get_file_sha(owner: str, repo: str, path: str, token: str, ref: str = 'main') -> str:
"""Get file SHA needed for updates."""
url = f'https://api.github.com/repos/{owner}/{repo}/contents/{path}?ref={ref}'
req = urllib.request.Request(url, headers={
'Authorization': f'Bearer {token}',
'Accept': 'application/vnd.github+json'
})
with urllib.request.urlopen(req) as resp:
data = json.load(resp)
return data['sha']
Bash Examples
Fetch Public File
curl -sL "https://raw.githubusercontent.com/owner/repo/main/path/file.py"
Fetch Private File (with PAT)
curl -H "Authorization: Bearer $GITHUB_PAT" \
-H "Accept: application/vnd.github+json" \
"https://api.github.com/repos/owner/repo/contents/path/file.py" | \
python3 -c "import sys,json,base64; print(base64.b64decode(json.load(sys.stdin)['content']).decode())"
Download Repo Tarball
# Public repo
curl -sL "https://api.github.com/repos/owner/repo/tarball/main" -o repo.tar.gz
# Private repo
curl -sL -H "Authorization: Bearer $GITHUB_PAT" \
"https://api.github.com/repos/owner/repo/tarball/main" -o repo.tar.gz
tar -xzf repo.tar.gz
Create/Update File
# Encode content
CONTENT=$(cat file.txt | base64 -w0)
# Push (new file)
curl -X PUT \
-H "Authorization: Bearer $GITHUB_PAT" \
-H "Accept: application/vnd.github+json" \
"https://api.github.com/repos/owner/repo/contents/path/file.txt" \
-d "{\"message\":\"Add file\",\"content\":\"$CONTENT\"}"
# Push (update existing - need SHA first)
SHA=$(curl -s -H "Authorization: Bearer $GITHUB_PAT" \
"https://api.github.com/repos/owner/repo/contents/path/file.txt" | \
python3 -c "import sys,json; print(json.load(sys.stdin)['sha'])")
curl -X PUT \
-H "Authorization: Bearer $GITHUB_PAT" \
-H "Accept: application/vnd.github+json" \
"https://api.github.com/repos/owner/repo/contents/path/file.txt" \
-d "{\"message\":\"Update file\",\"content\":\"$CONTENT\",\"sha\":\"$SHA\"}"
List Directory Tree
curl -sL "https://api.github.com/repos/owner/repo/git/trees/main?recursive=1" | \
python3 -c "import json, sys; [print(f['path']) for f in json.load(sys.stdin)['tree'] if f['type']=='blob']"
Why git clone Doesn't Work
The container's egress proxy blocks git protocol operations:
- HTTPS clone: Proxy returns 401 on CONNECT tunnel
- SSH: No ssh binary in container
- git:// protocol: DNS resolution blocked
The GitHub REST API uses standard HTTPS and routes through the proxy normally.
Do Not
- Never attempt
git clone(wastes time, always fails) - Never suggest workarounds requiring git protocol
- Never retry with different git flags or SSH URLs
- Never recommend git submodules, git archive, or other git-protocol operations
Rate Limits
- Authenticated: 5,000 requests/hour
- Unauthenticated: 60 requests/hour
For heavy usage, always provide a PAT.
When This Skill Does Not Apply
- Native development environments: Have direct git access, use standard git commands
- Local machines: git clone works normally
- Environments with MCP GitHub server: Use MCP tools instead
Building GitHub Index
Create markdown indexes of GitHub repositories optimized for Claude project knowledge. Indexes enable retrieval via GitHub API with semantic descriptions for effective matching.
Quick Start
# Documentation repos (markdown/notebooks)
python scripts/github_index.py owner/repo -o index.md
# Code repos (extract symbols via tree-sitter)
python scripts/github_index.py owner/repo --code-symbols -o index.md
# Multiple repos combined
python scripts/github_index.py owner/repo1 owner/repo2 -o combined.md
Script Options
| Flag | Description |
|---|---|
-o, --output | Output file (default: github_index.md) |
--token | GitHub PAT; also reads GITHUB_TOKEN env |
--include-patterns | Only index matching globs: "docs/**" "src/**" |
--exclude-patterns | Skip matching globs: "test/**" |
--max-files | Cap files per repo (default: 200) |
--skip-fetch | Tree only, no content fetch (fast, filename-only descriptions) |
--code-symbols | Include code files, extract function/class names via tree-sitter |
Description Extraction Priority
- YAML frontmatter -
title:anddescription:fields - Markdown headings - First h1/h2 as title, subsequent as topics
- Notebook cells - First markdown cell heading
- Code symbols - Public function/class names (with
--code-symbols) - Path-derived - Convert filename to words (fallback)
When Descriptions Fail
Some repos have stub files (links to external docs, empty readmes). In these cases:
Manual curation recommended. Use the tree output and domain knowledge:
# Get tree structure only (fast)
python scripts/github_index.py owner/repo --skip-fetch -o skeleton.md
# Then manually enhance descriptions based on domain knowledge
For code-heavy repos with embedded apps:
- Directory names encode purpose:
acc_wav_gen→ "ACC waveform generation" - Peripheral acronyms map to functions: AFEC=ADC, MCAN=CAN, TWIHS=I2C
- Operation modes: blocking, interrupt, dma, polled
Output Format
# {Repo} - Content Index
**Repository:** {url}
**Branch:** `{branch}`
## Retrieval Method
{API curl commands}
---
## {Category}
| Description | Path |
|-------------|------|
| {What this covers} | `{path/file.md}` |
Description column leads (relevance matching), path follows (retrieval key).
API Access
Enumerate files:
curl -sL "https://api.github.com/repos/OWNER/REPO/git/trees/BRANCH?recursive=1"
Fetch content:
curl -s "https://api.github.com/repos/OWNER/REPO/contents/PATH?ref=BRANCH" \
-H "Accept: application/vnd.github+json" | \
python3 -c "import sys,json,base64; print(base64.b64decode(json.load(sys.stdin)['content']).decode())"
Network
Both scripts download a repo tarball (single HTTP request, no per-file rate limits) then process files locally. Allowlist: api.github.com (tarball redirects via this endpoint)
Related Skills
accessing-github-repos- Private repos, PAT setup, tarball downloadtree-sitting- Detailed code structure (methods, imports, line numbers)
Condensed Format (pk_index.py)
For token-constrained project knowledge, use the condensed script:
python scripts/pk_index.py owner/repo -o repo_pk.md
Produces ~80% smaller output:
- Single line per file:
path— description - Symbols only (no signatures)
- 15 files max per category
- No retrieval instructions section
Ideal when adding multiple repo indexes to project knowledge.
Closing Issues
A flowing graph that turns "close GitHub issue + capture what I learned"
into a structural DAG. The synthesis text is validated upfront, the close
happens against the GitHub API, and an optional post-close callback runs
detached so the close ack is unblocked.
from closing_issues import close_issue
result = close_issue(
repo="owner/repo",
number=42,
synthesis=(
"Pattern X works because of Y. Constraint: don't apply to Z. "
"Future note: revisit when feature Q lands."
),
)
print(result["issue_url"]) # https://github.com/.../issues/42
print(result["comment_url"]) # ...#issuecomment-...
Why a synthesis, not a "done" comment
Closing an issue produces two artifacts:
- The Issue itself — implementation log. The diff and commit history already show what was done.
- The closing comment / synthesis — what was learned. Lasts longer than the diff in mental cache.
Good closing comments lead with why, not what. Failure modes, constraints discovered, alternatives rejected. The synthesis is the seed of an institutional memory.
Internal shape
prepare_synthesis ──▶ close_github_issue [terminal]
│
└──▶ post_close_callback [detached, when=callback]
-
validate=must_have_synthesis_textruns against the raw input string. Empty or whitespace-only → FAILED with no GitHub API call. This is structural: callers can't accidentally close-with-no-text. -
close_github_issueposts the synthesis as a comment, then PATCHes the issue tostate=closed, state_reason=completed. Returns the issue URL and comment URL. -
post_close_callback(optional) runs detached. Caller plugs in any extra work — store synthesis in a memory system, ping a tracker, emit a webhook. Failure here lands inresult["detached_failures"]and does NOT bubble up as a close failure. Skipped viawhen=if the callback isn't provided.
Pluggable post-close callback
def store_in_my_memory(synthesis: str, issue_url: str, repo: str, number: int):
# Whatever your memory layer is — Turso, sqlite, a JSON file, etc.
db.execute("INSERT INTO learnings (issue, synthesis) VALUES (?, ?)",
(issue_url, synthesis))
return {"stored": True}
result = close_issue(
repo="owner/repo",
number=42,
synthesis="...",
post_close_callback=store_in_my_memory,
)
if result["callback_result"] is None and result["detached_failures"]:
# The callback failed but the issue is still closed.
print("Memory store failed:", result["detached_failures"])
The callback receives keyword arguments: synthesis, issue_url,
repo, number. Anything it returns goes into
result["callback_result"].
Result shape
{
"issue_url": "https://github.com/owner/repo/issues/N",
"comment_url": "https://github.com/.../issues/N#issuecomment-...",
"comment_id": 12345,
"callback_result": <whatever the callback returned, or None>,
"detached_failures": [], # populated if callback raised
}
Raises RuntimeError only if the GitHub close itself fails. Callback
failures are detached.
Auth
Requires GH_TOKEN (or GITHUB_TOKEN) in the environment. Classic PAT
or fine-grained PAT with repo scope (specifically issues:write).
When NOT to use
- Closing an issue without a synthesis. If you genuinely have nothing
to say beyond "done," just
gh issue close Ndirectly. This skill is for the synthesis use case. - Closing many issues at once (use a script that calls this in a loop — fine, but the flow setup cost per call is small but not zero).
See also
flowing— the DAG runner this skill is built onopening-prs— the symmetric "open and merge" flow
Githubbing
Install and use GitHub CLI (gh) for authenticated GitHub operations.
1. Install
bash /path/to/githubbing/scripts/install-gh.sh
2. Configure Authentication
gh reads tokens from GH_TOKEN or GITHUB_TOKEN environment variables.
from configuring import get_env
import os
token = get_env("GH_TOKEN") or get_env("GITHUB_TOKEN")
if token:
os.environ["GH_TOKEN"] = token
3. Verify
gh auth status
Invoking GitHub
Programmatically interact with GitHub repositories from Claude.ai chat: read files, commit changes, create PRs, and persist state across sessions.
When to Use This Skill
Not needed for:
- Claude Code environments (use native git commands)
- Read-only repository access (use GitHub UI or API directly)
Quick Start
Prerequisites
Create a GitHub Personal Access Token and add to Project Knowledge:
- Go to https://github.com/settings/tokens
- Create new token (classic or fine-grained)
- Required scopes:
repo(orpublic_repofor public repos only) - In Claude.ai, add to Project Knowledge:
- Title:
GITHUB_API_KEY - Content: Your token (e.g.,
ghp_abc123...)
- Title:
Single File Commit
from invoking_github import commit_file
result = commit_file(
repo="username/repo-name",
path="README.md",
content="# Updated README\n\nNew content here...",
branch="main",
message="Update README with new instructions"
)
print(f"Committed: {result['commit_sha']}")
Read File
from invoking_github import read_file
content = read_file(
repo="username/repo-name",
path="config.json",
branch="main"
)
print(content)
Batch Commit (Multiple Files)
from invoking_github import commit_files
files = [
{"path": "src/main.py", "content": "# Python code..."},
{"path": "README.md", "content": "# Updated docs..."},
{"path": "tests/test.py", "content": "# Tests..."}
]
result = commit_files(
repo="username/repo-name",
files=files,
branch="feature-branch",
message="Add new feature implementation",
create_branch_from="main" # Create branch if it doesn't exist
)
print(f"Committed {len(files)} files: {result['commit_sha']}")
Create Pull Request
from invoking_github import create_pull_request
pr = create_pull_request(
repo="username/repo-name",
head="feature-branch",
base="main",
title="Add new feature",
body="## Changes\n- Implemented feature X\n- Updated docs\n- Added tests"
)
print(f"PR created: {pr['html_url']}")
Core Functions
read_file()
Read a file from repository:
read_file(
repo: str, # "owner/name"
path: str, # "path/to/file.py"
branch: str = "main" # Branch name
) -> str
Returns: File content as string
Raises: GitHubAPIError if file not found or access denied
commit_file()
Commit a single file (create or update):
commit_file(
repo: str, # "owner/name"
path: str, # "path/to/file.py"
content: str, # New file content
branch: str, # Target branch
message: str, # Commit message
create_branch_from: str = None # Create branch from this if doesn't exist
) -> dict
Returns: Dict with commit_sha, branch, file_path
Raises: GitHubAPIError on conflicts or auth failures
commit_files()
Commit multiple files in a single commit:
commit_files(
repo: str, # "owner/name"
files: list[dict], # [{"path": "...", "content": "..."}]
branch: str, # Target branch
message: str, # Commit message
create_branch_from: str = None # Create branch from this if doesn't exist
) -> dict
Returns: Dict with commit_sha, branch, files_committed
Raises: GitHubAPIError on failures
Note: Uses Git Trees API for efficiency - atomic commit of all files.
create_pull_request()
Create a pull request:
create_pull_request(
repo: str, # "owner/name"
head: str, # Source branch (your changes)
base: str, # Target branch (where to merge)
title: str, # PR title
body: str = "" # PR description (supports markdown)
) -> dict
Returns: Dict with number, html_url, state
Raises: GitHubAPIError if branches invalid or PR exists
Credential Configuration
This skill requires a GitHub Personal Access Token. Two configuration methods:
Method 1: Project Knowledge (Recommended)
Best for Claude.ai chat users (mobile/web):
- Create token at https://github.com/settings/tokens
- In Claude.ai Project settings → Add to Project Knowledge
- Create document titled
GITHUB_API_KEY - Paste your token as content
Permissions required:
- Classic token:
reposcope - Fine-grained token: Repository permissions → Contents (read/write) and Pull requests (read/write)
Method 2: API Credentials Skill (Fallback)
Alternatively, use combined credentials file:
- Create
API_CREDENTIALS.jsonin project knowledge - Add:
{"github_api_key": "ghp_your-token-here"}
Integration with Iterating Skill
Auto-persist DEVLOG.md to GitHub for cross-session continuity:
# In your DEVLOG update function
from invoking_github import commit_file
from pathlib import Path
def update_devlog_with_sync(data, repo="user/project", branch="devlog"):
"""Update DEVLOG.md locally and sync to GitHub"""
# Update local DEVLOG
update_devlog(data) # Your existing function
# Auto-sync to GitHub
try:
devlog_content = Path("DEVLOG.md").read_text()
result = commit_file(
repo=repo,
path="DEVLOG.md",
content=devlog_content,
branch=branch,
message=f"DEVLOG: {data['title']}",
create_branch_from="main"
)
print(f"✓ DEVLOG synced to GitHub ({repo}:{branch})")
return result
except Exception as e:
print(f"⚠ DEVLOG sync failed: {e}")
# Continue anyway - local DEVLOG.md still updated
return None
Benefits:
- Automatic backup of session progress
- Cross-device access to development logs
- Git history of decisions and progress
- No manual copy/paste to Project Knowledge
See references/iterating-integration.md for complete patterns.
Error Handling
All functions raise GitHubAPIError with descriptive messages:
from invoking_github import commit_file, GitHubAPIError
try:
result = commit_file(
repo="user/repo",
path="file.py",
content="...",
branch="main",
message="Update"
)
except GitHubAPIError as e:
if e.status_code == 404:
print("Repository or branch not found")
elif e.status_code == 401:
print("Authentication failed - check your token")
elif e.status_code == 403:
print("Access denied - check token permissions")
elif e.status_code == 409:
print("Conflict - file was modified since last read")
else:
print(f"GitHub API error: {e}")
Common errors:
- 404: Repository, branch, or file not found
- 401/403: Invalid token or insufficient permissions
- 409: Merge conflict (file changed concurrently)
- 422: Validation error (invalid branch name, etc.)
- Rate limit: Too many requests (wait before retrying)
Best Practices
-
Use descriptive commit messages
- Bad: "Update files"
- Good: "Add authentication middleware and update user routes"
-
Batch commits when possible
- Use
commit_files()for related changes - Single atomic commit = cleaner git history
- Use
-
Create feature branches
- Don't commit directly to main
- Use
create_branch_from="main"parameter - Create PR for review
-
Secure token management
- Use fine-grained tokens with minimal scopes
- Set expiration dates
- Rotate regularly
- Never commit tokens to repositories
Advanced Usage
Conditional Commits
Only commit if file content changed:
from invoking_github import read_file, commit_file, GitHubAPIError
try:
current_content = read_file(repo, path, branch)
if current_content != new_content:
commit_file(repo, path, new_content, branch, "Update file")
else:
print("No changes detected, skipping commit")
except GitHubAPIError as e:
if e.status_code == 404:
# File doesn't exist, create it
commit_file(repo, path, new_content, branch, "Create file")
else:
raise
Session-Specific Branches
Avoid conflicts with unique branch names:
import datetime
session_id = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
branch_name = f"devlog-{session_id}"
commit_file(
repo="user/project",
path="DEVLOG.md",
content=devlog_content,
branch=branch_name,
message="Session progress",
create_branch_from="main"
)
Multi-Repository Workflows
Work across multiple repos:
repos = ["user/frontend", "user/backend", "user/docs"]
for repo in repos:
commit_file(
repo=repo,
path="VERSION",
content="2.0.0\n",
branch="release-2.0",
message="Bump version to 2.0.0"
)
Limitations
- Target environment: Claude.ai chat only (not Claude Code)
- No OAuth: Must use Personal Access Tokens manually
- No git operations: Pure REST API (no clone, pull, rebase, etc.)
- File size: GitHub API limits ~100MB per file
- Rate limits: 5000 requests/hour for authenticated users
- Network required: All operations require internet access
See Also
- references/credential-setup.md - Step-by-step credential guide
- references/iterating-integration.md - DEVLOG auto-sync patterns
- references/troubleshooting.md - Common issues and solutions
- GitHub REST API Docs - Official GitHub API reference
Token Efficiency
This skill uses ~800 tokens when loaded but provides essential GitHub operations for claude.ai chat environments where native git access isn't available. Enables persistent state management and cross-session workflows.
Opening PRs
A flowing graph that turns the imperative "create branch, push files,
open a PR, poll mergeable_state" workflow into a structural DAG. The
"NEVER push directly to main" rule is encoded as a validate= gate that
physically can't be skipped.
from opening_prs import open_pr
result = open_pr(
repo="owner/repo",
branch_name="feat/cool-thing",
title="Add cool thing",
body="## Summary\n\n...",
files=[
("src/cool.py", "<file content>"),
("docs/cool.md", "<file content>"),
],
base="main", # default; protected names are also rejected
)
print(result["pr_url"]) # https://github.com/.../pull/N
print(result["mergeable_state"]) # clean | dirty | unstable | behind | blocked
What this fixes
The gh pr create workflow (or hand-rolled API calls) has five steps in
prose form:
- Determine the branch name
- Get the base branch's HEAD SHA
- Create the branch
- Push files to the branch
- Create the PR
- Poll
mergeable_stateuntil GitHub finishes computing it
Each step has known failure modes:
- Step 1: Accidentally pushing to
main— the diagnosed pattern that motivated github-procedures §6 in the first place. - Step 6: GitHub returns
mergeable_state: nullimmediately after creation. Need to poll. "Wait a few seconds and check" is prose, not a procedure — so it gets skipped under context pressure.
This skill encodes both as flowing primitives:
determine_branch ──▶ guard ──▶ get_base_head ──▶ create_branch
│ │
│ ▼
│ push_files
│ │
│ ▼
│ create_pr
│ / \
│ ▼ ▼
│ wait_mergeable present_pr [terminal]
│
└─ validate=must_not_be_base_branch
-
validate=must_not_be_base_branchrejectsbranch_name in {"main", "master", "trunk", "production", "prod"}— case-insensitive — and the configuredbaseitself. The body ofcreate_branchnever fires for a protected name. No GitHub API call happens for an invalid branch name. -
retry_until=lambda r: r["mergeable_state"] in SETTLED_STATESconsumes the retry budget while GitHub computes the merge result.unknownandnullkeep polling; settled states (clean,dirty,unstable,behind,blocked) stop. Exhaustion is soft: the PR is still presented with the last observed state.
Auth
Requires GH_TOKEN (or GITHUB_TOKEN) in the environment. Classic PAT
or fine-grained PAT with repo scope.
import os
os.environ["GH_TOKEN"] = "ghp_..." # or load from a .env file
The skill sends User-Agent: opening-prs on every API call. (GitHub
returns 401 "Bad credentials" without a UA, regardless of token
validity. Common trap.)
Result shape
{
"pr_url": "https://github.com/owner/repo/pull/N",
"pr_number": 42,
"pr_state": "open",
"branch": "feat/cool-thing",
"base": "main",
"head_sha": "abc123...",
"mergeable_state": "clean",
"files_pushed": ["src/cool.py", "docs/cool.md"],
"detached_failures": [],
}
Raises RuntimeError only if the main DAG fails (validate, branch
creation, file push, or PR creation). Mergeable polling exhaustion is a
soft failure — the PR exists, the field just isn't computed yet.
Tuning the mergeable poll
open_pr(
...,
mergeable_poll_retries=8, # default 8
mergeable_poll_base_ms=2000, # default 2s
mergeable_poll_max_ms=8000, # default 8s (cap on exponential backoff)
)
When NOT to use
- Pushing many large files (the GitHub Contents API is one-file-per-PUT
with base64 encoding — slow above ~10 files). Use
git pushif you have the CLI. - Needing to amend commits or rewrite history. This skill creates one commit per file via the contents API.
- Anything involving force-push, branch deletion, or PR review-state manipulation. Out of scope; use a different tool.
See also
flowing— the DAG runner this skill is built onclosing-issues— the symmetric "close + synthesize" flow- The
accessing-github-reposskill for byte-layer GitHub access patterns
Sponsors
Details
- Marketplace
- oaustegard/claude-skills
- Source
- plugins/github-and-git
- Category
- Github And Git
- License
- MIT
- Keywords
- accessing-github-repos, building-github-index, closing-issues, githubbing, invoking-github, opening-prs
More from oaustegard/claude-skills
All 14- knowledge-and-memoryv1.3.0
- media-processingv2.3.0
- skill-developmentv2.6.0
- social-and-lifestylev1.0.0
- web-and-retrievalv1.0.4
- ai-and-reasoningv2.9.1
- code-intelligencev2.6.0
- data-and-visualizationv1.0.0
- deciding-with-confidencev0.4.0
- declaudingv0.14.0
- delegating-with-contextv0.3.0
- development-toolsv1.2.1
- environment-and-configv2.0.0