Files
ljwx-children/OPENSPEC-SETUP.md
brunoandClaude Sonnet 4.5 0a91cb0677 feat(openspec): integrate OpenSpec 0.17.2 for API-first development
Integrate OpenSpec with complete OpenAPI-first development workflow:

**Configuration Files:**
- Add package.json with npm scripts for spec validation
- Add .openspec.yaml for validation rules (strict mode)
- Add .spectral.yaml for OpenAPI linting (100+ rules)
- Add openapi.yaml with initial API specification

**Automation:**
- Add scripts/generate-openapi-spec.py to auto-generate spec from FastAPI
- Add .claude/hooks/pre-commit-openspec.sh for pre-commit validation
- Add .github/workflows/openspec-validation.yml for CI/CD validation

**Documentation:**
- Add docs/workflows/openspec-development-workflow.md (500+ lines workflow guide)
- Add OPENSPEC-SETUP.md (quick start guide)
- Add README-OPENSPEC-INTEGRATION.md (integration summary)
- Update .claude/CLAUDE.md with OpenSpec commands and 9-step workflow

**Features Enabled:**
- OpenAPI-first development (design before code)
- Automatic spec validation on commit
- Breaking change detection in PRs
- Bidirectional sync between spec and code
- Spectral linting with 100+ best practice rules
- Auto-generated API documentation

**Validation Rules:**
- Require operationId, tags, descriptions on all operations
- Require 4xx and 5xx error responses
- Enforce naming conventions (kebab-case paths, PascalCase schemas)
- Require /health and /metrics endpoints (observability)

**Commands Available:**
- npm run spec:validate - Validate OpenAPI spec
- npm run spec:lint - Lint with Spectral
- npm run spec:generate - Generate from FastAPI
- npm run spec:sync - Generate + validate
- npm run spec:diff - Detect breaking changes
- npm run spec:watch - Auto-regenerate on changes

**Breaking Changes:** None (new feature)

**Next Steps:**
1. Run: npm install
2. Run: npm run spec:generate
3. Run: npm run spec:validate
4. Enable pre-commit hook: ln -sf ../../.claude/hooks/pre-commit-openspec.sh .git/hooks/pre-commit

Closes #7 (partially - Claude Configuration optimization)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
2025-12-31 23:25:52 +08:00

10 KiB

OpenSpec Integration - Setup & Quick Start

Status: ✅ Integrated | Version: OpenSpec 0.17.2 | Updated: 2025-12-31

📖 What is OpenSpec?

OpenSpec is an OpenAPI-first development workflow that ensures your API specification is always the source of truth.

Benefits:

  • 🎯 Design-first: Define API before writing code
  • ✅ Auto-validation: Spec validated on every commit
  • 🚫 Breaking change detection: Prevent accidental API breaks
  • 📄 Always up-to-date docs: Generated from code automatically
  • 🔄 Bidirectional sync: Spec ↔ Code stay in sync

🚀 Quick Start

1. Install Dependencies

# Install npm dependencies (OpenSpec + Spectral + tools)
npm install

# Or if you don't have package.json yet
npm init -y
npm install --save-dev @stoplight/spectral-cli nodemon

2. Verify Installation

# Check OpenSpec is available (system-wide)
which openspec
# → /Users/brunogao/.nvm/versions/node/v21.7.3/bin/openspec

openspec --version
# → 0.17.2

# Check Spectral is installed (project-local)
npx @stoplight/spectral-cli --version
# → 6.11.x

3. Generate Initial Spec

# Generate OpenAPI spec from FastAPI app
npm run spec:generate

# Output:
# ✅ OpenAPI specification generated: openapi.yaml
# ✅ OpenAPI JSON generated: openapi.json

4. Validate Spec

# Validate OpenAPI spec
npm run spec:validate

# Output:
# ✅ OpenAPI spec is valid
# No errors or warnings found

5. Enable Pre-commit Hook

# Install pre-commit hook
ln -sf ../../.claude/hooks/pre-commit-openspec.sh .git/hooks/pre-commit

# Or copy
cp .claude/hooks/pre-commit-openspec.sh .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit

📋 Available Commands

Validation & Linting

# Validate OpenAPI spec (structural validation)
npm run spec:validate

# Lint OpenAPI spec (best practices check)
npm run spec:lint

# Both validate + lint
npm run spec:sync

Generation

# Generate OpenAPI spec from FastAPI code
npm run spec:generate

# Watch mode (auto-regenerate on file changes)
npm run spec:watch

Comparison

# Compare current spec with backup (detect changes)
npm run spec:diff

# Compare with another spec file
npx openspec diff openapi.yaml openapi-v2.yaml

🔄 Development Workflow

Scenario 1: Adding a New Endpoint

Step 1: Design in OpenAPI spec

# Edit openapi.yaml
vim openapi.yaml

Add the new endpoint:

paths:
  /products:
    post:
      tags:
        - Products
      summary: Create new product
      operationId: createProduct
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProductCreate'
      responses:
        '201':
          description: Product created successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Product'

components:
  schemas:
    ProductCreate:
      type: object
      required:
        - name
        - price
      properties:
        name:
          type: string
          description: Product name
        price:
          type: number
          format: float
          minimum: 0

    Product:
      allOf:
        - $ref: '#/components/schemas/ProductCreate'
        - type: object
          properties:
            id:
              type: integer
            created_at:
              type: string
              format: date-time

Step 2: Validate the design

npm run spec:validate

Step 3: Implement in FastAPI

# backend/api/products.py
from fastapi import APIRouter
from pydantic import BaseModel

router = APIRouter(prefix="/products", tags=["Products"])

class ProductCreate(BaseModel):
    name: str
    price: float

class Product(ProductCreate):
    id: int
    created_at: str

@router.post("", response_model=Product, status_code=201, operation_id="createProduct")
async def create_product(product: ProductCreate):
    """Create new product - matches OpenAPI spec"""
    # Implementation
    return Product(id=1, name=product.name, price=product.price, created_at="2025-12-31T00:00:00Z")

Step 4: Sync and validate

# Generate spec from code
npm run spec:generate

# Validate it matches our design
npm run spec:validate

Step 5: Commit

git add .
git commit -m "feat(products): add create product endpoint"

# Pre-commit hook runs automatically:
# ✅ Generates OpenAPI spec
# ✅ Validates spec
# ✅ Adds openapi.yaml to commit

🎯 Configuration Files

.openspec.yaml - OpenSpec Configuration

Controls validation rules, linting, and generation settings.

Key sections:

validation:
  level: strict  # strict | normal | relaxed

paths:
  kebab-case: true  # Enforce kebab-case paths
  no-trailing-slash: true

security:
  require-security: true

responses:
  require-4xx: true  # All endpoints need error responses
  require-5xx: true

.spectral.yaml - Spectral Linting Rules

Advanced OpenAPI linting rules.

Custom rules for this project:

rules:
  # Gold Template specific
  require-trace-id-in-errors: warn
  require-examples: warn
  require-metrics-endpoint: warn
  require-health-endpoint: error

package.json - npm Scripts

Quick commands for OpenSpec operations.

{
  "scripts": {
    "spec:validate": "openspec validate openapi.yaml",
    "spec:lint": "openspec lint openapi.yaml",
    "spec:generate": "python3 scripts/generate-openapi-spec.py",
    "spec:sync": "npm run spec:generate && npm run spec:validate"
  }
}

🔍 Validation Rules

Enforced by Default

✅ Info Section:

  • info.title, info.version, info.description required
  • info.contact required (name, email)
  • info.license recommended (MIT)

✅ Operations:

  • Every operation must have operationId
  • Every operation must have tags
  • Every operation must have description
  • Every operation must have at least one 2xx response

✅ Error Handling:

  • All operations must have 4xx responses
  • All operations must have 5xx responses
  • Error responses should include trace_id for debugging

✅ Naming Conventions:

  • Paths use kebab-case: /user-profiles
  • No trailing slashes: /users not /users/
  • Schemas use PascalCase: UserProfile

✅ Observability:

  • API must have /health endpoint
  • API must have /metrics endpoint (Prometheus)

🚨 Common Issues & Solutions

Issue 1: "Operation must have operationId"

Error:

Error: Operation POST /users must have operationId

Solution:

# ❌ Missing operationId
@app.post("/users")
async def create_user(user: UserCreate):
    pass

# ✅ Add operationId
@app.post("/users", operation_id="createUser")
async def create_user(user: UserCreate):
    pass

Issue 2: "Breaking change detected"

Error:

BREAKING CHANGE: Removed required parameter 'email' from /users POST

Solution:

Option 1: Revert the change

git revert HEAD

Option 2: Create new API version

paths:
  /v2/users:  # New version
    post:
      # New schema without 'email'

  /v1/users:  # Old version (deprecated)
    post:
      deprecated: true

Option 3: Make it optional (if acceptable)

components:
  schemas:
    UserCreate:
      properties:
        email:
          type: string
          # Remove from 'required' array

Issue 3: "npm command not found"

Error:

npm run spec:validate
# → npm: command not found

Solution:

# Install Node.js and npm
# macOS (with Homebrew)
brew install node

# Or use nvm (recommended)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
nvm install 20
nvm use 20

# Verify
node --version
npm --version

Issue 4: "Spec out of sync with code"

Error:

openapi.yaml defines /users but code has /api/users

Solution:

# Regenerate spec from code
npm run spec:generate

# Review changes
git diff openapi.yaml

# If code is correct, update spec
# If spec is correct, update code

📊 CI/CD Integration

GitHub Actions Workflow

.github/workflows/openspec-validation.yml runs on every PR:

  1. Generate OpenAPI spec from FastAPI
  2. Validate spec with Spectral
  3. Detect breaking changes (vs base branch)
  4. Comment on PR with API changes
  5. Fail if breaking changes detected

Example PR Comment:

## 🔍 OpenAPI Spec Changes

### New Endpoints
- POST /products - Create new product

### Modified Endpoints
- GET /users - Added pagination parameters

### Breaking Changes
⚠️ None detected

🎓 Resources

Documentation

Tools

Project Files

  • OpenAPI Spec: openapi.yaml
  • Config: .openspec.yaml, .spectral.yaml
  • Generator: scripts/generate-openapi-spec.py
  • CI/CD: .github/workflows/openspec-validation.yml

✅ Verification Checklist

After setup, verify everything works:

  • npm install completes successfully
  • npm run spec:generate creates openapi.yaml
  • npm run spec:validate passes without errors
  • npm run spec:lint passes without errors
  • Pre-commit hook is installed (.git/hooks/pre-commit)
  • Pre-commit hook runs on git commit
  • GitHub Actions workflow exists (.github/workflows/openspec-validation.yml)

Status: ✅ OpenSpec fully integrated Next Steps: Read docs/workflows/openspec-development-workflow.md for detailed workflow Support: Create issue at https://github.com/yourusername/gold-template/issues


Quick Commands Reference:

npm run spec:validate    # Validate spec
npm run spec:generate    # Generate from code
npm run spec:sync        # Generate + validate
npm run spec:diff        # Compare changes
npm run spec:watch       # Auto-regenerate