mirror of
https://github.com/affaan-m/everything-claude-code.git
synced 2026-03-30 13:43:26 +08:00
feat: add C++ language support and hook tests (#539)
- agents: cpp-build-resolver, cpp-reviewer - commands: cpp-build, cpp-review, cpp-test - rules: cpp/ (coding-style, hooks, patterns, security, testing) - tests: 9 new hook test files with comprehensive coverage Cherry-picked from PR #436.
This commit is contained in:
173
commands/cpp-build.md
Normal file
173
commands/cpp-build.md
Normal file
@@ -0,0 +1,173 @@
|
||||
---
|
||||
description: Fix C++ build errors, CMake issues, and linker problems incrementally. Invokes the cpp-build-resolver agent for minimal, surgical fixes.
|
||||
---
|
||||
|
||||
# C++ Build and Fix
|
||||
|
||||
This command invokes the **cpp-build-resolver** agent to incrementally fix C++ build errors with minimal changes.
|
||||
|
||||
## What This Command Does
|
||||
|
||||
1. **Run Diagnostics**: Execute `cmake --build`, `clang-tidy`, `cppcheck`
|
||||
2. **Parse Errors**: Group by file and sort by severity
|
||||
3. **Fix Incrementally**: One error at a time
|
||||
4. **Verify Each Fix**: Re-run build after each change
|
||||
5. **Report Summary**: Show what was fixed and what remains
|
||||
|
||||
## When to Use
|
||||
|
||||
Use `/cpp-build` when:
|
||||
- `cmake --build build` fails with errors
|
||||
- Linker errors (undefined references, multiple definitions)
|
||||
- Template instantiation failures
|
||||
- Include/dependency issues
|
||||
- After pulling changes that break the build
|
||||
|
||||
## Diagnostic Commands Run
|
||||
|
||||
```bash
|
||||
# CMake configure
|
||||
cmake -B build -S .
|
||||
|
||||
# Build
|
||||
cmake --build build 2>&1 | head -100
|
||||
|
||||
# Static analysis (if available)
|
||||
clang-tidy src/*.cpp -- -std=c++17
|
||||
cppcheck --enable=all src/
|
||||
```
|
||||
|
||||
## Example Session
|
||||
|
||||
```text
|
||||
User: /cpp-build
|
||||
|
||||
Agent:
|
||||
# C++ Build Resolution
|
||||
|
||||
## Initial Diagnostics
|
||||
|
||||
```bash
|
||||
$ cmake --build build
|
||||
src/service/user.cpp:25:15: error: use of undeclared identifier 'UserRepository'
|
||||
src/handler/api.cpp:42:9: error: no matching function for call to 'process'
|
||||
src/handler/api.cpp:58:1: error: non-void function does not return a value
|
||||
```
|
||||
|
||||
Errors found: 3
|
||||
|
||||
## Fix 1: Undeclared Identifier
|
||||
|
||||
File: src/service/user.cpp:25
|
||||
Error: use of undeclared identifier 'UserRepository'
|
||||
Cause: Missing include
|
||||
|
||||
```cpp
|
||||
// Added include
|
||||
#include "repository/user_repository.hpp"
|
||||
```
|
||||
|
||||
```bash
|
||||
$ cmake --build build
|
||||
# 2 errors remaining
|
||||
```
|
||||
|
||||
## Fix 2: No Matching Function
|
||||
|
||||
File: src/handler/api.cpp:42
|
||||
Error: no matching function for call to 'process'
|
||||
|
||||
```cpp
|
||||
// Changed
|
||||
process(params.get("count"));
|
||||
// To
|
||||
process(std::stoi(params.get("count")));
|
||||
```
|
||||
|
||||
```bash
|
||||
$ cmake --build build
|
||||
# 1 error remaining
|
||||
```
|
||||
|
||||
## Fix 3: Missing Return
|
||||
|
||||
File: src/handler/api.cpp:58
|
||||
Error: non-void function does not return a value
|
||||
|
||||
```cpp
|
||||
std::optional<User> getUser(const std::string& id) {
|
||||
if (id.empty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
auto user = findUser(id);
|
||||
// Added missing return
|
||||
return user;
|
||||
}
|
||||
```
|
||||
|
||||
```bash
|
||||
$ cmake --build build
|
||||
# Build successful!
|
||||
```
|
||||
|
||||
## Final Verification
|
||||
|
||||
```bash
|
||||
$ ctest --test-dir build --output-on-failure
|
||||
Test project build
|
||||
1/5 Test #1: unit_tests ........ Passed 0.02 sec
|
||||
2/5 Test #2: integration_tests Passed 0.15 sec
|
||||
All tests passed.
|
||||
```
|
||||
|
||||
## Summary
|
||||
|
||||
| Metric | Count |
|
||||
|--------|-------|
|
||||
| Build errors fixed | 3 |
|
||||
| Linker errors fixed | 0 |
|
||||
| Files modified | 2 |
|
||||
| Remaining issues | 0 |
|
||||
|
||||
Build Status: ✅ SUCCESS
|
||||
```
|
||||
|
||||
## Common Errors Fixed
|
||||
|
||||
| Error | Typical Fix |
|
||||
|-------|-------------|
|
||||
| `undeclared identifier` | Add `#include` or fix typo |
|
||||
| `no matching function` | Fix argument types or add overload |
|
||||
| `undefined reference` | Link library or add implementation |
|
||||
| `multiple definition` | Use `inline` or move to .cpp |
|
||||
| `incomplete type` | Replace forward decl with `#include` |
|
||||
| `no member named X` | Fix member name or include |
|
||||
| `cannot convert X to Y` | Add appropriate cast |
|
||||
| `CMake Error` | Fix CMakeLists.txt configuration |
|
||||
|
||||
## Fix Strategy
|
||||
|
||||
1. **Compilation errors first** - Code must compile
|
||||
2. **Linker errors second** - Resolve undefined references
|
||||
3. **Warnings third** - Fix with `-Wall -Wextra`
|
||||
4. **One fix at a time** - Verify each change
|
||||
5. **Minimal changes** - Don't refactor, just fix
|
||||
|
||||
## Stop Conditions
|
||||
|
||||
The agent will stop and report if:
|
||||
- Same error persists after 3 attempts
|
||||
- Fix introduces more errors
|
||||
- Requires architectural changes
|
||||
- Missing external dependencies
|
||||
|
||||
## Related Commands
|
||||
|
||||
- `/cpp-test` - Run tests after build succeeds
|
||||
- `/cpp-review` - Review code quality
|
||||
- `/verify` - Full verification loop
|
||||
|
||||
## Related
|
||||
|
||||
- Agent: `agents/cpp-build-resolver.md`
|
||||
- Skill: `skills/cpp-coding-standards/`
|
||||
132
commands/cpp-review.md
Normal file
132
commands/cpp-review.md
Normal file
@@ -0,0 +1,132 @@
|
||||
---
|
||||
description: Comprehensive C++ code review for memory safety, modern C++ idioms, concurrency, and security. Invokes the cpp-reviewer agent.
|
||||
---
|
||||
|
||||
# C++ Code Review
|
||||
|
||||
This command invokes the **cpp-reviewer** agent for comprehensive C++-specific code review.
|
||||
|
||||
## What This Command Does
|
||||
|
||||
1. **Identify C++ Changes**: Find modified `.cpp`, `.hpp`, `.cc`, `.h` files via `git diff`
|
||||
2. **Run Static Analysis**: Execute `clang-tidy` and `cppcheck`
|
||||
3. **Memory Safety Scan**: Check for raw new/delete, buffer overflows, use-after-free
|
||||
4. **Concurrency Review**: Analyze thread safety, mutex usage, data races
|
||||
5. **Modern C++ Check**: Verify code follows C++17/20 conventions and best practices
|
||||
6. **Generate Report**: Categorize issues by severity
|
||||
|
||||
## When to Use
|
||||
|
||||
Use `/cpp-review` when:
|
||||
- After writing or modifying C++ code
|
||||
- Before committing C++ changes
|
||||
- Reviewing pull requests with C++ code
|
||||
- Onboarding to a new C++ codebase
|
||||
- Checking for memory safety issues
|
||||
|
||||
## Review Categories
|
||||
|
||||
### CRITICAL (Must Fix)
|
||||
- Raw `new`/`delete` without RAII
|
||||
- Buffer overflows and use-after-free
|
||||
- Data races without synchronization
|
||||
- Command injection via `system()`
|
||||
- Uninitialized variable reads
|
||||
- Null pointer dereferences
|
||||
|
||||
### HIGH (Should Fix)
|
||||
- Rule of Five violations
|
||||
- Missing `std::lock_guard` / `std::scoped_lock`
|
||||
- Detached threads without proper lifetime management
|
||||
- C-style casts instead of `static_cast`/`dynamic_cast`
|
||||
- Missing `const` correctness
|
||||
|
||||
### MEDIUM (Consider)
|
||||
- Unnecessary copies (pass by value instead of `const&`)
|
||||
- Missing `reserve()` on known-size containers
|
||||
- `using namespace std;` in headers
|
||||
- Missing `[[nodiscard]]` on important return values
|
||||
- Overly complex template metaprogramming
|
||||
|
||||
## Automated Checks Run
|
||||
|
||||
```bash
|
||||
# Static analysis
|
||||
clang-tidy --checks='*,-llvmlibc-*' src/*.cpp -- -std=c++17
|
||||
|
||||
# Additional analysis
|
||||
cppcheck --enable=all --suppress=missingIncludeSystem src/
|
||||
|
||||
# Build with warnings
|
||||
cmake --build build -- -Wall -Wextra -Wpedantic
|
||||
```
|
||||
|
||||
## Example Usage
|
||||
|
||||
```text
|
||||
User: /cpp-review
|
||||
|
||||
Agent:
|
||||
# C++ Code Review Report
|
||||
|
||||
## Files Reviewed
|
||||
- src/handler/user.cpp (modified)
|
||||
- src/service/auth.cpp (modified)
|
||||
|
||||
## Static Analysis Results
|
||||
✓ clang-tidy: 2 warnings
|
||||
✓ cppcheck: No issues
|
||||
|
||||
## Issues Found
|
||||
|
||||
[CRITICAL] Memory Leak
|
||||
File: src/service/auth.cpp:45
|
||||
Issue: Raw `new` without matching `delete`
|
||||
```cpp
|
||||
auto* session = new Session(userId); // Memory leak!
|
||||
cache[userId] = session;
|
||||
```
|
||||
Fix: Use `std::unique_ptr`
|
||||
```cpp
|
||||
auto session = std::make_unique<Session>(userId);
|
||||
cache[userId] = std::move(session);
|
||||
```
|
||||
|
||||
[HIGH] Missing const Reference
|
||||
File: src/handler/user.cpp:28
|
||||
Issue: Large object passed by value
|
||||
```cpp
|
||||
void processUser(User user) { // Unnecessary copy
|
||||
```
|
||||
Fix: Pass by const reference
|
||||
```cpp
|
||||
void processUser(const User& user) {
|
||||
```
|
||||
|
||||
## Summary
|
||||
- CRITICAL: 1
|
||||
- HIGH: 1
|
||||
- MEDIUM: 0
|
||||
|
||||
Recommendation: ❌ Block merge until CRITICAL issue is fixed
|
||||
```
|
||||
|
||||
## Approval Criteria
|
||||
|
||||
| Status | Condition |
|
||||
|--------|-----------|
|
||||
| ✅ Approve | No CRITICAL or HIGH issues |
|
||||
| ⚠️ Warning | Only MEDIUM issues (merge with caution) |
|
||||
| ❌ Block | CRITICAL or HIGH issues found |
|
||||
|
||||
## Integration with Other Commands
|
||||
|
||||
- Use `/cpp-test` first to ensure tests pass
|
||||
- Use `/cpp-build` if build errors occur
|
||||
- Use `/cpp-review` before committing
|
||||
- Use `/code-review` for non-C++ specific concerns
|
||||
|
||||
## Related
|
||||
|
||||
- Agent: `agents/cpp-reviewer.md`
|
||||
- Skills: `skills/cpp-coding-standards/`, `skills/cpp-testing/`
|
||||
251
commands/cpp-test.md
Normal file
251
commands/cpp-test.md
Normal file
@@ -0,0 +1,251 @@
|
||||
---
|
||||
description: Enforce TDD workflow for C++. Write GoogleTest tests first, then implement. Verify coverage with gcov/lcov.
|
||||
---
|
||||
|
||||
# C++ TDD Command
|
||||
|
||||
This command enforces test-driven development methodology for C++ code using GoogleTest/GoogleMock with CMake/CTest.
|
||||
|
||||
## What This Command Does
|
||||
|
||||
1. **Define Interfaces**: Scaffold class/function signatures first
|
||||
2. **Write Tests**: Create comprehensive GoogleTest test cases (RED)
|
||||
3. **Run Tests**: Verify tests fail for the right reason
|
||||
4. **Implement Code**: Write minimal code to pass (GREEN)
|
||||
5. **Refactor**: Improve while keeping tests green
|
||||
6. **Check Coverage**: Ensure 80%+ coverage
|
||||
|
||||
## When to Use
|
||||
|
||||
Use `/cpp-test` when:
|
||||
- Implementing new C++ functions or classes
|
||||
- Adding test coverage to existing code
|
||||
- Fixing bugs (write failing test first)
|
||||
- Building critical business logic
|
||||
- Learning TDD workflow in C++
|
||||
|
||||
## TDD Cycle
|
||||
|
||||
```
|
||||
RED → Write failing GoogleTest test
|
||||
GREEN → Implement minimal code to pass
|
||||
REFACTOR → Improve code, tests stay green
|
||||
REPEAT → Next test case
|
||||
```
|
||||
|
||||
## Example Session
|
||||
|
||||
````
|
||||
User: /cpp-test I need a function to validate email addresses
|
||||
|
||||
Agent:
|
||||
# TDD Session: Email Validator
|
||||
|
||||
## Step 1: Define Interface
|
||||
|
||||
```cpp
|
||||
// validator/email.hpp
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <expected>
|
||||
|
||||
enum class EmailError {
|
||||
Empty,
|
||||
InvalidFormat
|
||||
};
|
||||
|
||||
std::expected<void, EmailError> validate_email(const std::string& email);
|
||||
```
|
||||
|
||||
## Step 2: Write Tests (RED)
|
||||
|
||||
```cpp
|
||||
// validator/email_test.cpp
|
||||
#include <gtest/gtest.h>
|
||||
#include "email.hpp"
|
||||
|
||||
TEST(ValidateEmail, AcceptsSimpleEmail) {
|
||||
auto result = validate_email("user@example.com");
|
||||
EXPECT_TRUE(result.has_value());
|
||||
}
|
||||
|
||||
TEST(ValidateEmail, AcceptsSubdomain) {
|
||||
EXPECT_TRUE(validate_email("user@mail.example.com").has_value());
|
||||
}
|
||||
|
||||
TEST(ValidateEmail, AcceptsPlus) {
|
||||
EXPECT_TRUE(validate_email("user+tag@example.com").has_value());
|
||||
}
|
||||
|
||||
TEST(ValidateEmail, RejectsEmpty) {
|
||||
auto result = validate_email("");
|
||||
ASSERT_FALSE(result.has_value());
|
||||
EXPECT_EQ(result.error(), EmailError::Empty);
|
||||
}
|
||||
|
||||
TEST(ValidateEmail, RejectsNoAtSign) {
|
||||
EXPECT_FALSE(validate_email("userexample.com").has_value());
|
||||
}
|
||||
|
||||
TEST(ValidateEmail, RejectsNoDomain) {
|
||||
EXPECT_FALSE(validate_email("user@").has_value());
|
||||
}
|
||||
|
||||
TEST(ValidateEmail, RejectsNoLocalPart) {
|
||||
EXPECT_FALSE(validate_email("@example.com").has_value());
|
||||
}
|
||||
```
|
||||
|
||||
## Step 3: Run Tests - Verify FAIL
|
||||
|
||||
```bash
|
||||
$ cmake --build build && ctest --test-dir build --output-on-failure
|
||||
|
||||
1/1 Test #1: email_validator_test .....***Failed
|
||||
--- undefined reference to `validate_email`
|
||||
|
||||
FAIL
|
||||
```
|
||||
|
||||
✓ Tests fail as expected (unimplemented).
|
||||
|
||||
## Step 4: Implement Minimal Code (GREEN)
|
||||
|
||||
```cpp
|
||||
// validator/email.cpp
|
||||
#include "email.hpp"
|
||||
#include <regex>
|
||||
|
||||
std::expected<void, EmailError> validate_email(const std::string& email) {
|
||||
if (email.empty()) {
|
||||
return std::unexpected(EmailError::Empty);
|
||||
}
|
||||
static const std::regex pattern(R"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})");
|
||||
if (!std::regex_match(email, pattern)) {
|
||||
return std::unexpected(EmailError::InvalidFormat);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
```
|
||||
|
||||
## Step 5: Run Tests - Verify PASS
|
||||
|
||||
```bash
|
||||
$ cmake --build build && ctest --test-dir build --output-on-failure
|
||||
|
||||
1/1 Test #1: email_validator_test ..... Passed 0.01 sec
|
||||
|
||||
100% tests passed.
|
||||
```
|
||||
|
||||
✓ All tests passing!
|
||||
|
||||
## Step 6: Check Coverage
|
||||
|
||||
```bash
|
||||
$ cmake -DCMAKE_CXX_FLAGS="--coverage" -B build && cmake --build build
|
||||
$ ctest --test-dir build
|
||||
$ lcov --capture --directory build --output-file coverage.info
|
||||
$ lcov --list coverage.info
|
||||
|
||||
validator/email.cpp | 100%
|
||||
```
|
||||
|
||||
✓ Coverage: 100%
|
||||
|
||||
## TDD Complete!
|
||||
````
|
||||
|
||||
## Test Patterns
|
||||
|
||||
### Basic Tests
|
||||
```cpp
|
||||
TEST(SuiteName, TestName) {
|
||||
EXPECT_EQ(add(2, 3), 5);
|
||||
EXPECT_NE(result, nullptr);
|
||||
EXPECT_TRUE(is_valid);
|
||||
EXPECT_THROW(func(), std::invalid_argument);
|
||||
}
|
||||
```
|
||||
|
||||
### Fixtures
|
||||
```cpp
|
||||
class DatabaseTest : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override { db_ = create_test_db(); }
|
||||
void TearDown() override { db_.reset(); }
|
||||
std::unique_ptr<Database> db_;
|
||||
};
|
||||
|
||||
TEST_F(DatabaseTest, InsertsRecord) {
|
||||
db_->insert("key", "value");
|
||||
EXPECT_EQ(db_->get("key"), "value");
|
||||
}
|
||||
```
|
||||
|
||||
### Parameterized Tests
|
||||
```cpp
|
||||
class PrimeTest : public ::testing::TestWithParam<std::pair<int, bool>> {};
|
||||
|
||||
TEST_P(PrimeTest, ChecksPrimality) {
|
||||
auto [input, expected] = GetParam();
|
||||
EXPECT_EQ(is_prime(input), expected);
|
||||
}
|
||||
|
||||
INSTANTIATE_TEST_SUITE_P(Primes, PrimeTest, ::testing::Values(
|
||||
std::make_pair(2, true),
|
||||
std::make_pair(4, false),
|
||||
std::make_pair(7, true)
|
||||
));
|
||||
```
|
||||
|
||||
## Coverage Commands
|
||||
|
||||
```bash
|
||||
# Build with coverage
|
||||
cmake -DCMAKE_CXX_FLAGS="--coverage" -DCMAKE_EXE_LINKER_FLAGS="--coverage" -B build
|
||||
|
||||
# Run tests
|
||||
cmake --build build && ctest --test-dir build
|
||||
|
||||
# Generate coverage report
|
||||
lcov --capture --directory build --output-file coverage.info
|
||||
lcov --remove coverage.info '/usr/*' --output-file coverage.info
|
||||
genhtml coverage.info --output-directory coverage_html
|
||||
```
|
||||
|
||||
## Coverage Targets
|
||||
|
||||
| Code Type | Target |
|
||||
|-----------|--------|
|
||||
| Critical business logic | 100% |
|
||||
| Public APIs | 90%+ |
|
||||
| General code | 80%+ |
|
||||
| Generated code | Exclude |
|
||||
|
||||
## TDD Best Practices
|
||||
|
||||
**DO:**
|
||||
- Write test FIRST, before any implementation
|
||||
- Run tests after each change
|
||||
- Use `EXPECT_*` (continues) over `ASSERT_*` (stops) when appropriate
|
||||
- Test behavior, not implementation details
|
||||
- Include edge cases (empty, null, max values, boundary conditions)
|
||||
|
||||
**DON'T:**
|
||||
- Write implementation before tests
|
||||
- Skip the RED phase
|
||||
- Test private methods directly (test through public API)
|
||||
- Use `sleep` in tests
|
||||
- Ignore flaky tests
|
||||
|
||||
## Related Commands
|
||||
|
||||
- `/cpp-build` - Fix build errors
|
||||
- `/cpp-review` - Review code after implementation
|
||||
- `/verify` - Run full verification loop
|
||||
|
||||
## Related
|
||||
|
||||
- Skill: `skills/cpp-testing/`
|
||||
- Skill: `skills/tdd-workflow/`
|
||||
Reference in New Issue
Block a user