# Veritas — Systems Deep Dive

> The `libs/veritas/` area: ~64 Nx libraries that build **Veritas, an AI-native
> news agency for Ghana and pan-Africa** — from RSS ingestion and
> Ghanaian-language NLP through claim extraction, fact-checking, autonomous
> article/audio/video generation, a newsroom of AI agents, and the audience,
> distribution, and B2B monetization surfaces around them.

## What this area is

Veritas is a full news-media company expressed as code. The `libs/veritas/`
directory is not one package but a domain of roughly 64 separate Nx libraries,
each owning one capability of an autonomous newsroom: pulling in source
material, understanding it (including Ghanaian languages), verifying it,
generating publishable content across text/audio/video, distributing it through
web, USSD, TV, and watch surfaces, and selling structured access to it via a B2B
API. Almost every package is substantial implementation (the smallest is ~2,000
LOC); there are no empty scaffolds in this area.

The packages stack into clear tiers. At the **foundation** sit `veritas-core`
(branded primitives, `Result` types), `veritas-models` (Zod schemas +
validators), `veritas-database` (a generated Prisma client in
`src/generated/client` plus repositories), `veritas-events` (built on
`@oshun/event-bus`), `veritas-cache`, `veritas-storage`, `veritas-search`
(Elasticsearch), `veritas-auth`, and `veritas-api-client`. On top of that runs
the **editorial pipeline**: ingestion → NLP → claims/fact-checking → generation
→ production. A parallel **agent newsroom** (`veritas-agents-*`) wraps those
capabilities in role-based AI agents (Editor-in-Chief, correspondents,
fact-checkers) coordinated by an orchestrator. Surrounding all of it are
**audience** (recommendations, comments, community, newsletter, notifications),
**distribution** (USSD, platforms, regional, emergency), and **commercial**
(payments, billing, B2B SDKs, signup) layers.

The packages depend downward through the foundation tier and integrate with the
wider Oshun monorepo (`@oshun/database`, `@oshun/event-bus`, `@oshun/auth`)
rather than re-implementing infrastructure. NLP-heavy packages share
LLM/provider plumbing from `veritas-nlp-core` and `veritas-llm`; the agent
packages all extend `BaseAgent` from `veritas-agents-core`.

## How it fits the wider system

Consumers are the Veritas apps and BFF (not documented here) plus the agent
orchestrator, which composes these libraries into running workflows: ingestion
feeds claim extraction, claims feed fact-checking, verified material feeds
article and audio/video generation, and the output flows to distribution and
audience packages. The B2B tier (`veritas-b2b-sdk`, `veritas-b2b-sdk-python`,
`@veritas/billing`, `@veritas/signup`, `@veritas/developer-support`) exposes
that same content to external customers over a metered API. Boundaries:
foundation packages hold no business logic, agent packages hold orchestration
not transport, and Ghana-specific integrations (mobile money, Khaya NLP, USSD
telco gateways) are isolated in their own packages so the rest of the platform
stays provider-agnostic. The entity blocks below are grouped by tier for reading
order; walk the "used by" edges on any node to see its real consumers.

## Entity reference

### veritas-core

Foundation primitives for the platform (`libs/veritas/core/src/index.ts`):
branded types (`Uuid`, `UrlString`, `CountryCode`, `Slug`) with
constructors/validators, `Result`/`AsyncResult`, pagination and metadata
interfaces, and error-response helpers. Everything else builds on these types.

### veritas-models

Zod schemas and validation utilities for all Veritas domain models
(`libs/veritas/models/src/index.ts`), exporting the schemas plus `validate`,
`createValidator`, and `createTypeGuard` so API edges validate at run time, not
just compile time.

### veritas-database

The database layer (`libs/veritas/database`), by far the largest package (~144K
LOC across 96 files, mostly the generated Prisma client under
`src/generated/client`). Exports `prisma`/`createPrismaClient`, transaction
helpers (`withTransaction`, `withSerializableTransaction`), health checks, and a
`repositories/` set; integrates with `@oshun/database` patterns.

### veritas-events

Event-driven backbone (`libs/veritas/events/src/index.ts`) built on
`@oshun/event-bus`: `createEventBus`, `createVeritasPublisher`,
`createVeritasSubscriber`, and the `VERITAS_EVENT_TYPES` taxonomy for
cross-domain publish/subscribe with batching and pattern matching.

### veritas-cache

Caching layer (`libs/veritas/cache/src/index.ts`): `VeritasCacheService`,
`GlobalCacheService`, a `VeritasRealtimeService`, and purpose-built caches such
as `createArticleCache`, plus env-driven cache/pub-sub client factories.

### veritas-storage

Content storage utilities (`libs/veritas/storage/src/index.ts`) for articles,
media (video/audio/image variants, thumbnails), and archives —
`ArticleStorageService`, `MediaStorageService`, `ArchiveStorageService` under
the unified `VeritasStorageService`, with rich metadata/format types.

### veritas-search

Elasticsearch client wrapper (`libs/veritas/search/src/index.ts`): index/alias
management, bulk and query builders, search ranking, and a
`SearchAnalyticsService` (with an in-memory analytics storage option) for the
platform's search surface.

### veritas-auth

Authentication integration over `@oshun/auth` (`libs/veritas/auth/src`):
`AuthService`, `ApiKeyService`, `KeyService`, `OAuthService`, `PhoneOtpService`,
and `GuestSessionService` — covering both human (phone OTP/OAuth) and API-key
auth.

### veritas-api-client

A thin generated API client (`libs/veritas/api-client/src/index.ts`) that
re-exports `createClient` from `client.js` plus the OpenAPI
`components`/`operations`/`paths`/ `webhooks` types from a generated
`openapi.ts` — the typed HTTP surface for the platform API.

### veritas-ingestion-core

Core ingestion primitives (`libs/veritas/ingestion-core/src`): RSS/Atom feed
parsing (`feed/parser.ts`), HTTP fetch, content normalization, an HTML scraper
with a `robots.ts` robots-txt guard, and SimHash near-duplicate detection
(`dedup/simhash.ts`).

### veritas-nlp-core

Core NLP provider plumbing (`libs/veritas/nlp-core/src`): factory functions for
multiple model/search providers — `createAnthropicProvider`,
`createCohereProvider`, `createBraveProvider` (and env-from variants) — giving
the rest of the platform a unified NLP/embedding/search provider abstraction.

### veritas-ghana-nlp

Ghana-specific NLP integration (`libs/veritas/ghana-nlp/src`) wrapping the Khaya
API (`createKhayaClient`) for translation, TTS, STT, and NER across Ghanaian
languages — the localized counterpart to `veritas-nlp-core`.

### veritas-llm

Journalism-optimized LLM client (`libs/veritas/llm/src`):
`createJournalismLLMClient` with a `ContentSafetyService`, a
`createCostOptimizer`, and env-driven config — the newsroom's guarded,
cost-aware gateway to LLMs.

### veritas-rag

Retrieval-augmented generation (`libs/veritas/rag/src/index.ts`): an
`ArticleArchiveService` for chunking/indexing articles, a
`SemanticSearchService`, and a `ContextRetrievalService` (token-budgeted context
for AI), behind an `IEmbeddingService` seam and a top-level `RagService`.

### veritas-knowledge-graph

Knowledge-graph integration (`libs/veritas/knowledge-graph/src`): entity
extraction (`createEntityExtractor`), relationship mapping, temporal tracking,
and typed entity profile services — `PoliticianProfileService`,
`OrganizationProfileService`, `LocationProfileService`, `EventProfileService` —
under `KnowledgeGraphService`.

### veritas-story-clustering

Story-clustering algorithms (`libs/veritas/story-clustering/src`, ~10K LOC / 29
files) for grouping related coverage and building timelines: centroid
management, merge/branch event emission, a processing queue, and per-cluster
language metadata.

### veritas-content-classification

Content classification (`libs/veritas/content-classification/src`): topic
detection (`createTopicClassifier`), sensitivity analysis
(`createSensitivityClassifier`), and priority scoring (`createPriorityScorer`),
composed by a `createUnifiedClassifier`.

### veritas-claims

AI-powered claim extraction (`libs/veritas/claims/src`): `createClaimExtractor`
and an LLM-backed `createLLMExtractor`, with text-position mapping
(`createTextPositionMap`, `createBoundary`) so extracted claims point back to
exact source spans — the input stage for fact-checking.

### veritas-fact-checking

The fact-checking engine (`libs/veritas/fact-checking/src`, 14 files): claim
extraction, evidence retrieval and ranking (`createAIEvidenceRanker`),
multi-source credibility analysis (`createAICredibilityAnalyzer`,
`createCustomCredibilityScorer`), verdict generation
(`createAIVerdictGenerator`), a `ClaimBuster` client, and claim tracking.

### veritas-bias-detection

Bias detection (`libs/veritas/bias-detection/src`): political-bias scoring
(`createPoliticalBiasScorer`, `createBiasScore`) plus coverage-balance and
blindspot analysis per the package description — the editorial-neutrality check
on generated and ingested content.

### veritas-content-auth

Content authentication and provenance (`libs/veritas/content-auth/src`):
content-hashing, a blockchain timestamping/certificate flow
(`BlockchainService`, `createBlockchainTimestampManager`,
`createCertificateManager`), plus reverse-image-search and a `DetectionService`
for verifying media authenticity.

### veritas-research-assistant

Research assistant for the newsroom (`libs/veritas/research-assistant/src`):
`createHistoricalContextBuilder`, `createRelatedStoriesDiscovery`, and
`createBriefingGenerator` over a `createRagPipeline`, surfaced through
`createResearchAssistant` for background briefings on a developing story.

### veritas-article-generation

Autonomous article generation (`libs/veritas/article-generation/src`): a
pipeline of `createResearchGatherer` → `createOutlineBuilder` →
`createContentGenerator` → `createArticleRefiner`, orchestrated by
`createArticleGenerator` for multi-source synthesis with citations and
fact-verification.

### veritas-automated-content

Template-driven content generators (`libs/veritas/automated-content/src`, 20
files) for recurring data-driven stories: weather, sports
(`createSportsGenerator` with an HTTP provider), markets, traffic, fuel prices,
and load-shedding schedules — Ghana-relevant automated beats.

### veritas-headline-service

Headline generation and optimization (`libs/veritas/headline-service/src`):
`createHeadlineGenerator` plus an `createEngagementScorer`, `createSEOScorer`,
`createClickbaitDetector`, and an A/B-test manager, all under `HeadlineService`.

### veritas-audio-production

Audio production pipeline for broadcasts (`libs/veritas/audio-production/src`):
a `HybridTTSService`, an ElevenLabs client/config, and voice-profile + rendering
config factories — TTS for news read-outs.

### veritas-video-production

Video production library (`libs/veritas/video-production/src`, ~20K LOC / 38
files): script generation, avatar management (`VoiceAvatarSyncService`), an
`STTService`, AR overlay/session builders, a `VideoAgent`, and rendering/HLS
transcoding for video news.

### @veritas/live-stream

24/7 YouTube live-stream infrastructure (`libs/veritas/live-stream/src`, ~16K
LOC / 22 files): AI chat moderation (`AIModerationService`), an
`AIResponseGenerator`, an `EngagementAnalyticsService`, and breaking-news
banner/archive components for a continuous live channel.

### veritas-seo

SEO and discovery optimization (`libs/veritas/seo/src`): sitemap and
structured-data generators, a Web Stories generator, and Core Web Vitals
monitoring backed by a `createLighthouseWebVitalsRunner`.

### veritas-agents-core

The AI-agent framework (`libs/veritas/agents-core/src`, ~7K LOC): the
`BaseAgent` base class plus messaging, ID factories
(`createAgentId`/`createTaskId`/`createMessageId`), a
`createContextWindowManager`, and state/health monitoring — the substrate every
other `veritas-agents-*` package extends.

### veritas-agents-orchestrator

Multi-agent orchestration (`libs/veritas/agents-orchestrator/src`): an agent
registry (`createAgentRegistry`), task routing (`createOrchestrator`), and
conflict resolution (`createConflictResolver`) coordinating the agent newsroom.

### veritas-agents-editorial

Editorial agents (`libs/veritas/agents-editorial/src`, ~7K LOC):
`EditorInChiefAgent`, `ManagingEditorAgent`, and `ContentStrategistAgent` (with
factory functions) — the top-of-newsroom decision agents.

### veritas-agents-journalism

Journalism agents (`libs/veritas/agents-journalism/src`, ~11K LOC / 15 files): a
set of correspondent agents — `PoliticalCorrespondentAgent`,
`BusinessCorrespondentAgent`, `InvestigativeCorrespondentAgent`,
`RegionalCorrespondentAgent`, `SportsCorrespondentAgent`,
`BreakingNewsCorrespondentAgent` — covering distinct beats.

### veritas-agents-fact-checking

The fact-checking agent (`libs/veritas/agents-fact-checking/src`):
`FactCheckerAgent` (`createFactCheckerAgent`) wrapping the
`veritas-fact-checking` engine with IFCN methodology compliance per its
description.

### veritas-agents-social-media

Social-media management agents (`libs/veritas/agents-social-media/src`):
`SocialMediaManagerAgent`/`SocialMediaAgent` that plan and supervise
cross-platform posting (paired with `veritas-social-automation` for transport).

### veritas-agents-devops

DevOps/infrastructure agent (`libs/veritas/agents-devops/src`): a single
`DevOpsAgent` (`createDevOpsAgent`) for infrastructure-management tasks within
the agent framework.

### veritas-agents-product

Product-management agent (`libs/veritas/agents-product/src`): a
`ProductManagerAgent` (`createProductManagerAgent`) for product and
user-research tasks.

### veritas-agents-qa

QA/testing-automation agent (`libs/veritas/agents-qa/src`): a `QAAgent`
(`createQAAgent`) for automated quality-assurance work in the agent newsroom.

### veritas-ai-next-gen

Next-generation AI features (`libs/veritas/ai-next-gen/src`, ~6.6K LOC):
real-time interactive AI anchors (Tavus CVI, `createRealTimeAnchorManager`),
OSINT collection (`createOSINTManager`: satellite imagery, social-media
forensics, document analysis), and an investigation workflow manager.

### veritas-recommendations

Recommendation engine (`libs/veritas/recommendations/src`): content-based and
collaborative filtering services, a `DiversityService` for diversity injection,
and a `RealTimePersonalizationService`, composed under `RecommendationService`.

### @veritas/ab-testing

A/B testing framework (`libs/veritas/ab-testing/src`): an `ABTestingEngine` plus
an experiment analyzer and headline/recommendation testing managers for UI/UX
and content experiments.

### veritas-comments

Comment system with AI moderation (`libs/veritas/comments/src`):
`createCommentSystem`, a `createModerator`, a community manager, and a
dashboard, with notification hooks.

### veritas-community

Community features (`libs/veritas/community/src`): citizen journalism
(`createCitizenJournalismManager`), a SecureDrop-style anonymous submission flow
over an `OnionService` (`createSecureDropManager`), and gamification.

### veritas-newsletter

Newsletter/email automation (`libs/veritas/newsletter/src`): a
`createNewsletterManager` and `createAutomationManager` with template rendering
and provider services for both Mailchimp and AWS SES.

### veritas-notifications-lib

Unified notification service (`libs/veritas/notifications/src`): a
`NotificationService` fronting push, email, SMS, in-app, and WhatsApp providers
(`createPushProvider`, `createSMSProvider`, `createWhatsAppProvider`, …).

### veritas-cms-lib

Internal CMS and editorial tooling (`libs/veritas/cms/src`): content/workflow
managers, a breaking-news manager, an AI-assist manager (`AIService`), and push
notifications for the newsroom's editors.

### veritas-social-automation

Multi-platform social publishing (`libs/veritas/social-automation/src`, 18
files): platform adapters for Instagram, TikTok, YouTube, Facebook, Twitter/X,
LinkedIn, and WhatsApp behind a unified BullMQ-backed `createScheduler`, with
per-platform formatting and analytics.

### veritas-realtime-data

Real-time external-data integrations (`libs/veritas/realtime-data/src`): sports,
financial (with a `MobileMoneyService`), weather, and utility data managers
feeding the automated-content and live surfaces.

### veritas-archive

Historical archive and "On This Day" features (`libs/veritas/archive/src`):
`createArchiveManager`, `createOnThisDayManager`, a `createStoryTracker`, and
collections management for the back catalog.

### @veritas/ussd

USSD news channel (`libs/veritas/ussd/src`): a `USSDService` with telco gateway
adapters (`createGatewayAdapter`/`createGatewayManager`) and a menu
navigator/renderer for text-based news delivery on feature phones.

### veritas-platforms

Platform SDKs for non-web surfaces (`libs/veritas/platforms/src`): smartwatch
and TV app SDKs — `createAppleWatchSDK`, `createWearOSSDK`, `createAppleTVSDK`,
`createAndroidTVSDK`, `createFireTVSDK` — plus media-monitoring.

### @veritas/regional

Regional coverage for Ghana's 16 regions (`libs/veritas/regional/src`): regional
AI anchors, location-based delivery (with an `IPGeolocationService`), language
support, and a `WeatherService` for localized content.

### veritas-expansion

Pan-African geographic expansion (`libs/veritas/expansion/src`): market
research, content adaptation, AI-anchor, translation/voice/avatar services for
entering new African markets beyond Ghana.

### veritas-emergency

Crisis/emergency features (`libs/veritas/emergency/src`): emergency alert and
distribution managers (email + push), plus an election "war room" manager for
high-stakes live coverage.

### veritas-payments

Payments library (`libs/veritas/payments/src`, ~8K LOC): Ghana mobile money
(MTN/Vodafone/ AirtelTigo) via Paystack/Flutterwave, Stripe for international
cards, and Flutterwave for pan-African coverage — provider factories under a
`UnifiedPaymentService` with auto-routing, subscriptions, webhooks, and refunds.

### @veritas/billing

Usage billing for the B2B API (`libs/veritas/billing/src`, has a README):
pricing tiers, usage metering (`createUsageTracker`), invoice generation,
subscription management, usage alerts, and Stripe payment processing.

### veritas-b2b-sdk

The official JavaScript/TypeScript SDK for the Veritas News B2B API
(`libs/veritas/b2b-sdk/src`): a `createClient` plus helpers like
`createKeywordAlert` for external customers consuming articles, fact-checks,
entities, and alerts.

### veritas-b2b-sdk-python

The official Python SDK for the B2B API (`libs/veritas/b2b-sdk-python`, has a
README, ~4.7K LOC of Python): async + sync clients, full endpoint coverage,
retries with backoff, rate-limit handling, pagination iterators, and sandbox
detection — the Python counterpart to `veritas-b2b-sdk`.

### @veritas/signup

Self-service signup and enterprise-sales automation for the B2B API
(`libs/veritas/signup/src`): onboarding flow with analytics, calendar, email,
and notification services (real and in-memory/console implementations).

### @veritas/developer-support

AI-powered developer-support chatbot for the B2B API
(`libs/veritas/developer-support/src`, has a README): `createChatbot` over a
curated `createKnowledgeBase` using Claude or GPT-4, with conversation
management, analytics, and an embeddable widget.

### veritas-business

Profitability and business optimization (`libs/veritas/business/src`): managers
for API- revenue, ad-placement optimization, infrastructure-cost optimization,
AI-efficiency, and resource scaling — the platform's commercial-tuning logic.

### veritas-analytics-lib

Analytics library (`libs/veritas/analytics/src`, 14 files): an
`AnalyticsService` with pluggable handlers (console/HTTP), a
`createPIIScrubber`, and event-name filtering for tracking engagement, content
performance, and revenue metrics.

### veritas-operations

Ongoing-operations toolkit (`libs/veritas/operations/src`): security,
compliance, QA, monitoring, and automation managers — e.g. accessibility-test
and app-store-review managers, an `IncidentNotificationService`, and a
`FactCheckService` wrapper for operational use.

### veritas-risk

Risk-mitigation library (`libs/veritas/risk/src`):
technical/legal/business/reputational risk handling, including a
`createBackupManager`, a `CrisisNotificationService`, and bias/fact-check/NLP
service hooks for risk monitoring.

### @veritas/training-data

Phase 85–86 flywheel producer for the news agency
(`libs/veritas/training-data/src`): `VeritasTrainingDataPipeline` covers twelve
`VeritasTrainingKind` signals — `article-classification`, `fact-check`,
`bias-detection`, `editorial-decision`, `headline-optimization`,
`story-clustering`, `source-reliability`, and peers — emitted as
governance-gated (`governanceGrantId`), anonymized `VeritasTrainingRecord`s to a
pluggable `VeritasTrainingSink`.
