Skip to content

Latest commit

 

History

History
198 lines (161 loc) · 10 KB

File metadata and controls

198 lines (161 loc) · 10 KB

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project Overview

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.

Current State (Implemented)

  • ✅ 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

Core Functionality

  • 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

Essential Commands

IMPORTANT: Always use make commands when available

Development Workflow

  • make run - Initial setup: installs dependencies, creates .env files, starts containers
  • make watch - Start development server with file watching (http://localhost:8000)
  • make test - Run test suite with watch mode
  • make test/ci - Run test suite in CI mode without watch
  • make populate - Seed database with test data (3 chats, 9 messages, 10 guidelines)
  • make down - Stop containers
  • make clean-db - Remove database volumes

Database Operations (Always use these instead of npx directly)

  • make prisma/client/generate - Generate Prisma client
  • echo "migration_name" | make prisma/migrations/generate - Create migration files
  • make prisma/migrations/apply - Apply pending migrations

npm Scripts (when make is not available)

  • npm run dev - Development server with SWC
  • npm run lint - Run ESLint
  • npm run typecheck - TypeScript type checking
  • npm run test:ci - CI testing with coverage
  • npm run build - Production build

Architecture Overview

Clean Architecture Pattern (Domain-Driven Design)

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)

Application Layer Functions

  • 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

Entry Point

  • HTTP API: src/server.ts - REST endpoints for agent interactions

API Endpoints

  • POST /api/guideline: Create guidelines

    • Request: { "condition": "string", "action": "string", "isActive": boolean }
    • Response: Created guideline with ID and timestamps
    • Validation: All fields required
  • 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

Key Components

  • 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

Database Schema

Current Models

  • 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

Database Patterns

  • 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

Testing Strategy

TDD Outside-In Approach

  • 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/sdk at the boundary, not internal application functions

Testing Layers (Domain-Driven Design)

  • 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

Current Test Structure

  • 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)

Test Execution Commands

  • make test - Run all tests with watch mode for development
  • make test/ci - CI mode without watch, includes coverage report
  • Uses Jest with SWC for performance, TestContainers for real PostgreSQL database

TDD Workflow Example

  1. Write failing integration test for new feature
  2. Implement application layer function to handle business logic
  3. Create infrastructure layer (repository, controller) to satisfy test
  4. Refactor while keeping tests green
  5. Add edge cases and validation tests

Development Environment

Requirements

  • Node.js 20.10.0+
  • Docker and Docker Compose
  • PostgreSQL (via container)
  • Anthropic API key for Claude integration

Environment Setup

  • .env.example template includes ANTHROPIC_API_KEY
  • Run ./scripts/setup_env.sh to create .env.dev
  • Configure ANTHROPIC_API_KEY in .env.dev for production use
  • Tests work with mocked Anthropic SDK, no API key needed for development

Important Development Patterns

TDD Outside-In 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

Commands and Tools

  • ALWAYS use make commands when available instead of npm/npx directly
  • Migrations: Use echo "migration_name" | make prisma/migrations/generate
  • Testing: Use make test for development, make test/ci for CI
  • Linting: Always run npm run lint and npm run typecheck before commits

Clean Architecture Implementation

  • 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

Chat System Architecture

  • 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

Testing Architecture

  • 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

Error Handling

  • Use express-async-errors for async route handlers
  • Centralized error handling middleware
  • Graceful degradation when external services fail

Path Aliases

TypeScript paths configured in tsconfig.json:

  • @/src/* maps to ./src/*
  • Use tsconfig-paths/register for runtime resolution