rdev/docs/specs/sdlc-orchestration-system.md
jordan 62460bf098 feat: complete template upgrade - chassis framework, UI library, auth, app-nextjs, OpenAPI, and cookbook
Weeks 1-7 of the template upgrade plan:
- pkg/api: typed HTTPError with sentinels, Wrap/WrapMiddleware, Bind, health probes, OpenAPI schema/param builders
- skeleton/packages: ui (design tokens, components), layout (DashboardShell), auth (AuthProvider, ProtectedRoute), api-client
- skeleton/pkg: httperror, app/handler, app/bind, app/health, auth (JWT/API key middleware)
- components/app-nextjs: Next.js 14 App Router template with dashboard, server actions, auth
- cookbooks/feature-development.md with test and validation scripts
- Handler tests for components, project management, and woodpecker webhook
- 3 rounds of code review fixes applied

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-02 00:46:51 -07:00

2191 lines
67 KiB
Markdown

# SDLC Orchestration System Specification
## Overview
A deterministic, adaptive software development lifecycle system that enforces enterprise-grade development practices through structured artifacts, state management, and intelligent orchestration.
**Core Principles:**
1. Every command produces a concrete artifact at a deterministic location
2. Git is the source of truth for all SDLC state
3. A classifier engine recursively determines the next required action
4. All work happens on branches until verified and approved
5. The system is self-documenting and auditable
---
## Architecture
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ SDLC Orchestration System │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Claude │───▶│ Classifier │───▶│ SDLC CLI │───▶│ Git │ │
│ │ Commands │ │ Engine │ │ Tool │ │ Structure │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │ │ │ │ │
│ │ │ │ │ │
│ ▼ ▼ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ .sdlc/ Directory │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ roadmap/ │ │features/ │ │patterns/ │ │ audits/ │ │ state/ │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
```
---
## Git Structure (Source of Truth)
All SDLC artifacts live in `.sdlc/` at the repository root:
```
.sdlc/
├── state.yaml # Global SDLC state (current phase, active work)
├── config.yaml # Project SDLC configuration
├── roadmap/ # Strategic planning artifacts
│ ├── index.md # Roadmap overview with links
│ ├── v1.0/
│ │ ├── roadmap.md # Version roadmap document
│ │ ├── milestones.md # Milestone definitions
│ │ └── releases.md # Release schedule
│ └── backlog.md # Unprioritized ideas
├── features/ # Feature development artifacts
│ ├── index.md # Feature registry with status
│ └── {feature-slug}/
│ ├── manifest.yaml # Feature metadata and state machine
│ ├── spec.md # Canonical specification (immutable after approval)
│ ├── design.md # Architecture/design decisions
│ ├── tasks.md # Implementation task breakdown
│ ├── qa-plan.md # QA verification flow
│ ├── qa-results.md # QA execution results
│ ├── review.md # Code review findings
│ ├── audit.md # Post-implementation audit
│ └── changelog.md # Feature development history
├── patterns/ # Elevated patterns (canonical references)
│ ├── index.md # Pattern catalog
│ └── {pattern-slug}/
│ ├── pattern.md # Pattern specification
│ ├── examples.md # Code examples
│ ├── violations.md # Known violations to fix
│ └── adoption.md # Adoption tracking
├── audits/ # Codebase-wide audits
│ ├── index.md # Audit history
│ └── {audit-date}-{type}.md # Individual audit reports
├── branches/ # Branch lifecycle tracking
│ ├── index.md # Active branches
│ └── {branch-name}.yaml # Branch state and checklist
└── archives/ # Completed features (moved after release)
└── {feature-slug}/ # Same structure as features/
```
---
## State Machine
### Global States
```yaml
# .sdlc/state.yaml
version: 1
project:
name: "project-name"
current_roadmap: "v1.0"
active_work:
features:
- slug: "auth"
branch: "feature/auth"
phase: "implementation"
patterns:
- slug: "error-handling"
phase: "elevation"
audits:
- type: "api-consistency"
phase: "remediation"
blocked: []
last_updated: "2024-01-15T10:30:00Z"
last_action: "task-complete"
last_actor: "claude"
```
### Feature Lifecycle Phases
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ Feature Lifecycle State Machine │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ DRAFT │───▶│SPECIFIED │───▶│ PLANNED │───▶│ READY │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ │ │ │ │ │
│ │ spec.md │ design.md │ tasks.md │ branch created │
│ │ created │ approved │ qa-plan.md │ all prereqs met │
│ │ │ │ approved │ │
│ ▼ ▼ ▼ ▼ │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │IMPLEMENT │───▶│ REVIEW │───▶│ AUDIT │───▶│ QA │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ │ │ │ │ │
│ │ tasks done │ review.md │ audit.md │ qa-results.md │
│ │ │ all PASS │ all PASS │ all PASS │
│ ▼ ▼ ▼ ▼ │
│ │
│ ┌──────────┐ ┌──────────┐ │
│ │ MERGE │───▶│ RELEASED │ │
│ └──────────┘ └──────────┘ │
│ │ │ │
│ │ PR merged │ archived │
│ │ main updated │ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
```
### Feature Manifest (State Tracking)
```yaml
# .sdlc/features/auth/manifest.yaml
slug: "auth"
title: "User Authentication System"
created: "2024-01-10T09:00:00Z"
branch: "feature/auth"
roadmap_ref: "v1.0/M2"
phase: "implementation"
phase_history:
- phase: "draft"
entered: "2024-01-10T09:00:00Z"
exited: "2024-01-10T14:00:00Z"
- phase: "specified"
entered: "2024-01-10T14:00:00Z"
exited: "2024-01-11T10:00:00Z"
- phase: "planned"
entered: "2024-01-11T10:00:00Z"
exited: "2024-01-11T16:00:00Z"
- phase: "ready"
entered: "2024-01-11T16:00:00Z"
exited: "2024-01-12T09:00:00Z"
- phase: "implementation"
entered: "2024-01-12T09:00:00Z"
exited: null
artifacts:
spec:
status: "approved"
path: "spec.md"
approved_by: "user"
approved_at: "2024-01-10T14:00:00Z"
design:
status: "approved"
path: "design.md"
approved_by: "user"
approved_at: "2024-01-11T10:00:00Z"
tasks:
status: "approved"
path: "tasks.md"
total: 8
completed: 5
in_progress: 1
blocked: 0
qa_plan:
status: "approved"
path: "qa-plan.md"
checkpoints: 12
review:
status: "pending"
path: "review.md"
audit:
status: "pending"
path: "audit.md"
qa_results:
status: "pending"
path: "qa-results.md"
blockers: []
dependencies:
features: []
patterns: ["error-handling"]
```
---
## Classifier Engine
The classifier is a deterministic rules engine that evaluates current state and determines the next required action.
### Classifier Interface
```
Input: Current state (.sdlc/state.yaml + feature manifests)
Output: Next action (command + target + context)
```
### Classification Rules (Priority Order)
```yaml
# Classifier decision tree (evaluated top-to-bottom, first match wins)
rules:
# ============================================
# BLOCKERS (highest priority)
# ============================================
- id: "blocked-dependency"
condition: "feature.blockers.length > 0"
action: "BLOCKED"
message: "Feature blocked by: {blockers}"
next_command: null
# ============================================
# PHASE: DRAFT → SPECIFIED
# ============================================
- id: "needs-spec"
condition: "feature.phase == 'draft' AND NOT exists(spec.md)"
action: "CREATE_SPEC"
next_command: "/spec-feature {feature}"
output_path: ".sdlc/features/{feature}/spec.md"
- id: "spec-needs-approval"
condition: "feature.phase == 'draft' AND spec.status == 'draft'"
action: "AWAIT_APPROVAL"
message: "Spec requires user approval"
next_command: null
- id: "spec-approved"
condition: "feature.phase == 'draft' AND spec.status == 'approved'"
action: "TRANSITION"
transition_to: "specified"
# ============================================
# PHASE: SPECIFIED → PLANNED
# ============================================
- id: "needs-design"
condition: "feature.phase == 'specified' AND NOT exists(design.md)"
action: "CREATE_DESIGN"
next_command: "/design-feature {feature}"
output_path: ".sdlc/features/{feature}/design.md"
- id: "needs-tasks"
condition: "feature.phase == 'specified' AND design.status == 'approved' AND NOT exists(tasks.md)"
action: "CREATE_TASKS"
next_command: "/breakdown-feature {feature}"
output_path: ".sdlc/features/{feature}/tasks.md"
- id: "needs-qa-plan"
condition: "feature.phase == 'specified' AND tasks.status == 'approved' AND NOT exists(qa-plan.md)"
action: "CREATE_QA_PLAN"
next_command: "/create-qa-plan {feature}"
output_path: ".sdlc/features/{feature}/qa-plan.md"
- id: "planning-complete"
condition: "feature.phase == 'specified' AND qa_plan.status == 'approved'"
action: "TRANSITION"
transition_to: "planned"
# ============================================
# PHASE: PLANNED → READY
# ============================================
- id: "needs-branch"
condition: "feature.phase == 'planned' AND NOT branch_exists(feature.branch)"
action: "CREATE_BRANCH"
next_command: "/create-branch {feature}"
- id: "check-dependencies"
condition: "feature.phase == 'planned' AND has_unmet_dependencies(feature)"
action: "BLOCKED"
message: "Dependencies not met: {unmet_deps}"
- id: "ready-to-implement"
condition: "feature.phase == 'planned' AND branch_exists AND dependencies_met"
action: "TRANSITION"
transition_to: "ready"
# ============================================
# PHASE: READY → IMPLEMENTATION
# ============================================
- id: "start-implementation"
condition: "feature.phase == 'ready'"
action: "TRANSITION"
transition_to: "implementation"
# ============================================
# PHASE: IMPLEMENTATION
# ============================================
- id: "implement-next-task"
condition: "feature.phase == 'implementation' AND has_pending_tasks()"
action: "IMPLEMENT_TASK"
next_command: "/implement-task {feature} {next_task_id}"
- id: "implementation-complete"
condition: "feature.phase == 'implementation' AND all_tasks_complete()"
action: "TRANSITION"
transition_to: "review"
# ============================================
# PHASE: REVIEW
# ============================================
- id: "needs-review"
condition: "feature.phase == 'review' AND review.status == 'pending'"
action: "REVIEW_CODE"
next_command: "/review-feature {feature}"
output_path: ".sdlc/features/{feature}/review.md"
- id: "review-has-issues"
condition: "feature.phase == 'review' AND review.status == 'needs_fix'"
action: "FIX_REVIEW_ISSUES"
next_command: "/fix-review-issues {feature}"
- id: "review-passed"
condition: "feature.phase == 'review' AND review.status == 'passed'"
action: "TRANSITION"
transition_to: "audit"
# ============================================
# PHASE: AUDIT
# ============================================
- id: "needs-audit"
condition: "feature.phase == 'audit' AND audit.status == 'pending'"
action: "AUDIT_CODE"
next_command: "/audit-feature {feature}"
output_path: ".sdlc/features/{feature}/audit.md"
- id: "audit-has-issues"
condition: "feature.phase == 'audit' AND audit.status == 'needs_remediation'"
action: "REMEDIATE_AUDIT"
next_command: "/remediate-audit {feature}"
- id: "audit-passed"
condition: "feature.phase == 'audit' AND audit.status == 'passed'"
action: "TRANSITION"
transition_to: "qa"
# ============================================
# PHASE: QA
# ============================================
- id: "needs-qa"
condition: "feature.phase == 'qa' AND qa_results.status == 'pending'"
action: "RUN_QA"
next_command: "/run-qa {feature}"
output_path: ".sdlc/features/{feature}/qa-results.md"
- id: "qa-has-failures"
condition: "feature.phase == 'qa' AND qa_results.status == 'failed'"
action: "FIX_QA_FAILURES"
next_command: "/fix-qa-failures {feature}"
- id: "qa-passed"
condition: "feature.phase == 'qa' AND qa_results.status == 'passed'"
action: "TRANSITION"
transition_to: "merge"
# ============================================
# PHASE: MERGE
# ============================================
- id: "needs-merge"
condition: "feature.phase == 'merge'"
action: "MERGE_FEATURE"
next_command: "/merge-feature {feature}"
# ============================================
# PHASE: RELEASED
# ============================================
- id: "archive-feature"
condition: "feature.phase == 'released'"
action: "ARCHIVE"
next_command: "/archive-feature {feature}"
# ============================================
# PATTERN LIFECYCLE
# ============================================
- id: "pattern-needs-elevation"
condition: "pattern.phase == 'identified'"
action: "ELEVATE_PATTERN"
next_command: "/elevate-pattern {pattern}"
output_path: ".sdlc/patterns/{pattern}/pattern.md"
- id: "pattern-needs-examples"
condition: "pattern.phase == 'documented' AND NOT exists(examples.md)"
action: "ADD_EXAMPLES"
next_command: "/add-pattern-examples {pattern}"
- id: "pattern-needs-adoption"
condition: "pattern.phase == 'documented' AND examples.status == 'complete'"
action: "FIND_VIOLATIONS"
next_command: "/find-pattern-violations {pattern}"
output_path: ".sdlc/patterns/{pattern}/violations.md"
- id: "pattern-has-violations"
condition: "pattern.violations.count > 0"
action: "FIX_VIOLATIONS"
next_command: "/fix-pattern-violations {pattern}"
# ============================================
# DEFAULT
# ============================================
- id: "nothing-to-do"
condition: "true"
action: "IDLE"
message: "No actionable work found"
```
### Classifier Output Format
```yaml
# Classifier response
classification:
timestamp: "2024-01-15T10:30:00Z"
context:
feature: "auth"
current_phase: "implementation"
evaluation:
rule_matched: "implement-next-task"
conditions_checked:
- "feature.phase == 'implementation'" : true
- "has_pending_tasks()" : true
decision:
action: "IMPLEMENT_TASK"
command: "/implement-task auth task-004"
output_path: ".sdlc/features/auth/tasks.md"
context_for_command:
feature_slug: "auth"
task_id: "task-004"
task_title: "Implement JWT token validation"
task_spec: |
Validate JWT tokens on protected endpoints...
patterns_to_follow:
- "error-handling"
related_files:
- "internal/auth/jwt.go"
- "internal/middleware/auth.go"
```
---
## SDLC CLI Tool
### Command Reference
```bash
# ============================================
# INITIALIZATION
# ============================================
sdlc init # Initialize .sdlc/ structure
sdlc config set <key> <value> # Configure project settings
# ============================================
# ROADMAP MANAGEMENT
# ============================================
sdlc roadmap create <version> # Create new roadmap version
sdlc roadmap list # List all roadmap versions
sdlc roadmap show <version> # Display roadmap
sdlc roadmap set-active <version> # Set active roadmap version
# ============================================
# FEATURE MANAGEMENT
# ============================================
sdlc feature create <slug> # Create new feature
sdlc feature list # List all features with status
sdlc feature show <slug> # Show feature details
sdlc feature status <slug> # Show feature phase and progress
sdlc feature transition <slug> <phase> # Manually transition phase
sdlc feature block <slug> <reason> # Mark feature as blocked
sdlc feature unblock <slug> # Remove blocker
# ============================================
# ARTIFACT MANAGEMENT
# ============================================
sdlc artifact create <feature> <type> # Create artifact file
sdlc artifact approve <feature> <type> # Mark artifact as approved
sdlc artifact reject <feature> <type> # Mark artifact as rejected
sdlc artifact status <feature> # Show all artifact statuses
# ============================================
# TASK MANAGEMENT
# ============================================
sdlc task list <feature> # List tasks for feature
sdlc task start <feature> <task-id> # Mark task as in-progress
sdlc task complete <feature> <task-id> # Mark task as complete
sdlc task block <feature> <task-id> # Mark task as blocked
sdlc task add <feature> <title> # Add new task
# ============================================
# BRANCH MANAGEMENT
# ============================================
sdlc branch create <feature> # Create feature branch
sdlc branch status <feature> # Show branch checklist
sdlc branch sync <feature> # Sync branch with main
# ============================================
# PATTERN MANAGEMENT
# ============================================
sdlc pattern create <slug> # Create new pattern
sdlc pattern list # List all patterns
sdlc pattern show <slug> # Show pattern details
sdlc pattern adopt <slug> # Start adoption campaign
# ============================================
# AUDIT MANAGEMENT
# ============================================
sdlc audit create <type> # Create new audit
sdlc audit list # List all audits
sdlc audit show <id> # Show audit details
# ============================================
# STATE & CLASSIFICATION
# ============================================
sdlc state # Show current global state
sdlc next # Run classifier, show next action
sdlc next --execute # Run classifier and execute action
sdlc next --for <feature> # Classify for specific feature
sdlc history # Show action history
# ============================================
# QUERIES
# ============================================
sdlc query blocked # List all blocked items
sdlc query ready # List items ready for work
sdlc query needs-approval # List items awaiting approval
sdlc query in-progress # List items in progress
```
### CLI Output Format
```bash
$ sdlc next --for auth
┌─────────────────────────────────────────────────────────────────┐
│ SDLC Classifier Result │
├─────────────────────────────────────────────────────────────────┤
│ Feature: auth │
│ Current Phase: implementation │
│ Tasks: 5/8 complete, 1 in-progress, 2 pending │
├─────────────────────────────────────────────────────────────────┤
│ NEXT ACTION: IMPLEMENT_TASK │
│ │
│ Command: /implement-task auth task-004 │
│ Task: Implement JWT token validation │
│ Output: .sdlc/features/auth/tasks.md (updated)
│ │
│ Context provided to command: │
│ - Task specification │
│ - Required patterns: error-handling │
│ - Related files: internal/auth/jwt.go │
└─────────────────────────────────────────────────────────────────┘
Run with --execute to execute this action.
```
---
## Command Specifications
Every command MUST:
1. Read context from SDLC structure
2. Produce a concrete artifact
3. Write artifact to the correct location
4. Update manifest/state
5. Return structured output
### Command Catalog
#### Phase: Planning
| Command | Input | Output Location | Output Type |
|---------|-------|-----------------|-------------|
| `/plan-roadmap` | Version, goals | `.sdlc/roadmap/{version}/roadmap.md` | Roadmap document |
| `/spec-feature` | Feature slug | `.sdlc/features/{slug}/spec.md` | Specification |
| `/design-feature` | Feature slug | `.sdlc/features/{slug}/design.md` | Design document |
| `/breakdown-feature` | Feature slug | `.sdlc/features/{slug}/tasks.md` | Task breakdown |
| `/create-qa-plan` | Feature slug | `.sdlc/features/{slug}/qa-plan.md` | QA verification plan |
#### Phase: Implementation
| Command | Input | Output Location | Output Type |
|---------|-------|-----------------|-------------|
| `/create-branch` | Feature slug | `.sdlc/branches/{branch}.yaml` | Branch tracking |
| `/implement-task` | Feature, task ID | `.sdlc/features/{slug}/tasks.md` | Task completion |
| `/implement-feature` | Feature slug | `.sdlc/features/{slug}/tasks.md` | All tasks (orchestrated) |
#### Phase: Quality
| Command | Input | Output Location | Output Type |
|---------|-------|-----------------|-------------|
| `/review-feature` | Feature slug | `.sdlc/features/{slug}/review.md` | Review findings |
| `/fix-review-issues` | Feature slug | `.sdlc/features/{slug}/review.md` | Updated findings |
| `/audit-feature` | Feature slug | `.sdlc/features/{slug}/audit.md` | Audit findings |
| `/remediate-audit` | Feature slug | `.sdlc/features/{slug}/audit.md` | Updated findings |
| `/run-qa` | Feature slug | `.sdlc/features/{slug}/qa-results.md` | QA results |
| `/fix-qa-failures` | Feature slug | `.sdlc/features/{slug}/qa-results.md` | Updated results |
#### Phase: Release
| Command | Input | Output Location | Output Type |
|---------|-------|-----------------|-------------|
| `/merge-feature` | Feature slug | Git merge + manifest update | Merged branch |
| `/archive-feature` | Feature slug | `.sdlc/archives/{slug}/` | Archived feature |
#### Patterns
| Command | Input | Output Location | Output Type |
|---------|-------|-----------------|-------------|
| `/identify-pattern` | Pattern description | `.sdlc/patterns/{slug}/pattern.md` | Pattern draft |
| `/elevate-pattern` | Pattern slug | `.sdlc/patterns/{slug}/pattern.md` | Elevated pattern |
| `/add-pattern-examples` | Pattern slug | `.sdlc/patterns/{slug}/examples.md` | Code examples |
| `/find-pattern-violations` | Pattern slug | `.sdlc/patterns/{slug}/violations.md` | Violation list |
| `/fix-pattern-violations` | Pattern slug | `.sdlc/patterns/{slug}/adoption.md` | Adoption progress |
#### Orchestration
| Command | Input | Output Location | Output Type |
|---------|-------|-----------------|-------------|
| `/next` | Optional: feature | Classifier output | Next action |
| `/deliver` | Feature slug | Orchestrates full delivery | Full feature delivery |
---
## Document Specifications
### spec.md (Feature Specification)
```markdown
---
feature: auth
version: 1
status: approved
approved_by: user
approved_at: 2024-01-10T14:00:00Z
---
# Feature: User Authentication System
## Overview
[2-3 sentence summary of what this feature does]
## Problem Statement
[What problem does this solve? Why is it needed?]
## User Stories
- As a [user type], I want to [action] so that [benefit]
- ...
## Acceptance Criteria
- [ ] AC1: Users can register with email and password
- [ ] AC2: Users can log in with valid credentials
- [ ] AC3: Invalid credentials return appropriate error
- [ ] AC4: Sessions expire after 24 hours
- ...
## Non-Functional Requirements
- Performance: Login < 200ms p99
- Security: Passwords hashed with bcrypt, cost 12
- Availability: 99.9% uptime
## Out of Scope
- Social login (future feature)
- MFA (future feature)
## Dependencies
- Database provisioning (complete)
- Error handling pattern (in progress)
## Open Questions
[Any unresolved questions - must be empty before approval]
```
### tasks.md (Task Breakdown)
```markdown
---
feature: auth
version: 1
total_tasks: 8
completed: 5
in_progress: 1
blocked: 0
pending: 2
---
# Task Breakdown: User Authentication
## Summary
| Status | Count |
|--------|-------|
| ✓ Complete | 5 |
| → In Progress | 1 |
| ○ Pending | 2 |
| ✗ Blocked | 0 |
## Tasks
### task-001: Create User domain model ✓
- **Status:** complete
- **Completed:** 2024-01-12T10:00:00Z
- **Files:** `internal/domain/user.go`
- **Patterns:** error-handling
- **Notes:** Added validation for email format
### task-002: Create UserRepository interface ✓
- **Status:** complete
- **Completed:** 2024-01-12T11:00:00Z
- **Files:** `internal/port/user_repository.go`
### task-003: Implement PostgreSQL UserRepository ✓
- **Status:** complete
- **Completed:** 2024-01-12T14:00:00Z
- **Files:** `internal/adapter/postgres/user_repo.go`
- **Tests:** `internal/adapter/postgres/user_repo_test.go`
### task-004: Implement JWT token validation →
- **Status:** in_progress
- **Started:** 2024-01-12T15:00:00Z
- **Spec:** |
Implement JWT token validation middleware:
- Parse Authorization header (Bearer token)
- Validate token signature using project secret
- Extract claims and attach to context
- Return 401 for invalid/expired tokens
- **Files:**
- `internal/auth/jwt.go`
- `internal/middleware/auth.go`
- **Patterns:** error-handling
- **Depends on:** task-001, task-002
### task-005: Implement login endpoint ○
- **Status:** pending
- **Spec:** |
POST /api/v1/auth/login
- Accept email + password
- Validate credentials
- Return JWT token on success
- Return 401 on failure
- **Depends on:** task-003, task-004
### task-006: Implement register endpoint ○
- **Status:** pending
- **Spec:** |
POST /api/v1/auth/register
- Accept email + password
- Validate email format and password strength
- Hash password with bcrypt
- Create user record
- Return 201 on success
- **Depends on:** task-003
### task-007: Add authentication tests ✓
- **Status:** complete
- **Completed:** 2024-01-12T16:00:00Z
- **Files:** `internal/auth/*_test.go`
### task-008: Update API documentation ✓
- **Status:** complete
- **Completed:** 2024-01-12T16:30:00Z
- **Files:** `docs/api/auth.md`
```
### qa-plan.md (QA Verification Plan)
```markdown
---
feature: auth
version: 1
checkpoints: 12
categories:
- functional: 6
- security: 4
- performance: 2
---
# QA Verification Plan: User Authentication
## Functional Tests
### QA-001: User Registration Happy Path
- **Category:** functional
- **Priority:** P0
- **Steps:**
1. POST /api/v1/auth/register with valid email and password
2. Verify response status 201
3. Verify response contains user ID
4. Verify user exists in database
5. Verify password is hashed (not plaintext)
- **Expected:** User created successfully
### QA-002: User Registration - Invalid Email
- **Category:** functional
- **Priority:** P0
- **Steps:**
1. POST /api/v1/auth/register with invalid email format
2. Verify response status 400
3. Verify error message indicates email format issue
- **Expected:** Validation error returned
### QA-003: User Login Happy Path
- **Category:** functional
- **Priority:** P0
- **Steps:**
1. Create test user
2. POST /api/v1/auth/login with correct credentials
3. Verify response status 200
4. Verify response contains valid JWT token
5. Verify token contains correct claims
- **Expected:** Valid JWT returned
### QA-004: User Login - Invalid Password
- **Category:** functional
- **Priority:** P0
- **Steps:**
1. Create test user
2. POST /api/v1/auth/login with wrong password
3. Verify response status 401
4. Verify error message is generic (not revealing which field is wrong)
- **Expected:** Authentication error, no information leakage
### QA-005: Protected Endpoint - Valid Token
- **Category:** functional
- **Priority:** P0
- **Steps:**
1. Obtain valid JWT token
2. Access protected endpoint with token in Authorization header
3. Verify response status 200
4. Verify user context is available
- **Expected:** Access granted
### QA-006: Protected Endpoint - Expired Token
- **Category:** functional
- **Priority:** P0
- **Steps:**
1. Generate expired JWT token
2. Access protected endpoint with expired token
3. Verify response status 401
4. Verify error indicates token expiration
- **Expected:** Access denied with clear message
## Security Tests
### QA-007: SQL Injection Prevention
- **Category:** security
- **Priority:** P0
- **Steps:**
1. Attempt login with SQL injection payloads
2. Verify no SQL errors exposed
3. Verify queries are parameterized (code review)
- **Expected:** All inputs sanitized
### QA-008: Password Storage Security
- **Category:** security
- **Priority:** P0
- **Steps:**
1. Create user
2. Examine database record
3. Verify password is bcrypt hashed
4. Verify cost factor >= 12
- **Expected:** Passwords securely hashed
### QA-009: Token Secret Security
- **Category:** security
- **Priority:** P0
- **Steps:**
1. Verify JWT secret loaded from environment
2. Verify secret not logged
3. Verify secret not in code
- **Expected:** Secret properly managed
### QA-010: Brute Force Protection
- **Category:** security
- **Priority:** P1
- **Steps:**
1. Attempt 10 failed logins rapidly
2. Verify rate limiting kicks in
3. Verify appropriate error returned
- **Expected:** Rate limiting active
## Performance Tests
### QA-011: Login Latency
- **Category:** performance
- **Priority:** P1
- **Steps:**
1. Run 100 login requests
2. Measure p50, p90, p99 latency
- **Expected:** p99 < 200ms
### QA-012: Token Validation Latency
- **Category:** performance
- **Priority:** P1
- **Steps:**
1. Run 1000 authenticated requests
2. Measure validation overhead
- **Expected:** < 5ms overhead
```
### review.md (Code Review Findings)
```markdown
---
feature: auth
version: 1
reviewed_at: 2024-01-13T10:00:00Z
status: needs_fix
findings:
blocker: 0
critical: 1
warning: 3
suggestion: 2
---
# Code Review: User Authentication
## Summary
| Severity | Count | Status |
|----------|-------|--------|
| Blocker | 0 | - |
| Critical | 1 | ✗ Open |
| Warning | 3 | ✗ Open |
| Suggestion | 2 | ✗ Open |
**Verdict:** NEEDS_FIX
## Findings
### CRITICAL-001: Missing error context in JWT validation
- **File:** `internal/auth/jwt.go:45`
- **Status:** open
- **Issue:** Error returned without context, making debugging difficult
- **Code:**
```go
// Current
return nil, err
// Should be
return nil, fmt.Errorf("validate jwt token: %w", err)
```
- **Fix Applied:** [ ]
### WARNING-001: Inconsistent error handling in login handler
- **File:** `internal/handlers/auth.go:67`
- **Status:** open
- **Issue:** Uses `api.WriteError` instead of `api.WriteUnauthorized`
- **Pattern:** error-handling
- **Fix Applied:** [ ]
### WARNING-002: Missing table-driven tests for token validation
- **File:** `internal/auth/jwt_test.go`
- **Status:** open
- **Issue:** Tests cover happy path but miss edge cases
- **Missing cases:**
- Empty token
- Malformed token
- Token with invalid signature
- Token with missing claims
- **Fix Applied:** [ ]
### WARNING-003: Hardcoded token expiration
- **File:** `internal/auth/jwt.go:23`
- **Status:** open
- **Issue:** Token expiration hardcoded to 24h, should be configurable
- **Fix Applied:** [ ]
### SUGGESTION-001: Consider extracting JWT config
- **File:** `internal/auth/jwt.go`
- **Status:** open
- **Issue:** JWT configuration inline, could be cleaner as config struct
- **Fix Applied:** [ ]
### SUGGESTION-002: Add structured logging for auth events
- **File:** `internal/handlers/auth.go`
- **Status:** open
- **Issue:** No logging for login attempts (success/failure)
- **Fix Applied:** [ ]
## What's Good
- Clean separation between domain and handler layers
- Proper use of context for request scoping
- Good test coverage for happy paths
- Consistent API response format
```
### audit.md (Post-Implementation Audit)
```markdown
---
feature: auth
version: 1
audited_at: 2024-01-13T14:00:00Z
status: needs_remediation
categories:
- pattern_compliance
- security
- performance
- documentation
findings:
critical: 0
high: 2
medium: 3
low: 1
---
# Audit Report: User Authentication
## Summary
| Category | Status | Issues |
|----------|--------|--------|
| Pattern Compliance | ⚠️ | 2 issues |
| Security | ✓ | 0 issues |
| Performance | ⚠️ | 1 issue |
| Documentation | ⚠️ | 2 issues |
**Verdict:** NEEDS_REMEDIATION
## Pattern Compliance
### HIGH-001: Logging pattern not followed
- **Pattern:** logging-standards
- **Files:**
- `internal/handlers/auth.go` - No structured logging
- `internal/auth/jwt.go` - No trace ID propagation
- **Required:** All handlers must log with trace ID and structured fields
- **Remediation:** Apply logging pattern to all auth files
- **Remediated:** [ ]
### HIGH-002: Error handling inconsistent
- **Pattern:** error-handling
- **Files:**
- `internal/auth/jwt.go:45` - Missing error context
- `internal/auth/jwt.go:67` - Missing error context
- **Required:** All errors wrapped with context
- **Remediation:** Add error wrapping
- **Remediated:** [ ]
## Security
No issues found. ✓
## Performance
### MEDIUM-001: Database connection not pooled efficiently
- **File:** `internal/adapter/postgres/user_repo.go`
- **Issue:** Each query creates new connection
- **Impact:** Higher latency under load
- **Remediation:** Use connection pool from injected DB
- **Remediated:** [ ]
## Documentation
### MEDIUM-002: API documentation incomplete
- **File:** `docs/api/auth.md`
- **Missing:**
- Error response examples
- Rate limiting documentation
- **Remediation:** Add missing sections
- **Remediated:** [ ]
### LOW-001: Code comments sparse
- **Files:** Various
- **Issue:** Complex logic not commented
- **Remediation:** Add comments for non-obvious code
- **Remediated:** [ ]
## Recommendations
1. Run `/fix-pattern-violations logging-standards` on auth module
2. Run `/fix-pattern-violations error-handling` on auth module
3. Update API documentation
```
### pattern.md (Pattern Specification)
```markdown
---
pattern: error-handling
version: 2
status: elevated
created: 2024-01-05T09:00:00Z
elevated: 2024-01-10T14:00:00Z
adoption:
total_files: 45
compliant: 38
violations: 7
---
# Pattern: Error Handling
## Overview
All errors in {{PROJECT_NAME}} must be wrapped with context, use sentinel errors for known conditions, and propagate correctly through the hexagonal architecture.
## The Pattern
### 1. Error Wrapping
Always wrap errors with context using `fmt.Errorf` with `%w`:
```go
// ✓ GOOD
result, err := repo.FindByID(ctx, id)
if err != nil {
return nil, fmt.Errorf("find user by id %s: %w", id, err)
}
// ✗ BAD
result, err := repo.FindByID(ctx, id)
if err != nil {
return nil, err // Lost context!
}
```
### 2. Sentinel Errors
Define sentinel errors in `internal/domain/errors.go`:
```go
var (
ErrNotFound = errors.New("not found")
ErrAlreadyExists = errors.New("already exists")
ErrInvalidInput = errors.New("invalid input")
ErrUnauthorized = errors.New("unauthorized")
ErrForbidden = errors.New("forbidden")
)
```
### 3. Error Checking
Use `errors.Is` for sentinel errors:
```go
if errors.Is(err, domain.ErrNotFound) {
api.WriteNotFound(w, "user not found")
return
}
```
### 4. Handler Error Responses
Use appropriate response helpers:
```go
// ✓ GOOD
api.WriteNotFound(w, "user not found")
api.WriteBadRequest(w, "invalid email format")
api.WriteUnauthorized(w, "invalid credentials")
// ✗ BAD
api.WriteError(w, http.StatusNotFound, "NOT_FOUND", "user not found")
```
### 5. Never Swallow Errors
```go
// ✗ NEVER DO THIS
result, _ := something()
// ✓ ALWAYS HANDLE
result, err := something()
if err != nil {
// handle it
}
```
## Detection Rules
```go
// Violations to detect:
// 1. Bare error returns: `return nil, err` without wrapping
// 2. Ignored errors: `_, _ = something()` or `_ = err`
// 3. Direct status codes: `api.WriteError(w, 404, ...)` instead of helpers
// 4. errors.New in handlers (should use domain errors)
```
## Adoption Status
| Status | Files |
|--------|-------|
| Compliant | 38 |
| Violations | 7 |
| **Total** | 45 |
### Known Violations
See `.sdlc/patterns/error-handling/violations.md` for current violation list.
```
---
## Driver / Orchestrator
The driver is a simple loop that uses the classifier to determine and execute the next action.
### Driver Pseudocode
```python
def drive(target: str = None, max_iterations: int = 100):
"""
Main driver loop that advances SDLC state.
Args:
target: Optional specific feature/pattern to focus on
max_iterations: Safety limit to prevent infinite loops
"""
iteration = 0
while iteration < max_iterations:
iteration += 1
# 1. Run classifier
classification = sdlc_cli("next", target)
# 2. Check for terminal states
if classification.action == "IDLE":
log("No actionable work found")
break
if classification.action == "BLOCKED":
log(f"Blocked: {classification.message}")
prompt_user_for_resolution()
continue
if classification.action == "AWAIT_APPROVAL":
log(f"Awaiting approval: {classification.message}")
approval = prompt_user_for_approval()
if approval:
sdlc_cli("artifact", "approve", classification.artifact)
continue
# 3. Execute action
log(f"Executing: {classification.command}")
result = execute_claude_command(classification.command)
# 4. Verify output was produced
if not verify_output_exists(classification.output_path):
log(f"ERROR: Expected output not found at {classification.output_path}")
prompt_user_for_intervention()
continue
# 5. Update state
sdlc_cli("state", "record-action", classification.action)
# 6. Handle transitions
if classification.action == "TRANSITION":
sdlc_cli("feature", "transition", target, classification.transition_to)
# 7. Loop continues with next classification
if iteration >= max_iterations:
log("WARNING: Max iterations reached, stopping driver")
```
### Claude Command: `/next`
```markdown
---
description: Determine and optionally execute the next SDLC action
argument-hint: <feature-slug> or "all" for global next action
allowed-tools: Bash, Read, Write, Edit
---
Determine what needs to happen next for: $ARGUMENTS
## Instructions
1. Run the classifier:
```bash
sdlc next --for $ARGUMENTS
```
2. Parse the classifier output
3. If action is AWAIT_APPROVAL:
- Show what needs approval
- Ask user to approve/reject
- Record decision with `sdlc artifact approve/reject`
4. If action is BLOCKED:
- Show the blocker
- Ask user how to resolve
5. If action is a command:
- Show the recommended command
- Ask user: "Execute this? (y/n)"
- If yes, execute and verify output
6. After execution:
- Verify output file exists at expected location
- Update state: `sdlc state record-action <action>`
- Run classifier again to show next step
## Output Format
```markdown
## SDLC Status: {feature}
**Phase:** {current_phase}
**Progress:** {tasks_complete}/{tasks_total} tasks
### Next Action: {action}
**Command:** `{command}`
**Output:** `{output_path}`
**Context:**
{context_summary}
---
Execute this action? (y/n)
```
```
---
## Enterprise Considerations
### Audit Trail
Every action is logged:
```yaml
# .sdlc/state.yaml (history section)
history:
- timestamp: "2024-01-15T10:30:00Z"
action: "IMPLEMENT_TASK"
feature: "auth"
task: "task-004"
actor: "claude"
result: "success"
output: ".sdlc/features/auth/tasks.md"
- timestamp: "2024-01-15T10:35:00Z"
action: "TRANSITION"
feature: "auth"
from_phase: "implementation"
to_phase: "review"
actor: "classifier"
```
### Compliance Gates
Define required approvals:
```yaml
# .sdlc/config.yaml
compliance:
spec_approval:
required: true
approvers: ["user", "tech-lead"]
design_approval:
required: true
approvers: ["user", "architect"]
merge_approval:
required: true
approvers: ["user"]
checks:
- "all_tasks_complete"
- "review_passed"
- "audit_passed"
- "qa_passed"
```
### Metrics
Track development velocity:
```yaml
# .sdlc/metrics.yaml
features:
auth:
cycle_time_days: 5
phases:
draft_to_specified: 0.5
specified_to_planned: 1.0
planned_to_ready: 0.5
ready_to_implementation: 3.0
implementation_to_review: 0.5
review_to_audit: 0.25
audit_to_qa: 0.25
qa_to_merge: 0.25
review_iterations: 2
audit_iterations: 1
qa_iterations: 1
```
### Rollback Support
Every phase transition is reversible:
```bash
# Rollback feature to previous phase
sdlc feature rollback auth --to implementation
# This:
# 1. Updates manifest phase
# 2. Clears artifacts for phases after target
# 3. Records rollback in history
```
---
## rdev API Surface
Every classifier rule maps to an API-addressable state. The API provides full visibility and control over the SDLC workflow.
### Core Principle
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ API-First SDLC │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ External Driver (CI, UI, Bot) │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ rdev API │◀──── GET /sdlc/next "What needs to happen?" │
│ │ │◀──── GET /sdlc/blocked "What's stuck?" │
│ │ │◀──── POST /sdlc/resolve "Here's the answer" │
│ │ │◀──── POST /sdlc/execute "Do it" │
│ │ │◀──── POST /sdlc/commit "Save it" │
│ └─────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Classifier │───▶│ Executor │───▶│ Git │ │
│ │ Engine │ │ (Claude) │ │ (.sdlc/) │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
```
### API Endpoints
#### State & Classification
```
GET /projects/{project}/sdlc/state
```
Returns current SDLC state for the project.
```json
{
"project": "my-project",
"current_roadmap": "v1.0",
"active_features": [
{
"slug": "auth",
"phase": "implementation",
"branch": "feature/auth",
"tasks_complete": 5,
"tasks_total": 8,
"blocked": false
}
],
"active_patterns": [],
"blocked_items": []
}
```
---
```
GET /projects/{project}/sdlc/next
GET /projects/{project}/sdlc/next?feature={slug}
```
Run classifier and return the next required action.
```json
{
"classification": {
"rule_id": "implement-next-task",
"action": "IMPLEMENT_TASK",
"feature": "auth",
"task_id": "task-004"
},
"instruction": {
"summary": "Implement JWT token validation",
"command": "/implement-task auth task-004",
"output_path": ".sdlc/features/auth/tasks.md",
"context": {
"task_spec": "Implement JWT token validation middleware...",
"patterns_required": ["error-handling"],
"related_files": ["internal/auth/jwt.go"]
}
},
"execute_url": "/projects/my-project/sdlc/execute",
"can_auto_execute": true
}
```
---
```
GET /projects/{project}/sdlc/blocked
```
Returns all blocked items with resolution instructions.
```json
{
"blocked": [
{
"type": "feature",
"slug": "auth",
"rule_id": "spec-needs-approval",
"blocked_reason": "Specification requires user approval",
"resolution": {
"action": "APPROVE_ARTIFACT",
"instruction": "Review the specification and approve or request changes",
"artifact_path": ".sdlc/features/auth/spec.md",
"resolve_url": "/projects/my-project/sdlc/features/auth/artifacts/spec/approve",
"options": ["approve", "reject", "request_changes"]
}
},
{
"type": "feature",
"slug": "payment",
"rule_id": "blocked-dependency",
"blocked_reason": "Depends on feature 'auth' which is not complete",
"resolution": {
"action": "COMPLETE_DEPENDENCY",
"instruction": "Complete the 'auth' feature first",
"dependency": "auth",
"dependency_phase": "implementation",
"unblock_url": null
}
},
{
"type": "feature",
"slug": "notifications",
"rule_id": "design-decision-needed",
"blocked_reason": "Design decision required: Choose notification transport",
"resolution": {
"action": "ANSWER_QUESTION",
"instruction": "Answer the design question in the design document",
"question": "Which notification transport should we use?",
"options": ["websocket", "sse", "polling"],
"answer_path": ".sdlc/features/notifications/design.md",
"answer_section": "## Open Questions",
"resolve_url": "/projects/my-project/sdlc/features/notifications/resolve"
}
}
]
}
```
#### Execution
```
POST /projects/{project}/sdlc/execute
```
Execute the next classified action. Returns execution result and new state.
Request:
```json
{
"feature": "auth",
"action": "IMPLEMENT_TASK",
"task_id": "task-004",
"auto_commit": true
}
```
Response:
```json
{
"execution": {
"status": "success",
"action": "IMPLEMENT_TASK",
"duration_ms": 45000,
"output_path": ".sdlc/features/auth/tasks.md",
"files_modified": [
"internal/auth/jwt.go",
"internal/middleware/auth.go",
".sdlc/features/auth/tasks.md"
],
"commit": {
"sha": "abc123",
"message": "feat(auth): implement JWT token validation [task-004]"
}
},
"next": {
"action": "IMPLEMENT_TASK",
"task_id": "task-005",
"summary": "Implement login endpoint"
}
}
```
---
```
POST /projects/{project}/sdlc/resolve
```
Resolve a blocked item by providing the required input.
Request:
```json
{
"feature": "notifications",
"resolution_type": "ANSWER_QUESTION",
"question_id": "notification-transport",
"answer": "websocket",
"rationale": "WebSocket provides real-time bidirectional communication needed for instant notifications",
"auto_commit": true
}
```
Response:
```json
{
"resolution": {
"status": "resolved",
"file_updated": ".sdlc/features/notifications/design.md",
"commit": {
"sha": "def456",
"message": "docs(notifications): resolve design decision - use websocket transport"
}
},
"unblocked": true,
"next": {
"action": "CREATE_TASKS",
"command": "/breakdown-feature notifications"
}
}
```
#### Feature Management
```
POST /projects/{project}/sdlc/features
```
Create a new feature.
Request:
```json
{
"slug": "auth",
"title": "User Authentication System",
"roadmap_ref": "v1.0/M2",
"description": "Implement user registration, login, and session management"
}
```
---
```
GET /projects/{project}/sdlc/features/{slug}
```
Get feature details including all artifacts and current state.
```json
{
"slug": "auth",
"title": "User Authentication System",
"phase": "implementation",
"branch": "feature/auth",
"created": "2024-01-10T09:00:00Z",
"artifacts": {
"spec": {
"status": "approved",
"path": ".sdlc/features/auth/spec.md",
"url": "/projects/my-project/files/.sdlc/features/auth/spec.md"
},
"design": {
"status": "approved",
"path": ".sdlc/features/auth/design.md"
},
"tasks": {
"status": "in_progress",
"path": ".sdlc/features/auth/tasks.md",
"summary": {
"total": 8,
"complete": 5,
"in_progress": 1,
"pending": 2
}
},
"qa_plan": {
"status": "approved",
"checkpoints": 12
},
"review": {
"status": "pending"
},
"audit": {
"status": "pending"
},
"qa_results": {
"status": "pending"
}
},
"next_action": {
"action": "IMPLEMENT_TASK",
"task_id": "task-004"
}
}
```
---
```
POST /projects/{project}/sdlc/features/{slug}/transition
```
Manually transition a feature to a new phase (with validation).
Request:
```json
{
"to_phase": "review",
"force": false
}
```
Response:
```json
{
"transition": {
"from": "implementation",
"to": "review",
"status": "success"
}
}
```
Or if validation fails:
```json
{
"transition": {
"from": "implementation",
"to": "review",
"status": "blocked",
"reason": "Cannot transition: 2 tasks still pending",
"blockers": [
{"task_id": "task-007", "title": "Add authentication tests"},
{"task_id": "task-008", "title": "Update API documentation"}
]
}
}
```
#### Artifact Management
```
GET /projects/{project}/sdlc/features/{slug}/artifacts/{type}
```
Get artifact content.
```json
{
"artifact": {
"type": "spec",
"status": "approved",
"path": ".sdlc/features/auth/spec.md",
"content": "# Feature: User Authentication...",
"approved_by": "user",
"approved_at": "2024-01-10T14:00:00Z"
}
}
```
---
```
POST /projects/{project}/sdlc/features/{slug}/artifacts/{type}
```
Create or update an artifact.
Request:
```json
{
"content": "# Feature: User Authentication\n\n## Overview\n...",
"auto_commit": true,
"commit_message": "docs(auth): update specification"
}
```
---
```
POST /projects/{project}/sdlc/features/{slug}/artifacts/{type}/approve
```
Approve an artifact.
Request:
```json
{
"approved_by": "user",
"comments": "Looks good, approved for implementation"
}
```
---
```
POST /projects/{project}/sdlc/features/{slug}/artifacts/{type}/reject
```
Reject an artifact with feedback.
Request:
```json
{
"rejected_by": "user",
"reason": "Missing acceptance criteria for error cases",
"required_changes": [
"Add AC for invalid email format",
"Add AC for password requirements"
]
}
```
#### Task Management
```
GET /projects/{project}/sdlc/features/{slug}/tasks
```
List all tasks for a feature.
```json
{
"tasks": [
{
"id": "task-001",
"title": "Create User domain model",
"status": "complete",
"completed_at": "2024-01-12T10:00:00Z"
},
{
"id": "task-004",
"title": "Implement JWT token validation",
"status": "in_progress",
"started_at": "2024-01-12T15:00:00Z",
"spec": "Implement JWT token validation middleware..."
},
{
"id": "task-005",
"title": "Implement login endpoint",
"status": "pending",
"depends_on": ["task-003", "task-004"]
}
]
}
```
---
```
POST /projects/{project}/sdlc/features/{slug}/tasks/{task_id}/start
POST /projects/{project}/sdlc/features/{slug}/tasks/{task_id}/complete
POST /projects/{project}/sdlc/features/{slug}/tasks/{task_id}/block
```
Update task status.
#### Pattern Management
```
GET /projects/{project}/sdlc/patterns
GET /projects/{project}/sdlc/patterns/{slug}
POST /projects/{project}/sdlc/patterns
POST /projects/{project}/sdlc/patterns/{slug}/violations
POST /projects/{project}/sdlc/patterns/{slug}/adopt
```
#### Git Operations
```
POST /projects/{project}/sdlc/commit
```
Commit current SDLC changes.
Request:
```json
{
"message": "docs(auth): complete task-004 specification",
"files": [".sdlc/features/auth/tasks.md"]
}
```
---
```
POST /projects/{project}/sdlc/branches
```
Create a feature branch.
Request:
```json
{
"feature": "auth",
"base": "main"
}
```
---
```
POST /projects/{project}/sdlc/branches/{branch}/sync
```
Sync feature branch with main.
---
```
POST /projects/{project}/sdlc/merge
```
Merge a completed feature.
Request:
```json
{
"feature": "auth",
"strategy": "squash",
"delete_branch": true
}
```
### Classifier Rule → API Mapping
Every classifier rule has a corresponding API interaction:
| Rule ID | Action | API Endpoint | Method |
|---------|--------|--------------|--------|
| `needs-spec` | CREATE_SPEC | `/sdlc/execute` | POST |
| `spec-needs-approval` | AWAIT_APPROVAL | `/sdlc/features/{slug}/artifacts/spec/approve` | POST |
| `needs-design` | CREATE_DESIGN | `/sdlc/execute` | POST |
| `design-decision-needed` | ANSWER_QUESTION | `/sdlc/resolve` | POST |
| `needs-tasks` | CREATE_TASKS | `/sdlc/execute` | POST |
| `needs-qa-plan` | CREATE_QA_PLAN | `/sdlc/execute` | POST |
| `needs-branch` | CREATE_BRANCH | `/sdlc/branches` | POST |
| `blocked-dependency` | BLOCKED | `/sdlc/blocked` | GET (info only) |
| `implement-next-task` | IMPLEMENT_TASK | `/sdlc/execute` | POST |
| `implementation-complete` | TRANSITION | `/sdlc/features/{slug}/transition` | POST |
| `needs-review` | REVIEW_CODE | `/sdlc/execute` | POST |
| `review-has-issues` | FIX_ISSUES | `/sdlc/execute` | POST |
| `review-passed` | TRANSITION | `/sdlc/features/{slug}/transition` | POST |
| `needs-audit` | AUDIT_CODE | `/sdlc/execute` | POST |
| `audit-has-issues` | REMEDIATE | `/sdlc/execute` | POST |
| `needs-qa` | RUN_QA | `/sdlc/execute` | POST |
| `qa-has-failures` | FIX_FAILURES | `/sdlc/execute` | POST |
| `needs-merge` | MERGE | `/sdlc/merge` | POST |
### Blocking Resolution Flow
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ Blocking Resolution Flow │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ 1. GET /sdlc/blocked │
│ ↓ │
│ Returns: { │
│ "blocked_reason": "Design decision required", │
│ "question": "Which auth provider?", │
│ "options": ["jwt", "oauth", "session"], │
│ "answer_path": ".sdlc/features/auth/design.md", │
│ "resolve_url": "/sdlc/features/auth/resolve" │
│ } │
│ │
│ 2. POST /sdlc/features/auth/resolve │
│ Body: { │
│ "question_id": "auth-provider", │
│ "answer": "jwt", │
│ "rationale": "Stateless, works well with microservices" │
│ } │
│ ↓ │
│ System: Writes answer to design.md │
│ │
│ 3. POST /sdlc/commit │
│ Body: { "message": "docs(auth): decide on JWT provider" } │
│ ↓ │
│ System: Commits the change │
│ │
│ 4. GET /sdlc/next?feature=auth │
│ ↓ │
│ Returns: Next action (no longer blocked) │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
```
### Driver Loop (External Orchestrator)
```python
# Example driver that uses the API
import requests
BASE = "https://rdev.example.com/projects/my-project"
def drive_feature(feature_slug):
while True:
# 1. Check for blockers
blocked = requests.get(f"{BASE}/sdlc/blocked").json()
feature_blockers = [b for b in blocked["blocked"] if b["slug"] == feature_slug]
if feature_blockers:
blocker = feature_blockers[0]
if blocker["resolution"]["action"] == "ANSWER_QUESTION":
# Present to user, get answer
answer = prompt_user(blocker["resolution"]["question"],
blocker["resolution"]["options"])
# Resolve it
requests.post(blocker["resolution"]["resolve_url"], json={
"answer": answer,
"auto_commit": True
})
continue
elif blocker["resolution"]["action"] == "APPROVE_ARTIFACT":
# Show artifact, get approval
artifact = requests.get(f"{BASE}/sdlc/features/{feature_slug}/artifacts/{blocker['artifact']}").json()
if prompt_user_approval(artifact["content"]):
requests.post(blocker["resolution"]["resolve_url"], json={
"approved_by": "user"
})
continue
else:
print(f"Blocked: {blocker['blocked_reason']}")
break
# 2. Get next action
next_action = requests.get(f"{BASE}/sdlc/next?feature={feature_slug}").json()
if next_action["classification"]["action"] == "IDLE":
print("Feature complete!")
break
# 3. Execute it
result = requests.post(f"{BASE}/sdlc/execute", json={
"feature": feature_slug,
"action": next_action["classification"]["action"],
"auto_commit": True
}).json()
print(f"Executed: {result['execution']['action']}")
```
## Implementation Phases
### Phase 1: Core API Endpoints
1. `/sdlc/state` - GET current state
2. `/sdlc/features` - CRUD features
3. `/sdlc/features/{slug}/artifacts` - CRUD artifacts
4. `/sdlc/commit` - Commit changes
### Phase 2: Classifier & Execution
1. `/sdlc/next` - Run classifier
2. `/sdlc/execute` - Execute actions
3. `/sdlc/blocked` - List blockers
4. `/sdlc/resolve` - Resolve blockers
### Phase 3: Git Integration
1. `/sdlc/branches` - Branch management
2. `/sdlc/merge` - Merge features
3. Branch protection integration
### Phase 4: Task Execution
1. Claude command integration
2. Task status tracking
3. File modification tracking
### Phase 5: Full Workflow
1. Review/Audit/QA flows
2. Pattern management
3. Metrics and reporting
---
## Success Criteria
1. **Deterministic:** Same state always produces same next action
2. **Auditable:** Every action recorded with timestamp and actor
3. **Recoverable:** Can rollback any phase, can resume from any state
4. **Complete:** No work can be "lost" - everything has a place
5. **Enforceable:** Cannot merge without completing all gates
6. **Adaptive:** Rules can be customized per project
7. **Observable:** Current state always queryable
8. **Integrated:** Works seamlessly with Claude commands
---
## Appendix: File Templates
### .sdlc/config.yaml
```yaml
version: 1
project:
name: "{{PROJECT_NAME}}"
type: "composable-monorepo"
branches:
main: "main"
feature_prefix: "feature/"
phases:
enabled:
- draft
- specified
- planned
- ready
- implementation
- review
- audit
- qa
- merge
- released
required_artifacts:
specified: ["spec"]
planned: ["spec", "design", "tasks", "qa_plan"]
review: ["review"]
audit: ["audit"]
qa: ["qa_results"]
compliance:
require_approvals: true
require_branch: true
require_qa: true
patterns:
auto_enforce:
- error-handling
- logging-standards
```
### .sdlc/state.yaml (Initial)
```yaml
version: 1
project:
name: "{{PROJECT_NAME}}"
current_roadmap: null
active_work:
features: []
patterns: []
audits: []
blocked: []
last_updated: null
last_action: null
last_actor: null
history: []
```