claude-flow-novice 1.3.1 → 1.3.3

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.
@@ -0,0 +1,347 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Example Usage Script for Language Detection and CLAUDE.md Generation System
5
+ *
6
+ * This script demonstrates all the capabilities of the language detection system
7
+ * and shows how to integrate it into your workflow.
8
+ */
9
+
10
+ import { LanguageDetector } from './language-detector.js';
11
+ import { ClaudeMdGenerator } from './claude-md-generator.js';
12
+ import { IntegrationSystem } from './integration-system.js';
13
+ import path from 'path';
14
+ import fs from 'fs/promises';
15
+
16
+ async function runExample() {
17
+ console.log('šŸš€ Claude Flow Language Detection & CLAUDE.md Generation Demo');
18
+ console.log('═══════════════════════════════════════════════════════════════');
19
+
20
+ const projectPath = process.cwd();
21
+ console.log(`šŸ“ Project Path: ${projectPath}\n`);
22
+
23
+ try {
24
+ // Example 1: Basic Language Detection
25
+ console.log('šŸ“Š Example 1: Basic Language Detection');
26
+ console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
27
+
28
+ const detector = new LanguageDetector(projectPath);
29
+ const detectionResults = await detector.detectProject();
30
+
31
+ console.log(`šŸŽÆ Project Type: ${detectionResults.projectType}`);
32
+ console.log(`šŸ“ˆ Confidence: ${(detectionResults.confidence * 100).toFixed(1)}%`);
33
+
34
+ console.log('\nšŸ’» Detected Languages:');
35
+ for (const [lang, score] of Object.entries(detectionResults.languages)) {
36
+ const bar = 'ā–ˆ'.repeat(Math.floor(score * 20));
37
+ console.log(` ${lang.padEnd(15)} ${bar.padEnd(20)} ${(score * 100).toFixed(1)}%`);
38
+ }
39
+
40
+ if (Object.keys(detectionResults.frameworks).length > 0) {
41
+ console.log('\nšŸš€ Detected Frameworks:');
42
+ for (const [framework, score] of Object.entries(detectionResults.frameworks)) {
43
+ const bar = 'ā–“'.repeat(Math.floor(score * 20));
44
+ console.log(` ${framework.padEnd(15)} ${bar.padEnd(20)} ${(score * 100).toFixed(1)}%`);
45
+ }
46
+ }
47
+
48
+ const recommendations = detector.getRecommendations();
49
+ console.log('\nšŸ’” Recommendations:');
50
+ console.log(` Linting: ${recommendations.linting.join(', ') || 'None detected'}`);
51
+ console.log(` Testing: ${recommendations.testing.join(', ') || 'None detected'}`);
52
+ console.log(` Building: ${recommendations.building.join(', ') || 'None detected'}`);
53
+
54
+ // Example 2: CLAUDE.md Generation
55
+ console.log('\n\nšŸ“ Example 2: CLAUDE.md Generation');
56
+ console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
57
+
58
+ const generator = new ClaudeMdGenerator(projectPath, {
59
+ backupExisting: true,
60
+ preserveCustomSections: true,
61
+ });
62
+
63
+ console.log('šŸ”„ Generating CLAUDE.md with detected languages and frameworks...');
64
+ const claudeContent = await generator.generateClaudeMd();
65
+
66
+ console.log(`āœ… Generated ${claudeContent.length} characters of CLAUDE.md content`);
67
+ console.log('šŸ“„ Preview of generated content:');
68
+
69
+ // Show first few lines of generated content
70
+ const previewLines = claudeContent.split('\n').slice(0, 10);
71
+ previewLines.forEach((line, index) => {
72
+ console.log(
73
+ ` ${(index + 1).toString().padStart(2)}: ${line.substring(0, 80)}${line.length > 80 ? '...' : ''}`,
74
+ );
75
+ });
76
+
77
+ // Example 3: Integration System
78
+ console.log('\n\nšŸ”§ Example 3: Complete Integration System');
79
+ console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
80
+
81
+ const integration = new IntegrationSystem(projectPath, {
82
+ autoDetect: true,
83
+ autoGenerate: true,
84
+ backupExisting: true,
85
+ });
86
+
87
+ // Validate project
88
+ console.log('šŸ”Ž Validating project structure...');
89
+ const validation = await integration.validateProject();
90
+
91
+ console.log(`šŸ“Š Validation Status: ${validation.valid ? 'āœ… Valid' : 'āš ļø Issues Found'}`);
92
+
93
+ if (validation.issues.length > 0) {
94
+ console.log('āŒ Issues:');
95
+ validation.issues.forEach((issue) => {
96
+ console.log(` • ${issue.message}`);
97
+ if (issue.suggestion) {
98
+ console.log(` šŸ’” ${issue.suggestion}`);
99
+ }
100
+ });
101
+ }
102
+
103
+ if (validation.suggestions.length > 0) {
104
+ console.log('šŸ’” Suggestions:');
105
+ validation.suggestions.forEach((suggestion) => {
106
+ console.log(` • ${suggestion.message}`);
107
+ if (suggestion.suggestion) {
108
+ console.log(` → ${suggestion.suggestion}`);
109
+ }
110
+ });
111
+ }
112
+
113
+ // Generate comprehensive report
114
+ console.log('\nšŸ“Š Generating comprehensive project report...');
115
+ const report = await integration.generateProjectReport();
116
+
117
+ console.log(`šŸŽÆ Project Type: ${report.detection.projectType}`);
118
+ console.log(`šŸ“ˆ Detection Confidence: ${(report.detection.confidence * 100).toFixed(1)}%`);
119
+ console.log(`šŸ”§ Configuration: ${Object.keys(report.configuration).length} settings`);
120
+ console.log(`šŸ’” Suggestions: ${report.suggestions.length} recommendations`);
121
+
122
+ // Example 4: Update Detection
123
+ console.log('\n\nšŸ”„ Example 4: Update Detection');
124
+ console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
125
+
126
+ console.log('šŸ” Checking for project changes...');
127
+ const updateResult = await integration.updateForNewTechnology();
128
+
129
+ if (updateResult.changes.hasChanges) {
130
+ console.log(`šŸ“ˆ Changes detected: ${updateResult.changes.summary}`);
131
+
132
+ if (updateResult.changes.newTechnologies.length > 0) {
133
+ console.log('šŸ†• New technologies:');
134
+ updateResult.changes.newTechnologies.forEach((tech) => {
135
+ console.log(` • ${tech.name} (${tech.type})`);
136
+ });
137
+ }
138
+ } else {
139
+ console.log('✨ No changes detected since last scan');
140
+ }
141
+
142
+ // Example 5: Advanced Configuration
143
+ console.log('\n\nāš™ļø Example 5: Advanced Configuration Management');
144
+ console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
145
+
146
+ // Load current configuration
147
+ const config = await integration.loadConfiguration();
148
+ console.log('šŸ“‹ Current configuration keys:');
149
+ Object.keys(config).forEach((key) => {
150
+ console.log(
151
+ ` • ${key}: ${typeof config[key]} ${Array.isArray(config[key]) ? '(array)' : ''}`,
152
+ );
153
+ });
154
+
155
+ // Update preferences
156
+ const newPreferences = {
157
+ ...config,
158
+ includeAdvancedPatterns: true,
159
+ customTimestamp: new Date().toISOString(),
160
+ };
161
+
162
+ await integration.updateConfiguration(newPreferences);
163
+ console.log('āœ… Configuration updated with new preferences');
164
+
165
+ // Example 6: Performance and Statistics
166
+ console.log('\n\nšŸ“Š Example 6: Performance Statistics');
167
+ console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
168
+
169
+ const startTime = Date.now();
170
+
171
+ // Run multiple detections to test performance
172
+ const performanceTests = [];
173
+ for (let i = 0; i < 3; i++) {
174
+ const testStart = Date.now();
175
+ await detector.detectProject();
176
+ const testTime = Date.now() - testStart;
177
+ performanceTests.push(testTime);
178
+ }
179
+
180
+ const totalTime = Date.now() - startTime;
181
+ const avgTime = performanceTests.reduce((a, b) => a + b, 0) / performanceTests.length;
182
+
183
+ console.log(`ā±ļø Performance Metrics:`);
184
+ console.log(` Total Execution Time: ${totalTime}ms`);
185
+ console.log(` Average Detection Time: ${avgTime.toFixed(1)}ms`);
186
+ console.log(` File Analysis Speed: ~${Math.round(1000 / avgTime)} projects/second`);
187
+
188
+ // Example 7: Error Handling and Recovery
189
+ console.log('\n\nšŸ›”ļø Example 7: Error Handling');
190
+ console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
191
+
192
+ try {
193
+ // Test with non-existent directory
194
+ const testDetector = new LanguageDetector('/non/existent/path');
195
+ await testDetector.detectProject();
196
+ } catch (error) {
197
+ console.log(`āœ… Error handling working correctly: ${error.message}`);
198
+ }
199
+
200
+ // Test graceful fallbacks
201
+ const emptyDirGenerator = new ClaudeMdGenerator('/tmp/empty-test-dir', {
202
+ backupExisting: false,
203
+ });
204
+
205
+ try {
206
+ await fs.mkdir('/tmp/empty-test-dir', { recursive: true });
207
+ const emptyContent = await emptyDirGenerator.generateClaudeMd();
208
+ console.log(
209
+ `āœ… Graceful fallback: Generated ${emptyContent.length} characters for empty project`,
210
+ );
211
+ await fs.rmdir('/tmp/empty-test-dir', { recursive: true });
212
+ } catch (error) {
213
+ console.log(`āš ļø Fallback test error (expected): ${error.message}`);
214
+ }
215
+
216
+ // Final Summary
217
+ console.log('\n\nšŸŽ‰ Demo Complete!');
218
+ console.log('═══════════════════════════════════════════════════════════════');
219
+ console.log('āœ… All examples executed successfully');
220
+ console.log('šŸ“Š System is ready for production use');
221
+ console.log('\nšŸš€ Next Steps:');
222
+ console.log(' 1. Run `node src/language/cli.js init` to setup your project');
223
+ console.log(' 2. Use `node src/language/cli.js detect` for language detection');
224
+ console.log(' 3. Use `node src/language/cli.js generate` to create CLAUDE.md');
225
+ console.log(' 4. Use `node src/language/cli.js report` for comprehensive analysis');
226
+ } catch (error) {
227
+ console.error('āŒ Demo failed:', error.message);
228
+ console.error('šŸ“ Stack trace:', error.stack);
229
+ process.exit(1);
230
+ }
231
+ }
232
+
233
+ // CLI usage examples
234
+ function showUsageExamples() {
235
+ console.log('\nšŸ“š CLI Usage Examples');
236
+ console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
237
+
238
+ const examples = [
239
+ {
240
+ command: 'node src/language/cli.js detect',
241
+ description: 'Detect languages in current directory',
242
+ },
243
+ {
244
+ command: 'node src/language/cli.js detect -p /path/to/project --json',
245
+ description: 'Detect languages in specific path, output as JSON',
246
+ },
247
+ {
248
+ command: 'node src/language/cli.js generate --force',
249
+ description: 'Force regenerate CLAUDE.md file',
250
+ },
251
+ {
252
+ command: 'node src/language/cli.js init --interactive',
253
+ description: 'Initialize with interactive setup',
254
+ },
255
+ {
256
+ command: 'node src/language/cli.js update --check-only',
257
+ description: 'Check for changes without updating',
258
+ },
259
+ {
260
+ command: 'node src/language/cli.js report -o report.json',
261
+ description: 'Generate report and save to file',
262
+ },
263
+ {
264
+ command: 'node src/language/cli.js validate',
265
+ description: 'Validate project structure',
266
+ },
267
+ {
268
+ command: 'node src/language/cli.js config show',
269
+ description: 'Show current configuration',
270
+ },
271
+ {
272
+ command: 'node src/language/cli.js config set autoGenerate false',
273
+ description: 'Disable auto-generation',
274
+ },
275
+ {
276
+ command: 'node src/language/cli.js cleanup --days 7',
277
+ description: 'Clean up files older than 7 days',
278
+ },
279
+ ];
280
+
281
+ examples.forEach((example) => {
282
+ console.log(`\nšŸ’» ${example.command}`);
283
+ console.log(` ${example.description}`);
284
+ });
285
+ }
286
+
287
+ // Integration examples with Claude Flow
288
+ function showIntegrationExamples() {
289
+ console.log('\nšŸ”— Integration with Claude Flow Examples');
290
+ console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
291
+
292
+ const integrations = `
293
+ // Package.json scripts integration
294
+ {
295
+ "scripts": {
296
+ "claude:detect": "node src/language/cli.js detect",
297
+ "claude:generate": "node src/language/cli.js generate",
298
+ "claude:init": "node src/language/cli.js init",
299
+ "claude:update": "node src/language/cli.js update",
300
+ "claude:report": "node src/language/cli.js report",
301
+ "postinstall": "node src/language/cli.js update --check-only"
302
+ }
303
+ }
304
+
305
+ // Git hooks integration (.git/hooks/pre-commit)
306
+ #!/bin/sh
307
+ echo "šŸ” Checking for new technologies..."
308
+ node src/language/cli.js update --check-only
309
+ if [ $? -eq 1 ]; then
310
+ echo "āš ļø New technologies detected. Run 'npm run claude:update' to update CLAUDE.md"
311
+ fi
312
+
313
+ // CI/CD integration (.github/workflows/claude-flow.yml)
314
+ name: Claude Flow Integration
315
+ on: [push, pull_request]
316
+ jobs:
317
+ claude-flow:
318
+ runs-on: ubuntu-latest
319
+ steps:
320
+ - uses: actions/checkout@v3
321
+ - uses: actions/setup-node@v3
322
+ - run: npm install
323
+ - run: npm run claude:detect
324
+ - run: npm run claude:validate
325
+ - run: npm run claude:report -- --json > claude-report.json
326
+ - uses: actions/upload-artifact@v3
327
+ with:
328
+ name: claude-report
329
+ path: claude-report.json
330
+
331
+ // Pre-commit hook with husky
332
+ // .husky/pre-commit
333
+ #!/usr/bin/env sh
334
+ npx claude-flow-lang update --check-only
335
+ `;
336
+
337
+ console.log(integrations);
338
+ }
339
+
340
+ // Run the demo
341
+ if (process.argv[2] === '--usage') {
342
+ showUsageExamples();
343
+ } else if (process.argv[2] === '--integration') {
344
+ showIntegrationExamples();
345
+ } else {
346
+ runExample();
347
+ }