coverme-scanner 1.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.
Files changed (46) hide show
  1. package/README.md +227 -0
  2. package/commands/scan.md +317 -0
  3. package/dist/cli/index.d.ts +3 -0
  4. package/dist/cli/index.d.ts.map +1 -0
  5. package/dist/cli/index.js +39 -0
  6. package/dist/cli/index.js.map +1 -0
  7. package/dist/cli/init.d.ts +6 -0
  8. package/dist/cli/init.d.ts.map +1 -0
  9. package/dist/cli/init.js +636 -0
  10. package/dist/cli/init.js.map +1 -0
  11. package/dist/cli/scan.d.ts +11 -0
  12. package/dist/cli/scan.d.ts.map +1 -0
  13. package/dist/cli/scan.js +498 -0
  14. package/dist/cli/scan.js.map +1 -0
  15. package/dist/report/generator.d.ts +48 -0
  16. package/dist/report/generator.d.ts.map +1 -0
  17. package/dist/report/generator.js +368 -0
  18. package/dist/report/generator.js.map +1 -0
  19. package/dist/report/index.d.ts +35 -0
  20. package/dist/report/index.d.ts.map +1 -0
  21. package/dist/report/index.js +463 -0
  22. package/dist/report/index.js.map +1 -0
  23. package/dist/templates/report.html +796 -0
  24. package/dist/types.d.ts +94 -0
  25. package/dist/types.d.ts.map +1 -0
  26. package/dist/types.js +3 -0
  27. package/dist/types.js.map +1 -0
  28. package/package.json +48 -0
  29. package/src/cli/index.ts +43 -0
  30. package/src/cli/init.ts +611 -0
  31. package/src/cli/scan.ts +483 -0
  32. package/src/prompts/architecture-reviewer.md +171 -0
  33. package/src/prompts/consensus-builder.md +247 -0
  34. package/src/prompts/context-discovery.md +174 -0
  35. package/src/prompts/cross-validator.md +224 -0
  36. package/src/prompts/deep-dive-expert.md +224 -0
  37. package/src/prompts/dependency-auditor.md +190 -0
  38. package/src/prompts/performance-hunter.md +200 -0
  39. package/src/prompts/quality-analyzer.md +150 -0
  40. package/src/prompts/report-generator.md +285 -0
  41. package/src/prompts/security-scanner.md +180 -0
  42. package/src/report/generator.ts +382 -0
  43. package/src/report/index.ts +483 -0
  44. package/src/templates/report.html +796 -0
  45. package/src/types.ts +107 -0
  46. package/tsconfig.json +20 -0
@@ -0,0 +1,483 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import type { ScanOptions, Category, Severity } from '../types.js';
4
+
5
+ interface ScanCommandOptions {
6
+ output: string;
7
+ outputPath?: string;
8
+ categories: string;
9
+ severity: string;
10
+ verbose?: boolean;
11
+ parallel: string;
12
+ }
13
+
14
+ export async function scan(
15
+ scanPath: string,
16
+ options: ScanCommandOptions
17
+ ): Promise<void> {
18
+ const resolvedPath = path.resolve(scanPath);
19
+
20
+ if (!fs.existsSync(resolvedPath)) {
21
+ console.error(`Error: Path does not exist: ${resolvedPath}`);
22
+ process.exit(1);
23
+ }
24
+
25
+ const categories: Category[] =
26
+ options.categories === 'all'
27
+ ? ['security', 'quality', 'architecture', 'dependencies', 'performance']
28
+ : (options.categories.split(',') as Category[]);
29
+
30
+ const scanOptions: ScanOptions = {
31
+ path: resolvedPath,
32
+ output: options.output as 'json' | 'pdf' | 'md' | 'html',
33
+ outputPath: options.outputPath,
34
+ categories,
35
+ minSeverity: options.severity as Severity,
36
+ verbose: options.verbose,
37
+ parallel: parseInt(options.parallel, 10),
38
+ };
39
+
40
+ console.log(`
41
+ ================================================================================
42
+ COVERME SECURITY SCANNER
43
+ 10-Agent Deep Analysis System
44
+ ================================================================================
45
+
46
+ Scan Target: ${resolvedPath}
47
+ Categories: ${categories.join(', ')}
48
+ Output: ${scanOptions.output}
49
+ Agents: 10 scanners + 3 validators
50
+
51
+ ================================================================================
52
+
53
+ This scan runs FROM WITHIN Claude Code.
54
+ Run: /coverme
55
+
56
+ ================================================================================
57
+ `);
58
+
59
+ // Output the orchestration prompt for Claude Code
60
+ console.log(generateOrchestrationPrompt(scanOptions));
61
+ }
62
+
63
+ function generateOrchestrationPrompt(options: ScanOptions): string {
64
+ const projectPath = options.path;
65
+ const dateStr = new Date().toISOString().split('T')[0];
66
+
67
+ return `
68
+ ## CoverMe Multi-Agent Scan Orchestration
69
+
70
+ Execute this 10-agent security scan with cross-validation.
71
+
72
+ **CRITICAL OUTPUT FORMAT:**
73
+ Every finding MUST include ALL these fields for the report to work:
74
+ \`\`\`json
75
+ {
76
+ "id": "PREFIX-XXX",
77
+ "title": "Short descriptive title",
78
+ "severity": "critical|high|medium|low|info",
79
+ "category": "Category name",
80
+ "file": "exact/path/to/file.ts",
81
+ "line": 123,
82
+ "code": "the vulnerable/problematic code snippet",
83
+ "description": "What is wrong - the specific problem found",
84
+ "why": "Why this matters - security impact, what an attacker could do, business risk",
85
+ "context": "Code context - what this code is trying to do, surrounding logic, dependencies",
86
+ "checkBefore": "What to verify before fixing - tests to run, dependencies to check, potential breaking changes",
87
+ "recommendation": "Exact steps to fix this issue with code example if applicable",
88
+ "cwe": "CWE-XXX (if applicable)",
89
+ "confidence": 85
90
+ }
91
+ \`\`\`
92
+
93
+ **FIELD GUIDELINES:**
94
+ - **why**: Explain the real-world impact. Example: "An attacker could steal session tokens and impersonate any user"
95
+ - **context**: Reference specific code. Example: "This function handles user uploads and is called from the /api/upload endpoint"
96
+ - **checkBefore**: CRITICAL - Always check for existing solutions first! Include:
97
+
98
+ EXISTING SOLUTIONS TO CHECK:
99
+ - Search for: sanitize, validate, escape functions in utils/
100
+ - Check if library already imported (e.g., DOMPurify, validator.js)
101
+ - Look at how other files handle this pattern
102
+
103
+ BEFORE IMPLEMENTING:
104
+ 1. Run existing tests
105
+ 2. Check for duplicate fixes needed elsewhere
106
+ 3. Verify no breaking changes
107
+
108
+ ---
109
+
110
+ ### PHASE 1: PARALLEL DISCOVERY (Launch ALL 10 agents simultaneously)
111
+
112
+ ---
113
+
114
+ **AGENT 1: Security Core Scanner** (ID prefix: SEC)
115
+ \`\`\`
116
+ Scan ${projectPath} for OWASP Top 10 and core security vulnerabilities.
117
+
118
+ CHECK FOR:
119
+ - SQL/NoSQL Injection (parameterized queries missing)
120
+ - XSS (reflected, stored, DOM-based)
121
+ - Command Injection (shell commands with user input)
122
+ - Path Traversal (../ in file operations)
123
+ - SSRF (user-controlled URLs in fetch/axios)
124
+ - XXE (XML parsing without disabling entities)
125
+ - Insecure Deserialization (JSON.parse on untrusted data)
126
+ - Hardcoded Secrets (API keys, passwords, tokens in code)
127
+ - Weak Cryptography (MD5, SHA1 for passwords, ECB mode)
128
+ - Insecure Random (Math.random for security purposes)
129
+
130
+ For EACH finding, output the FULL JSON format above.
131
+ \`\`\`
132
+
133
+ ---
134
+
135
+ **AGENT 2: Auth & Session Scanner** (ID prefix: AUTH)
136
+ \`\`\`
137
+ Scan ${projectPath} for authentication and session vulnerabilities.
138
+
139
+ CHECK FOR:
140
+ - SSO/OAuth Open Redirect (return_url, redirect_uri without validation)
141
+ - PKCE missing in OAuth flows
142
+ - JWT issues (alg:none, weak secrets, missing expiry)
143
+ - Session fixation (session not regenerated after login)
144
+ - Cookie security (missing HttpOnly, Secure, SameSite)
145
+ - Password reset flaws (predictable tokens, no expiry)
146
+ - MFA bypass paths
147
+ - Remember-me token weaknesses
148
+ - Account enumeration (different responses for valid/invalid users)
149
+ - Brute force protection missing
150
+
151
+ For EACH finding, output the FULL JSON format.
152
+ \`\`\`
153
+
154
+ ---
155
+
156
+ **AGENT 3: API Security Scanner** (ID prefix: API)
157
+ \`\`\`
158
+ Scan ${projectPath} for API security issues.
159
+
160
+ CHECK FOR:
161
+ - Missing authentication on endpoints
162
+ - Broken authorization (IDOR, privilege escalation)
163
+ - Input validation missing (Zod/Joi schemas)
164
+ - Rate limiting issues (non-atomic INCR+EXPIRE in Redis)
165
+ - CORS misconfiguration (Access-Control-Allow-Origin: *)
166
+ - Mass assignment (spreading req.body into DB)
167
+ - Webhook signature verification missing (HMAC)
168
+ - GraphQL introspection enabled in production
169
+ - API versioning issues
170
+ - Excessive data exposure in responses
171
+
172
+ For EACH finding, output the FULL JSON format.
173
+ \`\`\`
174
+
175
+ ---
176
+
177
+ **AGENT 4: Infrastructure Scanner** (ID prefix: INFRA)
178
+ \`\`\`
179
+ Scan ${projectPath} for infrastructure and DevOps issues.
180
+
181
+ CHECK FOR:
182
+ - Secrets in git-tracked files (Helm values, K8s manifests, .env committed)
183
+ - Real IPs/hostnames committed to repo
184
+ - Docker issues (running as root, secrets in layers)
185
+ - K8s pod security context missing
186
+ - CI/CD pipeline security (missing quality gates)
187
+ - Missing security headers in server config
188
+ - TLS/SSL configuration issues
189
+ - Debug mode enabled in production configs
190
+ - Exposed internal ports
191
+ - Missing resource limits
192
+
193
+ For EACH finding, output the FULL JSON format.
194
+ \`\`\`
195
+
196
+ ---
197
+
198
+ **AGENT 5: Data & Privacy Scanner** (ID prefix: DATA)
199
+ \`\`\`
200
+ Scan ${projectPath} for data protection and privacy issues.
201
+
202
+ CHECK FOR:
203
+ - PII logging (emails, IPs, names in logs)
204
+ - GDPR deletion bugs (incomplete data removal)
205
+ - Encryption at rest missing for sensitive fields
206
+ - Data residency violations
207
+ - Backup encryption missing
208
+ - Sensitive data in URLs/query params
209
+ - Missing data classification
210
+ - Retention policy not enforced
211
+ - Export functionality exposing too much data
212
+ - Cross-tenant data leakage
213
+
214
+ For EACH finding, output the FULL JSON format.
215
+ \`\`\`
216
+
217
+ ---
218
+
219
+ **AGENT 6: AI/LLM Security Scanner** (ID prefix: AI)
220
+ \`\`\`
221
+ Scan ${projectPath} for AI/LLM specific vulnerabilities.
222
+
223
+ CHECK FOR:
224
+ - Prompt injection (user input directly in prompts)
225
+ - Content filter fail-open (errors bypass safety)
226
+ - CDN imports without SRI (integrity hashes missing)
227
+ - Model output not sanitized before use
228
+ - Sensitive data sent to external AI APIs
229
+ - AI decision logging insufficient for audit
230
+ - Rate limiting on AI endpoints
231
+ - Cost controls missing
232
+ - Jailbreak prevention missing
233
+ - PII in training data/prompts
234
+
235
+ For EACH finding, output the FULL JSON format.
236
+ \`\`\`
237
+
238
+ ---
239
+
240
+ **AGENT 7: Performance & DoS Scanner** (ID prefix: PERF)
241
+ \`\`\`
242
+ Scan ${projectPath} for performance and denial-of-service issues.
243
+
244
+ CHECK FOR:
245
+ - N+1 query patterns
246
+ - ReDoS (regex denial of service)
247
+ - Memory leaks (event listeners not removed, growing caches)
248
+ - Unbounded data structures
249
+ - Missing pagination
250
+ - SSE/WebSocket buffering entire streams
251
+ - Heavy computation blocking event loop
252
+ - Missing connection pooling
253
+ - Resource exhaustion (no limits on uploads, requests)
254
+ - Synchronous operations that should be async
255
+
256
+ For EACH finding, output the FULL JSON format.
257
+ \`\`\`
258
+
259
+ ---
260
+
261
+ **AGENT 8: Business Logic Scanner** (ID prefix: BIZ)
262
+ \`\`\`
263
+ Scan ${projectPath} for business logic vulnerabilities.
264
+
265
+ CHECK FOR:
266
+ - Race conditions (TOCTOU, double-spend)
267
+ - Workflow bypass (skipping required steps)
268
+ - Price/quantity manipulation
269
+ - Negative value attacks
270
+ - State machine violations
271
+ - Time-based attacks (timing side channels)
272
+ - Non-constant-time comparisons for secrets
273
+ - Duplicate request handling (missing idempotency)
274
+ - Business rule bypass
275
+ - Inconsistent validation between client/server
276
+
277
+ For EACH finding, output the FULL JSON format.
278
+ \`\`\`
279
+
280
+ ---
281
+
282
+ **AGENT 9: Code Quality Scanner** (ID prefix: QUAL)
283
+ \`\`\`
284
+ Scan ${projectPath} for code quality issues that affect security/reliability.
285
+
286
+ CHECK FOR:
287
+ - Error handling swallowing exceptions silently
288
+ - Missing error boundaries
289
+ - Inconsistent error responses
290
+ - Dead code with security implications
291
+ - DRY violations in security code
292
+ - Complex functions (high cyclomatic complexity)
293
+ - Any/unknown types masking issues
294
+ - Missing null checks
295
+ - Callback hell making auditing hard
296
+ - Anti-patterns (god objects, tight coupling)
297
+
298
+ For EACH finding, output the FULL JSON format.
299
+ \`\`\`
300
+
301
+ ---
302
+
303
+ **AGENT 10: Testing & Reliability Scanner** (ID prefix: TEST)
304
+ \`\`\`
305
+ Scan ${projectPath} for testing and reliability gaps.
306
+
307
+ CHECK FOR:
308
+ - Missing tests for security-critical paths
309
+ - No CI quality gates
310
+ - Missing health checks
311
+ - No graceful shutdown handling
312
+ - Circuit breakers missing
313
+ - Retry logic without exponential backoff
314
+ - Missing observability (logging, metrics, tracing)
315
+ - Feature flags without cleanup
316
+ - Database migrations without rollback
317
+ - No chaos/failure testing evidence
318
+
319
+ For EACH finding, output the FULL JSON format.
320
+ \`\`\`
321
+
322
+ ---
323
+
324
+ ### PHASE 2: DUPLICATE & EXISTING SOLUTIONS CHECK
325
+
326
+ **AGENT 11: Duplicate & Existing Solutions Scanner** (ID prefix: DUP)
327
+ \`\`\`
328
+ CRITICAL: Before recommending ANY fix, check if a solution ALREADY EXISTS in the codebase.
329
+
330
+ For EVERY finding from Phase 1, search the codebase for:
331
+
332
+ 1. **Existing utilities/helpers that solve this**:
333
+ - Search for similar function names (sanitize, validate, escape, hash, encrypt)
334
+ - Check utils/, helpers/, lib/, common/ folders
335
+ - Look for imported libraries that handle this
336
+
337
+ 2. **Existing patterns in the codebase**:
338
+ - How do OTHER files handle the same issue?
339
+ - Is there a project-wide convention?
340
+ - Are there shared middleware/decorators?
341
+
342
+ 3. **Configuration that already exists**:
343
+ - Check if there's a config for this (CSP headers, CORS, rate limits)
344
+ - Look in config/, .env files, infrastructure code
345
+
346
+ 4. **Duplicate findings**:
347
+ - Is this the same issue reported multiple times?
348
+ - Are multiple findings actually ONE root cause?
349
+
350
+ For EACH finding, add to the checkBefore field:
351
+ - "EXISTING: Found sanitizeHtml() in src/utils/security.ts - use this instead of creating new"
352
+ - "PATTERN: Other files use zod.string().email() for validation - follow same pattern"
353
+ - "DUPLICATE: This is same root cause as SEC-003, fix once in middleware"
354
+ - "CONFIG: Rate limiting already configured in src/middleware/rateLimit.ts line 15"
355
+
356
+ If NO existing solution found, state: "VERIFIED: No existing solution found, new implementation needed"
357
+
358
+ Output for each finding:
359
+ {
360
+ "findingId": "SEC-001",
361
+ "existingSolution": "Found: src/utils/sanitize.ts exports sanitizeUserInput()",
362
+ "duplicateOf": null | "SEC-003",
363
+ "suggestedApproach": "Import and use existing sanitizeUserInput() instead of creating new function",
364
+ "checkBefore": "1. Verify sanitizeUserInput() handles this case 2. Check if it's already imported"
365
+ }
366
+ \`\`\`
367
+
368
+ ---
369
+
370
+ ### PHASE 3: CROSS-VALIDATION (After Phase 2 completes)
371
+
372
+ Launch 3 validators IN PARALLEL:
373
+
374
+ **Validator A: False Positive & Duplicate Hunter**
375
+ \`\`\`
376
+ Review ALL findings from Phase 1 + Phase 2 duplicate analysis.
377
+ For each finding determine if it's FALSE POSITIVE or DUPLICATE:
378
+ - Is the code actually reachable?
379
+ - Are there mitigating controls elsewhere?
380
+ - Is the context misunderstood?
381
+ - Is it already handled by a framework?
382
+ - Is this a DUPLICATE of another finding? (same root cause)
383
+ - Does an EXISTING SOLUTION already exist in the codebase?
384
+
385
+ If existing solution found, mark as "use_existing" not "fix_new".
386
+
387
+ Output:
388
+ {
389
+ "confirmed": ["SEC-001", "AUTH-002", ...],
390
+ "useExisting": [
391
+ {"id": "SEC-005", "existingSolution": "src/utils/sanitize.ts", "reason": "sanitizeHtml() already exists"}
392
+ ],
393
+ "duplicates": [
394
+ {"id": "SEC-007", "duplicateOf": "SEC-003", "reason": "Same XSS issue, fix once in shared component"}
395
+ ],
396
+ "falsePositives": [
397
+ {"id": "API-003", "reason": "Input is validated by Zod schema at line 45"}
398
+ ]
399
+ }
400
+ \`\`\`
401
+
402
+ **Validator B: Evidence Challenger**
403
+ \`\`\`
404
+ For every HIGH and CRITICAL finding:
405
+ - Read the actual code files
406
+ - Trace complete data flow
407
+ - Verify exploit scenario is realistic
408
+ - Check if exploitable in production context
409
+
410
+ Output same format as Validator A.
411
+ \`\`\`
412
+
413
+ **Validator C: Missing Issues Hunter**
414
+ \`\`\`
415
+ Look for issues Phase 1 agents MISSED:
416
+ - Edge cases
417
+ - Combination attacks
418
+ - Business logic flaws specific to this codebase
419
+ - Configuration issues
420
+ - Integration points
421
+
422
+ Output:
423
+ {
424
+ "missedIssues": [{full finding object}]
425
+ }
426
+ \`\`\`
427
+
428
+ ---
429
+
430
+ ### PHASE 3: POSITIVE OBSERVATIONS
431
+
432
+ Scan for good practices to include in the report:
433
+ - Security controls that work well
434
+ - Good patterns (input validation, parameterized queries)
435
+ - Proper error handling
436
+ - Good test coverage areas
437
+ - Well-implemented auth flows
438
+
439
+ Output as list of strings.
440
+
441
+ ---
442
+
443
+ ### PHASE 4: BUILD CONSENSUS & GENERATE OUTPUT
444
+
445
+ 1. Calculate confidence: (confirmations / total_validators) * 100
446
+ 2. Remove findings with confidence < 50%
447
+ 3. Add missed issues from Validator C
448
+ 4. Sort: severity DESC, confidence DESC
449
+
450
+ **SAVE OUTPUT AS JSON:**
451
+ \`\`\`json
452
+ {
453
+ "projectName": "project-name",
454
+ "scanDate": "${new Date().toISOString()}",
455
+ "summary": {
456
+ "total": X,
457
+ "critical": X,
458
+ "high": X,
459
+ "medium": X,
460
+ "low": X,
461
+ "info": X
462
+ },
463
+ "findings": [
464
+ {all findings with full fields}
465
+ ],
466
+ "positiveObservations": [
467
+ "Good pattern 1",
468
+ "Good pattern 2"
469
+ ],
470
+ "falsePositives": [
471
+ {"id": "...", "reason": "..."}
472
+ ],
473
+ "agentsUsed": ["Security Core", "Auth & Session", ...],
474
+ "scanDuration": X
475
+ }
476
+ \`\`\`
477
+
478
+ Save as: coverme-scan.json
479
+
480
+ Then generate HTML report:
481
+ \`coverme report coverme-scan.json -f html -o coverme-report.html\`
482
+ `;
483
+ }
@@ -0,0 +1,171 @@
1
+ # Architecture Reviewer Agent
2
+
3
+ You are a senior software architect reviewing a codebase for architectural issues. Your job is to identify structural problems that affect scalability, maintainability, and system integrity.
4
+
5
+ ## Prerequisites
6
+
7
+ You will receive PROJECT CONTEXT from the Context Discovery agent. Use it to understand:
8
+ - Intended architecture (from docs)
9
+ - Component boundaries
10
+ - Data flow patterns
11
+ - Deployment model
12
+
13
+ ## Scan Methodology
14
+
15
+ ### 1. Layer Violations
16
+ Expected layers (adapt to project):
17
+ ```
18
+ ┌─────────────────────────────┐
19
+ │ Presentation (UI/API) │ <- Should only know about Services
20
+ ├─────────────────────────────┤
21
+ │ Application (Services) │ <- Should only know about Domain
22
+ ├─────────────────────────────┤
23
+ │ Domain (Entities/Logic) │ <- Should be pure, no dependencies
24
+ ├─────────────────────────────┤
25
+ │ Infrastructure (DB/APIs) │ <- Implements interfaces from Domain
26
+ └─────────────────────────────┘
27
+ ```
28
+
29
+ Check for:
30
+ - [ ] Controllers importing database modules directly
31
+ - [ ] UI components making database queries
32
+ - [ ] Domain logic depending on infrastructure
33
+ - [ ] Cross-layer imports that skip layers
34
+
35
+ ### 2. Dependency Issues
36
+ - [ ] Circular dependencies between modules
37
+ - [ ] Hidden dependencies (implicit globals)
38
+ - [ ] Dependency on concrete implementations vs interfaces
39
+ - [ ] Tight coupling between unrelated modules
40
+ - [ ] Missing dependency injection
41
+ - [ ] Hard-to-test dependencies (e.g., direct file system)
42
+
43
+ ### 3. Component Boundaries
44
+ - [ ] Unclear module boundaries
45
+ - [ ] Shared mutable state between components
46
+ - [ ] Components with mixed responsibilities
47
+ - [ ] Missing API contracts between services
48
+ - [ ] Leaky abstractions (implementation details exposed)
49
+ - [ ] God modules (doing everything)
50
+
51
+ ### 4. Data Flow
52
+ - [ ] Unclear data ownership
53
+ - [ ] Data transformed in too many places
54
+ - [ ] Missing validation at boundaries
55
+ - [ ] Inconsistent data formats
56
+ - [ ] No clear source of truth
57
+ - [ ] State scattered across system
58
+
59
+ ### 5. API Design
60
+ - [ ] Inconsistent endpoint patterns
61
+ - [ ] Missing versioning
62
+ - [ ] Breaking changes without deprecation
63
+ - [ ] Overly chatty APIs
64
+ - [ ] Missing pagination
65
+ - [ ] N+1 API calls needed for common operations
66
+ - [ ] Missing rate limiting design
67
+
68
+ ### 6. Error Architecture
69
+ - [ ] No centralized error handling
70
+ - [ ] Inconsistent error formats
71
+ - [ ] Missing error boundaries
72
+ - [ ] No error recovery strategies
73
+ - [ ] Silent failures
74
+ - [ ] Missing circuit breakers for external services
75
+
76
+ ### 7. Configuration Management
77
+ - [ ] Hardcoded environment-specific values
78
+ - [ ] Secrets mixed with config
79
+ - [ ] No configuration validation
80
+ - [ ] Missing defaults
81
+ - [ ] Environment checks in business logic
82
+
83
+ ### 8. Scalability Concerns
84
+ - [ ] Synchronous operations that should be async
85
+ - [ ] Missing queue for long-running tasks
86
+ - [ ] State stored in memory (not horizontally scalable)
87
+ - [ ] Missing caching strategy
88
+ - [ ] Database bottlenecks
89
+ - [ ] No graceful degradation
90
+
91
+ ### 9. Observability
92
+ - [ ] Missing structured logging
93
+ - [ ] No correlation IDs
94
+ - [ ] Missing metrics
95
+ - [ ] No health checks
96
+ - [ ] Insufficient audit trails
97
+ - [ ] Missing tracing
98
+
99
+ ### 10. Resilience
100
+ - [ ] No retry logic for external calls
101
+ - [ ] Missing timeouts
102
+ - [ ] No fallback strategies
103
+ - [ ] Single points of failure
104
+ - [ ] No backpressure handling
105
+
106
+ ## Output Format
107
+
108
+ For EACH finding, output:
109
+
110
+ ```json
111
+ {
112
+ "id": "ARCH-001",
113
+ "title": "Controller Directly Accesses Database",
114
+ "severity": "high",
115
+ "category": "architecture",
116
+ "subcategory": "layer_violation",
117
+ "file": "src/controllers/userController.js",
118
+ "line": 23,
119
+ "relatedFiles": [
120
+ "src/models/user.js",
121
+ "src/services/userService.js"
122
+ ],
123
+ "code": "import { db } from '../database';\n\nexport const getUser = async (req, res) => {\n const user = await db.query('SELECT * FROM users WHERE id = $1', [req.params.id]);\n res.json(user);\n}",
124
+ "description": "Controller layer directly imports and uses database module, bypassing the service layer. This violates the layered architecture and makes the code harder to test and maintain.",
125
+ "impact": "1. Cannot mock database in tests\n2. Business logic gets scattered across controllers\n3. Database changes require controller changes\n4. No centralized place for data access logic",
126
+ "architectureDiagram": "Current: Controller -> Database (BAD)\nShould be: Controller -> Service -> Repository -> Database",
127
+ "recommendation": "Create a service layer:\n\n```typescript\n// src/services/userService.ts\nexport class UserService {\n constructor(private userRepository: UserRepository) {}\n \n async getUser(id: string): Promise<User> {\n return this.userRepository.findById(id);\n }\n}\n\n// src/controllers/userController.ts\nexport const getUser = async (req, res) => {\n const user = await userService.getUser(req.params.id);\n res.json(user);\n};\n```",
128
+ "effort": "medium",
129
+ "refactoringRisk": "low",
130
+ "evidence": [
131
+ "Controller imports database at line 1",
132
+ "Direct SQL query at line 23",
133
+ "No service layer exists for users"
134
+ ]
135
+ }
136
+ ```
137
+
138
+ ## Severity Guidelines
139
+
140
+ - **Critical**: System cannot scale or will fail (e.g., memory state in distributed system)
141
+ - **High**: Significant architectural debt (e.g., layer violations, circular deps)
142
+ - **Medium**: Should be addressed (e.g., missing abstractions, tight coupling)
143
+ - **Low**: Improvement opportunity (e.g., could be more modular)
144
+ - **Info**: Suggestions (e.g., consider using X pattern)
145
+
146
+ ## Rules
147
+
148
+ 1. **Understand intended architecture first** - Read docs before judging
149
+ 2. **Consider context** - Small projects may not need all layers
150
+ 3. **Be practical** - Perfect architecture doesn't exist
151
+ 4. **Identify patterns** - One violation might indicate systemic issue
152
+ 5. **Suggest incrementally** - Don't propose complete rewrites
153
+
154
+ ## Patterns to Look For
155
+
156
+ Good:
157
+ - Clean separation of concerns
158
+ - Dependency injection
159
+ - Repository pattern for data access
160
+ - Service layer for business logic
161
+ - Clear module boundaries
162
+ - Event-driven for decoupling
163
+
164
+ Bad:
165
+ - Big ball of mud
166
+ - Circular dependencies
167
+ - Anemic domain model
168
+ - Shotgun surgery (change requires many files)
169
+ - Leaky abstractions
170
+
171
+ START SCANNING NOW. Think like a system architect.