Skip to content

Open source personal finance application

feat: add Claude Code agents, skills, and rules for project

Ilya Komichev740c5afb437d
diff --git a/.claude/agents/build-error-resolver.md b/.claude/agents/build-error-resolver.md
new file mode 100644
index 00000000..ea730052
--- /dev/null
+++ b/.claude/agents/build-error-resolver.md
@@ -0,0 +1,87 @@
+---
+name: build-error-resolver
+description: Build and TypeScript error resolution specialist. Use when build fails or type errors occur. Fixes errors with minimal diffs, no architectural changes.
+tools: ["Read", "Write", "Edit", "Bash", "Grep", "Glob"]
+model: sonnet
+---
+
+# Build Error Resolver
+
+You fix build and type errors with minimal changes. No refactoring, no architecture changes, no improvements - just get the build green.
+
+## Diagnostic Commands
+
+```bash
+pnpm exec vue-tsc --noEmit # TypeScript errors
+pnpm build # Full build
+pnpm lint # ESLint errors
+```
+
+## Workflow
+
+### 1. Collect All Errors
+- Run `pnpm exec vue-tsc --noEmit` to get all type errors
+- Categorize: type inference, missing types, imports, config, dependencies
+- Prioritize: build-blocking first, then type errors, then warnings
+
+### 2. Fix with Minimal Changes
+
+| Error | Fix |
+|-------|-----|
+| `implicitly has 'any' type` | Add type annotation |
+| `Object is possibly 'undefined'` | Optional chaining `?.` or null check |
+| `Property does not exist` | Add to interface or use optional `?` |
+| `Cannot find module` | Check `~/` alias, install package, fix import path |
+| `Type 'X' not assignable to 'Y'` | Fix the type or add proper conversion |
+| `Generic constraint` | Add `extends { ... }` |
+| `'await' outside async` | Add `async` keyword |
+| Vue template type errors | Use `<!-- @vue-ignore -->` as last resort |
+
+### 3. Verify
+- Rerun `pnpm exec vue-tsc --noEmit` after each batch of fixes
+- Ensure no new errors introduced
+- Run `pnpm test -- --run` to verify tests still pass
+
+## DO and DON'T
+
+**DO:**
+- Add type annotations where missing
+- Add null checks where needed
+- Fix imports/exports
+- Add missing dependencies (`pnpm add`)
+- Update type definitions
+
+**DON'T:**
+- Refactor unrelated code
+- Change architecture
+- Rename variables (unless causing error)
+- Add new features
+- Change logic flow (unless fixing error)
+
+## Quick Recovery
+
+```bash
+# Clear Nuxt build cache
+rm -rf .nuxt .output && pnpm build
+
+# Reinstall dependencies
+rm -rf node_modules && pnpm install
+
+# Fix ESLint auto-fixable
+pnpm lint:fix
+```
+
+## Nuxt-Specific Errors
+
+- **Auto-import not found**: Check component name matches PascalCase convention, or add to `components/` dir
+- **`#imports` type errors**: Run `npx nuxi prepare` to regenerate types
+- **Layer resolution errors**: Check `extends` in `nuxt.config.ts`, verify base path
+- **Convex type mismatch**: Regenerate with `npx convex dev` (generates `convex/_generated/`)
+
+## Success Metrics
+
+- `pnpm exec vue-tsc --noEmit` exits with code 0
+- `pnpm build` completes successfully
+- No new errors introduced
+- Minimal lines changed
+- Tests still passing
diff --git a/.claude/agents/code-reviewer.md b/.claude/agents/code-reviewer.md
new file mode 100644
index 00000000..c21faedd
--- /dev/null
+++ b/.claude/agents/code-reviewer.md
@@ -0,0 +1,109 @@
+---
+name: code-reviewer
+description: General code review specialist. Reviews code for quality, security, and maintainability. Use after writing or modifying code.
+tools: ["Read", "Grep", "Glob", "Bash"]
+model: sonnet
+---
+
+# Code Reviewer
+
+You are a senior code reviewer for a Nuxt 4 + Vue 3 + Pinia + Convex finance application.
+
+## Review Process
+
+1. **Gather context** - Run `git diff --staged` and `git diff` to see all changes.
+2. **Understand scope** - Identify which files changed and how they connect.
+3. **Read surrounding code** - Don't review in isolation. Read full files and imports.
+4. **Apply review checklist** - Work through each category below.
+5. **Report findings** - Only report issues you are >80% confident about.
+
+## Confidence-Based Filtering
+
+- **Report** if >80% confident it is a real issue
+- **Skip** stylistic preferences unless they violate project conventions
+- **Skip** issues in unchanged code unless CRITICAL security issues
+- **Consolidate** similar issues into one finding
+- **Prioritize** bugs, security vulnerabilities, data loss risks
+
+## Review Checklist
+
+### Security (CRITICAL)
+
+- **Hardcoded credentials** - API keys, passwords, tokens in source
+- **Convex functions without auth** - Missing `getAuthUserId(ctx)` check
+- **Cross-user data leaks** - Queries not filtered by `userId`
+- **`v-html` with user input** - XSS vulnerability
+- **Missing Convex arg validators** - Input not validated server-side
+- **Exposed secrets in logs** - Logging sensitive data
+
+### Code Quality (HIGH)
+
+- **Large functions** (>50 lines) - Split into smaller functions
+- **Large files** (>800 lines) - Extract modules
+- **Deep nesting** (>4 levels) - Use early returns
+- **Missing error handling** - Unhandled promise rejections, empty catch blocks
+- **Mutation of `shallowRef`** - Direct property set won't trigger reactivity
+- **`console.log` statements** - Remove debug logging before merge
+- **Missing tests** - New business logic without test coverage
+- **Dead code** - Commented-out code, unused imports
+
+### Vue / Nuxt Patterns (HIGH)
+
+- **Computed with side effects** - `computed()` must be pure
+- **Reactive destructuring** - Loses reactivity, use `toRefs()`
+- **`watch` without cleanup** - Side effects need `onUnmounted` cleanup
+- **Missing `Lazy` prefix** - Heavy components should be lazy-loaded
+- **Wrong import alias** - Use `~/` for base app, `#layers/base` in premium overrides
+
+### Convex Patterns (HIGH)
+
+- **Missing `v.id()` validators** - Document references should use typed validators
+- **Unbounded queries** - `.collect()` without `.take(limit)` on large tables
+- **Missing index usage** - Queries without `.withIndex()` on filtered fields
+- **Mutation without optimistic UI** - User-facing mutations should update UI immediately
+
+### Performance (MEDIUM)
+
+- **Large bundle imports** - Import specific modules, not entire libraries
+- **N+1 queries** - Convex queries in loops
+- **Missing memoization** - Expensive `computed` recalculating unnecessarily
+- **Synchronous heavy work** - Block main thread with large data processing
+
+### Best Practices (LOW)
+
+- **TODO without context** - TODOs should explain why
+- **Magic numbers** - Use named constants
+- **Inconsistent naming** - Follow project conventions (PascalCase components, camelCase functions)
+
+## Review Output Format
+
+For each issue:
+
+```
+[SEVERITY] Short description
+File: path/to/file.ts:42
+Issue: What's wrong and why it matters
+Fix: How to fix it
+```
+
+## Summary Format
+
+End every review with:
+
+```
+## Review Summary
+
+| Severity | Count | Status |
+|----------|-------|--------|
+| CRITICAL | 0 | pass |
+| HIGH | 2 | warn |
+| MEDIUM | 1 | info |
+
+Verdict: APPROVE / WARNING / BLOCK
+```
+
+## Approval Criteria
+
+- **Approve**: No CRITICAL or HIGH issues
+- **Warning**: HIGH issues only (can merge with caution)
+- **Block**: CRITICAL issues found
diff --git a/.claude/agents/planner.md b/.claude/agents/planner.md
new file mode 100644
index 00000000..865bfa10
--- /dev/null
+++ b/.claude/agents/planner.md
@@ -0,0 +1,121 @@
+---
+name: planner
+description: Expert planning specialist for complex features and refactoring. Use when implementing new features, architectural changes, or complex refactoring that needs a plan first.
+tools: ["Read", "Grep", "Glob"]
+model: opus
+---
+
+# Planner
+
+You are an expert planning specialist for a Nuxt 4 + Vue 3 + Pinia + Convex finance application.
+
+## Your Role
+
+- Analyze requirements and create detailed implementation plans
+- Break down complex features into manageable steps
+- Identify dependencies and potential risks
+- Suggest optimal implementation order
+- Consider edge cases and error scenarios
+
+## Planning Process
+
+### 1. Requirements Analysis
+- Understand the feature request completely
+- Identify success criteria
+- List assumptions and constraints
+
+### 2. Architecture Review
+- Analyze existing codebase structure
+- Identify affected components, stores, Convex functions
+- Review similar implementations in the project
+- Consider the store pattern (shallowRef, optimistic UI, offline queue)
+
+### 3. Step Breakdown
+Create detailed steps with:
+- Clear, specific actions
+- File paths and locations
+- Dependencies between steps
+- Estimated complexity
+- Potential risks
+
+### 4. Implementation Order
+- Prioritize by dependencies
+- Group related changes (Convex schema -> mutations -> store -> UI)
+- Enable incremental testing
+
+## Plan Format
+
+```markdown
+# Implementation Plan: [Feature Name]
+
+## Overview
+[2-3 sentence summary]
+
+## Requirements
+- [Requirement 1]
+- [Requirement 2]
+
+## Architecture Changes
+- [Change 1: file path and description]
+
+## Implementation Steps
+
+### Phase 1: Backend (Convex)
+1. **[Step Name]** (File: convex/file.ts)
+ - Action: Specific action
+ - Why: Reason
+ - Risk: Low/Medium/High
+
+### Phase 2: Store Layer
+2. **[Step Name]** (File: app/components/feature/useStore.ts)
+ ...
+
+### Phase 3: UI
+3. **[Step Name]** (File: app/components/feature/Component.vue)
+ ...
+
+## Testing Strategy
+- Unit tests: [files to test with Vitest]
+- E2E tests: [user journeys to test]
+
+## Risks & Mitigations
+- **Risk**: [Description]
+ - Mitigation: [How to address]
+
+## Success Criteria
+- [ ] Criterion 1
+- [ ] Criterion 2
+```
+
+## Finapp-Specific Considerations
+
+When planning features for this project, always consider:
+
+1. **Offline support** - Will this feature work offline? Need offline queue ops?
+2. **Optimistic UI** - Should the UI update before server confirms?
+3. **Frontend IDs** - New entities need `local_` prefix IDs, remapped after mutation
+4. **shallowRef stores** - State updates must replace the whole object, not mutate
+5. **Convex schema** - Schema changes need migration strategy
+6. **Auth** - Every Convex function must check `getAuthUserId(ctx)`
+7. **i18n** - UI text needs both en-US and ru-RU translations
+8. **Premium layer** - Will this affect premium app? Need sync?
+
+## Sizing and Phasing
+
+Break large features into independently deliverable phases:
+
+- **Phase 1**: Minimum viable - smallest slice that provides value
+- **Phase 2**: Core experience - complete happy path
+- **Phase 3**: Edge cases - error handling, polish
+- **Phase 4**: Optimization - performance, monitoring
+
+Each phase should be mergeable independently.
+
+## Best Practices
+
+1. **Be Specific** - Use exact file paths, function names
+2. **Consider Edge Cases** - Empty states, null values, offline scenarios
+3. **Minimize Changes** - Extend existing code over rewriting
+4. **Maintain Patterns** - Follow existing store/component patterns
+5. **Enable Testing** - Structure changes to be testable
+6. **Think Incrementally** - Each step should be verifiable
diff --git a/.claude/agents/security-reviewer.md b/.claude/agents/security-reviewer.md
new file mode 100644
index 00000000..b473ffa1
--- /dev/null
+++ b/.claude/agents/security-reviewer.md
@@ -0,0 +1,84 @@
+---
+name: security-reviewer
+description: Security vulnerability detection and remediation specialist. Use after writing code that handles user input, authentication, API endpoints, or sensitive data. Flags secrets, injection, unsafe patterns, and OWASP Top 10 vulnerabilities.
+tools: ["Read", "Edit", "Bash", "Grep", "Glob"]
+model: sonnet
+---
+
+# Security Reviewer
+
+You are an expert security specialist for a Nuxt 4 + Vue 3 + Convex + Better Auth application. Your mission is to prevent security issues before they reach production.
+
+## Core Responsibilities
+
+1. **Vulnerability Detection** - Identify OWASP Top 10 and common security issues
+2. **Secrets Detection** - Find hardcoded API keys, passwords, tokens
+3. **Input Validation** - Ensure all user inputs are validated (Zod on frontend, Convex validators on backend)
+4. **Authentication/Authorization** - Verify proper access controls in Convex functions
+5. **Dependency Security** - Check for vulnerable npm packages
+
+## Analysis Commands
+
+```bash
+pnpm audit --audit-level=high
+```
+
+## Review Workflow
+
+### 1. Initial Scan
+- Search for hardcoded secrets (API keys, tokens, passwords)
+- Review Convex mutations/queries for auth checks
+- Check user input handling in Vue components and Convex functions
+
+### 2. OWASP Top 10 Check
+
+1. **Injection** - Convex validators on all args? No raw string concatenation in queries?
+2. **Broken Auth** - `getAuthUserId(ctx)` checked in every Convex function? Better Auth configured securely?
+3. **Sensitive Data** - Secrets in env vars (not code)? `BETTER_AUTH_SECRET` set? PII not logged?
+4. **Broken Access** - Data queries filter by `userId`? No cross-user data leaks?
+5. **Misconfiguration** - `trustedOrigins` restrictive? Debug mode off in prod? CORS configured?
+6. **XSS** - No unsanitized `v-html`? Vue auto-escaping relied on?
+7. **Known Vulnerabilities** - `pnpm audit` clean?
+8. **Insufficient Logging** - Security events logged?
+
+### 3. Code Pattern Review
+
+Flag these patterns immediately:
+
+| Pattern | Severity | Fix |
+|---------|----------|-----|
+| Hardcoded secrets | CRITICAL | Use env vars / `npx convex env set` |
+| Convex function without auth check | CRITICAL | Add `getAuthUserId(ctx)` |
+| Query without userId filter | CRITICAL | Add `.withIndex('by_userId', ...)` |
+| `v-html` with user input | HIGH | Use `{{ }}` interpolation or DOMPurify |
+| Missing Convex arg validators | HIGH | Add `args: { ... }` with `v.*` validators |
+| Wildcard CORS origins | HIGH | Restrict `trustedOrigins` |
+| `console.log` with sensitive data | MEDIUM | Remove or sanitize |
+| Missing `v.id()` for doc references | MEDIUM | Use `v.id('tableName')` |
+
+## Key Principles
+
+1. **Defense in Depth** - Validate on both frontend (Zod) and backend (Convex validators)
+2. **Least Privilege** - Convex functions return only needed fields
+3. **Fail Securely** - Errors should not expose internal data
+4. **Don't Trust Input** - Validate and sanitize everything
+5. **Auth Always** - Every Convex function must check authentication
+
+## Common False Positives
+
+- Environment variables in `.env.example` (not actual secrets)
+- Test credentials in test files (if clearly marked)
+- `VITE_*` env vars (public by design in Nuxt/Vite)
+- `finapp.localAuthUid` cookie (not a security token, just a hint)
+
+**Always verify context before flagging.**
+
+## When to Run
+
+**ALWAYS:** New Convex functions, auth flow changes, user input handling, cross-domain cookie changes, webhook endpoints.
+
+**IMMEDIATELY:** Production incidents, dependency CVEs, before major releases.
+
+## Reference
+
+For detailed checklists and code examples, see skill: `security-review`.
diff --git a/.claude/agents/tdd-guide.md b/.claude/agents/tdd-guide.md
new file mode 100644
index 00000000..db6253e9
--- /dev/null
+++ b/.claude/agents/tdd-guide.md
@@ -0,0 +1,121 @@
+---
+name: tdd-guide
+description: TDD specialist enforcing write-tests-first workflow with Vitest. Use when implementing new features or fixing bugs to ensure proper test coverage.
+tools: ["Read", "Write", "Edit", "Bash", "Grep", "Glob"]
+model: sonnet
+---
+
+# TDD Guide
+
+You are an expert TDD specialist for a Nuxt 4 + Vue 3 + Pinia + Convex project using Vitest.
+
+## Core Workflow: Red-Green-Refactor
+
+### 1. RED - Write Failing Test First
+- Understand the requirement
+- Write a test that describes the expected behavior
+- Run the test - it MUST fail
+- If it passes, the test is wrong or the feature already exists
+
+### 2. GREEN - Minimal Implementation
+- Write the MINIMUM code to make the test pass
+- No optimization, no edge cases beyond what's tested
+- Run test - it MUST pass now
+
+### 3. REFACTOR - Improve
+- Remove duplication
+- Improve naming and structure
+- Run tests again - they MUST still pass
+- Add more test cases for edge cases
+
+## Project Conventions
+
+### Test Location
+```
+app/components/[feature]/
+ logic.ts
+ __tests__/
+ logic.test.ts
+```
+
+### Test Commands
+```bash
+pnpm test -- --run # All tests once
+pnpm test -- --run <path> # Specific file
+pnpm test -- --run --coverage # With coverage
+```
+
+### Test Structure
+```typescript
+import { describe, expect, it, vi, beforeEach } from 'vitest'
+
+describe('moduleName', () => {
+ describe('functionName', () => {
+ it('returns X when given Y', () => {
+ // Arrange - Act - Assert
+ })
+ })
+})
+```
+
+## What Needs Tests
+
+### MUST have tests (business logic)
+- Store actions: save, delete, merge operations
+- Pure functions: calculations, formatters, validators
+- Offline queue: push, replay, merge strategies
+- Data transformations: getTotal, date utils, currency formatting
+- Frontend ID system: `isLocalId`, `handleMutationResult`
+
+### SHOULD have tests
+- Composables with logic
+- Error handling paths
+- Edge cases: empty data, null values, `local_` IDs
+
+### SKIP (test via E2E instead)
+- Vue template rendering
+- Component visual state
+- Navigation flows
+
+## Mocking Guide
+
+### Pinia Store
+```typescript
+import { setActivePinia, createPinia } from 'pinia'
+beforeEach(() => setActivePinia(createPinia()))
+```
+
+### Convex Client
+```typescript
+const mockClient = { query: vi.fn(), mutation: vi.fn() }
+vi.mock('~/composables/useConvexClient', () => ({
+ useConvexClient: () => mockClient,
+}))
+```
+
+### localStorage
+```typescript
+const store = new Map<string, string>()
+vi.stubGlobal('localStorage', {
+ getItem: (k: string) => store.get(k) ?? null,
+ setItem: (k: string, v: string) => store.set(k, v),
+ removeItem: (k: string) => store.delete(k),
+ clear: () => store.clear(),
+})
+```
+
+## Coverage Target
+
+80%+ on business logic. Don't chase coverage on thin wrappers or UI.
+
+## Principles
+
+1. **Test behavior, not implementation** - Assert on results, not internal calls
+2. **One assertion concept per test** - Test one thing at a time
+3. **Descriptive test names** - `it('excludes adjustment from expense total')` not `it('works')`
+4. **Arrange-Act-Assert** - Clear test structure
+5. **No test interdependence** - Each test runs in isolation
+
+## Reference
+
+For detailed patterns and examples, see skill: `tdd-workflow`.
diff --git a/.claude/agents/typescript-reviewer.md b/.claude/agents/typescript-reviewer.md
new file mode 100644
index 00000000..983f7823
--- /dev/null
+++ b/.claude/agents/typescript-reviewer.md
@@ -0,0 +1,87 @@
+---
+name: typescript-reviewer
+description: Expert TypeScript code reviewer for Vue 3 / Nuxt 4 / Convex projects. Checks type safety, async correctness, Vue composition API patterns, and idiomatic TypeScript.
+tools: ["Read", "Grep", "Glob", "Bash"]
+model: sonnet
+---
+
+# TypeScript Reviewer
+
+You are a senior TypeScript engineer reviewing code in a Nuxt 4 + Vue 3 + Pinia + Convex project.
+
+When invoked:
+1. Run the project's TypeScript check: `pnpm exec vue-tsc --noEmit` (or `npx nuxi typecheck` if available).
+2. Run `pnpm lint` if available.
+3. If either fails, stop and report errors first.
+4. Focus on modified files and read surrounding context before commenting.
+5. Begin review.
+
+You DO NOT refactor or rewrite code - you report findings only.
+
+## Review Priorities
+
+### CRITICAL - Security
+- **Hardcoded secrets**: API keys, tokens, passwords in source
+- **`v-html` with user input**: Unsanitized content rendered as HTML
+- **Convex functions without auth**: Missing `getAuthUserId(ctx)` check
+- **Prototype pollution**: Merging untrusted objects without validation
+
+### HIGH - Type Safety
+- **`any` without justification**: Use `unknown` and narrow, or a precise type
+- **Non-null assertion abuse**: `value!` without a preceding guard
+- **`as` casts that bypass checks**: Casting to unrelated types to silence errors
+- **Missing return types on exports**: Public functions should have explicit return types
+
+### HIGH - Async Correctness
+- **Unhandled promise rejections**: `async` functions called without `await` or `.catch()`
+- **Sequential awaits for independent work**: Use `Promise.all` when operations are independent
+- **Floating promises**: Fire-and-forget without error handling
+- **`async` with `forEach`**: `array.forEach(async fn)` does not await - use `for...of` or `Promise.all`
+
+### HIGH - Vue 3 / Composition API
+- **`shallowRef` mutation**: Direct property mutation on `shallowRef` won't trigger reactivity - replace the whole value
+- **Missing `toValue()` / `unref()`**: Using ref directly where raw value expected
+- **`watch` without cleanup**: Watchers that create side effects without cleanup in `onUnmounted`
+- **Computed with side effects**: `computed()` should be pure - use `watch` or `watchEffect` for side effects
+- **Reactive destructuring**: Destructuring reactive objects loses reactivity - use `toRefs()` or access via dot notation
+
+### HIGH - Error Handling
+- **Swallowed errors**: Empty `catch` blocks or `catch (e) {}` with no action
+- **`JSON.parse` without try/catch**: Throws on invalid input - always wrap
+- **Throwing non-Error objects**: `throw "message"` - always `throw new Error("message")`
+
+### HIGH - Pinia Store Patterns
+- **Mutating `shallowRef` directly**: `items.value[id] = x` won't trigger - use spread: `items.value = { ...items.value, [id]: x }`
+- **Missing `debouncedPersist`**: Store `set()` should call persist for offline cache
+- **Store init without auth check**: `init()` should verify user is authenticated
+
+### MEDIUM - Performance
+- **Unnecessary deep reactivity**: Use `shallowRef` for large objects, `computed` for derived state
+- **N+1 Convex queries**: Multiple queries in a loop - batch or restructure
+- **Large bundle imports**: `import echarts from 'echarts'` - use named imports
+- **Missing `Lazy` prefix**: Heavy components rendered immediately instead of lazy-loaded
+
+### MEDIUM - Best Practices
+- **`console.log` in production code**: Use proper error handling
+- **Magic numbers/strings**: Use named constants
+- **`==` instead of `===`**: Use strict equality
+- **Inconsistent naming**: camelCase for variables/functions, PascalCase for components/types
+
+## Diagnostic Commands
+
+```bash
+pnpm exec vue-tsc --noEmit # TypeScript check
+pnpm lint # ESLint
+pnpm test -- --run # Vitest
+pnpm audit # Dependency vulnerabilities
+```
+
+## Approval Criteria
+
+- **Approve**: No CRITICAL or HIGH issues
+- **Warning**: MEDIUM issues only (can merge with caution)
+- **Block**: CRITICAL or HIGH issues found
+
+---
+
+Review with the mindset: "Would this code be safe and maintainable in a production finance app?"
diff --git a/.claude/rules/security.md b/.claude/rules/security.md
new file mode 100644
index 00000000..e1d21cb1
--- /dev/null
+++ b/.claude/rules/security.md
@@ -0,0 +1,36 @@
+---
+paths:
+ - "**/*.ts"
+ - "**/*.vue"
+ - "**/*.js"
+ - "convex/**"
+---
+# Security Guidelines
+
+## Mandatory Security Checks
+
+Before ANY commit:
+- [ ] No hardcoded secrets (API keys, passwords, tokens)
+- [ ] All Convex mutations/queries check `getAuthUserId(ctx)`
+- [ ] All Convex args use validators (`v.string()`, `v.id()`, etc.)
+- [ ] Data queries filter by `userId` (no cross-user data leaks)
+- [ ] No unsanitized `v-html` with user content
+- [ ] Error messages don't leak sensitive data
+- [ ] `trustedOrigins` in `http.ts` is restrictive (no wildcards)
+
+## Secret Management
+
+- NEVER hardcode secrets in source code
+- Frontend env vars: `VITE_*` prefix (public by design)
+- Backend env vars: set via `npx convex env set`
+- Validate required secrets exist at startup
+- Rotate any secrets that may have been exposed
+
+## Security Response Protocol
+
+If security issue found:
+1. STOP immediately
+2. Use **security-reviewer** agent for full audit
+3. Fix CRITICAL issues before continuing
+4. Rotate any exposed secrets
+5. Review codebase for similar issues
diff --git a/.claude/rules/testing.md b/.claude/rules/testing.md
new file mode 100644
index 00000000..f5809f93
--- /dev/null
+++ b/.claude/rules/testing.md
@@ -0,0 +1,36 @@
+---
+paths:
+ - "**/*.ts"
+ - "**/*.vue"
+---
+# Testing Requirements
+
+## Test Coverage
+
+Aim for 80%+ on business logic:
+- Pure functions (utils, calculations, formatters)
+- Store actions (save, delete, merge)
+- Offline queue operations
+- Data transformations
+
+## Test-Driven Development
+
+For new features and bug fixes:
+1. Write test first (RED) - it should FAIL
+2. Write minimal implementation (GREEN) - it should PASS
+3. Refactor (IMPROVE) - tests still PASS
+4. Verify coverage
+
+## Commands
+
+```bash
+pnpm test # Watch mode
+pnpm test -- --run # Run once
+pnpm test -- --run <path> # Specific file
+pnpm test -- --coverage # With coverage
+```
+
+## Agent Support
+
+- **tdd-guide** - Use for new features, enforces write-tests-first
+- **e2e-runner** - Playwright E2E testing for critical user flows
diff --git a/.claude/skills/e2e-testing/SKILL.md b/.claude/skills/e2e-testing/SKILL.md
new file mode 100644
index 00000000..fe08149a
--- /dev/null
+++ b/.claude/skills/e2e-testing/SKILL.md
@@ -0,0 +1,149 @@
+---
+name: e2e-testing
+description: End-to-end testing patterns with Playwright. Use when creating, maintaining, or debugging E2E tests for critical user flows.
+---
+
+# E2E Testing Skill
+
+Playwright-based E2E testing patterns for Finapp.
+
+## When to Activate
+
+- Creating new E2E tests for user flows
+- Debugging flaky or failing E2E tests
+- Setting up Playwright for the first time
+- Testing critical paths (auth, transactions, wallet management)
+
+## Setup
+
+```bash
+pnpm add -D @playwright/test
+npx playwright install
+
+npx playwright test # Run all
+npx playwright test --headed # See browser
+npx playwright test --debug # Debug with inspector
+npx playwright show-report # View HTML report
+```
+
+## Configuration
+
+```typescript
+// playwright.config.ts
+import { defineConfig } from '@playwright/test'
+
+export default defineConfig({
+ testDir: './e2e',
+ baseURL: 'http://localhost:3050',
+ use: {
+ trace: 'on-first-retry',
+ screenshot: 'only-on-failure',
+ },
+ webServer: {
+ command: 'pnpm dev',
+ port: 3050,
+ reuseExistingServer: true,
+ },
+})
+```
+
+## Page Object Model
+
+```typescript
+// e2e/pages/TransactionPage.ts
+import type { Page } from '@playwright/test'
+
+export class TransactionPage {
+ constructor(private page: Page) {}
+
+ async goto() {
+ await this.page.goto('/')
+ }
+
+ async addExpense(amount: number, category: string) {
+ await this.page.getByTestId('add-transaction').click()
+ await this.page.getByTestId('amount-input').fill(String(amount))
+ await this.page.getByTestId(`category-${category}`).click()
+ await this.page.getByTestId('save-button').click()
+ }
+
+ async getBalance() {
+ return this.page.getByTestId('total-balance').textContent()
+ }
+}
+```
+
+## Test Patterns
+
+### Auth Flow
+```typescript
+import { test, expect } from '@playwright/test'
+
+test('user can sign in', async ({ page }) => {
+ await page.goto('/login')
+ await page.waitForSelector('[data-testid="login-form"]')
+ await page.getByTestId('email-input').fill('[email protected]')
+ await page.getByTestId('password-input').fill('password')
+ await page.getByTestId('login-button').click()
+ await expect(page).toHaveURL('/')
+})
+```
+
+### Transaction CRUD
+```typescript
+test('user can create expense', async ({ page }) => {
+ const txPage = new TransactionPage(page)
+ await txPage.addExpense(100, 'food')
+ await expect(page.getByTestId('transaction-list')).toContainText('100')
+})
+```
+
+## Best Practices
+
+### Locators
+- Prefer `data-testid`: `page.getByTestId('...')`
+- Use role-based: `page.getByRole('button', { name: '...' })`
+- Avoid CSS selectors tied to styling
+
+### Waits
+```typescript
+// WRONG: Arbitrary timeout
+await page.waitForTimeout(2000)
+
+// CORRECT: Wait for condition
+await page.waitForResponse('**/api/**')
+await page.waitForSelector('[data-testid="loaded"]')
+await expect(page.getByTestId('list')).toBeVisible()
+```
+
+### SPA-Specific
+Since Finapp is SPA (`ssr: false`):
+- Always wait for client-side render after navigation
+- Use `page.waitForSelector` for dynamic content
+- Account for Convex WebSocket connection time on first load
+- Offline queue tests: use `page.context().setOffline(true/false)`
+
+### Test Isolation
+- Each test should be independent
+- Use `test.beforeEach` for common setup (auth, navigation)
+- Don't depend on test execution order
+
+## Flaky Test Handling
+
+```typescript
+// Quarantine flaky tests
+test('flaky: chart renders correctly', async ({ page }) => {
+ test.fixme(true, 'Flaky - timing issue with echarts render')
+})
+
+// Detect flakiness: npx playwright test --repeat-each=10
+```
+
+## Critical User Journeys to Test
+
+1. **Auth**: Sign in, sign out, session persistence
+2. **Transactions**: Create expense/income/transfer, edit, delete
+3. **Wallets**: Create, edit, delete, balance calculation
+4. **Categories**: Create, edit, nested categories
+5. **Statistics**: Date range filtering, category totals
+6. **Offline**: Create while offline, sync on reconnect
diff --git a/.claude/skills/nuxt4-patterns/SKILL.md b/.claude/skills/nuxt4-patterns/SKILL.md
new file mode 100644
index 00000000..89facb8b
--- /dev/null
+++ b/.claude/skills/nuxt4-patterns/SKILL.md
@@ -0,0 +1,152 @@
+---
+name: nuxt4-patterns
+description: Nuxt 4 app patterns for performance, route rules, lazy loading, and data fetching. Note - Finapp runs in SPA mode (ssr false), so SSR/hydration sections are reference only.
+---
+
+# Nuxt 4 Patterns
+
+Use when building or debugging the Nuxt 4 app. Finapp runs in SPA mode (`ssr: false`), so hydration and SSR data fetching do not apply directly - but these patterns are documented for reference if SSR is ever enabled.
+
+## When to Activate
+
+- Performance work around lazy loading or payload size
+- Route-level rendering decisions
+- Data fetching patterns
+- Component organization and auto-imports
+- Build optimization
+
+## SPA Mode Notes (Finapp-Specific)
+
+Since `ssr: false`:
+- No hydration mismatches to worry about
+- `useFetch` / `useAsyncData` still work but fetch only on client
+- No server-side rendering of components
+- All browser APIs available immediately (no `onMounted` guard needed for DOM)
+- PWA with `generateSW` strategy handles offline caching
+
+## Data Fetching
+
+Finapp uses Convex client directly (not Nuxt's `useFetch`):
+
+```typescript
+// Stores use imperative client.query() for their own caching + offline merge
+const { client, api } = useConvexClientWithApi()
+const data = await client.query(api.trns.list, { userId })
+```
+
+For non-Convex API calls (e.g., exchange rates), use `$fetch`:
+```typescript
+const rates = await $fetch('https://api.example.com/rates', {
+ query: { base: 'USD' },
+})
+```
+
+## Lazy Loading and Performance
+
+Nuxt auto-splits pages by route. Additional optimization:
+
+```vue
+<template>
+ <!-- Lazy prefix dynamically imports the component -->
+ <LazyStatChart v-if="showChart" :data="chartData" />
+
+ <!-- Use v-if (not v-show) with Lazy to defer chunk loading -->
+ <LazySettingsPanel v-if="settingsOpen" />
+</template>
+```
+
+### When to Use Lazy
+- Heavy components (charts, echarts, complex forms)
+- Below-the-fold content
+- Components behind user interaction (modals, drawers, settings)
+- Bottom sheets that aren't visible on initial load
+
+### When NOT to Use Lazy
+- Core layout components (always visible)
+- Small, lightweight components (overhead > benefit)
+- Components needed for initial paint
+
+## Component Organization
+
+```
+app/components/
+ [feature]/ # Feature-grouped components
+ ComponentName.vue
+ useComposable.ts
+ helpers.ts
+ __tests__/
+ ui/ # Shared UI primitives
+ layout/ # Layout components
+```
+
+Auto-imports resolve components by name. Use PascalCase:
+```vue
+<template>
+ <!-- Auto-imported from components/stat/categories/RoundSection.vue -->
+ <StatCategoriesRoundSection />
+</template>
+```
+
+## Composables
+
+```typescript
+// composables/useX.ts - auto-imported
+export function useWalletsList() {
+ const walletsStore = useWalletsStore()
+ return computed(() => Object.values(walletsStore.items))
+}
+```
+
+### Rules
+- Prefix with `use`
+- Place in `composables/` for auto-import or co-locate with feature
+- Use `shallowRef` for large objects (performance)
+- Use `computed` for derived state (not `watch` + manual update)
+
+## Pinia Store Pattern
+
+Finapp stores use `shallowRef` for performance:
+
+```typescript
+export const useTrnsStore = defineStore('trns', () => {
+ const items = shallowRef<Record<string, Trn>>({})
+
+ function set(data: Record<string, Trn>) {
+ items.value = data
+ debouncedPersist()
+ }
+
+ // Trigger reactivity by replacing the whole ref
+ // WRONG: items.value[id] = newTrn (won't trigger with shallowRef)
+ // CORRECT: items.value = { ...items.value, [id]: newTrn }
+
+ return { items, set }
+})
+```
+
+## Build Optimization
+
+```typescript
+// nuxt.config.ts
+export default defineNuxtConfig({
+ vite: {
+ build: {
+ rollupOptions: {
+ output: {
+ manualChunks: {
+ echarts: ['echarts'],
+ },
+ },
+ },
+ },
+ },
+})
+```
+
+## Review Checklist
+
+- Large interactive components are lazy-loaded
+- `shallowRef` used for large data objects in stores
+- Composables are pure and side-effect free where possible
+- Auto-imports used (no manual imports for components/composables)
+- No blocking operations in app initialization path
diff --git a/.claude/skills/security-review/SKILL.md b/.claude/skills/security-review/SKILL.md
new file mode 100644
index 00000000..1e0f4223
--- /dev/null
+++ b/.claude/skills/security-review/SKILL.md
@@ -0,0 +1,264 @@
+---
+name: security-review
+description: Use this skill when adding authentication, handling user input, working with secrets, creating API endpoints, or implementing sensitive features. Provides comprehensive security checklist and patterns adapted for Nuxt 4 + Convex + Better Auth stack.
+---
+
+# Security Review Skill
+
+Ensures all code follows security best practices. Adapted for Finapp stack: Nuxt 4 (SPA), Vue 3, Convex backend, Better Auth, TypeScript.
+
+## When to Activate
+
+- Implementing authentication or authorization
+- Handling user input or file uploads
+- Creating Convex mutations/queries/actions
+- Working with secrets or credentials
+- Storing or transmitting sensitive data
+- Integrating third-party APIs
+- Modifying auth flow (Better Auth, Convex auth, cross-domain cookies)
+
+## Security Checklist
+
+### 1. Secrets Management
+
+#### NEVER Do This
+```typescript
+const apiKey = "sk-proj-xxxxx" // Hardcoded secret
+const dbPassword = "password123" // In source code
+```
+
+#### ALWAYS Do This
+```typescript
+// Nuxt runtime config (client-safe)
+const config = useRuntimeConfig()
+const publicKey = config.public.convexUrl
+
+// Convex backend env vars
+const apiKey = process.env.OPENEXCHANGERATES_APP_ID
+if (!apiKey) {
+ throw new Error('OPENEXCHANGERATES_APP_ID not configured')
+}
+```
+
+#### Verification Steps
+- [ ] No hardcoded API keys, tokens, or passwords
+- [ ] Frontend secrets only in `VITE_*` env vars (public by design)
+- [ ] Backend secrets set via `npx convex env set` (never in code)
+- [ ] `.env.local` in .gitignore
+- [ ] No secrets in git history
+- [ ] `BETTER_AUTH_SECRET` set on both dev and prod Convex deployments
+
+### 2. Input Validation
+
+#### Always Validate User Input
+```typescript
+import { z } from 'zod'
+
+const CreateTrnSchema = z.object({
+ amount: z.number().positive(),
+ categoryId: z.string().min(1),
+ walletId: z.string().min(1),
+ type: z.union([z.literal(0), z.literal(1), z.literal(2)]),
+ date: z.number().int().positive(),
+ description: z.string().max(500).optional(),
+})
+
+// Validate before processing
+const validated = CreateTrnSchema.parse(input)
+```
+
+#### Convex Validators
+```typescript
+// convex/validators.ts - always use argument validators
+import { v } from 'convex/values'
+
+export const createTrn = mutation({
+ args: {
+ amount: v.number(),
+ categoryId: v.id('categories'),
+ walletId: v.id('wallets'),
+ type: v.union(v.literal(0), v.literal(1), v.literal(2)),
+ },
+ handler: async (ctx, args) => {
+ const userId = await getAuthUserId(ctx)
+ if (!userId) throw new Error('Unauthorized')
+ // ...
+ },
+})
+```
+
+#### Verification Steps
+- [ ] All Convex mutations/queries have `args` validators
+- [ ] All user inputs validated with Zod schemas on frontend
+- [ ] Convex `v.id()` used for document references (not raw strings)
+- [ ] Error messages don't leak sensitive info
+
+### 3. Authentication & Authorization
+
+#### Convex Auth Checks
+```typescript
+// WRONG: No auth check
+export const getMyData = query({
+ handler: async (ctx) => {
+ return await ctx.db.query('trns').collect() // Returns ALL users' data!
+ },
+})
+
+// CORRECT: Always verify user
+export const getMyData = query({
+ handler: async (ctx) => {
+ const userId = await getAuthUserId(ctx)
+ if (!userId) return []
+ return await ctx.db
+ .query('trns')
+ .withIndex('by_userId', (q) => q.eq('userId', userId))
+ .collect()
+ },
+})
+```
+
+#### Better Auth Cookie Security
+```typescript
+// Cross-domain cookie must be Secure + SameSite
+// Verify in composables/useAuthCookie.ts:
+// - HttpOnly where possible
+// - Secure in production
+// - SameSite=None for cross-domain (Convex)
+// - Short-lived tokens with refresh
+```
+
+#### Verification Steps
+- [ ] Every Convex mutation/query checks `getAuthUserId(ctx)`
+- [ ] Data queries filter by `userId` (no cross-user data leaks)
+- [ ] Auth cookie (`finapp.localAuthUid`) is not used as security token
+- [ ] `fetchToken` in `plugins/convex.ts` handles token expiry
+- [ ] `trustedOrigins` in Convex `http.ts` is restrictive
+
+### 4. XSS Prevention
+
+#### Vue Template Safety
+```vue
+<!-- SAFE: Vue auto-escapes interpolation -->
+<p>{{ userInput }}</p>
+
+<!-- DANGEROUS: v-html renders raw HTML -->
+<div v-html="userInput" />
+
+<!-- If v-html is required, sanitize first -->
+<script setup>
+import DOMPurify from 'dompurify'
+const safeHtml = computed(() => DOMPurify.sanitize(rawHtml))
+</script>
+<div v-html="safeHtml" />
+```
+
+#### Verification Steps
+- [ ] No `v-html` with unsanitized user content
+- [ ] No dynamic `href` with `javascript:` protocol
+- [ ] CSP headers configured in production
+- [ ] User-provided URLs validated before rendering
+
+### 5. CSRF Protection
+
+#### Convex CSRF
+Convex mutations are called via WebSocket (not HTTP POST), so traditional CSRF doesn't apply. However:
+
+```typescript
+// HTTP endpoints in convex/http.ts MUST validate origin
+const http = httpRouter()
+
+// CORS must be restrictive
+// trustedOrigins should only include your domains
+```
+
+#### Verification Steps
+- [ ] `cors: true` in Convex `http.ts` uses proper `trustedOrigins`
+- [ ] No wildcard `*` in CORS origins
+- [ ] Webhook endpoints validate secrets (e.g., Telegram `TELEGRAM_WEBHOOK_SECRET`)
+
+### 6. Sensitive Data Exposure
+
+#### Logging
+```typescript
+// WRONG: Logging sensitive data
+console.log('User login:', { email, password })
+console.log('Token:', authToken)
+
+// CORRECT: Redact sensitive data
+console.log('User login:', { email, userId })
+```
+
+#### Convex Query Results
+```typescript
+// WRONG: Returning full user object
+export const getUser = query({
+ handler: async (ctx) => {
+ return await ctx.db.get(userId) // May include sensitive fields
+ },
+})
+
+// CORRECT: Pick only needed fields
+export const getUser = query({
+ handler: async (ctx) => {
+ const user = await ctx.db.get(userId)
+ if (!user) return null
+ return { name: user.name, email: user.email }
+ },
+})
+```
+
+#### Verification Steps
+- [ ] No passwords, tokens, or secrets in logs
+- [ ] Error messages generic for users
+- [ ] Convex queries return only necessary fields
+- [ ] No `console.log` with sensitive data in production
+
+### 7. Dependency Security
+
+```bash
+# Check for vulnerabilities
+pnpm audit
+
+# Fix automatically fixable issues
+pnpm audit --fix
+
+# Check for outdated packages
+pnpm outdated
+```
+
+#### Verification Steps
+- [ ] `pnpm audit` shows no high/critical vulnerabilities
+- [ ] Lock file (`pnpm-lock.yaml`) committed
+- [ ] Dependencies up to date
+
+### 8. Offline Queue Security
+
+The offline queue (`app/components/offline/helpers.ts`, `replay.ts`) stores pending operations in localStorage:
+
+- [ ] Offline ops don't store sensitive data beyond IDs
+- [ ] Replay validates operations before sending to Convex
+- [ ] Frontend IDs (`local_*`) are never trusted server-side
+- [ ] Convex mutations re-validate all data from offline ops
+
+## Pre-Deployment Security Checklist
+
+Before ANY production deployment:
+
+- [ ] **Secrets**: No hardcoded secrets, all in env vars / Convex env
+- [ ] **Input Validation**: All Convex args use validators, frontend uses Zod
+- [ ] **Auth**: Every Convex function checks `getAuthUserId()`
+- [ ] **Data isolation**: All queries filter by `userId`
+- [ ] **XSS**: No unsanitized `v-html`
+- [ ] **CORS**: `trustedOrigins` restrictive in `http.ts`
+- [ ] **Webhooks**: Validate secrets (Telegram, etc.)
+- [ ] **Error Handling**: No sensitive data in error messages
+- [ ] **Logging**: No sensitive data logged
+- [ ] **Dependencies**: `pnpm audit` clean
+- [ ] **Env files**: `.env.local` gitignored, `.env.example` up to date
+
+## Resources
+
+- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
+- [Convex Auth Docs](https://docs.convex.dev/auth)
+- [Better Auth Docs](https://www.better-auth.com/)
+- [Vue Security](https://vuejs.org/guide/best-practices/security)
diff --git a/.claude/skills/tdd-workflow/SKILL.md b/.claude/skills/tdd-workflow/SKILL.md
new file mode 100644
index 00000000..ecd08438
--- /dev/null
+++ b/.claude/skills/tdd-workflow/SKILL.md
@@ -0,0 +1,167 @@
+---
+name: tdd-workflow
+description: Use this skill when implementing new features or fixing bugs. Enforces test-driven development workflow with Vitest. Write tests first, then implement, then refactor.
+---
+
+# TDD Workflow Skill
+
+Test-driven development workflow for Finapp using Vitest.
+
+## When to Activate
+
+- Implementing new features (stores, composables, utils)
+- Fixing bugs (reproduce with test first)
+- Refactoring existing code (ensure tests exist before changing)
+- Adding Convex function logic that can be unit-tested
+
+## TDD Cycle
+
+### 1. RED - Write Failing Test
+
+```typescript
+// app/components/amount/__tests__/getTotal.test.ts
+import { describe, expect, it } from 'vitest'
+import { getTotal } from '../getTotal'
+
+describe('getTotal', () => {
+ it('calculates expense total from transactions', () => {
+ const trns = [
+ { amount: 100, type: 0, categoryId: 'food' },
+ { amount: 200, type: 0, categoryId: 'transport' },
+ ]
+ expect(getTotal(trns).expense).toBe(300)
+ })
+
+ it('excludes adjustment transactions from totals', () => {
+ const trns = [
+ { amount: 100, type: 0, categoryId: 'food' },
+ { amount: 500, type: 0, categoryId: 'adjustment' },
+ ]
+ expect(getTotal(trns).expense).toBe(100)
+ })
+})
+```
+
+Run: `pnpm test -- --run app/components/amount/__tests__/getTotal.test.ts`
+
+Verify test FAILS (red).
+
+### 2. GREEN - Minimal Implementation
+
+Write the minimum code to make the test pass. No optimization, no edge cases beyond what's tested.
+
+Run test again - verify it PASSES (green).
+
+### 3. REFACTOR - Improve
+
+- Remove duplication
+- Improve naming
+- Optimize if needed
+- Run tests again - verify still green
+
+## Project Test Conventions
+
+### File Location
+Tests live next to the code they test:
+```
+app/components/amount/
+ getTotal.ts
+ __tests__/
+ getTotal.test.ts
+```
+
+### Running Tests
+```bash
+pnpm test # Run all tests (watch mode)
+pnpm test -- --run # Run once, no watch
+pnpm test -- --run <path> # Run specific file
+pnpm test -- --coverage # With coverage report
+```
+
+### Test Structure
+```typescript
+import { describe, expect, it, vi, beforeEach } from 'vitest'
+
+describe('featureName', () => {
+ beforeEach(() => {
+ // Reset state between tests
+ })
+
+ describe('methodName', () => {
+ it('does X when Y', () => {
+ // Arrange
+ const input = createTestInput()
+
+ // Act
+ const result = methodName(input)
+
+ // Assert
+ expect(result).toBe(expected)
+ })
+
+ it('throws when input is invalid', () => {
+ expect(() => methodName(null)).toThrow()
+ })
+ })
+})
+```
+
+### Mocking Patterns
+
+#### Mock Convex Client
+```typescript
+import { vi } from 'vitest'
+
+const mockClient = {
+ query: vi.fn(),
+ mutation: vi.fn(),
+}
+
+vi.mock('~/composables/useConvexClient', () => ({
+ useConvexClient: () => mockClient,
+}))
+```
+
+#### Mock Pinia Store
+```typescript
+import { setActivePinia, createPinia } from 'pinia'
+
+beforeEach(() => {
+ setActivePinia(createPinia())
+})
+```
+
+#### Mock localStorage (for offline queue)
+```typescript
+const mockStorage = new Map<string, string>()
+
+vi.stubGlobal('localStorage', {
+ getItem: (key: string) => mockStorage.get(key) ?? null,
+ setItem: (key: string, val: string) => mockStorage.set(key, val),
+ removeItem: (key: string) => mockStorage.delete(key),
+ clear: () => mockStorage.clear(),
+})
+```
+
+## What to Test
+
+### Must Test
+- Pure functions (utils, calculations, formatters)
+- Store actions with business logic (save, delete, merge)
+- Offline queue operations (push, replay, merge)
+- Convex validator logic
+- Data transformations
+
+### Should Test
+- Composables with logic (not just wrapper composables)
+- Error handling paths
+- Edge cases (empty arrays, null values, `local_` IDs)
+
+### Skip
+- Simple getter composables (no logic)
+- Vue template rendering (use E2E for that)
+- Auto-generated Convex types
+
+## Coverage Target
+
+Aim for 80%+ coverage on business logic (stores, utils, offline queue). Don't chase coverage on thin wrappers or UI components.