@nerviq/cli 0.9.3 → 0.9.5

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/src/convert.js ADDED
@@ -0,0 +1,336 @@
1
+ /**
2
+ * Nerviq Convert
3
+ *
4
+ * Converts configuration files between AI coding platforms.
5
+ * Reads the source platform's config and emits equivalent config
6
+ * for the target platform, preserving intent where possible.
7
+ *
8
+ * Supported conversions:
9
+ * claude → codex, cursor, copilot, gemini, windsurf, aider
10
+ * codex → claude, cursor, copilot, gemini, windsurf, aider
11
+ * cursor → claude, codex, copilot, gemini, windsurf, aider
12
+ * (any) → (any) using canonical model as intermediary
13
+ */
14
+
15
+ 'use strict';
16
+
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+
20
+ const COLORS = {
21
+ reset: '\x1b[0m',
22
+ bold: '\x1b[1m',
23
+ dim: '\x1b[2m',
24
+ red: '\x1b[31m',
25
+ green: '\x1b[32m',
26
+ yellow: '\x1b[33m',
27
+ blue: '\x1b[36m',
28
+ };
29
+
30
+ function c(text, color) {
31
+ return `${COLORS[color] || ''}${text}${COLORS.reset}`;
32
+ }
33
+
34
+ // ─── Platform config readers ─────────────────────────────────────────────────
35
+
36
+ /**
37
+ * Read the canonical "intent" from a source platform.
38
+ * Returns a normalized object with: name, description, rules[], mcpServers{}, hooks[]
39
+ */
40
+ function readSourceConfig(dir, from) {
41
+ const canonical = {
42
+ platform: from,
43
+ name: path.basename(dir),
44
+ description: null,
45
+ rules: [], // Array of { name, content, alwaysOn, glob, description }
46
+ mcpServers: {}, // { serverName: { command, args, env, url, type } }
47
+ hooks: [], // Array of { event, command, matcher }
48
+ techStack: [], // Detected languages/frameworks
49
+ lintCmd: null,
50
+ testCmd: null,
51
+ buildCmd: null,
52
+ };
53
+
54
+ if (from === 'claude') {
55
+ const claudeMd = fs.existsSync(path.join(dir, 'CLAUDE.md'))
56
+ ? fs.readFileSync(path.join(dir, 'CLAUDE.md'), 'utf8')
57
+ : null;
58
+ if (claudeMd) {
59
+ canonical.description = claudeMd.slice(0, 500);
60
+ canonical.rules.push({ name: 'CLAUDE.md', content: claudeMd, alwaysOn: true });
61
+ }
62
+ // Read .claude/settings.json for MCP
63
+ const settingsPath = path.join(dir, '.claude', 'settings.json');
64
+ if (fs.existsSync(settingsPath)) {
65
+ try {
66
+ const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
67
+ if (settings.mcpServers) canonical.mcpServers = settings.mcpServers;
68
+ } catch {}
69
+ }
70
+ }
71
+
72
+ if (from === 'codex') {
73
+ const agentsMd = fs.existsSync(path.join(dir, 'AGENTS.md'))
74
+ ? fs.readFileSync(path.join(dir, 'AGENTS.md'), 'utf8')
75
+ : null;
76
+ if (agentsMd) {
77
+ canonical.description = agentsMd.slice(0, 500);
78
+ canonical.rules.push({ name: 'AGENTS.md', content: agentsMd, alwaysOn: true });
79
+ }
80
+ }
81
+
82
+ if (from === 'cursor') {
83
+ const rulesDir = path.join(dir, '.cursor', 'rules');
84
+ if (fs.existsSync(rulesDir)) {
85
+ const files = fs.readdirSync(rulesDir).filter(f => f.endsWith('.mdc'));
86
+ for (const file of files) {
87
+ const content = fs.readFileSync(path.join(rulesDir, file), 'utf8');
88
+ // Parse frontmatter
89
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
90
+ let alwaysOn = false;
91
+ let glob = null;
92
+ let desc = null;
93
+ if (fmMatch) {
94
+ alwaysOn = /alwaysApply\s*:\s*true/i.test(fmMatch[1]);
95
+ const globMatch = fmMatch[1].match(/globs?\s*:\s*(.+)/i);
96
+ if (globMatch) glob = globMatch[1].trim();
97
+ const descMatch = fmMatch[1].match(/description\s*:\s*"?([^"\n]+)"?/i);
98
+ if (descMatch) desc = descMatch[1].trim();
99
+ }
100
+ canonical.rules.push({
101
+ name: file.replace('.mdc', ''),
102
+ content,
103
+ alwaysOn,
104
+ glob,
105
+ description: desc,
106
+ });
107
+ }
108
+ }
109
+ // Cursor MCP
110
+ const mcpPath = path.join(dir, '.cursor', 'mcp.json');
111
+ if (fs.existsSync(mcpPath)) {
112
+ try {
113
+ const mcp = JSON.parse(fs.readFileSync(mcpPath, 'utf8'));
114
+ if (mcp.mcpServers) canonical.mcpServers = mcp.mcpServers;
115
+ } catch {}
116
+ }
117
+ }
118
+
119
+ if (from === 'gemini') {
120
+ const geminiMd = fs.existsSync(path.join(dir, 'GEMINI.md'))
121
+ ? fs.readFileSync(path.join(dir, 'GEMINI.md'), 'utf8')
122
+ : null;
123
+ if (geminiMd) {
124
+ canonical.description = geminiMd.slice(0, 500);
125
+ canonical.rules.push({ name: 'GEMINI.md', content: geminiMd, alwaysOn: true });
126
+ }
127
+ }
128
+
129
+ if (from === 'windsurf') {
130
+ const windsurfRulesDir = path.join(dir, '.windsurf', 'rules');
131
+ if (fs.existsSync(windsurfRulesDir)) {
132
+ const files = fs.readdirSync(windsurfRulesDir).filter(f => f.endsWith('.md'));
133
+ for (const file of files) {
134
+ const content = fs.readFileSync(path.join(windsurfRulesDir, file), 'utf8');
135
+ canonical.rules.push({ name: file.replace('.md', ''), content, alwaysOn: true });
136
+ }
137
+ }
138
+ }
139
+
140
+ if (from === 'aider') {
141
+ const aiderConf = fs.existsSync(path.join(dir, '.aider.conf.yml'))
142
+ ? fs.readFileSync(path.join(dir, '.aider.conf.yml'), 'utf8')
143
+ : null;
144
+ if (aiderConf) {
145
+ canonical.rules.push({ name: '.aider.conf.yml', content: aiderConf, alwaysOn: false });
146
+ const lintMatch = aiderConf.match(/lint-cmd\s*:\s*(.+)/);
147
+ if (lintMatch) canonical.lintCmd = lintMatch[1].trim().replace(/^['"]|['"]$/g, '');
148
+ const testMatch = aiderConf.match(/test-cmd\s*:\s*(.+)/);
149
+ if (testMatch) canonical.testCmd = testMatch[1].trim().replace(/^['"]|['"]$/g, '');
150
+ }
151
+ }
152
+
153
+ if (from === 'copilot') {
154
+ const copilotPath = path.join(dir, '.github', 'copilot-instructions.md');
155
+ if (fs.existsSync(copilotPath)) {
156
+ const content = fs.readFileSync(copilotPath, 'utf8');
157
+ canonical.rules.push({ name: 'copilot-instructions', content, alwaysOn: true });
158
+ }
159
+ }
160
+
161
+ return canonical;
162
+ }
163
+
164
+ // ─── Platform config writers ─────────────────────────────────────────────────
165
+
166
+ function buildTargetOutput(canonical, to, { dryRun = false } = {}) {
167
+ const outputs = []; // Array of { path, content }
168
+ const combinedContent = canonical.rules.map(r => r.content).join('\n\n');
169
+
170
+ if (to === 'claude') {
171
+ // Extract or create CLAUDE.md from combined rules
172
+ const content = `# ${canonical.name}\n\n${combinedContent}\n`;
173
+ outputs.push({ file: 'CLAUDE.md', content });
174
+
175
+ if (Object.keys(canonical.mcpServers).length > 0) {
176
+ const settings = { mcpServers: canonical.mcpServers };
177
+ outputs.push({ file: '.claude/settings.json', content: JSON.stringify(settings, null, 2) + '\n' });
178
+ }
179
+ }
180
+
181
+ if (to === 'codex') {
182
+ const content = `# ${canonical.name}\n\n${combinedContent}\n`;
183
+ outputs.push({ file: 'AGENTS.md', content });
184
+ }
185
+
186
+ if (to === 'cursor') {
187
+ // Write each rule as an .mdc file
188
+ if (canonical.rules.length === 0) {
189
+ const content = `---\nalwaysApply: true\n---\n\n# ${canonical.name}\n\n${combinedContent}\n`;
190
+ outputs.push({ file: '.cursor/rules/core.mdc', content });
191
+ } else {
192
+ for (const rule of canonical.rules) {
193
+ const fm = rule.alwaysOn
194
+ ? `---\nalwaysApply: true\n---\n`
195
+ : rule.glob
196
+ ? `---\nglobs: ${rule.glob}\nalwaysApply: false\n---\n`
197
+ : `---\nalwaysApply: false\n---\n`;
198
+ outputs.push({ file: `.cursor/rules/${rule.name}.mdc`, content: `${fm}\n${rule.content}\n` });
199
+ }
200
+ }
201
+ if (Object.keys(canonical.mcpServers).length > 0) {
202
+ const mcp = { mcpServers: canonical.mcpServers };
203
+ outputs.push({ file: '.cursor/mcp.json', content: JSON.stringify(mcp, null, 2) + '\n' });
204
+ }
205
+ }
206
+
207
+ if (to === 'gemini') {
208
+ const content = `# ${canonical.name}\n\n${combinedContent}\n`;
209
+ outputs.push({ file: 'GEMINI.md', content });
210
+ if (Object.keys(canonical.mcpServers).length > 0) {
211
+ const settings = { mcpServers: canonical.mcpServers };
212
+ outputs.push({ file: '.gemini/settings.json', content: JSON.stringify(settings, null, 2) + '\n' });
213
+ }
214
+ }
215
+
216
+ if (to === 'windsurf') {
217
+ if (canonical.rules.length === 0) {
218
+ outputs.push({ file: '.windsurf/rules/core.md', content: `---\ntrigger: always_on\n---\n\n${combinedContent}\n` });
219
+ } else {
220
+ for (const rule of canonical.rules) {
221
+ const fm = `---\ntrigger: always_on\n---\n`;
222
+ const safeContent = rule.content.replace(/^---[\s\S]*?---\n/m, '').trim();
223
+ outputs.push({ file: `.windsurf/rules/${rule.name}.md`, content: `${fm}\n${safeContent}\n` });
224
+ }
225
+ }
226
+ }
227
+
228
+ if (to === 'aider') {
229
+ const confLines = ['# Generated by nerviq convert'];
230
+ if (canonical.lintCmd) confLines.push(`lint-cmd: '${canonical.lintCmd}'`);
231
+ if (canonical.testCmd) confLines.push(`test-cmd: '${canonical.testCmd}'`);
232
+ confLines.push('auto-commits: true');
233
+ confLines.push('auto-lint: true');
234
+ outputs.push({ file: '.aider.conf.yml', content: confLines.join('\n') + '\n' });
235
+ if (combinedContent.trim()) {
236
+ outputs.push({ file: 'CONVENTIONS.md', content: `# ${canonical.name} Conventions\n\n${combinedContent}\n` });
237
+ }
238
+ }
239
+
240
+ if (to === 'copilot') {
241
+ const content = `# ${canonical.name}\n\n${combinedContent}\n`;
242
+ outputs.push({ file: '.github/copilot-instructions.md', content });
243
+ }
244
+
245
+ return outputs;
246
+ }
247
+
248
+ // ─── Main convert function ────────────────────────────────────────────────────
249
+
250
+ async function runConvert({ dir = process.cwd(), from, to, dryRun = false, json = false } = {}) {
251
+ if (!from || !to) {
252
+ throw new Error('Both --from and --to are required. Example: nerviq convert --from claude --to codex');
253
+ }
254
+
255
+ const SUPPORTED = ['claude', 'codex', 'cursor', 'copilot', 'gemini', 'windsurf', 'aider', 'opencode'];
256
+ if (!SUPPORTED.includes(from)) throw new Error(`Unsupported source platform '${from}'. Use: ${SUPPORTED.join(', ')}`);
257
+ if (!SUPPORTED.includes(to)) throw new Error(`Unsupported target platform '${to}'. Use: ${SUPPORTED.join(', ')}`);
258
+ if (from === to) throw new Error(`Source and target platform are the same: '${from}'`);
259
+
260
+ const canonical = readSourceConfig(dir, from);
261
+ const outputs = buildTargetOutput(canonical, to, { dryRun });
262
+
263
+ const written = [];
264
+ const skipped = [];
265
+
266
+ if (!dryRun) {
267
+ for (const out of outputs) {
268
+ const outPath = path.join(dir, out.file);
269
+ const outDir = path.dirname(outPath);
270
+ if (!fs.existsSync(outPath)) {
271
+ fs.mkdirSync(outDir, { recursive: true });
272
+ fs.writeFileSync(outPath, out.content, 'utf8');
273
+ written.push(out.file);
274
+ } else {
275
+ skipped.push(out.file);
276
+ }
277
+ }
278
+ }
279
+
280
+ const result = {
281
+ from,
282
+ to,
283
+ dir,
284
+ dryRun,
285
+ sourceRulesFound: canonical.rules.length,
286
+ mcpServersFound: Object.keys(canonical.mcpServers).length,
287
+ outputFiles: outputs.map(o => o.file),
288
+ written: dryRun ? [] : written,
289
+ skipped: dryRun ? [] : skipped,
290
+ wouldWrite: dryRun ? outputs.map(o => o.file) : [],
291
+ };
292
+
293
+ if (json) return JSON.stringify(result, null, 2);
294
+
295
+ const lines = [''];
296
+ lines.push(c(` nerviq convert ${from} → ${to}`, 'bold'));
297
+ lines.push(c(' ═══════════════════════════════════════', 'dim'));
298
+ lines.push('');
299
+ lines.push(` Source platform: ${c(from, 'blue')} (${canonical.rules.length} rule(s) found)`);
300
+ lines.push(` Target platform: ${c(to, 'blue')}`);
301
+ lines.push(` Directory: ${dir}`);
302
+ lines.push(` MCP servers: ${Object.keys(canonical.mcpServers).length}`);
303
+ lines.push('');
304
+
305
+ if (dryRun) {
306
+ lines.push(c(' Dry run — no files written', 'yellow'));
307
+ lines.push('');
308
+ lines.push(' Would generate:');
309
+ for (const f of outputs) {
310
+ lines.push(` ${c('→', 'dim')} ${f.file}`);
311
+ }
312
+ } else if (written.length > 0 || skipped.length > 0) {
313
+ if (written.length > 0) {
314
+ lines.push(' Written:');
315
+ for (const f of written) lines.push(` ${c('✓', 'green')} ${f}`);
316
+ }
317
+ if (skipped.length > 0) {
318
+ lines.push(' Skipped (already exists):');
319
+ for (const f of skipped) lines.push(` ${c('-', 'dim')} ${f}`);
320
+ }
321
+ }
322
+
323
+ lines.push('');
324
+ if (!dryRun && written.length > 0) {
325
+ lines.push(c(` ✓ Conversion complete. Run \`nerviq audit --platform ${to}\` to verify.`, 'green'));
326
+ } else if (dryRun) {
327
+ lines.push(c(` Run without --dry-run to write files.`, 'dim'));
328
+ } else {
329
+ lines.push(c(` No new files written (all already exist).`, 'dim'));
330
+ }
331
+ lines.push('');
332
+
333
+ return lines.join('\n');
334
+ }
335
+
336
+ module.exports = { runConvert };
@@ -15,6 +15,7 @@ const os = require('os');
15
15
  const path = require('path');
16
16
  const { CopilotProjectContext } = require('./context');
17
17
  const { EMBEDDED_SECRET_PATTERNS, containsEmbeddedSecret } = require('../secret-patterns');
18
+ const { attachSourceUrls } = require('../source-urls');
18
19
  const { extractFrontmatter, validateInstructionFrontmatter, validatePromptFrontmatter } = require('./config-parser');
19
20
 
20
21
  // ─── Shared helpers ─────────────────────────────────────────────────────────
@@ -1928,6 +1929,8 @@ const COPILOT_TECHNIQUES = {
1928
1929
  },
1929
1930
  };
1930
1931
 
1932
+ attachSourceUrls('copilot', COPILOT_TECHNIQUES);
1933
+
1931
1934
  module.exports = {
1932
1935
  COPILOT_TECHNIQUES,
1933
1936
  };
@@ -15,6 +15,7 @@ const os = require('os');
15
15
  const path = require('path');
16
16
  const { CursorProjectContext } = require('./context');
17
17
  const { EMBEDDED_SECRET_PATTERNS, containsEmbeddedSecret } = require('../secret-patterns');
18
+ const { attachSourceUrls } = require('../source-urls');
18
19
  const { validateMdcFrontmatter, validateMcpEnvVars } = require('./config-parser');
19
20
 
20
21
  // ─── Shared helpers ─────────────────────────────────────────────────────────
@@ -1861,6 +1862,8 @@ const CURSOR_TECHNIQUES = {
1861
1862
  },
1862
1863
  };
1863
1864
 
1865
+ attachSourceUrls('cursor', CURSOR_TECHNIQUES);
1866
+
1864
1867
  module.exports = {
1865
1868
  CURSOR_TECHNIQUES,
1866
1869
  };
package/src/doctor.js ADDED
@@ -0,0 +1,253 @@
1
+ /**
2
+ * Nerviq Doctor
3
+ *
4
+ * Self-diagnostics for the nerviq CLI and the current project environment.
5
+ * Checks: Node version, dependencies, platform detection, freshness gates.
6
+ */
7
+
8
+ 'use strict';
9
+
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+ const { version } = require('../package.json');
13
+
14
+ const COLORS = {
15
+ reset: '\x1b[0m',
16
+ bold: '\x1b[1m',
17
+ dim: '\x1b[2m',
18
+ red: '\x1b[31m',
19
+ green: '\x1b[32m',
20
+ yellow: '\x1b[33m',
21
+ blue: '\x1b[36m',
22
+ };
23
+
24
+ function c(text, color) {
25
+ return `${COLORS[color] || ''}${text}${COLORS.reset}`;
26
+ }
27
+
28
+ const PLATFORM_SIGNALS = {
29
+ claude: ['CLAUDE.md', '.claude/CLAUDE.md', '.claude/settings.json'],
30
+ codex: ['AGENTS.md', '.codex/', '.codex/config.toml'],
31
+ cursor: ['.cursor/rules/', '.cursor/mcp.json', '.cursorrules'],
32
+ copilot: ['.github/copilot-instructions.md', '.github/'],
33
+ gemini: ['GEMINI.md', '.gemini/', '.gemini/settings.json'],
34
+ windsurf: ['.windsurf/', '.windsurfrules', '.windsurf/rules/'],
35
+ aider: ['.aider.conf.yml', '.aider.model.settings.yml'],
36
+ opencode: ['opencode.json', '.opencode/'],
37
+ };
38
+
39
+ const FRESHNESS_MODULES = {
40
+ claude: './freshness',
41
+ codex: './codex/freshness',
42
+ cursor: './cursor/freshness',
43
+ copilot: './copilot/freshness',
44
+ gemini: './gemini/freshness',
45
+ windsurf: './windsurf/freshness',
46
+ aider: './aider/freshness',
47
+ opencode: './opencode/freshness',
48
+ };
49
+
50
+ // ─── Individual checks ───────────────────────────────────────────────────────
51
+
52
+ function checkNodeVersion() {
53
+ const raw = process.version.replace('v', '');
54
+ const [major] = raw.split('.').map(Number);
55
+ const ok = major >= 18;
56
+ return {
57
+ label: 'Node.js version',
58
+ status: ok ? 'pass' : 'fail',
59
+ detail: `${process.version} (${ok ? 'meets' : 'below'} minimum v18)`,
60
+ fix: ok ? null : 'Upgrade Node.js to v18 or later: https://nodejs.org',
61
+ };
62
+ }
63
+
64
+ function checkDeps() {
65
+ const pkgPath = path.join(__dirname, '..', 'node_modules');
66
+ const exists = fs.existsSync(pkgPath);
67
+ return {
68
+ label: 'node_modules installed',
69
+ status: exists ? 'pass' : 'fail',
70
+ detail: exists ? `${pkgPath}` : 'node_modules missing',
71
+ fix: exists ? null : 'Run: npm install',
72
+ };
73
+ }
74
+
75
+ function checkJestInstalled() {
76
+ const jestPath = path.join(__dirname, '..', 'node_modules', 'jest', 'package.json');
77
+ const exists = fs.existsSync(jestPath);
78
+ let jestVersion = null;
79
+ if (exists) {
80
+ try {
81
+ jestVersion = require(jestPath).version;
82
+ } catch {}
83
+ }
84
+ return {
85
+ label: 'Jest test runner',
86
+ status: exists ? 'pass' : 'warn',
87
+ detail: exists ? `jest@${jestVersion}` : 'jest not found in node_modules',
88
+ fix: exists ? null : 'Run: npm install --save-dev jest',
89
+ };
90
+ }
91
+
92
+ function checkPlatformDetection(dir) {
93
+ const detected = [];
94
+ for (const [platform, signals] of Object.entries(PLATFORM_SIGNALS)) {
95
+ for (const signal of signals) {
96
+ const signalPath = path.join(dir, signal);
97
+ if (fs.existsSync(signalPath)) {
98
+ detected.push(platform);
99
+ break;
100
+ }
101
+ }
102
+ }
103
+
104
+ return {
105
+ label: 'Platform detection',
106
+ status: detected.length > 0 ? 'pass' : 'warn',
107
+ detail: detected.length > 0
108
+ ? `Detected: ${detected.join(', ')}`
109
+ : 'No platform config files found in current directory',
110
+ detected,
111
+ fix: detected.length === 0
112
+ ? 'Run `nerviq setup` to generate baseline config files for your platform'
113
+ : null,
114
+ };
115
+ }
116
+
117
+ function checkFreshnessGates() {
118
+ const results = [];
119
+ for (const [platform, modulePath] of Object.entries(FRESHNESS_MODULES)) {
120
+ try {
121
+ const freshness = require(modulePath);
122
+ const gate = freshness.checkReleaseGate({});
123
+ results.push({
124
+ platform,
125
+ status: gate.stale.length === 0 ? 'pass' : 'warn',
126
+ fresh: gate.fresh.length,
127
+ total: gate.results.length,
128
+ stale: gate.stale.length,
129
+ detail: gate.stale.length === 0
130
+ ? `All ${gate.results.length} P0 sources fresh`
131
+ : `${gate.stale.length}/${gate.results.length} P0 sources unverified/stale`,
132
+ });
133
+ } catch (e) {
134
+ results.push({ platform, status: 'error', detail: e.message });
135
+ }
136
+ }
137
+ return results;
138
+ }
139
+
140
+ function checkCliPermissions() {
141
+ const cliBin = path.join(__dirname, '..', 'bin', 'cli.js');
142
+ const exists = fs.existsSync(cliBin);
143
+ if (!exists) {
144
+ return { label: 'CLI binary (bin/cli.js)', status: 'fail', detail: 'bin/cli.js not found', fix: null };
145
+ }
146
+ return { label: 'CLI binary (bin/cli.js)', status: 'pass', detail: cliBin, fix: null };
147
+ }
148
+
149
+ function checkGitRepo(dir) {
150
+ const gitPath = path.join(dir, '.git');
151
+ const exists = fs.existsSync(gitPath);
152
+ return {
153
+ label: 'Git repository',
154
+ status: exists ? 'pass' : 'warn',
155
+ detail: exists ? '.git/ found' : 'Not a git repository',
156
+ fix: exists ? null : 'Run: git init (recommended for safety)',
157
+ };
158
+ }
159
+
160
+ // ─── Main doctor function ────────────────────────────────────────────────────
161
+
162
+ async function runDoctor({ dir = process.cwd(), json = false, verbose = false } = {}) {
163
+ const startMs = Date.now();
164
+
165
+ const checks = [
166
+ checkNodeVersion(),
167
+ checkDeps(),
168
+ checkJestInstalled(),
169
+ checkCliPermissions(),
170
+ checkGitRepo(dir),
171
+ checkPlatformDetection(dir),
172
+ ];
173
+
174
+ const freshnessChecks = checkFreshnessGates();
175
+
176
+ const totalPass = checks.filter(c => c.status === 'pass').length;
177
+ const totalWarn = checks.filter(c => c.status === 'warn').length;
178
+ const totalFail = checks.filter(c => c.status === 'fail').length;
179
+
180
+ const freshPass = freshnessChecks.filter(f => f.status === 'pass').length;
181
+ const freshWarn = freshnessChecks.filter(f => f.status !== 'pass').length;
182
+
183
+ const overallOk = totalFail === 0;
184
+ const elapsed = Date.now() - startMs;
185
+
186
+ if (json) {
187
+ return JSON.stringify({
188
+ nerviq: version,
189
+ node: process.version,
190
+ dir,
191
+ overallOk,
192
+ checks,
193
+ freshnessChecks,
194
+ totalPass,
195
+ totalWarn,
196
+ totalFail,
197
+ freshPass,
198
+ freshWarn,
199
+ elapsed,
200
+ }, null, 2);
201
+ }
202
+
203
+ const lines = [''];
204
+ lines.push(c(` nerviq doctor v${version}`, 'bold'));
205
+ lines.push(c(' ═══════════════════════════════════════', 'dim'));
206
+ lines.push('');
207
+
208
+ // Environment checks
209
+ lines.push(c(' Environment', 'bold'));
210
+ for (const chk of checks) {
211
+ const icon = chk.status === 'pass' ? c('✓', 'green') : chk.status === 'warn' ? c('⚠', 'yellow') : c('✗', 'red');
212
+ lines.push(` ${icon} ${chk.label.padEnd(32)} ${c(chk.detail, chk.status === 'pass' ? 'dim' : 'reset')}`);
213
+ if (chk.fix && (verbose || chk.status === 'fail')) {
214
+ lines.push(c(` Fix: ${chk.fix}`, 'yellow'));
215
+ }
216
+ }
217
+
218
+ // Platform detection detail
219
+ const detectedPlatforms = (checks.find(c => c.detected) || {}).detected || [];
220
+ if (detectedPlatforms.length > 0) {
221
+ lines.push('');
222
+ lines.push(c(' Detected Platforms', 'bold'));
223
+ for (const p of detectedPlatforms) {
224
+ lines.push(` ${c('✓', 'green')} ${p}`);
225
+ }
226
+ }
227
+
228
+ // Freshness
229
+ lines.push('');
230
+ lines.push(c(' Freshness Gates', 'bold'));
231
+ for (const f of freshnessChecks) {
232
+ const icon = f.status === 'pass' ? c('✓', 'green') : c('⚠', 'yellow');
233
+ const label = f.platform.padEnd(12);
234
+ lines.push(` ${icon} ${label} ${c(f.detail || f.status, f.status === 'pass' ? 'dim' : 'yellow')}`);
235
+ }
236
+
237
+ lines.push('');
238
+ lines.push(c(' Summary', 'bold'));
239
+ lines.push(` Checks: ${c(String(totalPass), 'green')} pass ${totalWarn > 0 ? c(String(totalWarn), 'yellow') + ' warn ' : ''}${totalFail > 0 ? c(String(totalFail), 'red') + ' fail' : ''}`);
240
+ lines.push(` Freshness: ${c(String(freshPass), 'green')} fresh ${freshWarn > 0 ? c(String(freshWarn), 'yellow') + ' stale/unverified' : ''}`);
241
+ lines.push(` Status: ${overallOk ? c('✓ Healthy', 'green') : c('✗ Issues found', 'red')}`);
242
+ lines.push(` Duration: ${elapsed}ms`);
243
+ lines.push('');
244
+
245
+ if (!overallOk) {
246
+ lines.push(c(' Run with --verbose for fix suggestions.', 'dim'));
247
+ lines.push('');
248
+ }
249
+
250
+ return lines.join('\n');
251
+ }
252
+
253
+ module.exports = { runDoctor };