React nextjs development

From paulpas/agent-skill-router · View interactive version

React nextjs development is an AI agent skill from the GitHub repository paulpas/agent-skill-router. Implements intelligent react nextjs development with multi-factor skill selection, fallback chains, and adherence to the 5 Laws of Elegant Defense

How to use this skill

Skill file

React Nextjs Development

Orchestrates intelligent skill selection and execution for react nextjs development workflows. Applies the 5 Laws of Elegant Defense to guide data naturally through the orchestration pipeline, preventing errors before they occur. Selects optimal skills based on multi-factor scoring including text similarity, historical performance, and system availability.

TL;DR Checklist

┌───────────────────────────────────────────────────────────────────────────────┐

│ Orchestration Flow │

└───────────────────────────────────────────────────────────────────────────────┘

User Request

↓

┌─────────────────┐

│ Parse Request │

│ & Extract │

│ Features │

└────────┬────────┘

↓

┌─────────────────────────────────────────────────────────────────────┐

│ Evaluate Available Skills │

│ │

│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │

│ │ Skill A │ │ Skill B │ │ Skill C │ │

│ │ - Match Score│ │ - Match Score│ │ - Match Score│ │

│ │ - Confidence │ │ - Confidence │ │ - Confidence │ │

│ │ - History │ │ - History │ │ - History │ │

│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │

│ │ │ │ │

│ └─────────────────┴─────────────────┘ │

│ ↓ │

│ Select Best Skill │

└─────────────────────────────────────────────────────────────────────┘

↓

┌─────────────────┐

│ Execute Skill │

└────────┬────────┘

↓

┌─────────────────┐

│ Handle Result │

└────────┬────────┘

↓

┌─────────────────────────────────────────────────────────────────────┐

│ Error Handling & Fallback │

│ │

│ Success? ────────► Return Result │

│ │

│ Fail? ────────┐ │

│ ↓ │

│ ┌──────────────────────────────────────────────────────────┐ │

│ │ Fallback Chain │ │

│ │ │ │

│ │ 1. Retry with adjusted parameters │ │

│ │ 2. Try Alternative Skill (if available) │ │

│ │ 3. Defer to Human Operator (if critical) │ │

│ │ 4. Log & Return Error │ │

│ └──────────────────────────────────────────────────────────┘ │

└─────────────────────────────────────────────────────────────────────┘

When to Use

Use this skill when:

When NOT to Use

Avoid this skill for:

Core Workflow

  1. Parse and Analyze Request - Extract intent, entities, and constraints from user input.

Checkpoint: All required parameters must be present and in valid format before proceeding.

  1. Score Available Skills - Calculate match scores using multi-factor algorithm:

Checkpoint: Skip to fallback if no skill scores above threshold.

  1. Select Optimal Skill - Choose skill with highest score that meets minimum confidence.

Checkpoint: Verify skill has not been disabled or deprecated.

  1. Execute with Fallback - Run skill execution wrapped in retry and fallback logic.

Checkpoint: Log all execution attempts for audit trail.

  1. Return or Fallback - Either return successful result or apply fallback chain:

Checkpoint: Record outcome with timing and confidence metadata.

Implementation Patterns

Pattern 1: Skill Selection Logic

import { readFileSync, existsSync } from 'fs';
import { join } from 'path';

interface NextProjectState {
  framework: 'app' | 'pages';
  hasTailwind: boolean;
  hasEslint: boolean;
  hasTypeScript: boolean;
  nodeVersion: string;
}

interface TaskSelection {
  command: string;
  args: string[];
  confidence: number;
  fallbackCommand?: string;
}

/**
 * Analyzes Next.js project structure and selects optimal development task.
 * Implements multi-factor scoring: framework type, dependency presence, user intent.
 */
export function selectNextTask(
  projectRoot: string,
  userIntent: string,
  availableTasks: string[]
): TaskSelection {
  // Guard clause - Early Exit (Law 1)
  if (!projectRoot || !existsSync(projectRoot)) {
    throw new Error(`Project root not found: ${projectRoot}`);
  }

  // Parse project state - Make Illegal States Unrepresentable (Law 2)
  const pkg = JSON.parse(readFileSync(join(projectRoot, 'package.json'), 'utf-8'));
  const hasAppRouter = existsSync(join(projectRoot, 'app'));
  const hasPagesRouter = existsSync(join(projectRoot, 'pages'));
  const framework = hasAppRouter ? 'app' : hasPagesRouter ? 'pages' : 'unknown';

  const score = (task: string): number => {
    let match = 0;
    if (task === 'dev' && userIntent.includes('run') && framework !== 'unknown') match += 0.8;
    if (task === 'build' && userIntent.includes('prod') && framework !== 'unknown') match += 0.9;
    if (task === 'lint' && userIntent.includes('check') && pkg.devDependencies?.eslint) match += 0.7;
    if (task === 'typecheck' && pkg.devDependencies?.typescript) match += 0.6;
    return match;
  };

  let bestTask = 'dev';
  let bestScore = 0;

  for (const task of availableTasks) {
    const s = score(task);
    if (s > bestScore) {
      bestScore = s;
      bestTask = task;
    }
  }

  // Atomic Predictability (Law 3) - Return new structure
  return {
    command: 'next',
    args: [bestTask],
    confidence: bestScore,
    fallbackCommand: bestTask === 'build' ? 'dev' : undefined
  };
}

Pattern 2: Execution with Fallback

import { execSync } from 'child_process';
import { join } from 'path';

interface ExecutionResult {
  success: boolean;
  output: string;
  attempts: number;
  latencyMs: number;
  fallbackUsed?: boolean;
}

/**
 * Executes Next.js task with resilient fallback chain.
 * Implements Fail Fast, Fail Loud (Law 4) for build/runtime errors.
 */
export function executeNextTask(
  taskConfig: TaskSelection,
  projectRoot: string,
  maxRetries: number = 2
): ExecutionResult {
  const startTime = Date.now();
  let lastError: Error | null = null;

  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      // Parse context - Ensure trusted state (Law 2)
      const env = { ...process.env, NODE_ENV: taskConfig.command === 'build' ? 'production' : 'development' };
      
      // Execute domain-specific command
      const output = execSync(`cd "${projectRoot}" && npx next ${taskConfig.args.join(' ')}`, {
        env,
        stdio: 'pipe',
        timeout: 300000
      }).toString();

      return {
        success: true,
        output,
        attempts: attempt + 1,
        latencyMs: Date.now() - startTime
      };
    } catch (err: any) {
      lastError = err;
      // Fail Fast - Don't patch bad build state (Law 4)
      if (err.message?.includes('ENOENT') || err.message?.includes('EACCES')) {
        throw new Error(`Critical system error: ${err.message}`);
      }
      
      // Transient error - apply fallback chain
      if (attempt === maxRetries && taskConfig.fallbackCommand) {
        console.warn(`Fallback triggered: switching to ${taskConfig.fallbackCommand}`);
        return executeNextTask({
          ...taskConfig,
          command: taskConfig.fallbackCommand,
          args: [],
          confidence: taskConfig.confidence * 0.8
        }, projectRoot, 0);
      }
    }
  }

  // All retries exhausted - Fail Loud (Law 4)
  throw new Error(`Next.js task failed after ${maxRetries + 1} attempts: ${lastError?.message}`);
}

MUST DO

MUST NOT DO

TL;DR Checklist

TL;DR for Code Generation

Output Template

When applying this skill, produce:

  1. Selected Skills - List of skill names with confidence scores
  2. Selection Rationale - Why each skill was chosen (match score, history, availability)
  3. Execution Plan - Order of execution with dependencies
  4. Fallback Strategy - Which fallback skills will be tried and in what order
  5. Risk Assessment - Any potential failure points and their impact
  6. Timing Estimates - Expected latency including fallback scenarios

Related Skills

| Skill | Purpose |

|---|---|

| typescript-typing-system | Provides TypeScript patterns for React components and Next.js API routes |

| frontend-architecture-patterns | Covers frontend architectural patterns that complement Next.js project structure |


Constraints

MUST DO

MUST NOT DO

Live References

Authoritative documentation links for this domain. The model follows markdown links at load time to resolve external references and inline content.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.