Constraints
Documents how Drift discovers, manages, and enforces architectural constraints as invariants in your codebase.
What this file does
Documents how Drift discovers, manages, and enforces architectural constraints as invariants in your codebase.
When to use it
- Adopting Drift's constraint system for automated architecture enforcement
- Defining team rules that must be checked in CI
- Migrating from manual code review to automated quality gates
- Creating custom constraints for project-specific patterns
Assumes this stack
Constraints
Architectural constraints are invariants that MUST be satisfied in your codebase. Drift learns these from your code and enforces them.
What are Constraints?
Constraints are rules that define how your codebase should be structured:
- "All API routes must have authentication"
- "Controllers cannot import database modules directly"
- "Services must be in the services/ directory"
- "Error responses must follow the standard format"
Unlike patterns (which describe HOW you do things), constraints describe what MUST or MUST NOT happen.
Constraint Lifecycle
Your Code → Drift Extracts → Discovered → You Review → Approved/Ignored → Enforced
- Extraction — Drift analyzes your code and discovers implicit constraints
- Discovery — New constraints await your review
- Approval — You approve constraints that should be enforced
- Enforcement — Drift flags violations in quality gates
Extracting Constraints
Drift can automatically discover constraints from your codebase:
drift constraints extract
Output:
Constraint Extraction
=====================
Discovered 12 new constraints:
HIGH CONFIDENCE (3):
auth-required-on-api
"All /api/* routes use authentication middleware"
Confidence: 0.95 (47/49 routes)
services-in-services-dir
"Service classes are located in src/services/"
Confidence: 0.92 (23/25 services)
error-response-format
"Error responses use { error: string, code: number } format"
Confidence: 0.91 (34/37 error handlers)
MEDIUM CONFIDENCE (5):
...
LOW CONFIDENCE (4):
...
Run 'drift constraints list' to see all constraints.
Managing Constraints
List Constraints
# List all constraints
drift constraints list
# Filter by status
drift constraints list --status discovered
drift constraints list --status approved
# Filter by category
drift constraints list --category auth
drift constraints list --category structural
Output:
Constraints
===========
APPROVED (5):
✓ auth-required-on-api (auth)
All /api/* routes use authentication middleware
✓ no-direct-db-in-controllers (structural)
Controllers cannot import database modules
✓ services-in-services-dir (structural)
Service classes in src/services/
...
DISCOVERED (7):
? error-response-format (api)
Error responses use standard format
Confidence: 0.91
? logging-in-services (logging)
Services use structured logging
Confidence: 0.85
...
IGNORED (2):
✗ legacy-auth-pattern (auth)
Ignored: Migrating to new auth system
Show Constraint Details
drift constraints show auth-required-on-api
Output:
Constraint: auth-required-on-api
================================
Category: auth
Status: approved
Confidence: 0.95
Description:
All /api/* routes use authentication middleware
Rule:
Source: src/api/**/*.ts, src/routes/**/*.ts
Requires: @RequireAuth, @Authenticate, authMiddleware
Evidence (47 locations):
src/api/users.controller.ts:12 - @RequireAuth()
src/api/orders.controller.ts:8 - @RequireAuth()
src/routes/payments.ts:15 - authMiddleware
...
Violations (2):
⚠️ src/api/health.ts:5 - No auth (intentional?)
⚠️ src/api/webhooks.ts:12 - No auth (webhook endpoint)
Approve Constraints
# Approve a specific constraint
drift constraints approve auth-required-on-api
Ignore Constraints
# Ignore a constraint
drift constraints ignore legacy-auth-pattern --reason "Migrating to new system"
Verify Files
Check if a file satisfies all constraints:
drift constraints verify src/api/users.controller.ts
Output:
Constraint Verification: src/api/users.controller.ts
====================================================
✓ auth-required-on-api
Route has @RequireAuth decorator
✓ no-direct-db-in-controllers
No database imports found
✓ error-response-format
Error responses use standard format
⚠️ logging-in-services (discovered, not enforced)
Missing structured logging
All approved constraints satisfied.
Check All Files
Check all source files against constraints:
drift constraints check
Options:
-c, --category <category>— Filter by category--min-confidence <number>— Minimum confidence threshold
Export Constraints
Export constraints to a JSON file:
drift constraints export constraints-backup.json
Options:
-c, --category <category>— Filter by category-s, --status <status>— Filter by status
Constraint Categories
| Category | Description | Examples |
|---|---|---|
auth | Authentication/authorization | Auth middleware required |
api | API design rules | Response format, versioning |
structural | Code organization | File locations, naming |
security | Security requirements | Input validation, sanitization |
data | Data access rules | No direct DB in controllers |
error | Error handling | Standard error format |
test | Testing requirements | Test file locations |
logging | Observability | Structured logging |
performance | Performance rules | Caching requirements |
validation | Input validation | Schema validation |
Custom Constraints
Create custom constraints in .drift/constraints/custom/:
{
"id": "no-console-in-production",
"name": "No console.log in production code",
"category": "logging",
"description": "Use structured logger instead of console.log",
"rule": {
"type": "forbidden-pattern",
"pattern": "console\\.(log|warn|error)\\(",
"files": "src/**/*.ts",
"exclude": ["**/*.test.ts", "**/*.spec.ts"]
},
"severity": "warning",
"message": "Use logger.info/warn/error instead of console methods"
}
Rule Types
| Type | Description |
|---|---|
forbidden-pattern | Regex pattern that must NOT appear |
required-pattern | Regex pattern that MUST appear |
import-restriction | Module import rules |
file-location | File must be in specific directory |
naming-convention | File/class/function naming rules |
dependency-rule | Module dependency restrictions |
Import Restriction Example
{
"id": "no-db-in-controllers",
"name": "No database imports in controllers",
"category": "structural",
"rule": {
"type": "import-restriction",
"source": "src/controllers/**/*.ts",
"forbidden": ["prisma", "@prisma/client", "src/db/**"]
}
}
File Location Example
{
"id": "services-location",
"name": "Services must be in services directory",
"category": "structural",
"rule": {
"type": "file-location",
"pattern": "*Service.ts",
"allowedPaths": ["src/services/**", "src/**/services/**"]
}
}
CI Integration
Quality Gate
Constraints are checked by the constraint-verification gate:
drift gate --gates constraint-verification
GitHub Actions
- name: Check Constraints
run: |
drift constraints check
drift gate --gates constraint-verification --format github
Pre-commit Hook
#!/bin/sh
# .husky/pre-commit
# Check constraints on changed files
drift constraints check
MCP Integration
drift_constraints Tool
{
"action": "list",
"status": "approved",
"category": "auth"
}
Actions:
list— List all constraintsshow— Show constraint details (requiresid)extract— Discover new constraints from codebaseapprove— Approve a constraint (requiresid)ignore— Ignore a constraint (requiresid, optionalreason)verify— Verify file against constraints (requiresfile)
Parameters:
action— Required. The action to performid— Constraint ID for show/approve/ignore actionsfile— File path for verify actioncategory— Filter by category:api,auth,data,error,test,security,structural,performance,logging,validationstatus— Filter by status:discovered,approved,ignored,customlimit— Max results (default: 20)minConfidence— Minimum confidence (0-1)reason— Reason for ignore action
Example: Check Before Generating Code
{
"action": "verify",
"file": "src/api/new-endpoint.ts"
}
Best Practices
1. Start with High-Confidence Constraints
drift constraints extract --min-confidence 0.9
drift constraints list --status discovered
# Review and approve individually
drift constraints approve <constraint-id>
2. Review Discovered Constraints Regularly
drift constraints list --status discovered
3. Document Why Constraints Exist
drift constraints approve auth-required --note "Security requirement per SOC2"
4. Use Custom Constraints for Team Rules
Create .drift/constraints/custom/team-rules.json for rules specific to your team.
5. Integrate with CI
drift gate --gates constraint-verification --fail-on error
Troubleshooting
No constraints discovered
- Run a full scan first:
drift scan - Check you have enough code for patterns to emerge
- Lower confidence threshold:
drift constraints extract --min-confidence 0.5
Too many false positives
- Ignore irrelevant constraints:
drift constraints ignore <id> - Add exceptions to custom constraints
- Adjust confidence thresholds
Constraint not being enforced
- Check constraint is approved:
drift constraints show <id> - Verify quality gate includes
constraint-verification - Check file isn't excluded in constraint rule
Next Steps
- Quality Gates — Enforce constraints in CI
- Contracts — API contract verification
- Configuration — Customize constraint settings
What's inside
12 sections covering lifecycle, extraction, management, categories, custom rules, CI integration, MCP tool, and troubleshooting
Change this for your project
- Replace
dadbodgeoff/driftwith your own Drift repository reference - Replace
.drift/constraints/custom/with your actual custom constraints directory - Replace
src/paths in examples with your project's source directory
Where it goes
Keep it in your repository where the agent or team that needs it will read it.
Worth borrowing
- Constraint lifecycle from extraction through approval to enforcement mirrors a review workflow
- Custom constraints use rule types like forbidden-pattern and import-restriction that are reusable across projects
Related Documents
DunApp PWA - Project Constraints
Defines 14 hard constraints for a Hungarian PWA project, banning Netlify deployment and enforcing local-only testing, Supabase backend, and zero-cost development.
Constraints
Defines a three-tier priority system for design decisions, with conflict resolution examples to guide trade-offs.
Version Constraints Guide
Teaches Composer version constraint syntax for WordPress plugins and themes using a custom shell script wrapper.
Specifying version constraints
Explains how to pin Terraform CLI, provider, and Ansible versions for IBM Cloud Schematics workspaces and actions.