# Veritas Domain - Architecture

> **Canonical source:** the canonical architecture document for this domain is
> [`deep-dive/architecture.md`](./deep-dive/architecture.md), rendered in the
> docs center. This file is its operational companion (service topology, APIs,
> schemas, runtime detail) — reconciled by linking, not duplicated (§2, §13).

This document describes the system architecture of the Veritas domain -- an
AI-powered news agency for Ghana and West Africa. It covers application
architecture, library dependency graph, data flow, key design decisions,
integration points, and infrastructure requirements.

---

## Table of Contents

1. [Architecture Overview](#architecture-overview)
2. [System Context](#system-context)
3. [Application Architecture](#application-architecture)
4. [Library Architecture](#library-architecture)
5. [Data Flow](#data-flow)
6. [Key Design Decisions](#key-design-decisions)
7. [Integration Points](#integration-points)
8. [Infrastructure Requirements](#infrastructure-requirements)
9. [Deployment Architecture](#deployment-architecture)

---

## Architecture Overview

**Architecture Type**: Modular monolith with service-oriented decomposition

Veritas follows a layered architecture where 13 applications coordinate through
shared libraries and infrastructure (PostgreSQL, Redis, Elasticsearch). Each
application is a standalone Node.js process (or mobile/web client) that can be
deployed and scaled independently, while sharing a common library layer of 57+
modules.

The system is organized into five conceptual layers:

```
+---------------------------------------------------------------------+
|                      CLIENT LAYER                                    |
|  Web PWA (Next.js)  |  Mobile (Expo/RN)  |  USSD  |  B2B SDK       |
+---------------------------------------------------------------------+
|                      API LAYER                                       |
|  REST API (Hono)    |  NLP Service (Hono) |  Analytics Service       |
+---------------------------------------------------------------------+
|                      PROCESSING LAYER                                |
|  Agents  |  AI Workers  |  CMS  |  Video  |  Audio  |  Social       |
+---------------------------------------------------------------------+
|                      INGESTION LAYER                                 |
|  Scheduler  |  Producer  |  Worker  |  Notifications                 |
+---------------------------------------------------------------------+
|                      DATA LAYER                                      |
|  PostgreSQL (pgvector)  |  Redis  |  Elasticsearch  |  MinIO (S3)    |
+---------------------------------------------------------------------+
```

---

## System Context

### External Systems

Veritas integrates with a broad ecosystem of external services:

```
+-------------+  +-------------+  +-------------+  +-----------+  +-----------+
| AI/LLM      |  | Media       |  | Search &    |  | Payment   |  | Social    |
| Providers   |  | Production  |  | Fact-Check  |  | Gateways  |  | Platforms |
|             |  |             |  |             |  |           |  |           |
| Anthropic   |  | HeyGen      |  | Serper      |  | Stripe    |  | YouTube   |
| OpenAI      |  | ElevenLabs  |  | Brave       |  | Paystack  |  | TikTok    |
| Cohere      |  | Ghana NLP   |  | ClaimBuster |  | MTN MoMo  |  | Instagram |
| HuggingFace |  | Tavus CVI   |  | Google FCT  |  | Vodafone  |  | WhatsApp  |
| Shotstack   |  | D-ID        |  |             |  | AirtelTigo|  | Telegram  |
+------+------+  +------+------+  +------+------+  +-----+-----+  +-----+-----+
       |                |                |                |              |
       v                v                v                v              v
+---------------------------------------------------------------------+
|                                                                       |
|                        VERITAS PLATFORM                               |
|                                                                       |
|  +---------------------------------------------------------------+   |
|  |                 VERITAS API (Port 3001)                         |   |
|  |  Framework: Hono  |  Auth: JWT  |  Docs: OpenAPI 3.0.3         |   |
|  +---+-------------------------------------------+---------------+   |
|      |                                           |                    |
|  +---v-----------+  +---------------------------v-+  +-----------+   |
|  | Ingestion     |  | Domain Libraries (57+)       |  | NLP Svc   |   |
|  | (Scheduler,   |  |                              |  | (Port     |   |
|  |  Producer,    |  | Agents, RAG, Knowledge Graph,|  |  3002)    |   |
|  |  Worker)      |  | Fact-checking, Bias, CMS,    |  |           |   |
|  +-------+-------+  | Analytics, Auth, Billing,    |  +-----------+   |
|          |           | B2B SDK, Social, Live Stream |                  |
|          |           +---------------+--------------+                  |
|          |                           |                                 |
|  +-------v---------------------------v------------------------------+ |
|  |                      DATA LAYER                                  | |
|  | PostgreSQL (pgvector, citext) | Redis | Elasticsearch | MinIO    | |
|  +--------------------------------------------------------------+   |
|                                                                       |
+---------------------------------------------------------------------+
       ^                ^                ^                ^
       |                |                |                |
+------+-----+  +------+-----+  +------+------+  +------+------+
| Web PWA    |  | Mobile App |  | B2B API     |  | RSS/USSD    |
| (Next.js)  |  | (Expo/RN)  |  | Partners    |  | Channels    |
| Port 3000  |  |            |  |             |  |             |
+------------+  +------------+  +-------------+  +-------------+
                   CLIENT APPLICATIONS
```

---

## Application Architecture

### Backend Services

#### veritas-api (Port 3001)

The primary REST API gateway for all client applications.

- **Framework**: Hono with `@hono/node-server`
- **API Style**: RESTful with OpenAPI 3.0.3 documentation via
  `@hono/zod-openapi` and Swagger UI via `@hono/swagger-ui`
- **Authentication**: JWT (HMAC-SHA256) with configurable API key auth
- **Rate Limiting**: Redis-backed sliding window rate limiter
- **Validation**: Zod schemas for all request/response payloads
- **Infrastructure**: PostgreSQL (pg pool), Redis (ioredis), Elasticsearch
  (`@elastic/elasticsearch`)
- **Stripe integration** for subscription management
- **80+ endpoints** organized across 29+ route files covering articles, sources,
  claims, subscriptions, billing, B2B, compliance, ads, writing assistant, and
  more

```
apps/veritas/api/src/
  main.ts                           # Entry point, config, server startup
  interfaces/http/
    server.ts                       # Hono app creation and middleware
    routes/v1/
      articles.ts                   # Article CRUD and search
      sources.ts                    # News source management
      claims.ts                     # Fact-check claims
      bias.ts                       # Bias analysis endpoints
      b2b-api.ts                    # B2B partner API
      writingAssistant.ts           # AI writing assistance
      ...                           # 20+ more route files
  infrastructure/
    postgres/createPool.ts          # PostgreSQL connection pool
    redis/createRedis.ts            # Redis client factory
    elasticsearch/createClient.ts   # Elasticsearch client factory
```

#### veritas-nlp (Port 3002)

Dedicated NLP microservice providing text analysis endpoints.

- **Framework**: Hono with `@hono/node-server`
- **Endpoints**: 20+ NLP analysis endpoints
- **Services**: Sentiment analysis, topic classification, keyword extraction,
  extractive/abstractive summarization, claim extraction, language detection,
  code-switching detection, Ghanaian English normalization, embeddings,
  similarity comparison, evidence search, Ghana NLP translation/TTS/NER

```
Available Endpoints:
  POST /sentiment               Sentiment analysis
  POST /topics/classify         Topic classification
  POST /keywords/extract        Keyword extraction
  POST /summarize/extractive    Extractive summarization
  POST /summarize/abstractive   Abstractive summarization
  POST /claims/extract          Claim extraction
  POST /language/detect         Language detection
  POST /language/code-switch    Code-switching detection
  POST /language/normalize      Ghanaian English normalization
  POST /embeddings/embed        Text embeddings
  POST /similarity/compare      Text similarity
  POST /evidence/search         Evidence retrieval
  POST /ghana/translate         Ghana NLP translation
  POST /ghana/tts               Text-to-speech
  POST /ghana/ner               Named entity recognition
  GET  /health                  Health check
  GET  /ready                   Readiness check
```

#### veritas-ingestion

Content ingestion service with three operational modes:

| Mode      | Command                  | Description                                    |
| --------- | ------------------------ | ---------------------------------------------- |
| Scheduler | `node main.js scheduler` | Fetches RSS/sitemap/social feeds on a schedule |
| Producer  | `node main.js producer`  | Enqueues unprocessed items into BullMQ         |
| Worker    | `node main.js worker`    | Processes items from queue (scrape, normalize) |
| Seed      | `node main.js seed`      | Seeds database with 300+ Ghana news sources    |

The ingestion pipeline flows: RSS/Sitemap/Social Collection -> Queueing ->
Scraping -> Content Normalization -> Language Detection -> Semantic
Deduplication -> Source Attribution -> Database Storage.

#### veritas-agents (Port 3006)

Multi-agent orchestration service running 7 specialized AI agents.

- **Architecture**: Event-driven with message bus, state manager, health
  monitor, and metrics collector
- **Orchestration**: Load-balanced task distribution with auto-scaling
- **Communication**: Redis-backed message bus with in-memory fallback
- **State**: Redis-backed state persistence with compression
- **Health**: Automatic self-healing with configurable failure thresholds

```
Components:
  Orchestrator    - Task distribution, agent registry, scaling
  Message Bus     - Agent-to-agent messaging (Redis or in-memory)
  State Manager   - Agent state persistence with TTL
  Health Monitor  - Self-healing with failure threshold detection
  Metrics         - Performance metrics collection
```

#### veritas-ai-workers

BullMQ-based AI content processing workers.

Available worker types:

| Category           | Workers                                                |
| ------------------ | ------------------------------------------------------ |
| Content Generation | weather-report, market-summary, fuel-price, trend      |
| Content Processing | article-summarization, headline-variants, tagging      |
| Analysis           | story-clustering, source-accuracy, blindspot-detection |
| Editorial          | fact-check, article-priority                           |

#### veritas-cms (Port 3004)

Editorial content management system.

- **Services**: Article CRUD, editorial queue, AI review (Managing Editor QC +
  Editor-in-Chief standards), publication scheduling, revision history
- **Scheduling**: Ghana timezone (Africa/Accra), quiet hours (22:00-06:00), peak
  traffic window optimization, max 6 articles per 30-minute window
- **AI Reviews**: Anthropic Claude-powered quality control with approve/reject/
  request-changes decisions

#### veritas-video (Port 3004)

Video production service with HeyGen AI avatar integration.

- **Commands**: serve (HTTP), worker (BullMQ), producer (queue), sync-avatars
- **Pipeline**: Article -> Script Generation (Claude) -> Avatar Selection
  (HeyGen) -> Video Rendering -> Captioning -> Platform Optimization ->
  Publishing
- **Platforms**: YouTube, YouTube Shorts, TikTok, Instagram Reels

#### veritas-audio

Audio production service with TTS and podcast capabilities.

- **Providers**: ElevenLabs (English), Ghana NLP/Khaya (local languages)
- **Features**: Article-to-audio conversion, voice profiles, persona management,
  pronunciation dictionaries, podcast series (Daily Digest, Weekly Deep Dive,
  Sports Recap, Money Matters, Culture, Twi Daily), podcast distribution (RSS
  feeds, OPML, Podcast 2.0 JSON)
- **Pipeline**: Article -> Text Chunking -> Voice Assignment -> TTS Synthesis ->
  Audio Storage (S3/MinIO) -> Distribution

#### veritas-social (Port 3005)

Multi-platform social media automation.

- **Commands**: serve (HTTP), worker (BullMQ), scheduler
- **Platforms**: Instagram, Facebook, WhatsApp, Twitter/X, YouTube, TikTok,
  Telegram, LinkedIn
- **Features**: Content calendar, cross-post scheduling, breaking news priority,
  platform-specific content adaptation

#### veritas-analytics (Port 3004)

Comprehensive analytics service.

- **Domains**: Content metrics, user engagement, revenue/subscription, social
  performance, real-time sessions, viral detection, anomaly detection
- **Features**: Conversion funnels, cohort analysis, user segmentation, revenue
  projections, churn analysis, best posting time analysis

#### veritas-notifications

Multi-channel notification delivery.

- **Email**: SMTP, SendGrid, SES, Postmark, Resend providers
- **Push**: Firebase Cloud Messaging (FCM)
- **Features**: Notification fatigue prevention, batch sending, template-based
  content

### Client Applications

#### veritas-web (Port 3000)

Next.js progressive web application.

- **Framework**: Next.js 16.x with React 19, App Router
- **Internationalization**: next-intl with locale-based routing (`/[locale]/`)
- **Styling**: Tailwind CSS
- **Features**: Reading list, offline page, PWA support, i18n

#### veritas-mobile

Expo/React Native mobile application.

- **Framework**: Expo SDK 51, React Native 0.74
- **State**: Zustand with Immer middleware
- **i18n**: i18next with react-i18next
- **Features**: Audio playback (react-native-track-player), video
  (react-native-video), offline storage, push notifications, biometric auth,
  secure storage

---

## Library Architecture

### Dependency Graph

The library ecosystem is organized in layers. Lower layers have no upward
dependencies; higher layers depend on lower ones.

```
+--------------------------------------------------------------------+
|                    APPLICATION LIBRARIES                             |
|  live-stream, social-automation, audio-production, video-production |
|  automated-content, emergency, newsletter, seo                     |
+--------------------------------------------------------------------+
         |           |            |              |
         v           v            v              v
+--------------------------------------------------------------------+
|                    DOMAIN LIBRARIES                                  |
|  agents-*  |  cms  |  rag  |  knowledge-graph  |  recommendations  |
|  headline-service  |  article-generation  |  content-classification |
|  fact-checking  |  bias-detection  |  claims  |  story-clustering   |
+--------------------------------------------------------------------+
         |           |            |              |
         v           v            v              v
+--------------------------------------------------------------------+
|                    SERVICE LIBRARIES                                 |
|  analytics  |  payments  |  billing  |  notifications               |
|  b2b-sdk  |  b2b-sdk-python  |  auth  |  search  |  cache          |
|  storage  |  events  |  community  |  comments  |  ussd            |
+--------------------------------------------------------------------+
         |           |            |              |
         v           v            v              v
+--------------------------------------------------------------------+
|                    FOUNDATION LIBRARIES                              |
|  core  |  models  |  database  |  llm  |  nlp-core  |  ghana-nlp   |
|  ingestion-core  |  agents-core  |  content-auth                    |
+--------------------------------------------------------------------+
```

### Key Library Relationships

```
@veritas/core
  ^-- @veritas/models (validates core types with Zod)
  ^-- @veritas/database (Prisma client, uses core types)
       ^-- @veritas/auth (adapter pattern, API keys, OAuth)
       ^-- @veritas/cache (Redis caching strategies)
       ^-- @veritas/search (Elasticsearch integration)

@veritas/llm
  ^-- @veritas/agents-core (base agent + LLM client)
       ^-- @veritas/agents-orchestrator
       ^-- @veritas/agents-editorial
       ^-- @veritas/agents-journalism
       ^-- @veritas/agents-fact-checking
       ^-- @veritas/agents-social-media
       ^-- @veritas/agents-devops
       ^-- @veritas/agents-product
       ^-- @veritas/agents-qa

@veritas/nlp-core
  ^-- @veritas/ghana-nlp (Khaya API client)
  ^-- @veritas/bias-detection
  ^-- @veritas/fact-checking
  ^-- @veritas/claims
  ^-- @veritas/content-classification
  ^-- @veritas/story-clustering

@veritas/ingestion-core
  ^-- veritas-ingestion app (scheduler, producer, worker)

@veritas/payments + @veritas/billing
  ^-- veritas-api (subscription and payment routes)
```

---

## Data Flow

### News Ingestion Pipeline

```
                    RSS Feeds (300+)
                         |
                    Sitemap URLs
                         |
                    Social Media (X/Twitter)
                         |
                         v
+-------------------------------------------+
|        SCHEDULER (veritas-ingestion)       |
|  - Fetches configured feeds on schedule   |
|  - Collects raw items from all sources    |
|  - Writes raw items to PostgreSQL         |
+-------------------------------------------+
                         |
                         v
+-------------------------------------------+
|         PRODUCER (veritas-ingestion)       |
|  - Queries for unprocessed items          |
|  - Enqueues them into BullMQ (Redis)      |
+-------------------------------------------+
                         |
                    BullMQ Queue
                         |
                         v
+-------------------------------------------+
|          WORKER (veritas-ingestion)        |
|  - Scrapes full content if missing        |
|  - Normalizes content structure           |
|  - Detects language                       |
|  - Deduplicates via pgvector embeddings   |
|  - Attributes source                      |
|  - Stores processed article in DB         |
+-------------------------------------------+
                         |
                         v
               PostgreSQL + Elasticsearch
```

### AI Processing Pipeline

```
          New Articles (from ingestion)
                    |
                    v
+-------------------------------------------+
|        AI WORKERS (veritas-ai-workers)     |
|                                           |
|  article-summarization  --+               |
|  headline-variants      --+-- Processing  |
|  article-tagging        --+   Queue       |
|  article-priority       --+   (BullMQ)    |
|  story-clustering       --+               |
|  source-accuracy        --+               |
|  fact-check             --+               |
+-------------------------------------------+
                    |
                    v
+-------------------------------------------+
|         AI AGENTS (veritas-agents)         |
|                                           |
|  Editor-in-Chief ----> Approve/Reject     |
|  Managing Editor ----> Edit/Review        |
|  Fact-Checker    ----> Verify Claims      |
|  Journalists     ----> Generate Content   |
|  Content Strat.  ----> Plan Topics        |
|  Social Media    ----> Schedule Posts     |
+-------------------------------------------+
                    |
                    v
+-------------------------------------------+
|              CMS (veritas-cms)             |
|                                           |
|  Draft -> AI Review -> Schedule/Publish   |
|  Revision tracking, quiet hours, peaks    |
+-------------------------------------------+
```

### Multimedia Production Pipeline

```
         Published Articles
              |
    +---------+---------+
    |         |         |
    v         v         v
+-------+ +-------+ +--------+
| Video | | Audio | | Social |
| Svc   | | Svc   | | Svc    |
+-------+ +-------+ +--------+
    |         |         |
    v         v         v
+-------+ +-------+ +--------+
| HeyGen| |Eleven | | Meta   |
| Avatar| | Labs  | | Graph  |
| Render| | TTS   | | API    |
+-------+ +-------+ +--------+
    |         |         |
    v         v         v
+-------+ +-------+ +--------+
|YouTube| |Podcast| |Facebook|
|TikTok | |RSS    | |Insta   |
|Shorts | |Apple  | |WhatsApp|
|Reels  | |Spotify| |Twitter |
+-------+ +-------+ +--------+
```

### Client Data Flow

```
+-------------------------------------------+
|          CLIENT APPLICATIONS               |
|                                           |
|  Web (Next.js) ---+                       |
|  Mobile (Expo) ---+--> veritas-api:3001   |
|  B2B SDK       ---+    (REST + JWT)       |
|  USSD          ---+                       |
+-------------------------------------------+
                    |
         +----------+----------+
         |          |          |
         v          v          v
    PostgreSQL    Redis    Elasticsearch
    (articles,   (cache,   (full-text
     users,      sessions,  article
     sources,    queues)    search)
     claims)
```

---

## Key Design Decisions

### 1. Modular Monolith over Microservices

**Decision**: Veritas uses a modular monolith architecture where all services
share a common library layer, rather than fully independent microservices.

**Rationale**: For a news platform where latency and data consistency matter,
shared libraries avoid the overhead of inter-service serialization/
deserialization. Each application can still be deployed independently, but they
share types and business logic through the library layer.

### 2. Hono over Fastify/Express

**Decision**: The API and NLP services use Hono as the HTTP framework.

**Rationale**: Hono provides excellent TypeScript support, built-in OpenAPI
integration via `@hono/zod-openapi`, minimal overhead, and runs on any standard
JavaScript runtime. It also enables consistent patterns between the API and NLP
services.

### 3. BullMQ for Job Orchestration

**Decision**: All background processing uses BullMQ queues backed by Redis.

**Rationale**: BullMQ provides reliable job processing with retries, priorities,
delayed jobs, repeatable schedules, and concurrency control. This is essential
for the ingestion pipeline, AI workers, video/audio production, and social media
scheduling where job reliability and ordering matter.

### 4. PostgreSQL with pgvector for Everything

**Decision**: PostgreSQL serves as both the relational database and the vector
store (via pgvector extension).

**Rationale**: Using a single database engine simplifies operations. pgvector
provides sufficient embedding search performance for the scale of Ghanaian news
(hundreds of thousands of articles), avoiding the operational complexity of a
separate vector database. Elasticsearch is used only for full-text search, not
vector similarity.

### 5. Prisma for Database Access

**Decision**: The database library uses Prisma ORM for schema management and
database access, while some apps use raw `pg` for performance-critical queries.

**Rationale**: Prisma provides type-safe database access, automatic migrations,
and a schema-first approach that aligns well with the domain model. Raw `pg` is
used in the API where fine-grained SQL control and connection pooling are
needed.

### 6. Multi-Agent Architecture

**Decision**: The AI editorial pipeline uses 7 specialized agents rather than a
single monolithic AI pipeline.

**Rationale**: Specialized agents mirror a real newsroom structure. Each agent
has focused capabilities and priority levels, enabling nuanced editorial
decisions. The editor-in-chief (priority 10) makes final publication decisions
while journalists (priority 7) focus on content generation.

### 7. Event-Driven Agent Communication

**Decision**: Agents communicate through an event-driven message bus with
Redis-backed persistence.

**Rationale**: Event-driven communication enables loose coupling between agents,
supports async processing, and allows the orchestrator to manage workload
distribution. Redis backing ensures message persistence across restarts with
in-memory fallback for development.

### 8. Ghana-Centric Language Architecture

**Decision**: The platform is built with Ghana's multilingual reality at its
core, not as an afterthought.

**Rationale**: Ghana has 6+ major languages with pervasive code-switching. The
NLP service includes dedicated endpoints for code-switching detection, Ghanaian
English normalization, and integration with the Ghana NLP Khaya API for local
language TTS, NER, and translation.

### 9. USSD Channel for Feature Phone Access

**Decision**: Veritas includes a USSD channel library for telco-based news
delivery.

**Rationale**: A significant portion of Ghanaians access information through
feature phones. USSD provides text-based news delivery with voice callback
support through MTN, Vodafone, AirtelTigo, and Glo gateway adapters.

### 10. Dual B2B SDKs (TypeScript + Python)

**Decision**: B2B API consumers are served with both TypeScript and Python SDKs.

**Rationale**: News organizations and data consumers use diverse tech stacks.
The Python SDK supports both async and sync usage patterns, while the TypeScript
SDK integrates naturally with the Node.js ecosystem. Both SDKs provide type
hints, rate limiting, and retry logic.

---

## Integration Points

### External API Integrations

| Service        | Library/App           | Protocol | Purpose                            |
| -------------- | --------------------- | -------- | ---------------------------------- |
| Anthropic      | agents-core, llm      | REST     | LLM orchestration, content gen     |
| OpenAI         | agents-core, llm      | REST     | Alternative LLM provider           |
| HeyGen         | veritas-video         | REST     | AI video avatar rendering          |
| ElevenLabs     | veritas-audio         | REST     | English text-to-speech             |
| Ghana NLP      | ghana-nlp             | REST     | Local language TTS, NER, translate |
| Tavus CVI      | live-stream           | REST     | Conversational video intelligence  |
| Elasticsearch  | search                | REST     | Full-text article search           |
| Stripe         | payments              | REST     | Card payments, subscriptions       |
| Paystack       | payments              | REST     | Ghana local payment processing     |
| Meta Graph API | veritas-social        | REST     | Instagram, Facebook, WhatsApp      |
| X/Twitter API  | veritas-social        | REST     | News monitoring, posting           |
| YouTube API    | veritas-social, video | REST     | Video uploads, live streaming      |
| TikTok API     | veritas-social, video | REST     | Short-form video, analytics        |
| Telegram Bot   | veritas-social        | REST     | Channel management                 |
| LinkedIn API   | veritas-social        | REST     | Company page updates               |
| Firebase       | notifications         | REST     | FCM push notifications             |
| Serper         | fact-checking         | REST     | Search for evidence                |
| Brave Search   | fact-checking         | REST     | Alternative evidence search        |
| ClaimBuster    | fact-checking         | REST     | Checkworthiness scoring            |
| Cohere         | rag                   | REST     | Embeddings and reranking           |

### Internal Service Communication

Services communicate through shared infrastructure rather than direct API calls:

| Communication Path              | Mechanism           |
| ------------------------------- | ------------------- |
| API -> Database                 | PostgreSQL (pg)     |
| API -> Search                   | Elasticsearch       |
| API -> Cache                    | Redis               |
| Ingestion -> Processing Queue   | BullMQ (Redis)      |
| AI Workers -> Processing Queue  | BullMQ (Redis)      |
| Agents -> Message Bus           | Redis pub/sub       |
| Agents -> State                 | Redis (KV)          |
| Video/Audio/Social -> Job Queue | BullMQ (Redis)      |
| Notifications -> Delivery       | Email/FCM providers |
| Web/Mobile -> API               | HTTP REST           |

---

## Infrastructure Requirements

### Core Infrastructure

| Service        | Version | Port(s)    | Purpose                           |
| -------------- | ------- | ---------- | --------------------------------- |
| PostgreSQL     | 15+     | 5432       | Primary database (with pgvector)  |
| Redis          | 7+      | 6379       | Caching, queues, sessions, pubsub |
| Elasticsearch  | 8+      | 9200       | Full-text article search          |
| MinIO / AWS S3 | --      | 9000, 9001 | Media asset storage               |

### PostgreSQL Extensions

| Extension | Purpose                                      |
| --------- | -------------------------------------------- |
| pgvector  | Vector embeddings for semantic deduplication |
| citext    | Case-insensitive text for slugs, emails      |

### Database Configuration

Veritas uses its own dedicated database within the shared PostgreSQL instance:

- **Database name**: `veritas`
- **Connection string env var**: `VERITAS_DATABASE_URL`
- **Default**: `postgresql://oshun:oshun_dev@localhost:5432/veritas`
- **Schema location**: `libs/veritas/database/prisma/schema.prisma`
- **Tables**: 50+ tables covering articles, sources, authors, entities, claims,
  media assets, subscriptions, users, translations, and more

### Redis Usage

| Namespace Prefix         | Purpose                 |
| ------------------------ | ----------------------- |
| `veritas:api:rate-limit` | API rate limiting       |
| `veritas:state:`         | Agent state persistence |
| `bull:*`                 | BullMQ job queues       |
| Article/search cache     | Response caching        |
| Session cache            | User session storage    |

### Application Ports

| Service           | Default Port | Env Variable        |
| ----------------- | ------------ | ------------------- |
| veritas-web       | 3000         | --                  |
| veritas-api       | 3001         | `PORT`              |
| veritas-nlp       | 3002         | `NLP_PORT` / `PORT` |
| veritas-cms       | 3004         | `CMS_PORT`          |
| veritas-analytics | 3004         | `ANALYTICS_PORT`    |
| veritas-video     | 3004         | `PORT`              |
| veritas-social    | 3005         | `PORT`              |
| veritas-agents    | 3006         | `AGENTS_PORT`       |

---

## Deployment Architecture

### Development

All services run locally against Docker-managed infrastructure:

```bash
# Start infrastructure
docker compose -f docker/docker-compose.dev.yml up -d
docker compose -f docker/docker-compose.dev.yml --profile search up -d

# Start services individually via Nx
pnpm nx serve veritas-api
pnpm nx serve veritas-nlp
pnpm nx serve veritas-web
```

### Production

Veritas is designed for deployment on Kubernetes or AWS ECS:

```
+--------------------------------------------------------------------+
|                    LOAD BALANCER (ALB/Nginx)                        |
+--------------------------------------------------------------------+
         |              |              |              |
         v              v              v              v
+------------+  +------------+  +------------+  +------------+
| API        |  | NLP        |  | Web        |  | Mobile     |
| (3+ pods)  |  | (2+ pods)  |  | (2+ pods)  |  | (CDN)      |
+------------+  +------------+  +------------+  +------------+
                                                     |
+--------------------------------------------------------------------+
|               WORKER POOL (Autoscaled)                              |
|  Ingestion Workers | AI Workers | Video Workers | Audio Workers     |
|  Social Workers | Notification Workers                              |
+--------------------------------------------------------------------+
                         |
+--------------------------------------------------------------------+
|               DATA TIER (Managed Services)                          |
|  RDS PostgreSQL | ElastiCache Redis | OpenSearch | S3               |
+--------------------------------------------------------------------+
```

### Build Artifacts

All backend services produce ESM bundles via esbuild:

| Service           | Output                             | Format |
| ----------------- | ---------------------------------- | ------ |
| veritas-api       | `dist/apps/veritas/api/main.mjs`   | ESM    |
| veritas-nlp       | `dist/apps/veritas/nlp/main.mjs`   | ESM    |
| veritas-ingestion | `dist/apps/veritas/ingestion/`     | ESM    |
| veritas-video     | `dist/apps/veritas/video/main.mjs` | ESM    |
| veritas-audio     | `dist/apps/veritas/audio/main.mjs` | ESM    |
| veritas-social    | `dist/apps/veritas/social/`        | ESM    |
| veritas-agents    | `dist/apps/veritas/agents/`        | CJS    |
| veritas-web       | `.next/` (Next.js build)           | --     |
| veritas-mobile    | EAS Build (iOS/Android)            | --     |
