Files
memohanzi/CLAUDE.md
Stefan Hardegger 0bb7c4f5e6 Initial Commit
2025-11-18 08:16:12 +01:00

392 lines
11 KiB
Markdown

# Instructions for Claude Code
## Critical: Specification Adherence
**YOU MUST READ AND FOLLOW THE SPECIFICATION DOCUMENT FIRST.**
Before implementing ANY feature, you MUST:
1. Read the relevant section in `HANZI-LEARNING-APP-SPECIFICATION.md`
2. Follow the specification EXACTLY as written
3. Do NOT make up alternatives or "improvements" without explicit approval
4. Do NOT skip steps or combine milestones without explicit approval
5. Do NOT change the technology stack
6. Do NOT modify the data models without approval
**The specification is the single source of truth. Deviations require explicit user approval.**
---
## Project Overview
This is **MemoHanzi** (记汉字 - "Remember Hanzi"), a self-hosted Hanzi (Chinese character) learning application using spaced repetition (SM-2 algorithm).
**Tech Stack (DO NOT CHANGE):**
- Next.js 16 with TypeScript and App Router
- PostgreSQL 18 with Prisma ORM
- NextAuth.js v5 for authentication
- Tailwind CSS for styling
- Docker Compose for deployment with Nginx reverse proxy
- Vitest for unit/integration tests
- Playwright for E2E tests
**Key Files to Reference:**
- `/HANZI-LEARNING-APP-SPECIFICATION.md` - Complete specification (READ THIS FIRST)
- Note: Project name is **MemoHanzi**, use `memohanzi` for directory/database names
- `/prisma/schema.prisma` - Database schema (once created)
- `/src/actions/*` - Server Actions
- `/src/lib/learning/sm2.ts` - SM-2 algorithm (critical implementation)
---
## Implementation Rules
### Rule 1: Follow the Milestones Sequentially
The specification defines 12 milestones (weeks). You MUST:
- Complete milestones in order (1 → 2 → 3 → ...)
- Finish all tasks in a milestone before moving to the next
- Ask for approval before starting each new milestone
- Report completion status for each milestone
**Current Milestone:** 1
### Rule 2: Database Schema is Fixed
The Prisma schema in the specification is FINAL. You MUST:
- Implement the schema EXACTLY as specified
- Include ALL models: Language, Hanzi, HanziForm, HanziTranscription, HanziMeaning, HanziHSKLevel, HanziPOS, HanziClassifier, User, UserPreference, Account, Session, VerificationToken, Collection, CollectionItem, UserHanziProgress, LearningSession, SessionReview
- Include ALL enums: UserRole, CharacterDisplay, Difficulty
- Include ALL fields and relations as specified
- Do NOT add extra fields without approval
- Do NOT simplify or "optimize" the schema
### Rule 3: SM-2 Algorithm Must Be Exact
The SM-2 algorithm implementation is critical. You MUST:
- Use the EXACT formulas from Section 5 of the specification
- Initial values: easeFactor=2.5, interval=1, consecutiveCorrect=0
- Implement correct answer logic EXACTLY as specified
- Implement incorrect answer logic EXACTLY as specified
- Implement card selection algorithm EXACTLY as specified
- Write comprehensive unit tests (90%+ coverage)
**Do NOT:**
- Use a different spaced repetition algorithm
- "Improve" or "simplify" the algorithm
- Skip any calculation steps
### Rule 4: Server Actions Only (No REST API)
All data operations use Next.js Server Actions. You MUST:
- Implement Server Actions as specified in Section 4
- Return the standard `ActionResult<T>` type
- Validate with Zod schemas
- Check authentication/authorization
- Use `revalidatePath()` after mutations
- Do NOT create REST API endpoints (except for NextAuth)
### Rule 5: Follow the UI/UX Specification
Page structure is defined in Section 6. You MUST:
- Create pages at the EXACT routes specified
- Implement the specified components
- Use the specified layouts (mobile-first, responsive)
- Include ALL specified features per page
- Do NOT create pages not in the specification
### Rule 6: Testing is Mandatory
For each feature you implement:
- Write unit tests for business logic (70% coverage minimum)
- Write integration tests for Server Actions
- Write E2E tests for critical user flows
- All tests must pass before moving to next milestone
### Rule 7: Security Requirements are Non-Negotiable
You MUST implement ALL security measures:
- Password hashing with bcrypt (10 rounds) and salt
- NextAuth.js session management
- Middleware for route protection
- Role-based access control in Server Actions
- Input validation with Zod (client AND server)
- No sensitive data in logs or error messages
- Follow the security checklist in Section 11
### Rule 8: Docker Configuration is Fixed
Use the EXACT Docker setup from Section 10:
- Three containers: nginx, app, postgres
- PostgreSQL 18 (not other versions)
- Nginx for reverse proxy with rate limiting
- Do NOT change the docker-compose.yml structure without approval
---
## When You're Unsure
If you encounter ANY of these situations:
❌ The specification is unclear
❌ You think there's a better approach
❌ You want to add a feature not in the spec
❌ You want to change the tech stack
❌ You want to simplify something
❌ You're not sure how to implement something
**STOP and ASK THE USER first. Do NOT proceed with assumptions.**
---
## Milestone Checklist Template
Before claiming a milestone is complete, verify:
**Milestone [N]: [Name]**
- [ ] All tasks from specification completed
- [ ] Code follows specification exactly
- [ ] No deviations from specified approach
- [ ] Tests written and passing
- [ ] Codebase builds with docker compose
- [ ] Security requirements met
- [ ] Documentation updated
- [ ] User approval obtained
---
## Common Mistakes to Avoid
### ❌ DON'T DO THIS:
1. **"I'll use a simpler data model"** → NO. Use the exact schema specified.
2. **"I'll implement REST API instead of Server Actions"** → NO. Server Actions only.
3. **"I'll use a different algorithm"** → NO. SM-2 as specified.
4. **"I'll skip tests for now"** → NO. Tests are mandatory.
5. **"I'll use Next.js 15 instead"** → NO. Next.js 16 as specified.
6. **"I'll combine these two milestones"** → NO. Follow the sequence.
7. **"I'll add this nice feature"** → NO. Only spec features in MVP.
### ✅ DO THIS:
1. Read the specification section before implementing
2. Ask for clarification if unclear
3. Implement exactly as specified
4. Write tests as you go
5. Report progress and completion
6. Ask before deviating
7. Don't be overly friendly
---
## Startup Checklist
When starting implementation:
1. [ ] Read the complete specification document
2. [ ] Confirm understanding of the tech stack
3. [ ] Confirm understanding of the milestone approach
4. [ ] Ask user which milestone to start with
5. [ ] Review that milestone's tasks in detail
6. [ ] Begin implementation following the specification
---
## Data Import Reference
When implementing import (Milestone 3), remember:
**HSK JSON Source:** https://github.com/drkameleon/complete-hsk-vocabulary/
**Required Fields:**
- simplified (required)
- forms[].traditional (required)
- forms[].transcriptions.pinyin (required)
- forms[].meanings[] (required, at least one)
**Optional Fields:**
- radical, level[], frequency, pos[], classifiers[]
- Additional transcriptions (numeric, wadegiles, etc.)
**CSV Format:**
```
simplified,traditional,pinyin,meaning,hsk_level,radical,frequency,pos,classifiers
```
---
## SM-2 Algorithm Quick Reference
**CRITICAL: Use these EXACT formulas**
### On Correct Answer:
```javascript
if (consecutiveCorrect === 0) {
interval = 1
} else if (consecutiveCorrect === 1) {
interval = 6
} else {
interval = Math.round(interval * easeFactor)
}
easeFactor = easeFactor + 0.1
consecutiveCorrect++
nextReviewDate = now + interval days
```
### On Incorrect Answer:
```javascript
interval = 1
consecutiveCorrect = 0
nextReviewDate = now + 1 day
easeFactor = Math.max(1.3, easeFactor - 0.2)
```
**Test this thoroughly with unit tests!**
---
## Progress Reporting Format
When reporting progress, use this format:
```
## Milestone [N] Progress
**Status:** [In Progress / Completed / Blocked]
**Completed Tasks:**
- [x] Task 1
- [x] Task 2
**In Progress:**
- [ ] Task 3 (50% done)
**Remaining:**
- [ ] Task 4
- [ ] Task 5
**Questions/Issues:**
- [List any blockers or questions]
**Deviations from Spec:**
- [List any deviations - should be NONE without approval]
```
---
## File Naming Conventions
Follow these conventions:
- Server Actions: `src/actions/[domain].ts` (e.g., `auth.ts`, `learning.ts`)
- Components: `src/components/[category]/[ComponentName].tsx`
- Tests: Co-located with source as `[filename].test.ts`
- E2E tests: `e2e/[feature].spec.ts`
---
## Prisma Workflow
When working with the database:
```bash
# Create migration
npx prisma migrate dev --name descriptive_name
# Generate Prisma Client (after schema changes)
npx prisma generate
# Seed database
npx prisma db seed
# View data
npx prisma studio
```
**IMPORTANT:** Never edit migration files manually after they're created.
---
## Testing Commands
```bash
# Unit tests
npm run test:unit
# Integration tests
npm run test:integration
# E2E tests
npm run test:e2e
# All tests
npm run test:ci
# Watch mode (during development)
npm run test:watch
```
---
# Communication Guidelines
## Avoid Sycophantic Language
- **NEVER** use phrases like "You're absolutely right!", "You're absolutely correct!", "Excellent point!", or similar flattery
- **NEVER** validate statements as "right" when the user didn't make a factual claim that could be evaluated
- **NEVER** use general praise or validation as conversational filler
- **NEVER** state that the code works now or a fix has been successfully implemented without building and verifying it first
## Appropriate Acknowledgments
Use brief, factual acknowledgments only to confirm understanding of instructions:
- "Got it."
- "Ok, that makes sense."
- "I understand."
- "I see the issue."
These should only be used when:
1. You genuinely understand the instruction and its reasoning
2. The acknowledgment adds clarity about what you'll do next
3. You're confirming understanding of a technical requirement or constraint
## Examples
### ❌ Inappropriate (Sycophantic)
User: "Yes please."
Assistant: "You're absolutely right! That's a great decision."
User: "Let's remove this unused code."
Assistant: "Excellent point! You're absolutely correct that we should clean this up."
### ✅ Appropriate (Brief Acknowledgment)
User: "Yes please."
Assistant: "Got it." [proceeds with the requested action]
User: "Let's remove this unused code."
Assistant: "I'll remove the unused code path." [proceeds with removal]
### ✅ Also Appropriate (No Acknowledgment)
User: "Yes please."
Assistant: [proceeds directly with the requested action]
## Rationale
- Maintains professional, technical communication
- Avoids artificial validation of non-factual statements
- Focuses on understanding and execution rather than praise
- Prevents misrepresenting user statements as claims that could be "right" or "wrong"
---
## Final Reminder
**The specification document is LAW.**
If something in this CLAUDE.md file conflicts with the specification, the specification wins.
When in doubt:
1. Check the specification
2. If still unclear, ASK THE USER
3. Do NOT make assumptions
4. Do NOT deviate without approval
Your goal is to implement the specification accurately, not to improve it or take shortcuts.
**Good luck, and stick to the spec!** 🎯