pruneplan 0.1.1 → 0.1.2

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 (3) hide show
  1. package/README.md +21 -20
  2. package/bin/pruneplan.js +167 -129
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  **Find dead code and unused packages. Review the cleanup before applying it.**
4
4
 
5
- `pruneplan` gives you one reviewable cleanup flow for unused dependencies, files, exports, and types. It uses [Knip](https://knip.dev/) to analyze the project, removes dependencies through the package manager already in use, and updates the lockfile as part of that removal.
5
+ `pruneplan` gives you a reviewable cleanup flow for unused dependencies, files, exports, and types. It uses [Knip](https://knip.dev/) to analyze a JavaScript or TypeScript project, and leaves changes in your working tree for review.
6
6
 
7
7
  ## Quick start
8
8
 
@@ -12,41 +12,42 @@ From the root of a JavaScript or TypeScript project:
12
12
  npx pruneplan
13
13
  ```
14
14
 
15
- This only prints a plan. After reviewing it, apply the cleanup interactively:
15
+ This only prints a plan. Apply selected candidates interactively:
16
16
 
17
17
  ```sh
18
18
  npx pruneplan --apply
19
19
  ```
20
20
 
21
- To scan a different project, pass its directory:
21
+ Choose candidate numbers separated by commas, or `all`. Configuration-like files are highlighted and require explicit selection. To scan another project, pass its directory:
22
22
 
23
23
  ```sh
24
24
  npx pruneplan ../my-app
25
25
  ```
26
26
 
27
- ## What happens when you apply
27
+ For CI or other non-interactive use, `--yes` applies all safely actionable findings without prompting. It excludes configuration-like files and aborts if the Knip findings changed since preview:
28
28
 
29
- 1. `pruneplan` asks Knip to scan the project and displays the cleanup candidates.
30
- 2. After you confirm, it removes unused dependencies with npm, pnpm, Yarn, or Bun, updating the package manager's lockfile.
31
- 3. It asks Knip to remove reported unused files, exports, and types.
32
- 4. It runs any `typecheck`, `lint`, `test`, and `build` scripts defined in the project's `package.json`.
33
- 5. It leaves the changes in your working tree for review with `git diff`.
29
+ ```sh
30
+ npx pruneplan --yes
31
+ ```
34
32
 
35
- For CI or other non-interactive use, `--yes` explicitly skips the prompt:
33
+ Use `--json` to print a machine-readable report, including warnings and Knip version/source:
36
34
 
37
35
  ```sh
38
- npx pruneplan --yes
36
+ npx pruneplan --json
39
37
  ```
40
38
 
41
- ## Safety
39
+ ## Review and safety
42
40
 
43
- - The default command only reports findings. It does not modify files.
44
- - Applying requires `--apply` plus an interactive confirmation, or the explicit `--yes` flag.
45
- - Package removals use your detected package manager so its lockfile is updated too.
46
- - npm and pnpm package removals skip install scripts.
47
- - Validation runs only scripts that already exist in your project. These are ordinary project commands and may have their own side effects.
48
- - Static analysis can miss runtime-loaded packages and exports used through reflection, plugins, or external consumers. Review the plan and final diff before committing.
49
- - If validation fails, the changes remain in your working tree so you can inspect and fix them; `pruneplan` does not discard project changes.
41
+ - The default command is preview-only and does not modify files.
42
+ - Interactive apply is item-selective; only selected files are removed and only selected dependencies are passed to your package manager.
43
+ - Knip's auto-fixer operates across findings rather than an individual selected export. To ensure pruneplan never changes unselected exports or types, those candidates are displayed for manual review but are not automatically fixed.
44
+ - Unlisted dependencies, duplicate exports, and other Knip issue categories are surfaced as warnings and are never interpreted as install suggestions or automatic cleanup.
45
+ - Configuration-like files are marked for extra review. Use Knip configuration (entries, workspaces, project patterns, or ignore settings) to correct analysis scope instead of assuming a flagged config file is dead.
46
+ - Immediately before applying, pruneplan scans again. If findings changed, interactive users review/select against the updated plan; `--yes` aborts rather than applying a stale plan.
47
+ - A dirty Git worktree is reported before changes. Existing changes are never automatically discarded.
48
+ - Available `typecheck`, `lint`, `test`, and `build` scripts are listed before apply and run afterwards. Passing checks does not guarantee every runtime path is covered.
49
+ - If validation fails, changes remain in the working tree. Review with `git diff` and recover manually as needed.
50
+ - Static analysis can miss runtime-loaded dependencies and exports used through reflection, plugins, dynamic routes, or external consumers. Findings are candidates, not proof they are safe to remove.
50
51
 
51
52
  ## Requirements
52
53
 
@@ -54,7 +55,7 @@ npx pruneplan --yes
54
55
  - A JavaScript or TypeScript project with a `package.json`
55
56
  - npm, pnpm, Yarn, or Bun, identified from a lockfile or the `packageManager` field
56
57
 
57
- Knip is installed as a dependency of `pruneplan`; you do not need to add it to the project being scanned.
58
+ Knip is bundled with pruneplan; a project-local Knip installation is preferred when present.
58
59
 
59
60
  ## License
60
61
 
package/bin/pruneplan.js CHANGED
@@ -3,68 +3,44 @@
3
3
  import { spawnSync } from 'node:child_process';
4
4
  import { createInterface } from 'node:readline/promises';
5
5
  import { stdin, stdout } from 'node:process';
6
- import { access, readFile } from 'node:fs/promises';
6
+ import { access, lstat, readFile, rm } from 'node:fs/promises';
7
7
  import path from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
9
 
10
- const KNIP_JSON_FLAG = '--reporter';
11
- const APPLY_FIX_TYPES = ['files', 'exports', 'types'];
12
10
  const CHECK_SCRIPTS = ['typecheck', 'lint', 'test', 'build'];
11
+ const AUTO_CATEGORIES = new Set(['files', 'exports', 'types', 'enumMembers', 'namespaceMembers', 'dependencies', 'devDependencies']);
12
+ const REVIEW_FIRST = /(^|[/\\])(?:eslint|prettier|vite|webpack|rollup|jest|vitest|knip|babel|postcss|tailwind|tsconfig|commitlint|lint-staged|stylelint|next|nuxt|svelte|astro|playwright|cypress)[^/\\]*\.(?:[cm]?[jt]sx?|json)$/i;
13
13
 
14
14
  function parseArgs(argv) {
15
- const options = { apply: false, yes: false, directory: process.cwd() };
15
+ const options = { apply: false, yes: false, json: false, directory: process.cwd() };
16
16
  let hasDirectory = false;
17
-
18
17
  for (const arg of argv) {
19
18
  if (arg === '--apply') options.apply = true;
20
- else if (arg === '--yes' || arg === '-y') {
21
- options.apply = true;
22
- options.yes = true;
23
- } else if (arg === '--help' || arg === '-h') options.help = true;
19
+ else if (arg === '--yes' || arg === '-y') { options.apply = true; options.yes = true; }
20
+ else if (arg === '--json') options.json = true;
21
+ else if (arg === '--help' || arg === '-h') options.help = true;
24
22
  else if (arg.startsWith('-')) throw new Error(`Unknown option: ${arg}`);
25
23
  else if (hasDirectory) throw new Error('Only one project path can be supplied.');
26
- else {
27
- options.directory = path.resolve(arg);
28
- hasDirectory = true;
29
- }
24
+ else { options.directory = path.resolve(arg); hasDirectory = true; }
30
25
  }
31
-
32
26
  return options;
33
27
  }
34
28
 
35
29
  function printHelp() {
36
30
  stdout.write(`pruneplan — review unused dependencies and dead code\n\n`);
37
- stdout.write(`Usage:\n pruneplan [project-directory] [--apply] [--yes]\n\n`);
38
- stdout.write(`Options:\n`);
39
- stdout.write(` --apply Apply the displayed cleanup plan after confirmation\n`);
40
- stdout.write(` --yes Apply without an interactive confirmation (for automation)\n`);
41
- stdout.write(` -h, --help Show this help\n\n`);
42
- stdout.write(`Knip is included with pruneplan; no project setup is required.\n`);
31
+ stdout.write(`Usage:\n pruneplan [project-directory] [--apply] [--yes] [--json]\n\n`);
32
+ stdout.write(`Options:\n --apply Review and select individual cleanup candidates\n --yes Apply all safely actionable candidates without prompts\n --json Print the Knip findings as a JSON report\n -h, --help Show this help\n\n`);
43
33
  }
44
34
 
45
35
  async function readProject(directory) {
46
- const packagePath = path.join(directory, 'package.json');
47
- const packageJson = JSON.parse(await readFile(packagePath, 'utf8'));
48
- return { packagePath, packageJson };
36
+ const packageJson = JSON.parse(await readFile(path.join(directory, 'package.json'), 'utf8'));
37
+ return { packageJson };
49
38
  }
50
39
 
51
40
  async function detectPackageManager(directory, packageJson) {
52
- const lockfiles = [
53
- ['pnpm-lock.yaml', 'pnpm'],
54
- ['yarn.lock', 'yarn'],
55
- ['bun.lock', 'bun'],
56
- ['bun.lockb', 'bun'],
57
- ['package-lock.json', 'npm'],
58
- ['npm-shrinkwrap.json', 'npm'],
59
- ];
60
-
61
- for (const [file, manager] of lockfiles) {
62
- try {
63
- await access(path.join(directory, file));
64
- return manager;
65
- } catch {}
41
+ for (const [file, manager] of [['pnpm-lock.yaml', 'pnpm'], ['yarn.lock', 'yarn'], ['bun.lock', 'bun'], ['bun.lockb', 'bun'], ['package-lock.json', 'npm'], ['npm-shrinkwrap.json', 'npm']]) {
42
+ try { await access(path.join(directory, file)); return manager; } catch {}
66
43
  }
67
-
68
44
  const declared = packageJson.packageManager?.split('@')[0];
69
45
  if (['npm', 'pnpm', 'yarn', 'bun'].includes(declared)) return declared;
70
46
  throw new Error('Could not detect the package manager. Add a lockfile or packageManager field to package.json.');
@@ -72,12 +48,12 @@ async function detectPackageManager(directory, packageJson) {
72
48
 
73
49
  function run(command, args, cwd, { capture = false } = {}) {
74
50
  const result = spawnSync(command, args, {
75
- cwd,
76
- encoding: 'utf8',
51
+ cwd, encoding: 'utf8',
77
52
  stdio: capture ? ['ignore', 'pipe', 'pipe'] : 'inherit',
53
+ // Windows package-manager and global Knip commands are commonly exposed as .cmd shims.
78
54
  shell: process.platform === 'win32',
55
+ windowsHide: true,
79
56
  });
80
-
81
57
  if (result.error) throw new Error(`${command} could not be started: ${result.error.message}`);
82
58
  return result;
83
59
  }
@@ -85,23 +61,15 @@ function run(command, args, cwd, { capture = false } = {}) {
85
61
  async function findKnip(directory) {
86
62
  let current = directory;
87
63
  while (true) {
88
- const localBin = path.join(current, 'node_modules', '.bin', process.platform === 'win32' ? 'knip.cmd' : 'knip');
89
- try {
90
- await access(localBin);
91
- return { command: localBin, prefixArgs: [] };
92
- } catch {}
93
-
64
+ const script = path.join(current, 'node_modules', 'knip', 'bin', 'knip.js');
65
+ try { await access(script); return { command: process.execPath, prefixArgs: [script], source: 'project-local' }; } catch {}
94
66
  const parent = path.dirname(current);
95
67
  if (parent === current) break;
96
68
  current = parent;
97
69
  }
98
- const bundledKnip = fileURLToPath(new URL('../node_modules/knip/bin/knip.js', import.meta.url));
99
- try {
100
- await access(bundledKnip);
101
- return { command: process.execPath, prefixArgs: [bundledKnip] };
102
- } catch {}
103
-
104
- return { command: 'knip', prefixArgs: [] };
70
+ const bundled = fileURLToPath(new URL('../node_modules/knip/bin/knip.js', import.meta.url));
71
+ try { await access(bundled); return { command: process.execPath, prefixArgs: [bundled], source: 'bundled' }; } catch {}
72
+ return { command: 'knip', prefixArgs: [], source: 'PATH' };
105
73
  }
106
74
 
107
75
  function extractIssues(output) {
@@ -110,62 +78,72 @@ function extractIssues(output) {
110
78
  if (start < 0 || end < start) throw new Error('Knip did not return JSON. Run `knip --reporter json` to inspect its output.');
111
79
  const parsed = JSON.parse(output.slice(start, end + 1));
112
80
  if (!Array.isArray(parsed.issues)) throw new Error('Knip JSON output did not include an issues array.');
113
- return parsed.issues;
81
+ return parsed;
114
82
  }
115
83
 
116
- function collectPlan(issues) {
84
+ function collectPlan(report) {
117
85
  const files = [];
118
86
  const exports = [];
119
87
  const dependencies = new Map();
120
-
121
- for (const issue of issues) {
122
- for (const item of issue.files ?? []) files.push({ file: issue.file, name: item.name });
88
+ const warnings = [];
89
+ for (const issue of report.issues) {
90
+ const file = issue.file ?? '(project)';
91
+ for (const item of issue.files ?? []) files.push({ kind: 'file', file, name: item.name, reason: 'Knip reported an unused file' });
123
92
  for (const category of ['exports', 'types', 'enumMembers', 'namespaceMembers']) {
124
- for (const item of issue[category] ?? []) exports.push({ file: issue.file, category, name: item.name });
93
+ for (const item of issue[category] ?? []) exports.push({ kind: 'export', file, category, name: item.name, reason: `Knip reported an unused ${category === 'exports' ? 'export' : category}` });
125
94
  }
126
95
  for (const category of ['dependencies', 'devDependencies']) {
127
96
  for (const item of issue[category] ?? []) {
128
- dependencies.set(item.name, { name: item.name, category, file: issue.file });
97
+ dependencies.set(`${category}:${item.name}`, { kind: 'dependency', name: item.name, category, file, reason: `Knip reported an unused ${category === 'dependencies' ? 'dependency' : 'dev dependency'}` });
129
98
  }
130
99
  }
100
+ for (const [category, items] of Object.entries(issue)) {
101
+ if (category === 'file' || AUTO_CATEGORIES.has(category) || !Array.isArray(items) || !items.length) continue;
102
+ for (const item of items) warnings.push({ category, file, name: item.name ?? item.dependency ?? JSON.stringify(item) });
103
+ }
131
104
  }
132
-
133
- return { files, exports, dependencies: [...dependencies.values()] };
105
+ const candidates = [...dependencies.values(), ...files, ...exports];
106
+ candidates.forEach((item, index) => { item.id = index + 1; item.reviewFirst = item.kind === 'file' && REVIEW_FIRST.test(item.file); });
107
+ return { files, exports, dependencies: [...dependencies.values()], warnings, candidates };
134
108
  }
135
109
 
136
- function displayPlan(plan, manager) {
137
- const total = plan.files.length + plan.exports.length + plan.dependencies.length;
138
- stdout.write(`\nPruneplan found ${total} cleanup candidate${total === 1 ? '' : 's'}.\n`);
139
- if (total === 0) {
140
- stdout.write('Your project looks tidy.\n');
141
- return;
142
- }
110
+ function planSummary(plan) {
111
+ return JSON.stringify(plan.candidates.map(({ kind, file, name, category }) => [kind, file, name, category]).sort());
112
+ }
143
113
 
144
- if (plan.dependencies.length) {
145
- stdout.write(`\nUnused packages (${plan.dependencies.length}) — will be removed with ${manager}:\n`);
146
- for (const item of plan.dependencies) stdout.write(` • ${item.name} (${item.category})\n`);
114
+ function displayPlan(plan, manager, knip) {
115
+ stdout.write(`\nKnip ${knip.version ?? 'version unavailable'} (${knip.source}) found ${plan.candidates.length} cleanup candidate${plan.candidates.length === 1 ? '' : 's'}.\n`);
116
+ if (!plan.candidates.length) stdout.write('No supported cleanup candidates found.\n');
117
+ for (const item of plan.candidates) {
118
+ const target = item.kind === 'dependency' ? `${item.name} (${item.category}, ${manager})` : item.kind === 'file' ? item.file : `${item.name} in ${item.file} (${item.category})`;
119
+ const action = item.kind === 'export' ? 'manual review only' : 'selectable';
120
+ stdout.write(` ${item.id}. [${item.kind}; ${action}] ${target}${item.reviewFirst ? ' — configuration-like file: review carefully' : ''}\n`);
147
121
  }
148
- if (plan.files.length) {
149
- stdout.write(`\nUnused files (${plan.files.length}) — Knip can delete these:\n`);
150
- for (const item of plan.files) stdout.write(` • ${item.file}\n`);
151
- }
152
- if (plan.exports.length) {
153
- stdout.write(`\nUnused exports and types (${plan.exports.length}) — Knip can remove these:\n`);
154
- for (const item of plan.exports) stdout.write(` • ${item.name} in ${item.file}\n`);
122
+ if (plan.warnings.length) {
123
+ stdout.write(`\nKnip warnings (${plan.warnings.length}) — review manually; pruneplan will not change these:\n`);
124
+ for (const warning of plan.warnings) stdout.write(` • ${warning.category}${warning.name ? `: ${warning.name}` : ''}${warning.file !== '(project)' ? ` in ${warning.file}` : ''}\n`);
155
125
  }
156
126
  }
157
127
 
158
- async function confirmApply() {
159
- if (!stdin.isTTY || !stdout.isTTY) {
160
- throw new Error('Applying in a non-interactive terminal requires the explicit `--yes` flag.');
161
- }
128
+ async function promptLine(question) {
129
+ if (!stdin.isTTY || !stdout.isTTY) throw new Error('Applying in a non-interactive terminal requires `--yes`.');
162
130
  const prompt = createInterface({ input: stdin, output: stdout });
163
- try {
164
- const answer = await prompt.question('\nApply this cleanup plan? [y/N] ');
165
- return answer.trim().toLowerCase() === 'y';
166
- } finally {
167
- prompt.close();
168
- }
131
+ try { return await prompt.question(question); } finally { prompt.close(); }
132
+ }
133
+
134
+ async function selectCandidates(plan, yes) {
135
+ const selectable = plan.candidates.filter((item) => item.kind !== 'export');
136
+ if (yes) return selectable.filter((item) => !item.reviewFirst);
137
+ if (!selectable.length) return [];
138
+ stdout.write('\nChoose item numbers to apply, separated by commas (or press Enter for none). Configuration-like files require explicit selection.\n');
139
+ const answer = (await promptLine('Apply: ')).trim();
140
+ if (!answer) return [];
141
+ if (answer.toLowerCase() === 'all') return selectable.filter((item) => !item.reviewFirst);
142
+ const numbers = answer.split(',').map((part) => part.trim());
143
+ if (numbers.some((part) => !/^\d+$/.test(part))) throw new Error('Enter comma-separated item numbers or `all`.');
144
+ const ids = new Set(numbers.map(Number));
145
+ if (ids.size !== numbers.length || [...ids].some((id) => !selectable.some((item) => item.id === id))) throw new Error('Selection includes an invalid or duplicate item number.');
146
+ return selectable.filter((item) => ids.has(item.id));
169
147
  }
170
148
 
171
149
  function managerRemoveArgs(manager, packages) {
@@ -178,73 +156,133 @@ function managerRemoveArgs(manager, packages) {
178
156
  }
179
157
  }
180
158
 
181
- async function runChecks(directory, packageJson) {
182
- const scripts = packageJson.scripts ?? {};
183
- const available = CHECK_SCRIPTS.filter((name) => typeof scripts[name] === 'string');
184
- if (!available.length) {
185
- stdout.write('\nNo typecheck, lint, test, or build scripts found; skipped validation.\n');
186
- return true;
159
+ async function getDirtyStatus(directory) {
160
+ const result = run('git', ['status', '--porcelain'], directory, { capture: true });
161
+ if (result.status !== 0) return null;
162
+ return result.stdout.trim().length > 0;
163
+ }
164
+
165
+ function safeProjectPath(directory, file) {
166
+ const absolute = path.resolve(directory, file);
167
+ const relative = path.relative(directory, absolute);
168
+ if (!relative || relative.startsWith(`..${path.sep}`) || relative === '..' || path.isAbsolute(relative)) throw new Error(`Refusing to remove a path outside the project: ${file}`);
169
+ return absolute;
170
+ }
171
+
172
+ async function assertNoSymlinkParent(directory, target) {
173
+ const relative = path.relative(directory, path.dirname(target));
174
+ let current = directory;
175
+ for (const part of relative.split(path.sep).filter(Boolean)) {
176
+ current = path.join(current, part);
177
+ try {
178
+ if ((await lstat(current)).isSymbolicLink()) {
179
+ throw new Error(`Refusing to remove a file through a symlinked directory: ${path.relative(directory, current)}`);
180
+ }
181
+ } catch (error) {
182
+ if (error.code === 'ENOENT') throw new Error(`Parent directory no longer exists; no changes applied: ${path.relative(directory, current)}`);
183
+ throw error;
184
+ }
187
185
  }
186
+ }
188
187
 
188
+ async function removeSelectedFiles(directory, selected) {
189
+ for (const item of selected.filter((candidate) => candidate.kind === 'file')) {
190
+ const target = safeProjectPath(directory, item.file);
191
+ await assertNoSymlinkParent(directory, target);
192
+ try { await lstat(target); } catch (error) {
193
+ if (error.code === 'ENOENT') throw new Error(`File no longer exists; no further changes applied: ${item.file}`);
194
+ throw error;
195
+ }
196
+ await rm(target, { force: false });
197
+ stdout.write(`Removed ${item.file}\n`);
198
+ }
199
+ }
200
+
201
+ async function runChecks(directory, packageJson) {
202
+ const available = CHECK_SCRIPTS.filter((name) => typeof packageJson.scripts?.[name] === 'string');
203
+ if (!available.length) { stdout.write('\nNo typecheck, lint, test, or build scripts found; skipped validation.\n'); return true; }
189
204
  const manager = await detectPackageManager(directory, packageJson);
190
- stdout.write(`\nRunning project checks with ${manager}: ${available.join(', ')}\n`);
205
+ stdout.write(`\nRunning checks with ${manager}: ${available.join(', ')}\n`);
191
206
  for (const name of available) {
192
- const args = manager === 'npm' ? ['run', name] : ['run', name];
193
- const result = run(manager, args, directory);
194
- if (result.status !== 0) {
195
- stdout.write(`\nValidation failed at \`${name}\`. Review the changes with git diff.\n`);
196
- return false;
197
- }
207
+ const result = run(manager, ['run', name], directory);
208
+ if (result.status !== 0) { stdout.write(`\nValidation failed at \`${name}\`. Changes remain in the working tree; inspect with git diff.\n`); return false; }
198
209
  }
199
210
  return true;
200
211
  }
201
212
 
213
+ async function scanProject(directory, knip) {
214
+ const result = run(knip.command, [...knip.prefixArgs, '--reporter', 'json', '--no-exit-code'], directory, { capture: true });
215
+ if (result.status !== 0) throw new Error(result.stderr.trim() || 'Knip scan failed. Check its configuration and try again.');
216
+ return extractIssues(result.stdout);
217
+ }
218
+
219
+ async function getKnipVersion(directory) {
220
+ for (const location of [directory, path.dirname(fileURLToPath(new URL('../package.json', import.meta.url)))]) {
221
+ try {
222
+ const pkg = JSON.parse(await readFile(path.join(location, 'node_modules/knip/package.json'), 'utf8'));
223
+ return pkg.version;
224
+ } catch {}
225
+ }
226
+ return null;
227
+ }
228
+
202
229
  async function main() {
203
230
  const options = parseArgs(process.argv.slice(2));
204
231
  if (options.help) return printHelp();
205
-
206
232
  const directory = path.resolve(options.directory);
207
233
  const { packageJson } = await readProject(directory);
208
234
  const manager = await detectPackageManager(directory, packageJson);
209
235
  const knip = await findKnip(directory);
236
+ knip.version = await getKnipVersion(directory);
210
237
 
211
238
  stdout.write(`Scanning ${path.relative(process.cwd(), directory) || '.'} with Knip…\n`);
212
- const scan = run(knip.command, [...knip.prefixArgs, KNIP_JSON_FLAG, 'json', '--no-exit-code'], directory, { capture: true });
213
- if (scan.status !== 0) {
214
- const details = scan.stderr.trim();
215
- throw new Error(details || 'Knip failed. Check its configuration and try again.');
239
+ const report = await scanProject(directory, knip);
240
+ const plan = collectPlan(report);
241
+ if (options.json) {
242
+ stdout.write(`${JSON.stringify({ knip: { version: knip.version, source: knip.source }, ...plan }, null, 2)}\n`);
243
+ return;
216
244
  }
217
-
218
- const plan = collectPlan(extractIssues(scan.stdout));
219
- displayPlan(plan, manager);
220
- const total = plan.files.length + plan.exports.length + plan.dependencies.length;
221
- if (!total || !options.apply) {
222
- if (total && !options.apply) stdout.write('\nPreview only. Run with --apply to make these changes.\n');
245
+ displayPlan(plan, manager, knip);
246
+ if (!options.apply || !plan.candidates.length) {
247
+ if (plan.candidates.length) stdout.write('\nPreview only. Run with --apply to select candidates.\n');
223
248
  return;
224
249
  }
225
250
 
226
- if (!options.yes && !(await confirmApply())) {
251
+ const dirty = await getDirtyStatus(directory);
252
+ if (dirty === true) stdout.write('\nWarning: the project worktree is dirty. Existing changes will not be discarded. Review the final diff carefully.\n');
253
+ else if (dirty === null) stdout.write('\nWarning: git status is unavailable; worktree cleanliness could not be checked.\n');
254
+ const checks = CHECK_SCRIPTS.filter((name) => typeof packageJson.scripts?.[name] === 'string');
255
+ stdout.write(`Available validation scripts: ${checks.length ? checks.join(', ') : 'none'}\n`);
256
+
257
+ let selected = await selectCandidates(plan, options.yes);
258
+ if (!selected.length) { stdout.write('No automatically applicable items selected. Exports and types are shown for manual review and will not be auto-fixed.\n'); return; }
259
+
260
+ // Re-scan immediately before changes. If Knip's result changed, interactive users must select again;
261
+ // --yes aborts rather than silently applying a plan different from the one it approved.
262
+ const currentPlan = collectPlan(await scanProject(directory, knip));
263
+ if (planSummary(currentPlan) !== planSummary(plan)) {
264
+ if (options.yes) throw new Error('Knip findings changed since the preview. Re-run pruneplan and review the updated plan.');
265
+ displayPlan(currentPlan, manager, knip);
266
+ selected = await selectCandidates(currentPlan, false);
267
+ if (!selected.length) { stdout.write('No changes made.\n'); return; }
268
+ const verifiedPlan = collectPlan(await scanProject(directory, knip));
269
+ if (planSummary(verifiedPlan) !== planSummary(currentPlan)) throw new Error('Knip findings changed again. Re-run pruneplan before applying; no changes made.');
270
+ } else if (!options.yes && (await promptLine('\nApply only the selected items? [y/N] ')).trim().toLowerCase() !== 'y') {
227
271
  stdout.write('No files changed.\n');
228
272
  return;
229
273
  }
230
274
 
231
- if (plan.dependencies.length) {
232
- const names = [...new Set(plan.dependencies.map(({ name }) => name))];
233
- stdout.write(`\nRemoving ${names.length} unused package${names.length === 1 ? '' : 's'}…\n`);
234
- const result = run(manager, managerRemoveArgs(manager, names), directory);
275
+ // Knip's fixer applies fixes globally, so export/type candidates are intentionally never passed to it.
276
+ // File removals and package removals are scoped to explicit selection only.
277
+ await removeSelectedFiles(directory, selected);
278
+ const packages = [...new Set(selected.filter((item) => item.kind === 'dependency').map((item) => item.name))];
279
+ if (packages.length) {
280
+ stdout.write(`\nRemoving selected packages with ${manager}: ${packages.join(', ')}\n`);
281
+ const result = run(manager, managerRemoveArgs(manager, packages), directory);
235
282
  if (result.status !== 0) throw new Error('Package manager removal failed. Review the current working tree before continuing.');
236
283
  }
237
-
238
- if (plan.files.length || plan.exports.length) {
239
- stdout.write('\nRemoving dead files and exports with Knip…\n');
240
- const args = ['--fix', '--no-exit-code', '--fix-type', APPLY_FIX_TYPES.join(',')];
241
- if (plan.files.length) args.push('--allow-remove-files');
242
- const result = run(knip.command, [...knip.prefixArgs, ...args], directory);
243
- if (result.status !== 0) throw new Error('Knip could not apply all code fixes. Review the current working tree before continuing.');
244
- }
245
-
246
284
  const checksPassed = await runChecks(directory, packageJson);
247
- stdout.write('\nCleanup applied. Review the result with `git diff` before committing.\n');
285
+ stdout.write('\nSelected cleanup applied. Review the result with `git diff` before committing.\n');
248
286
  if (!checksPassed) process.exitCode = 1;
249
287
  }
250
288
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pruneplan",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Review and safely apply unused dependency and dead code cleanup plans.",
5
5
  "type": "module",
6
6
  "author": "Lakshmi Udbhav Regadamilli",