# GitHub "God-Mode" AI Agent Prompt — Research Findings

> **Date**: 2026-02-14
> **Purpose**: Comprehensive research for building a "God-Mode" prompt that manages GitHub access for AI agents.

---

## 1. GitHub Fine-Grained PAT — Full Permission List

### Key Findings

- **GA since March 2025**: Fine-grained PATs are now generally available and enabled by default for all organizations, with breaking change protections.
- **50+ granular permissions** split into two categories: **Repository Permissions** (~25 permissions) and **Organization Permissions** (~15 permissions), each with `read`, `write`, or `admin` access levels.
- **Scoped to single owner**: Each token is limited to ONE user or organization and can be further restricted to specific repositories (unlike classic PATs).
- **Mandatory expiration**: Organization owners can enforce expiration policies and rotation. Tokens include `token_id` for audit log tracking.
- **`X-Accepted-GitHub-Permissions` header**: GitHub returns this in every REST API response, telling you exactly which permissions an endpoint needs.

### Complete Repository Permissions (25)

| Permission | Access Levels | What It Unlocks |
|---|---|---|
| **Actions** | read / write | Workflow runs, artifacts, caches, runners, OIDC |
| **Administration** | read / write | Repo settings, collaborators, teams, branch protection |
| **Codespaces** | read / write | Codespace creation, management, secrets |
| **Codespaces lifecycle admin** | read / write | Start/stop/delete codespaces for org |
| **Codespaces metadata** | read | List codespaces, machine types |
| **Codespaces secrets** | read / write | Codespace-level dev secrets |
| **Commit statuses** | read / write | Status checks on commits (`POST /repos/{owner}/{repo}/statuses/{sha}`) |
| **Contents** | read / write | Repo files, commits, branches, tags, releases, downloads |
| **Custom properties** | read / write | Repository custom property values |
| **Dependabot alerts** | read / write | View/dismiss Dependabot vulnerability alerts |
| **Dependabot secrets** | read / write | Dependabot automation secrets |
| **Deploy keys** | read / write / admin | SSH deploy keys for repos |
| **Deployments** | read / write | Deployment statuses, environments |
| **Discussions** | read / write | Repository Discussions (GraphQL only) |
| **Environments** | read / write | Deployment environments, protection rules, secrets |
| **Issues** | read / write | Issues, comments, labels, milestones, assignees |
| **Merge queues** | read / write | Merge queue management |
| **Metadata** | read (always granted) | Basic repo metadata — automatically included in every token |
| **Packages** | read / write | GitHub Packages (npm, Docker, Maven, etc.) |
| **Pages** | read / write | GitHub Pages build/deployment settings |
| **Pull requests** | read / write | PRs, reviews, comments, merge |
| **Repository hooks** | read / write | Webhooks on repositories |
| **Repository projects** | read / write / admin | Classic repository projects |
| **Secret scanning alerts** | read / write | Secret scanning alert management |
| **Secrets** | read / write | Actions secrets and variables |
| **Security events** | read / write | Code scanning, SARIF uploads |
| **Single file** | read / write | Access to a single specified file path |
| **Starring** | read / write | Star/unstar repositories |
| **Variables** | read / write | Actions variables (non-secret) |
| **Webhooks** | read / write | Repository webhook configuration |
| **Workflows** | write | Modify `.github/workflows/` files via API |

### Complete Organization Permissions (15+)

| Permission | Access Levels | What It Unlocks |
|---|---|---|
| **Administration** | read / write | Org settings, runners, OIDC, rulesets, billing, code security configs |
| **API Insights** | read | Org API usage stats, route stats, time stats |
| **Blocking users** | read / write | Block/unblock users from org |
| **Campaigns** | read / write | Security campaign management |
| **Custom organization roles** | read | View org role definitions |
| **Custom properties** | read / write / admin | Org-level custom property schemas and values |
| **Events** | read | Org event feeds |
| **GitHub Copilot Business** | read / write | Copilot seat management, metrics, billing |
| **Hosted runner custom images** | read / write | Custom images for GitHub-hosted runners |
| **Issue Types** | read / write | Org-level issue type management |
| **Members** | read / write | Invitations, memberships, roles, teams, outside collaborators |
| **Organization codespaces** | read / write | Org codespace policies |
| **Organization codespaces secrets** | read / write | Org-level codespace secrets |
| **Organization codespaces settings** | read / write | Codespace org settings |
| **Personal access token requests** | read / write | Approve/deny PAT requests |
| **Plan** | read | Org plan/billing info |
| **Projects** | read / write / admin | Organization Projects V2 |
| **Secrets** | read / write | Org-level Actions secrets |
| **Self-hosted runners** | read / write | Org self-hosted runner management |
| **Team discussions** | read / write | Team discussion threads |
| **Variables** | read / write | Org-level Actions variables |
| **Webhooks** | read / write | Org webhook configuration |

### Limitations of Fine-Grained PATs

- **Cannot** access enterprise-level APIs (SCIM, enterprise org creation)
- **Cannot** span multiple organizations with a single token
- **Cannot** be used by outside collaborators or open source contributors
- **Cannot** access internal repos outside your enterprise

### Best Practice Recommendations

1. **Principle of least privilege**: Only grant the specific permissions needed for each workflow
2. **Use `X-Accepted-GitHub-Permissions` header** to discover exactly which permissions each endpoint needs
3. **Set expiration dates**: Always set token expiration (30-90 days for automation)
4. **Require org owner approval**: Enable approval requirements for org-scoped tokens
5. **Prefer fine-grained over classic**: Classic PATs have broad scopes; fine-grained tokens are scoped to specific repos and permissions

### God-Mode Application

For an AI agent God-Mode prompt, define permission "profiles" based on task type:

```bash
# Minimal read-only profile (code review, issue triage)
PERMISSIONS: contents:read, issues:read, pull_requests:read, metadata:read

# CI/CD manager profile
PERMISSIONS: actions:write, contents:read, deployments:write, environments:write, commit_statuses:write

# Full developer profile
PERMISSIONS: contents:write, issues:write, pull_requests:write, actions:write, workflows:write, packages:write

# Admin profile (use sparingly)
PERMISSIONS: administration:write, repository_hooks:write, secrets:write, security_events:write
```

---

## 2. GitHub Apps vs PATs for AI Agent Automation

### Key Findings

- **GitHub Apps authenticate as installations** with short-lived tokens (1 hour) — ideal for automated bots and CI/CD systems. They get their own identity (no user seat consumed).
- **Fine-grained PATs are tied to a user account** — simpler setup but limited to one org, one person's permissions, and require periodic rotation.
- **Three auth modes for GitHub Apps**: (1) As the app itself (JWT, for managing installations), (2) As an installation (installation token, for org/repo operations), (3) On behalf of a user (user access token, for user-scoped actions).
- **Rate limits differ**: GitHub Apps get 5,000 requests/hour per installation (can go higher for GitHub Enterprise), vs PATs share the user's 5,000/hour limit.
- **GitHub Apps can trigger workflows**: Actions by GitHub Apps can trigger `push` and `pull_request` events (unlike `GITHUB_TOKEN`), enabling chain reactions.

### When to Use Each

| Scenario | Use | Why |
|---|---|---|
| Single developer AI assistant | Fine-grained PAT | Simple, user-scoped, sufficient for personal automation |
| Org-wide bot (issue triage, PR review) | GitHub App | Installation tokens, bot identity, no user seat |
| Multi-repo CI/CD automation | GitHub App | Cross-repo access, installation-level permissions |
| One-off scripts and debugging | Fine-grained PAT | Quick setup, no app registration needed |
| Multi-org coordination | GitHub App | Can be installed across multiple orgs |
| Audit-sensitive enterprise | GitHub App | Better audit trail, dedicated identity |

### GitHub App Authentication Flow

```bash
# Step 1: Generate JWT (10 min lifetime)
# Sign with RS256 using app private key
# Claims: iss=APP_CLIENT_ID, iat=NOW-60, exp=NOW+600

# Step 2: Get installation ID
curl -H "Authorization: Bearer $JWT" \
  https://api.github.com/app/installations

# Step 3: Generate installation access token (1 hour lifetime)
curl -X POST \
  -H "Authorization: Bearer $JWT" \
  -H "Accept: application/vnd.github+json" \
  https://api.github.com/app/installations/{installation_id}/access_tokens \
  -d '{"repositories":["repo1"],"permissions":{"contents":"write","pull_requests":"write"}}'

# Step 4: Use the installation token
curl -H "Authorization: token $INSTALLATION_TOKEN" \
  https://api.github.com/repos/org/repo/pulls
```

### Best Practice Recommendations

1. **Use GitHub Apps for any production automation** — installation tokens auto-expire, dedicated identity, better audit trail
2. **Use PATs for development/testing** — quick iteration, personal scope
3. **Rotate PATs aggressively** — 30-day max expiration for automated PATs
4. **Scope installation tokens** — when generating installation tokens, specify only the repos and permissions needed for that specific operation
5. **Store private keys securely** — App private keys in secrets managers, never in repos

### God-Mode Application

The God-Mode prompt should support both auth methods and auto-select:

```yaml
auth_strategy:
  primary: github_app  # For production/org automation
  fallback: fine_grained_pat  # For personal/dev use
  rules:
    - if: multi_repo OR org_wide → github_app
    - if: single_user AND simple_task → fine_grained_pat
    - if: enterprise_audit_required → github_app
    - always: scope to minimum permissions needed
```

---

## 3. GitHub Actions Reusable Workflows

### Key Findings

- **Reusable workflows** use `workflow_call` trigger — called like actions via `uses:` keyword from other workflows.
- **Org-wide workflow templates** are stored in the `.github` repository under `workflow-templates/` with `.yml` + `.properties.json` metadata files.
- **Composite actions** bundle multiple steps into a single action — useful for shared build/test/deploy patterns across repos.
- **Secrets can be inherited** with `secrets: inherit` — passes all caller secrets to the reusable workflow without explicit mapping.
- **Access control** for private repos: Settings → Actions → General → "Accessible from repositories in the org" enables sharing without making repos public.

### Reusable Workflow Syntax

```yaml
# .github/workflows/reusable-ci.yml (in shared repo)
name: Reusable CI Pipeline
on:
  workflow_call:
    inputs:
      python-version:
        required: true
        type: string
        default: "3.12"
      run-lint:
        required: false
        type: boolean
        default: true
    outputs:
      test-result:
        description: "Test pass/fail"
        value: ${{ jobs.test.outputs.result }}
    secrets:
      deploy-token:
        required: false

jobs:
  test:
    runs-on: ubuntu-latest
    outputs:
      result: ${{ steps.test.outputs.result }}
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-python@v5
        with:
          python-version: ${{ inputs.python-version }}
      - run: pip install -r requirements.txt
      - id: test
        run: |
          pytest --tb=short
          echo "result=pass" >> $GITHUB_OUTPUT
```

```yaml
# Caller workflow in any repo
name: CI
on: [push, pull_request]
jobs:
  ci:
    uses: my-org/.github/.github/workflows/reusable-ci.yml@main
    with:
      python-version: "3.12"
      run-lint: true
    secrets: inherit
```

### Org-Wide Template Structure

```
.github/                          # Org's .github repository
├── workflow-templates/
│   ├── ci-pipeline.yml           # The workflow template
│   ├── ci-pipeline.properties.json  # Metadata
│   ├── deploy-prod.yml
│   └── deploy-prod.properties.json
```

```json
// ci-pipeline.properties.json
{
  "name": "CI Pipeline",
  "description": "Standard CI for Python projects",
  "iconName": "python-logo",
  "categories": ["Python"],
  "filePatterns": ["requirements.txt", "pyproject.toml"]
}
```

### Best Practice Recommendations

1. **Centralize in `.github` repo**: Store all org-wide reusable workflows in the org's `.github` repository
2. **Version with tags**: Reference reusable workflows by tag (`@v1`) not branch, for stability
3. **Use `secrets: inherit`** for org-internal workflows to simplify secret passing
4. **Composite actions for build steps**: Use composite actions for common step sequences (setup, lint, test)
5. **Limit workflow_call inputs**: Keep interfaces small and well-documented

### God-Mode Application

AI agents should have templates for common workflows they can deploy:

```yaml
god_mode_workflows:
  - name: ai-issue-triage
    trigger: issues.opened
    reusable: org/.github/.github/workflows/ai-triage.yml@v1
  - name: ai-pr-review
    trigger: pull_request.opened
    reusable: org/.github/.github/workflows/ai-review.yml@v1
  - name: ai-test-generation
    trigger: workflow_dispatch
    reusable: org/.github/.github/workflows/ai-tests.yml@v1
```

---

## 4. GitHub Copilot Coding Agent Deep Dive

### Key Findings

- **AGENTS.md** (supported since Aug 2025): Place in repo root or any subdirectory. The nearest `AGENTS.md` in the directory tree takes precedence. Also supports `.github/copilot-instructions.md`, `.github/instructions/*.instructions.md`, `CLAUDE.md`, and `GEMINI.md`.
- **copilot-setup-steps.yml**: A GitHub Actions workflow at `.github/workflows/copilot-setup-steps.yml` that runs BEFORE the agent starts. Must contain a single `copilot-setup-steps` job. Must be on the default branch. Customizable: `timeout-minutes` (max 59), `services`, `runs-on`, `permissions`, `steps`.
- **Custom agents in `.github/agents/`**: Markdown files with YAML frontmatter. Properties: `name`, `description` (required), `tools`, `infer`, `mcp-servers`, `metadata`, `target`. Max 30,000 character prompt. Org-level agents in `{org}/.github/agents/` or `{org}/.github-private/agents/`.
- **Built-in MCP servers**: `github` (repo data, read-only by default) and `playwright` (web testing, localhost only). Org/enterprise admins can configure additional MCP servers.
- **How it works**: Agent runs in ephemeral GitHub Actions environment (Ubuntu x64 Linux only). Creates a draft PR, iterates on feedback. Works asynchronously on multiple issues in parallel.

### AGENTS.md Format

```markdown
# AGENTS.md

## Project Overview
This is a Python FastAPI project using Docker containers.

## Build & Test
- Install deps: `pip install -e ".[dev]"`
- Run tests: `pytest tests/ -v`
- Lint: `ruff check .`
- Type check: `mypy llmhost/`

## Architecture
- `llmhosts/` — Main package
- `tests/` — Test suite
- `infrastructure/` — Docker configs

## Conventions
- All code must pass ruff and mypy
- Write tests for every new function
- Use Pydantic v2 models for data validation
- Docker-only deployments

## Important Notes
- Never modify files in `docs/secure/`
- Always update CHANGELOG.md
```

### copilot-setup-steps.yml Format

```yaml
name: "Copilot Setup Steps"

on:
  workflow_dispatch:
  push:
    paths:
      - .github/workflows/copilot-setup-steps.yml
  pull_request:
    paths:
      - .github/workflows/copilot-setup-steps.yml

jobs:
  copilot-setup-steps:  # MUST be this exact name
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - name: Checkout code
        uses: actions/checkout@v5

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: "pip"

      - name: Install dependencies
        run: pip install -e ".[dev]"

      - name: Start services
        run: docker compose up -d
```

### Custom Agent Configuration (`.github/agents/`)

```markdown
---
name: security-reviewer
description: Reviews PRs for security vulnerabilities and best practices
tools: ["read", "search", "edit"]
infer: true
mcp-servers:
  custom-scanner:
    type: local
    command: npx
    args: ["security-scanner"]
    tools: ["*"]
    env:
      API_KEY: ${{ secrets.SCANNER_KEY }}
metadata:
  team: security
  severity: high
---

You are a security specialist. Review all code changes for:
- SQL injection vulnerabilities
- XSS attack vectors
- Insecure authentication patterns
- Hardcoded secrets or credentials
- Dependency vulnerabilities

Always provide specific line references and remediation steps.
```

### Tool Aliases Available to Custom Agents

| Alias | Compatible Names | Purpose |
|---|---|---|
| `execute` | `shell`, `Bash`, `powershell` | Run commands |
| `read` | `Read`, `NotebookRead` | Read files |
| `edit` | `Edit`, `MultiEdit`, `Write`, `NotebookEdit` | Edit files |
| `search` | `Grep`, `Glob` | Search files/text |
| `agent` | `custom-agent`, `Task` | Invoke other agents |
| `web` | `WebSearch`, `WebFetch` | Web access |
| `todo` | `TodoWrite` | Task lists (VS Code only) |

### Best Practice Recommendations

1. **Always create `copilot-setup-steps.yml`** — deterministic env setup is far better than letting the agent guess
2. **Use `AGENTS.md` at repo root** — provide build commands, test commands, architecture overview
3. **Create task-specific custom agents** — security reviewer, test writer, docs updater
4. **Scope agent tools carefully** — use `tools: ["read", "search"]` for analysis-only agents
5. **Set environment secrets in the `copilot` environment** — for MCP server auth, API keys

### God-Mode Application

```yaml
copilot_agent_setup:
  agents_md: true  # Auto-generate from project structure
  setup_steps: true  # Auto-generate from dependency files
  custom_agents:
    - security-reviewer  # PR security analysis
    - test-writer  # Test coverage improvement
    - docs-updater  # Documentation maintenance
    - issue-analyst  # Issue triage and labeling
  mcp_servers:
    - github  # Built-in, read-only repo access
    - playwright  # Built-in, localhost web testing
    - custom  # Org-specific tools
```

---

## 5. GitHub CLI (`gh`) Extensions

### Key Findings

- **Extensions are custom commands** for `gh` — repos named `gh-*`, installed with `gh extension install OWNER/gh-EXTENSION`.
- **Written as bash scripts or compiled binaries** (Go, Rust, etc.) — full access to `gh` API and auth context.
- **GitHub Agentic Workflows (`gh-aw`)** is the major new extension (Feb 2026, technical preview): automate repo tasks using AI coding agents in GitHub Actions, written in plain Markdown.
- **`gh-models`** (official GitHub extension): interact with AI models via CLI — REPL mode, single-shot inference, prompt evaluation, test generation.
- **Security model**: Extensions run with the user's `gh` auth token. Read-only by default for `gh-aw`, with write operations requiring explicit approval.

### Key Extensions for AI Agent Workflows

| Extension | Install Command | Purpose |
|---|---|---|
| `gh-aw` | `gh extension install github/gh-aw` | Agentic workflows — AI-powered repo automation |
| `gh-models` | `gh extension install github/gh-models` | AI model inference, prompting, eval |
| `gh-copilot` | Built-in | Copilot in the CLI |
| `gh-dash` | `gh extension install dlvhdr/gh-dash` | TUI dashboard for PRs and issues |
| `gh-poi` | `gh extension install seachicken/gh-poi` | Delete merged local branches |
| `gh-notify` | `gh extension install meiji163/gh-notify` | GitHub notification manager |

### GitHub Agentic Workflows (`gh-aw`) Details

```bash
# Install
gh extension install github/gh-aw

# Core commands
gh aw init          # Initialize agentic workflows in a repo
gh aw add           # Add a new workflow from template
gh aw compile       # Compile markdown workflows to GitHub Actions YAML
gh aw list          # List all agentic workflows
gh aw run           # Manually trigger a workflow
gh aw status        # Check workflow run status

# Supported AI engines
# - GitHub Copilot CLI (default)
# - Claude by Anthropic
# - OpenAI Codex
```

**Agentic Workflow Example** (markdown-based):

```markdown
# Issue Triage Agent

When a new issue is opened:
1. Read the issue title and body
2. Classify the issue as: bug, feature, question, or documentation
3. Apply the appropriate label
4. If it's a bug, check if similar issues exist
5. Add a helpful comment acknowledging the issue
```

### Scripting Patterns with `gh`

```bash
# List all repos in an org
gh repo list my-org --limit 1000 --json name,url

# Create issue programmatically
gh issue create --title "AI Agent Task" --body "Description" --label "ai-agent"

# Create PR from AI agent
gh pr create --title "fix: resolve issue #123" \
  --body "$(cat <<'EOF'
## Summary
AI agent fix for issue #123

## Changes
- Fixed the null pointer in auth.py
- Added test coverage

## Test plan
- [x] Unit tests pass
- [x] Integration tests pass
EOF
)"

# GraphQL query for complex operations
gh api graphql -f query='
  query {
    repository(owner: "my-org", name: "my-repo") {
      issues(first: 10, states: OPEN) {
        nodes { number title labels(first: 5) { nodes { name } } }
      }
    }
  }'

# Batch operations across repos
gh repo list my-org --json name -q '.[].name' | while read repo; do
  gh workflow run ci.yml -R "my-org/$repo"
done
```

### Best Practice Recommendations

1. **Use `gh api` for REST/GraphQL** — handles auth automatically, pagination, rate limiting
2. **Install `gh-aw` for agentic automation** — markdown-defined, safety guardrails built in
3. **Create custom extensions for repeated patterns** — `gh extension create` scaffolds a new extension
4. **Use `--json` and `-q` flags** for machine-readable output in scripts
5. **Leverage `gh auth token`** to get the current token for tools that need raw auth

### God-Mode Application

```bash
# The God-Mode prompt should teach AI agents to use gh CLI as primary GitHub interface:
gh auth status                    # Verify auth
gh api user                       # Get current user context
gh repo list ORG --json name      # Discover repos
gh issue list -R REPO --json number,title,labels  # Scan issues
gh pr create -R REPO ...          # Create PRs
gh api graphql -f query='...'     # Complex operations
gh aw run WORKFLOW                # Trigger agentic workflows
```

---

## 6. GitHub Branch Rulesets vs Branch Protection

### Key Findings

- **Rulesets are the modern replacement** for branch protection rules — recommended by GitHub for all new configurations.
- **Key advantage: multiple rulesets can stack** — unlike branch protection where only one rule applies at a time (and it's unclear which one when multiple match).
- **Organization-level rulesets** can apply across ALL repos in an org — branch protection is repo-specific only.
- **Bypass actors**: Rulesets support explicit bypass for specific users, teams, GitHub Apps, and deploy keys with modes: `always`, `pull_request`, and `exempt` (no audit entry).
- **Limits**: Up to 75 rulesets per repository + 75 org-wide rulesets. Rulesets have full REST API support.

### Rulesets vs Branch Protection Comparison

| Feature | Branch Protection | Rulesets |
|---|---|---|
| Scope | Per-repository only | Repo + org-wide |
| Stacking | Single rule applies (ambiguous) | Multiple rulesets stack cleanly |
| Bypass | Admin override only | Granular: users, teams, apps, deploy keys |
| API | REST API (legacy) | Full REST API (modern) |
| Tag protection | Separate feature | Unified with branch rules |
| Push rules | Not supported | File path restrictions, file size limits |
| Merge queue | Separate config | Integrated in ruleset |
| History/versioning | No | Full version history with rollback |
| Target patterns | Branch name patterns | Branch + tag patterns with `fnmatch` |

### Rulesets REST API

```bash
# List org rulesets
gh api /orgs/{org}/rulesets

# Create a repository ruleset
gh api -X POST /repos/{owner}/{repo}/rulesets \
  --input - <<'EOF'
{
  "name": "main-protection",
  "target": "branch",
  "enforcement": "active",
  "conditions": {
    "ref_name": {
      "include": ["refs/heads/main"],
      "exclude": []
    }
  },
  "bypass_actors": [
    {
      "actor_id": 1,
      "actor_type": "OrganizationAdmin",
      "bypass_mode": "pull_request"
    },
    {
      "actor_id": 123,
      "actor_type": "Integration",
      "bypass_mode": "always"
    }
  ],
  "rules": [
    { "type": "deletion" },
    { "type": "non_fast_forward" },
    { "type": "required_linear_history" },
    {
      "type": "pull_request",
      "parameters": {
        "required_approving_review_count": 1,
        "dismiss_stale_reviews_on_push": true,
        "require_code_owner_review": true,
        "require_last_push_approval": true
      }
    },
    {
      "type": "required_status_checks",
      "parameters": {
        "required_status_checks": [
          { "context": "ci/test" },
          { "context": "ci/lint" }
        ],
        "strict_required_status_checks_policy": true
      }
    }
  ]
}
EOF

# List rule suites (audit evaluations)
gh api "/orgs/{org}/rulesets/rule-suites?rule_suite_result=fail"

# Get ruleset version history
gh api /orgs/{org}/rulesets/{ruleset_id}/history

# Push rule bypass requests
gh api /repos/{owner}/{repo}/bypass-requests
```

### Available Rule Types

- `creation` — Restrict branch/tag creation
- `update` — Restrict branch/tag updates
- `deletion` — Prevent branch/tag deletion
- `non_fast_forward` — Prevent force pushes
- `required_linear_history` — Require squash/rebase merges
- `required_signatures` — Require signed commits
- `pull_request` — Require PRs with review parameters
- `required_status_checks` — Require CI checks to pass
- `required_deployments` — Require successful deployments
- `merge_queue` — Require merge queue
- `required_code_scanning` — Require code scanning results
- `file_path_restriction` — Restrict changes to certain paths
- `max_file_path_length` — Limit file path length
- `file_extension_restriction` — Restrict certain file extensions
- `max_file_size` — Limit file size

### Best Practice Recommendations

1. **Use rulesets, not branch protection** — they're the future, more flexible, and org-wide
2. **Create org-wide rulesets** for baseline protection (no force push to main, require PRs)
3. **Use bypass actors for AI agents** — grant your GitHub App bypass with `pull_request` mode so it can push to branches but still needs PR approval for main
4. **Enable rule suite auditing** — monitor which rules are being evaluated and bypassed
5. **Version your rulesets** — use the history API to track changes

### God-Mode Application

```yaml
branch_protection:
  method: rulesets  # NOT branch protection rules
  org_wide:
    - name: base-protection
      target: branch
      pattern: ["refs/heads/main", "refs/heads/release/*"]
      rules: [deletion, non_fast_forward, pull_request(1 review), required_status_checks]
    - name: ai-agent-bypass
      bypass_actors:
        - type: Integration
          app_id: AI_AGENT_APP_ID
          mode: pull_request  # Can push branches, still needs PR for main
```

---

## 7. GitHub Projects V2 API

### Key Findings

- **Exclusively GraphQL API** — Projects V2 has no REST API. All operations (CRUD) require GraphQL mutations.
- **Authentication**: `read:project` scope for queries, `project` scope for mutations. Works with PATs (classic), fine-grained PATs, and GitHub App installation tokens.
- **Custom fields**: Text, Number, Date, Single Select, Iteration — each has a typed GraphQL object. Single selects have option IDs, iterations have iteration IDs.
- **Status updates** (since June 2024): `ProjectV2StatusUpdate` object with `createProjectV2StatusUpdate` mutation. Supports ON_TRACK, AT_RISK, OFF_TRACK statuses with dates and descriptions.
- **Webhooks**: `projects_v2_item` event fires on item changes, `projects_v2_status_update` event for status updates.

### Key GraphQL Operations

```graphql
# Find project ID
query {
  organization(login: "my-org") {
    projectV2(number: 1) {
      id
      title
    }
  }
}

# List project fields (get field IDs for updates)
query {
  node(id: "PROJECT_ID") {
    ... on ProjectV2 {
      fields(first: 20) {
        nodes {
          ... on ProjectV2Field { id name }
          ... on ProjectV2SingleSelectField {
            id name
            options { id name }
          }
          ... on ProjectV2IterationField {
            id name
            configuration { iterations { startDate id } }
          }
        }
      }
    }
  }
}

# Add item to project
mutation {
  addProjectV2ItemById(input: {
    projectId: "PROJECT_ID"
    contentId: "ISSUE_OR_PR_NODE_ID"
  }) {
    item { id }
  }
}

# Update a field value (e.g., Status → "In Progress")
mutation {
  updateProjectV2ItemFieldValue(input: {
    projectId: "PROJECT_ID"
    itemId: "ITEM_ID"
    fieldId: "STATUS_FIELD_ID"
    value: { singleSelectOptionId: "IN_PROGRESS_OPTION_ID" }
  }) {
    projectV2Item { id }
  }
}

# Create a status update
mutation {
  createProjectV2StatusUpdate(input: {
    projectId: "PROJECT_ID"
    status: ON_TRACK
    body: "Sprint 5 on track. 8/12 items completed."
    startDate: "2026-02-10"
    targetDate: "2026-02-21"
  }) {
    statusUpdate { id }
  }
}

# Add a draft issue
mutation {
  addProjectV2DraftIssue(input: {
    projectId: "PROJECT_ID"
    title: "New feature request"
    body: "Description of the feature"
  }) {
    projectItem { id }
  }
}

# Delete item from project
mutation {
  deleteProjectV2Item(input: {
    projectId: "PROJECT_ID"
    itemId: "ITEM_ID"
  }) {
    deletedItemId
  }
}
```

### Using `gh` CLI for Projects V2

```bash
# Query project
gh api graphql -f query='
  query {
    organization(login: "my-org") {
      projectV2(number: 1) {
        id
        items(first: 50) {
          nodes {
            id
            content {
              ... on Issue { number title state }
              ... on PullRequest { number title state }
            }
            fieldValues(first: 10) {
              nodes {
                ... on ProjectV2ItemFieldSingleSelectValue { name }
                ... on ProjectV2ItemFieldTextValue { text }
              }
            }
          }
        }
      }
    }
  }'

# Add item
gh api graphql -f query='
  mutation {
    addProjectV2ItemById(input: {
      projectId: "PVT_xxx"
      contentId: "I_xxx"
    }) {
      item { id }
    }
  }'
```

### Automation with GitHub Actions

```yaml
# .github/workflows/project-automation.yml
name: Auto-add issues to project
on:
  issues:
    types: [opened]
jobs:
  add-to-project:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/add-to-project@v1
        with:
          project-url: https://github.com/orgs/my-org/projects/1
          github-token: ${{ secrets.PROJECT_PAT }}
```

### Best Practice Recommendations

1. **Cache field IDs** — field and option IDs are stable; query them once and store
2. **Use GitHub Actions for event-driven updates** — auto-move items on PR merge, issue close
3. **Create status updates programmatically** — weekly sprint status via scheduled workflow
4. **Use draft issues for backlog** — AI agents can create draft items without creating full issues
5. **Prefer `gh api graphql`** over raw curl — handles auth and pagination

### God-Mode Application

```yaml
project_management:
  auto_track: true
  on_issue_created: add_to_project, set_status("Todo")
  on_pr_opened: add_to_project, set_status("In Progress"), link_to_issue
  on_pr_merged: set_status("Done"), close_linked_issue
  weekly_status: createProjectV2StatusUpdate with sprint metrics
```

---

## 8. GitHub Packages and Container Registry (ghcr.io)

### Key Findings

- **ghcr.io is the Container Registry** — push Docker images as `ghcr.io/OWNER/IMAGE:TAG`. Free for public images, included in GitHub plan for private.
- **Auth for local dev**: PAT (classic) with `write:packages` + `read:packages` scopes → `docker login ghcr.io -u USERNAME --password-stdin`.
- **Auth for GitHub Actions**: Use the built-in `GITHUB_TOKEN` with `packages: write` permission — recommended for CI/CD.
- **Fine-grained PATs** support `packages` permission (read/write) for GitHub Packages.
- **Beyond Docker**: GitHub Packages also supports npm, Maven, Gradle, NuGet, and RubyGems registries.

### Docker Image Publishing

```bash
# Local development auth
echo $PAT | docker login ghcr.io -u USERNAME --password-stdin

# Build and tag
docker build -t ghcr.io/my-org/my-app:latest .
docker build -t ghcr.io/my-org/my-app:v1.2.3 .

# Push
docker push ghcr.io/my-org/my-app:latest
docker push ghcr.io/my-org/my-app:v1.2.3

# Pull (public images need no auth)
docker pull ghcr.io/my-org/my-app:latest
```

### GitHub Actions CI/CD Publishing

```yaml
name: Build and Push Docker Image
on:
  push:
    tags: ['v*']

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      - uses: actions/checkout@v5

      - name: Log in to GHCR
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ghcr.io/${{ github.repository }}
          tags: |
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=sha

      - name: Build and push
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
```

### Token Requirements Summary

| Scenario | Token Type | Required Scopes |
|---|---|---|
| Read public packages | None | — |
| Read private packages | PAT classic OR fine-grained | `read:packages` |
| Write packages (local) | PAT classic | `write:packages`, `read:packages` |
| Write packages (Actions) | `GITHUB_TOKEN` | `packages: write` |
| Delete packages | PAT classic OR fine-grained | `delete:packages` |
| Admin packages | PAT classic | `write:packages`, `read:packages` |

### Package Visibility and Linking

```bash
# List packages for a user/org
gh api /users/{username}/packages?package_type=container
gh api /orgs/{org}/packages?package_type=container

# Get package versions
gh api /users/{username}/packages/container/{package_name}/versions

# Delete a package version
gh api -X DELETE /users/{username}/packages/container/{package_name}/versions/{version_id}

# Change package visibility
# (must be done via GitHub web UI or GraphQL)
```

### Best Practice Recommendations

1. **Use `GITHUB_TOKEN` in Actions** — no PAT management, auto-scoped, auto-rotated
2. **Tag with semver + SHA** — `v1.2.3`, `1.2`, `sha-abc1234` for traceability
3. **Use `docker/metadata-action`** — auto-generates tags from git context
4. **Set packages to public** for open source — free storage and transfer
5. **Link packages to repositories** — enables GITHUB_TOKEN access and shows packages in repo sidebar

### God-Mode Application

```yaml
container_registry:
  registry: ghcr.io
  auth:
    actions: GITHUB_TOKEN  # Preferred for CI/CD
    local: fine_grained_pat with packages:write
  naming: ghcr.io/{org}/{repo}:{semver}
  auto_publish:
    on_tag: true  # v* tags trigger build+push
    on_merge_to_main: true  # latest tag
  cleanup:
    keep_last: 10  # Prune old versions
```

---

## Summary: God-Mode Prompt Architecture

### Authentication Layer
```
PRIMARY:   GitHub App (installation tokens, 1hr expiry, bot identity)
FALLBACK:  Fine-grained PAT (user-scoped, 30-day expiry, specific repos)
CI/CD:     GITHUB_TOKEN (auto-provided in Actions, auto-scoped)
```

### Permission Profiles
```
READER:    contents:read, issues:read, pull_requests:read
DEVELOPER: contents:write, issues:write, pull_requests:write, actions:write
CI_CD:     actions:write, packages:write, deployments:write, environments:write
ADMIN:     administration:write, secrets:write, security_events:write, webhooks:write
```

### Toolchain
```
CLI:       gh (primary), gh-aw (agentic workflows), gh-models (AI inference)
API:       REST (repos, issues, PRs, actions) + GraphQL (Projects V2, complex queries)
CI/CD:     Reusable workflows in .github repo, copilot-setup-steps.yml
Protection: Rulesets (not branch protection), bypass actors for AI apps
Registry:  ghcr.io with GITHUB_TOKEN in Actions
Agents:    AGENTS.md + .github/agents/ custom agents + MCP servers
```

### Event-Driven Automation
```
issue.opened     → AI triage (label, assign, comment)
pull_request.*   → AI review + project board update
push to main     → Build + publish to ghcr.io
schedule (cron)  → Weekly project status update
workflow_dispatch → Manual AI agent tasks
```
