Il Contesto e Tutto
La qualità delle risposte di Claude dipende direttamente dalla qualità del contesto che fornisci. Un prompt perfetto senza contesto produce risultati generici; un prompt semplice con contesto ricco produce codice specifico e coerente con il tuo progetto.
In questo articolo esploreremo come strutturare il repository, creare file di istruzioni, e configurare system prompt che permettano a Claude di capire profondamente il tuo progetto.
Cosa Imparerai
- Strutturare il repository per massimizzare la comprensione
- Creare CLAUDE.md e altri file di contesto
- Configurare system prompt efficaci
- Gestire progetti mono-repo e multi-repo
- Strategie per mantenere il contesto nelle sessioni lunghe
Panoramica della Serie
Questo è il secondo articolo della serie "Claude: AI-Driven Personal Project".
| # | Modulo | Stato |
|---|---|---|
| 1 | Foundation: Claude come Partner Tecnico | Completato |
| 2 | Contesto e Setup del Progetto | Sei qui |
| 3 | Ideazione e Requisiti | Prossimo |
| 4 | Architettura Backend e Frontend | |
| 5 | Struttura del Codice | |
| 6 | Prompt Engineering Avanzato | |
| 7 | Testing e qualità | |
| 8 | Documentazione | |
| 9 | Deploy e Manutenzione |
Come Claude Elabora il Contesto
Claude ha una finestra di contesto di 200.000 token (circa 150.000 parole). Questo è enorme rispetto ad altri LLM, ma va gestito strategicamente.
Contesto Window: Come Funziona
| Elemento | Token Approssimati | Note |
|---|---|---|
| System Prompt | 500 - 2.000 | Sempre presente in ogni richiesta |
| CLAUDE.md | 1.000 - 5.000 | Istruzioni progetto |
| File Codice (medio) | 500 - 2.000 | Per file incluso |
| Conversazione | Variabile | Cresce nel tempo |
| Risposta | Max 4.096 | Limite output di default |
Priorità del Contesto
Claude assegna peso diverso alle informazioni in base a dove si trovano:
1. SYSTEM PROMPT (massima priorità)
- Istruzioni su comportamento e stile
- Regole non negoziabili
- Sempre rispettate (se ben formulate)
2. CONTESTO RECENTE (alta priorità)
- Ultimi messaggi della conversazione
- File appena incollati
- Codice appena discusso
3. CONTESTO MEDIO (media priorità)
- Messaggi precedenti nella sessione
- File di documentazione inclusi
- Esempi forniti
4. CONTESTO LONTANO (bassa priorità)
- Inizio della conversazione
- Dettagli menzionati una volta
- Informazioni implicite
STRATEGIA: Ripeti le informazioni importanti
nei prompt successivi se la conversazione e lunga.
Struttura del Repository
Un repository ben organizzato aiuta Claude a navigare e comprendere il progetto anche senza leggere ogni file.
Struttura Consigliata
project-root/
├── CLAUDE.md # Istruzioni per Claude
├── README.md # Documentazione progetto
├── .cursorrules # (opzionale) Per Cursor IDE
├── docs/
│ ├── architecture.md # Decisioni architetturali
│ ├── api-spec.md # Specifiche API
│ └── adr/ # Architecture Decision Records
│ ├── 001-database-choice.md
│ └── 002-auth-strategy.md
│
├── apps/ # Mono-repo structure
│ ├── frontend/
│ │ ├── src/
│ │ ├── package.json
│ │ └── tsconfig.json
│ └── backend/
│ ├── src/
│ ├── package.json
│ └── tsconfig.json
│
├── packages/ # Shared code
│ └── shared-types/
│ └── src/
│
├── tools/
│ └── scripts/
│
├── .env.example # Variabili ambiente template
├── docker-compose.yml # Setup sviluppo locale
├── package.json # Root workspace
└── turbo.json # (se usi Turborepo)
Mono-repo vs Multi-repo
Mono-repo
- Pro: Tutto in un posto
- Pro: Refactoring atomici
- Pro: Un solo CLAUDE.md
- Contro: Può crescere molto
- Tooling: Turborepo, Nx, Lerna
Consigliato per progetti personali
Multi-repo
- Pro: Separazione chiara
- Pro: Deploy indipendenti
- Contro: Più overhead
- Contro: CLAUDE.md multipli
- Sync: Git submodules o manuale
Meglio per team o microservices
Consiglio per Progetti Personali
Per un progetto personale, usa un mono-repo. Avere tutto in un posto rende più facile dare contesto a Claude, fare refactoring, e mantenere coerenza. La complessità dei multi-repo non giustifica i benefici per un solo sviluppatore.
File CLAUDE.md: La Tua Bibbia
Il file CLAUDE.md è il documento più importante per lavorare con Claude.
Contiene tutto ciò che Claude deve sapere per aiutarti efficacemente.
Template Completo CLAUDE.md
# CLAUDE.md - Project Instructions
## Quick Reference
- **Project:** TaskFlow - Time tracking and task management
- **Stack:** Angular 21 + Node.js 22 + PostgreSQL 16
- **Author:** Solo developer
- **Status:** MVP Development (Phase 1)
---
## Project Overview
### What It Does
TaskFlow helps freelancers track time spent on tasks and generate
client invoices. Core features include task CRUD, time tracking
with start/stop timers, and weekly reports.
### Target Users
Solo freelancers and small teams (1-5 people) who need simple
time tracking without enterprise complexity.
### Success Metrics
- User can create and track a task in under 30 seconds
- Weekly report generation in one click
- Mobile-responsive for on-the-go tracking
---
## Technical Architecture
### Frontend (apps/frontend)
```
Framework: Angular 21 (standalone components)
State: Signals + Services (no NgRx for MVP)
Styling: Tailwind CSS 4
Testing: Jest + Angular Testing Library
Build: Vite via Angular CLI
```
### Backend (apps/backend)
```
Runtime: Node.js 22 + Express 5
Language: TypeScript 5.5 (strict mode)
ORM: Prisma 6
Database: PostgreSQL 16
Auth: JWT + Refresh Tokens
Testing: Jest + Supertest
```
### Shared (packages/shared-types)
```
Purpose: TypeScript interfaces shared between FE/BE
Exports: DTOs, API types, enums, constants
```
---
## Coding Conventions
### TypeScript
- Strict mode enabled (no implicit any)
- Prefer `interface` over `type` for objects
- Use `readonly` for immutable properties
- Prefer `const` assertions for literals
### Naming
- **Variables:** camelCase (`userName`, `taskCount`)
- **Functions:** camelCase, verb prefix (`getUserById`, `calculateTotal`)
- **Classes:** PascalCase (`TaskService`, `UserController`)
- **Interfaces:** PascalCase, no `I` prefix (`User`, not `IUser`)
- **Files:** kebab-case (`user-profile.component.ts`)
- **Folders:** kebab-case (`time-entries/`)
- **Constants:** SCREAMING_SNAKE_CASE (`MAX_RETRY_COUNT`)
### Code Style
```typescript
// Prefer
const user = await userService.findById(id);
if (!user) throw new NotFoundError('User', id);
// Avoid
const user = await userService.findById(id);
if (user === null || user === undefined) {{ '{' }}
throw new Error('User not found');
{{ '}' }}
```
### Error Handling
- Use custom error classes (`ValidationError`, `NotFoundError`)
- Always include error codes for API responses
- Log with structured data (JSON), not string concatenation
- Never expose stack traces in production
---
## API Design
### URL Structure
```
GET /api/v1/tasks # List tasks
POST /api/v1/tasks # Create task
GET /api/v1/tasks/:id # Get single task
PATCH /api/v1/tasks/:id # Update task (partial)
DELETE /api/v1/tasks/:id # Soft delete task
```
### Response Format
```typescript
// Success
{{ '{' }} success: true, data: T {{ '}' }}
{{ '{' }} success: true, data: T[], meta: {{ '{' }} page, limit, total {{ '}' }} {{ '}' }}
// Error
{{ '{' }} success: false, error: {{ '{' }} code: string, message: string {{ '}' }} {{ '}' }}
```
### Status Codes
- 200: Success (GET, PATCH)
- 201: Created (POST)
- 204: No Content (DELETE)
- 400: Validation Error
- 401: Unauthorized
- 403: Forbidden
- 404: Not Found
- 500: Internal Error
---
## Current Development State
### Completed
- [x] Project scaffolding and mono-repo setup
- [x] Database schema design
- [x] User authentication (login/register)
- [x] JWT middleware
### In Progress
- [ ] Task CRUD endpoints
- [ ] Task list component
### Blocked
- (none currently)
### Next Up
- Time entries feature
- Dashboard with weekly summary
---
## Known Issues and Tech Debt
1. **Token Refresh:** Currently no automatic refresh on 401
2. **Validation:** Some DTOs missing validation decorators
3. **Tests:** Backend services at 60% coverage, need 80%
4. **Types:** Some `any` usages in legacy migration code
---
## DO NOT
These are strict rules - never violate them:
- Do NOT use `any` type (use `unknown` or proper generics)
- Do NOT skip error handling (always handle or propagate)
- Do NOT commit secrets (use environment variables)
- Do NOT use `console.log` in production code (use logger)
- Do NOT skip tests for new features
- Do NOT use synchronous file operations
- Do NOT use `var` (use `const` or `let`)
- Do NOT mix business logic in controllers
---
## Testing Requirements
### Unit Tests
- Every service method must have tests
- Mock external dependencies
- Aim for 80%+ coverage
### Integration Tests
- Every API endpoint must have tests
- Use test database (not mocks)
- Test success and error cases
### Naming Convention
```typescript
describe('TaskService', () => {{ '{' }}
describe('createTask', () => {{ '{' }}
it('should create a task with valid data', async () => {{ '{' }}
// ...
{{ '}' }});
it('should throw ValidationError when title is empty', async () => {{ '{' }}
// ...
{{ '}' }});
{{ '}' }});
{{ '}' }});
```
---
## Useful Commands
```bash
# Development
npm run dev # Start all apps in dev mode
npm run dev:frontend # Frontend only
npm run dev:backend # Backend only
# Building
npm run build # Build all apps
npm run typecheck # TypeScript check
# Testing
npm run test # Run all tests
npm run test:watch # Watch mode
npm run test:coverage # With coverage report
# Database
npm run db:migrate # Run migrations
npm run db:seed # Seed development data
npm run db:studio # Open Prisma Studio
# Linting
npm run lint # Lint all
npm run lint:fix # Fix auto-fixable issues
```
---
## File Locations Quick Reference
| What | Where |
|------|-------|
| Frontend components | `apps/frontend/src/app/` |
| Backend controllers | `apps/backend/src/modules/*/controllers/` |
| Backend services | `apps/backend/src/modules/*/services/` |
| Database schema | `apps/backend/prisma/schema.prisma` |
| Shared types | `packages/shared-types/src/` |
| E2E tests | `apps/frontend/e2e/` |
| API tests | `apps/backend/src/modules/*/__tests__/` |
---
*Last updated: [DATE]*
*Maintained by: [YOUR NAME]*
System Prompt: Istruzioni Persistenti
Quando usi Claude.ai con i Progetti, puoi definire un System Prompt che viene incluso automaticamente in ogni conversazione. Per Claude Code, il file CLAUDE.md svolge una funzione simile.
System Prompt per Progetti Claude.ai
You are an expert software developer helping me build TaskFlow,
a time tracking and task management application.
## Your Role
- Technical partner and advisor
- Code reviewer with high standards
- Architecture consultant
## Technical Context
- Stack: Angular 21 + Node.js + PostgreSQL
- Style: TypeScript strict mode, functional where appropriate
- Architecture: Layered (Controller/Service/Repository)
## Response Guidelines
1. Always explain your reasoning before providing code
2. Point out potential issues or edge cases
3. Suggest tests for any new functionality
4. Be honest if you're uncertain about something
## Code Style
- TypeScript strict mode
- Prefer composition over inheritance
- Use descriptive names (avoid abbreviations)
- Include error handling in all examples
- Add JSDoc comments for public APIs
## When I Ask for Code
1. First, confirm you understand the requirement
2. Explain the approach you'll take
3. Provide the implementation
4. Suggest how to test it
5. Mention any caveats or limitations
## Communication
- Be concise but thorough
- Use bullet points for lists
- Use code blocks with proper language tags
- Ask clarifying questions when requirements are ambiguous
Esempio di Knowledge Files
Nei Progetti di Claude.ai, puoi aggiungere file alla "Knowledge base" che vengono automaticamente inclusi nel contesto.
File da Includere nella Knowledge Base
| File | Scopo | Priorità |
|---|---|---|
CLAUDE.md |
Istruzioni progetto complete | Essenziale |
docs/architecture.md |
Decisioni architetturali | Alta |
docs/api-spec.md |
Specifiche API | Alta |
tsconfig.json |
Configurazione TypeScript | Media |
package.json |
Dipendenze e script | Media |
prisma/schema.prisma |
Schema database | Alta |
Naming e Struttura Iniziale
Convenzioni di naming consistenti aiutano Claude a generare codice coerente con il resto del progetto.
Convenzioni di Naming Consistenti
// ══════════════════════════════════════════════════════════════
// FILE NAMING
// ══════════════════════════════════════════════════════════════
// Components (Angular)
user-profile.component.ts // kebab-case + .component.ts
user-profile.component.html
user-profile.component.scss
// Services
user.service.ts // singular noun + .service.ts
task-api.service.ts // can have prefix
// Models/Interfaces
user.model.ts // singular + .model.ts
task.interface.ts // or .interface.ts
// DTOs
create-user.dto.ts // verb-noun + .dto.ts
update-task.dto.ts
// Tests
user.service.spec.ts // same name + .spec.ts
user.controller.test.ts // or .test.ts
// ══════════════════════════════════════════════════════════════
// CODE NAMING
// ══════════════════════════════════════════════════════════════
// Variables and Functions
const userName = 'John'; // camelCase
const taskList: Task[] = [];
function calculateTotalTime() {{ '{' }} {{ '}' }}
async function fetchUserById(id: string) {{ '{' }} {{ '}' }}
// Classes and Interfaces
class TaskService {{ '{' }} {{ '}' }} // PascalCase
interface UserProfile {{ '{' }} {{ '}' }}
type TaskStatus = 'TODO' | 'DONE';
// Constants
const MAX_RETRY_COUNT = 3; // SCREAMING_SNAKE_CASE
const API_BASE_URL = '/api/v1';
const DEFAULT_PAGE_SIZE = 20;
// Enums
enum TaskPriority {{ '{' }} // PascalCase enum name
Low = 'LOW', // PascalCase members
Medium = 'MEDIUM',
High = 'HIGH',
{{ '}' }}
// ══════════════════════════════════════════════════════════════
// FOLDER NAMING
// ══════════════════════════════════════════════════════════════
src/
├── components/ // plural, kebab-case
│ └── user-profile/ // kebab-case
├── services/
├── models/
├── utils/
└── shared/ // generic names OK
Struttura Iniziale del Progetto
Aiutami a creare la struttura iniziale per TaskFlow.
## REQUISITI
- Mono-repo con frontend Angular e backend Node.js
- Package shared per tipi TypeScript comuni
- Configurazione Turborepo per build/dev
- Setup Docker per sviluppo locale
## OUTPUT DESIDERATO
1. Albero directory completo
2. File package.json root con workspaces
3. tsconfig.json base
4. docker-compose.yml per PostgreSQL
5. Script npm per comandi comuni
## VINCOLI
- Niente framework di troppo (keep it simple)
- Preferisco Prisma per ORM
- Jest per tutti i test
Strategie per Sessioni Lunghe
Le conversazioni lunghe possono far "dimenticare" a Claude dettagli importanti. Ecco strategie per mantenere la coerenza.
1. Checkpoint Periodici
Prima di continuare, facciamo un checkpoint.
## RIEPILOGO SESSIONE
Abbiamo lavorato su:
1. Creazione del TaskService
2. Implementazione CRUD per i task
3. Testing del service
## DECISIONI PRESE
- Usiamo Signals per lo state management
- Soft delete per i task (deleted_at timestamp)
- Validazione lato service, non controller
## PROSSIMI STEP
- Implementare il controller
- Creare le route
Confermi che questo riassunto è corretto?
2. File di Stato
# Session State - 2025-01-31
## Current Focus
Implementing Task module backend
## Files Modified This Session
- apps/backend/src/modules/tasks/task.service.ts (created)
- apps/backend/src/modules/tasks/task.repository.ts (created)
- apps/backend/prisma/schema.prisma (updated)
## Decisions Made
1. Task entity uses UUID primary key
2. Soft delete pattern with deleted_at column
3. Status enum: TODO, IN_PROGRESS, DONE
## Open Questions
- Should task have project relationship now or later?
- Pagination: offset or cursor-based?
## Next Session
- Create TaskController
- Add API routes
- Write integration tests
3. Nuova Sessione con Contesto
Riprendo il lavoro su TaskFlow dopo una pausa.
## CONTESTO
[Incolla sezione rilevante da CLAUDE.md]
## ULTIMA SESSIONE
- Ho completato TaskService e TaskRepository
- Il database schema è aggiornato
- Mancano controller e route
## OGGI VOGLIO
1. Creare TaskController con tutti gli endpoint
2. Definire le route in Express
3. Scrivere test di integrazione
Prima di iniziare, vuoi che ti mostri il codice
del service per avere contesto?
Gestione Multi-repo
Se devi lavorare con repository separati, ecco come mantenere coerenza.
CLAUDE.md per Multi-repo
# CLAUDE.md - Frontend Repository
## This Repository
Frontend application for TaskFlow.
This is ONE of multiple repos that make up the project.
## Related Repositories
- **Backend:** github.com/user/taskflow-backend
- **Shared Types:** github.com/user/taskflow-shared
## Cross-Repository Contracts
### API Base URL
Development: http://localhost:3000/api/v1
Production: https://api.taskflow.com/v1
### Authentication
- JWT in Authorization header
- Format: `Bearer {{ '{' }}token{{ '}' }}`
- Refresh via POST /auth/refresh
### Type Sharing
We use `@taskflow/shared-types` npm package.
Types are source of truth - generated from backend OpenAPI spec.
## When Making Changes That Affect Other Repos
1. Update shared-types first
2. Publish new version
3. Update both FE and BE
4. Test integration locally
Checklist Setup Progetto
Checklist: Contesto Ottimale
- Repository creato con struttura chiara
- CLAUDE.md completo nella root
- README.md con overview progetto
- System prompt configurato (se usi Claude.ai Projects)
- Knowledge files aggiunti al progetto
- Convenzioni di naming documentate
- File .env.example con variabili richieste
- docker-compose.yml per sviluppo locale
- Script npm per comandi comuni
Errori Comuni nella Gestione del Contesto
Errori da Evitare
- Contesto troppo lungo: 200K token sembrano tanti, ma si esauriscono. Mantieni CLAUDE.md conciso e focalizzato.
- Informazioni contraddittorie: Se aggiorni le convenzioni, aggiorna anche CLAUDE.md. Contesto inconsistente genera codice inconsistente.
- Troppi file nella Knowledge: Claude legge tutto. Se includi file irrilevanti, diluisci l'attenzione sulle parti importanti.
- Nessun checkpoint: Sessioni lunghe senza riepiloghi portano a drift e incoerenze.
- System prompt generico: "Sei un developer esperto" non basta. Sii specifico sul tuo stack e preferenze.
Conclusione
Un contesto ben strutturato è la chiave per ottenere risultati consistenti e di alta qualità da Claude. Investi tempo nella creazione di CLAUDE.md e nella struttura del repository: questo investimento si ripaga in ogni singola interazione successiva.
Punti Chiave
- CLAUDE.md è essenziale: Crea e mantieni aggiornato questo file
- Struttura repository chiara: Aiuta Claude a navigare il progetto
- Convenzioni consistenti: Naming predicibile genera codice predicibile
- Checkpoint regolari: Mantieni il contesto nelle sessioni lunghe
- Mono-repo per progetti personali: Semplifica la gestione del contesto
Prossimo Articolo
Nel prossimo articolo "Ideazione e Requisiti" vedremo come usare Claude per passare da un'idea vaga a requisiti concreti: MVP definition, user personas, use cases e prioritizzazione delle feature.







