@rahul05ranjan/dhruv-cli 1.2.4 → 1.4.6

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 (103) hide show
  1. package/.github/ENTERPRISE.md +275 -0
  2. package/.github/ISSUE_TEMPLATE/bug_report.md +45 -17
  3. package/.github/ISSUE_TEMPLATE/documentation_issue.md +61 -0
  4. package/.github/ISSUE_TEMPLATE/feature_request.md +61 -9
  5. package/.github/ISSUE_TEMPLATE/security_vulnerability.md +74 -0
  6. package/.github/dependabot.yml +42 -2
  7. package/.github/pull_request_template.md +13 -0
  8. package/.github/workflows/build-publish.yml +154 -0
  9. package/.github/workflows/ci.yml +251 -18
  10. package/.github/workflows/contribution.yml +169 -27
  11. package/.github/workflows/dependabot-auto-merge.yml +61 -2
  12. package/.github/workflows/deploy.yml +336 -0
  13. package/.github/workflows/monitoring.yml +270 -0
  14. package/.github/workflows/release.yml +229 -0
  15. package/.github/workflows/security.yml +198 -0
  16. package/.releaserc.json +50 -0
  17. package/AGENTS.md +13 -0
  18. package/CHANGELOG.md +8 -0
  19. package/PUBLISHING_FIX.md +92 -0
  20. package/__tests__/core.test.ts +318 -0
  21. package/__tests__/setup.ts +61 -0
  22. package/__tests__/workflows.test.ts +95 -0
  23. package/dist/commands/explain.js +13 -44
  24. package/dist/commands/fix.js +13 -38
  25. package/dist/commands/generate.js +45 -54
  26. package/dist/commands/health.d.ts +1 -0
  27. package/dist/commands/health.js +376 -0
  28. package/dist/commands/init.js +47 -42
  29. package/dist/commands/menu.js +90 -2
  30. package/dist/commands/metrics.d.ts +1 -0
  31. package/dist/commands/metrics.js +51 -0
  32. package/dist/commands/optimize.js +42 -34
  33. package/dist/commands/review.js +52 -48
  34. package/dist/commands/security-check.js +52 -42
  35. package/dist/commands/status.d.ts +1 -0
  36. package/dist/commands/status.js +45 -0
  37. package/dist/commands/suggest.js +13 -39
  38. package/dist/config/config.js +30 -2
  39. package/dist/core/ai.d.ts +77 -2
  40. package/dist/core/ai.js +207 -30
  41. package/dist/core/command-runner.d.ts +17 -0
  42. package/dist/core/command-runner.js +78 -0
  43. package/dist/core/logger.d.ts +40 -0
  44. package/dist/core/logger.js +138 -0
  45. package/dist/core/metrics.d.ts +34 -0
  46. package/dist/core/metrics.js +206 -0
  47. package/dist/core/prompts.d.ts +1 -0
  48. package/dist/core/prompts.js +121 -0
  49. package/dist/core/security.d.ts +34 -0
  50. package/dist/core/security.js +197 -0
  51. package/dist/index.js +40 -2
  52. package/dist/utils/ux.d.ts +3 -0
  53. package/dist/utils/ux.js +15 -0
  54. package/docs/agents/domain.md +51 -0
  55. package/docs/agents/issue-tracker.md +45 -0
  56. package/docs/agents/triage-labels.md +15 -0
  57. package/docs/api/.nojekyll +1 -0
  58. package/docs/api/assets/hierarchy.js +1 -0
  59. package/docs/api/assets/highlight.css +71 -0
  60. package/docs/api/assets/icons.js +18 -0
  61. package/docs/api/assets/icons.svg +1 -0
  62. package/docs/api/assets/main.js +60 -0
  63. package/docs/api/assets/navigation.js +1 -0
  64. package/docs/api/assets/search.js +1 -0
  65. package/docs/api/assets/style.css +1633 -0
  66. package/docs/api/hierarchy.html +1 -0
  67. package/docs/api/index.html +39 -0
  68. package/docs/api/modules.html +1 -0
  69. package/eslint.config.js +170 -0
  70. package/jest.config.json +37 -0
  71. package/lighthouserc.json +22 -0
  72. package/logs/.8a99b6cf655346317fdbf29f4fffcf91131432f3-audit.json +15 -0
  73. package/logs/.eee104bf8fff5ecd38a6a2842df260de6470a7c3-audit.json +15 -0
  74. package/package.json +62 -8
  75. package/src/commands/explain.ts +13 -42
  76. package/src/commands/fix.ts +13 -31
  77. package/src/commands/generate.ts +47 -46
  78. package/src/commands/health.ts +440 -0
  79. package/src/commands/init.ts +48 -42
  80. package/src/commands/menu.ts +86 -2
  81. package/src/commands/metrics.ts +65 -0
  82. package/src/commands/optimize.ts +40 -28
  83. package/src/commands/review.ts +54 -40
  84. package/src/commands/security-check.ts +54 -34
  85. package/src/commands/status.ts +47 -0
  86. package/src/commands/suggest.ts +13 -32
  87. package/src/config/config.ts +35 -2
  88. package/src/core/ai.ts +237 -26
  89. package/src/core/command-runner.ts +105 -0
  90. package/src/core/logger.ts +194 -0
  91. package/src/core/metrics.ts +232 -0
  92. package/src/core/prompts.ts +128 -0
  93. package/src/core/security.ts +243 -0
  94. package/src/index.ts +47 -2
  95. package/src/utils/ux.ts +18 -0
  96. package/test-suite.sh +147 -0
  97. package/tsconfig.json +3 -2
  98. package/typedoc.json +44 -0
  99. package/types/global.d.ts +13 -0
  100. package/validate-workflows.sh +270 -0
  101. package/.eslintignore +0 -1
  102. package/.eslintrc.cjs +0 -43
  103. package/src/core/ai.test.js +0 -40
@@ -1,55 +1,56 @@
1
- import { askOllama } from '../core/ai.js';
2
- import chalk from 'chalk';
3
- import { loadConfig } from '../config/config.js';
4
1
  import fs from 'fs';
5
- import { highlightCode, printError, printSuccess } from '../utils/ux.js';
2
+ import { runCommand } from '../core/command-runner.js';
3
+ import { getSystemMessage } from '../core/prompts.js';
4
+ import { printError, printSuccess } from '../utils/ux.js';
5
+
6
+ function buildPrompt(type: string, content: string): string {
7
+ if (type === 'tests' || type === 'test') {
8
+ return `Generate comprehensive unit tests for the following JavaScript code. Use Jest or Mocha syntax. Only return the test code without explanations:\n\n${content}`;
9
+ }
10
+ if (type === 'documentation' || type === 'docs') {
11
+ return `Generate JSDoc documentation for the following code:\n\n${content}`;
12
+ }
13
+ return `Generate ${type} for this code:\n\n${content}`;
14
+ }
15
+
16
+ /** Extracts test code from the response: a fenced block if present, else the raw response. */
17
+ function extractTestCode(response: string): string {
18
+ const fenced = response.match(/```(?:javascript|js)?\s*\n([\s\S]*?)```/);
19
+ if (fenced?.[1]) return fenced[1].trim();
20
+ return response
21
+ .replace(/^.*?(?=const|describe|test|it\s*\()/s, '')
22
+ .replace(/```[a-z]*\n?/g, '')
23
+ .trim();
24
+ }
6
25
 
7
26
  export async function generate(type: string, target: string) {
8
- const config = loadConfig();
9
- let content = '';
10
- if (fs.existsSync(target)) {
11
- content = fs.readFileSync(target, 'utf-8');
27
+ if (!fs.existsSync(target)) {
28
+ printError(`Target file "${target}" does not exist.`);
29
+ return;
12
30
  }
13
- let streamed = '';
14
- try {
15
- process.stdout.write(chalk.green('Generated code: '));
16
- await askOllama({
17
- prompt: `Generate only a valid JavaScript ${type} file for this code, no explanations, no Markdown, just the code.\n${content}`,
18
- model: config.model,
19
- onToken: (token: string) => {
20
- streamed += token;
21
- process.stdout.write(chalk.cyan(token));
22
- }
23
- });
24
- process.stdout.write('\n');
25
- // Robust code extraction for tests
26
- let codeToSave = streamed;
27
- if (type === 'tests' && target && typeof streamed === 'string') {
28
- const codeBlockMatch = streamed.match(/```(?:[a-z]*)?\n([\s\S]*?)```/);
29
- if (codeBlockMatch && codeBlockMatch[1]) {
30
- codeToSave = codeBlockMatch[1].trim();
31
- } else {
32
- // Remove Markdown, explanations, and keep only lines that look like code
33
- codeToSave = streamed
34
- .replace(/```[a-z]*\n|```/g, '') // remove code block markers
35
- .split('\n')
36
- .filter(line => line.trim() && !/^\s*#|^\s*\/\//.test(line) && /[;{}()=]/.test(line))
37
- .join('\n')
38
- .trim();
31
+
32
+ const content = fs.readFileSync(target, 'utf-8');
33
+
34
+ await runCommand({
35
+ name: 'generate',
36
+ input: { type, target },
37
+ header: `šŸ”Ø Generating ${type}: `,
38
+ buildRequest: (input, model) => ({
39
+ prompt: buildPrompt(input.type, content),
40
+ systemMessage: getSystemMessage('generate'),
41
+ model,
42
+ }),
43
+ onComplete: (response) => {
44
+ if (type !== 'tests' && type !== 'test') return;
45
+ const codeToSave = extractTestCode(response);
46
+ if (!codeToSave) {
47
+ printError('No valid test code generated.');
48
+ return;
39
49
  }
40
50
  const testFile = target.replace(/\.[^.]+$/, '.test.js');
41
51
  fs.writeFileSync(testFile, codeToSave);
42
52
  printSuccess(`Test file saved: ${testFile}`);
43
- }
44
- if (typeof highlightCode === 'function' && streamed.match(/```[a-z]*[\s\S]*?```/)) {
45
- const codeBlocks = streamed.match(/```([a-z]*)\n([\s\S]*?)```/g) || [];
46
- for (const block of codeBlocks) {
47
- const [, lang, code] = block.match(/```([a-z]*)\n([\s\S]*?)```/) || [];
48
- if (code) try { console.log(highlightCode(code, lang || 'js')); } catch (err) { console.error('Highlight error:', err); }
49
- }
50
- }
51
- } catch (err) {
52
- printError('Failed to generate code.');
53
- console.error(chalk.red((err as Error).message));
54
- }
53
+ },
54
+ footer: `šŸ” Want a review? Try: dhruv review ${target}`,
55
+ });
55
56
  }
@@ -0,0 +1,440 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import { loadConfig } from '../config/config.js';
4
+ import { printSuccess, printError, printInfo, printWarning } from '../utils/ux.js';
5
+ import { logger } from '../core/logger.js';
6
+ import { metricsCollector } from '../core/metrics.js';
7
+ import { securityManager } from '../core/security.js';
8
+ import { detectProjectType } from '../utils/projectType.js';
9
+ import fs from 'fs';
10
+ import path from 'path';
11
+ import os from 'os';
12
+
13
+ interface HealthCheckResult {
14
+ category: string;
15
+ status: 'pass' | 'warn' | 'fail';
16
+ message: string;
17
+ details?: unknown;
18
+ recommendation?: string;
19
+ }
20
+
21
+ interface SystemInfo {
22
+ platform: string;
23
+ arch: string;
24
+ nodeVersion: string;
25
+ totalMemory: string;
26
+ freeMemory: string;
27
+ uptime: string;
28
+ cpuCount: number;
29
+ }
30
+
31
+ export async function health(): Promise<void> {
32
+ console.log(chalk.blue.bold('šŸ” Dhruv CLI Health Check\n'));
33
+
34
+ const results: HealthCheckResult[] = [];
35
+ const startTime = Date.now();
36
+
37
+ try {
38
+ // System Information
39
+ const systemInfo = getSystemInfo();
40
+ console.log(chalk.cyan('šŸ“Š System Information:'));
41
+ Object.entries(systemInfo).forEach(([key, value]) => {
42
+ console.log(` ${key}: ${chalk.yellow(value)}`);
43
+ });
44
+ console.log();
45
+
46
+ // Configuration Check
47
+ results.push(...await checkConfiguration());
48
+
49
+ // Dependencies Check
50
+ results.push(...await checkDependencies());
51
+
52
+ // AI Service Check
53
+ results.push(...await checkAIService());
54
+
55
+ // Security Check
56
+ results.push(...await checkSecurity());
57
+
58
+ // Performance Check
59
+ results.push(...await checkPerformance());
60
+
61
+ // File System Check
62
+ results.push(...await checkFileSystem());
63
+
64
+ // Plugin System Check
65
+ results.push(...await checkPlugins());
66
+
67
+ // Display Results
68
+ displayResults(results);
69
+
70
+ const duration = Date.now() - startTime;
71
+ logger.info('Health check completed', { duration, results: results.length });
72
+
73
+ } catch (error) {
74
+ printError('Health check failed');
75
+ console.error(chalk.red((error as Error).message));
76
+ logger.error('Health check failed', error as Error);
77
+ }
78
+ }
79
+
80
+ function getSystemInfo(): SystemInfo {
81
+ const totalMem = os.totalmem();
82
+ const freeMem = os.freemem();
83
+ const uptime = os.uptime();
84
+
85
+ return {
86
+ platform: `${os.platform()} ${os.release()}`,
87
+ arch: os.arch(),
88
+ nodeVersion: process.version,
89
+ totalMemory: `${(totalMem / 1024 / 1024 / 1024).toFixed(2)} GB`,
90
+ freeMemory: `${(freeMem / 1024 / 1024 / 1024).toFixed(2)} GB`,
91
+ uptime: `${Math.floor(uptime / 3600)}h ${Math.floor((uptime % 3600) / 60)}m`,
92
+ cpuCount: os.cpus().length
93
+ };
94
+ }
95
+
96
+ async function checkConfiguration(): Promise<HealthCheckResult[]> {
97
+ const results: HealthCheckResult[] = [];
98
+
99
+ try {
100
+ const config = loadConfig();
101
+
102
+ // Check if config file exists
103
+ const configPath = path.join(process.cwd(), '.dhruv-config.json');
104
+ if (fs.existsSync(configPath)) {
105
+ results.push({
106
+ category: 'Configuration',
107
+ status: 'pass',
108
+ message: 'Configuration file found and loaded successfully'
109
+ });
110
+ } else {
111
+ results.push({
112
+ category: 'Configuration',
113
+ status: 'warn',
114
+ message: 'No configuration file found',
115
+ recommendation: 'Run "dhruv init" to create a configuration file'
116
+ });
117
+ }
118
+
119
+ // Check model configuration
120
+ if (config.model && config.model.trim().length > 0) {
121
+ results.push({
122
+ category: 'Configuration',
123
+ status: 'pass',
124
+ message: `Model configured: ${config.model}`
125
+ });
126
+ } else {
127
+ results.push({
128
+ category: 'Configuration',
129
+ status: 'fail',
130
+ message: 'No model configured',
131
+ recommendation: 'Set a model using "dhruv init" or --model flag'
132
+ });
133
+ }
134
+
135
+ // Check theme configuration
136
+ if (config.theme && ['default', 'dark', 'light', 'mono'].includes(config.theme)) {
137
+ results.push({
138
+ category: 'Configuration',
139
+ status: 'pass',
140
+ message: `Theme configured: ${config.theme}`
141
+ });
142
+ } else {
143
+ results.push({
144
+ category: 'Configuration',
145
+ status: 'warn',
146
+ message: 'Invalid or missing theme configuration',
147
+ recommendation: 'Set theme using "dhruv init"'
148
+ });
149
+ }
150
+
151
+ } catch (error) {
152
+ results.push({
153
+ category: 'Configuration',
154
+ status: 'fail',
155
+ message: `Configuration check failed: ${(error as Error).message}`,
156
+ details: error
157
+ });
158
+ }
159
+
160
+ return results;
161
+ }
162
+
163
+ async function checkDependencies(): Promise<HealthCheckResult[]> {
164
+ const results: HealthCheckResult[] = [];
165
+
166
+ try {
167
+ // Check package.json
168
+ const packagePath = path.join(process.cwd(), 'package.json');
169
+ if (fs.existsSync(packagePath)) {
170
+ const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf-8'));
171
+ results.push({
172
+ category: 'Dependencies',
173
+ status: 'pass',
174
+ message: `Package.json found with ${Object.keys(packageJson.dependencies || {}).length} dependencies`
175
+ });
176
+ } else {
177
+ results.push({
178
+ category: 'Dependencies',
179
+ status: 'fail',
180
+ message: 'package.json not found',
181
+ recommendation: 'Ensure you are in the correct project directory'
182
+ });
183
+ }
184
+
185
+ // Check node_modules
186
+ const nodeModulesPath = path.join(process.cwd(), 'node_modules');
187
+ if (fs.existsSync(nodeModulesPath)) {
188
+ results.push({
189
+ category: 'Dependencies',
190
+ status: 'pass',
191
+ message: 'Node modules installed'
192
+ });
193
+ } else {
194
+ results.push({
195
+ category: 'Dependencies',
196
+ status: 'fail',
197
+ message: 'Node modules not found',
198
+ recommendation: 'Run "npm install" to install dependencies'
199
+ });
200
+ }
201
+
202
+ } catch (error) {
203
+ results.push({
204
+ category: 'Dependencies',
205
+ status: 'fail',
206
+ message: `Dependencies check failed: ${(error as Error).message}`,
207
+ details: error
208
+ });
209
+ }
210
+
211
+ return results;
212
+ }
213
+
214
+ async function checkAIService(): Promise<HealthCheckResult[]> {
215
+ const results: HealthCheckResult[] = [];
216
+
217
+ try {
218
+ // Reuses the AI module's seam — no private Ollama connection here.
219
+ const { listModels } = await import('../core/ai.js');
220
+ await listModels();
221
+ results.push({
222
+ category: 'AI Service',
223
+ status: 'pass',
224
+ message: 'Ollama service is running and accessible'
225
+ });
226
+ } catch (error) {
227
+ results.push({
228
+ category: 'AI Service',
229
+ status: 'fail',
230
+ message: 'Ollama service is not accessible',
231
+ details: error,
232
+ recommendation: 'Start Ollama with "ollama serve"'
233
+ });
234
+ }
235
+
236
+ return results;
237
+ }
238
+
239
+ async function checkSecurity(): Promise<HealthCheckResult[]> {
240
+ const results: HealthCheckResult[] = [];
241
+
242
+ try {
243
+ const securityStatus = securityManager.getSecurityStatus();
244
+
245
+ results.push({
246
+ category: 'Security',
247
+ status: 'pass',
248
+ message: `Security manager active with ${securityStatus.blockedPatternsCount} patterns`,
249
+ details: {
250
+ inputValidation: securityStatus.config.enableInputValidation,
251
+ rateLimiting: securityStatus.config.enableRateLimiting,
252
+ activeRateLimits: securityStatus.activeRateLimits
253
+ }
254
+ });
255
+
256
+ } catch (error) {
257
+ results.push({
258
+ category: 'Security',
259
+ status: 'fail',
260
+ message: `Security check failed: ${(error as Error).message}`,
261
+ details: error
262
+ });
263
+ }
264
+
265
+ return results;
266
+ }
267
+
268
+ async function checkPerformance(): Promise<HealthCheckResult[]> {
269
+ const results: HealthCheckResult[] = [];
270
+
271
+ try {
272
+ // Memory usage check
273
+ const memUsage = process.memoryUsage();
274
+ const memUsageMB = memUsage.heapUsed / 1024 / 1024;
275
+
276
+ if (memUsageMB < 100) {
277
+ results.push({
278
+ category: 'Performance',
279
+ status: 'pass',
280
+ message: `Memory usage: ${memUsageMB.toFixed(2)} MB`
281
+ });
282
+ } else if (memUsageMB < 500) {
283
+ results.push({
284
+ category: 'Performance',
285
+ status: 'warn',
286
+ message: `High memory usage: ${memUsageMB.toFixed(2)} MB`,
287
+ recommendation: 'Monitor memory usage during extended use'
288
+ });
289
+ } else {
290
+ results.push({
291
+ category: 'Performance',
292
+ status: 'fail',
293
+ message: `Excessive memory usage: ${memUsageMB.toFixed(2)} MB`,
294
+ recommendation: 'Restart the application or investigate memory leaks'
295
+ });
296
+ }
297
+
298
+ // Update metrics
299
+ metricsCollector.updateMemoryUsage();
300
+
301
+ } catch (error) {
302
+ results.push({
303
+ category: 'Performance',
304
+ status: 'fail',
305
+ message: `Performance check failed: ${(error as Error).message}`,
306
+ details: error
307
+ });
308
+ }
309
+
310
+ return results;
311
+ }
312
+
313
+ async function checkFileSystem(): Promise<HealthCheckResult[]> {
314
+ const results: HealthCheckResult[] = [];
315
+
316
+ try {
317
+ // Check cache directory
318
+ const cacheDir = path.join(process.cwd(), '.dhruv-cache');
319
+ if (fs.existsSync(cacheDir)) {
320
+ const cacheFiles = fs.readdirSync(cacheDir);
321
+ results.push({
322
+ category: 'File System',
323
+ status: 'pass',
324
+ message: `Cache directory healthy with ${cacheFiles.length} files`
325
+ });
326
+ } else {
327
+ results.push({
328
+ category: 'File System',
329
+ status: 'pass',
330
+ message: 'Cache directory will be created on first use'
331
+ });
332
+ }
333
+
334
+ // Check logs directory
335
+ const logsDir = path.join(process.cwd(), 'logs');
336
+ if (fs.existsSync(logsDir)) {
337
+ const logFiles = fs.readdirSync(logsDir);
338
+ results.push({
339
+ category: 'File System',
340
+ status: 'pass',
341
+ message: `Logs directory healthy with ${logFiles.length} files`
342
+ });
343
+ } else {
344
+ results.push({
345
+ category: 'File System',
346
+ status: 'pass',
347
+ message: 'Logs directory will be created on first use'
348
+ });
349
+ }
350
+
351
+ } catch (error) {
352
+ results.push({
353
+ category: 'File System',
354
+ status: 'fail',
355
+ message: `File system check failed: ${(error as Error).message}`,
356
+ details: error
357
+ });
358
+ }
359
+
360
+ return results;
361
+ }
362
+
363
+ async function checkPlugins(): Promise<HealthCheckResult[]> {
364
+ const results: HealthCheckResult[] = [];
365
+
366
+ try {
367
+ const pluginsDir = path.join(process.cwd(), 'plugins');
368
+
369
+ if (fs.existsSync(pluginsDir)) {
370
+ const pluginFiles = fs.readdirSync(pluginsDir).filter(f => f.endsWith('.js'));
371
+ results.push({
372
+ category: 'Plugins',
373
+ status: 'pass',
374
+ message: `Plugin system active with ${pluginFiles.length} plugins`,
375
+ details: pluginFiles
376
+ });
377
+ } else {
378
+ results.push({
379
+ category: 'Plugins',
380
+ status: 'pass',
381
+ message: 'Plugin system ready (no plugins installed)'
382
+ });
383
+ }
384
+
385
+ } catch (error) {
386
+ results.push({
387
+ category: 'Plugins',
388
+ status: 'fail',
389
+ message: `Plugin check failed: ${(error as Error).message}`,
390
+ details: error
391
+ });
392
+ }
393
+
394
+ return results;
395
+ }
396
+
397
+ function displayResults(results: HealthCheckResult[]): void {
398
+ const categories = ['Configuration', 'Dependencies', 'AI Service', 'Security', 'Performance', 'File System', 'Plugins'];
399
+
400
+ categories.forEach(category => {
401
+ const categoryResults = results.filter(r => r.category === category);
402
+
403
+ if (categoryResults.length > 0) {
404
+ console.log(chalk.cyan(`\nšŸ“‹ ${category}:`));
405
+
406
+ categoryResults.forEach(result => {
407
+ const icon = result.status === 'pass' ? 'āœ…' : result.status === 'warn' ? 'āš ļø' : 'āŒ';
408
+ const color = result.status === 'pass' ? chalk.green : result.status === 'warn' ? chalk.yellow : chalk.red;
409
+
410
+ console.log(` ${icon} ${color(result.message)}`);
411
+
412
+ if (result.details) {
413
+ console.log(` ${chalk.gray(JSON.stringify(result.details, null, 2))}`);
414
+ }
415
+
416
+ if (result.recommendation) {
417
+ console.log(` šŸ’” ${chalk.blue(result.recommendation)}`);
418
+ }
419
+ });
420
+ }
421
+ });
422
+
423
+ // Summary
424
+ const summary = {
425
+ pass: results.filter(r => r.status === 'pass').length,
426
+ warn: results.filter(r => r.status === 'warn').length,
427
+ fail: results.filter(r => r.status === 'fail').length
428
+ };
429
+
430
+ console.log(chalk.blue.bold('\nšŸ“Š Summary:'));
431
+ console.log(` āœ… Passed: ${chalk.green(summary.pass)}`);
432
+ console.log(` āš ļø Warnings: ${chalk.yellow(summary.warn)}`);
433
+ console.log(` āŒ Failed: ${chalk.red(summary.fail)}`);
434
+
435
+ const overallStatus = summary.fail > 0 ? 'fail' : summary.warn > 0 ? 'warn' : 'pass';
436
+ const statusIcon = overallStatus === 'pass' ? 'šŸŽ‰' : overallStatus === 'warn' ? 'āš ļø' : 'āŒ';
437
+ const statusColor = overallStatus === 'pass' ? chalk.green : overallStatus === 'warn' ? chalk.yellow : chalk.red;
438
+
439
+ console.log(`\n${statusIcon} ${statusColor('Overall Status: ' + overallStatus.toUpperCase())}`);
440
+ }
@@ -1,54 +1,60 @@
1
1
  import inquirer from 'inquirer';
2
2
  import { saveConfig, loadConfig } from '../config/config.js';
3
3
  import chalk from 'chalk';
4
+ import { listModels } from '../core/ai.js';
4
5
 
5
6
  export async function init() {
6
7
  const current = loadConfig();
7
8
  let modelChoices = [current.model];
9
+
8
10
  try {
9
- // Dynamically import node-fetch for compatibility
10
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
11
- const fetch: any = (await import('node-fetch')).default;
12
- // Fetch models from Ollama REST API
13
- const res = await fetch('http://localhost:11434/api/tags');
14
- if (res.ok) {
15
- const data = (await res.json()) as { models?: { name: string }[] };
16
- if (Array.isArray(data.models) && data.models.length > 0) {
17
- modelChoices = data.models.map((m) => m.name);
18
- }
11
+ const models = await listModels();
12
+ if (models.length > 0) {
13
+ modelChoices = models;
19
14
  }
20
15
  } catch {
21
- // If Ollama is not running or fails, fallback to current model
16
+ console.log(chalk.yellow('Warning: Could not fetch available models from Ollama.'));
17
+ console.log(chalk.yellow('Using default model choices.'));
18
+ }
19
+
20
+ try {
21
+ const answers = await inquirer.prompt([
22
+ {
23
+ type: 'list',
24
+ name: 'model',
25
+ message: 'Which Ollama model do you want to use?',
26
+ choices: modelChoices,
27
+ default: current.model,
28
+ },
29
+ {
30
+ type: 'list',
31
+ name: 'responseFormat',
32
+ message: 'Preferred response format?',
33
+ choices: ['text', 'json', 'markdown'],
34
+ default: current.responseFormat,
35
+ },
36
+ {
37
+ type: 'confirm',
38
+ name: 'verbose',
39
+ message: 'Enable verbose output?',
40
+ default: current.verbose,
41
+ },
42
+ {
43
+ type: 'list',
44
+ name: 'theme',
45
+ message: 'Choose a color theme:',
46
+ choices: ['default', 'dark', 'light', 'mono'],
47
+ default: current.theme || 'default',
48
+ },
49
+ ]);
50
+
51
+ saveConfig(answers);
52
+ console.log(chalk.green('Configuration saved!'));
53
+ } catch (error) {
54
+ if ((error as { isTtyError?: boolean })?.isTtyError) {
55
+ console.log(chalk.red('This command requires an interactive terminal.'));
56
+ } else {
57
+ console.log(chalk.red('Configuration cancelled or failed.'));
58
+ }
22
59
  }
23
- const answers = await inquirer.prompt([
24
- {
25
- type: 'list',
26
- name: 'model',
27
- message: 'Which Ollama model do you want to use?',
28
- choices: modelChoices,
29
- default: current.model,
30
- },
31
- {
32
- type: 'list',
33
- name: 'responseFormat',
34
- message: 'Preferred response format?',
35
- choices: ['text', 'json', 'markdown'],
36
- default: current.responseFormat,
37
- },
38
- {
39
- type: 'confirm',
40
- name: 'verbose',
41
- message: 'Enable verbose output?',
42
- default: current.verbose,
43
- },
44
- {
45
- type: 'list',
46
- name: 'theme',
47
- message: 'Choose a color theme:',
48
- choices: ['default', 'dark', 'light', 'mono'],
49
- default: current.theme || 'default',
50
- },
51
- ]);
52
- saveConfig(answers);
53
- console.log(chalk.green('Configuration saved!'));
54
60
  }