Cursor Rules TemplatesCursor Rules Template

Cursor Rules Template: FastAPI + SQLAlchemy for AI Legal Research Assistant

Cursor rules template for building an AI legal research assistant with citations, case summaries, document search, and memo generation using Python FastAPI, SQLAlchemy, and PostgreSQL.

.cursorrules template.cursorrulescursor-rulesfastapisqlalchemypostgresqllegal researchcitationmemo generationai legal research

Target User

Developers building an AI legal research assistant with citations, case summaries, document search, and memo generation

Use Cases

  • Legal research automation with precise citations
  • Automated case summaries and topical digests
  • Document repository search with context-aware retrieval
  • Memo generation with structured citations and summaries

Markdown Template

Cursor Rules Template: FastAPI + SQLAlchemy for AI Legal Research Assistant

Framework Role & Context:
- You are an AI coding assistant specialized in building an AI Legal Research Assistant using Python, FastAPI, SQLAlchemy, and PostgreSQL. Your task is to provide concrete, testable instructions that lead to a production-ready implementation with precise citations and memo generation.
- You must cite sources with standard legal citation formats and attach page numbers or section identifiers when available.

Code Style and Style Guides:
- Follow PEP8, Black formatting, and isort for imports.
- Type hints with mypy, explicit return types, and clear docstrings.
- Use meaningful variable names and modular code design.

Architecture & Directory Rules:
- Project root contains: app/, core/, data/, services/, tests/ and migrations/
- app/api/ for endpoints, app/core/ for config, app/data/ for ORM models and migrations, app/services/ for business logic, app/models/ for SQLAlchemy models, app/tests/ for tests.
- Use Alembic for migrations and a migrations/ folder under app/data/.

Authentication & Security Rules:
- Implement OAuth2 with JWT access tokens for API endpoints.
- Secrets sourced from environment variables; never hard-code secrets.
- Enforce RBAC for sensitive legal operations (e.g., document access, memo export).

Database and ORM patterns:
- PostgreSQL as the database, SQLAlchemy ORM with declarative base.
- Use explicit relationships, back_populates, and lazy='select'.
- Migrations via Alembic; models: User, Document, Case, Citation, Memo.
- Avoid raw SQL in application code; parameterize all queries.

Testing & Linting Workflows:
- Use pytest with pytest-asyncio for async endpoints.
- Include unit tests for models and services; integration tests for API endpoints.
- Run pre-commit with Black, isort, Flake8, and Mypy on commit.
- CI should run tests, type checks, and linting on push.

Prohibited Actions and Anti-patterns for the AI:
- Do not hallucinate citations or fabricate case identifiers; always attach verifiable sources.
- Do not access non-public data without authorization; do not bypass auth checks.
- Do not perform network I/O or external fetches during reasoning without explicit user consent.
- Do not construct queries that leak internal secrets or expose private data.

Overview

This Cursor rules template documents a complete configuration for building an AI legal research assistant on the Python FastAPI + SQLAlchemy + PostgreSQL stack using Cursor AI. The rules define how the AI should reason about legal citations, generate precise case summaries, perform document search, and compose memos with traceable sources. It includes strict adherence to citation formats and safe AI practices suitable for production-grade legal tooling.

When to Use These Cursor Rules

  • You are architecting an AI legal research assistant that must cite authoritative cases and statutes.
  • You need deterministic memo generation with structured citations and source links.
  • Your app performs document search against a PostgreSQL-backed repository and returns ranked results with context.
  • You require a testable, linted FastAPI service with SQLAlchemy ORM patterns and strict security controls.

Copyable .cursorrules Configuration

Framework Role & Context:
- You are an AI coding assistant specialized in building an AI Legal Research Assistant using Python, FastAPI, SQLAlchemy, and PostgreSQL. Your task is to provide concrete, testable instructions that lead to a production-ready implementation with precise citations and memo generation.
- You must cite sources with standard legal citation formats and attach page numbers or section identifiers when available.

Code Style and Style Guides:
- Follow PEP8, Black formatting, and isort for imports.
- Type hints with mypy, explicit return types, and clear docstrings.
- Use meaningful variable names and modular code design.

Architecture & Directory Rules:
- Project root contains: app/, core/, data/, services/, tests/ and migrations/
- app/api/ for endpoints, app/core/ for config, app/data/ for ORM models and migrations, app/services/ for business logic, app/models/ for SQLAlchemy models, app/tests/ for tests.
- Use Alembic for migrations and a migrations/ folder under app/data/.

Authentication & Security Rules:
- Implement OAuth2 with JWT access tokens for API endpoints.
- Secrets sourced from environment variables; never hard-code secrets.
- Enforce RBAC for sensitive legal operations (e.g., document access, memo export).

Database and ORM patterns:
- PostgreSQL as the database, SQLAlchemy ORM with declarative base.
- Use explicit relationships, back_populates, and lazy='select'.
- Migrations via Alembic; models: User, Document, Case, Citation, Memo.
- Avoid raw SQL in application code; parameterize all queries.

Testing & Linting Workflows:
- Use pytest with pytest-asyncio for async endpoints.
- Include unit tests for models and services; integration tests for API endpoints.
- Run pre-commit with Black, isort, Flake8, and Mypy on commit.
- CI should run tests, type checks, and linting on push.

Prohibited Actions and Anti-patterns for the AI:
- Do not hallucinate citations or fabricate case identifiers; always attach verifiable sources.
- Do not access non-public data without authorization; do not bypass auth checks.
- Do not perform network I/O or external fetches during reasoning without explicit user consent.
- Do not construct queries that leak internal secrets or expose private data.

Recommended Project Structure

app/
├── api/
│   ├── v1/
│   │   └── endpoints/
│   └── dependencies/
├── core/
│   ├── config.py
│   └── security.py
├── data/
│   ├── models/
│   │   ├── base.py
│   │   ├── user.py
│   │   ├── document.py
│   │   ├── case.py
│   │   └── memo.py
│   ├── migrations/
│   └── database.py
├── services/
│   ├── search.py
│   ├── memo.py
│   └── citations.py
├── models/
│   └── sql.py
├── tests/
│   ├── test_models.py
│   ├── test_api.py
│   └── conftest.py
└── main.py

Core Engineering Principles

  • Explicitness: Clear data models, explicit database queries, and well-defined API contracts.
  • Security by design: OAuth2, RBAC, secrets management, audit logging.
  • Determinism: Reproducible results and citation traceability for every answer.
  • Testability: Unit, integration, and end-to-end tests with CI enforcement.
  • Maintainability: Small, focused modules with well-scoped responsibilities.

Code Construction Rules

  • Endpoint handlers must delegate to services, not perform business logic directly.
  • ORM queries must be parameterized; avoid string concatenation for SQL.
  • Models must include __tablename__, primary keys, and relationship mappings with lazy loading where appropriate.
  • Validation: Use Pydantic models for request bodies and responses, with strict field types.
  • Citation handling: Always attach source identifiers and page references; provide a citations field in memo outputs.
  • Performance: Use asynchronous DB sessions where supported; avoid blocking calls in endpoints.

Security and Production Rules

  • Use HTTPS in all environments; enforce TLS 1.2+.
  • Store secrets in a provider-managed secret store or environment variables; rotate regularly.
  • Implement input validation to prevent injection attacks and enforce access controls on document fetches.
  • Enable audit logging for access to documents and memo exports; protect PII.

Testing Checklist

  • Unit tests for models and service functions with isolated dependencies.
  • Integration tests for API endpoints using test clients; validate status codes and response shapes.
  • End-to-end tests for search, citation generation, and memo export flows.
  • Static typing check with mypy and linting with Flake8/Black in CI.
  • Security tests: token validation, RBAC behavior, and input sanitation checks.

Common Mistakes to Avoid

  • Inline SQL or dynamic string building for queries within business logic.
  • Skipping migrations or relying on schema drift during deployment.
  • Allowing untrusted user input to drive citation sources or search terms without validation.
  • Neglecting proper error handling for external data fetches and memo exports.

Related Cursor rules templates

Explore adjacent Cursor rules templates for similar stacks, workflows, and production constraints.

FAQ

What stack is this Cursor Rules Template tailored for?

This template targets a Python-based FastAPI + SQLAlchemy + PostgreSQL stack for building an AI legal research assistant with citations, case summaries, document search, and memo generation.

Can I adapt this for a different ORM?

Yes. The rules define architecture and patterns for SQLAlchemy; if you switch ORMs, map the same concepts to the new ORM with equivalent relationships, migrations, and query patterns. Do not bypass the authentication and citation rules when changing the data layer.

How are citations validated in memo outputs?

Citations must reference verifiable sources with page numbers or section identifiers. The AI should provide a citation string alongside each fact, and the memo should include a references section listing all cited sources with URLs whenever available.

What security practices are enforced?

Tokens are validated on every request; access to documents requires proper RBAC; secrets are not hard-coded and are rotated regularly. Audit logs capture access and export actions to support compliance and incident response.

How do I test the document search component?

Use integration tests that seed a test PostgreSQL database, index documents in a test search layer, and validate ranked results, relevance scoring, and citation extraction in responses.

How should memo generation handle edge cases?

Guard against empty results, missing citations, or partial data. Always return a structured memo with a citations block, metadata, and a summary. If data is insufficient, politely request user clarification instead of fabricating content.