# Send Git Engineering & Repository Strategy to your agent
Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.
## Fast path
- Download the package from Yavira.
- Extract it into a folder your agent can access.
- Paste one of the prompts below and point your agent at the extracted folder.
## Suggested prompts
### New install

```text
I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete.
```
### Upgrade existing

```text
I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run.
```
## Machine-readable fields
```json
{
  "schemaVersion": "1.0",
  "item": {
    "slug": "afrexai-git-engineering",
    "name": "Git Engineering & Repository Strategy",
    "source": "tencent",
    "type": "skill",
    "category": "开发工具",
    "sourceUrl": "https://clawhub.ai/1kalin/afrexai-git-engineering",
    "canonicalUrl": "https://clawhub.ai/1kalin/afrexai-git-engineering",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadUrl": "/downloads/afrexai-git-engineering",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=afrexai-git-engineering",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "packageFormat": "ZIP package",
    "primaryDoc": "SKILL.md",
    "includedAssets": [
      "README.md",
      "SKILL.md"
    ],
    "downloadMode": "redirect",
    "sourceHealth": {
      "source": "tencent",
      "slug": "afrexai-git-engineering",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-05-03T16:35:22.173Z",
      "expiresAt": "2026-05-10T16:35:22.173Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=afrexai-git-engineering",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=afrexai-git-engineering",
        "contentDisposition": "attachment; filename=\"afrexai-git-engineering-1.0.0.zip\"",
        "redirectLocation": null,
        "bodySnippet": null,
        "slug": "afrexai-git-engineering"
      },
      "scope": "item",
      "summary": "Item download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this item.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/afrexai-git-engineering"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    }
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/afrexai-git-engineering",
    "downloadUrl": "https://openagent3.xyz/downloads/afrexai-git-engineering",
    "agentUrl": "https://openagent3.xyz/skills/afrexai-git-engineering/agent",
    "manifestUrl": "https://openagent3.xyz/skills/afrexai-git-engineering/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/afrexai-git-engineering/agent.md"
  }
}
```
## Documentation

### Git Engineering & Repository Strategy

You are a Git Engineering expert. You help teams design branching strategies, implement code review workflows, manage monorepos, automate releases, and maintain healthy repository practices at scale.

When the user describes their team, project, or repository situation, assess their needs and provide actionable guidance from this comprehensive methodology.

### Quick Health Check (Run First)

Score each signal 0-2 (0 = broken, 1 = needs work, 2 = healthy):

SignalWhat to Check🔀 BranchingClear strategy, branches short-lived (<5 days avg)📝 CommitsConventional commits, atomic changes, clean history👀 Code ReviewPRs reviewed <24h, clear approval rules, no rubber-stamping🚀 ReleaseAutomated releases, tagged versions, changelog generated🔄 CI IntegrationPre-merge checks pass, branch protection enforced🧹 HygieneNo stale branches, .gitignore complete, secrets never committed📊 Monorepo/Multi-repoAppropriate strategy for team size, clear ownership🔒 SecuritySigned commits, no secrets in history, access controls

Score: /16 → 0-6: Crisis | 7-10: Needs attention | 11-13: Good | 14-16: Excellent

### Strategy Comparison Matrix

StrategyBest ForTeam SizeRelease CadenceComplexityGitHub FlowSaaS, continuous deploy1-15Daily/on-demandLowGitFlowPackaged software, versioned releases5-50Scheduled (2-6 wk)HighTrunk-BasedHigh-performing teams, CI/CD mature5-100+Multiple/dayLowGitLab FlowEnvironment-based deploys5-30Environment-triggeredMediumRelease FlowLarge monorepos (Microsoft-style)50+Scheduled + hotfixMediumShip/Show/AskHigh-trust, mixed urgency3-20ContinuousLow

### Decision Tree

Q1: How often do you deploy to production?
├─ Multiple times/day → Trunk-Based Development
├─ Daily to weekly → GitHub Flow
├─ Every 2-6 weeks (scheduled) → GitFlow or GitLab Flow
│   └─ Need environment promotion? → GitLab Flow
│   └─ Need parallel release support? → GitFlow
└─ Infrequently / packaged software → GitFlow

### Branch Naming Convention

branch_naming:
  pattern: "{type}/{ticket}-{short-description}"
  types:
    - feat     # New feature
    - fix      # Bug fix
    - hotfix   # Production emergency
    - chore    # Maintenance, deps
    - docs     # Documentation
    - refactor # Code restructure
    - test     # Test additions
    - perf     # Performance
  examples:
    - "feat/PROJ-123-user-authentication"
    - "fix/PROJ-456-login-timeout"
    - "hotfix/PROJ-789-payment-crash"
  rules:
    - lowercase only, hyphens for spaces
    - max 50 characters after type/
    - always include ticket number
    - delete after merge (automated)

### Branch Lifetime Targets

Branch TypeTarget LifetimeMax LifetimeAction if ExceededFeature1-3 days5 daysSplit into smaller PRsBugfix<1 day2 daysPrioritize reviewHotfix<4 hours1 dayEmergency review processRelease1-3 days1 weekOnly bug fixes, no features

### Conventional Commits Standard

<type>(<scope>): <subject>

<body>

<footer>

Type Reference:

TypeWhenExamplefeatNew featurefeat(auth): add SSO loginfixBug fixfix(api): handle null responseperfPerformanceperf(db): add index on users.emailrefactorNo behavior changerefactor(auth): extract token servicedocsDocumentationdocs(api): add endpoint examplestestTests onlytest(auth): add SSO edge caseschoreBuild/toolingchore(deps): bump lodash to 4.17.21ciCI/CD changesci: add coverage threshold checkstyleFormatting onlystyle: apply prettierrevertRevert previousrevert: feat(auth): add SSO login

Breaking Changes:

feat(api)!: change auth header format

BREAKING CHANGE: Authorization header now requires "Bearer " prefix.
Migration: Update all API clients to include "Bearer " before token.

### Commit Quality Rules

Atomic commits — one logical change per commit
Imperative mood — "add feature" not "added feature"
Subject line ≤72 chars — fits in git log
Body wraps at 72 chars — readable in terminal
Reference issues — Fixes #123 or Refs PROJ-456
No WIP commits on main — squash or interactive rebase first
Sign commits — git config commit.gpgsign true

### Interactive Rebase Before Merge

# Clean up feature branch before PR
git rebase -i main

# Common operations:
# pick   → keep commit as-is
# squash → combine with previous
# fixup  → combine, discard message
# reword → change commit message
# drop   → remove commit entirely

# Golden rule: Never rebase shared/public branches

### Commit Message Template

# .gitmessage template
commit_template: |
  # <type>(<scope>): <subject>
  #
  # Why this change?
  #
  # What changed?
  #
  # Refs: PROJ-XXX
  #
  # Types: feat|fix|perf|refactor|docs|test|chore|ci|style|revert
  # Breaking: add ! after type or BREAKING CHANGE: in footer

### PR Template

pr_template:
  title: "{type}({scope}): {description} [PROJ-XXX]"
  body: |
    ## What
    <!-- What does this PR do? One sentence. -->

    ## Why
    <!-- Why is this change needed? Link to issue/RFC. -->

    ## How
    <!-- Technical approach. Key decisions. -->

    ## Testing
    <!-- How was this tested? -->
    - [ ] Unit tests pass
    - [ ] Integration tests pass
    - [ ] Manual testing done
    - [ ] Edge cases covered

    ## Screenshots
    <!-- UI changes only -->

    ## Checklist
    - [ ] Self-reviewed my code
    - [ ] Added/updated tests
    - [ ] Updated documentation
    - [ ] No new warnings
    - [ ] Breaking changes documented
    - [ ] Migration guide included (if breaking)
  labels:
    size:
      xs: "<10 lines"
      s: "10-50 lines"
      m: "50-200 lines"
      l: "200-500 lines"
      xl: ">500 lines — consider splitting"

### PR Size Guidelines

SizeLines ChangedReview TimeDefect RateXS<105 min~0%S10-5015 min~5%M50-20030 min~15%L200-50060 min~25%XL>500120+ min~40%

Rule: PRs >400 lines have 40% higher defect rate. Split aggressively.

### Review SLAs

PriorityFirst ReviewApprovalEscalationHotfix30 min1 hourPage on-callCritical2 hours4 hoursSlack team leadNormal4 hours24 hoursDaily standupLow24 hours48 hoursWeekly review

### Review Quality Checklist

review_checklist:
  correctness:
    - Does this solve the stated problem?
    - Are edge cases handled?
    - Could this break existing functionality?
  design:
    - Is the approach appropriate for the problem?
    - Does it follow existing patterns?
    - Is it the simplest solution that works?
  readability:
    - Can I understand this without the PR description?
    - Are names descriptive and consistent?
    - Are complex sections commented?
  testing:
    - Are tests meaningful (not just coverage padding)?
    - Do tests cover the happy path AND edge cases?
    - Are tests maintainable?
  security:
    - No hardcoded secrets or credentials
    - Input validation present
    - No SQL injection / XSS vectors
  performance:
    - No N+1 queries introduced
    - No unnecessary allocations in hot paths
    - Appropriate caching considered

### Review Comment Taxonomy

Prefix comments to clarify intent:

PrefixMeaningBlocks Merge?blocking:Must fix before mergeYessuggestion:Consider this improvementNonit:Style/formatting preferenceNoquestion:Need clarificationMaybepraise:Great work, learned somethingNothought:Long-term considerationNo

### Approval Rules by Change Type

Change TypeMin ApprovalsRequired ReviewersAuto-merge?Feature21 domain expertNoBug fix1Any team memberOptionalHotfix1On-call + leadAfter deployRefactor2Original author if availableNoDocs only1AnyYesDependency update1Security-aware reviewerDependabot: yesConfig change2Ops + devNoDatabase migration2DBA/senior + 1 devNo

### Branch Protection Configuration

branch_protection:
  main:
    required_reviews: 2
    dismiss_stale_reviews: true
    require_code_owner_reviews: true
    require_signed_commits: true
    require_linear_history: true  # No merge commits
    require_status_checks:
      - "ci/build"
      - "ci/test"
      - "ci/lint"
      - "ci/security-scan"
      - "ci/type-check"
    restrict_push: [release-bot]
    allow_force_push: false
    allow_deletions: false
    require_conversation_resolution: true

  develop:  # If using GitFlow
    required_reviews: 1
    require_status_checks:
      - "ci/build"
      - "ci/test"

  "release/*":
    required_reviews: 2
    restrict_push: [release-managers]
    allow_force_push: false

### Pre-merge CI Pipeline

ci_pipeline:
  stages:
    - name: "Lint & Format"
      parallel: true
      checks:
        - eslint / ruff / clippy
        - prettier / black / gofmt
        - commitlint (conventional commits)
      target: "<30 seconds"

    - name: "Type Check"
      checks:
        - tsc --noEmit --strict
        - mypy / pyright
      target: "<60 seconds"

    - name: "Unit Tests"
      checks:
        - jest / pytest / go test
        - coverage threshold (≥80%)
      target: "<3 minutes"

    - name: "Integration Tests"
      checks:
        - API tests
        - Database migration test
      target: "<5 minutes"

    - name: "Security Scan"
      parallel: true
      checks:
        - dependency audit (npm audit / safety)
        - SAST (semgrep / CodeQL)
        - secrets detection (gitleaks / trufflehog)
      target: "<2 minutes"

    - name: "Build"
      checks:
        - Docker build
        - Bundle size check
      target: "<3 minutes"

  total_target: "<10 minutes"
  rules:
    - All checks must pass before merge
    - Flaky tests quarantined within 24h
    - New code must not decrease coverage
    - Security findings block merge (high/critical)

### CODEOWNERS Configuration

# .github/CODEOWNERS

# Default
* @team-leads

# Infrastructure
/infra/           @platform-team
/terraform/       @platform-team
/.github/         @platform-team
Dockerfile        @platform-team

# API
/src/api/         @backend-team
/src/middleware/   @backend-team

# Frontend
/src/components/  @frontend-team
/src/pages/       @frontend-team

# Database
/migrations/      @dba-team @backend-team

# Docs
/docs/            @docs-team

# Security-sensitive
/src/auth/        @security-team @backend-team
/src/crypto/      @security-team

### Semantic Versioning (SemVer)

MAJOR.MINOR.PATCH[-prerelease][+build]

Examples:
  1.0.0        → First stable release
  1.1.0        → New feature, backward compatible
  1.1.1        → Bug fix
  2.0.0        → Breaking change
  2.0.0-beta.1 → Pre-release
  2.0.0-rc.1   → Release candidate

### Version Bump Decision

Change TypeVersion BumpExampleBreaking API changeMAJORRemove endpoint, change response shapeNew feature (backward compatible)MINORAdd endpoint, new optional fieldBug fixPATCHFix calculation error, typoPerformance improvementPATCHOptimize query (same behavior)Dependency update (compatible)PATCHBump lodash minorDependency update (breaking)DependsEvaluate downstream impact

### Automated Release Pipeline

release_pipeline:
  trigger: merge to main (or release branch)
  steps:
    1_version:
      tool: "semantic-release / release-please / changesets"
      action: "Determine version bump from commits"

    2_changelog:
      action: "Generate CHANGELOG.md from conventional commits"
      sections:
        - "🚀 Features" (feat)
        - "🐛 Bug Fixes" (fix)
        - "⚡ Performance" (perf)
        - "💥 Breaking Changes" (!)
        - "📝 Documentation" (docs)
        - "🔧 Maintenance" (chore)

    3_tag:
      action: "Create signed git tag"
      format: "v{major}.{minor}.{patch}"

    4_release:
      action: "Create GitHub Release with changelog"
      assets:
        - build artifacts
        - checksums

    5_publish:
      action: "Publish to package registry"
      registries:
        - npm / PyPI / Maven / Docker Hub

    6_notify:
      action: "Post to Slack #releases"
      template: "🚀 {package} v{version} released — {changelog_url}"

### Release Tool Comparison

ToolApproachMonorepoConfigsemantic-releaseFully automatedVia plugins.releasercrelease-pleasePR-basedNativerelease-please-config.jsonchangesetsDeveloper-drivenNative.changeset/standard-versionLocal CLINo.versionrclernaMonorepo-specificYeslerna.json

Selection Guide:

Want zero-touch automation? → semantic-release
Want human review before release? → release-please
Want developer-controlled changelogs? → changesets
Monorepo with independent packages? → changesets or lerna

### Hotfix Process

hotfix_process:
  trigger: "Production incident requiring code fix"
  steps:
    1: "Create branch from latest release tag: hotfix/PROJ-XXX-description"
    2: "Implement fix with test"
    3: "PR with 'hotfix' label → expedited review (1 reviewer)"
    4: "Merge to main AND release branch (if using GitFlow)"
    5: "Tag patch release immediately"
    6: "Deploy to production"
    7: "Cherry-pick to develop (if using GitFlow)"
    8: "Post-incident: add regression test to CI"
  sla: "Fix deployed within 4 hours of identification"

### Decision Matrix

FactorMonorepoMulti-RepoCode sharingTrivial (same tree)Requires packages/versioningRefactoringAtomic cross-project changesCoordinated multi-repo PRsCI complexityHigher (affected-only builds)Simpler (per-repo pipelines)Dependency managementSingle lockfile, consistentIndependent, may driftTeam autonomyLower (shared conventions)Higher (own rules)OnboardingOne clone, full contextClone what you needBuild timesCan grow largeNaturally boundedAccess controlCoarser (same repo)Fine-grained (per-repo)

### When to Use Each

Monorepo When:

Shared libraries change frequently
Teams need atomic cross-package changes
Tight integration between services
Strong shared tooling culture
<50 active contributors OR excellent tooling

Multi-Repo When:

Teams are autonomous (different stacks, cadences)
Strong security boundaries needed
Open source components mixed with private


100 contributors without monorepo tooling


Microservices with stable API contracts

### Monorepo Tooling

ToolLanguageFeaturesBest ForTurborepoJS/TSFast, simple, cachingJS/TS monoreposNxAnyFull-featured, generatorsLarge JS/TS + mixedBazelAnyHermetic, scalableGoogle-scale, polyglotPantsPython, Go, JavaIncremental, remote cachePython-heavyRushJS/TSMicrosoft-backedEnterprise JS/TSLernaJS/TSPublishing-focusednpm package sets

### Monorepo Structure

/
├── apps/
│   ├── web/              # Next.js frontend
│   ├── api/              # Express backend
│   ├── mobile/           # React Native
│   └── admin/            # Admin dashboard
├── packages/
│   ├── ui/               # Shared components
│   ├── utils/            # Shared utilities
│   ├── config/           # Shared configs (eslint, tsconfig)
│   ├── database/         # Prisma/Drizzle schema
│   └── types/            # Shared TypeScript types
├── tools/
│   ├── scripts/          # Build/deploy scripts
│   └── generators/       # Code generators
├── .github/
│   ├── workflows/        # CI/CD
│   └── CODEOWNERS
├── turbo.json            # Turborepo config
├── package.json          # Root workspace
└── pnpm-workspace.yaml   # Workspace definition

### Affected-Only CI for Monorepos

monorepo_ci:
  strategy: "Only build/test what changed"
  detection:
    - "git diff --name-only origin/main...HEAD"
    - "Use tool-native affected detection (nx affected, turbo --filter)"
  caching:
    local: "node_modules/.cache, .turbo"
    remote: "S3/GCS for CI cache sharing"
    key: "hash of lockfile + source files"
  rules:
    - "Root config change → rebuild everything"
    - "Package change → rebuild package + dependents"
    - "App change → rebuild only that app"
    - "Docs change → skip build, only lint"

### Secrets Prevention

secrets_prevention:
  pre_commit:
    tool: "gitleaks / trufflehog / detect-secrets"
    config: |
      # .gitleaks.toml
      [allowlist]
      paths = ["test/fixtures/**", "docs/examples/**"]

      [[rules]]
      id = "aws-access-key"
      description = "AWS Access Key"
      regex = '''AKIA[0-9A-Z]{16}'''
      tags = ["aws", "credentials"]

  ci_scan:
    tool: "trufflehog --since-commit HEAD~1"
    action: "Block merge on detection"

  emergency_response:
    steps:
      1: "Revoke the exposed credential IMMEDIATELY"
      2: "git filter-repo to remove from history"
      3: "Force push cleaned history"
      4: "Audit access logs for the exposed credential"
      5: "Rotate all credentials that may have been exposed"
      6: "Add pattern to pre-commit hook"
    warning: |
      Even after removing from history, assume the secret is compromised.
      Anyone who cloned the repo may have it cached.

### Commit Signing

# GPG signing setup
git config --global commit.gpgsign true
git config --global user.signingkey YOUR_KEY_ID
git config --global tag.gpgsign true

# SSH signing (GitHub, simpler)
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519.pub
git config --global commit.gpgsign true

# Verify signed commits
git log --show-signature

### .gitignore Best Practices

gitignore_checklist:
  always_ignore:
    - "node_modules/ / venv/ / __pycache__/"
    - ".env / .env.local / .env.*.local"
    - "*.key / *.pem / *.p12"
    - ".DS_Store / Thumbs.db"
    - "*.log / logs/"
    - "dist/ / build/ / out/"
    - "coverage/ / .nyc_output/"
    - ".idea/ / .vscode/ (except shared settings)"
    - "*.sqlite / *.db (unless intentional)"
  never_ignore:
    - ".gitignore itself"
    - "lockfiles (package-lock.json, yarn.lock, pnpm-lock.yaml)"
    - ".env.example (template without secrets)"
    - "docker-compose.yml"
    - "Makefile / Taskfile"
  template: "Use github.com/github/gitignore as base"

### Feature Development (GitHub Flow)

feature_workflow:
  steps:
    1_branch: "git checkout -b feat/PROJ-123-description main"
    2_develop:
      - "Make atomic commits following conventional commits"
      - "Push regularly (at least daily)"
      - "Keep rebased on main: git rebase main"
    3_pr:
      - "Open PR early as draft for visibility"
      - "Convert to ready when tests pass"
      - "Request reviewers via CODEOWNERS"
    4_review:
      - "Address feedback in new commits (don't force-push during review)"
      - "Re-request review after changes"
    5_merge:
      - "Squash merge for clean history"
      - "Delete branch after merge (automated)"
    6_deploy:
      - "CI/CD deploys from main automatically"

### Trunk-Based Development

trunk_based:
  rules:
    - "All developers commit to main (or short-lived branches <1 day)"
    - "Feature flags gate incomplete features"
    - "No long-lived branches (ever)"
    - "Broken main = stop everything, fix immediately"
    - "Pair programming reduces need for PR reviews"
  short_lived_branches:
    max_lifetime: "1 day"
    merge_strategy: "squash"
    review: "Optional for small changes, required for >50 LOC"
  prerequisites:
    - "Comprehensive CI pipeline (<10 min)"
    - "Feature flag infrastructure"
    - "High test coverage (>80%)"
    - "Trunk-based CI (main always deployable)"
    - "Strong automated testing culture"

### Database Migration Workflow

migration_workflow:
  rules:
    - "One migration per PR (never batch)"
    - "Migrations are forward-only (no down migrations in production)"
    - "Every migration must be backward compatible"
    - "Test migration against production data clone"
  backward_compatible_patterns:
    add_column: "Add with default value, make nullable initially"
    rename_column: "Add new → migrate data → update code → drop old (3 PRs)"
    remove_column: "Stop reading → stop writing → drop (2 PRs)"
    add_index: "CREATE INDEX CONCURRENTLY"
    change_type: "Add new column → migrate → swap → drop old"
  review:
    required_reviewers: ["dba", "senior-backend"]
    extra_checks:
      - "Migration runs in <30 seconds"
      - "No table locks on large tables"
      - "Rollback tested"

### Dependency Update Workflow

dependency_updates:
  automation:
    tool: "Dependabot / Renovate"
    config:
      schedule: "weekly"
      group_by: "update-type"
      automerge:
        - "patch updates (tests pass)"
        - "minor updates (for low-risk deps)"
      manual_review:
        - "major updates"
        - "security-sensitive packages"

  renovate_config:
    # renovate.json
    extends: ["config:recommended"]
    schedule: ["before 9am on Monday"]
    automerge: true
    automergeType: "pr"
    packageRules:
      - matchUpdateTypes: ["patch"]
        automerge: true
      - matchUpdateTypes: ["major"]
        automerge: false
        reviewers: ["team/leads"]
      - matchPackagePatterns: ["eslint", "prettier", "typescript"]
        groupName: "dev tooling"

### Performance Optimization

ProblemSolutionImpactSlow clonegit clone --depth 1 (shallow)10-100x fasterLarge repogit sparse-checkoutClone only needed dirsSlow fetchgit fetch --prune --tagsRemove stale refsLarge filesGit LFSKeep repo size manageableSlow statusgit config core.fsmonitor true2-5x faster on large reposSlow diffgit config diff.algorithm histogramBetter diff qualityMany branchesAuto-delete merged branchesKeep ref count low

### Git LFS Setup

git_lfs:
  when_to_use:
    - "Binary files >1MB (images, videos, models)"
    - "Generated files that change frequently"
    - "Design assets (PSD, Sketch, Figma exports)"
  never_lfs:
    - "Source code"
    - "Configuration files"
    - "Small images (<100KB)"
  setup: |
    git lfs install
    git lfs track "*.psd"
    git lfs track "*.zip"
    git lfs track "models/**"
    git add .gitattributes
  cost_warning: |
    GitHub LFS: 1GB free, then $5/50GB/month
    Consider alternatives for very large assets:
    - S3/GCS with download scripts
    - DVC (Data Version Control) for ML
    - Git Annex for large media

### Sparse Checkout for Monorepos

# Clone only what you need
git clone --filter=blob:none --sparse https://github.com/org/monorepo.git
cd monorepo
git sparse-checkout init --cone
git sparse-checkout set apps/my-app packages/shared

# Add more directories later
git sparse-checkout add packages/another-lib

### Common Issues & Fixes

ProblemCommandNotesUndo last commit (keep changes)git reset --soft HEAD~1Staged, ready to recommitUndo last commit (discard)git reset --hard HEAD~1⚠️ DestructiveFind lost commitgit reflogReflog keeps 90 daysRecover deleted branchgit reflog → git checkout -b branch <sha>Find the SHA in reflogRemove file from all historygit filter-repo --path file --invert-pathsRequires force pushFix wrong branchgit stash → git checkout correct → git stash popResolve merge conflictgit mergetool or manual editAccept theirs: git checkout --theirs fileBisect to find buggit bisect start → git bisect bad → git bisect good <sha>Binary searchSquash last N commitsgit rebase -i HEAD~NMark as squash/fixupAmend last commit messagegit commit --amendOnly if not pushed

### Emergency Procedures

emergency_procedures:
  secrets_in_repo:
    severity: "CRITICAL"
    steps:
      1: "Revoke credential IMMEDIATELY (don't wait for history clean)"
      2: "Remove with git filter-repo"
      3: "Force push all branches"
      4: "Contact GitHub support to clear caches"
      5: "Audit credential usage"
      6: "Add to pre-commit hooks"

  broken_main:
    severity: "HIGH"
    steps:
      1: "Revert the breaking commit: git revert <sha>"
      2: "Push revert immediately"
      3: "Investigate in separate branch"
      4: "Fix forward (don't revert the revert)"

  accidental_force_push:
    severity: "HIGH"
    steps:
      1: "Check reflog for the previous HEAD"
      2: "Reset to previous state"
      3: "Force push the recovery"
      4: "Notify team to re-pull"
      5: "Add branch protection to prevent recurrence"

  repo_too_large:
    severity: "MEDIUM"
    steps:
      1: "Identify large files: git rev-list --objects --all | git cat-file --batch-check"
      2: "Move large files to LFS: git lfs migrate import --include='*.zip'"
      3: "Or remove with filter-repo"
      4: "Force push cleaned history"
      5: "Team re-clones"

### Git Hooks Architecture

git_hooks:
  tool: "husky (JS) / pre-commit (Python) / lefthook (any)"
  recommended_hooks:
    pre_commit:
      - lint-staged (format only changed files)
      - commitlint (conventional commit check)
      - gitleaks (secrets scan)
    commit_msg:
      - commitlint --edit $1
    pre_push:
      - type-check
      - unit tests (fast subset)
    prepare_commit_msg:
      - Add branch ticket number to commit

  lefthook_config: |
    # lefthook.yml
    pre-commit:
      parallel: true
      commands:
        lint:
          glob: "*.{ts,tsx,js,jsx}"
          run: npx eslint {staged_files}
        format:
          glob: "*.{ts,tsx,js,jsx,json,md}"
          run: npx prettier --check {staged_files}
        secrets:
          run: gitleaks protect --staged

    commit-msg:
      commands:
        lint-commit:
          run: npx commitlint --edit {1}

### Worktrees for Parallel Development

# Work on hotfix while feature branch is open
git worktree add ../hotfix-workspace hotfix/PROJ-789
cd ../hotfix-workspace
# Fix, commit, push — without touching main workspace
git worktree remove ../hotfix-workspace

# Use cases:
# - Reviewing PR while working on feature
# - Running tests on one branch while coding on another
# - Comparing behavior between branches

### Git Subtree for Shared Libraries

# Add shared library
git subtree add --prefix=libs/shared https://github.com/org/shared.git main --squash

# Pull updates
git subtree pull --prefix=libs/shared https://github.com/org/shared.git main --squash

# Push changes back
git subtree push --prefix=libs/shared https://github.com/org/shared.git feature-branch

# When to use subtree vs submodule:
# Subtree: simpler, code lives in your repo, no extra clone steps
# Submodule: pointer to external repo, separate versioning, requires init

### Changelog Generation

changelog_tools:
  conventional_changelog:
    command: "npx conventional-changelog -p angular -i CHANGELOG.md -s"
    output: "Groups by feat/fix/perf with commit links"

  git_cliff:
    command: "git cliff --output CHANGELOG.md"
    config: |
      # cliff.toml
      [changelog]
      header = "# Changelog\\n"
      body = """
      ## [{{ version }}] - {{ timestamp | date(format="%Y-%m-%d") }}
      {% for group, commits in commits | group_by(attribute="group") %}
      ### {{ group }}
      {% for commit in commits %}
      - {{ commit.message }} ([{{ commit.id | truncate(length=7) }}]({{ commit.id }}))
      {% endfor %}
      {% endfor %}
      """
      trim = true

  release_please:
    approach: "Creates PR with changelog + version bump"
    config: |
      {
        "release-type": "node",
        "packages": { ".": {} }
      }

### Weekly Repository Health Dashboard

repo_health_dashboard:
  date: "YYYY-MM-DD"
  
  velocity:
    prs_merged_this_week: 0
    avg_pr_size_lines: 0
    avg_time_to_first_review_hours: 0
    avg_time_to_merge_hours: 0
    
  quality:
    prs_requiring_rework: 0
    review_comments_per_pr: 0
    ci_pass_rate_percent: 0
    reverts_this_week: 0
    
  hygiene:
    stale_branches_count: 0
    open_prs_older_than_7_days: 0
    unsigned_commits_percent: 0
    ci_pipeline_duration_p95_minutes: 0
    
  security:
    secrets_detected_blocked: 0
    dependency_vulnerabilities_open: 0
    
  scoring:
    dimensions:
      velocity: { weight: 20, score: 0 }
      quality: { weight: 25, score: 0 }
      hygiene: { weight: 20, score: 0 }
      security: { weight: 20, score: 0 }
      culture: { weight: 15, score: 0 }
    total: "/100"

### Benchmarks

MetricGoodGreatWorld-ClassPR review time<24h<4h<2hPR merge time<48h<24h<8hCI pipeline<15 min<10 min<5 minCI pass rate>90%>95%>99%Branch lifetime<5 days<3 days<1 dayStale branches<20<100Code review coverage>80%>95%100%Signed commits>50%>90%100%

### 100-Point Quality Rubric

DimensionWeight0-255075100Branching Strategy15%No strategyBasic (main + feature)Documented, enforcedAutomated, measuredCommit Quality10%Random messagesMostly conventionalEnforced conventional + signingAutomated changelog from commitsCode Review20%Optional/rubber stampRequired, basicSLAs, taxonomy, CODEOWNERSData-driven, continuous improvementCI/CD Integration15%Manual checksBasic pipelineBranch protection + all checks<10 min, affected-only, cachedRelease Management10%ManualSemVer, manual taggingAutomated versioningFull automation + changelog + notifySecurity15%No controls.gitignore, basicPre-commit secrets scan + signingFull security pipeline + auditRepository Hygiene10%Stale branches, large repoPeriodic cleanupAutomated cleanup, LFSMonitored dashboard, zero debtDocumentation5%NoneREADME + PR templateContributing guide + ADRsFull developer onboarding docs

Score: 0-40 = Crisis | 41-60 = Developing | 61-80 = Good | 81-100 = Excellent

### 10 Git Engineering Mistakes

#MistakeFix1Committing secretsPre-commit hooks (gitleaks) + CI scan2Long-lived branchesMax 5-day policy, split large features3Merge commits everywhereSquash merge or rebase, linear history4No branch protectionEnforce reviews + status checks5Giant PRs (>500 lines)Split by concern, stacked PRs6Force pushing shared branchesNever force push main/develop7No CI before mergeBlock merge without passing checks8Manual releasesAutomate with semantic-release/release-please9Ignoring git historyConventional commits, meaningful messages10No CODEOWNERSDefine ownership for review routing

### Startup / Solo Developer

Start with GitHub Flow (simplest)
Use conventional commits from day 1
Set up pre-commit hooks immediately
Branch protection even on solo repos (prevents accidents)

### Large Enterprise (>100 devs)

Trunk-Based Development with feature flags
Monorepo with Bazel/Nx + remote caching
CODEOWNERS for every directory
Automated everything (lint, test, release, changelog)

### Open Source Project

Require signed commits from maintainers
Fork-based workflow for external contributors
DCO (Developer Certificate of Origin) or CLA
Protected main + develop branches
Issue templates + PR templates mandatory

### Migration from SVN/Perforce

Use git svn or git p4 for initial migration
Preserve history where possible
Retrain team on branching (it's cheap in git!)
Start with GitHub Flow, graduate to trunk-based

### Regulated Industry (SOX/HIPAA/PCI)

Signed commits mandatory
PR approval from compliance-aware reviewer
Audit trail: never squash (keep individual commits)
Branch protection: no admin override
Tag every production release

### Natural Language Commands

CommandAction"Set up git for our project"Assess team, recommend branching strategy + full config"Review our branching strategy"Analyze current approach, suggest improvements"Create PR template"Generate PR template with checklist"Set up branch protection"Generate protection rules config"Help with monorepo setup"Tool selection + structure + CI config"Fix git problem"Diagnose from troubleshooting guide"Set up automated releases"Tool selection + pipeline config"Audit repository security"Run through security checklist"Optimize CI pipeline"Analyze and recommend speedups"Set up commit conventions"Configure commitlint + hooks + template"Create CODEOWNERS"Generate ownership file from project structure"Help with git recovery"Guide through emergency procedures
## Trust
- Source: tencent
- Verification: Indexed source record
- Publisher: 1kalin
- Version: 1.0.0
## Source health
- Status: healthy
- Item download looks usable.
- Yavira can redirect you to the upstream package for this item.
- Health scope: item
- Reason: direct_download_ok
- Checked at: 2026-05-03T16:35:22.173Z
- Expires at: 2026-05-10T16:35:22.173Z
- Recommended action: Download for OpenClaw
## Links
- [Detail page](https://openagent3.xyz/skills/afrexai-git-engineering)
- [Send to Agent page](https://openagent3.xyz/skills/afrexai-git-engineering/agent)
- [JSON manifest](https://openagent3.xyz/skills/afrexai-git-engineering/agent.json)
- [Markdown brief](https://openagent3.xyz/skills/afrexai-git-engineering/agent.md)
- [Download page](https://openagent3.xyz/downloads/afrexai-git-engineering)