---
name: python
description: "Language-specific super-code guidelines for python."
risk: safe
source: community
date_added: "2026-06-16"
---
# Python: Idiomatic Efficiency Reference

## When to Use
- Use this skill when the task matches this description: Language-specific super-code guidelines for python.

## Table of Contents
1. [Comprehensions & Generators](#comprehensions)
2. [Unpacking & Destructuring](#unpacking)
3. [Built-ins & stdlib](#builtins)
4. [Functions & Defaults](#functions)
5. [Classes & Dataclasses](#classes)
6. [Error Handling](#errors)
7. [Type Hints](#types)
8. [Anti-patterns specific to Python](#antipatterns)

---

## 1. Comprehensions & Generators {#comprehensions}

```python
# ❌ Imperative accumulation
result = []
for item in items:
    if item.active:
        result.append(item.name.upper())

# ✅
result = [item.name.upper() for item in items if item.active]
```

```python
# ❌ Dict built in a loop
d = {}
for k, v in pairs:
    d[k] = v

# ✅
d = dict(pairs)
# or
d = {k: v for k, v in pairs}
```

```python
# ❌ Generator converted to list unnecessarily
total = sum(list(x * 2 for x in nums))

# ✅ — generator expression works directly in sum()
total = sum(x * 2 for x in nums)
```

**Use generator expressions (not list comprehensions) when the result is consumed once and not stored.**

---

## 2. Unpacking & Destructuring {#unpacking}

```python
# ❌ Index access
first = items[0]
rest = items[1:]

# ✅
first, *rest = items
```

```python
# ❌ Temporary variable for swap
tmp = a
a = b
b = tmp

# ✅
a, b = b, a
```

```python
# ❌ items() with separate indexing
for i in range(len(items)):
    print(i, items[i])

# ✅
for i, item in enumerate(items):
    print(i, item)
```

```python
# ❌ zip with separate index
for i in range(len(a)):
    process(a[i], b[i])

# ✅
for x, y in zip(a, b):
    process(x, y)
```

---

## 3. Built-ins & stdlib {#builtins}

```python
# ❌ Manual max search
max_val = items[0]
for item in items[1:]:
    if item > max_val:
        max_val = item

# ✅
max_val = max(items)
```

```python
# ❌ Manual grouping
from collections import defaultdict
groups = defaultdict(list)
for item in items:
    groups[item.category].append(item)

# ✅ — same thing, just be explicit about defaultdict; it IS the right tool
# (this example is already correct — don't replace defaultdict with a loop)
```

```python
# ❌ Manual sentinel for dict default
if key in d:
    val = d[key]
else:
    val = default

# ✅
val = d.get(key, default)
```

```python
# ❌ Rolling your own counter
counts = {}
for item in items:
    counts[item] = counts.get(item, 0) + 1

# ✅
from collections import Counter
counts = Counter(items)
```

**Use `itertools` (chain, islice, groupby, product) before writing nested loops for combinatorial or streaming logic.**

---

## 4. Functions & Defaults {#functions}

```python
# ❌ Mutable default argument (bug, not just style)
def append_to(item, lst=[]):
    lst.append(item)
    return lst

# ✅
def append_to(item, lst=None):
    if lst is None:
        lst = []
    lst.append(item)
    return lst
```

```python
# ❌ Positional args for everything when keyword clarity helps
create_user("Alice", True, False, 30)

# ✅ — use keyword args at call site for boolean/ambiguous params
create_user("Alice", is_admin=True, is_active=False, age=30)
```

```python
# ❌ Long function doing multiple things
def process_and_save(data):
    # 40 lines of transform
    # 20 lines of DB write
    ...

# ✅ — split only if each part is reused OR independently testable
def _transform(data): ...
def _save(record): ...
def process_and_save(data): _save(_transform(data))
```

---

## 5. Classes & Dataclasses {#classes}

```python
# ❌ Manual __init__ for data holders
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

# ✅
from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float
```

```python
# ❌ Class just to hold a namespace of functions
class MathUtils:
    @staticmethod
    def add(a, b): return a + b

# ✅ — module-level functions; classes for state + behavior
def add(a, b): return a + b
```

```python
# ❌ __repr__ written manually when dataclass gives it free
# (see above — use @dataclass)
```

**Use `@dataclass(frozen=True)` for immutable value objects. Use `NamedTuple` when you need tuple unpacking.**

---

## 6. Error Handling {#errors}

```python
# ❌ Bare except
try:
    risky()
except:
    pass

# ✅ — catch the specific exception; don't swallow silently
try:
    risky()
except ValueError as e:
    logger.warning("Invalid value: %s", e)
```

```python
# ❌ LBYL (look before you leap) when EAFP is cleaner
if os.path.exists(path):
    with open(path) as f:
        data = f.read()

# ✅ (EAFP)
try:
    with open(path) as f:
        data = f.read()
except FileNotFoundError:
    data = None
```

```python
# ❌ Re-raising with raise e (loses traceback)
except Exception as e:
    raise e

# ✅
except Exception:
    raise  # bare raise preserves original traceback
```

---

## 7. Type Hints {#types}

```python
# ❌ Overly verbose Union syntax (Python <3.10 style in new code)
from typing import Optional, Union
def f(x: Optional[int]) -> Union[str, None]: ...

# ✅ (Python 3.10+)
def f(x: int | None) -> str | None: ...
```

```python
# ❌ Any where a TypeVar or Protocol would be informative
from typing import Any
def first(lst: list[Any]) -> Any: ...

# ✅
from typing import TypeVar
T = TypeVar("T")
def first(lst: list[T]) -> T: ...
```

**Don't add type hints to every local variable — annotate function signatures and class fields; leave obvious locals inferred.**

---

## 8. Anti-patterns specific to Python {#antipatterns}

| Anti-pattern | Preferred |
|---|---|
| `len(lst) == 0` | `not lst` |
| `if x == True:` | `if x:` |
| `if x == None:` | `if x is None:` |
| `range(len(lst))` for iteration | `enumerate(lst)` |
| String concatenation in a loop | `"".join(parts)` |
| `import *` | explicit imports |
| Catching `Exception` to log and re-raise | bare `raise` or let it propagate |
| `print()` for debug output | `logging.debug()` |
| `os.path.join` (Python 3.4+) | `pathlib.Path / "subpath"` |
| Manual `__eq__` + `__hash__` on value objects | `@dataclass(eq=True, frozen=True)` |

## Limitations
- These are language-specific guidelines and do not cover overall architectural decisions.
- Over-compression might reduce readability; apply judgement.


---
name: python-development
description: "You are a Python project architecture expert specializing in scaffolding production-ready Python applications. Generate complete project structures with modern tooling (uv, FastAPI, Django), type hint (Alias for python-development-python-scaffold)"
risk: critical
source: "alias"
date_added: "2026-06-02"
---

# Python Development

> **This is an alias.** The canonical skill is **`python-development-python-scaffold`**.

This skill redirects to `python-development-python-scaffold`. Load it from the vault:

`skill-libraries/development/python-development-python-scaffold/SKILL.md`

## When to Use
- Use this skill when the task matches this description: You are a Python project architecture expert specializing in scaffolding production-ready Python applications. Generate complete project structures with modern tooling (uv, FastAPI, Django), type hint (Alias for python-development-python-scaffold).

## Why this alias exists

Users commonly search for `python-development` but the full skill name in this collection is `python-development-python-scaffold`. This alias ensures discoverability.

## 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.

## Examples
```text
Use @python-development for this task: You are a Python project architecture expert specializing in scaffolding production-ready Python applications. Generate complete project structures with modern tooling (uv, FastAPI, Django), type hint (Alias for python-development-python-scaffold).

Apply the skill to my current work and walk me through the safest next steps,
key checks, and the concrete output I should produce.
```


---
name: python-development-python-scaffold
description: "You are a Python project architecture expert specializing in scaffolding production-ready Python applications. Generate complete project structures with modern tooling (uv, FastAPI, Django), type hint"
risk: critical
source: community
date_added: "2026-02-27"
---

# Python Project Scaffolding

You are a Python project architecture expert specializing in scaffolding production-ready Python applications. Generate complete project structures with modern tooling (uv, FastAPI, Django), type hints, testing setup, and configuration following current best practices.

## Use this skill when

- Working on python project scaffolding tasks or workflows
- Needing guidance, best practices, or checklists for python project scaffolding

## Do not use this skill when

- The task is unrelated to python project scaffolding
- You need a different domain or tool outside this scope

## Context

The user needs automated Python project scaffolding that creates consistent, type-safe applications with proper structure, dependency management, testing, and tooling. Focus on modern Python patterns and scalable architecture.

## Requirements

$ARGUMENTS

## Instructions

### 1. Analyze Project Type

Determine the project type from user requirements:
- **FastAPI**: REST APIs, microservices, async applications
- **Django**: Full-stack web applications, admin panels, ORM-heavy projects
- **Library**: Reusable packages, utilities, tools
- **CLI**: Command-line tools, automation scripts
- **Generic**: Standard Python applications

### 2. Initialize Project with uv

```bash
# Create new project with uv
uv init <project-name>
cd <project-name>

# Initialize git repository
git init
echo ".venv/" >> .gitignore
echo "*.pyc" >> .gitignore
echo "__pycache__/" >> .gitignore
echo ".pytest_cache/" >> .gitignore
echo ".ruff_cache/" >> .gitignore

# Create virtual environment
uv venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
```

### 3. Generate FastAPI Project Structure

```
fastapi-project/
├── pyproject.toml
├── README.md
├── .gitignore
├── .env.example
├── src/
│   └── project_name/
│       ├── __init__.py
│       ├── main.py
│       ├── config.py
│       ├── api/
│       │   ├── __init__.py
│       │   ├── deps.py
│       │   ├── v1/
│       │   │   ├── __init__.py
│       │   │   ├── endpoints/
│       │   │   │   ├── __init__.py
│       │   │   │   ├── users.py
│       │   │   │   └── health.py
│       │   │   └── router.py
│       ├── core/
│       │   ├── __init__.py
│       │   ├── security.py
│       │   └── database.py
│       ├── models/
│       │   ├── __init__.py
│       │   └── user.py
│       ├── schemas/
│       │   ├── __init__.py
│       │   └── user.py
│       └── services/
│           ├── __init__.py
│           └── user_service.py
└── tests/
    ├── __init__.py
    ├── conftest.py
    └── api/
        ├── __init__.py
        └── test_users.py
```

**pyproject.toml**:
```toml
[project]
name = "project-name"
version = "0.1.0"
description = "FastAPI project description"
requires-python = ">=3.11"
dependencies = [
    "fastapi>=0.110.0",
    "uvicorn[standard]>=0.27.0",
    "pydantic>=2.6.0",
    "pydantic-settings>=2.1.0",
    "sqlalchemy>=2.0.0",
    "alembic>=1.13.0",
]

[project.optional-dependencies]
dev = [
    "pytest>=8.0.0",
    "pytest-asyncio>=0.23.0",
    "httpx>=0.26.0",
    "ruff>=0.2.0",
]

[tool.ruff]
line-length = 100
target-version = "py311"

[tool.ruff.lint]
select = ["E", "F", "I", "N", "W", "UP"]

[tool.pytest.ini_options]
testpaths = ["tests"]
asyncio_mode = "auto"
```

**src/project_name/main.py**:
```python
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from .api.v1.router import api_router
from .config import settings

app = FastAPI(
    title=settings.PROJECT_NAME,
    version=settings.VERSION,
    openapi_url=f"{settings.API_V1_PREFIX}/openapi.json",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(api_router, prefix=settings.API_V1_PREFIX)

@app.get("/health")
async def health_check() -> dict[str, str]:
    return {"status": "healthy"}
```

### 4. Generate Django Project Structure

```bash
# Install Django with uv
uv add django django-environ django-debug-toolbar

# Create Django project
django-admin startproject config .
python manage.py startapp core
```

**pyproject.toml for Django**:
```toml
[project]
name = "django-project"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
    "django>=5.0.0",
    "django-environ>=0.11.0",
    "psycopg[binary]>=3.1.0",
    "gunicorn>=21.2.0",
]

[project.optional-dependencies]
dev = [
    "django-debug-toolbar>=4.3.0",
    "pytest-django>=4.8.0",
    "ruff>=0.2.0",
]
```

### 5. Generate Python Library Structure

```
library-name/
├── pyproject.toml
├── README.md
├── LICENSE
├── src/
│   └── library_name/
│       ├── __init__.py
│       ├── py.typed
│       └── core.py
└── tests/
    ├── __init__.py
    └── test_core.py
```

**pyproject.toml for Library**:
```toml
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "library-name"
version = "0.1.0"
description = "Library description"
readme = "README.md"
requires-python = ">=3.11"
license = {text = "MIT"}
authors = [
    {name = "Your Name", email = "email@example.com"}
]
classifiers = [
    "Programming Language :: Python :: 3",
    "License :: OSI Approved :: MIT License",
]
dependencies = []

[project.optional-dependencies]
dev = ["pytest>=8.0.0", "ruff>=0.2.0", "mypy>=1.8.0"]

[tool.hatch.build.targets.wheel]
packages = ["src/library_name"]
```

### 6. Generate CLI Tool Structure

```python
# pyproject.toml
[project.scripts]
cli-name = "project_name.cli:main"

[project]
dependencies = [
    "typer>=0.9.0",
    "rich>=13.7.0",
]
```

**src/project_name/cli.py**:
```python
import typer
from rich.console import Console

app = typer.Typer()
console = Console()

@app.command()
def hello(name: str = typer.Option(..., "--name", "-n", help="Your name")):
    """Greet someone"""
    console.print(f"[bold green]Hello {name}![/bold green]")

def main():
    app()
```

### 7. Configure Development Tools

**.env.example**:
```env
# Application
PROJECT_NAME="Project Name"
VERSION="0.1.0"
DEBUG=True

# API
API_V1_PREFIX="/api/v1"
ALLOWED_ORIGINS=["http://localhost:3000"]

# Database
DATABASE_URL="postgresql://user:pass@localhost:5432/dbname"

# Security
SECRET_KEY="your-secret-key-here"
```

**Makefile**:
```makefile
.PHONY: install dev test lint format clean

install:
	uv sync

dev:
	uv run uvicorn src.project_name.main:app --reload

test:
	uv run pytest -v

lint:
	uv run ruff check .

format:
	uv run ruff format .

clean:
	find . -type d -name __pycache__ -exec rm -rf {} +
	find . -type f -name "*.pyc" -delete
	rm -rf .pytest_cache .ruff_cache
```

## Output Format

1. **Project Structure**: Complete directory tree with all necessary files
2. **Configuration**: pyproject.toml with dependencies and tool settings
3. **Entry Point**: Main application file (main.py, cli.py, etc.)
4. **Tests**: Test structure with pytest configuration
5. **Documentation**: README with setup and usage instructions
6. **Development Tools**: Makefile, .env.example, .gitignore

Focus on creating production-ready Python projects with modern tooling, type safety, and comprehensive testing setup.

## 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: python-fastapi-development
description: "Python FastAPI backend development with async patterns, SQLAlchemy, Pydantic, authentication, and production API patterns."
category: granular-workflow-bundle
risk: safe
source: personal
date_added: "2026-02-27"
---

# Python/FastAPI Development Workflow

## Overview

Specialized workflow for building production-ready Python backends with FastAPI, featuring async patterns, SQLAlchemy ORM, Pydantic validation, and comprehensive API patterns.

## When to Use This Workflow

Use this workflow when:
- Building new REST APIs with FastAPI
- Creating async Python backends
- Implementing database integration with SQLAlchemy
- Setting up API authentication
- Developing microservices

## Workflow Phases

### Phase 1: Project Setup

#### Skills to Invoke
- `app-builder` - Application scaffolding
- `python-development-python-scaffold` - Python scaffolding
- `fastapi-templates` - FastAPI templates
- `uv-package-manager` - Package management

#### Actions
1. Set up Python environment (uv/poetry)
2. Create project structure
3. Configure FastAPI app
4. Set up logging
5. Configure environment variables

#### Copy-Paste Prompts
```
Use @fastapi-templates to scaffold a new FastAPI project
```

```
Use @python-development-python-scaffold to set up Python project structure
```

### Phase 2: Database Setup

#### Skills to Invoke
- `prisma-expert` - Prisma ORM (alternative)
- `database-design` - Schema design
- `postgresql` - PostgreSQL setup
- `pydantic-models-py` - Pydantic models

#### Actions
1. Design database schema
2. Set up SQLAlchemy models
3. Create database connection
4. Configure migrations (Alembic)
5. Set up session management

#### Copy-Paste Prompts
```
Use @database-design to design PostgreSQL schema
```

```
Use @pydantic-models-py to create Pydantic models for API
```

### Phase 3: API Routes

#### Skills to Invoke
- `fastapi-router-py` - FastAPI routers
- `api-design-principles` - API design
- `api-patterns` - API patterns

#### Actions
1. Design API endpoints
2. Create API routers
3. Implement CRUD operations
4. Add request validation
5. Configure response models

#### Copy-Paste Prompts
```
Use @fastapi-router-py to create API endpoints with CRUD operations
```

```
Use @api-design-principles to design RESTful API
```

### Phase 4: Authentication

#### Skills to Invoke
- `auth-implementation-patterns` - Authentication
- `api-security-best-practices` - API security

#### Actions
1. Choose auth strategy (JWT, OAuth2)
2. Implement user registration
3. Set up login endpoints
4. Create auth middleware
5. Add password hashing

#### Copy-Paste Prompts
```
Use @auth-implementation-patterns to implement JWT authentication
```

### Phase 5: Error Handling

#### Skills to Invoke
- `fastapi-pro` - FastAPI patterns
- `error-handling-patterns` - Error handling

#### Actions
1. Create custom exceptions
2. Set up exception handlers
3. Implement error responses
4. Add request logging
5. Configure error tracking

#### Copy-Paste Prompts
```
Use @fastapi-pro to implement comprehensive error handling
```

### Phase 6: Testing

#### Skills to Invoke
- `python-testing-patterns` - pytest testing
- `api-testing-observability-api-mock` - API testing

#### Actions
1. Set up pytest
2. Create test fixtures
3. Write unit tests
4. Implement integration tests
5. Configure test database

#### Copy-Paste Prompts
```
Use @python-testing-patterns to write pytest tests for FastAPI
```

### Phase 7: Documentation

#### Skills to Invoke
- `api-documenter` - API documentation
- `openapi-spec-generation` - OpenAPI specs

#### Actions
1. Configure OpenAPI schema
2. Add endpoint documentation
3. Create usage examples
4. Set up API versioning
5. Generate API docs

#### Copy-Paste Prompts
```
Use @api-documenter to generate comprehensive API documentation
```

### Phase 8: Deployment

#### Skills to Invoke
- `deployment-engineer` - Deployment
- `docker-expert` - Containerization

#### Actions
1. Create Dockerfile
2. Set up docker-compose
3. Configure production settings
4. Set up reverse proxy
5. Deploy to cloud

#### Copy-Paste Prompts
```
Use @docker-expert to containerize FastAPI application
```

## Technology Stack

| Category | Technology |
|----------|------------|
| Framework | FastAPI |
| Language | Python 3.11+ |
| ORM | SQLAlchemy 2.0 |
| Validation | Pydantic v2 |
| Database | PostgreSQL |
| Migrations | Alembic |
| Auth | JWT, OAuth2 |
| Testing | pytest |

## Quality Gates

- [ ] All tests passing (>80% coverage)
- [ ] Type checking passes (mypy)
- [ ] Linting clean (ruff, black)
- [ ] API documentation complete
- [ ] Security scan passed
- [ ] Performance benchmarks met

## Related Workflow Bundles

- `development` - General development
- `database` - Database operations
- `security-audit` - Security testing
- `api-development` - API 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: python-packaging
description: "Comprehensive guide to creating, structuring, and distributing Python packages using modern packaging tools, pyproject.toml, and publishing to PyPI."
risk: safe
source: community
date_added: "2026-02-27"
---

# Python Packaging

Comprehensive guide to creating, structuring, and distributing Python packages using modern packaging tools, pyproject.toml, and publishing to PyPI.

## Use this skill when

- Creating Python libraries for distribution
- Building command-line tools with entry points
- Publishing packages to PyPI or private repositories
- Setting up Python project structure
- Creating installable packages with dependencies
- Building wheels and source distributions
- Versioning and releasing Python packages
- Creating namespace packages
- Implementing package metadata and classifiers

## Do not use this skill when

- The task is unrelated to python packaging
- 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: python-patterns
description: "Python development principles and decision-making. Framework selection, async patterns, type hints, project structure. Teaches thinking, not copying."
risk: critical
source: community
date_added: "2026-02-27"
---

# Python Patterns

> Python development principles and decision-making for 2025.
> **Learn to THINK, not memorize patterns.**

## When to Use
Use this skill when making Python architecture decisions, choosing frameworks, designing async patterns, or structuring Python projects.

---

## ⚠ How to Use This Skill

This skill teaches **decision-making principles**, not fixed code to copy.

- ASK user for framework preference when unclear
- Choose async vs sync based on CONTEXT
- Don't default to same framework every time

---

## 1. Framework Selection (2025)

### Decision Tree

```
What are you building?
│
├── API-first / Microservices
│   └── FastAPI (async, modern, fast)
│
├── Full-stack web / CMS / Admin
│   └── Django (batteries-included)
│
├── Simple / Script / Learning
│   └── Flask (minimal, flexible)
│
├── AI/ML API serving
│   └── FastAPI (Pydantic, async, uvicorn)
│
└── Background workers
    └── Celery + any framework
```

### Comparison Principles

| Factor | FastAPI | Django | Flask |
|--------|---------|--------|-------|
| **Best for** | APIs, microservices | Full-stack, CMS | Simple, learning |
| **Async** | Native | Django 5.0+ | Via extensions |
| **Admin** | Manual | Built-in | Via extensions |
| **ORM** | Choose your own | Django ORM | Choose your own |
| **Learning curve** | Low | Medium | Low |

### Selection Questions to Ask:
1. Is this API-only or full-stack?
2. Need admin interface?
3. Team familiar with async?
4. Existing infrastructure?

---

## 2. Async vs Sync Decision

### When to Use Async

```
async def is better when:
├── I/O-bound operations (database, HTTP, file)
├── Many concurrent connections
├── Real-time features
├── Microservices communication
└── FastAPI/Starlette/Django ASGI

def (sync) is better when:
├── CPU-bound operations
├── Simple scripts
├── Legacy codebase
├── Team unfamiliar with async
└── Blocking libraries (no async version)
```

### The Golden Rule

```
I/O-bound → async (waiting for external)
CPU-bound → sync + multiprocessing (computing)

Don't:
├── Mix sync and async carelessly
├── Use sync libraries in async code
└── Force async for CPU work
```

### Async Library Selection

| Need | Async Library |
|------|---------------|
| HTTP client | httpx |
| PostgreSQL | asyncpg |
| Redis | aioredis / redis-py async |
| File I/O | aiofiles |
| Database ORM | SQLAlchemy 2.0 async, Tortoise |

---

## 3. Type Hints Strategy

### When to Type

```
Always type:
├── Function parameters
├── Return types
├── Class attributes
├── Public APIs

Can skip:
├── Local variables (let inference work)
├── One-off scripts
├── Tests (usually)
```

### Common Type Patterns

```python
# These are patterns, understand them:

# Optional → might be None
from typing import Optional
def find_user(id: int) -> Optional[User]: ...

# Union → one of multiple types
def process(data: str | dict) -> None: ...

# Generic collections
def get_items() -> list[Item]: ...
def get_mapping() -> dict[str, int]: ...

# Callable
from typing import Callable
def apply(fn: Callable[[int], str]) -> str: ...
```

### Pydantic for Validation

```
When to use Pydantic:
├── API request/response models
├── Configuration/settings
├── Data validation
├── Serialization

Benefits:
├── Runtime validation
├── Auto-generated JSON schema
├── Works with FastAPI natively
└── Clear error messages
```

---

## 4. Project Structure Principles

### Structure Selection

```
Small project / Script:
├── main.py
├── utils.py
└── requirements.txt

Medium API:
├── app/
│   ├── __init__.py
│   ├── main.py
│   ├── models/
│   ├── routes/
│   ├── services/
│   └── schemas/
├── tests/
└── pyproject.toml

Large application:
├── src/
│   └── myapp/
│       ├── core/
│       ├── api/
│       ├── services/
│       ├── models/
│       └── ...
├── tests/
└── pyproject.toml
```

### FastAPI Structure Principles

```
Organize by feature or layer:

By layer:
├── routes/ (API endpoints)
├── services/ (business logic)
├── models/ (database models)
├── schemas/ (Pydantic models)
└── dependencies/ (shared deps)

By feature:
├── users/
│   ├── routes.py
│   ├── service.py
│   └── schemas.py
└── products/
    └── ...
```

---

## 5. Django Principles (2025)

### Django Async (Django 5.0+)

```
Django supports async:
├── Async views
├── Async middleware
├── Async ORM (limited)
└── ASGI deployment

When to use async in Django:
├── External API calls
├── WebSocket (Channels)
├── High-concurrency views
└── Background task triggering
```

### Django Best Practices

```
Model design:
├── Fat models, thin views
├── Use managers for common queries
├── Abstract base classes for shared fields

Views:
├── Class-based for complex CRUD
├── Function-based for simple endpoints
├── Use viewsets with DRF

Queries:
├── select_related() for FKs
├── prefetch_related() for M2M
├── Avoid N+1 queries
└── Use .only() for specific fields
```

---

## 6. FastAPI Principles

### async def vs def in FastAPI

```
Use async def when:
├── Using async database drivers
├── Making async HTTP calls
├── I/O-bound operations
└── Want to handle concurrency

Use def when:
├── Blocking operations
├── Sync database drivers
├── CPU-bound work
└── FastAPI runs in threadpool automatically
```

### Dependency Injection

```
Use dependencies for:
├── Database sessions
├── Current user / Auth
├── Configuration
├── Shared resources

Benefits:
├── Testability (mock dependencies)
├── Clean separation
├── Automatic cleanup (yield)
```

### Pydantic v2 Integration

```python
# FastAPI + Pydantic are tightly integrated:

# Request validation
@app.post("/users")
async def create(user: UserCreate) -> UserResponse:
    # user is already validated
    ...

# Response serialization
# Return type becomes response schema
```

---

## 7. Background Tasks

### Selection Guide

| Solution | Best For |
|----------|----------|
| **BackgroundTasks** | Simple, in-process tasks |
| **Celery** | Distributed, complex workflows |
| **ARQ** | Async, Redis-based |
| **RQ** | Simple Redis queue |
| **Dramatiq** | Actor-based, simpler than Celery |

### When to Use Each

```
FastAPI BackgroundTasks:
├── Quick operations
├── No persistence needed
├── Fire-and-forget
└── Same process

Celery/ARQ:
├── Long-running tasks
├── Need retry logic
├── Distributed workers
├── Persistent queue
└── Complex workflows
```

---

## 8. Error Handling Principles

### Exception Strategy

```
In FastAPI:
├── Create custom exception classes
├── Register exception handlers
├── Return consistent error format
└── Log without exposing internals

Pattern:
├── Raise domain exceptions in services
├── Catch and transform in handlers
└── Client gets clean error response
```

### Error Response Philosophy

```
Include:
├── Error code (programmatic)
├── Message (human readable)
├── Details (field-level when applicable)
└── NOT stack traces (security)
```

---

## 9. Testing Principles

### Testing Strategy

| Type | Purpose | Tools |
|------|---------|-------|
| **Unit** | Business logic | pytest |
| **Integration** | API endpoints | pytest + httpx/TestClient |
| **E2E** | Full workflows | pytest + DB |

### Async Testing

```python
# Use pytest-asyncio for async tests

import pytest
from httpx import AsyncClient

@pytest.mark.asyncio
async def test_endpoint():
    async with AsyncClient(app=app, base_url="http://test") as client:
        response = await client.get("/users")
        assert response.status_code == 200
```

### Fixtures Strategy

```
Common fixtures:
├── db_session → Database connection
├── client → Test client
├── authenticated_user → User with token
└── sample_data → Test data setup
```

---

## 10. Decision Checklist

Before implementing:

- [ ] **Asked user about framework preference?**
- [ ] **Chosen framework for THIS context?** (not just default)
- [ ] **Decided async vs sync?**
- [ ] **Planned type hint strategy?**
- [ ] **Defined project structure?**
- [ ] **Planned error handling?**
- [ ] **Considered background tasks?**

---

## 11. Anti-Patterns to Avoid

### ❌ DON'T:
- Default to Django for simple APIs (FastAPI may be better)
- Use sync libraries in async code
- Skip type hints for public APIs
- Put business logic in routes/views
- Ignore N+1 queries
- Mix async and sync carelessly

### ✅ DO:
- Choose framework based on context
- Ask about async requirements
- Use Pydantic for validation
- Separate concerns (routes → services → repos)
- Test critical paths

---

> **Remember**: Python patterns are about decision-making for YOUR specific context. Don't copy code—think about what serves your application best.

## 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: python-performance-optimization
description: "Profile and optimize Python code using cProfile, memory profilers, and performance best practices. Use when debugging slow Python code, optimizing bottlenecks, or improving application performance."
risk: safe
source: community
date_added: "2026-02-27"
---

# Python Performance Optimization

Comprehensive guide to profiling, analyzing, and optimizing Python code for better performance, including CPU profiling, memory optimization, and implementation best practices.

## Use this skill when

- Identifying performance bottlenecks in Python applications
- Reducing application latency and response times
- Optimizing CPU-intensive operations
- Reducing memory consumption and memory leaks
- Improving database query performance
- Optimizing I/O operations
- Speeding up data processing pipelines
- Implementing high-performance algorithms
- Profiling production applications

## Do not use this skill when

- The task is unrelated to python performance optimization
- 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: python-pptx-generator
description: "Generate complete Python scripts that build polished PowerPoint decks with python-pptx and real slide content."
category: development
risk: safe
source: self
source_type: self
date_added: "2026-04-06"
author: spideyashith
tags: [python, powerpoint, python-pptx, presentations, slide-decks]
tools: [claude, cursor, gemini, codex]
---

# Python PPTX Generator

## Overview

Use this skill when the user wants a ready-to-run Python script that creates a PowerPoint presentation with `python-pptx`.
It focuses on turning a topic brief into a complete slide deck script with real slide content, sensible structure, and a working save step.

## When to Use This Skill

- Use when the user wants a Python script that generates a `.pptx` file automatically
- Use when the user needs slide content drafted and encoded directly into `python-pptx`
- Use when the user wants a quick presentation generator for demos, classes, or internal briefings

## How It Works

### Step 1: Collect the Deck Brief

Ask for the topic, audience, tone, and target number of slides if the request does not already include them.
If constraints are missing, pick conservative defaults and state them in the generated script comments.

### Step 2: Plan the Narrative Arc

Outline the deck before writing code:

1. Title slide
2. Agenda or context
3. Core teaching or business points
4. Summary or next steps

Keep the slide count realistic for the requested audience and avoid filler slides.

### Step 3: Generate the Python Script

Write a complete script that:

- imports `Presentation` from `python-pptx`
- creates the deck
- selects appropriate built-in layouts
- writes real titles and bullet points
- saves the file with a clear filename
- prints a success message after saving

### Step 4: Keep the Output Runnable

The final answer should be a Python code block that can run after installing `python-pptx`.
Avoid pseudocode, placeholders, or missing imports.

## Examples

### Example 1: Educational Deck

```text
User: Create a 5-slide presentation on the basics of machine learning for a high school class.
Output: A complete Python script that creates a title slide, overview, core concepts, examples, and recap.
```

### Example 2: Business Briefing

```text
User: Generate a 7-slide deck for sales leadership on Q2 pipeline risks and mitigation options.
Output: A python-pptx script with executive-friendly slide titles, concise bullets, and a final recommendations slide.
```

## Best Practices

- ✅ Use standard `python-pptx` layouts unless the user asks for custom positioning
- ✅ Write audience-appropriate bullet points instead of placeholders
- ✅ Save the output file explicitly in the script, for example `output.pptx`
- ✅ Keep slide titles short and the bullet hierarchy readable
- ❌ Do not return partial snippets that require the user to assemble the rest
- ❌ Do not invent unsupported styling APIs without checking `python-pptx` capabilities

## Security & Safety Notes

- Install `python-pptx` only in an environment you control, for example a local virtual environment
- If the user will run the script on a shared machine, choose a safe output path and avoid overwriting existing presentations without confirmation
- If the request includes proprietary or sensitive presentation content, keep it out of public examples and sample filenames

## Common Pitfalls

- **Problem:** The generated script uses placeholder text instead of real content
  **Solution:** Draft the narrative first, then turn each slide into specific titles and bullets

- **Problem:** The deck uses too many slides for the requested audience
  **Solution:** Compress the outline to the most important 4 to 8 slides unless the user explicitly wants a longer deck

- **Problem:** The script forgets to save or print a completion message
  **Solution:** Always end with `prs.save(...)` and a short success print

## Related Skills

- `@pptx-official` - Use when the task is about inspecting or editing existing PowerPoint files
- `@docx-official` - Use when the requested output should be a document instead of a slide deck

## 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: python-pro
description: Master Python 3.12+ with modern features, async programming, performance optimization, and production-ready practices. Expert in the latest Python ecosystem including uv, ruff, pydantic, and FastAPI.
risk: critical
source: community
date_added: '2026-02-27'
---
You are a Python expert specializing in modern Python 3.12+ development with cutting-edge tools and practices from the 2024/2025 ecosystem.

## Use this skill when

- Writing or reviewing Python 3.12+ codebases
- Implementing async workflows or performance optimizations
- Designing production-ready Python services or tooling

## Do not use this skill when

- You need guidance for a non-Python stack
- You only need basic syntax tutoring
- You cannot modify Python runtime or dependencies

## Instructions

1. Confirm runtime, dependencies, and performance targets.
2. Choose patterns (async, typing, tooling) that match requirements.
3. Implement and test with modern tooling.
4. Profile and tune for latency, memory, and correctness.

## Purpose
Expert Python developer mastering Python 3.12+ features, modern tooling, and production-ready development practices. Deep knowledge of the current Python ecosystem including package management with uv, code quality with ruff, and building high-performance applications with async patterns.

## Capabilities

### Modern Python Features
- Python 3.12+ features including improved error messages, performance optimizations, and type system enhancements
- Advanced async/await patterns with asyncio, aiohttp, and trio
- Context managers and the `with` statement for resource management
- Dataclasses, Pydantic models, and modern data validation
- Pattern matching (structural pattern matching) and match statements
- Type hints, generics, and Protocol typing for robust type safety
- Descriptors, metaclasses, and advanced object-oriented patterns
- Generator expressions, itertools, and memory-efficient data processing

### Modern Tooling & Development Environment
- Package management with uv (2024's fastest Python package manager)
- Code formatting and linting with ruff (replacing black, isort, flake8)
- Static type checking with mypy and pyright
- Project configuration with pyproject.toml (modern standard)
- Virtual environment management with venv, pipenv, or uv
- Pre-commit hooks for code quality automation
- Modern Python packaging and distribution practices
- Dependency management and lock files

### Testing & Quality Assurance
- Comprehensive testing with pytest and pytest plugins
- Property-based testing with Hypothesis
- Test fixtures, factories, and mock objects
- Coverage analysis with pytest-cov and coverage.py
- Performance testing and benchmarking with pytest-benchmark
- Integration testing and test databases
- Continuous integration with GitHub Actions
- Code quality metrics and static analysis

### Performance & Optimization
- Profiling with cProfile, py-spy, and memory_profiler
- Performance optimization techniques and bottleneck identification
- Async programming for I/O-bound operations
- Multiprocessing and concurrent.futures for CPU-bound tasks
- Memory optimization and garbage collection understanding
- Caching strategies with functools.lru_cache and external caches
- Database optimization with SQLAlchemy and async ORMs
- NumPy, Pandas optimization for data processing

### Web Development & APIs
- FastAPI for high-performance APIs with automatic documentation
- Django for full-featured web applications
- Flask for lightweight web services
- Pydantic for data validation and serialization
- SQLAlchemy 2.0+ with async support
- Background task processing with Celery and Redis
- WebSocket support with FastAPI and Django Channels
- Authentication and authorization patterns

### Data Science & Machine Learning
- NumPy and Pandas for data manipulation and analysis
- Matplotlib, Seaborn, and Plotly for data visualization
- Scikit-learn for machine learning workflows
- Jupyter notebooks and IPython for interactive development
- Data pipeline design and ETL processes
- Integration with modern ML libraries (PyTorch, TensorFlow)
- Data validation and quality assurance
- Performance optimization for large datasets

### DevOps & Production Deployment
- Docker containerization and multi-stage builds
- Kubernetes deployment and scaling strategies
- Cloud deployment (AWS, GCP, Azure) with Python services
- Monitoring and logging with structured logging and APM tools
- Configuration management and environment variables
- Security best practices and vulnerability scanning
- CI/CD pipelines and automated testing
- Performance monitoring and alerting

### Advanced Python Patterns
- Design patterns implementation (Singleton, Factory, Observer, etc.)
- SOLID principles in Python development
- Dependency injection and inversion of control
- Event-driven architecture and messaging patterns
- Functional programming concepts and tools
- Advanced decorators and context managers
- Metaprogramming and dynamic code generation
- Plugin architectures and extensible systems

## Behavioral Traits
- Follows PEP 8 and modern Python idioms consistently
- Prioritizes code readability and maintainability
- Uses type hints throughout for better code documentation
- Implements comprehensive error handling with custom exceptions
- Writes extensive tests with high coverage (>90%)
- Leverages Python's standard library before external dependencies
- Focuses on performance optimization when needed
- Documents code thoroughly with docstrings and examples
- Stays current with latest Python releases and ecosystem changes
- Emphasizes security and best practices in production code

## Knowledge Base
- Python 3.12+ language features and performance improvements
- Modern Python tooling ecosystem (uv, ruff, pyright)
- Current web framework best practices (FastAPI, Django 5.x)
- Async programming patterns and asyncio ecosystem
- Data science and machine learning Python stack
- Modern deployment and containerization strategies
- Python packaging and distribution best practices
- Security considerations and vulnerability prevention
- Performance profiling and optimization techniques
- Testing strategies and quality assurance practices

## Response Approach
1. **Analyze requirements** for modern Python best practices
2. **Suggest current tools and patterns** from the 2024/2025 ecosystem
3. **Provide production-ready code** with proper error handling and type hints
4. **Include comprehensive tests** with pytest and appropriate fixtures
5. **Consider performance implications** and suggest optimizations
6. **Document security considerations** and best practices
7. **Recommend modern tooling** for development workflow
8. **Include deployment strategies** when applicable

## Example Interactions
- "Help me migrate from pip to uv for package management"
- "Optimize this Python code for better async performance"
- "Design a FastAPI application with proper error handling and validation"
- "Set up a modern Python project with ruff, mypy, and pytest"
- "Implement a high-performance data processing pipeline"
- "Create a production-ready Dockerfile for a Python application"
- "Design a scalable background task system with Celery"
- "Implement modern authentication patterns in FastAPI"

## 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: python-testing-patterns
description: "Implement comprehensive testing strategies with pytest, fixtures, mocking, and test-driven development. Use when writing Python tests, setting up test suites, or implementing testing best practices."
risk: safe
source: community
date_added: "2026-02-27"
---

# Python Testing Patterns

Comprehensive guide to implementing robust testing strategies in Python using pytest, fixtures, mocking, parameterization, and test-driven development practices.

## Use this skill when

- Writing unit tests for Python code
- Setting up test suites and test infrastructure
- Implementing test-driven development (TDD)
- Creating integration tests for APIs and services
- Mocking external dependencies and services
- Testing async code and concurrent operations
- Setting up continuous testing in CI/CD
- Implementing property-based testing
- Testing database operations
- Debugging failing tests

## Do not use this skill when

- The task is unrelated to python testing 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: qiskit
description: "Qiskit is the world's most popular open-source quantum computing framework with 13M+ downloads. Build quantum circuits, optimize for hardware, execute on simulators or real quantum computers, and analyze results. Supports IBM Quantum (100+ qubit systems), IonQ, Amazon Braket, and other providers."
license: Apache-2.0 license
metadata:
    skill-author: K-Dense Inc.
risk: critical
source: community
---

# Qiskit

## When to Use
- You are building or optimizing quantum circuits with Qiskit for simulators or real hardware.
- You need IBM Quantum-style tooling for transpilation, execution, visualization, or algorithm libraries.
- You want guidance on moving from a simple circuit prototype to backend-aware execution.

## Overview

Qiskit is the world's most popular open-source quantum computing framework with 13M+ downloads. Build quantum circuits, optimize for hardware, execute on simulators or real quantum computers, and analyze results. Supports IBM Quantum (100+ qubit systems), IonQ, Amazon Braket, and other providers.

**Key Features:**
- 83x faster transpilation than competitors
- 29% fewer two-qubit gates in optimized circuits
- Backend-agnostic execution (local simulators or cloud hardware)
- Comprehensive algorithm libraries for optimization, chemistry, and ML

## Quick Start

### Installation

```bash
uv pip install qiskit
uv pip install "qiskit[visualization]" matplotlib
```

### First Circuit

```python
from qiskit import QuantumCircuit
from qiskit.primitives import StatevectorSampler

# Create Bell state (entangled qubits)
qc = QuantumCircuit(2)
qc.h(0)           # Hadamard on qubit 0
qc.cx(0, 1)       # CNOT from qubit 0 to 1
qc.measure_all()  # Measure both qubits

# Run locally
sampler = StatevectorSampler()
result = sampler.run([qc], shots=1024).result()
counts = result[0].data.meas.get_counts()
print(counts)  # {'00': ~512, '11': ~512}
```

### Visualization

```python
from qiskit.visualization import plot_histogram

qc.draw('mpl')           # Circuit diagram
plot_histogram(counts)   # Results histogram
```

## Core Capabilities

### 1. Setup and Installation
For detailed installation, authentication, and IBM Quantum account setup:
- **See `references/setup.md`**

Topics covered:
- Installation with uv
- Python environment setup
- IBM Quantum account and API token configuration
- Local vs. cloud execution

### 2. Building Quantum Circuits
For constructing quantum circuits with gates, measurements, and composition:
- **See `references/circuits.md`**

Topics covered:
- Creating circuits with QuantumCircuit
- Single-qubit gates (H, X, Y, Z, rotations, phase gates)
- Multi-qubit gates (CNOT, SWAP, Toffoli)
- Measurements and barriers
- Circuit composition and properties
- Parameterized circuits for variational algorithms

### 3. Primitives (Sampler and Estimator)
For executing quantum circuits and computing results:
- **See `references/primitives.md`**

Topics covered:
- **Sampler**: Get bitstring measurements and probability distributions
- **Estimator**: Compute expectation values of observables
- V2 interface (StatevectorSampler, StatevectorEstimator)
- IBM Quantum Runtime primitives for hardware
- Sessions and Batch modes
- Parameter binding

### 4. Transpilation and Optimization
For optimizing circuits and preparing for hardware execution:
- **See `references/transpilation.md`**

Topics covered:
- Why transpilation is necessary
- Optimization levels (0-3)
- Six transpilation stages (init, layout, routing, translation, optimization, scheduling)
- Advanced features (virtual permutation elision, gate cancellation)
- Common parameters (initial_layout, approximation_degree, seed)
- Best practices for efficient circuits

### 5. Visualization
For displaying circuits, results, and quantum states:
- **See `references/visualization.md`**

Topics covered:
- Circuit drawings (text, matplotlib, LaTeX)
- Result histograms
- Quantum state visualization (Bloch sphere, state city, QSphere)
- Backend topology and error maps
- Customization and styling
- Saving publication-quality figures

### 6. Hardware Backends
For running on simulators and real quantum computers:
- **See `references/backends.md`**

Topics covered:
- IBM Quantum backends and authentication
- Backend properties and status
- Running on real hardware with Runtime primitives
- Job management and queuing
- Session mode (iterative algorithms)
- Batch mode (parallel jobs)
- Local simulators (StatevectorSampler, Aer)
- Third-party providers (IonQ, Amazon Braket)
- Error mitigation strategies

### 7. Qiskit Patterns Workflow
For implementing the four-step quantum computing workflow:
- **See `references/patterns.md`**

Topics covered:
- **Map**: Translate problems to quantum circuits
- **Optimize**: Transpile for hardware
- **Execute**: Run with primitives
- **Post-process**: Extract and analyze results
- Complete VQE example
- Session vs. Batch execution
- Common workflow patterns

### 8. Quantum Algorithms and Applications
For implementing specific quantum algorithms:
- **See `references/algorithms.md`**

Topics covered:
- **Optimization**: VQE, QAOA, Grover's algorithm
- **Chemistry**: Molecular ground states, excited states, Hamiltonians
- **Machine Learning**: Quantum kernels, VQC, QNN
- **Algorithm libraries**: Qiskit Nature, Qiskit ML, Qiskit Optimization
- Physics simulations and benchmarking

## Workflow Decision Guide

**If you need to:**

- Install Qiskit or set up IBM Quantum account → `references/setup.md`
- Build a new quantum circuit → `references/circuits.md`
- Understand gates and circuit operations → `references/circuits.md`
- Run circuits and get measurements → `references/primitives.md`
- Compute expectation values → `references/primitives.md`
- Optimize circuits for hardware → `references/transpilation.md`
- Visualize circuits or results → `references/visualization.md`
- Execute on IBM Quantum hardware → `references/backends.md`
- Connect to third-party providers → `references/backends.md`
- Implement end-to-end quantum workflow → `references/patterns.md`
- Build specific algorithm (VQE, QAOA, etc.) → `references/algorithms.md`
- Solve chemistry or optimization problems → `references/algorithms.md`

## Best Practices

### Development Workflow

1. **Start with simulators**: Test locally before using hardware
   ```python
   from qiskit.primitives import StatevectorSampler
   sampler = StatevectorSampler()
   ```

2. **Always transpile**: Optimize circuits before execution
   ```python
   from qiskit import transpile
   qc_optimized = transpile(qc, backend=backend, optimization_level=3)
   ```

3. **Use appropriate primitives**:
   - Sampler for bitstrings (optimization algorithms)
   - Estimator for expectation values (chemistry, physics)

4. **Choose execution mode**:
   - Session: Iterative algorithms (VQE, QAOA)
   - Batch: Independent parallel jobs
   - Single job: One-off experiments

### Performance Optimization

- Use optimization_level=3 for production
- Minimize two-qubit gates (major error source)
- Test with noisy simulators before hardware
- Save and reuse transpiled circuits
- Monitor convergence in variational algorithms

### Hardware Execution

- Check backend status before submitting
- Use least_busy() for testing
- Save job IDs for later retrieval
- Apply error mitigation (resilience_level)
- Start with fewer shots, increase for final runs

## Common Patterns

### Pattern 1: Simple Circuit Execution

```python
from qiskit import QuantumCircuit, transpile
from qiskit.primitives import StatevectorSampler

qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()

sampler = StatevectorSampler()
result = sampler.run([qc], shots=1024).result()
counts = result[0].data.meas.get_counts()
```

### Pattern 2: Hardware Execution with Transpilation

```python
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2 as Sampler
from qiskit import transpile

service = QiskitRuntimeService()
backend = service.backend("ibm_brisbane")

qc_optimized = transpile(qc, backend=backend, optimization_level=3)

sampler = Sampler(backend)
job = sampler.run([qc_optimized], shots=1024)
result = job.result()
```

### Pattern 3: Variational Algorithm (VQE)

```python
from qiskit_ibm_runtime import Session, EstimatorV2 as Estimator
from scipy.optimize import minimize

with Session(backend=backend) as session:
    estimator = Estimator(session=session)

    def cost_function(params):
        bound_qc = ansatz.assign_parameters(params)
        qc_isa = transpile(bound_qc, backend=backend)
        result = estimator.run([(qc_isa, hamiltonian)]).result()
        return result[0].data.evs

    result = minimize(cost_function, initial_params, method='COBYLA')
```

## Additional Resources

- **Official Docs**: https://quantum.ibm.com/docs
- **Qiskit Textbook**: https://qiskit.org/learn
- **API Reference**: https://docs.quantum.ibm.com/api/qiskit
- **Patterns Guide**: https://quantum.cloud.ibm.com/docs/en/guides/intro-to-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: qoder-delegate
description: Delegate coding tasks to the Qoder CLI (`qodercli`) only when the user
  explicitly requests it, while the orchestrator retains review and landing responsibility.
risk: safe
category: agent-orchestration
source: https://github.com/amElnagdy/delegate-skills
source_repo: amElnagdy/delegate-skills
source_type: community
date_added: '2026-08-26'
license: MIT
license_source: https://github.com/amElnagdy/delegate-skills/blob/master/LICENSE
metadata:
  version: 0.5.0
---
# Qoder Delegate

## When to Use

- You want to delegate a bounded coding task to a separate `qoder` implementer (`Qoder`) and then review its diff yourself.
- The user explicitly asked for delegation to this implementer.

You are the **orchestrator**. Delegate one bounded coding task to a separate **implementer** - Qoder CLI -
then review what it produced and land it yourself. You write the brief and own the judgment; Qoder
edits the working tree in its session; you verify and commit.

The loop needs only shell and file access, so any comparable orchestrator can drive it.

## When NOT to use this

- The task is small enough to do inline; delegation overhead is not worth it.
- `qodercli` is not installed or authenticated.
- You want to write the code yourself or need only an interactive Qoder session.

## Prerequisites (check once)

```bash
command -v qodercli
qodercli --version
qodercli --list-models
```

If the binary is missing, install it from Qoder's
[official Quick Start](https://docs.qoder.com/en/cli/quick-start). Authenticate with `qodercli login`,
or set `QODER_PERSONAL_ACCESS_TOKEN` for automation. A successful `--list-models` confirms the current
account can return its live model catalog.

## Choose model and context window

Qoder's available models can change. If the human requests a model, use its exact current value from
`qodercli --list-models`; never invent or pin a catalog entry. Otherwise omit `--model` and let Qoder
use its current default.

`--context-window <n>` is optional. Pass a positive integer only when the human requests a size or the
task needs an explicit budget. Qoder applies it only to supported models; surface an unsupported
model/size error instead of silently choosing another value.

## The loop

Run these five steps per task. Steps 1, 4, and 5 require judgment; 2 and 3 are mechanical.

### 1. Write the brief

Qoder sees the brief plus what it can inspect in the workspace, not this chat. Include the goal,
current state, what to change, what to leave untouched, the project's **actual** gates, and a closing
report contract. Tell Qoder not to commit. Keep one task per brief. See
[references/writing-the-brief.md](references/writing-the-brief.md).

### 2. Dispatch

Use the bundled relay. It wraps Qoder's non-interactive `stream-json` mode and writes `result.json`.
`<skill-dir>` is the installed folder containing this `SKILL.md`.

```bash
node "<skill-dir>/scripts/relay.mjs" --brief brief.txt --cd /path/to/repo
# choose a live model:                 add --model "<value from qodercli --list-models>"
# request a supported context window: add --context-window 32768
# resume the latest session:          add --resume-last  # delta brief only
# resume a specific session:          add --resume <id>  # delta brief only
# see every option:                   node .../relay.mjs --help
```

Implementation runs default to Qoder's `auto` permission mode. The relay never bypasses permissions
unless the caller explicitly requests it, and it never commits. See
[references/dispatch-and-poll.md](references/dispatch-and-poll.md).

### 3. Wait for completion

The relay blocks until Qoder exits. Run it with the orchestrator's background-command facility, or
background it in the shell and wait for `result.json`. Completion means the process exited and the
file contains a `status`; do not trust a progress display.

A pre-run usage error exits 2 and writes no result. Missing `qodercli` exits 127 and writes
`status: "qoder_unavailable"` with installation guidance.

Native Windows relay launch is not yet verified; do not claim it until a native Windows smoke passes.

### 4. Review - do not trust the self-report

Treat Qoder's final message and gate outcomes as claims:

- Re-run the project's gates yourself.
- Read the diff against the brief, starting with `touchedFiles`.
- Check any `--add-dir` workspaces separately; their changes are not in the primary tree report.
- Run relevant guard skills if installed.
- Round-trip migrations and grep for dangling references after removals or renames.

See [references/review-and-land.md](references/review-and-land.md).

### 5. Land it

The implementer edits; **the orchestrator commits**. Commit only after the gates pass and the diff
holds. If rework is needed, send a delta brief with `--resume-last` or `--resume <id>`, then review
again.

## Permission model

Qoder print mode cannot show approval prompts. The relay defaults to `auto`, which makes
non-interactive allow/deny decisions. `default` can deny actions that would require a prompt;
`accept_edits` permits workspace edits but may deny shell actions; `dont_ask` fails closed; `plan`
maps to `default` plus Qoder's Plan work state; and `bypass_permissions` is for explicitly trusted
runs only.

Qoder falls back to `default` when a non-default mode is requested outside a trusted directory. Check
`actualPermissionMode` in `result.json`; no requested mode replaces diff review.

## Authorization model

Delegation is something the human opts into. Once they ask for it, landing verified, gate-passing work
is the contract. Two limits remain: **surface, do not absorb** (report Qoder's design decisions and
non-blocking deviations) and **stop for scope changes** (ask before expanding beyond the brief). See
[references/review-and-land.md](references/review-and-land.md).

## References

- [references/writing-the-brief.md](references/writing-the-brief.md) - brief structure, real gates,
  report contract, secrets, and delta briefs.
- [references/dispatch-and-poll.md](references/dispatch-and-poll.md) - flags, model/context controls,
  artifacts, result fields, sessions, and failure recovery.
- [references/review-and-land.md](references/review-and-land.md) - independent review, commit boundary,
  and rework.
- [references/multi-task-queues.md](references/multi-task-queues.md) - sequential queues, constraint
  carry-forward, progress tracking, and final coherence.

## Limitations

- Docs-only import — executable `scripts/relay.mjs` not included; see upstream for full runtime. Requires `qoder` CLI, Node 18+, git.
- Relay never commits — it only returns structured result JSON; you review and land the commit.

> Adapted from [amElnagdy/delegate-skills](https://github.com/amElnagdy/delegate-skills) (MIT) — docs-only, runtime not bundled.


---
name: quality-nonconformance
description: Codified expertise for quality control, non-conformance investigation, root cause analysis, corrective action, and supplier quality management in regulated manufacturing.
risk: safe
source: https://github.com/ai-evos/agent-skills
date_added: '2026-02-27'
---

## When to Use
Use this skill when investigating product defects or process deviations, performing root cause analysis (RCA), managing Corrective and Preventive Actions (CAPA), interpreting Statistical Process Control (SPC) data, or auditing supplier quality.

# Quality & Non-Conformance Management

## Role and Context

You are a senior quality engineer with 15+ years in regulated manufacturing environments — FDA 21 CFR 820 (medical devices), IATF 16949 (automotive), AS9100 (aerospace), and ISO 13485 (medical devices). You manage the full non-conformance lifecycle from incoming inspection through final disposition. Your systems include QMS (eQMS platforms like MasterControl, ETQ, Veeva), SPC software (Minitab, InfinityQS), ERP (SAP QM, Oracle Quality), CMM and metrology equipment, and supplier portals. You sit at the intersection of manufacturing, engineering, procurement, regulatory, and customer quality. Your judgment calls directly affect product safety, regulatory standing, production throughput, and supplier relationships.

## Core Knowledge

### NCR Lifecycle

Every non-conformance follows a controlled lifecycle. Skipping steps creates audit findings and regulatory risk:

- **Identification:** Anyone can initiate. Record: who found it, where (incoming, in-process, final, field), what standard/spec was violated, quantity affected, lot/batch traceability. Tag or quarantine nonconforming material immediately — no exceptions. Physical segregation with red-tag or hold-tag in a designated MRB area. Electronic hold in ERP to prevent inadvertent shipment.
- **Documentation:** NCR number assigned per your QMS numbering scheme. Link to part number, revision, PO/work order, specification clause violated, measurement data (actuals vs. tolerances), photographs, and inspector ID. For FDA-regulated products, records must satisfy 21 CFR 820.90; for automotive, IATF 16949 §8.7.
- **Investigation:** Determine scope — is this an isolated piece or a systemic lot issue? Check upstream and downstream: other lots from the same supplier shipment, other units from the same production run, WIP and finished goods inventory from the same period. Containment actions must happen before root cause analysis begins.
- **Disposition via MRB (Material Review Board):** The MRB typically includes quality, engineering, and manufacturing representatives. For aerospace (AS9100), the customer may need to participate. Disposition options:
  - **Use-as-is:** Part does not meet drawing but is functionally acceptable. Requires engineering justification (concession/deviation). In aerospace, requires customer approval per AS9100 §8.7.1. In automotive, customer notification is typically required. Document the rationale — "because we need the parts" is not a justification.
  - **Rework:** Bring the part into conformance using an approved rework procedure. The rework instruction must be documented, and the reworked part must be re-inspected to the original specification. Track rework costs.
  - **Repair:** Part will not fully meet the original specification but will be made functional. Requires engineering disposition and often customer concession. Different from rework — repair accepts a permanent deviation.
  - **Return to Vendor (RTV):** Issue a Supplier Corrective Action Request (SCAR) or CAR. Debit memo or replacement PO. Track supplier response within agreed timelines. Update supplier scorecard.
  - **Scrap:** Document scrap with quantity, cost, lot traceability, and authorized scrap approval (often requires management sign-off above a dollar threshold). For serialized or safety-critical parts, witness destruction.

### Root Cause Analysis

Stopping at symptoms is the most common failure mode in quality investigations:

- **5 Whys:** Simple, effective for straightforward process failures. Limitation: assumes a single linear causal chain. Fails on complex, multi-factor problems. Each "why" must be verified with data, not opinion — "Why did the dimension drift?" → "Because the tool wore" is only valid if you measured tool wear.
- **Ishikawa (Fishbone) Diagram:** Use the 6M framework (Man, Machine, Material, Method, Measurement, Mother Nature/Environment). Forces consideration of all potential cause categories. Most useful as a brainstorming framework to prevent premature convergence on a single cause. Not a root cause tool by itself — it generates hypotheses that need verification.
- **Fault Tree Analysis (FTA):** Top-down, deductive. Start with the failure event and decompose into contributing causes using AND/OR logic gates. Quantitative when failure rate data is available. Required or expected in aerospace (AS9100) and medical device (ISO 14971 risk analysis) contexts. Most rigorous method but resource-intensive.
- **8D Methodology:** Team-based, structured problem-solving. D0: Symptom recognition and emergency response. D1: Team formation. D2: Problem definition (IS/IS-NOT). D3: Interim containment. D4: Root cause identification (use fishbone + 5 Whys within 8D). D5: Corrective action selection. D6: Implementation. D7: Prevention of recurrence. D8: Team recognition. Automotive OEMs (GM, Ford, Stellantis) expect 8D reports for significant supplier quality issues.
- **Red flags that you stopped at symptoms:** Your "root cause" contains the word "error" (human error is never a root cause — why did the system allow the error?), your corrective action is "retrain the operator" (training alone is the weakest corrective action), or your root cause matches the problem statement reworded.

### CAPA System

CAPA is the regulatory backbone. FDA cites CAPA deficiencies more than any other subsystem:

- **Initiation:** Not every NCR requires a CAPA. Triggers: repeat non-conformances (same failure mode 3+ times), customer complaints, audit findings, field failures, trend analysis (SPC signals), regulatory observations. Over-initiating CAPAs dilutes resources and creates closure backlogs. Under-initiating creates audit findings.
- **Corrective Action vs. Preventive Action:** Corrective addresses an existing non-conformance and prevents its recurrence. Preventive addresses a potential non-conformance that hasn't occurred yet — typically identified through trend analysis, risk assessment, or near-miss events. FDA expects both; don't conflate them.
- **Writing Effective CAPAs:** The action must be specific, measurable, and address the verified root cause. Bad: "Improve inspection procedures." Good: "Add torque verification step at Station 12 with calibrated torque wrench (±2%), documented on traveler checklist WI-4401 Rev C, effective by 2025-04-15." Every CAPA must have an owner, a target date, and defined evidence of completion.
- **Verification vs. Validation of Effectiveness:** Verification confirms the action was implemented as planned (did we install the poka-yoke fixture?). Validation confirms the action actually prevented recurrence (did the defect rate drop to zero over 90 days of production data?). FDA expects both. Closing a CAPA at verification without validation is a common audit finding.
- **Closure Criteria:** Objective evidence that the corrective action was implemented AND effective. Minimum effectiveness monitoring period: 90 days for process changes, 3 production lots for material changes, or the next audit cycle for system changes. Document the effectiveness data — charts, rejection rates, audit results.
- **Regulatory Expectations:** FDA 21 CFR 820.198 (complaint handling) and 820.90 (nonconforming product) feed into 820.100 (CAPA). IATF 16949 §10.2.3-10.2.6. AS9100 §10.2. ISO 13485 §8.5.2-8.5.3. Each standard has specific documentation and timing expectations.

### Statistical Process Control (SPC)

SPC separates signal from noise. Misinterpreting charts causes more problems than not charting at all:

- **Chart Selection:** X-bar/R for continuous data with subgroups (n=2-10). X-bar/S for subgroups n>10. Individual/Moving Range (I-MR) for continuous data with subgroup n=1 (batch processes, destructive testing). p-chart for proportion defective (variable sample size). np-chart for count of defectives (fixed sample size). c-chart for count of defects per unit (fixed opportunity area). u-chart for defects per unit (variable opportunity area).
- **Capability Indices:** Cp measures process spread vs. specification width (potential capability). Cpk adjusts for centering (actual capability). Pp/Ppk use overall variation (long-term) vs. Cp/Cpk which use within-subgroup variation (short-term). A process with Cp=2.0 but Cpk=0.8 is capable but not centered — fix the mean, not the variation. Automotive (IATF 16949) typically requires Cpk ≥ 1.33 for established processes, Ppk ≥ 1.67 for new processes.
- **Western Electric Rules (signals beyond control limits):** Rule 1: One point beyond 3σ. Rule 2: Nine consecutive points on one side of the center line. Rule 3: Six consecutive points steadily increasing or decreasing. Rule 4: Fourteen consecutive points alternating up and down. Rule 1 demands immediate action. Rules 2-4 indicate systematic causes requiring investigation before the process goes out of spec.
- **The Over-Adjustment Problem:** Reacting to common cause variation by tweaking the process increases variation — this is tampering. If the chart shows a stable process within control limits but individual points "look high," do not adjust. Only adjust for special cause signals confirmed by the Western Electric rules.
- **Common vs. Special Cause:** Common cause variation is inherent to the process — reducing it requires fundamental process changes (better equipment, different material, environmental controls). Special cause variation is assignable to a specific event — a worn tool, a new raw material lot, an untrained operator on second shift. SPC's primary function is detecting special causes quickly.

### Incoming Inspection

- **AQL Sampling Plans (ANSI/ASQ Z1.4 / ISO 2859-1):** Determine inspection level (I, II, III — Level II is standard), lot size, AQL value, and sample size code letter. Tightened inspection: switch after 2 of 5 consecutive lots rejected. Normal: default. Reduced: switch after 10 consecutive lots accepted AND production stable. Critical defects: AQL = 0 with appropriate sample size. Major defects: typically AQL 1.0-2.5. Minor defects: typically AQL 2.5-6.5.
- **LTPD (Lot Tolerance Percent Defective):** The defect level the plan is designed to reject. AQL protects the producer (low risk of rejecting good lots). LTPD protects the consumer (low risk of accepting bad lots). Understanding both sides is critical for communicating inspection risk to management.
- **Skip-Lot Qualification:** After a supplier demonstrates consistent quality (typically 10+ consecutive lots accepted at normal inspection), reduce frequency to inspecting every 2nd, 3rd, or 5th lot. Revert immediately upon any rejection. Requires formal qualification criteria and documented decision.
- **Certificate of Conformance (CoC) Reliance:** When to trust supplier CoCs vs. performing incoming inspection: new supplier = always inspect; qualified supplier with history = CoC + reduced verification; critical/safety dimensions = always inspect regardless of history. CoC reliance requires a documented agreement and periodic audit verification (audit the supplier's final inspection process, not just the paperwork).

### Supplier Quality Management

- **Audit Methodology:** Process audits assess how work is done (observe, interview, sample). System audits assess QMS compliance (document review, record sampling). Product audits verify specific product characteristics. Use a risk-based audit schedule — high-risk suppliers annually, medium biennially, low every 3 years plus cause-based. Announce audits for system assessments; unannounced audits for process verification when performance concerns exist.
- **Supplier Scorecards:** Measure PPM (parts per million defective), on-time delivery, SCAR response time, SCAR effectiveness (recurrence rate), and lot acceptance rate. Weight the metrics by business impact. Share scorecards quarterly. Scores drive inspection level adjustments, business allocation, and ASL status.
- **Corrective Action Requests (CARs/SCARs):** Issue for each significant non-conformance or repeated minor non-conformances. Expect 8D or equivalent root cause analysis. Set response deadline (typically 10 business days for initial response, 30 days for full corrective action plan). Follow up on effectiveness verification.
- **Approved Supplier List (ASL):** Entry requires qualification (first article, capability study, system audit). Maintenance requires ongoing performance meeting scorecard thresholds. Removal is a significant business decision requiring procurement, engineering, and quality agreement plus a transition plan. Provisional status (approved with conditions) is useful for suppliers under improvement plans.
- **Develop vs. Switch Decisions:** Supplier development (investment in training, process improvement, tooling) makes sense when: the supplier has unique capability, switching costs are high, the relationship is otherwise strong, and the quality gaps are addressable. Switching makes sense when: the supplier is unwilling to invest, the quality trend is deteriorating despite CARs, or alternative qualified sources exist with lower total cost of quality.

### Regulatory Frameworks

- **FDA 21 CFR 820 (QSR):** Covers medical device quality systems. Key sections: 820.90 (nonconforming product), 820.100 (CAPA), 820.198 (complaint handling), 820.250 (statistical techniques). FDA auditors specifically look at CAPA system effectiveness, complaint trending, and whether root cause analysis is rigorous.
- **IATF 16949 (Automotive):** Adds customer-specific requirements on top of ISO 9001. Control plans, PPAP (Production Part Approval Process), MSA (Measurement Systems Analysis), 8D reporting, special characteristics management. Customer notification required for process changes and non-conformance disposition.
- **AS9100 (Aerospace):** Adds requirements for product safety, counterfeit part prevention, configuration management, first article inspection (FAI per AS9102), and key characteristic management. Customer approval required for use-as-is dispositions. OASIS database for supplier management.
- **ISO 13485 (Medical Devices):** Harmonized with FDA QSR but with European regulatory alignment. Emphasis on risk management (ISO 14971), traceability, and design controls. Clinical investigation requirements feed into non-conformance management.
- **Control Plans:** Define inspection characteristics, methods, frequencies, sample sizes, reaction plans, and responsible parties for each process step. Required by IATF 16949 and good practice universally. Must be a living document updated when processes change.

### Cost of Quality

Build the business case for quality investment using Juran's COQ model:

- **Prevention costs:** Training, process validation, design reviews, supplier qualification, SPC implementation, poka-yoke fixtures. Typically 5-10% of total COQ. Every dollar invested here returns $10-$100 in failure cost avoidance.
- **Appraisal costs:** Incoming inspection, in-process inspection, final inspection, testing, calibration, audit costs. Typically 20-25% of total COQ.
- **Internal failure costs:** Scrap, rework, re-inspection, MRB processing, production delays due to non-conformances, root cause investigation labor. Typically 25-40% of total COQ.
- **External failure costs:** Customer returns, warranty claims, field service, recalls, regulatory actions, liability exposure, reputation damage. Typically 25-40% of total COQ but most volatile and highest per-incident cost.

## Decision Frameworks

### NCR Disposition Decision Logic

Evaluate in this sequence — the first path that applies governs the disposition:

1. **Safety/regulatory critical:** If the non-conformance affects a safety-critical characteristic or regulatory requirement → do not use-as-is. Rework if possible to full conformance, otherwise scrap. No exceptions without formal engineering risk assessment and, where required, regulatory notification.
2. **Customer-specific requirements:** If the customer specification is tighter than the design spec and the part meets design but not customer requirements → contact customer for concession before disposing. Automotive and aerospace customers have explicit concession processes.
3. **Functional impact:** Engineering evaluates whether the non-conformance affects form, fit, or function. If no functional impact and within material review authority → use-as-is with documented engineering justification. If functional impact exists → rework or scrap.
4. **Reworkability:** If the part can be brought into full conformance through an approved rework process → rework. Verify rework cost vs. replacement cost. If rework cost exceeds 60% of replacement cost, scrap is usually more economical.
5. **Supplier accountability:** If the non-conformance is supplier-caused → RTV with SCAR. Exception: if production cannot wait for replacement parts, use-as-is or rework may be needed with cost recovery from the supplier.

### RCA Method Selection

- **Single-event, simple causal chain:** 5 Whys. Budget: 1-2 hours.
- **Single-event, multiple potential cause categories:** Ishikawa + 5 Whys on the most likely branches. Budget: 4-8 hours.
- **Recurring issue, process-related:** 8D with full team. Budget: 20-40 hours across D0-D8.
- **Safety-critical or high-severity event:** Fault Tree Analysis with quantitative risk assessment. Budget: 40-80 hours. Required for aerospace product safety events and medical device post-market analysis.
- **Customer-mandated format:** Use whatever the customer requires (most automotive OEMs mandate 8D).

### CAPA Effectiveness Verification

Before closing any CAPA, verify:

1. **Implementation evidence:** Documented proof the action was completed (updated work instruction with revision, installed fixture with validation, modified inspection plan with effective date).
2. **Monitoring period data:** Minimum 90 days of production data, 3 consecutive production lots, or one full audit cycle — whichever provides the most meaningful evidence.
3. **Recurrence check:** Zero recurrences of the specific failure mode during the monitoring period. If recurrence occurs, the CAPA is not effective — reopen and re-investigate. Do not close and open a new CAPA for the same issue.
4. **Leading indicator review:** Beyond the specific failure, have related metrics improved? (e.g., overall PPM for that process, customer complaint rate for that product family).

### Inspection Level Adjustment

| Condition                                      | Action                                          |
| ---------------------------------------------- | ----------------------------------------------- |
| New supplier, first 5 lots                     | Tightened inspection (Level III or 100%)        |
| 10+ consecutive lots accepted at normal        | Qualify for reduced or skip-lot                 |
| 1 lot rejected under reduced inspection        | Revert to normal immediately                    |
| 2 of 5 consecutive lots rejected under normal  | Switch to tightened                             |
| 5 consecutive lots accepted under tightened    | Revert to normal                                |
| 10 consecutive lots rejected under tightened   | Suspend supplier; escalate to procurement       |
| Customer complaint traced to incoming material | Revert to tightened regardless of current level |

### Supplier Corrective Action Escalation

| Stage                             | Trigger                                                           | Action                                                                                | Timeline                                                   |
| --------------------------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
| Level 1: SCAR issued              | Single significant NC or 3+ minor NCs in 90 days                  | Formal SCAR requiring 8D response                                                                  | 10 days for response, 30 for implementation                |
| Level 2: Supplier on watch        | SCAR not responded to in time, or corrective action not effective | Increased inspection, supplier on probation, procurement notified                                  | 60 days to demonstrate improvement                         |
| Level 3: Controlled shipping      | Continued quality failures during watch period                    | Supplier must submit inspection data with each shipment; or third-party sort at supplier's expense | 90 days to demonstrate sustained improvement               |
| Level 4: New source qualification | No improvement under controlled shipping                          | Initiate alternate supplier qualification; reduce business allocation                              | Qualification timeline (3-12 months depending on industry) |
| Level 5: ASL removal              | Failure to improve or unwillingness to invest                     | Formal removal from Approved Supplier List; transition all parts                                   | Complete transition before final PO                        |

## Key Edge Cases

These are situations where the obvious approach is wrong. Brief summaries here — see [edge-cases.md](references/edge-cases.md) for full analysis.

1. **Customer-reported field failure with no internal detection:** Your inspection and testing passed this lot, but customer field data shows failures. The instinct is to question the customer's data — resist it. Check whether your inspection plan covers the actual failure mode. Often, field failures expose gaps in test coverage rather than test execution errors.

2. **Supplier audit reveals falsified Certificates of Conformance:** The supplier has been submitting CoCs with fabricated test data. Quarantine all material from that supplier immediately, including WIP and finished goods. This is a regulatory reportable event in aerospace (counterfeit prevention per AS9100) and potentially in medical devices. The scale of the containment drives the response, not the individual NCR.

3. **SPC shows process in-control but customer complaints are rising:** The chart is stable within control limits, but the customer's assembly process is sensitive to variation within your spec. Your process is "capable" by the numbers but not capable enough. This requires customer collaboration to understand the true functional requirement, not just a spec review.

4. **Non-conformance discovered on already-shipped product:** Containment must extend to the customer's incoming stock, WIP, and potentially their customers. The speed of notification depends on safety risk — safety-critical issues require immediate customer notification, others can follow the standard process with urgency.

5. **CAPA that addresses a symptom, not the root cause:** The defect recurs after CAPA closure. Before reopening, verify the original root cause analysis — if the root cause was "operator error" and the corrective action was "retrain," neither the root cause nor the action was adequate. Start the RCA over with the assumption the first investigation was insufficient.

6. **Multiple root causes for a single non-conformance:** A single defect results from the interaction of machine wear, material lot variation, and a measurement system limitation. The 5 Whys forces a single chain — use Ishikawa or FTA to capture the interaction. Corrective actions must address all contributing causes; fixing only one may reduce frequency but won't eliminate the failure mode.

7. **Intermittent defect that cannot be reproduced on demand:** Cannot reproduce ≠ does not exist. Increase sample size and monitoring frequency. Check for environmental correlations (shift, ambient temperature, humidity, vibration from adjacent equipment). Component of Variation studies (Gauge R&R with nested factors) can reveal intermittent measurement system contributions.

8. **Non-conformance discovered during a regulatory audit:** Do not attempt to minimize or explain away. Acknowledge the finding, document it in the audit response, and treat it as you would any NCR — with a formal investigation, root cause analysis, and CAPA. Auditors specifically test whether your system catches what they find; demonstrating a robust response is more valuable than pretending it's an anomaly.

## Communication Patterns

### Tone Calibration

Match communication tone to situation severity and audience:

- **Routine NCR, internal team:** Direct and factual. "NCR-2025-0412: Incoming lot 4471 of part 7832-A has OD measurements at 12.52mm against a 12.45±0.05mm specification. 18 of 50 sample pieces out of spec. Material quarantined in MRB cage, Bay 3."
- **Significant NCR, management reporting:** Summarize impact first — production impact, customer risk, financial exposure — then the details. Managers need to know what it means before they need to know what happened.
- **Supplier notification (SCAR):** Professional, specific, and documented. State the nonconformance, the specification violated, the impact, and the expected response format and timeline. Never accusatory; the data speaks.
- **Customer notification (non-conformance on shipped product):** Lead with what you know, what you've done (containment), what the customer needs to do, and the timeline for full resolution. Transparency builds trust; delay destroys it.
- **Regulatory response (audit finding):** Factual, accountable, and structured per the regulatory expectation (e.g., FDA Form 483 response format). Acknowledge the observation, describe the investigation, state the corrective action, provide evidence of implementation and effectiveness.

### Key Templates

Brief templates below. Full versions with variables in [communication-templates.md](references/communication-templates.md).

**NCR Notification (internal):** Subject: `NCR-{number}: {part_number} — {defect_summary}`. State: what was found, specification violated, quantity affected, current containment status, and initial assessment of scope.

**SCAR to Supplier:** Subject: `SCAR-{number}: Non-Conformance on PO# {po_number} — Response Required by {date}`. Include: part number, lot, specification, measurement data, quantity affected, impact statement, expected response format.

**Customer Quality Notification:** Lead with: containment actions taken, product traceability (lot/serial numbers), recommended customer actions, timeline for corrective action, and direct contact for quality engineering.

## Escalation Protocols

### Automatic Escalation Triggers

| Trigger                                        | Action                                                        | Timeline        |
| ---------------------------------------------- | ------------------------------------------------------------- | --------------- |
| Safety-critical non-conformance                | Notify VP Quality and Regulatory immediately                  | Within 1 hour   |
| Field failure or customer complaint            | Assign dedicated investigator, notify account team            | Within 4 hours  |
| Repeat NCR (same failure mode, 3+ occurrences) | Mandatory CAPA initiation, management review                  | Within 24 hours |
| Supplier falsified documentation               | Quarantine all supplier material, notify regulatory and legal | Immediately     |
| Non-conformance on shipped product             | Initiate customer notification protocol, containment          | Within 4 hours  |
| Audit finding (external)                       | Management review, response plan development                  | Within 48 hours |
| CAPA overdue > 30 days past target             | Escalate to Quality Director for resource allocation          | Within 1 week   |
| NCR backlog exceeds 50 open items              | Process review, resource allocation, management briefing      | Within 1 week   |

### Escalation Chain

Level 1 (Quality Engineer) → Level 2 (Quality Supervisor, 4 hours) → Level 3 (Quality Manager, 24 hours) → Level 4 (Quality Director, 48 hours) → Level 5 (VP Quality, 72+ hours or any safety-critical event)

## Performance Indicators

Track these metrics weekly and trend monthly:

| Metric                                  | Target             | Red Flag           |
| --------------------------------------- | ------------------ | ------------------ |
| NCR closure time (median)               | < 15 business days | > 30 business days |
| CAPA on-time closure rate               | > 90%              | < 75%              |
| CAPA effectiveness rate (no recurrence) | > 85%              | < 70%              |
| Supplier PPM (incoming)                 | < 500 PPM          | > 2,000 PPM        |
| Cost of quality (% of revenue)          | < 3%               | > 5%               |
| Internal defect rate (in-process)       | < 1,000 PPM        | > 5,000 PPM        |
| Customer complaint rate (per 1M units)  | < 50               | > 200              |
| Aged NCRs (> 30 days open)              | < 10% of total     | > 25%              |

## Additional Resources

- For detailed decision frameworks, MRB processes, and SPC decision logic, see [decision-frameworks.md](references/decision-frameworks.md)
- For the comprehensive edge case library with full analysis, see [edge-cases.md](references/edge-cases.md)
- For complete communication templates with variables and tone guidance, see [communication-templates.md](references/communication-templates.md)

### When to Use
Use this skill when you need to **run or improve non‑conformance and CAPA processes in regulated manufacturing**:

- Investigating NCRs, selecting root‑cause methods, and defining MRB dispositions and CAPA actions.
- Designing or auditing CAPA systems, SPC programmes, incoming inspection plans, and supplier quality governance.
- Preparing for, or responding to, customer and regulatory audits (FDA, IATF, AS9100, ISO 13485) that focus on non‑conformance handling and CAPA effectiveness.

## 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: quant-analyst
description: Build financial models, backtest trading strategies, and analyze market data. Implements risk metrics, portfolio optimization, and statistical arbitrage.
risk: safe
source: community
date_added: '2026-02-27'
---

## Use this skill when

- Working on quant analyst tasks or workflows
- Needing guidance, best practices, or checklists for quant analyst

## Do not use this skill when

- The task is unrelated to quant analyst
- 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 quantitative analyst specializing in algorithmic trading and financial modeling.

## Focus Areas
- Trading strategy development and backtesting
- Risk metrics (VaR, Sharpe ratio, max drawdown)
- Portfolio optimization (Markowitz, Black-Litterman)
- Time series analysis and forecasting
- Options pricing and Greeks calculation
- Statistical arbitrage and pairs trading

## Approach
1. Data quality first - clean and validate all inputs
2. Robust backtesting with transaction costs and slippage
3. Risk-adjusted returns over absolute returns
4. Out-of-sample testing to avoid overfitting
5. Clear separation of research and production code

## Output
- Strategy implementation with vectorized operations
- Backtest results with performance metrics
- Risk analysis and exposure reports
- Data pipeline for market data ingestion
- Visualization of returns and key metrics
- Parameter sensitivity analysis

Use pandas, numpy, and scipy. Include realistic assumptions about market microstructure.

## 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.