Salta al contenuto principale

02 - Contesto e Setup del Progetto con Claude

Fornisci contesto efficace a Claude: struttura repository, file CLAUDE.md, system prompt persistenti e strategie per progetti mono/multi-repo.

Cosa ne pensi di questo articolo?

02 - Contesto e Setup del Progetto con Claude
ClaudeFoto:Matheus BertelliPexels

In Breve

Fornisci contesto efficace a Claude: struttura repository, file CLAUDE.md, system prompt persistenti e strategie per progetti mono/multi-repo.

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
1Foundation: Claude come Partner TecnicoCompletato
2Contesto e Setup del ProgettoSei qui
3Ideazione e RequisitiProssimo
4Architettura Backend e Frontend
5Struttura del Codice
6Prompt Engineering Avanzato
7Testing e qualità
8Documentazione
9Deploy 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

ElementoToken ApprossimatiNote
System Prompt500 - 2.000Sempre presente in ogni richiesta
CLAUDE.md1.000 - 5.000Istruzioni progetto
File Codice (medio)500 - 2.000Per file incluso
ConversazioneVariabileCresce nel tempo
RispostaMax 4.096Limite output di default

Priorità del Contesto

Claude assegna peso diverso alle informazioni in base a dove si trovano:

Gerarchia di Priorità del Contesto
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

Repository Structure - Mono-repo
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 - Template Completo
# 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

System Prompt - Template per Sviluppo
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

FileScopoPriorità
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

Naming Conventions - Guida Completa
// ══════════════════════════════════════════════════════════════
// 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

Prompt - Scaffold Iniziale
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

Prompt - Checkpoint di Contesto
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.md - Traccia Sessione
# 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

Prompt - Ripresa Sessione Precedente
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

Struttura CLAUDE.md 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

  1. Contesto troppo lungo: 200K token sembrano tanti, ma si esauriscono. Mantieni CLAUDE.md conciso e focalizzato.
  2. Informazioni contraddittorie: Se aggiorni le convenzioni, aggiorna anche CLAUDE.md. Contesto inconsistente genera codice inconsistente.
  3. Troppi file nella Knowledge: Claude legge tutto. Se includi file irrilevanti, diluisci l'attenzione sulle parti importanti.
  4. Nessun checkpoint: Sessioni lunghe senza riepiloghi portano a drift e incoerenze.
  5. 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.

Prova Questi Strumenti

Strumenti gratuiti correlati a questo argomento.

Commenti

Caricamento commenti...

Accedi per commentare

Discuti questo articolo nella community

Unisciti al gruppo Telegram per discutere con altri sviluppatori, fare domande e condividere le tue esperienze.

Ti è piaciuto questo articolo?

Esplora altri contenuti sul blog o scopri i miei progetti