Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:47:11 +08:00
commit 8d68fa43fc
13 changed files with 4244 additions and 0 deletions

430
commands/analyze-code.md Normal file
View File

@@ -0,0 +1,430 @@
# 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
```bash
yarn upgrade @types/node @types/jest
```
### Coverage Data Not Available
```
Warning: No coverage data found
```
**Solution**: Run tests with coverage first
```bash
/test-all --coverage
```
### Memory Issues During Analysis
```
Error: JavaScript heap out of memory
```
**Solution**: Increase Node.js memory
```bash
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
```yaml
- 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
## Related Commands
- `/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.

523
commands/db-operations.md Normal file
View File

@@ -0,0 +1,523 @@
# Database Operations Command
Manage database operations for the ExFabrica Agentic Factory project, including migrations, seeding, backup, restore, and schema management using Drizzle ORM and PostgreSQL.
## Usage
```
/db-operations <operation> [--env=<environment>] [--force]
```
## Parameters
- **operation** (required): Database operation to perform
- `migrate` - Run pending database migrations
- `migrate:create` - Create a new migration file
- `migrate:rollback` - Rollback the last migration
- `seed` - Seed database with test/demo data
- `reset` - Drop all tables and recreate schema
- `backup` - Create database backup
- `restore` - Restore from backup
- `status` - Show migration and database status
- `validate` - Validate schema against models
- **--env** (optional): Target environment (dev, test, production). Defaults to current environment.
- **--force** (optional): Force operation without confirmation (use with caution)
## Operations
### 1. Migrations
#### Run Migrations
```
/db-operations migrate
```
Applies all pending migrations to the database in order.
**Process**:
1. Check database connection
2. Retrieve list of applied migrations
3. Identify pending migrations
4. Execute migrations in sequence
5. Record successful migrations
6. Rollback on error
**Output**:
```
🗃️ Running Database Migrations
================================
Database: exfabrica_af_dev
Environment: development
Pending migrations:
✓ 001_create_users_table.sql
✓ 002_create_projects_table.sql
✓ 003_add_user_roles.sql
All migrations completed successfully! (3.2s)
```
#### Create New Migration
```
/db-operations migrate:create add_organizations_table
```
Creates a new migration file with timestamp.
**Generated File**: `apps/backend/drizzle/migrations/20251029123456_add_organizations_table.sql`
#### Rollback Migration
```
/db-operations migrate:rollback
```
Rolls back the most recently applied migration.
**⚠️ WARNING**: Use with extreme caution in production!
### 2. Database Seeding
#### Seed Development Data
```
/db-operations seed
```
Populates the database with test/demo data for development.
**Seed Data Includes**:
- Test user accounts (admin, regular users)
- Sample projects and workflows
- Demo organizations
- Test API keys
- Sample data for each entity type
**Process**:
1. Check if database is empty or can be seeded
2. Clear existing seed data (if applicable)
3. Insert seed data in dependency order
4. Verify data integrity
5. Report seeded record counts
**Output**:
```
🌱 Seeding Database
===================
Environment: development
Seeding data:
✓ Users: 10 records created
✓ Organizations: 3 records created
✓ Projects: 15 records created
✓ Workflows: 23 records created
✓ API Keys: 5 records created
Database seeded successfully! (2.7s)
Test Accounts:
- admin@exfabrica.com / Admin123!
- user@exfabrica.com / User123!
```
### 3. Database Reset
```
/db-operations reset
```
**⚠️ DESTRUCTIVE OPERATION**: Drops all tables and recreates the schema.
**Confirmation Required** (unless --force is used):
```
⚠️ WARNING: This will delete ALL data in the database!
Database: exfabrica_af_dev
Environment: development
Are you sure you want to continue? (yes/no):
```
**Process**:
1. Request explicit confirmation
2. Create backup before reset (unless skipped)
3. Drop all tables in reverse dependency order
4. Recreate schema from migrations
5. Optionally seed with fresh data
**Use Cases**:
- Reset development database to clean state
- Clear test database between test runs
- Fix corrupted schema during development
### 4. Database Backup
```
/db-operations backup
```
Creates a full backup of the current database.
**Backup Location**: `backups/db/exfabrica_af_dev_20251029_123456.sql`
**Backup Includes**:
- Complete schema (tables, indexes, constraints)
- All data
- Sequences and serial values
- Custom types and functions
**Process**:
1. Generate backup filename with timestamp
2. Use `pg_dump` to create SQL backup
3. Compress backup file (gzip)
4. Verify backup integrity
5. Report backup location and size
**Output**:
```
💾 Creating Database Backup
===========================
Database: exfabrica_af_dev
Backup file: backups/db/exfabrica_af_dev_20251029_123456.sql.gz
✓ Backup created successfully
✓ Size: 12.4 MB (compressed)
✓ Records: ~45,000
Backup location:
c:\Users\nicol\Source\ExFabrica\ExFabrica\EAF\backups\db\exfabrica_af_dev_20251029_123456.sql.gz
```
### 5. Database Restore
```
/db-operations restore backups/db/exfabrica_af_dev_20251029_123456.sql.gz
```
Restores database from a backup file.
**⚠️ WARNING**: This will replace all current data!
**Process**:
1. Verify backup file exists and is valid
2. Request confirmation
3. Create safety backup of current state
4. Drop existing schema (optional)
5. Restore from backup file
6. Verify restoration success
### 6. Database Status
```
/db-operations status
```
Shows comprehensive database and migration status.
**Output**:
```
📊 Database Status
==================
Connection: ✓ Connected
Database: exfabrica_af_dev
Host: localhost:5432
Version: PostgreSQL 15.3
Migrations:
Applied: 23
Pending: 0
Last migration: 20251028_add_workflow_permissions.sql
Schema:
Tables: 12
Indexes: 34
Constraints: 28
Data Summary:
Users: 145 records
Projects: 67 records
Workflows: 234 records
Organizations: 8 records
Size:
Database: 124 MB
Largest table: workflows (45 MB)
Health: ✓ All checks passed
```
### 7. Schema Validation
```
/db-operations validate
```
Validates that the database schema matches Drizzle ORM model definitions.
**Checks**:
- All models have corresponding tables
- Column types match model definitions
- Indexes are correctly created
- Foreign key constraints are in place
- Default values are set correctly
**Output**:
```
✓ All models validated successfully
⚠ Warning: Index 'idx_users_email' missing on users table
⚠ Warning: Column 'updated_at' type mismatch (expected: timestamptz, found: timestamp)
```
## Environment Configuration
### Development Environment
```bash
# .env.development
DATABASE_URL=postgresql://dev:devpass@localhost:5432/exfabrica_af_dev
```
### Test Environment
```bash
# .env.test
DATABASE_URL=postgresql://test:testpass@localhost:5442/exfabrica_af_test
```
### Production Environment
```bash
# .env.production
DATABASE_URL=postgresql://prod:prodpass@db.example.com:5432/exfabrica_af_prod
```
## Examples
### Development Workflow
```bash
# Start fresh with clean database
/db-operations reset --force
/db-operations seed
# Make schema changes in code
# Generate migration
/db-operations migrate:create add_new_feature
# Apply migration
/db-operations migrate
# Verify
/db-operations status
```
### Production Deployment
```bash
# Create backup before migration
/db-operations backup --env=production
# Apply migrations
/db-operations migrate --env=production
# Verify
/db-operations status --env=production
```
### Testing Setup
```bash
# Reset test database
/db-operations reset --env=test --force
# Seed with test data
/db-operations seed --env=test
# Run tests
/test-all backend
```
## Safety Features
### Production Safeguards
- ⚠️ Explicit confirmation required for destructive operations
- 🔒 Automatic backup before reset or rollback in production
- ✅ Validation before applying migrations
- 📝 Detailed logging of all operations
- 🔄 Rollback capability for failed migrations
### Transaction Safety
- All migrations run within transactions
- Automatic rollback on error
- State consistency guaranteed
### Backup Retention
- Automatic backups retained for 30 days
- Manual backups retained indefinitely
- Cleanup command for old backups
## Migration Best Practices
### Creating Migrations
1. **Use descriptive names**
```
/db-operations migrate:create add_workflow_approvals
```
2. **Make migrations reversible**
Include both `up` and `down` migrations:
```sql
-- Up
CREATE TABLE approvals (...);
-- Down
DROP TABLE approvals;
```
3. **Test migrations locally first**
```
/db-operations migrate --env=dev
/db-operations migrate:rollback --env=dev
```
4. **Keep migrations small and focused**
- One logical change per migration
- Easier to review and rollback
### Migration Dependencies
Drizzle ORM ensures migrations run in order:
```
001_create_users_table.sql
002_create_organizations_table.sql
003_add_user_organization_relation.sql (depends on 001 and 002)
```
## Troubleshooting
### Cannot Connect to Database
```
Error: Connection refused at localhost:5432
```
**Solution**: Ensure PostgreSQL is running
```bash
docker compose up -d postgres
```
### Migration Failed
```
Error: Migration 003_add_column.sql failed
```
**Solution**: Check migration SQL syntax and rollback
```bash
/db-operations migrate:rollback
# Fix migration file
/db-operations migrate
```
### Schema Mismatch
```
Error: Table 'users' does not match model definition
```
**Solution**: Run validation and create corrective migration
```bash
/db-operations validate
/db-operations migrate:create fix_users_schema
```
### Seed Data Conflicts
```
Error: Duplicate key violation on users.email
```
**Solution**: Clear existing seed data first
```bash
/db-operations reset --force
/db-operations seed
```
### Backup File Corrupted
```
Error: Invalid backup file format
```
**Solution**: Use a different backup or restore from automated backups
```bash
ls backups/db/automated/
/db-operations restore backups/db/automated/latest.sql.gz
```
## CI/CD Integration
### Azure DevOps Pipeline
```yaml
- task: Script@1
displayName: 'Database Migrations'
inputs:
script: |
/db-operations backup --env=$(ENVIRONMENT)
/db-operations migrate --env=$(ENVIRONMENT)
/db-operations validate --env=$(ENVIRONMENT)
```
### Pre-Deployment Checklist
✅ Backup created
✅ Migrations tested in staging
✅ Schema validated
✅ Rollback plan prepared
## Drizzle ORM Schema Example
```typescript
// apps/backend/src/database/schema/users.schema.ts
import { pgTable, serial, varchar, timestamp } from 'drizzle-orm/pg-core';
export const users = pgTable('users', {
id: serial('id').primaryKey(),
email: varchar('email', { length: 255 }).notNull().unique(),
password: varchar('password', { length: 255 }).notNull(),
firstName: varchar('first_name', { length: 100 }),
lastName: varchar('last_name', { length: 100 }),
createdAt: timestamp('created_at').defaultNow(),
updatedAt: timestamp('updated_at').defaultNow(),
});
```
## Related Commands
- `/test-all backend` - Test database operations
- `/deploy` - Deploy with database migrations
- `/analyze-code` - Check migration file quality
## Advanced Operations
### Custom Seed Data
Create custom seed files in `apps/backend/drizzle/seeds/`:
```typescript
// custom-seed.ts
export async function seed(db: Database) {
await db.insert(users).values([
{ email: 'custom@example.com', password: 'hashed' }
]);
}
```
### Partial Migrations
Run specific migration range:
```bash
/db-operations migrate --from=001 --to=005
```
### Multi-Database Operations
Operate on multiple databases:
```bash
/db-operations migrate --all-environments
```
---
**Note**: Always test database operations in development before applying to staging or production. Keep backups and maintain a rollback plan for production changes.

208
commands/deploy.md Normal file
View File

@@ -0,0 +1,208 @@
# Deploy Command
Deploy the ExFabrica Agentic Factory applications to the specified environment with comprehensive validation and safety checks.
## Usage
```
/deploy <environment> [--skip-tests] [--skip-build]
```
## Parameters
- **environment** (required): Target deployment environment
- `dev` - Development environment
- `staging` - Staging/pre-production environment
- `production` - Production environment
- **--skip-tests** (optional): Skip running tests before deployment (not recommended for production)
- **--skip-build** (optional): Skip building the application (use existing build artifacts)
## Workflow
When you execute this command, Claude will:
1. **Pre-deployment Validation**
- Verify git working directory is clean (no uncommitted changes)
- Check current branch matches environment requirements
- Ensure all required environment variables are set
- Validate the target environment configuration
2. **Quality Checks** (unless --skip-tests is used)
- Run backend unit tests (`yarn workspace @bdqt/backend test`)
- Run frontend unit tests (`yarn workspace @bdqt/frontend test`)
- Run integration tests
- Verify test coverage meets minimum thresholds
3. **Build Process** (unless --skip-build is used)
- Clean previous build artifacts
- Build backend application (`yarn workspace @bdqt/backend build`)
- Build frontend application with SSR (`yarn workspace @bdqt/frontend build`)
- Generate OpenAPI client if backend changes detected
4. **Deployment Execution**
- For **dev**: Direct deployment to development environment
- For **staging**: Deploy to staging and run smoke tests
- For **production**:
- Require explicit confirmation
- Create deployment tag in git
- Deploy with zero-downtime strategy
- Run comprehensive smoke tests
- Monitor initial metrics
5. **Post-deployment**
- Verify application health endpoints
- Run smoke tests against deployed environment
- Update deployment logs
- Notify team (if configured)
## Examples
### Deploy to Development
```
/deploy dev
```
Quick deployment to development environment with all validations.
### Deploy to Staging
```
/deploy staging
```
Deploy to staging environment with full test suite and smoke tests.
### Deploy to Production
```
/deploy production
```
Deploy to production with maximum safety checks, explicit confirmation, and monitoring.
### Quick Development Deploy (skip tests)
```
/deploy dev --skip-tests
```
Fast deployment to development when you're confident in your changes.
## Safety Features
### Production Safeguards
- **Explicit confirmation required** before production deployment
- **Branch validation**: Must be on main/master branch
- **Test coverage**: Minimum coverage thresholds must be met
- **Git tag creation**: Every production deploy creates a version tag
- **Rollback capability**: Previous version kept for quick rollback
### All Environments
- **Health checks**: Verify application responds correctly
- **Database migrations**: Automatically run pending migrations
- **Environment validation**: Ensure all required secrets are configured
- **Build verification**: Confirm build artifacts are valid
## Environment-Specific Behavior
### Development (`dev`)
- Fast deployment cycle
- Automatic database seeding available
- Detailed error logging
- Hot reload capabilities maintained
### Staging (`staging`)
- Production-like configuration
- Full test suite execution
- Performance monitoring enabled
- Load testing option available
### Production (`production`)
- Zero-downtime deployment strategy
- Database backup before migrations
- Comprehensive monitoring and alerting
- Automatic rollback on critical errors
## Prerequisites
Before deploying, ensure:
1. **Environment Configuration**
- `.env.development`, `.env.staging`, or `.env.production` file exists
- All required environment variables are set
- Database connection is configured
2. **Infrastructure**
- Target environment is provisioned and accessible
- Database is running and migrations are ready
- Required Azure resources are available
3. **Code Quality**
- All tests passing locally
- No ESLint or TypeScript errors
- Code reviewed and approved (for production)
## Troubleshooting
### Deployment Fails on Tests
```
Error: Tests failed - cannot proceed with deployment
```
**Solution**: Run `/test-all` to identify and fix failing tests.
### Build Errors
```
Error: Build failed with TypeScript errors
```
**Solution**: Run `/analyze-code` to identify and fix type errors.
### Environment Configuration Missing
```
Error: Required environment variable DATABASE_URL not set
```
**Solution**: Check `.env.{environment}` file and ensure all required variables are present.
### Git Working Directory Not Clean
```
Error: Uncommitted changes detected
```
**Solution**: Commit or stash your changes before deploying.
## Related Commands
- `/test-all` - Run comprehensive test suite
- `/analyze-code` - Check code quality before deployment
- `/db-operations migrate` - Run database migrations manually
- `/generate-api-client` - Update API client before deployment
## Best Practices
1. **Always test before deploying to production**
```
/test-all
/deploy production
```
2. **Use staging as a production mirror**
```
/deploy staging
# Verify manually
/deploy production
```
3. **Keep deployments small and frequent**
- Deploy to dev multiple times per day
- Deploy to staging at least daily
- Deploy to production weekly or bi-weekly
4. **Monitor after deployment**
- Check application logs
- Verify key user flows
- Monitor performance metrics
## Azure DevOps Integration
This command can trigger Azure DevOps pipelines if configured in your `azure-pipelines.yml`:
- Development deploys trigger the `dev` pipeline
- Staging deploys trigger the `staging` pipeline
- Production deploys trigger the `production` pipeline with approvals
The command will wait for pipeline completion and report the results.
---
**Note**: This command respects the lifecycle hooks configured in `config/hooks.json` and will run pre-deployment and post-deployment hooks automatically.

View File

@@ -0,0 +1,441 @@
# Generate API Client Command
Generate the TypeScript OpenAPI client library from the NestJS backend API specifications, ensuring type-safe communication between frontend and backend applications.
## Usage
```
/generate-api-client [--watch] [--validate]
```
## Parameters
- **--watch** (optional): Watch mode - regenerate client on backend API changes
- **--validate** (optional): Validate OpenAPI spec before generation
## What This Command Does
This command automates the process of generating a type-safe API client for the frontend to consume the backend API. It:
1. Extracts OpenAPI specification from the NestJS backend
2. Validates the specification for correctness
3. Generates TypeScript client code with full type definitions
4. Updates the `@bdqt/api-client` shared library
5. Ensures type safety across the monorepo
## Workflow
When you execute this command, Claude will:
1. **Backend API Specification Extraction**
- Start the NestJS backend in development mode
- Access the Swagger/OpenAPI endpoint (typically `/api-docs`)
- Download the OpenAPI specification JSON
- Validate the specification structure
2. **Specification Validation** (if --validate is used)
- Check OpenAPI spec version (3.0 or 3.1)
- Validate all endpoint definitions
- Ensure all DTOs have proper typing
- Verify authentication schemes are defined
- Check for breaking changes from previous version
3. **Client Generation**
- Use OpenAPI Generator or similar tool
- Generate TypeScript client code with:
- API service classes
- Request/response type definitions
- Model interfaces
- Authentication helpers
- HTTP client configuration
4. **Library Update**
- Update `libs/api-client/src/` with generated code
- Run TypeScript compilation
- Generate TypeScript declarations
- Update package exports
5. **Verification**
- Compile the generated client
- Run type checking
- Verify all dependencies are satisfied
- Run basic smoke tests
## Examples
### Basic Generation
```
/generate-api-client
```
Generates the API client from the current backend specification.
### Generate with Validation
```
/generate-api-client --validate
```
Validates the OpenAPI spec before generating the client.
### Watch Mode for Development
```
/generate-api-client --watch
```
Continuously regenerates the client when backend API changes are detected.
## Generated Client Structure
The command generates code in the `libs/api-client/` workspace:
```
libs/api-client/
├── src/
│ ├── api/
│ │ ├── users.api.ts # Users API endpoints
│ │ ├── auth.api.ts # Authentication endpoints
│ │ └── index.ts # API exports
│ ├── models/
│ │ ├── user.model.ts # User model interface
│ │ ├── auth.model.ts # Auth-related models
│ │ └── index.ts # Model exports
│ ├── client.ts # HTTP client configuration
│ ├── configuration.ts # API configuration
│ └── index.ts # Main exports
├── package.json
└── tsconfig.json
```
## Client Usage Example
After generation, the frontend can use the type-safe client:
```typescript
// Frontend service example
import { UsersApi, CreateUserDto, User } from '@bdqt/api-client';
@Injectable()
export class UserService {
private usersApi: UsersApi;
constructor(private http: HttpClient) {
this.usersApi = new UsersApi(http);
}
async createUser(data: CreateUserDto): Promise<User> {
// Full type safety - TypeScript knows all properties
return this.usersApi.createUser(data).toPromise();
}
}
```
## Backend Decorators for OpenAPI
Ensure your NestJS controllers use proper decorators:
```typescript
@Controller('users')
@ApiTags('users')
export class UsersController {
@Post()
@ApiOperation({ summary: 'Create a new user' })
@ApiResponse({ status: 201, description: 'User created', type: User })
@ApiResponse({ status: 400, description: 'Invalid input' })
async create(@Body() createUserDto: CreateUserDto): Promise<User> {
return this.usersService.create(createUserDto);
}
}
```
## Configuration
### Backend OpenAPI Setup
Ensure your NestJS backend has Swagger configured (typically in `main.ts`):
```typescript
// apps/backend/src/main.ts
const config = new DocumentBuilder()
.setTitle('ExFabrica AF API')
.setDescription('ExFabrica Agentic Factory API')
.setVersion('1.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api-docs', app, document);
```
### Client Generator Configuration
Located in `libs/api-client/openapitools.json`:
```json
{
"generator-cli": {
"version": "6.2.0",
"generators": {
"typescript-angular": {
"inputSpec": "../../apps/backend/openapi.json",
"output": "./src",
"generatorName": "typescript-axios",
"additionalProperties": {
"npmName": "@bdqt/api-client",
"supportsES6": true,
"withInterfaces": true,
"useSingleRequestParameter": true
}
}
}
}
}
```
## Output Examples
### Success Output
```
🔧 Generating API Client
========================
✓ Backend API started on http://localhost:3000
✓ OpenAPI specification downloaded
✓ Specification validated (OpenAPI 3.0.3)
✓ Found 24 endpoints across 5 controllers
✓ Client code generated successfully
✓ TypeScript compilation successful
✓ Generated 24 API methods, 18 models
Summary:
--------
Endpoints: 24
Models: 18
Generated Files: 42
Size: 187 KB
Duration: 8.3s
The API client has been updated successfully! ✓
Updated workspace: @bdqt/api-client
```
### Validation Warnings
```
⚠️ Validation Warnings
-----------------------
1. Missing response type for DELETE /api/users/:id
Location: UsersController.remove()
Recommendation: Add @ApiResponse decorator
2. DTO missing property descriptions
Location: CreateUserDto
Affected: email, password, firstName, lastName
Recommendation: Add @ApiProperty({ description: '...' })
3. Deprecated endpoint still in use
Location: GET /api/auth/legacy-login
Recommendation: Remove or mark with @Deprecated
Client generated successfully, but consider fixing these warnings.
```
## Watch Mode
When running with `--watch`, the command monitors:
- Changes to `*.controller.ts` files in backend
- Changes to `*.dto.ts` files in backend
- Changes to OpenAPI decorators
- Manual OpenAPI spec updates
On detecting changes:
1. Debounces for 2 seconds (batch multiple changes)
2. Re-extracts OpenAPI specification
3. Compares with previous version
4. Regenerates only if changes detected
5. Notifies you of the update
## Troubleshooting
### Backend Not Starting
```
Error: Cannot start backend server
```
**Solution**: Ensure backend dependencies are installed and database is running
```bash
yarn install
docker compose up -d
```
### OpenAPI Spec Invalid
```
Error: Invalid OpenAPI specification
```
**Solution**: Check backend controller decorators and DTOs
- Ensure all endpoints have proper @ApiOperation
- Verify DTOs have @ApiProperty decorators
- Check for circular references
### Type Generation Errors
```
Error: Failed to generate TypeScript types
```
**Solution**: Update OpenAPI generator version
```bash
cd libs/api-client
yarn add -D @openapitools/openapi-generator-cli@latest
```
### Circular Dependency Detected
```
Error: Circular reference in User -> Profile -> User
```
**Solution**: Restructure models or use lazy imports
```typescript
// Use string reference instead of direct import
@ApiProperty({ type: () => 'Profile' })
profile?: Profile;
```
### Missing Authentication Types
```
Error: Cannot find 'Authorization' header type
```
**Solution**: Add authentication configuration to OpenAPI setup
```typescript
.addBearerAuth({ type: 'http', scheme: 'bearer', bearerFormat: 'JWT' })
```
## Breaking Changes Detection
The command detects breaking changes between versions:
**Breaking Changes**
- Removed endpoints
- Changed request/response types
- Removed model properties
- Changed authentication requirements
**Non-Breaking Changes**
- New endpoints
- New optional properties
- Added documentation
- New response codes
If breaking changes are detected, you'll receive a warning and recommendations for migration.
## Best Practices
1. **Regenerate after backend API changes**
```
# After modifying backend controllers/DTOs
/generate-api-client --validate
```
2. **Use watch mode during active development**
```
/generate-api-client --watch
```
3. **Commit generated client with backend changes**
- Keeps frontend and backend in sync
- Enables type checking across the monorepo
4. **Document your API properly**
```typescript
@ApiOperation({
summary: 'Create user',
description: 'Creates a new user account with the provided details'
})
@ApiResponse({
status: 201,
description: 'User successfully created',
type: User
})
```
5. **Version your API**
- Use API versioning in routes (`/api/v1/users`)
- Generate separate clients for different versions if needed
## Integration with Development Workflow
### Before Deployment
```bash
/generate-api-client --validate
/test-all
/deploy staging
```
### After Backend Changes
```bash
# Make backend changes
/generate-api-client
# Update frontend to use new types
/test-all frontend
```
### In CI/CD Pipeline
```yaml
- task: Script@1
displayName: 'Generate API Client'
inputs:
script: |
/generate-api-client --validate
- task: Script@1
displayName: 'Verify No Changes'
inputs:
script: |
git diff --exit-code libs/api-client/
# Fails if generated code differs (means it wasn't regenerated)
```
## Advanced Usage
### Custom Generator Configuration
Modify `libs/api-client/openapitools.json` for custom generation:
```json
{
"additionalProperties": {
"npmName": "@bdqt/api-client",
"supportsES6": true,
"withInterfaces": true,
"useSingleRequestParameter": true,
"modelPropertyNaming": "camelCase",
"enumPropertyNaming": "UPPERCASE"
}
}
```
### Multiple API Versions
Generate clients for different API versions:
```bash
/generate-api-client v1
/generate-api-client v2
```
Each version gets its own namespace:
- `@bdqt/api-client/v1`
- `@bdqt/api-client/v2`
## Related Commands
- `/test-all` - Test generated client integration
- `/deploy` - Deploy after client generation
- `/analyze-code` - Verify generated code quality
## Benefits
**Type Safety**: Full TypeScript typing across frontend-backend boundary
**Auto-completion**: IDE support for all API methods and models
**Error Prevention**: Catch API mismatches at compile time
**Documentation**: Generated client includes JSDoc from backend
**Consistency**: Single source of truth for API contracts
**Productivity**: No manual API client maintenance
---
**Note**: Always regenerate the client after making changes to backend API endpoints, DTOs, or authentication schemes to maintain type safety across the monorepo.

355
commands/test-all.md Normal file
View File

@@ -0,0 +1,355 @@
# Test All Command
Run the comprehensive test suite for the ExFabrica Agentic Factory monorepo, including unit tests, integration tests, and end-to-end tests for both backend and frontend applications.
## Usage
```
/test-all [target] [--coverage] [--watch] [--verbose]
```
## Parameters
- **target** (optional): Specific test target to run
- `backend` - Run only backend tests
- `frontend` - Run only frontend tests
- `e2e` - Run only end-to-end tests
- `unit` - Run only unit tests (backend + frontend)
- `integration` - Run only integration tests
- If omitted, runs all test suites
- **--coverage** (optional): Generate code coverage reports
- **--watch** (optional): Run tests in watch mode (auto-rerun on changes)
- **--verbose** (optional): Show detailed test output
## Test Suites
### Backend Tests (NestJS + Drizzle ORM)
**Unit Tests**
- Service layer tests
- Controller tests
- Utility function tests
- Guard and interceptor tests
**Integration Tests**
- API endpoint tests
- Database operation tests
- Authentication and authorization flows
- Third-party service integrations
**Test Location**: `apps/backend/src/**/*.spec.ts`
**Test Runner**: Jest
**Configuration**: `apps/backend/jest.config.js`
### Frontend Tests (Angular 20)
**Unit Tests**
- Component tests
- Service tests
- Pipe and directive tests
- Utility function tests
**Integration Tests**
- Component integration tests
- Router navigation tests
- State management tests
- HTTP interceptor tests
**Test Location**: `apps/frontend/src/**/*.spec.ts`
**Test Runner**: Karma + Jasmine
**Configuration**: `apps/frontend/karma.conf.js`
### End-to-End Tests
**E2E Scenarios**
- User authentication flows
- Critical user journeys
- Cross-application workflows
- API integration tests
**Test Location**: `apps/frontend/e2e/`
**Test Runner**: Protractor/Cypress (based on configuration)
## Workflow
When you execute this command, Claude will:
1. **Environment Setup**
- Verify Node.js version (22+)
- Check Yarn version (4.9.2)
- Ensure test database is available
- Set test environment variables
2. **Backend Tests**
- Run unit tests: `yarn workspace @bdqt/backend test`
- Run integration tests: `yarn workspace @bdqt/backend test:integration`
- Generate coverage report if requested
3. **Frontend Tests**
- Run unit tests: `yarn workspace @bdqt/frontend test --watch=false`
- Run in headless Chrome for CI compatibility
- Generate coverage report if requested
4. **E2E Tests** (if applicable)
- Start backend server in test mode
- Start frontend development server
- Run E2E test suite
- Shutdown servers after tests complete
5. **Results Aggregation**
- Combine test results from all suites
- Calculate overall coverage
- Generate unified test report
- Highlight any failures or warnings
## Examples
### Run All Tests
```
/test-all
```
Executes the complete test suite across all applications.
### Run Backend Tests Only
```
/test-all backend
```
Runs only the backend unit and integration tests.
### Run Frontend Tests Only
```
/test-all frontend
```
Runs only the frontend unit tests using Karma.
### Run Tests with Coverage
```
/test-all --coverage
```
Generates code coverage reports for all test suites.
### Run Tests in Watch Mode
```
/test-all backend --watch
```
Runs backend tests in watch mode for active development.
### Run E2E Tests with Verbose Output
```
/test-all e2e --verbose
```
Runs end-to-end tests with detailed logging.
## Coverage Thresholds
The test suite enforces minimum coverage thresholds:
### Backend Coverage Requirements
- **Statements**: 80%
- **Branches**: 75%
- **Functions**: 80%
- **Lines**: 80%
### Frontend Coverage Requirements
- **Statements**: 75%
- **Branches**: 70%
- **Functions**: 75%
- **Lines**: 75%
Tests will fail if coverage drops below these thresholds.
## Test Environment Configuration
### Backend Test Environment
- Uses in-memory SQLite for fast unit tests
- Uses test PostgreSQL database for integration tests (port 5442)
- JWT secrets use test values
- External API calls are mocked
### Frontend Test Environment
- Runs in headless Chrome
- Uses Angular testing utilities (TestBed)
- HTTP calls are mocked via HttpClientTestingModule
- LocalStorage/SessionStorage use test implementations
### E2E Test Environment
- Backend runs on port 3001 (test port)
- Frontend runs on port 4201 (test port)
- Test database is seeded with fixtures
- Clean state before each test suite
## Output Format
### Success Output
```
✓ Backend Unit Tests: 245 passed
✓ Backend Integration Tests: 67 passed
✓ Frontend Unit Tests: 189 passed
✓ E2E Tests: 34 passed
Total: 535 tests passed
Coverage: 82.5% (above threshold)
Duration: 3m 24s
All tests passed successfully! ✓
```
### Failure Output
```
✗ Backend Unit Tests: 243 passed, 2 failed
- UserService.createUser should hash password (apps/backend/src/users/users.service.spec.ts:42)
- AuthGuard should reject expired tokens (apps/backend/src/auth/auth.guard.spec.ts:78)
✓ Backend Integration Tests: 67 passed
✓ Frontend Unit Tests: 189 passed
Total: 499 tests passed, 2 failed
Coverage: 79.2% (below threshold)
Tests failed. Please fix the failing tests before proceeding.
```
## Troubleshooting
### Test Database Connection Issues
```
Error: Cannot connect to test database
```
**Solution**: Ensure Docker is running and test database is available
```bash
docker compose up -d postgres-test
```
### Chrome/Browser Not Found (Frontend Tests)
```
Error: ChromeHeadless not found
```
**Solution**: Install Chromium or configure alternative browser
```bash
yarn add -D puppeteer
```
### Port Already in Use (E2E Tests)
```
Error: Port 3001 already in use
```
**Solution**: Stop any running development servers or use different test ports
### Memory Issues (Large Test Suites)
```
Error: JavaScript heap out of memory
```
**Solution**: Increase Node.js memory limit
```bash
export NODE_OPTIONS="--max-old-space-size=4096"
```
### Flaky E2E Tests
```
Error: Element not found within timeout
```
**Solution**: Increase wait timeouts or add explicit waits in E2E tests
## Performance Optimization
### Parallel Test Execution
Tests run in parallel by default using Jest workers:
- Backend: `--maxWorkers=50%`
- Frontend: `--parallel=true`
### Test Caching
Jest caches test results between runs:
```bash
# Clear test cache if needed
yarn jest --clearCache
```
### Selective Test Running
Run only changed tests during development:
```bash
yarn test --onlyChanged
```
## CI/CD Integration
This command is designed to work seamlessly with Azure DevOps pipelines:
### Pipeline Integration
```yaml
- task: Script@1
displayName: 'Run Test Suite'
inputs:
script: |
/test-all --coverage
```
### Test Results Publishing
Test results are automatically formatted for Azure DevOps:
- JUnit XML for test results
- Cobertura XML for coverage reports
- HTML reports for detailed analysis
## Best Practices
1. **Run tests before committing**
```
/test-all
# Commit only if all tests pass
```
2. **Use watch mode during development**
```
/test-all backend --watch
```
3. **Check coverage regularly**
```
/test-all --coverage
```
4. **Fix failing tests immediately**
- Don't let failing tests accumulate
- Maintain high test quality standards
5. **Run E2E tests before major releases**
```
/test-all e2e
```
## Related Commands
- `/deploy` - Deploy after tests pass
- `/analyze-code` - Check code quality and test coverage
- `/db-operations seed` - Seed test database with fixtures
## Test Writing Guidelines
### Backend Test Example
```typescript
describe('UserService', () => {
it('should create a new user with hashed password', async () => {
const userData = { email: 'test@example.com', password: 'password123' };
const user = await userService.create(userData);
expect(user.password).not.toBe('password123');
expect(await bcrypt.compare('password123', user.password)).toBe(true);
});
});
```
### Frontend Test Example
```typescript
describe('LoginComponent', () => {
it('should disable submit button when form is invalid', () => {
component.loginForm.controls['email'].setValue('');
fixture.detectChanges();
const submitButton = fixture.nativeElement.querySelector('button[type="submit"]');
expect(submitButton.disabled).toBe(true);
});
});
```
---
**Note**: All tests use the Yarn workspace structure. Direct Jest/Karma commands should be run through Yarn workspaces to respect the monorepo configuration.