├── spec
├── .current-spec
└── 001-basic-todo-app
│ ├── .design-approved
│ ├── .tasks-approved
│ ├── .requirements-approved
│ ├── README.md
│ ├── requirements.md
│ ├── tasks.md
│ └── design.md
├── todo-app
├── src
│ ├── vite-env.d.ts
│ ├── index.css
│ ├── App.tsx
│ ├── main.tsx
│ ├── types
│ │ └── todo.ts
│ ├── utils
│ │ └── validation.ts
│ ├── components
│ │ ├── ErrorMessage.tsx
│ │ ├── TodoList.tsx
│ │ ├── TodoApp.tsx
│ │ ├── TodoForm.tsx
│ │ ├── TodoStats.tsx
│ │ └── TodoItem.tsx
│ ├── services
│ │ └── todoService.ts
│ ├── assets
│ │ └── react.svg
│ └── hooks
│ │ └── useTodos.ts
├── postcss.config.js
├── .prettierrc
├── tsconfig.json
├── vite.config.ts
├── .gitignore
├── tailwind.config.js
├── index.html
├── tsconfig.node.json
├── tsconfig.app.json
├── eslint.config.js
├── package.json
├── public
│ └── vite.svg
└── README.md
├── .claude
└── commands
│ └── spec
│ ├── update-task.md
│ ├── switch.md
│ ├── tasks.md
│ ├── approve.md
│ ├── new.md
│ ├── requirements.md
│ ├── design.md
│ ├── implement.md
│ ├── status.md
│ └── review.md
├── .gitignore
├── templates
├── tasks.md
├── requirements.md
└── design.md
├── CLAUDE.md
└── README.md
/spec/.current-spec:
--------------------------------------------------------------------------------
1 | 001-basic-todo-app
2 |
--------------------------------------------------------------------------------
/spec/001-basic-todo-app/.design-approved:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/spec/001-basic-todo-app/.tasks-approved:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/spec/001-basic-todo-app/.requirements-approved:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/todo-app/src/vite-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/todo-app/postcss.config.js:
--------------------------------------------------------------------------------
1 | export default {
2 | plugins: {
3 | autoprefixer: {},
4 | },
5 | }
--------------------------------------------------------------------------------
/todo-app/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "semi": true,
3 | "trailingComma": "es5",
4 | "singleQuote": true,
5 | "printWidth": 80,
6 | "tabWidth": 2,
7 | "useTabs": false
8 | }
--------------------------------------------------------------------------------
/todo-app/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "files": [],
3 | "references": [
4 | { "path": "./tsconfig.app.json" },
5 | { "path": "./tsconfig.node.json" }
6 | ]
7 | }
8 |
--------------------------------------------------------------------------------
/todo-app/src/index.css:
--------------------------------------------------------------------------------
1 | @import "tailwindcss";
2 |
3 | body {
4 | margin: 0;
5 | font-family: system-ui, -apple-system, 'Segoe UI', 'Roboto', 'Ubuntu', 'Cantarell', 'Noto Sans', sans-serif;
6 | }
7 |
--------------------------------------------------------------------------------
/todo-app/src/App.tsx:
--------------------------------------------------------------------------------
1 | import { TodoApp } from './components/TodoApp'
2 |
3 | function App() {
4 | return (
5 |
6 |
7 |
8 | )
9 | }
10 |
11 | export default App
12 |
--------------------------------------------------------------------------------
/todo-app/vite.config.ts:
--------------------------------------------------------------------------------
1 | import { defineConfig } from 'vite'
2 | import react from '@vitejs/plugin-react'
3 | import tailwindcss from '@tailwindcss/vite'
4 |
5 | // https://vite.dev/config/
6 | export default defineConfig({
7 | plugins: [react(), tailwindcss()],
8 | })
9 |
--------------------------------------------------------------------------------
/todo-app/src/main.tsx:
--------------------------------------------------------------------------------
1 | import { StrictMode } from 'react'
2 | import { createRoot } from 'react-dom/client'
3 | import './index.css'
4 | import App from './App.tsx'
5 |
6 | createRoot(document.getElementById('root')!).render(
7 |
8 |
9 | ,
10 | )
11 |
--------------------------------------------------------------------------------
/todo-app/src/types/todo.ts:
--------------------------------------------------------------------------------
1 | export interface Todo {
2 | id: string;
3 | text: string;
4 | completed: boolean;
5 | createdAt: Date;
6 | updatedAt: Date;
7 | }
8 |
9 | export type CreateTodoInput = Omit;
10 | export type UpdateTodoInput = Partial>;
--------------------------------------------------------------------------------
/todo-app/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | pnpm-debug.log*
8 | lerna-debug.log*
9 |
10 | node_modules
11 | dist
12 | dist-ssr
13 | *.local
14 |
15 | # Editor directories and files
16 | .vscode/*
17 | !.vscode/extensions.json
18 | .idea
19 | .DS_Store
20 | *.suo
21 | *.ntvs*
22 | *.njsproj
23 | *.sln
24 | *.sw?
25 |
--------------------------------------------------------------------------------
/todo-app/tailwind.config.js:
--------------------------------------------------------------------------------
1 | /** @type {import('tailwindcss').Config} */
2 | export default {
3 | content: [
4 | "./index.html",
5 | "./src/**/*.{js,ts,jsx,tsx}",
6 | ],
7 | theme: {
8 | extend: {
9 | colors: {
10 | primary: '#1D2130',
11 | success: '#28a745',
12 | danger: '#dc3545',
13 | }
14 | },
15 | },
16 | plugins: [],
17 | }
--------------------------------------------------------------------------------
/spec/001-basic-todo-app/README.md:
--------------------------------------------------------------------------------
1 | # Specification: Basic Todo App
2 |
3 | **Created:** July 21, 2025
4 | **Status:** Implementation Phase
5 |
6 | ## Current Phase Status
7 |
8 | - [x] Requirements Phase ✓
9 | - [x] Design Phase ✓
10 | - [x] Tasks Phase ✓
11 | - [ ] Implementation Phase
12 |
13 | ## Next Steps
14 |
15 | Use `/spec:implement` to begin the implementation phase for this basic todo app specification.
--------------------------------------------------------------------------------
/.claude/commands/spec/update-task.md:
--------------------------------------------------------------------------------
1 | ---
2 | allowed-tools: Bash(cat:*), Bash(grep:*), Write
3 | description: Mark a task as complete
4 | argument-hint:
5 | ---
6 |
7 | ## Current Tasks
8 |
9 | !`cat spec/$(cat spec/.current-spec)/tasks.md | grep -n "^- \[" | head -20`
10 |
11 | ## Your Task
12 |
13 | Update the task status for: "$ARGUMENTS"
14 |
15 | 1. Find the matching task in tasks.md
16 | 2. Change `- [ ]` to `- [x]` for that task
17 | 3. Show updated progress statistics
18 | 4. Suggest next task to work on
19 |
20 | Use the Write tool to update the file.
--------------------------------------------------------------------------------
/todo-app/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | Todo App
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/.claude/commands/spec/switch.md:
--------------------------------------------------------------------------------
1 | ---
2 | allowed-tools: Bash(ls:*), Bash(echo:*), Bash(test:*)
3 | description: Switch to a different specification
4 | argument-hint:
5 | ---
6 |
7 | ## Available Specifications
8 |
9 | !`ls -d spec/*/ 2>/dev/null | sort`
10 |
11 | ## Your Task
12 |
13 | Switch the active specification to: $ARGUMENTS
14 |
15 | 1. Verify the spec directory exists
16 | 2. Update `spec/.current-spec` with the new spec directory name ([ID]-$ARGUMENTS)
17 | 3. Show the status of the newly active spec
18 | 4. Display next recommended action
19 |
20 | If no argument provided, list all available specs.
--------------------------------------------------------------------------------
/todo-app/tsconfig.node.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
4 | "target": "ES2023",
5 | "lib": ["ES2023"],
6 | "module": "ESNext",
7 | "skipLibCheck": true,
8 |
9 | /* Bundler mode */
10 | "moduleResolution": "bundler",
11 | "allowImportingTsExtensions": true,
12 | "verbatimModuleSyntax": true,
13 | "moduleDetection": "force",
14 | "noEmit": true,
15 |
16 | /* Linting */
17 | "strict": true,
18 | "noUnusedLocals": true,
19 | "noUnusedParameters": true,
20 | "erasableSyntaxOnly": true,
21 | "noFallthroughCasesInSwitch": true,
22 | "noUncheckedSideEffectImports": true
23 | },
24 | "include": ["vite.config.ts"]
25 | }
26 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Dependencies
2 | node_modules/
3 | npm-debug.log*
4 | yarn-debug.log*
5 | yarn-error.log*
6 | pnpm-debug.log*
7 |
8 | # Build outputs
9 | dist/
10 | build/
11 | *.tsbuildinfo
12 |
13 | # Environment variables
14 | .env
15 | .env.local
16 | .env.development.local
17 | .env.test.local
18 | .env.production.local
19 |
20 | # IDE and editor files
21 | .vscode/
22 | .idea/
23 | *.swp
24 | *.swo
25 | *~
26 |
27 | # OS generated files
28 | .DS_Store
29 | .DS_Store?
30 | ._*
31 | .Spotlight-V100
32 | .Trashes
33 | ehthumbs.db
34 | Thumbs.db
35 |
36 | # Logs
37 | logs/
38 | *.log
39 |
40 | # Runtime data
41 | pids/
42 | *.pid
43 | *.seed
44 | *.pid.lock
45 |
46 | # Coverage directory used by tools like istanbul
47 | coverage/
48 | *.lcov
49 |
50 | # Temporary folders
51 | tmp/
52 | temp/
53 |
--------------------------------------------------------------------------------
/.claude/commands/spec/tasks.md:
--------------------------------------------------------------------------------
1 | ---
2 | allowed-tools: Bash(cat:*), Bash(test:*), Write
3 | description: Create implementation task list
4 | ---
5 |
6 | ## Context
7 |
8 | Current spec: !`cat spec/.current-spec 2>/dev/null`
9 | Design approved: !`test -f spec/$(cat spec/.current-spec)/.design-approved && echo "Yes" || echo "No"`
10 |
11 | ## Your Task
12 |
13 | 1. Verify design is approved
14 | 2. Create tasks.md with:
15 | - Overview with time estimates
16 | - Phase breakdown (Foundation, Core, Testing, Deployment)
17 | - Detailed task list with checkboxes
18 | - Task dependencies
19 | - Risk mitigation tasks
20 | 3. Each task should be specific and actionable
21 | 4. Use markdown checkboxes: `- [ ] Task description`
22 |
23 | Organize tasks to enable incremental development and testing.
--------------------------------------------------------------------------------
/.claude/commands/spec/approve.md:
--------------------------------------------------------------------------------
1 | ---
2 | allowed-tools: Bash(touch:*), Bash(test:*), Bash(cat:*)
3 | description: Approve a specification phase
4 | argument-hint: requirements|design|tasks
5 | ---
6 |
7 | ## Context
8 |
9 | Current spec: !`cat spec/.current-spec 2>/dev/null`
10 | Spec directory: !`ls -la spec/$(cat spec/.current-spec)/ 2>/dev/null`
11 |
12 | ## Your Task
13 |
14 | For the phase "$ARGUMENTS":
15 |
16 | 1. Verify the phase file exists (requirements.md, design.md, or tasks.md)
17 | 2. Create approval marker file: `.${ARGUMENTS}-approved`
18 | 3. Inform user about next steps:
19 | - After requirements → design phase
20 | - After design → tasks phase
21 | - After tasks → implementation
22 | 4. If invalid phase name, show valid options
23 |
24 | Use touch command to create approval markers.
--------------------------------------------------------------------------------
/todo-app/tsconfig.app.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
4 | "target": "ES2022",
5 | "useDefineForClassFields": true,
6 | "lib": ["ES2022", "DOM", "DOM.Iterable"],
7 | "module": "ESNext",
8 | "skipLibCheck": true,
9 |
10 | /* Bundler mode */
11 | "moduleResolution": "bundler",
12 | "allowImportingTsExtensions": true,
13 | "verbatimModuleSyntax": true,
14 | "moduleDetection": "force",
15 | "noEmit": true,
16 | "jsx": "react-jsx",
17 |
18 | /* Linting */
19 | "strict": true,
20 | "noUnusedLocals": true,
21 | "noUnusedParameters": true,
22 | "erasableSyntaxOnly": true,
23 | "noFallthroughCasesInSwitch": true,
24 | "noUncheckedSideEffectImports": true
25 | },
26 | "include": ["src"]
27 | }
28 |
--------------------------------------------------------------------------------
/.claude/commands/spec/new.md:
--------------------------------------------------------------------------------
1 | ---
2 | allowed-tools: Bash(mkdir:*), Bash(echo:*), Bash(date:*), Bash(ls:*)
3 | description: Create a new feature specification
4 | argument-hint:
5 | ---
6 |
7 | ## Current Spec Status
8 |
9 | !`ls -la spec/ 2>/dev/null | grep "^d" | wc -l | xargs -I {} echo "Total specs: {}"`
10 |
11 | ## Your Task
12 |
13 | Create a new specification directory for the feature: $ARGUMENTS
14 |
15 | 1. Determine the next ID number (format: 001, 002, etc.)
16 | 2. Create directory: `spec/[ID]-$ARGUMENTS/`
17 | 3. Update `spec/.current-spec` with the new spec directory name ([ID]-$ARGUMENTS)
18 | 4. Create a README.md in the new directory with:
19 | - Feature name
20 | - Creation date
21 | - Initial status checklist
22 | 5. Inform the user about next steps
23 |
24 | Use the Bash tool to create directories and files as needed.
--------------------------------------------------------------------------------
/todo-app/eslint.config.js:
--------------------------------------------------------------------------------
1 | import js from '@eslint/js'
2 | import globals from 'globals'
3 | import reactHooks from 'eslint-plugin-react-hooks'
4 | import reactRefresh from 'eslint-plugin-react-refresh'
5 | import tseslint from 'typescript-eslint'
6 | import { globalIgnores } from 'eslint/config'
7 |
8 | export default tseslint.config([
9 | globalIgnores(['dist']),
10 | {
11 | files: ['**/*.{ts,tsx}'],
12 | extends: [
13 | js.configs.recommended,
14 | tseslint.configs.recommended,
15 | reactHooks.configs['recommended-latest'],
16 | reactRefresh.configs.vite,
17 | ],
18 | languageOptions: {
19 | ecmaVersion: 2020,
20 | globals: globals.browser,
21 | },
22 | rules: {
23 | '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
24 | 'prefer-const': 'error',
25 | 'no-var': 'error',
26 | },
27 | },
28 | ])
29 |
--------------------------------------------------------------------------------
/.claude/commands/spec/requirements.md:
--------------------------------------------------------------------------------
1 | ---
2 | allowed-tools: Bash(cat:*), Bash(test:*), Bash(touch:*), Write
3 | description: Create or review requirements specification
4 | ---
5 |
6 | ## Context
7 |
8 | Current spec: !`cat spec/.current-spec 2>/dev/null || echo "No active spec"`
9 | Spec directory contents: !`ls -la spec/$(cat spec/.current-spec 2>/dev/null)/ 2>/dev/null || echo "Spec not found"`
10 |
11 | ## Your Task
12 |
13 | For the current active specification:
14 |
15 | 1. Check if requirements.md exists
16 | 2. If not, create a comprehensive requirements.md with:
17 | - Feature overview
18 | - User stories with acceptance criteria
19 | - Functional requirements (P0, P1, P2)
20 | - Non-functional requirements
21 | - Constraints and assumptions
22 | - Out of scope items
23 | - Success metrics
24 | 3. If it exists, display current content and suggest improvements
25 | 4. Remind user to use `/spec:approve requirements` when ready
26 |
27 | Use the Write tool to create/update the requirements.md file.
--------------------------------------------------------------------------------
/.claude/commands/spec/design.md:
--------------------------------------------------------------------------------
1 | ---
2 | allowed-tools: Bash(cat:*), Bash(test:*), Bash(ls:*), Write
3 | description: Create technical design specification
4 | ---
5 |
6 | ## Context
7 |
8 | Current spec: !`cat spec/.current-spec 2>/dev/null`
9 | Requirements approved: !`test -f spec/$(cat spec/.current-spec)/.requirements-approved && echo "Yes" || echo "No"`
10 | Current directory: !`ls -la spec/$(cat spec/.current-spec)/ 2>/dev/null`
11 |
12 | ## Your Task
13 |
14 | 1. Verify requirements are approved (look for .requirements-approved file)
15 | 2. If not approved, inform user to complete requirements first
16 | 3. If approved, create/update design.md with:
17 | - Architecture overview (with diagrams)
18 | - Technology stack decisions
19 | - Data model and schema
20 | - API design
21 | - Security considerations
22 | - Performance considerations
23 | - Deployment architecture
24 | - Technical risks and mitigations
25 | 4. Use ASCII art or mermaid diagrams where helpful
26 |
27 | Use the Write tool to create the design document.
--------------------------------------------------------------------------------
/.claude/commands/spec/implement.md:
--------------------------------------------------------------------------------
1 | ---
2 | allowed-tools: Bash(cat:*), Bash(test:*), Bash(grep:*), Write
3 | description: Start implementation from approved tasks
4 | argument-hint: [phase-number]
5 | ---
6 |
7 | ## Context
8 |
9 | Current spec: !`cat spec/.current-spec 2>/dev/null`
10 | Tasks approved: !`test -f spec/$(cat spec/.current-spec)/.tasks-approved && echo "Yes" || echo "No"`
11 |
12 | ## Current Tasks
13 |
14 | !`if [ -f "spec/$(cat spec/.current-spec)/tasks.md" ]; then
15 | echo "=== Phase Overview ==="
16 | grep "^## Phase" "spec/$(cat spec/.current-spec)/tasks.md"
17 | echo ""
18 | echo "=== Incomplete Tasks ==="
19 | grep "^- \[ \]" "spec/$(cat spec/.current-spec)/tasks.md" | head -20
20 | fi`
21 |
22 | ## Your Task
23 |
24 | 1. Verify all phases are approved
25 | 2. If phase number provided ($ARGUMENTS), focus on that phase
26 | 3. Display current incomplete tasks
27 | 4. Create an implementation session log
28 | 5. Guide user to:
29 | - Work on tasks sequentially
30 | - Update task checkboxes as completed
31 | - Commit changes regularly
32 | 6. Remind about using Write tool to update tasks.md
33 |
34 | Start implementing based on the task list!
--------------------------------------------------------------------------------
/.claude/commands/spec/status.md:
--------------------------------------------------------------------------------
1 | ---
2 | allowed-tools: Bash(ls:*), Bash(cat:*), Bash(grep:*), Bash(test:*), Bash(find:*)
3 | description: Show all specifications and their status
4 | ---
5 |
6 | ## Gather Status Information
7 |
8 | All specs: !`ls -d spec/*/ 2>/dev/null | sort`
9 | Current spec: !`cat spec/.current-spec 2>/dev/null || echo "None"`
10 |
11 | For each spec directory, check:
12 | !`for dir in spec/*/; do
13 | if [ -d "$dir" ]; then
14 | echo "=== $dir ==="
15 | ls -la "$dir" | grep -E "(requirements|design|tasks)\.md|\..*-approved"
16 | if [ -f "$dir/tasks.md" ]; then
17 | echo "Task progress:"
18 | grep "^- \[" "$dir/tasks.md" | head -5
19 | echo "Total tasks: $(grep -c "^- \[" "$dir/tasks.md" 2>/dev/null || echo 0)"
20 | echo "Completed: $(grep -c "^- \[x\]" "$dir/tasks.md" 2>/dev/null || echo 0)"
21 | fi
22 | echo ""
23 | fi
24 | done`
25 |
26 | ## Your Task
27 |
28 | Present a clear status report showing:
29 | 1. All specifications with their IDs and names
30 | 2. Current active spec (highlighted)
31 | 3. Phase completion status for each spec
32 | 4. Task progress percentage if applicable
33 | 5. Recommended next action for active spec
--------------------------------------------------------------------------------
/todo-app/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "todo-app",
3 | "private": true,
4 | "version": "0.0.0",
5 | "type": "module",
6 | "scripts": {
7 | "dev": "vite",
8 | "build": "tsc -b && vite build",
9 | "lint": "eslint .",
10 | "preview": "vite preview"
11 | },
12 | "dependencies": {
13 | "@tailwindcss/vite": "^4.1.11",
14 | "autoprefixer": "^10.4.21",
15 | "postcss": "^8.5.6",
16 | "react": "^19.1.0",
17 | "react-dom": "^19.1.0"
18 | },
19 | "devDependencies": {
20 | "@eslint/js": "^9.30.1",
21 | "@tailwindcss/postcss": "^4.1.11",
22 | "@types/node": "^24.0.15",
23 | "@types/react": "^19.1.8",
24 | "@types/react-dom": "^19.1.6",
25 | "@typescript-eslint/eslint-plugin": "^8.37.0",
26 | "@typescript-eslint/parser": "^8.37.0",
27 | "@vitejs/plugin-react": "^4.6.0",
28 | "eslint": "^9.31.0",
29 | "eslint-config-prettier": "^10.1.8",
30 | "eslint-plugin-prettier": "^5.5.3",
31 | "eslint-plugin-react": "^7.37.5",
32 | "eslint-plugin-react-hooks": "^5.2.0",
33 | "eslint-plugin-react-refresh": "^0.4.20",
34 | "globals": "^16.3.0",
35 | "prettier": "^3.6.2",
36 | "tailwindcss": "^4.1.11",
37 | "typescript": "~5.8.3",
38 | "typescript-eslint": "^8.35.1",
39 | "vite": "^7.0.4"
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/todo-app/public/vite.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/todo-app/src/utils/validation.ts:
--------------------------------------------------------------------------------
1 | export function sanitizeInput(input: string): string {
2 | return input
3 | .trim()
4 | .slice(0, 500) // Max length limit
5 | .replace(/[<>]/g, ''); // Basic XSS prevention
6 | }
7 |
8 | export function validateTodoText(text: string): { isValid: boolean; error?: string } {
9 | const sanitized = sanitizeInput(text);
10 |
11 | if (sanitized.length === 0) {
12 | return { isValid: false, error: 'Todo text cannot be empty' };
13 | }
14 |
15 | if (sanitized.length > 500) {
16 | return { isValid: false, error: 'Todo text cannot exceed 500 characters' };
17 | }
18 |
19 | return { isValid: true };
20 | }
21 |
22 | export function isStorageAvailable(): boolean {
23 | try {
24 | const testKey = '__storage_test__';
25 | localStorage.setItem(testKey, 'test');
26 | localStorage.removeItem(testKey);
27 | return true;
28 | } catch {
29 | return false;
30 | }
31 | }
32 |
33 | export function getStorageUsage(): { used: number; total: number; percentage: number } {
34 | if (!isStorageAvailable()) {
35 | return { used: 0, total: 0, percentage: 0 };
36 | }
37 |
38 | let used = 0;
39 | for (const key in localStorage) {
40 | if (Object.prototype.hasOwnProperty.call(localStorage, key)) {
41 | used += localStorage[key].length + key.length;
42 | }
43 | }
44 |
45 | // Rough estimate of localStorage limit (usually 5-10MB)
46 | const total = 5 * 1024 * 1024; // 5MB
47 | const percentage = (used / total) * 100;
48 |
49 | return { used, total, percentage };
50 | }
--------------------------------------------------------------------------------
/templates/tasks.md:
--------------------------------------------------------------------------------
1 | # Task List
2 |
3 | ## Overview
4 | [Brief summary of implementation phases and priorities]
5 |
6 | ## Phase 1: Foundation
7 | ### Setup & Configuration
8 | - [ ] [Task description] (Est: Xh)
9 | - [ ] [Task description] (Est: Xh)
10 |
11 | ### Core Infrastructure
12 | - [ ] [Task description] (Est: Xh)
13 | - [ ] [Task description] (Est: Xh)
14 |
15 | ## Phase 2: Core Features
16 | ### [Feature Group 1]
17 | - [ ] [Task description] (Est: Xh)
18 | - [ ] [Task description] (Est: Xh)
19 |
20 | ### [Feature Group 2]
21 | - [ ] [Task description] (Est: Xh)
22 | - [ ] [Task description] (Est: Xh)
23 |
24 | ## Phase 3: Integration & Testing
25 | ### Integration Tasks
26 | - [ ] [Task description] (Est: Xh)
27 | - [ ] [Task description] (Est: Xh)
28 |
29 | ### Testing Tasks
30 | - [ ] Write unit tests for [component] (Est: Xh)
31 | - [ ] Write integration tests for [feature] (Est: Xh)
32 | - [ ] Performance testing (Est: Xh)
33 |
34 | ## Phase 4: Polish & Documentation
35 | ### UI/UX Refinements
36 | - [ ] [Task description] (Est: Xh)
37 | - [ ] [Task description] (Est: Xh)
38 |
39 | ### Documentation
40 | - [ ] API documentation (Est: Xh)
41 | - [ ] User guide (Est: Xh)
42 | - [ ] Developer documentation (Est: Xh)
43 |
44 | ## Task Dependencies
45 | - Task X depends on Task Y
46 | - Task A must be completed before Task B
47 |
48 | ## Critical Path
49 | [Tasks that must be completed in sequence for project success]
50 |
51 | ## Risk Mitigation Tasks
52 | - [ ] [Backup plan task] (Est: Xh)
53 | - [ ] [Contingency task] (Est: Xh)
54 |
55 | ## Notes
56 | - Total estimated time: [sum of all tasks]
57 | - Priority tasks marked with 🔴
58 | - Optional enhancements marked with 🟢
59 | - Technical debt items marked with 🟡
--------------------------------------------------------------------------------
/templates/requirements.md:
--------------------------------------------------------------------------------
1 | # Requirements Document
2 |
3 | ## Overview
4 | [Brief description of what this feature/project aims to accomplish]
5 |
6 | ## Business Requirements
7 | [Why is this needed? What business value does it provide?]
8 |
9 | ## Functional Requirements
10 |
11 | ### Core Features
12 | 1. **[Feature Name]**
13 | - [Detailed description]
14 | - [Expected behavior]
15 | - [User interactions]
16 |
17 | 2. **[Feature Name]**
18 | - [Detailed description]
19 | - [Expected behavior]
20 | - [User interactions]
21 |
22 | ### User Stories
23 | - As a [user type], I want to [action] so that [benefit]
24 | - As a [user type], I want to [action] so that [benefit]
25 |
26 | ## Non-Functional Requirements
27 |
28 | ### Performance
29 | - [Response time requirements]
30 | - [Throughput requirements]
31 | - [Resource usage limits]
32 |
33 | ### Security
34 | - [Authentication requirements]
35 | - [Authorization requirements]
36 | - [Data protection requirements]
37 |
38 | ### Usability
39 | - [User interface requirements]
40 | - [Accessibility requirements]
41 | - [Documentation requirements]
42 |
43 | ## Technical Constraints
44 | - [Platform requirements]
45 | - [Technology stack limitations]
46 | - [Integration requirements]
47 |
48 | ## Acceptance Criteria
49 | 1. [Specific, measurable criteria for feature completion]
50 | 2. [Test scenarios that must pass]
51 | 3. [Performance benchmarks to meet]
52 |
53 | ## Out of Scope
54 | - [Features or requirements explicitly not included]
55 | - [Future considerations]
56 |
57 | ## Dependencies
58 | - [External systems]
59 | - [Third-party services]
60 | - [Internal components]
61 |
62 | ## Risks and Assumptions
63 | ### Risks
64 | - [Potential issues and mitigation strategies]
65 |
66 | ### Assumptions
67 | - [Assumptions made during requirements gathering]
--------------------------------------------------------------------------------
/todo-app/src/components/ErrorMessage.tsx:
--------------------------------------------------------------------------------
1 | interface ErrorMessageProps {
2 | message: string;
3 | onDismiss: () => void;
4 | }
5 |
6 | export function ErrorMessage({ message, onDismiss }: ErrorMessageProps) {
7 | return (
8 |
9 |
10 |
20 |
29 |
30 |
31 | );
32 | }
--------------------------------------------------------------------------------
/todo-app/README.md:
--------------------------------------------------------------------------------
1 | # Todo App
2 |
3 | A modern React TypeScript todo application built with Vite and styled with Tailwind CSS.
4 |
5 | ## Features
6 |
7 | - Add, edit, and delete todo items
8 | - Mark todos as complete/incomplete
9 | - Filter todos by status (all, active, completed)
10 | - Clear completed todos
11 | - Responsive design with Tailwind CSS
12 |
13 | ## Tech Stack
14 |
15 | - React 19
16 | - TypeScript
17 | - Vite
18 | - Tailwind CSS
19 | - ESLint & Prettier
20 |
21 | ## Project Setup
22 |
23 | ### Prerequisites
24 |
25 | - Node.js (version 18 or higher)
26 | - npm or yarn
27 |
28 | ### Installation
29 |
30 | 1. Clone the repository and navigate to the project directory:
31 | ```bash
32 | cd todo-app
33 | ```
34 |
35 | 2. Install dependencies:
36 | ```bash
37 | npm install
38 | ```
39 |
40 | ## Development
41 |
42 | ### Start Development Server
43 |
44 | Run the development server with hot reload:
45 |
46 | ```bash
47 | npm run dev
48 | ```
49 |
50 | The app will be available at `http://localhost:5173`
51 |
52 | ### Linting
53 |
54 | Run ESLint to check for code issues:
55 |
56 | ```bash
57 | npm run lint
58 | ```
59 |
60 | ## Build
61 |
62 | ### Production Build
63 |
64 | Create an optimized production build:
65 |
66 | ```bash
67 | npm run build
68 | ```
69 |
70 | The build output will be in the `dist/` directory.
71 |
72 | ### Preview Production Build
73 |
74 | Preview the production build locally:
75 |
76 | ```bash
77 | npm run preview
78 | ```
79 |
80 | ## Available Scripts
81 |
82 | - `npm run dev` - Start development server
83 | - `npm run build` - Build for production
84 | - `npm run lint` - Run ESLint
85 | - `npm run preview` - Preview production build
86 |
87 | ## Project Structure
88 |
89 | ```
90 | src/
91 | ├── components/
92 | │ └── TodoApp.tsx # Main todo application component
93 | ├── App.tsx # Root application component
94 | ├── index.css # Global styles and Tailwind imports
95 | └── main.tsx # Application entry point
96 | ```
97 |
--------------------------------------------------------------------------------
/todo-app/src/components/TodoList.tsx:
--------------------------------------------------------------------------------
1 | import type { Todo, UpdateTodoInput } from '../types/todo';
2 | import { TodoItem } from './TodoItem';
3 |
4 | interface TodoListProps {
5 | todos: Todo[];
6 | onToggleTodo: (id: string) => Promise;
7 | onUpdateTodo: (id: string, updates: UpdateTodoInput) => Promise;
8 | onDeleteTodo: (id: string) => Promise;
9 | }
10 |
11 | export function TodoList({ todos, onToggleTodo, onUpdateTodo, onDeleteTodo }: TodoListProps) {
12 | if (todos.length === 0) {
13 | return (
14 |
15 |
20 |
No todos yet
21 |
Add your first todo above to get started!
22 |
23 | );
24 | }
25 |
26 | // Sort todos: pending first, then completed, within each group sort by creation date
27 | const sortedTodos = [...todos].sort((a, b) => {
28 | // First, sort by completion status (pending first)
29 | if (a.completed !== b.completed) {
30 | return a.completed ? 1 : -1;
31 | }
32 |
33 | // Then sort by creation date (newest first for pending, oldest first for completed)
34 | if (!a.completed) {
35 | return b.createdAt.getTime() - a.createdAt.getTime();
36 | } else {
37 | return a.createdAt.getTime() - b.createdAt.getTime();
38 | }
39 | });
40 |
41 | return (
42 |
43 | {sortedTodos.map((todo) => (
44 |
51 | ))}
52 |
53 | );
54 | }
--------------------------------------------------------------------------------
/templates/design.md:
--------------------------------------------------------------------------------
1 | # Design Document
2 |
3 | ## Overview
4 | [High-level description of the technical approach]
5 |
6 | ## Architecture
7 |
8 | ### System Architecture
9 | [Diagram or description of overall system architecture]
10 |
11 | ### Component Design
12 | 1. **[Component Name]**
13 | - Purpose: [What this component does]
14 | - Responsibilities: [Key responsibilities]
15 | - Interfaces: [How it interacts with other components]
16 |
17 | 2. **[Component Name]**
18 | - Purpose: [What this component does]
19 | - Responsibilities: [Key responsibilities]
20 | - Interfaces: [How it interacts with other components]
21 |
22 | ## Data Design
23 |
24 | ### Data Models
25 | ```
26 | [Model Name]
27 | - field1: type (description)
28 | - field2: type (description)
29 | - field3: type (description)
30 | ```
31 |
32 | ### Database Schema
33 | [Tables, relationships, indexes]
34 |
35 | ### Data Flow
36 | [How data moves through the system]
37 |
38 | ## API Design
39 |
40 | ### Endpoints
41 | 1. **[HTTP Method] /path**
42 | - Purpose: [What this endpoint does]
43 | - Request: [Request format/parameters]
44 | - Response: [Response format]
45 | - Errors: [Possible error responses]
46 |
47 | ### Authentication & Authorization
48 | [How APIs are secured]
49 |
50 | ## User Interface Design
51 |
52 | ### Views/Pages
53 | 1. **[View Name]**
54 | - Purpose: [What this view shows]
55 | - Components: [UI components used]
56 | - User Actions: [What users can do]
57 |
58 | ### User Flow
59 | [Step-by-step user journey through the feature]
60 |
61 | ## Technical Decisions
62 |
63 | ### Technology Stack
64 | - [Language/Framework choices and rationale]
65 | - [Library selections and reasons]
66 | - [Tool choices and justification]
67 |
68 | ### Design Patterns
69 | - [Patterns used and why]
70 | - [Architectural patterns applied]
71 |
72 | ## Security Considerations
73 | - [Security measures implemented]
74 | - [Threat mitigation strategies]
75 | - [Data protection approaches]
76 |
77 | ## Performance Considerations
78 | - [Optimization strategies]
79 | - [Caching approach]
80 | - [Scalability considerations]
81 |
82 | ## Testing Strategy
83 | - [Unit testing approach]
84 | - [Integration testing plan]
85 | - [Performance testing requirements]
86 |
87 | ## Migration Plan
88 | [If applicable, how to migrate from current state]
89 |
90 | ## Future Considerations
91 | [Extensibility points and future enhancements]
--------------------------------------------------------------------------------
/todo-app/src/components/TodoApp.tsx:
--------------------------------------------------------------------------------
1 | import { useTodos } from '../hooks/useTodos';
2 | import { TodoForm } from './TodoForm';
3 | import { TodoList } from './TodoList';
4 | import { TodoStats } from './TodoStats';
5 | import { ErrorMessage } from './ErrorMessage';
6 |
7 | export function TodoApp() {
8 | const {
9 | todos,
10 | loading,
11 | error,
12 | stats,
13 | addTodo,
14 | updateTodo,
15 | deleteTodo,
16 | toggleTodo,
17 | clearCompleted,
18 | clearError,
19 | } = useTodos();
20 |
21 | if (loading) {
22 | return (
23 |
24 |
Loading todos...
25 |
26 | );
27 | }
28 |
29 | return (
30 |
31 |
32 | {/* Header */}
33 |
37 |
38 | {/* Error Message */}
39 | {error && (
40 |
41 | )}
42 |
43 | {/* Add Todo Form */}
44 |
47 |
48 | {/* Stats */}
49 |
0}
53 | />
54 |
55 | {/* Todo List */}
56 |
57 |
63 |
64 |
65 | {/* Footer */}
66 |
69 |
70 |
71 | );
72 | }
--------------------------------------------------------------------------------
/CLAUDE.md:
--------------------------------------------------------------------------------
1 | # CLAUDE.md
2 |
3 | This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4 |
5 | ## Project Overview
6 |
7 | This is a Spec-Driven Development Implementation Guide for Claude Code - a methodology framework providing custom slash commands for structured development workflows. It's not a traditional software project but a process framework.
8 |
9 | ## Commands
10 |
11 | This project uses custom Claude Code slash commands located in `.claude/commands/spec/`:
12 |
13 | - `/spec:new` - Create a new specification
14 | - `/spec:requirements` - Generate requirements document
15 | - `/spec:design` - Generate design document
16 | - `/spec:tasks` - Create task list
17 | - `/spec:approve` - Approve current phase
18 | - `/spec:implement` - Start implementation
19 | - `/spec:status` - Show project status
20 | - `/spec:switch` - Switch between specs
21 | - `/spec:update-task` - Update task completion
22 | - `/spec:review` - Review current phase
23 |
24 | ## Development Workflow
25 |
26 | The project enforces a four-phase sequential workflow:
27 |
28 | 1. **Requirements** → 2. **Design** → 3. **Tasks** → 4. **Implementation**
29 |
30 | Each phase must be approved before proceeding to the next. Approval creates marker files (e.g., `.requirements-approved`).
31 |
32 | ## Project Structure
33 |
34 | ```
35 | spec/ # All specifications stored here
36 | 001-/ # Each spec has its own directory
37 | README.md # Current phase document
38 | .requirements-approved
39 | .design-approved
40 | .tasks-approved
41 | .current-spec # Tracks active specification
42 | ```
43 |
44 | ## Key Implementation Notes
45 |
46 | - Specs are numbered sequentially (001, 002, etc.)
47 | - Active spec is tracked in `spec/.current-spec`
48 | - Each command has specific tool permissions in its frontmatter
49 | - Custom permissions configured in `.claude/settings.local.json`
50 | - No build/test commands - this is a methodology project
51 |
52 | ## Working with Specifications
53 |
54 | When implementing features based on a spec:
55 | 1. Check current status with `/spec:status`
56 | 2. Review the current phase document in `spec/XXX-name/README.md`
57 | 3. Follow the approved requirements, design, and task list
58 | 4. Update task completion using checkboxes or `/spec:update-task`
59 |
60 | ## Git Conventions
61 |
62 | - Use descriptive commits: `spec(001): complete requirements phase`
63 | - Each phase completion should be committed
64 | - Keep spec documents under version control
--------------------------------------------------------------------------------
/todo-app/src/components/TodoForm.tsx:
--------------------------------------------------------------------------------
1 | import { useState, type FormEvent } from 'react';
2 | import type { CreateTodoInput, Todo } from '../types/todo';
3 |
4 | interface TodoFormProps {
5 | onAddTodo: (input: CreateTodoInput) => Promise;
6 | }
7 |
8 | export function TodoForm({ onAddTodo }: TodoFormProps) {
9 | const [text, setText] = useState('');
10 | const [isSubmitting, setIsSubmitting] = useState(false);
11 |
12 | const handleSubmit = async (e: FormEvent) => {
13 | e.preventDefault();
14 |
15 | const trimmedText = text.trim();
16 | if (!trimmedText) return;
17 |
18 | setIsSubmitting(true);
19 | try {
20 | const result = await onAddTodo({ text: trimmedText });
21 | if (result) {
22 | setText(''); // Clear form on success
23 | }
24 | } finally {
25 | setIsSubmitting(false);
26 | }
27 | };
28 |
29 | const handleKeyDown = (e: React.KeyboardEvent) => {
30 | if (e.key === 'Escape') {
31 | setText('');
32 | }
33 | };
34 |
35 | return (
36 |
68 | );
69 | }
--------------------------------------------------------------------------------
/todo-app/src/components/TodoStats.tsx:
--------------------------------------------------------------------------------
1 | interface TodoStatsProps {
2 | stats: {
3 | total: number;
4 | completed: number;
5 | pending: number;
6 | };
7 | onClearCompleted: () => Promise;
8 | showClearButton?: boolean;
9 | }
10 |
11 | export function TodoStats({ stats, onClearCompleted, showClearButton = false }: TodoStatsProps) {
12 | const handleClearCompleted = async () => {
13 | if (window.confirm(`Are you sure you want to remove ${stats.completed} completed todos?`)) {
14 | await onClearCompleted();
15 | }
16 | };
17 |
18 | if (stats.total === 0) {
19 | return null;
20 | }
21 |
22 | return (
23 |
24 |
25 |
26 |
27 | {stats.total} total
28 |
29 |
30 | {stats.completed} completed
31 |
32 |
33 | {stats.pending} pending
34 |
35 |
36 |
37 | {showClearButton && (
38 |
45 | )}
46 |
47 |
48 | {/* Progress Bar */}
49 | {stats.total > 0 && (
50 |
51 |
52 | Progress
53 | {Math.round((stats.completed / stats.total) * 100)}%
54 |
55 |
61 |
62 | )}
63 |
64 | );
65 | }
--------------------------------------------------------------------------------
/todo-app/src/services/todoService.ts:
--------------------------------------------------------------------------------
1 | import type { Todo, CreateTodoInput, UpdateTodoInput } from '../types/todo';
2 |
3 | const STORAGE_KEY = 'todos';
4 |
5 | export class TodoService {
6 | static loadTodos(): Todo[] {
7 | try {
8 | const stored = localStorage.getItem(STORAGE_KEY);
9 | if (!stored) return [];
10 |
11 | const parsed = JSON.parse(stored);
12 | return parsed.map((todo: Record) => ({
13 | ...todo,
14 | createdAt: new Date(todo.createdAt as string),
15 | updatedAt: new Date(todo.updatedAt as string),
16 | }));
17 | } catch (error) {
18 | console.error('Failed to load todos:', error);
19 | return [];
20 | }
21 | }
22 |
23 | static saveTodos(todos: Todo[]): void {
24 | try {
25 | localStorage.setItem(STORAGE_KEY, JSON.stringify(todos));
26 | } catch (error) {
27 | console.error('Failed to save todos:', error);
28 | throw new Error('Failed to save todos. Storage might be full.');
29 | }
30 | }
31 |
32 | static addTodo(input: CreateTodoInput): Todo {
33 | const todos = this.loadTodos();
34 | const newTodo: Todo = {
35 | id: crypto.randomUUID(),
36 | text: input.text.trim(),
37 | completed: false,
38 | createdAt: new Date(),
39 | updatedAt: new Date(),
40 | };
41 |
42 | const updatedTodos = [...todos, newTodo];
43 | this.saveTodos(updatedTodos);
44 | return newTodo;
45 | }
46 |
47 | static updateTodo(id: string, updates: UpdateTodoInput): Todo | null {
48 | const todos = this.loadTodos();
49 | const todoIndex = todos.findIndex(todo => todo.id === id);
50 |
51 | if (todoIndex === -1) {
52 | return null;
53 | }
54 |
55 | const updatedTodo: Todo = {
56 | ...todos[todoIndex],
57 | ...updates,
58 | updatedAt: new Date(),
59 | };
60 |
61 | if (updates.text !== undefined) {
62 | updatedTodo.text = updates.text.trim();
63 | }
64 |
65 | todos[todoIndex] = updatedTodo;
66 | this.saveTodos(todos);
67 | return updatedTodo;
68 | }
69 |
70 | static deleteTodo(id: string): boolean {
71 | const todos = this.loadTodos();
72 | const filteredTodos = todos.filter(todo => todo.id !== id);
73 |
74 | if (filteredTodos.length === todos.length) {
75 | return false; // Todo not found
76 | }
77 |
78 | this.saveTodos(filteredTodos);
79 | return true;
80 | }
81 |
82 | static clearCompleted(): number {
83 | const todos = this.loadTodos();
84 | const activeTodos = todos.filter(todo => !todo.completed);
85 | const removedCount = todos.length - activeTodos.length;
86 |
87 | this.saveTodos(activeTodos);
88 | return removedCount;
89 | }
90 |
91 | static clearStorage(): void {
92 | localStorage.removeItem(STORAGE_KEY);
93 | }
94 |
95 | static getStats() {
96 | const todos = this.loadTodos();
97 | return {
98 | total: todos.length,
99 | completed: todos.filter(todo => todo.completed).length,
100 | pending: todos.filter(todo => !todo.completed).length,
101 | };
102 | }
103 | }
--------------------------------------------------------------------------------
/.claude/commands/spec/review.md:
--------------------------------------------------------------------------------
1 | ---
2 | allowed-tools: Bash(cat:*), Bash(test:*)
3 | description: Review current specification phase or implementation
4 | ---
5 |
6 | ## Review
7 |
8 | !`current=$(cat spec/.current-spec 2>/dev/null)
9 | if [ -z "$current" ]; then
10 | echo "No active spec. Use 'spec switch ' to select one."
11 | exit 0
12 | fi
13 |
14 | echo "Active spec: $current"
15 | echo "---"
16 |
17 | req_approved=false
18 | design_approved=false
19 | tasks_approved=false
20 |
21 | if [ -f "spec/$current/.requirements-approved" ]; then req_approved=true; fi
22 | if [ -f "spec/$current/.design-approved" ]; then design_approved=true; fi
23 | if [ -f "spec/$current/.tasks-approved" ]; then tasks_approved=true; fi
24 |
25 | if $req_approved && $design_approved && $tasks_approved; then
26 | # IMPLEMENTATION REVIEW
27 | echo "## Implementation Review"
28 | echo ""
29 | echo "All specification documents are approved. It's time to review the implementation against the spec."
30 | echo ""
31 | echo "**Your Task:**"
32 | echo ""
33 | echo "1. **Analyze the Specification:**"
34 | echo " - Read and understand the full specification:"
35 | echo " - spec/$current/requirements.md"
36 | echo " - spec/$current/design.md"
37 | echo " - spec/$current/tasks.md"
38 | echo ""
39 | echo "2. **Inspect the Code:**"
40 | echo " - Identify and review the code changes that implement this specification."
41 | echo " - Use tools to find the relevant commits or diffs if necessary."
42 | echo ""
43 | echo "3. **Verify Compliance:**"
44 | echo " - **Requirements:** Create a checklist from requirements.md and verify that each requirement is met by the code."
45 | echo " - **Design:** Confirm the implementation adheres to the architecture, patterns, and component choices outlined in design.md."
46 | echo " - **Tasks:** Ensure every item in tasks.md is completed and correctly implemented."
47 | echo ""
48 | echo "4. **Deliver Your Review:**"
49 | echo " - Summarize your findings."
50 | echo " - Highlight any deviations, bugs, or areas for improvement."
51 | echo " - If the implementation is solid, provide a confirmation."
52 |
53 | else
54 | # SPECIFICATION REVIEW
55 | echo "## Specification Review"
56 | echo ""
57 | echo "The following specification documents are present:"
58 | ls -1 "spec/$current/" | grep -E "(requirements|design|tasks)\.md"
59 | echo ""
60 | echo "Approval status:"
61 | if $req_approved; then echo "- ✅ requirements.md"; else echo "- ❌ requirements.md"; fi
62 | if $design_approved; then echo "- ✅ design.md"; else echo "- ❌ design.md"; fi
63 | if $tasks_approved; then echo "- ✅ tasks.md"; else echo "- ❌ tasks.md"; fi
64 | echo ""
65 | echo "**Your Task:**"
66 | echo ""
67 | echo "1. Identify the next document to be reviewed (the first one without a ✅)."
68 | echo "2. Display the content of that document."
69 | echo "3. Provide a review checklist for the document:"
70 | echo " - Does it meet all criteria for its type?"
71 | echo " - Is it complete, clear, and unambiguous?"
72 | echo " - Are there any missing elements or potential issues?"
73 | echo "4. After your review, remind the user how to approve the document if they are satisfied (e.g., spec approve requirements)."
74 | fi`
--------------------------------------------------------------------------------
/todo-app/src/assets/react.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/todo-app/src/hooks/useTodos.ts:
--------------------------------------------------------------------------------
1 | import { useState, useEffect, useCallback } from 'react';
2 | import type { Todo, CreateTodoInput, UpdateTodoInput } from '../types/todo';
3 | import { TodoService } from '../services/todoService';
4 | import { validateTodoText } from '../utils/validation';
5 |
6 | export function useTodos() {
7 | const [todos, setTodos] = useState([]);
8 | const [loading, setLoading] = useState(true);
9 | const [error, setError] = useState(null);
10 |
11 | // Load todos on mount
12 | useEffect(() => {
13 | try {
14 | const loadedTodos = TodoService.loadTodos();
15 | setTodos(loadedTodos);
16 | setError(null);
17 | } catch (err) {
18 | setError('Failed to load todos');
19 | console.error('Error loading todos:', err);
20 | } finally {
21 | setLoading(false);
22 | }
23 | }, []);
24 |
25 | // Add a new todo
26 | const addTodo = useCallback(async (input: CreateTodoInput): Promise => {
27 | const validation = validateTodoText(input.text);
28 | if (!validation.isValid) {
29 | setError(validation.error || 'Invalid todo text');
30 | return null;
31 | }
32 |
33 | try {
34 | const newTodo = TodoService.addTodo(input);
35 | setTodos(prev => [...prev, newTodo]);
36 | setError(null);
37 | return newTodo;
38 | } catch (err) {
39 | const errorMsg = err instanceof Error ? err.message : 'Failed to add todo';
40 | setError(errorMsg);
41 | return null;
42 | }
43 | }, []);
44 |
45 | // Update an existing todo
46 | const updateTodo = useCallback(async (id: string, updates: UpdateTodoInput): Promise => {
47 | if (updates.text !== undefined) {
48 | const validation = validateTodoText(updates.text);
49 | if (!validation.isValid) {
50 | setError(validation.error || 'Invalid todo text');
51 | return false;
52 | }
53 | }
54 |
55 | try {
56 | const updatedTodo = TodoService.updateTodo(id, updates);
57 | if (!updatedTodo) {
58 | setError('Todo not found');
59 | return false;
60 | }
61 |
62 | setTodos(prev => prev.map(todo => todo.id === id ? updatedTodo : todo));
63 | setError(null);
64 | return true;
65 | } catch (err) {
66 | const errorMsg = err instanceof Error ? err.message : 'Failed to update todo';
67 | setError(errorMsg);
68 | return false;
69 | }
70 | }, []);
71 |
72 | // Delete a todo
73 | const deleteTodo = useCallback(async (id: string): Promise => {
74 | try {
75 | const success = TodoService.deleteTodo(id);
76 | if (!success) {
77 | setError('Todo not found');
78 | return false;
79 | }
80 |
81 | setTodos(prev => prev.filter(todo => todo.id !== id));
82 | setError(null);
83 | return true;
84 | } catch (err) {
85 | const errorMsg = err instanceof Error ? err.message : 'Failed to delete todo';
86 | setError(errorMsg);
87 | return false;
88 | }
89 | }, []);
90 |
91 | // Toggle todo completion
92 | const toggleTodo = useCallback(async (id: string): Promise => {
93 | const todo = todos.find(t => t.id === id);
94 | if (!todo) {
95 | setError('Todo not found');
96 | return false;
97 | }
98 |
99 | return updateTodo(id, { completed: !todo.completed });
100 | }, [todos, updateTodo]);
101 |
102 | // Clear completed todos
103 | const clearCompleted = useCallback(async (): Promise => {
104 | try {
105 | const removedCount = TodoService.clearCompleted();
106 | setTodos(prev => prev.filter(todo => !todo.completed));
107 | setError(null);
108 | return removedCount;
109 | } catch (err) {
110 | const errorMsg = err instanceof Error ? err.message : 'Failed to clear completed todos';
111 | setError(errorMsg);
112 | return 0;
113 | }
114 | }, []);
115 |
116 | // Clear error
117 | const clearError = useCallback(() => {
118 | setError(null);
119 | }, []);
120 |
121 | // Get statistics
122 | const stats = {
123 | total: todos.length,
124 | completed: todos.filter(todo => todo.completed).length,
125 | pending: todos.filter(todo => !todo.completed).length,
126 | };
127 |
128 | return {
129 | todos,
130 | loading,
131 | error,
132 | stats,
133 | addTodo,
134 | updateTodo,
135 | deleteTodo,
136 | toggleTodo,
137 | clearCompleted,
138 | clearError,
139 | };
140 | }
--------------------------------------------------------------------------------
/spec/001-basic-todo-app/requirements.md:
--------------------------------------------------------------------------------
1 | # Requirements: Basic Todo App
2 |
3 | ## Feature Overview
4 |
5 | A simple, intuitive todo application that allows users to manage their daily tasks with basic CRUD operations and task status tracking.
6 |
7 | ## User Stories
8 |
9 | ### Epic: Task Management
10 | **As a user, I want to manage my tasks so that I can stay organized and productive.**
11 |
12 | #### US-001: Add Tasks
13 | - **As a user, I want to add new tasks so that I can track things I need to do**
14 | - **Acceptance Criteria:**
15 | - I can enter a task description
16 | - Tasks are saved and displayed in my list
17 | - Empty tasks cannot be added
18 | - Tasks have a default "pending" status
19 |
20 | #### US-002: View Tasks
21 | - **As a user, I want to view my task list so that I can see what needs to be done**
22 | - **Acceptance Criteria:**
23 | - All tasks are displayed in a clear list format
24 | - Tasks show description and current status
25 | - The list updates in real-time when tasks are added/modified
26 |
27 | #### US-003: Mark Tasks Complete
28 | - **As a user, I want to mark tasks as complete so that I can track my progress**
29 | - **Acceptance Criteria:**
30 | - I can toggle task status between pending and completed
31 | - Completed tasks are visually distinguished (strikethrough, different color)
32 | - Status changes persist across sessions
33 |
34 | #### US-004: Edit Tasks
35 | - **As a user, I want to edit task descriptions so that I can correct mistakes or update details**
36 | - **Acceptance Criteria:**
37 | - I can modify existing task descriptions
38 | - Changes are saved automatically or with confirmation
39 | - Original task cannot be lost during editing
40 |
41 | #### US-005: Delete Tasks
42 | - **As a user, I want to delete tasks so that I can remove items I no longer need**
43 | - **Acceptance Criteria:**
44 | - I can remove individual tasks from my list
45 | - Deletion is confirmed to prevent accidents
46 | - Deleted tasks are permanently removed
47 |
48 | ## Functional Requirements
49 |
50 | ### P0 (Must Have)
51 | - **REQ-001:** Add new tasks with text descriptions
52 | - **REQ-002:** Display all tasks in a list view
53 | - **REQ-003:** Mark tasks as complete/incomplete
54 | - **REQ-004:** Delete individual tasks
55 | - **REQ-005:** Data persistence across browser sessions
56 |
57 | ### P1 (Should Have)
58 | - **REQ-006:** Edit existing task descriptions
59 | - **REQ-007:** Visual differentiation between completed and pending tasks
60 | - **REQ-008:** Basic input validation (no empty tasks)
61 |
62 | ### P2 (Nice to Have)
63 | - **REQ-009:** Task counter (total/completed)
64 | - **REQ-010:** Clear all completed tasks
65 | - **REQ-011:** Basic keyboard shortcuts (Enter to add, Escape to cancel)
66 |
67 | ## Non-Functional Requirements
68 |
69 | ### Performance
70 | - App should load within 2 seconds
71 | - Task operations should be instant (<100ms response time)
72 |
73 | ### Usability
74 | - Simple, clean interface requiring no training
75 | - Mobile-responsive design
76 | - Accessible keyboard navigation
77 |
78 | ### Reliability
79 | - Data should persist in browser local storage
80 | - Graceful handling of storage quota exceeded
81 | - No data loss during normal operations
82 |
83 | ## Technical Constraints
84 |
85 | - Must work in modern browsers (Chrome 90+, Firefox 88+, Safari 14+)
86 | - Client-side only application (no backend required)
87 | - Use browser local storage for persistence
88 | - Responsive design for mobile devices
89 |
90 | ## Assumptions
91 |
92 | - Users will primarily use the app on a single device
93 | - Tasks are personal and don't need to be shared
94 | - Internet connectivity not required after initial load
95 | - Users understand basic web application interactions
96 |
97 | ## Out of Scope
98 |
99 | The following features are explicitly **not** included in this basic version:
100 | - User authentication/accounts
101 | - Task categories or tags
102 | - Due dates or reminders
103 | - Task priorities
104 | - Multi-user collaboration
105 | - Cloud synchronization
106 | - Mobile app (native)
107 | - Bulk operations
108 | - Task search/filtering
109 | - Data export/import
110 |
111 | ## Success Metrics
112 |
113 | - **Functional:** All P0 requirements implemented and working
114 | - **Usability:** User can add, complete, and delete a task within 30 seconds
115 | - **Technical:** App loads and functions offline after first visit
116 | - **Quality:** Zero critical bugs, graceful error handling for edge cases
117 |
118 | ## Dependencies
119 |
120 | - Modern web browser with local storage support
121 | - HTML5, CSS3, JavaScript (ES6+)
122 | - No external libraries or frameworks required for basic version
123 |
124 | ---
125 |
126 | **Review Status:** Ready for review
127 | **Next Phase:** Design (pending approval)
--------------------------------------------------------------------------------
/todo-app/src/components/TodoItem.tsx:
--------------------------------------------------------------------------------
1 | import { useState, useRef, useEffect } from 'react';
2 | import type { Todo, UpdateTodoInput } from '../types/todo';
3 |
4 | interface TodoItemProps {
5 | todo: Todo;
6 | onToggle: (id: string) => Promise;
7 | onUpdate: (id: string, updates: UpdateTodoInput) => Promise;
8 | onDelete: (id: string) => Promise;
9 | }
10 |
11 | export function TodoItem({ todo, onToggle, onUpdate, onDelete }: TodoItemProps) {
12 | const [isEditing, setIsEditing] = useState(false);
13 | const [editText, setEditText] = useState(todo.text);
14 | const [isUpdating, setIsUpdating] = useState(false);
15 | const [isDeleting, setIsDeleting] = useState(false);
16 | const inputRef = useRef(null);
17 |
18 | // Focus input when editing starts
19 | useEffect(() => {
20 | if (isEditing && inputRef.current) {
21 | inputRef.current.focus();
22 | inputRef.current.select();
23 | }
24 | }, [isEditing]);
25 |
26 | const handleToggle = async () => {
27 | setIsUpdating(true);
28 | try {
29 | await onToggle(todo.id);
30 | } finally {
31 | setIsUpdating(false);
32 | }
33 | };
34 |
35 | const handleEdit = () => {
36 | setIsEditing(true);
37 | setEditText(todo.text);
38 | };
39 |
40 | const handleSave = async () => {
41 | const trimmedText = editText.trim();
42 | if (!trimmedText) {
43 | setEditText(todo.text);
44 | setIsEditing(false);
45 | return;
46 | }
47 |
48 | if (trimmedText === todo.text) {
49 | setIsEditing(false);
50 | return;
51 | }
52 |
53 | setIsUpdating(true);
54 | try {
55 | const success = await onUpdate(todo.id, { text: trimmedText });
56 | if (success) {
57 | setIsEditing(false);
58 | }
59 | } finally {
60 | setIsUpdating(false);
61 | }
62 | };
63 |
64 | const handleCancel = () => {
65 | setEditText(todo.text);
66 | setIsEditing(false);
67 | };
68 |
69 | const handleKeyDown = (e: React.KeyboardEvent) => {
70 | if (e.key === 'Enter') {
71 | handleSave();
72 | } else if (e.key === 'Escape') {
73 | handleCancel();
74 | }
75 | };
76 |
77 | const handleDelete = async () => {
78 | if (window.confirm('Are you sure you want to delete this todo?')) {
79 | setIsDeleting(true);
80 | try {
81 | await onDelete(todo.id);
82 | } finally {
83 | setIsDeleting(false);
84 | }
85 | }
86 | };
87 |
88 | return (
89 |
90 | {/* Checkbox */}
91 |
107 |
108 | {/* Todo Text */}
109 |
110 | {isEditing ? (
111 | setEditText(e.target.value)}
116 | onKeyDown={handleKeyDown}
117 | onBlur={handleSave}
118 | disabled={isUpdating}
119 | aria-label={`Edit todo: ${todo.text}`}
120 | className="w-full px-2 py-1 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50"
121 | maxLength={500}
122 | />
123 | ) : (
124 |
133 | {todo.text}
134 |
135 | )}
136 |
137 |
138 | {/* Action Buttons */}
139 |
140 | {!isEditing && (
141 |
152 | )}
153 |
154 |
166 |
167 |
168 | {/* Creation Date */}
169 |
170 | {todo.createdAt.toLocaleDateString()}
171 |
172 |
173 | );
174 | }
--------------------------------------------------------------------------------
/spec/001-basic-todo-app/tasks.md:
--------------------------------------------------------------------------------
1 | # Tasks: Basic Todo App
2 |
3 | ## Overview
4 |
5 | **Total Estimated Time:** 12-16 hours
6 | **Target Timeline:** 3-4 days (part-time development)
7 |
8 | This task breakdown follows an incremental development approach, enabling continuous testing and validation at each phase.
9 |
10 | ## Phase Breakdown
11 |
12 | | Phase | Tasks | Estimated Time | Dependencies |
13 | |-------|-------|----------------|-------------|
14 | | Foundation | 8 tasks | 3-4 hours | None |
15 | | Core Features | 12 tasks | 6-8 hours | Foundation complete |
16 | | Enhancement | 6 tasks | 2-3 hours | Core complete |
17 | | Testing & QA | 5 tasks | 1-2 hours | All features complete |
18 |
19 | ---
20 |
21 | ## Phase 1: Foundation Setup
22 | *Estimated Time: 3-4 hours*
23 |
24 | ### Project Setup
25 | - [x] Initialize React + TypeScript project with Vite
26 | - [x] Configure ESLint and Prettier
27 | - [x] Set up basic folder structure (`src/components`, `src/services`, etc.)
28 | - [x] Install required dependencies (React, TypeScript, Tailwind CSS)
29 | - [x] Create basic HTML template in `public/index.html`
30 | - [x] Set up Tailwind CSS configuration
31 | - [x] Create global styles and CSS variables
32 | - [x] Test development server startup (`npm run dev`)
33 |
34 | **Dependencies:** None
35 | **Deliverable:** Working development environment
36 |
37 | ---
38 |
39 | ## Phase 2: Core Features Implementation
40 | *Estimated Time: 6-8 hours*
41 |
42 | ### Data Layer
43 | - [x] Create `Todo` interface in `src/types/todo.ts`
44 | - [x] Implement `todoService.ts` with localStorage operations
45 | - [x] `loadTodos()` - Load from localStorage
46 | - [x] `saveTodos()` - Save to localStorage
47 | - [x] `addTodo()` - Create new todo
48 | - [x] `updateTodo()` - Update existing todo
49 | - [x] `deleteTodo()` - Remove todo
50 | - [x] Create `useTodos.ts` custom hook for state management
51 | - [x] Add input validation and sanitization utilities
52 |
53 | ### UI Components
54 | - [x] Create main `TodoApp.tsx` component with layout
55 | - [x] Build `TodoForm.tsx` for adding new todos
56 | - [x] Input field with proper validation
57 | - [x] Add button with form submission
58 | - [x] Handle empty input prevention
59 | - [x] Build `TodoList.tsx` for displaying todos
60 | - [x] Handle empty state display
61 | - [x] Render list of TodoItem components
62 | - [x] Build `TodoItem.tsx` for individual todos
63 | - [x] Checkbox for completion toggle
64 | - [x] Text display with strikethrough for completed
65 | - [x] Delete button with confirmation
66 | - [x] Edit functionality (inline or modal)
67 |
68 | ### Integration
69 | - [x] Connect TodoForm to add todo functionality
70 | - [x] Connect TodoList to display todos from state
71 | - [x] Connect TodoItem actions to state updates
72 | - [x] Implement localStorage persistence
73 | - [x] Add basic error handling for storage operations
74 |
75 | **Dependencies:** Foundation complete
76 | **Deliverable:** Working todo CRUD operations
77 |
78 | ---
79 |
80 | ## Phase 3: Enhancement Features
81 | *Estimated Time: 2-3 hours*
82 |
83 | ### Statistics & Filtering
84 | - [x] Create `TodoStats.tsx` component showing total/completed counts
85 | - [x] Add "Clear Completed" functionality
86 | - [x] Implement basic keyboard shortcuts (Enter to submit, Escape to cancel)
87 |
88 | ### Polish & UX
89 | - [x] Add loading states and transitions
90 | - [x] Implement responsive design for mobile devices
91 | - [x] Add proper focus management for accessibility
92 | - [x] Enhance visual feedback (hover states, animations)
93 | - [x] Add confirmation dialogs for destructive actions
94 | - [x] Implement proper error messages for user feedback
95 |
96 | **Dependencies:** Core features complete
97 | **Deliverable:** Polished, user-friendly application
98 |
99 | ---
100 |
101 | ## Phase 4: Testing & Quality Assurance
102 | *Estimated Time: 1-2 hours*
103 |
104 | ### Testing
105 | - [ ] Manual testing of all CRUD operations
106 | - [ ] Test localStorage persistence across browser sessions
107 | - [ ] Cross-browser testing (Chrome, Firefox, Safari)
108 | - [ ] Mobile responsiveness testing
109 | - [ ] Accessibility testing (keyboard navigation, screen readers)
110 |
111 | **Dependencies:** All features complete
112 | **Deliverable:** Tested, production-ready application
113 |
114 | ---
115 |
116 | ## Task Dependencies
117 |
118 | ### Critical Path
119 | 1. Project Setup → Data Layer → UI Components → Integration
120 | 2. Core Features → Enhancement Features → Testing
121 |
122 | ### Parallel Development Opportunities
123 | - UI components can be built while data layer is being implemented
124 | - Styling and responsiveness can be done alongside feature development
125 | - Testing can begin as soon as individual features are complete
126 |
127 | ---
128 |
129 | ## Risk Mitigation Tasks
130 |
131 | ### Data Loss Prevention
132 | - [ ] Implement storage error handling with user notifications
133 | - [ ] Add data backup/export functionality as JSON download
134 | - [ ] Create storage quota monitoring with warnings
135 |
136 | ### Performance Optimization
137 | - [ ] Implement debounced storage saves (prevent excessive writes)
138 | - [ ] Add performance monitoring for large todo lists (>100 items)
139 | - [ ] Optimize re-renders with React.memo where appropriate
140 |
141 | ### Browser Compatibility
142 | - [ ] Test localStorage availability and fallback handling
143 | - [ ] Verify CSS Grid/Flexbox support across target browsers
144 | - [ ] Add feature detection for critical browser APIs
145 |
146 | ### Error Handling
147 | - [ ] Implement comprehensive error boundaries
148 | - [ ] Add user-friendly error messages
149 | - [ ] Create fallback UI for JavaScript disabled scenarios
150 |
151 | ---
152 |
153 | ## Development Guidelines
154 |
155 | ### Code Quality Standards
156 | - [ ] Follow React best practices (hooks, functional components)
157 | - [ ] Maintain TypeScript strict mode compliance
158 | - [ ] Ensure all components are properly typed
159 | - [ ] Use consistent naming conventions
160 | - [ ] Add JSDoc comments for complex functions
161 |
162 | ### Testing Checkpoints
163 | After each phase, verify:
164 | - [ ] All features work as specified in requirements
165 | - [ ] No console errors or warnings
166 | - [ ] Responsive design functions properly
167 | - [ ] Data persists correctly in localStorage
168 | - [ ] Application loads within performance targets (<2s)
169 |
170 | ---
171 |
172 | ## Deployment Preparation
173 |
174 | ### Build & Deploy
175 | - [ ] Run production build (`npm run build`)
176 | - [ ] Test production build locally (`npm run preview`)
177 | - [ ] Optimize bundle size and verify performance
178 | - [ ] Configure deployment to static hosting (Netlify/Vercel)
179 | - [ ] Set up custom domain (if applicable)
180 | - [ ] Test deployed application functionality
181 |
182 | ### Documentation
183 | - [ ] Create README.md with setup and usage instructions
184 | - [ ] Document any known limitations or browser requirements
185 | - [ ] Add screenshots of the working application
186 |
187 | ---
188 |
189 | ## Success Criteria
190 |
191 | ### Functional Requirements Met
192 | - [ ] All P0 requirements implemented and working
193 | - [ ] All P1 requirements implemented (edit, visual differentiation, validation)
194 | - [ ] At least 2 P2 requirements implemented (counter, clear completed, shortcuts)
195 |
196 | ### Quality Metrics Achieved
197 | - [ ] Application loads in <2 seconds
198 | - [ ] All operations respond in <100ms
199 | - [ ] Works correctly across all target browsers
200 | - [ ] Passes accessibility guidelines (keyboard navigation)
201 | - [ ] Mobile responsive design functions properly
202 |
203 | ### User Experience Validated
204 | - [ ] New user can add, complete, and delete a todo within 30 seconds
205 | - [ ] Application works offline after initial load
206 | - [ ] Data persists across browser sessions
207 | - [ ] Error states provide helpful feedback
208 |
209 | ---
210 |
211 | **Review Status:** Ready for review
212 | **Next Phase:** Implementation (pending approval)
--------------------------------------------------------------------------------
/spec/001-basic-todo-app/design.md:
--------------------------------------------------------------------------------
1 | # Design: Basic Todo App
2 |
3 | ## Architecture Overview
4 |
5 | The basic todo app follows a simple client-side architecture with local persistence:
6 |
7 | ```
8 | ┌─────────────────────────────────────────────┐
9 | │ Browser Client │
10 | │ │
11 | │ ┌─────────────┐ ┌─────────────────────┐ │
12 | │ │ UI │ │ Application │ │
13 | │ │ Component │◄─┤ Logic Layer │ │
14 | │ │ Layer │ │ │ │
15 | │ └─────────────┘ └─────────────────────┘ │
16 | │ │ │
17 | │ ▼ │
18 | │ ┌─────────────────┐ │
19 | │ │ Data Storage │ │
20 | │ │ (LocalStorage) │ │
21 | │ └─────────────────┘ │
22 | └─────────────────────────────────────────────┘
23 | ```
24 |
25 | ### Component Architecture
26 |
27 | ```
28 | App
29 | ├── TodoList
30 | │ ├── TodoItem (multiple)
31 | │ │ ├── TodoText
32 | │ │ ├── CompleteButton
33 | │ │ └── DeleteButton
34 | │ └── EmptyState
35 | ├── TodoInput
36 | │ ├── TextInput
37 | │ └── AddButton
38 | └── TodoStats
39 | ├── TotalCount
40 | └── CompletedCount
41 | ```
42 |
43 | ## Technology Stack Decisions
44 |
45 | ### Frontend Framework
46 | - **React** - Solid foundation for building modern web apps
47 | - **Tailwind CSS** - Utility-first CSS framework for rapid development
48 | - **Vite** - Fast build tool for modern web development
49 | - **TypeScript** - Strong typing for safer development
50 | - **ESLint** - Linting for JavaScript/TypeScript
51 | - **Prettier** - Code formatter for consistent code style
52 |
53 | ### Rationale
54 | - Simplicity: React is a mature and well-supported framework
55 | - Performance: Vite provides fast development server and optimized builds
56 | - Compatibility: React works in all modern browsers
57 | - Learning: Easy to understand and modify
58 |
59 | ### Alternative Considered
60 | - Vanilla JavaScript: Rejected due to lack of modern features and tooling support
61 | - jQuery: Rejected due to lack of modern features and tooling support
62 | - Svelte: Rejected due to small community and lack of tooling support
63 | - Next.js: Rejected due to complexity and overhead for basic CRUD operations
64 |
65 | ## Data Model and Schema
66 |
67 | ### Todo Entity
68 |
69 | ```javascript
70 | interface Todo {
71 | id: string; // UUID v4
72 | text: string; // Task description (1-500 chars)
73 | completed: boolean; // Completion status
74 | createdAt: Date; // Creation timestamp
75 | updatedAt: Date; // Last modification timestamp
76 | }
77 | ```
78 |
79 | ### Storage Schema
80 |
81 | **LocalStorage Key:** `todos`
82 | **Format:** JSON array of Todo objects
83 |
84 | ```javascript
85 | // Example stored data
86 | {
87 | "todos": [
88 | {
89 | "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
90 | "text": "Complete project documentation",
91 | "completed": false,
92 | "createdAt": "2025-07-21T10:00:00.000Z",
93 | "updatedAt": "2025-07-21T10:00:00.000Z"
94 | }
95 | ]
96 | }
97 | ```
98 |
99 | ## API Design
100 |
101 | ### Internal JavaScript API
102 |
103 | ```javascript
104 | class TodoService {
105 | // CRUD Operations
106 | static addTodo(text: string): Todo
107 | static getTodos(): Todo[]
108 | static updateTodo(id: string, updates: Partial): Todo
109 | static deleteTodo(id: string): boolean
110 | static clearCompleted(): number
111 |
112 | // Storage Operations
113 | static saveToStorage(todos: Todo[]): void
114 | static loadFromStorage(): Todo[]
115 | static clearStorage(): void
116 | }
117 | ```
118 |
119 | ### Event System
120 |
121 | ```javascript
122 | // Custom events for UI updates
123 | document.dispatchEvent(new CustomEvent('todosChanged', {
124 | detail: { todos: updatedTodos }
125 | }));
126 | ```
127 |
128 | ## User Interface Design
129 |
130 | ### Layout Structure
131 |
132 | ```
133 | ┌─────────────────────────────────────────┐
134 | │ Todo App Header │
135 | ├─────────────────────────────────────────┤
136 | │ ┌─────────────────────┐ ┌───────────┐ │
137 | │ │ New Task Input │ │ Add │ │
138 | │ └─────────────────────┘ └───────────┘ │
139 | ├─────────────────────────────────────────┤
140 | │ ☐ Task 1 - Learn JavaScript [Delete] │
141 | │ ☑ Task 2 - Build Todo App [Delete] │
142 | │ ☐ Task 3 - Deploy Application [Delete] │
143 | ├─────────────────────────────────────────┤
144 | │ 2 of 3 tasks completed │
145 | └─────────────────────────────────────────┘
146 | ```
147 |
148 | ### Visual Design Principles
149 | - **Minimalist:** Clean, uncluttered interface
150 | - **Accessible:** High contrast, keyboard navigation
151 | - **Responsive:** Works on mobile and desktop
152 | - **Intuitive:** Common UI patterns (checkboxes, buttons)
153 |
154 | ### Color Scheme
155 | ```css
156 | :root {
157 | --primary-color: #1D2130;
158 | --success-color: #28a745;
159 | --danger-color: #dc3545;
160 | --text-primary: #333333;
161 | --text-secondary: #666666;
162 | --background: #ffffff;
163 | --border: #e0e0e0;
164 | }
165 | ```
166 |
167 | ## Security Considerations
168 |
169 | ### Data Protection
170 | - **Local Storage:** Data remains on user's device
171 | - **No Authentication:** No user credentials to protect
172 | - **Input Sanitization:** Prevent XSS through proper HTML escaping
173 |
174 | ### Input Validation
175 | ```javascript
176 | function sanitizeInput(input) {
177 | return input
178 | .trim()
179 | .slice(0, 500) // Max length limit
180 | .replace(/[<>]/g, ''); // Basic XSS prevention
181 | }
182 | ```
183 |
184 | ### Content Security Policy
185 | ```html
186 |
188 | ```
189 |
190 | ## Performance Considerations
191 |
192 | ### Optimization Strategies
193 | 1. **Minimal DOM Manipulation:** Update only changed elements
194 | 2. **Event Delegation:** Single event listener for todo items
195 | 3. **Debounced Storage:** Batch storage operations
196 | 4. **Virtual Scrolling:** For large todo lists (future enhancement)
197 |
198 | ### Performance Targets
199 | - **Initial Load:** < 2 seconds
200 | - **Task Operations:** < 100ms response time
201 | - **Storage Operations:** < 50ms
202 | - **Memory Usage:** < 10MB for 1000 todos
203 |
204 | ### Monitoring
205 | ```javascript
206 | // Performance timing
207 | const startTime = performance.now();
208 | // ... operation
209 | const endTime = performance.now();
210 | console.log(`Operation took ${endTime - startTime}ms`);
211 | ```
212 |
213 | ## Deployment Architecture
214 |
215 | ### Static Hosting
216 | ```
217 | CDN/Static Host (Netlify, Vercel, GitHub Pages)
218 | ├── index.html
219 | ├── styles.css
220 | ├── app.js
221 | └── manifest.json (PWA support)
222 | ```
223 |
224 | ### File Structure
225 | ```
226 | todo-app/
227 | ├── public/
228 | │ ├── index.html # Main HTML template
229 | │ ├── favicon.ico # Application icon
230 | │ └── manifest.json # PWA manifest
231 | ├── src/
232 | │ ├── components/
233 | │ │ ├── TodoApp.tsx # Main application component
234 | │ │ ├── TodoList.tsx # Todo list display
235 | │ │ ├── TodoItem.tsx # Individual todo item
236 | │ │ ├── TodoForm.tsx # Add/edit todo form
237 | │ │ └── TodoFilters.tsx # Filter controls
238 | │ ├── services/
239 | │ │ └── todoService.ts # Data management & localStorage
240 | │ ├── hooks/
241 | │ │ └── useTodos.ts # Custom hook for todo state
242 | │ ├── utils/
243 | │ │ └── helpers.ts # Utility functions
244 | │ ├── types/
245 | │ │ └── todo.ts # TypeScript type definitions
246 | │ ├── styles/
247 | │ │ ├── index.css # Global styles
248 | │ │ ├── TodoApp.css # Main component styles
249 | │ │ └── responsive.css # Mobile responsive styles
250 | │ ├── App.tsx # Root component
251 | │ └── index.tsx # Application entry point
252 | ├── package.json # Dependencies and scripts
253 | ├── package-lock.json # Locked dependency versions
254 | └── tsconfig.json # TypeScript configuration
255 | ```
256 |
257 | ### Build Process
258 | - **Development:** `npm run dev` - Start development server with hot reload
259 | - **Production:** `npm run build` - Create optimized build in `dist/` folder
260 | - **Preview:** `npm run preview` - Test production build locally
261 | - **Deploy:** Upload `dist/` folder contents to any static hosting service
262 |
263 | ## Technical Risks and Mitigations
264 |
265 | ### Risk 1: Data Loss
266 | **Risk:** Browser storage cleared, causing todo loss
267 | **Impact:** High - Complete data loss
268 | **Mitigation:**
269 | - Implement export/backup functionality
270 | - Add browser storage warnings
271 | - Consider future cloud sync
272 |
273 | ### Risk 2: Browser Compatibility
274 | **Risk:** Features not supported in older browsers
275 | **Impact:** Medium - Reduced user base
276 | **Mitigation:**
277 | - Feature detection and graceful degradation
278 | - Polyfills for essential features
279 | - Clear browser requirements
280 |
281 | ### Risk 3: Storage Quota Exceeded
282 | **Risk:** LocalStorage limit reached with many todos
283 | **Impact:** Medium - Cannot add new todos
284 | **Mitigation:**
285 | - Monitor storage usage
286 | - Implement data cleanup options
287 | - User warnings at 80% capacity
288 |
289 | ### Risk 4: Performance Degradation
290 | **Risk:** Slow performance with large todo lists
291 | **Impact:** Low - Poor user experience
292 | **Mitigation:**
293 | - Pagination for large lists
294 | - Lazy rendering techniques
295 | - Performance monitoring
296 |
297 | ## Testing Strategy
298 |
299 | ### Unit Testing
300 | - Todo creation, update, deletion
301 | - Data validation and sanitization
302 | - Storage operations
303 |
304 | ### Integration Testing
305 | - UI interactions with data layer
306 | - Browser storage persistence
307 | - Cross-browser compatibility
308 |
309 | ### Manual Testing Scenarios
310 | 1. Add 100+ todos to test performance
311 | 2. Test offline functionality
312 | 3. Verify data persistence across browser sessions
313 | 4. Mobile device responsiveness testing
314 |
315 | ## Future Enhancements
316 |
317 | ### Phase 2 Considerations
318 | - Drag-and-drop reordering
319 | - Task categories/tags
320 | - Due dates and reminders
321 | - Dark mode theme
322 | - Keyboard shortcuts
323 | - PWA features (offline, installable)
324 |
325 | ### Phase 3 Considerations
326 | - Cloud synchronization
327 | - User accounts
328 | - Collaborative todos
329 | - Mobile native app
330 |
331 | ---
332 |
333 | **Review Status:** Ready for review
334 | **Next Phase:** Tasks (pending approval)
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Claude Code Spec-Driven Development Implementation Guide
2 |
3 | ## Table of Contents
4 | 1. [Overview](#overview)
5 | 2. [Benefits](#benefits)
6 | 3. [Prerequisites](#prerequisites)
7 | 4. [Quick Start](#quick-start)
8 | 5. [Installation](#installation)
9 | 6. [Command Reference](#command-reference)
10 | 7. [Workflow Example](#workflow-example)
11 | 8. [Templates](#templates)
12 | 9. [Best Practices](#best-practices)
13 | 10. [Troubleshooting](#troubleshooting)
14 | 11. [Advanced Usage](#advanced-usage)
15 |
16 | ## Overview
17 |
18 | This guide implements a spec-driven development workflow in Claude Code using custom slash commands. The workflow enforces a structured approach where specifications are created, reviewed, and approved before implementation begins.
19 |
20 | ### Core Concept
21 |
22 | Each feature is developed through four sequential phases:
23 |
24 | 1. **Requirements** - Define WHAT needs to be built
25 | 2. **Design** - Determine HOW it will be built
26 | 3. **Tasks** - Plan WHEN and in what order
27 | 4. **Implementation** - Execute the plan with progress tracking
28 |
29 | ### File Structure
30 |
31 | ```
32 | /spec/
33 | ├── 001-user-authentication/
34 | │ ├── requirements.md
35 | │ ├── design.md
36 | │ └── tasks.md
37 | ├── 002-payment-integration/
38 | │ ├── requirements.md
39 | │ ├── design.md
40 | │ └── tasks.md
41 | └── .current-spec # Stores the full spec directory name, e.g. 001-user-authentication
42 | ```
43 |
44 | ## Benefits
45 |
46 | - **🎯 Catch problems early** - Identify and resolve requirement ambiguities before coding
47 | - **🎮 Maintain control** - Review and approve each phase before proceeding
48 | - **🔄 Iterate safely** - Modify specifications without losing conversation context
49 | - **🧠 Keep AI focused** - Separate planning from coding for better results
50 | - **👥 Enable collaboration** - Living documentation for team reviews
51 | - **📚 Build knowledge** - Document decisions and preserve context
52 |
53 | ## Prerequisites
54 |
55 | - Claude Code installed and configured
56 | - Git repository initialized
57 | - Basic understanding of markdown
58 |
59 | ## Quick Start
60 |
61 | ```bash
62 | # 1. Set up the spec workflow (see Installation)
63 | mkdir -p .claude/commands/spec
64 | mkdir -p spec
65 |
66 | # 2. Create your first spec
67 | /spec:new user-authentication
68 |
69 | # 3. Follow the workflow
70 | /spec:requirements # Create requirements
71 | /spec:approve requirements # Mark as approved
72 | /spec:design # Create design
73 | /spec:approve design # Mark as approved
74 | /spec:tasks # Create task list
75 | /spec:approve tasks # Mark as approved
76 | /spec:implement # Start coding
77 | ```
78 |
79 | ## Installation
80 |
81 | ### Step 1: Create Directory Structure
82 |
83 | ```bash
84 | # Create directories for spec commands
85 | mkdir -p .claude/commands/spec
86 | mkdir -p spec
87 |
88 | # Create a file to track current spec
89 | echo "" > spec/.current-spec
90 | ```
91 |
92 | ### Step 2: Create Spec Commands
93 |
94 | #### `/spec:new` - Initialize New Specification
95 |
96 | Create `.claude/commands/spec/new.md`:
97 |
98 | ```markdown
99 | ---
100 | allowed-tools: Bash(mkdir:*), Bash(echo:*), Bash(date:*), Bash(ls:*)
101 | description: Create a new feature specification
102 | argument-hint:
103 | ---
104 |
105 | ## Current Spec Status
106 |
107 | !`ls -la spec/ 2>/dev/null | grep "^d" | wc -l | xargs -I {} echo "Total specs: {}"`
108 |
109 | ## Your Task
110 |
111 | Create a new specification directory for the feature: $ARGUMENTS
112 |
113 | 1. Determine the next ID number (format: 001, 002, etc.)
114 | 2. Create directory: `spec/[ID]-$ARGUMENTS/`
115 | 3. Update `spec/.current-spec` with the new spec directory name ([ID]-$ARGUMENTS)
116 | 4. Create a README.md in the new directory with:
117 | - Feature name
118 | - Creation date
119 | - Initial status checklist
120 | 5. Inform the user about next steps
121 |
122 | Use the Bash tool to create directories and files as needed.
123 | ```
124 |
125 | #### `/spec:requirements` - Generate Requirements Template
126 |
127 | Create `.claude/commands/spec/requirements.md`:
128 |
129 | ```markdown
130 | ---
131 | allowed-tools: Bash(cat:*), Bash(test:*), Bash(touch:*), Write
132 | description: Create or review requirements specification
133 | ---
134 |
135 | ## Context
136 |
137 | Current spec: !`cat spec/.current-spec 2>/dev/null || echo "No active spec"`
138 | Spec directory contents: !`ls -la spec/$(cat spec/.current-spec 2>/dev/null)/ 2>/dev/null || echo "Spec not found"`
139 |
140 | ## Your Task
141 |
142 | For the current active specification:
143 |
144 | 1. Check if requirements.md exists
145 | 2. If not, create a comprehensive requirements.md with:
146 | - Feature overview
147 | - User stories with acceptance criteria
148 | - Functional requirements (P0, P1, P2)
149 | - Non-functional requirements
150 | - Constraints and assumptions
151 | - Out of scope items
152 | - Success metrics
153 | 3. If it exists, display current content and suggest improvements
154 | 4. Remind user to use `/spec:approve requirements` when ready
155 |
156 | Use the Write tool to create/update the requirements.md file.
157 | ```
158 |
159 | #### `/spec:design` - Generate Design Document
160 |
161 | Create `.claude/commands/spec/design.md`:
162 |
163 | ```markdown
164 | ---
165 | allowed-tools: Bash(cat:*), Bash(test:*), Bash(ls:*), Write
166 | description: Create technical design specification
167 | ---
168 |
169 | ## Context
170 |
171 | Current spec: !`cat spec/.current-spec 2>/dev/null`
172 | Requirements approved: !`test -f spec/$(cat spec/.current-spec)/.requirements-approved && echo "Yes" || echo "No"`
173 | Current directory: !`ls -la spec/$(cat spec/.current-spec)/ 2>/dev/null`
174 |
175 | ## Your Task
176 |
177 | 1. Verify requirements are approved (look for .requirements-approved file)
178 | 2. If not approved, inform user to complete requirements first
179 | 3. If approved, create/update design.md with:
180 | - Architecture overview (with diagrams)
181 | - Technology stack decisions
182 | - Data model and schema
183 | - API design
184 | - Security considerations
185 | - Performance considerations
186 | - Deployment architecture
187 | - Technical risks and mitigations
188 | 4. Use ASCII art or mermaid diagrams where helpful
189 |
190 | Use the Write tool to create the design document.
191 | ```
192 |
193 | #### `/spec:tasks` - Generate Task List
194 |
195 | Create `.claude/commands/spec/tasks.md`:
196 |
197 | ```markdown
198 | ---
199 | allowed-tools: Bash(cat:*), Bash(test:*), Write
200 | description: Create implementation task list
201 | ---
202 |
203 | ## Context
204 |
205 | Current spec: !`cat spec/.current-spec 2>/dev/null`
206 | Design approved: !`test -f spec/$(cat spec/.current-spec)/.design-approved && echo "Yes" || echo "No"`
207 |
208 | ## Your Task
209 |
210 | 1. Verify design is approved
211 | 2. Create tasks.md with:
212 | - Overview with time estimates
213 | - Phase breakdown (Foundation, Core, Testing, Deployment)
214 | - Detailed task list with checkboxes
215 | - Task dependencies
216 | - Risk mitigation tasks
217 | 3. Each task should be specific and actionable
218 | 4. Use markdown checkboxes: `- [ ] Task description`
219 |
220 | Organize tasks to enable incremental development and testing.
221 | ```
222 |
223 | #### `/spec:approve` - Approve Specification Phase
224 |
225 | Create `.claude/commands/spec/approve.md`:
226 |
227 | ```markdown
228 | ---
229 | allowed-tools: Bash(touch:*), Bash(test:*), Bash(cat:*)
230 | description: Approve a specification phase
231 | argument-hint: requirements|design|tasks
232 | ---
233 |
234 | ## Context
235 |
236 | Current spec: !`cat spec/.current-spec 2>/dev/null`
237 | Spec directory: !`ls -la spec/$(cat spec/.current-spec)/ 2>/dev/null`
238 |
239 | ## Your Task
240 |
241 | For the phase "$ARGUMENTS":
242 |
243 | 1. Verify the phase file exists (requirements.md, design.md, or tasks.md)
244 | 2. Create approval marker file: `.${ARGUMENTS}-approved`
245 | 3. Inform user about next steps:
246 | - After requirements → design phase
247 | - After design → tasks phase
248 | - After tasks → implementation
249 | 4. If invalid phase name, show valid options
250 |
251 | Use touch command to create approval markers.
252 | ```
253 |
254 | #### `/spec:status` - Show Specification Status
255 |
256 | Create `.claude/commands/spec/status.md`:
257 |
258 | ```markdown
259 | ---
260 | allowed-tools: Bash(ls:*), Bash(cat:*), Bash(grep:*), Bash(test:*), Bash(find:*)
261 | description: Show all specifications and their status
262 | ---
263 |
264 | ## Gather Status Information
265 |
266 | All specs: !`ls -d spec/*/ 2>/dev/null | sort`
267 | Current spec: !`cat spec/.current-spec 2>/dev/null || echo "None"`
268 |
269 | For each spec directory, check:
270 | !`for dir in spec/*/; do
271 | if [ -d "$dir" ]; then
272 | echo "=== $dir ==="
273 | ls -la "$dir" | grep -E "(requirements|design|tasks)\.md|\..*-approved"
274 | if [ -f "$dir/tasks.md" ]; then
275 | echo "Task progress:"
276 | grep "^- \[" "$dir/tasks.md" | head -5
277 | echo "Total tasks: $(grep -c "^- \[" "$dir/tasks.md" 2>/dev/null || echo 0)"
278 | echo "Completed: $(grep -c "^- \[x\]" "$dir/tasks.md" 2>/dev/null || echo 0)"
279 | fi
280 | echo ""
281 | fi
282 | done`
283 |
284 | ## Your Task
285 |
286 | Present a clear status report showing:
287 | 1. All specifications with their IDs and names
288 | 2. Current active spec (highlighted)
289 | 3. Phase completion status for each spec
290 | 4. Task progress percentage if applicable
291 | 5. Recommended next action for active spec
292 | ```
293 |
294 | #### `/spec:implement` - Start Implementation Session
295 |
296 | Create `.claude/commands/spec/implement.md`:
297 |
298 | ```markdown
299 | ---
300 | allowed-tools: Bash(cat:*), Bash(test:*), Bash(grep:*), Write
301 | description: Start implementation from approved tasks
302 | argument-hint: [phase-number]
303 | ---
304 |
305 | ## Context
306 |
307 | Current spec: !`cat spec/.current-spec 2>/dev/null`
308 | Tasks approved: !`test -f spec/$(cat spec/.current-spec)/.tasks-approved && echo "Yes" || echo "No"`
309 |
310 | ## Current Tasks
311 |
312 | !`if [ -f "spec/$(cat spec/.current-spec)/tasks.md" ]; then
313 | echo "=== Phase Overview ==="
314 | grep "^## Phase" "spec/$(cat spec/.current-spec)/tasks.md"
315 | echo ""
316 | echo "=== Incomplete Tasks ==="
317 | grep "^- \[ \]" "spec/$(cat spec/.current-spec)/tasks.md" | head -20
318 | fi`
319 |
320 | ## Your Task
321 |
322 | 1. Verify all phases are approved
323 | 2. If phase number provided ($ARGUMENTS), focus on that phase
324 | 3. Display current incomplete tasks
325 | 4. Create an implementation session log
326 | 5. Guide user to:
327 | - Work on tasks sequentially
328 | - Update task checkboxes as completed
329 | - Commit changes regularly
330 | 6. Remind about using Write tool to update tasks.md
331 |
332 | Start implementing based on the task list!
333 | ```
334 |
335 | #### `/spec:switch` - Switch Active Specification
336 |
337 | Create `.claude/commands/spec/switch.md`:
338 |
339 | ```markdown
340 | ---
341 | allowed-tools: Bash(ls:*), Bash(echo:*), Bash(test:*)
342 | description: Switch to a different specification
343 | argument-hint:
344 | ---
345 |
346 | ## Available Specifications
347 |
348 | !`ls -d spec/*/ 2>/dev/null | sort`
349 |
350 | ## Your Task
351 |
352 | Switch the active specification to: $ARGUMENTS
353 |
354 | 1. Verify the spec directory exists
355 | 2. Update spec/.current-spec with the new spec directory name ([ID]-$ARGUMENTS)
356 | 3. Show the status of the newly active spec
357 | 4. Display next recommended action
358 |
359 | If no argument provided, list all available specs.
360 | ```
361 |
362 | ### Step 3: Create Helper Commands (Optional)
363 |
364 | #### `/spec:update-task` - Update Task Status
365 |
366 | Create `.claude/commands/spec/update-task.md`:
367 |
368 | ```markdown
369 | ---
370 | allowed-tools: Bash(cat:*), Bash(grep:*), Write
371 | description: Mark a task as complete
372 | argument-hint:
373 | ---
374 |
375 | ## Current Tasks
376 |
377 | !`cat spec/$(cat spec/.current-spec)/tasks.md | grep -n "^- \[" | head -20`
378 |
379 | ## Your Task
380 |
381 | Update the task status for: "$ARGUMENTS"
382 |
383 | 1. Find the matching task in tasks.md
384 | 2. Change `- [ ]` to `- [x]` for that task
385 | 3. Show updated progress statistics
386 | 4. Suggest next task to work on
387 |
388 | Use the Write tool to update the file.
389 | ```
390 |
391 | #### `/spec:review` - Review Current Phase
392 |
393 | Create `.claude/commands/spec/review.md`:
394 |
395 | ```markdown
396 | ---
397 | allowed-tools: Bash(cat:*), Bash(test:*)
398 | description: Review current specification phase
399 | ---
400 |
401 | ## Current Spec Status
402 |
403 | !`current=$(cat spec/.current-spec 2>/dev/null)
404 | if [ -n "$current" ]; then
405 | echo "Active spec: $current"
406 | echo "Files present:"
407 | ls -la "spec/$current/" | grep -E "(requirements|design|tasks)\.md"
408 | echo ""
409 | echo "Approval status:"
410 | ls -la "spec/$current/" | grep "approved"
411 | fi`
412 |
413 | ## Your Task
414 |
415 | 1. Identify which phase is currently active (not yet approved)
416 | 2. Display the content of that phase's document
417 | 3. Provide a review checklist:
418 | - Does it meet all criteria?
419 | - Is it complete and clear?
420 | - Any missing elements?
421 | 4. Remind user how to approve when ready
422 | ```
423 |
424 | ## Command Reference
425 |
426 | ### Core Commands
427 |
428 | | Command | Description | Usage |
429 | |---------|-------------|--------|
430 | | `/spec:new` | Create a new specification | `/spec:new user-authentication` |
431 | | `/spec:requirements` | Generate requirements template | `/spec:requirements` |
432 | | `/spec:design` | Generate design template | `/spec:design` |
433 | | `/spec:tasks` | Generate task list template | `/spec:tasks` |
434 | | `/spec:approve` | Approve a specification phase | `/spec:approve requirements` |
435 | | `/spec:implement` | Start implementation phase | `/spec:implement [phase]` |
436 | | `/spec:status` | Show all specs and progress | `/spec:status` |
437 | | `/spec:switch` | Switch active specification | `/spec:switch 001-user-auth` |
438 | | `/spec:update-task` | Mark task as complete | `/spec:update-task "Create user model"` |
439 | | `/spec:review` | Review current phase | `/spec:review` |
440 |
441 | ### Command Flow
442 |
443 | ```mermaid
444 | graph LR
445 | A["/spec:new"] --> B["/spec:requirements"]
446 | B --> C["/spec:approve requirements"]
447 | C --> D["/spec:design"]
448 | D --> E["/spec:approve design"]
449 | E --> F["/spec:tasks"]
450 | F --> G["/spec:approve tasks"]
451 | G --> H["/spec:implement"]
452 | ```
453 |
454 | ## Workflow Example
455 |
456 | ### Complete Feature Development Flow
457 |
458 | ```bash
459 | # Day 1: Specification
460 | /spec:new user-authentication
461 | # Creates: spec/001-user-authentication/
462 |
463 | /spec:requirements
464 | # Claude creates requirements.md template
465 | # You edit and refine the requirements
466 |
467 | /spec:approve requirements
468 | # Creates .requirements-approved marker
469 |
470 | # Day 2: Design
471 | /spec:design
472 | # Claude creates design.md based on requirements
473 | # You review and adjust the technical design
474 |
475 | /spec:approve design
476 | # Creates .design-approved marker
477 |
478 | # Day 3: Planning
479 | /spec:tasks
480 | # Claude creates detailed task breakdown
481 | # You review and adjust time estimates
482 |
483 | /spec:approve tasks
484 | # Creates .tasks-approved marker
485 |
486 | # Day 4-10: Implementation
487 | /spec:implement 1 # Focus on Phase 1
488 | # Work through tasks, updating checkboxes
489 |
490 | /spec:update-task "Initialize project repository"
491 | # Claude marks task as complete
492 |
493 | /spec:status # Check overall progress
494 | # See all specs and completion percentages
495 | ```
496 |
497 | ## Templates
498 |
499 | ### Requirements Template Structure
500 |
501 | ```markdown
502 | # Requirements Specification
503 |
504 | ## Feature Overview
505 | [High-level description of the feature]
506 |
507 | ## User Stories
508 |
509 | ### Story 1: [User can authenticate]
510 | **As a** registered user
511 | **I want** to log in with my credentials
512 | **So that** I can access my personal dashboard
513 |
514 | **Acceptance Criteria:**
515 | - [ ] User can enter email and password
516 | - [ ] System validates credentials
517 | - [ ] Successful login redirects to dashboard
518 | - [ ] Failed login shows error message
519 |
520 | ## Functional Requirements
521 |
522 | ### Must Have (P0)
523 | - **REQ-001**: System must support email/password authentication
524 | - **REQ-002**: Passwords must be hashed using bcrypt
525 |
526 | ### Should Have (P1)
527 | - **REQ-003**: Support "Remember me" functionality
528 | - **REQ-004**: Implement password reset via email
529 |
530 | ### Nice to Have (P2)
531 | - **REQ-005**: Support OAuth providers (Google, GitHub)
532 |
533 | ## Non-Functional Requirements
534 |
535 | ### Performance
536 | - Login response time < 500ms
537 | - Support 1000 concurrent users
538 |
539 | ### Security
540 | - Passwords minimum 8 characters
541 | - Session timeout after 30 minutes
542 | - HTTPS only
543 |
544 | ## Constraints and Assumptions
545 |
546 | ### Technical Constraints
547 | - Must use existing user database
548 | - Compatible with React frontend
549 |
550 | ### Assumptions
551 | - Users have valid email addresses
552 | - Email service is available
553 |
554 | ## Out of Scope
555 | - Two-factor authentication
556 | - Biometric authentication
557 |
558 | ## Success Metrics
559 | - Login success rate > 95%
560 | - Password reset completion > 80%
561 | ```
562 |
563 | ### Design Template Structure
564 |
565 | ```markdown
566 | # Technical Design Specification
567 |
568 | ## Architecture Overview
569 |
570 | ### System Context
571 |
572 | ```mermaid
573 | graph TD
574 | A[Browser] --> B[API Gateway]
575 | B --> C[Auth Service]
576 | C --> D[PostgreSQL]
577 | ```
578 |
579 | ## Technology Stack
580 |
581 | ### Frontend
582 | - **Framework**: React 18
583 | - **State Management**: Context API
584 | - **Styling**: TailwindCSS
585 | - **Form Handling**: React Hook Form
586 |
587 | ### Backend
588 | - **Runtime**: Node.js 20
589 | - **Framework**: Express.js
590 | - **Authentication**: JWT + bcrypt
591 | - **Database**: PostgreSQL 15
592 |
593 | ## Data Model
594 |
595 | ### Users Table
596 | ```sql
597 | CREATE TABLE users (
598 | id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
599 | email VARCHAR(255) UNIQUE NOT NULL,
600 | password_hash VARCHAR(255) NOT NULL,
601 | created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
602 | last_login TIMESTAMP
603 | );
604 | ```
605 |
606 | ### Sessions Table
607 | ```sql
608 | CREATE TABLE sessions (
609 | id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
610 | user_id UUID REFERENCES users(id),
611 | token_hash VARCHAR(255) NOT NULL,
612 | expires_at TIMESTAMP NOT NULL,
613 | created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
614 | );
615 | ```
616 |
617 | ## API Design
618 |
619 | ### POST /api/auth/login
620 | **Request**:
621 | ```json
622 | {
623 | "email": "user@example.com",
624 | "password": "securepassword"
625 | }
626 | ```
627 |
628 | **Response (200)**:
629 | ```json
630 | {
631 | "token": "eyJhbGciOiJIUzI1NiIs...",
632 | "user": {
633 | "id": "123e4567-e89b-12d3-a456-426614174000",
634 | "email": "user@example.com"
635 | }
636 | }
637 | ```
638 |
639 | ### POST /api/auth/logout
640 | **Headers**: `Authorization: Bearer `
641 |
642 | **Response (200)**:
643 | ```json
644 | {
645 | "message": "Logged out successfully"
646 | }
647 | ```
648 |
649 | ## Security Considerations
650 |
651 | ### Password Storage
652 | - Bcrypt with cost factor 12
653 | - Never store plain text passwords
654 |
655 | ### JWT Configuration
656 | - HS256 algorithm
657 | - 15-minute access token expiry
658 | - Secure, httpOnly cookies
659 |
660 | ### Rate Limiting
661 | - 5 login attempts per IP per minute
662 | - Exponential backoff for failed attempts
663 |
664 | ## Error Handling
665 |
666 | ### Standard Error Response
667 | ```json
668 | {
669 | "error": {
670 | "code": "AUTH_INVALID_CREDENTIALS",
671 | "message": "Invalid email or password",
672 | "timestamp": "2024-01-20T10:30:00Z"
673 | }
674 | }
675 | ```
676 |
677 | ## Technical Risks
678 |
679 | | Risk | Impact | Probability | Mitigation |
680 | |------|--------|-------------|------------|
681 | | Database connection failure | High | Low | Connection pooling, retry logic |
682 | | JWT secret exposure | Critical | Low | Environment variables, key rotation |
683 | | Brute force attacks | Medium | Medium | Rate limiting, account lockout |
684 | ```
685 |
686 | ### Tasks Template Structure
687 |
688 | ```markdown
689 | # Implementation Tasks
690 |
691 | ## Phase 1: Foundation Setup
692 |
693 | ### Development Environment
694 | - [ ] Initialize Node.js project with TypeScript
695 | - [ ] Set up ESLint and Prettier
696 | - [ ] Configure Jest for testing
697 | - [ ] Create docker-compose for PostgreSQL
698 |
699 | ### Project Structure
700 | - [ ] Create src/ directory structure
701 | - [ ] Set up environment variables
702 | - [ ] Configure build scripts
703 | - [ ] Initialize Git repository
704 |
705 | ## Phase 2: Backend Implementation
706 |
707 | ### Database Layer
708 | - [ ] Create database migrations for users table
709 | - [ ] Create database migrations for sessions table
710 | - [ ] Implement database connection module
711 | - [ ] Create user repository layer
712 |
713 | ### Authentication Logic
714 | - [ ] Implement password hashing utilities
715 | - [ ] Create JWT token generation/validation
716 | - [ ] Build login endpoint
717 | - [ ] Build logout endpoint
718 | - [ ] Add session management
719 |
720 | ### Middleware
721 | - [ ] Create authentication middleware
722 | - [ ] Implement rate limiting
723 | - [ ] Add request validation
724 | - [ ] Set up error handling
725 |
726 | ## Phase 3: Frontend Integration
727 |
728 | ### Components
729 | - [ ] Create login form component
730 | - [ ] Add form validation
731 | - [ ] Implement error displays
732 | - [ ] Create loading states
733 |
734 | ### State Management
735 | - [ ] Set up auth context
736 | - [ ] Implement login action
737 | - [ ] Handle token storage
738 | - [ ] Add logout functionality
739 |
740 | ## Phase 4: Testing & Documentation
741 |
742 | ### Testing
743 | - [ ] Write unit tests for auth utilities
744 | - [ ] Test API endpoints
745 | - [ ] Create integration tests
746 | - [ ] Manual testing checklist
747 |
748 | ### Documentation
749 | - [ ] API documentation
750 | - [ ] Setup instructions
751 | - [ ] Security guidelines
752 | - [ ] Deployment notes
753 |
754 | ## Dependencies
755 |
756 | ```mermaid
757 | graph TD
758 | A[Environment Setup] --> B[Database Layer]
759 | B --> C[Auth Logic]
760 | C --> D[API Endpoints]
761 | D --> E[Frontend Components]
762 | E --> F[Integration Tests]
763 | F --> G[Documentation]
764 | ```
765 |
766 | ## Definition of Done
767 |
768 | Each task is considered complete when:
769 | - Code is written and functional
770 | - Unit tests pass
771 | - Code review completed
772 | - Documentation updated
773 | ```
774 |
775 | ## Best Practices
776 |
777 | ### 1. Phase Discipline
778 | - ✅ Complete phases sequentially
779 | - ✅ Review thoroughly before approval
780 | - ✅ Keep approval markers in version control
781 | - ❌ Don't skip phases
782 | - ❌ Don't implement without approved specs
783 |
784 | ### 2. Documentation Standards
785 | - ✅ Use clear, specific language
786 | - ✅ Include concrete examples
787 | - ✅ Add diagrams where helpful
788 | - ❌ Avoid vague requirements
789 | - ❌ Don't over-engineer early phases
790 |
791 | ### 3. Task Management
792 | - ✅ Update task status immediately
793 | - ✅ Keep tasks small and specific
794 | - ✅ Include time estimates
795 | - ✅ Group related tasks
796 | - ❌ Don't batch status updates
797 |
798 | ### 4. Command Usage
799 | - ✅ Use commands in sequence
800 | - ✅ Review output before proceeding
801 | - ✅ Keep spec/.current-spec updated
802 | - ❌ Don't modify approval files manually
803 |
804 | ### 5. Version Control
805 | ```bash
806 | # Good commit messages
807 | git commit -m "spec(001): complete requirements phase"
808 | git commit -m "spec(001): add security requirements"
809 | git commit -m "impl(001): complete user model (tasks 3-5)"
810 |
811 | # Include spec files in commits
812 | git add spec/001-user-authentication/
813 | git commit -m "spec(001): approve design phase"
814 |
815 | # Branch naming
816 | git checkout -b feature/001-user-authentication
817 | git checkout -b spec/001-requirements
818 | ```
819 |
820 | ## Troubleshooting
821 |
822 | ### Common Issues and Solutions
823 |
824 | #### "No active spec" Error
825 | ```bash
826 | # Check current spec
827 | cat spec/.current-spec
828 |
829 | # If empty, set it manually
830 | echo "001-user-authentication" > spec/.current-spec # Use the full directory name
831 |
832 | # Or use switch command
833 | /spec:switch 001-user-authentication
834 | ```
835 |
836 | #### Phase Not Approved
837 | ```bash
838 | # Check approval status
839 | ls -la spec/001-user-authentication/.*-approved
840 |
841 | # Approve if ready
842 | /spec:approve requirements
843 | ```
844 |
845 | #### Tasks Not Updating
846 | ```bash
847 | # Ensure you're using Write tool in Claude
848 | # When updating tasks, be specific:
849 | /spec:update-task "exact task description"
850 |
851 | # Or manually edit and have Claude read
852 | vi spec/001-user-authentication/tasks.md
853 | ```
854 |
855 | #### Command Not Found
856 | ```bash
857 | # Check command exists
858 | ls .claude/commands/spec/
859 |
860 | # Ensure .md extension
861 | ls .claude/commands/spec/new.md
862 |
863 | # Commands should appear in
864 | /help
865 | ```
866 |
867 | ## Advanced Usage
868 |
869 | ### Creating Project Templates
870 |
871 | Create reusable templates for common project types:
872 |
873 | ```bash
874 | # Create template directory
875 | mkdir -p .claude/templates/web-api
876 |
877 | # Add template files
878 | cp spec/001-user-authentication/requirements.md .claude/templates/web-api/
879 | cp spec/001-user-authentication/design.md .claude/templates/web-api/
880 | ```
881 |
882 | ### Automated Status Reports
883 |
884 | Create a status report command:
885 |
886 | ```markdown
887 | # .claude/commands/spec/report.md
888 | ---
889 | allowed-tools: Bash(find:*), Bash(grep:*), Bash(date:*)
890 | description: Generate comprehensive spec report
891 | ---
892 |
893 | Generate a markdown report showing:
894 | - All specifications and their status
895 | - Task completion percentages
896 | - Timeline adherence
897 | - Blocked items
898 | - Next actions for each spec
899 | ```
900 |
901 | ### Integration with Issue Trackers
902 |
903 | Link specs to GitHub issues:
904 |
905 | ```markdown
906 | # In your spec files, reference issues
907 | ## Related Issues
908 | - Implements: #123
909 | - Fixes: #124, #125
910 | - Related to: #126
911 | ```
912 |
913 | ### Multi-Phase Implementation
914 |
915 | For large features, split implementation:
916 |
917 | ```bash
918 | /spec:implement 1 # Complete Phase 1
919 | # Commit and test
920 |
921 | /spec:implement 2 # Move to Phase 2
922 | # Continue iteratively
923 | ```
924 |
925 | ### Spec Archival
926 |
927 | When specs are complete:
928 |
929 | ```bash
930 | # Create archive directory
931 | mkdir -p spec/archive/2024
932 |
933 | # Move completed specs
934 | mv spec/001-user-authentication spec/archive/2024/
935 |
936 | # Update current spec if needed
937 | echo "" > spec/.current-spec
938 | ```
939 |
940 | ## Tips for Success
941 |
942 | 1. **Start Small**: First spec should be a simple feature
943 | 2. **Be Specific**: Vague requirements lead to rework
944 | 3. **Review Often**: Check `/spec:status` regularly
945 | 4. **Commit Frequently**: Keep specs in version control
946 | 5. **Iterate**: Specs can evolve, but track changes
947 | 6. **Team Alignment**: Share specs for review before approval
948 | 7. **Learn and Adapt**: Refine templates based on experience
949 |
950 | ## Conclusion
951 |
952 | This spec-driven workflow brings professional software development practices to AI-assisted coding. By separating planning from implementation and leveraging Claude Code's custom commands, you maintain control while maximizing productivity.
953 |
954 | ### Key Takeaways
955 |
956 | 1. **Structure enables creativity** - Clear specs let Claude focus on quality implementation
957 | 2. **Commands enforce discipline** - Slash commands guide the workflow naturally
958 | 3. **Documentation is automation** - Well-written specs reduce ambiguity
959 | 4. **Progress tracking builds confidence** - Always know where you are
960 |
961 | ### Next Steps
962 |
963 | 1. Install the commands in your project
964 | 2. Create your first spec with `/spec:new`
965 | 3. Follow the workflow for one complete feature
966 | 4. Refine templates based on your needs
967 | 5. Share with your team
968 |
969 | ---
970 |
971 | *Happy spec-driven development with Claude Code!*
--------------------------------------------------------------------------------