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