@workingpayload/agent-skills 1.0.1 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/APIForge/skill.md +165 -0
- package/AccessPlus/skill.md +136 -0
- package/AlgoMaster/skill.md +125 -0
- package/Architekt AI/skill.md +140 -0
- package/AuthCraft/skill.md +144 -0
- package/AutoScriptor/skill.md +137 -0
- package/BoilerCore/skill.md +136 -0
- package/BugHunter Pro/skill.md +133 -0
- package/ChangeScribe/skill.md +113 -0
- package/CodeMap/skill.md +194 -0
- package/CodeSage/skill.md +163 -0
- package/CommitCraft/skill.md +113 -0
- package/CoverageMax/skill.md +161 -0
- package/CronGenius/skill.md +157 -0
- package/DataPolish/skill.md +142 -0
- package/DataWeaver/skill.md +151 -0
- package/DockMaster/skill.md +158 -0
- package/DocuGenie/skill.md +138 -0
- package/EdgeGuard/skill.md +160 -0
- package/EnvWizard/skill.md +156 -0
- package/ErrorMedic/skill.md +152 -0
- package/FeatureSmith/skill.md +139 -0
- package/FlexiLayout/skill.md +144 -0
- package/FlowTester/skill.md +154 -0
- package/FunctionForge/skill.md +136 -0
- package/InputShield/skill.md +144 -0
- package/IssueForge/skill.md +148 -0
- package/KubeCrafter/skill.md +149 -0
- package/LogicLens/skill.md +132 -0
- package/MockSmith/skill.md +146 -0
- package/ModelSensei/skill.md +138 -0
- package/PRMentor/skill.md +103 -0
- package/PerfDetective/skill.md +90 -0
- package/PipelinePro/skill.md +146 -0
- package/PolyglotShift/skill.md +94 -0
- package/PromptForge/skill.md +118 -0
- package/QueryPulse/skill.md +123 -0
- package/README.md +327 -216
- package/ReadMeCraft/skill.md +127 -0
- package/RefactorX/skill.md +110 -0
- package/RenderBoost/skill.md +148 -0
- package/SEOMancer/skill.md +156 -0
- package/ScrapeMaster/skill.md +157 -0
- package/SecretSniffer/skill.md +123 -0
- package/SecureScan/skill.md +130 -0
- package/ServiceSplitter/skill.md +153 -0
- package/SpeedSmith/skill.md +155 -0
- package/StackWise/skill.md +155 -0
- package/TaskOrchestrator/skill.md +135 -0
- package/TestCrafter/skill.md +158 -0
- package/TraceMind/skill.md +143 -0
- package/UISmith/skill.md +131 -0
- package/bin/cli.js +436 -0
- package/extension-extender/SKILL.md +122 -0
- package/fastapi-furious/SKILL.md +148 -0
- package/package.json +42 -32
- package/python-master/SKILL.md +108 -0
- package/react-ranger/SKILL.md +93 -0
- package/scripts/build_index.py +282 -0
- package/scripts/doctor.py +542 -0
- package/scripts/install.py +436 -0
- package/scripts/route.py +348 -0
- package/scripts/score.py +355 -0
- package/scripts/test_skill.py +501 -0
- package/scripts/validate.py +254 -0
- package/skills-routing.json +1156 -0
- package/skills.json +3389 -0
- package/cli.js +0 -181
- package/skills/APIForge/skill.md +0 -32
- package/skills/AccessPlus/skill.md +0 -32
- package/skills/AlgoMaster/skill.md +0 -32
- package/skills/Architekt AI/skill.md +0 -32
- package/skills/AuthCraft/skill.md +0 -32
- package/skills/AutoScriptor/skill.md +0 -32
- package/skills/BoilerCore/skill.md +0 -32
- package/skills/BugHunter Pro/skill.md +0 -32
- package/skills/ChangeScribe/skill.md +0 -32
- package/skills/CodeSage/skill.md +0 -32
- package/skills/CommitCraft/skill.md +0 -32
- package/skills/CoverageMax/skill.md +0 -32
- package/skills/CronGenius/skill.md +0 -32
- package/skills/DataPolish/skill.md +0 -32
- package/skills/DataWeaver/skill.md +0 -32
- package/skills/DockMaster/skill.md +0 -32
- package/skills/DocuGenie/skill.md +0 -32
- package/skills/EdgeGuard/skill.md +0 -32
- package/skills/EnvWizard/skill.md +0 -32
- package/skills/ErrorMedic/skill.md +0 -32
- package/skills/Extension-Extender/SKILL.md +0 -41
- package/skills/Extension-Extender/references/ui-guidelines.md +0 -26
- package/skills/Fastapi-Furious/README.md +0 -16
- package/skills/Fastapi-Furious/SKILL.md +0 -37
- package/skills/FeatureSmith/skill.md +0 -32
- package/skills/FlexiLayout/skill.md +0 -32
- package/skills/FlowTester/skill.md +0 -32
- package/skills/FunctionForge/skill.md +0 -32
- package/skills/InputShield/skill.md +0 -32
- package/skills/IssueForge/skill.md +0 -32
- package/skills/KubeCrafter/skill.md +0 -32
- package/skills/LogicLens/skill.md +0 -32
- package/skills/MockSmith/skill.md +0 -32
- package/skills/ModelSensei/skill.md +0 -32
- package/skills/PRMentor/skill.md +0 -32
- package/skills/PerfDetective/skill.md +0 -32
- package/skills/PipelinePro/skill.md +0 -32
- package/skills/PolyglotShift/skill.md +0 -32
- package/skills/PromptForge/skill.md +0 -32
- package/skills/Python-Master/README.md +0 -11
- package/skills/Python-Master/SKILL.md +0 -37
- package/skills/QueryPulse/skill.md +0 -32
- package/skills/React-Ranger/README.md +0 -17
- package/skills/React-Ranger/SKILL.md +0 -37
- package/skills/ReadMeCraft/skill.md +0 -32
- package/skills/RefactorX/skill.md +0 -32
- package/skills/RenderBoost/skill.md +0 -32
- package/skills/SEOMancer/skill.md +0 -32
- package/skills/ScrapeMaster/skill.md +0 -32
- package/skills/SecretSniffer/skill.md +0 -32
- package/skills/SecureScan/skill.md +0 -32
- package/skills/ServiceSplitter/skill.md +0 -32
- package/skills/SpeedSmith/skill.md +0 -32
- package/skills/StackWise/skill.md +0 -32
- package/skills/TaskOrchestrator/skill.md +0 -32
- package/skills/TestCrafter/skill.md +0 -32
- package/skills/TraceMind/skill.md +0 -32
- package/skills/UISmith/skill.md +0 -32
- /package/{skills/Extension-Extender → extension-extender}/assets/manifest.json +0 -0
- /package/{skills/Extension-Extender → extension-extender}/assets/popup.css +0 -0
- /package/{skills/Extension-Extender → extension-extender}/assets/popup.html +0 -0
- /package/{skills/Extension-Extender → extension-extender}/assets/popup.js +0 -0
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: fastapi-furious
|
|
3
|
+
description: Builds, debugs, and fixes FastAPI applications with structured project scaffolding, endpoint checklists, Alembic migrations, security (CORS, rate limiting, JWT), async testing with httpx, and advanced patterns (WebSockets, file uploads, BackgroundTasks). Use when a user asks to build, create, fix, debug, or improve FastAPI code.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# FastAPI Furious
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
Production-ready FastAPI development covering project structure, endpoint design with validation checklists, database/migrations with Alembic, security hardening, async testing, and advanced patterns (WebSockets, file uploads, background tasks).
|
|
11
|
+
|
|
12
|
+
## Workflow
|
|
13
|
+
|
|
14
|
+
### 1. Project Scaffold
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
project/
|
|
18
|
+
├── app/
|
|
19
|
+
│ ├── main.py # App instance, middleware, lifespan events
|
|
20
|
+
│ ├── api/v1/
|
|
21
|
+
│ │ ├── router.py # Includes all v1 sub-routers
|
|
22
|
+
│ │ └── endpoints/ # One file per resource (users.py, items.py)
|
|
23
|
+
│ ├── core/
|
|
24
|
+
│ │ ├── config.py # pydantic-settings BaseSettings; reads .env
|
|
25
|
+
│ │ └── security.py # Password hashing, JWT encode/decode
|
|
26
|
+
│ ├── crud/ # DB query functions (no business logic)
|
|
27
|
+
│ ├── models/ # SQLAlchemy ORM models
|
|
28
|
+
│ ├── schemas/ # Pydantic v2 request/response models
|
|
29
|
+
│ └── deps.py # Shared dependencies (get_db, get_current_user)
|
|
30
|
+
├── alembic/
|
|
31
|
+
├── tests/
|
|
32
|
+
│ ├── conftest.py # Async test client, test DB setup
|
|
33
|
+
│ └── test_*.py
|
|
34
|
+
├── pyproject.toml
|
|
35
|
+
└── .env.example
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### 2. Endpoint Checklist
|
|
39
|
+
|
|
40
|
+
Apply to every endpoint before it is complete:
|
|
41
|
+
|
|
42
|
+
- [ ] `response_model=Schema` declared for validated, documented output.
|
|
43
|
+
- [ ] `async def` for any I/O (DB, file, HTTP). Never `time.sleep` in async.
|
|
44
|
+
- [ ] `HTTPException` with standard status codes; never error detail in a 200.
|
|
45
|
+
- [ ] `Depends()` for DB sessions, auth, config — never instantiate in route body.
|
|
46
|
+
- [ ] Pydantic `Field(...)` constraints (`min_length`, `ge`, `pattern`) over manual `if` checks.
|
|
47
|
+
- [ ] Status: `201` for creation, `204` for delete with no body.
|
|
48
|
+
|
|
49
|
+
### 3. Database & Migrations (Alembic)
|
|
50
|
+
|
|
51
|
+
- Async engine: `create_async_engine(settings.DATABASE_URL)`.
|
|
52
|
+
- Session dependency:
|
|
53
|
+
```python
|
|
54
|
+
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
|
55
|
+
async with AsyncSessionLocal() as session:
|
|
56
|
+
yield session
|
|
57
|
+
```
|
|
58
|
+
- Migration workflow: edit model → `alembic revision --autogenerate -m "description"` → review generated file → `alembic upgrade head`.
|
|
59
|
+
- **Pitfall**: `autogenerate` misses some changes (column type changes, constraints). Always review the diff before applying.
|
|
60
|
+
- Never edit applied migrations; create a new revision instead.
|
|
61
|
+
|
|
62
|
+
### 4. Security
|
|
63
|
+
|
|
64
|
+
- **CORS**: explicit `allow_origins` list. Never `["*"]` in production.
|
|
65
|
+
- **Rate limiting**: `slowapi` or `fastapi-limiter` (Redis-backed) on public endpoints. Stricter limits on auth endpoints.
|
|
66
|
+
- **Auth**: `python-jose` for JWT. Secrets via `pydantic-settings`; never hardcoded.
|
|
67
|
+
- **SQL injection**: always ORM queries or parameterized statements — never f-string SQL.
|
|
68
|
+
|
|
69
|
+
### 5. Error Handling
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
@app.exception_handler(Exception)
|
|
73
|
+
async def unhandled_exception_handler(request, exc):
|
|
74
|
+
logger.error("Unhandled error", exc_info=exc)
|
|
75
|
+
return JSONResponse(status_code=500, content={"detail": "Internal server error"})
|
|
76
|
+
```
|
|
77
|
+
- Custom exceptions for domain errors with dedicated handlers.
|
|
78
|
+
- Never expose raw stack traces to API consumers.
|
|
79
|
+
|
|
80
|
+
### 6. Testing
|
|
81
|
+
|
|
82
|
+
`pytest` + `httpx.AsyncClient` (all async). Per endpoint:
|
|
83
|
+
- Happy path: correct response model + status.
|
|
84
|
+
- `422` on bad input (missing field, wrong type).
|
|
85
|
+
- `401` on missing/invalid token.
|
|
86
|
+
- `404` on missing resource.
|
|
87
|
+
|
|
88
|
+
Mock external HTTP with `respx`. Use SQLite in-memory or separate Postgres schema — never production DB.
|
|
89
|
+
|
|
90
|
+
### 7. Debugging Decision Workflow
|
|
91
|
+
|
|
92
|
+
1. **Server won't start** → read traceback; usually missing env var or import error.
|
|
93
|
+
2. **422 Unprocessable Entity** → log `await request.body()`; compare against Pydantic schema.
|
|
94
|
+
3. **500 in production** → check structured logs for request ID; correlate with exception handler.
|
|
95
|
+
4. **Slow query** → `echo=True` on SQLAlchemy engine to log SQL; add index or rewrite.
|
|
96
|
+
5. **Event loop blocked** → `run_in_executor` for CPU-bound or synchronous blocking calls.
|
|
97
|
+
6. **Startup hangs** → check `lifespan` context manager; ensure `yield` is reached and async DB connections resolve.
|
|
98
|
+
|
|
99
|
+
### 8. Advanced Patterns
|
|
100
|
+
|
|
101
|
+
**WebSocket endpoints:**
|
|
102
|
+
```python
|
|
103
|
+
@router.websocket("/ws/{client_id}")
|
|
104
|
+
async def ws(websocket: WebSocket, client_id: str):
|
|
105
|
+
await websocket.accept()
|
|
106
|
+
try:
|
|
107
|
+
while True:
|
|
108
|
+
data = await websocket.receive_text()
|
|
109
|
+
await websocket.send_text(f"Echo: {data}")
|
|
110
|
+
except WebSocketDisconnect:
|
|
111
|
+
pass # Clean up connection state
|
|
112
|
+
```
|
|
113
|
+
Multi-instance: broadcast via Redis pub/sub, not in-process state. Add auth via query param token or first-message handshake.
|
|
114
|
+
|
|
115
|
+
**BackgroundTasks vs. task queue:** `BackgroundTasks` for fire-and-forget < 5s (emails, logging). External queue (Celery, ARQ, Dramatiq) for long-running, retriable, or critical work (payments, exports). Never `BackgroundTasks` for anything requiring failure tracking.
|
|
116
|
+
|
|
117
|
+
**File uploads:**
|
|
118
|
+
```python
|
|
119
|
+
@router.post("/upload")
|
|
120
|
+
async def upload(file: UploadFile = File(...)):
|
|
121
|
+
if file.size and file.size > 10_000_000:
|
|
122
|
+
raise HTTPException(413, "File too large")
|
|
123
|
+
contents = await file.read()
|
|
124
|
+
return {"filename": file.filename, "size": len(contents)}
|
|
125
|
+
```
|
|
126
|
+
Large files: stream to S3/GCS via `file.read(chunk_size)` loop. Set `client_max_body_size` at nginx level.
|
|
127
|
+
|
|
128
|
+
**Lifespan events (replacing deprecated `on_startup`/`on_shutdown`):**
|
|
129
|
+
```python
|
|
130
|
+
from contextlib import asynccontextmanager
|
|
131
|
+
|
|
132
|
+
@asynccontextmanager
|
|
133
|
+
async def lifespan(app: FastAPI):
|
|
134
|
+
pool = await create_pool() # startup
|
|
135
|
+
yield {"pool": pool}
|
|
136
|
+
await pool.close() # shutdown
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Edge Cases
|
|
140
|
+
|
|
141
|
+
1. **ASGI lifespan not supported by test client**: use `httpx.ASGITransport(app=app)` in test `conftest.py` to handle lifespan events during testing.
|
|
142
|
+
2. **Pydantic v1 vs v2 migration**: FastAPI 0.100+ uses Pydantic v2. If upgrading, run `bump-pydantic` to auto-migrate models. Key changes: `orm_mode` → `from_attributes`, `validator` → `field_validator`.
|
|
143
|
+
3. **Async DB session leaks**: if `get_db` doesn't use `async with`, sessions may not close on exceptions. Always use context manager pattern.
|
|
144
|
+
|
|
145
|
+
## Output Format
|
|
146
|
+
|
|
147
|
+
- Provide the complete updated file for changed files.
|
|
148
|
+
- State: (a) root cause (if debugging), (b) what changed, (c) how to verify.
|
package/package.json
CHANGED
|
@@ -1,32 +1,42 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@workingpayload/agent-skills",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "
|
|
5
|
-
"
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
"cli.js",
|
|
12
|
-
"
|
|
13
|
-
|
|
14
|
-
"
|
|
15
|
-
"
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
"
|
|
19
|
-
"
|
|
20
|
-
"
|
|
21
|
-
"
|
|
22
|
-
"
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
"
|
|
26
|
-
"
|
|
27
|
-
|
|
28
|
-
"
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@workingpayload/agent-skills",
|
|
3
|
+
"version": "2.0.1",
|
|
4
|
+
"description": "Install and run AI-powered developer skills across Claude, Gemini, and Google Antigravity",
|
|
5
|
+
"bin": {
|
|
6
|
+
"agent-skills": "./bin/cli.js"
|
|
7
|
+
},
|
|
8
|
+
"scripts": {
|
|
9
|
+
"validate": "node bin/cli.js validate",
|
|
10
|
+
"score": "node bin/cli.js score",
|
|
11
|
+
"test-skills": "node bin/cli.js test",
|
|
12
|
+
"build-index": "node bin/cli.js build-index"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"ai",
|
|
16
|
+
"claude",
|
|
17
|
+
"gemini",
|
|
18
|
+
"antigravity",
|
|
19
|
+
"skills",
|
|
20
|
+
"developer-tools",
|
|
21
|
+
"code-review",
|
|
22
|
+
"debugging"
|
|
23
|
+
],
|
|
24
|
+
"author": "workingpayload",
|
|
25
|
+
"license": "MIT",
|
|
26
|
+
"repository": {
|
|
27
|
+
"type": "git",
|
|
28
|
+
"url": "https://github.com/workingpayload/agent-skills"
|
|
29
|
+
},
|
|
30
|
+
"engines": {
|
|
31
|
+
"node": ">=18"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"bin/",
|
|
35
|
+
"scripts/",
|
|
36
|
+
"skills.json",
|
|
37
|
+
"skills-routing.json",
|
|
38
|
+
"*/skill.md",
|
|
39
|
+
"*/SKILL.md",
|
|
40
|
+
"extension-extender/assets/"
|
|
41
|
+
]
|
|
42
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: python-master
|
|
3
|
+
description: Builds, debugs, and fixes Python code using structured decision workflows with named tools (ruff, mypy, pytest, uv/poetry). Covers environment setup, testing, error handling, performance profiling, memory leak diagnosis, and dependency conflict resolution. Use when a user asks to build, fix, debug, or create Python code.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Python Master
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
Comprehensive Python development skill covering the full lifecycle: environment setup, building clean code, structured debugging, surgical fixing, testing, and performance optimization. Every step uses named tools with exact commands.
|
|
11
|
+
|
|
12
|
+
## Workflow
|
|
13
|
+
|
|
14
|
+
### 1. Environment Setup (Always First)
|
|
15
|
+
|
|
16
|
+
1. Check for existing environment: `.venv/`, `venv/`, or `pyproject.toml`.
|
|
17
|
+
- `pyproject.toml` exists → use `uv` (preferred) or `poetry`.
|
|
18
|
+
- Only `requirements.txt` → `python -m venv .venv && pip install -r requirements.txt`.
|
|
19
|
+
- New project → `uv init <name>` or `poetry new <name>`.
|
|
20
|
+
2. Never install into the global Python environment.
|
|
21
|
+
3. Confirm: `which python && python --version`.
|
|
22
|
+
|
|
23
|
+
### 2. Building Code
|
|
24
|
+
|
|
25
|
+
- PEP 8 compliant; type hints on all function signatures.
|
|
26
|
+
- Use `dataclasses` or `pydantic` for structured data; f-strings for formatting.
|
|
27
|
+
- One module per concern; functions under 40 lines; no global mutable state.
|
|
28
|
+
- After writing: `ruff check . --fix` → `mypy .` → `pytest -x`.
|
|
29
|
+
- **Pitfall — mutable defaults**: `def f(x=[])` shares state across calls. Use `def f(x=None): x = x or []`.
|
|
30
|
+
|
|
31
|
+
### 3. Debugging Decision Workflow
|
|
32
|
+
|
|
33
|
+
Follow in order — stop at the step that resolves the issue:
|
|
34
|
+
|
|
35
|
+
1. **Read the full traceback.** Identify file, line, and exception type.
|
|
36
|
+
2. `ImportError` / `ModuleNotFoundError` → verify venv is active, `pip show <pkg>`.
|
|
37
|
+
3. `TypeError` / `AttributeError` → add `breakpoint()` or `print(type(x), x)` before the failing line.
|
|
38
|
+
4. `KeyError` / `IndexError` → inspect data shape; use `.get()` for dicts, guard list access with `len()`.
|
|
39
|
+
5. No exception but wrong output → add `logging.debug` at function entry/exit to trace variable state.
|
|
40
|
+
6. Test was passing before → `pytest -x --tb=short` to isolate the regression.
|
|
41
|
+
7. `RecursionError` → check for missing base case or infinite mutual recursion; add `@functools.lru_cache` if memoization helps.
|
|
42
|
+
8. Once root cause is identified, **explain it before applying the fix**.
|
|
43
|
+
|
|
44
|
+
### 4. Fixing Code
|
|
45
|
+
|
|
46
|
+
- Surgical fixes only; do not rewrite files unless >60% of logic is wrong.
|
|
47
|
+
- After fixing: run `pytest path/to/test_file.py -x`.
|
|
48
|
+
- If no tests exist, write a regression test that reproduces the bug **before** fixing.
|
|
49
|
+
|
|
50
|
+
### 5. Testing
|
|
51
|
+
|
|
52
|
+
- Framework: `pytest` with tests in `tests/test_*.py`.
|
|
53
|
+
- Run: `pytest --tb=short -q` (quick), `pytest --cov=src --cov-report=term-missing` (coverage).
|
|
54
|
+
- Use `pytest.mark.parametrize` for data-driven cases; `unittest.mock.patch` / `pytest-mock` for external deps.
|
|
55
|
+
- Edge cases: empty input, `None`, boundary values, exception paths.
|
|
56
|
+
- Target: every public function has at least one happy-path and one error-path test.
|
|
57
|
+
|
|
58
|
+
### 6. Error Handling
|
|
59
|
+
|
|
60
|
+
- Specific exceptions only — never bare `except:`.
|
|
61
|
+
- I/O and network calls: `try/except` with `logging.error(msg, exc_info=True)`.
|
|
62
|
+
- Re-raise with context: `raise RuntimeError("context") from original_exc`.
|
|
63
|
+
- Define custom exceptions for domain errors: `class ValidationError(ValueError): ...`.
|
|
64
|
+
|
|
65
|
+
### 7. Performance
|
|
66
|
+
|
|
67
|
+
- **Profile first**: `python -m cProfile -s cumulative script.py | head -20`.
|
|
68
|
+
- Collections: `set` for membership, `collections.deque` for queues, `dict` over nested `if` chains.
|
|
69
|
+
- Numerical: NumPy vectorized ops over Python loops; `pandas` only for tabular structure.
|
|
70
|
+
- Async: `asyncio` with `async def` / `await`; never `time.sleep` in async code.
|
|
71
|
+
|
|
72
|
+
### 8. Advanced Diagnostics
|
|
73
|
+
|
|
74
|
+
**Memory leak diagnosis:**
|
|
75
|
+
```python
|
|
76
|
+
import tracemalloc
|
|
77
|
+
tracemalloc.start()
|
|
78
|
+
# ... run workload ...
|
|
79
|
+
for stat in tracemalloc.take_snapshot().statistics('lineno')[:10]:
|
|
80
|
+
print(stat)
|
|
81
|
+
```
|
|
82
|
+
Use `objgraph.show_most_common_types()` for reference cycles. For production: Py-Spy or Pyroscope for continuous profiling.
|
|
83
|
+
|
|
84
|
+
**Dependency conflicts:** `pip check` detects incompatible packages. Use `pip install --dry-run` to trace conflict chains. For forced versions: `constraints.txt` (`pip install -c constraints.txt`). With `uv`: `uv pip install --override`.
|
|
85
|
+
|
|
86
|
+
**Blocking calls in async code:**
|
|
87
|
+
```python
|
|
88
|
+
# CPU-bound → ProcessPoolExecutor (bypasses GIL)
|
|
89
|
+
# Blocking I/O → ThreadPoolExecutor (default)
|
|
90
|
+
loop = asyncio.get_running_loop()
|
|
91
|
+
result = await loop.run_in_executor(ProcessPoolExecutor(4), cpu_fn, data)
|
|
92
|
+
```
|
|
93
|
+
`ThreadPoolExecutor` does NOT bypass the GIL — use only for blocking I/O.
|
|
94
|
+
|
|
95
|
+
**Concurrency pitfalls:** `threading` shares the GIL — use `multiprocessing` or `ProcessPoolExecutor` for CPU parallelism. For async race conditions, use `asyncio.Lock`. For shared-memory data corruption, use `multiprocessing.Queue` or `multiprocessing.Value` with locks.
|
|
96
|
+
|
|
97
|
+
## Edge Cases
|
|
98
|
+
|
|
99
|
+
1. **Package with C extensions on Alpine Linux**: `pip install` fails with missing headers. Use `python:3.x-slim` (glibc) instead of Alpine (musl), or install build deps: `apk add gcc musl-dev`.
|
|
100
|
+
2. **Circular imports**: refactor by moving shared types to a `types.py` module, or use `TYPE_CHECKING` guard: `if TYPE_CHECKING: from module import Type`.
|
|
101
|
+
3. **`asyncio.run()` inside Jupyter**: Jupyter already runs an event loop. Use `await` directly or `nest_asyncio.apply()`.
|
|
102
|
+
|
|
103
|
+
## Output Format
|
|
104
|
+
|
|
105
|
+
When providing a fix or new code:
|
|
106
|
+
1. **Root cause**: what went wrong and why.
|
|
107
|
+
2. **Change**: the complete updated function/class (not a diff snippet).
|
|
108
|
+
3. **Verification**: exact command to confirm the fix works.
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: react-ranger
|
|
3
|
+
description: Builds, debugs, and fixes React applications using TypeScript, hooks, and modern patterns (Server Components, Zustand, React Query). Includes structured debugging decision tree, testing with Vitest/RTL, accessibility checklist, and performance optimization. Use when a user asks to build, create, fix, debug, or improve React code.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# React Ranger
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
Production-ready React development covering component architecture, structured debugging, state management decisions, testing with Vitest + React Testing Library, WCAG accessibility, and advanced patterns (RSC, bundle optimization, context performance).
|
|
11
|
+
|
|
12
|
+
## Workflow
|
|
13
|
+
|
|
14
|
+
### 1. Building Components
|
|
15
|
+
|
|
16
|
+
- Functional components with hooks only; no class components unless maintaining legacy.
|
|
17
|
+
- TypeScript: type all props with interfaces, never use `any`.
|
|
18
|
+
- One component per file; co-locate styles and tests alongside.
|
|
19
|
+
- `useMemo` / `useCallback` only when profiler confirms a problem — premature memoization adds complexity.
|
|
20
|
+
- **Pitfall**: object/array literals in JSX (`style={{ color: 'red' }}`) create new references every render; extract to a constant or `useMemo`.
|
|
21
|
+
|
|
22
|
+
### 2. Debugging Decision Tree
|
|
23
|
+
|
|
24
|
+
Follow in order — stop at the step that resolves the issue:
|
|
25
|
+
|
|
26
|
+
1. Open **React DevTools** → Profiler tab. Identify which component re-renders unexpectedly.
|
|
27
|
+
2. Re-render from parent → check if props are referentially stable; wrap callbacks in `useCallback`, objects in `useMemo`.
|
|
28
|
+
3. `useEffect` runs too often → audit dependency array. Every value used inside must be listed. Functions as deps must be wrapped in `useCallback`.
|
|
29
|
+
4. Stale values in `useEffect` → closure captured an old value. Add to dep array or use `useRef` for latest value without triggering re-renders.
|
|
30
|
+
5. List items behave incorrectly → verify stable, unique `key` props. Never use array index as key when items reorder.
|
|
31
|
+
6. Data fetching race conditions → use `AbortController` or `isCurrent` flag:
|
|
32
|
+
```ts
|
|
33
|
+
useEffect(() => {
|
|
34
|
+
let isCurrent = true;
|
|
35
|
+
fetchData().then(d => { if (isCurrent) setData(d); });
|
|
36
|
+
return () => { isCurrent = false; };
|
|
37
|
+
}, [dep]);
|
|
38
|
+
```
|
|
39
|
+
7. Render-phase crash → wrap routes in `ErrorBoundary` to catch without crashing the app.
|
|
40
|
+
8. Hydration mismatch (SSR/RSC) → ensure server and client render identical markup. Common causes: `Date.now()`, `Math.random()`, browser-only APIs (`window`, `localStorage`) in the initial render.
|
|
41
|
+
|
|
42
|
+
### 3. State Management Decision
|
|
43
|
+
|
|
44
|
+
| Need | Solution |
|
|
45
|
+
|------|----------|
|
|
46
|
+
| Local UI state | `useState` |
|
|
47
|
+
| Shared subtree | `useContext` + `useReducer` |
|
|
48
|
+
| Server/async state | React Query (`@tanstack/react-query`) or SWR |
|
|
49
|
+
| Global client state | Zustand (lightweight) or Redux Toolkit (large team) |
|
|
50
|
+
|
|
51
|
+
### 4. Testing (Vitest + React Testing Library)
|
|
52
|
+
|
|
53
|
+
- Location: `src/components/Foo/Foo.test.tsx` alongside component.
|
|
54
|
+
- Run: `npx vitest run` (CI) or `npx vitest` (watch).
|
|
55
|
+
- Per component: renders without crashing, interactions trigger correct state/callback, async ops use `waitFor`/`findBy*` (never `setTimeout`), error states show error UI.
|
|
56
|
+
- Use `screen.getByRole` / `getByLabelText` over `getByTestId` — role-based queries validate accessibility.
|
|
57
|
+
- Mock: `vi.mock('module-name')`.
|
|
58
|
+
|
|
59
|
+
### 5. Accessibility (a11y) Checklist
|
|
60
|
+
|
|
61
|
+
- [ ] Interactive elements keyboard focusable and operable (Enter/Space).
|
|
62
|
+
- [ ] Images: descriptive `alt`; decorative images `alt=""`.
|
|
63
|
+
- [ ] Form inputs associated with `<label>` via `htmlFor`/`id` or `aria-label`.
|
|
64
|
+
- [ ] Color not sole information channel (add icon, text, or pattern).
|
|
65
|
+
- [ ] Focus trapped in modals; returned to trigger on close.
|
|
66
|
+
- [ ] Dynamic content uses `role="alert"` or `aria-live="polite"`.
|
|
67
|
+
- [ ] Run `npx axe-core` or axe DevTools extension; resolve critical/serious violations.
|
|
68
|
+
|
|
69
|
+
### 6. React Server Components (RSC)
|
|
70
|
+
|
|
71
|
+
- In Next.js App Router, components are Server Components by default.
|
|
72
|
+
- Add `"use client"` at top of files using hooks, browser APIs, or event handlers.
|
|
73
|
+
- RSC constraints: no `useState`, `useEffect`, `useContext`. Data fetching via async/await in component body.
|
|
74
|
+
- Props across server/client boundary must be serializable — no functions, class instances, or Dates.
|
|
75
|
+
|
|
76
|
+
### 7. Performance
|
|
77
|
+
|
|
78
|
+
**Bundle analysis:** `npx vite-bundle-visualizer` (Vite) or `npx webpack-bundle-analyzer`. Check tree-shaking: `import { debounce } from 'lodash'` imports everything — use `lodash-es` or `lodash/debounce`.
|
|
79
|
+
|
|
80
|
+
**Context re-render fix:** Split context by update frequency (separate `UserContext` from `CartContext`). Wrap values in `useMemo`: `const value = useMemo(() => ({ user, login }), [user])`.
|
|
81
|
+
|
|
82
|
+
**Virtualization:** For lists >100 items, use `@tanstack/react-virtual` or `react-window` to render only visible rows.
|
|
83
|
+
|
|
84
|
+
## Edge Cases
|
|
85
|
+
|
|
86
|
+
1. **Concurrent features conflict**: `useTransition` and `Suspense` can cause unexpected loading states when combined with client-side navigation. Test transitions with slow networks (Chrome DevTools throttling).
|
|
87
|
+
2. **Third-party scripts blocking hydration**: scripts loaded via `<Script strategy="beforeInteractive">` can delay hydration. Use `afterInteractive` or `lazyOnload` unless the script is critical.
|
|
88
|
+
3. **CSS-in-JS with SSR**: libraries like `styled-components` need a server-side `ServerStyleSheet` to avoid FOUC. CSS Modules or Tailwind avoid this entirely.
|
|
89
|
+
|
|
90
|
+
## Output Format
|
|
91
|
+
|
|
92
|
+
- Provide the complete updated file for changed files.
|
|
93
|
+
- State: (a) root cause (if debugging), (b) what changed, (c) how to verify.
|