Validate Code
Comprehensive code validation ensuring all quality gates pass before considering work complete. Runs all project checks and itera…
Claude CodeGeneric
# Command: /validate-code
## Purpose
Comprehensive code validation ensuring all quality gates pass before considering work complete. Runs all project checks and iteratively fixes issues until completely passing.
## Usage
/validate-code /validate-code --fix /validate-code --verbose
## Workflow
### Phase 1: Full Validation Suite
Run all quality checks in sequence:
```bash
# 1. Type checking
npm run type-check
# 2. Linting
npm run lint
# 3. Test suite (with JSON output for analysis)
npm test -- --reporter=json --outputFile=test-results.json
# 4. Build verification
npm run build
Note: Tests are run with JSON output to test-results.json for detailed failure analysis and automated fixing. This file is gitignored.
Phase 2: Issue Detection & Resolution
Error Categories:
- TypeScript Errors: Type mismatches, missing types, compilation failures
- Lint Errors: Code style, best practices, ESLint rule violations
- Test Failures: Unit tests, integration tests, coverage thresholds
- Build Errors: Compilation issues, missing dependencies
Resolution Strategy:
- Categorize Issues: Group by type for efficient fixing
- Priority Order: TypeScript → Lint → Tests → Build
- Fix & Validate: Fix one category, re-run checks, repeat
- Loop Until Clean: Continue until all checks pass
Phase 3: Completion Validation
Success Criteria:
- ✅
npm run type-check- 0 errors, 0 warnings - ✅
npm run lint- 0 errors, 0 warnings - ✅
npm test- All tests pass, coverage ≥80% - ✅
npm run build- Clean build, no errors
Integration with Work Command:
- Auto-runs after
/workcommand completion - Required for Serena memory
completion_checklist.md - Blocks work completion until all checks pass
Implementation Logic
class ValidateCodeCommand {
async execute(options: ValidationOptions): Promise<ValidationResult> {
let allPassed = false;
let iterationCount = 0;
const maxIterations = 5;
while (!allPassed && iterationCount < maxIterations) {
console.log(`🔍 Validation Iteration ${iterationCount + 1}`);
// Run all checks
const results = await this.runAllChecks();
if (results.allPassed) {
allPassed = true;
await this.updateCompletionChecklist();
break;
}
// Fix issues by category
if (results.typeErrors.length > 0) {
await this.fixTypeScriptErrors(results.typeErrors);
}
if (results.lintErrors.length > 0) {
await this.fixLintErrors(results.lintErrors);
}
if (results.testFailures.length > 0) {
await this.fixTestFailures(results.testFailures);
}
if (results.buildErrors.length > 0) {
await this.fixBuildErrors(results.buildErrors);
}
iterationCount++;
}
if (!allPassed) {
throw new Error(`Validation failed after ${maxIterations} iterations`);
}
return { success: true, iterations: iterationCount };
}
private async runAllChecks(): Promise<ValidationResults> {
const typeCheck = await this.runCommand('npm run type-check');
const lint = await this.runCommand('npm run lint');
// Run tests with JSON output and increased timeout for long-running tests
console.log('🧪 Running tests (this may take several minutes)...');
const test = await this.runCommand(
'npm test -- --reporter=json --outputFile=test-results.json --run',
{ timeout: 300000 } // 5 minute timeout
);
const build = await this.runCommand('npm run build');
return {
allPassed:
typeCheck.success && lint.success && test.success && build.success,
typeErrors: this.parseTypeErrors(typeCheck.output),
lintErrors: this.parseLintErrors(lint.output),
testFailures: await this.parseTestFailuresFromJson(),
buildErrors: this.parseBuildErrors(build.output),
};
}
private async parseTestFailuresFromJson(): Promise<TestFailure[]> {
try {
const testResults = await this.readFile('test-results.json');
const results = JSON.parse(testResults);
const failures: TestFailure[] = [];
// Parse Vitest JSON format
if (results.testResults) {
for (const suite of results.testResults) {
if (suite.status === 'failed') {
for (const test of suite.assertionResults || []) {
if (test.status === 'failed') {
failures.push({
testName: test.title,
suiteName: suite.name,
errorMessage:
test.failureMessages?.join('\n') || 'Test failed',
filePath: suite.name,
location: test.location,
});
}
}
}
}
}
return failures;
} catch (error) {
console.warn('Could not parse test results JSON:', error.message);
return [];
}
}
private async updateCompletionChecklist(): Promise<void> {
// Update Serena memory with validation success
const checklist = {
timestamp: new Date().toISOString(),
typeCheck: '✅ PASSED',
lint: '✅ PASSED',
tests: '✅ PASSED',
build: '✅ PASSED',
readyForReview: true,
};
await this.writeToSerenaMemory('completion_checklist.md', checklist);
}
}
Error Fixing Strategies
TypeScript Errors
Common Issues & Fixes:
- Type mismatches: Add proper type annotations
- Missing imports: Add import statements
- Strict null checks: Add null/undefined guards
- Generic constraints: Add proper type parameters
Example Fix Pattern:
// Error: Property 'id' does not exist on type 'unknown'
// Fix: Add proper typing
interface User {
id: string;
name: string;
}
const user: User = userData as User;
Lint Errors
Auto-Fix Strategy:
# Try auto-fix first
npm run lint -- --fix
# Then handle remaining issues manually
**Com ```
Maintain Validate Code?
Let people know it's listed here — add the badge (live metrics, light/dark aware) or a plain link to your README or docs.
[Validate Code on getagentictools](https://getagentictools.com/loops/terrastories-command-validate-code?ref=badge)