vibe-coding-rules / rules
Cursor rule10 starsChanged 7 months agoMITView on GitHub
FastAPI layer architecture rules — Router → Service → Repository with Protocol injection
Where files are headingNew Cursor rule files have more rules about planning and tracking tasks, and fewer about code style.
Of the Cursor rule files we read, the 4,373 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository14 other files it gives its agents.
- website/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- website/CLAUDE.mdCLAUDE.md
- .cursor/rules/decomposition.mdcCursor rule
- .cursor/rules/integrations.mdcCursor rule
- llms.txtllms.txt
- add-providerSkill
- debug-backendSkill
- debug-frontendSkill
- debug-goSkill
- new-feature-goSkill
- new-feature-nextjsSkill
- new-featureSkill
- split-monolithSkill
The file
We split this architecture.mdc into the rules it gives an agent
6 rules. About 0 are common, 2 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 19
Every endpoint declares response_model= for OpenAPI fidelity.
- Very specific: line 20
Every endpoint (except /auth/*) requires user_id: str = Depends(get_current_user_id).
- Very specific: line 80
Every query scoped by user_id (multi-tenancy).
- Very specific: line 90
Use FastAPI Depends() + factory functions in app/core/deps.py.
- Distinctive: line 118
When editing a file, ask:
- Distinctive: line 121
Does this import cross the boundary?: Run mentally: would moving this import remove the violation?
≈ “Common” is an estimate: at least 1 in 5 of the 7,324 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
---
description: FastAPI layer architecture rules — Router → Service → Repository with Protocol injection
globs: ["**/*.py"]
alwaysApply: true
---
# Layer Architecture Rules
This codebase follows **strict 4-layer architecture**: Router → Service → Repository → ORM/HTTP/Storage.
Imports flow downward only. Each layer has hard boundaries you must NOT cross.
## Hard Rules
### 1. Router files (`app/routers/**`)
- Handlers are **thin**: ≤10 lines of executable code per handler.
- Allowed imports: `fastapi`, `app.schemas.*`, `app.core.deps`, `app.services.*`.
- **Forbidden imports**: `sqlalchemy`, `httpx`, `boto3`, `app.models.*`, `app.repositories.*` (except via `Depends`).
- Every endpoint declares `response_model=` for OpenAPI fidelity.
- Every endpoint (except `/auth/*`) requires `user_id: str = Depends(get_current_user_id)`.
- Business logic lives in services. Routers parse input, call one service method, return a response.
```python
# ✅ GOOD
@router.post("/wallet/charge", response_model=WalletResponse, status_code=201)
async def charge(
req: ChargeRequest,
user_id: str = Depends(get_current_user_id),
svc: WalletUserService = Depends(get_wallet_service),
) -> WalletResponse:
wallet = await svc.charge(user_id=user_id, amount=req.amount, key=req.idempotency_key)
return WalletResponse.from_domain(wallet)
```
```python
# ❌ BAD — business logic and SQL in router
@router.post("/wallet/charge")
async def charge(req: ChargeRequest, db: Session = Depends(get_db)):
wallet = db.query(Wallet).filter(Wallet.user_id == user_id).with_for_update().one()
if wallet.balance < req.amount:
raise HTTPException(402)
wallet.balance -= req.amount
db.commit()
return wallet
```
### 2. Service files (`app/services/**`)
- **Forbidden imports**: `sqlalchemy`, `httpx`, `boto3`, `redis`, FastAPI `Request`/`Response`/`HTTPException`.
- Allowed imports: `app.repositories.protocols`, `app.providers._types`, `app.domain.*`, stdlib, Pydantic.
- Services raise **domain exceptions** (e.g. `InsufficientFundsError`); routers map them to HTTP.
- Constructor injects **Protocol-typed** dependencies, not concrete classes.
```python
# ✅ GOOD
from app.repositories.protocols import WalletRepoProtocol
class WalletUserService:
def __init__(self, repo: WalletRepoProtocol):
self._repo = repo
async def charge(self, user_id: str, amount: Decimal, key: UUID) -> Wallet:
return await apply_ledger_entry(self._repo, LedgerEntry.deduct(user_id, amount, key))
```
```python
# ❌ BAD — service depends on SQLAlchemy
from sqlalchemy.orm import Session
class WalletUserService:
def __init__(self, db: Session):
self._db = db
```
### 3. Repository files (`app/repositories/sqlalchemy/**`)
- The only layer allowed to import `sqlalchemy`.
- Each repo class implements a Protocol from `app/repositories/protocols.py`.
- Returns **domain objects**, not ORM models. Translation happens at this boundary.
- Every query scoped by `user_id` (multi-tenancy).
### 4. Provider files (`app/providers/<vendor>/**`)
- The only layer allowed to import `httpx` directly.
- Each adapter returns `GenerateResult | ProviderError` — never raw `dict`.
- Uses the per-provider `httpx.AsyncClient` from `app/core/http.py`.
## Dependency Injection
Use FastAPI `Depends()` + factory functions in `app/core/deps.py`. **Do not** install `dependency-injector`, `punq`, or any other DI container.
```python
# app/core/deps.py
def get_wallet_service(db: Session = Depends(get_db)) -> WalletUserService:
return WalletUserService(repo=SQLAlchemyWalletRepo(db))
```
## Domain Exceptions
Services raise domain errors. Routers translate to HTTP.
```python
# app/services/wallet/exceptions.py
class InsufficientFundsError(Exception): ...
class WalletNotFoundError(Exception): ...
# app/routers/wallet.py
try:
wallet = await svc.charge(...)
except InsufficientFundsError:
raise HTTPException(402, detail="insufficient funds")
except WalletNotFoundError:
raise HTTPException(404, detail="wallet not found")
```
## Quick Layer Audit
When editing a file, ask:
1. **Is the file in the right layer for what it does?** A function that calls `httpx` belongs in a provider, not a service.
2. **Does this import cross the boundary?** Run mentally: would moving this import remove the violation? If yes, do it.
3. **If the test file requires mocking `Session`, the service is wrong.** Refactor to accept a Protocol.
## Anti-Patterns Rejected on Sight
- `def some_service_method(self, db: Session, ...)` → use Protocol-typed repo
- `from app.models.user import User` inside a service → return domain types from the repo
- `httpx.AsyncClient()` instantiated inside a function → use the shared per-provider client from `core/http.py`
- `raise HTTPException(...)` inside a service → raise a domain exception
- `db.query(...)` inside a router → move to service, then repo
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

