File size: 8,205 Bytes
7da7e2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import {Options, AIOptions} from './options'
import {Prompts} from './prompts'
import {Bot} from './bot'
import {codeReview} from './review'
import {LocalContextEngine} from './local-context'
import {LocalConsoleReporter} from './console-reporter'
import {feedbackTracker} from './feedback-tracker'
import {execSync} from 'child_process'
import {existsSync} from 'fs'

interface CLIArgs {
  staged?: boolean
  diff?: string
  files?: string[]
  model?: string
  minConfidence?: number
  minSeverity?: 'critical' | 'major' | 'minor' | 'info'
  disableReview?: boolean
  disableReleaseNotes?: boolean
  maxFiles?: number
  pathFilters?: string[]
  systemMessage?: string
  language?: string
  output?: 'console' | 'json'
  help?: boolean
}

const HELP_TEXT = `

PRIX CLI - Local AI PR Reviewer



Usage:

  prix-cli [options]



Options:

  --staged              Review staged files (git diff --cached)

  --diff <ref>          Review files changed since given git ref

  --files <paths>       Review specific files (comma-separated)

  --model <name>        LLM model to use (default: meta-llama/llama-4-scout-17b-16e-instruct)

  --min-confidence <n>  Minimum confidence threshold (0-100)

  --min-severity <lvl>  Minimum severity to report (critical|major|minor|info)

  --disable-review      Skip code review, only generate summary

  --disable-notes       Skip release notes generation

  --max-files <n>       Maximum files to review (0 = unlimited)

  --path-filters <p>    Path filters (comma-separated, e.g., "src/**,lib/**")

  --system-message <m>   Additional system message

  --language <lang>      Output language (default: en-US)

  --output <fmt>        Output format: console (default) or json

  --help, -h            Show this help message



Examples:

  prix-cli --staged                     Review staged changes

  prix-cli --diff HEAD~1                Review changes since last commit

  prix-cli --files src/app.ts,lib/util.ts   Review specific files

  prix-cli --min-severity major         Only show major/critical issues



Pre-commit Hook:

  Add to .git/hooks/pre-commit:

    npx prix-cli --staged --output console

`

function parseArgs(argv: string[]): CLIArgs {
  const args: CLIArgs = {}
  for (let i = 2; i < argv.length; i++) {
    const arg = argv[i]
    switch (arg) {
      case '--staged':
        args.staged = true
        break
      case '--diff':
        args.diff = argv[++i]
        break
      case '--files':
        args.files = argv[++i].split(',')
        break
      case '--model':
        args.model = argv[++i]
        break
      case '--min-confidence':
        args.minConfidence = parseInt(argv[++i], 10)
        break
      case '--min-severity':
        args.minSeverity = argv[++i] as any
        break
      case '--disable-review':
        args.disableReview = true
        break
      case '--disable-notes':
        args.disableReleaseNotes = true
        break
      case '--max-files':
        args.maxFiles = parseInt(argv[++i], 10)
        break
      case '--path-filters':
        args.pathFilters = argv[++i].split(',')
        break
      case '--system-message':
        args.systemMessage = argv[++i]
        break
      case '--language':
        args.language = argv[++i]
        break
      case '--output':
        args.output = argv[++i] as any
        break
      case '--help':
      case '-h':
        args.help = true
        break
    }
  }
  return args
}

function getStagedFiles(): string[] {
  try {
    const output = execSync('git diff --cached --name-only', {
      encoding: 'utf8',
      cwd: process.cwd()
    })
    return output.split('\n').filter(f => f.trim())
  } catch (e) {
    console.error('Failed to get staged files:', e)
    return []
  }
}

function getChangedFiles(sinceRef: string): string[] {
  try {
    const output = execSync(`git diff --name-only ${sinceRef}`, {
      encoding: 'utf8',
      cwd: process.cwd()
    })
    return output.split('\n').filter(f => f.trim())
  } catch (e) {
    console.error(`Failed to get changed files since ${sinceRef}:`, e)
    return []
  }
}

async function runLocalReview(args: CLIArgs): Promise<number> {
  const info = console.log
  const error = console.error

  info('๐Ÿ” PRIX CLI - Starting local code review...\n')

  if (!process.env.GROQ_API_KEY && !process.env.AI_API_KEY) {
    error(
      'โŒ Error: GROQ_API_KEY or AI_API_KEY environment variable is required'
    )
    return 1
  }

  let filesToReview: string[] = []

  if (args.staged) {
    filesToReview = getStagedFiles()
    info(`๐Ÿ“‹ Reviewing ${filesToReview.length} staged files\n`)
  } else if (args.diff) {
    filesToReview = getChangedFiles(args.diff)
    info(
      `๐Ÿ“‹ Reviewing ${filesToReview.length} files changed since ${args.diff}\n`
    )
  } else if (args.files) {
    filesToReview = args.files.filter(f => existsSync(f))
    info(`๐Ÿ“‹ Reviewing ${filesToReview.length} specified files\n`)
  } else {
    error('โŒ Error: Must specify --staged, --diff <ref>, or --files <paths>')
    return 1
  }

  if (filesToReview.length === 0) {
    info('โœ… No files to review')
    return 0
  }

  const options = new Options(
    false,
    args.disableReview || false,
    args.disableReleaseNotes || false,
    args.maxFiles?.toString() || '0',
    false,
    false,
    args.pathFilters || null,
    args.systemMessage || '',
    args.model || 'meta-llama/llama-4-scout-17b-16e-instruct',
    'llama-3.3-70b-versatile',
    '0.0',
    '3',
    '120000',
    '6',
    '6',
    process.env.API_BASE_URL || 'https://api.groq.com/openai/v1',
    args.language || 'en-US',
    false,
    args.minSeverity || 'minor',
    args.minConfidence?.toString() || '0',
    'false',
    'true'
  )

  const prompts = new Prompts()
  const localContext = new LocalContextEngine(filesToReview)
  const reporter = new LocalConsoleReporter()

  info('๐Ÿค– Initializing AI models...')

  let lightBot: Bot | null = null
  let heavyBot: Bot | null = null

  try {
    lightBot = new Bot(
      options,
      new AIOptions(
        options.lightModel,
        options.lightTokenLimits,
        options.modelTemperature
      )
    )
  } catch (e) {
    error(`โŒ Failed to initialize light model: ${e}`)
    return 1
  }

  try {
    heavyBot = new Bot(
      options,
      new AIOptions(
        options.heavyModel,
        options.heavyTokenLimits,
        options.modelTemperature
      )
    )
  } catch (e) {
    error(`โŒ Failed to initialize heavy model: ${e}`)
    return 1
  }

  info('โœ… AI models initialized\n')

  try {
    await localContext.initialize()

    const findings = await localContext.runReview(
      lightBot,
      heavyBot,
      options,
      prompts
    )

    reporter.printFindings(findings, {
      output: args.output || 'console',
      minSeverity: options.minimumSeverity,
      minConfidence: options.minConfidence
    })

    const critical = findings.filter(f => f.severity === 'critical').length
    const major = findings.filter(f => f.severity === 'major').length

    info(
      `\n๐Ÿ“Š Summary: ${critical} critical, ${major} major, ${findings.length} total findings`
    )

    if (critical > 0) {
      info('\nโš ๏ธ  Critical issues found! Consider fixing before committing.')
      return 1
    } else if (major > 0) {
      info('\nโ„น๏ธ  Major issues found. Review recommended before committing.')
      return 0
    } else {
      info('\nโœ… No significant issues found.')
      return 0
    }
  } catch (e) {
    error(`\nโŒ Review failed: ${e}`)
    return 1
  }
}

export async function main(argv: string[]): Promise<number> {
  const args = parseArgs(argv)

  if (args.help) {
    console.log(HELP_TEXT)
    return 0
  }

  return runLocalReview(args)
}

if (require.main === module) {
  main(process.argv)
    .then(code => {
      process.exit(code)
    })
    .catch(e => {
      console.error('Fatal error:', e)
      process.exit(1)
    })
}