HOME / SDD HUB / TEMPLATES / CONSTITUTION.MD
SPEC-DRIVEN DEVELOPMENT · PHASE 0 FOUNDATION

Project Constitution Guide & Templates

Lock Architectural Invariants, Prohibited Anti-Patterns, and Decision Precedence for AI Coding Agents

What is a Project Constitution (constitution.md)?

In Spec-Driven Development (SDD), a Project Constitution (constitution.md) serves as the supreme governance document of your repository. It acts as the immutable contract that dictates how human developers and autonomous AI coding agents (such as Cursor, Claude Code, and Devin) must write, structure, and verify software.

A common failure mode in AI-assisted engineering is architectural drift. As conversation threads grow, AI models lose context, introduce duplicate libraries, bypass abstraction layers, or invent conflicting state patterns. While prompt-level instructions like .cursorrules provide temporary style hints, a project constitution establishes permanent invariant laws that persist across every prompt, commit, and feature branch.

The Spec Bundle Hierarchy A production Spec Bundle consists of four tightly-coupled documents created across sequential phases:
  • constitution.md (Foundation): Non-negotiable principles, invariants, boundaries, and decision hierarchy.
  • requirements.md (Phase 1): Functional specifications authored in strict EARS+ syntax.
  • solution.md (Phase 2): Technical implementation details, database schemas, and Mermaid sequence diagrams.
  • tasks.md (Phase 3): Granular, testable implementation items sequenced for AI agents.

The 5 Pillars of a Production Constitution

A constitution is not a simple list of packages in your package.json. An effective constitution defines five core structural pillars:

1. Architectural Invariants

Immutable structural rules that must never be broken (e.g., domain entities must never import from transport controllers, database operations must be transactional, state must flow unidirectionally).

2. Technology Contracts

Strict language and framework versions. Explicit typing mandates (e.g., zero any types, strict null checks, runtime boundary parsing with Zod or Pydantic).

3. Prohibited Patterns (Anti-Patterns)

The "Negative Bill of Rights." Explicit prohibitions on actions AI agents frequently attempt (e.g., raw SQL strings, modifying committed migrations, disabling linters).

4. Quality & Verification Gates

Standard verification commands required before any commit is accepted (e.g., test suites, lint checks, typecheck commands, minimum code coverage thresholds).

5. Decision Precedence Hierarchy

When architectural trade-offs clash during implementation, AI agents must resolve ambiguity using this explicit ranking:

1. Security & Correctness > 2. Data Integrity > 3. Test Coverage > 4. Performance > 5. Developer Convenience

Template 1: Next.js 15 / React 19 Full-Stack

TYPESCRIPT · DRIZZLE · POSTGRES

Designed for modern full-stack web applications using the Next.js App Router, Server Actions, Drizzle ORM, and Tailwind CSS.

# Project Constitution: Next.js 15 Full-Stack

## 1. Core Architectural Invariants
1.1 Framework Standard: Next.js 15 with App Router only. The legacy Pages Router (/pages) is strictly prohibited.
1.2 Layer Isolation:
    - Route Handlers & Server Actions handle transport validation and authentication only.
    - Domain business logic must reside in dedicated service modules (/src/services/).
    - React components (/src/components/) are presentation-only; components must not execute direct database queries.
1.3 Unidirectional Data Flow: UI components receive data via Server Components or typed Server Action responses. Client components must not maintain duplicate remote state.

## 2. Technology Stack Contracts
2.1 Runtime & Language: Node.js 22 LTS, TypeScript with strict mode enabled.
2.2 Database & ORM: PostgreSQL with Drizzle ORM. All schema modifications must occur via Drizzle migrations.
2.3 Runtime Validation: All external inputs (request bodies, query params, server action payloads) must be validated with Zod schemas.
2.4 Styling: Tailwind CSS v4 using semantic design tokens. Raw inline hex styles and CSS modules are forbidden.

## 3. Prohibited Patterns (Strict Negative Constraints)
- NEVER use `any`, `unknown` without narrowing, or `@ts-ignore`.
- NEVER write raw SQL strings. All queries must use Drizzle ORM query builders or prepared statements.
- NEVER edit an existing migration file that has been committed to source control. Always generate a new incremental migration.
- NEVER commit credentials, API keys, or private environment variables.
- NEVER install new npm packages without explicit developer authorization in tasks.md.
- NEVER swallow errors in try/catch blocks without structured logging and user-facing error boundaries.

## 4. Error Handling & Telemetry
4.1 Server Actions must return a standardized Result type: `{ success: true, data: T } | { success: false, error: { code: string, message: string } }`.
4.2 Client errors must be captured via React Error Boundaries and dispatched to PostHog telemetry.

## 5. Verification Gates
Before proposing any code change, the agent must verify:
1. `npm run typecheck` passes with zero errors.
2. `npm run lint` passes with zero warnings.
3. `npm run test` passes all unit and integration tests.

## 6. Decision Precedence
1. Security & Authentication > 2. Data Integrity > 3. Type Safety > 4. Rendering Performance > 5. Brevity

Template 2: Cloud-Native Python / FastAPI

PYTHON 3.12+ · ASYNCPG · SQLALCHEMY 2.0

Designed for high-throughput asynchronous backend APIs and microservices using FastAPI, Pydantic v2, and SQLAlchemy 2.0.

# Project Constitution: Cloud-Native Python FastAPI

## 1. Core Architectural Invariants
1.1 Asynchronous I/O: All database operations, external HTTP calls, and file I/O must be 100% non-blocking using `async` and `await`.
1.2 Clean Layered Architecture:
    - Routers (/app/api/): Handle HTTP requests, dependency injection, and Pydantic schema validation.
    - Services (/app/services/): Contain core business logic. Must be framework-agnostic.
    - Repositories (/app/repositories/): Encapsulate SQLAlchemy queries. Services must never access database sessions directly.
1.3 Explicit Session Lifecycle: Database sessions (`AsyncSession`) are managed via FastAPI dependency injection with automatic rollback on unhandled exceptions.

## 2. Technology Stack Contracts
2.1 Language: Python 3.12+ with strict type hints on every function signature (`mypy --strict`).
2.2 Web Framework: FastAPI with Uvicorn.
2.3 Database & Migrations: PostgreSQL via `asyncpg`, SQLAlchemy 2.0 (mapped declarative models only), Alembic for schema migrations.
2.4 Data Parsing: Pydantic v2 BaseModels with strict validation enabled (`extra = "forbid"`).

## 3. Prohibited Patterns (Strict Negative Constraints)
- NEVER execute blocking synchronous operations (e.g., `requests.get()`, `time.sleep()`, standard open() for disk I/O). Always use `httpx.AsyncClient` and `asyncio.sleep()`.
- NEVER return raw SQLAlchemy model instances directly from endpoints. Always serialize through explicit Pydantic response models.
- NEVER modify existing Alembic migration files once committed. Always generate new migration revisions with descriptive messages.
- NEVER catch generic `Exception` without re-raising or converting to an RFC-7807 Problem Details response.
- NEVER hardcode secrets or connection strings. All configuration must load from `pydantic-settings` via environment variables.

## 4. Error Handling Standard
4.1 All API error responses must adhere strictly to RFC-7807 Problem Details format:
    `{ "type": "https://api.myspec.dev/errors/{code}", "title": "...", "status": 400, "detail": "...", "instance": "..." }`.

## 5. Verification Gates
Before marking any task complete, the agent must ensure:
1. `uv run ruff check .` passes with zero violations.
2. `uv run mypy .` passes with zero type errors.
3. `uv run pytest --cov=app --cov-report=term-missing` maintains > 85% test coverage.

## 6. Decision Precedence
1. Data Integrity & Atomicity > 2. Security > 3. Async Concurrency Safety > 4. Latency > 5. Code Conciseness

How to Deploy constitution.md in AI Coding Workflows

To get the most out of your project constitution, save the file directly in your repository root or under a dedicated specs directory:

Recommended Repository Path: specs/<bundle>/constitution.md (committed) - the MySpec MCP server downloads a working copy into a gitignored .specs/ mirror
Integrating with Cursor (.cursorrules):

Add a single directive in your .cursorrules file to enforce the constitution on every prompt:

You are an autonomous senior engineer. Before proposing any changes or writing code, read and strictly adhere to all invariants, prohibitions, and verification gates specified in specs/<bundle>/constitution.md. Never violate the decision precedence hierarchy.
Integrating with Claude Code (CLAUDE.md):

Reference your constitution directly inside your CLAUDE.md instructions:

## Architectural Governance
All project architecture, coding constraints, and prohibited patterns are codified in specs/<bundle>/constitution.md. Every proposed diff must satisfy the verification gates listed in that document.

Generate Custom Constitutions with MySpec

MySpec conducts an architectural interview to capture your specific tech stack, security constraints, and coding rules, then automatically synthesizes a tailored constitution.md for your repository.