agentleFS
yerdaulet-damiryerdaulet-damir/vibe-coding-rules/.cursor/rules/architecture.mdc

vibe-coding-rules / rules

Cursor rule28 starsChanged 7 months agoMITView on GitHub

FastAPI layer architecture rules — Router → Service → Repository with Protocol injection

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
  1. Very specific:

    Every endpoint declares response_model= for OpenAPI fidelity.

    line 19
  2. Very specific:

    Every endpoint (except /auth/*) requires user_id: str = Depends(get_current_user_id).

    line 20
  3. Very specific:

    Every query scoped by user_id (multi-tenancy).

    line 80
  4. Very specific:

    Use FastAPI Depends() + factory functions in app/core/deps.py.

    line 90
  5. Distinctive:

    When editing a file, ask:

    line 118
  6. Distinctive:

    Does this import cross the boundary?: Run mentally: would moving this import remove the violation?

    line 121

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
architecture.mdc
---
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

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.