UNPKG

cc-enhance

Version:

Adaptive prompt intelligence with 25-step selection, CLAUDE.md adherence, MCP tool orchestration, parallel execution and memory integration for Claude Code

285 lines 12.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.detectTaskType = detectTaskType; exports.generateContrarianAnalysis = generateContrarianAnalysis; exports.generateRequirements = generateRequirements; exports.enhancePrompt = enhancePrompt; exports.formatEnhancedPrompt = formatEnhancedPrompt; const agents_1 = require("./agents"); /** * Detect the task type from the user's request */ function detectTaskType(request) { const lower = request.toLowerCase(); const patterns = { implementation: ['implement', 'create', 'build', 'add', 'develop', 'feature'], analysis: ['analyze', 'introspect', 'review', 'evaluate', 'assess', 'examine'], debugging: ['fix', 'debug', 'troubleshoot', 'solve', 'error', 'bug', 'issue'], documentation: ['document', 'explain', 'describe', 'write docs', 'readme'], architecture: ['design', 'structure', 'architect', 'plan', 'organize'] }; let primary = 'implementation'; let maxMatches = 0; for (const [type, keywords] of Object.entries(patterns)) { const matches = keywords.filter(kw => lower.includes(kw)).length; if (matches > maxMatches) { maxMatches = matches; primary = type; } } // Detect contexts const contexts = []; if (lower.includes('test') || lower.includes('spec')) contexts.push('testing'); if (lower.includes('file') || lower.includes('create') || lower.includes('modify') || lower.includes('implement')) contexts.push('file-operations'); if (lower.includes('refactor') || lower.includes('optimize')) contexts.push('code-quality'); if (lower.includes('deploy') || lower.includes('config')) contexts.push('operations'); if (lower.includes('agent') || lower.includes('subagent')) contexts.push('agent-management'); return { primary, contexts }; } /** * Generate contrarian analysis questions */ function generateContrarianAnalysis(request, taskType) { const baseQuestions = [ 'Is this solving the real problem or just symptoms?', 'What assumptions are we making that could be wrong?', 'Could a simpler approach achieve the same result?', 'What if we did nothing instead?', 'Is there a 10x better solution we\'re missing?' ]; // Add task-specific contrarian questions const specificQuestions = { debugging: [ 'Is this actually a bug or expected behavior?', 'Could this be a configuration/deployment issue instead of code?', 'Are we debugging in the right place?' ], implementation: [ 'Do we really need this feature?', 'Is there an existing solution we can use instead?', 'Will this add unnecessary complexity?' ], architecture: [ 'Are we over-engineering this?', 'Will this architecture scale or create future problems?', 'Can we defer this decision until we know more?' ] }; const additionalQuestions = specificQuestions[taskType.primary] || []; return [...baseQuestions, ...additionalQuestions]; } /** * Generate requirements with parallel execution markers */ function generateRequirements(request, taskType) { const original = []; const adjusted = []; // Generate base requirements based on task type switch (taskType.primary) { case 'debugging': original.push('Reproduce the issue with test cases', 'Check logs and error messages', 'Verify recent code changes'); adjusted.push('Check recent deployments and config changes first', 'Validate that the issue is actually a bug', 'Search for similar past issues', 'Only debug code if config/deployment checks fail'); break; case 'implementation': original.push('Understand the requirements', 'Design the solution', 'Implement the feature', 'Add tests'); adjusted.push('Validate that the feature is necessary', 'Check for existing solutions first', 'Design for simplicity over completeness', 'Consider future maintenance burden'); break; default: original.push('Analyze the current state', 'Identify improvement areas', 'Implement changes', 'Validate results'); adjusted.push('Question if changes are needed', 'Consider the cost-benefit ratio', 'Start with minimal changes', 'Measure impact before and after'); } // Add parallel markers to appropriate tasks const markedOriginal = (0, agents_1.addParallelMarkers)(original); const markedAdjusted = (0, agents_1.addParallelMarkers)(adjusted); return { original: markedOriginal, adjusted: markedAdjusted }; } /** * Main enhancement function */ async function enhancePrompt(request, options = {}) { // Detect task type const taskType = detectTaskType(request); // Detect available agents if enabled let agentSuggestion; if (options.enableAgentDetection !== false) { try { const agents = await (0, agents_1.detectAgents)(); agentSuggestion = (0, agents_1.matchAgentToTask)(taskType.primary, request, agents); } catch (error) { // Silently handle agent detection errors } } // Generate contrarian analysis const contrarianAnalysis = generateContrarianAnalysis(request, taskType); // Generate requirements with parallel markers const requirements = generateRequirements(request, taskType); // Build the enhanced prompt structure const enhanced = { title: generateTitle(request), taskType, context: generateContext(request, taskType), contrarianAnalysis, adjustments: generateAdjustments(contrarianAnalysis), agentSuggestion, requirements, edgeCases: generateEdgeCases(taskType), constraints: generateConstraints(taskType), deliverables: generateDeliverables(taskType), successCriteria: generateSuccessCriteria(taskType), measurableOutcomes: generateMeasurableOutcomes(taskType) }; return enhanced; } /** * Format the enhanced prompt for output */ function formatEnhancedPrompt(prompt) { let output = `Enhanced Prompt: ${prompt.title}\n\n`; output += `DETECTED TASK TYPE:\n`; output += `Primary intent: ${prompt.taskType.primary}\n`; output += `Relevant contexts: ${prompt.taskType.contexts.join(', ') || 'general'}\n\n`; output += `CONTEXT & MOTIVATION:\n`; output += `${prompt.context}\n\n`; output += `CONTRARIAN ANALYSIS (EARLY):\n`; prompt.contrarianAnalysis.forEach(q => { output += `- ${q}\n`; }); output += `\n`; output += `CONTRARIAN-INFORMED ADJUSTMENTS:\n`; output += `Based on the contrarian analysis:\n`; prompt.adjustments.forEach(adj => { output += `- ${adj}\n`; }); output += `\n`; // Add agent suggestions if available if (prompt.agentSuggestion) { output += `AGENT RECOMMENDATIONS:\n`; output += (0, agents_1.formatAgentSuggestions)(prompt.agentSuggestion); output += `\n`; } output += `REQUIREMENTS (CONTRARIAN-INFORMED):\n`; output += `Original requirements:\n`; prompt.requirements.original.forEach(req => { output += `- ${req}\n`; }); output += `\nAdjusted based on contrarian analysis:\n`; prompt.requirements.adjusted.forEach(req => { output += `- ${req}\n`; }); output += `\n`; output += `PARALLEL EXECUTION NOTE:\n`; output += `Tasks marked with 🔄 can be executed in parallel using multiple Task invocations in a SINGLE message.\n\n`; output += `EDGE CASES & ROBUSTNESS:\n`; prompt.edgeCases.forEach(edge => { output += `- ${edge}\n`; }); output += `\n`; output += `CONSTRAINTS:\n`; prompt.constraints.forEach(constraint => { output += `- ${constraint}\n`; }); output += `\n`; output += `DELIVERABLES:\n`; prompt.deliverables.forEach(deliverable => { output += `- ${deliverable}\n`; }); output += `\n`; output += `SUCCESS CRITERIA:\n`; prompt.successCriteria.forEach(criteria => { output += `- [ ] ${criteria}\n`; }); output += `\n`; output += `MEASURABLE OUTCOMES:\n`; prompt.measurableOutcomes.forEach(outcome => { output += `- [ ] ${outcome}\n`; }); return output; } // Helper functions function generateTitle(request) { // Extract first 50 chars or first sentence const firstSentence = request.split(/[.!?]/)[0]; return firstSentence.length > 50 ? firstSentence.substring(0, 47) + '...' : firstSentence; } function generateContext(request, taskType) { const contexts = { implementation: 'This implementation task requires careful planning and execution to ensure it integrates well with existing code and meets all requirements.', debugging: 'This debugging task requires systematic investigation to identify root causes rather than just fixing symptoms.', analysis: 'This analysis task requires thorough examination of the current state to make informed decisions.', documentation: 'This documentation task ensures knowledge is captured and shared effectively with the team.', architecture: 'This architectural task shapes the long-term structure and maintainability of the system.' }; return contexts[taskType.primary] + ' ' + 'Understanding the full context and challenging assumptions will lead to better outcomes. ' + 'Each requirement should be validated against real needs rather than assumed ones.'; } function generateAdjustments(contrarianQuestions) { return [ 'Validate assumptions before proceeding with implementation', 'Consider simpler alternatives that achieve 80% of the value', 'Focus on root causes rather than surface symptoms', 'Measure impact to justify the work', 'Look for existing solutions before building new ones' ]; } function generateEdgeCases(taskType) { const common = [ 'Null/undefined/empty inputs', 'Concurrent access and race conditions', 'Resource limits and memory constraints', 'Network failures and timeouts' ]; const specific = { implementation: ['Feature flags and gradual rollout', 'Backward compatibility'], debugging: ['Intermittent failures', 'Environment-specific issues'], architecture: ['Scaling limits', 'Migration paths'] }; return [...common, ...(specific[taskType.primary] || [])]; } function generateConstraints(taskType) { return [ 'Must maintain backward compatibility', 'Should not introduce breaking changes', 'Keep changes focused and minimal', 'Preserve existing test coverage', 'Follow project conventions and patterns' ]; } function generateDeliverables(taskType) { const base = ['Updated code with changes', 'Test coverage for new code']; const specific = { implementation: ['Feature documentation', 'Usage examples'], debugging: ['Root cause analysis', 'Fix verification'], documentation: ['Updated documentation files', 'Code examples'], architecture: ['Design documents', 'Migration plan'] }; return [...base, ...(specific[taskType.primary] || [])]; } function generateSuccessCriteria(taskType) { return [ 'All tests pass', 'No regression in existing functionality', 'Code follows project standards', 'Changes are properly documented', 'Root cause addressed (not just symptoms)', 'Simpler alternatives considered' ]; } function generateMeasurableOutcomes(taskType) { const base = ['Task completed successfully', 'All acceptance criteria met']; const specific = { debugging: ['Issue resolved and verified', 'No recurrence of the problem'], implementation: ['Feature working as specified', 'User acceptance achieved'], performance: ['Measurable performance improvement', 'Metrics within targets'] }; return [...base, ...(specific[taskType.primary] || [])]; } //# sourceMappingURL=enhance.js.map