@sun-asterisk/impact-analyzer 1.0.4 → 1.0.6

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 (29) hide show
  1. package/.github/copilot-instructions.md +116 -0
  2. package/.github/prompts/README.md +91 -0
  3. package/.github/prompts/task-001-refactor.prompt.md +241 -0
  4. package/.specify/bugs/bug-001-database-detector.md +222 -0
  5. package/.specify/bugs/bug-002-database-detector.md +478 -0
  6. package/.specify/bugs/bug-003-multiline-detection.md +527 -0
  7. package/.specify/plans/architecture.md +186 -0
  8. package/.specify/specs/features/api-impact-detection.md +317 -0
  9. package/.specify/specs/features/component-impact-detection.md +263 -0
  10. package/.specify/specs/features/database-impact-detection.md +247 -0
  11. package/.specify/tasks/task-001-refactor-api-detector.md +284 -0
  12. package/.specify/tasks/task-002-database-detector.md +593 -0
  13. package/.specify/tasks/task-003-component-detector.md +0 -0
  14. package/.specify/tasks/task-004-report.md +484 -0
  15. package/README.md +13 -19
  16. package/core/detectors/database-detector.js +912 -0
  17. package/{modules → core}/detectors/endpoint-detector.js +11 -8
  18. package/{modules → core}/report-generator.js +102 -20
  19. package/core/utils/logger.js +12 -0
  20. package/index.js +6 -5
  21. package/package.json +1 -1
  22. package/modules/detectors/database-detector.js +0 -182
  23. /package/{modules → core}/change-detector.js +0 -0
  24. /package/{modules → core}/impact-analyzer.js +0 -0
  25. /package/{modules → core}/utils/ast-parser.js +0 -0
  26. /package/{modules → core}/utils/dependency-graph.js +0 -0
  27. /package/{modules → core}/utils/file-utils.js +0 -0
  28. /package/{modules → core}/utils/git-utils.js +0 -0
  29. /package/{modules → core}/utils/method-call-graph.js +0 -0
@@ -0,0 +1,247 @@
1
+ # Feature Spec: Database Impact Detection
2
+
3
+ ## 1. Overview
4
+
5
+ Identify database tables and models affected by code changes. This helps developers understand data layer impacts and plan database-related testing or migrations.
6
+
7
+ ## 2. User Story
8
+
9
+ > As a developer reviewing a pull request,
10
+ > I want to see which database tables are affected by the code changes,
11
+ > So that I can assess data integrity risks and plan database testing.
12
+
13
+ ## 3. Functional Requirements
14
+
15
+ ### FR-001: Detect Entity/Model Changes
16
+ - **Description**: Identify changes to ORM entity or model files
17
+ - **Patterns to Support**:
18
+ - TypeORM: `@Entity()` decorator
19
+ - Sequelize: `@Table()` decorator, `Model.init()`
20
+ - Mongoose: `mongoose.model()`, `new Schema()`
21
+ - Prisma: Changes to `schema.prisma`
22
+ - **Acceptance Criteria**:
23
+ - Detects new entity definitions
24
+ - Detects modified entity properties
25
+ - Detects deleted entities
26
+ - Detects relation changes
27
+
28
+ ### FR-002: Extract Table Names
29
+ - **Description**: Determine database table name from entity definition
30
+ - **Sources**:
31
+ - Explicit table name in decorator: `@Entity('users')`
32
+ - Decorator options: `@Entity({ name: 'users' })`
33
+ - Class name conversion (PascalCase → snake_case)
34
+ - Sequelize tableName option
35
+ - Mongoose collection name
36
+ - **Acceptance Criteria**:
37
+ - Correctly extracts explicit table names
38
+ - Correctly converts class names when not specified
39
+ - Handles custom naming strategies
40
+
41
+ ### FR-003: Detect Repository/DAO Changes
42
+ - **Description**: Find changes to data access layer code
43
+ - **Patterns to Support**:
44
+ - TypeORM Repository pattern
45
+ - Custom repository classes
46
+ - Query builder usage
47
+ - Raw SQL queries
48
+ - **Acceptance Criteria**:
49
+ - Identifies affected entity from repository
50
+ - Detects query method changes
51
+ - Identifies CRUD operations
52
+
53
+ ### FR-004: Classify Impact Type
54
+ - **Description**: Categorize the type of database impact
55
+ - **Categories**:
56
+ - `schema`: Column/property changes, new entities
57
+ - `query`: Repository method changes
58
+ - `relation`: Foreign key/relation changes
59
+ - `migration`: Migration file changes
60
+ - **Acceptance Criteria**:
61
+ - Correctly classifies schema changes
62
+ - Correctly classifies query-only changes
63
+ - Correctly classifies relation changes
64
+
65
+ ### FR-005: Identify CRUD Operations
66
+ - **Description**: Determine which database operations are affected
67
+ - **Operations**: SELECT, INSERT, UPDATE, DELETE
68
+ - **Detection Methods**:
69
+ - Method name analysis (find*, create*, update*, delete*)
70
+ - Query builder analysis
71
+ - Decorator analysis (@Query, etc.)
72
+ - **Acceptance Criteria**:
73
+ - Correctly identifies read operations
74
+ - Correctly identifies write operations
75
+ - Handles mixed operations
76
+
77
+ ### FR-006: Generate Database Report
78
+ - **Description**: Compile database impacts into structured report
79
+ - **Output**: `DatabaseImpact[]` array
80
+ - **Acceptance Criteria**:
81
+ - Includes table name and model name
82
+ - Includes impact classification
83
+ - Includes affected operations
84
+ - Deduplicates by table/impact type
85
+
86
+ ## 4. Non-Functional Requirements
87
+
88
+ ### NFR-001: Performance
89
+ - Analysis should add <5 seconds to total analysis time
90
+
91
+ ### NFR-002: Accuracy
92
+ - Should detect >95% of schema changes
93
+ - Should detect >85% of query changes
94
+
95
+ ## 5. Output Schema
96
+
97
+ ```javascript
98
+ /**
99
+ * @typedef {Object} DatabaseImpact
100
+ * @property {string} tableName - Database table name (snake_case)
101
+ * @property {string} modelName - Entity/Model class name
102
+ * @property {string} modelPath - File path to model definition
103
+ * @property {'schema'|'query'|'relation'|'migration'} impactType
104
+ * @property {('SELECT'|'INSERT'|'UPDATE'|'DELETE')[]} operations
105
+ * @property {FileChange} changeSource
106
+ * @property {'low'|'medium'|'high'|'critical'} severity
107
+ */
108
+ ```
109
+
110
+ ## 6. Severity Classification
111
+
112
+ | Severity | Criteria |
113
+ |----------|----------|
114
+ | Critical | Schema changes (columns, constraints) |
115
+ | High | Relation changes, DELETE operations |
116
+ | Medium | INSERT, UPDATE operations |
117
+ | Low | SELECT-only query changes |
118
+
119
+ ## 7. ORM Detection Patterns
120
+
121
+ ### TypeORM
122
+ ```javascript
123
+ // Entity detection
124
+ @Entity('users')
125
+ @Entity({ name: 'users' })
126
+ class User { }
127
+
128
+ // Column detection
129
+ @Column()
130
+ @PrimaryColumn()
131
+ @PrimaryGeneratedColumn()
132
+
133
+ // Relation detection
134
+ @OneToMany()
135
+ @ManyToOne()
136
+ @OneToOne()
137
+ @ManyToMany()
138
+
139
+ // Repository detection
140
+ class UserRepository extends Repository<User> { }
141
+ @EntityRepository(User)
142
+ ```
143
+
144
+ ### Sequelize
145
+ ```javascript
146
+ // Model detection
147
+ @Table({ tableName: 'users' })
148
+ class User extends Model { }
149
+
150
+ User.init({ }, { tableName: 'users' })
151
+
152
+ // Column detection
153
+ @Column
154
+ @PrimaryKey
155
+ @AutoIncrement
156
+
157
+ // Relation detection
158
+ @HasMany()
159
+ @BelongsTo()
160
+ @BelongsToMany()
161
+ ```
162
+
163
+ ### Mongoose
164
+ ```javascript
165
+ // Schema detection
166
+ const userSchema = new Schema({ })
167
+ mongoose.model('User', userSchema)
168
+
169
+ // Collection override
170
+ mongoose.model('User', userSchema, 'custom_users')
171
+ ```
172
+
173
+ ### Prisma
174
+ ```prisma
175
+ // Model detection in schema. prisma
176
+ model User {
177
+ id Int @id @default(autoincrement())
178
+ email String @unique
179
+ posts Post[]
180
+ }
181
+ ```
182
+
183
+ ## 8. Test Scenarios
184
+
185
+ ### Scenario 1: Entity Column Change
186
+ - **Given**: A property in an entity class is modified
187
+ - **When**: Analysis runs
188
+ - **Then**: Impact type is "schema" with high severity
189
+
190
+ ### Scenario 2: New Relation Added
191
+ - **Given**: A new relation decorator is added
192
+ - **When**: Analysis runs
193
+ - **Then**: Impact type is "relation"
194
+
195
+ ### Scenario 3: Repository Query Change
196
+ - **Given**: A repository method is modified
197
+ - **When**: Analysis runs
198
+ - **Then**: Impact type is "query" with affected operations
199
+
200
+ ### Scenario 4: Prisma Schema Change
201
+ - **Given**: schema.prisma is modified
202
+ - **When**: Analysis runs
203
+ - **Then**: Affected models are detected
204
+
205
+ ## 9. Edge Cases
206
+
207
+ | Case | Expected Behavior |
208
+ |------|-------------------|
209
+ | No ORM detected | Return empty array |
210
+ | Dynamic table names | Log warning, use class name |
211
+ | Abstract entities | Skip, not mapped to table |
212
+ | Embedded entities | Include in parent entity impact |
213
+ | View entities | Mark as "view" in output |
214
+
215
+ ## 10. Example
216
+
217
+ ### Input
218
+ ```javascript
219
+ // Changed file: src/entities/user.entity. js
220
+ // Modified lines: 8-10
221
+
222
+ @Entity('users')
223
+ class User {
224
+ @Column()
225
+ email; // Line 8 - CHANGED
226
+
227
+ @Column({ nullable: true }) // Line 9 - ADDED
228
+ phone; // Line 10 - ADDED
229
+ }
230
+ ```
231
+
232
+ ### Expected Output
233
+ ```javascript
234
+ {
235
+ database: [
236
+ {
237
+ tableName: "users",
238
+ modelName: "User",
239
+ modelPath: "src/entities/user.entity.js",
240
+ impactType: "schema",
241
+ operations: ["SELECT", "INSERT", "UPDATE"],
242
+ changeSource: { path: "src/entities/user. entity.js", ... },
243
+ severity: "critical"
244
+ }
245
+ ]
246
+ }
247
+ ```
@@ -0,0 +1,284 @@
1
+ # Task 001: Refactor API Detector for Performance & Simplicity
2
+
3
+ **Status:** 📋 TODO
4
+ **Priority:** 🔴 HIGH
5
+ **Assignee:** AI Agent
6
+ **Created:** 2025-12-25
7
+
8
+ ---
9
+
10
+ ## 📝 Overview
11
+
12
+ Refactor API detector to use `core/` folder structure, optimize performance, remove unused code, and improve logging with verbose mode.
13
+
14
+ ## 🎯 Goals
15
+
16
+ 1. **Migrate from `modules/` to `core/`** - Use consistent folder structure
17
+ 2. **Optimize Performance** - Remove unused functions, improve call graph traversal
18
+ 3. **Simplify Documentation** - Clear docs for AI code generation
19
+ 4. **Improve Logging** - Add verbose mode with clear, contextual logs
20
+
21
+ ## 📋 Tasks
22
+
23
+ ### 1. Folder Structure Migration
24
+
25
+ **Current (if using modules):**
26
+ ```
27
+ modules/
28
+ ├── api-detector.js
29
+ ├── call-graph-builder.js
30
+ └── utils.js
31
+ ```
32
+
33
+ **Target:**
34
+ ```
35
+ core/
36
+ ├── detectors/
37
+ │ └── endpoint-detector.js # API impact detection
38
+ └── utils/
39
+ ├── method-call-graph.js # Call graph building
40
+ └── ast-parser.js # AST parsing utilities
41
+ ```
42
+
43
+ **Action Items:**
44
+ - [ ] Move API detector logic to `core/detectors/endpoint-detector.js`
45
+ - [ ] Move call graph logic to `core/utils/method-call-graph.js`
46
+ - [ ] Update all imports to reference new paths
47
+ - [ ] Remove old `modules/` folder references
48
+
49
+ ### 2. Performance Optimization
50
+
51
+ **Remove Unused Functions:**
52
+ - [ ] Audit all exported functions - remove if not called
53
+ - [ ] Remove debug functions not used in production
54
+ - [ ] Remove duplicate utility functions
55
+ - [ ] Consolidate similar AST traversal logic
56
+
57
+ **Optimize Call Graph Traversal:**
58
+ - [ ] Use Set for visited nodes (avoid array lookups)
59
+ - [ ] Add max depth limit (default: 10 levels)
60
+ - [ ] Early return when endpoint found
61
+ - [ ] Cache decorator lookups per method
62
+
63
+ **Example Optimization:**
64
+ ```javascript
65
+ // Before: Array lookup O(n)
66
+ if (visited.includes(method)) return;
67
+
68
+ // After: Set lookup O(1)
69
+ if (visited.has(method)) return;
70
+ ```
71
+
72
+ **Optimize AST Parsing:**
73
+ - [ ] Parse files only once, cache results
74
+ - [ ] Skip node_modules and test files
75
+ - [ ] Use ts-morph's built-in filters
76
+
77
+ ### 3. Code Simplification
78
+
79
+ **Single Responsibility:**
80
+ - [ ] `endpoint-detector.js` - Only finds affected endpoints
81
+ - [ ] `method-call-graph.js` - Only builds call graphs
82
+ - [ ] `ast-parser.js` - Only parses AST and extracts symbols
83
+
84
+ **Remove Complex Logic:**
85
+ - [ ] Remove async command/queue detection (move to separate detector if needed)
86
+ - [ ] Focus on synchronous flow: Service → Controller → Endpoint
87
+ - [ ] Remove SNS/SQS specific logic (too specific)
88
+
89
+ **Simplified Algorithm:**
90
+ ```javascript
91
+ // core/detectors/endpoint-detector.js
92
+ export function findAffectedEndpoints(changedMethods, callGraph) {
93
+ const endpoints = [];
94
+
95
+ for (const method of changedMethods) {
96
+ const found = traverseToEndpoint(method, callGraph);
97
+ endpoints.push(...found);
98
+ }
99
+
100
+ return endpoints;
101
+ }
102
+
103
+ function traverseToEndpoint(method, callGraph, visited = new Set(), depth = 0) {
104
+ if (depth > 10 || visited.has(method)) return [];
105
+ visited.add(method);
106
+
107
+ // Check if endpoint
108
+ if (isHttpEndpoint(method)) {
109
+ return [extractEndpointInfo(method)];
110
+ }
111
+
112
+ // Traverse callers
113
+ const endpoints = [];
114
+ const callers = callGraph.getCallers(method);
115
+
116
+ for (const caller of callers) {
117
+ const found = traverseToEndpoint(caller, callGraph, visited, depth + 1);
118
+ endpoints.push(...found);
119
+ }
120
+
121
+ return endpoints;
122
+ }
123
+ ```
124
+
125
+ ### 4. Logging with Verbose Mode
126
+
127
+ **Add Verbose Flag:**
128
+ ```javascript
129
+ // Pass verbose option from CLI
130
+ const verbose = process.env.VERBOSE === 'true' || options.verbose;
131
+ ```
132
+
133
+ **Logging Levels:**
134
+
135
+ **Normal Mode (default):**
136
+ - [ ] Log only essential info: Start, Progress, Results
137
+ - [ ] No internal details
138
+ - [ ] Clean output for CI/CD
139
+
140
+ ```javascript
141
+ console.log('🔍 Analyzing API impacts...');
142
+ console.log('📡 Found 3 affected endpoints');
143
+ ```
144
+
145
+ **Verbose Mode (`--verbose`):**
146
+ - [ ] Log each step of traversal
147
+ - [ ] Show which methods are visited
148
+ - [ ] Display decorator information
149
+ - [ ] Show performance metrics
150
+
151
+ ```javascript
152
+ if (verbose) {
153
+ console.log(`[API Detector] Starting traversal from: ${method.name}`);
154
+ console.log(`[API Detector] Visiting caller: ${caller.name} (depth: ${depth})`);
155
+ console.log(`[API Detector] Found endpoint: ${httpMethod} ${path}`);
156
+ console.log(`[API Detector] Completed in ${duration}ms`);
157
+ }
158
+ ```
159
+
160
+ **Implementation Pattern:**
161
+ ```javascript
162
+ // core/utils/logger.js
163
+ export function createLogger(verbose = false) {
164
+ return {
165
+ info: (msg) => console.log(msg),
166
+ debug: (msg) => verbose && console.log(`[DEBUG] ${msg}`),
167
+ verbose: (component, msg) => verbose && console.log(`[${component}] ${msg}`)
168
+ };
169
+ }
170
+
171
+ // Usage in endpoint-detector.js
172
+ import { createLogger } from '../utils/logger.js';
173
+
174
+ export function findAffectedEndpoints(methods, callGraph, options = {}) {
175
+ const logger = createLogger(options.verbose);
176
+
177
+ logger.info('🔍 Analyzing API impacts...');
178
+ logger.verbose('EndpointDetector', `Processing ${methods.length} changed methods`);
179
+
180
+ for (const method of methods) {
181
+ logger.verbose('EndpointDetector', `Traversing from: ${method.name}`);
182
+ // ... detection logic
183
+ }
184
+
185
+ logger.info(`📡 Found ${endpoints.length} affected endpoints`);
186
+ return endpoints;
187
+ }
188
+ ```
189
+
190
+ ### 5. Documentation Updates
191
+
192
+ **File Headers:**
193
+ ```javascript
194
+ /**
195
+ * @file endpoint-detector.js
196
+ * @description Detects API endpoints affected by code changes via call graph traversal
197
+ *
198
+ * Algorithm:
199
+ * 1. Start from changed method
200
+ * 2. Traverse upward through callers
201
+ * 3. Stop when HTTP decorator found
202
+ * 4. Extract endpoint info (method, path)
203
+ *
204
+ * @example
205
+ * const endpoints = findAffectedEndpoints(changedMethods, callGraph);
206
+ * // Returns: [{ method: 'GET', path: '/users/:id', ... }]
207
+ */
208
+ ```
209
+
210
+ **Function JSDoc:**
211
+ ```javascript
212
+ /**
213
+ * Find API endpoints affected by changed methods
214
+ * @param {Array<string>} changedMethods - List of changed method names
215
+ * @param {CallGraph} callGraph - Method call graph with caller/callee relationships
216
+ * @param {Object} options - Options { verbose: boolean }
217
+ * @returns {Array<Endpoint>} List of affected endpoints
218
+ */
219
+ export function findAffectedEndpoints(changedMethods, callGraph, options = {}) {
220
+ // Implementation
221
+ }
222
+ ```
223
+
224
+ ## ✅ Acceptance Criteria
225
+
226
+ - [ ] All code moved to `core/` folder structure
227
+ - [ ] No references to old `modules/` folder
228
+ - [ ] Unused functions removed (document what was removed)
229
+ - [ ] Performance improved (measure before/after)
230
+ - [ ] Verbose mode works with `--verbose` flag
231
+ - [ ] Normal mode shows clean output
232
+ - [ ] All functions have JSDoc comments
233
+ - [ ] Code follows single responsibility principle
234
+ - [ ] Tests pass (if any exist)
235
+
236
+ ## 📊 Performance Targets
237
+
238
+ - [ ] Call graph traversal: < 100ms for 1000 methods
239
+ - [ ] Endpoint detection: < 50ms per changed method
240
+ - [ ] Memory usage: < 500MB for large codebases
241
+
242
+ ## 🧪 Testing
243
+
244
+ **Manual Test:**
245
+ ```bash
246
+ # Normal mode
247
+ node cli.js --input=src --base=origin/main
248
+
249
+ # Verbose mode
250
+ node cli.js --input=src --base=origin/main --verbose
251
+ ```
252
+
253
+ **Expected Output (Normal):**
254
+ ```
255
+ 🔍 Analyzing code changes...
256
+ 📊 Found 5 changed methods
257
+ 🔍 Analyzing API impacts...
258
+ 📡 Found 3 affected endpoints
259
+ ✅ Analysis complete
260
+ ```
261
+
262
+ **Expected Output (Verbose):**
263
+ ```
264
+ 🔍 Analyzing code changes...
265
+ [ChangeDetector] Parsing git diff: origin/main..HEAD
266
+ [ChangeDetector] Found 2 modified files
267
+ [ChangeDetector] Extracted 5 changed methods
268
+ 📊 Found 5 changed methods
269
+
270
+ 🔍 Analyzing API impacts...
271
+ [EndpointDetector] Processing 5 changed methods
272
+ [EndpointDetector] Traversing from: UserService.updateEmail
273
+ [EndpointDetector] Visiting caller: UserController.updateProfile (depth: 1)
274
+ [EndpointDetector] Found endpoint: PUT /users/:id
275
+ [EndpointDetector] Completed in 45ms
276
+ 📡 Found 3 affected endpoints
277
+ ✅ Analysis complete
278
+ ```
279
+
280
+ ## 📚 References
281
+
282
+ - API Impact Detection Spec: `.specify/specs/features/api-impact-detection.md`
283
+ - Architecture Doc: `.specify/plans/architecture.md`
284
+ - Code Rules: `.github/copilot-instructions.md`