codepolisher-cli 1.1.0 → 1.3.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.
- package/LICENSE +21 -21
- package/README.md +263 -250
- package/package.json +1 -1
- package/src/commands/review.js +28 -1
- package/src/comparison.js +128 -0
- package/src/display.js +74 -9
- package/src/index.js +2 -1
- package/src/prompt.js +9 -5
- package/src/save-correction.js +67 -0
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2026 ImPerial TeK. Solutions
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ImPerial TeK. Solutions
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,250 +1,263 @@
|
|
|
1
|
-
<div align="center">
|
|
2
|
-
|
|
3
|
-
<img src="https://capsule-render.vercel.app/api?type=waving&color=0:6366f1,100:a855f7&height=160§ion=header&text=CodePolisher%20CLI&fontSize=48&fontColor=ffffff&fontAlignY=38&desc=AI-powered%20code%20review%20from%20your%20terminal&descAlignY=58&descSize=16" width="100%" />
|
|
4
|
-
|
|
5
|
-
<br/>
|
|
6
|
-
|
|
7
|
-
[](https://nodejs.org/)
|
|
8
|
-
[](LICENSE)
|
|
9
|
-
[](https://github.com/v1ral-ITS/codepolisher-cli/actions/workflows/test.yml)
|
|
10
|
-
[](#supported-providers)
|
|
11
|
-
[](https://nodejs.org/)
|
|
8
|
+
[](LICENSE)
|
|
9
|
+
[](https://github.com/v1ral-ITS/codepolisher-cli/actions/workflows/test.yml)
|
|
10
|
+
[](#supported-providers)
|
|
11
|
+
[](https://www.npmjs.com/package/codepolisher-cli)
|
|
12
|
+
[](https://www.npmjs.com/package/codepolisher-cli)
|
|
13
|
+
|
|
14
|
+
<br/>
|
|
15
|
+
|
|
16
|
+
> **Polish code. Catch issues. Ship with confidence.**
|
|
17
|
+
> Review files or piped source with the AI provider you already use—without tying your workflow to a hosted backend.
|
|
18
|
+
|
|
19
|
+
<br/>
|
|
20
|
+
|
|
21
|
+
</div>
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## Table of Contents
|
|
26
|
+
|
|
27
|
+
- [How it works](#how-it-works)
|
|
28
|
+
- [Supported Providers](#supported-providers)
|
|
29
|
+
- [Install](#install)
|
|
30
|
+
- [Usage](#usage)
|
|
31
|
+
- [Configuration](#configuration)
|
|
32
|
+
- [Architecture](#architecture)
|
|
33
|
+
- [Security](#security)
|
|
34
|
+
- [Development](#development)
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## How it works
|
|
39
|
+
|
|
40
|
+
CodePolisher reads a file or standard input, builds a focused review prompt, sends it directly to your selected provider, and renders structured findings for a human or CI pipeline. Every terminal review shows the original and AI-suggested correction side by side. After reviewing the comparison, you can save the corrected script under a new filename without changing the original.
|
|
41
|
+
|
|
42
|
+
```
|
|
43
|
+
Source Code Review Pipeline Result
|
|
44
|
+
┌──────────────┐ ┌────────────────────┐ ┌─────────────────┐
|
|
45
|
+
│ file.js │────▶│ Detect language │────▶│ Summary │
|
|
46
|
+
│ script.py │────▶│ Apply focus/rules │────▶│ Inline findings │
|
|
47
|
+
│ stdin pipe │────▶│ Call your provider │────▶│ JSON or terminal│
|
|
48
|
+
└──────────────┘ └────────────────────┘ └─────────────────┘
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Your provider key stays under your control. CodePolisher CLI does not require Base44 and does not proxy reviews through the CodePolisher website.
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## Supported Providers
|
|
56
|
+
|
|
57
|
+
| Provider | Config name | Environment variable | Default model |
|
|
58
|
+
|----------|-------------|----------------------|---------------|
|
|
59
|
+
| OpenAI | `openai` | `OPENAI_API_KEY` | `gpt-4o-mini` |
|
|
60
|
+
| Anthropic | `anthropic` | `ANTHROPIC_API_KEY` | `claude-3-5-haiku-20241022` |
|
|
61
|
+
| Google Gemini | `gemini` | `GEMINI_API_KEY` | `gemini-1.5-flash` |
|
|
62
|
+
| DeepSeek | `deepseek` | `DEEPSEEK_API_KEY` | `deepseek-chat` |
|
|
63
|
+
| Venice.ai | `venice` | `VENICE_API_KEY` | `zai-org-glm-5-1` |
|
|
64
|
+
| Groq | `groq` | `GROQ_API_KEY` | `openai/gpt-oss-20b` |
|
|
65
|
+
| OpenRouter | `openrouter` | `OPENROUTER_API_KEY` | Account default |
|
|
66
|
+
| Ollama | `ollama` | None required | `llama3.2` |
|
|
67
|
+
|
|
68
|
+
Larger files automatically use the provider's configured large-file model unless you set an explicit model.
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Install
|
|
73
|
+
|
|
74
|
+
### From npm
|
|
75
|
+
|
|
76
|
+
CodePolisher CLI is officially published on the public npm registry.
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
npm install -g codepolisher-cli
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
### From source
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
git clone https://github.com/v1ral-ITS/codepolisher-cli.git
|
|
86
|
+
cd codepolisher-cli
|
|
87
|
+
npm install
|
|
88
|
+
npm link
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
> **Requires:** Node.js 18 or newer
|
|
92
|
+
|
|
93
|
+
---
|
|
94
|
+
|
|
95
|
+
## Usage
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
# Review a file
|
|
99
|
+
codepolisher review src/index.js
|
|
100
|
+
|
|
101
|
+
# Review piped code
|
|
102
|
+
cat src/index.js | codepolisher review --language javascript
|
|
103
|
+
|
|
104
|
+
# Focus the review
|
|
105
|
+
codepolisher review app.py --focus security,performance
|
|
106
|
+
|
|
107
|
+
# Run a security audit
|
|
108
|
+
codepolisher review server.js --security
|
|
109
|
+
|
|
110
|
+
# Apply project-specific rules
|
|
111
|
+
codepolisher review api.ts --rules "Require error handling and input validation."
|
|
112
|
+
|
|
113
|
+
# Emit machine-readable output for CI
|
|
114
|
+
codepolisher review app.js --output json --fail-on-critical
|
|
115
|
+
|
|
116
|
+
# Save the suggested correction without an interactive prompt
|
|
117
|
+
codepolisher review app.js --save-as app.fixed.js
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
For an interactive file review, CodePolisher asks whether you want to save the suggested correction after displaying it. Press Enter to keep the original unchanged, or answer `y` and accept the suggested `*.polished.*` filename (or enter another new filename). Existing files are never overwritten.
|
|
121
|
+
|
|
122
|
+
### Review controls
|
|
123
|
+
|
|
124
|
+
| Option | Purpose |
|
|
125
|
+
|--------|---------|
|
|
126
|
+
| `--language <lang>` | Supply a language hint |
|
|
127
|
+
| `--focus <areas>` | Focus on security, performance, readability, error handling, best practices, or testing |
|
|
128
|
+
| `--rules <text>` | Add custom review rules |
|
|
129
|
+
| `--strict` | Flag every issue |
|
|
130
|
+
| `--security` | Run a security-focused audit |
|
|
131
|
+
| `--output json` | Produce JSON for scripts and CI |
|
|
132
|
+
| `--save-as <file>` | Save the suggested correction to a new file without prompting |
|
|
133
|
+
| `--fail-on-critical` | Exit with code 1 when critical issues are found |
|
|
134
|
+
|
|
135
|
+
---
|
|
136
|
+
|
|
137
|
+
## Configuration
|
|
138
|
+
|
|
139
|
+
```bash
|
|
140
|
+
# Choose a provider
|
|
141
|
+
codepolisher config set provider openai
|
|
142
|
+
|
|
143
|
+
# Save a provider-specific API key
|
|
144
|
+
codepolisher config set api-key <your-key>
|
|
145
|
+
|
|
146
|
+
# Optionally override the model
|
|
147
|
+
codepolisher config set model gpt-4o
|
|
148
|
+
|
|
149
|
+
# Inspect or clear configuration
|
|
150
|
+
codepolisher config get
|
|
151
|
+
codepolisher config clear
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
Environment variables work without a local configuration file, so CI can inject provider keys through repository secrets.
|
|
155
|
+
|
|
156
|
+
For Ollama, no API key is required:
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
codepolisher config set provider ollama
|
|
160
|
+
codepolisher config set model llama3.2
|
|
161
|
+
codepolisher config set ollama-host http://localhost:11434
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
166
|
+
## Architecture
|
|
167
|
+
|
|
168
|
+
<details>
|
|
169
|
+
<summary>View project structure</summary>
|
|
170
|
+
|
|
171
|
+
```
|
|
172
|
+
bin/
|
|
173
|
+
└── codepolisher.js # Executable entry point
|
|
174
|
+
src/
|
|
175
|
+
├── index.js # Commander program and commands
|
|
176
|
+
├── api.js # Provider adapters and response parsing
|
|
177
|
+
├── config.js # Provider detection and secure local config
|
|
178
|
+
├── prompt.js # Review and security prompt builders
|
|
179
|
+
├── comparison.js # Line alignment and safe side-by-side comparisons
|
|
180
|
+
├── display.js # Human-readable terminal output
|
|
181
|
+
├── save-correction.js # Safe corrected-script filenames and writes
|
|
182
|
+
└── commands/
|
|
183
|
+
├── review.js # File/stdin review workflow
|
|
184
|
+
└── config-cmd.js # Configuration commands
|
|
185
|
+
test/
|
|
186
|
+
├── comparison.test.js # Comparison, normalization, and terminal safety tests
|
|
187
|
+
├── providers.test.js # Provider endpoint and environment tests
|
|
188
|
+
└── save-correction.test.js # Corrected-script save safety tests
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
</details>
|
|
192
|
+
|
|
193
|
+
### Design principles
|
|
194
|
+
|
|
195
|
+
- 🔌 **Provider-independent** — use a cloud provider, an aggregator, or local Ollama
|
|
196
|
+
- 🔐 **Keys stay yours** — environment variables are first-class and saved keys are provider-specific
|
|
197
|
+
- 🧰 **Terminal-native** — review files, pipes, and CI jobs without a browser
|
|
198
|
+
- 🤖 **Automation-ready** — structured JSON and meaningful failure exit codes
|
|
199
|
+
- 🧩 **Extensible** — provider adapters and prompts are isolated by responsibility
|
|
200
|
+
|
|
201
|
+
---
|
|
202
|
+
|
|
203
|
+
## Security
|
|
204
|
+
|
|
205
|
+
Saved configuration lives in `~/.codepolisher/config.json`. CodePolisher applies restrictive permissions on macOS and Linux and a private current-user ACL on Windows. It fails instead of silently saving when those protections cannot be applied.
|
|
206
|
+
|
|
207
|
+
For CI and shared machines, prefer provider environment variables and your platform's encrypted secret store.
|
|
208
|
+
|
|
209
|
+
---
|
|
210
|
+
|
|
211
|
+
## Development
|
|
212
|
+
|
|
213
|
+
```bash
|
|
214
|
+
# Install exact dependencies
|
|
215
|
+
npm ci
|
|
216
|
+
|
|
217
|
+
# Run the test suite
|
|
218
|
+
npm test
|
|
219
|
+
|
|
220
|
+
# Exercise the CLI locally
|
|
221
|
+
node bin/codepolisher.js --help
|
|
222
|
+
|
|
223
|
+
# Verify the package contents before publishing
|
|
224
|
+
npm pack --dry-run
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
Tests run on Node.js 18, 20, and 22 through GitHub Actions.
|
|
228
|
+
|
|
229
|
+
---
|
|
230
|
+
|
|
231
|
+
## License
|
|
232
|
+
|
|
233
|
+
[MIT](LICENSE) — use it however you want.
|
|
234
|
+
|
|
235
|
+
---
|
|
236
|
+
|
|
237
|
+
<div align="center">
|
|
238
|
+
|
|
239
|
+
<br/>
|
|
240
|
+
|
|
241
|
+
<img src="https://i.ibb.co/gFJwwVL4/ITSolutions-LOGO.jpg" alt="ImPerial TeK. Solutions" width="120" />
|
|
242
|
+
|
|
243
|
+
<br/>
|
|
244
|
+
|
|
245
|
+
**Bear Carrington**
|
|
246
|
+
|
|
247
|
+
*Founder | ImPerial TeK. Solutions (ITSolutions)*
|
|
248
|
+
|
|
249
|
+
📧 [ITSolutions_MGNT@proton.me](mailto:ITSolutions_MGNT@proton.me) · 🌐 [codepolisher.app](https://codepolisher.app)
|
|
250
|
+
|
|
251
|
+
<br/>
|
|
252
|
+
|
|
253
|
+
*Innovating technology with precision and integrity.*
|
|
254
|
+
|
|
255
|
+
© ImPerial TeK. Solutions — All Rights Reserved
|
|
256
|
+
|
|
257
|
+
<br/>
|
|
258
|
+
|
|
259
|
+
*If CodePolisher CLI improved your workflow, consider giving it a star ⭐*
|
|
260
|
+
|
|
261
|
+
<img src="https://capsule-render.vercel.app/api?type=waving&color=0:a855f7,100:6366f1&height=80§ion=footer" width="100%" />
|
|
262
|
+
|
|
263
|
+
</div>
|
package/package.json
CHANGED
package/src/commands/review.js
CHANGED
|
@@ -4,7 +4,16 @@ import ora from 'ora';
|
|
|
4
4
|
import { requireConfig } from '../config.js';
|
|
5
5
|
import { invokeLLM } from '../api.js';
|
|
6
6
|
import { buildReviewPrompt, buildSecurityPrompt } from '../prompt.js';
|
|
7
|
-
import {
|
|
7
|
+
import { hasMeaningfulChanges, normalizeCorrectedCode } from '../comparison.js';
|
|
8
|
+
import { promptToSaveCorrection, resolveSaveDestination, saveCorrectedCode } from '../save-correction.js';
|
|
9
|
+
import {
|
|
10
|
+
printHeader,
|
|
11
|
+
printSummary,
|
|
12
|
+
printComments,
|
|
13
|
+
printComparison,
|
|
14
|
+
printFooter,
|
|
15
|
+
printError,
|
|
16
|
+
} from '../display.js';
|
|
8
17
|
|
|
9
18
|
export async function reviewCommand(filePath, options) {
|
|
10
19
|
const config = requireConfig();
|
|
@@ -67,8 +76,26 @@ export async function reviewCommand(filePath, options) {
|
|
|
67
76
|
printHeader(filename, results.detected_language);
|
|
68
77
|
printSummary(results);
|
|
69
78
|
printComments(results.comments);
|
|
79
|
+
const correctedCode = normalizeCorrectedCode(results.corrected_code);
|
|
80
|
+
printComparison(code, correctedCode);
|
|
70
81
|
printFooter();
|
|
71
82
|
|
|
83
|
+
if (hasMeaningfulChanges(code, correctedCode)) {
|
|
84
|
+
try {
|
|
85
|
+
let savedPath = null;
|
|
86
|
+
if (options.saveAs) {
|
|
87
|
+
const destination = resolveSaveDestination(options.saveAs, filePath);
|
|
88
|
+
savedPath = await saveCorrectedCode(correctedCode, destination, filePath);
|
|
89
|
+
} else {
|
|
90
|
+
savedPath = await promptToSaveCorrection({ correctedCode, sourcePath: filePath });
|
|
91
|
+
}
|
|
92
|
+
if (savedPath) console.log(`Saved corrected script to ${savedPath}\n`);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
printError(`Could not save corrected script: ${error.message || error}`);
|
|
95
|
+
process.exitCode = 1;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
72
99
|
// Exit with non-zero if critical issues found
|
|
73
100
|
const hasCritical = results.comments?.some(c => c.severity === 'critical' || c.severity === 'security');
|
|
74
101
|
if (hasCritical && options.failOnCritical) {
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
const MAX_LCS_CELLS = 2_000_000;
|
|
2
|
+
const ANSI_SEQUENCE = /\u001B(?:\][^\u0007]*(?:\u0007|\u001B\\)|\[[0-?]*[ -/]*[@-~]|[@-_])/g;
|
|
3
|
+
|
|
4
|
+
export function sanitizeTerminalText(value) {
|
|
5
|
+
return String(value ?? '')
|
|
6
|
+
.replace(ANSI_SEQUENCE, '')
|
|
7
|
+
.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, '');
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function normalizeCorrectedCode(value) {
|
|
11
|
+
const code = String(value ?? '');
|
|
12
|
+
const fenced = code.match(/^\s*```[^\n]*\n([\s\S]*?)\n```\s*$/);
|
|
13
|
+
return fenced ? fenced[1] : code;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function hasMeaningfulChanges(original, corrected) {
|
|
17
|
+
if (!String(corrected ?? '').trim()) return false;
|
|
18
|
+
const normalize = (value) => String(value ?? '').replace(/\r\n/g, '\n');
|
|
19
|
+
return normalize(original) !== normalize(corrected);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function splitLines(value) {
|
|
23
|
+
return sanitizeTerminalText(value).replace(/\r\n/g, '\n').split('\n');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function fallbackRows(left, right) {
|
|
27
|
+
const rows = [];
|
|
28
|
+
const length = Math.max(left.length, right.length);
|
|
29
|
+
for (let index = 0; index < length; index += 1) {
|
|
30
|
+
const before = index < left.length ? left[index] : null;
|
|
31
|
+
const after = index < right.length ? right[index] : null;
|
|
32
|
+
rows.push({
|
|
33
|
+
kind: before === after ? 'same' : before === null ? 'added' : after === null ? 'removed' : 'changed',
|
|
34
|
+
before: before === null ? null : { number: index + 1, text: before },
|
|
35
|
+
after: after === null ? null : { number: index + 1, text: after },
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return rows;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function compareLines(original, corrected) {
|
|
42
|
+
const left = splitLines(original);
|
|
43
|
+
const right = splitLines(corrected);
|
|
44
|
+
if (left.length * right.length > MAX_LCS_CELLS) return fallbackRows(left, right);
|
|
45
|
+
|
|
46
|
+
const width = right.length + 1;
|
|
47
|
+
const table = new Uint32Array((left.length + 1) * width);
|
|
48
|
+
for (let i = left.length - 1; i >= 0; i -= 1) {
|
|
49
|
+
for (let j = right.length - 1; j >= 0; j -= 1) {
|
|
50
|
+
table[(i * width) + j] = left[i] === right[j]
|
|
51
|
+
? table[((i + 1) * width) + j + 1] + 1
|
|
52
|
+
: Math.max(table[((i + 1) * width) + j], table[(i * width) + j + 1]);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const operations = [];
|
|
57
|
+
let i = 0;
|
|
58
|
+
let j = 0;
|
|
59
|
+
while (i < left.length && j < right.length) {
|
|
60
|
+
if (left[i] === right[j]) {
|
|
61
|
+
operations.push({ kind: 'same', number: i + 1, otherNumber: j + 1, text: left[i] });
|
|
62
|
+
i += 1;
|
|
63
|
+
j += 1;
|
|
64
|
+
} else if (table[((i + 1) * width) + j] >= table[(i * width) + j + 1]) {
|
|
65
|
+
operations.push({ kind: 'removed', number: i + 1, text: left[i] });
|
|
66
|
+
i += 1;
|
|
67
|
+
} else {
|
|
68
|
+
operations.push({ kind: 'added', number: j + 1, text: right[j] });
|
|
69
|
+
j += 1;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
while (i < left.length) operations.push({ kind: 'removed', number: ++i, text: left[i - 1] });
|
|
73
|
+
while (j < right.length) operations.push({ kind: 'added', number: ++j, text: right[j - 1] });
|
|
74
|
+
|
|
75
|
+
const rows = [];
|
|
76
|
+
for (let cursor = 0; cursor < operations.length;) {
|
|
77
|
+
const operation = operations[cursor];
|
|
78
|
+
if (operation.kind === 'same') {
|
|
79
|
+
rows.push({
|
|
80
|
+
kind: 'same',
|
|
81
|
+
before: { number: operation.number, text: operation.text },
|
|
82
|
+
after: { number: operation.otherNumber, text: operation.text },
|
|
83
|
+
});
|
|
84
|
+
cursor += 1;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const removed = [];
|
|
89
|
+
const added = [];
|
|
90
|
+
while (cursor < operations.length && operations[cursor].kind !== 'same') {
|
|
91
|
+
const change = operations[cursor];
|
|
92
|
+
(change.kind === 'removed' ? removed : added).push(change);
|
|
93
|
+
cursor += 1;
|
|
94
|
+
}
|
|
95
|
+
const changeLength = Math.max(removed.length, added.length);
|
|
96
|
+
for (let changeIndex = 0; changeIndex < changeLength; changeIndex += 1) {
|
|
97
|
+
const before = removed[changeIndex] || null;
|
|
98
|
+
const after = added[changeIndex] || null;
|
|
99
|
+
rows.push({
|
|
100
|
+
kind: before && after ? 'changed' : before ? 'removed' : 'added',
|
|
101
|
+
before: before ? { number: before.number, text: before.text } : null,
|
|
102
|
+
after: after ? { number: after.number, text: after.text } : null,
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return rows;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function changedHunks(rows, context = 2) {
|
|
110
|
+
const selected = new Set();
|
|
111
|
+
rows.forEach((row, index) => {
|
|
112
|
+
if (row.kind === 'same') return;
|
|
113
|
+
for (let nearby = Math.max(0, index - context); nearby <= Math.min(rows.length - 1, index + context); nearby += 1) {
|
|
114
|
+
selected.add(nearby);
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
const output = [];
|
|
119
|
+
let previous = -2;
|
|
120
|
+
for (const index of [...selected].sort((a, b) => a - b)) {
|
|
121
|
+
if (output.length > 0 && index > previous + 1) {
|
|
122
|
+
output.push({ kind: 'separator', before: null, after: null });
|
|
123
|
+
}
|
|
124
|
+
output.push(rows[index]);
|
|
125
|
+
previous = index;
|
|
126
|
+
}
|
|
127
|
+
return output;
|
|
128
|
+
}
|
package/src/display.js
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import chalk from 'chalk';
|
|
2
|
+
import {
|
|
3
|
+
compareLines,
|
|
4
|
+
sanitizeTerminalText,
|
|
5
|
+
} from './comparison.js';
|
|
2
6
|
|
|
3
7
|
const SEVERITY_COLOR = {
|
|
4
8
|
critical: (s) => chalk.bgRed.white.bold(` ${s.toUpperCase()} `),
|
|
@@ -10,13 +14,14 @@ const SEVERITY_COLOR = {
|
|
|
10
14
|
};
|
|
11
15
|
|
|
12
16
|
function badge(severity) {
|
|
13
|
-
const
|
|
14
|
-
|
|
17
|
+
const normalized = typeof severity === 'string' && severity ? severity : 'unknown';
|
|
18
|
+
const fn = SEVERITY_COLOR[normalized] || ((s) => chalk.bgGray.white(` ${s.toUpperCase()} `));
|
|
19
|
+
return fn(normalized);
|
|
15
20
|
}
|
|
16
21
|
|
|
17
22
|
export function printHeader(filename, language) {
|
|
18
|
-
const lang = language ? chalk.cyan(language) : '';
|
|
19
|
-
const file = chalk.bold(filename || 'stdin');
|
|
23
|
+
const lang = language ? chalk.cyan(sanitizeTerminalText(language)) : '';
|
|
24
|
+
const file = chalk.bold(sanitizeTerminalText(filename || 'stdin'));
|
|
20
25
|
console.log('');
|
|
21
26
|
console.log(chalk.dim('─'.repeat(60)));
|
|
22
27
|
console.log(` ${chalk.bold.white('CodePolisher')} ${file} ${lang}`);
|
|
@@ -24,7 +29,8 @@ export function printHeader(filename, language) {
|
|
|
24
29
|
}
|
|
25
30
|
|
|
26
31
|
export function printSummary(results) {
|
|
27
|
-
const {
|
|
32
|
+
const { summary, correction_summary: correctionSummary } = results;
|
|
33
|
+
const comments = Array.isArray(results.comments) ? results.comments : [];
|
|
28
34
|
|
|
29
35
|
const counts = {
|
|
30
36
|
critical: comments.filter(c => c.severity === 'critical').length,
|
|
@@ -46,12 +52,19 @@ export function printSummary(results) {
|
|
|
46
52
|
|
|
47
53
|
if (summary) {
|
|
48
54
|
console.log(chalk.dim(' Summary'));
|
|
49
|
-
console.log(` ${chalk.white(summary)}`);
|
|
55
|
+
console.log(` ${chalk.white(sanitizeTerminalText(summary))}`);
|
|
56
|
+
console.log('');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (correctionSummary) {
|
|
60
|
+
console.log(chalk.dim(' Correction approach'));
|
|
61
|
+
console.log(` ${chalk.white(sanitizeTerminalText(correctionSummary))}`);
|
|
50
62
|
console.log('');
|
|
51
63
|
}
|
|
52
64
|
}
|
|
53
65
|
|
|
54
66
|
export function printComments(comments = []) {
|
|
67
|
+
if (!Array.isArray(comments)) comments = [];
|
|
55
68
|
if (!comments.length) {
|
|
56
69
|
console.log(chalk.green(' No issues found.'));
|
|
57
70
|
return;
|
|
@@ -68,19 +81,71 @@ export function printComments(comments = []) {
|
|
|
68
81
|
for (const c of sorted) {
|
|
69
82
|
const line = c.line ? chalk.dim(`line ${c.line}`) : chalk.dim('general');
|
|
70
83
|
console.log(` ${badge(c.severity)} ${line}`);
|
|
71
|
-
console.log(` ${chalk.white(c.message)}`);
|
|
84
|
+
console.log(` ${chalk.white(sanitizeTerminalText(c.message))}`);
|
|
85
|
+
if (c.impact) {
|
|
86
|
+
console.log(` ${chalk.dim('why it matters:')} ${chalk.white(sanitizeTerminalText(c.impact))}`);
|
|
87
|
+
}
|
|
72
88
|
if (c.fix) {
|
|
73
|
-
console.log(` ${chalk.dim('
|
|
89
|
+
console.log(` ${chalk.dim('recommended change:')} ${chalk.cyan(sanitizeTerminalText(c.fix))}`);
|
|
74
90
|
}
|
|
75
91
|
console.log('');
|
|
76
92
|
}
|
|
77
93
|
}
|
|
78
94
|
|
|
95
|
+
function truncate(value, width) {
|
|
96
|
+
if (value.length <= width) return value.padEnd(width);
|
|
97
|
+
if (width <= 1) return value.slice(0, width);
|
|
98
|
+
return `${value.slice(0, width - 1)}…`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function comparisonCell(line, marker, width) {
|
|
102
|
+
if (!line) return ' '.repeat(width);
|
|
103
|
+
const prefix = `${String(line.number).padStart(4)} ${marker} `;
|
|
104
|
+
return prefix + truncate(line.text.replace(/\t/g, ' '), Math.max(1, width - prefix.length));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function printComparison(original, corrected, columns = process.stdout.columns || 120) {
|
|
108
|
+
if (!String(corrected ?? '').trim()) {
|
|
109
|
+
console.log(chalk.yellow(' The provider did not return a corrected script.'));
|
|
110
|
+
console.log('');
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const rows = compareLines(original, corrected);
|
|
115
|
+
const visibleRows = rows.length <= 400
|
|
116
|
+
? rows
|
|
117
|
+
: [
|
|
118
|
+
...rows.slice(0, 200),
|
|
119
|
+
{ kind: 'separator', before: null, after: null, omitted: rows.length - 400 },
|
|
120
|
+
...rows.slice(-200),
|
|
121
|
+
];
|
|
122
|
+
const displayWidth = Math.min(Math.max(columns, 80), 200);
|
|
123
|
+
const cellWidth = Math.max(36, Math.floor((displayWidth - 5) / 2));
|
|
124
|
+
console.log(chalk.dim(' Side-by-side comparison (original vs. AI-suggested correction)'));
|
|
125
|
+
console.log(` ${chalk.bold(truncate('ORIGINAL', cellWidth))} | ${chalk.bold(truncate('CORRECTED', cellWidth))}`);
|
|
126
|
+
console.log(` ${'-'.repeat(cellWidth)}--+--${'-'.repeat(cellWidth)}`);
|
|
127
|
+
|
|
128
|
+
for (const row of visibleRows) {
|
|
129
|
+
if (row.kind === 'separator') {
|
|
130
|
+
const label = row.omitted ? `… ${row.omitted} comparison rows omitted …` : '…';
|
|
131
|
+
console.log(chalk.dim(` ${truncate(label, cellWidth)} | ${truncate(label, cellWidth)}`));
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
const left = comparisonCell(row.before, row.kind === 'same' ? ' ' : '-', cellWidth);
|
|
135
|
+
const right = comparisonCell(row.after, row.kind === 'same' ? ' ' : '+', cellWidth);
|
|
136
|
+
const color = row.kind === 'same' ? chalk.dim : row.kind === 'changed' ? chalk.yellow : chalk.cyan;
|
|
137
|
+
console.log(` ${color(left)} | ${color(right)}`);
|
|
138
|
+
}
|
|
139
|
+
console.log('');
|
|
140
|
+
console.log(chalk.dim(' Review this suggestion before using it in production.'));
|
|
141
|
+
console.log('');
|
|
142
|
+
}
|
|
143
|
+
|
|
79
144
|
export function printFooter() {
|
|
80
145
|
console.log(chalk.dim('─'.repeat(60)));
|
|
81
146
|
console.log('');
|
|
82
147
|
}
|
|
83
148
|
|
|
84
149
|
export function printError(msg) {
|
|
85
|
-
console.error(`\n${chalk.red.bold('Error:')} ${msg}\n`);
|
|
150
|
+
console.error(`\n${chalk.red.bold('Error:')} ${sanitizeTerminalText(msg)}\n`);
|
|
86
151
|
}
|
package/src/index.js
CHANGED
|
@@ -7,7 +7,7 @@ const program = new Command();
|
|
|
7
7
|
program
|
|
8
8
|
.name('codepolisher')
|
|
9
9
|
.description('AI-powered code review in your terminal — by ImPerial TeK. Solutions')
|
|
10
|
-
.version('1.
|
|
10
|
+
.version('1.3.0');
|
|
11
11
|
|
|
12
12
|
// review command
|
|
13
13
|
program
|
|
@@ -19,6 +19,7 @@ program
|
|
|
19
19
|
.option('--strict', 'Strict mode — flag every issue')
|
|
20
20
|
.option('--security', 'Run a full security audit')
|
|
21
21
|
.option('--output <format>', 'Output format: pretty (default) or json')
|
|
22
|
+
.option('--save-as <file>', 'Save the AI-suggested correction to a new file')
|
|
22
23
|
.option('--fail-on-critical', 'Exit code 1 if critical/security issues found')
|
|
23
24
|
.action(reviewCommand);
|
|
24
25
|
|
package/src/prompt.js
CHANGED
|
@@ -3,15 +3,17 @@ export const REVIEW_SCHEMA = {
|
|
|
3
3
|
properties: {
|
|
4
4
|
detected_language: { type: "string" },
|
|
5
5
|
summary: { type: "string" },
|
|
6
|
+
correction_summary: { type: "string" },
|
|
6
7
|
comments: {
|
|
7
8
|
type: "array",
|
|
8
9
|
items: {
|
|
9
10
|
type: "object",
|
|
10
11
|
properties: {
|
|
11
12
|
severity: { type: "string" },
|
|
12
|
-
line: { type: "number" },
|
|
13
|
+
line: { type: ["number", "null"] },
|
|
13
14
|
message: { type: "string" },
|
|
14
|
-
|
|
15
|
+
impact: { type: ["string", "null"] },
|
|
16
|
+
fix: { type: ["string", "null"] },
|
|
15
17
|
},
|
|
16
18
|
},
|
|
17
19
|
},
|
|
@@ -67,12 +69,14 @@ ${code}
|
|
|
67
69
|
Provide your review as a JSON object with this exact structure:
|
|
68
70
|
- "detected_language": the language you detected (string)
|
|
69
71
|
- "summary": a 2-3 sentence overall assessment of the code quality
|
|
72
|
+
- "correction_summary": a 2-4 sentence explanation of the correction strategy, including important behavior changes or tradeoffs
|
|
70
73
|
- "comments": an array of review comments, each with:
|
|
71
74
|
- "severity": one of "critical", "warning", "suggestion", "performance", "security", "good"
|
|
72
75
|
- "line": the line number (number or null if general)
|
|
73
|
-
- "message": a
|
|
74
|
-
- "
|
|
75
|
-
- "
|
|
76
|
+
- "message": a detailed, plain-language explanation of the issue or suggestion
|
|
77
|
+
- "impact": why the issue matters in practice (string or null)
|
|
78
|
+
- "fix": a concrete code fix or recommendation (string or null)
|
|
79
|
+
- "corrected_code": the complete, runnable corrected script with all fixes applied; return code only, without Markdown fences`;
|
|
76
80
|
}
|
|
77
81
|
|
|
78
82
|
export function buildSecurityPrompt(code, language = "auto", filename = null) {
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { constants } from 'fs';
|
|
2
|
+
import { access, writeFile } from 'fs/promises';
|
|
3
|
+
import { createInterface } from 'readline/promises';
|
|
4
|
+
import { dirname, parse, resolve } from 'path';
|
|
5
|
+
|
|
6
|
+
export function suggestedOutputPath(sourcePath) {
|
|
7
|
+
const absoluteSource = resolve(sourcePath);
|
|
8
|
+
const { dir, name, ext } = parse(absoluteSource);
|
|
9
|
+
return resolve(dir, `${name}.polished${ext}`);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
async function pathExists(filePath) {
|
|
13
|
+
try {
|
|
14
|
+
await access(filePath, constants.F_OK);
|
|
15
|
+
return true;
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (error?.code === 'ENOENT') return false;
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function saveCorrectedCode(correctedCode, destinationPath, sourcePath = null) {
|
|
23
|
+
const destination = resolve(destinationPath);
|
|
24
|
+
if (sourcePath && destination === resolve(sourcePath)) {
|
|
25
|
+
throw new Error('Choose a different filename; the original file will not be overwritten.');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
if (await pathExists(destination)) {
|
|
29
|
+
throw new Error(`File already exists: ${destination}`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
await writeFile(destination, correctedCode, { encoding: 'utf8', flag: 'wx' });
|
|
33
|
+
return destination;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function promptToSaveCorrection({ correctedCode, sourcePath, input = process.stdin, output = process.stdout }) {
|
|
37
|
+
if (!sourcePath || !input.isTTY || !output.isTTY) return null;
|
|
38
|
+
|
|
39
|
+
const prompt = createInterface({ input, output });
|
|
40
|
+
try {
|
|
41
|
+
const wantsSave = (await prompt.question('Would you like to save the suggested fix as a new file? (y/N) '))
|
|
42
|
+
.trim()
|
|
43
|
+
.toLowerCase();
|
|
44
|
+
if (wantsSave !== 'y' && wantsSave !== 'yes') return null;
|
|
45
|
+
|
|
46
|
+
const defaultPath = suggestedOutputPath(sourcePath);
|
|
47
|
+
while (true) {
|
|
48
|
+
const answer = (await prompt.question(`Save as [${defaultPath}]: `)).trim();
|
|
49
|
+
const destination = answer || defaultPath;
|
|
50
|
+
try {
|
|
51
|
+
return await saveCorrectedCode(correctedCode, destination, sourcePath);
|
|
52
|
+
} catch (error) {
|
|
53
|
+
output.write(`${error.message}\n`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
} finally {
|
|
57
|
+
prompt.close();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function resolveSaveDestination(value, sourcePath = null) {
|
|
62
|
+
if (!value) return null;
|
|
63
|
+
if (sourcePath && dirname(value) === '.') {
|
|
64
|
+
return resolve(dirname(resolve(sourcePath)), value);
|
|
65
|
+
}
|
|
66
|
+
return resolve(value);
|
|
67
|
+
}
|