# Veritas — Systems Deep Dive

> The `apps/veritas/` area: thirteen Nx applications that together form a
> Ghana-focused, AI-assisted news and media platform — ingestion, NLP, an agent
> newsroom, an editorial CMS, a public REST API, audio/video production, social
> distribution, notifications, analytics, plus a Next.js web reader and an Expo
> mobile app.

## What this area is

"Veritas" is a self-contained product: an automated newsroom for the Ghanaian
media market. Unlike the domain-scoped Oshun libraries, every project here is an
Nx `application` (each `project.json` carries `"type:app"` / `"type:service"`
and a `scope:veritas` or `domain:veritas` tag), and they wire together into a
single content pipeline rather than a shared library surface. The product
identity is concrete throughout the code, not cosmetic — Ghanaian languages
(Twi, Ewe, Ga, Dagbani, Hausa), Ghanaian mobile-money rails (MTN MoMo,
AirtelTigo Money, Vodafone Cash), Ghana's NPP↔NDC political axis, and Ghana
election-coverage law all appear as first-class domain logic.

The thirteen projects split into a few bands. **Acquisition + understanding:**
`veritas-ingestion` pulls and de-duplicates source articles, then `veritas-nlp`
and `veritas-ai-workers` enrich them (sentiment, claims, summaries, bias,
clustering). **Editorial + orchestration:** `veritas-cms` is the human/AI
editorial workflow and `veritas-agents` is a multi-agent orchestration layer
over the newsroom. **Serving:** `veritas-api` is the public Hono REST surface
that the two clients — `veritas-web` (Next.js) and `veritas-mobile` (Expo/React
Native) — consume. **Production + distribution:** `veritas-audio` (TTS/podcast),
`veritas-video` (AI-avatar video), `veritas-social` (cross-platform publishing)
and `veritas-notifications` (push/email/in-app). **Measurement:**
`veritas-analytics`.

These are real, substantial implementations — the smallest service
(`veritas-analytics`) carries 16 TypeScript modules and the largest
(`veritas-api`, 89) is a full hexagonal application. None of the thirteen is an
empty scaffold. Where a capability depends on an external SDK or credential (LLM
providers, ElevenLabs, HeyGen, FCM, payment gateways), the code is built around
an injectable client/provider seam rather than faking the result, so the domain
algorithms (SimHash dedup, RAKE keywords, RFM/funnel analytics, Ghana
election-compliance rules) run for real and the vendor call is the configurable
boundary.

## How it fits the wider system

The natural data flow is
`ingestion → (nlp + ai-workers) → cms → api → web / mobile`, with `audio`,
`video`, `social`, and `notifications` hanging off the published-content edge
and `analytics` observing the whole thing. The two client apps talk to
`veritas-api` over HTTP (the API is a Hono app exposing a versioned `/v1`
surface with OpenAPI/Swagger); `veritas-web` additionally implements a few of
its own Next.js route handlers (recommendations, behaviour tracking, article
search) for client-side personalization. Most backend services are Node
processes that share Postgres and Redis and use BullMQ for job queues. The
boundary with the rest of the Oshun monorepo is deliberately thin — Veritas is a
product app cluster, not a platform library, so the catalog of nodes below is
best read as the architecture of one application rather than a set of reusable
contracts.

## Entity reference

### veritas-agents

The multi-agent orchestration service for the autonomous newsroom
(`apps/veritas/agents`, package `@veritas/agents`). It is a real coordination
runtime, not a thin wrapper: `src/orchestration/orchestrator.ts` registers
agents and routes tasks by role/priority using `DISTRIBUTION_STRATEGIES`,
`src/core/base-agent.ts` is an abstract agent with a lifecycle + task loop,
`src/communication/message-bus.ts` and `src/state/state-manager.ts` provide the
fabric, and `src/monitoring/health-monitor.ts` adds self-healing actions plus a
`src/metrics/metrics-collector.ts` for Prometheus-style counters/histograms.
`src/core/llm-client.ts` is a unified LLM client built on the real
`@anthropic-ai/sdk` and `openai` SDKs with retry and token tracking; the
`main.ts` CLI wires it all behind a Redis-backed HTTP server on port 3006.

### veritas-ai-workers

A pool of BullMQ-orchestrated AI worker processes (`apps/veritas/ai-workers`,
`@veritas/ai-workers`) driven by a CLI (`src/main.ts` with `run`/`list`/
`status`/`schedule` commands over a Postgres `Pool`). Workers are grouped under
`src/workers/`: **content** generation tuned to Ghana (`weather-report`,
`fuel-price`, `market-summary`, `traffic-update`, `ecg-load-shedding`,
`event-calendar`, `gpl-score`, `trend-analysis`); **processing**
(`article-summarization`, `article-tagging`, `entity-extraction`,
`breaking-news`, `claim-linking`, `seo-metadata`, `headline-variants`,
`press-release`, `article-priority`); **analysis** (`political-bias`,
`sentiment-analysis`, `source-accuracy`, `blindspot-detection`,
`story-clustering` with embeddings); and **editorial** (`fact-check`,
`original-content`). A shared `workers/base/` provides the LLM, queue, pool, and
article-utility helpers, with the LLM provider as the injected seam.

### veritas-analytics

The analytics service (`apps/veritas/analytics`, `@veritas/analytics`) with
domain-specific metric math rather than generic counters. `src/content/` scores
engagement and computes trends/time-series; `src/user/` implements RFM
(recency/frequency/monetary), funnel analysis, cohort analysis and user
journeys; `src/revenue/metrics.ts` computes subscription/ad metrics, churn, and
revenue projections over typed transaction/subscription records; `src/social/`
adds viral-score, engagement-rate and platform-benchmark comparisons with
sentiment aggregation; and `src/collectors/realtime.ts` provides a real-time
collector plus viral-content and anomaly detectors. Stores are in-memory
factories (`createRevenueStore`, etc.) and an HTTP API is exposed via
`src/api/server.ts`.

### veritas-api

The public REST API and the largest project in the area (`apps/veritas/api`,
`@veritas/api`, ~89 TS modules) laid out hexagonally: `domain/`, `application/`,
`infrastructure/`, `interfaces/http/`. The server
(`src/interfaces/http/server.ts`) is a Hono app with CORS, timing, secure
headers, rate-limit / API-key-auth / sandbox middleware, and Swagger UI over a
generated OpenAPI spec. `infrastructure/` holds real Postgres pool, Redis,
Elasticsearch clients, JWT access tokens and AES-256-GCM encryption. The
`domain/` and `routes/v1/` surfaces are Ghana-specific: payments (`mtn-momo`,
`airteltigo-money`, `vodafone-cash`, `stripe`), `paywall`, `subscriptions`,
ads/`ad-networks`, `b2b-api`, `compliance/` (Ghana election-coverage law in
`election.ts`, `nmc`, `dpa` data-protection), and `sources/` transparency
(`bias`, `ownership`, `regional-emphasis`) plus a `political-bias-scorer` tuned
to the NPP↔NDC axis. A `load-test` target runs k6 scenarios.

### veritas-audio

The audio-production service (`apps/veritas/audio`, `@veritas/audio`) for
turning articles into speech and podcasts. `src/providers/` carries two TTS
backends — `elevenlabs.ts` and `ghana-nlp.ts` (synthesis for Twi/Ewe/Ga/Dagbani
against `translation-api.ghananlp.org`, with retry/backoff, a circuit breaker,
and an in-memory cache). `src/services/` implements the article-to-audio
pipeline, Ghana-voice and persona management, pronunciation, a voice assistant,
voice profiles, podcast series + distribution, radio syndication, and S3/MinIO
storage. Work is driven through a BullMQ queue (`src/queue/producer.ts` /
`worker.ts`) behind an HTTP server.

### veritas-cms

The editorial CMS service (`apps/veritas/cms`, `@veritas/cms`). It implements
article CRUD with revision tracking (content-hash snapshots in
`src/articles/article-service.ts`), a two-tier AI editorial review (QC +
Standards, see `src/reviews/`), smart publication scheduling with quiet-hours
and capacity limits (`src/scheduling/scheduler-service.ts`), an editorial queue
with cursor pagination, and a human-review workflow. Persistence is via a
pluggable `StorageAdapter`; the shipped implementation
(`src/storage/memory-storage.ts`) is an explicitly in-memory adapter for
single-process deployments, with the interface left open for a durable backend.
A Hono `server.ts` exposes it.

### veritas-ingestion

The news-acquisition pipeline (`apps/veritas/ingestion`, `@veritas/ingestion`),
run as a multi-mode CLI (`scheduler` / `producer` / `worker` / `seed`).
`src/collectors/` pulls RSS, sitemaps, social, and X/Twitter; `src/scraper/`
fetches article bodies with robots.txt awareness, throttling and extraction;
`src/pipeline/` normalizes, detects language, handles media/timestamps and runs
near-duplicate detection via `simhash.ts` (a real 64-bit SimHash with LSH
banding). Jobs flow through a Redis/BullMQ queue and Postgres tables
(`db/feeds`, `db/sources`, `db/normalized`, `db/social-monitors`). The seed data
is concrete: `src/seeds/tier1-ghana-sources.ts` encodes Ghana's major media
houses (Multimedia/Joy, Citi, Graphic, Media General/TV3, Despite, GBC,
GhanaWeb, GNA…) with a documented bias-scoring methodology, plus government
sources.

### veritas-mobile

The Expo / React Native mobile app "Veritas News" (`apps/veritas/mobile`, Nx
project `veritas-mobile`) — the most file-heavy project here (~173 tracked
files). It uses Expo Router with a tabbed shell (`app/(tabs)/`: home, listen,
watch, search, bookmarks, categories, settings, you), full auth flows
(login/signup/phone-OTP/email-verify/forgot/reset), and article/category/source
screens. It includes genuine native integrations: iOS widgets, CarPlay, Live
Activities and Siri Shortcuts in Swift (`ios-widgets/`), and Android Auto +
home-screen widgets in Kotlin (`android-auto/`, `android-widgets/`), surfaced
through Expo config plugins. `src/` adds Ghana-specific components (bias
indicators, mobile-money payment cards, compliance/paywall UI), a six-locale
i18n bundle (en, twi, ewe, ga, dag, ha), and services for offline, biometrics,
breaking alerts, and audio playback. Build/submit use EAS; e2e uses Detox.

### veritas-nlp

The NLP microservice (`apps/veritas/nlp`, `@veritas/nlp`), a Hono server
(`src/server.ts`) exposing text-processing endpoints backed by `src/services/`:
sentiment (HuggingFace with a `ghanaCalibration` step), keyword extraction (a
real RAKE implementation in `keywords/rake.ts`), topic classification,
extractive + abstractive summarization, claim extraction (heuristic regex
patterns plus an LLM path), embeddings (OpenAI and Cohere backends), similarity,
evidence retrieval (Brave + Serper search), language detection / code-switch
detection / Ghanaian-English normalization, and a Ghana-NLP client for
translation, TTS and NER. Each external model/provider is an injectable backend
behind a service module.

### veritas-notifications

The multi-channel notification service (`apps/veritas/notifications`,
`@veritas/notifications`, tagged `type:service`). `src/channels/` implements FCM
push, email (including digest items), and in-app delivery with a realtime hub.
`src/scheduling/timing.ts` adds smart timing — activity-pattern inference,
quiet-hours enforcement, per-kind digest schedules and rate caps — feeding a
queue (`scheduling/queue.ts`) and a scheduler (`scheduling/scheduler.ts`).
`src/preferences/service.ts` manages per-user channel/kind preferences, and an
HTTP API is exposed via `src/api/server.ts`. Identifiers are branded types
throughout (`UserId`, `NotificationId`, `TokenId`, `SubscriptionId`).

### veritas-social

The social-media automation service (`apps/veritas/social`, `@veritas/social`),
run as serve/scheduler/worker modes. `src/platforms/` holds adapters extending a
common `base.ts` for Twitter, Meta (Facebook/Instagram), LinkedIn, TikTok,
YouTube and Telegram, each gated by a `has<Platform>Config()` capability check.
`src/services/` layers on higher-level automation: channel-ecosystem and
growth-partnership automation, Instagram reels/stories, TikTok automation +
analytics, Telegram and WhatsApp channel automation, YouTube channel/shorts, a
unified scheduler and posting analytics. `src/calendar/` schedules around Ghana
public holidays, and a memory store backs the scheduler/publisher/worker
pipeline.

### veritas-video

The AI-avatar video-production service (`apps/veritas/video`, `@veritas/video`,
~85 TS modules). `src/providers/` integrates a broad provider set behind a
`unified.ts` provider with fallback strategy: HeyGen, Tavus (with
`GHANA_ANCHOR_PERSONAS`), D-ID, Runway, Shotstack, Pexels stock footage,
OpusClip, and transcription via AssemblyAI / Deepgram / Whisper (each able to
emit SRT/VTT/JSON). `src/services/` covers article-video and daily-bulletin/
shorts scripting, avatar profiles, a b-roll subsystem (concept extraction,
library, prompt generation, cache), captioning, live streaming, Instagram reels,
an accessibility suite (visual/motor/auditory-cognitive/voice-navigation), an
advertising layer (ad-service + YouTube monetization), notification strategy
(fatigue prevention, personalization), and payments. A BullMQ queue drives the
render jobs.

### veritas-web

The Next.js reader web app (`apps/veritas/web`, `@veritas/web`) built on the App
Router with locale routing (`src/app/[locale]/`) via `next-intl`, supporting
English, Twi, Ewe and Ga (`src/i18n/config.ts`). Alongside the rendered pages
(home, reading-list, offline) it ships its own Next.js API route handlers under
`src/app/api/v1/` for article search, behaviour events/profile, and
recommendations (including events and experiments). `src/lib/` carries the
client intelligence: a behaviour-tracking subsystem (reading-tracker,
profile-calculator, server-store) and a recommendations engine
(`lib/recommendations/`) doing collaborative + content-based filtering with
diversity injection and A/B testing. It is built mobile-Africa-first — a PWA
(`public/manifest.json`, `public/sw.js`), a DataSaver mode, skeleton loaders and
optimized images.
