Implement git_ops.rs providing AutoresearchGitOps struct that wraps git2::Repository for branch creation, committing with last_keep_sha tracking, hard-reset discard, and branch checkout — enabling the autoresearch experiment loop to keep/discard mutations via real git operations.
Components
Component
Description
Complexity
Dependencies
AutoresearchGitOps struct
Core struct wrapping project_dir and last_keep_sha, with new(), head_sha(), open_repo() methods. Opens git2::Repository on demand to avoid borrow issues.
low
-
Branch operations
create_branch() creates a new branch from HEAD and checks it out, setting last_keep_sha. checkout_branch() checks out an existing branch for resume scenarios.
medium
AutoresearchGitOps struct
Commit operation
commit() stages all changes via index.add_all, writes tree, creates commit with forge-autoresearch signature, updates last_keep_sha to new commit SHA.
medium
AutoresearchGitOps struct
Reset operation
reset_to_last_keep() performs git2::ResetType::Hard to the stored last_keep_sha, reverting working directory to last kept state.
low
AutoresearchGitOps struct
LoopGitOps trait implementation
Implement LoopGitOps trait from loop_runner.rs for AutoresearchGitOps. Requires interior mutability (Mutex) for last_keep_sha since trait uses &self but mutations need &mut self.
Add pub mod git_ops to src/cmd/autoresearch/mod.rs
low
-
Code Patterns
Create branch from HEAD
code
let repo = Repository::open(project_dir)?;
let head_commit = repo.head()?.peel_to_commit()?;
repo.branch(branch_name, &head_commit, false)?;
repo.set_head(&format!("refs/heads/{}", branch_name))?;
repo.checkout_head(Some(git2::build::CheckoutBuilder::new().force()))?;
Commit all changes
code
let repo = Repository::open(project_dir)?;
let mut index = repo.index()?;
index.add_all(["*"].iter(), IndexAddOption::DEFAULT, None)?;
index.write()?;
let tree_id = index.write_tree()?;
let tree = repo.find_tree(tree_id)?;
let sig = Signature::now("forge-autoresearch", "forge@localhost")?;
let head = repo.head()?.peel_to_commit()?;
let oid = repo.commit(Some("HEAD"), &sig, &sig, message, &tree, &[&head])?;
Hard reset to commit
code
let repo = Repository::open(project_dir)?;
let commit = repo.find_commit(oid)?;
let obj = commit.as_object();
repo.reset(obj, ResetType::Hard, None)?;
Checkout existing branch
code
let repo = Repository::open(project_dir)?;
repo.set_head(&format!("refs/heads/{}", branch_name))?;
repo.checkout_head(Some(git2::build::CheckoutBuilder::new().force()))?;
Acceptance Criteria
cargo test --lib cmd::autoresearch::git_ops passes with 11+ tests green
src/cmd/autoresearch/git_ops.rs exists with AutoresearchGitOps struct
create_branch() creates a new git branch from HEAD and checks it out
commit() stages all changes, creates a commit with forge-autoresearch signature, and updates last_keep_sha
reset_to_last_keep() performs git reset --hard to the stored last_keep_sha
checkout_branch() checks out an existing branch and sets last_keep_sha for resume
Full keep/discard cycle works: committed changes persist after keep, file changes revert after discard
All git2 operations use anyhow::Context for error enrichment
cargo clippy -- -D warnings passes clean
AutoresearchGitOps implements LoopGitOps trait (using Mutex for interior mutability if trait uses &self)
This spec was auto-generated from a design document.Original design: docs/superpowers/specs/autoresearch-tasks/T14-git-integration.md
SKILLS AND CONVENTIONS
The following skills provide guidance for this phase:
SKILL: RUST CONVENTIONS
Rust Conventions
Follow these Rust conventions for all code in this project:
Code Style
Use rustfmt defaults for formatting
Run cargo clippy and address all warnings before committing
Prefer ? operator for error propagation over .unwrap() in library code
Use .expect("meaningful message") only when failure indicates a bug
Error Handling
Use anyhow::Result for application code and CLI
Use thiserror for library errors that callers need to match on
Provide context with .context() or .with_context()
Log errors at the appropriate level (error, warn, info)
Naming
Use snake_case for functions, methods, variables, and modules
Use CamelCase for types, traits, and enum variants
Prefix private helper functions with underscore only if they shadow public ones
Use descriptive names; avoid single letters except for trivial loops
Module Structure
One module per file, except for small related types
Put tests in a #[cfg(test)] mod tests block at the end of each file
Use pub(crate) for internal visibility when appropriate
Re-export important types from the crate root
Documentation
Add doc comments (///) for all public items
Include examples in doc comments for complex functions
Use // comments sparingly for non-obvious implementation details
Keep CLAUDE.md updated with key concepts and patterns
Testing
Write unit tests for all non-trivial functions
Use descriptive test names: test_<function>_<scenario>
Group related tests with comment headers
Use tempdir() for tests that need filesystem access
SKILL: TESTING STRATEGY
Testing Strategy
Apply this testing strategy for all new code:
Test Levels
Unit Tests - Test individual functions in isolation
#[test]
fn test_example() {
// Arrange - Set up test data and conditions
let input = create_test_input();
// Act - Execute the code under test
let result = function_under_test(input);
// Assert - Verify the results
assert_eq!(result, expected_value);
}
What to Test
Happy path (normal operation)
Edge cases (empty input, boundaries, limits)
Error conditions (invalid input, failures)
Regression tests for fixed bugs
Test Helpers
Create helper functions for common test setup
Use tempdir() for filesystem tests
Use builders for complex test data
Running Tests
bash
cargo test # Run all tests
cargo test <test_name> # Run specific test
cargo test -- --nocapture # Show println! output
SKILL: CLI DESIGN
CLI Design
Follow these conventions for CLI commands and user interaction:
Command Structure
Use clap with derive macros for argument parsing
Organize commands as subcommands where logical
Provide both short and long flags for common options
Include helpful examples in help text
User Feedback
Print progress information during long operations
Use clear, action-oriented language ("Creating...", "Loading...")
Show success/failure status clearly
Provide next steps on completion
Output Formatting
Use consistent indentation for structured output
Add blank lines to separate sections for readability
Keep line length reasonable for terminal display
Use colors sparingly (via console crate) for emphasis
Error Messages
Be specific about what went wrong
Suggest how to fix the problem when possible
Include relevant file paths or values
Exit with non-zero status on error
Confirmation Prompts
Require confirmation for destructive operations
Provide --force flag to skip prompts in scripts
Default to the safer option (usually "no")
Example Pattern
rust
fn cmd_example(project_dir: &Path) -> Result<()> {
println!("Performing operation...");
// Do work
let result = do_work(project_dir)?;
// Report success
println!("Operation complete: {} items processed", result.count);
println!();
println!("Next steps:");
println!(" Run 'forge next-command' to continue");
Ok(())
}
SKILL: TDD WORKFLOW
TDD Workflow
Apply Test-Driven Development when implementing new functionality. Use your judgment
to determine when TDD is appropriate — it's most valuable for business logic,
algorithms, and complex state management.
Verify both instances truly represent the same concept
Extract to a well-named function/constant/type
Update all call sites
Run tests to confirm behavior unchanged
Warning
Premature abstraction is worse than duplication. Only abstract when:
The pattern appears 3+ times, OR
The duplication causes active maintenance burden
SKILL: SECURE CODING
Secure Coding
Follow these secure coding practices for all code in this project.
Input Validation
Validate all external input (user input, API responses, file contents)
Use allowlists over denylists when validating
Sanitize data before use in SQL, shell commands, or HTML output
Validate early, at system boundaries (CLI args, file reads, network responses)
Rust-Specific Security
Minimize unsafe blocks; document safety invariants when used
Use established crypto libraries (ring, rustls) — never roll your own
Validate and canonicalize file paths to prevent directory traversal
Handle symlinks carefully; use canonicalize() before path operations
Prefer OsStr/OsString for paths from external sources
Command Execution
Never interpolate untrusted input into shell commands
Use Command::new().arg() instead of shell string concatenation
Validate command arguments against an allowlist when possible
OWASP Awareness
Injection: Use parameterized queries, avoid string interpolation
Broken Auth: Never hardcode credentials, use secure session management
Sensitive Data: Encrypt at rest and in transit, minimize data collection
Broken Access Control: Verify permissions on every request, deny by default
Logging: Log security events, never log secrets or PII
Secrets Management
Never commit secrets to version control
Use environment variables or secret managers for credentials
Add sensitive file patterns to .gitignore (.env, *.key, credentials.*)
Error Handling
Never expose stack traces or internal details to users
Log detailed errors server-side only
Return generic error messages to external callers
Use .context() to add information without leaking internals
SKILL: CONTEXT7 INTEGRATION
Context7 Integration
Query Context7 for up-to-date library documentation before implementing code that
uses external dependencies. This ensures you use current APIs and best practices.
When to Query Context7
Before first use of an unfamiliar or rapidly-evolving library
When implementing patterns you haven't used recently
When errors suggest API changes or deprecations
When the spec mentions specific library features
When NOT to Query
Standard library features (Rust std, Python built-ins)
Well-known stable APIs you're confident about (serde, clap basics)
Query once per library per phase — avoid redundant queries for the same library
Be specific in queries: "jwt token validation" not just "auth"
If the library isn't found, proceed with general knowledge but note the gap
Limit to 3 Context7 queries per phase to avoid excessive API calls
Handling Missing Libraries
If Context7 doesn't have documentation for a library:
Check the library's README or docs.rs
Proceed with general knowledge
Add extra test coverage for that integration
SKILL: AGENT REVIEW
Agent Review
Before claiming phase completion, spawn an independent review agent to verify
your implementation. This catches issues you may have missed.
When to Trigger Review
After all implementation for the phase is complete
After all tests pass
Before emitting <promise>DONE</promise>
How to Spawn Review Agent
Use the Task tool with these parameters:
subagent_type: "general-purpose"
description: "Review phase N implementation" (replace N with phase number)
prompt: Include the phase context and checklist below
Example prompt to pass to the review agent:
text
Review the code changes for Phase {N} - {phase name}.
Run this command to see what changed:
git diff HEAD~{iterations} --stat
git diff HEAD~{iterations}
Check for:
1. DRY violations - duplicated code that should be extracted
2. Security issues - injection risks, hardcoded secrets, missing validation
3. Test coverage - are edge cases covered, are tests meaningful
4. Code clarity - naming, structure, comments where needed
Report issues as a numbered list with file:line references.
If no issues found, respond with: REVIEW PASSED
Replace {N} with the phase number, {phase name} with the phase name, and
{iterations} with the number of iterations completed in this phase.
Handling Review Results
REVIEW PASSED: Proceed to emit <promise>DONE</promise>
Issues found: Address each issue, re-run tests, then request another review
Max 2 review cycles: If issues persist after 2 reviews, emit <blocker>review-failed</blocker> and describe the unresolved issues
Review Scope
The reviewer checks only the current phase's changes, not the entire codebase.
Use git diff HEAD~N where N is the iteration count to see phase changes.
CRITICAL RULES
Follow the spec requirements exactly
Check existing code before making changes
Run tests/checks to verify your work
Only output LOOP_GIT_OPS TRAIT TESTS WRITTEN when the task is FULLY complete and verified
If tests fail, fix them before claiming completion
PROGRESS SIGNALS (Optional)
You can use these tags to communicate your progress:
When complete, output:
LOOP_GIT_OPS TRAIT TESTS WRITTEN
Assistant
I'll start by exploring the existing code to understand the current state of the implementation.
Assistant
Let me read the actual files to understand the current state precisely.
Assistant
Now I understand the task. The existing tests call methods directly on AutoresearchGitOps. Phase 03 requires tests that exercise the LoopGitOps trait interface (via trait objects) to verify the trait implementation contract. Let me write those tests.
Assistant
Now let me run the tests to verify they pass.
Assistant
Tests aren't being found. Let me check how the project is structured.
Assistant
The test fails because git reset --hard doesn't remove untracked files — it only reverts tracked file changes. Let me fix the test to match actual git semantics.
Assistant
Also fix the unused variable warning:
Assistant
All 25 tests pass (14 existing + 11 new trait tests). Let me run clippy to verify no warnings.
Assistant
The clippy warnings are all in pre-existing code outside of git_ops.rs, not in my changes. Let me verify that clippy is clean specifically for the git_ops module:
Assistant
No clippy warnings in git_ops.rs. The tests are clean. Let me verify the final state of the file.
Assistant
All 25 tests pass (14 existing + 11 new LoopGitOps trait tests), no clippy warnings in git_ops.rs.
New trait tests added (all use Box<dyn LoopGitOps>):
Test
What it verifies
test_trait_head_sha_returns_valid_hex
head_sha via trait returns 40-char hex
test_trait_create_branch_and_checkout
create_branch works through trait
test_trait_commit_returns_new_sha
commit advances HEAD, returns valid SHA
test_trait_reset_reverts_uncommitted_changes
reset restores tracked file content
test_trait_reset_without_keep_fails
reset errors with no keep SHA set
test_trait_checkout_existing_branch
checkout_branch via trait succeeds
test_trait_full_keep_discard_cycle
complete keep/discard through trait
test_trait_multiple_keep_discard_cycles
4 alternating keep/discard cycles
test_trait_commit_after_reset_works
commit succeeds after a discard reset
test_trait_create_branch_duplicate_fails
duplicate branch errors via trait
test_trait_checkout_nonexistent_branch_fails
nonexistent branch errors via trait
LOOP_GIT_OPS TRAIT TESTS WRITTEN
User
SKILL: AGENT REVIEW
Agent Review
Before claiming phase completion, spawn an independent review agent to verify
your implementation. This catches issues you may have missed.
When to Trigger Review
After all implementation for the phase is complete
After all tests pass
Before emitting <promise>DONE</promise>
How to Spawn Review Agent
Use the Task tool with these parameters:
subagent_type: "general-purpose"
description: "Review phase N implementation" (replace N with phase number)
prompt: Include the phase context and checklist below
Example prompt to pass to the review agent:
text
Review the code changes for Phase {N} - {phase name}.
Run this command to see what changed:
git diff HEAD~{iterations} --stat
git diff HEAD~{iterations}
Check for:
1. DRY violations - duplicated code that should be extracted
2. Security issues - injection risks, hardcoded secrets, missing validation
3. Test coverage - are edge cases covered, are tests meaningful
4. Code clarity - naming, structure, comments where needed
Report issues as a numbered list with file:line references.
If no issues found, respond with: REVIEW PASSED
Replace {N} with the phase number, {phase name} with the phase name, and
{iterations} with the number of iterations completed in this phase.
Handling Review Results
REVIEW PASSED: Proceed to emit <promise>DONE</promise>
Issues found: Address each issue, re-run tests, then request another review
Max 2 review cycles: If issues persist after 2 reviews, emit <blocker>review-failed</blocker> and describe the unresolved issues
Review Scope
The reviewer checks only the current phase's changes, not the entire codebase.
Use git diff HEAD~N where N is the iteration count to see phase changes.
CRITICAL RULES
Follow the spec requirements exactly
Check existing code before making changes
Run tests/checks to verify your work
Only output LOOP_GIT_OPS TRAIT TESTS WRITTEN when the task is FULLY complete and verified
If tests fail, fix them before claiming completion
PROGRESS SIGNALS (Optional)
You can use these tags to communicate your progress:
When complete, output:
LOOP_GIT_OPS TRAIT TESTS WRITTEN
User
SKILL: CONTEXT7 INTEGRATION
Context7 Integration
Query Context7 for up-to-date library documentation before implementing code that
uses external dependencies. This ensures you use current APIs and best practices.
When to Query Context7
Before first use of an unfamiliar or rapidly-evolving library
When implementing patterns you haven't used recently
When errors suggest API changes or deprecations
When the spec mentions specific library features
When NOT to Query
Standard library features (Rust std, Python built-ins)
Well-known stable APIs you're confident about (serde, clap basics)
Verify both instances truly represent the same concept
Extract to a well-named function/constant/type
Update all call sites
Run tests to confirm behavior unchanged
Warning
Premature abstraction is worse than duplication. Only abstract when:
The pattern appears 3+ times, OR
The duplication causes active maintenance burden
User
SKILL: TDD WORKFLOW
TDD Workflow
Apply Test-Driven Development when implementing new functionality. Use your judgment
to determine when TDD is appropriate — it's most valuable for business logic,
algorithms, and complex state management.
#[test]
fn test_example() {
// Arrange - Set up test data and conditions
let input = create_test_input();
// Act - Execute the code under test
let result = function_under_test(input);
// Assert - Verify the results
assert_eq!(result, expected_value);
}
What to Test
Happy path (normal operation)
Edge cases (empty input, boundaries, limits)
Error conditions (invalid input, failures)
Regression tests for fixed bugs
Test Helpers
Create helper functions for common test setup
Use tempdir() for filesystem tests
Use builders for complex test data
Running Tests
bash
cargo test # Run all tests
cargo test <test_name> # Run specific test
cargo test -- --nocapture # Show println! output