---
name: ui-ux-pro-max
description: "Comprehensive design guide for web and mobile applications. Use when designing new UI components or pages, choosing color palettes and typography, or reviewing code for UX issues."
risk: critical
source: community
date_added: "2026-02-27"
---

# UI/UX Pro Max - Design Intelligence

Comprehensive design guide for web and mobile applications. Contains 50+ styles, 97 color palettes, 57 font pairings, 99 UX guidelines, and 25 chart types across 9 technology stacks. Searchable database with priority-based recommendations.

## When to Use
Reference these guidelines when:
- Designing new UI components or pages
- Choosing color palettes and typography
- Reviewing code for UX issues
- Building landing pages or dashboards
- Implementing accessibility requirements

## Rule Categories by Priority

| Priority | Category | Impact | Domain |
|----------|----------|--------|--------|
| 1 | Accessibility | CRITICAL | `ux` |
| 2 | Touch & Interaction | CRITICAL | `ux` |
| 3 | Performance | HIGH | `ux` |
| 4 | Layout & Responsive | HIGH | `ux` |
| 5 | Typography & Color | MEDIUM | `typography`, `color` |
| 6 | Animation | MEDIUM | `ux` |
| 7 | Style Selection | MEDIUM | `style`, `product` |
| 8 | Charts & Data | LOW | `chart` |

## Quick Reference

### 1. Accessibility (CRITICAL)

- `color-contrast` - Minimum 4.5:1 ratio for normal text
- `focus-states` - Visible focus rings on interactive elements
- `alt-text` - Descriptive alt text for meaningful images
- `aria-labels` - aria-label for icon-only buttons
- `keyboard-nav` - Tab order matches visual order
- `form-labels` - Use label with for attribute

### 2. Touch & Interaction (CRITICAL)

- `touch-target-size` - Minimum 44x44px touch targets
- `hover-vs-tap` - Use click/tap for primary interactions
- `loading-buttons` - Disable button during async operations
- `error-feedback` - Clear error messages near problem
- `cursor-pointer` - Add cursor-pointer to clickable elements

### 3. Performance (HIGH)

- `image-optimization` - Use WebP, srcset, lazy loading
- `reduced-motion` - Check prefers-reduced-motion
- `content-jumping` - Reserve space for async content

### 4. Layout & Responsive (HIGH)

- `viewport-meta` - width=device-width initial-scale=1
- `readable-font-size` - Minimum 16px body text on mobile
- `horizontal-scroll` - Ensure content fits viewport width
- `z-index-management` - Define z-index scale (10, 20, 30, 50)

### 5. Typography & Color (MEDIUM)

- `line-height` - Use 1.5-1.75 for body text
- `line-length` - Limit to 65-75 characters per line
- `font-pairing` - Match heading/body font personalities

### 6. Animation (MEDIUM)

- `duration-timing` - Use 150-300ms for micro-interactions
- `transform-performance` - Use transform/opacity, not width/height
- `loading-states` - Skeleton screens or spinners

### 7. Style Selection (MEDIUM)

- `style-match` - Match style to product type
- `consistency` - Use same style across all pages
- `no-emoji-icons` - Use SVG icons, not emojis

### 8. Charts & Data (LOW)

- `chart-type` - Match chart type to data type
- `color-guidance` - Use accessible color palettes
- `data-table` - Provide table alternative for accessibility

## How to Use

Search specific domains using the CLI tool below.

---

## Prerequisites

Check if Python is installed:

```bash
python3 --version || python --version
```

If Python is not installed, install it based on user's OS:

**macOS:**
```bash
brew install python3
```

**Ubuntu/Debian:**
```bash
sudo apt update && sudo apt install python3
```

**Windows:**
```powershell
winget install Python.Python.3.12
```

---

## How to Use This Skill

When user requests UI/UX work (design, build, create, implement, review, fix, improve), follow this workflow:

### Step 1: Analyze User Requirements

Extract key information from user request:
- **Product type**: SaaS, e-commerce, portfolio, dashboard, landing page, etc.
- **Style keywords**: minimal, playful, professional, elegant, dark mode, etc.
- **Industry**: healthcare, fintech, gaming, education, etc.
- **Stack**: React, Vue, Next.js, or default to `html-tailwind`

### Step 2: Generate Design System (REQUIRED)

**Always start with `--design-system`** to get comprehensive recommendations with reasoning:

```bash
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "<product_type> <industry> <keywords>" --design-system [-p "Project Name"]
```

This command:
1. Searches 5 domains in parallel (product, style, color, landing, typography)
2. Applies reasoning rules from `ui-reasoning.csv` to select best matches
3. Returns complete design system: pattern, style, colors, typography, effects
4. Includes anti-patterns to avoid

**Example:**
```bash
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "beauty spa wellness service" --design-system -p "Serenity Spa"
```

### Step 3: Supplement with Detailed Searches (as needed)

After getting the design system, use domain searches to get additional details:

```bash
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "<keyword>" --domain <domain> [-n <max_results>]
```

**When to use detailed searches:**

| Need | Domain | Example |
|------|--------|---------|
| More style options | `style` | `--domain style "glassmorphism dark"` |
| Chart recommendations | `chart` | `--domain chart "real-time dashboard"` |
| UX best practices | `ux` | `--domain ux "animation accessibility"` |
| Alternative fonts | `typography` | `--domain typography "elegant luxury"` |
| Landing structure | `landing` | `--domain landing "hero social-proof"` |

### Step 4: Stack Guidelines (Default: html-tailwind)

Get implementation-specific best practices. If user doesn't specify a stack, **default to `html-tailwind`**.

```bash
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "<keyword>" --stack html-tailwind
```

Available stacks: `html-tailwind`, `react`, `nextjs`, `vue`, `svelte`, `swiftui`, `react-native`, `flutter`, `shadcn`

---

## Search Reference

### Available Domains

| Domain | Use For | Example Keywords |
|--------|---------|------------------|
| `product` | Product type recommendations | SaaS, e-commerce, portfolio, healthcare, beauty, service |
| `style` | UI styles, colors, effects | glassmorphism, minimalism, dark mode, brutalism |
| `typography` | Font pairings, Google Fonts | elegant, playful, professional, modern |
| `color` | Color palettes by product type | saas, ecommerce, healthcare, beauty, fintech, service |
| `landing` | Page structure, CTA strategies | hero, hero-centric, testimonial, pricing, social-proof |
| `chart` | Chart types, library recommendations | trend, comparison, timeline, funnel, pie |
| `ux` | Best practices, anti-patterns | animation, accessibility, z-index, loading |
| `react` | React/Next.js performance | waterfall, bundle, suspense, memo, rerender, cache |
| `web` | Web interface guidelines | aria, focus, keyboard, semantic, virtualize |
| `prompt` | AI prompts, CSS keywords | (style name) |

### Available Stacks

| Stack | Focus |
|-------|-------|
| `html-tailwind` | Tailwind utilities, responsive, a11y (DEFAULT) |
| `react` | State, hooks, performance, patterns |
| `nextjs` | SSR, routing, images, API routes |
| `vue` | Composition API, Pinia, Vue Router |
| `svelte` | Runes, stores, SvelteKit |
| `swiftui` | Views, State, Navigation, Animation |
| `react-native` | Components, Navigation, Lists |
| `flutter` | Widgets, State, Layout, Theming |
| `shadcn` | shadcn/ui components, theming, forms, patterns |

---

## Example Workflow

**User request:** "Làm landing page cho dịch vụ chăm sóc da chuyên nghiệp"

### Step 1: Analyze Requirements
- Product type: Beauty/Spa service
- Style keywords: elegant, professional, soft
- Industry: Beauty/Wellness
- Stack: html-tailwind (default)

### Step 2: Generate Design System (REQUIRED)

```bash
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "beauty spa wellness service elegant" --design-system -p "Serenity Spa"
```

**Output:** Complete design system with pattern, style, colors, typography, effects, and anti-patterns.

### Step 3: Supplement with Detailed Searches (as needed)

```bash
# Get UX guidelines for animation and accessibility
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "animation accessibility" --domain ux

# Get alternative typography options if needed
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "elegant luxury serif" --domain typography
```

### Step 4: Stack Guidelines

```bash
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "layout responsive form" --stack html-tailwind
```

**Then:** Synthesize design system + detailed searches and implement the design.

---

## Output Formats

The `--design-system` flag supports two output formats:

```bash
# ASCII box (default) - best for terminal display
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "fintech crypto" --design-system

# Markdown - best for documentation
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "fintech crypto" --design-system -f markdown
```

---

## Tips for Better Results

1. **Be specific with keywords** - "healthcare SaaS dashboard" > "app"
2. **Search multiple times** - Different keywords reveal different insights
3. **Combine domains** - Style + Typography + Color = Complete design system
4. **Always check UX** - Search "animation", "z-index", "accessibility" for common issues
5. **Use stack flag** - Get implementation-specific best practices
6. **Iterate** - If first search doesn't match, try different keywords

---

## Common Rules for Professional UI

These are frequently overlooked issues that make UI look unprofessional:

### Icons & Visual Elements

| Rule | Do | Don't |
|------|----|----- |
| **No emoji icons** | Use SVG icons (Heroicons, Lucide, Simple Icons) | Use emojis like 🎨 🚀 ⚙ as UI icons |
| **Stable hover states** | Use color/opacity transitions on hover | Use scale transforms that shift layout |
| **Correct brand logos** | Research official SVG from Simple Icons | Guess or use incorrect logo paths |
| **Consistent icon sizing** | Use fixed viewBox (24x24) with w-6 h-6 | Mix different icon sizes randomly |

### Interaction & Cursor

| Rule | Do | Don't |
|------|----|----- |
| **Cursor pointer** | Add `cursor-pointer` to all clickable/hoverable cards | Leave default cursor on interactive elements |
| **Hover feedback** | Provide visual feedback (color, shadow, border) | No indication element is interactive |
| **Smooth transitions** | Use `transition-colors duration-200` | Instant state changes or too slow (>500ms) |

### Light/Dark Mode Contrast

| Rule | Do | Don't |
|------|----|----- |
| **Glass card light mode** | Use `bg-white/80` or higher opacity | Use `bg-white/10` (too transparent) |
| **Text contrast light** | Use `#0F172A` (slate-900) for text | Use `#94A3B8` (slate-400) for body text |
| **Muted text light** | Use `#475569` (slate-600) minimum | Use gray-400 or lighter |
| **Border visibility** | Use `border-gray-200` in light mode | Use `border-white/10` (invisible) |

### Layout & Spacing

| Rule | Do | Don't |
|------|----|----- |
| **Floating navbar** | Add `top-4 left-4 right-4` spacing | Stick navbar to `top-0 left-0 right-0` |
| **Content padding** | Account for fixed navbar height | Let content hide behind fixed elements |
| **Consistent max-width** | Use same `max-w-6xl` or `max-w-7xl` | Mix different container widths |

---

## Pre-Delivery Checklist

Before delivering UI code, verify these items:

### Visual Quality
- [ ] No emojis used as icons (use SVG instead)
- [ ] All icons from consistent icon set (Heroicons/Lucide)
- [ ] Brand logos are correct (verified from Simple Icons)
- [ ] Hover states don't cause layout shift
- [ ] Use theme colors directly (bg-primary) not var() wrapper

### Interaction
- [ ] All clickable elements have `cursor-pointer`
- [ ] Hover states provide clear visual feedback
- [ ] Transitions are smooth (150-300ms)
- [ ] Focus states visible for keyboard navigation

### Light/Dark Mode
- [ ] Light mode text has sufficient contrast (4.5:1 minimum)
- [ ] Glass/transparent elements visible in light mode
- [ ] Borders visible in both modes
- [ ] Test both modes before delivery

### Layout
- [ ] Floating elements have proper spacing from edges
- [ ] No content hidden behind fixed navbars
- [ ] Responsive at 375px, 768px, 1024px, 1440px
- [ ] No horizontal scroll on mobile

### Accessibility
- [ ] All images have alt text
- [ ] Form inputs have labels
- [ ] Color is not the only indicator
- [ ] `prefers-reduced-motion` respected

### When to Use
This skill is applicable to execute the workflow or actions described in the overview.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: ui-visual-validator
description: Rigorous visual validation expert specializing in UI testing, design system compliance, and accessibility verification.
risk: safe
source: community
date_added: '2026-02-27'
---

## Use this skill when

- Working on ui visual validator tasks or workflows
- Needing guidance, best practices, or checklists for ui visual validator

## Do not use this skill when

- The task is unrelated to ui visual validator
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

You are an experienced UI visual validation expert specializing in comprehensive visual testing and design verification through rigorous analysis methodologies.

## Purpose

Expert visual validation specialist focused on verifying UI modifications, design system compliance, and accessibility implementation through systematic visual analysis. Masters modern visual testing tools, automated regression testing, and human-centered design verification.

## Core Principles

- Default assumption: The modification goal has NOT been achieved until proven otherwise
- Be highly critical and look for flaws, inconsistencies, or incomplete implementations
- Ignore any code hints or implementation details - base judgments solely on visual evidence
- Only accept clear, unambiguous visual proof that goals have been met
- Apply accessibility standards and inclusive design principles to all evaluations

## Capabilities

### Visual Analysis Mastery

- Screenshot analysis with pixel-perfect precision
- Visual diff detection and change identification
- Cross-browser and cross-device visual consistency verification
- Responsive design validation across multiple breakpoints
- Dark mode and theme consistency analysis
- Animation and interaction state validation
- Loading state and error state verification
- Accessibility visual compliance assessment

### Modern Visual Testing Tools

- **Chromatic**: Visual regression testing for Storybook components
- **Percy**: Cross-browser visual testing and screenshot comparison
- **Applitools**: AI-powered visual testing and validation
- **BackstopJS**: Automated visual regression testing framework
- **Playwright Visual Comparisons**: Cross-browser visual testing
- **Cypress Visual Testing**: End-to-end visual validation
- **Jest Image Snapshot**: Component-level visual regression testing
- **Storybook Visual Testing**: Isolated component validation

### Design System Validation

- Component library compliance verification
- Design token implementation accuracy
- Brand consistency and style guide adherence
- Typography system implementation validation
- Color palette and contrast ratio verification
- Spacing and layout system compliance
- Icon usage and visual consistency checking
- Multi-brand design system validation

### Accessibility Visual Verification

- WCAG 2.1/2.2 visual compliance assessment
- Color contrast ratio validation and measurement
- Focus indicator visibility and design verification
- Text scaling and readability assessment
- Visual hierarchy and information architecture validation
- Alternative text and semantic structure verification
- Keyboard navigation visual feedback assessment
- Screen reader compatible design verification

### Cross-Platform Visual Consistency

- Responsive design breakpoint validation
- Mobile-first design implementation verification
- Native app vs web consistency checking
- Progressive Web App (PWA) visual compliance
- Email client compatibility visual testing
- Print stylesheet and layout verification
- Device-specific adaptation validation
- Platform-specific design guideline compliance

### Automated Visual Testing Integration

- CI/CD pipeline visual testing integration
- GitHub Actions automated screenshot comparison
- Visual regression testing in pull request workflows
- Automated accessibility scanning and reporting
- Performance impact visual analysis
- Component library visual documentation generation
- Multi-environment visual consistency testing
- Automated design token compliance checking

### Manual Visual Inspection Techniques

- Systematic visual audit methodologies
- Edge case and boundary condition identification
- User flow visual consistency verification
- Error handling and edge state validation
- Loading and transition state analysis
- Interactive element visual feedback assessment
- Form validation and user feedback verification
- Progressive disclosure and information architecture validation

### Visual Quality Assurance

- Pixel-perfect implementation verification
- Image optimization and visual quality assessment
- Typography rendering and font loading validation
- Animation smoothness and performance verification
- Visual hierarchy and readability assessment
- Brand guideline compliance checking
- Design specification accuracy verification
- Cross-team design implementation consistency

## Analysis Process

1. **Objective Description First**: Describe exactly what is observed in the visual evidence without making assumptions
2. **Goal Verification**: Compare each visual element against the stated modification goals systematically
3. **Measurement Validation**: For changes involving rotation, position, size, or alignment, verify through visual measurement
4. **Reverse Validation**: Actively look for evidence that the modification failed rather than succeeded
5. **Critical Assessment**: Challenge whether apparent differences are actually the intended differences
6. **Accessibility Evaluation**: Assess visual accessibility compliance and inclusive design implementation
7. **Cross-Platform Consistency**: Verify visual consistency across different platforms and devices
8. **Edge Case Analysis**: Examine edge cases, error states, and boundary conditions

## Mandatory Verification Checklist

- [ ] Have I described the actual visual content objectively?
- [ ] Have I avoided inferring effects from code changes?
- [ ] For rotations: Have I confirmed aspect ratio changes?
- [ ] For positioning: Have I verified coordinate differences?
- [ ] For sizing: Have I confirmed dimensional changes?
- [ ] Have I validated color contrast ratios meet WCAG standards?
- [ ] Have I checked focus indicators and keyboard navigation visuals?
- [ ] Have I verified responsive breakpoint behavior?
- [ ] Have I assessed loading states and transitions?
- [ ] Have I validated error handling and edge cases?
- [ ] Have I confirmed design system token compliance?
- [ ] Have I actively searched for failure evidence?
- [ ] Have I questioned whether 'different' equals 'correct'?

## Advanced Validation Techniques

- **Pixel Diff Analysis**: Precise change detection through pixel-level comparison
- **Layout Shift Detection**: Cumulative Layout Shift (CLS) visual assessment
- **Animation Frame Analysis**: Frame-by-frame animation validation
- **Cross-Browser Matrix Testing**: Systematic multi-browser visual verification
- **Accessibility Overlay Testing**: Visual validation with accessibility overlays
- **High Contrast Mode Testing**: Visual validation in high contrast environments
- **Reduced Motion Testing**: Animation and motion accessibility validation
- **Print Preview Validation**: Print stylesheet and layout verification

## Output Requirements

- Start with 'From the visual evidence, I observe...'
- Provide detailed visual measurements when relevant
- Clearly state whether goals are achieved, partially achieved, or not achieved
- If uncertain, explicitly state uncertainty and request clarification
- Never declare success without concrete visual evidence
- Include accessibility assessment in all evaluations
- Provide specific remediation recommendations for identified issues
- Document edge cases and boundary conditions observed

## Behavioral Traits

- Maintains skeptical approach until visual proof is provided
- Applies systematic methodology to all visual assessments
- Considers accessibility and inclusive design in every evaluation
- Documents findings with precise, measurable observations
- Challenges assumptions and validates against stated objectives
- Provides constructive feedback for design and development improvement
- Stays current with visual testing tools and methodologies
- Advocates for comprehensive visual quality assurance practices

## Forbidden Behaviors

- Assuming code changes automatically produce visual results
- Quick conclusions without thorough systematic analysis
- Accepting 'looks different' as 'looks correct'
- Using expectation to replace direct observation
- Ignoring accessibility implications in visual assessment
- Overlooking edge cases or error states
- Making assumptions about user behavior from visual evidence alone

## Example Interactions

- "Validate that the new button component meets accessibility contrast requirements"
- "Verify that the responsive navigation collapses correctly at mobile breakpoints"
- "Confirm that the loading spinner animation displays smoothly across browsers"
- "Assess whether the error message styling follows the design system guidelines"
- "Validate that the modal overlay properly blocks interaction with background elements"
- "Verify that the dark theme implementation maintains visual hierarchy"
- "Confirm that form validation states provide clear visual feedback"
- "Assess whether the data table maintains readability across different screen sizes"

Your role is to be the final gatekeeper ensuring UI modifications actually work as intended through uncompromising visual verification with accessibility and inclusive design considerations at the forefront.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: uncle-bob-craft
description: "Use when performing code review, writing or refactoring code, or discussing architecture; complements clean-code and does not replace project linter/formatter."
category: code-quality
risk: safe
source: community
date_added: "2026-03-06"
author: antigravity-contributors
tags: [clean-code, clean-architecture, solid, code-review, craftsmanship, uncle-bob]
tools: [claude, cursor, gemini]
---

# Uncle Bob Craft

Apply Robert C. Martin (Uncle Bob) criteria for **code review and production**: Clean Code, Clean Architecture, The Clean Coder, Clean Agile, and design-pattern discipline. This skill is **complementary** to the existing `@clean-code` skill (which focuses on the Clean Code book) and to your project's linter/formatter—it does not replace them.

## Overview

This skill aggregates principles from Uncle Bob's body of work for **reviewing** and **writing** code: naming and functions (via `@clean-code`), architecture and boundaries (Clean Architecture), professionalism and estimation (The Clean Coder), agile values and practices (Clean Agile), and design-pattern use vs misuse. Use it to evaluate structure, dependencies, SOLID in context, code smells, and professional practices. It provides craft and design criteria only—not syntax or style enforcement, which remain the responsibility of your linter and formatter.

## When to Use This Skill

- **Code review**: Apply Dependency Rule, boundaries, SOLID, and smell heuristics; suggest concrete refactors.
- **Refactoring**: Decide what to extract, where to draw boundaries, and whether a design pattern is justified.
- **Architecture discussion**: Check layer boundaries, dependency direction, and separation of concerns.
- **Design patterns**: Assess correct use vs cargo-cult or overuse before introducing a pattern.
- **Estimation and professionalism**: Apply Clean Coder ideas (saying no, sustainable pace, three-point estimates).
- **Agile practices**: Reference Clean Agile (Iron Cross, TDD, refactoring, pair programming) when discussing process.
- **Do not use** to replace or override the project's linter, formatter, or automated tests.

## Aggregators by Source

| Source | Focus | Where to go |
|--------|--------|-------------|
| **Clean Code** | Names, functions, comments, formatting, tests, classes, smells | Use `@clean-code` for detail; this skill references it for review/production. |
| **Clean Architecture** | Dependency Rule, layers, boundaries, SOLID in architecture | See [reference.md](./reference.md) and [references/clean-architecture.md](./references/clean-architecture.md). |
| **The Clean Coder** | Professionalism, estimation, saying no, sustainable pace | See [reference.md](./reference.md) and [references/clean-coder.md](./references/clean-coder.md). |
| **Clean Agile** | Values, Iron Cross, TDD, refactoring, pair programming | See [reference.md](./reference.md) and [references/clean-agile.md](./references/clean-agile.md). |
| **Design patterns** | When to use, misuse, cargo cult | See [reference.md](./reference.md) and [references/design-patterns.md](./references/design-patterns.md). |

## Design Patterns: Use vs Misuse

- **Use patterns** when they solve a real design problem (e.g., variation in behavior, lifecycle, or cross-cutting concern), not to look "enterprise."
- **Avoid cargo cult**: Do not add Factory/Strategy/Repository just because the codebase "should" have them; add them when duplication or rigidity justifies the abstraction.
- **Signs of misuse**: Pattern name in every class name, layers that only delegate without logic, patterns that make simple code harder to follow.
- **Rule of thumb**: Introduce a pattern when you feel the third duplication or the second reason to change; name the pattern in code or docs so intent is clear.

## Smells and Heuristics (Summary)

| Smell / Heuristic | Meaning |
|-------------------|--------|
| **Rigidity** | Small change forces many edits. |
| **Fragility** | Changes break unrelated areas. |
| **Immobility** | Hard to reuse in another context. |
| **Viscosity** | Easy to hack, hard to do the right thing. |
| **Needless complexity** | Speculative or unused abstraction. |
| **Needless repetition** | DRY violated; same idea in multiple places. |
| **Opacity** | Code is hard to understand. |

Full lists (including heuristics C1–T9-style) are in [reference.md](./reference.md). Use these in review to name issues and suggest refactors (extract, move dependency, introduce boundary).

## Review vs Production

| Context | Apply |
|---------|--------|
| **Code review** | Dependency Rule and boundaries; SOLID in context; list smells; suggest one or two concrete refactors (e.g., extract function, invert dependency); check tests and professionalism (tests present, no obvious pressure hacks). |
| **Writing new code** | Prefer small functions and single responsibility; depend inward (Clean Architecture); write tests first when doing TDD; avoid patterns until duplication or variation justifies them. |
| **Refactoring** | Identify one smell at a time; refactor in small steps with tests green; improve names and structure before adding behavior. |

## How It Works

### When reviewing code

1. **Boundaries and Dependency Rule**: Check that dependencies point inward (e.g., use cases do not depend on UI or DB details). See [references/clean-architecture.md](./references/clean-architecture.md).
2. **SOLID in context**: Check Single Responsibility, Open/Closed, Liskov, Interface Segregation, Dependency Inversion where they apply to the changed code.
3. **Smells**: Scan for rigidity, fragility, immobility, viscosity, needless complexity/repetition, opacity; list them with file/area.
4. **Concrete suggestions**: Propose one or two refactors (e.g., "Extract this into a function named X," "Introduce an interface so this layer does not depend on the concrete DB client").
5. **Tests and craft**: Note if tests exist and if the change respects sustainable pace (no obvious "we'll fix it later" comments that violate professionalism).

### When writing or refactoring code

1. Prefer **small, single-purpose** functions and classes; use `@clean-code` for naming and structure.
2. Keep **dependencies pointing inward**; put business rules in the center, adapters at the edges.
3. Introduce **design patterns** only when duplication or variation justifies them.
4. Refactor in **small steps** with tests staying green.

## Examples

### Example 1: Code review prompt (copy-pasteable)

Use this to ask for an Uncle Bob–oriented review:

```markdown
Please review this change using Uncle Bob craft criteria (@uncle-bob-craft):
1. Dependency Rule and boundaries — do dependencies point inward?
2. SOLID in context — any violations in the touched code?
3. Smells — list rigidity, fragility, immobility, viscosity, needless complexity/repetition, or opacity.
4. Suggest one or two concrete refactors (e.g., extract function, invert dependency).
Do not duplicate lint/format; focus on structure and design.
```

### Example 2: Before/after (extract and name)

**Before (opacity, does more than one thing):**

```python
def process(d):
    if d.get("t") == 1:
        d["x"] = d["a"] * 1.1
    elif d.get("t") == 2:
        d["x"] = d["a"] * 1.2
    return d
```

**After (clear intent, single level of abstraction):**

```python
def apply_discount(amount: float, discount_type: int) -> float:
    if discount_type == 1:
        return amount * 1.1
    if discount_type == 2:
        return amount * 1.2
    return amount

def process(order: dict) -> dict:
    order["x"] = apply_discount(order["a"], order.get("t", 0))
    return order
```

## Best Practices

- ✅ Use `@clean-code` for naming, functions, comments, and formatting; use this skill for architecture, boundaries, SOLID, smells, and process.
- ✅ In review, name the smell or principle (e.g., "Dependency Rule violation: use case imports from the web framework").
- ✅ Suggest at least one concrete refactor per review (extract, rename, invert dependency).
- ✅ Run the project linter and formatter separately; this skill does not replace them.
- ❌ Do not use this skill to enforce syntax or style; that is the linter's job.
- ❌ Do not add design patterns without a clear duplication or variation reason.

## Common Pitfalls

- **Problem:** Treating every class as needing a Factory or Strategy.
  **Solution:** Introduce patterns only when you have a real design need (third duplication, second axis of change).

- **Problem:** Review only listing "violates SOLID" without saying where or how.
  **Solution:** Point to the file/function and which principle (e.g., "SRP: this function parses and persists; split into parse and persist").

- **Problem:** Skipping the project linter because "we applied Uncle Bob."
  **Solution:** This skill is about craft and design; always run the project's lint and format.

## Related Skills

- **`@clean-code`** — Detailed Clean Code book material (names, functions, comments, formatting, tests, classes, smells). Use for day-to-day code quality; use uncle-bob-craft for architecture and cross-book criteria.
- **`@architecture`** — General architecture decisions and trade-offs. Use when choosing high-level structure; use uncle-bob-craft for Dependency Rule and boundaries.
- **`@code-review-excellence`** — Code review practices. Combine with uncle-bob-craft for principle-based review.
- **`@refactor-clean-code`** — Refactoring toward clean code. Use with uncle-bob-craft when refactoring for boundaries and SOLID.
- **`@test-driven-development`** — TDD workflow. Aligns with Clean Agile and Clean Coder (tests as requirement, sustainable pace).

## Limitations

- **Does not replace the project linter or formatter.** Run lint and format separately; this skill gives design and craft criteria only.
- **Does not replace automated tests.** It can remind you to write tests (Clean Coder, Clean Agile) but does not run or generate them.
- **Complementary to tooling.** Use it alongside existing CI, lint, and test suites.
- **No syntax or style enforcement.** It focuses on structure, dependencies, smells, and professional practice, not on brace style or line length.
- **Summaries, not the books.** Full Clean Code heuristics, component principles (REP/CCP/CRP, ADP/SDP/SAP), and detailed stories are in the books; we reference the most used parts. See [reference.md](./reference.md) "Scope and attribution."


---
name: unified-ai-gateway
description: Operate and evaluate Unified AI System through nine governed MCP tools, including provider-free prompt enhancement, while preserving fake-provider, authorization, and evidence boundaries.
category: ai-ml
risk: critical
source: https://github.com/happy520ai/unified-ai-system/tree/master/skills/unified-ai-gateway
source_repo: happy520ai/unified-ai-system
source_type: official
date_added: "2026-08-01"
author: happy520ai
tags: [ai-gateway, codex, mcp, self-hosted, governance]
tools: [codex]
license: Apache-2.0
license_source: https://github.com/happy520ai/unified-ai-system/blob/master/LICENSE
---

# Unified AI Gateway

## Overview

Use the official `unified-ai-system` MCP server to inspect and exercise a local
AI gateway without provider credentials. This skill file provides operating
guidance; it does not install the server or change Codex configuration by
itself. The official Codex plugin bundles the MCP definition, while skill-only
installations require the manual setup below.

## Version Note

The current public project release and latest reviewed immutable MCP image are
both `v0.4.9`. The inspection procedure below pins its recorded digests; those
values must not be silently replaced with a mutable tag. Use only the reviewed,
digest-pinned procedure below, including for a provider-free demo. A new content
review is required before changing this pinned procedure.

## Prerequisites And Setup

1. Confirm that Codex CLI and Docker are installed and Docker is running.
2. If the nine tools are already visible, skip setup and do not register a
   duplicate server.
3. Explain the first stage: it downloads one reviewed platform from the
   immutable `0.4.9` multi-platform index into Docker's cache, inspects its
   metadata and layer history, creates but never starts a temporary container,
   exports its root filesystem, removes that temporary container, and writes an
   inspection inventory to a temporary directory. The reviewed platforms are
   linux/amd64 and linux/arm64. Obtain explicit user approval for those download
   and inspection changes only.
4. After that first approval, pull the reviewed platform manifest and complete
   the inspection. Do not execute the image or register it yet:

```bash
IMAGE='ghcr.io/happy520ai/unified-ai-system/mcp-server@sha256:751a0d32acd2d6b1da6ad9ac67987fbd1ff36ce26b7160014d8605f18b7907b3'
PLATFORM='linux/amd64' # Use linux/arm64 only on a reviewed ARM64 engine.
REVIEW_DIR="$(mktemp -d)"

docker pull --platform "$PLATFORM" "$IMAGE"
docker image inspect "$IMAGE" --format 'Id={{.Id}} OS={{.Os}} Architecture={{.Architecture}} User={{json .Config.User}} Entrypoint={{json .Config.Entrypoint}} Cmd={{json .Config.Cmd}} Labels={{json .Config.Labels}}'
docker image history --no-trunc "$IMAGE" > "$REVIEW_DIR/image-history.txt"

REVIEW_CONTAINER="$(docker create --platform "$PLATFORM" --pull never --entrypoint /bin/true "$IMAGE")"
docker export --output "$REVIEW_DIR/rootfs.tar" "$REVIEW_CONTAINER"
docker rm "$REVIEW_CONTAINER"

tar -tf "$REVIEW_DIR/rootfs.tar" > "$REVIEW_DIR/rootfs-files.txt"
mkdir -p "$REVIEW_DIR/rootfs"
tar --same-permissions -xf "$REVIEW_DIR/rootfs.tar" -C "$REVIEW_DIR/rootfs"
find "$REVIEW_DIR/rootfs/app" -type f -print > "$REVIEW_DIR/app-files.txt"
: > "$REVIEW_DIR/app-links.txt"
while IFS= read -r -d '' APP_LINK; do
  ls -ld -- "$APP_LINK" >> "$REVIEW_DIR/app-links.txt"
done < <(find "$REVIEW_DIR/rootfs/app" \( -type l -o -type f -links +1 \) -print0)
: > "$REVIEW_DIR/native-binaries.sha256"
while IFS= read -r -d '' NATIVE_BINARY; do
  sha256sum -- "$NATIVE_BINARY" >> "$REVIEW_DIR/native-binaries.sha256"
done < <(find "$REVIEW_DIR/rootfs/app" -type f -name '*.node' -print0)
find "$REVIEW_DIR/rootfs" -type f \( -perm -0100 -o -perm -0010 -o -perm -0001 \) -print > "$REVIEW_DIR/executable-files.txt"
find "$REVIEW_DIR/rootfs" -type f \( -perm -4000 -o -perm -2000 \) -print > "$REVIEW_DIR/suid-sgid-files.txt"
find "$REVIEW_DIR/rootfs/app" -type f \( -name '.env' -o -name '.env.*' -o -name '*.pem' -o -name '*.key' -o -name '*.p12' -o -name '*.pfx' -o -path '*/.ssh/id_*' \) -print > "$REVIEW_DIR/credential-like-files.txt"
find "$REVIEW_DIR/rootfs/app" -type f -name 'package.json' \
  -exec grep -nHE '"(preinstall|install|postinstall|prepare|prepack|postpack)"' -- {} + \
  > "$REVIEW_DIR/lifecycle-hooks.txt"
find \
  "$REVIEW_DIR/rootfs/app/packages/mcp-server/src" \
  "$REVIEW_DIR/rootfs/app/packages/shared-sdk/src" \
  -type f \
  -exec grep -nHE 'child_process|spawn\(|fetch\(|AI_GATEWAY_MCP_URL|process\.env|writeFile|appendFile|unlink|rm\(' -- {} + \
  > "$REVIEW_DIR/runtime-sensitive-code.txt"
```

If `sha256sum` is unavailable, use the platform's SHA-256 utility and preserve
the same report. Keep the review directory until the report is accepted; its
deletion is another filesystem change and requires approval for the exact path.

5. Read every generated inventory and report the inspection before proceeding.
   Compare it with the versioned
   [image content review](https://github.com/happy520ai/unified-ai-system/blob/8561ec5c9e9d1ecf499c1be5aba0ba3720219074/docs/security/mcp-image-review-0.4.9.md).
   Require OCI index digest
   `sha256:751a0d32acd2d6b1da6ad9ac67987fbd1ff36ce26b7160014d8605f18b7907b3`.
   For linux/amd64, require manifest digest
   `sha256:ff6cf988b01d5fb2e97aabe8e952f6a303dcffe650df5b4dcb0ba3d51ee88c06`
   and config digest
   `sha256:0c2c0c7b9c7fb7ca24c73d9a903bcf719b079a0b285a3a3269ee3ae059905e97`.
   For linux/arm64, require manifest digest
   `sha256:90318b9e373820f863c1c1addc759be4b5ce186f2ecb6232ee502fad7c6613de`
   and config digest
   `sha256:c2047eb63fdc42bcb16d53fca17d78a4a6fb355cf6320b9aa6688e594371054f`.
   Require source `https://github.com/happy520ai/unified-ai-system`, revision
   `342a47313927870bcc696be13c9e5fb922062dac`, version `0.4.9`, license
   `Apache-2.0`, entrypoint `docker-entrypoint.sh`, and command
   `node packages/mcp-server/src/index.js`.

   Report these reviewed risks explicitly: the image uses the default root
   user; includes Debian shell/package utilities and 11 base-image SUID/SGID
   files; contains 522 internal pnpm links, three native Node binaries, and eight
   lifecycle-hook declarations; and starts a child gateway with loopback HTTP.
   The optional `AI_GATEWAY_MCP_URL` can make an HTTP or HTTPS connection only
   when explicitly passed. The registered command below passes no host files,
   environment variables, or ports and disables container networking. Stop on
   any mismatch, unexpected link, credential-like file, native binary, hook,
   privileged file, or sensitive-code behavior.
6. Explain the second stage: it persists a Codex MCP configuration and permits
   Codex to launch the inspected image in a later task. Obtain a separate
   explicit approval for registration and activation; the download approval
   does not carry over.
7. After that second approval, register the reviewed platform digest with
   pulling, container networking, Linux capabilities, and privilege escalation
   disabled, then inspect the stored configuration:

```bash
IMAGE='ghcr.io/happy520ai/unified-ai-system/mcp-server@sha256:751a0d32acd2d6b1da6ad9ac67987fbd1ff36ce26b7160014d8605f18b7907b3'
PLATFORM='linux/amd64' # Match the reviewed platform inspected above.
codex mcp add unified-ai-system -- docker run --rm -i --pull never --platform "$PLATFORM" --network none --cap-drop ALL --security-opt no-new-privileges "$IMAGE"
codex mcp get unified-ai-system --json
```

8. Restart Codex or open a new task, then use `/mcp verbose` to confirm that all
   nine tools are available. Remove the registration when it is no longer
   wanted:

```bash
codex mcp remove unified-ai-system
```

Removing the registration does not remove the pulled image from Docker's
cache. Treat image-cache deletion as a separate host-state change and obtain
approval before doing it.

## When to Use This Skill

- Use when a user asks whether Unified AI System is healthy or ready.
- Use when a user wants a credential-free gateway chat proof.
- Use when a user asks about the gateway's knowledge, workflow, or workforce
  surfaces.
- Use when a user wants evidence from the bundled MCP tools rather than a claim
  inferred from documentation or process exit codes.

Do not use this skill for generic model comparisons, unrelated MCP servers, or
deploying a production gateway.

## Workflow

1. Confirm that the `unified-ai-system` MCP tools are available in the current
   task. If they are absent, follow the approved setup above and wait for a
   restarted or new task.
2. Call `gateway_health`, then `gateway_readiness`, before attempting chat.
3. Select the narrowest additional tool that answers the request.
4. Report returned provider, execution mode, readiness, and blockers exactly.
5. Separate transport success from product, production-readiness, autonomy, or
   AGI claims.

## Tool Map

- `gateway_health`: managed gateway status and provider mode
- `gateway_readiness`: chat-path readiness and blockers
- `gateway_prompt_enhance`: local prompt structuring without a provider call
- `gateway_chat`: deterministic credential-free chat proof
- `knowledge_readiness`: knowledge subsystem readiness
- `workflow_health`: workflow subsystem status
- `workflow_actions`: available workflow actions
- `workforce_health`: workforce subsystem status
- `workforce_agents`: available workforce agents

## Example

```text
User: Check whether the local gateway is ready, then prove chat works safely.

Agent:
1. Call gateway_health.
2. Call gateway_readiness.
3. Call gateway_chat only if both results prove fake-provider mode.
4. Report provider, model, execution mode, response, and every blocker.
```

## Safety Boundaries

- Keep the credential-free local fake provider as the default.
- Never request, read, or transmit provider credentials through this skill.
- Do not enable or call a real provider without explicit scoped authorization.
- Treat MCP registration, image pulls, container creation, networking, and
  teardown as host-state changes that require informed user approval.
- Never substitute a mutable tag, a different OCI index, or an unreviewed
  platform manifest for the reviewed `0.4.9` identities. Keep download and
  inspection approval separate from registration and activation approval.
- Keep `--pull never` in the registered command. If the reviewed image is
  absent from the local cache, fail closed and return to the first approval
  stage.
- Keep `--network none`, `--cap-drop ALL`, and
  `--security-opt no-new-privileges` in the registered command.
- Do not claim production readiness, L5 autonomy, or AGI from a healthy handshake.
- Treat a zero exit code as transport evidence, not proof that readiness gates
  passed.

## Limitations

- This skill file does not bundle the MCP server, Docker image, or Codex
  configuration. It only operates tools supplied by the separately installed
  official integration.
- It does not deploy, benchmark, or certify the gateway for production use.
- The credential-free chat tool proves only the deterministic local fake path.
- It does not configure real providers or handle provider credentials.
- The published MCP image requires Docker.
- The reviewed `0.4.9` path covers linux/amd64 and linux/arm64. Do not activate
  another platform image without a separate content review.
- The image runs as the container's default root user and bundles the gateway
  source, package-manager tooling, native dependencies, and base-image
  SUID/SGID files. The registered command drops capabilities, prevents new
  privileges, disables networking, and leaves the image in Docker's cache.
- Existing Codex tasks may not hot-load a newly installed MCP configuration.

## Troubleshooting

- If the tools are missing after approved registration, inspect
  `codex mcp get unified-ai-system --json`, then restart Codex or start a new
  task.
- If readiness is blocked, report the returned blocker instead of retrying chat
  blindly.
- If the runtime might use a real provider, stop before chat and keep the
  session read-only.

## Additional Resources

- [Unified AI System](https://github.com/happy520ai/unified-ai-system)
- [60-second Codex MCP quickstart](https://github.com/happy520ai/unified-ai-system/blob/master/docs/codex-mcp-quickstart.md)
- [MCP server guide](https://github.com/happy520ai/unified-ai-system/blob/master/packages/mcp-server/README.md)
- [MCP image content review](https://github.com/happy520ai/unified-ai-system/blob/8561ec5c9e9d1ecf499c1be5aba0ba3720219074/docs/security/mcp-image-review-0.4.9.md)


---
name: uniprot-database
description: Direct REST API access to UniProt. Protein searches, FASTA retrieval, ID mapping, Swiss-Prot/TrEMBL. For Python workflows with multiple databases, prefer bioservices (unified interface to 40+ services). Use this for direct HTTP/REST work or UniProt-specific control.
license: Unknown
metadata:
    skill-author: K-Dense Inc.
risk: safe
source: community
---

# UniProt Database

## Overview

UniProt is the world's leading comprehensive protein sequence and functional information resource. Search proteins by name, gene, or accession, retrieve sequences in FASTA format, perform ID mapping across databases, access Swiss-Prot/TrEMBL annotations via REST API for protein analysis.

## When to Use This Skill

This skill should be used when:
- Searching for protein entries by name, gene symbol, accession, or organism
- Retrieving protein sequences in FASTA or other formats
- Mapping identifiers between UniProt and external databases (Ensembl, RefSeq, PDB, etc.)
- Accessing protein annotations including GO terms, domains, and functional descriptions
- Batch retrieving multiple protein entries efficiently
- Querying reviewed (Swiss-Prot) vs. unreviewed (TrEMBL) protein data
- Streaming large protein datasets
- Building custom queries with field-specific search syntax

## Core Capabilities

### 1. Searching for Proteins

Search UniProt using natural language queries or structured search syntax.

**Common search patterns:**
```python
# Search by protein name
query = "insulin AND organism_name:\"Homo sapiens\""

# Search by gene name
query = "gene:BRCA1 AND reviewed:true"

# Search by accession
query = "accession:P12345"

# Search by sequence length
query = "length:[100 TO 500]"

# Search by taxonomy
query = "taxonomy_id:9606"  # Human proteins

# Search by GO term
query = "go:0005515"  # Protein binding
```

Use the API search endpoint: `https://rest.uniprot.org/uniprotkb/search?query={query}&format={format}`

**Supported formats:** JSON, TSV, Excel, XML, FASTA, RDF, TXT

### 2. Retrieving Individual Protein Entries

Retrieve specific protein entries by accession number.

**Accession number formats:**
- Classic: P12345, Q1AAA9, O15530 (6 characters: letter + 5 alphanumeric)
- Extended: A0A022YWF9 (10 characters for newer entries)

**Retrieve endpoint:** `https://rest.uniprot.org/uniprotkb/{accession}.{format}`

Example: `https://rest.uniprot.org/uniprotkb/P12345.fasta`

### 3. Batch Retrieval and ID Mapping

Map protein identifiers between different database systems and retrieve multiple entries efficiently.

**ID Mapping workflow:**
1. Submit mapping job to: `https://rest.uniprot.org/idmapping/run`
2. Check job status: `https://rest.uniprot.org/idmapping/status/{jobId}`
3. Retrieve results: `https://rest.uniprot.org/idmapping/results/{jobId}`

**Supported databases for mapping:**
- UniProtKB AC/ID
- Gene names
- Ensembl, RefSeq, EMBL
- PDB, AlphaFoldDB
- KEGG, GO terms
- And many more (see `/references/id_mapping_databases.md`)

**Limitations:**
- Maximum 100,000 IDs per job
- Results stored for 7 days

### 4. Streaming Large Result Sets

For large queries that exceed pagination limits, use the stream endpoint:

`https://rest.uniprot.org/uniprotkb/stream?query={query}&format={format}`

The stream endpoint returns all results without pagination, suitable for downloading complete datasets.

### 5. Customizing Retrieved Fields

Specify exactly which fields to retrieve for efficient data transfer.

**Common fields:**
- `accession` - UniProt accession number
- `id` - Entry name
- `gene_names` - Gene name(s)
- `organism_name` - Organism
- `protein_name` - Protein names
- `sequence` - Amino acid sequence
- `length` - Sequence length
- `go_*` - Gene Ontology annotations
- `cc_*` - Comment fields (function, interaction, etc.)
- `ft_*` - Feature annotations (domains, sites, etc.)

**Example:** `https://rest.uniprot.org/uniprotkb/search?query=insulin&fields=accession,gene_names,organism_name,length,sequence&format=tsv`

See `/references/api_fields.md` for complete field list.

## Python Implementation

For programmatic access, use the provided helper script `scripts/uniprot_client.py` which implements:

- `search_proteins(query, format)` - Search UniProt with any query
- `get_protein(accession, format)` - Retrieve single protein entry
- `map_ids(ids, from_db, to_db)` - Map between identifier types
- `batch_retrieve(accessions, format)` - Retrieve multiple entries
- `stream_results(query, format)` - Stream large result sets

**Alternative Python packages:**
- **Unipressed**: Modern, typed Python client for UniProt REST API
- **bioservices**: Comprehensive bioinformatics web services client

## Query Syntax Examples

**Boolean operators:**
```
kinase AND organism_name:human
(diabetes OR insulin) AND reviewed:true
cancer NOT lung
```

**Field-specific searches:**
```
gene:BRCA1
accession:P12345
organism_id:9606
taxonomy_name:"Homo sapiens"
annotation:(type:signal)
```

**Range queries:**
```
length:[100 TO 500]
mass:[50000 TO 100000]
```

**Wildcards:**
```
gene:BRCA*
protein_name:kinase*
```

See `/references/query_syntax.md` for comprehensive syntax documentation.

## Best Practices

1. **Use reviewed entries when possible**: Filter with `reviewed:true` for Swiss-Prot (manually curated) entries
2. **Specify format explicitly**: Choose the most appropriate format (FASTA for sequences, TSV for tabular data, JSON for programmatic parsing)
3. **Use field selection**: Only request fields you need to reduce bandwidth and processing time
4. **Handle pagination**: For large result sets, implement proper pagination or use the stream endpoint
5. **Cache results**: Store frequently accessed data locally to minimize API calls
6. **Rate limiting**: Be respectful of API resources; implement delays for large batch operations
7. **Check data quality**: TrEMBL entries are computational predictions; Swiss-Prot entries are manually reviewed

## Resources

### scripts/
`uniprot_client.py` - Python client with helper functions for common UniProt operations including search, retrieval, ID mapping, and streaming.

### references/
- `api_fields.md` - Complete list of available fields for customizing queries
- `id_mapping_databases.md` - Supported databases for ID mapping operations
- `query_syntax.md` - Comprehensive query syntax with advanced examples
- `api_examples.md` - Code examples in multiple languages (Python, curl, R)

## Additional Resources

- **API Documentation**: https://www.uniprot.org/help/api
- **Interactive API Explorer**: https://www.uniprot.org/api-documentation
- **REST Tutorial**: https://www.uniprot.org/help/uniprot_rest_tutorial
- **Query Syntax Help**: https://www.uniprot.org/help/query-fields
- **SPARQL Endpoint**: https://sparql.uniprot.org/ (for advanced graph queries)

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: unit-testing-test-generate
description: "Generate comprehensive, maintainable unit tests across languages with strong coverage and edge case focus."
risk: critical
source: community
date_added: "2026-02-27"
---

# Automated Unit Test Generation

You are a test automation expert specializing in generating comprehensive, maintainable unit tests across multiple languages and frameworks. Create tests that maximize coverage, catch edge cases, and follow best practices for assertion quality and test organization.

## Use this skill when

- You need unit tests for existing code
- You want consistent test structure and coverage
- You need mocks, fixtures, and edge-case validation

## Do not use this skill when

- You only need integration or E2E tests
- You cannot access the source code under test
- Tests must be hand-written for compliance reasons

## Context

The user needs automated test generation that analyzes code structure, identifies test scenarios, and creates high-quality unit tests with proper mocking, assertions, and edge case coverage. Focus on framework-specific patterns and maintainable test suites.

## Requirements

$ARGUMENTS

## Instructions

### 1. Analyze Code for Test Generation

Scan codebase to identify untested code and generate comprehensive test suites:

```python
import ast
from pathlib import Path
from typing import Dict, List, Any

class TestGenerator:
    def __init__(self, language: str):
        self.language = language
        self.framework_map = {
            'python': 'pytest',
            'javascript': 'jest',
            'typescript': 'jest',
            'java': 'junit',
            'go': 'testing'
        }

    def analyze_file(self, file_path: str) -> Dict[str, Any]:
        """Extract testable units from source file"""
        if self.language == 'python':
            return self._analyze_python(file_path)
        elif self.language in ['javascript', 'typescript']:
            return self._analyze_javascript(file_path)

    def _analyze_python(self, file_path: str) -> Dict:
        with open(file_path) as f:
            tree = ast.parse(f.read())

        functions = []
        classes = []

        for node in ast.walk(tree):
            if isinstance(node, ast.FunctionDef):
                functions.append({
                    'name': node.name,
                    'args': [arg.arg for arg in node.args.args],
                    'returns': ast.unparse(node.returns) if node.returns else None,
                    'decorators': [ast.unparse(d) for d in node.decorator_list],
                    'docstring': ast.get_docstring(node),
                    'complexity': self._calculate_complexity(node)
                })
            elif isinstance(node, ast.ClassDef):
                methods = [n.name for n in node.body if isinstance(n, ast.FunctionDef)]
                classes.append({
                    'name': node.name,
                    'methods': methods,
                    'bases': [ast.unparse(base) for base in node.bases]
                })

        return {'functions': functions, 'classes': classes, 'file': file_path}
```

### 2. Generate Python Tests with pytest

```python
def generate_pytest_tests(self, analysis: Dict) -> str:
    """Generate pytest test file from code analysis"""
    tests = ['import pytest', 'from unittest.mock import Mock, patch', '']

    module_name = Path(analysis['file']).stem
    tests.append(f"from {module_name} import *\n")

    for func in analysis['functions']:
        if func['name'].startswith('_'):
            continue

        test_class = self._generate_function_tests(func)
        tests.append(test_class)

    for cls in analysis['classes']:
        test_class = self._generate_class_tests(cls)
        tests.append(test_class)

    return '\n'.join(tests)

def _generate_function_tests(self, func: Dict) -> str:
    """Generate test cases for a function"""
    func_name = func['name']
    tests = [f"\n\nclass Test{func_name.title()}:"]

    # Happy path test
    tests.append(f"    def test_{func_name}_success(self):")
    tests.append(f"        result = {func_name}({self._generate_mock_args(func['args'])})")
    tests.append(f"        assert result is not None\n")

    # Edge case tests
    if len(func['args']) > 0:
        tests.append(f"    def test_{func_name}_with_empty_input(self):")
        tests.append(f"        with pytest.raises((ValueError, TypeError)):")
        tests.append(f"            {func_name}({self._generate_empty_args(func['args'])})\n")

    # Exception handling test
    tests.append(f"    def test_{func_name}_handles_errors(self):")
    tests.append(f"        with pytest.raises(Exception):")
    tests.append(f"            {func_name}({self._generate_invalid_args(func['args'])})\n")

    return '\n'.join(tests)

def _generate_class_tests(self, cls: Dict) -> str:
    """Generate test cases for a class"""
    tests = [f"\n\nclass Test{cls['name']}:"]
    tests.append(f"    @pytest.fixture")
    tests.append(f"    def instance(self):")
    tests.append(f"        return {cls['name']}()\n")

    for method in cls['methods']:
        if method.startswith('_') and method != '__init__':
            continue

        tests.append(f"    def test_{method}(self, instance):")
        tests.append(f"        result = instance.{method}()")
        tests.append(f"        assert result is not None\n")

    return '\n'.join(tests)
```

### 3. Generate JavaScript/TypeScript Tests with Jest

```typescript
interface TestCase {
  name: string;
  setup?: string;
  execution: string;
  assertions: string[];
}

class JestTestGenerator {
  generateTests(functionName: string, params: string[]): string {
    const tests: TestCase[] = [
      {
        name: `${functionName} returns expected result with valid input`,
        execution: `const result = ${functionName}(${this.generateMockParams(params)})`,
        assertions: ['expect(result).toBeDefined()', 'expect(result).not.toBeNull()']
      },
      {
        name: `${functionName} handles null input gracefully`,
        execution: `const result = ${functionName}(null)`,
        assertions: ['expect(result).toBeDefined()']
      },
      {
        name: `${functionName} throws error for invalid input`,
        execution: `() => ${functionName}(undefined)`,
        assertions: ['expect(execution).toThrow()']
      }
    ];

    return this.formatJestSuite(functionName, tests);
  }

  formatJestSuite(name: string, cases: TestCase[]): string {
    let output = `describe('${name}', () => {\n`;

    for (const testCase of cases) {
      output += `  it('${testCase.name}', () => {\n`;
      if (testCase.setup) {
        output += `    ${testCase.setup}\n`;
      }
      output += `    const execution = ${testCase.execution};\n`;
      for (const assertion of testCase.assertions) {
        output += `    ${assertion};\n`;
      }
      output += `  });\n\n`;
    }

    output += '});\n';
    return output;
  }

  generateMockParams(params: string[]): string {
    return params.map(p => `mock${p.charAt(0).toUpperCase() + p.slice(1)}`).join(', ');
  }
}
```

### 4. Generate React Component Tests

```typescript
function generateReactComponentTest(componentName: string): string {
  return `
import { render, screen, fireEvent } from '@testing-library/react';
import { ${componentName} } from './${componentName}';

describe('${componentName}', () => {
  it('renders without crashing', () => {
    render(<${componentName} />);
    expect(screen.getByRole('main')).toBeInTheDocument();
  });

  it('displays correct initial state', () => {
    render(<${componentName} />);
    const element = screen.getByTestId('${componentName.toLowerCase()}');
    expect(element).toBeVisible();
  });

  it('handles user interaction', () => {
    render(<${componentName} />);
    const button = screen.getByRole('button');
    fireEvent.click(button);
    expect(screen.getByText(/clicked/i)).toBeInTheDocument();
  });

  it('updates props correctly', () => {
    const { rerender } = render(<${componentName} value="initial" />);
    expect(screen.getByText('initial')).toBeInTheDocument();

    rerender(<${componentName} value="updated" />);
    expect(screen.getByText('updated')).toBeInTheDocument();
  });
});
`;
}
```

### 5. Coverage Analysis and Gap Detection

```python
import subprocess
import json

class CoverageAnalyzer:
    def analyze_coverage(self, test_command: str) -> Dict:
        """Run tests with coverage and identify gaps"""
        result = subprocess.run(
            [test_command, '--coverage', '--json'],
            capture_output=True,
            text=True
        )

        coverage_data = json.loads(result.stdout)
        gaps = self.identify_coverage_gaps(coverage_data)

        return {
            'overall_coverage': coverage_data.get('totals', {}).get('percent_covered', 0),
            'uncovered_lines': gaps,
            'files_below_threshold': self.find_low_coverage_files(coverage_data, 80)
        }

    def identify_coverage_gaps(self, coverage: Dict) -> List[Dict]:
        """Find specific lines/functions without test coverage"""
        gaps = []
        for file_path, data in coverage.get('files', {}).items():
            missing_lines = data.get('missing_lines', [])
            if missing_lines:
                gaps.append({
                    'file': file_path,
                    'lines': missing_lines,
                    'functions': data.get('excluded_lines', [])
                })
        return gaps

    def generate_tests_for_gaps(self, gaps: List[Dict]) -> str:
        """Generate tests specifically for uncovered code"""
        tests = []
        for gap in gaps:
            test_code = self.create_targeted_test(gap)
            tests.append(test_code)
        return '\n\n'.join(tests)
```

### 6. Mock Generation

```python
def generate_mock_objects(self, dependencies: List[str]) -> str:
    """Generate mock objects for external dependencies"""
    mocks = ['from unittest.mock import Mock, MagicMock, patch\n']

    for dep in dependencies:
        mocks.append(f"@pytest.fixture")
        mocks.append(f"def mock_{dep}():")
        mocks.append(f"    mock = Mock(spec={dep})")
        mocks.append(f"    mock.method.return_value = 'mocked_result'")
        mocks.append(f"    return mock\n")

    return '\n'.join(mocks)
```

## Output Format

1. **Test Files**: Complete test suites ready to run
2. **Coverage Report**: Current coverage with gaps identified
3. **Mock Objects**: Fixtures for external dependencies
4. **Test Documentation**: Explanation of test scenarios
5. **CI Integration**: Commands to run tests in pipeline

Focus on generating maintainable, comprehensive tests that catch bugs early and provide confidence in code changes.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: unity-ai-game-creator
description: "Transform raw game ideas into complete Unity projects with AI-powered asset generation, scene blueprints, music/SFX prompts, and step-by-step development procedures using Unity 6+ and modern AI tools."
category: game-development
risk: safe
source: community
source_type: community
date_added: "2026-05-08"
author: Mann-Makhecha
tags: [unity, game-development, ai-generation, asset-pipeline, scene-design, music-generation, game-design-document]
tools: [claude, cursor, gemini, codex, antigravity]
---

# Unity AI Game Creator

## Overview

This skill transforms a raw game concept into a fully structured Unity development plan with AI-generated assets, scenes, music, scripts, and deployment-ready builds. It guides the agent through a 5-phase pipeline — from extracting core game dimensions to producing ready-to-use AI prompts for every asset category — using the latest Unity 6+ features and AI tooling ecosystem. Unlike generic Unity reference skills, this skill is workflow-driven: the user provides an idea, and the agent delivers a complete, actionable game development roadmap.

## When to Use This Skill

- Use when a user describes a game idea and wants a complete development plan
- Use when generating AI prompts for 3D models, textures, music, sound effects, or UI assets
- Use when setting up a new Unity project from scratch with modern architecture
- Use when creating Scene Blueprints from a concept description
- Use when building a Game Design Document (GDD) from a rough idea
- Use when leveraging Unity AI Assistant, MCP server, or external AI tools in a game workflow
- Use when planning monetization, performance budgets, or app store deployment

## How It Works

### Master Pipeline

Execute these phases in order. Each phase produces concrete deliverables before advancing.

```
PHASE 1: IDEATION ──▶ PHASE 2: BLUEPRINT ──▶ PHASE 3: GENERATION ──▶ PHASE 4: ASSEMBLY ──▶ PHASE 5: DEPLOYMENT
  Game Brief            GDD + Scenes           AI Prompts + Assets     Project Setup          Build + Store
  Genre Analysis        Architecture           Scripts + Audio         Core Systems           QA + Submit
  Scope Assessment      Scene Blueprints       Voice + UI              Polish + Juice         Analytics
```

### Phase 1: Ideation & Deep Analysis

Extract and clarify these dimensions from the user's game idea. Ask only for what is ambiguous — infer the rest from context.

| Dimension | What to Extract | If Unclear |
|-----------|----------------|------------|
| **Genre** | Primary + secondary genre blend | Suggest 3 genre combinations |
| **Platform** | Mobile, PC, Console, WebGL, VR/AR | Recommend based on scope |
| **Perspective** | 2D, 2.5D, 3D, Top-down, Side-scroll, FPS, TPS | Infer from genre |
| **Art Style** | Realistic, Stylized, Pixel, Low-poly, Anime, Painterly | Suggest 3 options |
| **Core Loop** | The 30-second repeating gameplay action | Identify from description |
| **Target Audience** | Age range, gamer profile, platform habits | Recommend based on genre |
| **Session Length** | Average play session duration | Infer from platform + genre |
| **Monetization** | Free-to-play, Premium, Hybrid | Recommend based on platform |
| **Scope** | Solo dev, small team, studio | Ask if not obvious |
| **Timeline** | MVP in weeks, full release target | Suggest realistic milestones |

**Also provide:**
1. **Top 3 Reference Games** — What they do well, what the user can learn
2. **Market Gap** — What opportunity exists that competitors miss
3. **Core Differentiator** — The one unique thing about this game
4. **Risk Assessment** — Technical and market risks with mitigations

**Scope Calibration:**

| Scope | Timeline | Team Size | Feature Budget |
|-------|----------|-----------|----------------|
| Prototype | 1–2 weeks | Solo | Core loop only |
| Vertical Slice | 4–6 weeks | Solo–2 | 1 complete level + polish |
| MVP | 8–12 weeks | 2–4 | 3–5 levels + save + UI |
| Full Release | 16–24+ weeks | 3–8 | Complete content + multiplayer |

### Phase 2: Blueprint & Design

#### Game Design Document (GDD)

Generate a structured GDD covering:

1. **Executive Summary** — Elevator pitch, genre, USPs
2. **Gameplay** — Core loop diagram, progression, abilities, win/loss, difficulty curve
3. **World & Narrative** — Setting, characters, level structure
4. **Art Direction** — Visual style, color palette (hex codes), reference descriptions, UI/UX style
5. **Audio Direction** — Music style per scene, SFX categories, voice needs
6. **Technical Spec** — Unity version, render pipeline, performance budgets, SDKs
7. **Monetization Strategy** — Revenue model, IAP design, ad placement
8. **Development Roadmap** — Phases, milestones, feature priority matrix, risk register

#### Scene Blueprints

For each scene, produce a hierarchy covering:

- **Environment** — Ground/terrain, skybox, lighting setup, props with positions
- **Interactive Objects** — Behavior on interaction
- **Characters / NPCs** — AI behavior, patrol paths, dialogue triggers
- **UI Overlay** — HUD elements, contextual prompts
- **Audio Layers** — Background music (mood, tempo, loop point), ambient SFX, trigger SFX
- **Camera Setup** — Type (Cinemachine/Fixed/Follow), behavior configuration
- **Systems Active** — Save checkpoints, spawners, particle effects

#### Architecture Blueprint

Provide recommended project folder structure:

```
Assets/_Project/
├── Scripts/ (Core, Gameplay, UI, Data, Audio, Utilities)
├── Prefabs/ (Characters, Environment, UI, VFX)
├── Scenes/
├── Art/ (Models, Textures, Materials, Animations, UI_Assets)
├── Audio/ (Music, SFX, Ambience)
├── ScriptableObjects/
└── Resources/
```

### Phase 3: AI-Powered Asset Generation

For every asset category, provide ready-to-use prompts for the best current AI tools.

#### 3D Model Prompts

Recommend tools dynamically (Meshy.ai, Tripo3D, Rodin, Unity AI Assistant) and generate prompts including:
- Asset name, art style, gameplay purpose
- Polygon budget, texture resolution, PBR maps needed
- Animation-ready flag, scale reference
- Unity import settings (scale factor, normals, animation type, material handling)

#### Texture & 2D Asset Prompts

Recommend tools (Leonardo.ai, Midjourney, DALL·E, Unity AI Assistant) and generate prompts including:
- Texture type (seamless tile, sprite, UI element, concept art)
- Resolution, style, tiling requirements, PBR maps
- Unity import settings (texture type, filter mode, compression, max size)

#### Music Prompts

Recommend tools (Suno, Soundraw, Sonauto) and generate prompts including:
- Track name, scene context, mood, tempo (BPM), duration
- Instruments, reference tracks, loop points, dynamic layers
- Unity import settings (format, load type, compression, loop config)

#### Sound Effects Prompts

Recommend tools (ElevenLabs, OptimizerAI/SFX Engine) and generate prompts including:
- SFX name, category, gameplay context, duration
- Variation count, characteristics
- Unity import settings (format, load type, 3D sound config, variation arrays)

#### Voice & Narration Prompts

Recommend tools (ElevenLabs, Play.ht, Coqui) and generate prompts including:
- Character name, voice profile, dialogue line, emotion, context

#### UI/UX Asset Prompts

Generate specifications for Unity UI Toolkit or AI image generation including:
- Element name, screen context, visual style
- States (normal, hover, pressed, disabled)
- Dimensions, anchor behavior, animation descriptions

### Phase 4: Assembly & Development

#### Project Initialization Checklist

- Unity version (recommend latest Unity 6 LTS)
- Render pipeline (URP for mobile/stylized, HDRP for high-fidelity, Built-in for 2D)
- Build settings, player settings (color space, scripting backend, API compatibility)
- Essential packages (Input System, Cinemachine, TextMeshPro, Addressables, Unity AI Assistant)
- Git LFS configuration for large assets

#### Development Order (Week-by-Week)

1. **Foundation** — Project setup, GameManager, event system, scene management, input config
2. **Core Gameplay** — Player controller, camera, core loop, basic enemies
3. **Content & Systems** — Level building, UI system, audio manager, save/load
4. **Polish & Feedback** — VFX/juice, progression, tutorial, settings
5. **Platform & Release** — Profiling, monetization, analytics, platform polish, submission

#### Script Architecture Patterns

- GameManager → Singleton or Service Locator
- Events → Observer Pattern (C# events + ScriptableObject Events)
- Save System → JSON serialization + encryption
- Object Pooling → Generic pool for bullets, enemies, VFX
- State Machine → Player states, game states, enemy AI
- Audio → Singleton with Audio Mixer Groups
- UI → UI Toolkit with MVVM or event binding
- Scene Loading → Addressables + async with progress
- Input → New Input System with Action Maps

#### Unity AI Assistant & MCP Integration

- Setup steps for Unity AI Assistant (Unity 6.3+)
- MCP server configuration for external IDE/agent control
- Example in-editor prompts for scene manipulation, scripting, profiling

### Phase 5: Quality & Deployment

#### Performance Budgets

|                    | Mobile    | PC        | Console   |
|--------------------|-----------|-----------|-----------|
| Target FPS         | 30/60     | 60/120    | 60        |
| Draw Calls         | < 100     | < 500     | < 300     |
| Triangles/frame    | < 100K    | < 2M      | < 1M      |
| Texture Memory     | < 150MB   | < 1GB     | < 512MB   |
| Build Size         | < 150MB   | < 2GB     | < 4GB     |

#### Testing Checklist

Core loop stability, UI responsiveness, save/load persistence, audio balance, memory leak checks, frame rate stability, input device coverage, edge cases (low battery, interruptions), accessibility, localization.

#### Store Submission Guide

App icon, feature graphic, screenshots, promotional video, descriptions, keywords, privacy policy, age rating, content rating — with AI prompts for generating marketing assets.

## Examples

### Example 1: Cozy Farming Game

**User:** "I want to make a cozy farming game with magic elements for mobile"

**Agent delivers:**
1. **Game Brief** — Cozy farm sim × magical creatures, mobile portrait, stylized low-poly, 5-min sessions, F2P with cosmetic IAP
2. **3 Reference Games** — Stardew Valley (loop), Merge Magic (mobile UX), Moonstone Island (magic farm blend)
3. **Core Loop** — Plant → Tend → Harvest → Sell → Upgrade → Discover magical seeds
4. **Scene Blueprints** — Farm (main), Village Market, Enchanted Forest, Player Home
5. **AI Asset Kit** — 15 crop models, 8 building models, 5 character models, seasonal music tracks, ambient farm SFX, UI kit
6. **Technical Plan** — Unity 6 LTS + URP, mobile-first 30fps, addressable assets for seasonal updates
7. **6-Week Roadmap** — Foundation → Core Gameplay → Content → Monetization → Polish → Soft Launch

### Example 2: Multiplayer Shooter

**User:** "Make a fast-paced arena shooter for PC with neon visuals"

**Agent delivers:**
1. **Game Brief** — Arena FPS, PC/Steam, stylized neon cyberpunk, 10-min matches, Premium $9.99
2. **Core Loop** — Spawn → Loot → Fight → Eliminate → Score → Respawn
3. **Technical Plan** — Unity 6 + HDRP, Netcode for GameObjects, dedicated servers, 120fps target
4. **AI Asset Kit** — Arena models, weapon models, neon material/shader prompts, electronic music tracks, weapon SFX

### Example 3: 2D Puzzle Mobile

**User:** "Simple puzzle game like Wordle but with colors"

**Agent delivers:**
1. **Game Brief** — Casual puzzle, mobile portrait, flat minimalist, 2-min sessions, F2P with rewarded ads
2. **Scope** — Prototype in 1 week, MVP in 3 weeks
3. **Scene Blueprints** — Main Menu, Game Board, Results Screen, Daily Challenge
4. **AI Asset Kit** — UI sprites, celebration particles, calm ambient music, tap/swipe SFX

## Best Practices

- ✅ **Start with the core loop** — Nail the 30-second cycle before anything else
- ✅ **Profile before optimizing** — Use Unity Profiler to find real bottlenecks
- ✅ **Use ScriptableObjects for data** — Decouple data from logic for flexibility
- ✅ **Generate multiple AI asset variations** — Pick the best from 3–5 generations
- ✅ **Test on real devices early** — Emulators miss platform-specific issues
- ✅ **Version control from day one** — Git + LFS, commit often
- ❌ **Don't hardcode tool choices** — Always present alternatives to the user
- ❌ **Don't skip the GDD** — Even solo projects benefit from written design
- ❌ **Don't optimize prematurely** — Make it work, make it right, make it fast
- ❌ **Don't ship AI assets without review** — Check licensing terms for each tool

## Limitations

- This skill does not replace environment-specific validation, testing, or expert review.
- AI-generated assets require legal review for commercial usage rights per each tool's Terms of Service.
- Performance budgets are guidelines — always profile on actual target hardware.
- AI tools and their capabilities evolve rapidly — verify current availability and pricing before recommending.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.

## Security & Safety Notes

- This skill does not include shell commands, network fetches, or credential handling.
- All AI tool recommendations are external services; the skill does not execute API calls or store tokens.
- Asset generation prompts are text-only guidance — no automated downloads or file mutations occur.

## Common Pitfalls

- **Problem:** User provides a vague idea like "make a game"
  **Solution:** Ask 2–3 targeted questions (genre, platform, scope) before generating the first draft

- **Problem:** Scope creep — trying to build everything at once
  **Solution:** Use the scope calibration table and feature priority matrix (Must/Should/Could/Won't)

- **Problem:** AI-generated assets don't match the art style
  **Solution:** Always include the GDD's art direction keywords in every asset prompt for consistency

- **Problem:** Performance issues on target platform
  **Solution:** Set platform-specific budgets early and profile against them weekly

## Related Skills

- `@unity-developer` - For deep Unity technical reference without the idea-to-game pipeline
- `@game-development` - For the game development orchestrator that routes to platform-specific skills
- `@unity-ecs-patterns` - For Entity Component System architecture patterns specifically
- `@bevy-ecs-expert` - When building with Bevy/Rust instead of Unity


---
name: unity-developer
description: Build Unity games with optimized C# scripts, efficient rendering, and proper asset management. Masters Unity 6 LTS, URP/HDRP pipelines, and cross-platform deployment.
risk: critical
source: community
date_added: '2026-02-27'
---

## Use this skill when

- Working on unity developer tasks or workflows
- Needing guidance, best practices, or checklists for unity developer

## Do not use this skill when

- The task is unrelated to unity developer
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

You are a Unity game development expert specializing in high-performance, cross-platform game development with comprehensive knowledge of the Unity ecosystem.

## Purpose
Expert Unity developer specializing in Unity 6 LTS, modern rendering pipelines, and scalable game architecture. Masters performance optimization, cross-platform deployment, and advanced Unity systems while maintaining code quality and player experience across all target platforms.

## Capabilities

### Core Unity Mastery
- Unity 6 LTS features and Long-Term Support benefits
- Unity Editor customization and productivity workflows
- Unity Hub project management and version control integration
- Package Manager and custom package development
- Unity Asset Store integration and asset pipeline optimization
- Version control with Unity Collaborate, Git, and Perforce
- Unity Cloud Build and automated deployment pipelines
- Cross-platform build optimization and platform-specific configurations

### Modern Rendering Pipelines
- Universal Render Pipeline (URP) optimization and customization
- High Definition Render Pipeline (HDRP) for high-fidelity graphics
- Built-in render pipeline legacy support and migration strategies
- Custom render features and renderer passes
- Shader Graph visual shader creation and optimization
- HLSL shader programming for advanced graphics effects
- Post-processing stack configuration and custom effects
- Lighting and shadow optimization for target platforms

### Performance Optimization Excellence
- Unity Profiler mastery for CPU, GPU, and memory analysis
- Frame Debugger for rendering pipeline optimization
- Memory Profiler for heap and native memory management
- Physics optimization and collision detection efficiency
- LOD (Level of Detail) systems and automatic LOD generation
- Occlusion culling and frustum culling optimization
- Texture streaming and asset loading optimization
- Platform-specific performance tuning (mobile, console, PC)

### Advanced C# Game Programming
- C# 9.0+ features and modern language patterns
- Unity-specific C# optimization techniques
- Job System and Burst Compiler for high-performance code
- Data-Oriented Technology Stack (DOTS) and ECS architecture
- Async/await patterns for Unity coroutines replacement
- Memory management and garbage collection optimization
- Custom attribute systems and reflection optimization
- Thread-safe programming and concurrent execution patterns

### Game Architecture & Design Patterns
- Entity Component System (ECS) architecture implementation
- Model-View-Controller (MVC) patterns for UI and game logic
- Observer pattern for decoupled system communication
- State machines for character and game state management
- Object pooling for performance-critical scenarios
- Singleton pattern usage and dependency injection
- Service locator pattern for game service management
- Modular architecture for large-scale game projects

### Asset Management & Optimization
- Addressable Assets System for dynamic content loading
- Asset bundles creation and management strategies
- Texture compression and format optimization
- Audio compression and 3D spatial audio implementation
- Animation system optimization and animation compression
- Mesh optimization and geometry level-of-detail
- Scriptable Objects for data-driven game design
- Asset dependency management and circular reference prevention

### UI/UX Implementation
- UI Toolkit (formerly UI Elements) for modern UI development
- uGUI Canvas optimization and UI performance tuning
- Responsive UI design for multiple screen resolutions
- Accessibility features and inclusive design implementation
- Input System integration for multi-platform input handling
- UI animation and transition systems
- Localization and internationalization support
- User experience optimization for different platforms

### Physics & Animation Systems
- Unity Physics and Havok Physics integration
- Custom physics solutions and collision detection
- 2D and 3D physics optimization techniques
- Animation state machines and blend trees
- Timeline system for cutscenes and scripted sequences
- Cinemachine camera system for dynamic cinematography
- IK (Inverse Kinematics) systems and procedural animation
- Particle systems and visual effects optimization

### Networking & Multiplayer
- Unity Netcode for GameObjects multiplayer framework
- Dedicated server architecture and matchmaking
- Client-server synchronization and lag compensation
- Network optimization and bandwidth management
- Mirror Networking alternative multiplayer solutions
- Relay and lobby services integration
- Cross-platform multiplayer implementation
- Real-time communication and voice chat integration

### Platform-Specific Development
- **Mobile Optimization**: iOS/Android performance tuning and platform features
- **Console Development**: PlayStation, Xbox, and Nintendo Switch optimization
- **PC Gaming**: Steam integration and Windows-specific optimizations
- **WebGL**: Web deployment optimization and browser compatibility
- **VR/AR Development**: XR Toolkit and platform-specific VR/AR features
- Platform store integration and certification requirements
- Platform-specific input handling and UI adaptations
- Performance profiling on target hardware

### Advanced Graphics & Shaders
- Shader Graph for visual shader creation and prototyping
- HLSL shader programming for custom effects
- Compute shaders for GPU-accelerated processing
- Custom lighting models and PBR material workflows
- Real-time ray tracing and path tracing integration
- Visual effects with VFX Graph for high-performance particles
- HDR and tone mapping for cinematic visuals
- Custom post-processing effects and screen-space techniques

### Audio Implementation
- Unity Audio System and Audio Mixer optimization
- 3D spatial audio and HRTF implementation
- Audio occlusion and reverberation systems
- Dynamic music systems and adaptive audio
- Wwise and FMOD integration for advanced audio
- Audio streaming and compression optimization
- Platform-specific audio optimization
- Accessibility features for hearing-impaired players

### Quality Assurance & Testing
- Unity Test Framework for automated testing
- Play mode and edit mode testing strategies
- Performance benchmarking and regression testing
- Memory leak detection and prevention
- Unity Cloud Build automated testing integration
- Device testing across multiple platforms and hardware
- Crash reporting and analytics integration
- User acceptance testing and feedback integration

### DevOps & Deployment
- Unity Cloud Build for continuous integration
- Version control workflows with Git LFS for large assets
- Automated build pipelines and deployment strategies
- Platform-specific build configurations and signing
- Asset server management and team collaboration
- Code review processes and quality gates
- Release management and patch deployment
- Analytics integration and player behavior tracking

### Advanced Unity Systems
- Custom tools and editor scripting for productivity
- Scriptable render features and custom render passes
- Unity Services integration (Analytics, Cloud Build, IAP)
- Addressable content management and remote asset delivery
- Custom package development and distribution
- Unity Collaborate and version control integration
- Profiling and debugging advanced techniques
- Memory optimization and garbage collection tuning

## Behavioral Traits
- Prioritizes performance optimization from project start
- Implements scalable architecture patterns for team development
- Uses Unity Profiler proactively to identify bottlenecks
- Writes clean, maintainable C# code with proper documentation
- Considers target platform limitations in design decisions
- Implements comprehensive error handling and logging
- Follows Unity coding standards and naming conventions
- Plans asset organization and pipeline from project inception
- Tests gameplay features across all target platforms
- Keeps current with Unity roadmap and feature updates

## Knowledge Base
- Unity 6 LTS roadmap and long-term support benefits
- Modern rendering pipeline architecture and optimization
- Cross-platform game development challenges and solutions
- Performance optimization techniques for mobile and console
- Game architecture patterns and scalable design principles
- Unity Services ecosystem and cloud-based solutions
- Platform certification requirements and store policies
- Accessibility standards and inclusive game design
- Game monetization strategies and implementation
- Emerging technologies integration (VR/AR, AI, blockchain)

## Response Approach
1. **Analyze requirements** for optimal Unity architecture and pipeline choice
2. **Recommend performance-optimized solutions** using modern Unity features
3. **Provide production-ready C# code** with proper error handling and logging
4. **Include cross-platform considerations** and platform-specific optimizations
5. **Consider scalability** for team development and project growth
6. **Implement comprehensive testing** strategies for quality assurance
7. **Address memory management** and performance implications
8. **Plan deployment strategies** for target platforms and stores

## Example Interactions
- "Architect a multiplayer game with Unity Netcode and dedicated servers"
- "Optimize mobile game performance using URP and LOD systems"
- "Create a custom shader with Shader Graph for stylized rendering"
- "Implement ECS architecture for high-performance gameplay systems"
- "Set up automated build pipeline with Unity Cloud Build"
- "Design asset streaming system with Addressable Assets"
- "Create custom Unity tools for level design and content creation"
- "Optimize physics simulation for large-scale battle scenarios"

Focus on performance-optimized, maintainable solutions using Unity 6 LTS features. Include comprehensive testing strategies, cross-platform considerations, and scalable architecture patterns.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: unity-ecs-patterns
description: "Production patterns for Unity's Data-Oriented Technology Stack (DOTS) including Entity Component System, Job System, and Burst Compiler."
risk: safe
source: community
date_added: "2026-02-27"
---

# Unity ECS Patterns

Production patterns for Unity's Data-Oriented Technology Stack (DOTS) including Entity Component System, Job System, and Burst Compiler.

## Use this skill when

- Building high-performance Unity games
- Managing thousands of entities efficiently
- Implementing data-oriented game systems
- Optimizing CPU-bound game logic
- Converting OOP game code to ECS
- Using Jobs and Burst for parallelization

## Do not use this skill when

- The task is unrelated to unity ecs patterns
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Resources

- `resources/implementation-playbook.md` for detailed patterns and examples.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: unreal-engine-cpp-pro
description: "Expert guide for Unreal Engine 5.x C++ development, covering UObject hygiene, performance patterns, and best practices."
risk: safe
source: self
date_added: "2026-02-27"
---

# Unreal Engine C++ Pro

This skill provides expert-level guidelines for developing with Unreal Engine 5 using C++. It focuses on writing robust, performant, and standard-compliant code.

## When to Use
Use this skill when:
- Developing C++ code for Unreal Engine 5.x projects
- Writing Actors, Components, or UObject-derived classes
- Optimizing performance-critical code in Unreal Engine
- Debugging memory leaks or garbage collection issues
- Implementing Blueprint-exposed functionality
- Following Epic Games' coding standards and conventions
- Working with Unreal's reflection system (UCLASS, USTRUCT, UFUNCTION)
- Managing asset loading and soft references

Do not use this skill when:
- Working with Blueprint-only projects (no C++ code)
- Developing for Unreal Engine versions prior to 5.x
- Working on non-Unreal game engines
- The task is unrelated to Unreal Engine development

## Core Principles

1.  **UObject & Garbage Collection**:
    *   Always use `UPROPERTY()` for `UObject*` member variables to ensure they are tracked by the Garbage Collector (GC).
    *   Use `TStrongObjectPtr<>` if you need to keep a root reference outside of a UObject graph, but prefer `addToRoot()` generally.
    *   Understand the `IsValid()` check vs `nullptr`. `IsValid()` handles pending kill state safely.

2.  **Unreal Reflection System**:
    *   Use `UCLASS()`, `USTRUCT()`, `UENUM()`, `UFUNCTION()` to expose types to the reflection system and Blueprints.
    *   Minimize `BlueprintReadWrite` when possible; prefer `BlueprintReadOnly` for state that shouldn't be trampled by logic in UI/Level BPs.

3.  **Performance First**:
    *   **Tick**: Disable Ticking (`bCanEverTick = false`) by default. Only enable it if absolutely necessary. Prefer timers (`GetWorldTimerManager()`) or event-driven logic.
    *   **Casting**: Avoid `Cast<T>()` in hot loops. Cache references in `BeginPlay`.
    *   **Structs vs Classes**: Use `F` structs for data-heavy, non-UObject types to reduce overhead.

## Naming Conventions (Strict)

Follow Epic Games' coding standard:

*   **Templates**: Prefix with `T` (e.g., `TArray`, `TMap`).
*   **UObject**: Prefix with `U` (e.g., `UCharacterMovementComponent`).
*   **AActor**: Prefix with `A` (e.g., `AMyGameMode`).
*   **SWidget**: Prefix with `S` (Slate widgets).
*   **Structs**: Prefix with `F` (e.g., `FVector`).
*   **Enums**: Prefix with `E` (e.g., `EWeaponState`).
*   **Interfaces**: Prefix with `I` (e.g., `IInteractable`).
*   **Booleans**: Prefix with `b` (e.g., `bIsDead`).

## Common Patterns

### 1. Robust Component Lookup
Avoid `GetComponentByClass` in `Tick`. Do it in `PostInitializeComponents` or `BeginPlay`.

```cpp
void AMyCharacter::PostInitializeComponents() {
    Super::PostInitializeComponents();
    HealthComp = FindComponentByClass<UHealthComponent>();
    check(HealthComp); // Fail hard in dev if missing
}
```

### 2. Interface Implementation
Use interfaces to decouple systems (e.g., Interaction system).

```cpp
// Interface call check
if (TargetActor->Implements<UInteractable>()) {
    IInteractable::Execute_OnInteract(TargetActor, this);
}
```

### 3. Async Loading (Soft References)
Avoid hard references (`UPROPERTY(EditDefaultsOnly) TSubclassOf<AActor>`) for massive assets which force load orders. Use `TSoftClassPtr` or `TSoftObjectPtr`.

```cpp
UPROPERTY(EditAnywhere, BlueprintReadWrite)
TSoftClassPtr<AWeapon> WeaponClassToLoad;

void AMyCharacter::Equip() {
    if (WeaponClassToLoad.IsPending()) {
        WeaponClassToLoad.LoadSynchronous(); // Or use StreamableManager for async
    }
}
```

## Debugging

*   **Logging**: Use `UE_LOG` with custom categories.
    ```cpp
    DEFINE_LOG_CATEGORY_STATIC(LogMyGame, Log, All);
    UE_LOG(LogMyGame, Warning, TEXT("Health is low: %f"), CurrentHealth);
    ```
*   **Screen Messages**:
    ```cpp
    if (GEngine) GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("Died!"));
    ```
*   **Visual Logger**: extremely useful for AI debugging. Implement `IVisualLoggerDebugSnapshotInterface`.

## Checklist before PR

- [ ] Does this Actor need to Tick? Can it be a Timer?
- [ ] Are all `UObject*` members wrapped in `UPROPERTY`?
- [ ] Are hard references (TSubclassOf) causing load chains? Can they be Soft Ptrs?
- [ ] Did you clean up verified delegates in `EndPlay`?

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.