/ .github / scripts / claude-enhancer.js
claude-enhancer.js
   1  #!/usr/bin/env node
   2  
   3  /**
   4   * Claude AI Content Enhancement Engine
   5   *
   6   * Advanced AI-powered CV content enhancement using Claude API with intelligent
   7   * prompt engineering, content optimization, and professional development insights.
   8   *
   9   * Features:
  10   * - Intelligent content analysis and enhancement
  11   * - Professional tone optimization
  12   * - Skills gap analysis and recommendations
  13   * - Industry trend integration
  14   * - Token usage optimization with caching
  15   * - Multi-stage enhancement pipeline
  16   * - Meta-commentary artifact removal (Issue #100 fix)
  17   * - XML-structured output formatting
  18   * - Robust content filtering and cleaning
  19   *
  20   * Meta-Commentary Fix (Issue #100):
  21   * This version includes comprehensive fixes to prevent Claude AI from generating
  22   * explanatory text and meta-commentary in CV content. Implementation includes:
  23   * - System prompts explicitly forbidding meta-commentary
  24   * - XML-structured output format specifications
  25   * - Multi-layer content cleaning and artifact removal
  26   * - Enhanced JSON parsing with fallback content extraction
  27   * - Comprehensive test suite for content validation
  28   *
  29   * Usage: node claude-enhancer.js
  30   *        node claude-enhancer.js --test-cleaning  # Test content cleaning functions
  31   *
  32   * Environment Variables:
  33   * - ANTHROPIC_API_KEY: Claude API key for authentication
  34   * - AI_BUDGET: Token budget for enhancement session
  35   * - CREATIVITY_LEVEL: Enhancement creativity (conservative|balanced|creative|innovative)
  36   * - ACTIVITY_SCORE: Current GitHub activity score for context
  37   */
  38  
  39  const fs = require('fs').promises;
  40  const path = require('path');
  41  const crypto = require('crypto');
  42  const https = require('https');
  43  const { execFile: _execFile } = require('child_process');
  44  const { sleep } = require('./utils/apiClient');
  45  const { XMLFewShotIntegrator } = require('./enhancer-modules/xml-few-shot-integrator');
  46  
  47  // Configuration
  48  const CONFIG = {
  49      ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,
  50      USE_CLAUDE_CODE: process.env.USE_CLAUDE_CODE !== 'false',
  51      CLAUDE_CODE_MODEL: process.env.CLAUDE_CODE_MODEL || 'sonnet',
  52      AI_BUDGET: process.env.AI_BUDGET || 'sufficient',
  53      CREATIVITY_LEVEL: process.env.CREATIVITY_LEVEL || 'balanced',
  54      ACTIVITY_SCORE: parseFloat(process.env.ACTIVITY_SCORE) || 50,
  55      API_VERSION: '2023-06-01',
  56      MODEL: process.env.CLAUDE_MODEL || 'claude-sonnet-4-20250514',
  57      OUTPUT_DIR: 'data',
  58      CACHE_DIR: 'data/ai-cache',
  59      MAX_TOKENS: 4000,
  60      TEMPERATURE_MAP: {
  61          'conservative': 0.3,
  62          'balanced': 0.5,
  63          'creative': 0.7,
  64          'innovative': 0.9
  65      }
  66  };
  67  
  68  /**
  69   * Claude API client with intelligent caching and token optimization
  70   */
  71  class ClaudeApiClient {
  72      constructor(apiKey) {
  73          this.apiKey = apiKey;
  74          this.baseUrl = 'https://api.anthropic.com/v1/messages';
  75          this.tokenUsage = {
  76              input_tokens: 0,
  77              output_tokens: 0,
  78              cache_creation_tokens: 0,
  79              cache_read_tokens: 0
  80          };
  81          this.requestCount = 0;
  82          this.cacheHits = 0;
  83      }
  84  
  85      /**
  86       * Make Claude API request with caching and token tracking
  87       */
  88      async makeRequest(messages, options = {}, sourceContent = '') {
  89          const temperature = CONFIG.TEMPERATURE_MAP[CONFIG.CREATIVITY_LEVEL] || 0.5;
  90          const maxTokens = options.maxTokens || CONFIG.MAX_TOKENS;
  91  
  92          // Generate cache key for identical requests
  93          const cacheKey = this.generateCacheKey({ messages, temperature, maxTokens }, sourceContent);
  94          const cachedResponse = await this.getCachedResponse(cacheKey);
  95  
  96          if (cachedResponse && !options.skipCache) {
  97              console.log('๐Ÿ“ฆ Cache hit for Claude request');
  98              this.cacheHits++;
  99              return cachedResponse;
 100          }
 101  
 102          // Route to Claude Code CLI or direct API
 103          const useClaudeCode = CONFIG.USE_CLAUDE_CODE && !CONFIG.ANTHROPIC_API_KEY;
 104          const responseData = useClaudeCode
 105              ? await this._makeClaudeCodeRequest(messages, maxTokens)
 106              : await this._makeDirectApiRequest(messages, temperature, maxTokens);
 107  
 108          // Track token usage
 109          if (responseData.usage) {
 110              this.tokenUsage.input_tokens += responseData.usage.input_tokens || 0;
 111              this.tokenUsage.output_tokens += responseData.usage.output_tokens || 0;
 112              this.tokenUsage.cache_creation_tokens += responseData.usage.cache_creation_input_tokens || 0;
 113              this.tokenUsage.cache_read_tokens += responseData.usage.cache_read_input_tokens || 0;
 114          }
 115  
 116          // Cache successful responses
 117          await this.cacheResponse(cacheKey, responseData);
 118  
 119          return responseData;
 120      }
 121  
 122      /**
 123       * Make request via Claude Code CLI (uses Max subscription billing)
 124       */
 125      async _makeClaudeCodeRequest(messages, _maxTokens) {
 126          // Separate system messages from user/assistant messages
 127          const systemParts = messages.filter(m => m.role === 'system').map(m => m.content);
 128          const userParts = messages.filter(m => m.role !== 'system').map(m => m.content);
 129          const prompt = userParts.join('\n\n');
 130  
 131          try {
 132              console.log(`๐Ÿค– Making Claude Code CLI request (model: ${CONFIG.CLAUDE_CODE_MODEL})...`);
 133              this.requestCount++;
 134  
 135              const result = await new Promise(async (resolve, reject) => {
 136                  const { spawn } = require('child_process');
 137  
 138                  const args = [
 139                      '-p', prompt,
 140                      '--output-format', 'json',
 141                      '--model', CONFIG.CLAUDE_CODE_MODEL,
 142                      '--max-turns', '1',
 143                      '--no-chrome'
 144                  ];
 145  
 146                  if (systemParts.length > 0) {
 147                      args.push('--append-system-prompt', systemParts.join('\n\n'));
 148                  }
 149  
 150                  // Clear CLAUDECODE env var to allow spawning from within a Claude Code session
 151                  const env = { ...process.env };
 152                  delete env.CLAUDECODE;
 153  
 154                  let stdout = '';
 155                  let stderr = '';
 156                  // spawn passes args directly to execvp โ€” no shell, no arg length issues
 157                  const child = spawn('claude', args, { env });
 158  
 159                  child.stdout.on('data', (data) => { stdout += data; });
 160                  child.stderr.on('data', (data) => { stderr += data; });
 161  
 162                  child.on('close', (code) => {
 163                      if (code !== 0 && !stdout) {
 164                          reject(new Error(`Claude Code CLI exited with code ${code}${stderr ? ` โ€” ${stderr.slice(0, 200)}` : ''}`));
 165                          return;
 166                      }
 167                      // Claude Code may exit non-zero for budget limits but still return valid output
 168                      resolve(stdout);
 169                  });
 170  
 171                  child.on('error', (error) => {
 172                      reject(new Error(`Claude Code CLI spawn error: ${error.message}`));
 173                  });
 174              });
 175  
 176              // Claude Code --output-format json returns a JSON array:
 177              // [0] {type:"system"} init metadata
 178              // [1] {type:"assistant", message: {content: [{text}], usage}} the response
 179              // [2] {type:"result"} session summary
 180              const parsed = JSON.parse(result);
 181              const assistantMsg = Array.isArray(parsed)
 182                  ? parsed.find(item => item.type === 'assistant')
 183                  : null;
 184  
 185              if (!assistantMsg?.message?.content?.[0]?.text) {
 186                  throw new Error('Could not extract assistant response from Claude Code output');
 187              }
 188  
 189              const message = assistantMsg.message;
 190  
 191              // Return in the same shape as the Anthropic API response
 192              return {
 193                  content: message.content,
 194                  usage: {
 195                      input_tokens: message.usage?.input_tokens || 0,
 196                      output_tokens: message.usage?.output_tokens || 0,
 197                      cache_creation_input_tokens: message.usage?.cache_creation_input_tokens || 0,
 198                      cache_read_input_tokens: message.usage?.cache_read_input_tokens || 0
 199                  }
 200              };
 201  
 202          } catch (error) {
 203              console.error('โŒ Claude Code CLI request failed:', error.message);
 204              throw error;
 205          }
 206      }
 207  
 208      /**
 209       * Make request via direct Anthropic API (uses API credits)
 210       */
 211      async _makeDirectApiRequest(messages, temperature, maxTokens) {
 212          const requestBody = {
 213              model: CONFIG.MODEL,
 214              max_tokens: maxTokens,
 215              temperature,
 216              messages: messages.map(msg => ({
 217                  role: msg.role,
 218                  content: msg.content
 219              }))
 220          };
 221  
 222          try {
 223              console.log('๐Ÿค– Making Claude API request...');
 224              this.requestCount++;
 225  
 226              const response = await this.httpRequest(this.baseUrl, {
 227                  method: 'POST',
 228                  headers: {
 229                      'Content-Type': 'application/json',
 230                      'x-api-key': this.apiKey,
 231                      'anthropic-version': CONFIG.API_VERSION
 232                  },
 233                  body: JSON.stringify(requestBody)
 234              });
 235  
 236              const responseData = JSON.parse(response.body);
 237  
 238              if (responseData.error) {
 239                  throw new Error(`Claude API Error: ${responseData.error.message}`);
 240              }
 241  
 242              return responseData;
 243  
 244          } catch (error) {
 245              console.error('โŒ Claude API request failed:', error.message);
 246              throw error;
 247          }
 248      }
 249  
 250      /**
 251       * HTTP request wrapper
 252       */
 253      async httpRequest(url, options, maxRetries = 3, retryDelay = 1000) {
 254          for (let i = 0; i < maxRetries; i++) {
 255              try {
 256                  return await new Promise((resolve, reject) => {
 257                      const req = https.request(url, options, (res) => {
 258                          let body = '';
 259                          res.on('data', chunk => body += chunk);
 260                          res.on('end', () => {
 261                              if (res.statusCode >= 200 && res.statusCode < 300) {
 262                                  resolve({ body, statusCode: res.statusCode });
 263                              } else if (res.statusCode >= 500 || res.statusCode === 429) { // Retry on 5xx or Too Many Requests
 264                                  reject(new Error(`HTTP ${res.statusCode}: ${body}`));
 265                              } else {
 266                                  reject(new Error(`HTTP ${res.statusCode}: ${body}`));
 267                              }
 268                          });
 269                      });
 270  
 271                      req.on('error', reject);
 272                      req.setTimeout(60000, () => {
 273                          req.destroy();
 274                          reject(new Error('Request timeout'));
 275                      });
 276  
 277                      if (options.body) {
 278                          req.write(options.body);
 279                      }
 280                      req.end();
 281                  });
 282              } catch (error) {
 283                  if (i < maxRetries - 1) {
 284                      const delay = retryDelay * Math.pow(2, i);
 285                      console.warn(`Retrying ${url} in ${delay}ms due to error: ${error.message}`);
 286                      await sleep(delay);
 287                  } else {
 288                      throw error; // Last retry failed
 289                  }
 290              }
 291          }
 292      }
 293  
 294      /**
 295       * Generate a content-aware cache key for request deduplication.
 296       * @param {object} requestPayload - The core request object (messages, temperature, maxTokens).
 297       * @param {string} [sourceContent=''] - The raw source content being enhanced (e.g., the original summary text).
 298       * @returns {string} A SHA256 hash representing the unique request.
 299       */
 300      generateCacheKey(requestPayload, sourceContent = '') {
 301          // Combine the request structure with a hash of the actual content being processed.
 302          const contentHash = crypto.createHash('sha256').update(sourceContent).digest('hex');
 303          const payloadString = JSON.stringify(requestPayload);
 304  
 305          // The final key depends on both the prompt and the data.
 306          return crypto.createHash('sha256').update(payloadString + contentHash).digest('hex').substring(0, 16);
 307      }
 308  
 309      /**
 310       * Retrieve cached response
 311       */
 312      async getCachedResponse(cacheKey) {
 313          try {
 314              const cachePath = path.join(CONFIG.CACHE_DIR, `${cacheKey}.json`);
 315              const cached = await fs.readFile(cachePath, 'utf8');
 316              const cachedData = JSON.parse(cached);
 317  
 318              // Check if cache is still valid (24 hours)
 319              if (Date.now() - cachedData.timestamp < 24 * 60 * 60 * 1000) {
 320                  return cachedData.response;
 321              }
 322          } catch (error) {
 323              // Cache miss or error - continue with API request
 324          }
 325          return null;
 326      }
 327  
 328      /**
 329       * Cache API response
 330       */
 331      async cacheResponse(cacheKey, response) {
 332          try {
 333              await this.ensureCacheDir();
 334              const cachePath = path.join(CONFIG.CACHE_DIR, `${cacheKey}.json`);
 335              const cacheData = {
 336                  timestamp: Date.now(),
 337                  response
 338              };
 339              await fs.writeFile(cachePath, JSON.stringify(cacheData), 'utf8');
 340          } catch (error) {
 341              console.warn('โš ๏ธ Failed to cache response:', error.message);
 342          }
 343      }
 344  
 345      /**
 346       * Ensure cache directory exists
 347       */
 348      async ensureCacheDir() {
 349          try {
 350              await fs.access(CONFIG.CACHE_DIR);
 351          } catch {
 352              await fs.mkdir(CONFIG.CACHE_DIR, { recursive: true });
 353          }
 354      }
 355  
 356      /**
 357       * Get token usage statistics
 358       */
 359      getUsageStats() {
 360          const totalTokens = this.tokenUsage.input_tokens + this.tokenUsage.output_tokens;
 361          const cacheEfficiency = this.requestCount > 0 ? (this.cacheHits / this.requestCount) * 100 : 0;
 362  
 363          return {
 364              ...this.tokenUsage,
 365              total_tokens: totalTokens,
 366              request_count: this.requestCount,
 367              cache_hits: this.cacheHits,
 368              cache_efficiency_percent: Math.round(cacheEfficiency * 10) / 10
 369          };
 370      }
 371  }
 372  
 373  /**
 374   * CV Content Enhancement Engine
 375   *
 376   * Multi-stage AI enhancement pipeline for professional CV content
 377   */
 378  class CVContentEnhancer {
 379      constructor() {
 380          this.client = new ClaudeApiClient(CONFIG.ANTHROPIC_API_KEY);
 381          this.xmlIntegrator = new XMLFewShotIntegrator();
 382          this.enhancementStartTime = Date.now();
 383          this.enhancementResults = {};
 384          this.useXMLPrompts = process.env.USE_XML_PROMPTS !== 'false'; // Default to true
 385      }
 386  
 387      /**
 388       * Run comprehensive CV content enhancement
 389       */
 390      async enhance() {
 391          console.log('๐Ÿค– **CLAUDE AI CONTENT ENHANCEMENT INITIATED**');
 392          console.log(`๐ŸŽจ Creativity level: ${CONFIG.CREATIVITY_LEVEL}`);
 393          console.log(`๐Ÿ’ฐ AI budget: ${CONFIG.AI_BUDGET}`);
 394          console.log(`๐Ÿ“Š Activity score: ${CONFIG.ACTIVITY_SCORE}/100`);
 395          console.log('');
 396  
 397          try {
 398              // Ensure output directory exists
 399              await this.ensureOutputDir();
 400  
 401              // Load existing CV data and activity metrics
 402              const currentCVData = await this.loadCurrentCVData();
 403              const activityMetrics = await this.loadActivityMetrics();
 404  
 405              // Load keyword gaps to guide enhancement
 406              const keywordGaps = await this.loadKeywordGaps();
 407              if (keywordGaps.top_missing?.length) {
 408                  console.log(`๐Ÿ”‘ Keyword gaps to address: ${keywordGaps.top_missing.slice(0,5).map(g=>g.kw).join(', ')} ...`);
 409              }
 410  
 411              const enhancementPlan = {
 412                  metadata: {
 413                      enhancement_timestamp: new Date().toISOString(),
 414                      creativity_level: CONFIG.CREATIVITY_LEVEL,
 415                      ai_budget: CONFIG.AI_BUDGET,
 416                      activity_score: CONFIG.ACTIVITY_SCORE,
 417                      enhancer_version: '2.1.0'
 418                  }
 419              };
 420  
 421              // Multi-stage enhancement pipeline
 422              console.log('๐Ÿ“ Stage 1: Professional Summary Enhancement');
 423              enhancementPlan.professional_summary = await this.enhanceProfessionalSummary(currentCVData, activityMetrics);
 424  
 425              console.log('โšก Stage 2: Skills Analysis & Optimization');
 426              enhancementPlan.skills_enhancement = await this.enhanceSkillsSection(currentCVData, activityMetrics);
 427  
 428              console.log('๐ŸŽฏ Stage 3: Experience Description Optimization');
 429              enhancementPlan.experience_enhancement = await this.enhanceExperience(currentCVData, activityMetrics);
 430  
 431              console.log('๐Ÿš€ Stage 4: Project Impact Analysis');
 432              enhancementPlan.project_enhancement = await this.enhanceProjects(currentCVData, activityMetrics);
 433  
 434              if (CONFIG.AI_BUDGET !== 'insufficient' && (CONFIG.CREATIVITY_LEVEL === 'creative' || CONFIG.CREATIVITY_LEVEL === 'innovative')) {
 435                  console.log('๐Ÿ”ฎ Stage 5: Strategic Career Insights');
 436                  enhancementPlan.strategic_insights = await this.generateStrategicInsights(currentCVData, activityMetrics);
 437              }
 438  
 439              // Generate enhancement summary
 440              enhancementPlan.enhancement_summary = this.generateEnhancementSummary(enhancementPlan);
 441  
 442              // Save enhancement results
 443              await this.saveEnhancementResults(enhancementPlan);
 444  
 445              const enhancementTime = ((Date.now() - this.enhancementStartTime) / 1000).toFixed(2);
 446              const usageStats = this.client.getUsageStats();
 447  
 448              console.log(`โœ… Enhancement completed in ${enhancementTime}s`);
 449              console.log(`๐Ÿ“Š Token usage: ${usageStats.total_tokens} total (${usageStats.cache_efficiency_percent}% cache efficiency)`);
 450              console.log(`๐Ÿ“ Results saved to ${CONFIG.OUTPUT_DIR}/`);
 451  
 452              return enhancementPlan;
 453  
 454          } catch (error) {
 455              console.error('โŒ Enhancement failed:', error.message);
 456              throw error;
 457          }
 458      }
 459  
 460      /**
 461       * Load narrative intelligence data if available
 462       */
 463      async loadNarrativeIntelligence() {
 464          try {
 465              const narrativePath = path.join('data', 'narratives', 'narrative-integration.json');
 466              const content = await fs.readFile(narrativePath, 'utf8');
 467              const narrativeData = JSON.parse(content);
 468  
 469              console.log('๐Ÿ“– Loaded professional narrative intelligence data');
 470              return narrativeData;
 471          } catch (error) {
 472              console.log('๐Ÿ“ No narrative intelligence data available, using standard enhancement');
 473              return null;
 474          }
 475      }
 476  
 477      /**
 478       * Enhance professional summary with AI optimization
 479       * Enhanced with XML structuring and few-shot learning (Issues #96, #97)
 480       */
 481      async enhanceProfessionalSummary(cvData, activityMetrics) {
 482          // Use XML-structured prompts with few-shot examples for enhanced quality
 483          if (this.useXMLPrompts) {
 484              return await this.enhanceProfessionalSummaryXML(cvData, activityMetrics);
 485          }
 486  
 487          // Legacy method for backward compatibility
 488          return await this.enhanceProfessionalSummaryLegacy(cvData, activityMetrics);
 489      }
 490  
 491      /**
 492       * Enhanced professional summary using XML structuring and few-shot prompting
 493       */
 494      async enhanceProfessionalSummaryXML(cvData, activityMetrics) {
 495          console.log('๐Ÿ”จ Using XML-structured prompt with few-shot examples...');
 496  
 497          try {
 498              // Initialize XML integrator
 499              await this.xmlIntegrator.initialize();
 500  
 501              // Construct XML-structured prompt with few-shot examples
 502              const promptResult = await this.xmlIntegrator.enhanceProfessionalSummaryXML(
 503                  cvData,
 504                  activityMetrics,
 505                  CONFIG.CREATIVITY_LEVEL
 506              );
 507  
 508              console.log(`๐Ÿ“Š Expected quality improvement: ${(promptResult.quality_expected * 100).toFixed(1)}%`);
 509  
 510              // Create messages for Claude API
 511              const messages = [
 512                  {
 513                      role: 'system',
 514                      content: 'You are a professional CV enhancement specialist. You MUST respond ONLY with clean JSON structure. NEVER include explanatory text, process descriptions, or meta-commentary. Follow the provided examples exactly.'
 515                  },
 516                  {
 517                      role: 'user',
 518                      content: promptResult.xmlPrompt
 519                  }
 520              ];
 521  
 522              // Make API request
 523              const response = await this.client.makeRequest(messages, { maxTokens: 800 }, promptResult.contextData.currentContent);
 524              const responseText = response.content[0]?.text?.trim();
 525  
 526              // Clean and parse response
 527              const cleanedResponse = this.cleanResponseText(responseText);
 528              let enhancementData;
 529  
 530              try {
 531                  enhancementData = JSON.parse(cleanedResponse);
 532  
 533                  // Clean enhanced content
 534                  if (enhancementData.enhanced) {
 535                      enhancementData.enhanced = this.cleanEnhancedContent(enhancementData.enhanced);
 536                  } else if (enhancementData.enhanced_summary) {
 537                      enhancementData.enhanced_summary = this.cleanEnhancedContent(enhancementData.enhanced_summary);
 538                      enhancementData.enhanced = enhancementData.enhanced_summary; // Normalize
 539                  }
 540              } catch (parseError) {
 541                  console.warn('โš ๏ธ JSON parsing failed, attempting content extraction');
 542                  enhancementData = this.extractContentFromText(cleanedResponse);
 543              }
 544  
 545              // Validate response quality
 546              const validation = await this.xmlIntegrator.validateResponse(enhancementData, 'professional-summary', promptResult.quality_expected);
 547  
 548              console.log(`โœ… Response validation: ${validation.valid ? 'PASSED' : 'FAILED'} (Score: ${(validation.score * 100).toFixed(1)}%)`);
 549              if (validation.quality_improvement) {
 550                  console.log('๐ŸŽฏ Quality improvement achieved beyond expected threshold');
 551              }
 552  
 553              return {
 554                  original: promptResult.contextData.currentContent,
 555                  enhanced: enhancementData.enhanced || enhancementData.enhanced_summary,
 556                  strategic_analysis: enhancementData.strategic_improvements || enhancementData.key_differentiators,
 557                  ats_optimization: enhancementData.ats_keywords || [],
 558                  confidence_score: enhancementData.confidence_score || validation.score,
 559                  enhancement_applied: true,
 560                  prompt_strategy: 'xml-few-shot',
 561                  xml_metadata: promptResult.metadata,
 562                  validation_results: validation,
 563                  improvement_notes: this.analyzeSummaryImprovement(
 564                      promptResult.contextData.currentContent,
 565                      enhancementData.enhanced || enhancementData.enhanced_summary
 566                  ),
 567                  quality_indicators: {
 568                      xml_structured: true,
 569                      few_shot_guided: true,
 570                      validation_passed: validation.valid,
 571                      quality_score: validation.score,
 572                      expected_improvement: promptResult.quality_expected
 573                  }
 574              };
 575  
 576          } catch (error) {
 577              console.warn('โš ๏ธ XML professional summary enhancement failed, falling back to legacy method');
 578              return await this.enhanceProfessionalSummaryLegacy(cvData, activityMetrics);
 579          }
 580      }
 581  
 582      /**
 583       * Legacy professional summary enhancement method
 584       */
 585      async enhanceProfessionalSummaryLegacy(cvData, activityMetrics) {
 586          // Load narrative intelligence if available
 587          const narrativeData = await this.loadNarrativeIntelligence();
 588  
 589          const currentSummary = narrativeData?.enhanced_summary ||
 590                                cvData?.professional_summary ||
 591                                "AI Engineer and Software Architect with expertise in autonomous systems and machine learning.";
 592  
 593          // Dynamic persona and strategy based on creativity level
 594          const creativityStrategies = {
 595              'conservative': {
 596                  persona: 'Alexandra Chen, Senior Technical Recruiter at Microsoft, specializing in AI/ML leadership roles. You\'ve successfully placed 200+ AI engineers at Fortune 500 companies.',
 597                  approach: 'evidence-based optimization with proven industry language',
 598                  tone: 'authoritative and credible',
 599                  focus: 'quantifiable achievements and established expertise'
 600              },
 601              'balanced': {
 602                  persona: 'Dr. Marcus Rodriguez, Executive Search Partner at Andreessen Horowitz, focusing on AI startup leadership. You understand both technical depth and market positioning.',
 603                  approach: 'strategic positioning that balances innovation with credibility',
 604                  tone: 'confident thought leadership',
 605                  focus: 'unique value proposition with market awareness'
 606              },
 607              'creative': {
 608                  persona: 'Sarah Kim, Chief Talent Officer at OpenAI, identifying breakthrough AI talent. You recognize unconventional brilliance and emerging paradigms.',
 609                  approach: 'innovative narrative that positions for future opportunities',
 610                  tone: 'visionary and compelling',
 611                  focus: 'transformative potential and cutting-edge innovation'
 612              },
 613              'innovative': {
 614                  persona: 'Dr. Elena Vasquez, Venture Partner at Sequoia focusing on AI moonshots. You spot rare talent that will define the next decade of AI.',
 615                  approach: 'revolutionary positioning for paradigm-shifting roles',
 616                  tone: 'bold and transformational',
 617                  focus: 'groundbreaking innovation and industry disruption'
 618              }
 619          };
 620  
 621          const strategy = creativityStrategies[CONFIG.CREATIVITY_LEVEL] || creativityStrategies['balanced'];
 622  
 623          // Context analysis for intelligent narrative integration
 624          const activityInsight = CONFIG.ACTIVITY_SCORE >= 80 ? 'exceptionally active contributor with consistent innovation' :
 625                                 CONFIG.ACTIVITY_SCORE >= 60 ? 'highly engaged developer with strong technical output' :
 626                                 CONFIG.ACTIVITY_SCORE >= 40 ? 'focused contributor with quality-driven development' :
 627                                 'selective contributor with deep technical focus';
 628  
 629          const technicalBreadth = (activityMetrics?.top_languages?.length || 3) >= 5 ? 'remarkable technical versatility across multiple paradigms' :
 630                                   (activityMetrics?.top_languages?.length || 3) >= 3 ? 'solid multi-language expertise with platform agility' :
 631                                   'deep specialization with focused technical mastery';
 632  
 633          const professionalArchetype = CONFIG.ACTIVITY_SCORE >= 70 && (activityMetrics?.total_repos || 0) >= 20 ? 'prolific innovator' :
 634                                       CONFIG.ACTIVITY_SCORE >= 50 && (activityMetrics?.total_repos || 0) >= 10 ? 'strategic technologist' :
 635                                       'specialized expert';
 636  
 637          const messages = [
 638              {
 639                  role: 'system',
 640                  content: 'You are a professional CV enhancement specialist. You MUST respond ONLY with clean, professional content. NEVER include explanatory text like "Here\'s an enhanced...", process descriptions, or meta-commentary. Your response must be structured JSON only, containing the enhanced content and analysis without any additional explanations or formatting notes.'
 641              },
 642              {
 643                  role: 'user',
 644                  content: `You are ${strategy.persona}
 645  
 646  CANDIDATE ANALYSIS:
 647  You're reviewing a ${professionalArchetype} with ${CONFIG.ACTIVITY_SCORE}/100 GitHub activity score, demonstrating ${activityInsight}. Their technical portfolio (${activityMetrics?.top_languages?.join(', ') || 'Python, JavaScript, TypeScript'}) across ${activityMetrics?.total_repos || 'multiple'} repositories reveals ${technicalBreadth}.
 648  
 649  ${narrativeData ? `
 650  PROFESSIONAL INTELLIGENCE CONTEXT:
 651  Based on comprehensive GitHub data mining, this candidate has:
 652  - Technical achievements: ${narrativeData.narratives_available?.technical_achievements || 0} evidence-backed accomplishments
 653  - Leadership examples: ${narrativeData.narratives_available?.leadership_examples || 0} demonstrated instances
 654  - Validated skills: ${narrativeData.validated_skills?.join(', ') || 'Multiple technical competencies'} with concrete evidence
 655  - Top achievements: ${narrativeData.top_achievements?.map(a => a.achievement).join('; ') || 'Consistent technical contributions'}
 656  
 657  This intelligence provides concrete evidence for professional claims and should inform your enhancement strategy.
 658  ` : ''}
 659  
 660  MARKET CONTEXT (2025):
 661  The AI engineering landscape demands professionals who bridge autonomous systems research with production-grade implementation. The market rewards those who can lead human-AI collaboration initiatives and drive sustainable AI development practices.
 662  
 663  ENHANCEMENT MISSION (${CONFIG.CREATIVITY_LEVEL} approach):
 664  Transform their current summary using ${strategy.approach}, creating a ${strategy.tone} narrative focused on ${strategy.focus}. ${narrativeData ? 'Leverage the professional intelligence context to create evidence-backed claims rather than generic statements.' : ''} Position them as someone ready for senior AI engineering roles that shape the future of autonomous systems.
 665  
 666  CURRENT SUMMARY:
 667  "${currentSummary}"
 668  
 669  <output_format>
 670  Respond with ONLY this JSON structure. Do not include any explanatory text, process descriptions, or meta-commentary:
 671  
 672  {
 673    "enhanced_summary": "2-3 compelling sentences that immediately communicate transformative value",
 674    "strategic_improvements": {
 675      "positioning_shift": "How this repositions them in the market",
 676      "value_amplification": "Key strengths magnified",
 677      "market_alignment": "Industry demands addressed"
 678    },
 679    "ats_keywords": ["keyword1", "keyword2", "keyword3"],
 680    "confidence_score": 0.95
 681  }
 682  </output_format>`
 683              }
 684          ];
 685  
 686          try {
 687              const response = await this.client.makeRequest(messages, { maxTokens: 500 }, currentSummary);
 688              const responseText = response.content[0]?.text?.trim();
 689  
 690              // Clean the response text from potential artifacts
 691              const cleanedResponse = this.cleanResponseText(responseText);
 692  
 693              // Parse JSON response
 694              let enhancementData;
 695              try {
 696                  enhancementData = JSON.parse(cleanedResponse);
 697  
 698                  // Additional cleaning of the enhanced_summary field
 699                  if (enhancementData.enhanced_summary) {
 700                      enhancementData.enhanced_summary = this.cleanEnhancedContent(enhancementData.enhanced_summary);
 701                  }
 702              } catch (parseError) {
 703                  console.warn('โš ๏ธ JSON parsing failed, attempting content extraction');
 704                  enhancementData = this.extractContentFromText(cleanedResponse);
 705              }
 706  
 707              return {
 708                  original: currentSummary,
 709                  enhanced: enhancementData.enhanced_summary,
 710                  strategic_analysis: enhancementData.strategic_improvements,
 711                  ats_optimization: enhancementData.ats_keywords,
 712                  confidence_score: enhancementData.confidence_score,
 713                  enhancement_applied: true,
 714                  prompt_strategy: strategy.approach,
 715                  improvement_notes: this.analyzeSummaryImprovement(currentSummary, enhancementData.enhanced_summary)
 716              };
 717          } catch (error) {
 718              console.warn('โš ๏ธ Professional summary enhancement failed, using original');
 719              return {
 720                  original: currentSummary,
 721                  enhanced: currentSummary,
 722                  enhancement_applied: false,
 723                  error: error.message
 724              };
 725          }
 726      }
 727  
 728      /**
 729       * Enhance skills section with proficiency analysis
 730       * Enhanced with XML structuring and few-shot learning (Issues #96, #97)
 731       */
 732      async enhanceSkillsSection(cvData, activityMetrics) {
 733          // Use XML-structured prompts with few-shot examples for enhanced quality
 734          if (this.useXMLPrompts) {
 735              return await this.enhanceSkillsSectionXML(cvData, activityMetrics);
 736          }
 737  
 738          // Legacy method for backward compatibility
 739          return await this.enhanceSkillsSectionLegacy(cvData, activityMetrics);
 740      }
 741  
 742      /**
 743       * Enhanced skills section using XML structuring and few-shot prompting
 744       */
 745      async enhanceSkillsSectionXML(cvData, activityMetrics) {
 746          console.log('๐Ÿ”จ Using XML-structured skills enhancement prompt...');
 747  
 748          try {
 749              // Construct XML-structured prompt with few-shot examples
 750              const promptResult = await this.xmlIntegrator.enhanceSkillsSectionXML(
 751                  cvData,
 752                  activityMetrics,
 753                  CONFIG.CREATIVITY_LEVEL
 754              );
 755  
 756              console.log(`๐Ÿ“Š Expected skills quality improvement: ${(promptResult.quality_expected * 100).toFixed(1)}%`);
 757  
 758              // Create messages for Claude API
 759              const messages = [
 760                  {
 761                      role: 'system',
 762                      content: 'You are a professional skills analysis specialist. Respond ONLY with the requested JSON structure. Do not include explanatory text or meta-commentary. Follow the provided examples for structure and quality.'
 763                  },
 764                  {
 765                      role: 'user',
 766                      content: promptResult.xmlPrompt
 767                  }
 768              ];
 769  
 770              // Make API request
 771              const response = await this.client.makeRequest(messages, { maxTokens: 1000 }, JSON.stringify(cvData.skills));
 772              const responseText = response.content[0]?.text?.trim();
 773  
 774              // Clean and parse response
 775              const cleanedResponse = this.cleanResponseText(responseText);
 776              let skillsData;
 777  
 778              try {
 779                  skillsData = JSON.parse(cleanedResponse);
 780              } catch (parseError) {
 781                  console.warn('โš ๏ธ Skills JSON parsing failed, using fallback structure');
 782                  skillsData = {
 783                      skill_architecture: { core_competencies: [], emerging_expertise: [], market_differentiators: [] },
 784                      development_roadmap: { immediate_priorities: [], strategic_investments: [], innovation_opportunities: [] },
 785                      positioning_strategy: { technical_narrative: this.cleanEnhancedContent(cleanedResponse).substring(0, 200) + '...' },
 786                      confidence_assessment: 0.7
 787                  };
 788              }
 789  
 790              // Validate response quality
 791              const validation = await this.xmlIntegrator.validateResponse(skillsData, 'skills-enhancement', promptResult.quality_expected);
 792  
 793              console.log(`โœ… Skills validation: ${validation.valid ? 'PASSED' : 'FAILED'} (Score: ${(validation.score * 100).toFixed(1)}%)`);
 794  
 795              return {
 796                  skill_analysis: skillsData.skill_architecture,
 797                  development_roadmap: skillsData.development_roadmap,
 798                  positioning_strategy: skillsData.positioning_strategy,
 799                  confidence_score: skillsData.confidence_assessment || validation.score,
 800                  github_context: {
 801                      activity_score: CONFIG.ACTIVITY_SCORE,
 802                      top_languages: activityMetrics?.top_languages || [],
 803                      total_repos: activityMetrics?.total_repos || 0
 804                  },
 805                  enhancement_applied: true,
 806                  prompt_strategy: 'xml-few-shot',
 807                  xml_metadata: promptResult.metadata,
 808                  validation_results: validation,
 809                  recommendations: this.extractSkillRecommendations(skillsData),
 810                  quality_indicators: {
 811                      xml_structured: true,
 812                      few_shot_guided: true,
 813                      validation_passed: validation.valid,
 814                      quality_score: validation.score,
 815                      expected_improvement: promptResult.quality_expected
 816                  }
 817              };
 818  
 819          } catch (error) {
 820              console.warn('โš ๏ธ XML skills enhancement failed, falling back to legacy method');
 821              return await this.enhanceSkillsSectionLegacy(cvData, activityMetrics);
 822          }
 823      }
 824  
 825      /**
 826       * Legacy skills enhancement method
 827       */
 828      async enhanceSkillsSectionLegacy(cvData, activityMetrics) {
 829          // Expert personas based on creativity level
 830          const expertPersonas = {
 831              'conservative': {
 832                  persona: 'Dr. James Liu, Principal Engineering Manager at Google DeepMind, who has assessed technical skills of 500+ AI engineers for critical autonomous systems projects.',
 833                  approach: 'evidence-based skill validation with proven industry frameworks',
 834                  focus: 'demonstrable expertise with quantifiable proficiency levels'
 835              },
 836              'balanced': {
 837                  persona: 'Maria Santos, VP of Engineering at Anthropic, who built the technical hiring framework for constitutional AI development teams.',
 838                  approach: 'strategic skill positioning that balances depth with market relevance',
 839                  focus: 'comprehensive technical portfolio with growth trajectory'
 840              },
 841              'creative': {
 842                  persona: 'Dr. Raj Patel, Chief Technology Officer at Scale AI, pioneering the next generation of human-AI collaborative systems.',
 843                  approach: 'innovative skill narrative that positions for emerging opportunities',
 844                  focus: 'transformative technical capabilities with future-ready expertise'
 845              },
 846              'innovative': {
 847                  persona: 'Alex Chen, Co-founder and CTO of Adept AI, revolutionizing how AI agents interact with complex software systems.',
 848                  approach: 'visionary skill architecture for paradigm-shifting AI development',
 849                  focus: 'breakthrough technical innovation with industry-defining potential'
 850              }
 851          };
 852  
 853          const expert = expertPersonas[CONFIG.CREATIVITY_LEVEL] || expertPersonas['balanced'];
 854  
 855          // Activity-based insights
 856          const skillDepthIndicator = CONFIG.ACTIVITY_SCORE >= 80 ? 'demonstrates exceptional depth across multiple domains' :
 857                                     CONFIG.ACTIVITY_SCORE >= 60 ? 'shows strong technical versatility with consistent growth' :
 858                                     CONFIG.ACTIVITY_SCORE >= 40 ? 'exhibits focused expertise with quality-driven development' :
 859                                     'displays specialized knowledge with strategic technical choices';
 860  
 861          const expertiseEvolution = (activityMetrics?.top_languages?.length || 3) >= 5 ? 'polyglot technologist with rapid technology adoption' :
 862                                    (activityMetrics?.top_languages?.length || 3) >= 3 ? 'multi-platform engineer with strategic language selection' :
 863                                    'domain specialist with deep technical mastery';
 864  
 865          const communityImpact = (activityMetrics?.total_stars || 0) >= 100 ? 'significant open-source influence with community recognition' :
 866                                 (activityMetrics?.total_stars || 0) >= 20 ? 'growing technical influence with peer acknowledgment' :
 867                                 'focused contribution with quality-driven development';
 868  
 869          const messages = [
 870              {
 871                  role: 'system',
 872                  content: 'You are a professional skills analysis specialist. Respond ONLY with the requested JSON structure. Do not include explanatory text, analysis descriptions, or meta-commentary. Provide only clean, structured data without any additional formatting or process explanations.'
 873              },
 874              {
 875                  role: 'user',
 876                  content: `You are ${expert.persona}
 877  
 878  TECHNICAL PROFILE ANALYSIS:
 879  You're evaluating a developer who ${skillDepthIndicator}, functioning as a ${expertiseEvolution} with ${communityImpact}. Their GitHub footprint (${CONFIG.ACTIVITY_SCORE}/100 activity, ${activityMetrics?.top_languages?.join(', ') || 'Python, JavaScript, TypeScript'} expertise, ${activityMetrics?.total_repos || 'multiple'} repositories) reveals sophisticated technical judgment.
 880  
 881  MARKET INTELLIGENCE (2025):
 882  The AI engineering market prioritizes professionals who master autonomous agent development, real-time AI system optimization, and human-AI collaboration interfaces. Critical skills include production ML ops, edge computing for AI, and sustainable AI architecture patterns.
 883  
 884  SKILL ENHANCEMENT MISSION (${CONFIG.CREATIVITY_LEVEL} methodology):
 885  Using ${expert.approach}, create a ${expert.focus} skills analysis that positions this developer for senior AI engineering roles requiring both technical mastery and innovative thinking.
 886  
 887  GITHUB EVIDENCE BASE:
 888  - Activity Pattern: ${CONFIG.ACTIVITY_SCORE}/100 (${skillDepthIndicator})
 889  - Language Portfolio: ${activityMetrics?.top_languages?.join(', ') || 'Python, JavaScript, TypeScript'}
 890  - Repository Volume: ${activityMetrics?.total_repos || 'N/A'} projects
 891  - Community Recognition: ${activityMetrics?.total_stars || 'N/A'} stars
 892  
 893  <output_format>
 894  Respond with ONLY this JSON structure:
 895  
 896  {
 897    "skill_architecture": {
 898      "core_competencies": [
 899        {"skill": "AI/ML Systems", "proficiency": "Expert", "evidence": "GitHub activity justification"},
 900        {"skill": "Software Architecture", "proficiency": "Advanced", "evidence": "Repository pattern analysis"}
 901      ],
 902      "emerging_expertise": ["Future-ready skills based on current trajectory"],
 903      "market_differentiators": ["Unique technical combinations that create competitive advantage"]
 904    },
 905    "development_roadmap": {
 906      "immediate_priorities": ["Skills to develop in next 6 months"],
 907      "strategic_investments": ["Technologies to master for market positioning"],
 908      "innovation_opportunities": ["Cutting-edge areas for thought leadership"]
 909    },
 910    "positioning_strategy": {
 911      "technical_narrative": "How to present this skill portfolio compellingly",
 912      "market_alignment": "Industry demands this portfolio addresses",
 913      "differentiation_thesis": "What makes this skill combination unique"
 914    },
 915    "confidence_assessment": 0.95
 916  }
 917  </output_format>`
 918              }
 919          ];
 920  
 921          try {
 922              const response = await this.client.makeRequest(messages, { maxTokens: 800 }, JSON.stringify(cvData.skills));
 923              const responseText = response.content[0]?.text?.trim();
 924  
 925              // Clean the response text from potential artifacts
 926              const cleanedResponse = this.cleanResponseText(responseText);
 927  
 928              // Parse structured JSON response
 929              let skillsData;
 930              try {
 931                  skillsData = JSON.parse(cleanedResponse);
 932              } catch (parseError) {
 933                  console.warn('โš ๏ธ Skills JSON parsing failed, using fallback structure');
 934                  // Fallback structure if JSON parsing fails
 935                  skillsData = {
 936                      skill_architecture: { core_competencies: [], emerging_expertise: [], market_differentiators: [] },
 937                      development_roadmap: { immediate_priorities: [], strategic_investments: [], innovation_opportunities: [] },
 938                      positioning_strategy: { technical_narrative: this.cleanEnhancedContent(cleanedResponse).substring(0, 200) + '...' },
 939                      confidence_assessment: 0.7
 940                  };
 941              }
 942  
 943              return {
 944                  skill_analysis: skillsData.skill_architecture,
 945                  development_roadmap: skillsData.development_roadmap,
 946                  positioning_strategy: skillsData.positioning_strategy,
 947                  confidence_score: skillsData.confidence_assessment,
 948                  github_context: {
 949                      activity_score: CONFIG.ACTIVITY_SCORE,
 950                      top_languages: activityMetrics?.top_languages || [],
 951                      total_repos: activityMetrics?.total_repos || 0,
 952                      expertise_evolution: expertiseEvolution,
 953                      community_impact: communityImpact
 954                  },
 955                  enhancement_applied: true,
 956                  expert_methodology: expert.approach,
 957                  recommendations: this.extractSkillRecommendations(skillsData)
 958              };
 959          } catch (error) {
 960              console.warn('โš ๏ธ Skills enhancement failed');
 961              return {
 962                  enhancement_applied: false,
 963                  error: error.message
 964              };
 965          }
 966      }
 967  
 968      /**
 969       * Enhance experience descriptions
 970       * Enhanced with XML structuring and few-shot learning (Issues #96, #97)
 971       */
 972      async enhanceExperience(cvData, activityMetrics) {
 973          // Use XML-structured prompts with few-shot examples for enhanced quality
 974          if (this.useXMLPrompts) {
 975              return await this.enhanceExperienceXML(cvData, activityMetrics);
 976          }
 977  
 978          // Legacy method for backward compatibility
 979          return await this.enhanceExperienceLegacy(cvData, activityMetrics);
 980      }
 981  
 982      /**
 983       * Enhanced experience using XML structuring and few-shot prompting
 984       */
 985      async enhanceExperienceXML(cvData, activityMetrics) {
 986          console.log('๐Ÿ”จ Using XML-structured experience enhancement prompt...');
 987  
 988          try {
 989              // Construct XML-structured prompt with few-shot examples
 990              const promptResult = await this.xmlIntegrator.enhanceExperienceXML(
 991                  cvData,
 992                  activityMetrics,
 993                  CONFIG.CREATIVITY_LEVEL
 994              );
 995  
 996              console.log(`๐Ÿ“Š Expected experience quality improvement: ${(promptResult.quality_expected * 100).toFixed(1)}%`);
 997  
 998              // Create messages for Claude API
 999              const messages = [
1000                  {
1001                      role: 'system',
1002                      content: 'You are a professional experience enhancement specialist. Respond ONLY with the requested JSON structure. Do not include explanatory text or meta-commentary. Follow the provided examples for professional language and structure.'
1003                  },
1004                  {
1005                      role: 'user',
1006                      content: promptResult.xmlPrompt
1007                  }
1008              ];
1009  
1010              // Make API request
1011              const response = await this.client.makeRequest(messages, { maxTokens: 1200 }, JSON.stringify(cvData.experience));
1012              const responseText = response.content[0]?.text?.trim();
1013  
1014              // Clean and parse response
1015              const cleanedResponse = this.cleanResponseText(responseText);
1016              let experienceData;
1017  
1018              try {
1019                  experienceData = JSON.parse(cleanedResponse);
1020              } catch (parseError) {
1021                  console.warn('โš ๏ธ Experience JSON parsing failed, using fallback structure');
1022                  experienceData = {
1023                      experience_transformation: [],
1024                      career_progression_narrative: { leadership_evolution: this.cleanEnhancedContent(cleanedResponse).substring(0, 200) + '...' },
1025                      strategic_positioning: { technical_authority: 'Advanced AI/ML systems development' },
1026                      confidence_score: 0.7
1027                  };
1028              }
1029  
1030              // Validate response quality
1031              const validation = await this.xmlIntegrator.validateResponse(experienceData, 'experience-enhancement', promptResult.quality_expected);
1032  
1033              console.log(`โœ… Experience validation: ${validation.valid ? 'PASSED' : 'FAILED'} (Score: ${(validation.score * 100).toFixed(1)}%)`);
1034  
1035              return {
1036                  experience_enhancement: experienceData.experience_transformation,
1037                  career_narrative: experienceData.career_progression_narrative,
1038                  strategic_positioning: experienceData.strategic_positioning,
1039                  confidence_score: experienceData.confidence_score || validation.score,
1040                  leadership_progression: this.analyzeLeadershipProgression(CONFIG.ACTIVITY_SCORE),
1041                  market_positioning: this.analyzeMarketPositioning(CONFIG.ACTIVITY_SCORE, activityMetrics),
1042                  focus_areas: [
1043                      'Autonomous systems innovation',
1044                      'Technical leadership progression',
1045                      'Quantifiable business impact',
1046                      'AI/ML architecture excellence',
1047                      'Human-AI collaboration leadership'
1048                  ],
1049                  enhancement_applied: true,
1050                  prompt_strategy: 'xml-few-shot',
1051                  xml_metadata: promptResult.metadata,
1052                  validation_results: validation,
1053                  quality_indicators: {
1054                      xml_structured: true,
1055                      few_shot_guided: true,
1056                      validation_passed: validation.valid,
1057                      quality_score: validation.score,
1058                      expected_improvement: promptResult.quality_expected
1059                  }
1060              };
1061  
1062          } catch (error) {
1063              console.warn('โš ๏ธ XML experience enhancement failed, falling back to legacy method');
1064              return await this.enhanceExperienceLegacy(cvData, activityMetrics);
1065          }
1066      }
1067  
1068      /**
1069       * Legacy experience enhancement method
1070       */
1071      async enhanceExperienceLegacy(cvData, activityMetrics) {
1072          // Career narrative experts by creativity level
1073          const careerExperts = {
1074              'conservative': {
1075                  persona: 'Linda Zhang, Executive Coach specializing in AI leadership transitions, who has guided 150+ engineers to senior roles at Google, Microsoft, and Amazon.',
1076                  methodology: 'proven achievement quantification with established leadership frameworks',
1077                  narrative_style: 'authoritative progression with measurable impact'
1078              },
1079              'balanced': {
1080                  persona: 'Carlos Rivera, Career Strategy Partner at Sequoia Capital, helping technical founders articulate their journey from engineer to visionary leader.',
1081                  methodology: 'strategic storytelling that balances technical depth with business acumen',
1082                  narrative_style: 'compelling leadership evolution with innovation highlights'
1083              },
1084              'creative': {
1085                  persona: 'Dr. Aisha Patel, Executive Career Architect for AI unicorn startups, crafting narratives for technical leaders who will define the next decade of AI.',
1086                  methodology: 'transformative experience positioning for breakthrough opportunities',
1087                  narrative_style: 'visionary technical leadership with paradigm-shifting impact'
1088              },
1089              'innovative': {
1090                  persona: 'Morgan Kim, Chief People Officer at OpenAI, recognizing exceptional technical narratives that signal revolutionary potential in AI development.',
1091                  methodology: 'revolutionary experience articulation for industry-defining roles',
1092                  narrative_style: 'groundbreaking technical innovation with transformational leadership'
1093              }
1094          };
1095  
1096          const expert = careerExperts[CONFIG.CREATIVITY_LEVEL] || careerExperts['balanced'];
1097  
1098          // Dynamic career trajectory analysis
1099          const leadershipProgression = CONFIG.ACTIVITY_SCORE >= 80 ? 'demonstrates exceptional technical leadership with consistent innovation delivery' :
1100                                       CONFIG.ACTIVITY_SCORE >= 60 ? 'shows strong technical influence with growing leadership responsibilities' :
1101                                       CONFIG.ACTIVITY_SCORE >= 40 ? 'exhibits focused technical expertise with emerging leadership qualities' :
1102                                       'displays deep technical specialization with selective leadership engagement';
1103  
1104          const innovationCapacity = (activityMetrics?.total_repos || 0) >= 20 ? 'prolific technical innovator with diverse project portfolio' :
1105                                     (activityMetrics?.total_repos || 0) >= 10 ? 'strategic technical contributor with impactful project selection' :
1106                                     'focused technical expert with high-impact project concentration';
1107  
1108          const marketPositioning = CONFIG.ACTIVITY_SCORE >= 70 && (activityMetrics?.total_stars || 0) >= 50 ? 'industry-recognized technical leader ready for executive roles' :
1109                                    CONFIG.ACTIVITY_SCORE >= 50 ? 'emerging technical authority positioned for senior leadership' :
1110                                    'specialized technical expert ready for expanded influence';
1111  
1112          const messages = [
1113              {
1114                  role: 'system',
1115                  content: 'You are a professional experience enhancement specialist. Respond ONLY with the requested JSON structure. Do not include explanatory text, process descriptions, or meta-commentary. Provide only clean, structured data without any additional formatting or analysis explanations.'
1116              },
1117              {
1118                  role: 'user',
1119                  content: `You are ${expert.persona}
1120  
1121  CAREER TRAJECTORY ANALYSIS:
1122  You're crafting the experience narrative for a professional who ${leadershipProgression}, functioning as a ${innovationCapacity}. Their technical footprint positions them as a ${marketPositioning}.
1123  
1124  CURRENT PROFILE INDICATORS:
1125  - Technical Leadership Score: ${CONFIG.ACTIVITY_SCORE}/100
1126  - Innovation Portfolio: ${activityMetrics?.total_repos || 'Multiple'} projects demonstrating ${innovationCapacity}
1127  - Community Influence: ${activityMetrics?.total_stars || 'Growing'} recognition points
1128  - Technology Mastery: ${activityMetrics?.top_languages?.join(', ') || 'Python, JavaScript, TypeScript'} expertise
1129  
1130  MARKET CONTEXT (2025):
1131  Senior AI engineering roles demand professionals who can architect autonomous systems, lead human-AI collaboration initiatives, and drive sustainable AI development at scale. The market rewards leaders who bridge cutting-edge research with production-grade implementation.
1132  
1133  NARRATIVE ENHANCEMENT MISSION (${CONFIG.CREATIVITY_LEVEL} approach):
1134  Using ${expert.methodology}, create ${expert.narrative_style} that transforms their technical journey into a compelling leadership progression story. Focus on autonomous systems innovation, team impact, and business outcome alignment.
1135  
1136  CURRENT EXPERIENCE DATA:
1137  ${JSON.stringify(cvData.experience || [], null, 2)}
1138  
1139  <output_format>
1140  Respond with ONLY this JSON structure:
1141  
1142  {
1143    "experience_transformation": [
1144      {
1145        "role_title": "Enhanced title that reflects leadership scope",
1146        "impact_narrative": "Compelling 2-3 sentence description showcasing autonomous systems innovation and quantifiable business impact",
1147        "key_achievements": [
1148          "Specific accomplishment with metrics (e.g., 'Architected autonomous ML pipeline reducing deployment time by 75%')",
1149          "Leadership milestone with team impact",
1150          "Innovation breakthrough with industry relevance"
1151        ],
1152        "technical_leadership_evidence": "How this role demonstrates progression toward senior AI engineering leadership"
1153      }
1154    ],
1155    "career_progression_narrative": {
1156      "leadership_evolution": "How their journey shows increasing technical and team leadership",
1157      "innovation_trajectory": "Pattern of growing influence in AI/autonomous systems development",
1158      "market_positioning": "Why this experience prepares them for senior AI engineering roles"
1159    },
1160    "strategic_positioning": {
1161      "technical_authority": "Areas where they demonstrate thought leadership",
1162      "business_impact_pattern": "How their work consistently drives organizational outcomes",
1163      "future_readiness": "Evidence they're prepared for next-level AI engineering challenges"
1164    },
1165    "confidence_score": 0.95
1166  }
1167  </output_format>`
1168              }
1169          ];
1170  
1171          try {
1172              const response = await this.client.makeRequest(messages, { maxTokens: 900 }, JSON.stringify(cvData.experience));
1173              const responseText = response.content[0]?.text?.trim();
1174  
1175              // Clean the response text from potential artifacts
1176              const cleanedResponse = this.cleanResponseText(responseText);
1177  
1178              // Parse structured JSON response
1179              let experienceData;
1180              try {
1181                  experienceData = JSON.parse(cleanedResponse);
1182              } catch (parseError) {
1183                  console.warn('โš ๏ธ Experience JSON parsing failed, using fallback structure');
1184                  // Fallback structure if JSON parsing fails
1185                  experienceData = {
1186                      experience_transformation: [],
1187                      career_progression_narrative: { leadership_evolution: this.cleanEnhancedContent(cleanedResponse).substring(0, 200) + '...' },
1188                      strategic_positioning: { technical_authority: 'Advanced AI/ML systems development' },
1189                      confidence_score: 0.7
1190                  };
1191              }
1192  
1193              return {
1194                  experience_enhancement: experienceData.experience_transformation,
1195                  career_narrative: experienceData.career_progression_narrative,
1196                  strategic_positioning: experienceData.strategic_positioning,
1197                  confidence_score: experienceData.confidence_score,
1198                  leadership_progression: leadershipProgression,
1199                  market_positioning: marketPositioning,
1200                  focus_areas: [
1201                      'Autonomous systems innovation',
1202                      'Technical leadership progression',
1203                      'Quantifiable business impact',
1204                      'AI/ML architecture excellence',
1205                      'Human-AI collaboration leadership'
1206                  ],
1207                  enhancement_applied: true,
1208                  expert_methodology: expert.methodology
1209              };
1210          } catch (error) {
1211              console.warn('โš ๏ธ Experience enhancement failed');
1212              return {
1213                  enhancement_applied: false,
1214                  error: error.message
1215              };
1216          }
1217      }
1218  
1219      /**
1220       * Enhance project descriptions with impact analysis
1221       */
1222      async enhanceProjects(cvData, activityMetrics) {
1223          const messages = [
1224              {
1225                  role: 'system',
1226                  content: 'You are a professional project portfolio specialist. Respond with clean, professional project enhancement strategies only. Do not include explanatory text, process descriptions, or meta-commentary. Provide only the requested enhancement content without additional formatting or analysis.'
1227              },
1228              {
1229                  role: 'user',
1230                  content: `As a technical project portfolio specialist, enhance project descriptions for an AI Engineer's portfolio:
1231  
1232  **GitHub Portfolio Context:**
1233  - Total Projects: ${activityMetrics?.total_repos || 'N/A'}
1234  - Community Engagement: ${activityMetrics?.total_stars || 'N/A'} stars, ${activityMetrics?.total_forks || 'N/A'} forks
1235  - Language Diversity: ${activityMetrics?.language_count || 'N/A'} languages
1236  - Development Activity: ${CONFIG.ACTIVITY_SCORE}/100
1237  
1238  **Project Enhancement Strategy:**
1239  1. Transform technical descriptions into compelling project narratives
1240  2. Highlight innovation and problem-solving approach
1241  3. Quantify project impact and technical complexity
1242  4. Demonstrate expertise in AI, autonomous systems, and software architecture
1243  5. Show progression from simple to sophisticated projects
1244  
1245  **Target Project Categories:**
1246  - AI/ML Systems & Autonomous Agents
1247  - Software Architecture & System Design
1248  - Real-time Processing & Edge Computing
1249  - Developer Tools & Automation
1250  - Research & Innovation Projects
1251  
1252  **Enhancement Style:** ${CONFIG.CREATIVITY_LEVEL}
1253  
1254  <output_format>
1255  Provide enhanced project descriptions that:
1256  - Lead with problem statement and innovative solution
1257  - Highlight technical sophistication and architectural decisions
1258  - Quantify impact, performance, or adoption metrics
1259  - Connect to broader industry trends in AI/autonomous systems
1260  - Demonstrate continuous learning and technology adoption
1261  
1262  Create compelling project narratives that showcase technical expertise and innovation capability.
1263  </output_format>`
1264              }
1265          ];
1266  
1267          try {
1268              const response = await this.client.makeRequest(messages, { maxTokens: 600 }, JSON.stringify(cvData.projects));
1269              const responseText = response.content[0]?.text?.trim();
1270  
1271              // Clean the response text from potential artifacts
1272              const cleanedResponse = this.cleanResponseText(responseText);
1273              const projectEnhancement = this.cleanEnhancedContent(cleanedResponse);
1274  
1275              return {
1276                  enhancement_strategy: projectEnhancement,
1277                  portfolio_metrics: {
1278                      total_repos: activityMetrics?.total_repos || 0,
1279                      community_impact: (activityMetrics?.total_stars || 0) + (activityMetrics?.total_forks || 0),
1280                      language_diversity: activityMetrics?.language_count || 0,
1281                      activity_score: CONFIG.ACTIVITY_SCORE
1282                  },
1283                  enhancement_applied: true
1284              };
1285          } catch (error) {
1286              console.warn('โš ๏ธ Project enhancement failed');
1287              return {
1288                  enhancement_applied: false,
1289                  error: error.message
1290              };
1291          }
1292      }
1293  
1294      /**
1295       * Generate strategic career insights (advanced enhancement)
1296       */
1297      async generateStrategicInsights(cvData, activityMetrics) {
1298          // Strategic visionaries by creativity level
1299          const strategicExperts = {
1300              'conservative': {
1301                  persona: 'Dr. Jennifer Wu, Managing Partner at Andreessen Horowitz focusing on AI infrastructure investments, who has guided 50+ technical leaders to C-suite roles.',
1302                  approach: 'proven strategic positioning with established career advancement frameworks',
1303                  vision_scope: 'systematic market positioning with validated growth strategies'
1304              },
1305              'balanced': {
1306                  persona: 'Robert Kim, Executive Strategy Consultant for AI unicorns (Anthropic, OpenAI, Scale), architecting career trajectories for technical visionaries.',
1307                  approach: 'comprehensive strategic analysis balancing technical mastery with market opportunity',
1308                  vision_scope: 'multifaceted growth strategy with innovation leadership potential'
1309              },
1310              'creative': {
1311                  persona: 'Dr. Priya Sharma, Chief Strategy Officer at Mistral AI, identifying breakthrough talent for next-generation AI development paradigms.',
1312                  approach: 'innovative strategic positioning for emerging AI leadership opportunities',
1313                  vision_scope: 'transformative career architecture for industry-shaping roles'
1314              },
1315              'innovative': {
1316                  persona: 'Alex Thompson, Founding Partner at AI-focused venture fund, recognizing technical leaders who will define the next decade of artificial intelligence.',
1317                  approach: 'revolutionary strategic vision for paradigm-defining AI leadership',
1318                  vision_scope: 'visionary career trajectory for industry transformation leaders'
1319              }
1320          };
1321  
1322          const strategist = strategicExperts[CONFIG.CREATIVITY_LEVEL] || strategicExperts['balanced'];
1323  
1324          // Strategic positioning analysis
1325          const leadershipReadiness = CONFIG.ACTIVITY_SCORE >= 80 ? 'ready for executive AI leadership roles with proven innovation capacity' :
1326                                     CONFIG.ACTIVITY_SCORE >= 60 ? 'positioned for senior technical leadership with strong growth trajectory' :
1327                                     CONFIG.ACTIVITY_SCORE >= 40 ? 'prepared for expanded technical influence with focused expertise development' :
1328                                     'specialized for high-impact technical roles with strategic skill building';
1329  
1330          const marketDifferentiation = (activityMetrics?.total_stars || 0) >= 100 ? 'established technical thought leader with significant industry influence' :
1331                                       (activityMetrics?.total_stars || 0) >= 20 ? 'emerging technical authority with growing market recognition' :
1332                                       'focused technical expert with potential for expanded influence';
1333  
1334          const innovationProfile = (activityMetrics?.top_languages?.length || 3) >= 5 ? 'polyglot innovator positioned for cross-platform AI architecture leadership' :
1335                                    (activityMetrics?.top_languages?.length || 3) >= 3 ? 'multi-domain technologist ready for comprehensive AI system leadership' :
1336                                    'specialized expert positioned for deep technical domain leadership';
1337  
1338          const messages = [
1339              {
1340                  role: 'system',
1341                  content: 'You are a professional strategic insights specialist. Respond ONLY with the requested JSON structure. Do not include explanatory text, analysis descriptions, or meta-commentary. Provide only clean, structured strategic data without any additional formatting or process explanations.'
1342              },
1343              {
1344                  role: 'user',
1345                  content: `You are ${strategist.persona}
1346  
1347  STRATEGIC LEADERSHIP ASSESSMENT:
1348  You're analyzing a technical professional who is ${leadershipReadiness}, functioning as a ${marketDifferentiation} with characteristics of a ${innovationProfile}. Their technical foundation positions them uniquely in the evolving AI leadership landscape.
1349  
1350  PROFESSIONAL INTELLIGENCE METRICS:
1351  - Leadership Readiness Score: ${CONFIG.ACTIVITY_SCORE}/100
1352  - Innovation Portfolio: ${activityMetrics?.total_repos || 'Comprehensive'} projects demonstrating ${innovationProfile}
1353  - Market Influence: ${activityMetrics?.total_stars || 'Growing'} recognition indicating ${marketDifferentiation}
1354  - Technical Versatility: ${activityMetrics?.top_languages?.join(', ') || 'Python, JavaScript, TypeScript'} mastery
1355  - Geographic Advantage: Tasmania, Australia (unique timezone positioning for global AI collaboration)
1356  
1357  MARKET LANDSCAPE ANALYSIS (2025):
1358  The AI leadership market demands professionals who can architect autonomous agent ecosystems, lead multi-modal AI development, and drive responsible AI governance at scale. Critical opportunities exist in human-AI collaboration interfaces, sustainable AI development, and AI safety leadership.
1359  
1360  STRATEGIC VISION MISSION (${CONFIG.CREATIVITY_LEVEL} methodology):
1361  Using ${strategist.approach}, create ${strategist.vision_scope} that positions this professional for the highest-impact AI leadership opportunities in the next 3-5 years.
1362  
1363  CURRENT TECHNICAL PROFILE:
1364  ${JSON.stringify(cvData, null, 2)}
1365  
1366  <output_format>
1367  Respond with ONLY this JSON structure:
1368  
1369  {
1370    "executive_positioning": {
1371      "primary_value_proposition": "Core differentiating strength for AI leadership roles",
1372      "market_opportunity_alignment": "How their profile aligns with emerging AI market needs",
1373      "competitive_differentiation": "What makes them uniquely positioned vs other AI leaders"
1374    },
1375    "growth_trajectory": {
1376      "immediate_opportunities": [
1377        "Specific roles/companies to target in next 12 months"
1378      ],
1379      "strategic_skill_investments": [
1380        "Key capabilities to develop for maximum career impact"
1381      ],
1382      "thought_leadership_areas": [
1383        "Technical domains where they could establish industry authority"
1384      ]
1385    },
1386    "market_positioning_strategy": {
1387      "industry_narrative": "How to position their technical journey as preparation for AI leadership",
1388      "geographic_leverage": "How to maximize Tasmania location for global AI opportunities",
1389      "innovation_thesis": "Technical philosophy that differentiates their approach to AI development"
1390    },
1391    "execution_roadmap": {
1392      "quarter_1_actions": ["Immediate steps to enhance market positioning"],
1393      "year_1_milestones": ["Key achievements to establish thought leadership"],
1394      "long_term_vision": "Ultimate career destination and impact potential"
1395    },
1396    "confidence_assessment": 0.95
1397  }
1398  </output_format>`
1399              }
1400          ];
1401  
1402          try {
1403              const response = await this.client.makeRequest(messages, { maxTokens: 1000 }, JSON.stringify(cvData));
1404              const responseText = response.content[0]?.text?.trim();
1405  
1406              // Clean the response text from potential artifacts
1407              const cleanedResponse = this.cleanResponseText(responseText);
1408  
1409              // Parse comprehensive strategic JSON response
1410              let strategicData;
1411              try {
1412                  strategicData = JSON.parse(cleanedResponse);
1413              } catch (parseError) {
1414                  console.warn('โš ๏ธ Strategic insights JSON parsing failed, using fallback structure');
1415                  // Fallback structure if JSON parsing fails
1416                  strategicData = {
1417                      executive_positioning: { primary_value_proposition: this.cleanEnhancedContent(cleanedResponse).substring(0, 150) + '...' },
1418                      growth_trajectory: { immediate_opportunities: [], strategic_skill_investments: [] },
1419                      market_positioning_strategy: { industry_narrative: 'AI engineering leadership positioning' },
1420                      execution_roadmap: { quarter_1_actions: [], year_1_milestones: [] },
1421                      confidence_assessment: 0.75
1422                  };
1423              }
1424  
1425              return {
1426                  executive_positioning: strategicData.executive_positioning,
1427                  growth_strategy: strategicData.growth_trajectory,
1428                  market_positioning: strategicData.market_positioning_strategy,
1429                  execution_plan: strategicData.execution_roadmap,
1430                  confidence_score: strategicData.confidence_assessment,
1431                  leadership_readiness: leadershipReadiness,
1432                  market_differentiation: marketDifferentiation,
1433                  innovation_profile: innovationProfile,
1434                  market_context: {
1435                      activity_score: CONFIG.ACTIVITY_SCORE,
1436                      specialization: 'AI Engineering & Autonomous Systems Leadership',
1437                      location_advantage: 'Tasmania, Australia (Global AI Collaboration Hub)',
1438                      innovation_focus: 'Autonomous AI Architecture, Human-AI Collaboration Leadership, Sustainable AI Development'
1439                  },
1440                  strategic_methodology: strategist.approach,
1441                  insights_generated: true
1442              };
1443          } catch (error) {
1444              console.warn('โš ๏ธ Strategic insights generation failed');
1445              return {
1446                  insights_generated: false,
1447                  error: error.message
1448              };
1449          }
1450      }
1451  
1452      /**
1453       * Load current CV data from existing files
1454       */
1455      async loadCurrentCVData() {
1456          try {
1457              const cvDataPath = path.join(CONFIG.OUTPUT_DIR, 'base-cv.json');
1458              const cvData = await fs.readFile(cvDataPath, 'utf8');
1459              return JSON.parse(cvData);
1460          } catch (error) {
1461              console.log('๐Ÿ“ No existing CV data found, using defaults');
1462              return {
1463                  professional_summary: "AI Engineer and Software Architect specializing in autonomous systems and machine learning.",
1464                  skills: [],
1465                  experience: [],
1466                  projects: []
1467              };
1468          }
1469      }
1470  
1471      /**
1472       * Load GitHub activity metrics
1473       */
1474      async loadActivityMetrics() {
1475          try {
1476              const activityPath = path.join(CONFIG.OUTPUT_DIR, 'activity-summary.json');
1477              const activityData = await fs.readFile(activityPath, 'utf8');
1478              const parsedData = JSON.parse(activityData);
1479  
1480              return {
1481                  total_repos: parsedData.summary?.raw_data?.repositories || 0,
1482                  total_stars: parsedData.summary?.raw_data?.stars_received || 0,
1483                  total_forks: parsedData.summary?.raw_data?.total_forks || 0,
1484                  top_languages: parsedData.skill_analysis?.top_3_skills || ['Python', 'JavaScript', 'TypeScript'],
1485                  language_count: parsedData.summary?.raw_data?.languages_used || 0,
1486                  development_velocity: parsedData.summary?.raw_data?.repositories || 0
1487              };
1488          } catch (error) {
1489              console.log('๐Ÿ“Š No activity metrics found, using defaults');
1490              return {
1491                  total_repos: 0,
1492                  total_stars: 0,
1493                  total_forks: 0,
1494                  top_languages: ['Python', 'JavaScript', 'TypeScript'],
1495                  language_count: 3,
1496                  development_velocity: 0
1497              };
1498          }
1499      }
1500  
1501      async loadKeywordGaps() {
1502          try {
1503              const { execSync } = require('child_process');
1504              const output = execSync('node keyword-scorer.js --gaps', { encoding: 'utf8', cwd: __dirname });
1505              return JSON.parse(output);
1506          } catch {
1507              return { ats_score: null, top_missing: [] };
1508          }
1509      }
1510  
1511      /**
1512       * Generate enhancement summary with XML prompt engineering statistics
1513       */
1514      generateEnhancementSummary(enhancementPlan) {
1515          const usageStats = this.client.getUsageStats();
1516          const enhancementTime = (Date.now() - this.enhancementStartTime) / 1000;
1517          const xmlStats = this.xmlIntegrator.getStats();
1518  
1519          return {
1520              enhancement_overview: {
1521                  total_stages_completed: Object.keys(enhancementPlan).filter(key =>
1522                      key !== 'metadata' && key !== 'enhancement_summary'
1523                  ).length,
1524                  creativity_level: CONFIG.CREATIVITY_LEVEL,
1525                  ai_budget_used: CONFIG.AI_BUDGET,
1526                  enhancement_duration_seconds: Math.round(enhancementTime),
1527                  xml_prompts_enabled: this.useXMLPrompts
1528              },
1529              token_analytics: usageStats,
1530              xml_prompt_analytics: {
1531                  xml_integrator_initialized: xmlStats.initialized,
1532                  xml_constructor_stats: xmlStats.xml_constructor_stats,
1533                  performance_metrics: xmlStats.performance_metrics,
1534                  quality_improvements: this.countQualityImprovements(enhancementPlan)
1535              },
1536              enhancement_effectiveness: {
1537                  professional_summary: enhancementPlan.professional_summary?.enhancement_applied || false,
1538                  skills_analysis: enhancementPlan.skills_enhancement?.enhancement_applied || false,
1539                  experience_optimization: enhancementPlan.experience_enhancement?.enhancement_applied || false,
1540                  project_enhancement: enhancementPlan.project_enhancement?.enhancement_applied || false,
1541                  strategic_insights: enhancementPlan.strategic_insights?.insights_generated || false
1542              },
1543              quality_indicators: {
1544                  xml_structured_prompts: this.countXMLStructuredPrompts(enhancementPlan),
1545                  few_shot_guided_enhancements: this.countFewShotEnhancements(enhancementPlan),
1546                  validation_passed_count: this.countValidationPasses(enhancementPlan),
1547                  average_quality_score: this.calculateAverageQualityScore(enhancementPlan)
1548              },
1549              recommendations: {
1550                  content_freshness: 'Enhanced with current industry trends and XML-structured prompts',
1551                  market_alignment: `Optimized for ${CONFIG.CREATIVITY_LEVEL} creativity approach with few-shot learning`,
1552                  technical_positioning: 'Aligned with AI/ML industry demands using advanced prompt engineering',
1553                  career_advancement: 'Strategic insights provided with evidence-based validation and quality scoring'
1554              }
1555          };
1556      }
1557  
1558      /**
1559       * Count quality improvements from XML enhancements
1560       */
1561      countQualityImprovements(enhancementPlan) {
1562          let count = 0;
1563          ['professional_summary', 'skills_enhancement', 'experience_enhancement'].forEach(section => {
1564              if (enhancementPlan[section]?.validation_results?.quality_improvement) {
1565                  count++;
1566              }
1567          });
1568          return count;
1569      }
1570  
1571      /**
1572       * Count XML-structured prompts used
1573       */
1574      countXMLStructuredPrompts(enhancementPlan) {
1575          let count = 0;
1576          ['professional_summary', 'skills_enhancement', 'experience_enhancement'].forEach(section => {
1577              if (enhancementPlan[section]?.quality_indicators?.xml_structured) {
1578                  count++;
1579              }
1580          });
1581          return count;
1582      }
1583  
1584      /**
1585       * Count few-shot guided enhancements
1586       */
1587      countFewShotEnhancements(enhancementPlan) {
1588          let count = 0;
1589          ['professional_summary', 'skills_enhancement', 'experience_enhancement'].forEach(section => {
1590              if (enhancementPlan[section]?.quality_indicators?.few_shot_guided) {
1591                  count++;
1592              }
1593          });
1594          return count;
1595      }
1596  
1597      /**
1598       * Count validation passes
1599       */
1600      countValidationPasses(enhancementPlan) {
1601          let count = 0;
1602          ['professional_summary', 'skills_enhancement', 'experience_enhancement'].forEach(section => {
1603              if (enhancementPlan[section]?.quality_indicators?.validation_passed) {
1604                  count++;
1605              }
1606          });
1607          return count;
1608      }
1609  
1610      /**
1611       * Calculate average quality score
1612       */
1613      calculateAverageQualityScore(enhancementPlan) {
1614          const scores = [];
1615          ['professional_summary', 'skills_enhancement', 'experience_enhancement'].forEach(section => {
1616              const score = enhancementPlan[section]?.quality_indicators?.quality_score;
1617              if (score && typeof score === 'number') {
1618                  scores.push(score);
1619              }
1620          });
1621          return scores.length > 0 ? scores.reduce((sum, score) => sum + score, 0) / scores.length : 0;
1622      }
1623  
1624      /**
1625       * Save enhancement results
1626       */
1627      async saveEnhancementResults(enhancementPlan) {
1628          const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
1629  
1630          // Save comprehensive enhancement results
1631          const enhancementPath = path.join(CONFIG.OUTPUT_DIR, `ai-enhancement-${timestamp}.json`);
1632          await fs.writeFile(enhancementPath, JSON.stringify(enhancementPlan, null, 2), 'utf8');
1633  
1634          // Save current enhancement for CV integration
1635          const currentPath = path.join(CONFIG.OUTPUT_DIR, 'ai-enhancements.json');
1636          await fs.writeFile(currentPath, JSON.stringify({
1637              last_updated: new Date().toISOString(),
1638              creativity_level: CONFIG.CREATIVITY_LEVEL,
1639              ai_budget: CONFIG.AI_BUDGET,
1640              activity_score: CONFIG.ACTIVITY_SCORE,
1641              professional_summary: enhancementPlan.professional_summary,
1642              skills_enhancement: enhancementPlan.skills_enhancement,
1643              enhancement_summary: enhancementPlan.enhancement_summary
1644          }, null, 2), 'utf8');
1645  
1646          console.log(`๐Ÿ’พ Enhancement results saved:`);
1647          console.log(`  ๐Ÿค– Comprehensive: ${enhancementPath}`);
1648          console.log(`  ๐Ÿ“‹ Current: ${currentPath}`);
1649      }
1650  
1651      /**
1652       * Ensure output directory exists
1653       */
1654      async ensureOutputDir() {
1655          try {
1656              await fs.access(CONFIG.OUTPUT_DIR);
1657          } catch {
1658              await fs.mkdir(CONFIG.OUTPUT_DIR, { recursive: true });
1659          }
1660      }
1661  
1662      /**
1663       * Clean response text from Claude API to remove meta-commentary artifacts
1664       */
1665      cleanResponseText(text) {
1666          if (!text) return text;
1667  
1668          // Remove common meta-commentary patterns
1669          const metaPatterns = [
1670              /^Here's an enhanced.*?:\s*/i,
1671              /^\*\*Enhanced.*?\*\*\s*/i,
1672              /^Enhanced.*?:\s*/i,
1673              /\n\nThis enhancement:.*$/s,
1674              /\n\n.*?enhancement.*?:\s*\n.*$/s,
1675              /\n\n.*?improvement.*?:\s*\n.*$/s,
1676              /The.*?provided.*?placeholder.*$/s,
1677              /^I'll.*?\.\s*/i,
1678              /^Let me.*?\.\s*/i
1679          ];
1680  
1681          let cleaned = text;
1682          for (const pattern of metaPatterns) {
1683              cleaned = cleaned.replace(pattern, '');
1684          }
1685  
1686          return cleaned.trim();
1687      }
1688  
1689      /**
1690       * Clean enhanced content from artifacts and meta-commentary
1691       */
1692      cleanEnhancedContent(content) {
1693          if (!content) return content;
1694  
1695          // Remove specific meta-commentary patterns from enhanced content
1696          let cleaned = content
1697              .replace(/^Here's an enhanced.*?:\s*/i, '')
1698              .replace(/^\*\*Enhanced.*?\*\*\s*/i, '')
1699              .replace(/^Enhanced.*?:\s*/i, '')
1700              .replace(/\n\nThis enhancement:.*$/s, '')
1701              .replace(/\n\n.*?enhancement.*?$/s, '')
1702              .replace(/The.*?provided.*?placeholder.*$/s, '')
1703              .replace(/^- .*?\n/gm, '') // Remove bullet point explanations
1704              .replace(/\n\n+/g, ' ') // Replace multiple newlines with single space
1705              .trim();
1706  
1707          // If content still looks like meta-commentary, extract just the summary part
1708          if (cleaned.toLowerCase().includes('this ') || cleaned.toLowerCase().includes('the ')) {
1709              const summaryMatch = cleaned.match(/Results-driven.*?\.|Innovative.*?\.|Experienced.*?\.|Senior.*?\./i);
1710              if (summaryMatch) {
1711                  cleaned = summaryMatch[0];
1712              }
1713          }
1714  
1715          return cleaned;
1716      }
1717  
1718      /**
1719       * Extract content from text when JSON parsing fails
1720       */
1721      extractContentFromText(text) {
1722          const cleaned = this.cleanResponseText(text);
1723  
1724          // Try to parse as JSON first, even if it looks malformed
1725          try {
1726              const jsonMatch = cleaned.match(/\{[\s\S]*\}/);
1727              if (jsonMatch) {
1728                  const jsonData = JSON.parse(jsonMatch[0]);
1729                  if (jsonData.enhanced_summary) {
1730                      jsonData.enhanced_summary = this.cleanEnhancedContent(jsonData.enhanced_summary);
1731                      return jsonData;
1732                  }
1733              }
1734          } catch (error) {
1735              // Continue with text extraction
1736          }
1737  
1738          // Try to extract enhanced summary from various patterns
1739          let enhancedSummary = cleaned;
1740  
1741          // Look for enhanced summary in quotes or after colons
1742          const summaryPatterns = [
1743              /"enhanced_summary":\s*"([^"]+)"/i,
1744              /enhanced.*?summary.*?:\s*"([^"]+)"/i,
1745              /summary.*?:\s*"([^"]+)"/i,
1746              /"([^"]*(?:AI|Engineer|Software|Architect)[^"]*)"/i
1747          ];
1748  
1749          for (const pattern of summaryPatterns) {
1750              const match = cleaned.match(pattern);
1751              if (match && match[1]) {
1752                  enhancedSummary = match[1];
1753                  break;
1754              }
1755          }
1756  
1757          return {
1758              enhanced_summary: this.cleanEnhancedContent(enhancedSummary),
1759              strategic_improvements: { positioning_shift: "Enhanced with AI optimization" },
1760              ats_keywords: [],
1761              confidence_score: 0.7
1762          };
1763      }
1764  
1765      // Helper methods
1766      analyzeSummaryImprovement(original, enhanced) {
1767          if (!enhanced) return { improvement_indicators: ['Enhancement processing failed'] };
1768  
1769          return {
1770              length_change: enhanced.length - original.length,
1771              word_count_change: enhanced.split(' ').length - original.split(' ').length,
1772              improvement_indicators: [
1773                  'Enhanced professional language',
1774                  'Improved value proposition clarity',
1775                  'Strengthened industry positioning'
1776              ]
1777          };
1778      }
1779  
1780      analyzeLeadershipProgression(activityScore) {
1781          return activityScore >= 80 ? 'demonstrates exceptional technical leadership with consistent innovation delivery' :
1782                 activityScore >= 60 ? 'shows strong technical influence with growing leadership responsibilities' :
1783                 activityScore >= 40 ? 'exhibits focused technical expertise with emerging leadership qualities' :
1784                 'displays deep technical specialization with selective leadership engagement';
1785      }
1786  
1787      analyzeMarketPositioning(activityScore, activityMetrics) {
1788          return activityScore >= 70 && (activityMetrics?.total_stars || 0) >= 50 ? 'industry-recognized technical leader ready for executive roles' :
1789                 activityScore >= 50 ? 'emerging technical authority positioned for senior leadership' :
1790                 'specialized technical expert ready for expanded influence';
1791      }
1792  
1793      extractSkillRecommendations(skillsData) {
1794          // Extract actionable recommendations from structured skills analysis
1795          if (skillsData && skillsData.development_roadmap) {
1796              return [
1797                  ...skillsData.development_roadmap.immediate_priorities || [],
1798                  ...skillsData.development_roadmap.strategic_investments || [],
1799                  ...skillsData.development_roadmap.innovation_opportunities || []
1800              ];
1801          }
1802  
1803          // Fallback recommendations
1804          return [
1805              'Continue developing AI/ML expertise',
1806              'Expand cloud architecture knowledge',
1807              'Strengthen autonomous systems experience',
1808              'Enhance leadership and mentoring skills'
1809          ];
1810      }
1811  }
1812  
1813  /**
1814   * Main execution function
1815   */
1816  async function main() {
1817      if (!CONFIG.ANTHROPIC_API_KEY && !CONFIG.USE_CLAUDE_CODE) {
1818          console.error('โŒ ANTHROPIC_API_KEY environment variable is required (or set USE_CLAUDE_CODE=true)');
1819          process.exit(1);
1820      }
1821  
1822      if (!CONFIG.ANTHROPIC_API_KEY && CONFIG.USE_CLAUDE_CODE) {
1823          console.log('๐Ÿ”ง Using Claude Code CLI (Max subscription) โ€” no API key needed');
1824      }
1825  
1826      try {
1827          const enhancer = new CVContentEnhancer();
1828          const results = await enhancer.enhance();
1829  
1830          const usageStats = enhancer.client.getUsageStats();
1831  
1832          console.log('\n๐ŸŽ‰ **ENHANCEMENT COMPLETE**');
1833          console.log(`๐Ÿค– Stages completed: ${results.enhancement_summary?.enhancement_overview?.total_stages_completed || 'N/A'}`);
1834          console.log(`๐Ÿ“Š Token usage: ${usageStats.total_tokens} (${usageStats.cache_efficiency_percent}% cached)`);
1835          console.log(`๐ŸŽจ Creativity level: ${CONFIG.CREATIVITY_LEVEL}`);
1836          console.log(`โšก Activity score: ${CONFIG.ACTIVITY_SCORE}/100`);
1837  
1838          return results;
1839      } catch (error) {
1840          console.error('โŒ Enhancement failed:', error.message);
1841          process.exit(1);
1842      }
1843  }
1844  
1845  /**
1846   * Test content cleaning functions with sample problematic outputs
1847   */
1848  function testContentCleaning() {
1849      console.log('๐Ÿงช Testing content cleaning functions...');
1850  
1851      const enhancer = new CVContentEnhancer();
1852  
1853      // Test cases with typical problematic outputs
1854      const testCases = [
1855          {
1856              name: 'Meta-commentary with explanation',
1857              input: 'Here\'s an enhanced professional summary:\n\n**Enhanced Summary:**\nResults-driven AI Engineer and Software Architect who has successfully delivered 15+ autonomous systems that have increased operational efficiency by an average of 40% across enterprise clients.\n\nThis enhancement:\n- Opens with a strong, measurable impact statement\n- Incorporates specific technical expertise',
1858              expected: 'Results-driven AI Engineer and Software Architect who has successfully delivered 15+ autonomous systems that have increased operational efficiency by an average of 40% across enterprise clients.'
1859          },
1860          {
1861              name: 'Process explanation artifact',
1862              input: 'I\'ll provide an enhanced summary: Senior AI Engineer with deep expertise in autonomous systems and machine learning architectures. The numbers provided are placeholders that should be adjusted to match actual achievements.',
1863              expected: 'Senior AI Engineer with deep expertise in autonomous systems and machine learning architectures.'
1864          },
1865          {
1866              name: 'JSON with meta-commentary',
1867              input: '{"enhanced_summary": "Here\'s an enhanced professional summary: Innovative AI Engineer specializing in autonomous systems development.", "confidence_score": 0.95}',
1868              expected: 'Innovative AI Engineer specializing in autonomous systems development.'
1869          },
1870          {
1871              name: 'Clean professional summary',
1872              input: 'Senior AI Engineer and Software Architect with 8+ years experience developing cutting-edge autonomous systems and machine learning solutions.',
1873              expected: 'Senior AI Engineer and Software Architect with 8+ years experience developing cutting-edge autonomous systems and machine learning solutions.'
1874          }
1875      ];
1876  
1877      testCases.forEach((testCase, index) => {
1878          console.log(`\n๐Ÿ” Test ${index + 1}: ${testCase.name}`);
1879          console.log('๐Ÿ“ฅ Input:', testCase.input.substring(0, 100) + '...');
1880  
1881          let enhanced;
1882  
1883          // For JSON test cases, use the extraction function
1884          if (testCase.input.startsWith('{')) {
1885              const extracted = enhancer.extractContentFromText(testCase.input);
1886              enhanced = extracted.enhanced_summary;
1887          } else {
1888              const cleaned = enhancer.cleanResponseText(testCase.input);
1889              enhanced = enhancer.cleanEnhancedContent(cleaned);
1890          }
1891  
1892          console.log('๐Ÿงน Cleaned:', enhanced.substring(0, 100) + (enhanced.length > 100 ? '...' : ''));
1893          console.log('โœ… Expected:', testCase.expected.substring(0, 100) + (testCase.expected.length > 100 ? '...' : ''));
1894  
1895          // Basic validation
1896          const isClean = !enhanced.toLowerCase().includes('here\'s') &&
1897                         !enhanced.toLowerCase().includes('this enhancement') &&
1898                         !enhanced.toLowerCase().includes('i\'ll provide');
1899  
1900          console.log(`${isClean ? 'โœ…' : 'โŒ'} Cleaning ${isClean ? 'successful' : 'needs improvement'}`);
1901      });
1902  
1903      console.log('\n๐ŸŽ‰ Content cleaning test completed');
1904  }
1905  
1906  // Execute if called directly
1907  if (require.main === module) {
1908      const args = process.argv.slice(2);
1909  
1910      if (args.includes('--test-cleaning')) {
1911          testContentCleaning();
1912      } else {
1913          main().catch(console.error);
1914      }
1915  }
1916  
1917  module.exports = { CVContentEnhancer, CONFIG, ClaudeApiClient };