---
title: "Complete Feature Traceability Workflow"
description: "End-to-end example of tracing a feature from requirement to deployment"
---

# Complete Feature Traceability Workflow

This example demonstrates a complete traceability workflow for implementing a user authentication feature in an e-commerce platform.

## Scenario Overview

**Project**: E-commerce Platform
**Feature**: User Authentication System
**Timeline**: 2-week sprint
**Team**: 3 developers, 2 testers, 1 product owner

## Step 1: Create Project

```bash
# Initialize project
trace project create "E-commerce Platform" \
  --description "Online retail platform with product catalog and checkout" \
  --template software-development

# Output:
# ✓ Project created successfully
# ID: proj_ecom_2024_001
# Name: E-commerce Platform
# Template: software-development
# Created: 2024-12-02T10:00:00Z
```

## Step 2: Create Feature Requirement

```bash
# Create main feature requirement
trace item create proj_ecom_2024_001 \
  --type feature \
  --title "User Authentication System" \
  --description "Implement secure user authentication with email/password and OAuth" \
  --priority 90 \
  --status planned \
  --metadata '{
    "acceptance_criteria": [
      "Users can register with email and password",
      "Email verification required",
      "OAuth login with Google and Facebook",
      "Password reset functionality",
      "Session management with JWT tokens",
      "MFA support (optional)"
    ],
    "business_value": "Enable personalized shopping experience and order tracking",
    "estimated_effort": "13 story points"
  }'

# Output:
# ✓ Item created successfully
# ID: item_auth_feature_001
# Type: feature
# Title: User Authentication System
# Priority: 90
```

## Step 3: Break Down Into Sub-Requirements

```bash
# User Registration
trace item create proj_ecom_2024_001 \
  --type requirement \
  --title "REQ-AUTH-001: User Registration" \
  --description "Users must be able to register with email and password" \
  --priority 95 \
  --metadata '{
    "requirement_id": "REQ-AUTH-001",
    "acceptance_criteria": [
      "Email validation (RFC 5322 compliant)",
      "Password strength: minimum 8 characters, 1 uppercase, 1 number, 1 special char",
      "Duplicate email check",
      "Send verification email",
      "Account activation via email link"
    ]
  }'

# Output: item_req_registration_001

# Link to parent feature
trace link create item_req_registration_001 item_auth_feature_001 \
  --type child_of \
  --metadata '{"relationship": "requirement breakdown"}'

# Email Verification
trace item create proj_ecom_2024_001 \
  --type requirement \
  --title "REQ-AUTH-002: Email Verification" \
  --description "Email verification must be required before account activation" \
  --priority 90 \
  --metadata '{
    "requirement_id": "REQ-AUTH-002",
    "acceptance_criteria": [
      "Generate secure verification token (256-bit)",
      "Token expires after 24 hours",
      "Resend verification email option",
      "Clear error messages for expired tokens"
    ]
  }'

# Output: item_req_verification_001

trace link create item_req_verification_001 item_auth_feature_001 \
  --type child_of

# OAuth Integration
trace item create proj_ecom_2024_001 \
  --type requirement \
  --title "REQ-AUTH-003: OAuth Integration" \
  --description "Support OAuth login with Google and Facebook" \
  --priority 85 \
  --metadata '{
    "requirement_id": "REQ-AUTH-003",
    "providers": ["google", "facebook"],
    "acceptance_criteria": [
      "OAuth 2.0 flow implementation",
      "Profile data synchronization",
      "Fallback to email if OAuth fails",
      "Link multiple OAuth accounts to same user"
    ]
  }'

# Output: item_req_oauth_001

trace link create item_req_oauth_001 item_auth_feature_001 \
  --type child_of
```

## Step 4: Create Design Documents

```bash
# Architecture Design
trace item create proj_ecom_2024_001 \
  --type design \
  --title "Authentication Service Architecture" \
  --description "Design document for authentication microservice" \
  --content "$(cat <<'EOF'
# Authentication Service Architecture

## Overview
Microservice-based authentication using JWT tokens and Redis session store.

## Components
1. **AuthService**: Core authentication logic
2. **UserRepository**: Database access layer
3. **TokenManager**: JWT generation and validation
4. **EmailService**: Verification email sender
5. **OAuthProvider**: Google/Facebook integration

## Technology Stack
- Go 1.21+ (backend)
- PostgreSQL 15 (user data)
- Redis 7 (session cache)
- JWT (token format)
- SendGrid (email delivery)

## Security Measures
- bcrypt for password hashing (cost factor: 12)
- HTTPS only
- Rate limiting: 5 attempts per minute
- CSRF protection
- XSS prevention
EOF
)"

# Output: item_design_arch_001

trace link create item_design_arch_001 item_auth_feature_001 \
  --type satisfies \
  --metadata '{"design_phase": "high-level-architecture"}'
```

## Step 5: Implement Code

```bash
# Create code items for implementation
trace item create proj_ecom_2024_001 \
  --type code \
  --title "AuthService.go" \
  --file-path "backend/services/auth/auth_service.go" \
  --metadata '{
    "language": "go",
    "package": "auth",
    "loc": 450,
    "functions": [
      "Register",
      "Login",
      "VerifyEmail",
      "ResetPassword",
      "RefreshToken"
    ]
  }' \
  --content "$(cat <<'EOF'
package auth

import (
    "context"
    "crypto/rand"
    "encoding/base64"
    "time"

    "golang.org/x/crypto/bcrypt"
)

// AuthService handles user authentication operations
type AuthService struct {
    userRepo      UserRepository
    tokenManager  *TokenManager
    emailService  EmailService
    cache         CacheStore
}

// Register creates a new user account
func (s *AuthService) Register(ctx context.Context, req RegisterRequest) (*User, error) {
    // Validate email format
    if !isValidEmail(req.Email) {
        return nil, ErrInvalidEmail
    }

    // Check password strength
    if err := validatePasswordStrength(req.Password); err != nil {
        return nil, err
    }

    // Check for existing user
    exists, err := s.userRepo.EmailExists(ctx, req.Email)
    if err != nil {
        return nil, err
    }
    if exists {
        return nil, ErrEmailAlreadyExists
    }

    // Hash password with bcrypt
    hashedPassword, err := bcrypt.GenerateFromPassword(
        []byte(req.Password),
        12, // cost factor
    )
    if err != nil {
        return nil, err
    }

    // Generate verification token
    verificationToken, err := generateSecureToken(32)
    if err != nil {
        return nil, err
    }

    // Create user
    user := &User{
        Email:             req.Email,
        PasswordHash:      string(hashedPassword),
        VerificationToken: verificationToken,
        CreatedAt:         time.Now(),
        IsVerified:        false,
    }

    if err := s.userRepo.Create(ctx, user); err != nil {
        return nil, err
    }

    // Send verification email
    if err := s.emailService.SendVerificationEmail(user); err != nil {
        // Log error but don't fail registration
        log.Errorf("Failed to send verification email: %v", err)
    }

    return user, nil
}

// Login authenticates user and returns JWT token
func (s *AuthService) Login(ctx context.Context, email, password string) (*AuthToken, error) {
    user, err := s.userRepo.FindByEmail(ctx, email)
    if err != nil {
        return nil, ErrInvalidCredentials
    }

    // Verify password
    if err := bcrypt.CompareHashAndPassword(
        []byte(user.PasswordHash),
        []byte(password),
    ); err != nil {
        return nil, ErrInvalidCredentials
    }

    // Check if email is verified
    if !user.IsVerified {
        return nil, ErrEmailNotVerified
    }

    // Generate JWT token
    token, err := s.tokenManager.GenerateToken(user)
    if err != nil {
        return nil, err
    }

    // Store session in Redis
    if err := s.cache.SetSession(ctx, user.ID, token, 24*time.Hour); err != nil {
        log.Errorf("Failed to cache session: %v", err)
    }

    return token, nil
}

// VerifyEmail activates user account
func (s *AuthService) VerifyEmail(ctx context.Context, token string) error {
    user, err := s.userRepo.FindByVerificationToken(ctx, token)
    if err != nil {
        return ErrInvalidVerificationToken
    }

    // Check token expiration (24 hours)
    if time.Since(user.CreatedAt) > 24*time.Hour {
        return ErrVerificationTokenExpired
    }

    user.IsVerified = true
    user.VerificationToken = ""
    user.VerifiedAt = time.Now()

    return s.userRepo.Update(ctx, user)
}

func generateSecureToken(length int) (string, error) {
    bytes := make([]byte, length)
    if _, err := rand.Read(bytes); err != nil {
        return "", err
    }
    return base64.URLEncoding.EncodeToString(bytes), nil
}

func validatePasswordStrength(password string) error {
    if len(password) < 8 {
        return ErrPasswordTooShort
    }
    // Additional validation logic...
    return nil
}
EOF
)"

# Output: item_code_authservice_001

# Link code implements requirements
trace link create item_code_authservice_001 item_req_registration_001 \
  --type implements \
  --metadata '{
    "implemented_by": "Register function",
    "lines": "25-80"
  }'

trace link create item_code_authservice_001 item_req_verification_001 \
  --type implements \
  --metadata '{
    "implemented_by": "VerifyEmail function",
    "lines": "120-145"
  }'

# User Repository
trace item create proj_ecom_2024_001 \
  --type code \
  --title "UserRepository.go" \
  --file-path "backend/repositories/user_repository.go" \
  --metadata '{
    "language": "go",
    "package": "repositories",
    "loc": 280
  }'

# Output: item_code_userrepo_001

trace link create item_code_userrepo_001 item_code_authservice_001 \
  --type depends_on \
  --metadata '{"dependency_type": "data_access"}'

# OAuth Provider
trace item create proj_ecom_2024_001 \
  --type code \
  --title "OAuthProvider.go" \
  --file-path "backend/services/auth/oauth_provider.go" \
  --metadata '{
    "language": "go",
    "package": "auth",
    "loc": 320
  }'

# Output: item_code_oauth_001

trace link create item_code_oauth_001 item_req_oauth_001 \
  --type implements
```

## Step 6: Create Test Cases

```bash
# Unit Tests
trace item create proj_ecom_2024_001 \
  --type test \
  --title "Test: User Registration Success" \
  --test-type unit \
  --metadata '{
    "test_id": "TEST-AUTH-001",
    "test_framework": "testify",
    "execution_time": "0.05s"
  }' \
  --content "$(cat <<'EOF'
func TestRegister_Success(t *testing.T) {
    // Setup
    mockRepo := &MockUserRepository{}
    mockEmail := &MockEmailService{}
    service := NewAuthService(mockRepo, mockEmail)

    req := RegisterRequest{
        Email:    "user@example.com",
        Password: "SecurePass123!",
    }

    mockRepo.On("EmailExists", mock.Anything, req.Email).Return(false, nil)
    mockRepo.On("Create", mock.Anything, mock.Anything).Return(nil)
    mockEmail.On("SendVerificationEmail", mock.Anything).Return(nil)

    // Execute
    user, err := service.Register(context.Background(), req)

    // Assert
    assert.NoError(t, err)
    assert.NotNil(t, user)
    assert.Equal(t, req.Email, user.Email)
    assert.NotEmpty(t, user.VerificationToken)
    assert.False(t, user.IsVerified)

    mockRepo.AssertExpectations(t)
    mockEmail.AssertExpectations(t)
}
EOF
)"

# Output: item_test_reg_success_001

trace link create item_test_reg_success_001 item_req_registration_001 \
  --type verifies \
  --metadata '{
    "test_coverage": "happy_path",
    "assertion_count": 5
  }'

trace link create item_test_reg_success_001 item_code_authservice_001 \
  --type tests \
  --metadata '{
    "function_under_test": "Register",
    "coverage_percentage": 85
  }'

# Test: Email Validation
trace item create proj_ecom_2024_001 \
  --type test \
  --title "Test: Invalid Email Format" \
  --test-type unit \
  --metadata '{
    "test_id": "TEST-AUTH-002",
    "test_type": "negative"
  }' \
  --content "$(cat <<'EOF'
func TestRegister_InvalidEmail(t *testing.T) {
    service := NewAuthService(mockRepo, mockEmail)

    invalidEmails := []string{
        "invalid",
        "invalid@",
        "@example.com",
        "invalid@.com",
        "invalid..double@example.com",
    }

    for _, email := range invalidEmails {
        req := RegisterRequest{
            Email:    email,
            Password: "SecurePass123!",
        }

        user, err := service.Register(context.Background(), req)

        assert.Error(t, err)
        assert.Nil(t, user)
        assert.Equal(t, ErrInvalidEmail, err)
    }
}
EOF
)"

# Output: item_test_email_validation_001

trace link create item_test_email_validation_001 item_req_registration_001 \
  --type verifies \
  --metadata '{"test_coverage": "email_validation"}'

# Integration Test
trace item create proj_ecom_2024_001 \
  --type test \
  --title "Test: Complete Registration Flow" \
  --test-type integration \
  --metadata '{
    "test_id": "TEST-AUTH-INT-001",
    "requires_database": true,
    "requires_email_mock": true,
    "execution_time": "1.2s"
  }' \
  --content "$(cat <<'EOF'
func TestRegistrationFlow_Integration(t *testing.T) {
    // Setup test database
    db := setupTestDB(t)
    defer db.Close()

    emailService := &MockEmailService{}
    service := NewAuthService(
        NewUserRepository(db),
        emailService,
    )

    // Step 1: Register user
    req := RegisterRequest{
        Email:    "integration@test.com",
        Password: "IntegrationTest123!",
    }

    emailService.On("SendVerificationEmail", mock.Anything).Return(nil)

    user, err := service.Register(context.Background(), req)
    require.NoError(t, err)
    require.NotNil(t, user)

    verificationToken := user.VerificationToken

    // Step 2: Attempt login before verification (should fail)
    _, err = service.Login(context.Background(), req.Email, req.Password)
    assert.Error(t, err)
    assert.Equal(t, ErrEmailNotVerified, err)

    // Step 3: Verify email
    err = service.VerifyEmail(context.Background(), verificationToken)
    assert.NoError(t, err)

    // Step 4: Login after verification (should succeed)
    token, err := service.Login(context.Background(), req.Email, req.Password)
    assert.NoError(t, err)
    assert.NotNil(t, token)
    assert.NotEmpty(t, token.AccessToken)
    assert.NotEmpty(t, token.RefreshToken)

    emailService.AssertExpectations(t)
}
EOF
)"

# Output: item_test_reg_flow_001

trace link create item_test_reg_flow_001 item_auth_feature_001 \
  --type verifies \
  --metadata '{
    "test_scope": "end_to_end",
    "covers_requirements": ["REQ-AUTH-001", "REQ-AUTH-002"]
  }'
```

## Step 7: Create Database Schema

```bash
# Database Migration
trace item create proj_ecom_2024_001 \
  --type database \
  --title "Users Table Schema" \
  --metadata '{
    "migration_version": "20241202_001",
    "database": "postgresql",
    "table": "users"
  }' \
  --content "$(cat <<'EOF'
-- Migration: 20241202_001_create_users_table.sql

CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email VARCHAR(255) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    verification_token VARCHAR(255),
    is_verified BOOLEAN DEFAULT FALSE,
    verified_at TIMESTAMP,
    reset_token VARCHAR(255),
    reset_token_expires_at TIMESTAMP,
    oauth_provider VARCHAR(50),
    oauth_provider_id VARCHAR(255),
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
    last_login_at TIMESTAMP,

    -- Indexes
    CONSTRAINT email_format CHECK (email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$')
);

CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_verification_token ON users(verification_token)
    WHERE verification_token IS NOT NULL;
CREATE INDEX idx_users_reset_token ON users(reset_token)
    WHERE reset_token IS NOT NULL;
CREATE INDEX idx_users_oauth ON users(oauth_provider, oauth_provider_id)
    WHERE oauth_provider IS NOT NULL;

-- Add updated_at trigger
CREATE TRIGGER update_users_updated_at
    BEFORE UPDATE ON users
    FOR EACH ROW
    EXECUTE FUNCTION update_updated_at_column();

COMMENT ON TABLE users IS 'User accounts with authentication details';
COMMENT ON COLUMN users.password_hash IS 'bcrypt hashed password (cost factor: 12)';
COMMENT ON COLUMN users.verification_token IS 'Email verification token (expires after 24h)';
EOF
)"

# Output: item_db_users_001

trace link create item_db_users_001 item_req_registration_001 \
  --type supports \
  --metadata '{"schema_element": "user storage"}'

trace link create item_code_userrepo_001 item_db_users_001 \
  --type depends_on \
  --metadata '{"dependency_type": "data_storage"}'
```

## Step 8: Create API Documentation

```bash
# API Endpoint
trace item create proj_ecom_2024_001 \
  --type api \
  --title "POST /api/v1/auth/register" \
  --metadata '{
    "method": "POST",
    "endpoint": "/api/v1/auth/register",
    "version": "v1",
    "authentication": "none"
  }' \
  --content "$(cat <<'EOF'
# POST /api/v1/auth/register

Register a new user account.

## Request

### Headers
```
Content-Type: application/json
```

### Body
```json
{
  "email": "user@example.com",
  "password": "SecurePass123!",
  "firstName": "John",
  "lastName": "Doe"
}
```

### Validation Rules
- email: Valid RFC 5322 format, max 255 characters
- password: Min 8 characters, 1 uppercase, 1 number, 1 special character
- firstName: Optional, max 100 characters
- lastName: Optional, max 100 characters

## Response

### Success (201 Created)
```json
{
  "success": true,
  "data": {
    "userId": "550e8400-e29b-41d4-a716-446655440000",
    "email": "user@example.com",
    "isVerified": false,
    "createdAt": "2024-12-02T10:00:00Z"
  },
  "message": "Registration successful. Please check your email for verification."
}
```

### Error Responses

#### 400 Bad Request - Invalid Email
```json
{
  "success": false,
  "error": {
    "code": "INVALID_EMAIL",
    "message": "Email format is invalid"
  }
}
```

#### 400 Bad Request - Weak Password
```json
{
  "success": false,
  "error": {
    "code": "WEAK_PASSWORD",
    "message": "Password must be at least 8 characters and contain uppercase, number, and special character"
  }
}
```

#### 409 Conflict - Email Exists
```json
{
  "success": false,
  "error": {
    "code": "EMAIL_EXISTS",
    "message": "An account with this email already exists"
  }
}
```

#### 429 Too Many Requests
```json
{
  "success": false,
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Too many registration attempts. Please try again in 5 minutes."
  }
}
```

## Rate Limiting
- 5 requests per minute per IP address
- 10 requests per hour per email address

## Security
- All requests must be over HTTPS
- Password is hashed with bcrypt (cost factor: 12)
- Verification email sent to provided address
EOF
)"

# Output: item_api_register_001

trace link create item_api_register_001 item_req_registration_001 \
  --type exposes \
  --metadata '{"api_layer": "REST"}'

trace link create item_api_register_001 item_code_authservice_001 \
  --type consumes \
  --metadata '{"handler_function": "RegisterHandler"}'
```

## Step 9: View Complete Traceability Matrix

```bash
# Get feature with all relationships
trace item get item_auth_feature_001 --show-links --depth 3

# Output:
# ┌─────────────────────────────────────────────────────────────────┐
# │ Feature: User Authentication System                             │
# │ ID: item_auth_feature_001                                       │
# │ Priority: 90 | Status: in_progress                              │
# └─────────────────────────────────────────────────────────────────┘
#
# Requirements (3):
#   ├─ REQ-AUTH-001: User Registration [child_of]
#   │  ├─ Implemented by: AuthService.go [implements]
#   │  ├─ Tested by: Test: User Registration Success [verifies]
#   │  ├─ Tested by: Test: Invalid Email Format [verifies]
#   │  ├─ Exposed by: POST /api/v1/auth/register [exposes]
#   │  └─ Supported by: Users Table Schema [supports]
#   │
#   ├─ REQ-AUTH-002: Email Verification [child_of]
#   │  ├─ Implemented by: AuthService.go [implements]
#   │  └─ Verified by: Test: Complete Registration Flow [verifies]
#   │
#   └─ REQ-AUTH-003: OAuth Integration [child_of]
#      └─ Implemented by: OAuthProvider.go [implements]
#
# Implementation (3 files):
#   ├─ AuthService.go
#   │  ├─ Depends on: UserRepository.go [depends_on]
#   │  ├─ Depends on: Users Table Schema [depends_on]
#   │  ├─ Tested by: Test: User Registration Success [tests]
#   │  └─ Consumed by: POST /api/v1/auth/register [consumes]
#   │
#   ├─ UserRepository.go
#   │  └─ Depends on: Users Table Schema [depends_on]
#   │
#   └─ OAuthProvider.go
#
# Test Coverage (3 tests):
#   ├─ Test: User Registration Success (PASSED)
#   ├─ Test: Invalid Email Format (PASSED)
#   └─ Test: Complete Registration Flow (PASSED)
#
# Coverage: 87% (Requirements: 100%, Code: 85%, Tests: 3/3)

# Generate traceability report
trace report generate proj_ecom_2024_001 \
  --type traceability-matrix \
  --filter "feature=item_auth_feature_001" \
  --format html \
  --output "auth_traceability_report.html"

# Generate test coverage report
trace report generate proj_ecom_2024_001 \
  --type test-coverage \
  --filter "feature=item_auth_feature_001" \
  --format markdown \
  --output "auth_test_coverage.md"
```

## Step 10: Track Progress and Metrics

```bash
# View feature progress
trace analytics query proj_ecom_2024_001 \
  --metric completion-rate \
  --filter "feature=item_auth_feature_001"

# Output:
# Feature Completion: 75%
# ├─ Requirements: 100% (3/3 defined)
# ├─ Design: 100% (1/1 completed)
# ├─ Implementation: 66% (2/3 files completed)
# ├─ Unit Tests: 100% (3/3 passed)
# ├─ Integration Tests: 100% (1/1 passed)
# └─ Documentation: 50% (1/2 completed)

# View test execution results
trace test results item_test_reg_flow_001

# Output:
# Test: Complete Registration Flow
# Status: PASSED
# Duration: 1.234s
# Assertions: 12/12 passed
# Coverage: 87% of AuthService.go
# Last Execution: 2024-12-02T14:30:00Z

# Check for orphaned code (code not linked to requirements)
trace validate proj_ecom_2024_001 \
  --rule orphaned-code \
  --report

# Check for untested requirements
trace validate proj_ecom_2024_001 \
  --rule untested-requirements \
  --report
```

## Summary

This workflow demonstrates:

1. **Hierarchical Tracing**: Feature → Requirements → Code → Tests → API
2. **Bidirectional Links**: Requirements trace down to implementation, tests trace up to requirements
3. **Multiple Link Types**: implements, verifies, depends_on, exposes, consumes, supports
4. **Real Code**: Actual Go implementation with proper error handling
5. **Comprehensive Testing**: Unit tests, integration tests, negative tests
6. **Complete Coverage**: Database schema, API documentation, test cases
7. **Validation**: Metrics, coverage analysis, orphan detection

## Files Created

- `/Users/kooshapari/temp-PRODVERCEL/485/kush/trace/docs-site/content/docs/01-wiki/03-examples/08-complete-feature-traceability/index.mdx`
