@paths.design/caws-cli 3.4.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,315 @@
1
+ ---
2
+ description: Comprehensive testing standards and verification requirements
3
+ globs:
4
+ alwaysApply: true
5
+ ---
6
+
7
+ # Testing Standards & Verification Requirements
8
+
9
+ ## Testing Pyramid Requirements
10
+
11
+ ### Unit Tests (Foundation Layer)
12
+
13
+ - **Coverage Thresholds**: 80% line coverage, 90% branch coverage minimum
14
+ - **Test Isolation**: Each test completely independent, no shared state
15
+ - **Mock Strategy**: Mock external dependencies, test business logic in isolation
16
+ - **Naming Convention**: `describe('ComponentName', () => { it('should do something', () => {}) })`
17
+ - **Assertion Style**: Use descriptive assertions, avoid generic `toBe(true)`
18
+
19
+ ### Integration Tests (Middle Layer)
20
+
21
+ - **Database Integration**: Real database connections, not mocked
22
+ - **External APIs**: Test actual HTTP calls with proper error handling
23
+ - **Component Communication**: Test inter-component contracts
24
+ - **Setup/Teardown**: Proper database seeding and cleanup
25
+ - **Async Handling**: All async operations properly awaited and tested
26
+
27
+ ### End-to-End Tests (Top Layer)
28
+
29
+ - **Full User Journeys**: Complete workflows from start to finish
30
+ - **Real Browsers**: Use actual browser automation, not mocked DOM
31
+ - **Data Persistence**: Verify data survives application restarts
32
+ - **Performance Baselines**: Include timing assertions where relevant
33
+
34
+ ## Test Quality Standards
35
+
36
+ ### Test Structure Requirements
37
+
38
+ ```typescript
39
+ describe("ComponentName", () => {
40
+ describe("when condition A", () => {
41
+ it("should behave correctly", () => {
42
+ // Given: Setup preconditions
43
+ // When: Execute the action
44
+ // Then: Verify the outcome
45
+ });
46
+ });
47
+ });
48
+ ```
49
+
50
+ ### Edge Case Coverage
51
+
52
+ - **Null/Undefined**: Test with null, undefined, empty arrays, empty objects
53
+ - **Boundary Values**: Test minimums, maximums, and edge boundaries
54
+ - **Error Conditions**: Test all error paths and exception handling
55
+ - **Concurrency**: Test race conditions and concurrent access
56
+ - **Resource Limits**: Test memory limits, timeouts, rate limits
57
+
58
+ ### Test Data Management
59
+
60
+ - **Realistic Fixtures**: Use representative data, not just minimal examples
61
+ - **Factory Pattern**: Create test data factories for consistent object creation
62
+ - **Cleanup Strategy**: Ensure tests don't leave persistent state
63
+ - **Isolation**: Tests must not interfere with each other
64
+
65
+ ## Verification Requirements
66
+
67
+ ### Pre-Commit Verification
68
+
69
+ - [ ] All unit tests pass (`npm test`)
70
+ - [ ] No tests skipped in production code
71
+ - [ ] Coverage thresholds met
72
+ - [ ] No console errors or warnings in tests
73
+ - [ ] Database tests use real connections
74
+
75
+ ### Integration Verification
76
+
77
+ - [ ] Database schema matches migrations
78
+ - [ ] External API contracts validated
79
+ - [ ] Authentication/authorization tested
80
+ - [ ] Error handling verified end-to-end
81
+
82
+ ### Performance Verification
83
+
84
+ - [ ] Response times within documented SLAs
85
+ - [ ] Memory usage within limits
86
+ - [ ] Database query performance acceptable
87
+ - [ ] Concurrent user load handled
88
+
89
+ ## Test Infrastructure Standards
90
+
91
+ ### Testing Tools & Frameworks
92
+
93
+ - **Test Runner**: Jest, Vitest, or equivalent with parallel execution
94
+ - **Assertion Library**: Built-in assertions with descriptive matchers
95
+ - **Mocking**: Comprehensive mocking for external dependencies
96
+ - **Coverage**: Istanbul/NYC for coverage reporting
97
+ - **CI Integration**: Automated test execution in CI pipeline
98
+
99
+ ### Database Testing
100
+
101
+ - **Test Database**: Separate database instance for tests
102
+ - **Schema Sync**: Automatic schema setup/teardown
103
+ - **Data Seeding**: Deterministic test data seeding
104
+ - **Transaction Rollback**: Tests wrapped in transactions for cleanup
105
+
106
+ ### CI/CD Testing
107
+
108
+ - **Parallel Execution**: Tests run in parallel for speed
109
+ - **Flaky Test Detection**: Automatic retry for known flaky tests
110
+ - **Coverage Reporting**: Coverage reports uploaded to CI
111
+ - **Test Result Storage**: Historical test results tracked
112
+
113
+ ## Testing Anti-Patterns (Forbidden)
114
+
115
+ ### ❌ Mocking Core Business Logic
116
+
117
+ ```typescript
118
+ // DON'T: Mock the function you're supposed to test
119
+ jest.mock("./businessLogic", () => ({
120
+ calculateTotal: jest.fn(() => 100),
121
+ }));
122
+
123
+ test("calculateTotal", () => {
124
+ expect(calculateTotal()).toBe(100); // Tests the mock, not the logic
125
+ });
126
+ ```
127
+
128
+ ### ❌ Testing Implementation Details
129
+
130
+ ```typescript
131
+ // DON'T: Test private methods or internal state
132
+ test("internal counter increments", () => {
133
+ component.privateCounter = 5; // Accessing private state
134
+ expect(component.privateCounter).toBe(5);
135
+ });
136
+ ```
137
+
138
+ ### ❌ Inadequate Error Testing
139
+
140
+ ```typescript
141
+ // DON'T: Generic error testing
142
+ test("throws error", () => {
143
+ expect(() => riskyOperation()).toThrow(); // Too vague
144
+ });
145
+ ```
146
+
147
+ ### ❌ No Cleanup in Integration Tests
148
+
149
+ ```typescript
150
+ // DON'T: Leave test data behind
151
+ test("creates user", async () => {
152
+ await createUser({ name: "test" });
153
+ // No cleanup - data persists
154
+ });
155
+ ```
156
+
157
+ ## Testing Best Practices
158
+
159
+ ### ✅ Proper Error Testing
160
+
161
+ ```typescript
162
+ test("throws specific error for invalid input", () => {
163
+ expect(() => validateEmail("invalid")).toThrow(ValidationError);
164
+ expect(() => validateEmail("invalid")).toThrow("Invalid email format");
165
+ });
166
+ ```
167
+
168
+ ### ✅ Realistic Test Data
169
+
170
+ ```typescript
171
+ const realisticUser = {
172
+ id: "user-123",
173
+ email: "user@example.com",
174
+ name: "John Doe",
175
+ createdAt: new Date("2024-01-01"),
176
+ preferences: { theme: "dark", notifications: true },
177
+ };
178
+ ```
179
+
180
+ ### ✅ Proper Async Testing
181
+
182
+ ```typescript
183
+ test("resolves with correct data", async () => {
184
+ const result = await fetchUserData("user-123");
185
+ expect(result).toEqual(expectedUserData);
186
+ });
187
+ ```
188
+
189
+ ### ✅ Database Test Cleanup
190
+
191
+ ```typescript
192
+ describe("UserService", () => {
193
+ let dbClient;
194
+
195
+ beforeEach(async () => {
196
+ dbClient = await createTestDbConnection();
197
+ await seedTestData(dbClient);
198
+ });
199
+
200
+ afterEach(async () => {
201
+ await cleanupTestData(dbClient);
202
+ await dbClient.end();
203
+ });
204
+ });
205
+ ```
206
+
207
+ ## Test Documentation Requirements
208
+
209
+ ### Test Comments for Complex Logic
210
+
211
+ ```typescript
212
+ test("calculates compound interest with monthly compounding", () => {
213
+ // Formula: A = P(1 + r/n)^(nt)
214
+ // Where: A = final amount, P = principal, r = rate, n = compounding frequency, t = time
215
+ const principal = 1000;
216
+ const rate = 0.05; // 5%
217
+ const compoundingFrequency = 12; // monthly
218
+ const timeInYears = 2;
219
+
220
+ const result = calculateCompoundInterest(
221
+ principal,
222
+ rate,
223
+ compoundingFrequency,
224
+ timeInYears
225
+ );
226
+ const expected = 1104.54; // Pre-calculated expected value
227
+
228
+ expect(result).toBeCloseTo(expected, 2);
229
+ });
230
+ ```
231
+
232
+ ### Test Coverage Comments
233
+
234
+ ```typescript
235
+ // Test Coverage:
236
+ // ✅ Happy path: valid input -> correct output
237
+ // ✅ Edge case: zero principal -> zero result
238
+ // ✅ Edge case: negative rate -> throws error
239
+ // ✅ Error case: invalid compounding frequency -> throws error
240
+ // ✅ Boundary: very large numbers -> handles precision
241
+ ```
242
+
243
+ ## Performance Testing Standards
244
+
245
+ ### Response Time Assertions
246
+
247
+ ```typescript
248
+ test("responds within SLA", async () => {
249
+ const startTime = Date.now();
250
+ const result = await expensiveOperation();
251
+ const duration = Date.now() - startTime;
252
+
253
+ expect(duration).toBeLessThan(5000); // 5 second SLA
254
+ expect(result).toBeDefined();
255
+ });
256
+ ```
257
+
258
+ ### Load Testing Guidelines
259
+
260
+ - Test with realistic concurrent users
261
+ - Include warm-up periods
262
+ - Measure 95th percentile response times
263
+ - Test memory usage under load
264
+ - Verify graceful degradation
265
+
266
+ ## Mutation Testing Standards
267
+
268
+ ### Mutation Operators to Cover
269
+
270
+ - **Arithmetic Operators**: `+`, `-`, `*`, `/`, `%`
271
+ - **Logical Operators**: `&&`, `||`, `!`
272
+ - **Comparison Operators**: `==`, `!=`, `<`, `>`, `<=`, `>=`
273
+ - **Conditional Boundaries**: `if` conditions, ternary operators
274
+ - **Return Statements**: Missing/incorrect returns
275
+ - **Variable Assignments**: Wrong variable assignments
276
+
277
+ ### Mutation Score Targets
278
+
279
+ - **Critical Components**: 80%+ mutation score
280
+ - **Business Logic**: 70%+ mutation score
281
+ - **Utilities**: 60%+ mutation score
282
+ - **UI Components**: 50%+ mutation score (may be lower due to test complexity)
283
+
284
+ ## Accessibility Testing (Web Components)
285
+
286
+ ### Screen Reader Testing
287
+
288
+ ```typescript
289
+ test("is accessible to screen readers", () => {
290
+ render(<Button>Click me</Button>);
291
+
292
+ // Test ARIA labels
293
+ expect(screen.getByRole("button")).toHaveAttribute("aria-label", "Click me");
294
+
295
+ // Test keyboard navigation
296
+ userEvent.tab();
297
+ expect(screen.getByRole("button")).toHaveFocus();
298
+ });
299
+ ```
300
+
301
+ ### Color Contrast Testing
302
+
303
+ ```typescript
304
+ test("meets color contrast requirements", () => {
305
+ render(<Text variant="error">Error message</Text>);
306
+
307
+ const element = screen.getByText("Error message");
308
+ const styles = window.getComputedStyle(element);
309
+
310
+ // Verify contrast ratio programmatically
311
+ expect(
312
+ getContrastRatio(styles.color, styles.backgroundColor)
313
+ ).toBeGreaterThan(4.5);
314
+ });
315
+ ```
@@ -0,0 +1,251 @@
1
+ ---
2
+ description: Infrastructure, deployment, and operational standards
3
+ globs:
4
+ alwaysApply: true
5
+ ---
6
+
7
+ # Infrastructure & Deployment Standards
8
+
9
+ ## Database Standards
10
+
11
+ ### Connection Management
12
+
13
+ - **Connection Pooling**: Always use connection pools, never single connections
14
+ - **Pool Configuration**: Set appropriate min/max connections based on load
15
+ - **Timeout Handling**: Configure connection, query, and idle timeouts
16
+ - **Health Checks**: Implement connection health validation
17
+ - **Graceful Shutdown**: Properly close connections on application shutdown
18
+
19
+ ### Schema Management
20
+
21
+ - **Migration Scripts**: Version-controlled, transactional migrations
22
+ - **Downgrade Scripts**: Provide rollback migrations for all changes
23
+ - **Idempotent Operations**: Migrations safe to run multiple times
24
+ - **Testing**: All migrations tested against production-like data
25
+ - **Documentation**: Migration purpose and impact clearly documented
26
+
27
+ ### Data Integrity
28
+
29
+ - **Constraints**: Foreign keys, unique constraints, check constraints
30
+ - **Transactions**: All multi-table operations in transactions
31
+ - **Atomicity**: Either all changes succeed or all fail
32
+ - **Consistency**: Database always in valid state
33
+ - **Isolation**: Concurrent operations don't interfere
34
+
35
+ ## API Standards
36
+
37
+ ### RESTful Design
38
+
39
+ - **Resource Naming**: Plural nouns, consistent casing
40
+ - **HTTP Methods**: GET (read), POST (create), PUT/PATCH (update), DELETE
41
+ - **Status Codes**: Proper HTTP status codes (200, 201, 400, 404, 500, etc.)
42
+ - **Content Types**: JSON for data, appropriate content-type headers
43
+ - **Versioning**: API versioning strategy (URL, headers, or content negotiation)
44
+
45
+ ### Error Handling
46
+
47
+ - **Structured Errors**: Consistent error response format
48
+ - **Error Codes**: Machine-readable error codes with human-readable messages
49
+ - **Logging**: All errors logged with appropriate severity
50
+ - **Client Guidance**: Error responses include actionable information
51
+ - **No Information Leakage**: Sensitive information not exposed in errors
52
+
53
+ ## Security Standards
54
+
55
+ ### Authentication & Authorization
56
+
57
+ - **Token Management**: Secure token storage and validation
58
+ - **Session Handling**: Proper session lifecycle management
59
+ - **Role-Based Access**: Clear role definitions and enforcement
60
+ - **Permission Checking**: Every operation validates permissions
61
+ - **Audit Logging**: All security events logged
62
+
63
+ ### Input Validation
64
+
65
+ - **Schema Validation**: All inputs validated against schemas
66
+ - **Sanitization**: User input sanitized before processing
67
+ - **Type Safety**: Runtime type checking for external inputs
68
+ - **Length Limits**: Reasonable limits on input sizes
69
+ - **Content Filtering**: Malicious content detection and blocking
70
+
71
+ ## Monitoring & Observability
72
+
73
+ ### Logging Standards
74
+
75
+ - **Structured Logging**: JSON format with consistent field names
76
+ - **Log Levels**: ERROR, WARN, INFO, DEBUG appropriately used
77
+ - **Context Information**: Request IDs, user context, operation details
78
+ - **Performance Logging**: Response times, resource usage
79
+ - **Error Correlation**: Related events linked together
80
+
81
+ ### Metrics Collection
82
+
83
+ - **Business Metrics**: User registrations, API calls, conversion rates
84
+ - **Performance Metrics**: Response times, throughput, error rates
85
+ - **Resource Metrics**: CPU, memory, disk, network usage
86
+ - **Custom Metrics**: Application-specific KPIs
87
+ - **Alert Thresholds**: Defined thresholds for automated alerts
88
+
89
+ ### Health Checks
90
+
91
+ - **Application Health**: Service availability and responsiveness
92
+ - **Dependency Health**: Database, external APIs, message queues
93
+ - **Resource Health**: Disk space, memory, connection pools
94
+ - **Business Health**: Core business operations functional
95
+ - **Automated Recovery**: Self-healing capabilities
96
+
97
+ ## Deployment Standards
98
+
99
+ ### Environment Configuration
100
+
101
+ - **Environment Variables**: No hardcoded configuration values
102
+ - **Configuration Files**: Version-controlled, environment-specific configs
103
+ - **Secrets Management**: Secure storage and access for secrets
104
+ - **Validation**: Configuration validated at startup
105
+ - **Documentation**: All configuration options documented
106
+
107
+ ### Container Standards
108
+
109
+ - **Base Images**: Minimal, secure base images
110
+ - **Layer Optimization**: Efficient layer caching and ordering
111
+ - **Security Scanning**: Container images scanned for vulnerabilities
112
+ - **Resource Limits**: CPU and memory limits set appropriately
113
+ - **Health Checks**: Container health checks implemented
114
+
115
+ ### CI/CD Pipeline
116
+
117
+ - **Automated Testing**: Full test suite runs on every commit
118
+ - **Security Scanning**: Automated security scans in pipeline
119
+ - **Performance Testing**: Automated performance regression tests
120
+ - **Deployment Automation**: Zero-touch deployment processes
121
+ - **Rollback Capability**: Automated rollback procedures
122
+
123
+ ## Reliability Standards
124
+
125
+ ### Circuit Breaker Pattern
126
+
127
+ - **Failure Threshold**: Configurable failure count before opening
128
+ - **Recovery Timeout**: Time before attempting recovery
129
+ - **Success Threshold**: Successes needed to close circuit
130
+ - **Fallback Behavior**: Graceful degradation when circuit open
131
+ - **Monitoring**: Circuit state and failure rates monitored
132
+
133
+ ### Retry Logic
134
+
135
+ - **Exponential Backoff**: Increasing delay between retries
136
+ - **Jitter**: Randomization to prevent thundering herd
137
+ - **Maximum Retries**: Configurable retry limits
138
+ - **Retry Conditions**: Only retry appropriate error types
139
+ - **Circuit Integration**: Retry logic respects circuit breaker state
140
+
141
+ ### Graceful Degradation
142
+
143
+ - **Feature Flags**: Ability to disable features under load
144
+ - **Fallback Content**: Cached or simplified content when services fail
145
+ - **Progressive Enhancement**: Core functionality works without extras
146
+ - **User Communication**: Clear messaging about degraded functionality
147
+ - **Automatic Recovery**: Services automatically recover when possible
148
+
149
+ ## Performance Standards
150
+
151
+ ### Response Time SLAs
152
+
153
+ - **API Endpoints**: P95 response times defined and monitored
154
+ - **Page Load Times**: Frontend performance budgets
155
+ - **Database Queries**: Query performance thresholds
156
+ - **Background Jobs**: Job completion time limits
157
+ - **Real-time Operations**: Sub-second response requirements
158
+
159
+ ### Resource Management
160
+
161
+ - **Memory Usage**: Monitor and limit memory consumption
162
+ - **CPU Utilization**: Efficient CPU usage patterns
163
+ - **Disk I/O**: Optimize file system operations
164
+ - **Network Usage**: Efficient network communication
165
+ - **Connection Pools**: Proper sizing of database and external connections
166
+
167
+ ### Caching Strategy
168
+
169
+ - **Cache Invalidation**: Proper cache invalidation strategies
170
+ - **Cache Penetration**: Protection against cache penetration attacks
171
+ - **Cache Warming**: Proactive cache population for hot data
172
+ - **Distributed Caching**: Scalable caching across multiple instances
173
+ - **Cache Monitoring**: Cache hit rates and performance monitoring
174
+
175
+ ## Scalability Standards
176
+
177
+ ### Horizontal Scaling
178
+
179
+ - **Stateless Design**: Applications designed for horizontal scaling
180
+ - **Shared Nothing**: Instances don't share local state
181
+ - **Load Balancing**: Proper load distribution across instances
182
+ - **Session Management**: Distributed session storage
183
+ - **Configuration**: Centralized configuration management
184
+
185
+ ### Database Scaling
186
+
187
+ - **Read Replicas**: Read operations distributed across replicas
188
+ - **Sharding Strategy**: Data partitioning strategy defined
189
+ - **Connection Pooling**: Efficient connection management
190
+ - **Query Optimization**: Efficient query patterns
191
+ - **Indexing Strategy**: Appropriate indexes for query patterns
192
+
193
+ ### Asynchronous Processing
194
+
195
+ - **Message Queues**: Asynchronous task processing
196
+ - **Background Jobs**: Long-running tasks processed asynchronously
197
+ - **Event-Driven Architecture**: Loose coupling through events
198
+ - **Dead Letter Queues**: Handling of failed message processing
199
+ - **Monitoring**: Queue depth and processing rate monitoring
200
+
201
+ ## Backup & Recovery
202
+
203
+ ### Data Backup
204
+
205
+ - **Regular Backups**: Automated backup schedules
206
+ - **Backup Verification**: Backup integrity validation
207
+ - **Retention Policies**: Backup retention periods defined
208
+ - **Encryption**: Backup data encrypted at rest and in transit
209
+ - **Testing**: Backup restoration regularly tested
210
+
211
+ ### Disaster Recovery
212
+
213
+ - **Recovery Time Objective (RTO)**: Maximum acceptable downtime
214
+ - **Recovery Point Objective (RPO)**: Maximum data loss acceptable
215
+ - **Multi-Region Deployment**: Geographic redundancy
216
+ - **Failover Procedures**: Automated and manual failover processes
217
+ - **Recovery Testing**: Regular disaster recovery drills
218
+
219
+ ### Business Continuity
220
+
221
+ - **Service Level Agreements**: Defined uptime and performance guarantees
222
+ - **Incident Response**: Defined incident response procedures
223
+ - **Communication Plans**: Stakeholder communication during incidents
224
+ - **Post-Mortem Process**: Incident analysis and improvement process
225
+ - **Continuous Improvement**: Regular review and improvement of processes
226
+
227
+ ## Compliance & Governance
228
+
229
+ ### Security Compliance
230
+
231
+ - **Data Encryption**: Data encrypted at rest and in transit
232
+ - **Access Controls**: Principle of least privilege enforced
233
+ - **Audit Trails**: Comprehensive audit logging
234
+ - **Vulnerability Management**: Regular security assessments
235
+ - **Incident Response**: Security incident response procedures
236
+
237
+ ### Data Privacy
238
+
239
+ - **Data Classification**: Sensitive data properly classified
240
+ - **Retention Policies**: Data retention periods defined
241
+ - **Consent Management**: User consent properly managed
242
+ - **Data Deletion**: Right to deletion implemented
243
+ - **Privacy Impact Assessments**: Privacy risks assessed
244
+
245
+ ### Regulatory Compliance
246
+
247
+ - **GDPR Compliance**: EU data protection regulations
248
+ - **CCPA Compliance**: California consumer privacy regulations
249
+ - **Industry Standards**: Relevant industry compliance requirements
250
+ - **Audit Readiness**: Systems designed for regulatory audits
251
+ - **Documentation**: Compliance evidence properly documented