forked from cardosofelipe/fast-next-template
docs: extract coding standards and add workflow documentation
- Create docs/development/WORKFLOW.md with branch strategy, issue management, testing requirements, and code review process - Create docs/development/CODING_STANDARDS.md with technical patterns, auth DI pattern, testing patterns, and security guidelines - Streamline CLAUDE.md to link to detailed documentation instead of embedding all content - Add branch/issue workflow rules: single branch per feature for both design and implementation phases 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
387
CLAUDE.md
387
CLAUDE.md
@@ -9,9 +9,11 @@ Claude Code context for **Syndarix** - AI-Powered Software Consulting Agency.
|
||||
## Syndarix Project Context
|
||||
|
||||
### Vision
|
||||
|
||||
Syndarix is an autonomous platform that orchestrates specialized AI agents to deliver complete software solutions with minimal human intervention. It acts as a virtual consulting agency with AI agents playing roles like Product Owner, Architect, Engineers, QA, etc.
|
||||
|
||||
### Repository
|
||||
|
||||
- **URL:** https://gitea.pragmazest.com/cardosofelipe/syndarix
|
||||
- **Issue Tracker:** Gitea Issues (primary)
|
||||
- **CI/CD:** Gitea Actions
|
||||
@@ -43,9 +45,11 @@ search_knowledge(project_id="proj-123", query="auth flow")
|
||||
create_issue(project_id="proj-123", title="Add login")
|
||||
```
|
||||
|
||||
### Syndarix-Specific Directories
|
||||
### Directory Structure
|
||||
|
||||
```
|
||||
docs/
|
||||
├── development/ # Workflow and coding standards
|
||||
├── requirements/ # Requirements documents
|
||||
├── architecture/ # Architecture documentation
|
||||
├── adrs/ # Architecture Decision Records
|
||||
@@ -53,97 +57,96 @@ docs/
|
||||
```
|
||||
|
||||
### Current Phase
|
||||
|
||||
**Backlog Population** - Creating detailed issues for Phase 0-1 implementation.
|
||||
|
||||
---
|
||||
|
||||
## Development Workflow & Standards
|
||||
## Development Standards
|
||||
|
||||
**CRITICAL: These rules are mandatory for all development work.**
|
||||
**CRITICAL: These rules are mandatory. See linked docs for full details.**
|
||||
|
||||
### 1. Issue-Driven Development
|
||||
### Quick Reference
|
||||
|
||||
**Every piece of work MUST have an issue in the Gitea tracker first.**
|
||||
| Topic | Documentation |
|
||||
|-------|---------------|
|
||||
| **Workflow & Branching** | [docs/development/WORKFLOW.md](./docs/development/WORKFLOW.md) |
|
||||
| **Coding Standards** | [docs/development/CODING_STANDARDS.md](./docs/development/CODING_STANDARDS.md) |
|
||||
| **Design System** | [frontend/docs/design-system/](./frontend/docs/design-system/) |
|
||||
| **Backend E2E Testing** | [backend/docs/E2E_TESTING.md](./backend/docs/E2E_TESTING.md) |
|
||||
| **Demo Mode** | [frontend/docs/DEMO_MODE.md](./frontend/docs/DEMO_MODE.md) |
|
||||
|
||||
- Issue tracker: https://gitea.pragmazest.com/cardosofelipe/syndarix/issues
|
||||
- Create detailed, well-scoped issues before starting work
|
||||
- Structure issues to enable parallel work by multiple agents
|
||||
- Reference issues in commits and PRs
|
||||
### Essential Rules Summary
|
||||
|
||||
### 2. Git Hygiene
|
||||
1. **Issue-Driven Development**: Every piece of work MUST have an issue first
|
||||
2. **Branch per Feature**: `feature/<issue-number>-<description>`, single branch for design+implementation
|
||||
3. **Testing Required**: All code must be tested, aim for >90% coverage
|
||||
4. **Code Review**: Must pass multi-agent review before merge
|
||||
5. **No Direct Commits**: Never commit directly to `main` or `dev`
|
||||
|
||||
**Branch naming convention:** `feature/123-description`
|
||||
### Common Commands
|
||||
|
||||
- Every issue gets its own feature branch
|
||||
- No direct commits to `main` or `dev`
|
||||
- Keep branches focused and small
|
||||
- Delete branches after merge
|
||||
```bash
|
||||
# Backend
|
||||
IS_TEST=True uv run pytest # Run tests
|
||||
uv run ruff check src/ # Lint
|
||||
uv run mypy src/ # Type check
|
||||
python migrate.py auto "message" # Database migration
|
||||
|
||||
**Workflow:**
|
||||
# Frontend
|
||||
npm test # Unit tests
|
||||
npm run lint # Lint
|
||||
npm run type-check # Type check
|
||||
npm run generate:api # Regenerate API client
|
||||
```
|
||||
main (production-ready)
|
||||
└── dev (integration branch)
|
||||
└── feature/123-description (issue branch)
|
||||
```
|
||||
|
||||
### 3. Testing Requirements
|
||||
|
||||
**All code must be tested. No exceptions.**
|
||||
|
||||
- **TDD preferred**: Write tests first when possible
|
||||
- **Test after**: If not TDD, write tests immediately after testable code
|
||||
- **Coverage types**: Unit, integration, functional, E2E as appropriate
|
||||
- **Minimum coverage**: Aim for >90% on new code
|
||||
|
||||
### 4. Code Review Process
|
||||
|
||||
**Before merging any feature branch, code must pass multi-agent review:**
|
||||
|
||||
| Check | Description |
|
||||
|-------|-------------|
|
||||
| Bug hunting | Logic errors, edge cases, race conditions |
|
||||
| Linting | `ruff check` passes with no errors |
|
||||
| Typing | `mypy` passes with no errors |
|
||||
| Formatting | Code follows style guidelines |
|
||||
| Performance | No obvious bottlenecks or N+1 queries |
|
||||
| Security | No vulnerabilities (OWASP top 10) |
|
||||
| Architecture | Follows established patterns and ADRs |
|
||||
|
||||
**Issue is NOT done until review passes with flying colors.**
|
||||
|
||||
### 5. QA Before Main
|
||||
|
||||
**Before merging `dev` into `main`:**
|
||||
|
||||
- Full test suite passes
|
||||
- Manual QA verification
|
||||
- Performance baseline check
|
||||
- Security scan
|
||||
- Code must be clean, functional, bug-free, well-architected, and secure
|
||||
|
||||
### 6. Implementation Plan Updates
|
||||
|
||||
- Keep `docs/architecture/IMPLEMENTATION_ROADMAP.md` updated
|
||||
- Mark completed items as work progresses
|
||||
- Add new items discovered during implementation
|
||||
|
||||
### 7. UI/UX Design Approval
|
||||
|
||||
**Frontend tasks involving UI/UX require design approval:**
|
||||
|
||||
1. **Design Issue**: Create issue with `design` label
|
||||
2. **Prototype**: Build interactive React prototype (navigable demo)
|
||||
3. **Review**: User inspects and provides feedback
|
||||
4. **Approval**: User approves before implementation begins
|
||||
5. **Implementation**: Follow approved design, respecting design system
|
||||
|
||||
**Design constraints:**
|
||||
- Prototypes: Best effort to match design system (not required)
|
||||
- Production code: MUST follow `frontend/docs/design-system/` strictly
|
||||
|
||||
---
|
||||
|
||||
### Key Extensions to Add (from PragmaStack base)
|
||||
## Claude Code-Specific Guidance
|
||||
|
||||
### Critical User Preferences
|
||||
|
||||
**File Operations:**
|
||||
- ALWAYS use Read/Write/Edit tools instead of `cat >> file << EOF`
|
||||
- Never use heredoc - it triggers manual approval dialogs
|
||||
|
||||
**Work Style:**
|
||||
- User prefers autonomous operation without frequent interruptions
|
||||
- Ask for batch permissions upfront for long work sessions
|
||||
- Work independently, document decisions clearly
|
||||
- Only use emojis if the user explicitly requests it
|
||||
|
||||
### Critical Pattern: Auth Store DI
|
||||
|
||||
**ALWAYS use `useAuth()` from `AuthContext`, NEVER import `useAuthStore` directly!**
|
||||
|
||||
```typescript
|
||||
// ❌ WRONG
|
||||
import { useAuthStore } from '@/lib/stores/authStore';
|
||||
|
||||
// ✅ CORRECT
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
```
|
||||
|
||||
See [CODING_STANDARDS.md](./docs/development/CODING_STANDARDS.md#auth-store-dependency-injection) for details.
|
||||
|
||||
### Tool Usage Preferences
|
||||
|
||||
**Prefer specialized tools over bash:**
|
||||
- Use Read/Write/Edit tools for file operations
|
||||
- Use Task tool with `subagent_type=Explore` for codebase exploration
|
||||
- Use Grep tool for code search, not bash `grep`
|
||||
|
||||
**Parallel tool calls for:**
|
||||
- Independent git commands
|
||||
- Reading multiple unrelated files
|
||||
- Running multiple test suites
|
||||
- Independent validation steps
|
||||
|
||||
---
|
||||
|
||||
## Key Extensions (from PragmaStack base)
|
||||
|
||||
- Celery + Redis for agent job queue
|
||||
- WebSocket/SSE for real-time updates
|
||||
- pgvector for RAG knowledge base
|
||||
@@ -151,244 +154,20 @@ main (production-ready)
|
||||
|
||||
---
|
||||
|
||||
## PragmaStack Development Guidelines
|
||||
|
||||
*The following guidelines are inherited from PragmaStack and remain applicable.*
|
||||
|
||||
## Claude Code-Specific Guidance
|
||||
|
||||
### Critical User Preferences
|
||||
|
||||
#### File Operations - NEVER Use Heredoc/Cat Append
|
||||
**ALWAYS use Read/Write/Edit tools instead of `cat >> file << EOF` commands.**
|
||||
|
||||
This triggers manual approval dialogs and disrupts workflow.
|
||||
|
||||
```bash
|
||||
# WRONG ❌
|
||||
cat >> file.txt << EOF
|
||||
content
|
||||
EOF
|
||||
|
||||
# CORRECT ✅ - Use Read, then Write tools
|
||||
```
|
||||
|
||||
#### Work Style
|
||||
- User prefers autonomous operation without frequent interruptions
|
||||
- Ask for batch permissions upfront for long work sessions
|
||||
- Work independently, document decisions clearly
|
||||
- Only use emojis if the user explicitly requests it
|
||||
|
||||
### When Working with This Stack
|
||||
|
||||
**Dependency Management:**
|
||||
- Backend uses **uv** (modern Python package manager), not pip
|
||||
- Always use `uv run` prefix: `IS_TEST=True uv run pytest`
|
||||
- Or use Makefile commands: `make test`, `make install-dev`
|
||||
- Add dependencies: `uv add <package>` or `uv add --dev <package>`
|
||||
|
||||
**Database Migrations:**
|
||||
- Use the `migrate.py` helper script, not Alembic directly
|
||||
- Generate + apply: `python migrate.py auto "message"`
|
||||
- Never commit migrations without testing them first
|
||||
- Check current state: `python migrate.py current`
|
||||
|
||||
**Frontend API Client Generation:**
|
||||
- Run `npm run generate:api` after backend schema changes
|
||||
- Client is auto-generated from OpenAPI spec
|
||||
- Located in `frontend/src/lib/api/generated/`
|
||||
- NEVER manually edit generated files
|
||||
|
||||
**Testing Commands:**
|
||||
- Backend unit/integration: `IS_TEST=True uv run pytest` (always prefix with `IS_TEST=True`)
|
||||
- Backend E2E (requires Docker): `make test-e2e`
|
||||
- Frontend unit: `npm test`
|
||||
- Frontend E2E: `npm run test:e2e`
|
||||
- Use `make test` or `make test-cov` in backend for convenience
|
||||
|
||||
**Backend E2E Testing (requires Docker):**
|
||||
- Install deps: `make install-e2e`
|
||||
- Run all E2E tests: `make test-e2e`
|
||||
- Run schema tests only: `make test-e2e-schema`
|
||||
- Run all tests: `make test-all` (unit + E2E)
|
||||
- Uses Testcontainers (real PostgreSQL) + Schemathesis (OpenAPI contract testing)
|
||||
- Markers: `@pytest.mark.e2e`, `@pytest.mark.postgres`, `@pytest.mark.schemathesis`
|
||||
- See: `backend/docs/E2E_TESTING.md` for complete guide
|
||||
|
||||
### 🔴 CRITICAL: Auth Store Dependency Injection Pattern
|
||||
|
||||
**ALWAYS use `useAuth()` from `AuthContext`, NEVER import `useAuthStore` directly!**
|
||||
|
||||
```typescript
|
||||
// ❌ WRONG - Bypasses dependency injection
|
||||
import { useAuthStore } from '@/lib/stores/authStore';
|
||||
const { user, isAuthenticated } = useAuthStore();
|
||||
|
||||
// ✅ CORRECT - Uses dependency injection
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
const { user, isAuthenticated } = useAuth();
|
||||
```
|
||||
|
||||
**Why This Matters:**
|
||||
- E2E tests inject mock stores via `window.__TEST_AUTH_STORE__`
|
||||
- Unit tests inject via `<AuthProvider store={mockStore}>`
|
||||
- Direct `useAuthStore` imports bypass this injection → **tests fail**
|
||||
- ESLint will catch violations (added Nov 2025)
|
||||
|
||||
**Exceptions:**
|
||||
1. `AuthContext.tsx` - DI boundary, legitimately needs real store
|
||||
2. `client.ts` - Non-React context, uses dynamic import + `__TEST_AUTH_STORE__` check
|
||||
|
||||
### E2E Test Best Practices
|
||||
|
||||
When writing or fixing Playwright tests:
|
||||
|
||||
**Navigation Pattern:**
|
||||
```typescript
|
||||
// ✅ CORRECT - Use Promise.all for Next.js Link clicks
|
||||
await Promise.all([
|
||||
page.waitForURL('/target', { timeout: 10000 }),
|
||||
link.click()
|
||||
]);
|
||||
```
|
||||
|
||||
**Selectors:**
|
||||
- Use ID-based selectors for validation errors: `#email-error`
|
||||
- Error IDs use dashes not underscores: `#new-password-error`
|
||||
- Target `.border-destructive[role="alert"]` to avoid Next.js route announcer conflicts
|
||||
- Avoid generic `[role="alert"]` which matches multiple elements
|
||||
|
||||
**URL Assertions:**
|
||||
```typescript
|
||||
// ✅ Use regex to handle query params
|
||||
await expect(page).toHaveURL(/\/auth\/login/);
|
||||
|
||||
// ❌ Don't use exact strings (fails with query params)
|
||||
await expect(page).toHaveURL('/auth/login');
|
||||
```
|
||||
|
||||
**Configuration:**
|
||||
- Uses 12 workers in non-CI mode (`playwright.config.ts`)
|
||||
- Reduces to 2 workers in CI for stability
|
||||
- Tests are designed to be non-flaky with proper waits
|
||||
|
||||
### Important Implementation Details
|
||||
|
||||
**Authentication Testing:**
|
||||
- Backend fixtures in `tests/conftest.py`:
|
||||
- `async_test_db`: Fresh SQLite per test
|
||||
- `async_test_user` / `async_test_superuser`: Pre-created users
|
||||
- `user_token` / `superuser_token`: Access tokens for API calls
|
||||
- Always use `@pytest.mark.asyncio` for async tests
|
||||
- Use `@pytest_asyncio.fixture` for async fixtures
|
||||
|
||||
**Database Testing:**
|
||||
```python
|
||||
# Mock database exceptions correctly
|
||||
from unittest.mock import patch, AsyncMock
|
||||
|
||||
async def mock_commit():
|
||||
raise OperationalError("Connection lost", {}, Exception())
|
||||
|
||||
with patch.object(session, 'commit', side_effect=mock_commit):
|
||||
with patch.object(session, 'rollback', new_callable=AsyncMock) as mock_rollback:
|
||||
with pytest.raises(OperationalError):
|
||||
await crud_method(session, obj_in=data)
|
||||
mock_rollback.assert_called_once()
|
||||
```
|
||||
|
||||
**Frontend Component Development:**
|
||||
- Follow design system docs in `frontend/docs/design-system/`
|
||||
- Read `08-ai-guidelines.md` for AI code generation rules
|
||||
- Use parent-controlled spacing (see `04-spacing-philosophy.md`)
|
||||
- WCAG AA compliance required (see `07-accessibility.md`)
|
||||
|
||||
**Security Considerations:**
|
||||
- Backend has comprehensive security tests (JWT attacks, session hijacking)
|
||||
- Never skip security headers in production
|
||||
- Rate limiting is configured in route decorators: `@limiter.limit("10/minute")`
|
||||
- Session revocation is database-backed, not just JWT expiry
|
||||
|
||||
### Common Workflows Guidance
|
||||
|
||||
**When Adding a New Feature:**
|
||||
1. Start with backend schema and CRUD
|
||||
2. Implement API route with proper authorization
|
||||
3. Write backend tests (aim for >90% coverage)
|
||||
4. Generate frontend API client: `npm run generate:api`
|
||||
5. Implement frontend components
|
||||
6. Write frontend unit tests
|
||||
7. Add E2E tests for critical flows
|
||||
8. Update relevant documentation
|
||||
|
||||
**When Fixing Tests:**
|
||||
- Backend: Check test database isolation and async fixture usage
|
||||
- Frontend unit: Verify mocking of `useAuth()` not `useAuthStore`
|
||||
- E2E: Use `Promise.all()` pattern and regex URL assertions
|
||||
|
||||
**When Debugging:**
|
||||
- Backend: Check `IS_TEST=True` environment variable is set
|
||||
- Frontend: Run `npm run type-check` first
|
||||
- E2E: Use `npm run test:e2e:debug` for step-by-step debugging
|
||||
- Check logs: Backend has detailed error logging
|
||||
|
||||
**Demo Mode (Frontend-Only Showcase):**
|
||||
- Enable: `echo "NEXT_PUBLIC_DEMO_MODE=true" > frontend/.env.local`
|
||||
- Uses MSW (Mock Service Worker) to intercept API calls in browser
|
||||
- Zero backend required - perfect for Vercel deployments
|
||||
- **Fully Automated**: MSW handlers auto-generated from OpenAPI spec
|
||||
- Run `npm run generate:api` → updates both API client AND MSW handlers
|
||||
- No manual synchronization needed!
|
||||
- Demo credentials (any password ≥8 chars works):
|
||||
- User: `demo@example.com` / `DemoPass123`
|
||||
- Admin: `admin@example.com` / `AdminPass123`
|
||||
- **Safe**: MSW never runs during tests (Jest or Playwright)
|
||||
- **Coverage**: Mock files excluded from linting and coverage
|
||||
- **Documentation**: `frontend/docs/DEMO_MODE.md` for complete guide
|
||||
|
||||
### Tool Usage Preferences
|
||||
|
||||
**Prefer specialized tools over bash:**
|
||||
- Use Read/Write/Edit tools for file operations
|
||||
- Never use `cat`, `echo >`, or heredoc for file manipulation
|
||||
- Use Task tool with `subagent_type=Explore` for codebase exploration
|
||||
- Use Grep tool for code search, not bash `grep`
|
||||
|
||||
**When to use parallel tool calls:**
|
||||
- Independent git commands: `git status`, `git diff`, `git log`
|
||||
- Reading multiple unrelated files
|
||||
- Running multiple test suites simultaneously
|
||||
- Independent validation steps
|
||||
|
||||
## Custom Skills
|
||||
|
||||
No Claude Code Skills installed yet. To create one, invoke the built-in "skill-creator" skill.
|
||||
|
||||
**Potential skill ideas for this project:**
|
||||
- API endpoint generator workflow (schema → CRUD → route → tests → frontend client)
|
||||
- Component generator with design system compliance
|
||||
- Database migration troubleshooting helper
|
||||
- Test coverage analyzer and improvement suggester
|
||||
- E2E test generator for new features
|
||||
|
||||
## Additional Resources
|
||||
|
||||
**Comprehensive Documentation:**
|
||||
**Documentation:**
|
||||
- [AGENTS.md](./AGENTS.md) - Framework-agnostic AI assistant context
|
||||
- [README.md](./README.md) - User-facing project overview
|
||||
- `backend/docs/` - Backend architecture, coding standards, common pitfalls
|
||||
- `frontend/docs/design-system/` - Complete design system guide
|
||||
- [docs/development/](./docs/development/) - Development workflow and standards
|
||||
- [backend/docs/](./backend/docs/) - Backend architecture and guides
|
||||
- [frontend/docs/design-system/](./frontend/docs/design-system/) - Complete design system
|
||||
|
||||
**API Documentation (when running):**
|
||||
- Swagger UI: http://localhost:8000/docs
|
||||
- ReDoc: http://localhost:8000/redoc
|
||||
- OpenAPI JSON: http://localhost:8000/api/v1/openapi.json
|
||||
|
||||
**Testing Documentation:**
|
||||
- Backend tests: `backend/tests/` (97% coverage)
|
||||
- Frontend E2E: `frontend/e2e/README.md`
|
||||
- Design system: `frontend/docs/design-system/08-ai-guidelines.md`
|
||||
|
||||
---
|
||||
|
||||
**For project architecture, development commands, and general context, see [AGENTS.md](./AGENTS.md).**
|
||||
|
||||
312
docs/development/CODING_STANDARDS.md
Normal file
312
docs/development/CODING_STANDARDS.md
Normal file
@@ -0,0 +1,312 @@
|
||||
# Coding Standards
|
||||
|
||||
Technical coding standards and patterns for Syndarix development.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Backend Standards](#backend-standards)
|
||||
- [Frontend Standards](#frontend-standards)
|
||||
- [Testing Patterns](#testing-patterns)
|
||||
- [Security Guidelines](#security-guidelines)
|
||||
|
||||
---
|
||||
|
||||
## Backend Standards
|
||||
|
||||
### Dependency Management
|
||||
|
||||
- Use **uv** (modern Python package manager), not pip
|
||||
- Always use `uv run` prefix for commands
|
||||
- Add dependencies: `uv add <package>` or `uv add --dev <package>`
|
||||
|
||||
```bash
|
||||
# Running tests
|
||||
IS_TEST=True uv run pytest
|
||||
|
||||
# Or use Makefile
|
||||
make test
|
||||
make install-dev
|
||||
```
|
||||
|
||||
### Database Migrations
|
||||
|
||||
- Use the `migrate.py` helper script, not Alembic directly
|
||||
- Never commit migrations without testing them first
|
||||
|
||||
```bash
|
||||
# Generate and apply migration
|
||||
python migrate.py auto "message"
|
||||
|
||||
# Check current state
|
||||
python migrate.py current
|
||||
```
|
||||
|
||||
### Authentication Testing Fixtures
|
||||
|
||||
Backend fixtures in `tests/conftest.py`:
|
||||
|
||||
| Fixture | Purpose |
|
||||
|---------|---------|
|
||||
| `async_test_db` | Fresh SQLite per test |
|
||||
| `async_test_user` | Pre-created regular user |
|
||||
| `async_test_superuser` | Pre-created admin user |
|
||||
| `user_token` | Access token for regular user |
|
||||
| `superuser_token` | Access token for admin |
|
||||
|
||||
```python
|
||||
# Always use these decorators for async tests
|
||||
@pytest.mark.asyncio
|
||||
async def test_something():
|
||||
pass
|
||||
|
||||
# Use for async fixtures
|
||||
@pytest_asyncio.fixture
|
||||
async def my_fixture():
|
||||
pass
|
||||
```
|
||||
|
||||
### Database Exception Mocking
|
||||
|
||||
```python
|
||||
from unittest.mock import patch, AsyncMock
|
||||
|
||||
async def mock_commit():
|
||||
raise OperationalError("Connection lost", {}, Exception())
|
||||
|
||||
with patch.object(session, 'commit', side_effect=mock_commit):
|
||||
with patch.object(session, 'rollback', new_callable=AsyncMock) as mock_rollback:
|
||||
with pytest.raises(OperationalError):
|
||||
await crud_method(session, obj_in=data)
|
||||
mock_rollback.assert_called_once()
|
||||
```
|
||||
|
||||
### Security Considerations
|
||||
|
||||
- Backend has comprehensive security tests (JWT attacks, session hijacking)
|
||||
- Never skip security headers in production
|
||||
- Rate limiting: `@limiter.limit("10/minute")`
|
||||
- Session revocation is database-backed, not just JWT expiry
|
||||
|
||||
---
|
||||
|
||||
## Frontend Standards
|
||||
|
||||
### Auth Store Dependency Injection
|
||||
|
||||
**CRITICAL: ALWAYS use `useAuth()` from `AuthContext`, NEVER import `useAuthStore` directly!**
|
||||
|
||||
```typescript
|
||||
// ❌ WRONG - Bypasses dependency injection
|
||||
import { useAuthStore } from '@/lib/stores/authStore';
|
||||
const { user, isAuthenticated } = useAuthStore();
|
||||
|
||||
// ✅ CORRECT - Uses dependency injection
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
const { user, isAuthenticated } = useAuth();
|
||||
```
|
||||
|
||||
**Why This Matters:**
|
||||
- E2E tests inject mock stores via `window.__TEST_AUTH_STORE__`
|
||||
- Unit tests inject via `<AuthProvider store={mockStore}>`
|
||||
- Direct `useAuthStore` imports bypass this injection → **tests fail**
|
||||
- ESLint will catch violations
|
||||
|
||||
**Exceptions:**
|
||||
1. `AuthContext.tsx` - DI boundary, legitimately needs real store
|
||||
2. `client.ts` - Non-React context, uses dynamic import + `__TEST_AUTH_STORE__` check
|
||||
|
||||
### API Client Generation
|
||||
|
||||
```bash
|
||||
# After backend schema changes
|
||||
npm run generate:api
|
||||
```
|
||||
|
||||
- Client is auto-generated from OpenAPI spec
|
||||
- Located in `frontend/src/lib/api/generated/`
|
||||
- **NEVER manually edit generated files**
|
||||
|
||||
### Component Development
|
||||
|
||||
- Follow design system docs in `frontend/docs/design-system/`
|
||||
- Read `08-ai-guidelines.md` for AI code generation rules
|
||||
- Use parent-controlled spacing (see `04-spacing-philosophy.md`)
|
||||
- WCAG AA compliance required (see `07-accessibility.md`)
|
||||
|
||||
### Route Groups Structure
|
||||
|
||||
```
|
||||
src/app/[locale]/
|
||||
├── (auth)/ # Public auth pages (login, register, password reset)
|
||||
│ # Uses AuthLayoutClient - redirects authenticated users
|
||||
├── (authenticated)/ # Protected app pages
|
||||
│ # Uses AuthGuard + Header/Footer
|
||||
├── admin/ # Admin pages with sidebar
|
||||
│ # Uses AuthGuard requireAdmin
|
||||
├── dev/ # Design system documentation
|
||||
└── prototypes/ # UI prototypes for approval
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Testing Patterns
|
||||
|
||||
### Frontend Unit Tests
|
||||
|
||||
```typescript
|
||||
// Mock useAuth correctly
|
||||
jest.mock('@/lib/auth/AuthContext', () => ({
|
||||
useAuth: () => ({
|
||||
user: { id: '1', email: 'test@example.com' },
|
||||
isAuthenticated: true,
|
||||
}),
|
||||
}));
|
||||
```
|
||||
|
||||
### E2E Test Best Practices (Playwright)
|
||||
|
||||
**Navigation Pattern:**
|
||||
```typescript
|
||||
// ✅ CORRECT - Use Promise.all for Next.js Link clicks
|
||||
await Promise.all([
|
||||
page.waitForURL('/target', { timeout: 10000 }),
|
||||
link.click()
|
||||
]);
|
||||
```
|
||||
|
||||
**Selectors:**
|
||||
- Use ID-based selectors for validation errors: `#email-error`
|
||||
- Error IDs use dashes not underscores: `#new-password-error`
|
||||
- Target `.border-destructive[role="alert"]` to avoid Next.js route announcer conflicts
|
||||
- Avoid generic `[role="alert"]` which matches multiple elements
|
||||
|
||||
**URL Assertions:**
|
||||
```typescript
|
||||
// ✅ Use regex to handle query params
|
||||
await expect(page).toHaveURL(/\/auth\/login/);
|
||||
|
||||
// ❌ Don't use exact strings (fails with query params)
|
||||
await expect(page).toHaveURL('/auth/login');
|
||||
```
|
||||
|
||||
**Configuration:**
|
||||
- Uses 12 workers in non-CI mode
|
||||
- Reduces to 2 workers in CI for stability
|
||||
|
||||
### Backend E2E Testing
|
||||
|
||||
Requires Docker for Testcontainers.
|
||||
|
||||
```bash
|
||||
# Install deps
|
||||
make install-e2e
|
||||
|
||||
# Run all E2E tests
|
||||
make test-e2e
|
||||
|
||||
# Run schema tests only
|
||||
make test-e2e-schema
|
||||
|
||||
# Run all tests (unit + E2E)
|
||||
make test-all
|
||||
```
|
||||
|
||||
Uses:
|
||||
- Testcontainers (real PostgreSQL)
|
||||
- Schemathesis (OpenAPI contract testing)
|
||||
|
||||
Markers:
|
||||
- `@pytest.mark.e2e`
|
||||
- `@pytest.mark.postgres`
|
||||
- `@pytest.mark.schemathesis`
|
||||
|
||||
See: `backend/docs/E2E_TESTING.md` for complete guide.
|
||||
|
||||
---
|
||||
|
||||
## Security Guidelines
|
||||
|
||||
### OWASP Top 10 Compliance
|
||||
|
||||
All code must be reviewed for:
|
||||
- Injection vulnerabilities (SQL, command, XSS)
|
||||
- Broken authentication
|
||||
- Sensitive data exposure
|
||||
- Security misconfiguration
|
||||
- Insecure deserialization
|
||||
|
||||
### Rate Limiting
|
||||
|
||||
```python
|
||||
from app.core.limiter import limiter
|
||||
|
||||
@router.post("/endpoint")
|
||||
@limiter.limit("10/minute")
|
||||
async def endpoint():
|
||||
pass
|
||||
```
|
||||
|
||||
### JWT Security
|
||||
|
||||
- Tokens stored securely (httpOnly cookies preferred)
|
||||
- Short expiration times
|
||||
- Refresh token rotation
|
||||
- Database-backed session revocation
|
||||
|
||||
---
|
||||
|
||||
## Common Workflows
|
||||
|
||||
### Adding a New Feature
|
||||
|
||||
1. Start with backend schema and CRUD
|
||||
2. Implement API route with proper authorization
|
||||
3. Write backend tests (aim for >90% coverage)
|
||||
4. Generate frontend API client: `npm run generate:api`
|
||||
5. Implement frontend components
|
||||
6. Write frontend unit tests
|
||||
7. Add E2E tests for critical flows
|
||||
8. Update relevant documentation
|
||||
|
||||
### Fixing Tests
|
||||
|
||||
| Layer | Check |
|
||||
|-------|-------|
|
||||
| Backend | Test database isolation, async fixture usage |
|
||||
| Frontend unit | Mock `useAuth()` not `useAuthStore` |
|
||||
| E2E | Use `Promise.all()` pattern, regex URL assertions |
|
||||
|
||||
### Debugging
|
||||
|
||||
| Layer | Action |
|
||||
|-------|--------|
|
||||
| Backend | Check `IS_TEST=True` environment variable |
|
||||
| Frontend | Run `npm run type-check` first |
|
||||
| E2E | Use `npm run test:e2e:debug` for step-by-step |
|
||||
| All | Check logs - backend has detailed error logging |
|
||||
|
||||
---
|
||||
|
||||
## Demo Mode
|
||||
|
||||
Frontend-only showcase mode for demos without backend.
|
||||
|
||||
```bash
|
||||
# Enable
|
||||
echo "NEXT_PUBLIC_DEMO_MODE=true" > frontend/.env.local
|
||||
```
|
||||
|
||||
- Uses MSW (Mock Service Worker) to intercept API calls
|
||||
- Zero backend required - perfect for Vercel deployments
|
||||
- MSW handlers auto-generated from OpenAPI spec
|
||||
- Run `npm run generate:api` → updates both API client AND MSW handlers
|
||||
|
||||
**Demo Credentials:**
|
||||
- User: `demo@example.com` / `DemoPass123`
|
||||
- Admin: `admin@example.com` / `AdminPass123`
|
||||
|
||||
**Safety:**
|
||||
- MSW never runs during tests (Jest or Playwright)
|
||||
- Mock files excluded from linting and coverage
|
||||
|
||||
See: `frontend/docs/DEMO_MODE.md` for complete guide.
|
||||
228
docs/development/WORKFLOW.md
Normal file
228
docs/development/WORKFLOW.md
Normal file
@@ -0,0 +1,228 @@
|
||||
# Development Workflow
|
||||
|
||||
This document defines the development workflow, branching strategy, and issue management rules for Syndarix.
|
||||
|
||||
## Issue-Driven Development
|
||||
|
||||
**Every piece of work MUST have an issue in the Gitea tracker first.**
|
||||
|
||||
- Issue tracker: https://gitea.pragmazest.com/cardosofelipe/syndarix/issues
|
||||
- Create detailed, well-scoped issues before starting work
|
||||
- Structure issues to enable parallel work by multiple agents
|
||||
- Reference issues in commits and PRs
|
||||
|
||||
---
|
||||
|
||||
## Git Branching Strategy
|
||||
|
||||
### Branch Naming Convention
|
||||
|
||||
```
|
||||
feature/<issue-number>-<short-description>
|
||||
```
|
||||
|
||||
Examples:
|
||||
- `feature/123-user-authentication`
|
||||
- `feature/456-project-dashboard`
|
||||
|
||||
### Branch Workflow
|
||||
|
||||
```
|
||||
main (production-ready)
|
||||
└── dev (integration branch)
|
||||
└── feature/123-description (issue branch)
|
||||
```
|
||||
|
||||
### Rules
|
||||
|
||||
1. **Every issue gets its own feature branch**
|
||||
2. **No direct commits to `main` or `dev`**
|
||||
3. **Keep branches focused and small**
|
||||
4. **Delete branches after merge**
|
||||
5. **All branches must be mergeable to dev** - if work isn't ready to merge, keep it in a separate branch
|
||||
|
||||
---
|
||||
|
||||
## Issue and Branch Structure for Features
|
||||
|
||||
### Single Branch per Feature
|
||||
|
||||
For UI/UX features that require both design and implementation:
|
||||
|
||||
1. **Create a single feature branch** for both design prototype and implementation
|
||||
2. **Do NOT create separate branches** for design vs implementation
|
||||
|
||||
### Issue Structure Options
|
||||
|
||||
Choose one of these approaches based on complexity:
|
||||
|
||||
#### Option A: Single Issue with Tasks (Recommended for most features)
|
||||
|
||||
```markdown
|
||||
## Issue: Add User Profile Page (#123)
|
||||
|
||||
### Tasks
|
||||
- [ ] Design: Create interactive prototype in /prototypes
|
||||
- [ ] Design: Get user approval on the design
|
||||
- [ ] Implementation: Build page following design system
|
||||
- [ ] Implementation: Write tests
|
||||
- [ ] Cleanup: Remove prototype after implementation
|
||||
```
|
||||
|
||||
Branch: `feature/123-user-profile-page`
|
||||
|
||||
#### Option B: User Story with Sub-Issues (For complex features)
|
||||
|
||||
```markdown
|
||||
## User Story: Project Management (#100)
|
||||
├── Sub-issue: Design project dashboard (#101)
|
||||
├── Sub-issue: Implement project dashboard (#102)
|
||||
├── Sub-issue: Design project settings (#103)
|
||||
└── Sub-issue: Implement project settings (#104)
|
||||
```
|
||||
|
||||
Branch: `feature/100-project-management` (single branch for the entire user story)
|
||||
|
||||
**Important:** Even with multiple sub-issues, use a **single branch** for the user story.
|
||||
|
||||
---
|
||||
|
||||
## UI/UX Design Workflow
|
||||
|
||||
### For New UI Features
|
||||
|
||||
1. **Create Issue**: Use `design` label
|
||||
2. **Build Prototype**: Create in `/frontend/src/app/[locale]/prototypes/<feature>/`
|
||||
3. **User Review**: Get feedback on the prototype
|
||||
4. **Approval**: User approves design before implementation
|
||||
5. **Implementation**: Build in production location following design system
|
||||
6. **Cleanup**: Remove prototype after implementation
|
||||
|
||||
### Design Guidelines
|
||||
|
||||
| Phase | Requirements |
|
||||
|-------|-------------|
|
||||
| **Prototype** | Best effort to match design system (not required) |
|
||||
| **Production** | MUST follow `frontend/docs/design-system/` strictly |
|
||||
|
||||
---
|
||||
|
||||
## Testing Requirements
|
||||
|
||||
**All code must be tested. No exceptions.**
|
||||
|
||||
### Testing Approach
|
||||
|
||||
- **TDD preferred**: Write tests first when possible
|
||||
- **Test after**: If not TDD, write tests immediately after testable code
|
||||
- **Coverage types**: Unit, integration, functional, E2E as appropriate
|
||||
- **Minimum coverage**: Aim for >90% on new code
|
||||
|
||||
### Testing Commands
|
||||
|
||||
```bash
|
||||
# Backend
|
||||
IS_TEST=True uv run pytest # Unit/integration tests
|
||||
make test-e2e # E2E tests (requires Docker)
|
||||
|
||||
# Frontend
|
||||
npm test # Unit tests
|
||||
npm run test:e2e # E2E tests
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Code Review Process
|
||||
|
||||
**Before merging any feature branch, code must pass multi-agent review:**
|
||||
|
||||
| Check | Description |
|
||||
|-------|-------------|
|
||||
| Bug hunting | Logic errors, edge cases, race conditions |
|
||||
| Linting | `ruff check` / `eslint` passes with no errors |
|
||||
| Typing | `mypy` / `tsc --noEmit` passes with no errors |
|
||||
| Formatting | Code follows style guidelines |
|
||||
| Performance | No obvious bottlenecks or N+1 queries |
|
||||
| Security | No vulnerabilities (OWASP top 10) |
|
||||
| Architecture | Follows established patterns and ADRs |
|
||||
|
||||
**Issue is NOT done until review passes with flying colors.**
|
||||
|
||||
---
|
||||
|
||||
## QA Before Main
|
||||
|
||||
**Before merging `dev` into `main`:**
|
||||
|
||||
- [ ] Full test suite passes
|
||||
- [ ] Manual QA verification
|
||||
- [ ] Performance baseline check
|
||||
- [ ] Security scan
|
||||
- [ ] Code must be clean, functional, bug-free, well-architected, and secure
|
||||
|
||||
---
|
||||
|
||||
## Commit Message Format
|
||||
|
||||
```
|
||||
<type>(<scope>): <description>
|
||||
|
||||
[optional body]
|
||||
|
||||
[optional footer]
|
||||
```
|
||||
|
||||
### Types
|
||||
|
||||
- `feat`: New feature
|
||||
- `fix`: Bug fix
|
||||
- `docs`: Documentation only
|
||||
- `style`: Formatting, missing semicolons, etc.
|
||||
- `refactor`: Code change that neither fixes a bug nor adds a feature
|
||||
- `test`: Adding missing tests
|
||||
- `chore`: Maintenance tasks
|
||||
|
||||
### Examples
|
||||
|
||||
```
|
||||
feat(auth): add password reset functionality
|
||||
fix(api): handle null response in user endpoint
|
||||
docs(readme): update installation instructions
|
||||
test(frontend): add unit tests for ProjectDashboard
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pull Request Process
|
||||
|
||||
1. **Create PR from feature branch to dev**
|
||||
2. **PR title**: Same format as commit messages
|
||||
3. **PR body**: Include summary, test plan, and issue reference
|
||||
4. **Wait for CI**: All checks must pass
|
||||
5. **Code review**: Address all feedback
|
||||
6. **Merge**: Squash and merge when approved
|
||||
7. **Cleanup**: Delete feature branch after merge
|
||||
|
||||
---
|
||||
|
||||
## Documentation Updates
|
||||
|
||||
- Keep `docs/architecture/IMPLEMENTATION_ROADMAP.md` updated
|
||||
- Mark completed items as work progresses
|
||||
- Add new items discovered during implementation
|
||||
- Update ADRs when architectural decisions change
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Action | Command/Location |
|
||||
|--------|-----------------|
|
||||
| Create branch | `git checkout -b feature/<issue>-<desc>` |
|
||||
| Run backend tests | `IS_TEST=True uv run pytest` |
|
||||
| Run frontend tests | `npm test` |
|
||||
| Check types (backend) | `uv run mypy src/` |
|
||||
| Check types (frontend) | `npm run type-check` |
|
||||
| Lint (backend) | `uv run ruff check src/` |
|
||||
| Lint (frontend) | `npm run lint` |
|
||||
| Generate API client | `npm run generate:api` |
|
||||
Reference in New Issue
Block a user