claude-code-workflow 6.3.22 → 6.3.24

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 (42) hide show
  1. package/.claude/agents/issue-plan-agent.md +10 -5
  2. package/.claude/commands/issue/plan.md +1 -1
  3. package/.claude/skills/review-code/SKILL.md +170 -0
  4. package/.claude/skills/review-code/phases/actions/action-collect-context.md +139 -0
  5. package/.claude/skills/review-code/phases/actions/action-complete.md +115 -0
  6. package/.claude/skills/review-code/phases/actions/action-deep-review.md +302 -0
  7. package/.claude/skills/review-code/phases/actions/action-generate-report.md +263 -0
  8. package/.claude/skills/review-code/phases/actions/action-quick-scan.md +164 -0
  9. package/.claude/skills/review-code/phases/orchestrator.md +251 -0
  10. package/.claude/skills/review-code/phases/state-manager.md +752 -0
  11. package/.claude/skills/review-code/phases/state-schema.md +174 -0
  12. package/.claude/skills/review-code/specs/issue-classification.md +228 -0
  13. package/.claude/skills/review-code/specs/quality-standards.md +214 -0
  14. package/.claude/skills/review-code/specs/review-dimensions.md +337 -0
  15. package/.claude/skills/review-code/specs/rules/architecture-rules.json +63 -0
  16. package/.claude/skills/review-code/specs/rules/correctness-rules.json +60 -0
  17. package/.claude/skills/review-code/specs/rules/index.md +140 -0
  18. package/.claude/skills/review-code/specs/rules/performance-rules.json +59 -0
  19. package/.claude/skills/review-code/specs/rules/readability-rules.json +60 -0
  20. package/.claude/skills/review-code/specs/rules/security-rules.json +58 -0
  21. package/.claude/skills/review-code/specs/rules/testing-rules.json +59 -0
  22. package/.claude/skills/review-code/templates/issue-template.md +186 -0
  23. package/.claude/skills/review-code/templates/review-report.md +173 -0
  24. package/.claude/skills/skill-generator/SKILL.md +56 -17
  25. package/.claude/skills/skill-generator/templates/autonomous-orchestrator.md +10 -0
  26. package/.claude/skills/skill-generator/templates/sequential-phase.md +9 -0
  27. package/.claude/skills/skill-generator/templates/skill-md.md +84 -5
  28. package/.claude/workflows/cli-templates/schemas/solution-schema.json +3 -3
  29. package/ccw/src/templates/dashboard-js/views/issue-manager.js +8 -0
  30. package/package.json +1 -1
  31. package/.claude/skills/code-reviewer/README.md +0 -340
  32. package/.claude/skills/code-reviewer/SKILL.md +0 -308
  33. package/.claude/skills/code-reviewer/phases/01-code-discovery.md +0 -246
  34. package/.claude/skills/code-reviewer/phases/02-security-analysis.md +0 -442
  35. package/.claude/skills/code-reviewer/phases/03-best-practices-review.md +0 -36
  36. package/.claude/skills/code-reviewer/phases/04-report-generation.md +0 -278
  37. package/.claude/skills/code-reviewer/specs/best-practices-requirements.md +0 -346
  38. package/.claude/skills/code-reviewer/specs/quality-standards.md +0 -252
  39. package/.claude/skills/code-reviewer/specs/security-requirements.md +0 -243
  40. package/.claude/skills/code-reviewer/templates/best-practice-finding.md +0 -234
  41. package/.claude/skills/code-reviewer/templates/report-template.md +0 -316
  42. package/.claude/skills/code-reviewer/templates/security-finding.md +0 -161
@@ -0,0 +1,337 @@
1
+ # Review Dimensions
2
+
3
+ 代码审查维度定义和检查点规范。
4
+
5
+ ## When to Use
6
+
7
+ | Phase | Usage | Section |
8
+ |-------|-------|---------|
9
+ | action-deep-review | 获取维度检查规则 | All |
10
+ | action-generate-report | 维度名称映射 | Dimension Names |
11
+
12
+ ---
13
+
14
+ ## Dimension Overview
15
+
16
+ | Dimension | Weight | Focus | Key Indicators |
17
+ |-----------|--------|-------|----------------|
18
+ | **Correctness** | 25% | 功能正确性 | 边界条件、错误处理、类型安全 |
19
+ | **Security** | 25% | 安全风险 | 注入攻击、敏感数据、权限 |
20
+ | **Performance** | 15% | 执行效率 | 算法复杂度、资源使用 |
21
+ | **Readability** | 15% | 可维护性 | 命名、结构、注释 |
22
+ | **Testing** | 10% | 测试质量 | 覆盖率、边界测试 |
23
+ | **Architecture** | 10% | 架构一致性 | 分层、依赖、模式 |
24
+
25
+ ---
26
+
27
+ ## 1. Correctness (正确性)
28
+
29
+ ### 检查清单
30
+
31
+ - [ ] **边界条件处理**
32
+ - 空数组/空字符串
33
+ - Null/Undefined
34
+ - 数值边界 (0, 负数, MAX_INT)
35
+ - 集合边界 (首元素, 末元素)
36
+
37
+ - [ ] **错误处理**
38
+ - Try-catch 覆盖
39
+ - 错误不被静默吞掉
40
+ - 错误信息有意义
41
+ - 资源正确释放
42
+
43
+ - [ ] **类型安全**
44
+ - 类型转换正确
45
+ - 避免隐式转换
46
+ - TypeScript strict mode
47
+
48
+ - [ ] **逻辑完整性**
49
+ - If-else 分支完整
50
+ - Switch 有 default
51
+ - 循环终止条件正确
52
+
53
+ ### 常见问题模式
54
+
55
+ ```javascript
56
+ // ❌ 问题: 未检查 null
57
+ function getName(user) {
58
+ return user.name.toUpperCase(); // user 可能为 null
59
+ }
60
+
61
+ // ✅ 修复
62
+ function getName(user) {
63
+ return user?.name?.toUpperCase() ?? 'Unknown';
64
+ }
65
+
66
+ // ❌ 问题: 空 catch 块
67
+ try {
68
+ await fetchData();
69
+ } catch (e) {} // 错误被静默吞掉
70
+
71
+ // ✅ 修复
72
+ try {
73
+ await fetchData();
74
+ } catch (e) {
75
+ console.error('Failed to fetch data:', e);
76
+ throw e;
77
+ }
78
+ ```
79
+
80
+ ---
81
+
82
+ ## 2. Security (安全性)
83
+
84
+ ### 检查清单
85
+
86
+ - [ ] **注入防护**
87
+ - SQL 注入 (使用参数化查询)
88
+ - XSS (避免 innerHTML)
89
+ - 命令注入 (避免 exec)
90
+ - 路径遍历
91
+
92
+ - [ ] **认证授权**
93
+ - 权限检查完整
94
+ - Token 验证
95
+ - Session 管理
96
+
97
+ - [ ] **敏感数据**
98
+ - 无硬编码密钥
99
+ - 日志不含敏感信息
100
+ - 传输加密
101
+
102
+ - [ ] **依赖安全**
103
+ - 无已知漏洞依赖
104
+ - 版本锁定
105
+
106
+ ### 常见问题模式
107
+
108
+ ```javascript
109
+ // ❌ 问题: SQL 注入风险
110
+ const query = `SELECT * FROM users WHERE id = ${userId}`;
111
+
112
+ // ✅ 修复: 参数化查询
113
+ const query = `SELECT * FROM users WHERE id = ?`;
114
+ db.query(query, [userId]);
115
+
116
+ // ❌ 问题: XSS 风险
117
+ element.innerHTML = userInput;
118
+
119
+ // ✅ 修复
120
+ element.textContent = userInput;
121
+
122
+ // ❌ 问题: 硬编码密钥
123
+ const apiKey = 'sk-xxxxxxxxxxxx';
124
+
125
+ // ✅ 修复
126
+ const apiKey = process.env.API_KEY;
127
+ ```
128
+
129
+ ---
130
+
131
+ ## 3. Performance (性能)
132
+
133
+ ### 检查清单
134
+
135
+ - [ ] **算法复杂度**
136
+ - 避免 O(n²) 在大数据集
137
+ - 使用合适的数据结构
138
+ - 避免不必要的循环
139
+
140
+ - [ ] **I/O 效率**
141
+ - 批量操作 vs 循环单条
142
+ - 避免 N+1 查询
143
+ - 适当使用缓存
144
+
145
+ - [ ] **资源使用**
146
+ - 内存泄漏
147
+ - 连接池使用
148
+ - 大文件流式处理
149
+
150
+ - [ ] **异步处理**
151
+ - 并行 vs 串行
152
+ - Promise.all 使用
153
+ - 避免阻塞
154
+
155
+ ### 常见问题模式
156
+
157
+ ```javascript
158
+ // ❌ 问题: N+1 查询
159
+ for (const user of users) {
160
+ const posts = await db.query('SELECT * FROM posts WHERE user_id = ?', [user.id]);
161
+ }
162
+
163
+ // ✅ 修复: 批量查询
164
+ const userIds = users.map(u => u.id);
165
+ const posts = await db.query('SELECT * FROM posts WHERE user_id IN (?)', [userIds]);
166
+
167
+ // ❌ 问题: 串行执行可并行操作
168
+ const a = await fetchA();
169
+ const b = await fetchB();
170
+ const c = await fetchC();
171
+
172
+ // ✅ 修复: 并行执行
173
+ const [a, b, c] = await Promise.all([fetchA(), fetchB(), fetchC()]);
174
+ ```
175
+
176
+ ---
177
+
178
+ ## 4. Readability (可读性)
179
+
180
+ ### 检查清单
181
+
182
+ - [ ] **命名规范**
183
+ - 变量名见名知意
184
+ - 函数名表达动作
185
+ - 常量使用 UPPER_CASE
186
+ - 避免缩写和单字母
187
+
188
+ - [ ] **函数设计**
189
+ - 单一职责
190
+ - 长度 < 50 行
191
+ - 参数 < 5 个
192
+ - 嵌套 < 4 层
193
+
194
+ - [ ] **代码组织**
195
+ - 逻辑分组
196
+ - 空行分隔
197
+ - Import 顺序
198
+
199
+ - [ ] **注释质量**
200
+ - 解释 WHY 而非 WHAT
201
+ - 及时更新
202
+ - 无冗余注释
203
+
204
+ ### 常见问题模式
205
+
206
+ ```javascript
207
+ // ❌ 问题: 命名不清晰
208
+ const d = new Date();
209
+ const a = users.filter(x => x.s === 'active');
210
+
211
+ // ✅ 修复
212
+ const currentDate = new Date();
213
+ const activeUsers = users.filter(user => user.status === 'active');
214
+
215
+ // ❌ 问题: 函数过长、职责过多
216
+ function processOrder(order) {
217
+ // ... 200 行代码,包含验证、计算、保存、通知
218
+ }
219
+
220
+ // ✅ 修复: 拆分职责
221
+ function validateOrder(order) { /* ... */ }
222
+ function calculateTotal(order) { /* ... */ }
223
+ function saveOrder(order) { /* ... */ }
224
+ function notifyCustomer(order) { /* ... */ }
225
+ ```
226
+
227
+ ---
228
+
229
+ ## 5. Testing (测试)
230
+
231
+ ### 检查清单
232
+
233
+ - [ ] **测试覆盖**
234
+ - 核心逻辑有测试
235
+ - 边界条件有测试
236
+ - 错误路径有测试
237
+
238
+ - [ ] **测试质量**
239
+ - 测试独立
240
+ - 断言明确
241
+ - Mock 适度
242
+
243
+ - [ ] **测试可维护性**
244
+ - 命名清晰
245
+ - 结构统一
246
+ - 避免重复
247
+
248
+ ### 常见问题模式
249
+
250
+ ```javascript
251
+ // ❌ 问题: 测试不独立
252
+ let counter = 0;
253
+ test('increment', () => {
254
+ counter++; // 依赖外部状态
255
+ expect(counter).toBe(1);
256
+ });
257
+
258
+ // ✅ 修复: 每个测试独立
259
+ test('increment', () => {
260
+ const counter = new Counter();
261
+ counter.increment();
262
+ expect(counter.value).toBe(1);
263
+ });
264
+
265
+ // ❌ 问题: 缺少边界测试
266
+ test('divide', () => {
267
+ expect(divide(10, 2)).toBe(5);
268
+ });
269
+
270
+ // ✅ 修复: 包含边界情况
271
+ test('divide by zero throws', () => {
272
+ expect(() => divide(10, 0)).toThrow();
273
+ });
274
+ ```
275
+
276
+ ---
277
+
278
+ ## 6. Architecture (架构)
279
+
280
+ ### 检查清单
281
+
282
+ - [ ] **分层结构**
283
+ - 层次清晰
284
+ - 依赖方向正确
285
+ - 无循环依赖
286
+
287
+ - [ ] **模块化**
288
+ - 高内聚低耦合
289
+ - 接口定义清晰
290
+ - 职责单一
291
+
292
+ - [ ] **设计模式**
293
+ - 使用合适的模式
294
+ - 避免过度设计
295
+ - 遵循项目既有模式
296
+
297
+ ### 常见问题模式
298
+
299
+ ```javascript
300
+ // ❌ 问题: 层次混乱 (Controller 直接操作数据库)
301
+ class UserController {
302
+ async getUser(req, res) {
303
+ const user = await db.query('SELECT * FROM users WHERE id = ?', [req.params.id]);
304
+ res.json(user);
305
+ }
306
+ }
307
+
308
+ // ✅ 修复: 分层清晰
309
+ class UserController {
310
+ constructor(private userService: UserService) {}
311
+
312
+ async getUser(req, res) {
313
+ const user = await this.userService.findById(req.params.id);
314
+ res.json(user);
315
+ }
316
+ }
317
+
318
+ // ❌ 问题: 循环依赖
319
+ // moduleA.ts
320
+ import { funcB } from './moduleB';
321
+ // moduleB.ts
322
+ import { funcA } from './moduleA';
323
+
324
+ // ✅ 修复: 提取共享模块或使用依赖注入
325
+ ```
326
+
327
+ ---
328
+
329
+ ## Severity Mapping
330
+
331
+ | Severity | Criteria |
332
+ |----------|----------|
333
+ | **Critical** | 安全漏洞、数据损坏风险、崩溃风险 |
334
+ | **High** | 功能缺陷、性能严重问题、重要边界未处理 |
335
+ | **Medium** | 代码质量问题、可维护性问题 |
336
+ | **Low** | 风格问题、优化建议 |
337
+ | **Info** | 信息性建议、学习机会 |
@@ -0,0 +1,63 @@
1
+ {
2
+ "dimension": "architecture",
3
+ "prefix": "ARCH",
4
+ "description": "Rules for detecting architecture issues including coupling, layering, and design patterns",
5
+ "rules": [
6
+ {
7
+ "id": "circular-dependency",
8
+ "category": "dependency",
9
+ "severity": "high",
10
+ "pattern": "import\\s+.*from\\s+['\"]\\.\\..*['\"]",
11
+ "patternType": "regex",
12
+ "contextPattern": "export.*import.*from.*same-module",
13
+ "description": "Potential circular dependency detected. Circular imports cause initialization issues and tight coupling",
14
+ "recommendation": "Extract shared code to a separate module, use dependency injection, or restructure the dependency graph",
15
+ "fixExample": "// Before - A imports B, B imports A\n// moduleA.ts\nimport { funcB } from './moduleB';\nexport const funcA = () => funcB();\n\n// moduleB.ts\nimport { funcA } from './moduleA'; // circular!\n\n// After - extract shared logic\n// shared.ts\nexport const sharedLogic = () => { ... };\n\n// moduleA.ts\nimport { sharedLogic } from './shared';"
16
+ },
17
+ {
18
+ "id": "god-class",
19
+ "category": "single-responsibility",
20
+ "severity": "high",
21
+ "pattern": "class\\s+\\w+\\s*\\{",
22
+ "patternType": "regex",
23
+ "methodThreshold": 15,
24
+ "lineThreshold": 300,
25
+ "description": "Class with too many methods or lines violates single responsibility principle",
26
+ "recommendation": "Split into smaller, focused classes. Each class should have one reason to change",
27
+ "fixExample": "// Before - UserManager handles everything\nclass UserManager {\n createUser() { ... }\n updateUser() { ... }\n sendEmail() { ... }\n generateReport() { ... }\n validatePassword() { ... }\n}\n\n// After - separated concerns\nclass UserRepository { create, update, delete }\nclass EmailService { sendEmail }\nclass ReportGenerator { generate }\nclass PasswordValidator { validate }"
28
+ },
29
+ {
30
+ "id": "layer-violation",
31
+ "category": "layering",
32
+ "severity": "high",
33
+ "pattern": "import.*(?:repository|database|sql|prisma|mongoose).*from",
34
+ "patternType": "regex",
35
+ "contextPath": ["controller", "handler", "route", "component"],
36
+ "description": "Direct database access from presentation layer violates layered architecture",
37
+ "recommendation": "Access data through service/use-case layer. Keep controllers thin and delegate to services",
38
+ "fixExample": "// Before - controller accesses DB directly\nimport { prisma } from './database';\nconst getUsers = async () => prisma.user.findMany();\n\n// After - use service layer\nimport { userService } from './services';\nconst getUsers = async () => userService.getAll();"
39
+ },
40
+ {
41
+ "id": "missing-interface",
42
+ "category": "abstraction",
43
+ "severity": "medium",
44
+ "pattern": "new\\s+\\w+Service\\(|new\\s+\\w+Repository\\(",
45
+ "patternType": "regex",
46
+ "negativePatterns": ["interface", "implements", "inject"],
47
+ "description": "Direct instantiation of services/repositories creates tight coupling",
48
+ "recommendation": "Define interfaces and use dependency injection for loose coupling and testability",
49
+ "fixExample": "// Before - tight coupling\nclass OrderService {\n private repo = new OrderRepository();\n}\n\n// After - loose coupling\ninterface IOrderRepository {\n findById(id: string): Promise<Order>;\n}\n\nclass OrderService {\n constructor(private repo: IOrderRepository) {}\n}"
50
+ },
51
+ {
52
+ "id": "mixed-concerns",
53
+ "category": "separation-of-concerns",
54
+ "severity": "medium",
55
+ "pattern": "fetch\\s*\\(|axios\\.|http\\.",
56
+ "patternType": "regex",
57
+ "contextPath": ["component", "view", "page"],
58
+ "description": "Network calls in UI components mix data fetching with presentation",
59
+ "recommendation": "Extract data fetching to hooks, services, or state management layer",
60
+ "fixExample": "// Before - fetch in component\nfunction UserList() {\n const [users, setUsers] = useState([]);\n useEffect(() => {\n fetch('/api/users').then(r => r.json()).then(setUsers);\n }, []);\n}\n\n// After - custom hook\nfunction useUsers() {\n return useQuery('users', () => userService.getAll());\n}\n\nfunction UserList() {\n const { data: users } = useUsers();\n}"
61
+ }
62
+ ]
63
+ }
@@ -0,0 +1,60 @@
1
+ {
2
+ "dimension": "correctness",
3
+ "prefix": "CORR",
4
+ "description": "Rules for detecting logical errors, null handling, and error handling issues",
5
+ "rules": [
6
+ {
7
+ "id": "null-check",
8
+ "category": "null-check",
9
+ "severity": "high",
10
+ "pattern": "\\w+\\.\\w+(?!\\.?\\?)",
11
+ "patternType": "regex",
12
+ "negativePatterns": ["\\?\\.", "if\\s*\\(", "!==?\\s*null", "!==?\\s*undefined", "&&\\s*\\w+\\."],
13
+ "description": "Property access without null/undefined check may cause runtime errors",
14
+ "recommendation": "Add null/undefined check before accessing properties using optional chaining or conditional checks",
15
+ "fixExample": "// Before\nobj.property.value\n\n// After\nobj?.property?.value\n// or\nif (obj && obj.property) { obj.property.value }"
16
+ },
17
+ {
18
+ "id": "empty-catch",
19
+ "category": "empty-catch",
20
+ "severity": "high",
21
+ "pattern": "catch\\s*\\([^)]*\\)\\s*\\{\\s*\\}",
22
+ "patternType": "regex",
23
+ "description": "Empty catch block silently swallows errors, hiding bugs and making debugging difficult",
24
+ "recommendation": "Log the error, rethrow it, or handle it appropriately. Never silently ignore exceptions",
25
+ "fixExample": "// Before\ncatch (e) { }\n\n// After\ncatch (e) {\n console.error('Operation failed:', e);\n throw e; // or handle appropriately\n}"
26
+ },
27
+ {
28
+ "id": "unreachable-code",
29
+ "category": "unreachable-code",
30
+ "severity": "medium",
31
+ "pattern": "return\\s+[^;]+;\\s*\\n\\s*[^}\\s]",
32
+ "patternType": "regex",
33
+ "description": "Code after return statement is unreachable and will never execute",
34
+ "recommendation": "Remove unreachable code or restructure the logic to ensure all code paths are accessible",
35
+ "fixExample": "// Before\nfunction example() {\n return value;\n doSomething(); // unreachable\n}\n\n// After\nfunction example() {\n doSomething();\n return value;\n}"
36
+ },
37
+ {
38
+ "id": "array-index-unchecked",
39
+ "category": "boundary-check",
40
+ "severity": "high",
41
+ "pattern": "\\[\\d+\\]|\\[\\w+\\](?!\\s*[!=<>])",
42
+ "patternType": "regex",
43
+ "negativePatterns": ["\\.length", "Array\\.isArray", "\\?.\\["],
44
+ "description": "Array index access without boundary check may cause undefined access or out-of-bounds errors",
45
+ "recommendation": "Check array length or use optional chaining before accessing array elements",
46
+ "fixExample": "// Before\nconst item = arr[index];\n\n// After\nconst item = arr?.[index];\n// or\nconst item = index < arr.length ? arr[index] : defaultValue;"
47
+ },
48
+ {
49
+ "id": "comparison-type-coercion",
50
+ "category": "type-safety",
51
+ "severity": "medium",
52
+ "pattern": "[^!=]==[^=]|[^!]==[^=]",
53
+ "patternType": "regex",
54
+ "negativePatterns": ["===", "!=="],
55
+ "description": "Using == instead of === can lead to unexpected type coercion",
56
+ "recommendation": "Use strict equality (===) to avoid implicit type conversion",
57
+ "fixExample": "// Before\nif (value == null)\nif (a == b)\n\n// After\nif (value === null || value === undefined)\nif (a === b)"
58
+ }
59
+ ]
60
+ }
@@ -0,0 +1,140 @@
1
+ # Code Review Rules Index
2
+
3
+ This directory contains externalized review rules for the multi-dimensional code review skill.
4
+
5
+ ## Directory Structure
6
+
7
+ ```
8
+ rules/
9
+ ├── index.md # This file
10
+ ├── correctness-rules.json # CORR - Logic and error handling
11
+ ├── security-rules.json # SEC - Security vulnerabilities
12
+ ├── performance-rules.json # PERF - Performance issues
13
+ ├── readability-rules.json # READ - Code clarity
14
+ ├── testing-rules.json # TEST - Test quality
15
+ └── architecture-rules.json # ARCH - Design patterns
16
+ ```
17
+
18
+ ## Rule File Schema
19
+
20
+ Each rule file follows this JSON schema:
21
+
22
+ ```json
23
+ {
24
+ "dimension": "string", // Dimension identifier
25
+ "prefix": "string", // Finding ID prefix (4 chars)
26
+ "description": "string", // Dimension description
27
+ "rules": [
28
+ {
29
+ "id": "string", // Unique rule identifier
30
+ "category": "string", // Rule category within dimension
31
+ "severity": "critical|high|medium|low",
32
+ "pattern": "string", // Detection pattern
33
+ "patternType": "regex|includes|ast",
34
+ "negativePatterns": [], // Patterns that exclude matches
35
+ "caseInsensitive": false, // For regex patterns
36
+ "contextPattern": "", // Additional context requirement
37
+ "contextPath": [], // Path patterns for context
38
+ "lineThreshold": 0, // For size-based rules
39
+ "methodThreshold": 0, // For complexity rules
40
+ "description": "string", // Issue description
41
+ "recommendation": "string", // How to fix
42
+ "fixExample": "string" // Code example
43
+ }
44
+ ]
45
+ }
46
+ ```
47
+
48
+ ## Dimension Summary
49
+
50
+ | Dimension | Prefix | Rules | Focus Areas |
51
+ |-----------|--------|-------|-------------|
52
+ | Correctness | CORR | 5 | Null checks, error handling, type safety |
53
+ | Security | SEC | 5 | XSS, injection, secrets, crypto |
54
+ | Performance | PERF | 5 | Complexity, I/O, memory leaks |
55
+ | Readability | READ | 5 | Naming, length, nesting, magic values |
56
+ | Testing | TEST | 5 | Assertions, coverage, mock quality |
57
+ | Architecture | ARCH | 5 | Dependencies, layering, coupling |
58
+
59
+ ## Severity Levels
60
+
61
+ | Severity | Description | Action |
62
+ |----------|-------------|--------|
63
+ | **critical** | Security vulnerability or data loss risk | Must fix before release |
64
+ | **high** | Bug or significant quality issue | Fix in current sprint |
65
+ | **medium** | Code smell or maintainability concern | Plan to address |
66
+ | **low** | Style or minor improvement | Address when convenient |
67
+
68
+ ## Pattern Types
69
+
70
+ ### regex
71
+ Standard regular expression pattern. Supports flags via `caseInsensitive`.
72
+
73
+ ```json
74
+ {
75
+ "pattern": "catch\\s*\\([^)]*\\)\\s*\\{\\s*\\}",
76
+ "patternType": "regex"
77
+ }
78
+ ```
79
+
80
+ ### includes
81
+ Simple substring match. Faster than regex for literal strings.
82
+
83
+ ```json
84
+ {
85
+ "pattern": "innerHTML",
86
+ "patternType": "includes"
87
+ }
88
+ ```
89
+
90
+ ### ast (Future)
91
+ AST-based detection for complex structural patterns.
92
+
93
+ ```json
94
+ {
95
+ "pattern": "function[params>5]",
96
+ "patternType": "ast"
97
+ }
98
+ ```
99
+
100
+ ## Usage in Code
101
+
102
+ ```javascript
103
+ // Load rules
104
+ const rules = JSON.parse(fs.readFileSync('correctness-rules.json'));
105
+
106
+ // Apply rules
107
+ for (const rule of rules.rules) {
108
+ const matches = detectByPattern(content, rule.pattern, rule.patternType);
109
+ for (const match of matches) {
110
+ // Check negative patterns
111
+ if (rule.negativePatterns?.some(np => match.context.includes(np))) {
112
+ continue;
113
+ }
114
+ findings.push({
115
+ id: `${rules.prefix}-${counter++}`,
116
+ severity: rule.severity,
117
+ category: rule.category,
118
+ description: rule.description,
119
+ recommendation: rule.recommendation,
120
+ fixExample: rule.fixExample
121
+ });
122
+ }
123
+ }
124
+ ```
125
+
126
+ ## Adding New Rules
127
+
128
+ 1. Identify the appropriate dimension
129
+ 2. Create rule with unique `id` within dimension
130
+ 3. Choose appropriate `patternType`
131
+ 4. Provide clear `description` and `recommendation`
132
+ 5. Include practical `fixExample`
133
+ 6. Test against sample code
134
+
135
+ ## Rule Maintenance
136
+
137
+ - Review rules quarterly for relevance
138
+ - Update patterns as language/framework evolves
139
+ - Track false positive rates
140
+ - Collect feedback from users
@@ -0,0 +1,59 @@
1
+ {
2
+ "dimension": "performance",
3
+ "prefix": "PERF",
4
+ "description": "Rules for detecting performance issues including inefficient algorithms, memory leaks, and resource waste",
5
+ "rules": [
6
+ {
7
+ "id": "nested-loops",
8
+ "category": "algorithm-complexity",
9
+ "severity": "medium",
10
+ "pattern": "for\\s*\\([^)]+\\)\\s*\\{[^}]*for\\s*\\([^)]+\\)|forEach\\s*\\([^)]+\\)\\s*\\{[^}]*forEach",
11
+ "patternType": "regex",
12
+ "description": "Nested loops may indicate O(n^2) or worse complexity. Consider if this can be optimized",
13
+ "recommendation": "Use Map/Set for O(1) lookups, break early when possible, or restructure the algorithm",
14
+ "fixExample": "// Before - O(n^2)\nfor (const a of listA) {\n for (const b of listB) {\n if (a.id === b.id) { ... }\n }\n}\n\n// After - O(n)\nconst bMap = new Map(listB.map(b => [b.id, b]));\nfor (const a of listA) {\n const b = bMap.get(a.id);\n if (b) { ... }\n}"
15
+ },
16
+ {
17
+ "id": "array-in-loop",
18
+ "category": "inefficient-operation",
19
+ "severity": "high",
20
+ "pattern": "\\.includes\\s*\\(|indexOf\\s*\\(|find\\s*\\(",
21
+ "patternType": "includes",
22
+ "contextPattern": "for|while|forEach|map|filter|reduce",
23
+ "description": "Array search methods inside loops cause O(n*m) complexity. Consider using Set or Map",
24
+ "recommendation": "Convert array to Set before the loop for O(1) lookups",
25
+ "fixExample": "// Before - O(n*m)\nfor (const item of items) {\n if (existingIds.includes(item.id)) { ... }\n}\n\n// After - O(n)\nconst idSet = new Set(existingIds);\nfor (const item of items) {\n if (idSet.has(item.id)) { ... }\n}"
26
+ },
27
+ {
28
+ "id": "synchronous-io",
29
+ "category": "io-efficiency",
30
+ "severity": "high",
31
+ "pattern": "readFileSync|writeFileSync|execSync|spawnSync",
32
+ "patternType": "includes",
33
+ "description": "Synchronous I/O blocks the event loop and degrades application responsiveness",
34
+ "recommendation": "Use async versions (readFile, writeFile) or Promise-based APIs",
35
+ "fixExample": "// Before\nconst data = fs.readFileSync(path);\n\n// After\nconst data = await fs.promises.readFile(path);\n// or\nfs.readFile(path, (err, data) => { ... });"
36
+ },
37
+ {
38
+ "id": "memory-leak-closure",
39
+ "category": "memory-leak",
40
+ "severity": "high",
41
+ "pattern": "addEventListener\\s*\\(|setInterval\\s*\\(|setTimeout\\s*\\(",
42
+ "patternType": "regex",
43
+ "negativePatterns": ["removeEventListener", "clearInterval", "clearTimeout"],
44
+ "description": "Event listeners and timers without cleanup can cause memory leaks",
45
+ "recommendation": "Always remove event listeners and clear timers in cleanup functions (componentWillUnmount, useEffect cleanup)",
46
+ "fixExample": "// Before\nuseEffect(() => {\n window.addEventListener('resize', handler);\n}, []);\n\n// After\nuseEffect(() => {\n window.addEventListener('resize', handler);\n return () => window.removeEventListener('resize', handler);\n}, []);"
47
+ },
48
+ {
49
+ "id": "unnecessary-rerender",
50
+ "category": "react-performance",
51
+ "severity": "medium",
52
+ "pattern": "useState\\s*\\(\\s*\\{|useState\\s*\\(\\s*\\[",
53
+ "patternType": "regex",
54
+ "description": "Creating new object/array references in useState can cause unnecessary re-renders",
55
+ "recommendation": "Use useMemo for computed values, useCallback for functions, or consider state management libraries",
56
+ "fixExample": "// Before - new object every render\nconst [config] = useState({ theme: 'dark' });\n\n// After - stable reference\nconst defaultConfig = useMemo(() => ({ theme: 'dark' }), []);\nconst [config] = useState(defaultConfig);"
57
+ }
58
+ ]
59
+ }