This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
This is an MVP for a Guideline-Aware AI Agent inspired by Parlant.io's implementation. The agent dynamically incorporates behavioral guidelines from a database into prompts sent to Claude AI, creating context-aware responses for sales scenarios.
- ✅ Guidelines CRUD API with database persistence
- ✅ Message API with Claude AI integration and required chatId
- ✅ Chat concept with conversation grouping and context-aware summaries
- ✅ Dynamic prompt construction from active guidelines + chat context
- ✅ Customer-focused summary generation to avoid repetition
- ✅ Full prompt and response tracking in database
- ✅ Comprehensive test suite with 97%+ coverage (21 tests)
- ✅ Clean Architecture with layered application functions
- ✅ TDD outside-in approach with integration testing
- Store behavioral guidelines in PostgreSQL database (condition, action, isActive)
- Group messages into conversations via required chatId (UUID)
- Generate customer-focused summaries highlighting emotions, interests, and actions taken
- Retrieve active guidelines and construct dynamic prompts with chat context
- Send prompts to Claude AI via Anthropic SDK
- Persist messages, prompts, responses, and chat summaries for full traceability
- Sales-focused scenarios with objection handling and conversational continuity
make run- Initial setup: installs dependencies, creates .env files, starts containersmake watch- Start development server with file watching (http://localhost:8000)make test- Run test suite with watch modemake test/ci- Run test suite in CI mode without watchmake populate- Seed database with test data (3 chats, 9 messages, 10 guidelines)make down- Stop containersmake clean-db- Remove database volumes
make prisma/client/generate- Generate Prisma clientecho "migration_name" | make prisma/migrations/generate- Create migration filesmake prisma/migrations/apply- Apply pending migrations
npm run dev- Development server with SWCnpm run lint- Run ESLintnpm run typecheck- TypeScript type checkingnpm run test:ci- CI testing with coveragenpm run build- Production build
The codebase follows layered architecture with clear separation of concerns:
- Domain: Business entities and interfaces (Message, Chat, Guideline)
- Application: Business logic and use cases (buildPrompt, generateResponse, ensureChatAndUpdateSummary, generateSummary)
- Infrastructure: External concerns (Controllers, repositories, Claude service, database)
- buildPrompt.ts: Retrieves active guidelines and chat context to construct prompts
- generateResponse.ts: Handles Claude API calls with pre-built prompts
- ensureChatAndUpdateSummary.ts: Manages chat creation and summary generation workflow
- generateSummary.ts: Creates customer-focused conversation summaries using Claude
- Separation of Concerns: Each function has single responsibility for maintainability and testability
- HTTP API:
src/server.ts- REST endpoints for agent interactions
-
POST /api/guideline: Create guidelines
- Request:
{ "condition": "string", "action": "string", "isActive": boolean } - Response: Created guideline with ID and timestamps
- Validation: All fields required
- Request:
-
POST /api/message: Send message to AI agent and receive response with chat context
- Request:
{ "message": "string", "userId": number, "chatId": "uuid" }(all fields required) - Response:
{ "response": "string" } - Process: ensureChatAndUpdateSummary(chatId) → buildPrompt(message, chatId) → generateResponse(prompt) → save all to DB
- Database: Stores content, prompt, response, userId, chatId for full traceability and conversation grouping
- Request:
- Guidelines System: Dynamic prompt construction based on active database guidelines
- Chat Management: Conversation grouping with automatic chat creation and context-aware summaries
- Claude Integration: Anthropic SDK with singleton pattern for efficiency
- Message Processing: Complete workflow from user input to AI response with chat context and persistence
- Summary Generation: Customer-focused summaries to avoid repetition and improve conversation flow
- Database Tracking: Full traceability of prompts, responses, and chat summaries for debugging/optimization
- chat: Groups related messages and stores conversation summaries
id(UUID),summary(customer-focused summary), timestamps
- message: Stores user inputs, constructed prompts, and AI responses
id(UUID),content(user message),prompt(constructed),response(AI),userId,chatId(required FK), timestamps
- guideline: Stores behavioral rules for prompt construction
id(UUID),condition(trigger),action(behavior),isActive(boolean), timestamps
- PostgreSQL with Prisma ORM
- UUID-based primary keys for all models
- Timestamptz for timezone-aware created/updated dates
- Default values for new fields to handle existing data
- Migration strategy: Always use
echo "name" | make prisma/migrations/generate
- Test-First Development: Always write tests before implementation
- Outside-In Flow: Start with integration tests → implement application layer → infrastructure layer
- Real Database Integration: TestContainers with PostgreSQL for authentic integration testing
- External Service Mocking: Mock
@anthropic-ai/sdkat the boundary, not internal application functions
- Integration Tests: HTTP endpoints testing complete workflows through all layers
- Mock Strategy: Mock only external dependencies (Anthropic SDK) while using real database
- Centralized Setup: Mock configuration in
tests/config/setup/setup.integration.ts - Coverage Focus: Business logic and critical paths with 97%+ coverage
- Chat Integration: Chat creation, message association, summary generation (3 tests)
- Message Integration: Complete message flow with chat context and validation (8 tests)
- Guidelines Integration: CRUD operations with database persistence (5 tests)
- Claude Integration: Prompt construction and AI response with mocked Anthropic SDK (3 tests)
- Health Check: Basic application health (2 tests)
make test- Run all tests with watch mode for developmentmake test/ci- CI mode without watch, includes coverage report- Uses Jest with SWC for performance, TestContainers for real PostgreSQL database
- Write failing integration test for new feature
- Implement application layer function to handle business logic
- Create infrastructure layer (repository, controller) to satisfy test
- Refactor while keeping tests green
- Add edge cases and validation tests
- Node.js 20.10.0+
- Docker and Docker Compose
- PostgreSQL (via container)
- Anthropic API key for Claude integration
.env.exampletemplate includesANTHROPIC_API_KEY- Run
./scripts/setup_env.shto create.env.dev - Configure
ANTHROPIC_API_KEYin.env.devfor production use - Tests work with mocked Anthropic SDK, no API key needed for development
- Always start with tests: Write failing integration test before any implementation
- Outside-In Flow: Integration test → Application layer → Infrastructure layer
- Domain-Driven Design: Organize code by business domains (chat, message, guideline)
- Mock only external boundaries: Real database + mocked Anthropic SDK
- ALWAYS use
makecommands when available instead of npm/npx directly - Migrations: Use
echo "migration_name" | make prisma/migrations/generate - Testing: Use
make testfor development,make test/cifor CI - Linting: Always run
npm run lintandnpm run typecheckbefore commits
- Domain Layer: Business entities (Message, Chat, Guideline interfaces)
- Application Layer: Business logic (buildPrompt, ensureChatAndUpdateSummary, generateSummary)
- Infrastructure Layer: External concerns (controllers, repositories, Claude service)
- Single Responsibility: Each application function has one clear purpose
- Dependency Direction: Infrastructure depends on Application, Application depends on Domain
- Required ChatId: All messages must belong to a conversation (UUID)
- Automatic Chat Creation: First message creates chat, subsequent messages update summary
- Customer-Focused Summaries: Capture emotions, interests, and actions taken to avoid repetition
- Context-Aware Prompts: Include chat summary in prompt construction for continuity
- 21 Integration Tests: Complete workflows through HTTP endpoints
- TestContainers: Real PostgreSQL database for authentic testing
- Mocked External Services: Anthropic SDK mocked at boundary
- 97%+ Coverage: High confidence in business logic correctness
- TDD Workflow: Test → Application → Infrastructure → Refactor
- Use
express-async-errorsfor async route handlers - Centralized error handling middleware
- Graceful degradation when external services fail
TypeScript paths configured in tsconfig.json:
@/src/*maps to./src/*- Use
tsconfig-paths/registerfor runtime resolution