@polymorphism-tech/morph-spec 3.1.0 → 3.2.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 (51) hide show
  1. package/CLAUDE.md +534 -0
  2. package/README.md +78 -4
  3. package/bin/morph-spec.js +50 -1
  4. package/bin/render-template.js +56 -10
  5. package/bin/task-manager.cjs +101 -7
  6. package/docs/cli-auto-detection.md +219 -0
  7. package/docs/llm-interaction-config.md +735 -0
  8. package/docs/troubleshooting.md +269 -0
  9. package/package.json +5 -1
  10. package/src/commands/advance-phase.js +93 -2
  11. package/src/commands/approve.js +221 -0
  12. package/src/commands/capture-pattern.js +121 -0
  13. package/src/commands/generate.js +128 -1
  14. package/src/commands/init.js +37 -0
  15. package/src/commands/migrate-state.js +158 -0
  16. package/src/commands/search-patterns.js +126 -0
  17. package/src/commands/spawn-team.js +172 -0
  18. package/src/commands/task.js +2 -2
  19. package/src/commands/update.js +36 -0
  20. package/src/commands/upgrade.js +346 -0
  21. package/src/generator/.gitkeep +0 -0
  22. package/src/generator/config-generator.js +206 -0
  23. package/src/generator/templates/config.json.template +40 -0
  24. package/src/generator/templates/project.md.template +67 -0
  25. package/src/lib/checkpoint-hooks.js +258 -0
  26. package/src/lib/metadata-extractor.js +380 -0
  27. package/src/lib/phase-state-machine.js +214 -0
  28. package/src/lib/state-manager.js +120 -0
  29. package/src/lib/template-data-sources.js +325 -0
  30. package/src/lib/validators/content-validator.js +351 -0
  31. package/src/llm/.gitkeep +0 -0
  32. package/src/llm/analyzer.js +215 -0
  33. package/src/llm/environment-detector.js +43 -0
  34. package/src/llm/few-shot-examples.js +216 -0
  35. package/src/llm/project-config-schema.json +188 -0
  36. package/src/llm/prompt-builder.js +96 -0
  37. package/src/llm/schema-validator.js +121 -0
  38. package/src/orchestrator.js +206 -0
  39. package/src/sanitizer/.gitkeep +0 -0
  40. package/src/sanitizer/context-sanitizer.js +221 -0
  41. package/src/sanitizer/patterns.js +163 -0
  42. package/src/scanner/.gitkeep +0 -0
  43. package/src/scanner/project-scanner.js +242 -0
  44. package/src/types/index.js +477 -0
  45. package/src/ui/.gitkeep +0 -0
  46. package/src/ui/diff-display.js +91 -0
  47. package/src/ui/interactive-wizard.js +96 -0
  48. package/src/ui/user-review.js +211 -0
  49. package/src/ui/wizard-questions.js +190 -0
  50. package/src/writer/.gitkeep +0 -0
  51. package/src/writer/file-writer.js +86 -0
@@ -0,0 +1,121 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import { appendFileSync, existsSync, readFileSync } from 'fs';
4
+ import { join } from 'path';
5
+
6
+ /**
7
+ * Capture Pattern Command - Document lessons learned
8
+ *
9
+ * Appends patterns to patterns-learned.md for future reference
10
+ */
11
+
12
+ const program = new Command();
13
+
14
+ const VALID_CATEGORIES = ['success', 'avoid', 'optimization', 'security', 'convention', 'best-practice'];
15
+
16
+ program
17
+ .name('capture-pattern')
18
+ .description('Capture a pattern or lesson learned from a feature')
19
+ .argument('<feature>', 'Feature name')
20
+ .argument('<category>', `Pattern category (${VALID_CATEGORIES.join(', ')})`)
21
+ .argument('<description>', 'Brief description of the pattern')
22
+ .option('--auto', 'Auto-capture without opening editor', false)
23
+ .action(async (featureName, category, description, options) => {
24
+ try {
25
+ // Validate category
26
+ if (!VALID_CATEGORIES.includes(category)) {
27
+ console.error(chalk.red(`\n❌ Invalid category: ${category}`));
28
+ console.log(chalk.gray(`Valid categories: ${VALID_CATEGORIES.join(', ')}\n`));
29
+ process.exit(1);
30
+ }
31
+
32
+ // Get patterns file path
33
+ const patternsPath = join(process.cwd(), '.morph/memory/patterns-learned.md');
34
+
35
+ if (!existsSync(patternsPath)) {
36
+ console.error(chalk.red(`\n❌ Patterns file not found: ${patternsPath}`));
37
+ console.log(chalk.yellow('Run "morph-spec init" to create the file.\n'));
38
+ process.exit(1);
39
+ }
40
+
41
+ // Create pattern entry
42
+ const timestamp = new Date().toISOString().split('T')[0];
43
+ const categoryDisplay = category === 'avoid' ? 'Anti-Pattern to Avoid' :
44
+ category === 'success' ? 'Best Practice' :
45
+ category === 'optimization' ? 'Performance Optimization' :
46
+ category === 'security' ? 'Security Best Practice' :
47
+ category === 'convention' ? 'Convention' :
48
+ 'Best Practice';
49
+
50
+ const patternTemplate = `
51
+
52
+ ---
53
+
54
+ ## Pattern: ${description}
55
+
56
+ **Source:** Feature \`${featureName}\` (${timestamp})
57
+ **Category:** ${categoryDisplay}
58
+ **Date:** ${timestamp}
59
+
60
+ **Problem:**
61
+ [Describe the problem this pattern solves]
62
+
63
+ **Implementation:**
64
+ \`\`\`csharp
65
+ // Add code example here
66
+ \`\`\`
67
+
68
+ **Why:**
69
+ - [Reason 1]
70
+ - [Reason 2]
71
+
72
+ **When to Use:**
73
+ [Describe scenarios where this pattern applies]
74
+
75
+ **Reuse:** [List features/scenarios where this can be reused]
76
+
77
+ ---
78
+ `;
79
+
80
+ // Append to file
81
+ appendFileSync(patternsPath, patternTemplate, 'utf8');
82
+
83
+ console.log(chalk.green(`\n✅ Pattern captured successfully`));
84
+ console.log(chalk.cyan(` Feature: ${featureName}`));
85
+ console.log(chalk.cyan(` Category: ${categoryDisplay}`));
86
+ console.log(chalk.cyan(` Description: ${description}\n`));
87
+
88
+ if (!options.auto) {
89
+ console.log(chalk.bold('📝 Next Steps:'));
90
+ console.log(chalk.gray(`1. Edit ${patternsPath}`));
91
+ console.log(chalk.gray('2. Fill in: Problem, Implementation (code), Why, When to Use'));
92
+ console.log(chalk.gray('3. Add code examples and rationale\n'));
93
+ }
94
+
95
+ // Show location in file
96
+ const content = readFileSync(patternsPath, 'utf8');
97
+ const lines = content.split('\n');
98
+ const patternLine = lines.findIndex(line => line.includes(`Pattern: ${description}`));
99
+
100
+ if (patternLine !== -1) {
101
+ console.log(chalk.gray(`Pattern added at line ${patternLine + 1}`));
102
+ }
103
+
104
+ console.log(chalk.gray(`\nFile: ${patternsPath}\n`));
105
+
106
+ } catch (error) {
107
+ console.error(chalk.red(`\n❌ Error capturing pattern: ${error.message}\n`));
108
+ process.exit(1);
109
+ }
110
+ });
111
+
112
+ // Only parse if run directly (not imported as module)
113
+ if (import.meta.url === `file://${process.argv[1]}`) {
114
+ if (process.argv.length > 2) {
115
+ program.parse(process.argv);
116
+ } else {
117
+ program.help();
118
+ }
119
+ }
120
+
121
+ export default program;
@@ -4,11 +4,13 @@
4
4
  */
5
5
 
6
6
  import { mkdirSync, writeFileSync } from 'fs';
7
- import { dirname } from 'path';
7
+ import { dirname, join } from 'path';
8
8
  import ora from 'ora';
9
9
  import chalk from 'chalk';
10
10
  import { logger } from '../utils/logger.js';
11
11
  import * as DesignSystemGenerator from '../lib/design-system-generator.js';
12
+ import { getFeature } from '../lib/state-manager.js';
13
+ import { extractFeatureMetadata } from '../lib/metadata-extractor.js';
12
14
 
13
15
  // ============================================================================
14
16
  // Design System Subcommand
@@ -118,6 +120,126 @@ export async function generateDesignSystemCommand(designSystemPath, options) {
118
120
  }
119
121
  }
120
122
 
123
+ // ============================================================================
124
+ // Metadata Subcommand
125
+ // ============================================================================
126
+
127
+ /**
128
+ * Generate metadata.json from feature outputs
129
+ * @param {string} featureName - Feature name
130
+ * @param {Object} options - CLI options
131
+ */
132
+ export async function generateMetadataCommand(featureName, options) {
133
+ if (!featureName) {
134
+ logger.error('Feature name required');
135
+ logger.dim(' Usage: morph-spec generate metadata <feature>');
136
+ logger.blank();
137
+ logger.dim(' Example:');
138
+ logger.dim(' morph-spec generate metadata my-feature');
139
+ process.exit(1);
140
+ }
141
+
142
+ logger.header('MORPH-SPEC Metadata Generator');
143
+ logger.blank();
144
+
145
+ const spinner = ora('Extracting metadata...').start();
146
+
147
+ try {
148
+ // Get feature state
149
+ const feature = getFeature(featureName);
150
+ if (!feature) {
151
+ spinner.fail('Feature not found');
152
+ logger.error(`Feature not found: ${featureName}`);
153
+ process.exit(1);
154
+ }
155
+
156
+ // Extract metadata
157
+ const metadata = extractFeatureMetadata(feature);
158
+
159
+ spinner.succeed('Metadata extracted!');
160
+ logger.blank();
161
+
162
+ // Display summary
163
+ logger.header('Feature Summary:');
164
+ logger.info(`Feature: ${chalk.cyan(metadata.feature)}`);
165
+ logger.info(`Phase: ${chalk.cyan(metadata.phase)}`);
166
+ logger.info(`Status: ${chalk.cyan(metadata.status)}`);
167
+
168
+ if (metadata.progress) {
169
+ const progressBar = '█'.repeat(Math.floor(metadata.progress.percentage / 5)) +
170
+ '░'.repeat(20 - Math.floor(metadata.progress.percentage / 5));
171
+ logger.info(`Progress: ${chalk.cyan(`${metadata.progress.completed}/${metadata.progress.total}`)} ${progressBar} ${chalk.cyan(metadata.progress.percentage + '%')}`);
172
+ }
173
+
174
+ logger.info(`Active Agents: ${chalk.cyan(metadata.agents.length)}`);
175
+ logger.info(`Checkpoints: ${chalk.cyan(metadata.checkpoints.length)}`);
176
+ logger.blank();
177
+
178
+ // Show outputs
179
+ logger.header('Outputs Extracted:');
180
+ Object.entries(metadata.outputs).forEach(([type, data]) => {
181
+ if (data.error) {
182
+ logger.error(` ✗ ${type}: ${data.error}`);
183
+ } else {
184
+ logger.success(` ✓ ${type}`);
185
+
186
+ // Show key stats
187
+ if (type === 'spec' && data.summary) {
188
+ logger.dim(` Tags: ${data.summary.tags.join(', ')}`);
189
+ }
190
+ if (type === 'decisions' && data.total) {
191
+ logger.dim(` Decisions: ${data.total} ADRs`);
192
+ }
193
+ if (type === 'tasks' && data.total) {
194
+ logger.dim(` Tasks: ${data.total} (${data.regularTasks} regular + ${data.checkpoints} checkpoints)`);
195
+ }
196
+ }
197
+ });
198
+ logger.blank();
199
+
200
+ if (options.dryRun) {
201
+ logger.warn('Dry run - file not written');
202
+ logger.blank();
203
+ return;
204
+ }
205
+
206
+ // Determine output path
207
+ const outputPath = options.output ||
208
+ join(process.cwd(), `.morph/project/outputs/${featureName}/metadata.json`);
209
+
210
+ // Write metadata
211
+ const writeSpinner = ora('Writing metadata.json...').start();
212
+
213
+ mkdirSync(dirname(outputPath), { recursive: true });
214
+
215
+ const jsonContent = options.pretty !== false
216
+ ? JSON.stringify(metadata, null, 2)
217
+ : JSON.stringify(metadata);
218
+
219
+ writeFileSync(outputPath, jsonContent, 'utf8');
220
+
221
+ writeSpinner.succeed('Metadata generated!');
222
+ logger.blank();
223
+
224
+ logger.success(` ✓ ${outputPath}`);
225
+ logger.blank();
226
+
227
+ // Usage tip
228
+ logger.header('💡 Usage:');
229
+ logger.dim(` cat ${outputPath}`);
230
+ logger.dim(` # Quick status check - no need to read full markdown files`);
231
+ logger.blank();
232
+
233
+ } catch (error) {
234
+ spinner.fail('Generation failed');
235
+ logger.error(error.message);
236
+ if (error.stack) {
237
+ logger.dim(error.stack);
238
+ }
239
+ process.exit(1);
240
+ }
241
+ }
242
+
121
243
  // ============================================================================
122
244
  // Main Generate Command (router for future subcommands)
123
245
  // ============================================================================
@@ -132,6 +254,10 @@ export async function generateCommand(subcommand, args, options) {
132
254
  await generateDesignSystemCommand(args[0], options);
133
255
  break;
134
256
 
257
+ case 'metadata':
258
+ await generateMetadataCommand(args[0], options);
259
+ break;
260
+
135
261
  // Future: Add more generation commands
136
262
  // case 'component':
137
263
  // await generateComponentCommand(args[0], options);
@@ -142,6 +268,7 @@ export async function generateCommand(subcommand, args, options) {
142
268
  logger.blank();
143
269
  logger.info('Available subcommands:');
144
270
  logger.dim(' design-system Generate CSS + theme files from ui-design-system.md');
271
+ logger.dim(' metadata Generate metadata.json from feature outputs');
145
272
  logger.blank();
146
273
  logger.dim('Run "morph-spec generate --help" for more information');
147
274
  process.exit(1);
@@ -18,6 +18,8 @@ import {
18
18
  createDirectoryLink
19
19
  } from '../utils/file-copier.js';
20
20
  import { saveProjectMorphVersion, getInstalledCLIVersion } from '../utils/version-checker.js';
21
+ import { AutoContextOrchestrator } from '../orchestrator.js';
22
+ import { detectClaudeCode } from '../llm/environment-detector.js';
21
23
 
22
24
  export async function initCommand(options) {
23
25
  const targetPath = options.path || process.cwd();
@@ -250,6 +252,41 @@ Run \`morph-spec detect\` to analyze your project.
250
252
 
251
253
  logger.blank();
252
254
 
255
+ // 12. Auto-detect project context (if Claude Code is available and not --skip-detection)
256
+ if (!options.skipDetection && detectClaudeCode()) {
257
+ logger.blank();
258
+ logger.header('Auto-Detecting Project Context');
259
+ logger.dim('Using Claude Code LLM to analyze your project...');
260
+ logger.blank();
261
+
262
+ try {
263
+ const orchestrator = new AutoContextOrchestrator();
264
+ const result = await orchestrator.execute(targetPath, {
265
+ skipReview: false,
266
+ fallbackOnError: true,
267
+ wizardMode: options.wizard || false
268
+ });
269
+
270
+ if (result.success) {
271
+ logger.success('Project context detected and saved to .morph/project.md');
272
+ } else {
273
+ logger.warn('Auto-detection incomplete. Run "morph-spec update" to retry.');
274
+ }
275
+ } catch (error) {
276
+ logger.warn(`Auto-detection failed: ${error.message}`);
277
+ logger.dim('You can run "morph-spec update" later to re-analyze your project.');
278
+ }
279
+ } else if (options.skipDetection) {
280
+ logger.dim('\nSkipped auto-detection (--skip-detection flag)');
281
+ logger.dim('Run "morph-spec update" later to analyze your project.');
282
+ } else {
283
+ logger.warn('\n⚠️ Claude Code not detected');
284
+ logger.dim('Auto-detection requires Claude Code CLI.');
285
+ logger.dim('Run "morph-spec update --wizard" to configure manually.');
286
+ }
287
+
288
+ logger.blank();
289
+
253
290
  } catch (error) {
254
291
  spinner.fail('Installation failed');
255
292
  logger.error(error.message);
@@ -0,0 +1,158 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import { readFileSync, writeFileSync, existsSync } from 'fs';
4
+ import { join } from 'path';
5
+
6
+ /**
7
+ * Migrate State Command - Upgrade state.json to v3.0 schema
8
+ *
9
+ * Adds approval gates to existing features
10
+ */
11
+
12
+ const program = new Command();
13
+
14
+ program
15
+ .name('migrate-state')
16
+ .description('Migrate state.json to v3.0 schema (add approval gates)')
17
+ .option('--dry-run', 'Preview changes without writing')
18
+ .option('--force', 'Skip confirmation')
19
+ .action(async (options) => {
20
+ try {
21
+ const statePath = join(process.cwd(), '.morph/state.json');
22
+
23
+ if (!existsSync(statePath)) {
24
+ console.error(chalk.red(`\n❌ No state.json found at ${statePath}`));
25
+ console.log(chalk.yellow('This project may not be initialized with MORPH-SPEC.\n'));
26
+ process.exit(1);
27
+ }
28
+
29
+ // Read current state
30
+ const state = JSON.parse(readFileSync(statePath, 'utf8'));
31
+
32
+ console.log(chalk.cyan('\n🔄 Migrating state.json to v3.0 schema...\n'));
33
+
34
+ // Check if already migrated
35
+ if (state.version === '3.0.0') {
36
+ console.log(chalk.green('✅ State already at v3.0.0 - no migration needed\n'));
37
+ process.exit(0);
38
+ }
39
+
40
+ // Track changes
41
+ let featuresUpdated = 0;
42
+ const changes = [];
43
+
44
+ // Migrate each feature
45
+ Object.entries(state.features || {}).forEach(([featureName, feature]) => {
46
+ // Skip if already has approvalGates
47
+ if (feature.approvalGates) {
48
+ return;
49
+ }
50
+
51
+ // Determine which gates to auto-approve based on current phase
52
+ const currentPhase = feature.phase || 'proposal';
53
+ const approvalGates = {
54
+ proposal: { approved: false, timestamp: null, approvedBy: null },
55
+ uiux: { approved: false, timestamp: null, approvedBy: null },
56
+ design: { approved: false, timestamp: null, approvedBy: null },
57
+ tasks: { approved: false, timestamp: null, approvedBy: null }
58
+ };
59
+
60
+ // Auto-approve past gates
61
+ const phaseOrder = ['proposal', 'setup', 'uiux', 'design', 'clarify', 'tasks', 'implement', 'sync', 'archived'];
62
+ const currentPhaseIndex = phaseOrder.indexOf(currentPhase);
63
+
64
+ if (currentPhaseIndex >= phaseOrder.indexOf('proposal')) {
65
+ approvalGates.proposal.approved = true;
66
+ approvalGates.proposal.timestamp = feature.createdAt || new Date().toISOString();
67
+ approvalGates.proposal.approvedBy = 'auto-migration';
68
+ }
69
+
70
+ if (currentPhaseIndex >= phaseOrder.indexOf('design')) {
71
+ approvalGates.design.approved = true;
72
+ approvalGates.design.timestamp = feature.updatedAt || new Date().toISOString();
73
+ approvalGates.design.approvedBy = 'auto-migration';
74
+ }
75
+
76
+ if (currentPhaseIndex >= phaseOrder.indexOf('tasks')) {
77
+ approvalGates.tasks.approved = true;
78
+ approvalGates.tasks.timestamp = feature.updatedAt || new Date().toISOString();
79
+ approvalGates.tasks.approvedBy = 'auto-migration';
80
+ }
81
+
82
+ // Add approval gates to feature
83
+ feature.approvalGates = approvalGates;
84
+
85
+ featuresUpdated++;
86
+ changes.push({
87
+ feature: featureName,
88
+ phase: currentPhase,
89
+ approvedGates: Object.entries(approvalGates)
90
+ .filter(([_, gate]) => gate.approved)
91
+ .map(([name]) => name)
92
+ });
93
+ });
94
+
95
+ // Update state version
96
+ state.version = '3.0.0';
97
+
98
+ // Show changes
99
+ console.log(chalk.bold('📊 Migration Summary:\n'));
100
+ console.log(chalk.cyan(` Features to update: ${featuresUpdated}`));
101
+
102
+ if (changes.length > 0) {
103
+ console.log(chalk.gray('\n Changes:'));
104
+ changes.forEach(change => {
105
+ console.log(chalk.white(` - ${change.feature} (${change.phase})`));
106
+ console.log(chalk.gray(` Auto-approved gates: ${change.approvedGates.join(', ') || 'none'}`));
107
+ });
108
+ }
109
+
110
+ console.log('');
111
+
112
+ // Dry run
113
+ if (options.dryRun) {
114
+ console.log(chalk.yellow('🔍 DRY RUN - No changes written\n'));
115
+ console.log(chalk.gray('Run without --dry-run to apply migration.\n'));
116
+ return;
117
+ }
118
+
119
+ // Confirmation
120
+ if (!options.force) {
121
+ console.log(chalk.yellow('⚠️ This will modify .morph/state.json'));
122
+ console.log(chalk.gray(' A backup will be created at .morph/state.json.backup\n'));
123
+ console.log(chalk.gray(' Run with --force to skip this confirmation, or Ctrl+C to cancel.\n'));
124
+
125
+ // Wait for user confirmation (in CLI context, assume proceed for now)
126
+ // In real implementation, use inquirer for interactive confirmation
127
+ }
128
+
129
+ // Backup original
130
+ const backupPath = `${statePath}.backup`;
131
+ writeFileSync(backupPath, JSON.stringify(state, null, 2));
132
+ console.log(chalk.gray(`📦 Backup created: ${backupPath}\n`));
133
+
134
+ // Write migrated state
135
+ writeFileSync(statePath, JSON.stringify(state, null, 2));
136
+
137
+ console.log(chalk.green('✅ Migration complete!\n'));
138
+ console.log(chalk.bold('Next steps:\n'));
139
+ console.log(chalk.gray('1. Review .morph/config/llm-interaction.json (created on next init)'));
140
+ console.log(chalk.gray('2. Configure approval gates, checkpoints, patterns'));
141
+ console.log(chalk.gray('3. Continue working with v3.0 features\n'));
142
+
143
+ } catch (error) {
144
+ console.error(chalk.red(`\n❌ Migration failed: ${error.message}\n`));
145
+ process.exit(1);
146
+ }
147
+ });
148
+
149
+ // Only parse if run directly (not imported as module)
150
+ if (import.meta.url === `file://${process.argv[1]}`) {
151
+ if (process.argv.length > 2) {
152
+ program.parse(process.argv);
153
+ } else {
154
+ program.help();
155
+ }
156
+ }
157
+
158
+ export default program;
@@ -0,0 +1,126 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import { readFileSync, existsSync } from 'fs';
4
+ import { join } from 'path';
5
+
6
+ /**
7
+ * Search Patterns Command - Find relevant patterns
8
+ *
9
+ * Searches patterns-learned.md for keywords
10
+ */
11
+
12
+ const program = new Command();
13
+
14
+ program
15
+ .name('search-patterns')
16
+ .description('Search for patterns by keyword')
17
+ .argument('<keyword>', 'Keyword to search for')
18
+ .option('--category <category>', 'Filter by category')
19
+ .option('--limit <number>', 'Limit number of results', '10')
20
+ .option('--json', 'Output as JSON', false)
21
+ .action(async (keyword, options) => {
22
+ try {
23
+ // Get patterns file path
24
+ const patternsPath = join(process.cwd(), '.morph/memory/patterns-learned.md');
25
+
26
+ if (!existsSync(patternsPath)) {
27
+ console.error(chalk.red(`\n❌ Patterns file not found: ${patternsPath}`));
28
+ console.log(chalk.yellow('No patterns learned yet. Complete some features first!\n'));
29
+ process.exit(1);
30
+ }
31
+
32
+ // Read patterns file
33
+ const content = readFileSync(patternsPath, 'utf8');
34
+
35
+ // Split into pattern sections
36
+ const sections = content.split('---').filter(s => s.trim().length > 0);
37
+
38
+ // Search patterns
39
+ const keywordLower = keyword.toLowerCase();
40
+ const matches = [];
41
+
42
+ sections.forEach(section => {
43
+ if (section.toLowerCase().includes(keywordLower)) {
44
+ // Extract pattern name
45
+ const nameMatch = section.match(/## Pattern: (.+)/);
46
+ const categoryMatch = section.match(/\*\*Category:\*\* (.+)/);
47
+ const sourceMatch = section.match(/\*\*Source:\*\* (.+)/);
48
+
49
+ if (nameMatch) {
50
+ const patternName = nameMatch[1].trim();
51
+ const category = categoryMatch ? categoryMatch[1].trim() : 'Unknown';
52
+ const source = sourceMatch ? sourceMatch[1].trim() : 'Unknown';
53
+
54
+ // Filter by category if specified
55
+ if (options.category && !category.toLowerCase().includes(options.category.toLowerCase())) {
56
+ return;
57
+ }
58
+
59
+ matches.push({
60
+ name: patternName,
61
+ category,
62
+ source,
63
+ content: section.trim(),
64
+ preview: section.substring(0, 300).trim() + '...'
65
+ });
66
+ }
67
+ }
68
+ });
69
+
70
+ // Limit results
71
+ const limit = parseInt(options.limit, 10);
72
+ const limitedMatches = matches.slice(0, limit);
73
+
74
+ if (options.json) {
75
+ // JSON output
76
+ console.log(JSON.stringify({ keyword, matches: limitedMatches, total: matches.length }, null, 2));
77
+ return;
78
+ }
79
+
80
+ // Pretty output
81
+ if (limitedMatches.length === 0) {
82
+ console.log(chalk.yellow(`\n⚠️ No patterns found for keyword: "${keyword}"\n`));
83
+ console.log(chalk.gray('Try a different keyword or broader search term.\n'));
84
+ return;
85
+ }
86
+
87
+ console.log(chalk.bold(`\n🔍 Found ${matches.length} pattern(s) for: "${keyword}"`));
88
+ if (matches.length > limit) {
89
+ console.log(chalk.gray(`Showing first ${limit} results (use --limit to see more)\n`));
90
+ }
91
+ console.log('━'.repeat(60));
92
+
93
+ limitedMatches.forEach((match, index) => {
94
+ console.log(chalk.green(`\n${index + 1}. ${match.name}`));
95
+ console.log(chalk.cyan(` Category: ${match.category}`));
96
+ console.log(chalk.gray(` Source: ${match.source}`));
97
+
98
+ // Show first few lines of the pattern
99
+ const lines = match.content.split('\n').slice(0, 15);
100
+ console.log(chalk.gray('\n ' + lines.join('\n ')));
101
+
102
+ if (match.content.split('\n').length > 15) {
103
+ console.log(chalk.gray(` ... (see full pattern in ${patternsPath})`));
104
+ }
105
+ });
106
+
107
+ console.log('\n' + '━'.repeat(60));
108
+ console.log(chalk.bold('\n💡 Usage:'));
109
+ console.log(chalk.gray(` Edit ${patternsPath} to see full pattern details\n`));
110
+
111
+ } catch (error) {
112
+ console.error(chalk.red(`\n❌ Error searching patterns: ${error.message}\n`));
113
+ process.exit(1);
114
+ }
115
+ });
116
+
117
+ // Only parse if run directly (not imported as module)
118
+ if (import.meta.url === `file://${process.argv[1]}`) {
119
+ if (process.argv.length > 2) {
120
+ program.parse(process.argv);
121
+ } else {
122
+ program.help();
123
+ }
124
+ }
125
+
126
+ export default program;