Custom Domain Expert
Configure the Domain Expert for your specific business domain
Why Customize the Domain Expert?
Generic AI knowledge isn't enough. An AI that knows "how e-commerce works" doesn't know how your e-commerce works. It doesn't know your SKU naming conventions, your fulfillment partner APIs, your pricing rules, or why that one legacy field exists.
The Domain Expert is your project's institutional knowledge, encoded in a way agents can consume. It answers the questions that would otherwise require pinging a senior engineer: "Why is this like this?" "What's the pattern for X?" "Who owns this system?"
Step-by-Step Customization
Step 1: Create the Domain Expert Document
The Domain Expert's knowledge lives in agent_docs/domain-expert.md:
# agent_docs/domain-expert.md
## Business Domain
### What We Do
[Your company's core business in 2-3 sentences]
### Key Entities
[List your domain objects: User, Order, Product, etc.]
### Business Rules
[Critical rules that must never be violated]
## Architecture
### System Overview
[High-level architecture diagram or description]
### Service Boundaries
[Which services own which domains]
### Data Flow
[How data moves through your system]
## Conventions
### Naming
[Your naming conventions for entities, APIs, files]
### Patterns
[Common patterns used in your codebase]
### Anti-Patterns
[Things to avoid and why]Step 2: Document Your Data Sources
## Data Sources
### Primary Database (PostgreSQL)
- **users**: User accounts and profiles
- **orders**: Order records with status tracking
- **products**: Product catalog with pricing
- Connection: DATABASE_URL environment variable
### Analytics (BigQuery)
- **events**: User behavior events
- **metrics**: Aggregated business metrics
- Access: Via analytics-service API, not direct queries
### External APIs
- **Stripe**: Payment processing
- **SendGrid**: Transactional email
- **Twilio**: SMS notifications
- All keys in secrets manager, never hardcodedStep 3: Add Business Rules
## Business Rules
### Critical (Never Violate)
1. **PII Handling**: Never log or expose email, phone, SSN
2. **Payment Data**: Never store card numbers, use Stripe tokens
3. **Pricing**: Always calculate server-side, never trust client
4. **Auth**: All API endpoints require authentication
### Important (Strong Preference)
1. **Soft Deletes**: Never hard-delete user data
2. **Audit Trail**: All state changes must be logged
3. **Idempotency**: All write operations must be idempotent
### Contextual (Depends on Situation)
1. **Caching**: Cache reads aggressively, invalidate on writes
2. **Async**: Prefer async for operations > 100msStep 4: Document Your APIs
## API Conventions
### REST Endpoints
- Base: `/api/v1/`
- Resources: plural nouns (users, orders, products)
- Actions: `POST /resource/:id/action`
### Response Format
```json
{
"data": { ... },
"meta": { "page": 1, "total": 100 },
"errors": []
}
```
### Error Codes
- 400: Bad request (client error)
- 401: Unauthorized (no/invalid token)
- 403: Forbidden (valid token, no permission)
- 404: Not found
- 422: Validation failed
- 500: Server error (never expose internals)Example Configurations by Domain
Fintech / Financial Services
## Domain: Financial Services
### Regulatory Requirements
- **PCI-DSS**: Card data handling compliance
- **SOC 2**: Audit logging requirements
- **KYC/AML**: Identity verification flows
### Money Handling Rules
1. Always use decimal types, never floats
2. Store amounts in cents (integer)
3. Include currency code with every amount
4. All transactions must be idempotent (idempotency key)
5. Double-entry bookkeeping for all ledger operations
### Audit Requirements
- Every financial operation logged with:
- Timestamp, actor, action, before/after state
- IP address, user agent, session ID
- Logs retained for 7 years minimum
### Testing Requirements
- All money calculations need property-based tests
- Reconciliation jobs must have rollback proceduresHealthcare
## Domain: Healthcare
### HIPAA Compliance
- **PHI Definition**: Name, DOB, SSN, medical record numbers,
health conditions, treatment information
- **Minimum Necessary**: Only access PHI needed for the task
- **Audit Trail**: All PHI access must be logged
### Data Handling
1. PHI encrypted at rest (AES-256) and in transit (TLS 1.3)
2. No PHI in logs, error messages, or stack traces
3. PHI queries require explicit role authorization
4. Data export requires compliance officer approval
### Integration Patterns
- HL7 FHIR for external health system integration
- All external calls through integration service
- Retry with exponential backoff, max 3 attempts
### Environment Separation
- PHI only in production environment
- Dev/staging use synthetic test data onlyE-commerce
## Domain: E-commerce
### Product Catalog
- **SKU Format**: {CATEGORY}-{BRAND}-{VARIANT}-{SIZE}
- **Pricing**: Base price + modifiers (size, color, etc.)
- **Inventory**: Real-time sync with warehouse API
### Order Lifecycle
1. CREATED → PAID → PROCESSING → SHIPPED → DELIVERED
2. Can only transition forward (except CANCELED)
3. CANCELED allowed from CREATED, PAID, PROCESSING only
4. Refunds trigger reverse state machine
### Fulfillment Rules
- Orders < $50: Standard shipping only
- Orders > $500: Require fraud review
- International: Customs declaration required
- Oversized items: Special carrier API
### Pricing Rules
- Discounts applied: member → promo → volume (in order)
- Tax calculated after discounts
- Never show negative prices (floor at $0.01)SaaS Platform
## Domain: SaaS Platform
### Multi-tenancy
- **Isolation**: Row-level security with tenant_id
- **Data**: Never cross tenant boundaries
- **Queries**: Always include tenant_id in WHERE clause
### Subscription Model
- **Plans**: Free, Starter ($29), Pro ($99), Enterprise (custom)
- **Billing Cycle**: Monthly or annual (2 months free)
- **Usage Limits**: Enforced at API layer, not database
### Feature Flags
- All new features behind flags
- Flags defined in: /config/feature-flags.yaml
- Rollout: internal → beta → 10% → 50% → 100%
### API Rate Limits
- Free: 100 req/min
- Starter: 1000 req/min
- Pro: 10000 req/min
- Enterprise: CustomWhere to Put Domain Knowledge
Domain knowledge lives in the agent_docs/ directory at your project root:
agent_docs/
├── domain-expert.md # Main domain knowledge (required)
├── glossary.md # Domain terminology definitions
├── architecture/
│ ├── overview.md # System architecture
│ ├── data-flow.md # How data moves
│ └── services.md # Service boundaries
├── integrations/
│ ├── stripe.md # Payment integration details
│ ├── sendgrid.md # Email integration
│ └── warehouse-api.md # Fulfillment integration
└── runbooks/
├── deploy.md # Deployment procedures
├── incident.md # Incident response
└── on-call.md # On-call proceduresTeaching About Data Sources
The Domain Expert needs to know where data lives and how to access it:
Database Schema Documentation
## Database: PostgreSQL
### Core Tables
#### users
| Column | Type | Description |
|--------|------|-------------|
| id | uuid | Primary key |
| email | varchar(255) | Unique, indexed |
| created_at | timestamp | Auto-set on insert |
| status | enum | active, suspended, deleted |
#### orders
| Column | Type | Description |
|--------|------|-------------|
| id | uuid | Primary key |
| user_id | uuid | FK to users, indexed |
| status | enum | Order lifecycle state |
| total_cents | integer | Total in cents |
### Indexes
- users: email (unique), created_at
- orders: user_id, status, created_at
### Common Queries
```sql
-- Get user with recent orders
SELECT u.*, array_agg(o.*) as orders
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE u.id = $1
AND o.created_at > NOW() - INTERVAL '30 days'
GROUP BY u.id;
```API Documentation
## External APIs
### Stripe (Payments)
- **Base URL**: https://api.stripe.com/v1
- **Auth**: Bearer token (STRIPE_SECRET_KEY)
- **Used For**: Charges, subscriptions, refunds
Key Endpoints:
- POST /charges - Create a charge
- POST /refunds - Refund a charge
- GET /customers/:id - Get customer details
### Internal Services
- **user-service**: User management (port 3001)
- **order-service**: Order processing (port 3002)
- **notification-service**: Email/SMS (port 3003)
Service Discovery: Kubernetes DNS
Format: {service}.{namespace}.svc.cluster.localValidation and Testing
After configuring your Domain Expert, validate it works:
# Ask the Domain Expert domain-specific questions
You: What's our SKU naming convention?
Domain Expert: SKUs follow the pattern {CATEGORY}-{BRAND}-{VARIANT}-{SIZE}.
For example, SHIRT-NIKE-BLU-L for a large blue Nike shirt.
You: Can we hard-delete user data?
Domain Expert: No. Per business rules, we use soft deletes for all
user data. The status field should be set to 'deleted' and
deleted_at timestamp recorded. This maintains audit trail
compliance.
You: How do we handle payment failures?
Domain Expert: Payment failures trigger the retry flow:
1. Immediate retry (network issues)
2. 1 hour delay retry (temporary bank issues)
3. 24 hour delay with user notification
4. Mark subscription as past_due after 3 failuresKeeping It Current
Best practices for maintenance:
- PR Reviews: Check if domain docs need updates with each PR
- Quarterly Audit: Review all domain docs for accuracy
- Incident-Driven: If an incident reveals missing knowledge, add it
- Onboarding Test: Can a new hire understand the domain from these docs?
Next Steps
Domain knowledge is part of your broader Memory Bank. Learn how to set up the complete Memory Bank for comprehensive project context.