scai 0.1.97 → 0.1.98

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/dist/CHANGELOG.md CHANGED
@@ -138,7 +138,6 @@ Type handling with the module pipeline
138
138
  * Improved CLI configuration settings with context-aware actions
139
139
  * Improved logging and added active repo change detection
140
140
 
141
- ## 2025-08-23
141
+ ## 2025-08-24
142
142
 
143
- * Improved CLI configuration settings with context-aware actions
144
- * Added CLI configuration settings with context-aware actions and improved logging
143
+ Improved CLI review command with AI-generated suggestions and enhanced user interface.
@@ -9,11 +9,11 @@ import os from 'os';
9
9
  import path from 'path';
10
10
  import { spawnSync } from 'child_process';
11
11
  import columnify from 'columnify';
12
+ import { Spinner } from '../lib/spinner.js'; // adjust path as needed
12
13
  function truncate(str, length) {
13
14
  return str.length > length ? str.slice(0, length - 3) + '...' : str;
14
15
  }
15
16
  // Fetch open PRs with review requested
16
- import { Spinner } from '../lib/spinner.js'; // adjust path as needed
17
17
  export async function getPullRequestsForReview(token, owner, repo, username, branch = 'main', filterForUser = true) {
18
18
  const spinner = new Spinner('Fetching pull requests and diffs...');
19
19
  spinner.start();
@@ -87,7 +87,6 @@ function askUserToPickPR(prs) {
87
87
  ID: `#${pr.number}`,
88
88
  Title: chalk.gray(truncate(pr.title, 50)),
89
89
  Author: chalk.magentaBright(pr.user || '—'),
90
- Status: pr.draft ? 'Draft' : 'Open',
91
90
  Created: pr.created_at?.split('T')[0] || '',
92
91
  'Requested Reviewers': pr.requested_reviewers?.length
93
92
  ? pr.requested_reviewers.join(', ')
@@ -106,11 +105,12 @@ function askUserToPickPR(prs) {
106
105
  columnSplitter: ' ',
107
106
  headingTransform: (h) => chalk.cyan(h.toUpperCase()),
108
107
  config: {
108
+ '#': { maxWidth: 4 },
109
109
  Title: { maxWidth: 50 },
110
110
  'Requested Reviewers': { maxWidth: 30 },
111
111
  'Actual Reviewers': { maxWidth: 30 },
112
112
  Reviews: { maxWidth: 20 },
113
- }
113
+ },
114
114
  }));
115
115
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
116
116
  rl.question(`\n👉 Choose a PR to review [1-${prs.length}]: `, (answer) => {
@@ -130,9 +130,9 @@ function askUserToPickPR(prs) {
130
130
  function askReviewMethod() {
131
131
  return new Promise((resolve) => {
132
132
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
133
- console.log("\n🔍 Choose review method:");
133
+ console.log(chalk.bold("\n🔍 Choose review method:\n"));
134
134
  console.log('1) Review whole PR at once');
135
- console.log('2) Review chunk by chunk');
135
+ console.log('2) Review chunk by chunk\n');
136
136
  rl.question(`👉 Choose an option [1-2]: `, (answer) => {
137
137
  rl.close();
138
138
  resolve(answer === '2' ? 'chunk' : 'whole');
@@ -255,34 +255,134 @@ function colorDiffLine(line) {
255
255
  return chalk.yellow(line);
256
256
  return line;
257
257
  }
258
- // Review a single chunk
258
+ function parseAISuggestions(aiOutput) {
259
+ return aiOutput
260
+ .split(/\n\d+\.\s/) // Split on "1. ", "2. ", "3. "
261
+ .map(s => s.trim())
262
+ .filter(Boolean)
263
+ .map(s => s.replace(/^💬\s*/, ''));
264
+ }
265
+ async function promptAIReviewSuggestions(aiOutput, chunkContent) {
266
+ // Strip first line if it's a summary like "Here are 4 suggestions:"
267
+ const lines = aiOutput.split('\n');
268
+ if (lines.length > 3 && /^here (are|is).*:?\s*$/i.test(lines[0])) {
269
+ aiOutput = lines.slice(1).join('\n').trim();
270
+ }
271
+ let suggestions = parseAISuggestions(aiOutput);
272
+ let selected = null;
273
+ while (!selected) {
274
+ const colorFuncs = [
275
+ chalk.cyan,
276
+ chalk.green,
277
+ chalk.yellow,
278
+ chalk.magenta,
279
+ chalk.blue,
280
+ chalk.red
281
+ ];
282
+ const rows = suggestions.map((s, i) => ({
283
+ No: String(i + 1).padStart(2),
284
+ Suggestion: colorFuncs[i % colorFuncs.length](s) // cycle through colors
285
+ }));
286
+ const rendered = columnify(rows, {
287
+ columns: ['No', 'Suggestion'],
288
+ showHeaders: false,
289
+ columnSplitter: ' ',
290
+ config: {
291
+ No: {
292
+ align: 'right',
293
+ dataTransform: (val) => chalk.cyan.bold(`${val}.`)
294
+ },
295
+ Suggestion: {
296
+ maxWidth: 80,
297
+ dataTransform: (val) => chalk.white(val)
298
+ }
299
+ }
300
+ });
301
+ console.log('\n' + chalk.yellow(chalk.bold('--- Review Suggestions ---')) + '\n');
302
+ console.log(rendered.replace(/\n/g, '\n\n'));
303
+ console.log();
304
+ console.log(chalk.gray('Select an option above or:'));
305
+ console.log(chalk.cyan(' r)') + ' Regenerate suggestions');
306
+ console.log(chalk.cyan(' c)') + ' Write custom review');
307
+ console.log(chalk.cyan(' s)') + ' Skip this chunk');
308
+ console.log(chalk.cyan(' q)') + ' Cancel review');
309
+ const range = `1-${suggestions.length}`;
310
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
311
+ const answer = await new Promise(resolve => rl.question(chalk.bold(`\n👉 Choose [${range},r,c,s,q]: `), resolve));
312
+ rl.close();
313
+ const trimmed = answer.trim().toLowerCase();
314
+ if (['1', '2', '3'].includes(trimmed)) {
315
+ const idx = parseInt(trimmed, 10) - 1;
316
+ selected = suggestions[idx];
317
+ const rlEdit = readline.createInterface({ input: process.stdin, output: process.stdout });
318
+ const editAnswer = await new Promise(resolve => rlEdit.question('✍️ Edit this suggestion before submitting? [y/N]: ', resolve));
319
+ rlEdit.close();
320
+ if (editAnswer.trim().toLowerCase() === 'y') {
321
+ selected = await promptEditReview(selected);
322
+ }
323
+ }
324
+ else if (trimmed === 'r') {
325
+ console.log(chalk.yellow('\nRegenerating suggestions...\n'));
326
+ const newSuggestion = await reviewModule.run({ content: chunkContent });
327
+ const newOutput = newSuggestion.content || aiOutput;
328
+ suggestions = parseAISuggestions(newOutput);
329
+ }
330
+ else if (trimmed === 'c') {
331
+ selected = await promptCustomReview();
332
+ }
333
+ else if (trimmed === 's') {
334
+ return "skip";
335
+ }
336
+ else if (trimmed === 'q') {
337
+ console.log(chalk.red('\nReview cancelled.\n'));
338
+ return "cancel";
339
+ }
340
+ else {
341
+ console.log(chalk.red('\n⚠️ Invalid input. Try again.\n'));
342
+ }
343
+ }
344
+ console.log(chalk.green('\n✅ Selected suggestion:\n'), selected, '\n');
345
+ const action = await askReviewApproval();
346
+ if (action === 'approve')
347
+ return selected;
348
+ if (action === 'reject')
349
+ return selected;
350
+ if (action === 'edit')
351
+ return await promptEditReview(selected);
352
+ if (action === 'custom')
353
+ return await promptCustomReview();
354
+ if (action === 'cancel') {
355
+ console.log(chalk.yellow('Review cancelled.\n'));
356
+ return "cancel";
357
+ }
358
+ return null;
359
+ }
259
360
  export async function reviewChunk(chunk, chunkIndex, totalChunks) {
260
- const lines = chunk.content.split('\n');
261
- const coloredDiff = lines.map(colorDiffLine).join('\n');
262
361
  console.log(chalk.gray('\n' + '━'.repeat(60)));
263
362
  console.log(`📄 ${chalk.bold('File')}: ${chalk.cyan(chunk.filePath)}`);
264
363
  console.log(`🔢 ${chalk.bold('Chunk')}: ${chunkIndex + 1} of ${totalChunks}`);
364
+ // Build colored diff
365
+ const lines = chunk.content.split('\n');
366
+ const coloredDiff = lines.map(colorDiffLine).join('\n');
367
+ // 1️⃣ Run the AI review
265
368
  const suggestion = await reviewModule.run({
266
369
  content: chunk.content,
267
370
  filepath: chunk.filePath
268
371
  });
269
- const summary = suggestion.content?.trim() || 'AI review summary not available.';
270
- console.log(`🔍 ${chalk.bold('Summary')}: ${summary}`);
372
+ const aiOutput = suggestion.content?.trim() || '1. AI review summary not available.';
373
+ // 2️⃣ Show the diff
271
374
  console.log(`\n${chalk.bold('--- Diff ---')}\n`);
272
375
  console.log(coloredDiff);
273
- console.log(`\n${chalk.bold('--- AI Review ---')}\n`);
274
- console.log(chalk.blue(`💬 ${summary}`));
275
- console.log(chalk.gray('━'.repeat(60)));
276
- const choice = await promptChunkReviewMenu();
277
- if (choice === 'edit') {
278
- const edited = await promptEditReview(summary); // edit based on the suggestion
279
- return { choice: edited, summary: edited };
376
+ // 3️⃣ Prompt user to pick/skip/cancel
377
+ const selectedReview = await promptAIReviewSuggestions(aiOutput, chunk.content);
378
+ if (selectedReview === "cancel") {
379
+ return { choice: "cancel", summary: "" };
280
380
  }
281
- else if (choice === 'skip') {
282
- await waitForSpaceOrQ(); // pause between chunks
283
- return { choice: 'cancel', summary }; // skip this one
381
+ if (selectedReview === "skip") {
382
+ await waitForSpaceOrQ();
383
+ return { choice: "skip", summary: "" };
284
384
  }
285
- return { choice, summary };
385
+ return { choice: selectedReview ?? "", summary: selectedReview ?? "" };
286
386
  }
287
387
  function waitForSpaceOrQ() {
288
388
  return new Promise(resolve => {
@@ -371,24 +471,34 @@ export async function reviewPullRequestCmd(branch = 'main', showAll = false) {
371
471
  const reviewMethod = chunks.length > 1 ? await askReviewMethod() : 'chunk';
372
472
  let reviewComments = [];
373
473
  if (reviewMethod === 'whole') {
374
- const suggestion = await reviewModule.run({ content: diff, filepath: 'Whole PR Diff' });
375
- console.log(chalk.yellowBright("Suggestion: ", suggestion));
474
+ const result = await reviewModule.run({ content: diff, filepath: 'Whole PR Diff' });
475
+ console.log(chalk.yellowBright("Raw AI output:\n"), result.content);
476
+ // Use the parsed array for selecting or displaying suggestions
477
+ let suggestions = result.suggestions;
478
+ if (suggestions && suggestions.length > 3 && /here (are|is) \d+ suggestions/i.test(suggestions[0])) {
479
+ suggestions = suggestions.slice(1);
480
+ }
376
481
  const finalReviewChoice = await askReviewApproval();
377
482
  let reviewText = '';
483
+ // Pick the first suggestion as default if any exist
484
+ if (suggestions && suggestions.length > 0) {
485
+ reviewText = suggestions[0];
486
+ }
378
487
  if (finalReviewChoice === 'approve') {
379
488
  reviewText = 'PR approved';
380
- await submitReview(pr.number, suggestion.content, 'APPROVE');
489
+ await submitReview(pr.number, reviewText, 'APPROVE');
381
490
  }
382
491
  else if (finalReviewChoice === 'reject') {
383
492
  reviewText = 'Changes requested';
384
- await submitReview(pr.number, suggestion.content, 'REQUEST_CHANGES');
493
+ await submitReview(pr.number, reviewText, 'REQUEST_CHANGES');
385
494
  }
386
495
  else if (finalReviewChoice === 'custom') {
387
496
  reviewText = await promptCustomReview();
388
497
  await submitReview(pr.number, reviewText, 'COMMENT');
389
498
  }
390
499
  else if (finalReviewChoice === 'edit') {
391
- reviewText = await promptEditReview(suggestion.content);
500
+ // let user edit the AI suggestion
501
+ reviewText = await promptEditReview(reviewText);
392
502
  await submitReview(pr.number, reviewText, 'COMMENT');
393
503
  }
394
504
  }
@@ -398,7 +508,11 @@ export async function reviewPullRequestCmd(branch = 'main', showAll = false) {
398
508
  for (let i = 0; i < chunks.length; i++) {
399
509
  const chunk = chunks[i];
400
510
  const { choice, summary } = await reviewChunk(chunk, i, chunks.length);
401
- if (choice === 'cancel' || choice === 'skip') {
511
+ if (choice === 'cancel') {
512
+ console.log(chalk.red(`🚫 Review cancelled at chunk ${i + 1}`));
513
+ return; // exit reviewPullRequestCmd early
514
+ }
515
+ if (choice === 'skip') {
402
516
  console.log(chalk.gray(`⏭️ Skipped chunk ${i + 1}`));
403
517
  continue;
404
518
  }
@@ -3,11 +3,11 @@ import path from 'path';
3
3
  import readline from 'readline';
4
4
  import { queryFiles, indexFile } from '../db/fileIndex.js';
5
5
  import { summaryModule } from '../pipeline/modules/summaryModule.js';
6
- import { styleOutput } from '../utils/summarizer.js';
7
6
  import { detectFileType } from '../fileRules/detectFileType.js';
8
7
  import { generateEmbedding } from '../lib/generateEmbedding.js';
9
8
  import { sanitizeQueryForFts } from '../utils/sanitizeQuery.js';
10
9
  import { getDbForRepo } from '../db/client.js';
10
+ import { styleText } from '../utils/outputFormatter.js';
11
11
  export async function summarizeFile(filepath) {
12
12
  let content = '';
13
13
  let filePathResolved;
@@ -40,7 +40,7 @@ export async function summarizeFile(filepath) {
40
40
  const match = matches.find(row => path.resolve(row.path) === filePathResolved);
41
41
  if (match?.summary) {
42
42
  console.log(`🧠 Cached summary for ${filepath}:\n`);
43
- console.log(styleOutput(match.summary));
43
+ console.log(styleText(match.summary));
44
44
  return;
45
45
  }
46
46
  try {
@@ -73,7 +73,7 @@ export async function summarizeFile(filepath) {
73
73
  console.warn('⚠️ No summary generated.');
74
74
  return;
75
75
  }
76
- console.log(styleOutput(response.summary));
76
+ console.log(styleText(response.summary));
77
77
  if (filePathResolved) {
78
78
  const fileType = detectFileType(filePathResolved);
79
79
  indexFile(filePathResolved, response.summary, fileType);
@@ -82,7 +82,6 @@ async function ensureOllamaRunning() {
82
82
  return;
83
83
  }
84
84
  console.log(chalk.yellow('⚙️ Ollama is not running. Attempting to start it...'));
85
- let ollamaStarted = false;
86
85
  try {
87
86
  const child = spawn('ollama', ['serve'], {
88
87
  detached: true,
@@ -6,21 +6,32 @@ export const reviewModule = {
6
6
  async run({ content, filepath }) {
7
7
  const model = Config.getModel();
8
8
  const prompt = `
9
- You are a senior software engineer reviewing a pull request.
10
- ALWAYS make 3 concise suggestions for improvements based on the input code diff.
11
- Use this format ONLY and output ONLY those suggestions:
9
+ Suggest ALWAYS 3 concise suggestions for improvements based on the input code diff.
12
10
 
13
- 1. ...
14
- 2. ...
15
- 3. ...
11
+ - Use one of these types for each suggestion: style, refactor, bug, docs, test
12
+ - Keep each message short, clear, and actionable
13
+
14
+ Format your response exactly as:
15
+
16
+ 1. <type>: <message>
17
+ 2. <type>: <message>
18
+ 3. <type>: <message>
16
19
 
17
20
  Changes:
18
21
  ${content}
19
22
  `.trim();
20
23
  const response = await generate({ content: prompt, filepath }, model);
24
+ // Parse response: only keep numbered lines
25
+ const lines = response.content
26
+ .split('\n')
27
+ .map(line => line.trim())
28
+ .filter(line => /^\d+\.\s+/.test(line));
29
+ // Remove numbering and any surrounding quotes
30
+ const suggestions = lines.map(line => line.replace(/^\d+\.\s+/, '').replace(/^"(.*)"$/, '$1').trim());
21
31
  return {
22
32
  content: response.content,
23
33
  filepath,
34
+ suggestions
24
35
  };
25
36
  }
26
37
  };
@@ -0,0 +1,53 @@
1
+ import columnify from "columnify";
2
+ /**
3
+ * Format structured rows for terminal output.
4
+ */
5
+ export function styleRows(rows, options = {}) {
6
+ if (!rows || rows.length === 0)
7
+ return "";
8
+ const terminalWidth = process.stdout.columns || 80;
9
+ const { maxWidthFraction = 2 / 3 } = options;
10
+ return columnify(rows, {
11
+ columnSplitter: " ",
12
+ maxLineWidth: terminalWidth,
13
+ config: Object.fromEntries(Object.keys(rows[0]).map((key) => [
14
+ key,
15
+ { maxWidth: Math.floor(terminalWidth * maxWidthFraction), align: "left" },
16
+ ])),
17
+ });
18
+ }
19
+ /**
20
+ * Format a plain string for terminal output (wraps lines to terminal width).
21
+ */
22
+ export function styleText(text, options = {}) {
23
+ const terminalWidth = process.stdout.columns || 80;
24
+ const { maxWidthFraction = 2 / 3 } = options;
25
+ const maxWidth = Math.floor(terminalWidth * maxWidthFraction);
26
+ // Wrap each line to maxWidth
27
+ const wrapped = text
28
+ .split("\n")
29
+ .map((line) => {
30
+ if (line.length <= maxWidth)
31
+ return line;
32
+ const chunks = [];
33
+ let start = 0;
34
+ while (start < line.length) {
35
+ chunks.push(line.slice(start, start + maxWidth));
36
+ start += maxWidth;
37
+ }
38
+ return chunks.join("\n");
39
+ })
40
+ .join("\n");
41
+ return wrapped;
42
+ }
43
+ /**
44
+ * Parse numbered suggestions or key-value text into rows for columnify.
45
+ */
46
+ export function parseAndStyleSuggestions(text, options = {}) {
47
+ // Simple parser: each line becomes { No: n, Suggestion: line }
48
+ const rows = text
49
+ .trim()
50
+ .split("\n")
51
+ .map((line, idx) => ({ No: (idx + 1).toString(), Suggestion: line }));
52
+ return styleRows(rows, options);
53
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "scai",
3
- "version": "0.1.97",
3
+ "version": "0.1.98",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "scai": "./dist/index.js"
@@ -1,17 +0,0 @@
1
- import columnify from "columnify";
2
- export function styleOutput(summaryText) {
3
- const terminalWidth = process.stdout.columns || 80;
4
- // Split by line to simulate multiple rows instead of one long wrapped field
5
- const lines = summaryText.trim().split('\n').map(line => ({ Summary: line }));
6
- const formatted = columnify(lines, {
7
- columnSplitter: ' ',
8
- maxLineWidth: terminalWidth,
9
- config: {
10
- Summary: {
11
- maxWidth: Math.floor((terminalWidth * 2) / 3),
12
- align: "left",
13
- },
14
- },
15
- });
16
- return formatted;
17
- }