Skip to content

suggest-improvements

Access: /template suggest-improvements or /t suggest-improvements

Analyzes your MakerKit application and suggests improvements based on best practices, performance metrics, and user experience patterns.

What It Does

The suggest-improvements command helps you:

  • Analyze code quality and architecture
  • Identify optimization opportunities
  • Suggest UI/UX enhancements
  • Recommend security improvements
  • Propose scalability enhancements
  • Identify technical debt
  • Suggest new features based on usage

Usage

bash
/template suggest-improvements "Description"
# or
/t suggest-improvements "Description"

When prompted, specify:

  • Analysis focus areas
  • Business goals and priorities
  • Current pain points
  • Future scaling needs

Prerequisites

  • A working MakerKit application
  • Usage data (optional but helpful)
  • Commercial MakerKit license from MakerKit

What Gets Analyzed

1. Code Quality Analysis

typescript
// Analyze code quality metrics
async function analyzeCodeQuality() {
  const suggestions = [];
  
  // Check for code duplication
  const duplicates = await findDuplicateCode();
  if (duplicates.length > 0) {
    suggestions.push({
      category: 'Code Quality',
      priority: 'medium',
      title: 'Reduce Code Duplication',
      description: `Found ${duplicates.length} instances of duplicated code`,
      impact: 'Improved maintainability and reduced bugs',
      effort: 'medium',
      implementation: duplicates.map(d => ({
        files: d.files,
        suggestion: `Extract common logic into a shared utility or component`,
        example: generateRefactoringExample(d),
      })),
    });
  }
  
  // Check component complexity
  const complexComponents = await analyzeComponentComplexity();
  for (const component of complexComponents) {
    if (component.complexity > 15) {
      suggestions.push({
        category: 'Code Quality',
        priority: 'high',
        title: `Simplify ${component.name}`,
        description: 'Component is too complex',
        metrics: {
          currentComplexity: component.complexity,
          targetComplexity: 10,
          linesOfCode: component.loc,
        },
        impact: 'Better testability and maintainability',
        effort: 'medium',
        implementation: [
          'Break down into smaller components',
          'Extract complex logic into custom hooks',
          'Use composition instead of conditional rendering',
        ],
      });
    }
  }
  
  // Check for missing tests
  const coverage = await getTestCoverage();
  if (coverage.percentage < 70) {
    suggestions.push({
      category: 'Code Quality',
      priority: 'high',
      title: 'Improve Test Coverage',
      description: `Current coverage is ${coverage.percentage}%`,
      impact: 'Reduced bugs and regression prevention',
      effort: 'high',
      implementation: coverage.uncoveredFiles.map(file => ({
        file,
        suggestion: 'Add unit tests for critical paths',
        template: generateTestTemplate(file),
      })),
    });
  }
  
  return suggestions;
}

2. Performance Improvements

typescript
// Suggest performance optimizations
async function suggestPerformanceImprovements() {
  const suggestions = [];
  
  // Database query optimization
  const slowQueries = await identifySlowQueries();
  if (slowQueries.length > 0) {
    suggestions.push({
      category: 'Performance',
      priority: 'high',
      title: 'Optimize Database Queries',
      description: `${slowQueries.length} queries are running slowly`,
      impact: '50% faster page loads',
      effort: 'low',
      implementation: slowQueries.map(query => ({
        query: query.sql,
        currentTime: `${query.avgTime}ms`,
        suggestion: query.optimization,
        index: query.suggestedIndex,
      })),
    });
  }
  
  // Image optimization
  const unoptimizedImages = await findUnoptimizedImages();
  if (unoptimizedImages.length > 0) {
    const totalSavings = unoptimizedImages.reduce((acc, img) => acc + img.potentialSavings, 0);
    
    suggestions.push({
      category: 'Performance',
      priority: 'medium',
      title: 'Optimize Images',
      description: `Save ${formatBytes(totalSavings)} by optimizing images`,
      impact: 'Faster page loads, especially on mobile',
      effort: 'low',
      implementation: [
        {
          action: 'Convert images to WebP format',
          command: 'pnpm add -D @squoosh/lib && pnpm optimize:images',
          savings: '~60% file size reduction',
        },
        {
          action: 'Implement responsive images',
          example: `
<Image
  src="/hero.jpg"
  alt="Hero"
  sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
  priority
/>`,
        },
      ],
    });
  }
  
  // Bundle size optimization
  const bundleAnalysis = await analyzeBundleSize();
  const largePackages = bundleAnalysis.packages.filter(p => p.size > 100000);
  
  if (largePackages.length > 0) {
    suggestions.push({
      category: 'Performance',
      priority: 'medium',
      title: 'Reduce Bundle Size',
      description: 'Large packages are impacting load time',
      impact: '30% faster initial page load',
      effort: 'medium',
      implementation: largePackages.map(pkg => ({
        package: pkg.name,
        currentSize: formatBytes(pkg.size),
        alternatives: pkg.alternatives,
        lazyLoadExample: generateLazyLoadExample(pkg.name),
      })),
    });
  }
  
  return suggestions;
}

3. UI/UX Enhancements

typescript
// Suggest UI/UX improvements
async function suggestUIUXImprovements() {
  const suggestions = [];
  
  // Accessibility audit
  const a11yIssues = await runAccessibilityAudit();
  if (a11yIssues.length > 0) {
    suggestions.push({
      category: 'UI/UX',
      priority: 'high',
      title: 'Improve Accessibility',
      description: 'Make your app usable for everyone',
      impact: 'Better SEO and increased user base',
      effort: 'medium',
      implementation: a11yIssues.map(issue => ({
        component: issue.component,
        issue: issue.description,
        fix: issue.suggestedFix,
        wcagLevel: issue.wcagLevel,
      })),
    });
  }
  
  // Loading states
  const missingLoadingStates = await findMissingLoadingStates();
  if (missingLoadingStates.length > 0) {
    suggestions.push({
      category: 'UI/UX',
      priority: 'medium',
      title: 'Add Loading States',
      description: 'Improve perceived performance',
      impact: 'Better user experience during data fetching',
      effort: 'low',
      implementation: missingLoadingStates.map(component => ({
        component,
        suggestion: 'Add skeleton loader or spinner',
        example: `
export function ${component}Skeleton() {
  return (
    <div className="animate-pulse">
      <div className="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
      <div className="h-4 bg-gray-200 rounded w-1/2"></div>
    </div>
  );
}`,
      })),
    });
  }
  
  // Mobile responsiveness
  const responsiveIssues = await checkResponsiveness();
  if (responsiveIssues.length > 0) {
    suggestions.push({
      category: 'UI/UX',
      priority: 'high',
      title: 'Improve Mobile Experience',
      description: 'Ensure app works well on all devices',
      impact: '40% of users are on mobile',
      effort: 'medium',
      implementation: responsiveIssues.map(issue => ({
        component: issue.component,
        breakpoint: issue.breakpoint,
        issue: issue.description,
        fix: issue.suggestedCSS,
      })),
    });
  }
  
  // Dark mode
  const hasDarkMode = await checkDarkModeSupport();
  if (!hasDarkMode) {
    suggestions.push({
      category: 'UI/UX',
      priority: 'low',
      title: 'Add Dark Mode Support',
      description: 'Reduce eye strain and save battery',
      impact: 'Improved user satisfaction',
      effort: 'medium',
      implementation: [
        {
          step: 'Configure Tailwind CSS',
          code: `// tailwind.config.js
darkMode: 'class',`,
        },
        {
          step: 'Add theme provider',
          code: `// components/theme-provider.tsx
export function ThemeProvider({ children }) {
  return (
    <NextThemesProvider
      attribute="class"
      defaultTheme="system"
      enableSystem
    >
      {children}
    </NextThemesProvider>
  );
}`,
        },
        {
          step: 'Add theme toggle',
          component: 'ThemeToggle',
        },
      ],
    });
  }
  
  return suggestions;
}

4. Security Enhancements

typescript
// Suggest security improvements
async function suggestSecurityEnhancements() {
  const suggestions = [];
  
  // API rate limiting
  const hasRateLimiting = await checkRateLimiting();
  if (!hasRateLimiting) {
    suggestions.push({
      category: 'Security',
      priority: 'high',
      title: 'Implement API Rate Limiting',
      description: 'Prevent abuse and ensure fair usage',
      impact: 'Protection against DDoS and API abuse',
      effort: 'low',
      implementation: [
        {
          step: 'Install Upstash rate limiter',
          command: 'pnpm add @upstash/ratelimit @upstash/redis',
        },
        {
          step: 'Add middleware',
          code: `// middleware.ts
const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.slidingWindow(10, "10 s"),
});

export async function middleware(request: NextRequest) {
  const ip = request.ip ?? "127.0.0.1";
  const { success } = await ratelimit.limit(ip);
  
  if (!success) {
    return new NextResponse("Too Many Requests", { status: 429 });
  }
}`,
        },
      ],
    });
  }
  
  // Input sanitization
  const unsanitizedInputs = await findUnsanitizedInputs();
  if (unsanitizedInputs.length > 0) {
    suggestions.push({
      category: 'Security',
      priority: 'critical',
      title: 'Sanitize User Inputs',
      description: 'Prevent XSS and injection attacks',
      impact: 'Critical security improvement',
      effort: 'medium',
      implementation: unsanitizedInputs.map(input => ({
        file: input.file,
        line: input.line,
        current: input.code,
        fixed: input.sanitizedVersion,
      })),
    });
  }
  
  // Content Security Policy
  const hasCSP = await checkCSPHeader();
  if (!hasCSP) {
    suggestions.push({
      category: 'Security',
      priority: 'medium',
      title: 'Add Content Security Policy',
      description: 'Prevent XSS and data injection attacks',
      impact: 'Enhanced security posture',
      effort: 'low',
      implementation: [
        {
          step: 'Add CSP header',
          file: 'next.config.js',
          code: generateCSPConfig(),
        },
      ],
    });
  }
  
  return suggestions;
}

5. Scalability Suggestions

typescript
// Suggest scalability improvements
async function suggestScalabilityImprovements() {
  const suggestions = [];
  
  // Database connection pooling
  const connectionUsage = await analyzeDBConnections();
  if (connectionUsage.peakConnections > connectionUsage.maxConnections * 0.8) {
    suggestions.push({
      category: 'Scalability',
      priority: 'high',
      title: 'Implement Connection Pooling',
      description: 'Database connections are near capacity',
      impact: 'Support 10x more concurrent users',
      effort: 'low',
      implementation: [
        {
          step: 'Configure PgBouncer',
          config: generatePgBouncerConfig(),
        },
        {
          step: 'Update connection string',
          change: 'Point to PgBouncer instead of direct DB',
        },
      ],
    });
  }
  
  // Caching strategy
  const cacheableQueries = await identifyCacheableQueries();
  if (cacheableQueries.length > 5) {
    suggestions.push({
      category: 'Scalability',
      priority: 'medium',
      title: 'Implement Redis Caching',
      description: 'Cache frequently accessed data',
      impact: '80% reduction in database load',
      effort: 'medium',
      implementation: [
        {
          step: 'Add Redis client',
          command: 'pnpm add @upstash/redis',
        },
        {
          step: 'Implement caching layer',
          example: generateCachingExample(cacheableQueries[0]),
        },
        {
          step: 'Cache invalidation strategy',
          pattern: 'Use tags for granular invalidation',
        },
      ],
    });
  }
  
  // Background job processing
  const longRunningTasks = await findLongRunningTasks();
  if (longRunningTasks.length > 0) {
    suggestions.push({
      category: 'Scalability',
      priority: 'medium',
      title: 'Move Tasks to Background Jobs',
      description: 'Improve API response times',
      impact: 'Better user experience and scalability',
      effort: 'high',
      implementation: [
        {
          step: 'Set up BullMQ',
          command: 'pnpm add bullmq',
        },
        {
          step: 'Create job processors',
          tasks: longRunningTasks.map(task => ({
            current: task.name,
            jobName: `process${task.name}`,
            estimatedTime: task.avgDuration,
          })),
        },
      ],
    });
  }
  
  return suggestions;
}

6. Feature Suggestions

typescript
// Suggest new features based on usage
async function suggestNewFeatures() {
  const suggestions = [];
  const usage = await analyzeUsagePatterns();
  
  // Team collaboration features
  if (usage.avgTeamSize > 3 && !await hasFeature('realtime-collaboration')) {
    suggestions.push({
      category: 'Features',
      priority: 'medium',
      title: 'Add Real-time Collaboration',
      description: 'Teams are actively working together',
      impact: 'Improved team productivity',
      effort: 'high',
      implementation: [
        {
          step: 'Implement presence system',
          tech: 'Supabase Realtime',
          example: generatePresenceExample(),
        },
        {
          step: 'Add collaborative editing',
          library: 'Yjs or Liveblocks',
        },
        {
          step: 'Show active users',
          component: 'ActiveUsersIndicator',
        },
      ],
    });
  }
  
  // Advanced search
  if (usage.searchQueries > 1000 && !await hasFeature('advanced-search')) {
    suggestions.push({
      category: 'Features',
      priority: 'high',
      title: 'Implement Advanced Search',
      description: 'Users are actively searching',
      impact: 'Better content discovery',
      effort: 'medium',
      implementation: [
        {
          step: 'Add full-text search',
          sql: 'CREATE EXTENSION IF NOT EXISTS pg_trgm;',
        },
        {
          step: 'Implement filters',
          component: 'SearchFilters',
        },
        {
          step: 'Add search analytics',
          purpose: 'Understand what users are looking for',
        },
      ],
    });
  }
  
  // API for integrations
  if (usage.powerUsers > 10 && !await hasFeature('public-api')) {
    suggestions.push({
      category: 'Features',
      priority: 'low',
      title: 'Build Public API',
      description: 'Power users need programmatic access',
      impact: 'Enable integrations and automation',
      effort: 'high',
      implementation: [
        {
          step: 'Design RESTful API',
          docs: 'Use OpenAPI specification',
        },
        {
          step: 'Implement API keys',
          security: 'Rotate keys, set expiration',
        },
        {
          step: 'Add rate limiting',
          tiers: 'Different limits per plan',
        },
        {
          step: 'Generate SDK',
          tools: 'openapi-generator',
        },
      ],
    });
  }
  
  return suggestions;
}

7. Technical Debt

typescript
// Identify and prioritize technical debt
async function analyzeTechnicalDebt() {
  const suggestions = [];
  
  // Outdated dependencies
  const outdated = await getOutdatedDependencies();
  const critical = outdated.filter(dep => dep.severity === 'critical');
  
  if (critical.length > 0) {
    suggestions.push({
      category: 'Technical Debt',
      priority: 'critical',
      title: 'Update Critical Dependencies',
      description: 'Security vulnerabilities in dependencies',
      impact: 'Prevent security breaches',
      effort: 'medium',
      implementation: critical.map(dep => ({
        package: dep.name,
        current: dep.current,
        latest: dep.latest,
        breaking: dep.breaking,
        migration: dep.migrationGuide,
      })),
    });
  }
  
  // Code that needs refactoring
  const codeSmells = await detectCodeSmells();
  if (codeSmells.length > 0) {
    suggestions.push({
      category: 'Technical Debt',
      priority: 'low',
      title: 'Refactor Problem Areas',
      description: 'Improve code maintainability',
      impact: 'Easier feature development',
      effort: 'medium',
      implementation: codeSmells.map(smell => ({
        file: smell.file,
        issue: smell.type,
        complexity: smell.complexity,
        suggestion: smell.refactoringSuggestion,
      })),
    });
  }
  
  return suggestions;
}

8. Generate Improvement Report

typescript
// Generate comprehensive improvement report
export async function generateImprovementReport() {
  console.log('🔍 Analyzing your MakerKit application...\n');
  
  const allSuggestions = [];
  
  // Run all analyses
  const analyses = [
    { name: 'Code Quality', fn: analyzeCodeQuality },
    { name: 'Performance', fn: suggestPerformanceImprovements },
    { name: 'UI/UX', fn: suggestUIUXImprovements },
    { name: 'Security', fn: suggestSecurityEnhancements },
    { name: 'Scalability', fn: suggestScalabilityImprovements },
    { name: 'Features', fn: suggestNewFeatures },
    { name: 'Technical Debt', fn: analyzeTechnicalDebt },
  ];
  
  for (const analysis of analyses) {
    console.log(`Analyzing ${analysis.name}...`);
    const suggestions = await analysis.fn();
    allSuggestions.push(...suggestions);
  }
  
  // Sort by priority and effort
  const prioritized = prioritizeSuggestions(allSuggestions);
  
  // Generate report
  const report = {
    generated: new Date().toISOString(),
    summary: {
      total: allSuggestions.length,
      critical: allSuggestions.filter(s => s.priority === 'critical').length,
      high: allSuggestions.filter(s => s.priority === 'high').length,
      medium: allSuggestions.filter(s => s.priority === 'medium').length,
      low: allSuggestions.filter(s => s.priority === 'low').length,
    },
    quickWins: prioritized.filter(s => s.effort === 'low' && s.priority !== 'low'),
    roadmap: generateRoadmap(prioritized),
    suggestions: prioritized,
  };
  
  // Save reports
  const markdown = generateImprovementMarkdown(report);
  await fs.writeFile('improvement-report.md', markdown);
  
  const html = generateImprovementHTML(report);
  await fs.writeFile('improvement-report.html', html);
  
  console.log('\n📊 Analysis Complete!');
  console.log(`Found ${report.summary.total} improvement opportunities`);
  console.log(`Quick wins: ${report.quickWins.length}`);
  console.log('\n📄 Reports saved: improvement-report.md, improvement-report.html');
  
  return report;
}

function prioritizeSuggestions(suggestions) {
  // Score based on impact/effort ratio
  return suggestions
    .map(s => ({
      ...s,
      score: calculateScore(s),
    }))
    .sort((a, b) => b.score - a.score);
}

function generateRoadmap(suggestions) {
  return {
    immediate: suggestions.filter(s => s.priority === 'critical'),
    shortTerm: suggestions.filter(s => s.priority === 'high' && s.effort !== 'high'),
    mediumTerm: suggestions.filter(s => s.priority === 'medium' || s.effort === 'high'),
    longTerm: suggestions.filter(s => s.priority === 'low'),
  };
}

Implementation Tracking

Track improvement implementation:

typescript
// Track which improvements have been implemented
export async function trackImprovements() {
  const implemented = await getImplementedImprovements();
  const pending = await getPendingImprovements();
  
  console.log('📈 Improvement Progress:');
  console.log(`Implemented: ${implemented.length}`);
  console.log(`In Progress: ${pending.filter(p => p.status === 'in-progress').length}`);
  console.log(`Pending: ${pending.filter(p => p.status === 'pending').length}`);
}

License Requirement

Important: This command requires a commercial MakerKit license from https://makerkit.dev?atp=MqaGgc MakerKit is a premium SaaS starter kit and requires proper licensing for commercial use.

Built with ❤️ for the AI Coding community, by Praney Behl