Coding Rules Generator
Generate architecture-aware coding rules that AI coding tools (Claude Code, Cursor, GitHub Copilot) enforce automatically across every session. Optionally generates hard enforcement tooling (ESLint, dependency-cruiser, pre-commit hooks, architecture tests).
Input: SDL document
Output: CLAUDE.md, .cursorrules, .github/copilot-instructions.md, per-project CLAUDE.md, optional enforcement configs
What It Generates
Advisory Rules (CLAUDE.md / .cursorrules / copilot-instructions.md)
A single markdown file (output to 3 locations for tool coverage) containing architecture-derived coding rules organized by category:
| Category |
Source SDL Section |
Example Rules |
| Architecture |
architecture.style |
Module boundary rules, service isolation, communication patterns |
| File Structure |
architecture.projects |
Framework conventions, ORM patterns, folder organization |
| Data Access |
data |
Repository pattern, database query rules, search engine usage |
| API Patterns |
architecture.projects.backend |
REST/GraphQL/gRPC conventions, versioning, service base paths |
| Authentication |
auth |
Provider-specific rules (Clerk/Auth0/Cognito), token handling, RBAC |
| Error Handling |
errorHandling |
Error format, global handler, circuit breaker, retry patterns |
| Integrations |
integrations |
Service client isolation, webhook handling, payment/email patterns |
| Testing |
testing |
Framework-specific rules, coverage targets, test structure |
| Observability |
observability |
Logging rules, tracing, metrics collection |
| Security |
nonFunctional.security |
PII handling, encryption, audit logging, OWASP compliance |
| Caching |
data.cache |
Cache invalidation, TTL, cache-aside pattern |
| Queues |
data.queues |
Message handling, idempotency, dead letter queues |
| Code Quality |
(always generated) |
SOLID principles, naming, DRY, single responsibility |
| Design Patterns |
(always generated) |
Framework-appropriate patterns (repository, factory, strategy) |
| File Size & Structure |
(always generated) |
Max file length, function complexity, extraction rules |
| API Design Quality |
(always generated) |
Pagination, filtering, consistent responses, HATEOAS |
| Database Queries |
(always generated) |
N+1 prevention, indexing, query optimization |
| Testing Quality |
(always generated) |
AAA pattern, test naming, mocking boundaries |
| Performance |
(always generated) |
Lazy loading, pagination, connection pooling |
| Import Organization |
(always generated) |
Import ordering, barrel exports, circular dependency prevention |
| Tech Debt Avoidance |
(always generated) |
TODO tracking, deprecation patterns, refactoring triggers |
| Resilience |
(always generated) |
Retry policies, timeouts, fallbacks, circuit breakers |
| Input Validation |
(always generated) |
Schema validation, sanitization, boundary validation |
| Concurrency |
(always generated) |
Race conditions, locking, atomic operations |
| Configuration |
(always generated) |
Env var patterns, secrets management, feature flags |
| Migration Safety |
(always generated) |
Backward compatibility, zero-downtime deploys, rollback |
| Documentation |
(always generated) |
When to document, inline comments, API docs |
| Git Workflow |
(always generated) |
Branch naming, commit messages, PR conventions |
Conditional Categories (added when applicable)
| Category |
Condition |
Rules |
| Accessibility |
Frontend projects exist |
WCAG compliance, ARIA, keyboard navigation, color contrast |
| State Management |
Frontend projects exist |
Framework-specific state rules (React Context, Redux, Zustand) |
| Mobile |
Mobile projects exist |
Platform guidelines, navigation, permissions, offline |
| Internationalization |
Multiple regions defined |
i18n patterns, locale handling, RTL support |
Per-Project Rules
For monorepo setups, generates {project-name}/CLAUDE.md with project-specific rules:
- Backend: framework conventions, API style, ORM patterns, port assignment
- Frontend: rendering mode, styling approach, component library, state management
Enforcement Tooling (Optional)
When coding-rules-enforcement is in artifacts.generate, produces hard gates:
| File |
Purpose |
Language |
.eslintrc.sdl.js |
Custom ESLint rules from architecture |
TypeScript/JS |
pyproject.sdl.toml |
Ruff/flake8 config from architecture |
Python |
.golangci.sdl.yml |
golangci-lint config from architecture |
Go |
.dependency-cruiser.sdl.cjs |
Module boundary enforcement |
TypeScript/JS |
.lintstagedrc.sdl.json |
Pre-commit hook config |
All |
tests/architecture.test.ts |
Architecture conformance tests |
TypeScript |
How Rules Are Generated
Rules are deterministic — same SDL input always produces identical output. The generator:
- Reads architecture style, projects, data layer, auth, integrations from SDL
- Applies framework-specific rule templates (e.g., Express error handling vs FastAPI exception handlers)
- Adds conditional categories based on project composition
- Generates per-project overlays for monorepo setups
- Renders all rules into a single markdown document
Framework-Aware Rules
The generator tailors rules to the specific tech stack:
| Framework |
Tailored Rules |
| Node.js/Express |
Middleware patterns, async/await error handling, route organization |
| Python/FastAPI |
Pydantic models, dependency injection, async endpoints |
| Go |
Interface-based design, error wrapping, goroutine safety |
| .NET 8 |
Controller patterns, DI container, middleware pipeline |
| Java/Spring |
Bean lifecycle, AOP patterns, Spring Security |
| Next.js |
App Router conventions, Server Components, RSC boundaries |
| React |
Hook rules, component composition, render optimization |
When to Use
- After
/architect:scaffold — generate rules that match the scaffolded project structure
- After SDL changes — regenerate to keep rules in sync with architecture evolution
- When onboarding AI tools — drop
CLAUDE.md into any project for instant architecture awareness
- When adding enforcement — use
coding-rules-enforcement artifact for CI/CD gates
Integration
The coding rules generator is available as an SDL artifact type:
artifacts:
generate:
- coding-rules # Advisory rules (CLAUDE.md, .cursorrules, copilot-instructions)
- coding-rules-enforcement # Hard gates (ESLint, dependency-cruiser, pre-commit, arch tests)
Both are generated via the generate_from_sdl agent tool or the /api/sdl/generate endpoint.
Hard Enforcement Tooling
When coding-rules-enforcement is in artifacts.generate, the advisory rules above are backed by hard gates — linters, module boundary checks, architecture tests, pre-commit hooks, and a CI workflow. All configs are derived deterministically from the SDL document.
API: POST /api/sdl/generate with artifactType: "coding-rules-enforcement" (no dedicated route)
Language Detection
The generator inspects architecture.projects.backend[] and frontend[] frameworks to determine which configs to produce:
| Framework |
Language |
Configs Generated |
nodejs |
TypeScript |
ESLint, dependency-cruiser, arch tests |
nextjs, react, vue, angular, svelte |
TypeScript |
ESLint (with React hooks/a11y if applicable) |
python-fastapi |
Python |
Ruff + Mypy config |
go |
Go |
golangci-lint config |
java-spring |
Java |
ArchUnit tests |
dotnet-8 |
C# |
NetArchTest tests |
Files Produced
| File |
Language |
Purpose |
.eslintrc.sdl.js |
TypeScript/JS |
Custom ESLint rules from SDL architecture |
pyproject.sdl.toml |
Python |
Ruff lint + Mypy strict + pytest coverage config |
.golangci.sdl.yml |
Go |
16+ linters with complexity limits |
.dependency-cruiser.sdl.cjs |
TypeScript/JS |
Module boundary enforcement (modular-monolith/microservices) |
.lintstagedrc.sdl.json |
All |
Pre-commit hook command mapping |
.husky/pre-commit |
All |
Git pre-commit hook script |
__tests__/architecture.sdl.test.ts |
TypeScript |
Architecture conformance tests |
src/test/java/architecture/ArchitectureTest.java |
Java |
ArchUnit architecture tests |
tests/Architecture.Tests/ArchitectureTests.cs |
.NET |
NetArchTest architecture tests |
.github/workflows/enforce-architecture.yml |
All |
CI gate workflow |
ESLint Rules (TypeScript/JS)
20+ rules enforced:
@typescript-eslint/no-explicit-any: error — no any type
max-params: 3 — max function parameters
no-console: error (allow warn) — no console.log in production
no-var, prefer-const — modern variable declarations
no-magic-numbers: warn — avoid unlabeled constants
max-depth: 3 — max nesting depth
max-lines: 500 — max file size
max-lines-per-function: 50 — max function length
@typescript-eslint/consistent-type-imports — type-only imports
import/no-cycle — no circular imports
import/order — enforced import ordering
@typescript-eslint/naming-convention — camelCase functions, PascalCase types, UPPER_CASE enums
@typescript-eslint/no-floating-promises — no unhandled promises
no-await-in-loop: warn — avoid sequential async in loops
@typescript-eslint/no-unused-vars — no dead code
React-specific (when frontend uses React/Next.js):
react-hooks/rules-of-hooks — hook call rules
react-hooks/exhaustive-deps — dependency arrays
jsx-a11y/* — accessibility rules (alt-text, valid anchors, key events, labels)
Dependency Cruiser Rules (Module Boundaries)
Generated when architecture.style is modular-monolith or microservices:
| Rule |
Severity |
What It Prevents |
no-circular |
error |
Circular dependencies |
no-cross-module-internals |
error |
Importing another module's internal files (only .interface.ts and .types.ts allowed) |
no-db-in-routes |
error |
Routes importing database directly |
no-repository-in-routes |
error |
Routes bypassing services to access repositories |
shared-no-module-imports |
error |
Shared utilities depending on business modules |
orm-only-in-repositories-{name} |
error |
ORM package imported outside repository files |
Architecture Tests
TypeScript (__tests__/architecture.sdl.test.ts):
- Module Boundaries: no module imports another module's repository or internal files
- Data Access Patterns: service files don't use database client directly; route files don't import repositories
- Security: no hardcoded secrets (Stripe keys, Anthropic keys, base64 keys)
- Dependency Graph: runs dependency-cruiser validation (modular-monolith/microservices)
- Coverage: validates coverage target from SDL
testing.coverage.target
Java (ArchitectureTest.java with ArchUnit):
- Controllers don't access repositories
- Services don't depend on controllers
- Repositories don't depend on services
- No cyclic package dependencies
- Per-module internal access restrictions
.NET (ArchitectureTests.cs with NetArchTest):
- Controllers don't reference repositories
- Services don't depend on controllers
- Repositories don't depend on services
CI Workflow (.github/workflows/enforce-architecture.yml)
Runs on PR to main/develop and push to main. Jobs by language:
| Job |
Steps |
lint-typescript |
npm ci → ESLint → dependency-cruiser → architecture tests |
lint-python |
pip install → ruff check → ruff format → mypy → pytest with coverage |
lint-go |
golangci-lint → go test with coverage threshold |
lint-java |
mvnw verify (includes ArchUnit) |
lint-dotnet |
dotnet restore → dotnet test Architecture.Tests |
commit-lint |
commitlint (conventional commits) |
SDL Sections Used (Enforcement)
| SDL Section |
What It Controls |
architecture.projects.backend[].framework |
Which language configs to generate |
architecture.projects.frontend[].framework |
React hooks/a11y rules, TypeScript linting |
architecture.style |
Enables dependency-cruiser module boundary rules |
architecture.services[] |
Module names for cross-module import restrictions |
architecture.projects.backend[].orm |
ORM-specific import restrictions |
testing.coverage.target |
Coverage enforcement threshold in CI |
Advisory vs. Enforcement
| Aspect |
Advisory rules (above) |
Enforcement tooling (this section) |
| Output |
CLAUDE.md, .cursorrules, copilot-instructions.md |
ESLint, Ruff, golangci-lint, tests, CI |
| Enforcement |
Advisory (AI tool reads them) |
Hard gates (CI blocks violations) |
| Scope |
27+ categories of architecture rules |
Linting, boundaries, secrets, coverage |
| When |
Always useful |
When team needs CI-level enforcement |
Use advisory rules alone for AI-guided development; add coding-rules-enforcement in artifacts.generate for automated CI gates.
1---2name: coding-rules3description: Generate AI-consumable coding rules (CLAUDE.md, .cursorrules, copilot-instructions) and enforcement tooling from SDL4---56# Coding Rules Generator78Generate **architecture-aware coding rules** that AI coding tools (Claude Code, Cursor, GitHub Copilot) enforce automatically across every session. Optionally generates hard enforcement tooling (ESLint, dependency-cruiser, pre-commit hooks, architecture tests).910**Input**: SDL document11**Output**: `CLAUDE.md`, `.cursorrules`, `.github/copilot-instructions.md`, per-project `CLAUDE.md`, optional enforcement configs1213---1415## What It Generates1617### Advisory Rules (CLAUDE.md / .cursorrules / copilot-instructions.md)1819A single markdown file (output to 3 locations for tool coverage) containing architecture-derived coding rules organized by category:2021| Category | Source SDL Section | Example Rules |22|---|---|---|23| Architecture | `architecture.style` | Module boundary rules, service isolation, communication patterns |24| File Structure | `architecture.projects` | Framework conventions, ORM patterns, folder organization |25| Data Access | `data` | Repository pattern, database query rules, search engine usage |26| API Patterns | `architecture.projects.backend` | REST/GraphQL/gRPC conventions, versioning, service base paths |27| Authentication | `auth` | Provider-specific rules (Clerk/Auth0/Cognito), token handling, RBAC |28| Error Handling | `errorHandling` | Error format, global handler, circuit breaker, retry patterns |29| Integrations | `integrations` | Service client isolation, webhook handling, payment/email patterns |30| Testing | `testing` | Framework-specific rules, coverage targets, test structure |31| Observability | `observability` | Logging rules, tracing, metrics collection |32| Security | `nonFunctional.security` | PII handling, encryption, audit logging, OWASP compliance |33| Caching | `data.cache` | Cache invalidation, TTL, cache-aside pattern |34| Queues | `data.queues` | Message handling, idempotency, dead letter queues |35| Code Quality | (always generated) | SOLID principles, naming, DRY, single responsibility |36| Design Patterns | (always generated) | Framework-appropriate patterns (repository, factory, strategy) |37| File Size & Structure | (always generated) | Max file length, function complexity, extraction rules |38| API Design Quality | (always generated) | Pagination, filtering, consistent responses, HATEOAS |39| Database Queries | (always generated) | N+1 prevention, indexing, query optimization |40| Testing Quality | (always generated) | AAA pattern, test naming, mocking boundaries |41| Performance | (always generated) | Lazy loading, pagination, connection pooling |42| Import Organization | (always generated) | Import ordering, barrel exports, circular dependency prevention |43| Tech Debt Avoidance | (always generated) | TODO tracking, deprecation patterns, refactoring triggers |44| Resilience | (always generated) | Retry policies, timeouts, fallbacks, circuit breakers |45| Input Validation | (always generated) | Schema validation, sanitization, boundary validation |46| Concurrency | (always generated) | Race conditions, locking, atomic operations |47| Configuration | (always generated) | Env var patterns, secrets management, feature flags |48| Migration Safety | (always generated) | Backward compatibility, zero-downtime deploys, rollback |49| Documentation | (always generated) | When to document, inline comments, API docs |50| Git Workflow | (always generated) | Branch naming, commit messages, PR conventions |5152### Conditional Categories (added when applicable)5354| Category | Condition | Rules |55|---|---|---|56| Accessibility | Frontend projects exist | WCAG compliance, ARIA, keyboard navigation, color contrast |57| State Management | Frontend projects exist | Framework-specific state rules (React Context, Redux, Zustand) |58| Mobile | Mobile projects exist | Platform guidelines, navigation, permissions, offline |59| Internationalization | Multiple regions defined | i18n patterns, locale handling, RTL support |6061### Per-Project Rules6263For monorepo setups, generates `{project-name}/CLAUDE.md` with project-specific rules:64- Backend: framework conventions, API style, ORM patterns, port assignment65- Frontend: rendering mode, styling approach, component library, state management6667### Enforcement Tooling (Optional)6869When `coding-rules-enforcement` is in `artifacts.generate`, produces hard gates:7071| File | Purpose | Language |72|---|---|---|73| `.eslintrc.sdl.js` | Custom ESLint rules from architecture | TypeScript/JS |74| `pyproject.sdl.toml` | Ruff/flake8 config from architecture | Python |75| `.golangci.sdl.yml` | golangci-lint config from architecture | Go |76| `.dependency-cruiser.sdl.cjs` | Module boundary enforcement | TypeScript/JS |77| `.lintstagedrc.sdl.json` | Pre-commit hook config | All |78| `tests/architecture.test.ts` | Architecture conformance tests | TypeScript |7980---8182## How Rules Are Generated8384Rules are **deterministic** — same SDL input always produces identical output. The generator:85861. Reads architecture style, projects, data layer, auth, integrations from SDL872. Applies framework-specific rule templates (e.g., Express error handling vs FastAPI exception handlers)883. Adds conditional categories based on project composition894. Generates per-project overlays for monorepo setups905. Renders all rules into a single markdown document9192### Framework-Aware Rules9394The generator tailors rules to the specific tech stack:9596| Framework | Tailored Rules |97|---|---|98| Node.js/Express | Middleware patterns, async/await error handling, route organization |99| Python/FastAPI | Pydantic models, dependency injection, async endpoints |100| Go | Interface-based design, error wrapping, goroutine safety |101| .NET 8 | Controller patterns, DI container, middleware pipeline |102| Java/Spring | Bean lifecycle, AOP patterns, Spring Security |103| Next.js | App Router conventions, Server Components, RSC boundaries |104| React | Hook rules, component composition, render optimization |105106---107108## When to Use109110- After `/architect:scaffold` — generate rules that match the scaffolded project structure111- After SDL changes — regenerate to keep rules in sync with architecture evolution112- When onboarding AI tools — drop `CLAUDE.md` into any project for instant architecture awareness113- When adding enforcement — use `coding-rules-enforcement` artifact for CI/CD gates114115## Integration116117The coding rules generator is available as an SDL artifact type:118```yaml119artifacts:120 generate:121 - coding-rules # Advisory rules (CLAUDE.md, .cursorrules, copilot-instructions)122 - coding-rules-enforcement # Hard gates (ESLint, dependency-cruiser, pre-commit, arch tests)123```124125Both are generated via the `generate_from_sdl` agent tool or the `/api/sdl/generate` endpoint.126127---128129## Hard Enforcement Tooling130131When `coding-rules-enforcement` is in `artifacts.generate`, the advisory rules above are backed by hard gates — linters, module boundary checks, architecture tests, pre-commit hooks, and a CI workflow. All configs are derived deterministically from the SDL document.132133**API**: `POST /api/sdl/generate` with `artifactType: "coding-rules-enforcement"` (no dedicated route)134135### Language Detection136137The generator inspects `architecture.projects.backend[]` and `frontend[]` frameworks to determine which configs to produce:138139| Framework | Language | Configs Generated |140|-----------|----------|-------------------|141| `nodejs` | TypeScript | ESLint, dependency-cruiser, arch tests |142| `nextjs`, `react`, `vue`, `angular`, `svelte` | TypeScript | ESLint (with React hooks/a11y if applicable) |143| `python-fastapi` | Python | Ruff + Mypy config |144| `go` | Go | golangci-lint config |145| `java-spring` | Java | ArchUnit tests |146| `dotnet-8` | C# | NetArchTest tests |147148### Files Produced149150| File | Language | Purpose |151|------|----------|---------|152| `.eslintrc.sdl.js` | TypeScript/JS | Custom ESLint rules from SDL architecture |153| `pyproject.sdl.toml` | Python | Ruff lint + Mypy strict + pytest coverage config |154| `.golangci.sdl.yml` | Go | 16+ linters with complexity limits |155| `.dependency-cruiser.sdl.cjs` | TypeScript/JS | Module boundary enforcement (modular-monolith/microservices) |156| `.lintstagedrc.sdl.json` | All | Pre-commit hook command mapping |157| `.husky/pre-commit` | All | Git pre-commit hook script |158| `__tests__/architecture.sdl.test.ts` | TypeScript | Architecture conformance tests |159| `src/test/java/architecture/ArchitectureTest.java` | Java | ArchUnit architecture tests |160| `tests/Architecture.Tests/ArchitectureTests.cs` | .NET | NetArchTest architecture tests |161| `.github/workflows/enforce-architecture.yml` | All | CI gate workflow |162163### ESLint Rules (TypeScript/JS)16416520+ rules enforced:166167- `@typescript-eslint/no-explicit-any: error` — no `any` type168- `max-params: 3` — max function parameters169- `no-console: error` (allow warn) — no console.log in production170- `no-var, prefer-const` — modern variable declarations171- `no-magic-numbers: warn` — avoid unlabeled constants172- `max-depth: 3` — max nesting depth173- `max-lines: 500` — max file size174- `max-lines-per-function: 50` — max function length175- `@typescript-eslint/consistent-type-imports` — type-only imports176- `import/no-cycle` — no circular imports177- `import/order` — enforced import ordering178- `@typescript-eslint/naming-convention` — camelCase functions, PascalCase types, UPPER_CASE enums179- `@typescript-eslint/no-floating-promises` — no unhandled promises180- `no-await-in-loop: warn` — avoid sequential async in loops181- `@typescript-eslint/no-unused-vars` — no dead code182183**React-specific** (when frontend uses React/Next.js):184- `react-hooks/rules-of-hooks` — hook call rules185- `react-hooks/exhaustive-deps` — dependency arrays186- `jsx-a11y/*` — accessibility rules (alt-text, valid anchors, key events, labels)187188### Dependency Cruiser Rules (Module Boundaries)189190Generated when `architecture.style` is `modular-monolith` or `microservices`:191192| Rule | Severity | What It Prevents |193|------|----------|-----------------|194| `no-circular` | error | Circular dependencies |195| `no-cross-module-internals` | error | Importing another module's internal files (only `.interface.ts` and `.types.ts` allowed) |196| `no-db-in-routes` | error | Routes importing database directly |197| `no-repository-in-routes` | error | Routes bypassing services to access repositories |198| `shared-no-module-imports` | error | Shared utilities depending on business modules |199| `orm-only-in-repositories-{name}` | error | ORM package imported outside repository files |200201### Architecture Tests202203**TypeScript** (`__tests__/architecture.sdl.test.ts`):204- Module Boundaries: no module imports another module's repository or internal files205- Data Access Patterns: service files don't use database client directly; route files don't import repositories206- Security: no hardcoded secrets (Stripe keys, Anthropic keys, base64 keys)207- Dependency Graph: runs dependency-cruiser validation (modular-monolith/microservices)208- Coverage: validates coverage target from SDL `testing.coverage.target`209210**Java** (`ArchitectureTest.java` with ArchUnit):211- Controllers don't access repositories212- Services don't depend on controllers213- Repositories don't depend on services214- No cyclic package dependencies215- Per-module internal access restrictions216217**.NET** (`ArchitectureTests.cs` with NetArchTest):218- Controllers don't reference repositories219- Services don't depend on controllers220- Repositories don't depend on services221222### CI Workflow (`.github/workflows/enforce-architecture.yml`)223224Runs on PR to main/develop and push to main. Jobs by language:225226| Job | Steps |227|-----|-------|228| `lint-typescript` | npm ci → ESLint → dependency-cruiser → architecture tests |229| `lint-python` | pip install → ruff check → ruff format → mypy → pytest with coverage |230| `lint-go` | golangci-lint → go test with coverage threshold |231| `lint-java` | mvnw verify (includes ArchUnit) |232| `lint-dotnet` | dotnet restore → dotnet test Architecture.Tests |233| `commit-lint` | commitlint (conventional commits) |234235### SDL Sections Used (Enforcement)236237| SDL Section | What It Controls |238|-------------|-----------------|239| `architecture.projects.backend[].framework` | Which language configs to generate |240| `architecture.projects.frontend[].framework` | React hooks/a11y rules, TypeScript linting |241| `architecture.style` | Enables dependency-cruiser module boundary rules |242| `architecture.services[]` | Module names for cross-module import restrictions |243| `architecture.projects.backend[].orm` | ORM-specific import restrictions |244| `testing.coverage.target` | Coverage enforcement threshold in CI |245246### Advisory vs. Enforcement247248| Aspect | Advisory rules (above) | Enforcement tooling (this section) |249|--------|----------------|---------------------------|250| Output | CLAUDE.md, .cursorrules, copilot-instructions.md | ESLint, Ruff, golangci-lint, tests, CI |251| Enforcement | Advisory (AI tool reads them) | Hard gates (CI blocks violations) |252| Scope | 27+ categories of architecture rules | Linting, boundaries, secrets, coverage |253| When | Always useful | When team needs CI-level enforcement |254255Use advisory rules alone for AI-guided development; add `coding-rules-enforcement` in `artifacts.generate` for automated CI gates.