generated from john/python-template
Created new code-review agent and ran it using Claude.
This commit is contained in:
@@ -0,0 +1,146 @@
|
||||
---
|
||||
name: python-code-reviewer
|
||||
description: Perform an evidence-based, senior architect code review for Python codebases using FastAPI, NiceGUI, SQLModel, SQLAlchemy, Pydantic V2, asyncio, and OpenRouter. Use when asked to review Python repositories, perform architectural or code audits, or evaluate code against Python 3.12+ best practices.
|
||||
---
|
||||
|
||||
# Python Code Reviewer
|
||||
|
||||
Perform thorough, evidence-based code reviews for Python projects. Every finding must cite concrete file paths and line ranges, avoid speculation, and include recommended fixes.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Performing an architectural or code quality review of a Python codebase.
|
||||
- Auditing applications using FastAPI, NiceGUI, SQLModel/SQLAlchemy, Pydantic V2, or asyncio workers.
|
||||
- Generating structured Markdown review reports in `./docs`.
|
||||
|
||||
## Technical Stack Scope
|
||||
|
||||
- **Runtime:** Python 3.12+
|
||||
- **Web Application:** FastAPI and NiceGUI
|
||||
- **Persistence:** SQLModel, SQLAlchemy (SQLite and PostgreSQL support)
|
||||
- **Validation & Settings:** Pydantic V2 and pydantic-settings
|
||||
- **Concurrency:** Python asyncio workers
|
||||
- **Vision/LLM Integration:** OpenRouter / provider adapters
|
||||
- **Quality & Testing:** pytest, pytest-asyncio, Ruff, and ty
|
||||
|
||||
## Review Workflow
|
||||
|
||||
1. **Map the Repository First:** Inspect entry points, package layout, configurations, dependency manifests, and any project-specific rule files (`AGENTS.md`, `CLAUDE.md`, `.github/instructions/`). Project-specific conventions override generic advice.
|
||||
2. **Read Representative Modules:** Sample across all layers (routes/pages, UI components, services, workers, persistence, provider adapters, settings, tests) before drawing conclusions.
|
||||
3. **Verify Claims:** Run or reference project tooling (`ruff check`, `ty`, `pytest`) rather than guessing.
|
||||
4. **Prioritize Hot Paths:** Focus deeply on request handling, database sessions, background workers, and external API calls.
|
||||
5. **Enforce Read-Only Safety:** Do not modify code unless explicitly instructed.
|
||||
|
||||
## Core Review Areas
|
||||
|
||||
### 1. Python Best Practices (3.12+)
|
||||
- **Type Annotations:** Ensure completeness, modern syntax (`X | None`, builtin generics, `Self`, `type` statements), and avoid unparameterized containers or bare `Any`.
|
||||
- **Error Handling:** Identify bare/broad `except`, swallowed exceptions, missing `raise ... from`, and exceptions used for control flow.
|
||||
- **Resource Management:** Verify context managers for files, DB sessions, HTTP clients, and locks. Check for leaked tasks or connections.
|
||||
- **Data Modeling:** Check proper use of dataclasses vs. Pydantic models vs. dictionaries. Eliminate mutable default arguments and stringly-typed payloads.
|
||||
- **Idioms & Clean Code:** Verify `pathlib` usage over `os.path`, comprehensions vs manual loops, removal of dead code, and elimination of magic numbers.
|
||||
|
||||
### 2. FastAPI
|
||||
- **Dependency Injection:** Verify `Depends` is used for shared resources (DB sessions, settings, clients) rather than global singletons.
|
||||
- **Route Design:** Validate HTTP verbs, status codes, path/query/body typing, `response_model`, and domain-based router organization.
|
||||
- **Lifecycle & Concurrency:** Ensure lifespan handlers are used instead of deprecated `@app.on_event`. Flag blocking synchronous calls in `async def` endpoints.
|
||||
|
||||
### 3. NiceGUI
|
||||
- **Separation of Concerns:** Ensure UI components delegate business logic and persistence to service layers.
|
||||
- **Client State Handling:** Verify correct use of client-scoped state vs global state to avoid state leaks across sessions.
|
||||
- **Async Execution:** Check for blocking operations on the UI event loop and unbounded timers/pollers.
|
||||
|
||||
### 4. Persistence (SQLModel / SQLAlchemy)
|
||||
- **Session Lifecycle:** Enforce one session per request/unit of work with explicit commit/rollback/close boundaries.
|
||||
- **Query Optimization:** Detect N+1 patterns, missing eager loads (`selectinload`/`joinedload`), queries inside loops, and unindexed filters.
|
||||
- **Cross-Dialect Portability:** Check compatibility for both SQLite (WAL mode, pragmas) and PostgreSQL (JSONB, locking, autoincrement).
|
||||
|
||||
### 5. Pydantic V2 & Settings
|
||||
- **V2 Migration:** Flag legacy V1 patterns (`@validator`, `Config` class, `.dict()`, `parse_obj`) and use V2 equivalents (`@field_validator`, `model_config = ConfigDict(...)`, `model_dump()`).
|
||||
- **Settings Management:** Ensure `BaseSettings` is the single source of truth without scattered `os.getenv` calls or committed secrets.
|
||||
|
||||
### 6. Concurrency & Asyncio Workers
|
||||
- **Task Lifecycle:** Flag unreferenced `create_task` calls that risk garbage collection, missing cancellation handling, and lack of graceful shutdown.
|
||||
- **Backpressure & Synchronization:** Check for appropriate use of `asyncio.Queue`, `TaskGroup`, `Lock`, and backoff retries.
|
||||
|
||||
### 7. Provider Adapters (OpenRouter / APIs)
|
||||
- **Adapter Encapsulation:** Verify provider-specific details (headers, model names, payload formats) do not leak into UI or business logic.
|
||||
- **Client Lifecycle:** Reuse shared `AsyncClient` instances with proper connection pooling and timeouts. Validate API responses using Pydantic schemas.
|
||||
|
||||
### 8. Testing & Quality Tooling
|
||||
- **Test Isolation:** Verify tests do not rely on live external services, real clocks, or shared global state.
|
||||
- **Async Test Setup:** Check `pytest-asyncio` configuration and fixture lifecycle.
|
||||
|
||||
### 9. Duplication & Consolidation
|
||||
- Identify repeated code blocks, candidate helper abstractions, divergent patterns for identical operations, and duplicated domain constants.
|
||||
|
||||
## Output Report Structure & Template
|
||||
|
||||
Generate Markdown reports in `./docs` following this exact template structure:
|
||||
|
||||
```markdown
|
||||
# Architecture & Code Review Report
|
||||
|
||||
**Repository Target:** `project-root/`
|
||||
**Target Stack:** Python 3.12+ | FastAPI | NiceGUI | SQLModel/SQLAlchemy | Pydantic V2 | asyncio | OpenRouter
|
||||
|
||||
---
|
||||
|
||||
## 1. Executive Summary
|
||||
- 5-10 bullets on overall health, top risks, and high-leverage refactors.
|
||||
|
||||
---
|
||||
|
||||
## 2. Findings by Severity
|
||||
|
||||
### Critical Severity
|
||||
#### [CRIT-01] Title
|
||||
- **Location:** `path/to/file.py:lines`
|
||||
- **Problem & Consequence:** Concrete consequence, not a style opinion.
|
||||
- **Recommendation:** Fix with before/after sketch.
|
||||
- **Effort:** S / M / L
|
||||
|
||||
### High Severity
|
||||
#### [HIGH-01] Title
|
||||
...
|
||||
|
||||
### Medium Severity
|
||||
#### [MED-01] Title
|
||||
...
|
||||
|
||||
### Low Severity
|
||||
#### [LOW-01] Title
|
||||
...
|
||||
|
||||
---
|
||||
|
||||
## 3. Stack-Specific Analysis
|
||||
- Python 3.12+ Best Practices
|
||||
- FastAPI
|
||||
- NiceGUI
|
||||
- SQLModel & SQLAlchemy
|
||||
- Pydantic V2 & Settings
|
||||
- Asyncio Workers
|
||||
- OpenRouter / Adapter Boundary
|
||||
- Testing & Quality Tooling
|
||||
|
||||
---
|
||||
|
||||
## 4. Duplication & Consolidation Report
|
||||
| Pattern / Duplication | Locations | Proposed Canonical Home | Estimated Lines Removed |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
|
||||
### Proposed Canonical Abstractions
|
||||
- Code signatures and implementation homes.
|
||||
|
||||
---
|
||||
|
||||
## 5. Prioritized Action Plan
|
||||
1. **Phase 1: Quick Wins (PR 1-2)**
|
||||
2. **Phase 2: Reliability & Concurrency (PR 3-4)**
|
||||
3. **Phase 3: Consolidation & Refactoring (PR 5-6)**
|
||||
|
||||
---
|
||||
|
||||
## 6. Preserved Strengths
|
||||
- Existing patterns worth maintaining.
|
||||
Reference in New Issue
Block a user