smart-review 1.0.1 → 1.0.3

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,580 @@
1
+ # Smart Review
2
+
3
+ > Language: [English](README.en-US.md) | [中文](README.md)
4
+
5
+ 🚀 AI-powered code review tool combining static rules and AI analysis.
6
+
7
+ ## ✨ Features
8
+
9
+ - Static rule checks for Security, Performance, Best Practices
10
+ - AI analysis (OpenAI-compatible) with incremental Git Diff review
11
+ - Smart batching and chunked processing for large files
12
+ - Git Hook integration (pre-commit)
13
+ - Highly configurable and multilingual output
14
+
15
+ ## 📦 Installation
16
+
17
+ ```bash
18
+ npm install --save-dev smart-review
19
+ # or
20
+ yarn add --dev smart-review
21
+ ```
22
+
23
+ After installation, configuration files are created under `.smart-review/` and a `pre-commit` Git hook is set up.
24
+
25
+ ## 🚀 Quick Start
26
+
27
+ ```bash
28
+ # Re-initialize if needed
29
+ node bin/install.js
30
+
31
+ # Review staged files (recommended)
32
+ smart-review --staged
33
+
34
+ # Review specific files
35
+ smart-review --files src/example.js
36
+ ```
37
+
38
+ Initialized directory structure:
39
+
40
+ ```
41
+ .smart-review/
42
+ ├── smart-review.json # Main config file
43
+ ├── ai-rules/ # AI prompt directory
44
+ └── local-rules/ # Local static rules directory
45
+ ├── security.js # Security rules
46
+ ├── performance.js # Performance rules
47
+ └── best-practices.js # Best practices rules
48
+ ```
49
+
50
+ ### Basic Usage
51
+
52
+ #### Review staged files (Git Hook)
53
+ ```bash
54
+ smart-review --staged
55
+ ```
56
+
57
+ #### Review specific files
58
+ ```bash
59
+ smart-review --files test/src/test-file.js
60
+ smart-review --files test/src/index.tsx,test/src/large-test-file.js
61
+ ```
62
+
63
+ #### Git Diff Incremental Mode
64
+ When enabled, the tool only analyzes changed lines, drastically improving efficiency:
65
+
66
+ ```bash
67
+ # Review changes in the staging area (recommended)
68
+ smart-review --staged
69
+
70
+ # Review changes in specified files
71
+ smart-review --files src/modified-file.js
72
+ ```
73
+
74
+ Benefits of incremental review:
75
+ - Efficient — analyze only changed lines, skip untouched content
76
+ - Precise — issues linked to exact changed lines
77
+ - Cost-optimized — reduce AI token usage
78
+ - Fast feedback — ideal for large projects
79
+
80
+ How it works:
81
+ 1. Detect Git changes via `git diff`
82
+ 2. Extract changed lines and context
83
+ 3. Run static rule checks and AI analysis on the changes
84
+ 4. Keep sufficient context to ensure accuracy
85
+
86
+ #### Large File Chunked Analysis
87
+ For very large files, the tool automatically segments the file:
88
+ ```bash
89
+ smart-review --files test/src/large-test-file.js
90
+ ```
91
+
92
+ Sample output:
93
+ ```
94
+ Review in progress, please wait...
95
+ 🔍 Start analyzing file in segments: test/src/large-test-file.js, total 2 segments
96
+ 🔍 Analyzing segment 1/2 (lines 1-150), estimated 2400 tokens, 150 lines of code
97
+ ✅ Segment 1 completed, found 8 issues
98
+ 🔍 Analyzing segment 2/2 (lines 130-302), estimated 2800 tokens, 172 lines of code
99
+ ✅ Segment 2 completed, found 12 issues
100
+ 🎯 Segmented analysis completed, 20 issues found in total
101
+ ```
102
+
103
+ #### Batch Processing Example
104
+ For multiple files in batches:
105
+ ```
106
+ Review in progress, please wait...
107
+ 🔍 Analyzing batch: src/utils.js, src/config.js, src/helper.js, estimated 3200 tokens, 3 files
108
+ ✅ Batch completed: src/utils.js, src/config.js, src/helper.js, found 5 issues, time: 2.3s
109
+ Progress: 1/3, total time: 2.3s
110
+ 🔍 Analyzing batch: src/api.js, src/database.js, estimated 2800 tokens, 2 files
111
+ ✅ Batch completed: src/api.js, src/database.js, found 3 issues, time: 1.8s
112
+ Progress: 2/3, total time: 4.1s
113
+ ```
114
+
115
+ ### Git Hook Integration
116
+ Add to `package.json` if you use Husky:
117
+ ```json
118
+ {
119
+ "husky": {
120
+ "hooks": {
121
+ "pre-commit": "smart-review --staged"
122
+ }
123
+ }
124
+ }
125
+ ```
126
+
127
+ ## ⚙️ Config
128
+
129
+ Main config `.smart-review/smart-review.json` example:
130
+
131
+ ```json
132
+ {
133
+ "ai": {
134
+ "enabled": true,
135
+ "model": "deepseek-chat",
136
+ "baseURL": "https://api.deepseek.com/v1",
137
+ "reviewOnlyChanges": true,
138
+ "maxResponseTokens": 8192,
139
+ "maxFileSizeKB": 500,
140
+ "enabledFor": [".js", ".ts", ".jsx", ".tsx", ".py", ".java"],
141
+ "useStaticHints": true,
142
+ "maxRequestTokens": 8000,
143
+ "temperature": 0,
144
+ "concurrency": 3
145
+ },
146
+ "riskLevels": {
147
+ "critical": { "block": true },
148
+ "high": { "block": true },
149
+ "medium": { "block": true },
150
+ "low": { "block": false },
151
+ "suggestion": { "block": false }
152
+ },
153
+ "locale": "en-US"
154
+ }
155
+ ```
156
+
157
+ ### Config Options
158
+
159
+ #### AI (`ai`)
160
+ - `enabled`: Enable AI analysis
161
+ - `model`: OpenAI model name
162
+ - `apiKey`: OpenAI API key
163
+ - `baseURL`: API base URL
164
+ - `reviewOnlyChanges`: Enable Git Diff incremental review; true analyzes only changed lines
165
+ - `maxResponseTokens`: Max tokens in AI response
166
+ - `maxFileSizeKB`: Max size per file
167
+ - `enabledFor`: File extensions supported by AI analysis
168
+ - `useStaticHints`: Include static rules as AI context
169
+ - `maxRequestTokens`: Max tokens per request
170
+ - `minFilesPerBatch` / `maxFilesPerBatch`: Batch sizing
171
+ - `tokenRatio`: Token estimation ratio
172
+ - `chunkOverlapLines`: Overlap between segments to keep context
173
+ - `includeStaticHints`: Include rule hints in AI analysis
174
+ - `temperature`: Model creativity; 0 favors deterministic outputs
175
+ - `concurrency`: Number of concurrent AI requests
176
+
177
+ #### Risk Levels (`riskLevels`)
178
+ - `critical` / `high` / `medium` / `low` / `suggestion`
179
+ - Each level supports `block` to decide whether to block commits
180
+
181
+ #### Output Control (`suppressLowLevelOutput`)
182
+ - `true`: Output only blocking levels (`block: true`)
183
+ - `false`: Output all detected issues (default)
184
+
185
+ #### Rule Loading Strategy (`useExternalRulesOnly`)
186
+ - `true`: Use only external rules from `.smart-review/local-rules`, ignore bundled rules
187
+ - `false`: Merge mode (default) — external override bundled by id; unique ids become additions
188
+
189
+ #### Ignore Review Configuration
190
+
191
+ Smart Review supports file-level and in-file ignore.
192
+
193
+ ##### 1. File-level ignore (`ignoreFiles`)
194
+
195
+ Exact match:
196
+ ```json
197
+ {
198
+ "ignoreFiles": [
199
+ "src/config/secrets.js",
200
+ "test/fixtures/data.json"
201
+ ]
202
+ }
203
+ ```
204
+
205
+ Glob patterns:
206
+ ```json
207
+ {
208
+ "ignoreFiles": [
209
+ "**/node_modules/**",
210
+ "dist/*",
211
+ "**/*.min.js",
212
+ "**/build/**",
213
+ "**/*.bundle.js"
214
+ ]
215
+ }
216
+ ```
217
+
218
+ Regular expressions:
219
+ ```json
220
+ {
221
+ "ignoreFiles": [
222
+ ".*\\.generated\\.",
223
+ "large.*\\.js$",
224
+ "/test.*\\.spec\\./",
225
+ ".*\\.temp\\."
226
+ ]
227
+ }
228
+ ```
229
+
230
+ ##### 2. In-file ignore comments
231
+
232
+ Single line:
233
+ ```javascript
234
+ // review-disable-next-line
235
+ const password = "hardcoded-password"; // The next line will be ignored
236
+
237
+ /* review-disable-next-line */
238
+ const apiKey = "sk-1234567890"; // The next line will be ignored
239
+ ```
240
+
241
+ Block ignore:
242
+ ```javascript
243
+ // review-disable-start
244
+ const config = {
245
+ password: "admin123",
246
+ apiKey: "secret-key",
247
+ token: "hardcoded-token"
248
+ };
249
+ // review-disable-end
250
+
251
+ /* review-disable-start */
252
+ function unsafeFunction() {
253
+ eval(userInput); // This block will be ignored
254
+ document.innerHTML = data;
255
+ }
256
+ /* review-disable-end */
257
+ ```
258
+
259
+ Supported comment styles
260
+ - JavaScript/TypeScript: `//` and `/* */`
261
+ - Python/Ruby: `#`
262
+ - HTML/Svelte: `<!-- -->`
263
+ - CSS/SCSS/Less: `/* */`
264
+ - Java/Go/C/C++/Rust/PHP: `//` and `/* */`
265
+
266
+ Notes
267
+ - Ignore comments must be on separate lines, not mixed with code
268
+ - `review-disable-next-line` affects the immediately following line only
269
+ - `review-disable-start/end` must be paired and affect the range between them
270
+ - In-file ignore affects static rules only, not AI analysis
271
+
272
+ ## 📋 Built-in Rules
273
+
274
+ ### Security
275
+ - **SEC001**: Hardcoded passwords/keys
276
+ - **SEC002**: SQL injection risk — string-concatenated queries
277
+ - **SEC003**: XSS risk — direct manipulation of HTML content
278
+ - **SEC004**: Command injection risk — dangerous command execution APIs
279
+
280
+ ### Performance
281
+ - **PERF001**: DB queries inside loops — possible N+1 query issues
282
+ - **PERF002**: Memory leak risk — timers created but not cleared
283
+
284
+ ### Best Practices
285
+ - **BP001**: Debugging code — console.log, print, alert, etc.
286
+ - **BP002**: Magic numbers — suggest using named constants
287
+
288
+ ## 🔧 Custom Rules
289
+
290
+ Example: custom security rule
291
+ ```javascript
292
+ // .smart-review/local-rules/custom-security.js
293
+ export const rules = {
294
+ security: [
295
+ {
296
+ id: 'CUSTOM001',
297
+ name: 'Sensitive information leakage',
298
+ pattern: '(token|secret|password)\\s*=\\s*['"]^["']+['"]',
299
+ risk: 'high',
300
+ message: 'Possible hardcoded sensitive information found',
301
+ suggestion: 'Use environment variables or secure configuration management',
302
+ flags: 'gi'
303
+ }
304
+ ]
305
+ };
306
+ ```
307
+
308
+ Example: performance rule
309
+ ```javascript
310
+ export const rules = {
311
+ performance: [
312
+ {
313
+ id: 'PERF001',
314
+ name: 'Complexity check',
315
+ pattern: function(content) {
316
+ const lines = content.split('\n');
317
+ const issues = [];
318
+ lines.forEach((line, index) => {
319
+ if (line.includes('for') && line.includes('for')) {
320
+ issues.push(`Line ${index + 1}: nested loops may impact performance`);
321
+ }
322
+ });
323
+ return issues;
324
+ },
325
+ risk: 'medium',
326
+ message: 'Performance issue detected',
327
+ suggestion: 'Optimize algorithmic complexity'
328
+ }
329
+ ]
330
+ };
331
+ ```
332
+
333
+ ### AI prompt customization
334
+
335
+ **`.smart-review/ai-rules/custom-prompts.txt`**
336
+ ```text
337
+ Please pay special attention to:
338
+ 1. Unhandled Promise rejections
339
+ 2. Proper error handling for API calls
340
+ 3. Ensure sensitive data is not accidentally logged
341
+ ```
342
+
343
+ **`.smart-review/ai-rules/security-focus.txt`**
344
+ ```text
345
+ Security review focus:
346
+ - Validate user input
347
+ - Verify access control logic
348
+ - Ensure data encryption and masking
349
+ ```
350
+
351
+ ## 🚀 Performance Optimization
352
+
353
+ ### Git Diff incremental review
354
+ Core optimization: review only changed content.
355
+
356
+ #### Benefits
357
+ - Review speed up 70–90%
358
+ - Token usage down 60–80%
359
+ - Memory optimized — load only relevant code segments
360
+ - Reduced network payload — smaller API requests
361
+
362
+ #### Best for
363
+ - Daily development commits
364
+ - Feature iterations
365
+ - Bug fixes
366
+ - Refactoring focus areas
367
+
368
+ #### Context preservation
369
+ ```json
370
+ {
371
+ "ai": {
372
+ "reviewOnlyChanges": true,
373
+ "contextMergeLines": 10,
374
+ "chunkOverlapLines": 5
375
+ }
376
+ }
377
+ ```
378
+
379
+ ### Large file strategy
380
+
381
+ Smart batching efficiently handles huge files.
382
+
383
+ #### Segmentation
384
+ - Auto-detect files exceeding token limits
385
+ - Split into overlapping segments
386
+ - Preserve context via overlap
387
+ - Parallel analysis supported
388
+
389
+ #### Token management
390
+ ```json
391
+ {
392
+ "ai": {
393
+ "maxRequestTokens": 8000,
394
+ "chunkOverlapLines": 5,
395
+ "minFilesPerBatch": 1,
396
+ "maxFilesPerBatch": 10
397
+ }
398
+ }
399
+ ```
400
+
401
+ #### Tips
402
+ 1. Tune batch parameters
403
+ ```json
404
+ {
405
+ "ai": {
406
+ "maxRequestTokens": 6000,
407
+ "chunkOverlapLines": 10,
408
+ "minFilesPerBatch": 1,
409
+ "maxFilesPerBatch": 5
410
+ }
411
+ }
412
+ ```
413
+ 2. Enable concurrency
414
+ ```json
415
+ {
416
+ "ai": {
417
+ "concurrency": 3,
418
+ "maxFilesPerBatch": 5
419
+ }
420
+ }
421
+ ```
422
+ 3. Smart batching parameters
423
+ ```json
424
+ {
425
+ "ai": {
426
+ "minFilesPerBatch": 1,
427
+ "maxFilesPerBatch": 5
428
+ }
429
+ }
430
+ ```
431
+ 4. File filtering
432
+ ```json
433
+ {
434
+ "ignoreFiles": [
435
+ "**/*.min.js",
436
+ "**/dist/**",
437
+ "**/*.generated.*"
438
+ ]
439
+ }
440
+ ```
441
+
442
+ ### Memory and network optimization
443
+
444
+ - Streaming: large files are read in streaming mode
445
+ - Request retries: built-in retry logic handles network flaps
446
+ - Caching: static rule results cache to avoid recomputation
447
+ - Incremental analysis: only changed parts are analyzed
448
+
449
+ ## 🔌 API Usage
450
+
451
+ Minimal Node.js integration example:
452
+ ```javascript
453
+ import { ConfigLoader, CodeReviewer } from './index.js';
454
+
455
+ async function main() {
456
+ const loader = new ConfigLoader(process.cwd());
457
+ const config = await loader.loadConfig();
458
+ const rules = await loader.loadRules(config);
459
+ const reviewer = new CodeReviewer(config, rules);
460
+
461
+ const result = await reviewer.reviewStagedFiles();
462
+ if (result.blockSubmission) {
463
+ console.log('Blocking issues found; please fix before committing');
464
+ process.exit(1);
465
+ }
466
+ console.log('Review completed successfully');
467
+ }
468
+
469
+ main().catch((err) => {
470
+ console.error(err);
471
+ process.exit(1);
472
+ });
473
+ ```
474
+
475
+ ## 🚀 CI/CD Integration
476
+
477
+ ### GitHub Actions
478
+ ```yaml
479
+ name: smart-review
480
+ on: [push, pull_request]
481
+ jobs:
482
+ review:
483
+ runs-on: ubuntu-latest
484
+ steps:
485
+ - uses: actions/checkout@v4
486
+ - uses: actions/setup-node@v4
487
+ with:
488
+ node-version: '18'
489
+ - run: npm ci
490
+ - name: Run Smart Review
491
+ run: smart-review --staged
492
+ ```
493
+
494
+ ### GitLab CI
495
+ ```yaml
496
+ stages:
497
+ - review
498
+
499
+ smart_review:
500
+ stage: review
501
+ image: node:18
502
+ script:
503
+ - npm ci
504
+ - smart-review --staged
505
+ only:
506
+ - merge_requests
507
+ - branches
508
+ ```
509
+
510
+ ## 🌍 Internationalization (i18n)
511
+
512
+ - Config `locale`: set at the top level in `.smart-review/smart-review.json`. Supported values: `zh-CN`, `en-US`. Example: `{ "locale": "en-US" }`.
513
+ - Env var `SMART_REVIEW_LOCALE`: highest priority; the installer selects rule templates based on this value.
514
+ - Selection priority: Env var > Project config `.smart-review/smart-review.json` > Template default `templates/smart-review.json` > fallback `zh-CN`.
515
+ - Template directories: `templates/rules/<locale>/security.js | performance.js | best-practices.js`. Missing files for a locale fall back to `zh-CN`.
516
+ - CLI/Git hook messages switch language automatically according to `locale`.
517
+
518
+ Switch examples:
519
+
520
+ ```bash
521
+ # Windows PowerShell (current session)
522
+ $env:SMART_REVIEW_LOCALE='en-US'; node bin/install.js
523
+
524
+ # macOS/Linux bash
525
+ export SMART_REVIEW_LOCALE=en-US && node bin/install.js
526
+ ```
527
+
528
+ To add a new language (e.g., `ja-JP`), create `templates/rules/ja-JP/` with the three rule files and set `"locale": "ja-JP"` or use the env var.
529
+
530
+ ## 🌍 Environment Variables
531
+
532
+ ```bash
533
+ export OPENAI_API_KEY="your-api-key"
534
+ export DEBUG_SMART_REVIEW=true
535
+ export SMART_REVIEW_LOCALE=en-US
536
+ ```
537
+
538
+ To use a custom OpenAI-compatible endpoint, set `ai.baseURL` in `.smart-review/smart-review.json`:
539
+
540
+ ```json
541
+ {
542
+ "ai": { "baseURL": "https://api.openai.com/v1" }
543
+ }
544
+ ```
545
+
546
+ ## 🔧 CLI Options
547
+
548
+ ```bash
549
+ smart-review [options]
550
+ --staged Review Git staged files
551
+ --files <files> Review specific files (comma separated)
552
+ --ai Force enable AI analysis
553
+ --no-ai Disable AI analysis
554
+ --diff-only Only review changed lines (Git Diff mode)
555
+ --debug Print debug logs
556
+ ```
557
+
558
+ ## 🛠️ Troubleshooting
559
+
560
+ - Ensure Git for Windows is installed if using Windows; hooks rely on `bash`.
561
+ - If the hook test warns about executability on Windows, it will still work; the installer handles Windows gracefully.
562
+
563
+ ### Debug Mode
564
+
565
+ Enable debug logs:
566
+ ```bash
567
+ DEBUG_SMART_REVIEW=true smart-review --staged
568
+ # or
569
+ smart-review --staged --debug
570
+ ```
571
+
572
+ ## 🤝 Contributing
573
+
574
+ 1. Fork the project
575
+ 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
576
+ 3. Commit changes (`git commit -m 'Add amazing feature'`)
577
+ 4. Push the branch (`git push origin feature/amazing-feature`)
578
+ 5. Open a Pull Request
579
+
580
+ ⭐ If this project helps you, please star the repo!