返回 Skills
giuseppe-trisciuoglio/developer-kit· MIT 内容可用

constitution

Creates, updates, validates, and displays the architectural DNA of a project through two shared documents: docs/specs/architecture.md (technology stack, architectural rules, security constraints, AI guardrails) and docs/specs/ontology.md (domain glossary / Ubiquitous Language). Use BEFORE brainstorm as a project setup step, or at any point in the SDD lifecycle to validate specs/tasks against architecture principles. Triggers on 'create constitution', 'update constitution', 'constitution check', 'validate against constitution', 'project principles', 'architectural guardrails', 'setup project architecture', 'define ontology'.

安装

与 skills.sh 相同的 Command / Prompt 安装方式


name: constitution description: "Creates, updates, validates, and displays the architectural DNA of a project through two shared documents: docs/specs/architecture.md (technology stack, architectural rules, security constraints, AI guardrails) and docs/specs/ontology.md (domain glossary / Ubiquitous Language). Use BEFORE brainstorm as a project setup step, or at any point in the SDD lifecycle to validate specs/tasks against architecture principles. Triggers on 'create constitution', 'update constitution', 'constitution check', 'validate against constitution', 'project principles', 'architectural guardrails', 'setup project architecture', 'define ontology'." allowed-tools: Read, Write, Edit, Grep, Glob, Bash, AskUserQuestion, TodoWrite

Overview

The Constitution skill manages the architectural DNA of a project through two shared documents:

FilePurpose
docs/specs/architecture.mdTechnology stack, infrastructure, architectural rules, security constraints, AI guardrails
docs/specs/ontology.mdDomain glossary (Ubiquitous Language) — terms, definitions, bounded contexts

These files live at docs/specs/ and are shared across all specifications. Unlike a monolithic constitution.md, these are created/enriched by brainstorm (Phase 6.8.6) and spec-to-tasks (Phase 1.5).

Instructions

  1. Identify the operation from $ARGUMENTS or user intent: create, update, check, or show.
  2. For create: ask which files to create (architecture.md, ontology.md, or both), gather required information via AskUserQuestion, then write the files using the templates below.
  3. For update: identify the target file and section, apply the change surgically, update the Last Updated date.
  4. For check: read both constitution files, read the target file, validate against architectural rules and ontology terms, output a Constitution Check Report.
  5. For show: read and display both files formatted for readability.
  6. Always confirm with the user before writing or overwriting files.

Examples

# Create constitution before first brainstorm
/developer-kit-specs:constitution create

# Validate a spec against architecture and ontology
/developer-kit-specs:constitution check --target=docs/specs/001/2024-01-15--user-auth.md

# Update the security constraints section
/developer-kit-specs:constitution update --file=architecture --section=security

# Show current constitution
/developer-kit-specs:constitution show

When to Use

ScenarioOperation
New project — define stack and domain language before first brainstormcreate
Stack or security rules changedupdate
Validate a spec, task, or file against architecture and ontologycheck
Review current architecture and ontologyshow

Trigger phrases:

  • "Create constitution", "Setup project architecture", "Define ontology"
  • "Update constitution", "Update architecture", "Update ontology"
  • "Constitution check", "Validate against constitution"
  • "Show constitution", "Project principles", "Architectural guardrails"

Operations

create

  1. Ask which files to create: "Both" (recommended), "architecture.md only", "ontology.md only"
  2. Check if files exist → ask to overwrite or skip
  3. For architecture.md: gather via AskUserQuestion (domains, infrastructure, stack, data, style, rules)
  4. For ontology.md: ask for terms or create empty scaffold
  5. Confirm before writing each file

Template lookup order:

  • Primary: ${CLAUDE_PLUGIN_ROOT}/templates/architecture.md
  • Fallback: skills/constitution/references/architecture.md

update

  1. Parse --file=architecture|ontology and --section=<name>
  2. Read target file, apply change surgically
  3. Update Last Updated date
  4. Write file

check

  1. Read both constitution files
  2. Read target file (--target=<path>)
  3. Validate against architecture rules, security constraints, and ontology
  4. Output Constitution Check Report

show

  1. Read both docs/specs/architecture.md and docs/specs/ontology.md
  2. Display formatted for readability

Context Rot Prevention

The Constitution survives context rot through file-based storage:

  • Read at session start: Both docs/specs/architecture.md and docs/specs/ontology.md
  • Never assume in context: MUST be read from file before implementation
  • Validate work: Compare against constitution, not memory

For detailed scenarios and recovery protocols, see references/context-rot-prevention.md.

Constraints and Warnings

  • Does NOT modify source code — only creates/updates constitution files
  • CRITICAL violations MUST be resolved — WARNINGs are advisory
  • One architecture.md and one ontology.md per project — shared across all specs
  • Update Last Updated date on every change
  • Use ADRs for significant architectural decisions
  • Context rot risk: Files > 30 days old may have drifted

Best Practices

  • Create before brainstorm: Constitution established early ensures consistency
  • Library Verification: Before using ANY external library, verify it's in the architecture's Library Verification section
  • Spec Death Principle: Archive completed specs to archived/ — never let specs become stale
  • Ontology enrichment: Updated by brainstorm (Phase 6.8.6) and spec-to-tasks (Phase 1.5)
  • Report format: Security section first, then CWE compliance, architecture, library verification, ontology

Constitution Check Report Format

## Constitution Check Report
Target: <file path>
Date: YYYY-MM-DD

### Security Check (CWE/OWASP Compliance)
| Rule | Level | Status | Location | CWE/OWASP |
|------|-------|--------|----------|-----------|
| No SQL injection | CRITICAL | ✅ OK | - | CWE-89 |

### CWE Compliance Report
| CWE | OWASP | Status | Location |
|-----|-------|--------|----------|
| CWE-89 | A03 | ✅ OK | - |

### Architecture Check
| Rule | Status | Detail |
|------|--------|--------|
| Constructor injection | ✅ OK | - |

### Library Verification Check
| Library | Status | Detail |
|---------|--------|--------|
| bcrypt | ✅ OK | Using hash(password, 12) |

### Ontology Check
| Term | Status | Detail |
|------|--------|--------|
| "User" used consistently | ✅ OK | - |

### Summary
- CRITICAL violations: 0
- WARNING violations: 0
- Compliant rules: N

For detailed security patterns (CWE/OWASP mappings), see references/security-patterns.md.

Integration with SDD Workflow

[Session Start] → Read Constitution files
        ↓
[Optional] constitution create        ← this skill (pre-brainstorm setup)
        ↓
brainstorm                            ← Constitution loaded before brainstorming
        ↓
spec-to-tasks                         ← Constitution validates spec
        ↓
task-implementation                   ← Constitution guardrails active
        ↓
task-review                           ← Constitution check validates
        ↓
[Session End] → Constitution files updated if needed

Required loading before:

  • specs.brainstorm — Validate requirements align with architecture
  • specs.spec-to-tasks — Check stack compatibility
  • specs.task-implementation — Apply AI guardrails
  • specs.task-review — Constitution check

Reference Files

FilePurpose
references/architecture.mdFull architecture template
references/ontology.mdFull ontology template
references/security-patterns.mdCWE/OWASP patterns, verification format
references/context-rot-prevention.mdDetailed scenarios and recovery protocols
references/constitution-check-report.mdComplete report examples

For complete templates and detailed reference material, consult the references/ directory.

附带文件

references/architecture.md
# Project Architecture

**Created**: YYYY-MM-DD
**Last Updated**: YYYY-MM-DD

---

## 1. Logical Architecture

> Describes the decomposition of the system into domains, bounded contexts, modules and their relationships. This section is about WHAT the system does from a domain perspective, independent of technology.

### 1.1 Domains and Bounded Contexts

| Bounded Context | Description | Key Responsibilities | Dependencies |
|-----------------|-------------|----------------------|--------------|
| [e.g., Identity] | [e.g., User authentication and authorization] | [e.g., Registration, Login, RBAC] | [e.g., None — core context] |
| [e.g., Catalog] | [e.g., Product catalog management] | [e.g., CRUD products, categories, search] | [e.g., Identity] |
| [e.g., Ordering] | [e.g., Order lifecycle management] | [e.g., Cart, Checkout, Payment, Fulfillment] | [e.g., Catalog, Identity] |

### 1.2 Module Map

```
┌─────────────────────────────────────────────────────┐
│                    [System Name]                     │
├──────────┬──────────┬──────────┬────────────────────┤
│ [Module] │ [Module] │ [Module] │ [Module]           │
│          │          │          │                    │
│  → [dep] │  → [dep] │          │  → [dep]          │
└──────────┴──────────┴──────────┴────────────────────┘
```

<!-- Describe the logical dependency flow between modules.
     Use arrows (→) to indicate "depends on" relationships.
     Keep it at a high level; this is NOT a class diagram. -->

### 1.3 Shared Kernel

| Shared Concept | Used By | Description |
|---------------|---------|-------------|
| [e.g., Money value object] | [e.g., Catalog, Ordering] | [e.g., Currency + amount, no arithmetic logic] |
| [e.g., Event bus interface] | [e.g., All contexts] | [e.g., In-process event dispatch contract] |

### 1.4 Context Map

<!-- Describe the relationships between bounded contexts.
     Patterns: Upstream/Downstream, Conformist, Anti-Corruption Layer,
     Open Host Service, Published Language, Separate Ways, Partnership. -->

| Upstream | Downstream | Relationship Pattern | Notes |
|----------|-----------|---------------------|-------|
| [e.g., Identity] | [e.g., Ordering] | [e.g., Open Host Service] | [e.g., REST API for user lookup] |
| [e.g., Catalog] | [e.g., Ordering] | [e.g., Published Language] | [e.g., Shared product ID schema] |

---

## 2. Infrastructure Architecture

> Describes the deployment model, networking, data flow, and scaling strategy. This section is about WHERE and HOW the system runs in production.

### 2.1 Deployment Topology

```
[Client/Browser] ──HTTPS──▶ [CDN / Load Balancer]
                                  │
                         ┌────────┴────────┐
                         │   [App Tier]     │
                         │  [e.g., ECS / K8s]│
                         └────────┬────────┘
                                  │
                    ┌─────────────┼─────────────┐
                    │             │             │
              ┌─────┴─────┐ ┌────┴────┐ ┌──────┴─────┐
              │ [Service] │ │[Service]│ │ [Service]  │
              └─────┬─────┘ └────┬────┘ └──────┬─────┘
                    │             │             │
              ┌─────┴─────┐      │      ┌──────┴─────┐
              │  [DB/Store]│      │      │  [DB/Store]│
              └───────────┘      │      └────────────┘
                          ┌──────┴──────┐
                          │ [Message Bus]│
                          └─────────────┘
```

<!-- Replace with actual topology. Use ASCII art or reference a diagram file
     in docs/architecture/diagrams/. -->

### 2.2 Infrastructure Components

| Component | Technology | Version | Purpose | Environment |
|-----------|-----------|---------|---------|-------------|
| Hosting | [e.g., AWS ECS Fargate] | [e.g., N/A] | [e.g., Container orchestration] | [e.g., All] |
| CI/CD | [e.g., GitHub Actions] | [e.g., N/A] | [e.g., Build, test, deploy pipeline] | [e.g., All] |
| Containerization | [e.g., Docker] | [e.g., 24.x] | [e.g., Application packaging] | [e.g., All] |
| Load Balancer | [e.g., AWS ALB] | [e.g., N/A] | [e.g., TLS termination, routing] | [e.g., Staging, Prod] |
| Message Broker | [e.g., RabbitMQ / SQS] | [e.g., 3.12] | [e.g., Async event processing] | [e.g., All] |
| CDN | [e.g., CloudFront] | [e.g., N/A] | [e.g., Static assets, caching] | [e.g., Prod] |
| Secrets Manager | [e.g., AWS Secrets Manager] | [e.g., N/A] | [e.g., Credential storage] | [e.g., All] |

### 2.3 Networking

| Network Zone | CIDR / Description | Accessible From | Purpose |
|-------------|---------------------|-----------------|---------|
| [e.g., Public] | [e.g., ALB only] | [e.g., Internet] | [e.g., HTTPS entry point] |
| [e.g., Private App] | [e.g., 10.0.1.0/24] | [e.g., Public zone only] | [e.g., Application services] |
| [e.g., Data] | [e.g., 10.0.2.0/24] | [e.g., Private App only] | [e.g., Databases, caches] |

### 2.4 Scaling Strategy

| Component | Scaling Type | Trigger | Min / Max |
|-----------|-------------|---------|-----------|
| [e.g., App Service] | [e.g., Horizontal (auto)] | [e.g., CPU > 70%] | [e.g., 2 / 10] |
| [e.g., Database] | [e.g., Vertical (manual)] | [e.g., Storage > 80%] | [e.g., N/A] |
| [e.g., Cache] | [e.g., Vertical (manual)] | [e.g., Memory > 85%] | [e.g., N/A] |

### 2.5 Environments

| Environment | Purpose | URL / Access | Infra Differences |
|-------------|---------|--------------|-------------------|
| [e.g., Local] | [e.g., Development] | [e.g., localhost:3000] | [e.g., Docker Compose, no ALB] |
| [e.g., Staging] | [e.g., Pre-production testing] | [e.g., staging.example.com] | [e.g., Single instance, no auto-scaling] |
| [e.g., Production] | [e.g., Live traffic] | [e.g., app.example.com] | [e.g., Full setup with HA] |

---

## 3. Software Architecture

> Describes the technical structure of the codebase: layers, patterns, conventions, and technology stack. This section is about HOW the system is built.

### 3.1 Technology Stack

| Component | Technology | Version | Notes |
|-----------|-----------|---------|-------|
| Language | [e.g., TypeScript] | [e.g., 5.4] | |
| Runtime | [e.g., Node.js] | [e.g., 20 LTS] | |
| Framework | [e.g., NestJS] | [e.g., 10.x] | |
| Key Libraries | [e.g., Drizzle ORM, Passport, class-validator] | | |
| Testing | [e.g., Jest, Supertest] | | [e.g., Unit + Integration] |

### 3.2 Data Architecture

| Component | Technology | Version | Notes |
|-----------|-----------|---------|-------|
| Primary Database | [e.g., PostgreSQL] | [e.g., 16] | |
| Caching | [e.g., Redis, none] | | |
| ORM / Data Access | [e.g., Drizzle ORM] | [e.g., 0.30] | |
| Migrations | [e.g., Drizzle Kit] | | |
| File Storage | [e.g., S3, none] | | |

### 3.3 Architectural Style

<!-- Pick the primary architectural style and describe how it is applied.
     Common styles: Layered, Hexagonal (Ports & Adapters), Clean Architecture,
     Microservices, Event-Driven, CQRS. -->

**Style**: [e.g., Hexagonal Architecture (Ports & Adapters)]

```
┌────────────────────────────────────────────────────────┐
│                    Presentation Layer                   │
│          [e.g., REST Controllers, GraphQL Resolvers]    │
├────────────────────────────────────────────────────────┤
│                    Application Layer                    │
│          [e.g., Use Cases, Application Services]        │
├────────────────────────────────────────────────────────┤
│                      Domain Layer                       │
│          [e.g., Entities, Value Objects, Domain Events] │
├────────────────────────────────────────────────────────┤
│                    Infrastructure Layer                 │
│     [e.g., Repositories, External API Clients, DB]      │
└────────────────────────────────────────────────────────┘
```

### 3.4 Project Structure

<!-- Show the canonical directory layout of the project.
     This helps AI agents and new developers understand code organization. -->

```
src/
├── [module-a]/           # [e.g., Bounded Context: Identity]
│   ├── domain/           #   Entities, Value Objects, Domain Events
│   ├── application/      #   Use Cases, Application Services
│   ├── infrastructure/   #   Repositories, External Clients
│   └── presentation/     #   Controllers, DTOs
├── [module-b]/           # [e.g., Bounded Context: Catalog]
│   └── ...
├── shared/               # Shared Kernel
│   ├── domain/           #   Common value objects, interfaces
│   └── infrastructure/   #   Common infrastructure utilities
└── config/               # Application configuration
```

### 3.5 Architectural Rules

- [e.g., "Domain entities must not depend on framework annotations."]
- [e.g., "Use constructor injection. Never use `@Autowired` on fields."]
- [e.g., "Repositories return domain entities, not framework types."]
- [e.g., "Cross-module communication via domain events only, never direct method calls."]

### 3.6 Design Patterns

| Pattern | Usage | Example |
|---------|-------|---------|
| [e.g., Repository] | [e.g., Data access abstraction] | [e.g., `UserRepository` interface in domain, impl in infrastructure] |
| [e.g., CQRS] | [e.g., Separate read/write models] | [e.g., Commands mutate state, Queries return DTOs] |
| [e.g., Domain Event] | [e.g., Loose coupling between modules] | [e.g., `OrderPlacedEvent` published to message bus] |
| [e.g., Factory] | [e.g., Complex entity creation] | [e.g., `OrderFactory.create()` enforces invariants] |

### 3.7 API Conventions

| Aspect | Convention | Example |
|--------|-----------|---------|
| URL Style | [e.g., kebab-case, plural nouns] | [e.g., `/api/v1/user-profiles`] |
| Authentication | [e.g., Bearer JWT] | [e.g., `Authorization: Bearer <token>`] |
| Versioning | [e.g., URL path] | [e.g., `/api/v1/...`] |
| Error Format | [e.g., RFC 7807 Problem Details] | [e.g., `{ "type": "...", "title": "...", "status": 422 }`] |
| Pagination | [e.g., Cursor-based] | [e.g., `?cursor=abc&limit=20`] |

### 3.8 Library Verification

<!-- Documents the exact API signatures and versions of all dependencies.
     AI agents MUST verify against this section before using any library. -->

#### [Library Name]

**Package**: [npm/maven/pypi package name]
**Version**: [Exact version, e.g., 2.14.1]

**Approved APIs**:
| API | Signature | Purpose |
|-----|-----------|---------|
| `methodName` | `(param1: Type, param2: Type): ReturnType` | Brief description |

**Usage Constraints**:
- [Constraint 1]
- [Constraint 2]

**Forbidden APIs**:
| API | Reason |
|-----|--------|
| `deprecatedMethod` | Use `newMethod` instead |

---

## 4. Security Constraints

**Note**: Every rule maps to industry standards (OWASP, CWE) for compliance traceability.

### Enforcement Levels

| Level | Meaning | What Happens |
|-------|---------|---------------|
| **CRITICAL** | Must pass before merge | Blocks merge, requires immediate fix |
| **SHOULD** | Should pass, minor deviation acceptable | Warning logged, needs justification |
| **MAY** | Informational, best practice | Suggestion only |

### Forbidden Patterns (CRITICAL — Blocks Merge)

| Pattern | CWE-ID | OWASP | Reason | Detection |
|---------|--------|-------|--------|-----------|
| Raw SQL string concatenation | CWE-89 | A03:2021 | SQL Injection | Grep for `'+` in SQL contexts |
| Hardcoded secrets/credentials | CWE-798 | A02:2021 | Credential Exposure | Grep for `password=`, `secret=`, `api_key=` |
| Deserialization of untrusted data | CWE-502 | A08:2021 | Software/Data Integrity | Look for `ObjectInputStream`, unvalidated `JSON.parse` |
| Unvalidated redirects | CWE-601 | A01:2021 | Broken Access Control | Check for `redirect(` without validation |
| Missing authentication on sensitive endpoints | CWE-306 | A01:2021 | Broken Access Control | Scan for public endpoints without auth |
| Insufficient password hashing | CWE-916 | A02:2021 | Cryptographic Failures | Check for plain text or MD5/SHA1 storage |
| Use of deprecated crypto (MD5, SHA1) | CWE-327 | A02:2021 | Cryptographic Failures | Grep for MD5/SHA1 in crypto contexts |
| XML External Entity (XXE) | CWE-611 | A05:2021 | Security Misconfiguration | Check for XML parsers without entity restrictions |
| Path traversal (unsafe file access) | CWE-22 | A01:2021 | Broken Access Control | Check for unsanitized file path inputs |

### Required Patterns (CRITICAL — Must Implement)

| Pattern | CWE-ID | OWASP | Why Required |
|---------|--------|-------|--------------|
| All SQL queries use parameterized statements | CWE-20 | A03:2021 | Prevents SQL injection |
| All secrets via environment variables or Secrets Manager | CWE-522 | A02:2021 | Prevents credential exposure |
| Password hashing with bcrypt cost factor >= 12 | CWE-916 | A02:2021 | Brute force protection |
| JWT tokens include expiration and signature verification | CWE-345 | A01:2021 | Session integrity |
| CSRF tokens on state-changing operations | CWE-352 | A01:2021 | CSRF prevention |
| Secure session cookies (HttpOnly, Secure, SameSite) | CWE-1004 | A01:2021 | Session hijacking prevention |
| Input validation on all public endpoints | CWE-20 | A03:2021 | Prevents injection attacks |
| Output encoding for XSS prevention | CWE-79 | A03:2021 | XSS prevention |

### Recommended Patterns (SHOULD — Strongly Advised)

| Pattern | CWE-ID | Why Recommended |
|---------|--------|-----------------|
| Input sanitization beyond validation | CWE-138 | Defense in depth |
| Rate limiting on authentication endpoints | CWE-307 | Brute force protection |
| Security event logging | CWE-778 | Audit trail and incident response |
| Timeout for external API calls | CWE-835 | Resource exhaustion prevention |
| Content Security Policy headers | CWE-1021 | XSS prevention |
| File upload validation (type, size, content) | CWE-434 | Malicious file upload prevention |
| SQL query timeout to prevent DoS | CWE-400 | Database resource exhaustion |

---

## 5. AI Guardrails

Rules that AI agents MUST follow when generating code for this project:

- **Library Verification**: Before using ANY external library:
  1. Check if library is in "Library Verification" section (3.8)
  2. Verify exact version matches
  3. Use ONLY listed APIs with correct signatures
  4. Follow usage constraints
  5. NEVER use forbidden APIs

- **Architectural Compliance**:
  1. Respect the Architectural Style (3.3) — do not bypass layers
  2. Follow the Project Structure (3.4) — place files in the correct location
  3. Obey Architectural Rules (3.5) — no exceptions without ADR
  4. Use Design Patterns (3.6) where specified
  5. Follow API Conventions (3.7) for all endpoints

- **Spec Death Principle**: Every spec has a limited lifespan:
  1. During implementation, spec is the source of truth
  2. After completion, run `specs.sync` to update spec
  3. Archive completed specs to `archived/` folder — never let specs become stale
  4. A spec that lives forever without archiving becomes misleading technical debt

- **Context Rot Prevention**:
  1. Read `docs/specs/architecture.md` at session start
  2. Read `docs/specs/ontology.md` at session start
  3. Do NOT assume Constitution is in context — it MUST be read from file
  4. Validate all work against Constitution files, not memory
  5. If you notice assumptions contradicting Constitution, re-read immediately

- [Guardrail 1, e.g., "Never generate `@Transactional` on repository methods."]
- [Guardrail 2, e.g., "Always generate tests alongside implementation code."]
- [Guardrail 3, e.g., "Do not introduce new dependencies without explicit approval."]
references/constitution-check-report.md
# Constitution Check Report Examples

Complete report examples for different scenarios.

---

## Example 1: Clean Check (No Violations)

```markdown
## Constitution Check Report
Target: src/services/UserService.java
Date: 2024-01-15

### Security Check (CWE/OWASP Compliance)
| Rule | Level | Status | Location | CWE/OWASP |
|------|-------|--------|----------|-----------|
| No SQL injection | CRITICAL | ✅ OK | - | CWE-89 |
| No hardcoded secrets | CRITICAL | ✅ OK | - | CWE-798 |
| CSRF protection | CRITICAL | ✅ OK | - | CWE-352 |
| Password hashing | CRITICAL | ✅ OK | - | CWE-916 |
| Secure session cookies | CRITICAL | ✅ OK | - | CWE-1004 |
| Rate limiting | SHOULD | ✅ OK | - | CWE-307 |
| Security logging | SHOULD | ✅ OK | - | CWE-778 |

**CRITICAL Violations (MUST fix)**: 0
**SHOULD Warnings**: 0
**Compliant**: 6

### CWE Compliance Report
| CWE | OWASP | Status | Location | Last Verified |
|-----|-------|--------|----------|---------------|
| CWE-89 | A03 | ✅ OK | UserRepository.java:45 | 2024-01-15 |
| CWE-798 | A02 | ✅ OK | - | 2024-01-15 |
| CWE-352 | A01 | ✅ OK | - | 2024-01-15 |
| CWE-916 | A02 | ✅ OK | AuthService.java:23 | 2024-01-15 |
| CWE-307 | A07 | ✅ OK | - | 2024-01-15 |
| CWE-778 | A09 | ✅ OK | - | 2024-01-15 |

### Architecture Check
| Rule | Status | Detail |
|------|--------|--------|
| Constructor injection required | ✅ OK | All dependencies via constructor |
| Layered architecture followed | ✅ OK | Service → Repository → DB |
| No hardcoded secrets | ✅ OK | All config via @Value or env |

### Library Verification Check
| Library | Status | Detail |
|---------|--------|--------|
| bcrypt | ✅ OK | Using hash(password, 12) |
| Spring JPA | ✅ OK | Parameterized queries via JPQL |
| Lombok | ✅ OK | @Slf4j, @Getter, @Setter only |

### Ontology Check
| Term | Status | Detail |
|------|--------|--------|
| "User" used consistently | ✅ OK | No synonym "Account" found |
| "Order" domain model used | ✅ OK | No technical terms mixed |

### Summary
- CRITICAL violations: 0
- WARNING violations: 0
- Compliant rules: 15
- Library verification: All verified ✅
```

---

## Example 2: Multiple Violations

```markdown
## Constitution Check Report
Target: src/controllers/AuthController.ts
Date: 2024-01-15

### Security Check (CWE/OWASP Compliance)
| Rule | Level | Status | Location | CWE/OWASP |
|------|-------|--------|----------|-----------|
| No SQL injection | CRITICAL | ✅ OK | - | CWE-89 |
| No hardcoded secrets | CRITICAL | ❌ FAIL | auth-service.ts:42 | CWE-798 |
| CSRF protection | CRITICAL | ✅ OK | - | CWE-352 |
| Password hashing | CRITICAL | ✅ OK | - | CWE-916 |
| Secure session cookies | CRITICAL | ⚠️ WARN | cookie-middleware.ts:15 | CWE-1004 |
| Rate limiting | SHOULD | ⚠️ WARN | auth-controller.ts:15 | CWE-307 |
| Security logging | SHOULD | ⚠️ WARN | - | CWE-778 |

**CRITICAL Violations (MUST fix)**: 1 — Blocks merge
**SHOULD Warnings**: 3 — Needs justification
**Compliant**: 3

### CWE Compliance Report
| CWE | OWASP | Status | Location | Last Verified |
|-----|-------|--------|----------|---------------|
| CWE-89 | A03 | ✅ OK | - | 2024-01-15 |
| CWE-798 | A02 | ❌ FAIL | auth-service.ts:42 | 2024-01-15 |
| CWE-352 | A01 | ✅ OK | - | 2024-01-15 |
| CWE-916 | A02 | ✅ OK | auth-service.ts:23 | 2024-01-15 |
| CWE-1004 | A01 | ⚠️ WARN | cookie-middleware.ts:15 | 2024-01-15 |
| CWE-307 | A07 | ⚠️ WARN | auth-controller.ts:15 | 2024-01-15 |

**Gap Analysis**:
- CWE-798 (Secrets): Hardcoded API key found → Use env variable
- CWE-1004 (Cookies): Missing SameSite attribute → Add SameSite=Strict
- CWE-307 (Rate Limiting): Not implemented → Add express-rate-limit

### Architecture Check
| Rule | Status | Detail |
|------|--------|--------|
| Constructor injection required | ✅ OK | - |
| Authentication middleware used | ⚠️ WARN | Middleware not in architecture |
| No hardcoded secrets | ❌ FAIL | Line 42: hardcoded "api_key_xxx" |

### Library Verification Check
| Library | Status | Detail |
|---------|--------|--------|
| bcrypt | ✅ OK | Using hash(password, 12) |
| express | ⚠️ WARN | Missing rate-limit dependency |
| jsonwebtoken | ✅ OK | Using verify() correctly |
| lodash | ❌ CRITICAL | Not in Library Verification section |

### Ontology Check
| Term | Status | Detail |
|------|--------|--------|
| "User" used consistently | ✅ OK | - |
| "Authentication" vs "AuthN" | ⚠️ WARN | Inconsistent terminology |

### Summary
- CRITICAL violations: 2 (must fix before proceeding)
  - Hardcoded secret in auth-service.ts:42
  - Unverified library (lodash)
- WARNING violations: 5 (should fix)
- Compliant rules: 7
- **BLOCKED**: Fix CRITICAL violations to proceed
```

---

## Example 3: Context Rot Warning

```markdown
## Constitution Check Report
Target: docs/specs/003-old-feature/2023-06-01--feature-spec.md
Date: 2024-01-15

### ⚠️ Context Rot Warning
This file has not been updated in 30+ days.
Context rot may have occurred — architectural decisions may have drifted.
Consider running `specs.sync` or updating the spec before continuing.

### Security Check (CWE/OWASP Compliance)
| Rule | Level | Status | Location | CWE/OWASP |
|------|-------|--------|----------|-----------|
| No SQL injection | CRITICAL | ✅ OK | - | CWE-89 |
| No hardcoded secrets | CRITICAL | ✅ OK | - | CWE-798 |

**CRITICAL Violations (MUST fix)**: 0
**Compliant**: 2

### Architecture Check
| Rule | Status | Detail |
|------|--------|--------|
| Implementation matches spec | ⚠️ WARN | Code structure changed since spec |
| Stack consistency | ✅ OK | - |

### Summary
- CRITICAL violations: 0
- WARNING violations: 1
- Context rot risk: HIGH
- **Recommendation**: Run `specs.sync` before continuing work on this spec
```
references/context-rot-prevention.md
# Context Rot Prevention

Detailed scenarios and recovery protocols for maintaining Constitution relevance.

---

## What is Context Rot?

**Context rot** is the degradation of long conversations where:
1. Early decisions get buried deep in conversation context
2. Agents forget architectural constraints over time
3. Specifications drift from original principles
4. Team knowledge becomes implicit, not documented
5. Different agents have inconsistent understanding

---

## Why File-Based Constitution?

| Approach | Context Rot | Reliability | Team Visibility |
|----------|-------------|-------------|-----------------|
| **File-based** (ours) | Immune | Always current | Shared across team |
| Context-based | Degrades over time | May be incomplete | Single-user |
| Session memory | Degrades | Depends on model | Not shared |

---

## Session Start Checklist

At the beginning of EVERY session:

```
[ ] Read `docs/specs/architecture.md`
[ ] Read `docs/specs/ontology.md`
[ ] Check if Constitution has been updated since last session
[ ] Validate current work against Constitution
[ ] Flag any deviations in decision-log
```

---

## Warning Signs of Context Rot

If you notice these, re-read the Constitution immediately:

- "I assumed we use X but I see Y in the code"
- "I thought we had A but it's not in the codebase"
- "The spec says B but it doesn't match reality"
- Decisions contradicting previous conversations
- "This was decided earlier but I can't find it in context"

---

## Recovery Protocol

When context rot is detected:

1. **Stop**: Don't continue implementation
2. **Read**: `cat docs/specs/architecture.md` and `docs/specs/ontology.md`
3. **Compare**: Match current state against Constitution
4. **Fix**: Update decision-log if deviations exist
5. **Resume**: Continue with correct context

---

## Detailed Scenarios

### Scenario 1: Long Implementation Session

```
Day 1: Constitution created
Day 5: Brainstorm generates spec
Day 10: Implementation starts
Day 15: Context is fading...

→ At Day 15, re-read Constitution before continuing
→ Validate current work against architecture
→ Fix any drift before it compounds
```

### Scenario 2: Returning After Break

```
Week 1: Feature development started
Week 3: Other work on different features

→ Return to original feature → Re-read Constitution first
→ Match current state vs Constitution
→ Resume with correct context, not memory
```

### Scenario 3: Handoff to Different Agent

```
Agent A: Created Constitution, started work
Agent B: Taking over the feature

→ Agent B reads Constitution files first
→ Understands architecture from files, not memory
→ Continues with consistent context
```

### Scenario 4: Multi-Agent Environment

```
[Agent 1] → Works on Feature A
[Agent 2] → Works on Feature B

→ Both agents read Constitution at session start
→ Both validate against same architecture
→ Consistent decisions across features
```

---

## File Freshness Evaluation

When running `constitution check`, evaluate target file age:

| Age of Target File | Risk | Action |
|--------------------|------|--------|
| < 7 days | LOW | Proceed normally |
| 7-30 days | MEDIUM | Warn user, check for updates |
| > 30 days | HIGH | Suggest review/update, context rot likely |

**Context Rot Warning Template**:

```markdown
> ⚠️ **Context Rot Warning**: This file has not been updated in 30+ days.
> Context rot may have occurred — architectural decisions may have drifted.
> Consider running `specs.sync` or updating the spec before continuing.
```

---

## Recovery Actions (High Context Rot Risk)

1. Read current Constitution files (`docs/specs/architecture.md`, `docs/specs/ontology.md`)
2. Compare spec vs Constitution
3. Identify drifts
4. Update spec or Constitution
5. Document deviations in decision-log

---

## Prevention Strategies

1. **Short sessions**: Keep sessions focused, not sprawling
2. **Reference files**: Always point to file locations, not conversation context
3. **Update constitution**: When architecture changes, update the files
4. **Archive specs**: Completed specs go to `archived/`, not kept active forever
5. **Decision log**: Track architectural decisions in ADR format
references/ontology.md
# Project Ontology — Ubiquitous Language

**Created**: YYYY-MM-DD
**Last Updated**: YYYY-MM-DD

---

## Domain Glossary

| Term | Definition | Bounded Context |
|------|-----------|-----------------|
| [Term 1] | [Clear, unambiguous definition of the term] | [Context where this term applies] |
| [Term 2] | [Definition] | [Context] |

*Guidelines for definitions:*
- *One sentence if possible*
- *Avoid circular definitions*
- *Include the bounded context where it applies*
- *Distinguish from related but different terms*

## Bounded Contexts

| Context | Description | Key Terms |
|---------|-------------|-----------|
| [Context 1] | [What this context is responsible for] | [Comma-separated key terms] |
| [Context 2] | [Description] | [Key terms] |

## Conceptual Mapping

```
┌────────────────────────────────────────────────────────────┐
│                    [Domain Name]                           │
├────────────────────────────────────────────────────────────┤
│  [Context A] ──────────▶ [Context B]                      │
│       │                      │                             │
│       │   [Relationship type:                         │   │
│       │    upstream/downstream,                       │   │
│       │    conformist, anti-corruption-layer,         │   │
│       │    open-host-service, etc.]                   │   │
│       │                                              │   │
│       └──────────────────▶ [Context C]                 │   │
│                                                            │
└────────────────────────────────────────────────────────────┘
```

*Describe relationships between bounded contexts. Focus on integration patterns and data flow.*

## Ubiquitous Language Rules

1. **Consistent terminology**: Same term = same concept throughout
2. **No synonyms for defined terms**: If "User" is defined, don't use "Account" interchangeably
3. **Context matters**: A term may have different meanings in different contexts
4. **Living document**: Add terms as they emerge during brainstorming and implementation

## Anti-Patterns to Avoid

| Anti-Pattern | Example | Correct |
|-------------|---------|---------|
| Synonyms | Calling same entity "User" in one place and "Account" in another | Pick one term, use everywhere |
| Ambiguous terms | "Order" could mean order request, order entity, or order record | Specify: "OrderRequest", "OrderEntity", "OrderRecord" |
| Technical jargon in domain | Using "primary key", "foreign key" in domain descriptions | Use domain terms, not DB terms |
| Time-dependent definitions | "Active" meaning current vs historical | Specify temporal context |

## Enrichment Process

The ontology is enriched during the SDD lifecycle:

| Phase | How Ontology is Enriched |
|-------|------------------------|
| `constitution create` | Initial terms from project setup |
| `brainstorm` Phase 6.8.6 | Terms extracted from idea description |
| `spec-to-tasks` Phase 1.5 | Terms from spec added |
| `task-implementation` | New domain concepts added as discovered |

*When adding terms: Update `Last Updated` date and maintain consistent formatting.*
references/README.md
# Constitution Skill Reference Files

This directory contains reference materials extracted from the main SKILL.md to enable progressive disclosure and reduce skill complexity.

## Files

| File | Purpose |
|------|---------|
| `architecture.md` | Full architecture template (sections 1-5) |
| `ontology.md` | Full ontology template with enrichment process |
| `security-patterns.md` | CWE/OWASP mappings, forbidden/required patterns |
| `context-rot-prevention.md` | Detailed scenarios and recovery protocols |
| `constitution-check-report.md` | Complete report examples |

## Structure

The main SKILL.md provides a concise overview (~180 lines), while reference files contain detailed content for consultation when needed.

## Migration

These files were moved from `SKILL.md` to enable:
- Compliance with skill size limits (500 lines, 5000 tokens)
- Progressive disclosure for detailed reference material
- Separation of templates from instructions
    constitution | Prompt Minder