Git Integration Guide¶
Configure automated Git workflows for version control, commits, and pull requests.
Overview¶
Sleepless Agent integrates with Git to: - Automatically commit task results - Create feature branches for serious tasks - Generate pull requests - Maintain clean Git history - Manage multiple projects
Task Execution → Git Operations
↓ ↓
Random Thought → thought-ideas branch
Serious Task → Feature branch + PR
Basic Setup¶
1. Install Git and GitHub CLI¶
# macOS
brew install git gh
# Ubuntu/Debian
sudo apt install git gh
# Verify installation
git --version
gh --version
2. Configure Git User¶
# Set global Git user (for agent commits)
git config --global user.name "Sleepless Agent"
git config --global user.email "agent@sleepless.local"
# Or use environment variables
export GIT_USER_NAME="Sleepless Agent"
export GIT_USER_EMAIL="agent@sleepless.local"
3. Authenticate GitHub CLI¶
# Interactive authentication
gh auth login
# Choose:
# - GitHub.com
# - HTTPS
# - Authenticate with browser
# Verify authentication
gh auth status
Repository Configuration¶
1. Local Repository Setup¶
# Initialize workspace repository
cd workspace/projects
git init
# Add remote
git remote add origin git@github.com:username/sleepless-workspace.git
# Initial commit
git add .
git commit -m "Initial workspace setup"
git push -u origin main
2. Configuration in config.yaml¶
git:
# Repository settings
use_remote_repo: true
remote_repo_url: git@github.com:username/sleepless-workspace.git
auto_create_repo: true
default_branch: main
# Commit settings
auto_commit: true
commit_message_format: "[Agent] {task_type}: {description}"
sign_commits: false # Set true if using GPG
# Pull request settings
create_pull_requests: true
pr_template: |
## Summary
{task_description}
## Changes
{file_changes}
## Task Details
- Task ID: {task_id}
- Priority: {priority}
- Duration: {duration}
Generated by Sleepless Agent
# Branch settings
branch_prefix:
random: "thought/"
serious: "feature/"
bug: "fix/"
docs: "docs/"
Workflow Patterns¶
1. Random Thoughts Workflow¶
Random thoughts are automatically committed to a single branch:
# Agent workflow for random thoughts
git checkout -b thought-ideas # One-time setup
git add .
git commit -m "Random thought: Explore async patterns"
git push origin thought-ideas
Configuration:
workflows:
random_thought:
branch: thought-ideas
auto_commit: true
auto_push: true
squash_commits: false # Keep all thoughts
2. Serious Tasks Workflow¶
Serious tasks create feature branches and PRs:
# Agent workflow for serious tasks
git checkout -b feature/implement-caching
git add .
git commit -m "Implement: Add caching layer to API"
git push origin feature/implement-caching
gh pr create --title "Add caching layer" --body "..."
Configuration:
workflows:
serious_task:
create_branch: true
branch_pattern: "feature/{task_slug}"
create_pr: true
auto_merge: false # Require manual review
delete_branch_after_merge: true
3. Project-Based Workflow¶
Tasks within projects share a workspace:
workflows:
project:
workspace_pattern: "projects/{project_name}"
branch_pattern: "{project_name}/{task_slug}"
group_commits: true
pr_per_milestone: true
Advanced Git Features¶
1. Commit Hooks¶
.gitmessage template:
[Agent] {TYPE}: Brief description
## What changed
- Detail 1
- Detail 2
## Why
Explanation of the change
Task: #{task_id}
Project: {project_name}
Pre-commit hook (.git/hooks/pre-commit):
#!/bin/bash
# Check for secrets
if git diff --cached --name-only | xargs grep -E "(api_key|secret|token|password)" ; then
echo "Error: Possible secrets detected"
exit 1
fi
# Validate Python syntax
for file in $(git diff --cached --name-only | grep "\.py$"); do
python -m py_compile "$file" || exit 1
done
2. Git Attributes¶
.gitattributes:
# Handle line endings
* text=auto
*.py text eol=lf
*.md text eol=lf
# Mark generated files
*_generated.* linguist-generated=true
workspace/tasks/** linguist-generated=true
# Exclude from diffs
*.log -diff
*.db -diff
3. Git Ignore Patterns¶
.gitignore:
# Environment
.env
.env.*
!.env.example
# Workspace
workspace/tasks/
workspace/data/*.db
workspace/data/*.db-journal
# Logs
*.log
logs/
# Python
__pycache__/
*.pyc
.pytest_cache/
# IDE
.vscode/
.idea/
Pull Request Automation¶
1. PR Templates¶
.github/pull_request_template.md:
## Description
{task_description}
## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Refactoring
## Testing
- [ ] Tests pass locally
- [ ] New tests added
- [ ] Documentation updated
## Task Information
- **Task ID**: {task_id}
- **Priority**: {priority}
- **Execution Time**: {duration}
## Files Changed
{file_list}
---
*Generated by Sleepless Agent*
2. Automated PR Creation¶
def create_pull_request(task, branch_name):
"""Create PR using GitHub CLI"""
# Prepare PR body
pr_body = format_pr_template(task)
# Create PR
cmd = [
'gh', 'pr', 'create',
'--title', task.description,
'--body', pr_body,
'--base', 'main',
'--head', branch_name
]
result = subprocess.run(cmd, capture_output=True)
if result.returncode == 0:
pr_url = result.stdout.decode().strip()
log.info(f"Created PR: {pr_url}")
return pr_url
else:
log.error(f"Failed to create PR: {result.stderr}")
return None
3. PR Labels and Assignment¶
github:
pr_settings:
auto_label: true
labels:
serious: "priority:high"
random: "type:exploration"
bug: "type:bug"
docs: "type:documentation"
auto_assign: true
assignees:
- username1
- username2
reviewers:
serious:
- senior-dev
documentation:
- docs-team
Multi-Repository Management¶
1. Repository Mapping¶
repositories:
main:
url: git@github.com:org/main-repo.git
path: workspace/repos/main
default_branch: develop
frontend:
url: git@github.com:org/frontend.git
path: workspace/repos/frontend
default_branch: main
backend:
url: git@github.com:org/backend.git
path: workspace/repos/backend
default_branch: main
# Task routing
task_routing:
frontend_tasks:
repository: frontend
branch_prefix: "feature/agent/"
backend_tasks:
repository: backend
branch_prefix: "feature/agent/"
2. Cross-Repository Operations¶
class MultiRepoManager:
def __init__(self, config):
self.repos = config['repositories']
def clone_all(self):
"""Clone all configured repositories"""
for name, repo in self.repos.items():
if not os.path.exists(repo['path']):
subprocess.run([
'git', 'clone',
repo['url'],
repo['path']
])
def update_all(self):
"""Pull latest changes for all repos"""
for name, repo in self.repos.items():
os.chdir(repo['path'])
subprocess.run(['git', 'pull'])
Security Best Practices¶
1. Secret Scanning¶
Pre-commit secret scanning:
# Install detect-secrets
pip install detect-secrets
# Generate baseline
detect-secrets scan > .secrets.baseline
# Pre-commit hook
detect-secrets-hook --baseline .secrets.baseline
2. Signed Commits¶
# Generate GPG key
gpg --gen-key
# Configure Git to sign commits
git config --global user.signingkey YOUR_KEY_ID
git config --global commit.gpgsign true
# Add to config.yaml
git:
sign_commits: true
gpg_key: YOUR_KEY_ID
3. Protected Branches¶
GitHub branch protection rules: - Require pull request reviews - Dismiss stale reviews - Require status checks - Include administrators - Restrict push access
Monitoring Git Operations¶
1. Git Metrics¶
def collect_git_metrics():
return {
'commits_today': count_commits_since(datetime.today()),
'pending_prs': count_open_prs(),
'branches_active': count_active_branches(),
'repo_size': get_repo_size(),
'uncommitted_changes': check_uncommitted()
}
2. Git Health Checks¶
#!/bin/bash
# git_health.sh
echo "Git Repository Health Check"
# Check for uncommitted changes
if [ -n "$(git status --porcelain)" ]; then
echo "⚠️ Uncommitted changes detected"
fi
# Check for unpushed commits
if [ -n "$(git log @{u}..)" ]; then
echo "⚠️ Unpushed commits found"
fi
# Check branch status
current_branch=$(git branch --show-current)
echo "Current branch: $current_branch"
# Check remote connectivity
if git ls-remote --exit-code --heads origin > /dev/null 2>&1; then
echo "✅ Remote repository accessible"
else
echo "❌ Cannot reach remote repository"
fi
Troubleshooting¶
Common Issues¶
-
Authentication failures
-
Merge conflicts
-
Large file issues
Recovery Procedures¶
-
Reset to clean state
-
Recover lost commits
Best Practices¶
1. Commit Guidelines¶
- Keep commits atomic and focused
- Write descriptive commit messages
- Include task ID in commits
- Sign commits when possible
2. Branch Management¶
- Use consistent naming conventions
- Clean up old branches regularly
- Protect important branches
- Use feature flags for long-running changes
3. PR Management¶
- Keep PRs small and reviewable
- Include tests with changes
- Update documentation
- Respond to reviews promptly
4. Repository Hygiene¶
- Regular garbage collection
- Archive old branches
- Clean up large files
- Maintain .gitignore