From 33bbf60bad5d4f6fdd0e77ab83d1dd5c1bc42a78 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Tue, 17 Feb 2026 11:46:12 -0600 Subject: [PATCH] generalize presets into mosaic profiles with runtime overlays --- README.md | 4 + STANDARDS.md | 2 + bin/mosaic-link-runtime-assets | 4 + profiles/README.md | 22 ++ profiles/domains/crypto-web3.json | 181 ++++++++++++++++ profiles/domains/fintech-security.json | 181 ++++++++++++++++ profiles/domains/healthcare-hipaa.json | 189 ++++++++++++++++ profiles/tech-stacks/nestjs-backend.json | 154 ++++++++++++++ profiles/tech-stacks/nextjs-fullstack.json | 171 +++++++++++++++ profiles/tech-stacks/python-fastapi.json | 168 +++++++++++++++ profiles/tech-stacks/react-frontend.json | 161 ++++++++++++++ profiles/workflows/api-development.json | 182 ++++++++++++++++ profiles/workflows/frontend-component.json | 201 ++++++++++++++++++ profiles/workflows/testing-automation.json | 196 +++++++++++++++++ .../settings-overlays/jarvis-ralph.json | 52 +++++ 15 files changed, 1868 insertions(+) create mode 100644 profiles/README.md create mode 100644 profiles/domains/crypto-web3.json create mode 100644 profiles/domains/fintech-security.json create mode 100644 profiles/domains/healthcare-hipaa.json create mode 100644 profiles/tech-stacks/nestjs-backend.json create mode 100644 profiles/tech-stacks/nextjs-fullstack.json create mode 100644 profiles/tech-stacks/python-fastapi.json create mode 100644 profiles/tech-stacks/react-frontend.json create mode 100644 profiles/workflows/api-development.json create mode 100644 profiles/workflows/frontend-component.json create mode 100644 profiles/workflows/testing-automation.json create mode 100644 runtime/claude/settings-overlays/jarvis-ralph.json diff --git a/README.md b/README.md index 20c0143..8c90540 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,9 @@ bash ~/src/mosaic-bootstrap/install.sh - Shared standards document: `~/.mosaic/STANDARDS.md` - Shared operational guides: `~/.mosaic/guides/` - Shared quality rails/scripts: `~/.mosaic/rails/` +- Shared runtime-neutral presets/profiles: `~/.mosaic/profiles/` - Runtime adapter docs: `~/.mosaic/adapters/` +- Runtime overlays: `~/.mosaic/runtime/` - Shared wrapper commands: `~/.mosaic/bin/` - Canonical skills directory: `~/.mosaic/skills` @@ -50,6 +52,8 @@ Installer also links Claude-compatible paths back to Mosaic canonicals: - `~/.claude/agent-guides` -> `~/.mosaic/guides` - `~/.claude/scripts/{git,codex,bootstrap}` -> `~/.mosaic/rails/...` - `~/.claude/templates` -> `~/.mosaic/templates/agent` +- `~/.claude/presets/{domains,tech-stacks,workflows}` -> `~/.mosaic/profiles/...` +- `~/.claude/presets/*.json` runtime overlays -> `~/.mosaic/runtime/claude/settings-overlays/` Run manually: diff --git a/STANDARDS.md b/STANDARDS.md index 5de43e7..6c9f4b6 100644 --- a/STANDARDS.md +++ b/STANDARDS.md @@ -51,3 +51,5 @@ Runtime-compatible guides and rails are hosted at: - `~/.mosaic/guides/` - `~/.mosaic/rails/` +- `~/.mosaic/profiles/` (runtime-neutral domain/workflow/stack presets) +- `~/.mosaic/runtime/` (runtime-specific overlays) diff --git a/bin/mosaic-link-runtime-assets b/bin/mosaic-link-runtime-assets index 5a15030..257183e 100755 --- a/bin/mosaic-link-runtime-assets +++ b/bin/mosaic-link-runtime-assets @@ -48,6 +48,10 @@ link_tree_files "$MOSAIC_HOME/rails/git" "$HOME/.claude/scripts/git" link_tree_files "$MOSAIC_HOME/rails/codex" "$HOME/.claude/scripts/codex" link_tree_files "$MOSAIC_HOME/rails/bootstrap" "$HOME/.claude/scripts/bootstrap" link_tree_files "$MOSAIC_HOME/templates/agent" "$HOME/.claude/templates" +link_tree_files "$MOSAIC_HOME/profiles/domains" "$HOME/.claude/presets/domains" +link_tree_files "$MOSAIC_HOME/profiles/tech-stacks" "$HOME/.claude/presets/tech-stacks" +link_tree_files "$MOSAIC_HOME/profiles/workflows" "$HOME/.claude/presets/workflows" +link_tree_files "$MOSAIC_HOME/runtime/claude/settings-overlays" "$HOME/.claude/presets" for qa_script in \ debug-hook.sh \ diff --git a/profiles/README.md b/profiles/README.md new file mode 100644 index 0000000..383ce52 --- /dev/null +++ b/profiles/README.md @@ -0,0 +1,22 @@ +# Mosaic Profiles + +Profiles are runtime-neutral context packs that can be consumed by any agent runtime. + +## Layout + +- `domains/`: regulated-domain and security context (HIPAA, fintech, crypto, etc.) +- `tech-stacks/`: stack-specific conventions and quality checks +- `workflows/`: reusable execution workflows + +## Runtime Split + +- Runtime-neutral content belongs here under `~/.mosaic/profiles`. +- Runtime-specific settings belong under `~/.mosaic/runtime//...`. + +Current runtime overlay example: + +- `~/.mosaic/runtime/claude/settings-overlays/jarvis-ralph.json` + +## Claude Compatibility + +`mosaic-link-runtime-assets` links these into `~/.claude/presets/*` so existing Claude flows keep working while `~/.mosaic` remains canonical. diff --git a/profiles/domains/crypto-web3.json b/profiles/domains/crypto-web3.json new file mode 100644 index 0000000..2baf46f --- /dev/null +++ b/profiles/domains/crypto-web3.json @@ -0,0 +1,181 @@ +{ + "name": "Cryptocurrency & Web3 Security", + "description": "Security patterns for blockchain, cryptocurrency, and Web3 applications", + "domainKeywords": ["crypto", "blockchain", "web3", "defi", "nft", "wallet", "smart contract", "ethereum"], + "compliance": { + "regulations": ["AML", "KYC", "FATF", "BSA", "Regional crypto regulations"], + "scope": "Applications handling cryptocurrencies and digital assets", + "requirements": [ + "Secure private key management", + "Anti-money laundering (AML) compliance", + "Know Your Customer (KYC) verification", + "Transaction monitoring and reporting", + "Wallet security and multi-signature", + "Smart contract security audits" + ] + }, + "securityPatterns": { + "walletSecurity": { + "privateKeys": "Never store private keys in plaintext", + "keyDerivation": "Use BIP32/BIP44 for key derivation", + "storage": "Hardware Security Modules (HSMs) for production", + "backup": "Secure backup and recovery procedures", + "multiSig": "Multi-signature wallets for high-value transactions" + }, + "smartContracts": { + "auditing": "Professional security audits required", + "testing": "Comprehensive test coverage including edge cases", + "upgradeability": "Consider proxy patterns for upgradeable contracts", + "accessControl": "Role-based access control in contracts", + "gasOptimization": "Optimize for gas efficiency and DoS protection" + }, + "transactionSecurity": { + "validation": "Multi-layer transaction validation", + "monitoring": "Real-time transaction monitoring", + "limits": "Configurable transaction limits", + "timelock": "Time-delayed execution for large transactions", + "approval": "Multi-party approval workflows" + }, + "apiSecurity": { + "authentication": "Strong API authentication (JWT + API keys)", + "rateLimit": "Aggressive rate limiting for trading APIs", + "signing": "Request signing for sensitive operations", + "websockets": "Secure WebSocket connections for real-time data" + } + }, + "implementationPatterns": { + "backend": { + "walletIntegration": { + "abstraction": "Abstract wallet operations behind service layer", + "keyManagement": "Separate key management from application logic", + "transactions": "Queue and batch transactions for efficiency", + "monitoring": "Monitor blockchain for transaction confirmations" + }, + "tradingEngine": { + "orderMatching": "Secure order matching algorithms", + "balanceTracking": "Accurate balance tracking with locks", + "riskManagement": "Position limits and risk controls", + "latency": "Low-latency execution for competitive trading" + }, + "compliance": { + "kyc": "Identity verification workflows", + "aml": "Automated AML screening and monitoring", + "reporting": "Suspicious activity reporting (SAR)", + "sanctions": "OFAC and sanctions list screening" + } + }, + "frontend": { + "walletConnection": { + "webWallets": "Support for MetaMask, WalletConnect, etc.", + "security": "Validate wallet signatures and addresses", + "persistence": "Secure session management", + "switching": "Handle network and account switching" + }, + "trading": { + "realTime": "Real-time price and order book updates", + "charting": "Advanced charting capabilities", + "orderTypes": "Support for various order types", + "riskWarnings": "Clear risk disclosures and warnings" + } + } + }, + "blockchainIntegration": { + "ethereum": { + "web3": "Use ethers.js or web3.js for blockchain interaction", + "infura": "Reliable node access via Infura/Alchemy", + "events": "Event listening and log parsing", + "gasManagement": "Dynamic gas price management" + }, + "bitcoin": { + "addresses": "Support for multiple address types", + "utxo": "UTXO management and coin selection", + "fees": "Dynamic fee estimation", + "scripting": "Advanced scripting for complex transactions" + }, + "multiChain": { + "abstraction": "Chain-agnostic service interfaces", + "bridging": "Cross-chain bridge integrations", + "networks": "Support for testnets and multiple networks", + "consensus": "Handle different consensus mechanisms" + } + }, + "testingRequirements": { + "coverage": { + "minimum": "95% for financial logic modules", + "focus": "Security-critical components and edge cases" + }, + "security": [ + "Smart contract security audits", + "Penetration testing for web interfaces", + "Key management security testing", + "Transaction flow security validation", + "API security testing" + ], + "blockchain": [ + "Test on multiple networks (mainnet, testnet)", + "Handle network congestion scenarios", + "Test transaction failure and retry logic", + "Validate gas estimation accuracy", + "Test blockchain reorganization handling" + ] + }, + "context7Libraries": [ + "ethers", + "web3", + "@metamask/providers", + "bitcoinjs-lib", + "@walletconnect/client", + "bip32", + "bip39" + ], + "codeTemplates": { + "walletService": { + "description": "Secure wallet service interface", + "template": "@Injectable()\nexport class WalletService {\n async signTransaction(transaction: Transaction, keyId: string): Promise {\n const privateKey = await this.keyManager.getKey(keyId);\n return this.signer.sign(transaction, privateKey);\n }\n\n async validateAddress(address: string, network: Network): Promise {\n return this.validator.isValid(address, network);\n }\n}" + }, + "transactionMonitor": { + "description": "Blockchain transaction monitoring", + "template": "this.web3.eth.subscribe('pendingTransactions', (txHash) => {\n this.web3.eth.getTransaction(txHash).then(tx => {\n if (this.isWatchedAddress(tx.to)) {\n this.processIncomingTransaction(tx);\n }\n });\n});" + }, + "smartContractInteraction": { + "description": "Safe smart contract interaction", + "template": "const contract = new ethers.Contract(address, abi, signer);\nconst gasEstimate = await contract.estimateGas.transfer(to, amount);\nconst tx = await contract.transfer(to, amount, {\n gasLimit: gasEstimate.mul(110).div(100), // 10% buffer\n gasPrice: await this.getOptimalGasPrice()\n});" + } + }, + "complianceChecklist": [ + "Know Your Customer (KYC) procedures implemented", + "Anti-Money Laundering (AML) monitoring in place", + "Suspicious activity reporting (SAR) procedures", + "OFAC and sanctions screening implemented", + "Transaction monitoring and analysis tools", + "Customer due diligence (CDD) procedures", + "Enhanced due diligence (EDD) for high-risk customers", + "Record keeping and data retention policies", + "Compliance training for staff", + "Regular compliance audits and reviews" + ], + "securityBestPractices": [ + "Never store private keys in application code", + "Use hardware security modules (HSMs) for key storage", + "Implement multi-signature wallets for treasury management", + "Conduct regular security audits of smart contracts", + "Use time-locked transactions for large amounts", + "Implement comprehensive transaction monitoring", + "Use secure random number generation", + "Validate all blockchain data independently", + "Implement proper access controls and authentication", + "Maintain detailed audit logs of all operations" + ], + "riskAssessment": [ + "Private key compromise and theft", + "Smart contract vulnerabilities and exploits", + "Exchange hacks and loss of user funds", + "Regulatory compliance failures", + "Market manipulation and fraud", + "Technical failures and system outages", + "Insider threats and malicious employees", + "Third-party service provider risks", + "Quantum computing threats to cryptography", + "Cross-chain bridge vulnerabilities" + ] +} \ No newline at end of file diff --git a/profiles/domains/fintech-security.json b/profiles/domains/fintech-security.json new file mode 100644 index 0000000..04278c5 --- /dev/null +++ b/profiles/domains/fintech-security.json @@ -0,0 +1,181 @@ +{ + "name": "Fintech Security Compliance", + "description": "PCI DSS and financial security requirements for fintech applications", + "domainKeywords": ["payment", "financial", "banking", "credit", "debit", "transaction", "pci", "fintech"], + "compliance": { + "regulations": ["PCI DSS", "PSD2", "SOX", "KYC", "AML"], + "scope": "Applications processing payment card data", + "requirements": [ + "Secure cardholder data", + "Encrypt transmission of cardholder data", + "Protect stored cardholder data", + "Maintain vulnerability management program", + "Implement strong access control measures", + "Regularly monitor and test networks", + "Maintain information security policy" + ] + }, + "dataClassification": { + "pan": { + "definition": "Primary Account Number (Credit/Debit card number)", + "storage": "Never store full PAN unless absolutely necessary", + "masking": "Show only last 4 digits", + "encryption": "AES-256 if storage required", + "transmission": "Always encrypted with TLS 1.2+" + }, + "sadData": { + "definition": "Sensitive Authentication Data", + "types": ["CVV2", "PIN", "Track data"], + "storage": "Never store SAD after authorization", + "handling": "Process but do not retain" + }, + "cardholderData": { + "definition": "PAN + cardholder name, service code, expiration date", + "minimization": "Store only if business need exists", + "retention": "Purge when no longer needed", + "access": "Restrict access to authorized personnel only" + } + }, + "securityPatterns": { + "encryption": { + "algorithm": "AES-256 for data at rest", + "keyManagement": "Hardware Security Modules (HSMs) preferred", + "transmission": "TLS 1.2+ for data in transit", + "tokenization": "Replace PAN with non-sensitive tokens" + }, + "authentication": { + "mfa": "Multi-factor authentication mandatory", + "passwordPolicy": "Complex passwords, regular rotation", + "sessionManagement": "Secure session handling with timeout", + "biometric": "Support for biometric authentication" + }, + "authorization": { + "rbac": "Role-based access control", + "segregationOfDuties": "Separate roles for sensitive operations", + "leastPrivilege": "Minimum necessary access principle", + "approval": "Multi-person approval for high-value transactions" + }, + "fraudPrevention": { + "riskScoring": "Real-time transaction risk assessment", + "monitoring": "Anomaly detection and behavioral analytics", + "alerts": "Immediate alerts for suspicious activities", + "blocking": "Automatic blocking of fraudulent transactions" + } + }, + "implementationPatterns": { + "backend": { + "paymentProcessing": { + "tokenization": "Use payment tokens instead of card data", + "validation": "Validate all payment inputs", + "logging": "Log transactions without sensitive data", + "encryption": "Encrypt cardholder data before storage" + }, + "apiSecurity": { + "rateLimit": "Implement rate limiting", + "apiKeys": "Secure API key management", + "signing": "Request signing for sensitive operations", + "monitoring": "Monitor API usage patterns" + }, + "database": { + "encryption": "Database-level encryption for sensitive fields", + "access": "Database access controls and monitoring", + "backup": "Encrypted backups with secure key management", + "masking": "Data masking for non-production environments" + } + }, + "frontend": { + "paymentForms": { + "https": "Always use HTTPS for payment pages", + "validation": "Client-side validation with server confirmation", + "autocomplete": "Disable autocomplete for sensitive fields", + "iframes": "Use secure iframes for payment card input" + }, + "dataHandling": { + "noStorage": "Never store payment data in browser", + "masking": "Mask card numbers in UI", + "timeout": "Session timeout for payment pages", + "clearData": "Clear payment data from memory after use" + } + } + }, + "testingRequirements": { + "coverage": { + "minimum": "90% for payment processing modules", + "focus": "Security controls and fraud prevention" + }, + "security": [ + "Penetration testing quarterly", + "Vulnerability scanning monthly", + "Code review for all payment code", + "Test encryption implementation", + "Validate tokenization process" + ], + "compliance": [ + "PCI DSS compliance validation", + "Test access controls", + "Validate audit logging", + "Test incident response procedures", + "Verify data retention policies" + ] + }, + "context7Libraries": [ + "stripe", + "bcrypt", + "jsonwebtoken", + "helmet", + "express-rate-limit", + "crypto" + ], + "codeTemplates": { + "paymentEntity": { + "description": "Payment entity with tokenization", + "template": "@Entity()\nexport class Payment {\n @Tokenized()\n @Column()\n cardToken: string;\n\n @Column()\n lastFourDigits: string;\n\n @Encrypted()\n @Column()\n amount: number;\n}" + }, + "transactionLog": { + "description": "Secure transaction logging", + "template": "await this.auditService.logTransaction({\n transactionId: transaction.id,\n userId: user.id,\n amount: transaction.amount,\n currency: transaction.currency,\n status: 'COMPLETED',\n riskScore: riskAssessment.score,\n timestamp: new Date()\n});" + }, + "fraudCheck": { + "description": "Fraud prevention check", + "template": "const riskScore = await this.fraudService.assessRisk({\n userId: user.id,\n amount: transaction.amount,\n location: transaction.location,\n deviceFingerprint: request.deviceId\n});\n\nif (riskScore > FRAUD_THRESHOLD) {\n await this.alertService.triggerFraudAlert(transaction);\n}" + } + }, + "complianceChecklist": [ + "Cardholder data is encrypted at rest and in transit", + "Sensitive authentication data is not stored", + "Access to cardholder data is restricted and monitored", + "Strong cryptography and security protocols are used", + "Antivirus software is maintained", + "Secure systems and applications are developed", + "Access to data is restricted by business need-to-know", + "Unique IDs are assigned to each person with computer access", + "Physical access to cardholder data is restricted", + "All access to network resources is logged and monitored", + "Security systems and processes are regularly tested", + "Information security policy is maintained" + ], + "riskAssessment": [ + "Unauthorized access to payment data", + "Data breaches and card data theft", + "Fraud and unauthorized transactions", + "System vulnerabilities and exploits", + "Insider threats and malicious employees", + "Third-party payment processor risks", + "Network security vulnerabilities", + "Application security weaknesses", + "Physical security of payment systems", + "Business continuity and disaster recovery" + ], + "regulatoryReporting": [ + "PCI DSS compliance reports", + "Suspicious activity reports (SARs)", + "Currency transaction reports (CTRs)", + "Know Your Customer (KYC) documentation", + "Anti-Money Laundering (AML) compliance", + "Data breach notification requirements", + "Consumer privacy disclosures", + "Financial audit requirements", + "Incident response documentation", + "Third-party risk assessments" + ] +} \ No newline at end of file diff --git a/profiles/domains/healthcare-hipaa.json b/profiles/domains/healthcare-hipaa.json new file mode 100644 index 0000000..59dc4f0 --- /dev/null +++ b/profiles/domains/healthcare-hipaa.json @@ -0,0 +1,189 @@ +{ + "name": "Healthcare HIPAA Compliance", + "description": "HIPAA compliance requirements for healthcare applications handling PHI", + "domainKeywords": ["health", "medical", "patient", "hipaa", "phi", "healthcare"], + "compliance": { + "regulation": "HIPAA (Health Insurance Portability and Accountability Act)", + "scope": "All applications handling Protected Health Information (PHI)", + "requirements": [ + "Encrypt PHI at rest and in transit", + "Implement access controls for PHI", + "Audit all access to PHI", + "Ensure data integrity", + "Implement proper user authentication", + "Maintain data minimization practices" + ] + }, + "dataClassification": { + "phi": { + "definition": "Individually identifiable health information", + "examples": [ + "Names, addresses, birth dates", + "Phone numbers, email addresses", + "Social Security numbers", + "Medical record numbers", + "Health plan beneficiary numbers", + "Account numbers", + "Certificate/license numbers", + "Vehicle identifiers and serial numbers", + "Device identifiers and serial numbers", + "Web Universal Resource Locators (URLs)", + "Internet Protocol (IP) address numbers", + "Biometric identifiers", + "Full face photographic images", + "Medical diagnoses and treatment information", + "Lab results and vital signs" + ], + "encryption": "AES-256 encryption required", + "storage": "Must be encrypted at rest", + "transmission": "Must be encrypted in transit (TLS 1.2+)" + } + }, + "securityPatterns": { + "encryption": { + "algorithm": "AES-256", + "keyManagement": "Use AWS KMS, Azure Key Vault, or similar", + "implementation": "Field-level encryption for PHI columns", + "example": "@Encrypted decorator for entity fields" + }, + "authentication": { + "method": "Multi-factor authentication required", + "tokenType": "JWT with refresh tokens", + "sessionTimeout": "Maximum 15 minutes inactive timeout", + "passwordPolicy": "Minimum 8 characters, complexity requirements" + }, + "authorization": { + "model": "Role-Based Access Control (RBAC)", + "principle": "Minimum necessary access", + "implementation": "Care group permissions with data segmentation", + "auditTrail": "Log all authorization decisions" + }, + "auditLogging": { + "requirement": "All PHI access must be logged", + "fields": [ + "User ID", + "Patient ID", + "Action performed", + "Timestamp", + "IP address", + "Success/failure", + "Data accessed" + ], + "retention": "6 years minimum", + "integrity": "Logs must be tamper-evident" + } + }, + "implementationPatterns": { + "backend": { + "entities": { + "phiFields": "Mark PHI fields with @PHIEncrypted decorator", + "auditables": "Extend BaseAuditableEntity for PHI entities", + "relationships": "Implement proper access control on relationships" + }, + "controllers": { + "authentication": "All PHI endpoints require authentication", + "authorization": "Check user permissions before PHI access", + "logging": "Log all PHI access attempts", + "validation": "Validate all inputs to prevent injection" + }, + "services": { + "encryption": "Encrypt PHI before database storage", + "decryption": "Decrypt PHI only for authorized access", + "minimization": "Return only necessary PHI fields", + "auditing": "Create audit log entries for all PHI operations" + } + }, + "frontend": { + "dataHandling": { + "localStorage": "Never store PHI in localStorage", + "sessionStorage": "Only encrypted session data allowed", + "memory": "Clear PHI from component state on unmount", + "logging": "Never log PHI to console or external services" + }, + "ui": { + "masking": "Mask sensitive data by default", + "permissions": "Hide UI elements based on user roles", + "timeout": "Implement session timeout with warnings", + "accessibility": "Ensure screen readers don't expose PHI inappropriately" + } + } + }, + "testingRequirements": { + "coverage": { + "minimum": "80% for all PHI-handling modules", + "focus": "Security and privacy controls" + }, + "security": [ + "Test for PHI leakage in API responses", + "Verify encryption of PHI fields", + "Test authorization controls", + "Validate audit logging functionality", + "Test session timeout behavior" + ], + "compliance": [ + "Verify minimum necessary access", + "Test audit log completeness", + "Validate encryption implementation", + "Test user access controls", + "Verify data retention policies" + ] + }, + "context7Libraries": [ + "@nestjs/jwt", + "bcrypt", + "helmet", + "crypto", + "jsonwebtoken", + "express-rate-limit" + ], + "codeTemplates": { + "phiEntity": { + "description": "Entity with PHI fields", + "template": "@Entity()\nexport class Patient {\n @PHIEncrypted()\n @Column()\n firstName: string;\n\n @AuditableField()\n @Column()\n medicalRecordNumber: string;\n}" + }, + "auditLog": { + "description": "Audit log entry", + "template": "await this.auditService.log({\n userId: user.id,\n action: 'VIEW_PATIENT',\n resourceType: 'Patient',\n resourceId: patientId,\n ipAddress: request.ip,\n timestamp: new Date()\n});" + }, + "authGuard": { + "description": "HIPAA auth guard", + "template": "@UseGuards(JwtAuthGuard, RolesGuard)\n@RequirePermission('view_patient_phi')\n@ApiSecurity('bearer')" + } + }, + "complianceChecklist": [ + "All PHI fields are encrypted at rest", + "All PHI transmission uses TLS 1.2+", + "User authentication is implemented with MFA", + "Role-based access control is enforced", + "All PHI access is logged and auditable", + "Session timeout is configured (max 15 minutes)", + "Password policies meet HIPAA requirements", + "Data backup and recovery procedures are secure", + "Incident response procedures are documented", + "Employee access is based on minimum necessary principle" + ], + "riskAssessment": [ + "Unauthorized access to PHI", + "Data breaches due to weak encryption", + "Insider threats and inappropriate access", + "Data loss due to inadequate backups", + "System vulnerabilities and exploits", + "Third-party vendor security risks", + "Physical security of systems and data", + "Network security and access controls", + "Application security vulnerabilities", + "Business continuity and disaster recovery" + ], + "incidentResponse": [ + "Identify and contain the incident", + "Assess the scope and severity", + "Notify affected individuals if required", + "Report to HHS if breach affects 500+ individuals", + "Implement corrective actions", + "Document all incident response activities", + "Conduct post-incident review and lessons learned", + "Update security policies and procedures", + "Provide additional training if needed", + "Monitor for similar incidents" + ] +} \ No newline at end of file diff --git a/profiles/tech-stacks/nestjs-backend.json b/profiles/tech-stacks/nestjs-backend.json new file mode 100644 index 0000000..a39c655 --- /dev/null +++ b/profiles/tech-stacks/nestjs-backend.json @@ -0,0 +1,154 @@ +{ + "name": "NestJS Backend", + "description": "NestJS backend with TypeORM, PostgreSQL, and comprehensive testing", + "filePatterns": ["*.ts", "*.js"], + "excludePatterns": ["*.spec.ts", "*.test.ts", "*.d.ts"], + "techStack": { + "framework": "NestJS", + "language": "TypeScript", + "database": "TypeORM + PostgreSQL", + "validation": "class-validator + class-transformer", + "testing": "Jest + Supertest", + "documentation": "Swagger/OpenAPI", + "caching": "Redis + cache-manager", + "queues": "Bull + Redis" + }, + "conventions": { + "naming": { + "variables": "camelCase", + "functions": "camelCase", + "classes": "PascalCase", + "interfaces": "PascalCase with I prefix", + "types": "PascalCase with T prefix", + "enums": "PascalCase", + "constants": "UPPER_SNAKE_CASE" + }, + "fileStructure": { + "modules": "Feature-based modules in src/{feature}/", + "controllers": "{feature}.controller.ts", + "services": "{feature}.service.ts", + "entities": "{feature}.entity.ts", + "dtos": "dto/{feature}.dto.ts", + "tests": "{feature}.controller.spec.ts, {feature}.service.spec.ts" + }, + "imports": { + "style": "Absolute imports with @ prefix when available", + "grouping": "Third-party, @nestjs, internal, relative", + "sorting": "Alphabetical within groups" + } + }, + "qualityChecks": { + "lint": { + "command": "npx eslint --fix", + "config": "Google TypeScript ESLint config", + "autoFix": true + }, + "format": { + "command": "npx prettier --write", + "config": "80 character line limit", + "autoFix": true + }, + "build": { + "command": "npm run build", + "checkTypes": true, + "failOnError": true + }, + "test": { + "unit": "npm run test:unit", + "integration": "npm run test:integration", + "coverage": "npm run test:cov", + "minimumCoverage": 40 + } + }, + "codePatterns": { + "controller": { + "decorators": ["@Controller", "@ApiTags", "@UseGuards"], + "methods": ["@Get", "@Post", "@Put", "@Delete", "@Patch"], + "responses": ["@ApiResponse", "@ApiOperation"], + "validation": ["@Body", "@Param", "@Query with DTOs"], + "errorHandling": "Use HttpException and custom exception filters" + }, + "service": { + "injection": "Constructor dependency injection with @Injectable", + "methods": "Async methods with proper error handling", + "database": "Use TypeORM repository pattern", + "transactions": "@Transaction decorator for data consistency" + }, + "entity": { + "decorators": ["@Entity", "@PrimaryGeneratedColumn", "@Column"], + "relationships": ["@ManyToOne", "@OneToMany", "@ManyToMany"], + "validation": "class-validator decorators on fields", + "timestamps": "Include createdAt, updatedAt with @CreateDateColumn" + }, + "dto": { + "validation": "class-validator decorators (@IsString, @IsOptional)", + "transformation": "class-transformer decorators (@Transform, @Type)", + "swagger": "Swagger decorators (@ApiProperty, @ApiPropertyOptional)", + "inheritance": "Use PartialType, PickType for variations" + }, + "testing": { + "unit": "Test services and controllers independently with mocks", + "integration": "Test complete request/response cycles", + "mocking": "Use jest.mock for dependencies", + "coverage": "Focus on business logic and edge cases" + } + }, + "context7Libraries": [ + "@nestjs/common", + "@nestjs/core", + "@nestjs/typeorm", + "@nestjs/swagger", + "@nestjs/jwt", + "@nestjs/passport", + "@nestjs/cache-manager", + "@nestjs/throttler", + "typeorm", + "class-validator", + "class-transformer", + "jest" + ], + "commonImports": { + "controller": [ + "import { Controller, Get, Post, Put, Delete, Patch, Body, Param, Query, UseGuards, HttpException, HttpStatus } from '@nestjs/common';", + "import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';" + ], + "service": [ + "import { Injectable } from '@nestjs/common';", + "import { InjectRepository } from '@nestjs/typeorm';", + "import { Repository } from 'typeorm';" + ], + "entity": [ + "import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';", + "import { IsString, IsOptional, IsNumber, IsBoolean, IsDate } from 'class-validator';" + ], + "dto": [ + "import { IsString, IsOptional, IsNumber, IsBoolean, IsEmail, IsArray } from 'class-validator';", + "import { Transform, Type } from 'class-transformer';", + "import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';" + ] + }, + "bestPractices": [ + "Use dependency injection for all services and repositories", + "Validate all input data using DTOs with class-validator", + "Document all API endpoints with Swagger decorators", + "Implement proper error handling with custom exception filters", + "Use TypeORM repositories for database operations", + "Write unit tests for all services and integration tests for controllers", + "Use environment variables for configuration", + "Implement rate limiting and security guards", + "Use transactions for operations affecting multiple entities", + "Follow REST API conventions for endpoint naming" + ], + "securityConsiderations": [ + "Validate and sanitize all inputs", + "Use JWT authentication with proper token validation", + "Implement role-based access control (RBAC)", + "Use HTTPS in production environments", + "Implement rate limiting to prevent abuse", + "Hash passwords using bcrypt", + "Use parameterized queries to prevent SQL injection", + "Implement proper CORS configuration", + "Log security-relevant events for auditing", + "Use environment variables for sensitive configuration" + ] +} \ No newline at end of file diff --git a/profiles/tech-stacks/nextjs-fullstack.json b/profiles/tech-stacks/nextjs-fullstack.json new file mode 100644 index 0000000..ce39fd5 --- /dev/null +++ b/profiles/tech-stacks/nextjs-fullstack.json @@ -0,0 +1,171 @@ +{ + "name": "Next.js Fullstack", + "description": "Next.js 14+ with App Router, TypeScript, Tailwind CSS, and modern fullstack development", + "filePatterns": ["*.tsx", "*.ts", "*.jsx", "*.js"], + "excludePatterns": ["*.test.tsx", "*.test.ts", "*.spec.tsx", "*.spec.ts", "*.d.ts"], + "techStack": { + "framework": "Next.js 14+ with App Router", + "language": "TypeScript", + "styling": "Tailwind CSS", + "database": "Prisma + PostgreSQL", + "authentication": "NextAuth.js", + "stateManagement": "Zustand + React Query", + "testing": "Jest + React Testing Library", + "deployment": "Vercel", + "api": "Next.js API Routes / Server Actions" + }, + "conventions": { + "naming": { + "components": "PascalCase (UserProfile.tsx)", + "pages": "lowercase with hyphens (user-profile/page.tsx)", + "apiRoutes": "lowercase with hyphens (api/user-profile/route.ts)", + "hooks": "camelCase with use prefix (useAuth.ts)", + "utilities": "camelCase (formatDate.ts)", + "constants": "UPPER_SNAKE_CASE", + "types": "PascalCase with T prefix" + }, + "fileStructure": { + "appRouter": "app/{route}/page.tsx, layout.tsx", + "apiRoutes": "app/api/{endpoint}/route.ts", + "components": "components/{feature}/{ComponentName}.tsx", + "hooks": "hooks/use{HookName}.ts", + "libs": "lib/{utility}.ts", + "types": "types/{feature}.types.ts", + "prisma": "prisma/schema.prisma, prisma/migrations/", + "tests": "__tests__/{ComponentName}.test.tsx" + }, + "imports": { + "style": "Absolute imports with @ prefix", + "grouping": "React/Next, third-party, internal, relative", + "sorting": "Alphabetical within groups" + } + }, + "qualityChecks": { + "lint": { + "command": "npx eslint --fix", + "config": "Next.js ESLint + TypeScript", + "autoFix": true + }, + "format": { + "command": "npx prettier --write", + "config": "80 character line limit", + "autoFix": true + }, + "build": { + "command": "npm run build", + "checkTypes": true, + "failOnError": true + }, + "test": { + "unit": "npm test", + "coverage": "npm run test:coverage", + "minimumCoverage": 75 + } + }, + "codePatterns": { + "page": { + "structure": "Default export function with metadata", + "metadata": "Use generateMetadata for dynamic SEO", + "loading": "Create loading.tsx for loading states", + "error": "Create error.tsx for error boundaries", + "notFound": "Create not-found.tsx for 404 handling" + }, + "layout": { + "structure": "Root layout with html and body tags", + "metadata": "Define default metadata and viewport", + "providers": "Wrap children with necessary providers", + "fonts": "Use next/font for font optimization" + }, + "component": { + "client": "Use 'use client' directive for client components", + "server": "Default to server components when possible", + "props": "Define TypeScript interfaces for props", + "memo": "Use React.memo for performance when needed" + }, + "apiRoute": { + "structure": "Export named functions (GET, POST, etc.)", + "params": "Use typed params and searchParams", + "responses": "Return NextResponse with proper status codes", + "middleware": "Use middleware for auth and validation" + }, + "serverActions": { + "directive": "Use 'use server' directive", + "validation": "Validate input data with zod", + "revalidation": "Use revalidatePath/revalidateTag", + "errors": "Handle errors gracefully" + }, + "database": { + "prisma": "Use Prisma Client for database operations", + "transactions": "Use Prisma transactions for complex operations", + "migrations": "Use Prisma migrate for schema changes", + "seeding": "Create seed scripts for development data" + } + }, + "context7Libraries": [ + "next", + "react", + "@next/font", + "next-auth", + "@prisma/client", + "prisma", + "tailwindcss", + "zustand", + "@tanstack/react-query", + "zod" + ], + "commonImports": { + "page": [ + "import { Metadata } from 'next';", + "import { notFound } from 'next/navigation';" + ], + "component": [ + "import React from 'react';", + "import Link from 'next/link';", + "import Image from 'next/image';" + ], + "apiRoute": [ + "import { NextRequest, NextResponse } from 'next/server';", + "import { getServerSession } from 'next-auth';" + ], + "serverAction": [ + "import { revalidatePath } from 'next/cache';", + "import { redirect } from 'next/navigation';" + ] + }, + "bestPractices": [ + "Use App Router instead of Pages Router for new projects", + "Default to Server Components, use Client Components only when needed", + "Use Next.js Image component for optimized images", + "Implement proper SEO with metadata API", + "Use Server Actions for form handling and mutations", + "Implement proper error handling with error boundaries", + "Use Prisma for type-safe database operations", + "Implement proper authentication with NextAuth.js", + "Use Tailwind CSS for styling with design system approach", + "Implement proper loading states and skeleton screens" + ], + "seoOptimization": [ + "Use generateMetadata for dynamic meta tags", + "Implement proper Open Graph and Twitter Card tags", + "Use structured data (JSON-LD) where appropriate", + "Implement proper canonical URLs", + "Use Next.js Image component with alt text", + "Implement proper heading hierarchy", + "Use semantic HTML elements", + "Generate sitemap.xml and robots.txt", + "Implement proper internal linking", + "Optimize Core Web Vitals" + ], + "performanceOptimizations": [ + "Use Next.js Image component with proper sizing", + "Implement code splitting with dynamic imports", + "Use React.lazy and Suspense for component lazy loading", + "Optimize fonts with next/font", + "Use streaming with loading.tsx files", + "Implement proper caching strategies", + "Use ISR (Incremental Static Regeneration) when appropriate", + "Optimize bundle size with proper imports", + "Use web workers for heavy computations", + "Implement proper database query optimization" + ] +} \ No newline at end of file diff --git a/profiles/tech-stacks/python-fastapi.json b/profiles/tech-stacks/python-fastapi.json new file mode 100644 index 0000000..c3c0fd5 --- /dev/null +++ b/profiles/tech-stacks/python-fastapi.json @@ -0,0 +1,168 @@ +{ + "name": "Python FastAPI", + "description": "FastAPI with SQLAlchemy, Pydantic, and modern Python development practices", + "filePatterns": ["*.py"], + "excludePatterns": ["*_test.py", "*test*.py", "__pycache__/*"], + "techStack": { + "framework": "FastAPI", + "language": "Python 3.9+", + "database": "SQLAlchemy + PostgreSQL", + "validation": "Pydantic", + "testing": "Pytest + httpx", + "documentation": "OpenAPI/Swagger (auto-generated)", + "async": "asyncio + asyncpg", + "serialization": "Pydantic models" + }, + "conventions": { + "naming": { + "variables": "snake_case", + "functions": "snake_case", + "classes": "PascalCase", + "constants": "UPPER_SNAKE_CASE", + "modules": "lowercase_with_underscores", + "packages": "lowercase" + }, + "fileStructure": { + "routers": "app/routers/{feature}.py", + "models": "app/models/{feature}.py", + "schemas": "app/schemas/{feature}.py", + "services": "app/services/{feature}.py", + "database": "app/database.py", + "tests": "tests/test_{feature}.py" + }, + "imports": { + "style": "Absolute imports from project root", + "grouping": "Standard library, third-party, local", + "sorting": "Alphabetical within groups" + } + }, + "qualityChecks": { + "lint": { + "command": "flake8 .", + "config": "PEP 8 compliance", + "autoFix": false + }, + "format": { + "command": "black .", + "config": "88 character line limit", + "autoFix": true + }, + "typeCheck": { + "command": "mypy .", + "config": "Strict type checking", + "autoFix": false + }, + "build": { + "command": "python -m compileall .", + "checkSyntax": true, + "failOnError": true + }, + "test": { + "unit": "pytest tests/", + "coverage": "pytest --cov=app tests/", + "minimumCoverage": 80 + } + }, + "codePatterns": { + "router": { + "structure": "Use APIRouter with proper prefixes and tags", + "endpoints": "Async functions with proper HTTP methods", + "dependencies": "Use Depends() for dependency injection", + "responses": "Type-annotated response models", + "errors": "Use HTTPException for error handling" + }, + "model": { + "sqlalchemy": "Use SQLAlchemy declarative base", + "relationships": "Properly define foreign keys and relationships", + "validation": "Include proper field constraints", + "timestamps": "Include created_at, updated_at fields" + }, + "schema": { + "pydantic": "Use Pydantic BaseModel for request/response schemas", + "validation": "Include proper field validation", + "serialization": "Configure proper serialization options", + "inheritance": "Use inheritance for variations (Create, Update, Response)" + }, + "service": { + "async": "Use async/await for database operations", + "transactions": "Implement proper transaction handling", + "error_handling": "Comprehensive error handling with custom exceptions", + "logging": "Structured logging for debugging and monitoring" + }, + "testing": { + "fixtures": "Use pytest fixtures for test setup", + "client": "Use TestClient for endpoint testing", + "database": "Use separate test database", + "mocking": "Mock external dependencies and services" + } + }, + "context7Libraries": [ + "fastapi", + "sqlalchemy", + "pydantic", + "pytest", + "httpx", + "asyncpg", + "uvicorn", + "alembic" + ], + "commonImports": { + "router": [ + "from fastapi import APIRouter, Depends, HTTPException, status", + "from sqlalchemy.orm import Session", + "from app.database import get_db" + ], + "model": [ + "from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Boolean", + "from sqlalchemy.ext.declarative import declarative_base", + "from sqlalchemy.orm import relationship", + "from datetime import datetime" + ], + "schema": [ + "from pydantic import BaseModel, EmailStr, validator", + "from typing import Optional, List", + "from datetime import datetime" + ], + "service": [ + "from sqlalchemy.orm import Session", + "from sqlalchemy.exc import IntegrityError", + "from fastapi import HTTPException, status" + ] + }, + "bestPractices": [ + "Use async/await for I/O operations", + "Implement proper dependency injection with Depends()", + "Use Pydantic models for request/response validation", + "Follow PEP 8 style guidelines", + "Use type hints for all functions and variables", + "Implement proper error handling with HTTP status codes", + "Use SQLAlchemy for database operations with proper relationships", + "Write comprehensive tests with pytest", + "Use environment variables for configuration", + "Implement proper logging for debugging and monitoring" + ], + "securityConsiderations": [ + "Validate and sanitize all input data using Pydantic", + "Use proper authentication and authorization mechanisms", + "Hash passwords using secure algorithms (bcrypt)", + "Implement rate limiting to prevent abuse", + "Use HTTPS in production environments", + "Validate JWT tokens properly", + "Use parameterized queries to prevent SQL injection", + "Implement proper CORS configuration", + "Log security-relevant events for auditing", + "Use environment variables for sensitive configuration" + ], + "asyncPatterns": [ + "Use async def for route handlers that perform I/O", + "Use asyncio.gather() for concurrent operations", + "Implement proper connection pooling for database", + "Use async context managers for resource management", + "Handle exceptions properly in async functions", + "Use asyncio.create_task() for background tasks", + "Implement proper shutdown handling for async resources", + "Use async generators for streaming responses", + "Avoid blocking operations in async functions", + "Use proper async testing patterns with pytest-asyncio" + ] +} \ No newline at end of file diff --git a/profiles/tech-stacks/react-frontend.json b/profiles/tech-stacks/react-frontend.json new file mode 100644 index 0000000..6374fc7 --- /dev/null +++ b/profiles/tech-stacks/react-frontend.json @@ -0,0 +1,161 @@ +{ + "name": "React Frontend", + "description": "React 18+ with TypeScript, Tailwind CSS, and modern development practices", + "filePatterns": ["*.tsx", "*.ts", "*.jsx", "*.js"], + "excludePatterns": ["*.test.tsx", "*.test.ts", "*.spec.tsx", "*.spec.ts", "*.d.ts"], + "techStack": { + "framework": "React 18+", + "language": "TypeScript", + "styling": "Tailwind CSS", + "stateManagement": "React Query + Context API", + "routing": "React Router", + "testing": "React Testing Library + Jest", + "bundler": "Create React App / Vite", + "icons": "Heroicons + Lucide React", + "charts": "Chart.js + react-chartjs-2" + }, + "conventions": { + "naming": { + "components": "PascalCase (UserProfile.tsx)", + "hooks": "camelCase with use prefix (useAuth.ts)", + "utilities": "camelCase (formatDate.ts)", + "constants": "UPPER_SNAKE_CASE", + "types": "PascalCase with T prefix", + "interfaces": "PascalCase with I prefix" + }, + "fileStructure": { + "components": "src/components/{feature}/{ComponentName}.tsx", + "hooks": "src/hooks/use{HookName}.ts", + "services": "src/services/{feature}.service.ts", + "types": "src/types/{feature}.types.ts", + "contexts": "src/contexts/{Feature}Context.tsx", + "pages": "src/pages/{PageName}.tsx", + "tests": "src/components/{feature}/__tests__/{ComponentName}.test.tsx" + }, + "imports": { + "style": "Absolute imports with @ prefix when available", + "grouping": "React, third-party, internal, relative", + "sorting": "Alphabetical within groups" + } + }, + "qualityChecks": { + "lint": { + "command": "npx eslint --fix", + "config": "ESLint React + TypeScript + a11y", + "autoFix": true + }, + "format": { + "command": "npx prettier --write", + "config": "80 character line limit, single quotes", + "autoFix": true + }, + "build": { + "command": "npm run build", + "checkTypes": true, + "failOnError": true + }, + "test": { + "unit": "npm test", + "coverage": "npm run test:coverage", + "minimumCoverage": 70 + } + }, + "codePatterns": { + "component": { + "structure": "Functional components with TypeScript interfaces", + "props": "Define interface for component props", + "state": "Use useState, useReducer for local state", + "effects": "Use useEffect with proper cleanup", + "memo": "Use React.memo for performance optimization when needed", + "forwardRef": "Use forwardRef for components that need ref access" + }, + "hooks": { + "custom": "Extract reusable logic into custom hooks", + "naming": "Always start with 'use' prefix", + "dependencies": "Properly declare useEffect dependencies", + "cleanup": "Return cleanup functions from useEffect when needed" + }, + "styling": { + "tailwind": "Use Tailwind utility classes", + "responsive": "Mobile-first responsive design", + "darkMode": "Support dark mode with Tailwind dark: prefix", + "accessibility": "Include proper ARIA labels and keyboard navigation" + }, + "stateManagement": { + "local": "useState for component-local state", + "global": "Context API for app-wide state", + "server": "React Query for server state management", + "forms": "Controlled components with validation" + }, + "testing": { + "render": "Use @testing-library/react render method", + "queries": "Use semantic queries (getByRole, getByLabelText)", + "userEvents": "Use @testing-library/user-event for interactions", + "mocking": "Mock external dependencies and API calls", + "accessibility": "Test with screen reader and keyboard navigation" + } + }, + "context7Libraries": [ + "react", + "react-dom", + "react-router-dom", + "@tanstack/react-query", + "tailwindcss", + "@testing-library/react", + "@testing-library/user-event", + "@heroicons/react", + "lucide-react", + "chart.js" + ], + "commonImports": { + "component": [ + "import React, { useState, useEffect, useCallback, useMemo } from 'react';", + "import { useNavigate, useParams } from 'react-router-dom';" + ], + "hook": [ + "import { useState, useEffect, useCallback, useContext } from 'react';", + "import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';" + ], + "test": [ + "import { render, screen, fireEvent, waitFor } from '@testing-library/react';", + "import userEvent from '@testing-library/user-event';", + "import { BrowserRouter } from 'react-router-dom';" + ] + }, + "bestPractices": [ + "Use functional components with hooks instead of class components", + "Extract custom hooks for reusable stateful logic", + "Use React.memo for performance optimization when appropriate", + "Implement proper error boundaries for error handling", + "Use React Query for server state management", + "Follow accessibility guidelines (WCAG 2.1)", + "Implement responsive design with mobile-first approach", + "Use TypeScript for type safety", + "Write comprehensive tests for components and hooks", + "Optimize bundle size with code splitting and lazy loading" + ], + "accessibilityRequirements": [ + "Provide meaningful alt text for images", + "Use semantic HTML elements", + "Ensure proper heading hierarchy (h1, h2, h3)", + "Include ARIA labels for interactive elements", + "Support keyboard navigation for all interactive elements", + "Maintain sufficient color contrast ratios", + "Provide focus indicators for keyboard users", + "Use role attributes when semantic HTML is insufficient", + "Test with screen readers", + "Ensure form fields have associated labels" + ], + "performanceOptimizations": [ + "Use React.lazy for code splitting", + "Implement virtualization for long lists", + "Use useMemo and useCallback to prevent unnecessary re-renders", + "Optimize images with proper formats and sizes", + "Use React.memo for components that receive stable props", + "Implement proper error boundaries", + "Use React Query for efficient data fetching and caching", + "Minimize bundle size by importing only needed modules", + "Use web workers for heavy computations", + "Implement proper loading states and skeleton screens" + ] +} \ No newline at end of file diff --git a/profiles/workflows/api-development.json b/profiles/workflows/api-development.json new file mode 100644 index 0000000..201f0e5 --- /dev/null +++ b/profiles/workflows/api-development.json @@ -0,0 +1,182 @@ +{ + "name": "API Development Workflow", + "description": "Standardized workflow for REST/GraphQL API endpoint development", + "workflowType": "api-development", + "applicablePatterns": ["REST", "GraphQL", "WebSocket"], + "phases": { + "planning": { + "description": "API design and specification phase", + "activities": [ + "Define API contract and OpenAPI specification", + "Design request/response schemas", + "Plan error handling and status codes", + "Consider rate limiting and pagination", + "Document authentication and authorization requirements" + ] + }, + "implementation": { + "description": "Core API implementation phase", + "activities": [ + "Create controller/resolver with proper routing", + "Implement service layer with business logic", + "Add input validation and sanitization", + "Implement proper error handling", + "Add authentication and authorization guards" + ] + }, + "testing": { + "description": "Comprehensive API testing phase", + "activities": [ + "Write unit tests for service layer", + "Create integration tests for endpoints", + "Test error scenarios and edge cases", + "Validate API documentation accuracy", + "Perform security testing" + ] + }, + "documentation": { + "description": "API documentation and examples", + "activities": [ + "Generate/update OpenAPI documentation", + "Create usage examples and tutorials", + "Document rate limits and quotas", + "Add error code documentation", + "Update API versioning information" + ] + } + }, + "implementationPatterns": { + "controller": { + "structure": "Thin controller with business logic in services", + "validation": "Use DTOs for input validation", + "responses": "Standardized response format", + "errors": "Consistent error handling middleware", + "documentation": "Comprehensive API documentation decorators" + }, + "service": { + "business_logic": "Core business logic implementation", + "data_access": "Repository pattern for data operations", + "transactions": "Database transaction management", + "caching": "Implement caching where appropriate", + "external_apis": "Handle external API integrations" + }, + "validation": { + "input": "Validate all input parameters and body data", + "sanitization": "Sanitize inputs to prevent injection attacks", + "authorization": "Verify user permissions for operations", + "rate_limiting": "Implement appropriate rate limiting", + "idempotency": "Support idempotent operations where needed" + }, + "responses": { + "success": "Consistent success response format", + "errors": "Standardized error response structure", + "pagination": "Implement cursor or offset pagination", + "filtering": "Support query filtering and sorting", + "versioning": "Handle API versioning appropriately" + } + }, + "qualityGates": { + "pre_implementation": [ + "API specification reviewed and approved", + "Data models and schemas defined", + "Authentication requirements clarified", + "Rate limiting strategy determined", + "Error handling approach documented" + ], + "implementation": [ + "Code follows established patterns and conventions", + "Input validation implemented for all parameters", + "Proper error handling and logging added", + "Authentication and authorization enforced", + "Business logic separated from controller logic" + ], + "testing": [ + "Unit tests cover all service methods", + "Integration tests validate API contracts", + "Error scenarios properly tested", + "Performance tests pass acceptance criteria", + "Security tests identify no critical vulnerabilities" + ], + "deployment": [ + "API documentation is accurate and complete", + "Monitoring and alerting configured", + "Database migrations applied successfully", + "Configuration validated in target environment", + "Rollback procedures documented and tested" + ] + }, + "testingStrategy": { + "unit_tests": { + "scope": "Individual service methods and business logic", + "mocking": "Mock external dependencies and database", + "coverage": "Minimum 80% code coverage", + "focus": "Business logic and edge cases" + }, + "integration_tests": { + "scope": "Full API endpoint testing with real database", + "scenarios": "Happy path and error scenarios", + "data": "Use test fixtures and factories", + "cleanup": "Clean up test data after each test" + }, + "contract_tests": { + "scope": "API contract validation", + "tools": "OpenAPI validation and contract testing", + "versioning": "Backward compatibility testing", + "documentation": "Ensure examples work correctly" + }, + "performance_tests": { + "scope": "Load and stress testing", + "metrics": "Response time, throughput, resource usage", + "scenarios": "Normal and peak load conditions", + "bottlenecks": "Identify and address performance issues" + }, + "security_tests": { + "scope": "Authentication, authorization, and input validation", + "scenarios": "SQL injection, XSS, authentication bypass", + "tools": "Automated security scanning", + "compliance": "Ensure regulatory compliance requirements" + } + }, + "codeTemplates": { + "restController": { + "framework": "universal", + "template": "// REST Controller Template\n@Controller('/api/v1/users')\n@ApiTags('users')\nexport class UsersController {\n constructor(private usersService: UsersService) {}\n\n @Get()\n @ApiOperation({ summary: 'Get all users' })\n @ApiResponse({ status: 200, description: 'Users retrieved successfully' })\n async getUsers(@Query() query: GetUsersDto): Promise> {\n const users = await this.usersService.getUsers(query);\n return { data: users, message: 'Users retrieved successfully' };\n }\n\n @Post()\n @ApiOperation({ summary: 'Create new user' })\n @ApiResponse({ status: 201, description: 'User created successfully' })\n async createUser(@Body() createUserDto: CreateUserDto): Promise> {\n const user = await this.usersService.createUser(createUserDto);\n return { data: user, message: 'User created successfully' };\n }\n}" + }, + "serviceLayer": { + "framework": "universal", + "template": "// Service Layer Template\n@Injectable()\nexport class UsersService {\n constructor(private usersRepository: UsersRepository) {}\n\n async getUsers(query: GetUsersDto): Promise {\n try {\n const users = await this.usersRepository.findWithFilters(query);\n return users;\n } catch (error) {\n throw new ServiceException('Failed to retrieve users', error);\n }\n }\n\n async createUser(createUserDto: CreateUserDto): Promise {\n try {\n const existingUser = await this.usersRepository.findByEmail(createUserDto.email);\n if (existingUser) {\n throw new ConflictException('User with this email already exists');\n }\n \n const user = await this.usersRepository.create(createUserDto);\n return user;\n } catch (error) {\n throw new ServiceException('Failed to create user', error);\n }\n }\n}" + }, + "integrationTest": { + "framework": "universal", + "template": "// Integration Test Template\ndescribe('Users API', () => {\n let app: TestingModule;\n let httpServer: any;\n\n beforeAll(async () => {\n app = await Test.createTestingModule({\n imports: [AppModule],\n }).compile();\n \n httpServer = app.createNestApplication();\n await httpServer.init();\n });\n\n describe('GET /api/v1/users', () => {\n it('should return users list', async () => {\n const response = await request(httpServer)\n .get('/api/v1/users')\n .expect(200);\n\n expect(response.body.data).toBeInstanceOf(Array);\n expect(response.body.message).toBe('Users retrieved successfully');\n });\n\n it('should handle pagination', async () => {\n const response = await request(httpServer)\n .get('/api/v1/users?page=1&limit=10')\n .expect(200);\n\n expect(response.body.data.length).toBeLessThanOrEqual(10);\n });\n });\n\n describe('POST /api/v1/users', () => {\n it('should create new user', async () => {\n const newUser = {\n name: 'John Doe',\n email: 'john@example.com'\n };\n\n const response = await request(httpServer)\n .post('/api/v1/users')\n .send(newUser)\n .expect(201);\n\n expect(response.body.data.name).toBe(newUser.name);\n expect(response.body.data.email).toBe(newUser.email);\n });\n\n it('should validate required fields', async () => {\n const response = await request(httpServer)\n .post('/api/v1/users')\n .send({})\n .expect(400);\n\n expect(response.body.errors).toBeDefined();\n });\n });\n});" + } + }, + "bestPractices": [ + "Use consistent REST conventions for endpoint naming", + "Implement proper HTTP status codes for different scenarios", + "Add comprehensive input validation and sanitization", + "Use DTOs for request/response data structures", + "Implement proper error handling with meaningful messages", + "Add rate limiting to prevent API abuse", + "Use pagination for endpoints returning large datasets", + "Implement API versioning strategy from the start", + "Add comprehensive logging for debugging and monitoring", + "Use dependency injection for better testability", + "Implement proper authentication and authorization", + "Add API documentation with examples and use cases" + ], + "commonPitfalls": [ + "Putting business logic directly in controllers", + "Not validating input parameters properly", + "Inconsistent error handling and response formats", + "Missing or outdated API documentation", + "Not implementing proper pagination", + "Ignoring rate limiting and abuse prevention", + "Poor error messages that don't help clients", + "Not versioning APIs properly", + "Missing or inadequate logging", + "Not testing error scenarios thoroughly", + "Exposing sensitive information in error responses", + "Not handling database connection failures gracefully" + ] +} \ No newline at end of file diff --git a/profiles/workflows/frontend-component.json b/profiles/workflows/frontend-component.json new file mode 100644 index 0000000..0b7a53c --- /dev/null +++ b/profiles/workflows/frontend-component.json @@ -0,0 +1,201 @@ +{ + "name": "Frontend Component Development", + "description": "Standardized workflow for React/Vue component development with accessibility and testing", + "workflowType": "frontend-component", + "applicablePatterns": ["React", "Vue", "Angular", "Web Components"], + "phases": { + "design": { + "description": "Component design and specification phase", + "activities": [ + "Define component API and props interface", + "Create component design system documentation", + "Plan responsive behavior and breakpoints", + "Design accessibility features and ARIA labels", + "Consider component composition and reusability" + ] + }, + "implementation": { + "description": "Core component implementation phase", + "activities": [ + "Create component with TypeScript interfaces", + "Implement responsive styling with CSS/Tailwind", + "Add accessibility features (ARIA, keyboard navigation)", + "Implement component state management", + "Add proper error boundaries and loading states" + ] + }, + "testing": { + "description": "Comprehensive component testing phase", + "activities": [ + "Write unit tests for component logic", + "Create integration tests with user interactions", + "Test accessibility with screen readers", + "Validate responsive behavior across devices", + "Test component with different prop combinations" + ] + }, + "documentation": { + "description": "Component documentation and examples", + "activities": [ + "Create Storybook stories for all variants", + "Document component API and usage examples", + "Add accessibility guidelines and best practices", + "Create interactive documentation", + "Document component performance characteristics" + ] + } + }, + "implementationPatterns": { + "structure": { + "functional": "Use functional components with hooks", + "typescript": "Define proper TypeScript interfaces for props", + "composition": "Design for component composition and reusability", + "separation": "Separate logic, presentation, and styling concerns", + "naming": "Use descriptive and consistent naming conventions" + }, + "styling": { + "responsive": "Mobile-first responsive design approach", + "design_tokens": "Use design tokens for consistency", + "css_modules": "Scoped styling to prevent conflicts", + "accessibility": "Ensure sufficient color contrast and focus indicators", + "dark_mode": "Support light and dark theme variations" + }, + "accessibility": { + "semantic_html": "Use semantic HTML elements when possible", + "aria_labels": "Add appropriate ARIA labels and descriptions", + "keyboard_nav": "Implement full keyboard navigation support", + "screen_readers": "Ensure screen reader compatibility", + "focus_management": "Proper focus management and indicators" + }, + "state_management": { + "local_state": "Use useState for component-local state", + "side_effects": "Use useEffect with proper cleanup", + "performance": "Use useMemo and useCallback for optimization", + "context": "Use React Context for component tree state", + "forms": "Controlled components with proper validation" + }, + "error_handling": { + "boundaries": "Implement error boundaries for error containment", + "validation": "Input validation with user-friendly messages", + "loading_states": "Proper loading and skeleton states", + "fallbacks": "Graceful degradation for component failures", + "user_feedback": "Clear feedback for user actions" + } + }, + "qualityGates": { + "design": [ + "Component API designed with reusability in mind", + "Accessibility requirements identified and documented", + "Responsive behavior planned for all breakpoints", + "Design tokens and styling approach determined", + "Component composition strategy defined" + ], + "implementation": [ + "TypeScript interfaces defined for all props", + "Component implements planned accessibility features", + "Responsive behavior works across all target devices", + "Component follows established coding patterns", + "Error handling and edge cases addressed" + ], + "testing": [ + "Unit tests cover all component logic and edge cases", + "Accessibility tests pass with screen reader testing", + "Integration tests validate user interaction flows", + "Visual regression tests prevent styling issues", + "Performance tests meet established benchmarks" + ], + "documentation": [ + "Storybook stories demonstrate all component variants", + "API documentation is complete and accurate", + "Usage examples and best practices documented", + "Accessibility guidelines provided", + "Performance characteristics documented" + ] + }, + "testingStrategy": { + "unit_tests": { + "scope": "Component logic, prop handling, and state changes", + "tools": "React Testing Library, Jest", + "coverage": "Minimum 85% code coverage", + "focus": "User interactions and business logic" + }, + "accessibility_tests": { + "scope": "ARIA labels, keyboard navigation, screen reader compatibility", + "tools": "axe-core, @testing-library/jest-dom", + "manual": "Manual testing with actual screen readers", + "standards": "WCAG 2.1 AA compliance" + }, + "visual_tests": { + "scope": "Component appearance across different states", + "tools": "Chromatic, Percy, or similar visual testing", + "devices": "Test across multiple device sizes", + "themes": "Test light/dark theme variations" + }, + "integration_tests": { + "scope": "Component behavior within larger application context", + "user_flows": "End-to-end user interaction scenarios", + "data_flow": "Test with real or realistic data", + "performance": "Component performance under load" + }, + "responsive_tests": { + "scope": "Component behavior across different screen sizes", + "breakpoints": "Test all defined responsive breakpoints", + "orientation": "Portrait and landscape orientations", + "devices": "Physical device testing when possible" + } + }, + "codeTemplates": { + "reactComponent": { + "framework": "React", + "template": "import React, { useState, useEffect, useCallback } from 'react';\nimport { cn } from '@/lib/utils';\n\ninterface ComponentNameProps {\n /** Primary content for the component */\n children?: React.ReactNode;\n /** Additional CSS class names */\n className?: string;\n /** Component variant */\n variant?: 'primary' | 'secondary' | 'outline';\n /** Component size */\n size?: 'sm' | 'md' | 'lg';\n /** Disabled state */\n disabled?: boolean;\n /** Click handler */\n onClick?: () => void;\n}\n\n/**\n * ComponentName - Brief description of what this component does\n * \n * @example\n * \n * Content goes here\n * \n */\nexport const ComponentName: React.FC = ({\n children,\n className,\n variant = 'primary',\n size = 'md',\n disabled = false,\n onClick,\n ...props\n}) => {\n const [isActive, setIsActive] = useState(false);\n\n const handleClick = useCallback(() => {\n if (!disabled && onClick) {\n onClick();\n }\n }, [disabled, onClick]);\n\n const handleKeyDown = useCallback((event: React.KeyboardEvent) => {\n if (event.key === 'Enter' || event.key === ' ') {\n event.preventDefault();\n handleClick();\n }\n }, [handleClick]);\n\n return (\n \n {children}\n \n );\n};\n\nComponentName.displayName = 'ComponentName';" + }, + "componentTest": { + "framework": "React Testing Library", + "template": "import { render, screen, fireEvent, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport { axe, toHaveNoViolations } from 'jest-axe';\nimport { ComponentName } from './ComponentName';\n\n// Extend Jest matchers\nexpect.extend(toHaveNoViolations);\n\ndescribe('ComponentName', () => {\n const user = userEvent.setup();\n\n it('renders with default props', () => {\n render(Test Content);\n \n const button = screen.getByRole('button', { name: 'Test Content' });\n expect(button).toBeInTheDocument();\n expect(button).toHaveClass('bg-primary'); // default variant\n });\n\n it('handles click events', async () => {\n const handleClick = jest.fn();\n render(\n \n Click me\n \n );\n\n const button = screen.getByRole('button', { name: 'Click me' });\n await user.click(button);\n \n expect(handleClick).toHaveBeenCalledTimes(1);\n });\n\n it('supports keyboard navigation', async () => {\n const handleClick = jest.fn();\n render(\n \n Press Enter\n \n );\n\n const button = screen.getByRole('button', { name: 'Press Enter' });\n button.focus();\n \n await user.keyboard('{Enter}');\n expect(handleClick).toHaveBeenCalledTimes(1);\n \n await user.keyboard(' ');\n expect(handleClick).toHaveBeenCalledTimes(2);\n });\n\n it('handles disabled state correctly', async () => {\n const handleClick = jest.fn();\n render(\n \n Disabled\n \n );\n\n const button = screen.getByRole('button', { name: 'Disabled' });\n expect(button).toBeDisabled();\n expect(button).toHaveAttribute('aria-disabled', 'true');\n \n await user.click(button);\n expect(handleClick).not.toHaveBeenCalled();\n });\n\n it('applies correct variant styles', () => {\n const { rerender } = render(\n \n Secondary\n \n );\n \n let button = screen.getByRole('button');\n expect(button).toHaveClass('bg-secondary');\n \n rerender(\n \n Outline\n \n );\n \n button = screen.getByRole('button');\n expect(button).toHaveClass('border');\n });\n\n it('has no accessibility violations', async () => {\n const { container } = render(\n \n Accessible Button\n \n );\n \n const results = await axe(container);\n expect(results).toHaveNoViolations();\n });\n\n it('supports custom className', () => {\n render(\n \n Custom\n \n );\n \n const button = screen.getByRole('button');\n expect(button).toHaveClass('custom-class');\n });\n});" + }, + "storybookStory": { + "framework": "Storybook", + "template": "import type { Meta, StoryObj } from '@storybook/react';\nimport { ComponentName } from './ComponentName';\n\nconst meta: Meta = {\n title: 'Components/ComponentName',\n component: ComponentName,\n parameters: {\n layout: 'centered',\n docs: {\n description: {\n component: 'A versatile button component with multiple variants and sizes.',\n },\n },\n },\n argTypes: {\n variant: {\n control: 'select',\n options: ['primary', 'secondary', 'outline'],\n description: 'The visual variant of the button',\n },\n size: {\n control: 'select', \n options: ['sm', 'md', 'lg'],\n description: 'The size of the button',\n },\n disabled: {\n control: 'boolean',\n description: 'Whether the button is disabled',\n },\n onClick: {\n action: 'clicked',\n description: 'Function called when button is clicked',\n },\n },\n};\n\nexport default meta;\ntype Story = StoryObj;\n\n// Default story\nexport const Default: Story = {\n args: {\n children: 'Button',\n variant: 'primary',\n size: 'md',\n disabled: false,\n },\n};\n\n// Variants showcase\nexport const Variants: Story = {\n render: () => (\n
\n Primary\n Secondary\n Outline\n
\n ),\n};\n\n// Sizes showcase\nexport const Sizes: Story = {\n render: () => (\n
\n Small\n Medium\n Large\n
\n ),\n};\n\n// Disabled state\nexport const Disabled: Story = {\n args: {\n children: 'Disabled Button',\n disabled: true,\n },\n};\n\n// Interactive example\nexport const Interactive: Story = {\n render: () => {\n const [count, setCount] = React.useState(0);\n return (\n
\n

Count: {count}

\n setCount(count + 1)}>\n Increment\n \n
\n );\n },\n};" + } + }, + "accessibilityRequirements": [ + "Use semantic HTML elements when possible (button, input, etc.)", + "Provide meaningful alt text for images", + "Ensure sufficient color contrast (4.5:1 for normal text)", + "Support keyboard navigation for all interactive elements", + "Use ARIA labels and descriptions where needed", + "Implement proper focus management and indicators", + "Support screen readers with appropriate ARIA attributes", + "Test with actual assistive technologies", + "Provide skip links for navigation", + "Use proper heading hierarchy", + "Ensure form labels are properly associated", + "Implement error states with clear messaging" + ], + "performanceOptimizations": [ + "Use React.memo for components that receive stable props", + "Implement useMemo for expensive calculations", + "Use useCallback for event handlers passed to child components", + "Optimize images with proper formats and lazy loading", + "Implement virtualization for large lists", + "Use code splitting for large components", + "Minimize bundle size by importing only needed modules", + "Use CSS-in-JS efficiently to avoid style recalculations", + "Implement proper error boundaries to prevent crashes", + "Monitor component re-render frequency and optimize" + ], + "bestPractices": [ + "Design components for reusability and composition", + "Use TypeScript for better development experience and catch errors", + "Follow accessibility guidelines from the start", + "Write comprehensive tests including accessibility tests", + "Document components with clear examples and usage", + "Use consistent naming conventions across components", + "Implement proper error handling and loading states", + "Consider mobile-first responsive design", + "Use design tokens for consistent styling", + "Optimize for performance without premature optimization", + "Follow the principle of least privilege for component APIs", + "Use proper semantic HTML for better accessibility" + ] +} \ No newline at end of file diff --git a/profiles/workflows/testing-automation.json b/profiles/workflows/testing-automation.json new file mode 100644 index 0000000..9aec7b2 --- /dev/null +++ b/profiles/workflows/testing-automation.json @@ -0,0 +1,196 @@ +{ + "name": "Testing Automation Workflow", + "description": "Comprehensive testing workflow for unit, integration, and end-to-end testing", + "workflowType": "testing-automation", + "applicablePatterns": ["Unit Testing", "Integration Testing", "E2E Testing", "Performance Testing"], + "phases": { + "planning": { + "description": "Test planning and strategy phase", + "activities": [ + "Define testing strategy and coverage goals", + "Identify critical paths and edge cases", + "Plan test data and fixtures", + "Define testing environments and CI/CD integration", + "Establish quality gates and acceptance criteria" + ] + }, + "implementation": { + "description": "Test implementation phase", + "activities": [ + "Write unit tests for individual functions and components", + "Create integration tests for API endpoints and workflows", + "Implement end-to-end tests for user journeys", + "Set up test data factories and fixtures", + "Configure test environments and mocking" + ] + }, + "automation": { + "description": "Test automation and CI/CD integration", + "activities": [ + "Integrate tests into CI/CD pipeline", + "Set up parallel test execution", + "Configure test reporting and notifications", + "Implement test result analysis and trending", + "Set up automated test maintenance" + ] + }, + "monitoring": { + "description": "Test monitoring and maintenance phase", + "activities": [ + "Monitor test execution metrics and trends", + "Maintain test suites and remove flaky tests", + "Update tests for new features and changes", + "Analyze test coverage and identify gaps", + "Optimize test execution performance" + ] + } + }, + "testingLevels": { + "unit": { + "scope": "Individual functions, methods, and components in isolation", + "goals": "Fast feedback, high coverage, isolated testing", + "tools": "Jest, Vitest, Mocha, Jasmine", + "coverage": "80%+ for business logic", + "characteristics": "Fast (<1s), Isolated, Repeatable, Self-validating" + }, + "integration": { + "scope": "Interaction between multiple components or services", + "goals": "Verify component integration and data flow", + "tools": "Supertest, TestContainers, Testing Library", + "coverage": "Critical integration points", + "characteristics": "Moderate speed, Real dependencies, Contract validation" + }, + "contract": { + "scope": "API contracts between services", + "goals": "Ensure API compatibility and prevent breaking changes", + "tools": "Pact, OpenAPI validators, Postman", + "coverage": "All public APIs", + "characteristics": "Consumer-driven, Version compatibility, Schema validation" + }, + "e2e": { + "scope": "Complete user workflows from start to finish", + "goals": "Validate critical user journeys work end-to-end", + "tools": "Playwright, Cypress, Selenium", + "coverage": "Critical business flows", + "characteristics": "Slow, Real browser, Full system testing" + }, + "performance": { + "scope": "System performance under various load conditions", + "goals": "Ensure performance requirements are met", + "tools": "Artillery, K6, JMeter, Lighthouse", + "coverage": "Critical performance paths", + "characteristics": "Load testing, Stress testing, Performance monitoring" + } + }, + "testingPatterns": { + "aaa": { + "name": "Arrange, Act, Assert", + "description": "Structure tests with clear setup, execution, and verification", + "example": "// Arrange\nconst user = createTestUser();\n// Act\nconst result = await service.createUser(user);\n// Assert\nexpect(result.id).toBeDefined();" + }, + "given_when_then": { + "name": "Given, When, Then (BDD)", + "description": "Behavior-driven testing with clear preconditions, actions, and outcomes", + "example": "describe('User registration', () => {\n it('should create user when valid data provided', async () => {\n // Given\n const userData = validUserData();\n // When\n const user = await userService.register(userData);\n // Then\n expect(user).toMatchObject(userData);\n });\n});" + }, + "test_doubles": { + "name": "Test Doubles (Mocks, Stubs, Spies)", + "description": "Use test doubles to isolate system under test", + "types": { + "mock": "Verify interactions with dependencies", + "stub": "Provide controlled responses", + "spy": "Monitor calls to real objects", + "fake": "Working implementation with shortcuts" + } + }, + "data_driven": { + "name": "Data-Driven Testing", + "description": "Test same logic with multiple input datasets", + "example": "test.each([\n ['valid@email.com', true],\n ['invalid-email', false],\n ['', false]\n])('validates email %s as %s', (email, expected) => {\n expect(isValidEmail(email)).toBe(expected);\n});" + } + }, + "qualityGates": { + "coverage": { + "unit_tests": "80% minimum for business logic", + "integration_tests": "All critical integration points covered", + "e2e_tests": "All critical user journeys covered", + "mutation_testing": "70% mutation score for critical components" + }, + "performance": { + "test_execution": "Unit tests <5 minutes, Integration <15 minutes", + "feedback_time": "Developer feedback within 10 minutes", + "parallel_execution": "Tests run in parallel where possible", + "flaky_tests": "<1% flaky test rate" + }, + "quality": { + "test_reliability": "95% pass rate on consecutive runs", + "test_maintainability": "Tests updated with code changes", + "test_readability": "Tests serve as documentation", + "test_isolation": "Tests don't depend on each other" + } + }, + "codeTemplates": { + "unitTest": { + "framework": "Jest/Vitest", + "template": "import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';\nimport { UserService } from './UserService';\nimport { MockUserRepository } from './__mocks__/UserRepository';\n\ndescribe('UserService', () => {\n let userService: UserService;\n let mockRepository: MockUserRepository;\n\n beforeEach(() => {\n mockRepository = new MockUserRepository();\n userService = new UserService(mockRepository);\n });\n\n afterEach(() => {\n vi.clearAllMocks();\n });\n\n describe('createUser', () => {\n it('should create user with valid data', async () => {\n // Arrange\n const userData = {\n name: 'John Doe',\n email: 'john@example.com',\n password: 'securePassword123'\n };\n const expectedUser = { id: '123', ...userData };\n mockRepository.create.mockResolvedValue(expectedUser);\n\n // Act\n const result = await userService.createUser(userData);\n\n // Assert\n expect(result).toEqual(expectedUser);\n expect(mockRepository.create).toHaveBeenCalledWith(userData);\n expect(mockRepository.create).toHaveBeenCalledTimes(1);\n });\n\n it('should throw error when email already exists', async () => {\n // Arrange\n const userData = {\n name: 'John Doe',\n email: 'existing@example.com',\n password: 'securePassword123'\n };\n mockRepository.findByEmail.mockResolvedValue({ id: '456', email: userData.email });\n\n // Act & Assert\n await expect(userService.createUser(userData))\n .rejects\n .toThrow('User with email already exists');\n \n expect(mockRepository.findByEmail).toHaveBeenCalledWith(userData.email);\n expect(mockRepository.create).not.toHaveBeenCalled();\n });\n\n it('should handle repository errors gracefully', async () => {\n // Arrange\n const userData = {\n name: 'John Doe',\n email: 'john@example.com',\n password: 'securePassword123'\n };\n const dbError = new Error('Database connection failed');\n mockRepository.create.mockRejectedValue(dbError);\n\n // Act & Assert\n await expect(userService.createUser(userData))\n .rejects\n .toThrow('Failed to create user');\n });\n });\n\n describe('getUserById', () => {\n it('should return user when found', async () => {\n // Arrange\n const userId = '123';\n const expectedUser = { id: userId, name: 'John Doe', email: 'john@example.com' };\n mockRepository.findById.mockResolvedValue(expectedUser);\n\n // Act\n const result = await userService.getUserById(userId);\n\n // Assert\n expect(result).toEqual(expectedUser);\n expect(mockRepository.findById).toHaveBeenCalledWith(userId);\n });\n\n it('should return null when user not found', async () => {\n // Arrange\n const userId = '999';\n mockRepository.findById.mockResolvedValue(null);\n\n // Act\n const result = await userService.getUserById(userId);\n\n // Assert\n expect(result).toBeNull();\n expect(mockRepository.findById).toHaveBeenCalledWith(userId);\n });\n });\n});" + }, + "integrationTest": { + "framework": "Supertest + Jest", + "template": "import request from 'supertest';\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { INestApplication } from '@nestjs/common';\nimport { AppModule } from '../src/app.module';\nimport { DatabaseService } from '../src/database/database.service';\nimport { createTestUser, cleanupTestData } from './fixtures/user.fixtures';\n\ndescribe('Users API Integration Tests', () => {\n let app: INestApplication;\n let databaseService: DatabaseService;\n let testUserId: string;\n\n beforeAll(async () => {\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [AppModule],\n }).compile();\n\n app = moduleFixture.createNestApplication();\n databaseService = moduleFixture.get(DatabaseService);\n \n await app.init();\n \n // Set up test data\n const testUser = await createTestUser(databaseService);\n testUserId = testUser.id;\n });\n\n afterAll(async () => {\n // Clean up test data\n await cleanupTestData(databaseService);\n await app.close();\n });\n\n describe('POST /users', () => {\n it('should create a new user', async () => {\n const newUser = {\n name: 'Jane Doe',\n email: 'jane@example.com',\n password: 'securePassword123'\n };\n\n const response = await request(app.getHttpServer())\n .post('/users')\n .send(newUser)\n .expect(201);\n\n expect(response.body).toMatchObject({\n id: expect.any(String),\n name: newUser.name,\n email: newUser.email,\n createdAt: expect.any(String)\n });\n expect(response.body.password).toBeUndefined();\n\n // Verify user was actually created in database\n const createdUser = await databaseService.user.findUnique({\n where: { id: response.body.id }\n });\n expect(createdUser).toBeTruthy();\n expect(createdUser.name).toBe(newUser.name);\n });\n\n it('should return 400 for invalid data', async () => {\n const invalidUser = {\n name: '', // Invalid: empty name\n email: 'invalid-email', // Invalid: bad email format\n password: '123' // Invalid: too short\n };\n\n const response = await request(app.getHttpServer())\n .post('/users')\n .send(invalidUser)\n .expect(400);\n\n expect(response.body.errors).toBeDefined();\n expect(response.body.errors).toContain(\n expect.objectContaining({\n field: 'email',\n message: expect.stringContaining('valid email')\n })\n );\n });\n\n it('should return 409 for duplicate email', async () => {\n const duplicateUser = {\n name: 'John Duplicate',\n email: 'existing@example.com', // Email already exists\n password: 'securePassword123'\n };\n\n await request(app.getHttpServer())\n .post('/users')\n .send(duplicateUser)\n .expect(409);\n });\n });\n\n describe('GET /users/:id', () => {\n it('should return user when found', async () => {\n const response = await request(app.getHttpServer())\n .get(`/users/${testUserId}`)\n .expect(200);\n\n expect(response.body).toMatchObject({\n id: testUserId,\n name: expect.any(String),\n email: expect.any(String),\n createdAt: expect.any(String)\n });\n expect(response.body.password).toBeUndefined();\n });\n\n it('should return 404 for non-existent user', async () => {\n const nonExistentId = '999999';\n \n await request(app.getHttpServer())\n .get(`/users/${nonExistentId}`)\n .expect(404);\n });\n\n it('should return 400 for invalid user id format', async () => {\n await request(app.getHttpServer())\n .get('/users/invalid-id')\n .expect(400);\n });\n });\n\n describe('PUT /users/:id', () => {\n it('should update user successfully', async () => {\n const updateData = {\n name: 'Updated Name',\n email: 'updated@example.com'\n };\n\n const response = await request(app.getHttpServer())\n .put(`/users/${testUserId}`)\n .send(updateData)\n .expect(200);\n\n expect(response.body).toMatchObject({\n id: testUserId,\n name: updateData.name,\n email: updateData.email,\n updatedAt: expect.any(String)\n });\n\n // Verify update in database\n const updatedUser = await databaseService.user.findUnique({\n where: { id: testUserId }\n });\n expect(updatedUser.name).toBe(updateData.name);\n expect(updatedUser.email).toBe(updateData.email);\n });\n });\n});" + }, + "e2eTest": { + "framework": "Playwright", + "template": "import { test, expect } from '@playwright/test';\nimport { LoginPage } from '../pages/LoginPage';\nimport { DashboardPage } from '../pages/DashboardPage';\nimport { UserProfilePage } from '../pages/UserProfilePage';\n\ntest.describe('User Management E2E Tests', () => {\n let loginPage: LoginPage;\n let dashboardPage: DashboardPage;\n let userProfilePage: UserProfilePage;\n\n test.beforeEach(async ({ page }) => {\n loginPage = new LoginPage(page);\n dashboardPage = new DashboardPage(page);\n userProfilePage = new UserProfilePage(page);\n \n // Navigate to application\n await page.goto('/login');\n });\n\n test('complete user registration and profile update flow', async ({ page }) => {\n // Step 1: Register new user\n await loginPage.clickSignUpLink();\n \n const newUser = {\n name: 'Test User',\n email: `test${Date.now()}@example.com`,\n password: 'SecurePassword123!'\n };\n \n await loginPage.fillRegistrationForm(newUser);\n await loginPage.submitRegistration();\n \n // Verify registration success\n await expect(page.locator('[data-testid=\"registration-success\"]'))\n .toBeVisible();\n \n // Step 2: Login with new user\n await loginPage.login(newUser.email, newUser.password);\n \n // Verify successful login and dashboard access\n await expect(dashboardPage.welcomeMessage)\n .toContainText(`Welcome, ${newUser.name}`);\n \n // Step 3: Navigate to profile settings\n await dashboardPage.clickProfileMenu();\n await dashboardPage.clickProfileSettings();\n \n // Verify profile page loaded\n await expect(userProfilePage.profileForm).toBeVisible();\n \n // Step 4: Update profile information\n const updatedInfo = {\n name: 'Updated Test User',\n bio: 'This is my updated bio',\n phone: '+1234567890'\n };\n \n await userProfilePage.updateProfile(updatedInfo);\n await userProfilePage.saveChanges();\n \n // Verify update success\n await expect(userProfilePage.successMessage)\n .toContainText('Profile updated successfully');\n \n // Step 5: Verify changes persist after page reload\n await page.reload();\n \n await expect(userProfilePage.nameField)\n .toHaveValue(updatedInfo.name);\n await expect(userProfilePage.bioField)\n .toHaveValue(updatedInfo.bio);\n await expect(userProfilePage.phoneField)\n .toHaveValue(updatedInfo.phone);\n \n // Step 6: Test profile picture upload\n await userProfilePage.uploadProfilePicture('./fixtures/test-avatar.jpg');\n \n // Verify image upload\n await expect(userProfilePage.profileImage)\n .toBeVisible();\n \n // Step 7: Test account security settings\n await userProfilePage.clickSecurityTab();\n \n // Change password\n await userProfilePage.changePassword(\n newUser.password,\n 'NewSecurePassword123!'\n );\n \n await expect(userProfilePage.successMessage)\n .toContainText('Password changed successfully');\n \n // Step 8: Test logout and login with new password\n await dashboardPage.logout();\n \n await loginPage.login(newUser.email, 'NewSecurePassword123!');\n \n // Verify successful login with new password\n await expect(dashboardPage.welcomeMessage)\n .toContainText(`Welcome, ${updatedInfo.name}`);\n });\n\n test('should handle profile update errors gracefully', async ({ page }) => {\n // Login as existing user\n await loginPage.login('existing@example.com', 'password123');\n \n // Navigate to profile\n await dashboardPage.navigateToProfile();\n \n // Try to update with invalid data\n await userProfilePage.fillName(''); // Empty name should fail\n await userProfilePage.fillEmail('invalid-email'); // Invalid email\n await userProfilePage.saveChanges();\n \n // Verify error messages\n await expect(userProfilePage.nameError)\n .toContainText('Name is required');\n await expect(userProfilePage.emailError)\n .toContainText('Please enter a valid email');\n \n // Verify form wasn't submitted\n await expect(userProfilePage.successMessage)\n .not.toBeVisible();\n });\n\n test('should be accessible with keyboard navigation', async ({ page }) => {\n await loginPage.login('existing@example.com', 'password123');\n await dashboardPage.navigateToProfile();\n \n // Test keyboard navigation through form\n await page.keyboard.press('Tab'); // Focus name field\n await expect(userProfilePage.nameField).toBeFocused();\n \n await page.keyboard.press('Tab'); // Focus email field\n await expect(userProfilePage.emailField).toBeFocused();\n \n await page.keyboard.press('Tab'); // Focus bio field\n await expect(userProfilePage.bioField).toBeFocused();\n \n // Test form submission with keyboard\n await userProfilePage.fillName('Keyboard User');\n await page.keyboard.press('Enter'); // Should submit form\n \n await expect(userProfilePage.successMessage)\n .toContainText('Profile updated successfully');\n });\n});" + } + }, + "testDataManagement": { + "fixtures": { + "description": "Pre-defined test data for consistent testing", + "patterns": "Factory pattern, Builder pattern, Object mothers", + "storage": "JSON files, Database seeds, In-memory objects" + }, + "factories": { + "description": "Dynamic test data generation", + "tools": "Faker.js, Factory Bot, Factory Girl", + "benefits": "Unique data, Customizable, Realistic" + }, + "mocking": { + "description": "Fake implementations for external dependencies", + "types": "API mocks, Database mocks, Service mocks", + "tools": "MSW, Nock, Sinon, Jest mocks" + }, + "cleanup": { + "description": "Clean up test data after test execution", + "strategies": "Database transactions, Cleanup hooks, Isolated test databases", + "importance": "Prevent test interference, Maintain test isolation" + } + }, + "bestPractices": [ + "Write tests first (TDD) or alongside implementation", + "Keep tests independent and isolated from each other", + "Use descriptive test names that explain the scenario", + "Follow the AAA pattern (Arrange, Act, Assert)", + "Mock external dependencies to ensure test isolation", + "Write both positive and negative test cases", + "Keep tests simple and focused on one thing", + "Use test data factories for consistent test data", + "Clean up test data after test execution", + "Run tests frequently during development", + "Maintain tests as first-class code with proper refactoring", + "Use code coverage as a guide, not a target" + ], + "antiPatterns": [ + "Tests that depend on other tests or test order", + "Tests that test implementation details instead of behavior", + "Over-mocking that makes tests brittle", + "Tests with unclear or generic names", + "Tests that are too complex or test multiple things", + "Ignoring or commenting out failing tests", + "Tests that duplicate production logic", + "Hard-coded test data that becomes outdated", + "Tests that require manual setup or intervention", + "Flaky tests that pass/fail randomly", + "Tests that take too long to run", + "Tests without proper assertions" + ] +} \ No newline at end of file diff --git a/runtime/claude/settings-overlays/jarvis-ralph.json b/runtime/claude/settings-overlays/jarvis-ralph.json new file mode 100644 index 0000000..ef3851e --- /dev/null +++ b/runtime/claude/settings-overlays/jarvis-ralph.json @@ -0,0 +1,52 @@ +{ + "_comment": "Claude runtime overlay managed by Mosaic. Merge into ~/.claude/settings.json as needed.", + + "model": "opus", + + "additionalAllowedCommands": [ + "ralph", + "./ralph.sh", + "scripts/ralph/ralph.sh", + "alembic", + "alembic upgrade", + "alembic downgrade", + "alembic revision", + "alembic history", + "uvicorn", + "fastapi", + "ruff", + "ruff check", + "ruff format", + "black", + "isort", + "httpx" + ], + + "projectConfigs": { + "jarvis": { + "path": "~/src/jarvis", + "model": "opus", + "skills": ["jarvis", "ralph", "prd"], + "guides": ["backend", "frontend", "authentication"], + "env": { + "PYTHONPATH": "packages/plugins" + } + } + }, + + "presets": { + "jarvis-ralph": { + "description": "Ralph autonomous development for Jarvis", + "model": "opus", + "skills": ["jarvis", "ralph"], + "systemPrompt": "You are an autonomous coding agent following the Ralph pattern. Focus on one story at a time, run quality checks, and commit only when passing." + }, + "jarvis-review": { + "description": "Code review mode for Jarvis PRs", + "model": "opus", + "skills": ["jarvis"], + "guides": ["code-review"], + "systemPrompt": "Review code changes for quality, security, and adherence to Jarvis patterns." + } + } +}