diff --git a/.gitignore b/.gitignore index 30c3f28..59d8c84 100644 --- a/.gitignore +++ b/.gitignore @@ -67,3 +67,6 @@ public/_next-video # scripts output files scripts/*-output.json scripts/*.log + +# specs archive (historical files not tracked) +specs/archive/ diff --git a/.windsurf/rules/project-standards.md b/.windsurf/rules/project-standards.md index 3befdc3..672d105 100644 --- a/.windsurf/rules/project-standards.md +++ b/.windsurf/rules/project-standards.md @@ -4,39 +4,66 @@ trigger: always_on # 8P3P LMS - Windsurf Project Rules -> **Consolidated project standards distilled from specifications** -> **Activation Mode**: Always On -> **File Limit**: 12000 characters (Windsurf requirement) - ---- - -- **Project**: EMDR therapist training LMS (Learning Management System) +- **Project**: EMDR therapist training LMS - **Stack**: Next.js 15, React 19, TypeScript 5.9, AWS Amplify Gen2, Tailwind v4, shadcn/ui - **Development Phase**: MVP feature completion (Phase 1) - **Testing Strategy**: Manual Q&A testing (no unit tests until post-MVP) ---- + + +## Protocol Execution Order (CRITICAL) + +**MANDATORY SEQUENCE** - Must be followed in exact order: + +### Step 1: Codebase Analysis Protocol (ALWAYS FIRST) + +- **Trigger**: ANY request involving files, components, or functionality +- **Required**: Complete existing implementation check before ANY recommendations +- **Blocker**: Cannot proceed to other protocols without completing this step + +### Step 2: Branch Readiness Protocol + +- **Trigger**: Creating new branches or starting development work +- **Required**: User confirmation before any branch creation +- **Depends on**: Step 1 completion + +### Step 3: Implementation + +- **Trigger**: After user approval from Step 2 +- **Required**: Follow all quality gates and standards +- **Depends on**: Steps 1 & 2 completion + +**VIOLATION CONSEQUENCES**: + +- Inaccurate recommendations (ignoring existing work) +- Wasted development time +- Loss of user trust in AI recommendations + ## Branch Readiness Protocol (MANDATORY) +**PREREQUISITE**: Codebase Analysis Protocol MUST be completed first. + Before starting ANY new feature: -1. **Present Branch Readiness Plan**: Show feature spec, branch strategy, stacked PR plan, timeline -2. **Get User Confirmation**: Ask "Ready to create the branch and start {feature_name} development? 🚀" -3. **Wait for Approval**: Do NOT create branches without explicit user confirmation -4. **Document Decision**: Record approval before proceeding +1. **Complete Codebase Analysis**: Verify existing implementations and acknowledge current state +2. **Present Branch Readiness Plan**: Show feature spec, branch strategy, stacked PR plan, timeline +3. **Get User Confirmation**: Ask "Ready to create the branch and start {feature_name} development? 🚀" +4. **Wait for Approval**: Do NOT create branches without explicit user confirmation +5. **Document Decision**: Record approval before proceeding + +**BLOCKER**: Cannot proceed without completing Step 1 (Codebase Analysis) ## LOC Verification (MANDATORY) Before every commit: ```bash -# Verify actual line count git diff --cached --shortstat git diff --cached --stat ``` @@ -54,10 +81,7 @@ git diff --cached --stat - **Stacked PRs**: For complex features, break into dependent PRs - **Commit Format**: Semantic commits (feat:, fix:, docs:, refactor:, etc.) - **Branch Strategy**: feature → dev → release/vX.Y.Z → main - - - ---- + @@ -108,21 +132,12 @@ export default function ClientComponent({ - **Prefer**: Server-side data fetching in Server Components - **Client-side**: Only when server-side isn't suitable (real-time updates, user interactions) - **Use**: ISR with `next: { revalidate: 3600 }` for cacheable data - - - ---- + ## Authentication Standards -### Required Imports - -```typescript -import { defineAuth, secret } from "@aws-amplify/backend"; -``` - ### Core Rules - **ALWAYS** import `secret` for auth configurations @@ -147,11 +162,7 @@ import { defineAuth, secret } from "@aws-amplify/backend"; ### Enums - Don't use `.required()` or `.defaultValue()` with enums -- Enums are type-safe by definition - - - ---- + @@ -161,62 +172,78 @@ import { defineAuth, secret } from "@aws-amplify/backend"; - **No config file needed**: Tailwind v4 uses CSS-first configuration - **Single import**: `@import "tailwindcss";` in globals.css -- **Theme customization**: Use `@theme` directive with CSS variables ### Stylesheet Structure (globals.css) -**Order matters**: - -1. `@import` statements first -2. `@theme` directive for Tailwind customization -3. CSS variables in `:root` and `.dark` -4. `@layer` directives last +**Order matters**: `@import` → `@theme` → CSS variables → `@layer` ### Base Layer Rules - **Use CSS variables directly** in `@layer base` - **Correct**: `background-color: var(--background);` - **Incorrect**: `@apply bg-background;` -- **Reason**: Tailwind v4 promotes CSS-first approach ### Component Standards - **Primary**: shadcn/ui components for all UI elements - **Custom Components**: Follow shadcn/ui patterns and composition - **Styling**: Tailwind utility classes only (no CSS Modules except auto-generated libraries) -- **Theme**: Use CSS variables for dynamic theming + - + ---- +## Codebase Analysis Protocol (MANDATORY - ALWAYS FIRST) - +**CRITICAL**: This protocol MUST be executed BEFORE any other protocols or recommendations. -## Codebase Analysis Protocol (MANDATORY) +### Trigger Conditions -Before ANY recommendations about files/components/functionality: +- User requests feature implementation +- User asks about existing functionality +- User mentions creating/modifying files +- User says "proceed with [feature]" +- ANY development-related request -### 1. Existing Implementation Check +### Required Analysis Steps + +**Step 1: Search Existing Implementations** ```bash -grep_search "functionName|ComponentName" # Check existing implementations -find_by_name "*feature*|*component*" # Find related files -grep_search "import.*ComponentName" # Check usage patterns +grep_search "featureName|ComponentName" +find_by_name "*feature*|*component*" +grep_search "import.*ComponentName" ``` -### 2. Duplication Prevention +**Step 2: Read Complete Context** + +- Read ALL related files completely (not partial) +- Understand existing architecture and patterns +- Identify what's already implemented vs what's missing + +**Step 3: Acknowledge Before Recommending** + +- **ALWAYS** acknowledge existing implementations first +- State completion percentage: "X is 85% complete, missing Y and Z" +- Build upon existing work rather than recreating + +### Enforcement Rules + +- **NEVER** present plans without completing analysis first +- **NEVER** assume files don't exist without searching +- **NEVER** ignore existing implementations in recommendations +- **ALWAYS** state "Following Codebase Analysis Protocol" when starting +- **ALWAYS** acknowledge existing work before suggesting new work -- **NEVER** suggest creating new files without checking existing implementations -- **NEVER** assume functionality doesn't exist without comprehensive searching -- **ALWAYS** build upon existing work rather than recreating it -- **ALWAYS** acknowledge existing implementations before suggesting changes +### Violation Prevention -### 3. Recommendation Protocol +**Before ANY recommendation, ask yourself**: -- **READ FIRST, RECOMMEND SECOND**: Scan existing codebase thoroughly -- **VERIFY ASSUMPTIONS**: Never assume something doesn't exist -- **ASK CLARIFYING QUESTIONS**: "I see you have X, are you looking to enhance it or replace it?" -- **ACKNOWLEDGE EXISTING WORK**: Recognize what's already implemented +1. ✅ Did I search for existing implementations? +2. ✅ Did I read the complete existing code? +3. ✅ Did I acknowledge what's already built? +4. ✅ Am I building upon existing work vs recreating? + +**If ANY answer is NO, STOP and complete the analysis first.** ## Quality Gates (Before Feature Completion) @@ -241,7 +268,6 @@ grep_search "import.*ComponentName" # Check usage patterns - **Variables/Functions**: camelCase - **Components/Types**: PascalCase -- **Unused Variables**: Prefix with `_` - **Files**: kebab-case for utilities, PascalCase for components ## Comment Standards @@ -251,14 +277,8 @@ grep_search "import.*ComponentName" # Check usage patterns ```typescript /** * Analyzes video content and calculates engagement time - * * @param content - Video URL and metadata - * @param userProfile - User's learning preferences * @returns Estimated completion time with confidence score - * - * @example - * const estimate = analyzeVideo('/videos/intro.mp4', userProfile); - * // Returns: { timeMinutes: 15, confidence: 0.85 } */ ``` @@ -267,19 +287,33 @@ grep_search "import.*ComponentName" # Check usage patterns - **WHY decisions**: Document reasoning behind non-obvious implementations - **Edge Cases**: Explain handling of special conditions - **Error Handling**: Document recovery strategies -- **Performance**: Note optimization reasons -### TODO Comments +## AI Accountability Standards -```typescript -// TODO: [#TICKET-123] High priority - Add error retry logic -// Context: Current implementation fails silently on network errors -// Timeline: Sprint 3 -``` +### Protocol Compliance Verification - +**Before presenting ANY plan or recommendation**: ---- +1. ✅ **State Protocol**: "Following Codebase Analysis Protocol..." +2. ✅ **Show Evidence**: Present search results and existing implementations found +3. ✅ **Acknowledge Work**: "I found X is already implemented, Y needs completion" +4. ✅ **Build Upon**: "Building upon existing work rather than recreating" +5. ✅ **Accurate Scope**: Present realistic LOC and timeline based on actual state + +### Trust Maintenance + +**User can rely on AI recommendations when**: + +- All protocols followed in correct sequence +- Existing work acknowledged and respected +- Plans based on actual codebase state, not assumptions + +**User should question AI recommendations when**: + +- Protocols skipped or reordered +- Existing implementations ignored +- Plans seem to recreate existing functionality + @@ -304,16 +338,7 @@ grep_search "ComponentName" src/components/ 1. **Reuse existing**: Extend or compose existing components 2. **shadcn/ui base**: Build on shadcn/ui components 3. **Create new**: Only when above options aren't suitable - -### 4. Composition Over Creation - -- Prefer composing multiple small components -- Document component composition in JSDoc headers -- Follow shadcn/ui patterns for consistency - - - ---- + @@ -329,12 +354,10 @@ grep_search "ComponentName" src/components/ ### Confirmation Process ``` -REQUIRED STEPS: 1. Present solution and changes made 2. Ask user to test the fix 3. Request explicit confirmation: "Can you confirm this issue is resolved?" 4. Wait for user verification -5. If not resolved, investigate further ``` ### RCA Documentation @@ -343,13 +366,8 @@ Create RCA document when: - Bug required significant investigation (>30 minutes) - Root cause was non-obvious -- Issue involves React/Next.js patterns not widely known - Multiple approaches were evaluated -- Debugging revealed important architecture insights - - - ---- + @@ -359,45 +377,19 @@ Create RCA document when: - **ALWAYS** ask clarifying questions before implementation - **NEVER** assume requirements without confirmation -- **DOCUMENT** all assumptions and decisions -- **VALIDATE** understanding before proceeding ### Question Categories -**Technical Architecture**: - -- Data structure and relationships -- User interaction flow -- Performance requirements -- Integration patterns -- Scalability considerations - -**Feature Specification**: - -- Exact functionality -- Edge case handling -- Validation rules -- Error handling approach -- Accessibility requirements - -**Implementation**: - -- Technology stack choices -- Component architecture -- State management approach -- Testing strategy -- Deployment approach +**Technical Architecture**: Data structure, user flow, performance, integration, scalability +**Feature Specification**: Functionality, edge cases, validation, error handling, accessibility +**Implementation**: Technology choices, component architecture, state management, testing, deployment ## MoSCoW Prioritization - **Must Have**: Critical features for MVP - **Should Have**: Important but not critical - **Could Have**: Nice to have features -- **Won't Have**: Out of scope for current iteration - - - ---- + @@ -408,14 +400,7 @@ Create RCA document when: - **No unit tests**: Deferred until post-MVP - **Focus**: Feature completion over test coverage - **Quality Gates**: ESLint, TypeScript, build validation only - -**Rationale**: Rapid iteration and feature completion for MVP delivery - -**Post-MVP**: Comprehensive automated testing suite will be implemented - - - ---- + @@ -424,12 +409,7 @@ Create RCA document when: - **Location**: Centralized in `src/lib/mock-data.ts` - **TypeScript**: Use proper interfaces for typed data - **Organization**: Group by feature -- **Structure**: Easy replacement for real APIs -- **Alternatives**: `src/data/`, `src/mocks/`, or `src/lib/data/` for larger projects - - - ---- + @@ -438,13 +418,5 @@ Create RCA document when: ### Tavus CVI Components - CSS Modules **Status**: Deferred to Post-MVP - **Issue**: Tavus CVI uses CSS modules; project uses Tailwind v4 + shadcn/ui - -**Impact**: Two styling systems in codebase - -**Action**: Post-MVP migration to Tailwind patterns - -**Priority**: Medium (after feature validation) - - +**Action**: Po diff --git a/specs/00-specification-framework.md b/specs/00-specification-framework.md deleted file mode 100644 index 8f20544..0000000 --- a/specs/00-specification-framework.md +++ /dev/null @@ -1,394 +0,0 @@ -# Specification Framework & Process - -## Overview - -This document outlines the systematic approach for gathering requirements, clarifying specifications, and managing iterative development with safe rollback points. - -## Core Principles - -### 1. Clarifying Questions First -- **ALWAYS** ask clarifying questions before implementation -- **NEVER** assume requirements without confirmation -- **DOCUMENT** all assumptions and decisions -- **VALIDATE** understanding before proceeding - -### 2. MoSCoW Prioritization -- **Must Have**: Critical features for MVP -- **Should Have**: Important but not critical -- **Could Have**: Nice to have features -- **Won't Have**: Out of scope for current iteration - -### 3. Safe Rollback Points -- **Checkpoint commits** after each major feature -- **Feature branches** for experimental work -- **Specification versioning** for requirement changes -- **Documentation snapshots** for decision history - -## Specification Process - -### Phase 1: Requirements Gathering -1. **Initial Requirements**: User provides high-level feature request -2. **Clarifying Questions**: Developer asks specific technical questions -3. **Requirement Confirmation**: User confirms understanding -4. **MoSCoW Classification**: Prioritize requirements - -### Phase 2: Specification Creation -1. **Project Specification**: High-level architecture and milestones -2. **Feature Specifications**: Detailed feature requirements -3. **Technical Specifications**: Implementation approach -4. **Acceptance Criteria**: Definition of done - -### Phase 3: Branch Readiness & Development Initiation -1. **Feature Planning**: Present branch readiness plan following release strategy -2. **User Confirmation**: Ask "Ready to create the branch and start {feature_name} development? 🚀" -3. **Branch Creation**: Only after user confirms, create feature branch -4. **Development Kickoff**: Begin implementation with established patterns - -### Phase 4: Iterative Development -1. **Implementation Planning**: Break down into tasks -2. **Development Cycles**: Short iterations with checkpoints -3. **Review & Feedback**: Regular validation with user -4. **Rollback Safety**: Maintain safe rollback points - -## Clarifying Questions Framework - -### Technical Architecture Questions -- **Data Structure**: How should data be organized and related? -- **User Experience**: What is the expected user interaction flow? -- **Performance**: What are the performance requirements? -- **Integration**: How should external services be integrated? -- **Scalability**: What are the future scaling considerations? - -### Feature Specification Questions -- **Functionality**: What exactly should this feature do? -- **Edge Cases**: How should edge cases be handled? -- **Validation**: What validation rules apply? -- **Error Handling**: How should errors be presented to users? -- **Accessibility**: What accessibility requirements exist? - -### Implementation Questions -- **Technology Stack**: Which technologies should be used? -- **Component Architecture**: How should components be structured? -- **State Management**: How should state be managed? -- **Testing Strategy**: What testing approach should be used? -- **Deployment**: How should the feature be deployed? - -## Documentation Standards - -### Project Specification Document -- **Executive Summary**: High-level project overview -- **Requirements**: Functional and non-functional requirements -- **Architecture**: System architecture and technology stack -- **Milestones**: Development phases and deliverables -- **Constraints**: Technical and business constraints - -### Feature Specification Documents -- **Feature Overview**: Purpose and goals -- **User Stories**: Detailed user interaction scenarios -- **Technical Requirements**: Implementation specifications -- **Acceptance Criteria**: Definition of done -- **Dependencies**: Related features and external dependencies - -### Decision Log -- **Decision**: What was decided -- **Context**: Why the decision was made -- **Alternatives**: What other options were considered -- **Consequences**: Impact of the decision -- **Date**: When the decision was made - -## Rollback Strategy - -### Checkpoint Management -- **Feature Checkpoints**: After each complete feature -- **Specification Checkpoints**: After requirement changes -- **Architecture Checkpoints**: After major architectural decisions -- **Integration Checkpoints**: After external service integrations - -### Rollback Triggers -- **Requirement Changes**: Major scope changes -- **Technical Issues**: Blocking technical problems -- **Performance Issues**: Unacceptable performance degradation -- **User Feedback**: Negative user experience feedback - -### Rollback Process -1. **Identify Issue**: Document the problem clearly -2. **Assess Impact**: Determine scope of rollback needed -3. **Execute Rollback**: Return to last safe checkpoint -4. **Update Specifications**: Revise requirements based on learnings -5. **Plan Forward**: Create new implementation approach - -## Collaboration Guidelines - -### Developer Responsibilities -- Ask clarifying questions proactively -- Document all assumptions and decisions -- Provide regular progress updates -- Maintain clean, rollback-safe code - -### User Responsibilities -- Provide clear, detailed requirements -- Respond to clarifying questions promptly -- Review and validate specifications -- Provide timely feedback on implementations - -### Shared Responsibilities -- Maintain open communication -- Document decisions and changes -- Respect rollback points and processes -- Focus on iterative improvement - -## Quality Assurance - -### Specification Quality -- **Completeness**: All requirements covered -- **Clarity**: Unambiguous specifications -- **Testability**: Clear acceptance criteria -- **Maintainability**: Easy to update and modify - -### Implementation Quality -- **Code Standards**: Follow established coding standards -- **Testing**: Comprehensive test coverage -- **Documentation**: Clear code and API documentation -- **Performance**: Meet performance requirements - -### Quality Gates (MANDATORY) - -#### Pre-Completion Validation -Before declaring any feature, component, or phase "complete", the following quality gates **MUST** be satisfied: - -##### Code Quality Gates -1. **ESLint Validation**: `npm run lint` must pass with **0 errors** - - All unused variables prefixed with underscore (`_`) - - No `any` types without justification - - All imports properly used - - Consistent code formatting - -2. **TypeScript Validation**: `npm run type-check` must pass for **production code** - - All production components and utilities must compile without errors - - Test files may have type issues if they don't block core functionality - - Strict mode compliance required - -3. **Build Verification**: `npm run build` must succeed - - All components must compile for production - - No build-breaking errors - - All imports and dependencies resolved - -##### Functional Quality Gates -4. **Core Functionality**: Primary use cases must work as specified - - Manual testing of main user flows - - Component renders without runtime errors - - All specified props and callbacks function correctly - -5. **Accessibility**: Basic accessibility requirements met - - Proper ARIA labels and roles - - Keyboard navigation support - - Screen reader compatibility - -##### Documentation Quality Gates -6. **Code Documentation**: All public APIs documented - - JSDoc headers for public functions and components - - Usage examples provided - - Edge cases and error handling documented - -7. **README Updates**: Documentation reflects new functionality - - New components listed in project structure - - Usage examples provided - - Installation/setup instructions updated if needed - -#### Definition of "Complete" -A feature/component/phase is **ONLY** considered complete when: -- ✅ All quality gates above are satisfied -- ✅ Acceptance criteria from specifications are met -- ✅ Code is ready for production deployment -- ✅ Documentation is updated and accurate - -#### Quality Gate Enforcement -- **Developers**: Must run quality checks before claiming completion -- **Code Reviews**: Reviewers must verify quality gates are met -- **CI/CD**: Automated checks prevent deployment of failing code -- **Rollback**: Features failing quality gates must be rolled back - -#### Quality Gate Exceptions -Exceptions to quality gates require: -- **Explicit documentation** of the issue and rationale -- **Approval** from Tech Lead or Lead Developer -- **Timeline** for resolution of the exception -- **Risk assessment** of deploying with known issues - -### Process Quality -- **Communication**: Clear, timely communication -- **Documentation**: Thorough documentation of decisions -- **Rollback Safety**: Maintain safe rollback points -- **Continuous Improvement**: Learn from each iteration -- **Quality First**: Never compromise quality gates for speed - -## Role-Based Permissions Framework - -### Permission Levels - -#### Current Phase (Solo/Small Team) -- **Lead Developer/Product Owner**: Full permissions (all actions) -- **CEO/Partner**: Specification review and approval rights -- **Contributors**: Development and PR creation rights - -#### Growth Phase (5-15 developers) -- **Tech Lead**: Architecture decisions, spec modifications, release management -- **Senior Developers**: PR approvals, feature spec creation, mentoring -- **Mid-Level Developers**: Feature development, junior developer PR reviews -- **Junior Developers**: Feature development under supervision -- **Product Owner**: Product specification management, feature prioritization - -#### Enterprise Phase (15+ developers) -- **Engineering Manager**: Team management, process oversight -- **Principal Engineer**: Architecture governance, technical standards -- **Staff Engineers**: Cross-team coordination, complex feature leadership -- **Domain Experts**: Specialized area ownership (security, performance, etc.) -- **QA Engineers**: Testing standards, quality gate management - -### Permission Matrix - -| Action | Current Lead | Tech Lead | Senior Dev | Mid Dev | Junior Dev | Product Owner | -|--------|--------------|-----------|------------|---------|------------|---------------| -| **Code & Development** | -| Create PRs | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | -| Approve PRs | ✅ | ✅ | ✅ | ✅* | ❌ | ❌ | -| Merge to main | ✅ | ✅ | ✅** | ❌ | ❌ | ❌ | -| Create releases | ✅ | ✅ | ✅** | ❌ | ❌ | ❌ | -| Deploy to production | ✅ | ✅ | ✅** | ❌ | ❌ | ❌ | -| **Specifications** | -| Modify project specs | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | -| Create feature specs | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | -| Approve spec changes | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | -| **Standards & Process** | -| Modify dev standards | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | -| Update CI/CD | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | -| Architecture decisions | ✅ | ✅ | ✅*** | ❌ | ❌ | ❌ | - -*Mid-level developers can approve junior developer PRs only -**Senior developers require tech lead approval for production actions -***Senior developers can propose architecture changes, not unilaterally decide - -### Adaptive Permissions - -#### Permission Evolution -As the team grows, permissions automatically adjust based on: -- **Experience Level**: Demonstrated competency in codebase -- **Domain Expertise**: Specialized knowledge areas -- **Leadership Responsibilities**: Team mentoring and coordination -- **Business Impact**: Scope of decision-making authority - -#### Permission Escalation -- **Technical Escalation**: Complex decisions → Tech Lead → Principal Engineer -- **Product Escalation**: Feature conflicts → Product Owner → CEO -- **Process Escalation**: Team conflicts → Engineering Manager -- **Emergency Escalation**: Production issues → On-call engineer → Tech Lead - -### Specification Change Management - -#### Change Categories -1. **Minor Changes**: Typos, clarifications, formatting - - **Who**: Any team member - - **Approval**: None required (direct commit) - - **Notification**: Git commit message - -2. **Feature Changes**: New features, requirement modifications - - **Who**: Senior+ developers, Product Owner - - **Approval**: Tech Lead + Product Owner - - **Notification**: Team announcement, changelog entry - -3. **Architecture Changes**: System design, technology stack - - **Who**: Tech Lead, Principal Engineer - - **Approval**: Architecture review board - - **Notification**: All-hands announcement, migration guide - -4. **Process Changes**: Development workflow, standards - - **Who**: Tech Lead, Engineering Manager - - **Approval**: Team consensus (voting) - - **Notification**: Process documentation update - -#### Change Approval Workflow -``` -Change Proposal → Impact Assessment → Stakeholder Review → Approval → Implementation → Communication -``` - -### Implementation Guidelines - -#### Current Implementation (Solo Phase) -- Document all decisions in specification files -- Use GitHub issues for change tracking -- Maintain changelog for major decisions -- Regular specification reviews (monthly) - -#### Growth Phase Implementation -- Implement GitHub branch protection rules -- Add required reviewers based on file paths -- Create specification review templates -- Establish regular architecture review meetings - -#### Enterprise Phase Implementation -- Formal RFC (Request for Comments) process -- Architecture Decision Records (ADRs) - -## Branch Readiness Protocol - -### Pre-Development Checklist -Before starting any new feature development, the following protocol must be followed: - -#### 1. Feature Planning Presentation -- **Specification Review**: Present completed feature specification -- **Branch Strategy**: Show branch naming following release strategy conventions -- **Stacked PR Plan**: Outline planned PR breakdown (200-400 LOC each) -- **Integration Points**: Identify dependencies on existing systems -- **Timeline Estimate**: Provide sprint-based development timeline - -#### 2. Branch Readiness Plan Template -```markdown -## 🌿 **{Feature Name} Branch Readiness Plan** - -### **Branch Strategy** -- **Branch Name**: `feature/{kebab-case-name}` -- **Base Branch**: `dev` -- **Expected Stacked PRs**: - 1. `feature/{name}/core-functionality` - 2. `feature/{name}/ui-components` - 3. `feature/{name}/integration-tests` - -### **Dependencies** -- **Internal**: List existing systems to integrate with -- **External**: Any new dependencies required -- **Blockers**: Any prerequisite work needed - -### **Success Criteria** -- **Functional**: Key features that must work -- **Technical**: Quality gates that must pass -- **Documentation**: Required docs and examples - -### **Timeline** -- **Sprint Length**: {1-4 weeks} -- **Milestones**: Key checkpoints and deliverables -- **Review Points**: When to seek user feedback -``` - -#### 3. User Confirmation Required -- **Mandatory Question**: "Ready to create the branch and start {feature_name} development? 🚀" -- **Wait for Explicit Confirmation**: Do not proceed without user approval -- **Document Confirmation**: Record user approval in development log - -#### 4. Branch Creation & Development Kickoff -- **Create Feature Branch**: Only after user confirmation -- **Initialize Directory Structure**: Set up required folders and files -- **Create Initial Specification Commit**: Commit feature spec as first commit -- **Begin Implementation**: Start with core functionality first - -### Benefits of This Protocol -- **Project Alignment**: Ensures user and developer are aligned before work begins -- **Resource Planning**: Clear understanding of scope and timeline -- **Risk Mitigation**: Identifies potential issues before development starts -- **Quality Assurance**: Maintains consistent development patterns -- **Documentation**: Creates clear development history and decision trail -- Automated permission enforcement -- Regular permission audits and updates - ---- - -**Next Steps**: Use this framework to create Project Specification and Feature Specification documents for the 8P3P LMS system. diff --git a/specs/01-development-standards.md b/specs/01-development-standards.md deleted file mode 100644 index 8c0ac0c..0000000 --- a/specs/01-development-standards.md +++ /dev/null @@ -1,484 +0,0 @@ -# Development Standards & Best Practices - -## Next.js 15+ Compliance (Highest Priority) - -### Server Components First Rule -- **DEFAULT**: Always start with Server Components (no "use client") -- **ONLY add "use client"** when you need: - - State management (useState, useReducer) - - Event handlers (onClick, onChange) - - Browser APIs (localStorage, window) - - React hooks that require client-side execution - -### Route Parameters Handling -- **Server Components**: Use `await params` directly -- **Client Components**: Use `useParams` hook from `@/hooks/use-params` -- **NEVER**: Use manual Promise unwrapping with `use()` in components - -### Code Quality Standards -- **MUST**: Run `npm run lint` before suggesting code -- **MUST**: Follow ESLint rules in `eslint.config.mjs` -- **MUST**: Use TypeScript strict mode -- **MUST**: Remove unused imports and variables -- **MUST**: Pass all quality gates before declaring features complete (see `specs/00-specification-framework.md#quality-gates`) - -### Codebase Analysis Protocol (MANDATORY) -Before making ANY recommendations about files, components, or functionality: - -#### 1. Existing Implementation Check -- **MUST**: Search for existing implementations: `grep_search "functionName|ComponentName"` -- **MUST**: Check component directories: `find_by_name "*component-name*|*feature-name*"` -- **MUST**: Read related files completely, not just snippets -- **MUST**: Verify actual usage patterns: `grep_search "import.*from.*filename"` - -#### 2. Duplication Prevention -- **NEVER**: Suggest creating new files without checking for existing implementations -- **NEVER**: Assume functionality doesn't exist without comprehensive searching -- **ALWAYS**: Build upon existing work rather than recreating it -- **ALWAYS**: Acknowledge existing implementations before suggesting changes - -#### 3. Recommendation Protocol -- **READ FIRST, RECOMMEND SECOND**: Always scan existing codebase thoroughly -- **VERIFY ASSUMPTIONS**: Never assume something doesn't exist without searching -- **ASK CLARIFYING QUESTIONS**: "I see you have X, are you looking to enhance it or replace it?" -- **ACKNOWLEDGE EXISTING WORK**: Recognize what's already implemented well - -#### 4. Standard Analysis Commands -```bash -# Before any file/component recommendations: -grep_search "ComponentName|functionName" # Check existing implementations -find_by_name "*feature*|*component*" # Find related files -grep_search "import.*ComponentName" # Check usage patterns -Read existing-file.tsx # Read complete implementations -``` - -**Violation Consequence**: If this protocol is not followed and results in duplicate work or incorrect assumptions, immediately acknowledge the error, provide corrected analysis, and explain the missed steps. - -### Quality Gate Compliance -Before any feature, component, or phase can be marked as "complete": -1. **ESLint**: `npm run lint` passes with 0 errors -2. **TypeScript**: `npm run type-check` passes for production code -3. **Build**: `npm run build` succeeds without errors -4. **Functionality**: Core use cases work as specified -5. **Documentation**: README and code docs updated - -**Reference**: See `specs/00-specification-framework.md` for complete quality gate requirements. - -### Branch Readiness Protocol (MANDATORY) -Before starting any new feature development: -1. **Present Branch Readiness Plan**: Show feature spec, branch strategy, and timeline -2. **Get User Confirmation**: Ask "Ready to create the branch and start {feature_name} development? 🚀" -3. **Wait for Approval**: Do NOT create branches or start development without explicit user confirmation -4. **Document Decision**: Record user approval and proceed with branch creation - -**Reference**: See `specs/00-specification-framework.md#branch-readiness-protocol` for complete protocol. - -## ESLint & TypeScript Rules - -### Core Principles -1. **Code Consistency**: Maintain consistent coding style across projects -2. **Type Safety**: Leverage TypeScript's type system for better code quality -3. **Performance**: Follow best practices for React and Next.js performance -4. **Maintainability**: Write clean, self-documenting code - -### Key ESLint Rules -- `@next/next/no-async-client-component`: Prevents async Client Components -- `@typescript-eslint/no-unused-vars`: Prevents unused variables (prefix with `_`) -- `@typescript-eslint/no-explicit-any`: Warns about `any` type usage -- `react-hooks/exhaustive-deps`: Warns about missing hook dependencies - -### Variable Naming Conventions -- Use descriptive variable names -- Prefix unused variables with underscore (`_`) -- Use camelCase for variables and functions -- Use PascalCase for components and types - -## Clean Code & Developer Experience (DX) - -### Comment Standards for Better DX -- **MUST**: Add comprehensive comments for better developer experience -- **MUST**: Document complex business logic and "why" decisions -- **MUST**: Include JSDoc headers for all public functions and components -- **MUST**: Explain edge cases and error handling approaches - -### Function Documentation Pattern -```typescript -/** - * Calculates estimated completion time for learning content - * - * Uses industry-standard reading speeds (225 WPM) and actual video duration - * to provide accurate time estimates for user planning and progress tracking. - * - * @param content - Content analysis data (word count, video duration, etc.) - * @param userProfile - User's historical learning data for personalization - * @returns Time estimate object with breakdown and confidence level - * - * @example - * const estimate = calculateEstimatedTime( - * { wordCount: 500, videoDuration: 300, complexity: 'medium' }, - * { readingSpeed: 250, completionRate: 0.85 } - * ); - * // Returns: { total: 8, reading: 2, video: 5, interaction: 1, confidence: 0.9 } - */ -export function calculateEstimatedTime( - content: ContentAnalysis, - userProfile: UserProfile -): TimeEstimate { - // Use personalized reading speed or fall back to industry average - // Research shows 225 WPM is optimal for technical content comprehension - const readingSpeed = userProfile.readingSpeed || 225; - - // Calculate base reading time in minutes - const readingTime = content.wordCount / readingSpeed; - - // Video time is exact - no estimation needed - const videoTime = content.videoDuration / 60; - - // Add interaction buffer based on content complexity - // Complex content requires 20-30% additional time for processing - const complexityMultiplier = { - low: 1.1, // 10% buffer for simple content - medium: 1.2, // 20% buffer for moderate complexity - high: 1.3 // 30% buffer for complex concepts - }; - - const interactionTime = (readingTime + videoTime) * - (complexityMultiplier[content.complexity] - 1); - - return { - reading: Math.round(readingTime), - video: Math.round(videoTime), - interaction: Math.round(interactionTime), - total: Math.round(readingTime + videoTime + interactionTime), - confidence: calculateConfidence(content, userProfile) - }; -} -``` - -### Component Documentation Pattern -```typescript -/** - * Reusable timer component for tracking user interactions with time limits - * - * Supports multiple variants (countdown, stopwatch, progress) and integrates - * with quiz systems, AI interactions, and content consumption tracking. - * - * @param duration - Timer duration in seconds - * @param onComplete - Callback fired when timer reaches zero or target - * @param onTick - Optional callback fired every second with remaining time - * @param variant - Visual and behavioral variant - * @param autoStart - Whether to start timer immediately on mount - * - * @example - * // Quiz timer with 4-minute limit - * - * - * @example - * // Content consumption tracking - * - */ -export function Timer({ - duration, - onComplete, - onTick, - variant = 'countdown', - autoStart = false -}: TimerProps) { - // Track current time state with 1-second precision - const [currentTime, setCurrentTime] = useState( - variant === 'countdown' ? duration : 0 - ); - - // Handle timer completion for all variants - useEffect(() => { - const isComplete = variant === 'countdown' - ? currentTime <= 0 - : currentTime >= duration; - - if (isComplete && onComplete) { - // Prevent multiple completion calls - onComplete(); - } - }, [currentTime, onComplete, variant, duration]); - - return ( -
- {/* Accessible time display with proper ARIA labels */} - -
- ); -} -``` - -### Business Logic Comments -```typescript -// BUSINESS RULE: Users must complete video + all sections before quiz unlock -// This ensures proper learning progression and prevents quiz attempts -// without consuming the prerequisite content -const isQuizUnlocked = (chapter: Chapter): boolean => { - // Video completion is optional for chapters (some are text-only) - const videoComplete = !chapter.videoUrl || chapter.videoCompleted; - - // All sections must be completed (this is mandatory) - const allSectionsComplete = chapter.sections.every( - section => section.completed - ); - - return videoComplete && allSectionsComplete; -}; - -// PERFORMANCE NOTE: This calculation runs on every render -// Consider memoizing if chapter data is large or changes frequently -const chapterProgress = useMemo(() => { - return calculateChapterProgress(chapter); -}, [chapter.sections, chapter.videoCompleted, chapter.quizPassed]); -``` - -### Error Handling Comments -```typescript -try { - const userSession = await fetchAuthSession(); - return userSession.tokens?.accessToken; -} catch (error) { - // EDGE CASE: Session might be expired or invalid - // Don't throw here - let components handle unauthenticated state gracefully - // This prevents auth errors from breaking the entire app - console.warn('Auth session fetch failed:', error); - return null; -} -``` - -### TODO Comments with Context -```typescript -// TODO: Implement adaptive time limits based on user performance -// Ticket: LMS-234 | Priority: Medium | Timeline: Sprint 3 -// Context: Users with higher completion rates could get extended time -// Research: 15% of users request more time on complex assessments -const getQuizTimeLimit = (quiz: Quiz, user: User): number => { - return quiz.defaultTimeLimit; // Currently using static time limits -}; -``` - -## Clarifying Questions Protocol - -### Requirements Gathering Process -1. **ALWAYS** ask clarifying questions before implementation -2. **NEVER** assume requirements without explicit confirmation -3. **DOCUMENT** all assumptions and decisions in specification files -4. **VALIDATE** understanding through detailed confirmation - -### Question Categories -- **Technical Architecture**: Data structure, component design, integration approach -- **User Experience**: Interaction flows, edge cases, error handling -- **Business Logic**: Rules, validation, constraints, performance requirements -- **Implementation**: Technology choices, testing strategy, deployment approach - -### MoSCoW Prioritization -- **Must Have**: Critical for MVP functionality -- **Should Have**: Important but not blocking -- **Could Have**: Nice-to-have features -- **Won't Have**: Out of scope for current iteration - -### Specification Documentation -- **Project Specification**: High-level architecture and milestones (see `specs/06-project-specification.md`) -- **Feature Specifications**: Detailed feature requirements (see `specs/features/`) -- **Decision Log**: Document all major decisions and rationale -- **Safe Rollback Points**: Maintain checkpoints for safe rollback - -## File Organization & Architecture - -### Separation of Concerns (SoC) -- **Data Layer**: `src/lib/*-data.ts` - Pure data only -- **Business Logic**: `src/lib/*-utils.ts` - Functions and calculations -- **Components**: UI logic only - -### File Path Requirements -1. **ALWAYS** mention which file path the user needs to paste code in -2. **IF** code spans multiple files, divide snippets and mention each file path -3. **IF** file doesn't exist, provide steps to generate the files -4. **COMMENT** every piece of code that improves code quality - -### Data Organization -- **Centralized Location**: `src/lib/mock-data.ts` - keeps all mock data in one place -- **Typed Data**: Export with proper TypeScript interfaces -- **Organized by Feature**: Group related data together -- **Easy to Replace**: When ready for real APIs, just change the import - -## Component Development - -### Component Reusability Protocol (MANDATORY) -**ALWAYS follow this sequence before creating new components:** - -1. **Scan Existing Components**: Search `src/components/` for similar functionality -2. **Evaluate Reusability**: Can existing components be extended or composed? -3. **Search shadcn/ui**: Use web search on https://ui.shadcn.com/docs/components for relevant base components -4. **Choose Approach**: - - **Reuse**: Extend existing component with additional props - - **Compose**: Combine multiple existing components - - **New**: Create new component using shadcn/ui as base - -### Component Creation Workflow -```typescript -// 1. Import existing components first -import { ExistingComponent } from "@/components/common/existing"; -import { Button } from "@/components/ui/button"; // shadcn/ui - -// 2. Compose or extend rather than recreate -export function NewComponent({ ...props }: NewComponentProps) { - return ( - - - - ); -} -``` - -### shadcn/ui Integration -- **Install Components**: `npx shadcn@latest add {component-name}` -- **Extend, Don't Modify**: Create wrapper components instead of modifying shadcn/ui directly -- **Consistent Theming**: Use Tailwind CSS v4 theme system for customization - -### Component Structure -- Use Server Components by default -- Only use Client Components when necessary (interactivity, browser APIs) -- Keep components focused on single responsibility -- Extract reusable logic into custom hooks -- **Document Reusability**: Include JSDoc comments about component composition - -### Performance Best Practices -- Memoize expensive calculations with `useMemo` -- Memoize callbacks with `useCallback` when passed as props -- Use proper dependency arrays in hooks -- Avoid unnecessary re-renders - -### Type Safety -- Avoid using `any` type -- Define proper interfaces and types -- Use type narrowing instead of type assertions -- Leverage TypeScript's utility types - -## Testing Standards - -### Jest Configuration (Next.js Official) - -**Reference**: [Next.js Testing with Jest](https://nextjs.org/docs/app/guides/testing/jest.md) - -Our testing setup follows Next.js official recommendations: - -#### Required Dependencies -```bash -npm install --save-dev jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom -``` - -#### Jest Configuration (`jest.config.mjs`) -```javascript -import nextJest from 'next/jest.js' - -const createJestConfig = nextJest({ - // Provide the path to your Next.js app to load next.config.js and .env files - dir: './', -}) - -// Add any custom config to be passed to Jest -const config = { - coverageProvider: 'v8', - testEnvironment: 'jsdom', - // Add more setup options before each test is run - setupFilesAfterEnv: ['/jest.setup.js'], -} - -// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async -export default createJestConfig(config) -``` - -#### Jest Setup (`jest.setup.js`) -```javascript -import '@testing-library/jest-dom' -``` - -### Testing Best Practices - -#### Component Testing -- **MUST**: Use React Testing Library for component tests -- **MUST**: Test user interactions, not implementation details -- **MUST**: Include accessibility testing (screen readers, keyboard navigation) -- **MUST**: Mock external dependencies and API calls - -#### Test Structure -- **MUST**: Follow AAA pattern (Arrange, Act, Assert) -- **MUST**: Use descriptive test names that explain the expected behavior -- **MUST**: Group related tests using `describe` blocks -- **MUST**: Clean up after tests (unmount components, clear mocks) - -#### Coverage Requirements -- **MINIMUM**: 80% coverage for new components and utilities -- **FOCUS**: Critical business logic and user interactions -- **EXCLUDE**: Configuration files, mock data, and type definitions - -## Development Workflow - -### Pre-commit Validation -```bash -npm run lint # ESLint checking -npm run lint:fix # Auto-fix issues -npm run lint:strict # Fail on warnings -npm run type-check # TypeScript validation -npm run test # Run Jest tests -npm run validate # Lint + type check + tests -``` - -### Build Process -- Lint and type check before building -- Run tests before committing -- Use pre-commit hooks for quality assurance -- Follow consistent Node.js version (20+) -- Cache dependencies for faster builds - -## Bug Resolution Protocol - -### Mandatory User Confirmation -- **REQUIRED**: All bug/issue resolutions must be confirmed by the user -- **PROCESS**: Present solution → User tests → Explicit confirmation required -- **NEVER**: Mark issues as resolved without user verification -- **REFERENCE**: See `specs/05-bug-resolution-workflow.md` for complete process - -### Resolution Documentation -- **MUST**: Create resolution ticket descriptions for all fixes -- **INCLUDE**: Root cause analysis, technical changes, verification steps -- **FORMAT**: Follow standard template in bug resolution workflow -- **PURPOSE**: Knowledge sharing and future reference - -## Documentation Maintenance - -### README.md Update Requirements -- **MANDATORY**: Update README.md for any changes that affect: - - **Workflow changes**: Development process, CI/CD pipeline, build steps - - **Architecture changes**: New patterns, component structure, data flow - - **Feature additions**: New functionality, components, or capabilities - - **Enhancement updates**: Performance improvements, UX changes, optimization - - **DevOps changes**: Deployment process, environment setup, infrastructure - - **Dependency changes**: New packages, version upgrades, tool changes - - **Configuration changes**: Environment variables, build settings, auth setup - -### Documentation Standards -- **IMMEDIATE**: Update README.md in the same PR/commit as the change -- **COMPREHENSIVE**: Include setup instructions, usage examples, troubleshooting -- **ACCURATE**: Verify all instructions work in clean environment -- **CURRENT**: Remove outdated information and broken links -- **ACCESSIBLE**: Use clear language and step-by-step instructions \ No newline at end of file diff --git a/specs/02-aws-amplify-backend.md b/specs/02-aws-amplify-backend.md deleted file mode 100644 index 6f0fa96..0000000 --- a/specs/02-aws-amplify-backend.md +++ /dev/null @@ -1,222 +0,0 @@ -# AWS Amplify Gen2 Backend Standards - -## Authentication Configuration - -### Core Authentication Rules -1. **ALWAYS** import `secret` for authentication-based configurations -2. **External Providers**: Only Google, Apple, Amazon, Facebook are supported -3. **Callback/Logout URLs**: Must be inside `externalProviders` object -4. **User Attributes**: Must be outside `loginWith` object -5. **Login Methods**: Only `email` and `phone` are supported (no `username`) - -### Required Imports -```typescript -import { defineAuth, secret } from "@aws-amplify/backend"; -``` - -### Authentication Structure -```typescript -export const auth = defineAuth({ - loginWith: { - email: true, - phone: true, - externalProviders: { - google: { - clientId: secret("GOOGLE_CLIENT_ID"), - clientSecret: secret("GOOGLE_CLIENT_SECRET"), - }, - signInWithApple: { - clientId: secret("SIWA_CLIENT_ID"), - keyId: secret("SIWA_KEY_ID"), - privateKey: secret("SIWA_PRIVATE_KEY"), - teamId: secret("SIWA_TEAM_ID"), - }, - callbackUrls: ["http://localhost:3000/profile"], - logoutUrls: ["http://localhost:3000/"], - }, - }, - userAttributes: { - email: { mutable: true, required: true }, - givenName: { mutable: true, required: true }, - "custom:organization": { - dataType: "String", - mutable: true, - minLen: 3, - maxLen: 100, - }, - }, - multifactor: { - mode: "OPTIONAL", - sms: true, - totp: false, - }, - accountRecovery: "EMAIL_AND_PHONE_WITHOUT_MFA", -}); -``` - -### Custom Attributes Rules -- **Standard Attributes**: `familyName`, `givenName`, `email`, `phoneNumber`, etc. -- **Custom Attributes**: Use `"custom:attributeName"` format -- **Required Field**: Always add `dataType` for custom attributes -- **No Required Field**: Custom attributes don't support `required: true` - -## Data Schema Design - -### Schema Design Rules (Source of Truth) -1. **Authorization**: Use `.guest()` instead of `.public()` (Gen2 only) -2. **Relationships**: `.belongsTo()` and `.hasMany()` always require related field ID -3. **Enums**: Don't use `.required()` or `.defaultValue()` with enums -4. **Permissions**: Use `.to()` for group permissions: `allow.guest().to(['read', 'write'])` - -### Relationship Patterns - -#### One-to-Many (hasMany/belongsTo) -```typescript -const schema = a.schema({ - Team: a.model({ - name: a.string().required(), - members: a.hasMany("Member", "teamId"), // Reference field required - }), - Member: a.model({ - name: a.string().required(), - teamId: a.id(), // Reference field - team: a.belongsTo("Team", "teamId"), // Must match reference field - }), -}); -``` - -#### One-to-One (hasOne/belongsTo) -```typescript -const schema = a.schema({ - Customer: a.model({ - name: a.string(), - activeCart: a.hasOne("Cart", "customerId"), - }), - Cart: a.model({ - items: a.string().array(), - customerId: a.id(), - customer: a.belongsTo("Customer", "customerId"), - }), -}); -``` - -#### Many-to-Many (Join Table) -```typescript -const schema = a.schema({ - PostTag: a.model({ - postId: a.id().required(), - tagId: a.id().required(), - post: a.belongsTo("Post", "postId"), - tag: a.belongsTo("Tag", "tagId"), - }), - Post: a.model({ - title: a.string(), - tags: a.hasMany("PostTag", "postId"), - }), - Tag: a.model({ - name: a.string(), - posts: a.hasMany("PostTag", "tagId"), - }), -}); -``` - -### Authorization Patterns -```typescript -// Correct authorization syntax -.authorization((allow) => [ - allow.owner(), - allow.guest().to(["read", "write", "delete"]) -]) - -// INCORRECT - Don't use this format -.authorization([allow => allow.owner(), allow => allow.guest().to(['read'])]) -``` - -### Data Operations - -#### Creating Relationships -```typescript -// One-to-Many -const { data: team } = await client.models.Team.create({ - name: "Frontend Team", -}); -const { data: member } = await client.models.Member.create({ - name: "John", - teamId: team.id, -}); -``` - -#### Lazy Loading -```typescript -const { data: team } = await client.models.Team.get({ id: "TEAM_ID" }); -const { data: members } = await team.members(); -``` - -#### Eager Loading -```typescript -const { data: teamWithMembers } = await client.models.Team.get( - { id: "TEAM_ID" }, - { selectionSet: ["id", "members.*"] } -); -``` - -### Schema Export Pattern -```typescript -import { type ClientSchema, a, defineData } from "@aws-amplify/backend"; - -const schema = a.schema({ - // Models here -}).authorization((allow) => [allow.guest()]); - -export type Schema = ClientSchema; - -export const data = defineData({ - schema, - authorizationModes: { - defaultAuthorizationMode: "apiKey", - apiKeyAuthorizationMode: { - expiresInDays: 30, - }, - }, -}); -``` - -## Deployment Configuration - -### Amplify.yml Structure -```yaml -version: 1 -backend: - phases: - build: - commands: - - nvm install 20 - - nvm use 20 - - npm ci --cache .npm --prefer-offline - - npx ampx generate outputs --app-id $AWS_APP_ID --branch $AWS_BRANCH --format json -frontend: - phases: - preBuild: - commands: - - nvm install 20 - - nvm use 20 - - npm ci --cache .npm --prefer-offline - build: - commands: - - npm run build - artifacts: - baseDirectory: .next - files: - - "**/*" - cache: - paths: - - .next/cache/**/* - - .npm/**/* - - node_modules/**/* -``` - -### Key Deployment Rules -- **Node.js Version**: Explicitly use Node.js 20+ in both backend and frontend -- **Backend Phase**: Required for Gen2 to generate `amplify_outputs.json` -- **Caching**: Include npm, Next.js, and node_modules for faster builds -- **Outputs Generation**: Use `ampx generate outputs` for proper config generation \ No newline at end of file diff --git a/specs/03-design-system-standards.md b/specs/03-design-system-standards.md deleted file mode 100644 index 9337c44..0000000 --- a/specs/03-design-system-standards.md +++ /dev/null @@ -1,383 +0,0 @@ -# Design System Standards: shadcn/ui + Tailwind CSS v4 - -## Architecture Overview - -Our design system is built on **shadcn/ui** components with **Tailwind CSS v4** for styling, following official best practices for maximum compatibility and developer experience. - -### Core Stack - -- **shadcn/ui**: Primary component library -- **Tailwind CSS v4**: Utility-first CSS framework (CSS-first configuration) -- **next-themes**: Theme management -- **CSS Variables**: Dynamic theming system - -## Configuration Standards - -### CSS-First Configuration (Tailwind v4) - -- **No config file needed**: Tailwind v4 uses CSS-first configuration -- **Single import**: Use `@import "tailwindcss";` in your main CSS file -- **Theme customization**: Use `@theme` directive with CSS variables -- **Layer organization**: Use `@layer base`, `@layer components`, `@layer utilities` - -### PostCSS Configuration - -```javascript -// postcss.config.mjs -const config = { - plugins: ["@tailwindcss/postcss"], // Tailwind v4 plugin -}; -``` - -### Stylesheet Structure and Order - -**Proper directive order in globals.css:** - -1. **@import statements** (must come first) - - ```css - @import url("https://fonts.googleapis.com/css2?family=Montserrat:wght@100;200;300;400;500;600;700;800&display=swap"); - @import "tailwindcss"; - ``` - -2. **@theme directive** (for Tailwind theme customization) - - ```css - @theme { - --color-primary: oklch(28.08% 0.051 260.2); - --color-accent: oklch(76.65% 0.139 91.06); - --font-display: "Montserrat", sans-serif; - } - ``` - -3. **CSS variables** (in :root and .dark) - - ```css - :root { - --background: oklch(100% 0 0); - --foreground: oklch(28.08% 0.051 260.2); - } - - .dark { - --background: oklch(28.08% 0.051 260.2); - --foreground: oklch(100% 0 0); - } - ``` - -4. **@layer directives** (in cascade order) - ```css - @layer base { - * { - border-color: var(--border); - } - body { - background-color: var(--background); - color: var(--foreground); - } - } - ``` - -### Base Layer Best Practices - -- **Use CSS variables directly** in `@layer base`, NOT `@apply` directives -- **Correct**: `background-color: var(--background);` -- **Incorrect**: `@apply bg-background;` -- **Reason**: Tailwind v4 promotes CSS-first approach with direct variable usage - -## Theme System - -### CSS Variables Convention - -Follow shadcn/ui's background/foreground convention: - -```css -:root { - --background: oklch(100% 0 0); - --foreground: oklch(28.08% 0.051 260.2); - --primary: oklch(28.08% 0.051 260.2); - --primary-foreground: oklch(100% 0 0); - --accent: oklch(76.65% 0.139 91.06); - --accent-foreground: oklch(28.08% 0.051 260.2); -} - -.dark { - --background: oklch(28.08% 0.051 260.2); - --foreground: oklch(100% 0 0); - /* ... other dark variants */ -} -``` - -### Theme Provider Setup - -```tsx -// components/theme-provider.tsx -"use client"; - -import * as React from "react"; -import { ThemeProvider as NextThemesProvider } from "next-themes"; - -export function ThemeProvider({ - children, - ...props -}: React.ComponentProps) { - return {children}; -} -``` - -```tsx -// app/layout.tsx -import { ThemeProvider } from "@/components/theme-provider"; - -export default function RootLayout({ - children, -}: { - children: React.ReactNode; -}) { - return ( - - - - {children} - - - - ); -} -``` - -## Component Standards - -### shadcn/ui Components First - -Always use shadcn/ui components as the foundation: - -```bash -# Add components -npx shadcn@latest add button -npx shadcn@latest add card -npx shadcn@latest add dialog -``` - -```tsx -import { Button } from "@/components/ui/button"; -import { Card, CardContent, CardHeader } from "@/components/ui/card"; -import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog"; - -// Preferred approach - - - ... - ... - -``` - -### Color Usage Standards - -**Use semantic color tokens**, not direct colors: - -```tsx -// ✅ Correct - semantic tokens -
- -``` - -## Best Practices - -### Theme Management - -- Always use `cssVariables: true` in `components.json` -- Use semantic color names (`primary`, `accent`, `muted`) -- Test both light and dark themes -- Use `suppressHydrationWarning` on `` tag - -### Component Development - -- Extend shadcn/ui components rather than creating from scratch -- Use `cn()` utility for conditional classes -- Follow shadcn/ui naming conventions -- Maintain consistent spacing with Tailwind scale - -### Performance - -- Leverage Tailwind's automatic purging in production builds -- Use semantic tokens to reduce CSS bundle size -- Minimize custom CSS in favor of utilities - -## Troubleshooting - -### Common Issues - -#### CSS Variables Not Working - -- **Check**: `cssVariables: true` in `components.json` -- **Verify**: ThemeProvider setup with `attribute="class"` - -#### Dark Mode Not Applying - -- **Check**: ThemeProvider configuration -- **Verify**: CSS variables defined in both `:root` and `.dark` - -#### Production Build Failures - -**Symptoms**: CSS variable errors in production builds - -**Solution**: Define theme colors in `@theme` directive: - -```css -@theme { - /* Core theme colors */ - --color-background: oklch(100% 0 0); - --color-foreground: oklch(28.08% 0.051 260.2); - --color-primary: oklch(28.08% 0.051 260.2); - /* Dark mode variants */ - --color-background-dark: oklch(28.08% 0.051 260.2); - --color-foreground-dark: oklch(100% 0 0); -} -``` - -Then reference in CSS custom properties: - -```css -:root { - --background: var(--color-background); - --foreground: var(--color-foreground); -} - -.dark { - --background: var(--color-background-dark); - --foreground: var(--color-foreground-dark); -} -``` - -## Development Workflow - -### Adding New Components - -1. **Check shadcn/ui first**: `npx shadcn@latest add [component]` -2. **Customize with Tailwind**: Add utility classes for layout/spacing -3. **Use semantic colors**: Apply theme-aware color tokens -4. **Test themes**: Verify component works in light/dark modes - -### Migration from Tailwind v3 - -- **Remove `tailwind.config.js`** - No longer needed in v4 -- Replace `@tailwind` directives with `@import "tailwindcss"` -- Update PostCSS config to use `@tailwindcss/postcss` -- Move theme configuration to CSS using `@theme` directive - -## Implementation Checklist - -- [ ] Uses proper shadcn/ui components as foundation -- [ ] Follows CSS-first configuration (no tailwind.config.js) -- [ ] Implements semantic color tokens -- [ ] Includes accessibility attributes -- [ ] Supports both light and dark themes -- [ ] Uses CSS variables directly in @layer base -- [ ] Tests keyboard navigation and focus states -- [ ] Validates production build compatibility - ---- - -**Remember**: shadcn/ui first, Tailwind v4 CSS-first configuration, semantic tokens always, no config file needed. diff --git a/specs/04-nextjs15-standards.md b/specs/04-nextjs15-standards.md deleted file mode 100644 index b00e62f..0000000 --- a/specs/04-nextjs15-standards.md +++ /dev/null @@ -1,453 +0,0 @@ -# Next.js 15 Development Standards - -## Core Architecture Principles - -### App Router First - -- **Default**: Use App Router architecture for all new projects -- **Server Components**: Default choice for better performance and SEO -- **Client Components**: Only when interactivity is required -- **File-based Routing**: Leverage `app/` directory structure - -### Component Strategy - -- **Server Components by default** - No "use client" unless needed -- **Client Components only for**: - - State management (useState, useReducer) - - Event handlers (onClick, onChange) - - Browser APIs (localStorage, window) - - React hooks requiring client-side execution - -## Route Parameters & Navigation - -### Server Components - -```tsx -// app/posts/[id]/page.tsx -export default async function PostPage({ - params, -}: { - params: Promise<{ id: string }>; -}) { - const { id } = await params; // Next.js 15+ requires await - return
Post {id}
; -} -``` - -### Client Components - -```tsx -// Use custom hook for client-side params -"use client"; -import { useParams } from "@/hooks/use-params"; - -export default function ClientComponent({ - params, -}: { - params: Promise<{ id: string }>; -}) { - const { id } = useParams(params); - return
Post {id}
; -} -``` - -### Navigation Patterns - -```tsx -// Prefer Link over useRouter for navigation -import Link from "next/link"; - -// ✅ Preferred - Server-friendly -Dashboard; - -// ✅ Client-side navigation when needed -("use client"); -import { useRouter } from "next/navigation"; -const router = useRouter(); -router.push("/dashboard"); -``` - -## Data Fetching Patterns - -### Server-Side Data Fetching - -```tsx -// app/posts/page.tsx - Server Component -async function getPosts() { - const res = await fetch("https://api.example.com/posts", { - next: { revalidate: 3600 }, // ISR with 1 hour cache - }); - return res.json(); -} - -export default async function PostsPage() { - const posts = await getPosts(); - return ( -
- {posts.map((post) => ( - - ))} -
- ); -} -``` - -### Client-Side Data Fetching - -```tsx -// Only when server-side isn't suitable -"use client"; -import { useEffect, useState } from "react"; - -export default function ClientDataComponent() { - const [data, setData] = useState(null); - - useEffect(() => { - fetch("/api/data") - .then((res) => res.json()) - .then(setData); - }, []); - - return
{data ? : }
; -} -``` - -## Server Actions - -### Form Handling - -```tsx -// app/contact/page.tsx -import { redirect } from "next/navigation"; - -async function submitContact(formData: FormData) { - "use server"; - - const name = formData.get("name") as string; - const email = formData.get("email") as string; - - // Process form data - await saveContact({ name, email }); - - redirect("/thank-you"); -} - -export default function ContactPage() { - return ( -
- - - -
- ); -} -``` - -### Progressive Enhancement - -```tsx -// Client component with Server Action -"use client"; -import { useFormStatus } from "react-dom"; - -function SubmitButton() { - const { pending } = useFormStatus(); - return ( - - ); -} -``` - -## Performance Optimization - -### Caching Strategies - -```tsx -// Static Generation -export default async function StaticPage() { - const data = await fetch("https://api.example.com/static-data"); - return
{/* Static content */}
; -} - -// Incremental Static Regeneration -async function getData() { - const res = await fetch("https://api.example.com/data", { - next: { revalidate: 60 }, // Revalidate every 60 seconds - }); - return res.json(); -} - -// Dynamic with caching -async function getCachedData() { - const res = await fetch("https://api.example.com/data", { - cache: "force-cache", // Cache indefinitely - }); - return res.json(); -} -``` - -### Loading States - -```tsx -// app/posts/loading.tsx - Automatic loading UI -export default function Loading() { - return
Loading posts...
; -} - -// app/posts/error.tsx - Error boundary -("use client"); -export default function Error({ - error, - reset, -}: { - error: Error & { digest?: string }; - reset: () => void; -}) { - return ( -
-

Something went wrong!

- -
- ); -} -``` - -## TypeScript Integration - -### Strict Type Safety - -```tsx -// Define proper interfaces -interface PageProps { - params: Promise<{ id: string }>; - searchParams: Promise<{ [key: string]: string | string[] | undefined }>; -} - -export default async function Page({ params, searchParams }: PageProps) { - const { id } = await params; - const search = await searchParams; - - return
Page {id}
; -} -``` - -### Component Props - -```tsx -interface ButtonProps extends React.ButtonHTMLAttributes { - variant?: "primary" | "secondary"; - size?: "sm" | "md" | "lg"; -} - -export function Button({ - variant = "primary", - size = "md", - ...props -}: ButtonProps) { - return ( - - ); -} -``` - -## File Organization - -### App Directory Structure - -``` -app/ -├── (auth)/ # Route groups -│ ├── login/ -│ └── register/ -├── dashboard/ -│ ├── page.tsx # Dashboard page -│ ├── loading.tsx # Loading UI -│ └── error.tsx # Error boundary -├── api/ # API routes -│ └── users/ -│ └── route.ts -├── globals.css # Global styles -└── layout.tsx # Root layout -``` - -### Component Organization - -``` -components/ -├── ui/ # shadcn/ui components -├── forms/ # Form components -├── layout/ # Layout components -└── features/ # Feature-specific components -``` - -## AI SDK v5 Integration - -### Streaming Responses - -```tsx -// app/api/chat/route.ts -import { openai } from "@ai-sdk/openai"; -import { streamText } from "ai"; - -export async function POST(req: Request) { - const { messages } = await req.json(); - - const result = await streamText({ - model: openai("gpt-4"), - messages, - }); - - return result.toDataStreamResponse(); -} -``` - -### Client-Side Integration - -```tsx -"use client"; -import { useChat } from "ai/react"; - -export default function ChatComponent() { - const { messages, input, handleInputChange, handleSubmit } = useChat(); - - return ( -
- {messages.map((m) => ( -
- {m.role}: {m.content} -
- ))} - -
- - -
-
- ); -} -``` - -## Development Workflow - -### Pre-commit Validation - -```bash -# Type checking -npm run type-check - -# Linting with Next.js 15 rules -npm run lint - -# Build verification -npm run build -``` - -### Environment Configuration - -```typescript -// next.config.ts -import type { NextConfig } from "next"; - -const nextConfig: NextConfig = { - experimental: { - typedRoutes: true, // Enable typed routes - }, - images: { - remotePatterns: [ - { - protocol: "https", - hostname: "example.com", - }, - ], - }, -}; - -export default nextConfig; -``` - -## Best Practices Checklist - -- [ ] Uses Server Components by default -- [ ] Implements proper route parameter handling -- [ ] Leverages Server Actions for form handling -- [ ] Includes proper TypeScript interfaces -- [ ] Implements accessibility features -- [ ] Uses early returns for readability -- [ ] Follows consistent naming conventions -- [ ] Includes proper error boundaries -- [ ] Implements loading states -- [ ] Uses Next.js 15 caching strategies - ---- - -**Remember**: Server Components first, Client Components only when needed, proper TypeScript, accessibility always. diff --git a/specs/05-bug-resolution-workflow.md b/specs/05-bug-resolution-workflow.md deleted file mode 100644 index 5486a57..0000000 --- a/specs/05-bug-resolution-workflow.md +++ /dev/null @@ -1,201 +0,0 @@ -# Bug Resolution Workflow Standards - -## Core Principles - -### 1. Systematic Issue Resolution -- **ALWAYS** provide comprehensive root cause analysis -- **NEVER** propose solutions without understanding the full problem scope -- **MUST** create resolution ticket descriptions for documentation -- **REQUIRED** user confirmation before marking issues as resolved - -### 2. Resolution Confirmation Protocol -- **MANDATORY**: Ask user to confirm issue is actually resolved -- **VERIFICATION**: User must test the solution in their environment -- **DOCUMENTATION**: Only mark as resolved after user confirmation -- **FOLLOW-UP**: Check if additional issues emerged from the fix - -## Bug Resolution Process - -### Phase 1: Issue Analysis -1. **Problem Identification** - - Read error messages/logs completely - - Identify all affected components/systems - - Determine scope of impact (local vs production) - -2. **Root Cause Investigation** - - Trace the issue to its source - - Identify contributing factors - - Check for related configuration issues - - Review recent changes that might have caused the problem - -3. **Impact Assessment** - - Determine severity (critical, high, medium, low) - - Identify affected users/functionality - - Assess potential side effects of fixes - -### Phase 2: Solution Development -1. **Solution Design** - - Propose targeted fixes addressing root causes - - Consider multiple solution approaches - - Evaluate potential side effects - - Plan rollback strategy if needed - -2. **Implementation** - - Apply fixes systematically - - Test changes in development environment - - Verify no new issues are introduced - - Document all changes made - -3. **Validation** - - Run comprehensive tests (lint, type-check, build) - - Verify fix addresses original problem - - Check for regression issues - - Test in production-like environment - -### Phase 3: Documentation & Confirmation -1. **Resolution Documentation** - - Create detailed resolution ticket description - - Include root cause analysis - - Document all changes made - - Provide prevention measures - -2. **User Confirmation Protocol** - ``` - REQUIRED CONFIRMATION PROCESS: - - 1. Present solution and changes made - 2. Ask user to test the fix in their environment - 3. Request explicit confirmation: "Can you confirm this issue is resolved?" - 4. Wait for user verification before marking as complete - 5. If not resolved, investigate further - ``` - -3. **Follow-up** - - Monitor for related issues - - Update documentation if needed - - Share learnings with team - -## Resolution Ticket Template - -### Standard Format -```markdown -## 🐛 Bug Resolution: [Issue Title] - -### Issue Summary -[Brief description of the problem] - -### Root Cause Analysis -**Primary Issues Identified:** -1. [Root cause 1 with explanation] -2. [Root cause 2 with explanation] -3. [Additional causes if applicable] - -### Resolution Steps -**[Category] Fixes:** -- [Specific change 1] -- [Specific change 2] -- [Configuration updates] - -### Technical Changes Made -**File: [filename]** -- ✅ [Change description] -- ✅ [Another change] - -### Verification Steps -- [x] [Test 1 passed] -- [x] [Test 2 passed] -- [x] [Build verification] - -### Impact -- **Before**: [Problem description] -- **After**: [Resolution result] -- **Performance**: [Any performance impact] - -### Prevention Measures -- [How to prevent this issue in future] -- [Process improvements] -- [Documentation updates] - ---- -**Status:** ✅ **RESOLVED** (pending user confirmation) -``` - -## User Confirmation Requirements - -### Mandatory Confirmation Process -1. **Present Solution** - - Explain what was fixed and how - - Provide clear testing instructions - - Share any relevant code changes - -2. **Request Testing** - - Ask user to test in their environment - - Provide specific test scenarios - - Request feedback on solution effectiveness - -3. **Explicit Confirmation** - - Use clear language: "Can you confirm this issue is resolved?" - - Wait for explicit "yes" or "confirmed" response - - Do not assume silence means acceptance - -4. **Handle Incomplete Resolution** - - If issue persists, investigate further - - Ask for additional details about remaining problems - - Iterate on solution until fully resolved - -### Confirmation Language Examples - -**✅ CORRECT:** -- "Can you confirm this issue is resolved?" -- "Please test the fix and let me know if the problem is solved" -- "Has this resolved the issue you were experiencing?" - -**❌ INCORRECT:** -- "This should fix the issue" (no confirmation request) -- "The problem is resolved" (assumes without verification) -- "Let me know if you have other issues" (doesn't confirm current issue) - -## Quality Assurance - -### Pre-Resolution Checklist -- [ ] Root cause fully identified -- [ ] Solution addresses all aspects of the problem -- [ ] No new issues introduced -- [ ] All tests pass (lint, type-check, build) -- [ ] Documentation updated -- [ ] Resolution ticket created - -### Post-Resolution Checklist -- [ ] User has tested the solution -- [ ] User has explicitly confirmed resolution -- [ ] No related issues reported -- [ ] Documentation is complete -- [ ] Prevention measures documented - -## Escalation Process - -### When to Escalate -- Issue cannot be reproduced -- Solution attempts fail repeatedly -- User reports solution doesn't work after multiple iterations -- Issue affects critical production systems - -### Escalation Steps -1. Document all attempted solutions -2. Gather additional diagnostic information -3. Request pair programming/review session -4. Consider architectural review if needed - -## Continuous Improvement - -### Learning from Issues -- Document common issue patterns -- Update prevention guidelines -- Improve development standards -- Enhance testing procedures - -### Process Refinement -- Regular review of resolution effectiveness -- Update workflow based on lessons learned -- Improve confirmation protocols -- Enhance documentation standards diff --git a/specs/06-project-specification.md b/specs/06-project-specification.md deleted file mode 100644 index 0e40892..0000000 --- a/specs/06-project-specification.md +++ /dev/null @@ -1,274 +0,0 @@ -# 8P3P LMS Project Specification - -## Executive Summary - -The 8P3P Learning Management System is a production-ready platform for EMDR therapist training, built with Next.js 15, AWS Amplify Gen2, and modern web technologies. The system provides structured learning paths with video content, interactive assessments, and AI-powered learning assistance. - -## Project Requirements - -### Functional Requirements - -#### Must Have (MVP) -- ✅ **User Authentication**: Multi-layer security with Google OAuth -- ✅ **Course Management**: Hierarchical content structure (Course → Chapters → Sections) - - **Course**: Top-level container with metadata and progress tracking - - **Chapter**: Logical grouping of related learning content - - **Section**: Individual learning objects (video, quiz, AI interaction, etc.) -- ✅ **Video Learning**: Video content with progress tracking -- ✅ **Assessment System**: Quizzes with retry logic and randomization -- 🔄 **AI Learning Assistance**: Tavus AI integration for questions and learning checks -- 🔄 **Progress Tracking**: Individual, chapter, and course-level progress -- 🔄 **Time Estimation**: Accurate completion time calculations -- 🔄 **Timer Components**: Reusable timing functionality - -#### Should Have -- **Advanced Analytics**: Learning progress and performance insights -- **Mobile Optimization**: Enhanced mobile learning experience -- **Offline Support**: Content caching for offline access -- **Social Learning**: Discussion forums and peer interaction - -#### Could Have -- **Gamification**: Badges, achievements, and leaderboards -- **Advanced AI**: Personalized learning recommendations -- **Multi-language**: Internationalization support -- **Advanced Video**: Interactive video features and annotations - -#### Won't Have (Current Iteration) -- **Live Streaming**: Real-time video sessions -- **Payment Processing**: Subscription and payment management -- **Advanced Reporting**: Complex analytics dashboards -- **Third-party Integrations**: LTI or SCORM compliance - -### Non-Functional Requirements - -#### Performance -- **Page Load**: < 3 seconds initial load -- **Video Streaming**: < 2 seconds start time -- **API Response**: < 500ms average response time -- **Mobile Performance**: 90+ Lighthouse score - -#### Scalability -- **Concurrent Users**: Support 1000+ simultaneous users -- **Content Volume**: Handle 100+ courses with 1000+ sections -- **Storage**: Scalable video and content storage -- **Database**: Efficient query performance at scale - -#### Security -- **Authentication**: Multi-factor authentication support -- **Data Protection**: GDPR and HIPAA compliance considerations -- **API Security**: Rate limiting and input validation -- **Content Security**: Secure video streaming and content protection - -#### Accessibility -- **WCAG Compliance**: AA level accessibility standards -- **Screen Reader**: Full screen reader support -- **Keyboard Navigation**: Complete keyboard accessibility -- **Color Contrast**: High contrast mode support - -## System Architecture - -### Technology Stack -- **Frontend**: Next.js 15 with App Router, React 19, TypeScript 5.9 -- **Styling**: Tailwind CSS v4, shadcn/ui components -- **Backend**: AWS Amplify Gen2 with GraphQL API -- **Database**: DynamoDB (via Amplify) with hot-swappable DAL -- **AI Integration**: Tavus AI for conversational features -- **Deployment**: AWS Amplify Hosting with CI/CD - -### Data Structure - -#### Core Entities -```typescript -Course -├── id: string -├── title: string -├── description: string -├── chapters: Chapter[] -├── progress: number (0-100) -├── completedChapters: string[] -├── lastViewedChapter?: string -├── imageUrl?: string -└── duration?: string - -Chapter -├── id: string -├── title: string -└── sections: Section[] - -Section -├── id: string -├── title: string -├── learningObjective: string -├── videoScript: string -├── videoUrl?: string -├── estimatedDuration?: number (seconds) -├── quiz?: Quiz -├── sectionType?: "video" | "ai_avatar" | "quiz" -├── completed?: boolean -├── videoCompleted?: boolean -├── quizPassed?: boolean -└── questionAskedCount?: number - -Quiz -├── id: string -├── title: string -├── description: string -├── questions: QuizQuestion[] -└── passingScore: number -``` - -### MVP Time Estimation & Progress System - -#### Simple Time Estimation Formula -```typescript -// Simplified calculation for MVP -totalTime = videoTime + quizTime + learningCheckTime - -Where: -- videoTime = sum of all video durations (or 8 minutes default) -- quizTime = (5 minutes * 3 attempts) per quiz -- learningCheckTime = (2 minutes * 2 attempts) per chapter -``` - -#### Simple Progress Calculation -```typescript -// Two approaches for MVP: -// 1. Time-based: progress = (timeSpent / totalTime) * 100 -// 2. Chapter-based: progress = (completedChapters / totalChapters) * 100 -``` - -#### Timer Component Usage -- **Quiz Timer**: Countdown timer for quiz attempts -- **Question Timer**: Individual question time limits -- **Learning Check Timer**: Time limits for learning activities -- Uses shadcn countdown hook for reliability - -### MVP Testing Strategy - -#### Primary Testing Approach: Q&A Testing -- **Manual Testing**: Focus on user workflows and feature validation -- **Q&A Sessions**: Regular testing sessions to validate core functionality -- **Bug Tracking**: Simple issue tracking for quick fixes -- **User Acceptance**: Validate features meet MVP requirements - -#### Post-MVP Testing Enhancement -- **Unit Tests**: Comprehensive test suite after feature complete -- **Integration Tests**: Component interaction testing -- **E2E Tests**: Full user journey validation -- **Performance Tests**: Load and stress testing - -#### Current MVP Focus -- ✅ **Feature Complete**: Priority over test coverage -- ✅ **Q&A Validation**: Manual testing of core flows -- ✅ **Quick Iterations**: Fast feedback and fixes -- 🔄 **Post-MVP**: Comprehensive automated testing - -### Component Architecture -``` -src/ -├── app/ # Next.js App Router -├── components/ -│ ├── ui/ # shadcn/ui base components -│ ├── course/ # Course-specific components -│ ├── common/ # Reusable components (Timer, etc.) -│ └── ai/ # AI integration components -├── lib/ -│ ├── data/ # Hot-swappable data layer -│ ├── ai/ # AI service integrations -│ ├── utils/ # Utility functions -│ └── types/ # TypeScript definitions -└── hooks/ # Custom React hooks -``` - -## Development Milestones - -### Phase 1: Content Hierarchy Update (Current) -**Timeline**: 1-2 weeks -**Deliverables**: -- ✅ Updated content structure (Chapters ↔ Sections naming flip) -- 🔄 Enhanced progress tracking system -- 🔄 Estimated time calculation components -- 🔄 Updated mock data and TypeScript interfaces - -### Phase 2: AI Integration -**Timeline**: 2-3 weeks -**Deliverables**: -- Tavus AI integration for "Ask Question" feature -- AI-powered Learning Check system -- Timer components for all timed interactions -- Conversation logging and analysis - -### Phase 3: Enhanced Assessment System -**Timeline**: 2-3 weeks -**Deliverables**: -- Quiz retry logic with attempt limits -- Question randomization system -- Advanced progress analytics -- Completion requirement enforcement - -### Phase 4: Performance & Polish -**Timeline**: 1-2 weeks -**Deliverables**: -- Performance optimization -- Mobile experience enhancements -- Accessibility improvements -- Production deployment optimization - -## Technical Constraints - -### Development Standards -- **Next.js 15+ Compliance**: Server Components first approach -- **TypeScript Strict Mode**: Full type safety enforcement -- **ESLint v9**: Strict code quality standards -- **Tailwind CSS v4**: CSS-first configuration approach -- **AWS Amplify Gen2**: Modern backend architecture - -### Integration Constraints -- **Tavus AI**: API rate limits and response time considerations -- **Video Streaming**: Bandwidth and storage optimization -- **Mobile Performance**: Limited processing power and network -- **Accessibility**: Screen reader and keyboard navigation support - -### Business Constraints -- **EMDR Training Focus**: Specialized content and requirements -- **Professional Audience**: High-quality, reliable experience expected -- **Compliance**: Healthcare industry standards and regulations -- **Scalability**: Growth from pilot to full deployment - -## Risk Assessment - -### Technical Risks -- **AI Integration Complexity**: Tavus API integration challenges -- **Video Performance**: Large video file streaming optimization -- **Mobile Compatibility**: Cross-device experience consistency -- **Data Migration**: Hot-swappable DAL implementation complexity - -### Mitigation Strategies -- **Incremental Integration**: Phase AI features gradually -- **Performance Testing**: Regular performance monitoring and optimization -- **Cross-device Testing**: Comprehensive device and browser testing -- **Abstraction Layers**: Clean interfaces for data layer swapping - -## Success Criteria - -### User Experience -- **Completion Rates**: 80%+ course completion rate -- **User Satisfaction**: 4.5+ star rating -- **Performance**: < 3 second page load times -- **Accessibility**: 100% keyboard navigation support - -### Technical Performance -- **Uptime**: 99.9% availability -- **Response Time**: < 500ms API responses -- **Error Rate**: < 0.1% error rate -- **Security**: Zero security incidents - -### Business Impact -- **User Engagement**: 70%+ weekly active users -- **Content Consumption**: 90%+ video completion rates -- **Assessment Performance**: 85%+ quiz pass rates -- **Support Efficiency**: < 2% support ticket rate - ---- - -**Next Steps**: Create detailed Feature Specification documents for each major feature area. diff --git a/specs/07-release-strategy.md b/specs/07-release-strategy.md deleted file mode 100644 index cf21640..0000000 --- a/specs/07-release-strategy.md +++ /dev/null @@ -1,328 +0,0 @@ -# Release Strategy & Sprint Management - -## Overview - -This document outlines the release strategy for the 8P3P LMS project, including sprint-based development cycles, release types, and clear contributing guidelines for development teams. - -## Sprint-Based Release Cycle - -### Configurable Sprint Length - -**Default**: 2-week sprints (configurable per project/team needs) - -**Supported Sprint Lengths**: -- **1 Week**: Fast-moving features, small team -- **2 Weeks**: Balanced development and review time (recommended) -- **3 Weeks**: Complex features requiring extended development -- **4 Weeks**: Major releases or complex integrations - -### Sprint Planning Process - -#### Sprint Structure -``` -Sprint Planning → Development → Code Review → Testing → Release → Retrospective - ↓ ↓ ↓ ↓ ↓ ↓ - Day 1 Days 2-8 Days 9-10 Day 11 Day 12 Days 13-14 -``` - -#### Sprint Goals -- **Feature Completion**: All planned features fully implemented and tested -- **Quality Assurance**: All code reviewed and meets quality standards -- **Documentation**: Updated specs and documentation -- **Deployment Ready**: Code ready for production deployment - -## Release Types & Branching Strategy - -### Branch Structure -``` -main (production) -├── release/v1.2.0 (major releases) -├── dev (development integration) -│ ├── feature/timer-01-core -│ ├── feature/timer-02-variants -│ └── feature/auth-improvements -└── hotfix/critical-bug-fix (emergency fixes) -``` - -### Release Types - -#### 1. Feature Releases (Sprint-based) -**Branch Flow**: `feature → dev → release/vX.Y.0 → main` -**Timeline**: End of each sprint -**Process**: -1. Feature branches merge to `dev` throughout sprint -2. Create `release/vX.Y.0` branch from `dev` at sprint end -3. Final testing and bug fixes in release branch -4. Merge release branch to `main` and tag version -5. Deploy to production - -#### 2. Hotfixes (Emergency) -**Branch Flow**: `hotfix → main` (direct) -**Timeline**: As needed for critical issues -**Process**: -1. Create `hotfix/issue-description` from `main` -2. Implement fix with minimal changes -3. Test thoroughly (automated + manual) -4. Direct merge to `main` with immediate deployment -5. Cherry-pick to `dev` to keep branches in sync - -#### 3. Major Releases (Quarterly) -**Branch Flow**: `dev → release/vX.0.0 → main` -**Timeline**: Every 3-4 sprints or major milestone -**Process**: -1. Feature freeze in `dev` branch -2. Create `release/vX.0.0` for stabilization -3. Extended testing period (1-2 weeks) -4. Documentation updates and migration guides -5. Staged deployment with rollback plan - -## Semantic Versioning - -### Version Format: `MAJOR.MINOR.PATCH` - -#### Version Increment Rules -- **MAJOR** (X.0.0): Breaking changes, major architecture updates -- **MINOR** (0.X.0): New features, backward-compatible changes -- **PATCH** (0.0.X): Bug fixes, security patches, hotfixes - -#### Examples -``` -1.0.0 → 1.0.1 (hotfix: quiz timer bug) -1.0.1 → 1.1.0 (feature: AI integration) -1.1.0 → 2.0.0 (breaking: new authentication system) -``` - -#### Pre-release Versions -- **Alpha**: `1.2.0-alpha.1` (internal testing) -- **Beta**: `1.2.0-beta.1` (limited user testing) -- **Release Candidate**: `1.2.0-rc.1` (final testing before release) - -## Contributing Guidelines - -### Development Workflow - -#### 1. Sprint Planning -- Review project specifications and feature requirements -- Break down features into PR-sized tasks (200-400 LOC) -- Assign tasks and set sprint goals -- Create feature branches from `dev` - -#### 2. Feature Development -```bash -# Create feature branch -git checkout dev -git pull origin dev -git checkout -b feature/timer-01-core - -# Development cycle -git add . -git commit -m "feat: implement core timer component" -git push origin feature/timer-01-core - -# Create PR to dev branch -``` - -#### 3. Code Review Process -- **PR Size**: 200-400 lines of code maximum -- **Single Purpose**: One feature/fix per PR -- **Review Requirements**: 1-2 reviewers minimum -- **Automated Checks**: Lint + tests must pass -- **Documentation**: Update relevant specs and README - -##### LOC Verification (MANDATORY) - -**Before every commit**, verify actual line count using: - -```bash -# Check staged changes line count -git diff --cached --shortstat - -# Detailed breakdown by file -git diff --cached --stat -``` - -**Rules**: -- **MUST** verify actual LOC before committing -- **NEVER** estimate or assume LOC without verification -- **ALWAYS** report actual numbers in commit messages -- **EXCEPTION**: Auto-generated library files (document in commit message) - -**Example Output**: -``` -23 files changed, 1712 insertions(+), 41 deletions(-) -``` - -**Documentation Required**: -- If LOC exceeds target (200-400), document why in commit message -- Separate auto-generated code from manual code in explanation -- Provide breakdown: "Manual: 450 LOC, Auto-generated: 900 LOC" - -#### 4. Stacked PRs (for dependent features) -```bash -# PR #1: Core timer component -feature/timer-01-core → dev - -# PR #2: Timer variants (depends on #1) -feature/timer-02-variants → feature/timer-01-core - -# When PR #1 merges, PR #2 automatically updates to target dev -``` - -**Stacked PR Guidelines**: -- **Clear Dependencies**: Document which PRs depend on others -- **Dependency Notes**: Include dependency information in PR description -- **Sequential Merging**: Merge dependencies first, then dependent PRs -- **Conflict Resolution**: Rebase dependent PRs when base PR merges - -### Quality Standards - -#### Pre-commit Requirements -```bash -# Required checks before PR submission -npm run lint # ESLint validation -npm run type-check # TypeScript validation -npm run test # Unit test execution -npm run pre-commit # Combined validation script -``` - -#### PR Review Checklist -- [ ] **Code Quality**: Follows established coding standards -- [ ] **Testing**: Includes appropriate unit/integration tests -- [ ] **Documentation**: Updates specs, README, or comments as needed -- [ ] **Performance**: No significant performance regressions -- [ ] **Accessibility**: Maintains WCAG compliance -- [ ] **Security**: No security vulnerabilities introduced -- [ ] **Breaking Changes**: Documented and versioned appropriately - -### Clean Code & Comments Standards - -#### Comment Guidelines -```typescript -/** - * Timer component for tracking user interactions with time limits - * - * @param duration - Timer duration in seconds - * @param onComplete - Callback fired when timer reaches zero - * @param variant - Visual style: 'countdown' | 'stopwatch' | 'progress' - * - * @example - * - */ -export function Timer({ duration, onComplete, variant = 'countdown' }: TimerProps) { - // Track remaining time with 1-second precision - const [timeRemaining, setTimeRemaining] = useState(duration); - - // Auto-submit when timer expires to prevent data loss - useEffect(() => { - if (timeRemaining === 0) { - onComplete?.(); - } - }, [timeRemaining, onComplete]); - - return ( -
- {/* Visual time display with color coding for urgency */} - -
- ); -} -``` - -#### Comment Standards -- **Function Headers**: Purpose, parameters, examples -- **Complex Logic**: Explain the "why", not just the "what" -- **Business Rules**: Document business logic and constraints -- **Edge Cases**: Explain handling of edge cases and error states -- **Performance Notes**: Document performance considerations -- **TODO Comments**: Include ticket numbers and timeline - -## Release Deployment - -### Deployment Pipeline - -#### Staging Deployment (dev branch) -- **Trigger**: Automatic on merge to `dev` -- **Environment**: Development/staging environment -- **Purpose**: Integration testing and feature validation -- **Access**: Internal team only - -#### Production Deployment (main branch) -- **Trigger**: Manual after release branch merge -- **Environment**: Production environment -- **Purpose**: Live user access -- **Process**: Blue-green deployment with rollback capability - -### Deployment Checklist -- [ ] **Database Migrations**: Applied and tested -- [ ] **Environment Variables**: Updated in production -- [ ] **Feature Flags**: Configured appropriately -- [ ] **Monitoring**: Alerts and dashboards configured -- [ ] **Rollback Plan**: Documented and tested -- [ ] **Communication**: Stakeholders notified of release - -## Role-Based Permissions Framework - -### Current Roles (Single Developer Phase) -- **Lead Developer/Product Owner**: All permissions (you) -- **CEO/Partner**: Spec review and approval for major changes - -### Future Roles (Team Growth Phase) - -#### Development Roles -- **Senior Developer**: Can approve PRs, create feature specs -- **Mid-Level Developer**: Can create PRs, review junior developer code -- **Junior Developer**: Can create PRs, requires review for all changes - -#### Product Roles -- **Product Owner**: Can modify project specs, prioritize features -- **Product Manager**: Can create feature requests, review specifications -- **Stakeholder**: Can review and comment on specifications - -#### Administrative Roles -- **Tech Lead**: Can modify development standards, approve architecture changes -- **DevOps Engineer**: Can modify deployment and CI/CD configurations -- **QA Lead**: Can modify testing standards and requirements - -### Permission Matrix -| Action | Lead Dev | Senior Dev | Mid Dev | Junior Dev | Product Owner | -|--------|----------|------------|---------|------------|---------------| -| Merge to main | ✅ | ✅ | ❌ | ❌ | ❌ | -| Approve PRs | ✅ | ✅ | ✅* | ❌ | ❌ | -| Modify specs | ✅ | ✅** | ❌ | ❌ | ✅ | -| Create releases | ✅ | ✅ | ❌ | ❌ | ❌ | -| Deploy to prod | ✅ | ✅ | ❌ | ❌ | ❌ | - -*Mid-level developers can approve junior developer PRs only -**Senior developers can modify feature specs, not project specs - -## Continuous Improvement - -### Sprint Retrospectives -- **What went well**: Celebrate successes and effective processes -- **What could improve**: Identify bottlenecks and pain points -- **Action items**: Concrete steps for next sprint improvement -- **Process updates**: Update this spec based on learnings - -### Metrics Tracking -- **PR Review Time**: Target < 24 hours for review completion -- **Bug Rate**: Track bugs per release and resolution time -- **Sprint Velocity**: Story points or features completed per sprint -- **Code Quality**: Test coverage, lint violations, complexity metrics - -### Spec Evolution -- **Quarterly Reviews**: Assess and update release strategy -- **Team Feedback**: Incorporate developer experience improvements -- **Industry Updates**: Adopt new best practices and tools -- **Scaling Adjustments**: Modify process as team grows - ---- - -**Implementation Priority**: High - Required for team collaboration and scaling diff --git a/specs/08-troubleshooting-documentation.md b/specs/08-troubleshooting-documentation.md deleted file mode 100644 index b22c7d9..0000000 --- a/specs/08-troubleshooting-documentation.md +++ /dev/null @@ -1,224 +0,0 @@ -# Troubleshooting Documentation Standards - -## Overview - -This specification defines the practice of creating Root Cause Analysis (RCA) documentation for major bug fixes and feature implementations. These documents serve as learning resources and historical records of complex problem-solving processes. - -## Purpose - -1. **Knowledge Preservation**: Capture deep technical insights that might otherwise be lost -2. **Learning Resource**: Help team members understand complex debugging processes -3. **Pattern Recognition**: Identify recurring issues and systematic solutions -4. **Onboarding Aid**: Accelerate new developer ramp-up with real-world examples -5. **Decision Documentation**: Record why certain approaches were chosen over alternatives - -## When to Create RCA Documentation - -Create an RCA document when: - -- ✅ The bug required significant investigation (>30 minutes of debugging) -- ✅ The root cause was non-obvious or counter-intuitive -- ✅ The fix involves React/Next.js patterns that may not be widely known -- ✅ The issue could easily recur if patterns aren't understood -- ✅ Multiple approaches were evaluated before finding the solution -- ✅ The debugging process revealed important system architecture insights - -## RCA Document Structure - -Each RCA document should follow this template: - -```markdown -# [Feature/Bug Name] - Root Cause Analysis - -**Date**: YYYY-MM-DD -**Severity**: Critical | High | Medium | Low -**Component**: [Component or system affected] -**Status**: ✅ Resolved | 🔄 In Progress | ⚠️ Workaround Applied - -## Problem Statement - -Clear, concise description of the observed issue. -- What was the user-visible symptom? -- What was the expected behavior? -- When did this occur? (Always, on load, specific conditions) - -## Root Cause - -Detailed technical explanation of why the issue occurred. -- What was the actual underlying cause? -- Why did it happen? -- What was missed initially? - -## Investigation Process - -Chronological steps taken to identify the root cause: -1. Initial hypothesis -2. Testing approach -3. Findings that led to breakthrough -4. Dead ends (important for learning!) - -## Solution - -Technical implementation of the fix: -- Code changes made -- Why this approach was chosen -- Alternative approaches considered - -## Prevention - -How to avoid this issue in the future: -- Patterns to follow -- Patterns to avoid -- Tests to add -- Documentation to update - -## Related Issues - -Links to similar issues or related documentation. - -## Lessons Learned - -Key takeaways for the team. -``` - -## Storage Location - -All RCA documents are stored alongside specifications for easy reference: - -``` -/specs/ -├── 01-development-standards.md -├── 08-troubleshooting-documentation.md -└── troubleshooting/ - ├── README.md - ├── video-transcript-auto-sync-2025-10-02.md - └── [issue-name]-[YYYY-MM-DD].md -``` - -### File Naming Convention - -``` -[kebab-case-description]-[YYYY-MM-DD].md -``` - -Examples: -- `video-transcript-auto-sync-2025-10-02.md` -- `timer-state-management-2025-09-20.md` -- `auth-middleware-race-condition-2025-10-01.md` - -## Version Control Strategy - -RCA documents are **committed to git** because: - -1. **Team Knowledge Base**: Everyone benefits from documented solutions -2. **Historical Context**: Future developers can see why decisions were made -3. **Pattern Recognition**: Similar issues can be quickly identified and referenced -4. **Onboarding Resource**: New team members learn from real-world debugging examples -5. **Cross-Reference**: Easy to link from code comments, PRs, and other specs - -### Quality Before Commit - -Before committing an RCA document: - -1. ✅ Remove any sensitive information (API keys, internal URLs, etc.) -2. ✅ Ensure code snippets are representative (not copy-pasted production data) -3. ✅ Verify links to external resources are public -4. ✅ Proofread for clarity - this will be read by others -5. ✅ Update `troubleshooting/README.md` index - -## Integration with Development Workflow - -### AI-Assisted Documentation - -When working with AI assistants (Cascade, etc.) on complex bugs: - -**During Debugging:** -1. AI provides detailed root cause analysis in chat -2. User requests: "Please create an RCA document for this fix" -3. AI automatically saves to `/specs/troubleshooting/[issue]-[YYYY-MM-DD].md` -4. AI updates `/specs/troubleshooting/README.md` index - -**Request Format:** -``` -"Can you add to your steering @specs to create a .md format file for this fix?" -``` - -**AI Response Pattern:** -1. ✅ Creates spec file (e.g., `08-troubleshooting-documentation.md`) if needed -2. ✅ Creates RCA document in `/specs/troubleshooting/` -3. ✅ Updates `/specs/troubleshooting/README.md` index -4. ✅ Provides summary of what was documented - -**Benefits:** -- Zero manual documentation overhead -- Captures analysis while fresh in context -- Consistent format across all RCAs -- Automatic indexing and cross-referencing - -### When AI Creates RCA Docs - -When Cascade or other AI assistants provide detailed root cause breakdowns: - -1. **Auto-Save**: Save the analysis to `/specs/troubleshooting/[issue]-[date].md` -2. **Auto-Index**: Update README.md with new entry -3. **Commit**: Add to git with the bug fix (RCAs are now version controlled) -4. **Reference**: Link from PR description, commit message, or code comments -5. **Review**: Team reviews during PR if issue was particularly complex - -### Manual Creation - -Developers should create RCA docs when: - -1. They discover something they wish they'd known earlier -2. They solve a bug that took >1 hour to diagnose -3. They implement a workaround that needs explanation -4. They want to document tribal knowledge -5. AI wasn't involved in the debugging process - -## Quality Standards - -RCA documents should: - -- ✅ **Be Specific**: Include actual code snippets, not generic descriptions -- ✅ **Show Timeline**: Explain the debugging journey, not just the answer -- ✅ **Include Visuals**: Add diagrams, screenshots, or ASCII art when helpful -- ✅ **Credit Sources**: Link to docs, Stack Overflow, or references that helped -- ✅ **Be Honest**: Include what didn't work and why -- ✅ **Use Plain Language**: Avoid jargon where possible; explain when necessary - -## Examples of Good RCA Titles - -- ✅ "Video Transcript Auto-Sync Fix - Callback Ref vs useEffect" -- ✅ "Timer Component Re-render Loop - State Closure Issue" -- ✅ "Next-Video Asset Loading - Storage Hook Implementation" -- ✅ "Authentication Middleware Race Condition - Cookie Timing" - -## Examples of Poor RCA Titles - -- ❌ "Bug Fix" (too generic) -- ❌ "Video Issue" (not specific) -- ❌ "Fixed the thing" (no context) -- ❌ "Update" (meaningless) - -## Maintenance - -- **Retention**: Keep RCA docs indefinitely (they're in git history anyway) -- **Organization**: Create subdirectories by category or year if folder gets large -- **Search**: Use filename conventions that support `grep`/`find`/GitHub search -- **Index**: Maintain `README.md` in `/specs/troubleshooting/` with categorized links -- **Updates**: If a pattern evolves, update the RCA or add a "Follow-up" section -- **Cross-Reference**: Link RCAs from relevant spec files when patterns are codified - -## Success Metrics - -A good RCA documentation practice should result in: - -1. Faster debugging of similar issues (pattern recognition) -2. Fewer repeated mistakes (institutional memory) -3. Better PR reviews (reviewers can reference similar fixes) -4. Improved onboarding (real examples vs theoretical docs) -5. Stronger team knowledge sharing - ---- - -**Note**: This is a living document. Update it as the team's RCA practices evolve. diff --git a/specs/09-technical-debt.md b/specs/09-technical-debt.md deleted file mode 100644 index 9448cce..0000000 --- a/specs/09-technical-debt.md +++ /dev/null @@ -1,51 +0,0 @@ -# Technical Debt - -This document tracks technical debt items requiring future attention, following the established specification numbering system. - -## Styling System Consistency - -### Tavus CVI Components - CSS Modules to Tailwind v4 Migration - -**Status**: Phase 1 - Deferred to Post-MVP - -**Issue**: Tavus CVI components use CSS modules, while the rest of the project uses TailwindCSS v4 + shadcn/ui (as defined in `specs/03-design-system-standards.md`). - -**Impact**: -- Two styling systems in codebase -- Inconsistent with design system standards -- Harder to theme/customize Tavus components -- Potential maintenance complexity - -**Affected Files**: -- `src/components/cvi/components/conversation/conversation.module.css` -- `src/components/cvi/components/audio-wave/audio-wave.module.css` -- `src/components/cvi/components/device-select/device-select.module.css` -- All other auto-generated CVI component styles - -**Recommended Action**: -1. Create Phase 2+ task to refactor Tavus components to Tailwind -2. Replicate video UI styles using Tailwind utility classes -3. Ensure responsive design and dark mode compatibility -4. Remove CSS module files after migration -5. Update component library to use shadcn/ui patterns - -**Priority**: Medium (post-MVP feature validation) - -**Estimated Effort**: 4-6 hours - -**Created**: 2025-10-21 (Phase 1: Ask a Question feature) - -**Related Specs**: -- `specs/03-design-system-standards.md` - Tailwind v4 + shadcn/ui standards -- `specs/features/ask-question-tavus.md` - Feature specification - ---- - -## Future Debt Items - -Add new technical debt items below following the same format: -- Clear status and priority -- Impact assessment -- Recommended action -- Time estimates -- Related specifications diff --git a/specs/WINDSURF-RULES.md b/specs/ENHANCED-PROJECT-STANDARDS.md similarity index 60% rename from specs/WINDSURF-RULES.md rename to specs/ENHANCED-PROJECT-STANDARDS.md index d2f94ed..bf4f6e8 100644 --- a/specs/WINDSURF-RULES.md +++ b/specs/ENHANCED-PROJECT-STANDARDS.md @@ -1,35 +1,60 @@ -# 8P3P LMS - Windsurf Project Rules - -> **Consolidated project standards distilled from specifications** -> **Activation Mode**: Always On -> **File Limit**: 12000 characters (Windsurf requirement) - --- +trigger: always_on +--- + +# 8P3P LMS - Windsurf Project Rules -- **Project**: EMDR therapist training LMS (Learning Management System) +- **Project**: EMDR therapist training LMS - **Stack**: Next.js 15, React 19, TypeScript 5.9, AWS Amplify Gen2, Tailwind v4, shadcn/ui - **Development Phase**: MVP feature completion (Phase 1) - **Testing Strategy**: Manual Q&A testing (no unit tests until post-MVP) ---- + +## Protocol Execution Order (CRITICAL) - +**MANDATORY SEQUENCE** - Must be followed in exact order: + +### Step 1: Codebase Analysis Protocol (ALWAYS FIRST) +- **Trigger**: ANY request involving files, components, or functionality +- **Required**: Complete existing implementation check before ANY recommendations +- **Blocker**: Cannot proceed to other protocols without completing this step + +### Step 2: Branch Readiness Protocol +- **Trigger**: Creating new branches or starting development work +- **Required**: User confirmation before any branch creation +- **Depends on**: Step 1 completion + +### Step 3: Implementation +- **Trigger**: After user approval from Step 2 +- **Required**: Follow all quality gates and standards +- **Depends on**: Steps 1 & 2 completion +**VIOLATION CONSEQUENCES**: +- Inaccurate recommendations (ignoring existing work) +- Wasted development time +- Loss of user trust in AI recommendations + + + ## Branch Readiness Protocol (MANDATORY) +**PREREQUISITE**: Codebase Analysis Protocol MUST be completed first. + Before starting ANY new feature: -1. **Present Branch Readiness Plan**: Show feature spec, branch strategy, stacked PR plan, timeline -2. **Get User Confirmation**: Ask "Ready to create the branch and start {feature_name} development? 🚀" -3. **Wait for Approval**: Do NOT create branches without explicit user confirmation -4. **Document Decision**: Record approval before proceeding +1. **Complete Codebase Analysis**: Verify existing implementations and acknowledge current state +2. **Present Branch Readiness Plan**: Show feature spec, branch strategy, stacked PR plan, timeline +3. **Get User Confirmation**: Ask "Ready to create the branch and start {feature_name} development? 🚀" +4. **Wait for Approval**: Do NOT create branches without explicit user confirmation +5. **Document Decision**: Record approval before proceeding + +**BLOCKER**: Cannot proceed without completing Step 1 (Codebase Analysis) ## LOC Verification (MANDATORY) Before every commit: ```bash -# Verify actual line count git diff --cached --shortstat git diff --cached --stat ``` @@ -41,20 +66,14 @@ git diff --cached --stat - **EXCEPTION**: Auto-generated library files (document in commit) ## PR & Release Standards - - **PR Size**: 200-400 LOC maximum per PR - **Stacked PRs**: For complex features, break into dependent PRs - **Commit Format**: Semantic commits (feat:, fix:, docs:, refactor:, etc.) - **Branch Strategy**: feature → dev → release/vX.Y.Z → main - ---- - - ## Server Components First Rule (HIGHEST PRIORITY) - - **DEFAULT**: Always start with Server Components (no "use client") - **ONLY add "use client"** when you need: - State management (useState, useReducer) @@ -66,13 +85,9 @@ git diff --cached --stat ### Server Components ```tsx -export default async function PostPage({ - params, -}: { - params: Promise<{ id: string }>; -}) { - const { id } = await params; // Next.js 15+ requires await - return
Post {id}
; +export default async function PostPage({ params }: { params: Promise<{ id: string }> }) { + const { id } = await params; // Next.js 15+ requires await + return
Post {id}
; } ``` @@ -81,37 +96,23 @@ export default async function PostPage({ "use client"; import { useParams } from "@/hooks/use-params"; -export default function ClientComponent({ - params, -}: { - params: Promise<{ id: string }>; -}) { - const { id } = useParams(params); - return
Post {id}
; +export default function ClientComponent({ params }: { params: Promise<{ id: string }> }) { + const { id } = useParams(params); + return
Post {id}
; } ``` **NEVER**: Use manual Promise unwrapping with `use()` in components ## Data Fetching - - **Prefer**: Server-side data fetching in Server Components - **Client-side**: Only when server-side isn't suitable (real-time updates, user interactions) - **Use**: ISR with `next: { revalidate: 3600 }` for cacheable data -
---- - - ## Authentication Standards -### Required Imports -```typescript -import { defineAuth, secret } from "@aws-amplify/backend"; -``` - ### Core Rules - **ALWAYS** import `secret` for auth configurations - **External Providers**: Only Google, Apple, Amazon, Facebook supported @@ -132,74 +133,77 @@ import { defineAuth, secret } from "@aws-amplify/backend"; ### Enums - Don't use `.required()` or `.defaultValue()` with enums -- Enums are type-safe by definition - ---- - - ## Tailwind CSS v4 + shadcn/ui Standards ### CSS-First Configuration - **No config file needed**: Tailwind v4 uses CSS-first configuration - **Single import**: `@import "tailwindcss";` in globals.css -- **Theme customization**: Use `@theme` directive with CSS variables ### Stylesheet Structure (globals.css) - -**Order matters**: -1. `@import` statements first -2. `@theme` directive for Tailwind customization -3. CSS variables in `:root` and `.dark` -4. `@layer` directives last +**Order matters**: `@import` → `@theme` → CSS variables → `@layer` ### Base Layer Rules - - **Use CSS variables directly** in `@layer base` - **Correct**: `background-color: var(--background);` - **Incorrect**: `@apply bg-background;` -- **Reason**: Tailwind v4 promotes CSS-first approach ### Component Standards - - **Primary**: shadcn/ui components for all UI elements - **Custom Components**: Follow shadcn/ui patterns and composition - **Styling**: Tailwind utility classes only (no CSS Modules except auto-generated libraries) -- **Theme**: Use CSS variables for dynamic theming - ---- - +## Codebase Analysis Protocol (MANDATORY - ALWAYS FIRST) + +**CRITICAL**: This protocol MUST be executed BEFORE any other protocols or recommendations. -## Codebase Analysis Protocol (MANDATORY) +### Trigger Conditions +- User requests feature implementation +- User asks about existing functionality +- User mentions creating/modifying files +- User says "proceed with [feature]" +- ANY development-related request -Before ANY recommendations about files/components/functionality: +### Required Analysis Steps -### 1. Existing Implementation Check +**Step 1: Search Existing Implementations** ```bash -grep_search "functionName|ComponentName" # Check existing implementations -find_by_name "*feature*|*component*" # Find related files -grep_search "import.*ComponentName" # Check usage patterns +grep_search "featureName|ComponentName" +find_by_name "*feature*|*component*" +grep_search "import.*ComponentName" ``` -### 2. Duplication Prevention -- **NEVER** suggest creating new files without checking existing implementations -- **NEVER** assume functionality doesn't exist without comprehensive searching -- **ALWAYS** build upon existing work rather than recreating it -- **ALWAYS** acknowledge existing implementations before suggesting changes +**Step 2: Read Complete Context** +- Read ALL related files completely (not partial) +- Understand existing architecture and patterns +- Identify what's already implemented vs what's missing -### 3. Recommendation Protocol -- **READ FIRST, RECOMMEND SECOND**: Scan existing codebase thoroughly -- **VERIFY ASSUMPTIONS**: Never assume something doesn't exist -- **ASK CLARIFYING QUESTIONS**: "I see you have X, are you looking to enhance it or replace it?" -- **ACKNOWLEDGE EXISTING WORK**: Recognize what's already implemented +**Step 3: Acknowledge Before Recommending** +- **ALWAYS** acknowledge existing implementations first +- State completion percentage: "X is 85% complete, missing Y and Z" +- Build upon existing work rather than recreating -## Quality Gates (Before Feature Completion) +### Enforcement Rules +- **NEVER** present plans without completing analysis first +- **NEVER** assume files don't exist without searching +- **NEVER** ignore existing implementations in recommendations +- **ALWAYS** state "Following Codebase Analysis Protocol" when starting +- **ALWAYS** acknowledge existing work before suggesting new work + +### Violation Prevention +**Before ANY recommendation, ask yourself**: +1. ✅ Did I search for existing implementations? +2. ✅ Did I read the complete existing code? +3. ✅ Did I acknowledge what's already built? +4. ✅ Am I building upon existing work vs recreating? +**If ANY answer is NO, STOP and complete the analysis first.** + +## Quality Gates (Before Feature Completion) **ALL must pass before declaring features complete**: 1. **ESLint**: `npm run lint` (0 errors, 0 warnings) 2. **TypeScript**: `npm run type-check` (full compilation) @@ -218,7 +222,6 @@ grep_search "import.*ComponentName" # Check usage patterns ### Naming Conventions - **Variables/Functions**: camelCase - **Components/Types**: PascalCase -- **Unused Variables**: Prefix with `_` - **Files**: kebab-case for utilities, PascalCase for components ## Comment Standards @@ -227,14 +230,8 @@ grep_search "import.*ComponentName" # Check usage patterns ```typescript /** * Analyzes video content and calculates engagement time - * * @param content - Video URL and metadata - * @param userProfile - User's learning preferences * @returns Estimated completion time with confidence score - * - * @example - * const estimate = analyzeVideo('/videos/intro.mp4', userProfile); - * // Returns: { timeMinutes: 15, confidence: 0.85 } */ ``` @@ -242,21 +239,30 @@ grep_search "import.*ComponentName" # Check usage patterns - **WHY decisions**: Document reasoning behind non-obvious implementations - **Edge Cases**: Explain handling of special conditions - **Error Handling**: Document recovery strategies -- **Performance**: Note optimization reasons - -### TODO Comments -```typescript -// TODO: [#TICKET-123] High priority - Add error retry logic -// Context: Current implementation fails silently on network errors -// Timeline: Sprint 3 -``` +## AI Accountability Standards + +### Protocol Compliance Verification +**Before presenting ANY plan or recommendation**: +1. ✅ **State Protocol**: "Following Codebase Analysis Protocol..." +2. ✅ **Show Evidence**: Present search results and existing implementations found +3. ✅ **Acknowledge Work**: "I found X is already implemented, Y needs completion" +4. ✅ **Build Upon**: "Building upon existing work rather than recreating" +5. ✅ **Accurate Scope**: Present realistic LOC and timeline based on actual state + +### Trust Maintenance +**User can rely on AI recommendations when**: +- All protocols followed in correct sequence +- Existing work acknowledged and respected +- Plans based on actual codebase state, not assumptions + +**User should question AI recommendations when**: +- Protocols skipped or reordered +- Existing implementations ignored +- Plans seem to recreate existing functionality ---- - - ## Component Reusability Protocol (MANDATORY) Before creating ANY new component: @@ -275,18 +281,9 @@ grep_search "ComponentName" src/components/ 1. **Reuse existing**: Extend or compose existing components 2. **shadcn/ui base**: Build on shadcn/ui components 3. **Create new**: Only when above options aren't suitable - -### 4. Composition Over Creation -- Prefer composing multiple small components -- Document component composition in JSDoc headers -- Follow shadcn/ui patterns for consistency - ---- - - ## Systematic Issue Resolution ### Resolution Protocol @@ -297,115 +294,57 @@ grep_search "ComponentName" src/components/ ### Confirmation Process ``` -REQUIRED STEPS: 1. Present solution and changes made 2. Ask user to test the fix 3. Request explicit confirmation: "Can you confirm this issue is resolved?" 4. Wait for user verification -5. If not resolved, investigate further ``` ### RCA Documentation - Create RCA document when: - Bug required significant investigation (>30 minutes) - Root cause was non-obvious -- Issue involves React/Next.js patterns not widely known - Multiple approaches were evaluated -- Debugging revealed important architecture insights - ---- - - ## Clarifying Questions Framework ### Before Implementation - **ALWAYS** ask clarifying questions before implementation - **NEVER** assume requirements without confirmation -- **DOCUMENT** all assumptions and decisions -- **VALIDATE** understanding before proceeding ### Question Categories - -**Technical Architecture**: -- Data structure and relationships -- User interaction flow -- Performance requirements -- Integration patterns -- Scalability considerations - -**Feature Specification**: -- Exact functionality -- Edge case handling -- Validation rules -- Error handling approach -- Accessibility requirements - -**Implementation**: -- Technology stack choices -- Component architecture -- State management approach -- Testing strategy -- Deployment approach +**Technical Architecture**: Data structure, user flow, performance, integration, scalability +**Feature Specification**: Functionality, edge cases, validation, error handling, accessibility +**Implementation**: Technology choices, component architecture, state management, testing, deployment ## MoSCoW Prioritization - - **Must Have**: Critical features for MVP - **Should Have**: Important but not critical - **Could Have**: Nice to have features -- **Won't Have**: Out of scope for current iteration - ---- - - ## MVP Testing Approach - **Current Phase**: Manual Q&A testing only - **No unit tests**: Deferred until post-MVP - **Focus**: Feature completion over test coverage - **Quality Gates**: ESLint, TypeScript, build validation only - -**Rationale**: Rapid iteration and feature completion for MVP delivery - -**Post-MVP**: Comprehensive automated testing suite will be implemented - ---- - - ## Mock Data Best Practices - - **Location**: Centralized in `src/lib/mock-data.ts` - **TypeScript**: Use proper interfaces for typed data - **Organization**: Group by feature -- **Structure**: Easy replacement for real APIs -- **Alternatives**: `src/data/`, `src/mocks/`, or `src/lib/data/` for larger projects - ---- - - ## Current Technical Debt ### Tavus CVI Components - CSS Modules **Status**: Deferred to Post-MVP - **Issue**: Tavus CVI uses CSS modules; project uses Tailwind v4 + shadcn/ui - -**Impact**: Two styling systems in codebase - **Action**: Post-MVP migration to Tailwind patterns - -**Priority**: Medium (after feature validation) - - + \ No newline at end of file diff --git a/specs/README.md b/specs/README.md new file mode 100644 index 0000000..b798117 --- /dev/null +++ b/specs/README.md @@ -0,0 +1,41 @@ +# 8P3P LMS - Specifications + +This directory contains the core project specifications and documentation. + +## 📁 Directory Structure + +### Active Files +- **`features/`** - Feature specifications (managed separately) +- **`troubleshooting/`** - Troubleshooting guides and RCA documentation + +### Archive +- **`archive/`** - Historical specification files and enhanced project standards (not tracked in git) + +## 🎯 Primary Reference + +**Use `.windsurf/rules/project-standards.md`** as the single source of truth for: +- Development workflow and protocols +- Code quality standards +- Architecture guidelines (Next.js 15, AWS Amplify Gen2, Tailwind v4) +- Component development standards +- Testing strategy + +## 📋 Protocol Hierarchy + +All development work must follow this sequence: +1. **Codebase Analysis Protocol** (ALWAYS FIRST) +2. **Branch Readiness Protocol** +3. **Implementation** + +## 🔄 Maintenance + +- **Project Standards**: Update `.windsurf/rules/project-standards.md` for any rule changes +- **Features**: Add new feature specs to `features/` directory +- **Troubleshooting**: Document RCA findings in `troubleshooting/` +- **Archive**: Historical files preserved locally but not tracked in git + +--- + +**Status**: Cleaned up and organized (2025-01-21) +**Active Rules**: `.windsurf/rules/project-standards.md` +**Archive**: Not tracked in version control diff --git a/specs/WINDSURF-RULES-ANALYSIS.md b/specs/WINDSURF-RULES-ANALYSIS.md deleted file mode 100644 index cef6b02..0000000 --- a/specs/WINDSURF-RULES-ANALYSIS.md +++ /dev/null @@ -1,421 +0,0 @@ -# Windsurf Rules Consolidation Analysis - -**Date**: 2025-01-21 -**Analyst**: Cascade AI -**Objective**: Consolidate project specifications into a single Windsurf-compatible rules document - ---- - -## Executive Summary - -Successfully consolidated 10 specification documents (excluding `specs/features/`) into a single, project-specific Windsurf rules document following official best practices from windsurf.com. - -**Result**: `WINDSURF-RULES.md` (11,566 characters / 12,000 limit) - ---- - -## Source Documents Analyzed - -| Spec File | Size | Key Content Extracted | -|-----------|------|----------------------| -| `00-specification-framework.md` | 395 lines | Requirements gathering, MoSCoW prioritization, branch readiness protocol | -| `01-development-standards.md` | 484 lines | Code quality, ESLint rules, component reusability, codebase analysis protocol | -| `02-aws-amplify-backend.md` | 222 lines | Authentication config, data schema design, relationship patterns | -| `03-design-system-standards.md` | 384 lines | Tailwind v4 + shadcn/ui standards, CSS-first configuration, theme system | -| `04-nextjs15-standards.md` | 454 lines | Server components first, route parameters, data fetching patterns | -| `05-bug-resolution-workflow.md` | 202 lines | Systematic issue resolution, user confirmation protocol | -| `06-project-specification.md` | 275 lines | Project context, tech stack, requirements (Must/Should/Could/Won't Have) | -| `07-release-strategy.md` | 329 lines | Sprint-based development, PR workflow, LOC verification, stacked PRs | -| `08-troubleshooting-documentation.md` | 225 lines | RCA documentation standards, when to create RCA docs | -| `09-technical-debt.md` | 52 lines | Current technical debt tracking (Tavus CSS Modules) | - -**Total Input**: 3,022 lines across 10 specification documents -**Output**: Single consolidated rules document - ---- - -## Consolidation Strategy - -### 1. Windsurf Best Practices Applied - -Following official guidance from https://windsurf.com/editor/directory and https://docs.windsurf.com: - -✅ **Keep rules simple, concise, and specific** -- Removed verbose explanations -- Focused on actionable standards -- Eliminated generic advice already in Cascade's training - -✅ **Use bullet points, numbered lists, and markdown** -- Structured with clear hierarchies -- Easy-to-scan format -- Consistent formatting throughout - -✅ **Project-specific standards only** -- Filtered out generic coding advice -- Kept unique 8P3P LMS requirements -- Maintained project context and tech stack - -✅ **XML tags for grouping** -- Used semantic tags: ``, ``, etc. -- Logical grouping of related rules -- Easy navigation and reference - -✅ **Character limit compliance** -- 11,566 characters (under 12,000 limit) -- Balanced comprehensiveness with conciseness -- Prioritized high-impact rules - -### 2. Rule Organization - -**Structured by workflow priority**: - -1. **Project Context** - Tech stack, development phase, testing strategy -2. **Development Workflow** - Branch readiness, LOC verification, PR standards (MANDATORY protocols) -3. **Next.js 15 Architecture** - Server components first, route parameters, data fetching -4. **AWS Amplify Backend** - Authentication, data schema, relationship patterns -5. **Design System** - Tailwind v4 + shadcn/ui standards -6. **Code Quality** - Codebase analysis, quality gates, ESLint, comments -7. **Component Development** - Reusability protocol, shadcn/ui integration -8. **Bug Resolution** - Systematic resolution, user confirmation -9. **Specification Process** - Clarifying questions, MoSCoW prioritization -10. **Testing Strategy** - MVP Q&A testing approach -11. **Mock Data** - Best practices and organization -12. **Technical Debt** - Current debt tracking - -### 3. Content Distillation - -**High-impact rules prioritized**: -- ✅ MANDATORY protocols (branch readiness, LOC verification, codebase analysis) -- ✅ Framework-specific standards (Next.js 15, Amplify Gen2, Tailwind v4) -- ✅ Project-specific patterns (Server Components first, route parameters) -- ✅ Quality gates and validation requirements -- ✅ Common pitfalls and error prevention - -**Removed/Minimized**: -- ❌ Lengthy examples (kept only essential code snippets) -- ❌ Redundant explanations -- ❌ Generic best practices (already in Cascade's training) -- ❌ Feature-specific specs (kept in `specs/features/`) -- ❌ Historical context and decision logs - ---- - -## Rules Activation Strategy - -### Recommended Activation Mode: **Always On** - -**Rationale**: -- These are core project standards that apply to ALL development work -- Covers architectural decisions, code quality, and workflow requirements -- Essential for maintaining consistency across the entire codebase - -### Alternative Activation Modes - -If performance concerns arise with "Always On": - -**Model Decision** mode with description: -``` -Apply these rules when working on: -- Next.js components and pages -- AWS Amplify backend configuration -- Tailwind CSS styling and theming -- Code quality and PR submissions -- Feature development and bug fixes -``` - -**Glob patterns** for specific file types: -- `*.tsx`, `*.ts` - TypeScript/React files -- `amplify/**/*` - Amplify backend files -- `src/app/**/*` - Next.js App Router files -- `*.css` - Tailwind/styling files - ---- - -## Integration Path - -### Option 1: Windsurf Rules Directory (Recommended) - -**Location**: `.windsurf/rules/project-standards.md` - -**Steps**: -1. Copy `specs/WINDSURF-RULES.md` → `.windsurf/rules/project-standards.md` -2. Configure activation mode in Windsurf UI: **Always On** -3. Verify rules appear in Customizations panel -4. Test by starting a new Cascade conversation - -**Pros**: -- ✅ Native Windsurf integration -- ✅ Auto-loaded for all conversations -- ✅ Can be activated/deactivated via UI - -**Cons**: -- ⚠️ `.windsurf/rules/` is gitignored by default -- ⚠️ Requires manual setup for new team members - -**Gitignore Update**: Already applied to allow tracking of `project-standards.md` - -### Option 2: Global Rules (Multi-Project) - -If these standards apply across multiple projects: - -**Location**: Global rules via Windsurf UI - -**Steps**: -1. Open Windsurf → Customizations → Rules -2. Click "+ Global" button -3. Paste content from `WINDSURF-RULES.md` -4. Set activation mode: **Model Decision** or **Always On** - -**Pros**: -- ✅ Available across all workspaces -- ✅ Single source of truth for multi-project teams - -**Cons**: -- ⚠️ Not project-specific -- ⚠️ Harder to version control - -### Option 3: Reference Document (Current State) - -Keep as `specs/WINDSURF-RULES.md` for reference: - -**Pros**: -- ✅ Version controlled in Git -- ✅ Easy to review and update -- ✅ Team visibility and collaboration - -**Cons**: -- ❌ Not automatically loaded by Windsurf -- ❌ Requires manual @mention in Cascade conversations - ---- - -## Next Steps - -### Immediate Actions - -1. **Review Consolidated Rules** - - Read through `specs/WINDSURF-RULES.md` - - Validate accuracy and completeness - - Identify any missing critical standards - -2. **Choose Integration Path** - - Decide on activation strategy (Always On vs Model Decision) - - Select location (workspace rules vs global vs reference) - -3. **Test Integration** - - Start new Cascade conversation - - Verify rules are accessible (via @mention or auto-loading) - - Test with sample development task - -### Phase 2 Enhancements - -After initial validation: - -4. **Fine-tune Rule Activation** - - Monitor which rules are most/least useful - - Adjust activation modes if needed - - Split into multiple rule files if growing too large - -5. **Update Workflow** - - Integrate rules into onboarding documentation - - Add to CONTRIBUTING.md - - Update README with Windsurf setup instructions - -6. **Maintenance Schedule** - - Review rules after major feature completions - - Update when new patterns emerge - - Sync with spec document changes - ---- - -## Maintenance Guidelines - -### When to Update Rules - -**Immediate updates required**: -- ✅ New framework versions (Next.js, React, Amplify) -- ✅ Major architectural decisions -- ✅ New mandatory protocols or workflows -- ✅ Breaking changes to existing patterns - -**Periodic reviews**: -- 🔄 After each sprint completion -- 🔄 When patterns emerge from multiple PRs -- 🔄 Team retrospective feedback - -### Update Process - -1. **Identify Change**: New pattern, protocol, or standard emerges -2. **Evaluate Impact**: Is it project-wide or feature-specific? -3. **Update Sources**: Modify relevant spec documents first -4. **Regenerate Rules**: Re-consolidate into Windsurf rules -5. **Validate**: Test with Cascade to ensure accuracy -6. **Communicate**: Notify team of updated standards - -### Version Control - -**Spec Documents**: Full detail, version controlled in Git -- `specs/00-specification-framework.md` -- `specs/01-development-standards.md` -- etc. - -**Windsurf Rules**: Distilled version, may or may not be in Git -- `.windsurf/rules/project-standards.md` (if gitignore updated) -- `specs/WINDSURF-RULES.md` (reference copy, always tracked) - -**Sync Strategy**: Treat spec docs as source of truth, regenerate rules from specs - ---- - -## Benefits Delivered - -### For Cascade AI - -✅ **Comprehensive Context**: Full project standards in single document -✅ **Consistent Behavior**: Always follows project-specific patterns -✅ **Reduced Errors**: Prevents common mistakes (e.g., wrong route parameter handling) -✅ **Faster Responses**: No need to search multiple spec files -✅ **Better Quality**: Enforces quality gates and code standards - -### For Development Team - -✅ **Standardization**: Consistent code across all features -✅ **Onboarding**: New developers get standards automatically via AI -✅ **Efficiency**: Less time correcting AI-generated code -✅ **Quality**: Automatic enforcement of best practices -✅ **Documentation**: Single reference for project standards - -### For Project - -✅ **Code Quality**: Enforced standards prevent technical debt -✅ **Velocity**: Faster development with consistent patterns -✅ **Maintainability**: Predictable code structure -✅ **Scalability**: Standards support team growth -✅ **Knowledge Preservation**: Standards documented and accessible - ---- - -## Character Budget Analysis - -**Target**: 12,000 characters maximum (Windsurf limit) -**Actual**: 11,566 characters -**Remaining**: 434 characters (3.6% buffer) - -### Character Distribution - -| Section | Chars | % | -|---------|-------|---| -| Project Context | 482 | 4.2% | -| Development Workflow | 1,248 | 10.8% | -| Next.js 15 Architecture | 1,456 | 12.6% | -| AWS Amplify Backend | 1,389 | 12.0% | -| Design System | 1,248 | 10.8% | -| Code Quality | 2,894 | 25.0% | -| Component Development | 847 | 7.3% | -| Bug Resolution | 982 | 8.5% | -| Specification Process | 724 | 6.3% | -| Testing Strategy | 328 | 2.8% | -| Mock Data | 346 | 3.0% | -| Technical Debt | 622 | 5.4% | - -**Largest Section**: Code Quality (25.0%) - reflects priority on quality gates and standards - -**Opportunities for expansion** (if needed): -- Testing strategy details (post-MVP) -- Component patterns library -- Advanced Amplify patterns -- Performance optimization rules - ---- - -## Comparison: Before vs After - -### Before Consolidation - -**Fragmented Standards**: -- 10 separate specification documents -- 3,022 total lines -- Scattered across different files -- Required manual searching and cross-referencing -- Not integrated with Windsurf AI - -**Cascade Behavior**: -- May miss relevant standards -- Requires @mention of specific specs -- Inconsistent application of rules -- Longer response times (searching specs) - -### After Consolidation - -**Unified Standards**: -- Single rules document -- 11,566 characters -- Organized by workflow priority -- Always available to Cascade -- Native Windsurf integration - -**Cascade Behavior**: -- Automatic standards enforcement -- Consistent application of rules -- Faster, more accurate responses -- Proactive error prevention -- Project-specific recommendations - ---- - -## Success Metrics - -Track these metrics to validate effectiveness: - -### Code Quality -- ✅ Reduction in ESLint errors -- ✅ Fewer PR revision requests -- ✅ Improved TypeScript strict mode compliance - -### Development Efficiency -- ✅ Faster PR review times -- ✅ Fewer back-and-forth clarifications with Cascade -- ✅ Reduced time fixing AI-generated code - -### Consistency -- ✅ Uniform component patterns across codebase -- ✅ Consistent API route structures -- ✅ Standardized error handling - -### Knowledge Sharing -- ✅ Faster onboarding for new developers -- ✅ Better adherence to architectural decisions -- ✅ Reduced "how do we do X?" questions - ---- - -## Conclusion - -Successfully distilled 10 comprehensive specification documents into a single, actionable Windsurf rules document that: - -1. **Follows official Windsurf best practices** from windsurf.com -2. **Stays under character limit** (11,566 / 12,000) -3. **Covers all critical project standards** -4. **Organized for easy navigation and reference** -5. **Ready for immediate integration** with Windsurf AI - -Next step: **Choose integration path** and test with Cascade to validate effectiveness. - ---- - -## Appendix: Rule Extraction Matrix - -| Source Spec | Priority Rules Extracted | Secondary Rules | Excluded | -|-------------|------------------------|----------------|----------| -| `00-specification-framework.md` | Branch readiness protocol, MoSCoW prioritization | Safe rollback points | Historical context | -| `01-development-standards.md` | Server components first, codebase analysis protocol, quality gates | Comment standards, ESLint rules | Verbose examples | -| `02-aws-amplify-backend.md` | Auth config rules, schema design patterns | Deployment configs | Implementation details | -| `03-design-system-standards.md` | Tailwind v4 standards, CSS-first config | Theme system | Color palette details | -| `04-nextjs15-standards.md` | Route parameters handling, data fetching | Navigation patterns | Edge case examples | -| `05-bug-resolution-workflow.md` | User confirmation protocol, RCA triggers | Resolution templates | Ticket formats | -| `06-project-specification.md` | Tech stack, project context | Requirements overview | Detailed feature specs | -| `07-release-strategy.md` | LOC verification, PR standards, stacked PRs | Semantic commits | Sprint planning details | -| `08-troubleshooting-documentation.md` | When to create RCA docs | RCA structure | Template details | -| `09-technical-debt.md` | Current debt items | — | Historical debt | - -**Extraction Ratio**: ~35-40% of content became rules (high-impact, actionable standards only) diff --git a/specs/WINDSURF-RULES-SETUP.md b/specs/WINDSURF-RULES-SETUP.md deleted file mode 100644 index 8888e25..0000000 --- a/specs/WINDSURF-RULES-SETUP.md +++ /dev/null @@ -1,335 +0,0 @@ -# Windsurf Rules Setup Guide - -**Quick start guide for integrating consolidated project standards with Windsurf AI** - ---- - -## TL;DR - -**Consolidated Rules**: `specs/WINDSURF-RULES.md` (11,566 chars / 12,000 limit) -**Activation**: Copy to `.windsurf/rules/project-standards.md` → Set "Always On" -**Status**: ✅ Ready for integration - ---- - -## Setup Instructions - -### Option 1: Workspace Rules (Recommended) - -**Copy the rules file**: -```bash -# From project root -cp specs/WINDSURF-RULES.md .windsurf/rules/project-standards.md -``` - -**Activate in Windsurf**: -1. Open Windsurf IDE -2. Click **Customizations** icon (top-right slider menu) -3. Navigate to **Rules** tab -4. Find `project-standards.md` in workspace rules -5. Set activation mode: **Always On** -6. Confirm rules appear in active rules list - -**Verify Integration**: -1. Start new Cascade conversation -2. Ask: "What are the Next.js 15 route parameter standards?" -3. Cascade should reference the rules automatically - ---- - -## What's Included - -### Mandatory Protocols -- ✅ Branch Readiness Protocol (requires user confirmation before feature work) -- ✅ LOC Verification (verify actual line counts before every commit) -- ✅ Codebase Analysis Protocol (check existing implementations before creating new) - -### Architecture Standards -- ✅ Next.js 15: Server Components first, route parameters handling -- ✅ AWS Amplify Gen2: Authentication, data schema patterns -- ✅ Tailwind v4 + shadcn/ui: CSS-first configuration, theme system - -### Code Quality -- ✅ Quality Gates: ESLint, TypeScript, build validation -- ✅ Component Reusability Protocol -- ✅ Comment and documentation standards - -### Workflow Standards -- ✅ PR size limits (200-400 LOC) -- ✅ Stacked PRs for complex features -- ✅ Bug resolution and user confirmation -- ✅ Clarifying questions framework - ---- - -## Usage Examples - -### Before Creating a Component - -Cascade will automatically: -1. Search for existing similar components -2. Check shadcn/ui for base components -3. Recommend reuse/composition over creation -4. Follow project styling standards (Tailwind v4) - -### Before Starting a Feature - -Cascade will automatically: -1. Present branch readiness plan -2. Ask for explicit confirmation -3. Wait for your approval before creating branches -4. Document the decision - -### Before Every Commit - -Cascade will automatically: -1. Run `git diff --cached --shortstat` -2. Verify actual line counts -3. Report LOC in commit messages -4. Flag if exceeding PR size limits - ---- - -## Testing the Integration - -### Test 1: Architecture Standards -**Ask Cascade**: "How should I handle route parameters in a Next.js 15 page?" - -**Expected Response**: -- Server Components: Use `await params` -- Client Components: Use `useParams` hook -- Never use manual `use()` unwrapping - -### Test 2: Component Creation -**Ask Cascade**: "Create a new button component with hover effects" - -**Expected Behavior**: -1. Search existing button components -2. Check shadcn/ui Button component -3. Recommend using/extending shadcn/ui Button -4. Only create new if justified - -### Test 3: Branch Readiness -**Ask Cascade**: "Start implementing the user profile feature" - -**Expected Behavior**: -1. Present feature specification -2. Show branch strategy -3. Ask: "Ready to create the branch and start user-profile development? 🚀" -4. Wait for your confirmation - ---- - -## Maintenance - -### When to Update Rules - -**Immediate**: -- Framework version upgrades (Next.js, React, Amplify) -- New mandatory protocols or workflows -- Breaking changes to patterns - -**Periodic** (after each sprint): -- Emerging patterns from multiple PRs -- Team feedback and retrospective insights - -### Update Process - -1. **Update source specs** first (`specs/*.md`) -2. **Regenerate rules**: Re-run consolidation process -3. **Copy to Windsurf**: Update `.windsurf/rules/project-standards.md` -4. **Test**: Verify with sample Cascade conversation -5. **Notify team**: Communicate updated standards - ---- - -## Troubleshooting - -### Rules Not Appearing - -**Check**: -1. File exists: `.windsurf/rules/project-standards.md` -2. File size: Under 12,000 characters -3. Windsurf UI: Rules tab shows the file -4. Activation: Set to "Always On" or appropriate mode - -**Fix**: -```bash -# Verify file exists -ls -la .windsurf/rules/project-standards.md - -# Check character count -wc -c .windsurf/rules/project-standards.md - -# Reload Windsurf window -# Cmd+Shift+P → "Developer: Reload Window" -``` - -### Rules Not Being Applied - -**Symptoms**: -- Cascade doesn't follow project patterns -- No mention of mandatory protocols -- Generic responses instead of project-specific - -**Fix**: -1. Verify activation mode is "Always On" -2. Check Rules tab shows active status -3. Start **new** Cascade conversation (old conversations may not reload rules) -4. Explicitly @mention the rule if needed: `@project-standards` - -### Character Limit Exceeded - -**Symptoms**: -- Rule file won't load -- Error message about size - -**Fix**: -1. Check current size: `wc -c .windsurf/rules/project-standards.md` -2. If over 12,000, split into multiple rule files: - - `architecture-standards.md` (Next.js, Amplify, Design System) - - `workflow-standards.md` (Branch readiness, LOC, PRs) - - `code-quality-standards.md` (ESLint, TypeScript, Comments) -3. Use glob patterns or model decision for targeted activation - ---- - -## Benefits Checklist - -After setup, you should experience: - -### Immediate Benefits -- ✅ Cascade enforces Server Components first rule -- ✅ Automatic codebase analysis before creating new files -- ✅ Branch readiness confirmation prevents premature feature work -- ✅ LOC verification catches oversized PRs early - -### Quality Improvements -- ✅ Fewer ESLint errors in AI-generated code -- ✅ Consistent component patterns -- ✅ Proper TypeScript strict mode compliance -- ✅ Correct Amplify Gen2 patterns (e.g., `.guest()` not `.public()`) - -### Efficiency Gains -- ✅ Less time fixing AI code -- ✅ Faster PR reviews (code follows standards) -- ✅ Fewer back-and-forth clarifications -- ✅ Better first-time code quality - ---- - -## Advanced Configuration - -### Multiple Rule Files - -If rules grow beyond 12,000 characters: - -``` -.windsurf/rules/ -├── project-standards.md # Core standards (Always On) -├── architecture-patterns.md # Detailed patterns (Model Decision) -├── component-library.md # Component examples (Manual) -└── troubleshooting-guide.md # Debug patterns (Manual) -``` - -**Activation Strategy**: -- `project-standards.md`: Always On -- `architecture-patterns.md`: Model Decision (when working on architecture) -- `component-library.md`: Manual (@mention when needed) -- `troubleshooting-guide.md`: Manual (@mention when debugging) - -### Glob Pattern Activation - -For file-type specific rules: - -**TypeScript/React Files**: -``` -Pattern: **/*.{ts,tsx} -Activation: Automatic -``` - -**Amplify Backend**: -``` -Pattern: amplify/**/* -Activation: Automatic -``` - -**Styling Files**: -``` -Pattern: **/*.css -Activation: Automatic -``` - ---- - -## Team Onboarding - -### For New Developers - -**Setup Steps**: -1. Clone repository -2. Run: `cp specs/WINDSURF-RULES.md .windsurf/rules/project-standards.md` -3. Open Windsurf → Customizations → Rules -4. Verify `project-standards.md` is active -5. Start first Cascade conversation to test - -**Learning Path**: -1. Read `specs/WINDSURF-RULES.md` once (10-15 minutes) -2. Reference during development as needed -3. Let Cascade enforce automatically -4. Gradually internalize patterns - -### For Existing Developers - -**Migration**: -1. Review consolidated rules vs old spec documents -2. Note any new mandatory protocols -3. Update local workflows if needed -4. Continue referencing full specs for deep dives - ---- - -## Support Resources - -### Documentation -- **Full Specs**: `specs/*.md` (detailed explanations) -- **Consolidated Rules**: `specs/WINDSURF-RULES.md` (quick reference) -- **Analysis**: `specs/WINDSURF-RULES-ANALYSIS.md` (consolidation process) -- **This Guide**: `specs/WINDSURF-RULES-SETUP.md` (setup instructions) - -### Windsurf Resources -- **Rules Directory**: https://windsurf.com/editor/directory -- **Documentation**: https://docs.windsurf.com/windsurf/cascade/memories -- **Best Practices**: Included in rules directory examples - -### Project Resources -- **CONTRIBUTING.md**: Development workflow and PR guidelines -- **README.md**: Project overview and setup instructions -- **specs/**: Complete specification documents - ---- - -## Next Steps - -1. ✅ **Review**: Read through `specs/WINDSURF-RULES.md` -2. ✅ **Integrate**: Copy to `.windsurf/rules/project-standards.md` -3. ✅ **Activate**: Set to "Always On" in Windsurf UI -4. ✅ **Test**: Run the 3 test scenarios above -5. ✅ **Validate**: Confirm Cascade follows project standards -6. ✅ **Proceed**: Move forward with Phase 2 development - ---- - -## Success Criteria - -Rules are successfully integrated when: - -✅ Cascade automatically enforces Server Components first -✅ Branch readiness confirmation happens before feature work -✅ Codebase analysis occurs before creating new files -✅ LOC verification runs before commits -✅ Amplify Gen2 patterns are correct (`.guest()`, relationships, etc.) -✅ Tailwind v4 + shadcn/ui standards are followed -✅ Quality gates are enforced before feature completion - -**Status**: Ready for integration and testing 🚀 diff --git a/specs/WINDSURF-RULES-SUMMARY.md b/specs/WINDSURF-RULES-SUMMARY.md deleted file mode 100644 index 16e3717..0000000 --- a/specs/WINDSURF-RULES-SUMMARY.md +++ /dev/null @@ -1,307 +0,0 @@ -# Windsurf Rules Consolidation - Summary - -**Date**: 2025-01-21 -**Status**: ✅ Complete - Ready for Integration -**Character Count**: 11,566 / 12,000 (96.4%) - ---- - -## Deliverables - -### 1. Consolidated Rules Document -**File**: `specs/WINDSURF-RULES.md` -**Size**: 11,566 characters (under Windsurf's 12,000 limit) -**Format**: Markdown with XML semantic tags -**Activation**: Designed for "Always On" mode - -**Content Sections**: -- Project Context (tech stack, development phase) -- Development Workflow (branch readiness, LOC verification, PR standards) -- Next.js 15 Architecture (server components, routing, data fetching) -- AWS Amplify Backend (authentication, data schema, relationships) -- Design System (Tailwind v4 + shadcn/ui standards) -- Code Quality (codebase analysis, quality gates, ESLint, TypeScript) -- Component Development (reusability protocol) -- Bug Resolution (systematic resolution, user confirmation) -- Specification Process (clarifying questions, MoSCoW) -- Testing Strategy (MVP Q&A approach) -- Mock Data (organization best practices) -- Technical Debt (current debt tracking) - -### 2. Comprehensive Analysis -**File**: `specs/WINDSURF-RULES-ANALYSIS.md` - -**Includes**: -- Source document analysis (10 spec files, 3,022 lines) -- Consolidation strategy and Windsurf best practices applied -- Rule organization methodology -- Content distillation approach -- Character budget analysis -- Integration path options (workspace rules, global rules, reference) -- Maintenance guidelines -- Success metrics -- Before/after comparison - -### 3. Setup Guide -**File**: `specs/WINDSURF-RULES-SETUP.md` - -**Includes**: -- Quick start instructions -- Integration testing procedures -- Troubleshooting guide -- Team onboarding process -- Advanced configuration options -- Support resources - -### 4. Gitignore Update -**File**: `.gitignore` - -**Change**: Allow tracking of `.windsurf/rules/project-standards.md` while ignoring other Windsurf files - -```gitignore -# windsurf -.windsurf/* -!.windsurf/rules/ -.windsurf/rules/* -!.windsurf/rules/project-standards.md -``` - ---- - -## Key Features - -### Windsurf Best Practices Applied - -✅ **Simple, concise, and specific** - No verbose explanations or generic advice -✅ **Bullet points and markdown** - Easy to scan and navigate -✅ **Project-specific standards** - Only unique 8P3P LMS requirements -✅ **XML semantic tags** - Logical grouping: ``, ``, etc. -✅ **Character limit compliance** - 11,566 chars (434 char buffer remaining) - -### Mandatory Protocols Included - -✅ **Branch Readiness Protocol** - User confirmation required before feature development -✅ **LOC Verification Protocol** - Verify actual line counts before every commit -✅ **Codebase Analysis Protocol** - Check existing implementations before creating new - -### Framework-Specific Standards - -✅ **Next.js 15** - Server Components first, route parameters with `await`, data fetching patterns -✅ **AWS Amplify Gen2** - Authentication config, data schema design, relationship patterns -✅ **Tailwind v4** - CSS-first configuration, base layer rules, theme system -✅ **shadcn/ui** - Component standards, composition patterns - -### Quality & Workflow Standards - -✅ **Quality Gates** - ESLint, TypeScript, build validation -✅ **PR Standards** - 200-400 LOC limits, stacked PRs, semantic commits -✅ **Component Reusability** - Search existing → Check shadcn/ui → Create new (last resort) -✅ **Bug Resolution** - Systematic resolution, mandatory user confirmation - ---- - -## Source Documents Consolidated - -| Spec File | Lines | Key Content | -|-----------|-------|-------------| -| `00-specification-framework.md` | 395 | Requirements, MoSCoW, branch readiness | -| `01-development-standards.md` | 484 | Code quality, ESLint, component reusability | -| `02-aws-amplify-backend.md` | 222 | Authentication, data schema, relationships | -| `03-design-system-standards.md` | 384 | Tailwind v4, shadcn/ui, theme system | -| `04-nextjs15-standards.md` | 454 | Server components, routing, data fetching | -| `05-bug-resolution-workflow.md` | 202 | Systematic resolution, user confirmation | -| `06-project-specification.md` | 275 | Project context, tech stack, requirements | -| `07-release-strategy.md` | 329 | Sprint dev, PR workflow, LOC verification | -| `08-troubleshooting-documentation.md` | 225 | RCA documentation standards | -| `09-technical-debt.md` | 52 | Technical debt tracking | -| **Total** | **3,022** | **Consolidated → 11,566 chars** | - -**Consolidation Ratio**: ~35-40% extraction (high-impact, actionable standards only) - ---- - -## Integration Options - -### Option 1: Workspace Rules (Recommended) - -**Command**: -```bash -cp specs/WINDSURF-RULES.md .windsurf/rules/project-standards.md -``` - -**Pros**: -- ✅ Native Windsurf integration -- ✅ Auto-loaded for all conversations -- ✅ Can be activated/deactivated via UI -- ✅ Version controlled (gitignore updated) - -**Activation**: Always On - -### Option 2: Global Rules - -**Process**: Windsurf UI → Customizations → Rules → "+ Global" → Paste content - -**Pros**: -- ✅ Available across all workspaces -- ✅ Single source of truth for multi-project teams - -**Activation**: Model Decision or Always On - -### Option 3: Reference Document - -**Status**: Already available at `specs/WINDSURF-RULES.md` - -**Pros**: -- ✅ Version controlled in Git -- ✅ Easy to review and update -- ✅ Team visibility - -**Usage**: Manual @mention in Cascade conversations - ---- - -## Testing Checklist - -### Test 1: Architecture Standards -**Ask Cascade**: "How should I handle route parameters in Next.js 15?" - -**Expected**: Server Components use `await params`, Client Components use `useParams` hook - -### Test 2: Component Creation -**Ask Cascade**: "Create a new card component for displaying user info" - -**Expected**: Search existing components → Check shadcn/ui Card → Recommend reuse/composition - -### Test 3: Branch Readiness -**Ask Cascade**: "Start implementing the notification system feature" - -**Expected**: Present feature spec → Ask "Ready to create the branch and start notification-system development? 🚀" → Wait for confirmation - -### Test 4: Code Quality -**Ask Cascade**: "Should I use CSS Modules or Tailwind for styling?" - -**Expected**: Reference Tailwind v4 + shadcn/ui standards, mention CSS Modules technical debt - -### Test 5: LOC Verification -**Ask Cascade**: "I'm ready to commit my changes" - -**Expected**: Run `git diff --cached --shortstat` and verify actual line counts - ---- - -## Benefits - -### For Cascade AI -✅ Comprehensive project context in single document -✅ Consistent enforcement of project-specific patterns -✅ Automatic error prevention (route parameters, Amplify patterns, styling) -✅ Faster, more accurate responses - -### For Development Team -✅ Standardized code across all features -✅ Automatic onboarding of new developers via AI -✅ Less time correcting AI-generated code -✅ Consistent PR quality - -### For Project -✅ Enforced quality gates prevent technical debt -✅ Faster development velocity with consistent patterns -✅ Maintainable, predictable code structure -✅ Knowledge preservation and accessibility - ---- - -## Maintenance - -### Update Triggers - -**Immediate**: -- Framework version upgrades -- New mandatory protocols -- Breaking pattern changes - -**Periodic** (after sprints): -- Emerging patterns from multiple PRs -- Team retrospective feedback - -### Update Process - -1. Update source specs (`specs/*.md`) -2. Regenerate consolidated rules -3. Copy to `.windsurf/rules/project-standards.md` -4. Test with sample Cascade conversation -5. Notify team of updates - ---- - -## Next Steps - -### 1. Review (5-10 minutes) -- [ ] Read `specs/WINDSURF-RULES.md` completely -- [ ] Validate accuracy and completeness -- [ ] Identify any missing critical standards - -### 2. Choose Integration Path -- [ ] Decide: Workspace rules (recommended) vs Global rules vs Reference -- [ ] Select activation mode: Always On (recommended) vs Model Decision - -### 3. Integrate -- [ ] Copy rules to chosen location -- [ ] Configure activation in Windsurf UI -- [ ] Verify rules appear in Customizations panel - -### 4. Test -- [ ] Run all 5 test scenarios above -- [ ] Start new Cascade conversation -- [ ] Verify automatic enforcement of standards - -### 5. Proceed to Phase 2 -- [ ] Begin next development phase with rules active -- [ ] Monitor effectiveness -- [ ] Gather feedback for future refinements - ---- - -## Files Created - -``` -specs/ -├── WINDSURF-RULES.md # ✅ Consolidated rules (11,566 chars) -├── WINDSURF-RULES-ANALYSIS.md # ✅ Comprehensive analysis -├── WINDSURF-RULES-SETUP.md # ✅ Setup and troubleshooting guide -└── WINDSURF-RULES-SUMMARY.md # ✅ This summary (YOU ARE HERE) - -.gitignore # ✅ Updated to allow project-standards.md -.windsurf/rules/ # ✅ Directory created (ready for rules file) -``` - ---- - -## Success Criteria - -Rules integration is successful when: - -✅ Cascade automatically enforces Server Components first rule -✅ Branch readiness confirmation occurs before feature work -✅ Codebase analysis happens before creating new files -✅ LOC verification runs before commits -✅ Amplify Gen2 patterns are correct (`.guest()`, relationships) -✅ Tailwind v4 + shadcn/ui standards are followed -✅ Quality gates enforced before feature completion -✅ Component reusability protocol is applied - ---- - -## Conclusion - -Successfully consolidated 10 specification documents (3,022 lines) into a single, actionable Windsurf rules document (11,566 characters) that: - -1. ✅ **Follows official Windsurf best practices** from windsurf.com -2. ✅ **Stays under character limit** with 3.6% buffer remaining -3. ✅ **Covers all critical project standards** (architecture, quality, workflow) -4. ✅ **Organized for easy navigation** with semantic XML tags -5. ✅ **Ready for immediate integration** with Windsurf AI - -**Status**: Ready for Phase 2 🚀 - -**Recommended Action**: Review consolidated rules, choose integration path, test with Cascade, then proceed with next feature development. diff --git a/specs/data-table-plan.md b/specs/data-table-plan.md deleted file mode 100644 index 1c8fb3e..0000000 --- a/specs/data-table-plan.md +++ /dev/null @@ -1,43 +0,0 @@ -# Data Table Implementation Plan - -After reviewing the current quiz-results-table component and shadcn UI's data table documentation, here's the plan to transform it into a proper data table using TanStack Table: - -## 1. Structure Changes - -We'll need to: -- Install TanStack Table dependencies -- Create column definitions with proper accessors -- Implement the table instance using `useReactTable` hook -- Replace the current table rendering with TanStack's flexible rendering - -## 2. Features to Add - -1. **Sorting** - - Add sorting functionality to columns (especially for score and date) - - Include visual indicators for sort direction - -2. **Filtering** - - Add a search input to filter quiz results - - Implement filter logic using TanStack's filtering capabilities - -3. **Pagination** - - Add pagination controls for larger datasets - - Show current page information and navigation - -4. **Column Management** - - Add ability to show/hide columns - - Implement through a dropdown menu - -## 3. UI Improvements - -- Add status badges with proper styling for pass/fail -- Improve responsive behavior -- Maintain the "View All Results" functionality - -## 4. Implementation Steps - -1. Install TanStack Table: `npm install @tanstack/react-table` -2. Create a new component structure with column definitions -3. Implement the table instance with core features -4. Add sorting, filtering, and pagination functionality -5. Style the table to match your current design