-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.ts
More file actions
774 lines (662 loc) · 27.5 KB
/
cli.ts
File metadata and controls
774 lines (662 loc) · 27.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
import { Command } from 'commander';
import chalk from 'chalk';
import ora from 'ora';
import { resolve, basename } from 'node:path';
import { mkdir, writeFile, readFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { analyzeProject } from './analyzers/project-analyzer.js';
import { writeIfChanged } from './utils/write-if-changed.js';
import { extractManualSections, insertManualSections, extractManualTail } from './utils/manual-sections.js';
import {
generatePages,
generateComponents,
generateApiRoutes,
generateLib,
generateSchema,
generateComponentGraph,
generateDependencyMap,
} from './generators/index.js';
import { generateClaudeMd, generateCursorRules, generateCopilotInstructions } from './generators/ai-context-generator.js';
import { saveState, computeDiff, loadState } from './utils/state.js';
import { DEFAULT_CONFIG, type FondamentaConfig } from './types/index.js';
import {
ALL_AGENTS,
runAgents,
printAgentResult,
printFindings,
printSummary,
generateAgentsReport,
} from './agents/index.js';
const VERSION = '0.5.0';
const program = new Command();
program
.name('fondamenta')
.description('Zero-dependency codebase intelligence for AI agents. Static analysis → structured Markdown.')
.version(VERSION);
// ── ANALYZE ──────────────────────────────────────────────────────────
program
.command('analyze')
.description('Analyze a project and generate structured documentation')
.argument('[path]', 'Project root directory', '.')
.option('-o, --output <dir>', 'Output directory', '.planning')
.option('-f, --framework <name>', 'Force framework detection (nextjs-app, nextjs-pages, nuxt, sveltekit, remix)')
.option('--no-schema', 'Skip ORM schema analysis')
.option('--incremental', 'Only regenerate files affected by recent git changes')
.option('--no-preserve-manual', 'Disable manual section preservation (enabled by default)')
.option('-v, --verbose', 'Show detailed progress')
.action(async (path: string, opts: Record<string, unknown>) => {
const projectRoot = resolve(path);
const outputDir = resolve(projectRoot, opts.output as string);
const verbose = opts.verbose as boolean;
printBanner();
if (!existsSync(projectRoot)) {
console.error(chalk.red(` Error: Directory not found: ${projectRoot}`));
process.exit(1);
}
const config = await loadConfig(projectRoot, opts);
// Framework detection
const spinnerDetect = ora(' Detecting framework...').start();
const { detectFramework } = await import('./framework/detector.js');
const detection = await detectFramework(projectRoot);
if (config.framework === 'auto') {
config.framework = detection.framework;
}
spinnerDetect.succeed(
` Framework: ${chalk.cyan(config.framework)} ${chalk.dim(`(${detection.confidence}% confidence)`)}`,
);
if (verbose && detection.signals.length > 0) {
for (const signal of detection.signals) {
console.log(chalk.dim(` → ${signal}`));
}
}
// Incremental mode: use git diff to filter files
if (opts.incremental) {
config.incremental = true;
}
// Analyze
const spinnerAnalyze = ora(' Analyzing codebase...').start();
const result = await analyzeProject(projectRoot, config);
spinnerAnalyze.succeed(
` Analyzed ${chalk.cyan(String(result.totalFiles))} files in ${chalk.cyan(`${result.duration}ms`)}`,
);
const { graph } = result;
printStats(graph);
// Generate outputs
const spinnerGen = ora(' Generating documentation...').start();
const projectName = await getProjectName(projectRoot);
const ctx = {
graph: result.graph,
projectName,
generatedAt: new Date().toISOString().split('T')[0],
};
await mkdir(resolve(outputDir, 'dependencies'), { recursive: true });
const generators = getGenerators(ctx, config, result.framework);
const preserveManual = opts.preserveManual !== false;
let filesWritten = 0;
let filesSkipped = 0;
for (const gen of generators) {
if (!gen.enabled) continue;
let content = gen.fn();
if (!content) continue;
const filePath = resolve(outputDir, gen.path);
// Preserve manual sections from existing file
if (preserveManual) {
try {
const existing = await readFile(filePath, 'utf-8');
const manualSections = extractManualSections(existing);
if (manualSections.length > 0) {
content = insertManualSections(content, manualSections);
}
// Also preserve split-point tail (content after "---\n\n## Manual Notes")
const manualTail = extractManualTail(existing, '## Manual Notes');
if (manualTail) {
content = content.trimEnd() + '\n\n' + manualTail;
}
} catch {
// File doesn't exist yet — nothing to preserve
}
}
// Write only if content changed
const changed = await writeIfChanged(filePath, content);
if (changed) {
filesWritten++;
if (verbose) {
console.log(chalk.dim(` ✓ ${gen.path}`));
}
} else {
filesSkipped++;
if (verbose) {
console.log(chalk.dim(` ○ ${gen.path} (unchanged)`));
}
}
}
// Save state for diff
await saveState(outputDir, projectRoot, config, result.framework, {
pages: graph.pages.length,
components: graph.components.length,
apiRoutes: graph.apiRoutes.length,
libs: graph.libs.length,
models: graph.schema.models.length,
enums: graph.schema.enums.length,
});
const skippedMsg = filesSkipped > 0 ? chalk.dim(` (${filesSkipped} unchanged)`) : '';
spinnerGen.succeed(` Generated ${chalk.cyan(String(filesWritten))} files → ${chalk.cyan(outputDir)}${skippedMsg}`);
console.log('');
console.log(chalk.green(' Done!'));
console.log(chalk.dim(` Output: ${outputDir}`));
console.log('');
});
// ── DIFF ─────────────────────────────────────────────────────────────
program
.command('diff')
.description('Show changes since last analysis')
.argument('[path]', 'Project root directory', '.')
.option('-o, --output <dir>', 'Output directory', '.planning')
.option('--ci', 'Exit with code 1 if analysis is outdated')
.option('--agents', 'Show agent findings diff if AGENTS-REPORT.md exists')
.action(async (path: string, opts: Record<string, unknown>) => {
const projectRoot = resolve(path);
const outputDir = resolve(projectRoot, opts.output as string);
const ciMode = opts.ci as boolean;
printBanner();
const config = await loadConfig(projectRoot, opts);
const previousState = await loadState(outputDir);
if (!previousState) {
console.log(chalk.yellow(' No previous analysis found. Run `fondamenta analyze` first.'));
if (ciMode) process.exit(1);
return;
}
const spinnerDiff = ora(' Computing diff...').start();
const diff = await computeDiff(projectRoot, config, outputDir);
spinnerDiff.stop();
console.log(chalk.dim(` Last analysis: ${previousState.analyzedAt}`));
console.log(chalk.dim(` Framework: ${previousState.framework}`));
console.log('');
if (!diff.isOutdated) {
console.log(chalk.green(' ✓ Analysis is up to date'));
console.log(chalk.dim(` ${diff.unchanged} files unchanged`));
console.log('');
return;
}
// Show changes
if (diff.added.length > 0) {
console.log(chalk.green(` + ${diff.added.length} added`));
for (const f of diff.added.slice(0, 10)) {
console.log(chalk.green(` + ${f}`));
}
if (diff.added.length > 10) {
console.log(chalk.dim(` ... and ${diff.added.length - 10} more`));
}
}
if (diff.modified.length > 0) {
console.log(chalk.yellow(` ~ ${diff.modified.length} modified`));
for (const f of diff.modified.slice(0, 10)) {
console.log(chalk.yellow(` ~ ${f}`));
}
if (diff.modified.length > 10) {
console.log(chalk.dim(` ... and ${diff.modified.length - 10} more`));
}
}
if (diff.removed.length > 0) {
console.log(chalk.red(` - ${diff.removed.length} removed`));
for (const f of diff.removed.slice(0, 10)) {
console.log(chalk.red(` - ${f}`));
}
if (diff.removed.length > 10) {
console.log(chalk.dim(` ... and ${diff.removed.length - 10} more`));
}
}
console.log(chalk.dim(` ${diff.unchanged} unchanged`));
console.log('');
const total = diff.added.length + diff.modified.length + diff.removed.length;
console.log(chalk.yellow(` ⚠ Analysis is outdated (${total} changes). Run \`fondamenta analyze\` to update.`));
console.log('');
// Show agents diff if requested
if (opts.agents) {
const reportPath = resolve(outputDir, 'AGENTS-REPORT.md');
if (existsSync(reportPath)) {
const spinnerAgents = ora(' Running agents...').start();
const result = await analyzeProject(projectRoot, config);
const summary = runAgents(result.graph, config);
spinnerAgents.stop();
const previousReport = await readFile(reportPath, 'utf-8');
const prevFindingsMatch = previousReport.match(/(\d+) findings/);
const prevFindings = prevFindingsMatch ? parseInt(prevFindingsMatch[1]) : 0;
const currentFindings = summary.results.reduce((sum, r) => sum + r.findings.length, 0);
console.log('');
if (currentFindings > prevFindings) {
console.log(chalk.red(` ⚠ ${currentFindings - prevFindings} new findings since last report`));
} else if (currentFindings < prevFindings) {
console.log(chalk.green(` ✓ ${prevFindings - currentFindings} fewer findings since last report`));
} else {
console.log(chalk.dim(` → Agent findings unchanged (${currentFindings})`));
}
} else {
console.log(chalk.dim(' No AGENTS-REPORT.md found. Run `fondamenta agents --report` first.'));
}
}
if (ciMode) process.exit(1);
});
// ── WATCH ────────────────────────────────────────────────────────────
program
.command('watch')
.description('Watch for changes and regenerate documentation')
.argument('[path]', 'Project root directory', '.')
.option('-o, --output <dir>', 'Output directory', '.planning')
.option('-d, --debounce <ms>', 'Debounce interval in ms', '500')
.option('--agents', 'Run code health agents after each regeneration')
.action(async (path: string, opts: Record<string, unknown>) => {
const projectRoot = resolve(path);
const outputDir = resolve(projectRoot, opts.output as string);
const debounceMs = parseInt(opts.debounce as string, 10) || 500;
printBanner();
console.log(chalk.cyan(' Watch mode — press Ctrl+C to stop'));
console.log('');
const config = await loadConfig(projectRoot, opts);
// Initial analysis
console.log(chalk.dim(' Running initial analysis...'));
const initialResult = await analyzeProject(projectRoot, config);
const projectName = await getProjectName(projectRoot);
await mkdir(resolve(outputDir, 'dependencies'), { recursive: true });
await runGeneration(projectRoot, outputDir, config, projectName, initialResult, opts.agents as boolean);
console.log(chalk.green(` ✓ Initial analysis complete (${initialResult.totalFiles} files)`));
console.log('');
// Watch for changes
const { watch } = await import('chokidar');
const watchPatterns = [
resolve(projectRoot, '**/*.ts'),
resolve(projectRoot, '**/*.tsx'),
];
const ignorePatterns = [
'**/node_modules/**',
'**/.next/**',
'**/dist/**',
'**/.planning/**',
];
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
let isRegenerating = false;
const watcher = watch(watchPatterns, {
ignored: ignorePatterns,
persistent: true,
ignoreInitial: true,
});
const regenerate = async () => {
if (isRegenerating) return;
isRegenerating = true;
const spinner = ora(' Regenerating...').start();
try {
const result = await analyzeProject(projectRoot, config);
await runGeneration(projectRoot, outputDir, config, projectName, result, opts.agents as boolean);
spinner.succeed(` Regenerated (${result.totalFiles} files, ${result.duration}ms)`);
} catch (err) {
spinner.fail(` Regeneration failed: ${err}`);
}
isRegenerating = false;
};
const scheduleRegeneration = (filePath: string) => {
const rel = filePath.replace(projectRoot + '/', '');
console.log(chalk.dim(` Changed: ${rel}`));
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(regenerate, debounceMs);
};
watcher
.on('change', scheduleRegeneration)
.on('add', scheduleRegeneration)
.on('unlink', scheduleRegeneration);
console.log(chalk.dim(` Watching ${projectRoot} (debounce: ${debounceMs}ms)`));
console.log('');
// Keep alive
process.on('SIGINT', () => {
console.log('');
console.log(chalk.dim(' Watch mode stopped.'));
watcher.close();
process.exit(0);
});
});
// ── AI-CONTEXT ───────────────────────────────────────────────────────
program
.command('ai-context')
.description('Generate AI-specific context files (CLAUDE.md, .cursorrules, copilot)')
.argument('[path]', 'Project root directory', '.')
.option('-o, --output <dir>', 'Output directory', '.planning')
.option('--claude', 'Generate CLAUDE.md snippet')
.option('--cursor', 'Generate .cursorrules snippet')
.option('--copilot', 'Generate .github/copilot-instructions.md')
.option('--all', 'Generate all AI context files')
.action(async (path: string, opts: Record<string, unknown>) => {
const projectRoot = resolve(path);
const outputDir = resolve(projectRoot, opts.output as string);
const genClaude = opts.claude as boolean || opts.all as boolean;
const genCursor = opts.cursor as boolean || opts.all as boolean;
const genCopilot = opts.copilot as boolean || opts.all as boolean;
if (!genClaude && !genCursor && !genCopilot) {
console.log(chalk.yellow(' Specify at least one target: --claude, --cursor, --copilot, or --all'));
return;
}
printBanner();
const config = await loadConfig(projectRoot, opts);
const spinnerAnalyze = ora(' Analyzing codebase...').start();
const result = await analyzeProject(projectRoot, config);
spinnerAnalyze.succeed(` Analyzed ${chalk.cyan(String(result.totalFiles))} files`);
const projectName = await getProjectName(projectRoot);
const ctx = {
graph: result.graph,
projectName,
generatedAt: new Date().toISOString().split('T')[0],
};
let generated = 0;
if (genClaude) {
const content = generateClaudeMd(ctx, result.framework);
const filePath = resolve(projectRoot, 'CLAUDE.md');
if (existsSync(filePath)) {
// Append to existing
const existing = await readFile(filePath, 'utf-8');
const marker = '# Codebase Context (auto-generated by fondamenta)';
if (existing.includes(marker)) {
// Replace existing section
const before = existing.substring(0, existing.indexOf(marker));
await writeFile(filePath, before.trimEnd() + '\n\n' + content, 'utf-8');
} else {
await writeFile(filePath, existing.trimEnd() + '\n\n' + content, 'utf-8');
}
console.log(chalk.green(` ✓ Updated CLAUDE.md`));
} else {
await writeFile(filePath, content, 'utf-8');
console.log(chalk.green(` ✓ Created CLAUDE.md`));
}
generated++;
}
if (genCursor) {
const content = generateCursorRules(ctx, result.framework);
const filePath = resolve(projectRoot, '.cursorrules');
await writeFile(filePath, content, 'utf-8');
console.log(chalk.green(` ✓ Created .cursorrules`));
generated++;
}
if (genCopilot) {
const dir = resolve(projectRoot, '.github');
await mkdir(dir, { recursive: true });
const content = generateCopilotInstructions(ctx, result.framework);
const filePath = resolve(dir, 'copilot-instructions.md');
await writeFile(filePath, content, 'utf-8');
console.log(chalk.green(` ✓ Created .github/copilot-instructions.md`));
generated++;
}
console.log('');
console.log(chalk.green(` Done! Generated ${generated} AI context files.`));
console.log('');
});
// ── INIT ─────────────────────────────────────────────────────────────
program
.command('init')
.description('Initialize configuration file')
.action(async () => {
const configPath = resolve('fondamenta.config.ts');
if (existsSync(configPath)) {
console.log(chalk.yellow(' fondamenta.config.ts already exists'));
return;
}
const configContent = `import { defineConfig } from 'fondamenta';
export default defineConfig({
output: '.planning',
framework: 'auto',
language: 'en',
generators: {
pages: true,
components: true,
apiRoutes: true,
lib: true,
schemaXref: true,
componentGraph: true,
dependencyMap: true,
},
exclude: [
'**/node_modules/**',
'**/.next/**',
'**/dist/**',
'**/*.test.*',
'**/*.spec.*',
],
schema: {
provider: 'auto',
},
ai: {
generateClaudeMd: false,
generateCursorRules: false,
generateCopilotInstructions: false,
},
});
`;
await writeFile(configPath, configContent, 'utf-8');
console.log(chalk.green(' Created fondamenta.config.ts'));
});
// ── AGENTS ──────────────────────────────────────────────────────────
program
.command('agents')
.description('Run code health agents on the project graph')
.argument('[path]', 'Project root directory', '.')
.option('-o, --output <dir>', 'Output directory', '.planning')
.option('--free', 'Run only free-tier agents')
.option('--agent <id>', 'Run a single agent by ID')
.option('--ci', 'Exit with code 1 if errors are found')
.option('--report', 'Generate AGENTS-REPORT.md in output directory')
.option('--list', 'List all available agents')
.option('--json', 'Output results as JSON')
.option('-f, --framework <name>', 'Force framework detection')
.action(async (path: string, opts: Record<string, unknown>) => {
const projectRoot = resolve(path);
const outputDir = resolve(projectRoot, opts.output as string);
const jsonMode = opts.json as boolean;
if (!jsonMode) {
printBanner();
}
// --list: just show agents and exit
if (opts.list) {
if (!jsonMode) {
console.log(chalk.dim(' Available agents:'));
console.log('');
for (const agent of ALL_AGENTS) {
const tierBadge = agent.tier === 'free'
? chalk.green(' FREE ')
: chalk.yellow(' PRO ');
console.log(` ${tierBadge} ${chalk.bold(agent.id)}`);
console.log(chalk.dim(` ${agent.description}`));
}
console.log('');
console.log(chalk.dim(` ${ALL_AGENTS.filter(a => a.tier === 'free').length} free, ${ALL_AGENTS.filter(a => a.tier === 'pro').length} pro`));
console.log('');
}
return;
}
if (!existsSync(projectRoot)) {
console.error(chalk.red(` Error: Directory not found: ${projectRoot}`));
process.exit(1);
}
const config = await loadConfig(projectRoot, opts);
// Analyze the project
let startTime = Date.now();
const spinnerAnalyze = jsonMode ? null : ora(' Analyzing codebase...').start();
const result = await analyzeProject(projectRoot, config);
if (spinnerAnalyze) {
spinnerAnalyze.succeed(
` Analyzed ${chalk.cyan(String(result.totalFiles))} files in ${chalk.cyan(`${result.duration}ms`)}`,
);
}
// Run agents
const agentStartTime = Date.now();
const spinnerAgents = jsonMode ? null : ora(' Running agents...').start();
const agentOptions: { freeOnly?: boolean; agentIds?: string[] } = {};
if (opts.free) agentOptions.freeOnly = true;
if (opts.agent) agentOptions.agentIds = [opts.agent as string];
const summary = runAgents(result.graph, config, agentOptions);
const agentDuration = Date.now() - agentStartTime;
if (spinnerAgents) {
spinnerAgents.stop();
}
// JSON output mode
if (jsonMode) {
const jsonOutput = {
version: VERSION,
timestamp: new Date().toISOString(),
summary: {
totalFindings: summary.results.reduce((sum, r) => sum + r.findings.length, 0),
errors: summary.errors,
warnings: summary.warnings,
infos: summary.infos,
agentsRan: summary.results.filter((r) => !r.skipped).length,
agentsSkipped: summary.results.filter((r) => r.skipped).length,
totalDurationMs: agentDuration,
},
results: summary.results.map((agentResult) => ({
agentId: agentResult.agentId,
tier: agentResult.tier,
skipped: agentResult.skipped,
skipReason: agentResult.skipReason,
durationMs: agentResult.durationMs,
findings: agentResult.findings,
})),
};
console.log(JSON.stringify(jsonOutput, null, 2));
// CI mode: exit with error if findings include errors
if (opts.ci && summary.errors > 0) {
process.exit(1);
}
return;
}
console.log('');
// Print per-agent results
for (const agentResult of summary.results) {
printAgentResult(agentResult, ALL_AGENTS);
}
// Print detailed findings (errors first, then warnings)
const errorsAndWarnings = summary.results
.flatMap((r) => r.findings)
.filter((f) => f.severity === 'error' || f.severity === 'warning');
printFindings(errorsAndWarnings);
// Print summary line
console.log('');
printSummary(summary);
console.log('');
// Generate report if requested
if (opts.report) {
await mkdir(outputDir, { recursive: true });
const reportPath = resolve(outputDir, 'AGENTS-REPORT.md');
const reportContent = generateAgentsReport(summary, ALL_AGENTS);
await writeFile(reportPath, reportContent, 'utf-8');
console.log(chalk.green(` Report saved to ${reportPath}`));
console.log('');
}
// CI mode: exit with error if findings include errors
if (opts.ci && summary.errors > 0) {
process.exit(1);
}
});
program.parse();
// ── HELPERS ──────────────────────────────────────────────────────────
function printBanner() {
console.log('');
console.log(chalk.bold(' FONDAMENTA'));
console.log(chalk.dim(` v${VERSION} — Zero-dependency codebase intelligence`));
console.log('');
}
function printStats(graph: import('./types/index.js').ProjectGraph) {
console.log('');
console.log(chalk.dim(' Found:'));
console.log(chalk.dim(` ${graph.pages.length} pages`));
console.log(chalk.dim(` ${graph.components.length} components/hooks`));
console.log(chalk.dim(` ${graph.apiRoutes.length} API routes`));
console.log(chalk.dim(` ${graph.libs.length} lib files`));
console.log(chalk.dim(` ${graph.schema.models.length} DB models, ${graph.schema.enums.length} enums`));
console.log('');
}
function getGenerators(
ctx: { graph: import('./types/index.js').ProjectGraph; projectName: string; generatedAt: string },
config: FondamentaConfig,
framework: import('./types/index.js').Framework,
) {
return [
{ name: 'pages', fn: () => generatePages(ctx), path: 'dependencies/pages-atomic.md', enabled: config.generators.pages },
{ name: 'components', fn: () => generateComponents(ctx), path: 'dependencies/components-atomic.md', enabled: config.generators.components },
{ name: 'api-routes', fn: () => generateApiRoutes(ctx), path: 'dependencies/api-routes-atomic.md', enabled: config.generators.apiRoutes },
{ name: 'lib', fn: () => generateLib(ctx), path: 'dependencies/lib-atomic.md', enabled: config.generators.lib },
{ name: 'schema', fn: () => generateSchema(ctx), path: 'dependencies/schema-crossref-atomic.md', enabled: config.generators.schemaXref },
{ name: 'component-graph', fn: () => generateComponentGraph(ctx), path: 'dependencies/component-graph.md', enabled: config.generators.componentGraph },
{ name: 'dependency-map', fn: () => generateDependencyMap(ctx, framework), path: 'DEPENDENCY-MAP.md', enabled: config.generators.dependencyMap },
];
}
async function runGeneration(
projectRoot: string,
outputDir: string,
config: FondamentaConfig,
projectName: string,
result: import('./analyzers/project-analyzer.js').AnalysisResult,
runAgentsFlag?: boolean,
) {
const ctx = {
graph: result.graph,
projectName,
generatedAt: new Date().toISOString().split('T')[0],
};
const generators = getGenerators(ctx, config, result.framework);
for (const gen of generators) {
if (!gen.enabled) continue;
const content = gen.fn();
if (content) {
const filePath = resolve(outputDir, gen.path);
await writeIfChanged(filePath, content);
}
}
await saveState(outputDir, projectRoot, config, result.framework, {
pages: result.graph.pages.length,
components: result.graph.components.length,
apiRoutes: result.graph.apiRoutes.length,
libs: result.graph.libs.length,
models: result.graph.schema.models.length,
enums: result.graph.schema.enums.length,
});
// Run agents if requested
if (runAgentsFlag) {
const summary = runAgents(result.graph, config);
printSummary(summary);
}
}
async function loadConfig(
projectRoot: string,
opts: Record<string, unknown>,
): Promise<FondamentaConfig> {
let config: FondamentaConfig = { ...DEFAULT_CONFIG };
// Load fondamenta.config.ts if present
const configPath = resolve(projectRoot, 'fondamenta.config.ts');
if (existsSync(configPath)) {
try {
const raw = await readFile(configPath, 'utf-8');
// Extract license key from config file via regex (avoids ts execution)
const licenseMatch = raw.match(/license:\s*['"](FA-PRO-[^'"]+)['"]/);
if (licenseMatch) {
if (!config.agents) config.agents = {} as any;
(config.agents as any).license = licenseMatch[1];
}
} catch {
// ignore config read errors
}
}
if (opts.output) config.output = opts.output as string;
if (opts.framework) config.framework = opts.framework as any;
if (opts.schema === false) config.schema.provider = 'none';
return config;
}
async function getProjectName(projectRoot: string): Promise<string> {
try {
const pkgPath = resolve(projectRoot, 'package.json');
if (existsSync(pkgPath)) {
const pkg = JSON.parse(await readFile(pkgPath, 'utf-8'));
return pkg.name || basename(projectRoot);
}
} catch {
// ignore
}
return basename(projectRoot);
}
export function defineConfig(config: Partial<FondamentaConfig>): FondamentaConfig {
return { ...DEFAULT_CONFIG, ...config };
}