Repository navigation
AI Context Pack
Canonical source:
docs/15-ai-context/ai-context-pack.md— this page is rendered from it on every publish; edit the source.
Optimized reference for AI coding agents working on the ClawAI codebase. Read this first, then CLAUDE.md at the project root for mandatory rules.
What: ClawAI is a local-first AI orchestration platform that routes user messages to the optimal AI provider (cloud or local Ollama) based on task type, privacy needs, cost, and latency.
Why: Organizations need a single interface that intelligently selects from multiple AI providers while keeping sensitive data local when required.
How: 21 NestJS microservices communicate via RabbitMQ events, each owning its own database. A Next.js frontend connects through an Nginx reverse proxy. Ollama runs locally for privacy-sensitive tasks and as the routing brain in AUTO mode.
- User sends a message through the Next.js frontend (port 3000).
- Nginx reverse proxy (port 4000) routes the request to the chat service.
- Chat service creates a USER message and publishes
message.createdto RabbitMQ. - Routing service consumes the event, evaluates routing mode and policies, publishes
message.routed. - Chat service consumes routing result, assembles context (memories, context packs, file chunks, thread history).
- Chat service calls the selected AI provider (Ollama, OpenAI, Anthropic, Google, DeepSeek) with fallback chain.
- ASSISTANT message is stored, SSE pushes completion to the frontend.
-
message.completedevent triggers memory extraction (Ollama) and audit logging (MongoDB). - Each service owns its own PostgreSQL or MongoDB database; no shared databases.
- All inter-service communication is async (RabbitMQ) or HTTP (for synchronous data fetches during context assembly).
| Service | Port | Database | Purpose |
|---|---|---|---|
| auth | 4001 | PG claw_auth
|
JWT auth, RBAC (Admin/Operator/Viewer), sessions, user management |
| chat | 4002 | PG claw_chat
|
Threads, messages, context assembly, AI execution, SSE streaming |
| connector | 4003 | PG claw_connectors
|
Cloud provider configs (encrypted), health checks, model sync |
| routing | 4004 | PG claw_routing
|
7 routing modes, policy engine, Ollama-assisted AUTO routing |
| memory | 4005 | PG claw_memory
|
Memory CRUD, extraction via Ollama, context packs (pgvector) |
| file | 4006 | PG claw_files
|
File upload, chunking (JSON/CSV/MD/text), storage |
| audit | 4007 | MongoDB claw_audit
|
10 audit event types, usage ledger |
| ollama | 4008 | PG claw_ollama
|
Local model management, role assignments, pull jobs, generation |
| health | 4009 | None | Aggregated health checks from all services |
| client-logs | 4010 | MongoDB claw_client_logs
|
Frontend log ingestion, batched, TTL 30 days |
| server-logs | 4011 | MongoDB claw_server_logs
|
Backend log aggregation, TTL 30 days |
| image | 4012 | PG claw_image
|
Image generation via AI providers |
| file-generation | 4013 | PG claw_filegen
|
AI-driven file/document generation |
Controller (3 lines max: extract params, call service, return result)
-> Service (business logic, validation, event publishing, max 30 lines/method)
-> Repository (pure data access, no throws, no business logic)
-> Manager (complex orchestration, max 80 lines/method, complexity <= 15)
Controllers never contain try/catch or throw statements. Repositories never throw. Services own all validation and permission checks.
- Topic exchange:
claw.events(durable) - DLQ with 3 retries and exponential backoff
- Key events:
message.created,message.routed,message.completed,connector.synced,user.login - Publishers and consumers are defined in service modules; event payloads are typed in
packages/shared-types
- Chat completions stream to connected clients via Server-Sent Events
- Frontend uses
fetch-based SSE (notEventSource) to support Authorization headers - Connection managed through
ChatExecutionManager
- When primary provider fails, routing provides a fallback provider/model
- Chat execution tries primary, then fallback, logging which succeeded
- Local Ollama is always available as ultimate fallback
-
No
any-- useunknown, generics, or proper types. Tests are exempt. -
No
console.log-- use NestJSLogger(backend) or logger utility (frontend). Onlyconsole.warn/console.errorallowed. -
All input validated with Zod -- every
z.string()needs.max(), everyz.array()needs.max(). -
Errors use
BusinessExceptionwith machine-readablecodestring. Entity-not-found usesEntityNotFoundException. - No inline types/enums/constants in logic files -- extract to dedicated files (see Extraction Rules below).
-
No direct
process.env-- use Zod-validatedAppConfig. -
No
!non-null assertions -- handle nullability explicitly. -
No string literal unions -- use enums from
src/enums/orsrc/common/enums/. -
Third-party libraries must be wrapped in
src/common/utilities/<name>.utility.ts. - No Prisma/Mongoose calls outside repositories.
| What | Backend Location | Frontend Location |
|---|---|---|
| Types/interfaces | src/modules/<domain>/types/<name>.types.ts |
src/types/<domain>.types.ts |
| Enums | src/common/enums/<name>.enum.ts |
src/enums/<name>.enum.ts |
| Constants | src/common/constants/<name>.constants.ts |
src/constants/<name>.constants.ts |
| Utilities | src/common/utilities/<name>.utility.ts |
src/utilities/<name>.utility.ts |
| DTOs | src/modules/<domain>/dto/<name>.dto.ts |
N/A |
| Hooks | N/A | src/hooks/<domain>/use-<name>.ts |
| Repositories | src/modules/<domain>/<domain>.repository.ts |
src/repositories/<domain>/<domain>.repository.ts |
-
Connector encryption -- API keys encrypted with AES-256-GCM. The
ENCRYPTION_KEYenv var is 64 hex chars. Changing it invalidates all stored connector configs. Seeconnector-service/src/common/utilities/. -
JWT secrets --
JWT_SECRETsigns all tokens. Changing it invalidates all sessions. Refresh token rotation is implemented. -
Database migrations -- Prisma migrations in each service. Always run
npx prisma migrate dev --name <name>. Never edit existing migration files. Each service has its ownprisma/directory. -
RabbitMQ event contracts -- Event payloads are shared via
packages/shared-types. Changing a payload shape requires updating all consumers. -
Context assembly token budget --
ChatExecutionManagertruncates context to fit token limits. Bugs here cause silent data loss or provider API errors. -
Ollama model role assignments -- The router model (
gemma3:4bdefault) powers AUTO routing. If misconfigured, all AUTO routing breaks. -
Log redaction -- Pino is configured to redact
authorization,password,refreshToken,apiKey,token,secret. Adding new sensitive fields requires updating redaction config.
-
DTO:
apps/claw-<service>/src/modules/<domain>/dto/<name>.dto.ts(Zod schema + inferred type) -
Controller:
apps/claw-<service>/src/modules/<domain>/<domain>.controller.ts(3-line method) -
Service:
apps/claw-<service>/src/modules/<domain>/<domain>.service.ts(business logic) -
Repository:
apps/claw-<service>/src/modules/<domain>/<domain>.repository.ts(data access) -
Test:
apps/claw-<service>/src/__tests__/<domain>/<name>.spec.ts -
Nginx:
infra/nginx/nginx.conf(add route mapping if new path prefix)
-
Payload type:
packages/shared-types/src/events/<event-name>.event.ts -
Export:
packages/shared-types/src/index.ts - Publisher: In the service module that owns the event
- Consumer: In the service module(s) that react to it
-
Update:
CLAUDE.mdevent bus table
-
Page:
apps/claw-frontend/src/app/(authenticated)/<route>/page.tsx(render only, one controller hook) -
Controller hook:
apps/claw-frontend/src/hooks/<domain>/use-<name>.ts -
Repository:
apps/claw-frontend/src/repositories/<domain>/<domain>.repository.ts -
Types:
apps/claw-frontend/src/types/<domain>.types.ts -
i18n: Add keys to all 9 locale files in
apps/claw-frontend/src/lib/i18n/locales/ - Sidebar: Update navigation components if needed
-
Schema:
apps/claw-<service>/prisma/schema.prisma -
Migration:
npx prisma migrate dev --name add-<table-name>(run inside the service directory) - Repository: New or updated repository file
- Types: Update shared types if exposed to other services
| Priority | File | Why |
|---|---|---|
| 1 |
CLAUDE.md (project root) |
All mandatory rules, architecture, patterns, env vars |
| 2 | docs/00-start-here/system-at-a-glance.md |
Visual architecture, service map, key flows |
| 3 | packages/shared-types/src/ |
All shared enums, event payloads, auth types |
| 4 | packages/shared-rabbitmq/src/ |
RabbitMQ module, retry logic, structured logger |
| 5 | apps/claw-chat-service/src/modules/chat-messages/ |
Most complex service -- context assembly + execution |
| 6 | apps/claw-routing-service/src/modules/routing/ |
Routing decision engine |
| 7 | apps/claw-frontend/src/app/(portal)/chat/ |
Main chat UI pages and components |
| 8 | apps/claw-frontend/src/hooks/chat/ |
Chat hooks -- demonstrate the hook pattern |
| 9 | infra/nginx/nginx.conf |
All route mappings |
| 10 | .env.example |
Every environment variable the system uses |
-
Backend: Vitest (ADR-099). Tests in
apps/claw-<service>/src/__tests__/. Unit tests for services and managers; integration tests for controllers. -
Frontend: Vitest. Tests colocated or in
__tests__directories. -
E2E: Playwright. In
apps/claw-frontend/tests/e2e/(apps/claw-frontend/playwright.config.ts). - Every new function needs a test. No exceptions.
-
Test files are exempt from the no-
anyrule and inline restrictions. - Pre-commit hook runs all tests -- they must pass before commit.
-
2766 test files across the monorepo (
.ai/manifests/tests.json).
-
Pre-commit hook -- 5 steps (Prettier, ESLint, TypeScript, build, tests). All must pass. Do not add
eslint-disablecomments. - Event contracts -- Changing RabbitMQ event shapes without updating all consumers causes silent failures.
- Prisma migrations -- Never delete or modify existing migration files. Always create new ones.
- Auth flow -- JWT + refresh token rotation is security-critical. Test thoroughly after any auth changes.
- Connector encryption -- AES-256-GCM. Changing encryption logic or key format breaks all stored API keys.
- i18n completeness -- All 9 locales must have every key. Missing keys cause runtime errors in non-English locales.
- Database isolation -- Services never share databases. Cross-service data access goes through RabbitMQ or HTTP.
- Import patterns -- Third-party libraries are wrapped in utilities. Direct imports outside wrappers will fail linting.
- Nginx routes -- Changing route patterns without updating both Nginx config and frontend API calls breaks the frontend.
-
Shared packages -- Changes to
packages/shared-typesorpackages/shared-rabbitmqaffect all services. Rebuild and test broadly.
ClawAI Wiki · source-controlled under wiki/ · generated/mirrored from the current repository knowledge layer.
ClawAI Wiki
Product
- Product-Vision
- Flagship-Features
- Business-Overview
- Requirements-Register
- Drift-Log
- Runtime-Managed-Connector-Providers
- Threads
- ADR-Index
Architecture
- System-at-a-Glance
- Architecture-Map
- System-Architecture
- Message-Flow
- End-to-End-Data-Flow
- Routing-Engine
- Event-Bus
- Security-Architecture
Platform
- Backend-Services
- Frontend-Architecture
- Shared-Packages
- Database-Reference
- API-Reference
- Provider-Catalog
- Memory-and-Context-Architecture
- File-Support-Architecture
- Research-and-Web-Crawling
Runtime & Ops
- Docker-Guide
- Nginx-Reference
- CI-CD-Pipeline
- Logging-and-Observability
- Operational-Runbooks
- Troubleshooting
Quality
Engineering OS
- AI-Native-Engineering-OS
- Generated-Manifests
- Rules-Catalog
- Skills-Catalog
- Context-Layer
- Engineering-Memory
- Tooling-and-Automation
- Scripts-and-Operations
- ESLint-and-Architecture-Enforcement
- Extended-Work-Skills
Agents
Reference