# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

LockNKey is a quantum-resistant password manager that uses NIST-approved post-quantum cryptography algorithms (CRYSTALS-Kyber, CRYSTALS-Dilithium, SPHINCS+) to protect against future quantum computer threats. The project targets security-conscious developers who want to future-proof their password security.

## Architecture

This is a microservices-based application with the following planned structure:

### Frontend Stack
- **Next.js 14** with App Router
- **shadcn/ui** + TailwindCSS for UI components
- **TypeScript** for type safety
- **Zustand** for state management
- **React Query** for API client
- **Chrome Extension** for browser integration

### Backend Services
- **Python FastAPI**: Quantum encryption service using pqcrypto/liboqs libraries
- **Node.js Express**: Vault and collaboration services
- **Supabase**: Authentication and PostgreSQL database
- **Redis**: Key caching and message queues
- **Kong OSS**: API Gateway

### Quantum Cryptography Implementation
- **Hybrid Encryption**: CRYSTALS-Kyber (KEM) + AES-256-GCM (data encryption)
- **Digital Signatures**: CRYSTALS-Dilithium for integrity verification
- **Hash-based Signatures**: SPHINCS+ as conservative fallback
- **Algorithm Agility**: Runtime switching between quantum algorithms

## Critical Development Protocols

### Docker Container Rebuild Protocol (CRITICAL)

**RULE**: When rebuilding Docker containers after code changes, you MUST follow this complete procedure:

```bash
# Step 1: Stop the running container
docker stop <container-name>

# Step 2: Remove the container
docker rm <container-name>

# Step 3: Remove the image
docker rmi <image-name>

# Step 4: Rebuild without cache
docker-compose build --no-cache <service-name>

# Step 5: Start fresh container
docker-compose up -d <service-name>
```

**Why This Matters**: Docker caches build layers. Simply running `docker-compose build` or `docker restart` may use cached layers containing old compiled code, causing the container to run outdated JavaScript even after TypeScript source files were updated.

**Example for vault-service**:
```bash
docker stop lockkey-vault-service
docker rm lockkey-vault-service
docker rmi backend-vault-service
docker-compose build --no-cache vault-service
docker-compose up -d vault-service
```

**Common Mistake**: Running `npm run build` locally and then `docker restart` will NOT update the container. The container must be rebuilt with fresh image layers.

### Database Management Protocol (CRITICAL)

**RULE**: You are NEVER allowed to reset the database.

**Why This Matters**: Resetting the database will destroy all user data, test data, and development progress. This operation is irreversible and can cause catastrophic data loss.

**Prohibited Actions**:
- Running database reset commands (e.g., `supabase db reset`)
- Dropping and recreating databases
- Truncating all tables
- Deleting migration history

**If database changes are needed**:
- Create new migration files using `apply_migration` tool
- Test migrations on development branches
- Never bypass the migration system

### TDD Approach for Production Code

The project uses Test-Driven Development enhanced with the **1% Solution Methodology** to build production-ready features efficiently:

1. **Test First**: Every feature starts with failing tests
2. **Incremental Development**: Small cycles of red-green-refactor
3. **1% Solution Principle**: **Try 1% solution before 100% solution**
   - When tests fail, try minimal targeted fixes first
   - Avoid complex refactoring when simple changes might work
   - Apply DRY (Don't Repeat Yourself) principle to minimize code duplication
   - Example: Fix UUID conversion vs. rewriting entire endpoints
4. **Production Hardening**: Additional test cycles for:
   - Error scenarios → Robust error handling
   - Performance requirements → Optimizations
   - Security concerns → Protection measures
   - Accessibility needs → WCAG compliance
5. **Continuous Refactoring**: Improve code quality with test safety net
6. **Living Documentation**: Tests document intended behavior
7. **Focus on design mode prototype first** before backend implementation

## MCP-Enhanced Development Workflow

### Required Workflow Process

#### 1. Planning & Documentation
- **Always create detailed plans** before any implementation
- **Document all plans** in:
  - `.claude/task/` directory using format: `YYYY-MM-DD-<feature-name>-plan.md` (for detailed task planning)
  - **Basic Memory (Obsidian vault)** at `~/Documents/Obsidian Vault/plans/` for permanent, searchable storage
- **Use time MCP** to log start and completion of each task
- **Use memory MCP** to create knowledge graph of project decisions
- **Use basic-memory MCP** to:
  - Store architectural decisions in `/decisions/` (ADRs)
  - Create handoff documentation in `/handoffs/`
  - Track milestones in `/milestones/`
  - Document research findings in `/research/`
  - Store security findings in `/security/`
  - Track performance benchmarks in `/performance/`

**CRITICAL: Agent-Specific Documentation Organization**

When working with specialized agents (via Task tool), ALL documentation created by an agent MUST be stored in the agent's own folder within the Obsidian vault to maintain organization:

- **lockkey-qa** (QA Engineer) → `/lockkey/agents/qa/`
  - Test reports, E2E test results, bug findings, verification documents

- **lockkey-backend** (Backend Developer) → `/lockkey/agents/backend/`
  - Implementation notes, API documentation, database migrations, service architecture

- **lockkey-ux** (UX Designer) → `/lockkey/agents/ux/`
  - Design decisions, component documentation, accessibility audits, user flow analysis

- **lockkey-security** (Security Engineer) → `/lockkey/agents/security/`
  - Security findings, vulnerability reports, penetration test results, compliance audits

- **lockkey-pm** (Project Manager) → `/lockkey/agents/pm/`
  - Sprint planning, roadmaps, task breakdowns, team coordination documents

- **lockkey-analyst** (Market Researcher) → `/lockkey/agents/analyst/`
  - Market research, competitive analysis, user research, business intelligence

**Rules**:
1. When invoking an agent, specify the folder in the prompt: "Document your findings in `/lockkey/agents/{agent-name}/`"
2. Each agent folder should use clear naming: `YYYY-MM-DD-{topic}-{type}.md`
3. Cross-reference documents between agent folders using Obsidian wikilinks: `[[../qa/test-report]]`
4. **ALL implementation and test documentation goes in agent folders** (no longer use `/lockkey/testing/` or `/lockkey/implementation/`)
5. General project documentation (architecture, decisions, handoffs) goes in: `/lockkey/decisions/`, `/lockkey/handoffs/`, `/lockkey/milestones/`

**Example Prompt for Agent**:
```
Task for lockkey-qa agent:
"Perform E2E testing of the vault page. Document all findings in /lockkey/agents/qa/ using filename: 2025-10-25-vault-e2e-test-report.md"
```

This ensures documentation is organized by creator/responsibility, making it easy to:
- Find all work done by a specific agent
- Track agent-specific patterns and workflows
- Maintain clear separation of concerns
- Enable better collaboration between agents

#### 2. TDD Implementation Process (Red-Green-Refactor-Production + 1% Solution)
- **BEFORE CODING**: Use context7 MCP to research all libraries and frameworks
- **RED Phase**: Write failing tests that define expected behavior
- **GREEN Phase**: Write minimal code to make tests pass
  - **Apply 1% Solution**: Try minimal fixes first (e.g., parameter conversion, status codes)
  - **Before complex solutions**: Exhaust simple targeted changes
  - **DRY Principle**: Extract common patterns to avoid duplication
- **REFACTOR Phase**: Improve code quality while maintaining passing tests
  - **1% Refactoring**: Small, incremental improvements over large rewrites
  - **Maintain test coverage**: Ensure refactoring doesn't break existing functionality
- **PRODUCTION Phase**: Continue TDD cycles to add:
  - Error handling (write error tests → implement handlers)
  - Performance optimizations (write performance tests → optimize)
  - Security measures (write security tests → implement protections)
  - Accessibility features (write a11y tests → implement features)
  - Edge cases (write edge case tests → handle them)
- **HANDOFF Phase**: MANDATORY task completion documentation for context continuity

#### 3. MCP Server Usage Requirements

**context7 (Library Research)**
- MUST research before using any library or framework
- Check for latest documentation and best practices
- Verify compatibility with quantum cryptography requirements

**memory (Knowledge Graph)**
- **📖 FULL GUIDE**: See `.claude/guides/memory-mcp-query-guide.md` for comprehensive query patterns
- **CRITICAL: Query Optimization Required**
  - ⚠️ **DANGER: NEVER use `read_graph()` routinely** - causes token overflow (25K limit)
  - ✅ **BEST**: Use `open_nodes([names])` when you know entity names (most efficient)
  - ✅ **GOOD**: Use `search_nodes("specific query")` for discovery (filtered results)
  - ⚠️ **RISKY**: Use `read_graph()` only for debugging (returns EVERYTHING)
  - **Token Budget**: Keep memory queries under 5,000 tokens per session
  - **Graph Size**: Keep total entities under 150 to prevent overflow
- **Query Method Hierarchy**: `open_nodes()` > `search_nodes()` > `read_graph()`
- **Quick Examples**:
  ```typescript
  // ✅ Find recent work
  search_nodes("2025-09-29")

  // ✅ Load specific entities
  open_nodes(["LockNKey.Phase.Argon2idMigration", "LockNKey.Component.AuthService"])

  // ✅ Find by category
  search_nodes("LockNKey.Component")

  // ❌ NEVER do this routinely
  read_graph()  // Returns everything - causes overflow!
  ```
- **Naming Convention**: ALL entities MUST use prefix `LockNKey.<category>.<name>`
- **Categories**: Phase, Component, Feature, Decision, Test, Issue, Milestone
- **Best Practices**:
  - Search before creating (avoid duplicates)
  - Include timestamps in observations (enables time-based queries)
  - Delete obsolete entities (keep graph clean)
  - Create relations between tests and implementations
  - Document architectural decisions as observations
  - Check entity dates to ensure working with current information

**time (Activity Logging)**
- Log task start times
- Log milestone completions
- Track time spent on TDD cycles
- Record deployment and testing timestamps

#### 4. Documentation Standards

**Plan Documents** (`.claude/task/`)
- Include: Objective, User Story, Test Strategy, Implementation Approach
- List all tests to be written
- Define success criteria
- Document architectural decisions

**Test Documentation**
- Each test file must have clear descriptions
- Document why each test exists
- Explain what production feature it drives

**Memory MCP Entities**
Example entities to create:
- `LockNKey.Feature.QuantumIndicator`
- `LockNKey.Test.PasswordStrengthChecker`
- `LockNKey.Component.VaultInterface`
- `LockNKey.Decision.UsedNextJS14`
- `LockNKey.Issue.PerformanceOptimization`

#### 5. MANDATORY HANDOFF Documentation (Context Continuity)

**EVERY TASK COMPLETION MUST INCLUDE:**

**A. Update Task Plan Document**
- Add completion summary with timestamp
- Document what's working vs. pending
- List exact files created/modified
- Include test results and coverage

**B. Update MCP Memory Graph**
- Create/update relevant entities with current status
- Add observations about what was accomplished
- Create milestone entities for major completions
- Update relations between components

**C. Document Next Steps**
- **IMMEDIATE NEXT TASK**: Specific actionable next step
- **DEPENDENCIES**: What needs to be done before next task
- **CONTEXT NEEDED**: Key files/concepts next developer must understand
- **VERIFICATION**: How to confirm current work is functional

**D. Handoff Template** (must be added to every completed task):
```markdown
## 🔄 HANDOFF DOCUMENTATION

### ✅ What Was Completed
- [Specific accomplishments with file paths]
- [Test results: X/Y tests passing]
- [Visual verification: screenshots/URLs]

### 🎯 Immediate Next Task
**Task**: [Specific next implementation]
**Files to Create**: [List of files]
**Dependencies**: [What must be read/understood first]
**Success Criteria**: [How to know it's done]

### 🧠 Context for Next Developer
**Key Files to Read First**:
- [File 1]: [Why important]
- [File 2]: [Why important]

**Current State**:
- Development server: [URL if running]
- Test command: [How to run tests]
- Key decisions: [Important architectural choices]

### 🔍 Verification Steps
1. [How to confirm current work functions]
2. [How to run tests]
3. [How to access live demo]
```

**FAILURE TO PROVIDE HANDOFF DOCUMENTATION MEANS TASK IS INCOMPLETE**

### Commands

#### Slash Commands (Available in Claude Code)

**`/orchestrate <task description>`** - Complete task orchestration with context discovery and execution until completion
```bash
/orchestrate "implement password sharing feature"
/orchestrate "fix login bug where users can't sign in"
/orchestrate "add password strength indicator to UI"
```

**Workflow:**
1. Loads agent-orchestrator skill
2. **Invokes Explore agent AND project-manager IN PARALLEL (single message)** to simultaneously:
   - Search Obsidian vault for context
   - Get Linear issues and status
3. **Invokes Plan agent to create detailed execution plan** (after both context agents complete)
4. Executes plan with appropriate specialized agent(s)
5. **Loops until Linear issue is marked "Done" or "Complete"**

**`/status [days]`** - Discover current codebase status from Obsidian vault and Linear issues
```bash
/status        # Default: 7 days lookback
/status 14     # 14 days lookback
/status 30     # 30 days lookback
```

**`/tdd [fe|be] [ultrathink]`** - Execute TDD workflow with planning and context-aware development
```bash
/tdd be                    # Backend TDD workflow
/tdd fe                    # Frontend TDD workflow
/tdd be ultrathink         # Backend TDD with ultrathinking
```

#### Development Commands (to be implemented)
```bash
# Testing (when test framework is set up)
npm test                 # Run all tests
npm test:watch          # Run tests in watch mode
npm test:coverage       # Run tests with coverage
npm test:e2e            # Run Playwright E2E tests

# Quality Checks
ruff check .            # Python linting
npx biome check .       # TypeScript/JavaScript linting
```

## Key Implementation Details

### Quantum Security Features
- **Q-Shield Indicators**: Visual quantum protection status throughout UI
- **Performance Targets**: <100ms encryption/decryption, <300ms auto-fill overhead
- **Security Dashboard**: Quantum readiness scores and threat timeline
- **Migration Tools**: Seamless import from LastPass, 1Password, Bitwarden with quantum re-encryption

### User Experience Design
- **Progressive Disclosure**: Technical details layered appropriately for different user types
- **Familiar Patterns**: Build on established password manager UX conventions
- **Educational Components**: Help users understand quantum threats and benefits
- **Performance Transparency**: Clear feedback during quantum operations

### Security Architecture
- **Zero-Knowledge**: Client-side master password derivation using quantum-resistant algorithms
- **Key Management**: Redis storage with 7-day expiration and monthly rotation
- **Hybrid Protection**: Quantum algorithms for future-proofing + traditional crypto for performance
- **Crypto-Agility**: Ability to upgrade algorithms as standards evolve

## Development Priorities

### Phase 1: Design Prototype (Current)
- Frontend implementation with mock quantum indicators
- TDD implementation of core UI components
- User journey validation through interactive prototypes
- Integration with Supabase Auth

### Phase 2: Quantum Foundation
- Python FastAPI encryption service with real quantum algorithms
- Redis key management implementation
- Performance benchmarking and optimization
- Integration testing between services

### Phase 3: Full Integration
- Browser extension development
- End-to-end password management workflow
- Migration tools for existing password managers
- Security audit and compliance validation

## Important Considerations

### Performance Requirements
- Quantum encryption operations must complete within acceptable user experience bounds
- Background processing for CPU-intensive quantum operations
- Caching strategies for frequently accessed encrypted data

### Security Compliance
- NIST post-quantum cryptography standards compliance
- Zero-knowledge architecture maintenance
- Secure key derivation and storage practices
- Regular security audits and penetration testing

### User Education
- Balance technical transparency with usability
- Progressive onboarding for quantum security concepts
- Clear communication about quantum threat timeline and protection benefits

### TDD & Quality Requirements
- No production code without failing test first
- **1% Solution Methodology**: Always try minimal fixes before complex refactoring
- **DRY Principle**: Eliminate code duplication through reusable components/functions
- Test coverage target: >80% for critical paths
- Performance tests must validate quantum operation targets
- Security tests must cover OWASP top 10
- Accessibility tests must ensure WCAG 2.1 AA compliance

### 1% Solution Examples (Proven Effective)
- **UUID Conversion**: `UUID(string_id)` vs. rewriting endpoints
- **Status Code Fix**: Add explicit `status_code=200` vs. debugging middleware
- **Dual Input Support**: Accept header OR JSON body vs. changing test framework
- **Parameter Type Fixes**: Simple type conversion vs. complex validation rewrite
- **Time Investment**: 30 minutes targeted fixes vs. hours/days of refactoring