---
slug: "bl1nk-mood"
source_type: "readme"
source_url: "https://cdn.jsdelivr.net/gh/billlzzz10/bl1nk-mood@main/README.md"
repo: "https://github.com/billlzzz10/bl1nk-mood"
source_file: "README.md"
branch: "main"
---
# **MoodTracker - AI Agent Development System**

## 📋 **AGENTS.md - Complete Agent Instructions**

```markdown
# MoodTracker - AI Agent Collaboration System

## 🎯 AGENT PHILOSOPHY
Agents are **active collaborators**, not just code writers. Each agent has specific capabilities and tools to transform requirements into production-ready code with zero duplication.

## 🤖 AGENT TEAM STRUCTURE

### **Architect Agent** 🏗️
**Capabilities:** Schema design, system architecture, technical decisions
**Tools:** Prisma, Zod, TypeScript compiler, OpenAPI generator
**Skills:**
- Database schema optimization
- API design patterns
- Type system design
- Performance analysis
- Security assessment

**Commands:**
```bash
# Schema analysis
npx prisma studio
npx prisma migrate dev --name <feature>
npm run type-check:strict

# Generate specs
npm run openapi:generate
npm run schema:validate

# Architecture decisions
npm run arch:review <component>
npm run deps:analyze
```

### **Engineer Agent** 👨‍💻
**Capabilities:** Implementation, component development, API creation
**Tools:** Next.js, React, Tailwind, shadcn/ui, Clerk, Lucide React
**Skills:**
- Component composition
- API route implementation
- State management
- Performance optimization
- Testing implementation

**Commands:**
```bash
# Component scaffolding
npm run generate:component <name> --type=<type>
npm run generate:api <endpoint>
npm run generate:hook <name>

# Code quality
npm run lint:fix
npm run format
npm run validate:imports

# Development
npm run dev
npm run build
npm run analyze:bundle
```

### **QA Agent** 🧪
**Capabilities:** Testing, validation, quality assurance
**Tools:** Jest, Testing Library, Playwright, Lighthouse, ESLint
**Skills:**
- Test strategy design
- Coverage analysis
- Performance testing
- Accessibility validation
- Security scanning

**Commands:**
```bash
# Testing
npm test -- --coverage --watchAll=false
npm run test:e2e
npm run test:integration

# Quality gates
npm run quality:gate
npm run accessibility:scan
npm run security:audit

# Reports
npm run report:coverage
npm run report:performance
npm run report:issues
```

### **Workflow Agent** 🔄
**Capabilities:** Automation, CI/CD, deployment, monitoring
**Tools:** GitHub Actions, Vercel CLI, AWS CLI, Cloudflare
**Skills:**
- Pipeline design
- Deployment strategies
- Monitoring setup
- Backup/restore
- Performance monitoring

**Commands:**
```bash
# Deployment
vercel deploy --prod
vercel env pull
npm run deploy:staging

# Monitoring
npm run logs:production
npm run metrics:check
npm run health:check

# Automation
npm run workflow:trigger <workflow>
npm run backup:create
npm run restore:latest
```

## 🛠️ **TOOL CONFIGURATION**

### **CLI Tools Setup**
```bash
# Install all required CLI tools
npm install -g vercel@latest
npm install -g @clerk/clerk-cli
npm install -g wrangler@latest
npm install -g qwen-cli

# Configure agents
export AGENT_ROLE="engineer"
export AGENT_TOOLS="nextjs,react,tailwind,prisma"
export AGENT_VALIDATION="strict"

# Tool configuration files
touch .agentrc
touch .tools.json
```

### **Agent Configuration (.agentrc)**
```json
{
  "agents": {
    "architect": {
      "allowedOperations": [
        "schema:modify",
        "api:design",
        "deps:add",
        "config:update"
      ],
      "validationLevel": "strict",
      "tools": ["prisma", "zod", "typescript", "openapi"]
    },
    "engineer": {
      "allowedOperations": [
        "component:create",
        "api:implement",
        "hook:create",
        "page:create"
      ],
      "validationLevel": "normal",
      "tools": ["nextjs", "react", "tailwind", "clerk", "lucide"]
    }
  },
  "workflows": {
    "beforeCreate": ["check:duplicate", "validate:requirements"],
    "afterCreate": ["run:tests", "update:registry", "generate:docs"]
  }
}
```

## 📁 **FILE GENERATION SYSTEM**

### **Smart Templates**
```typescript
// .devflow/templates/smart-generator.ts
import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';

class SmartGenerator {
  static async generateComponent(componentName: string, options: any = {}) {
    const componentDir = `src/components/${componentName}`;
    
    // Check for duplicates
    if (fs.existsSync(componentDir)) {
      throw new Error(`Component ${componentName} already exists`);
    }
    
    // Create directory structure
    fs.mkdirSync(componentDir, { recursive: true });
    
    // Generate files based on type
    const template = this.getTemplate('component', options.type || 'standard');
    
    // Apply template with variables
    const files = {
      [`${componentName}.tsx`]: this.renderTemplate(template.component, { componentName }),
      [`${componentName}.test.tsx`]: this.renderTemplate(template.test, { componentName }),
      [`${componentName}.stories.tsx`]: this.renderTemplate(template.stories, { componentName }),
      'index.ts': `export { ${componentName} } from './${componentName}';`
    };
    
    // Write files
    Object.entries(files).forEach(([filename, content]) => {
      fs.writeFileSync(path.join(componentDir, filename), content);
    });
    
    // Update component registry
    this.updateComponentRegistry(componentName, options);
    
    // Run validation
    execSync(`npm run validate:component ${componentName}`);
    
    return { success: true, path: componentDir };
  }
  
  static async generateAPI(endpoint: string, method: string = 'GET') {
    // Similar smart generation for API endpoints
  }
}
```

### **Command System**
```bash
#!/bin/bash
# .devflow/scripts/agent-commands.sh

# Smart Generation Commands
agent-generate() {
  case $1 in
    "component")
      npx tsx .devflow/templates/generate-component.ts $2 $3
      ;;
    "api")
      npx tsx .devflow/templates/generate-api.ts $2 $3
      ;;
    "hook")
      npx tsx .devflow/templates/generate-hook.ts $2
      ;;
    "page")
      npx tsx .devflow/templates/generate-page.ts $2
      ;;
    *)
      echo "Unknown generation type: $1"
      ;;
  esac
}

# Validation Commands
agent-validate() {
  case $1 in
    "imports")
      npx tsx .devflow/validators/import-validator.ts
      ;;
    "exports")
      npx tsx .devflow/validators/export-validator.ts
      ;;
    "deps")
      npx tsx .devflow/validators/dependency-validator.ts
      ;;
    *)
      npm run validate:$1
      ;;
  esac
}

# Documentation Commands
agent-docs() {
  case $1 in
    "generate")
      npx typedoc --out docs/api src
      npm run openapi:generate
      ;;
    "update")
      npx tsx .devflow/scripts/update-readme.ts
      ;;
    "check")
      npx tsx .devflow/validators/doc-coverage.ts
      ;;
  esac
}
```

## 🔄 **WORKFLOW AUTOMATION**

### **Automated Quality Pipeline**
```yaml
# .devflow/workflows/auto-quality.yaml
name: Auto Quality Pipeline

triggers:
  - onFileChange: "src/**/*.{ts,tsx}"
  - onTime: "0 9 * * *"  # Daily at 9 AM
  - onCommand: "npm run quality:auto"

jobs:
  code_analysis:
    runner: local
    steps:
      - name: Check for duplicates
        run: npx tsx .devflow/analyzers/duplicate-checker.ts
        
      - name: Validate imports/exports
        run: npx tsx .devflow/analyzers/import-validator.ts
        
      - name: Check component consistency
        run: npx tsx .devflow/analyzers/component-consistency.ts
        
      - name: Generate report
        run: npx tsx .devflow/reporters/quality-report.ts

  dependency_management:
    runner: local
    steps:
      - name: Check for updates
        run: npm outdated
        
      - name: Analyze bundle size impact
        run: npm run analyze:bundle
        
      - name: Security audit
        run: npm audit

  documentation_sync:
    runner: local
    steps:
      - name: Update API docs
        run: npm run docs:api
        
      - name: Update component docs
        run: npm run docs:components
        
      - name: Update README
        run: npx tsx .devflow/scripts/update-readme.ts
```

### **Intelligent Task Management**
```typescript
// .devflow/tasks/task-manager.ts
interface Task {
  id: string;
  title: string;
  description: string;
  requirements: string[];
  dependencies: string[];
  status: 'pending' | 'in-progress' | 'completed' | 'blocked';
  assignedAgent?: string;
  estimatedTime: number;
  actualTime?: number;
  files: string[];
  validationRules: string[];
}

class TaskManager {
  private tasks: Map<string, Task> = new Map();
  
  async createTaskFromRequirement(reqId: string): Promise<Task> {
    // Analyze requirement and create task
    const requirement = await this.getRequirement(reqId);
    
    const task: Task = {
      id: `TASK-${Date.now()}`,
      title: `Implement ${reqId}`,
      description: requirement.description,
      requirements: [reqId],
      dependencies: this.findDependencies(reqId),
      status: 'pending',
      estimatedTime: this.estimateTime(requirement),
      files: this.determineFiles(requirement),
      validationRules: this.getValidationRules(reqId)
    };
    
    this.tasks.set(task.id, task);
    await this.assignToAgent(task);
    
    return task;
  }
  
  async autoAssignTasks() {
    // Automatically assign tasks to available agents
    const pendingTasks = Array.from(this.tasks.values())
      .filter(t => t.status === 'pending');
    
    for (const task of pendingTasks) {
      const bestAgent = await this.findBestAgentForTask(task);
      task.assignedAgent = bestAgent;
      task.status = 'in-progress';
      
      // Notify agent
      await this.notifyAgent(bestAgent, task);
    }
  }
}
```

## 📊 **INTELLIGENT VALIDATION SYSTEM**

### **Real-time Code Validation**
```typescript
// .devflow/validators/smart-validator.ts
import { watch } from 'chokidar';
import { ESLint } from 'eslint';
import * as ts from 'typescript';

class SmartValidator {
  private fileWatcher: any;
  private eslint: ESLint;
  
  constructor() {
    this.eslint = new ESLint({
      useEslintrc: true,
      fix: true
    });
    
    this.setupFileWatcher();
  }
  
  private setupFileWatcher() {
    this.fileWatcher = watch(['src/**/*.{ts,tsx}'], {
      ignored: /(^|[\/\\])\../,
      persistent: true
    });
    
    this.fileWatcher.on('change', async (filePath: string) => {
      await this.validateFile(filePath);
    });
  }
  
  async validateFile(filePath: string) {
    const validations = [
      this.validateImports(filePath),
      this.validateExports(filePath),
      this.validateTypes(filePath),
      this.validateNaming(filePath),
      this.validateStructure(filePath)
    ];
    
    const results = await Promise.all(validations);
    const issues = results.flat();
    
    if (issues.length > 0) {
      await this.suggestFixes(filePath, issues);
      await this.updateRegistry(filePath);
    }
  }
  
  async validateImports(filePath: string): Promise<string[]> {
    const content = await fs.readFile(filePath, 'utf-8');
    const issues: string[] = [];
    
    // Check for duplicate imports
    const importRegex = /import.*from ['"](https://github.com/billlzzz10/bl1nk-mood/blob/HEAD/.*)['"]/g;
    const imports = [...content.matchAll(importRegex)];
    
    const importMap = new Map();
    imports.forEach((match, index) => {
      const importPath = match[1];
      if (importMap.has(importPath)) {
        issues.push(`Duplicate import: ${importPath}`);
      }
      importMap.set(importPath, index);
    });
    
    // Check for unused imports
    const sourceFile = ts.createSourceFile(
      filePath,
      content,
      ts.ScriptTarget.Latest,
      true
    );
    
    // Import analysis logic here
    
    return issues;
  }
}
```

### **Component Registry Auto-update**
```typescript
// .devflow/registry/auto-registry.ts
class AutoRegistry {
  static async scanAndUpdate() {
    const components = await this.scanComponents();
    const apis = await this.scanAPIs();
    const hooks = await this.scanHooks();
    
    // Update registry files
    await this.updateComponentRegistry(components);
    await this.updateAPIRegistry(apis);
    await this.updateHookRegistry(hooks);
    
    // Generate documentation
    await this.generateComponentDocs(components);
    await this.generateAPIDocs(apis);
  }
  
  static async scanComponents(): Promise<ComponentInfo[]> {
    const componentDir = 'src/components';
    const components: ComponentInfo[] = [];
    
    // Recursively scan directory
    const files = await glob(`${componentDir}/**/*.tsx`);
    
    for (const file of files) {
      const content = await fs.readFile(file, 'utf-8');
      const info = this.extractComponentInfo(file, content);
      components.push(info);
    }
    
    return components;
  }
  
  static extractComponentInfo(filePath: string, content: string): ComponentInfo {
    const nameMatch = content.match(/export (?:const|function) (\w+)/);
    const propMatch = content.match(/interface (\w+)Props/);
    const requirementMatches = content.match(/REQ-[A-Z]+-\d{3}/g) || [];
    
    return {
      name: nameMatch?.[1] || path.basename(filePath, '.tsx'),
      filePath,
      props: propMatch?.[1] || 'unknown',
      requirements: requirementMatches,
      exports: this.extractExports(content),
      dependencies: this.extractDependencies(content),
      lastUpdated: new Date()
    };
  }
}
```

## 📈 **REPORTING & ANALYTICS**

### **Automated Reporting System**
```typescript
// .devflow/reporters/smart-reporter.ts
class SmartReporter {
  async generateDailyReport() {
    const date = new Date().toISOString().split('T')[0];
    
    const report = {
      date,
      summary: {
        components: await this.getComponentStats(),
        apis: await this.getAPIStats(),
        tests: await this.getTestStats(),
        issues: await this.getIssueStats()
      },
      quality: {
        coverage: await this.getCoverage(),
        performance: await this.getPerformance(),
        security: await this.getSecurityScore()
      },
      recommendations: await this.generateRecommendations()
    };
    
    // Save report
    const reportPath = `.devflow/reports/daily/${date}.json`;
    await fs.writeFile(reportPath, JSON.stringify(report, null, 2));
    
    // Send to relevant agents
    await this.distributeReport(report);
    
    return report;
  }
  
  async generateRecommendations() {
    const recommendations = [];
    
    // Analyze component duplication
    const duplicates = await this.findDuplicateComponents();
    if (duplicates.length > 0) {
      recommendations.push({
        type: 'optimization',
        priority: 'medium',
        message: `Found ${duplicates.length} duplicate components`,
        action: 'agent-refactor-components'
      });
    }
    
    // Check test coverage
    const coverage = await this.getCoverage();
    if (coverage < 80) {
      recommendations.push({
        type: 'quality',
        priority: 'high',
        message: `Test coverage is ${coverage}% (target: 80%)`,
        action: 'agent-write-tests'
      });
    }
    
    // Check bundle size
    const bundleSize = await this.getBundleSize();
    if (bundleSize > 500) {
      recommendations.push({
        type: 'performance',
        priority: 'medium',
        message: `Bundle size is ${bundleSize}KB`,
        action: 'agent-optimize-bundle'
      });
    }
    
    return recommendations;
  }
}
```

## 🚀 **DEPLOYMENT & PRODUCTION WORKFLOWS**

### **Vercel + Clerk Integration**
```typescript
// .devflow/deploy/vercel-clerk.ts
import { Clerk } from '@clerk/clerk-sdk-node';
import { Vercel } from '@vercel/sdk';

class DeploymentManager {
  private clerk: Clerk;
  private vercel: Vercel;
  
  constructor() {
    this.clerk = new Clerk({ secretKey: process.env.CLERK_SECRET_KEY });
    this.vercel = new Vercel({ token: process.env.VERCEL_TOKEN });
  }
  
  async deployWithAuth() {
    // 1. Build project
    await this.buildProject();
    
    // 2. Sync Clerk environment variables
    await this.syncClerkEnv();
    
    // 3. Deploy to Vercel
    const deployment = await this.vercel.deploy({
      projectId: process.env.VERCEL_PROJECT_ID,
      target: 'production'
    });
    
    // 4. Configure Vercel Blob
    await this.configureBlobStorage();
    
    // 5. Set up monitoring
    await this.setupMonitoring(deployment.url);
    
    return deployment;
  }
  
  async syncClerkEnv() {
    const envVars = {
      NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: process.env.CLERK_PUBLISHABLE_KEY,
      CLERK_SECRET_KEY: process.env.CLERK_SECRET_KEY,
      NEXT_PUBLIC_CLERK_SIGN_IN_URL: '/sign-in',
      NEXT_PUBLIC_CLERK_SIGN_UP_URL: '/sign-up'
    };
    
    // Upload to Vercel
    for (const [key, value] of Object.entries(envVars)) {
      await this.vercel.env.create({
        projectId: process.env.VERCEL_PROJECT_ID,
        key,
        value,
        target: ['production', 'preview', 'development']
      });
    }
  }
  
  async configureBlobStorage() {
    // Configure Vercel Blob for image storage
    await this.vercel.blob.createStore('moodtracker-images');
    
    // Set up CORS and permissions
    await this.vercel.blob.updateStore('moodtracker-images', {
      allowedOrigins: ['https://*.vercel.app', 'http://localhost:3000'],
      maxFileSize: 10 * 1024 * 1024, // 10MB
      allowedMimeTypes: ['image/jpeg', 'image/png', 'image/gif']
    });
  }
}
```

### **Multi-environment Deployment**
```bash
#!/bin/bash
# .devflow/scripts/deploy-smart.sh

# Smart deployment script
deploy() {
  ENVIRONMENT=$1
  BRANCH=$2
  
  case $ENVIRONMENT in
    "development")
      echo "🚀 Deploying to Development..."
      npm run deploy:dev
      ;;
      
    "staging")
      echo "🚀 Deploying to Staging..."
      npm run deploy:staging
      
      # Run staging tests
      npm run test:e2e -- --env=staging
      ;;
      
    "production")
      echo "🚀 Deploying to Production..."
      
      # Pre-deployment checks
      npm run quality:gate
      npm run security:audit
      npm run performance:check
      
      # Deploy
      npm run deploy:prod
      
      # Post-deployment
      npm run health:check
      npm run metrics:report
      ;;
      
    *)
      echo "Unknown environment: $ENVIRONMENT"
      ;;
  esac
}

# Automated rollback
rollback() {
  DEPLOYMENT_ID=$1
  
  echo "🔄 Rolling back deployment $DEPLOYMENT_ID..."
  
  vercel rollback $DEPLOYMENT_ID
  
  # Notify team
  npm run notify -- --type=rollback --deployment=$DEPLOYMENT_ID
  
  # Log incident
  npm run log:incident -- --type=rollback --deployment=$DEPLOYMENT_ID
}
```

## 📚 **DOCUMENTATION AUTO-GENERATION**

### **Auto-documentation System**
```typescript
// .devflow/docs/auto-docgen.ts
class AutoDocGen {
  async generateAllDocs() {
    await this.generateComponentDocs();
    await this.generateAPIDocs();
    await this.generateHookDocs();
    await this.generateUsageExamples();
    await this.updateREADME();
  }
  
  async generateComponentDocs() {
    const components = await this.scanComponents();
    
    const docs = components.map(comp => ({
      name: comp.name,
      description: this.extractDescription(comp.content),
      props: this.extractProps(comp.content),
      examples: this.generateExamples(comp.name, comp.props),
      requirements: comp.requirements,
      usage: this.generateUsage(comp.name, comp.props)
    }));
    
    // Generate markdown
    const markdown = docs.map(doc => this.renderComponentDoc(doc)).join('\n\n');
    
    await fs.writeFile('docs/components.md', markdown);
    
    // Also generate TypeDoc comments
    await this.updateSourceComments(components);
  }
  
  async updateREADME() {
    const readmeTemplate = await fs.readFile('.devflow/templates/README.md', 'utf-8');
    
    const data = {
      projectName: 'MoodTracker',
      version: process.env.npm_package_version,
      lastUpdated: new Date().toISOString(),
      componentCount: await this.countComponents(),
      apiCount: await this.countAPIs(),
      testCoverage: await this.getTestCoverage(),
      qualityScore: await this.getQualityScore()
    };
    
    const readme = this.renderTemplate(readmeTemplate, data);
    
    await fs.writeFile('README.md', readme);
  }
}
```

---

# **README.md**

```markdown
# MoodTracker - Emotion & Habit Tracking App

[![Quality Gate](https://img.shields.io/badge/quality-gate-passing-brightgreen)](https://github.com/yourusername/moodtracker/actions)
[![Coverage](https://img.shields.io/badge/coverage-95%25-brightgreen)](https://github.com/yourusername/moodtracker/actions)
[![TypeScript](https://img.shields.io/badge/types-TypeScript-blue)](https://www.typescriptlang.org/)
[![Next.js](https://img.shields.io/badge/framework-Next.js-black)](https://nextjs.org/)
[![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)

A comprehensive mood and habit tracking application inspired by Daylio, built with modern web technologies and designed for AI agent collaboration.

## 🚀 Quick Start

```bash
# Clone repository
git clone https://github.com/yourusername/moodtracker.git
cd moodtracker

# Setup with AI agent assistance
npm run setup:smart

# Or manual setup
npm install
cp .env.example .env.local
npm run db:setup
npm run dev
```

## 🏗️ Architecture

```
┌─────────────────────────────────────────────────┐
│                 AI Agent System                 │
├─────────────────────────────────────────────────┤
│   🤖 Architect │ 👨‍💻 Engineer │ 🧪 QA Agent    │
└─────────────────────────────────────────────────┘
                         │
┌─────────────────────────────────────────────────┐
│            Development Workflow                  │
│   • Smart Code Generation                        │
│   • Automated Validation                         │
│   • Real-time Documentation                      │
└─────────────────────────────────────────────────┘
                         │
┌─────────────────────────────────────────────────┐
│            Tech Stack                           │
│   • Next.js 16 (App Router)                     │
│   • TypeScript (Strict Mode)                    │
│   • Tailwind CSS + shadcn/ui                    │
│   • Prisma + PostgreSQL                         │
│   • Clerk Authentication                        │
│   • Vercel Blob Storage                         │
└─────────────────────────────────────────────────┘
```

## 🔧 Smart Development

### For AI Agents
```bash
# Agent command system
npm run agent:component --name=Button --type=ui
npm run agent:api --endpoint=/entries --method=POST
npm run agent:hook --name=useMood --type=custom

# Validation & Quality
npm run validate:smart
npm run quality:auto
npm run docs:generate

# Task Management
npm run task:create --requirement=REQ-ENTRY-001
npm run task:assign --agent=engineer
npm run task:complete --id=TASK-001
```

### For Developers
```bash
# Development
npm run dev                    # Start development server
npm run build                  # Build for production
npm run lint                   # Run ESLint
npm run type-check             # TypeScript validation

# Testing
npm test                       # Run all tests
npm run test:e2e               # E2E tests
npm run test:coverage          # Coverage report

# Deployment
npm run deploy:staging         # Deploy to staging
npm run deploy:production      # Deploy to production
npm run rollback               # Rollback last deployment
```

## 🤖 AI Agent Integration

This project is optimized for AI agent collaboration:

### Agent Commands
```bash
# Component Generation
agent-generate component Button --type=ui --variant=primary

# API Generation
agent-generate api /entries --method=POST --auth=required

# Validation
agent-validate imports
agent-validate exports
agent-validate deps

# Documentation
agent-docs generate
agent-docs update
agent-docs check
```

### Smart Features
- **Auto-registry**: Components automatically register themselves
- **Smart validation**: Real-time code quality checking
- **Duplicate prevention**: Detects and prevents code duplication
- **Requirement mapping**: Every piece of code maps to a requirement
- **Auto-documentation**: Documentation generated from code

## 📊 Quality & Metrics

### Quality Gates
```bash
# Run all quality checks
npm run quality:gate

# Individual checks
npm run lint:strict
npm run type-check:strict
npm run test:coverage
npm run bundle:analyze
npm run security:audit
```

### Monitoring
- **Test Coverage**: >90% target
- **TypeScript**: Strict mode enabled
- **Bundle Size**: <500KB optimized
- **Performance**: 90+ Lighthouse score
- **Accessibility**: 100% WCAG 2.1 AA

## 🔐 Authentication & Storage

### Clerk Authentication
```typescript
// Configured automatically
import { ClerkProvider } from '@clerk/nextjs';

export default function App({ children }) {
  return <ClerkProvider>{children}</ClerkProvider>;
}
```

### Vercel Blob Storage
```typescript
// For image uploads
import { put } from '@vercel/blob';

async function uploadImage(file: File) {
  const { url } = await put(file.name, file, {
    access: 'public'
  });
  return url;
}
```

## 🚀 Deployment

### Vercel Deployment
```bash
# Automatic deployment on main branch
git push origin main

# Manual deployment
vercel --prod

# Environment setup
vercel env pull .env.local
```

### Environment Variables
```env
# Authentication
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=your_key
CLERK_SECRET_KEY=your_secret_key

# Database
DATABASE_URL=postgresql://...

# Storage
BLOB_READ_WRITE_TOKEN=your_token

# API Keys
OPENAI_API_KEY=your_key # For AI features
```

## 📈 Performance Optimization

- **Image Optimization**: Automatic with next/image
- **Code Splitting**: Automatic with Next.js
- **Bundle Analysis**: Run `npm run analyze:bundle`
- **Caching Strategy**: Implemented at edge
- **CDN**: Vercel Edge Network

## 🤝 Contributing

### For AI Agents
1. Check for existing implementations before creating new
2. Map all code to requirements (REQ-XXX-XXX)
3. Run validation before submitting
4. Update documentation automatically
5. Register new components in registry

### For Developers
1. Follow TypeScript strict mode
2. Use provided component templates
3. Run quality gates before committing
4. Update tests for new features
5. Document API changes

## 📄 License

MIT License - see [LICENSE](https://github.com/billlzzz10/bl1nk-mood/tree/HEAD/LICENSE) for details.

## 🔗 Links

- [Live Demo](https://moodtracker.vercel.app)
- [API Documentation](https://moodtracker.vercel.app/api-docs)
- [Component Library](https://moodtracker.vercel.app/storybook)
- [GitHub Repository](https://github.com/yourusername/moodtracker)
- [Issue Tracker](https://github.com/yourusername/moodtracker/issues)

---

**Built with ❤️ by AI Agents and Developers**
```

---

# **corconcept.md - System Core Concepts**

```markdown
# MoodTracker - Core Concepts & Architecture

## 🎯 VISION
Build a mood tracking system where AI agents and developers collaborate seamlessly, with zero code duplication and automated quality assurance.

## 🏗️ ARCHITECTURE PRINCIPLES

### 1. Single Source of Truth
```
Zod Schemas → TypeScript Types → Prisma Schema → OpenAPI Spec
     ↓              ↓                ↓              ↓
Validation     Type Safety     Database        API Contract
```

### 2. Agent-First Design
- Every piece of code is agent-discoverable
- Self-documenting code patterns
- Automated registry updates
- Smart code generation

### 3. Zero Duplication
- Centralized component registry
- Smart import/export validation
- Requirement mapping system
- Auto-detection of similar code

### 4. Quality by Default
- Real-time validation
- Automated testing
- Performance monitoring
- Security scanning

## 🔄 SYSTEM WORKFLOWS

### Development Workflow
```
1. Requirement Analysis
   ↓
2. Smart Code Generation
   ↓
3. Automated Validation
   ↓
4. Registry Update
   ↓
5. Documentation Generation
   ↓
6. Quality Gate
```

### Agent Collaboration
```
Architect Agent
    ↓ (Designs schema)
Engineer Agent  
    ↓ (Implements code)
QA Agent
    ↓ (Validates quality)
Workflow Agent
    ↓ (Deploys & Monitors)
```

## 📦 CORE MODULES

### 1. Registry System
- **Component Registry**: Tracks all UI components
- **API Registry**: Tracks all API endpoints
- **Hook Registry**: Tracks all custom hooks
- **Schema Registry**: Tracks all Zod schemas

### 2. Validation System
- **Import/Export Validator**: Ensures proper module boundaries
- **Type Validator**: Ensures type safety
- **Duplicate Detector**: Prevents code duplication
- **Requirement Mapper**: Maps code to requirements

### 3. Generation System
- **Component Generator**: Creates standardized components
- **API Generator**: Creates standardized API routes
- **Hook Generator**: Creates standardized hooks
- **Test Generator**: Creates accompanying tests

### 4. Documentation System
- **Auto-docgen**: Generates documentation from code
- **TypeDoc Integration**: Extracts TypeScript documentation
- **OpenAPI Generation**: Generates API specifications
- **Storybook Integration**: UI component documentation

## 🛠️ TOOL INTEGRATION

### Primary Stack
- **Framework**: Next.js 14 (App Router)
- **Language**: TypeScript (Strict Mode)
- **Styling**: Tailwind CSS + shadcn/ui
- **Database**: Prisma + PostgreSQL
- **Auth**: Clerk
- **Icons**: Lucide React + Lobe Icons
- **Storage**: Vercel Blob
- **Deployment**: Vercel

### AI Tooling
- **Local**: Qwen CLI, OpenCode
- **Cloud**: AWS Q, AWS Bedrock
- **Validation**: Custom validation runners
- **Generation**: Smart template system

### Quality Tools
- **Testing**: Jest, Testing Library, Playwright
- **Linting**: ESLint, TypeScript ESLint
- **Formatting**: Prettier
- **Analysis**: Bundle Analyzer, Lighthouse
- **Security**: npm audit, Snyk

## 🔌 PLUGIN SYSTEM

### Extensible Architecture
```
Core System
    ↓
Plugin Manager
    ↓
┌─────────┬─────────┬─────────┐
│ Auth    │ Storage │ Analytics│
│ Plugin  │ Plugin  │ Plugin  │
└─────────┴─────────┴─────────┘
```

### Available Plugins
1. **Clerk Plugin**: Authentication & user management
2. **Vercel Blob Plugin**: File storage
3. **Analytics Plugin**: Usage tracking
4. **Notification Plugin**: Push notifications
5. **Export Plugin**: Data export functionality

## 📊 MONITORING & ANALYTICS

### Real-time Monitoring
```typescript
interface SystemMetrics {
  performance: {
    responseTime: number;
    bundleSize: number;
    lighthouseScore: number;
  };
  quality: {
    testCoverage: number;
    typeCoverage: number;
    lintScore: number;
  };
  usage: {
    activeUsers: number;
    apiCalls: number;
    storageUsed: number;
  };
}
```

### Agent Performance
- **Task Completion Rate**: % of tasks completed successfully
- **Code Quality Score**: Quality of generated code
- **Efficiency Metrics**: Time taken per task type
- **Collaboration Score**: How well agents work together

## 🚀 SCALING STRATEGY

### Horizontal Scaling
```
Load Balancer
    ↓
┌─────────────────┐
│ App Instances   │
│ (Stateless)     │
└─────────────────┘
    ↓
┌─────────────────┐
│ Database        │
│ (Read Replicas) │
└─────────────────┘
    ↓
┌─────────────────┐
│ Cache Layer     │
│ (Redis)         │
└─────────────────┘
```

### Database Optimization
- **Read/Write Separation**: Primary for writes, replicas for reads
- **Connection Pooling**: Managed by Prisma
- **Query Optimization**: Auto-indexing suggestions
- **Data Archiving**: Old data moved to cold storage

## 🔐 SECURITY MODEL

### Layers of Security
1. **Authentication**: Clerk-based JWT tokens
2. **Authorization**: Role-based access control
3. **Data Encryption**: At-rest and in-transit
4. **Input Validation**: Zod schema validation
5. **Rate Limiting**: API request limiting
6. **Audit Logging**: All actions logged

### Compliance
- **GDPR**: User data rights
- **PDPA**: Thai data protection
- **CCPA**: California privacy
- **SOC 2**: Security controls

## 📈 FUTURE EXTENSIONS

### Planned Features
1. **Mobile Apps**: React Native wrappers
2. **Offline Support**: PWA capabilities
3. **Team Features**: Shared mood boards
4. **Therapist Portal**: Professional features
5. **Wearable Integration**: Health data sync
6. **Voice Input**: Voice-based journaling

### AI Enhancements
1. **Predictive Analytics**: Mood prediction
2. **Pattern Recognition**: Behavior patterns
3. **Personalized Insights**: Custom recommendations
4. **Natural Language**: Journal analysis
5. **Automated Summaries**: Weekly/monthly summaries

---

## 🎯 SUCCESS METRICS

### Technical Metrics
- **Code Quality**: >90% test coverage
- **Performance**: <3s page load, <200ms API response
- **Reliability**: 99.9% uptime
- **Security**: Zero critical vulnerabilities

### Product Metrics
- **User Engagement**: Daily active users >40%
- **Retention**: 30-day retention >30%
- **Satisfaction**: NPS >50
- **Growth**: Month-over-month user growth

### Agent Metrics
- **Efficiency**: Tasks completed per day
- **Accuracy**: Code quality scores
- **Collaboration**: Successful handoffs
- **Innovation**: New patterns discovered

---

**This system represents a new paradigm in software development where AI agents are first-class citizens, working alongside humans to create maintainable, scalable, and high-quality software.**

## 🤝 GETTING HELP

### For AI Agents
- Check `.devflow/agents/` for role-specific guides
- Use `npm run agent:help` for command reference
- Consult registry files for existing implementations

### For Developers
- Check `docs/` for detailed documentation
- Use `npm run help` for command reference
- Join Discord for community support

### Emergency Procedures
- **Build Failure**: Run `npm run doctor`
- **Database Issues**: Run `npm run db:repair`
- **Deployment Issues**: Run `npm run deploy:rollback`
- **Security Incident**: Run `npm run security:incident`
```

---

## 🚀 **Quick Start Commands**

```bash
# 1. Clone and setup
git clone <repo>
cd moodtracker
npm run setup:smart

# 2. Start development
npm run dev

# 3. Open agent dashboard
npm run agent:dashboard

# 4. Deploy when ready
npm run deploy:production
```#   b l 1 n k - m o o d  
 