Files
gh-hubexab-eaf-pluginclaude…/commands/analyze-code.md
2025-11-29 18:47:11 +08:00

10 KiB
Raw Blame History

Analyze Code Command

Perform comprehensive code quality analysis on the ExFabrica Agentic Factory codebase, including linting, type checking, test coverage analysis, and security vulnerability scanning.

Usage

/analyze-code [workspace] [--fix] [--strict] [--report]

Parameters

  • workspace (optional): Specific workspace to analyze
    • backend - Analyze backend application only
    • frontend - Analyze frontend application only
    • api-client - Analyze shared API client library
    • If omitted, analyzes entire monorepo
  • --fix (optional): Automatically fix auto-fixable issues
  • --strict (optional): Use strict mode (fail on warnings)
  • --report (optional): Generate detailed HTML report

Analysis Categories

1. Linting (ESLint)

Checks

  • Code style consistency
  • Best practice violations
  • Potential bugs and errors
  • Unused variables and imports
  • Complexity metrics

Configuration

  • Backend: apps/backend/.eslintrc.js
  • Frontend: apps/frontend/.eslintrc.json
  • Shared: Root .eslintrc.json

2. Type Checking (TypeScript)

Checks

  • Type safety violations
  • Missing type definitions
  • Incorrect type assertions
  • Unused types and interfaces
  • Strict null checks

Configuration

  • Backend: apps/backend/tsconfig.json
  • Frontend: apps/frontend/tsconfig.app.json
  • Shared: Root tsconfig.base.json

3. Test Coverage

Metrics

  • Statement coverage
  • Branch coverage
  • Function coverage
  • Line coverage
  • Uncovered files report

Thresholds

  • Backend: 80% minimum coverage
  • Frontend: 75% minimum coverage

4. Security Scanning

Checks

  • Known vulnerabilities in dependencies (yarn audit)
  • Security best practices violations
  • Hardcoded secrets detection
  • SQL injection risks
  • XSS vulnerabilities

5. Code Complexity

Metrics

  • Cyclomatic complexity
  • Cognitive complexity
  • Maintainability index
  • Code duplication
  • Function length

6. Dependency Analysis

Checks

  • Outdated dependencies
  • Circular dependencies
  • Unused dependencies
  • Version conflicts
  • License compliance

Workflow

When you execute this command, Claude will:

  1. Preparation

    • Determine analysis scope (workspace or monorepo)
    • Set up analysis tools and configurations
    • Clear previous analysis artifacts
  2. Linting Analysis

    • Run ESLint on all TypeScript/JavaScript files
    • Report errors, warnings, and info messages
    • Auto-fix issues if --fix flag is used
  3. Type Checking

    • Run TypeScript compiler in check mode
    • Identify type errors and warnings
    • Report any any types in strict mode
  4. Coverage Analysis

    • Calculate test coverage from previous test runs
    • Identify files with low coverage
    • Generate coverage reports
  5. Security Scanning

    • Run yarn audit to check for vulnerabilities
    • Scan for hardcoded secrets using patterns
    • Check for common security anti-patterns
  6. Complexity Analysis

    • Calculate complexity metrics
    • Identify complex functions needing refactoring
    • Report code duplication
  7. Report Generation

    • Aggregate results from all analyses
    • Generate summary report
    • Create detailed HTML report if requested

Examples

Analyze Entire Monorepo

/analyze-code

Runs all analysis checks on the complete codebase.

Analyze Backend Only

/analyze-code backend

Focuses analysis on the NestJS backend application.

Analyze Frontend Only

/analyze-code frontend

Focuses analysis on the Angular frontend application.

Analyze and Auto-Fix Issues

/analyze-code --fix

Automatically fixes ESLint and formatting issues.

Strict Analysis with HTML Report

/analyze-code --strict --report

Runs strict analysis and generates detailed HTML report.

Fix Backend Issues

/analyze-code backend --fix

Auto-fixes linting issues in backend code.

Output Format

Summary Report

Code Quality Analysis Report
============================

Workspace: All
Analyzed Files: 342
Duration: 1m 47s

📋 LINTING (ESLint)
  ✓ Backend: 0 errors, 3 warnings
  ✗ Frontend: 2 errors, 7 warnings
   API Client: 0 errors, 1 warning

🔍 TYPE CHECKING (TypeScript)
  ✓ Backend: 0 errors
  ✓ Frontend: 0 errors
  ✓ API Client: 0 errors

📊 TEST COVERAGE
  ✓ Backend: 82.5% (above 80% threshold)
  ⚠ Frontend: 73.2% (below 75% threshold)
  ✓ API Client: 88.1% (above 80% threshold)

🔒 SECURITY
  ⚠ 3 moderate vulnerabilities found
   12 low severity issues
  Recommendation: Run 'yarn audit fix'

📈 COMPLEXITY
  ⚠ 5 functions with high complexity (>10)
   3 files with code duplication
  Recommendation: Refactor complex functions

📦 DEPENDENCIES
  ✓ All dependencies up to date
   2 unused dependencies detected

Overall Grade: B (Good)
Recommendations: Fix frontend linting errors, improve frontend test coverage

Detailed Issue Report

❌ ERRORS (2)

apps/frontend/src/app/components/user-profile/user-profile.component.ts:45:7
  error  'userId' is declared but never used  @typescript-eslint/no-unused-vars

apps/frontend/src/app/services/data.service.ts:128:5
  error  Missing return type on function  @typescript-eslint/explicit-function-return-type

⚠️  WARNINGS (11)

apps/backend/src/users/users.service.ts:67:3
  warning  Function 'processUserData' has complexity of 12  complexity

[... additional warnings ...]

Analysis Details

ESLint Rules Enforced

Error-Level Rules

  • no-unused-vars - No unused variables
  • no-console - No console.log in production code
  • @typescript-eslint/no-explicit-any - Avoid using any type
  • @typescript-eslint/explicit-function-return-type - Explicit return types

Warning-Level Rules

  • complexity - Cyclomatic complexity > 10
  • max-lines-per-function - Functions > 50 lines
  • no-duplicate-imports - Duplicate import statements

TypeScript Strict Mode

When using --strict, additional checks are enabled:

  • strictNullChecks - Strict null checking
  • strictFunctionTypes - Strict function types
  • noImplicitAny - No implicit any types
  • noImplicitThis - No implicit this
  • alwaysStrict - Parse in strict mode

Security Patterns Detected

Critical Issues

  • Hardcoded API keys or passwords
  • SQL queries without parameterization
  • Eval or Function constructor usage
  • Insecure random number generation

Warning Issues

  • Missing input validation
  • Unescaped user input in templates
  • HTTP instead of HTTPS
  • Weak cryptographic algorithms

HTML Report Generation

When using --report, generates detailed HTML reports in:

  • reports/code-analysis/index.html - Main report
  • reports/code-analysis/coverage/ - Coverage reports
  • reports/code-analysis/linting/ - ESLint reports
  • reports/code-analysis/complexity/ - Complexity metrics

Open in browser for interactive exploration.

Troubleshooting

ESLint Config Not Found

Error: Cannot find ESLint configuration

Solution: Ensure .eslintrc.js or .eslintrc.json exists in workspace

TypeScript Errors in node_modules

Error: Type errors in node_modules/@types/...

Solution: Update @types packages or exclude from type checking

yarn upgrade @types/node @types/jest

Coverage Data Not Available

Warning: No coverage data found

Solution: Run tests with coverage first

/test-all --coverage

Memory Issues During Analysis

Error: JavaScript heap out of memory

Solution: Increase Node.js memory

export NODE_OPTIONS="--max-old-space-size=4096"

Auto-Fix Capabilities

The --fix flag can automatically resolve:

Fixable Issues

  • Code formatting (via Prettier)
  • Import order
  • Missing semicolons
  • Trailing whitespace
  • Single vs double quotes
  • Spacing and indentation

Not Auto-Fixable

  • Type errors
  • Unused variables (may break code)
  • Complex logic issues
  • Security vulnerabilities
  • High complexity functions

CI/CD Integration

Azure DevOps Pipeline

- task: Script@1
  displayName: 'Code Quality Analysis'
  inputs:
    script: |
      /analyze-code --strict --report

- task: PublishCodeCoverageResults@1
  inputs:
    codeCoverageTool: 'Cobertura'
    summaryFileLocation: '$(System.DefaultWorkingDirectory)/coverage/cobertura-coverage.xml'

Quality Gates

Fail the build if:

  • Any ESLint errors (warnings allowed)
  • Any TypeScript errors
  • Coverage below threshold
  • Critical or high security vulnerabilities

Best Practices

  1. Analyze before committing

    /analyze-code --fix
    
  2. Run strict analysis before merging to main

    /analyze-code --strict
    
  3. Review HTML report for complex issues

    /analyze-code --report
    
  4. Fix errors immediately, schedule warnings

    • Errors must be fixed before commit
    • Warnings should be addressed in near future
  5. Monitor trends over time

    • Track coverage trends
    • Monitor complexity growth
    • Watch dependency updates

Coding Standards

Backend (NestJS)

  • Use dependency injection
  • Implement proper error handling
  • Use DTOs for validation
  • Follow REST/GraphQL conventions
  • Document API endpoints with Swagger

Frontend (Angular)

  • Use OnPush change detection
  • Implement smart/dumb component pattern
  • Use RxJS operators correctly
  • Avoid memory leaks (unsubscribe)
  • Follow Angular style guide

Shared (TypeScript)

  • Explicit return types
  • No any types
  • Use strict null checks
  • Document public APIs
  • Write unit tests
  • /test-all --coverage - Run tests and generate coverage
  • /deploy - Deploy only after passing analysis
  • /generate-api-client - Update API client after backend changes

Continuous Improvement

Metrics to Track

  • Code coverage trend (aim for 85%+)
  • Number of ESLint violations
  • Average complexity score
  • Security vulnerability count
  • Build/analysis duration

Goals

  • Zero ESLint errors in main branch
  • 85%+ test coverage across all workspaces
  • No high/critical security vulnerabilities
  • Average complexity < 8
  • All TypeScript in strict mode

Note: This command integrates with pre-commit hooks to ensure code quality before commits. Configure in config/hooks.json to run automatically.