This file provides specialized guidance for AI agents working with the bgit codebase.
bgit is a sophisticated Git workflow automation tool built in Rust with a trait-based, step-driven architecture. The system orchestrates complex Git workflows through interactive steps while enforcing smart rules to prevent common Git mistakes.
- Step-Based Execution Engine (
src/step.rs+src/workflow_queue.rs) - Rules Validation System (
src/rules/) - Atomic Git Events (
src/events/) - Cross-Platform Authentication (
src/auth/with SSH agent management) - Two-Tier Configuration (local + global config system)
- Hook Execution Framework (platform-specific implementations)
// Core step execution
pub(crate) trait ActionStep {
fn execute(&self) -> Result<Step, Box<BGitError>>;
}
pub(crate) trait PromptStep {
fn execute(&self) -> Result<Step, Box<BGitError>>;
}
// Git operations
pub(crate) trait AtomicEvent<'a> {
fn execute(&self) -> Result<bool, Box<BGitError>>;
fn pre_execute_hook(&self) -> Result<bool, Box<BGitError>>;
fn post_execute_hook(&self) -> Result<bool, Box<BGitError>>;
}
// Validation rules
pub(crate) trait Rule {
fn check(&self) -> Result<RuleOutput, Box<BGitError>>;
fn try_fix(&self) -> Result<bool, Box<BGitError>>;
}- ActionSteps:
ta##_descriptive_name.rs(e.g.,ta01_is_git_repo.rs) - PromptSteps:
pa##_ask_descriptive_action.rs(e.g.,pa05_ask_to_add.rs) - Rules:
a##_rule_description.rs(e.g.,a12_no_secrets_staged.rs) - Events:
git_operation.rs(e.g.,git_commit.rs,git_push.rs)
- Each module typically has a single public struct implementing the relevant trait
- Error handling uses
BGitErrorwith contextual information - Configuration access through
BGitConfigandBGitGlobalConfig - Cross-platform implementations use conditional compilation (
#[cfg(unix)],#[cfg(windows)])
src/
├── main.rs # Entry point and CLI routing
├── step.rs # Core execution model
├── workflow_queue.rs # Workflow execution engine
├── bgit_error.rs # Structured error handling
├── rules.rs + rules/ # validation rules
├── events.rs + events/ # Git operations
├── auth/ + auth/ssh/ # Authentication and SSH management
├── config/ # Two-tier configuration system
├── workflows/default/action/ # ActionStep implementations
├── workflows/default/prompt/ # PromptStep implementations
├── hook_executor/ # Cross-platform hook execution
├── llm_tools/ # AI integration components
└── cmd/ # CLI command implementations
- Rule Structure: Implement
Ruletrait insrc/rules/aXX_rule_name.rs - Error Handling: Use
BGitErrorwith appropriate workflow type - Configuration: Add rule to
WorkflowRulesenum if configurable - Auto-fixing: Implement
try_fix()for recoverable failures - Testing: Focus on edge cases and cross-platform compatibility
- Step Type: Choose
ActionStep(automated) vsPromptStep(interactive) - Step Progression: Define clear next step logic in
execute()return - State Management: Use Git repository state to determine flow
- Error Recovery: Handle failures gracefully with appropriate error context
- User Experience: For prompts, provide clear choices and guidance
- Event Wrapper: Implement
AtomicEventtrait with proper Git2 integration - Rule Integration: Call appropriate rules in
pre_execute_hook() - Hook Support: Implement pre/post hook execution points
- Authentication: Integrate with existing auth system when needed
- Platform Support: Ensure cross-platform compatibility
// Local configuration (repository-specific)
let config = BGitConfig::load()?;
let rule_level = config.workflow_rules.get_rule_level("default", "a12_no_secrets_staged");
// Global configuration (user-wide)
let global_config = BGitGlobalConfig::load_global()?;
let auth_preference = global_config.auth_preference;// Structured error creation
BGitError::new(
"Rule Check Failed".to_string(),
format!("Secret detected in file: {}", file_path),
BGitErrorWorkflowType::Rules,
step_name.to_string(),
NO_EVENT.to_string(),
rule_name.to_string(),
)
// Rule execution with auto-fixing
match rule.check() {
Ok(RuleOutput::Success) => Ok(true),
Ok(RuleOutput::Exception(msg)) => {
if rule.try_fix()? {
rule.check() // Re-check after fix
} else {
Err(error)
}
}
Err(e) => Err(e),
}The a12_no_secrets_staged rule demonstrates sophisticated pattern matching:
- Regex Detection: patterns for different secret types
- Entropy Analysis: Statistical randomness measurement
- Context Validation: Custom validators for specific secret formats
- False Positive Reduction: Whitelist common words, detect patterns
The SSH system (src/auth/ssh/) provides:
- Agent Lifecycle: Automatic creation, key loading, cleanup
- Cross-Platform: Unix sockets vs Windows named pipes
- Key Discovery: Automatic
~/.ssh/id_*detection - Retry Logic: Configurable attempts with exponential backoff
- Stale Cleanup: Process validation and socket cleanup
- Rule Logic: Test detection, fixing, and edge cases
- Step Progression: Verify correct workflow routing
- Configuration: Test parsing, defaults, and overrides
- Cross-Platform: Validate platform-specific implementations
- Error Handling: Ensure proper error propagation and context
- Use
tempfilefor temporary Git repositories - Use
assert_cmdfor CLI testing - Mock external dependencies (SSH agents, remote repositories)
- Test complete workflow scenarios end-to-end
- Rule Execution: Cache expensive checks when possible
- Git Operations: Minimize repository state queries
- SSH Agent: Reuse connections, avoid redundant key loading
- Configuration: Load once and pass references
- Pattern Matching: Compile regex patterns once
- Use
Box<dyn Trait>for trait objects to enable dynamic dispatch - Prefer
&stroverStringfor temporary string operations - Use
Arc<>for shared configuration data across threads
- Credentials: Base64 encode in configuration files
- Memory: Clear sensitive data after use when possible
- Logging: Never log credentials or secrets
- File Permissions: Respect SSH key file permissions
- Process Isolation: Clean up SSH agents and temporary files
- Maintain high sensitivity for security rules
- Balance false positives vs false negatives
- Provide clear remediation guidance
- Support whitelist mechanisms for known safe patterns
- Implement auth strategy in
src/auth/ - Update
PreferredAuthenum - Integrate with existing event system
- Add configuration options
- Test cross-platform compatibility
- Create new rule file following naming convention
- Implement
Ruletrait with proper error handling - Add to rule registry in
src/rules.rs - Update configuration schema if needed
- Add comprehensive tests
- Create event file in
src/events/ - Implement
AtomicEventtrait - Integrate with rules system
- Add hook support points
- Update workflow steps as needed
- Understand Traits First: Focus on understanding the core traits before diving into implementations
- Follow Data Flow: Trace how steps, rules, and events interact
- Check Cross-Platform Code: Pay attention to
#[cfg]attributes for platform differences - Review Error Paths: Understand how errors propagate through the system
- Study Configuration: Understand how behavior is customized through config
- Follow Existing Patterns: Match naming conventions and code structure
- Implement Error Handling: Always include proper
BGitErrorcontext - Consider Cross-Platform: Use appropriate platform abstractions
- Add Documentation: Include clear docstrings for public interfaces
- Test Thoroughly: Consider edge cases and error conditions
- No Emoji Symbols: All logging output must be emoji-free for compatibility across terminals and systems
- Clear Status Messages: Use plain text for success/failure indicators
- Use "Successfully" instead of "✓"
- Use "Failed" instead of "✗"
- Use "Warning" instead of "⚠"
- Debug vs User Output: Debug logs (
debug!()) are for developers, user output (println!()) should be concise - Consistent Formatting: Maintain consistent message structure across similar operations
- Cross-Platform Text: Ensure all text displays correctly on Unix, Windows, and different terminal emulators
// Good: Emoji-free logging
debug!("Successfully created persistent agent");
println!("SSH key '{}' added successfully!", key_name);
// Bad: Contains emoji symbols
debug!("✓ Successfully created persistent agent");
println!("✓ SSH key '{}' added successfully!", key_name);- Ignoring Platform Differences: Not handling Windows vs Unix differences
- Poor Error Context: Generic error messages without proper context
- Rule Bypass: Forgetting to integrate rules into new operations
- Memory Leaks: Not properly cleaning up SSH agents or temporary resources
- Configuration Conflicts: Not respecting user configuration overrides
This guide should help AI agents understand the bgit codebase architecture and contribute effectively while maintaining the existing code quality and design patterns.