Create 5 performance benchmark cases (2 mined from real forge git history, 3 synthetic) that test whether the PerformanceOracle specialist agent can detect real performance issues. Each benchmark consists of a code.rs with buggy Rust code, context.md explaining the domain, and expected.json defining must_find and must_not_flag entries with severity and location.
Components
Component
Description
Complexity
Dependencies
Benchmark Loading Test
Test that BenchmarkSuite::load(forge_dir, "performance") returns exactly 5 cases, each with non-empty code, context, and at least one must_find entry. Validates all 5 benchmark names exist.
low
-
sync-event-batching Benchmark
Real benchmark mined from commit 06cd7fe. Code shows synchronous Mutex lock (lock_sync) inside a tokio task blocking the async runtime, lock held during entire batch flush, and no time-based flush. Three must_find entries (critical/high/medium), two must_not_flag entries.
medium
-
non-shared-connection Benchmark
Real benchmark mined from commit 54b9a63. Code shows DbHandle creating a new database connection on every conn() call, causing data isolation for in-memory DBs and connection overhead for file-based DBs. Three must_find entries, two must_not_flag entries.
medium
-
n-plus-one-query Benchmark
Synthetic benchmark showing classic N+1 query pattern in a dashboard builder: nested loops each making individual DB queries instead of JOINs or batch queries. Three must_find entries, two must_not_flag entries.
low
-
blocking-in-async Benchmark
Synthetic benchmark showing blocking std::fs I/O, CPU-intensive hashing, and std::process::Command inside async functions instead of using tokio::fs, spawn_blocking, and tokio::process. Four must_find entries, two must_not_flag entries.
low
-
unnecessary-cloning Benchmark
Synthetic benchmark showing unnecessary .clone() calls on large data structures in hot-path event processing: cloning in filter loops, taking ownership unnecessarily, cloning in aggregation, and chunks().to_vec(). Four must_find entries, two must_not_flag entries.
low
-
Code Patterns
Benchmark Directory Structure
code
.forge/autoresearch/benchmarks/performance/<case-name>/
code.rs — Rust code with performance bugs
context.md — Domain context explaining the code
expected.json — Must-find issues and must-not-flag false positives
Expected JSON Structure
code
{
"must_find": [
{
"id": "issue-id",
"severity": "critical|high|medium",
"description": "What the issue is",
"location": "code.rs:line-range"
}
],
"must_not_flag": [
{
"id": "fp-id",
"description": "Why this is not a problem"
}
]
}
Benchmark Suite Load Test
code
#[test]
fn test_performance_benchmarks_load() {
let forge_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let suite = BenchmarkSuite::load(forge_dir, "performance").unwrap();
assert_eq!(suite.specialist, "performance");
assert_eq!(suite.cases.len(), 5);
for case in &suite.cases {
assert!(!case.code.is_empty());
assert!(!case.context.is_empty());
assert!(!case.expected.must_find.is_empty());
}
}
#[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 PERFORMANCE BENCHMARK TEST 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:
X% - Report completion percentage (0-100)
description - Signal you're blocked and need help
new approach - Signal you're changing strategy
Example: 50% indicates you're halfway done.
TASK
Implement phase 01 - Write performance benchmark loading test
When complete, output:
PERFORMANCE BENCHMARK TEST WRITTEN
Assistant
I'll start by exploring the existing codebase to understand the benchmark infrastructure and autoresearch module structure.
Assistant
Now let me look at the existing benchmarks for reference patterns.
Assistant
Let me look at one existing benchmark case for reference, then check the git history for the two real commits.
Assistant
Let me check the specific commits mentioned in the spec.
Assistant
Good, both commits exist. Let me see what they changed.
Assistant
Let me get the pre-fix event batching code more specifically - looking for the lock_sync pattern.
Assistant
Now let me get more detail on the pre-fix code for the two real benchmarks to craft accurate code.rs files.
Assistant
Now I have all the context I need. Let me create all 5 benchmark cases. I'll create them in parallel.
Assistant
Now creating the 3 synthetic benchmarks.
Assistant
Now let me add the performance benchmarks loading test to benchmarks.rs. I'll add it after the architecture test.
Assistant
I already read it earlier, but let me read it again.
Assistant
Now let me validate the JSON files and run the test.
Assistant
All JSON files validate and the test passes. Let me also run the existing benchmark tests to make sure I didn't break anything.
Assistant
All 15 benchmark tests pass, including the new performance test.
cargo test --lib autoresearch::benchmarks::tests::test_performance_benchmarks_load passes
100%
PERFORMANCE BENCHMARK TEST 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 PERFORMANCE BENCHMARK TEST 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:
X% - Report completion percentage (0-100)
description - Signal you're blocked and need help
new approach - Signal you're changing strategy
Example: 50% indicates you're halfway done.
TASK
Implement phase 01 - Write performance benchmark loading test
When complete, output:
PERFORMANCE BENCHMARK TEST 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