loadwise 0.6.2 → 0.7.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.
Files changed (86) hide show
  1. package/README.md +152 -100
  2. package/dist/bin/loadwise.js +126 -49
  3. package/dist/lib/accessibility/frontend-detect.js +6 -5
  4. package/dist/lib/accessibility/usage.js +10 -2
  5. package/dist/lib/editor/configured-setup.js +61 -0
  6. package/dist/lib/editor/editor-launcher.js +165 -0
  7. package/dist/lib/editor/fix-edits.js +19 -0
  8. package/dist/lib/editor/jetbrains-setup.js +53 -0
  9. package/dist/lib/editor/language-server.js +31 -14
  10. package/dist/lib/editor/managed-config.js +37 -0
  11. package/dist/lib/editor/native-setup.js +85 -0
  12. package/dist/lib/editor/release-vsix.js +61 -0
  13. package/dist/lib/editor/server-commands.js +2 -0
  14. package/dist/lib/editor/setup-server.js +87 -0
  15. package/dist/lib/editor/setup-vim.js +61 -0
  16. package/dist/lib/editor/setup.js +131 -0
  17. package/dist/lib/editor/stdio-setup.js +6 -0
  18. package/dist/lib/maintainability/cli/inputs.js +3 -2
  19. package/dist/lib/maintainability/cli.js +14 -5
  20. package/dist/lib/maintainability/examples.js +4 -0
  21. package/dist/lib/maintainability/rule-ids.js +3 -0
  22. package/dist/lib/maintainability/site-fixes/unused-bindings.js +138 -3
  23. package/dist/lib/maintainability/unused/unused-bindings.js +39 -4
  24. package/dist/lib/performance/cli/changed-lines.js +8 -1
  25. package/dist/lib/performance/cli/cli-arguments.js +19 -8
  26. package/dist/lib/performance/cli/cli-output.js +3 -0
  27. package/dist/lib/performance/cli.js +8 -4
  28. package/dist/lib/performance/datastores/pg-integrity.js +7 -0
  29. package/dist/lib/performance/datastores/pooling.js +6 -1
  30. package/dist/lib/performance/engine/native-syntax.js +3 -0
  31. package/dist/lib/performance/frontend/frontend-perf.js +80 -20
  32. package/dist/lib/performance/request/bulk-listener-registration.js +111 -0
  33. package/dist/lib/performance/request/fastify-receivers.js +93 -0
  34. package/dist/lib/performance/request/fresh-loop-socket.js +103 -0
  35. package/dist/lib/performance/request/mongoose-lean.js +140 -53
  36. package/dist/lib/performance/request/node-event-listener-leak.js +99 -5
  37. package/dist/lib/performance/request/phase5-ast.js +6 -7
  38. package/dist/lib/performance/request/phase5-rules.js +133 -13
  39. package/dist/lib/performance/request/request-handlers.js +120 -23
  40. package/dist/lib/performance/site-fixes/collection-existence.js +2 -1
  41. package/dist/lib/performance/site-fixes/collections.js +1 -2
  42. package/dist/lib/performance/site-fixes/frontend-fixes.js +10 -6
  43. package/dist/lib/performance/site-fixes/helpers.js +3 -4
  44. package/dist/lib/performance/site-fixes/integrity.js +2 -4
  45. package/dist/lib/reliability/react-bugs.js +11 -3
  46. package/dist/lib/reliability/usage.js +16 -5
  47. package/dist/lib/security/cli.js +15 -4
  48. package/dist/lib/shared/agent/agent-init.js +26 -4
  49. package/dist/lib/shared/agent/agent-prompt.js +74 -0
  50. package/dist/lib/shared/agent/agent-session.js +6 -1
  51. package/dist/lib/shared/agent/agent-verify.js +54 -10
  52. package/dist/lib/shared/agent/review-delivery.js +1 -1
  53. package/dist/lib/shared/analysis/scan-cache.js +3 -2
  54. package/dist/lib/shared/check.js +172 -20
  55. package/dist/lib/shared/fix/fix-convergence.js +15 -29
  56. package/dist/lib/shared/fix/fix-handoff.js +16 -11
  57. package/dist/lib/shared/fix/fix-imports.js +47 -38
  58. package/dist/lib/shared/fix/fix-presentation-prettier.js +1 -46
  59. package/dist/lib/shared/fix/fix-presentation-rows.js +45 -1
  60. package/dist/lib/shared/fix/fix-presentation.js +4 -3
  61. package/dist/lib/shared/fix/fix-safety.js +26 -1
  62. package/dist/lib/shared/fix/fix-scope.js +82 -0
  63. package/dist/lib/shared/fix/fix-terminal.js +28 -1
  64. package/dist/lib/shared/fix/project-file-access.js +17 -26
  65. package/dist/lib/shared/fix/read-fix-text.js +20 -0
  66. package/dist/lib/shared/fix.js +215 -102
  67. package/dist/lib/shared/report-fp.js +93 -0
  68. package/dist/lib/shared/reporting/automatic-fix-signal.js +10 -0
  69. package/dist/lib/shared/reporting/check-text.js +50 -0
  70. package/dist/lib/shared/reporting/pillars.js +45 -16
  71. package/dist/lib/shared/reporting/source-report.js +2 -0
  72. package/dist/lib/shared/system/atomic-write.js +5 -2
  73. package/dist/lib/shared/system/sentry.js +203 -0
  74. package/dist/lib/shared/system/shell-argument.js +5 -1
  75. package/dist/lib/shared/system/terminal-safe.js +3 -2
  76. package/dist/lib/shared/system/terminal-style.js +131 -0
  77. package/docs/assets/cli-workflow.gif +0 -0
  78. package/integrations/sublime/plugin.py +22 -0
  79. package/integrations/zed/Cargo.lock +845 -0
  80. package/integrations/zed/Cargo.toml +11 -0
  81. package/integrations/zed/extension.toml +11 -0
  82. package/integrations/zed/src/lib.rs +25 -0
  83. package/package.json +11 -3
  84. package/plugin/.claude-plugin/plugin.json +1 -1
  85. package/plugin/commands/loadwise.md +11 -6
  86. package/schema/loadwise.config.schema.json +2 -0
@@ -1,48 +1,68 @@
1
+ import fs from 'node:fs';
2
+ import { fixScopeGuard } from './fix/fix-scope.js';
1
3
  import path from 'node:path';
2
4
  import { parseArgs } from 'node:util';
3
5
  import { scanForFixes } from './check.js';
4
6
  import { pillars } from './reporting/pillars.js';
5
7
  import { realTarget } from './system/real-target.js';
6
8
  import { ruleWhy, withoutWhyComment } from './fix/fix-presentation.js';
7
- import { labelledLines } from './fix/fix-terminal.js';
9
+ import { labelledLines, previewDiff } from './fix/fix-terminal.js';
8
10
  import { groupByReason } from './reporting/reason-groups.js';
9
11
  import { formatHandoff, fixInstructions } from './fix/fix-handoff.js';
10
12
  import { attachRecipeFixes } from './fix/fix-recipes.js';
11
13
  import { recordBulk } from './fix/fix-history.js';
12
14
  import { writeReviewHandoff } from './agent/review-delivery.js';
13
15
  import { hunkRange, writeFixes } from './fix/fix-convergence.js';
16
+ import { stylePatchLine } from './system/terminal-style.js';
14
17
  import { printTerminalLine, terminalSafe } from './system/terminal-safe.js';
18
+ import { optionArguments, quoteArgument } from './system/shell-argument.js';
15
19
  function hasFix(finding) {
16
20
  return Boolean(finding.fix);
17
21
  }
18
- const usage = `Usage: loadwise fix (--yes | --all | --handoff) [checkers...]
19
- --yes Apply automatic fixes.
22
+ const usage = `Usage: loadwise fix [--apply | --all | --id <id> | --handoff] [directory] [checkers...]
23
+ With no edit mode, preview automatic fixes.
24
+ --apply, --yes Apply automatic fixes.
20
25
  --all Apply every generated fix, including edits marked for individual review.
21
- --dry-run Preview converged unified diffs without writing files.
26
+ --dry-run Show generated edits before project formatting, without writing files.
27
+ --id <id> Apply exactly the named findings, including review-marked edits (repeatable or comma-separated).
28
+ [directory] Project folder (default: current folder). Use ./perf for a folder named like a checker.
29
+ --config <file> Read project settings from this file.
30
+ --workspace <name|path> Restrict edits to selected packages (repeatable).
31
+ --uncommitted Limit edits to changes since HEAD, including untracked files.
32
+ --staged | --changed-since <ref> Limit edits to changed lines.
22
33
  --rule <id> Limit fixes to the named rule ID (repeatable).
23
34
  --handoff Print a read-only Markdown brief for manual findings.
24
- --review With --yes or --all, save this run and print a handoff for any coding agent.
25
- --json With --yes or --all, print the applied hunks, manual findings and pending review findings as JSON.
35
+ --review Save an applied fix report for a coding agent.
36
+ --json Print the preview or applied fix report as JSON.
26
37
  --recipe <name|file.cjs> With --all, use verified-private-types or a trusted local fix recipe.
27
38
  --only Select checkers by name. Spaces or commas separate multiple names.
28
39
  --no-verify-types Skip Layer-2 semantic type-check verification on modified TS files.
29
40
  --no-comments Do not add the "// Loadwise <rule-id>: <why>" comment above each fixed statement.
30
- --no-format Do not format the changed lines with the project's Prettier.
41
+ --no-format Skip project Prettier when applying edits.
31
42
  Checkers: performance (perf), reliability (rel), maintainability (maint), security (sec), accessibility (a11y).
32
43
  Omit checker names to use the project's configured checkers.
33
44
 
34
- loadwise fix --all
35
- loadwise fix --yes performance
45
+ loadwise fix
46
+ loadwise fix --only perf --id <finding-id>
47
+ loadwise fix --apply --only perf
36
48
  loadwise fix --all --only perf,sec`;
37
- function fixOptions(args) {
38
- const { values, positionals } = parseArgs({
49
+ function parseFixArgs(args) {
50
+ return parseArgs({
39
51
  args,
40
52
  allowPositionals: true,
53
+ tokens: true,
41
54
  options: {
55
+ config: { type: 'string' },
56
+ workspace: { type: 'string', multiple: true, default: [] },
57
+ staged: { type: 'boolean' },
58
+ uncommitted: { type: 'boolean' },
59
+ 'changed-since': { type: 'string' },
42
60
  yes: { type: 'boolean' },
61
+ apply: { type: 'boolean' },
43
62
  all: { type: 'boolean' },
44
63
  'dry-run': { type: 'boolean' },
45
64
  rule: { type: 'string', multiple: true },
65
+ id: { type: 'string', multiple: true },
46
66
  handoff: { type: 'boolean' },
47
67
  review: { type: 'boolean' },
48
68
  json: { type: 'boolean' },
@@ -54,36 +74,77 @@ function fixOptions(args) {
54
74
  'no-verify-types': { type: 'boolean' },
55
75
  },
56
76
  });
57
- if (values.handoff && (values.yes || values.all || values.recipe !== undefined))
58
- throw new Error('--handoff is read-only. Use it separately from --yes, --all and --recipe.');
59
- if (values.handoff && values.json)
60
- throw new Error('--handoff prints Markdown. Use check --json for a read-only JSON report.');
61
- if (values.handoff && values.review)
62
- throw new Error('--review requires a fix run with --yes or --all.');
63
- if (values.handoff && (values.comments || values['no-comments'] || values['no-format']))
64
- throw new Error('--comments, --no-comments and --no-format apply to a fix run with --yes or --all.');
65
- if (!values.yes && !values.all && !values.handoff)
66
- throw new Error(usage);
67
- if (values.recipe !== undefined && (!values.all || !values.recipe.trim())) {
68
- throw new Error('--recipe needs --all and a recipe name or local filename.');
69
- }
77
+ }
78
+ function fixTarget(values, positionals) {
70
79
  const selected = new Set();
71
- for (const list of [...(values.only ?? []), ...positionals]) {
80
+ const checkerFor = (selector) => pillars.find(({ name, jsonKey }) => selector === name || selector === jsonKey);
81
+ const directoryOperands = positionals.filter((value) => !value.split(',').every((item) => checkerFor(item.trim())) &&
82
+ fs.statSync(value, { throwIfNoEntry: false })?.isDirectory());
83
+ if (directoryOperands.length > 1)
84
+ throw new Error('fix accepts at most one project directory.');
85
+ const directory = path.resolve(directoryOperands[0] ?? '.');
86
+ const scopeArgs = [
87
+ ...directoryOperands.map((operand) => (operand.startsWith('-') ? './' + operand : operand)),
88
+ ...(values.config === undefined ? [] : optionArguments('--config', values.config)),
89
+ ...values.workspace.flatMap((selector) => optionArguments('--workspace', selector)),
90
+ ...(values.uncommitted ? ['--uncommitted'] : []),
91
+ ...(values.staged ? ['--staged'] : []),
92
+ ...(values['changed-since'] === undefined ? [] : optionArguments('--changed-since', values['changed-since'])),
93
+ ];
94
+ for (const list of [...(values.only ?? []), ...positionals.filter((value) => !directoryOperands.includes(value))]) {
72
95
  for (const item of list.split(',')) {
73
96
  const selector = item.trim();
74
- const checker = pillars.find(({ name, jsonKey }) => name === selector || jsonKey === selector);
97
+ const checker = checkerFor(selector);
75
98
  if (!checker)
76
99
  throw new Error(`Invalid checker "${selector}". Choose performance, reliability, maintainability, security, or accessibility.`);
77
100
  selected.add(checker.name);
78
101
  }
79
102
  }
80
- const rules = (values.rule ?? [])
81
- .flatMap((entry) => entry.split(','))
82
- .map((entry) => entry.trim())
83
- .filter(Boolean);
84
103
  return {
85
- includeReview: Boolean(values.all),
86
- dryRun: Boolean(values['dry-run']),
104
+ scopeArgs,
105
+ scope: {
106
+ directory,
107
+ workspace: values.workspace,
108
+ staged: values.staged,
109
+ ref: values.uncommitted ? 'HEAD' : values['changed-since'],
110
+ },
111
+ selected: selected.size ? [...selected] : undefined,
112
+ };
113
+ }
114
+ function fixOptions(args) {
115
+ const { values, positionals, tokens } = parseFixArgs(args);
116
+ const applyAutomatic = values.apply || values.yes;
117
+ if (values.handoff && (applyAutomatic || values.all || values.recipe !== undefined))
118
+ throw new Error('--handoff is read-only. Use it separately from --apply, --yes, --all and --recipe.');
119
+ if (values.handoff && values.json)
120
+ throw new Error('--handoff prints Markdown. Use check --json for a read-only JSON report.');
121
+ if (values.handoff && values.review)
122
+ throw new Error('--review cannot be combined with --handoff.');
123
+ if (values.handoff && (values.comments || values['no-comments'] || values['no-format']))
124
+ throw new Error('--handoff cannot be combined with --comments, --no-comments or --no-format.');
125
+ const ids = values.id?.flatMap((entry) => entry.split(',').map((id) => id.trim()));
126
+ if (ids?.includes(''))
127
+ throw new Error('--id must be a nonempty finding ID for each selection.');
128
+ if (ids && values.handoff)
129
+ throw new Error('--id cannot be combined with --handoff.');
130
+ if (values.recipe !== undefined && (!values.all || !values.recipe.trim())) {
131
+ throw new Error('--recipe needs --all and a recipe name or local filename.');
132
+ }
133
+ const target = fixTarget(values, positionals);
134
+ const rules = (values.rule ?? []).flatMap((entry) => entry.split(',').map((rule) => rule.trim()));
135
+ if (rules.includes(''))
136
+ throw new Error('--rule must be a nonempty rule ID for each selection.');
137
+ // Remove mode flags by token index so option values and operands after "--" stay verbatim.
138
+ const modeIndexes = new Set(tokens
139
+ .filter((token) => token.kind === 'option' && ['apply', 'yes', 'dry-run'].includes(token.name))
140
+ .map((token) => token.index));
141
+ const applyArgs = [...(values.all || ids ? [] : ['--apply']), ...args.filter((_, index) => !modeIndexes.has(index))];
142
+ return {
143
+ ...target,
144
+ applyCommand: ['npx', 'loadwise', 'fix', ...applyArgs.map(quoteArgument)].join(' '),
145
+ ids: ids ? new Set(ids) : undefined,
146
+ includeReview: Boolean(values.all || ids),
147
+ dryRun: Boolean(values['dry-run'] || (!applyAutomatic && !values.all && !ids && !values.handoff)),
87
148
  rules: rules.length ? new Set(rules) : undefined,
88
149
  handoff: Boolean(values.handoff),
89
150
  requestReview: Boolean(values.review),
@@ -92,48 +153,64 @@ function fixOptions(args) {
92
153
  comments: !values['no-comments'],
93
154
  format: !values['no-format'],
94
155
  verifyTypes: !values['no-verify-types'],
95
- selected: selected.size ? [...selected] : undefined,
96
156
  };
97
157
  }
98
158
  function location(finding) {
99
- return `${finding.checker} ${finding.file}:${finding.line} [${finding.ruleId} #${finding.id}]`;
159
+ return `${finding.file}:${finding.line} ${finding.checker}/${finding.ruleId} #${finding.id}`;
100
160
  }
101
- function printFixed(applied) {
102
- const printNote = (finding, indentation) => {
103
- if (!finding.fix.note)
104
- return;
105
- for (const line of labelledLines('Note', finding.fix.note, indentation))
106
- printTerminalLine(line);
107
- };
108
- const printWhy = (why) => {
109
- if (why)
110
- for (const line of labelledLines('Why', why))
111
- printTerminalLine(line);
112
- };
113
- for (const group of groupByReason(applied, (finding) => finding.ruleId)) {
161
+ function selectFindingIds(findings, ids) {
162
+ if (!ids)
163
+ return findings;
164
+ const matches = findings.filter((finding) => finding.id && ids.has(finding.id));
165
+ const byId = Map.groupBy(matches, (finding) => finding.id);
166
+ for (const id of ids) {
167
+ const count = byId.get(id)?.length ?? 0;
168
+ if (!count)
169
+ throw new Error(`Invalid --id: #${id} is absent from the selected scan. Run loadwise check to refresh the IDs.`);
170
+ if (count > 1)
171
+ throw new Error(`Invalid --id: #${id} is ambiguous. Narrow the scan with --only.`);
172
+ }
173
+ return matches;
174
+ }
175
+ function counted(count, noun, plural = noun + 's') {
176
+ return `${count} ${count === 1 ? noun : plural}`;
177
+ }
178
+ function printExplanation(label, text, indent) {
179
+ if (!text)
180
+ return;
181
+ for (const line of labelledLines(label, text, indent))
182
+ printTerminalLine(line);
183
+ }
184
+ function printFixes(applied) {
185
+ for (const group of groupByReason(applied, (finding) => [finding.checker, finding.ruleId])) {
114
186
  const [first] = group;
115
- const why = ruleWhy(first.ruleId);
116
- if (group.length === 1) {
117
- printTerminalLine('Fixed: ' + location(first));
118
- printWhy(why);
119
- printNote(first, ' ');
120
- continue;
121
- }
122
- printTerminalLine(`Fixed ${group.length} [${first.ruleId}]:`);
123
- printWhy(why);
187
+ const multiple = group.length > 1;
188
+ const title = multiple
189
+ ? `${first.checker}/${first.ruleId} (${counted(group.length, 'fix', 'fixes')})`
190
+ : location(first);
191
+ printTerminalLine(' ' + title);
192
+ printExplanation('Why', ruleWhy(first.ruleId), ' ');
124
193
  for (const finding of group) {
125
- printTerminalLine(` ${finding.checker} ${finding.file}:${finding.line} #${finding.id}`);
126
- printNote(finding, ' ');
194
+ if (multiple)
195
+ printTerminalLine(` ${finding.file}:${finding.line} #${finding.id}`);
196
+ printExplanation('Note', finding.fix.note, multiple ? ' ' : ' ');
127
197
  }
128
198
  }
129
199
  }
130
- function applyBulkFixes(findings, directory, { includeReview = false, format = false, verifyTypes = true, dryRun = false } = {}) {
200
+ function printOutstanding(title, findings) {
201
+ if (!findings.length)
202
+ return;
203
+ console.log(`\n${title} (${findings.length})`);
204
+ for (const finding of findings)
205
+ printTerminalLine(' ' + location(finding));
206
+ }
207
+ function applyBulkFixes(findings, directory, { includeReview = false, format = false, verifyTypes = true, dryRun = false, requireAll = false, guard, reviewReservations = findings, } = {}) {
131
208
  const reviewedRanges = new Map();
132
209
  const target = (change) => {
133
210
  const file = realTarget(path.resolve(directory, change.file));
134
211
  return process.platform === 'win32' ? file.toLowerCase() : file;
135
212
  };
136
- for (const finding of findings) {
213
+ for (const finding of reviewReservations) {
137
214
  if (!finding.fix?.requiresReview)
138
215
  continue;
139
216
  for (const change of finding.fix.changes) {
@@ -152,81 +229,133 @@ function applyBulkFixes(findings, directory, { includeReview = false, format = f
152
229
  const [first, last] = hunkRange(change);
153
230
  return reviewedRanges.get(target(change))?.some(([start, end]) => first <= end && start <= last) ?? false;
154
231
  }
232
+ const outsideScope = [];
155
233
  for (const finding of findings) {
156
234
  if (!hasFix(finding))
157
235
  manual.push(finding);
236
+ else if (guard && !finding.fix.changes.every((change) => guard.allowsChange(change)))
237
+ outsideScope.push({
238
+ finding,
239
+ reason: 'The complete fix extends outside the selected workspace or changed lines, or the staged file has unstaged edits.',
240
+ });
158
241
  else if (finding.fix.requiresReview || finding.fix.changes.some(touchesReviewedLines))
159
242
  review.push(finding);
160
243
  else
161
244
  automatic.push(finding);
162
245
  }
246
+ if (requireAll && outsideScope.length)
247
+ throw new Error(outsideScope.map(({ finding, reason }) => `#${finding.id}: ${reason}`).join('\n'));
163
248
  const written = writeFixes(includeReview ? [...automatic, ...review] : automatic, directory, {
249
+ requireAll,
164
250
  format,
165
251
  verifyTypes,
166
252
  dryRun,
253
+ validateUpdates: guard?.validateUpdates,
167
254
  });
168
- return { automatic, manual, review, ...written };
255
+ return { automatic, manual, review, ...written, refused: [...outsideScope, ...written.refused] };
169
256
  }
170
- async function attachRecipe(scanned, recipe) {
257
+ async function attachRecipe(scanned, recipe, directory) {
171
258
  if (recipe === 'verified-private-types') {
172
259
  const { attachVerifiedPrivateTypes } = await import('../maintainability/unused/verified-private-types.js');
173
- return await attachVerifiedPrivateTypes(scanned, process.cwd());
260
+ return await attachVerifiedPrivateTypes(scanned, directory);
174
261
  }
175
262
  if (recipe)
176
- return await attachRecipeFixes(scanned, recipe, process.cwd());
263
+ return await attachRecipeFixes(scanned, path.resolve(recipe), directory);
177
264
  return scanned;
178
265
  }
179
266
  function withoutFixComment(finding) {
180
267
  return finding.fix ? { ...finding, fix: withoutWhyComment(finding.fix, finding.ruleId) } : finding;
181
268
  }
182
- function fixSummary(includeReview, { applied, changedFiles, manual, review }) {
183
- return includeReview
184
- ? `${applied} generated fix(es) in ${changedFiles} file(s), ${manual} manual, ${review} review-marked fix(es) applied.`
185
- : `${applied} automatic fix(es) in ${changedFiles} file(s), ${manual} manual, ${review} requiring individual review.`;
186
- }
187
269
  function printDryRunDiff(updates, directory) {
270
+ const printPatch = (line) => console.log(stylePatchLine(terminalSafe(line)));
188
271
  for (const { file, before, after } of updates) {
189
272
  const rel = path.relative(directory, file).split(path.sep).join('/');
190
- printTerminalLine(`--- a/${rel}`);
191
- printTerminalLine(`+++ b/${rel}`);
192
- for (const line of (before ?? '').split('\n'))
193
- printTerminalLine(`-${line}`);
194
- for (const line of after.split('\n'))
195
- printTerminalLine(`+${line}`);
273
+ printPatch(before === undefined ? '--- /dev/null' : `--- a/${rel}`);
274
+ printPatch(`+++ b/${rel}`);
275
+ for (const line of previewDiff(before ?? '', after))
276
+ printPatch(line);
196
277
  }
197
278
  }
279
+ function printFixReport(result, includeReview, dryRun, directory, instructions) {
280
+ const { applied, manual, review, refused, changedFiles, updates } = result;
281
+ const editKind = dryRun ? 'proposed' : includeReview ? 'generated' : 'automatic';
282
+ const summary = `${counted(applied.length, editKind + ' fix', editKind + ' fixes')} in ${counted(changedFiles, 'file')}`;
283
+ console.log(`${dryRun ? 'Preview' : 'Applied'}: ${summary}.`);
284
+ printFixes(applied);
285
+ if (includeReview && review.length) {
286
+ const reviewedIds = new Set(review.map((finding) => finding.id));
287
+ const reviewCount = applied.filter((finding) => reviewedIds.has(finding.id)).length;
288
+ if (reviewCount)
289
+ console.log(` Includes ${counted(reviewCount, 'review-marked fix', 'review-marked fixes')}.`);
290
+ }
291
+ if (dryRun && updates.length) {
292
+ console.log('\nDiff');
293
+ printDryRunDiff(updates, directory);
294
+ }
295
+ if (!includeReview)
296
+ printOutstanding('Requires individual review', review);
297
+ printOutstanding('Manual changes', manual);
298
+ if (refused.length) {
299
+ console.log(`\nRefused fixes (${refused.length})`);
300
+ for (const { finding, reason } of refused) {
301
+ printTerminalLine(' ' + location(finding));
302
+ for (const line of labelledLines('Reason', reason, ' '))
303
+ printTerminalLine(line);
304
+ }
305
+ }
306
+ if (!dryRun || changedFiles)
307
+ console.log('\n' + terminalSafe(instructions));
308
+ }
309
+ async function prepareFixes(scanned, { recipe, scope, comments, ids }) {
310
+ const withRecipe = await attachRecipe(scanned, recipe, scope.directory);
311
+ const findings = comments ? withRecipe : withRecipe.map(withoutFixComment);
312
+ const missingFix = ids && findings.find((finding) => !finding.fix);
313
+ if (missingFix)
314
+ throw new Error(`Invalid --id: #${missingFix.id} has no generated fix.`);
315
+ return findings;
316
+ }
198
317
  async function runFix(args) {
199
318
  if (args.length === 1 && ['--help', '-h'].includes(args[0])) {
200
319
  console.log(usage);
201
320
  return 0;
202
321
  }
203
- const { selected, includeReview, dryRun, rules, recipe, handoff, json, requestReview, comments, format, verifyTypes, } = fixOptions(args);
204
- const scannedAll = await scanForFixes(selected);
205
- const scanned = rules ? scannedAll.filter((finding) => rules.has(finding.ruleId)) : scannedAll;
322
+ const options = fixOptions(args);
323
+ const { selected, includeReview, dryRun, applyCommand, ids, rules, handoff, json, requestReview, format, verifyTypes, scope, scopeArgs, } = options;
324
+ const action = dryRun ? 'Previewing fixes' : 'Applying fixes';
325
+ const scannedAll = await scanForFixes(selected, scopeArgs, json || handoff ? undefined : action);
326
+ const scanned = selectFindingIds(rules ? scannedAll.filter((finding) => rules.has(finding.ruleId)) : scannedAll, ids);
206
327
  if (handoff) {
207
- console.log(terminalSafe(formatHandoff(scanned, selected)));
328
+ console.log(terminalSafe(formatHandoff(scanned, selected, scopeArgs, rules)));
208
329
  return 0;
209
330
  }
210
- const withRecipe = await attachRecipe(scanned, recipe);
211
- const findings = comments ? withRecipe : withRecipe.map(withoutFixComment);
212
- const { applied, manual, review, refused, changedFiles, updates } = applyBulkFixes(findings, process.cwd(), {
331
+ const findings = await prepareFixes(scanned, options);
332
+ const result = applyBulkFixes(findings, scope.directory, {
333
+ // Filtering the output to one rule must still reserve lines flagged for review by a different rule.
334
+ reviewReservations: rules && !includeReview ? scannedAll : findings,
335
+ guard: fixScopeGuard(scope),
336
+ requireAll: Boolean(ids),
213
337
  includeReview,
214
338
  format,
215
339
  verifyTypes,
216
340
  dryRun,
217
341
  });
342
+ const { applied, manual, review, refused, changedFiles } = result;
218
343
  const pendingReview = includeReview ? [] : review;
219
344
  if (changedFiles && !dryRun)
220
- recordBulk(process.cwd(), {
345
+ recordBulk(scope.directory, {
221
346
  applied,
222
347
  manual,
223
348
  pendingReview,
224
349
  });
225
- const instructions = fixInstructions(findings.length, selected, manual.length);
350
+ const instructions = dryRun
351
+ ? changedFiles
352
+ ? `To apply these fixes, run:\n${applyCommand}`
353
+ : 'No proposed edits to apply.'
354
+ : fixInstructions(findings.length, selected, manual.length, scopeArgs, rules);
226
355
  const notApplied = refused.map(({ finding, reason }) => ({ id: finding.id, ruleId: finding.ruleId, reason }));
227
356
  const report = { changedFiles, dryRun, applied, manual, pendingReview, notApplied, instructions };
228
357
  if (requestReview && !dryRun)
229
- await writeReviewHandoff(process.cwd(), 'fix', {
358
+ await writeReviewHandoff(scope.directory, 'fix', {
230
359
  args,
231
360
  format: 'json',
232
361
  report,
@@ -236,23 +365,7 @@ async function runFix(args) {
236
365
  console.log(JSON.stringify(report));
237
366
  return 0;
238
367
  }
239
- if (dryRun && updates.length)
240
- printDryRunDiff(updates, process.cwd());
241
- if (!includeReview)
242
- for (const finding of review)
243
- printTerminalLine('Review individually: ' + location(finding));
244
- for (const finding of manual)
245
- printTerminalLine('Manual change: ' + location(finding));
246
- for (const { finding, reason } of refused)
247
- printTerminalLine(`Not applied: ${location(finding)}: ${reason}`);
248
- printFixed(applied);
249
- console.log(fixSummary(includeReview, {
250
- applied: applied.length,
251
- changedFiles,
252
- manual: manual.length,
253
- review: review.length,
254
- }));
255
- console.log(instructions);
368
+ printFixReport(result, includeReview, dryRun, scope.directory, instructions);
256
369
  return 0;
257
370
  }
258
371
  export { runFix, applyBulkFixes, realTarget };
@@ -0,0 +1,93 @@
1
+ // `loadwise report-fp`: builds a privacy-safe, pre-filled GitHub false-positive issue URL.
2
+ // Never sends telemetry automatically and never embeds user source code or local file paths.
3
+ import { spawn } from 'node:child_process';
4
+ import { parseArgs } from 'node:util';
5
+ import { packageManifest } from './package-root.js';
6
+ import { pillarOfRule } from './rule-registry.js';
7
+ const fpRepoIssuesUrl = 'https://github.com/IbrahimHafez1/loadwise/issues/new';
8
+ const fpUsage = 'Usage: loadwise report-fp --rule <rule-id> [--command "<cmd>"] [--expected "<text>"] [--note "<generic reason>"] [--open]';
9
+ /** Redacts local paths, credentialed URLs, tokens, and emails before placing text in an issue URL. */
10
+ function sanitizeFpText(text) {
11
+ return text
12
+ .replaceAll(/\b(?:postgres|mysql|mongodb|redis|https?):\/\/[^/\s]+@[^\s]+/gi, '<redacted-url>')
13
+ .replaceAll(/\bBearer\s+\S+/gi, 'Bearer <redacted-token>')
14
+ .replaceAll(/\b(?:gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]{8,}|(?:AKIA|ASIA)[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]+|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]*)\b/g, '<redacted-token>')
15
+ .replaceAll(/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASS|PWD|DSN|AUTH)[A-Z0-9_]*=[^\s'"]+/gi, '<redacted-env>')
16
+ .replaceAll(/[A-Za-z]:\\[^\s'"`]+/g, '<redacted-path>')
17
+ .replaceAll(/(?<![:\w])\/(?:[^\s'"`/]+\/)+[^\s'"`]+/g, '<redacted-path>')
18
+ .replaceAll(/\b(?![0-9]+\/[0-9]+)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+\.[A-Za-z0-9]{1,10}\b/g, '<redacted-path>')
19
+ .replaceAll(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, '<redacted-email>')
20
+ .replaceAll(/\s+/g, ' ')
21
+ .trim()
22
+ .slice(0, 400);
23
+ }
24
+ /** Validates `rule` and constructs a pre-filled `.github/ISSUE_TEMPLATE/false-positive.yml` URL. */
25
+ function buildFpIssueUrl(options) {
26
+ const rule = options.rule.trim();
27
+ if (!rule || !pillarOfRule(rule)) {
28
+ throw new Error(`Unknown rule "${options.rule}". Pass the rule id from the Loadwise report (for example, array-repeated-find).`);
29
+ }
30
+ const sanitizedCommand = sanitizeFpText(options.command ?? 'npx loadwise check') || 'npx loadwise check';
31
+ const sanitizedExpected = sanitizeFpText(options.expected ?? 'No warning (code is safe or intentional)') ||
32
+ 'No warning (code is safe or intentional)';
33
+ const sanitizedNote = options.note ? sanitizeFpText(options.note) : '';
34
+ const titleSuffix = sanitizedNote ? sanitizedNote.slice(0, 60) : 'false positive';
35
+ const params = new URLSearchParams({
36
+ template: 'false-positive.yml',
37
+ title: `[FP] ${rule}: ${titleSuffix}`,
38
+ rule,
39
+ command: sanitizedCommand,
40
+ expected: sanitizedExpected,
41
+ code: '// Replace with a minimal, anonymized 5-line repro (no proprietary code, file paths, or project names)',
42
+ why: sanitizedNote || 'Describe why this pattern is safe or intentional (without project internals).',
43
+ version: `${packageManifest.version} (Node ${process.version}, ${process.platform})`,
44
+ });
45
+ return `${fpRepoIssuesUrl}?${params.toString()}`;
46
+ }
47
+ function openUrlInBrowser(url) {
48
+ const [command, args] = process.platform === 'win32'
49
+ ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
50
+ : [process.platform === 'darwin' ? 'open' : 'xdg-open', [url]];
51
+ const child = spawn(command, args, { detached: true, stdio: 'ignore' });
52
+ child.on('error', (error) => {
53
+ console.error(`Could not open browser: ${error.message}`);
54
+ });
55
+ child.unref();
56
+ }
57
+ function runReportFp(args) {
58
+ const { values, positionals } = parseArgs({
59
+ args,
60
+ allowPositionals: true,
61
+ options: {
62
+ help: { type: 'boolean', short: 'h' },
63
+ rule: { type: 'string' },
64
+ command: { type: 'string' },
65
+ expected: { type: 'string' },
66
+ note: { type: 'string' },
67
+ open: { type: 'boolean' },
68
+ },
69
+ });
70
+ if (values.help) {
71
+ console.log(fpUsage);
72
+ return 0;
73
+ }
74
+ if (positionals.length > 0 || !values.rule)
75
+ throw new Error(fpUsage);
76
+ const url = buildFpIssueUrl({
77
+ rule: values.rule,
78
+ command: values.command,
79
+ expected: values.expected,
80
+ note: values.note,
81
+ });
82
+ console.log('Privacy-safe false-positive issue link (review the form for any private details before submitting):');
83
+ console.log(url);
84
+ if (values.open) {
85
+ openUrlInBrowser(url);
86
+ console.log('Opened in your default browser. Review and add a minimal anonymized snippet before submitting.');
87
+ }
88
+ else {
89
+ console.log('Re-run with --open to launch this URL in your browser.');
90
+ }
91
+ return 0;
92
+ }
93
+ export { buildFpIssueUrl, runReportFp, sanitizeFpText };
@@ -0,0 +1,10 @@
1
+ const automaticFixSignal = 'loadwise:automatic-fixes-available';
2
+ const collectFixSignals = 'LOADWISE_INTERNAL_COLLECT_FIX_SIGNALS';
3
+ function reportAutomaticFixes(findings) {
4
+ if (!process.send || !process.connected || process.env[collectFixSignals] !== '1')
5
+ return;
6
+ if (findings.some(({ fix }) => fix?.changes.length && !fix.requiresReview)) {
7
+ process.send(automaticFixSignal, undefined, undefined, () => undefined);
8
+ }
9
+ }
10
+ export { automaticFixSignal, collectFixSignals, reportAutomaticFixes };
@@ -0,0 +1,50 @@
1
+ import { wrapWords } from '../fix/fix-terminal.js';
2
+ const findingLine = /^((?:\S.*:\d+(?::\d+)? )?\[[a-z][a-z0-9-]*(?: #[0-9a-f-]+)?\] (?:critical|high|medium|low)): (.*)$/;
3
+ const groupedCount = /^(.*) \((\d+ findings)\)$/;
4
+ const packageHeading = /^-- .+ --$/;
5
+ const summaryLine = /^\d+ (?:(?:source |graph )?file\(s\)(?: checked| compared)?, \d+ |(?:new |contextual )?finding\(s\) )/;
6
+ const countedWord = /(\d+) ((?:(?:source|graph|new|contextual|contract|breaking) )?(?:file|finding|change))\(s\)/g;
7
+ const singleWarning = '1 finding(s) are warnings and do not affect the exit code.';
8
+ const explanationLabel = ' Why: ';
9
+ const maximumWidth = 100;
10
+ function explainLines(message, columns) {
11
+ const width = Math.max(1, Math.min(columns, maximumWidth) - explanationLabel.length);
12
+ const hangingIndent = ' '.repeat(explanationLabel.length);
13
+ return wrapWords(message, width).map((line, index) => (index ? hangingIndent : explanationLabel) + line);
14
+ }
15
+ /** Lay out the combined report while passing through checker-specific details and commands. */
16
+ function formatCheckText(text, columns = process.stdout.columns || maximumWidth) {
17
+ const lines = [];
18
+ let reportedFindings = false;
19
+ for (const line of text.split('\n')) {
20
+ const finding = findingLine.exec(line);
21
+ if (finding) {
22
+ if (reportedFindings && lines.at(-1))
23
+ lines.push('');
24
+ const [, heading, explanation] = finding;
25
+ const group = heading.startsWith('[') ? groupedCount.exec(explanation) : null;
26
+ lines.push(group ? `${heading} (${group[2]})` : heading);
27
+ lines.push(...explainLines(group ? group[1] : explanation, columns));
28
+ reportedFindings = true;
29
+ }
30
+ else if (packageHeading.test(line)) {
31
+ if (lines.at(-1))
32
+ lines.push('');
33
+ lines.push(line);
34
+ reportedFindings = false;
35
+ }
36
+ else if (summaryLine.test(line)) {
37
+ if (reportedFindings && lines.at(-1))
38
+ lines.push('');
39
+ lines.push(line === singleWarning
40
+ ? '1 finding is a warning and does not affect the exit code.'
41
+ : line.replaceAll(countedWord, (_match, count, word) => `${count} ${word}${count === '1' ? '' : 's'}`));
42
+ reportedFindings = false;
43
+ }
44
+ else {
45
+ lines.push(line);
46
+ }
47
+ }
48
+ return lines.join('\n');
49
+ }
50
+ export { formatCheckText };