# Lilith — Systems Deep Dive

> The `libs/lilith/` area: nine Nx libraries that are the shared building blocks
> — infra spine, client SDKs, event-bus integration, a cross-domain bridge, and
> a generative-video safety policy — behind Lilith, Oshun's consciousness /
> meditation end-user platform.

## What this area is

Lilith is Oshun's end-user meditation and spiritual-exploration product: guided
meditations, AI persona conversations, progress tracking, and personalization
(see `libs/lilith/README.md`, which names the domain, scope tag `scope:lilith`,
API port 4006, and database schema `lilith`). The deployable pieces live under
`apps/lilith/svc-*`; the `libs/lilith/` packages documented here are **libraries
those services share**, not services themselves. None of the nine is
independently deployed — they are imported by the Lilith service fleet, the web
shell, and external partners.

The nine fall into five clusters. The **infra spine** is `@lilith/service-lib`
(by far the largest — the platform toolkit: database, Vault, TLS, circuit
breakers, security middleware, logging/tracing/metrics, input-validation
schemas), `@lilith/fastify-core` (the standardized Fastify server factory), and
`@lilith/common` (small cross-service utilities: HTTP-status constants, audit
logger, language detection, a CSPRNG id helper, a session store). The
**event-bus integration** cluster is `@lilith/event-publisher` (emits `lilith.*`
domain events) and `@lilith/event-handlers` (subscribes to other domains' events
and fans them out to connected WebSocket clients). The **client SDKs** are
`@lilith/sdk` (the first-party TypeScript SDK) and `@lilith/partner-sdk` (the
external-partner SDK). The **cross-domain bridge** is `@lilith/sophia-adapter`,
which maps Lilith's content/knowledge model onto Sophia's APIs. The **safety
policy** is `@lilith/continuous-video-policy`, a pure-logic library implementing
the §25.3 rules for continuous/generative video.

The packages depend on each other and on platform libs in a few concrete ways
visible in the source: `@lilith/fastify-core`'s `server-factory.ts` lazily
imports `LilithLogger` from `@lilith/service-lib` (with a console fallback);
both event packages build on `@oshun/event-bus`; `@lilith/sophia-adapter` builds
on `@sophia/client`; and `@lilith/service-lib` re-exports a slice of
`@oshun/errors`. `@lilith/common` and `@lilith/continuous-video-policy` are the
most self-contained — pure utilities and pure policy logic with no upstream
Lilith dependencies.

## How it fits the wider system

The Lilith services (`apps/lilith/svc-*`) compose the infra spine: each service
stands up a server via `@lilith/fastify-core`, pulls security middleware,
config, logging, and resilience from `@lilith/service-lib`, and shares small
constants/helpers from `@lilith/common`. Those services publish lifecycle events
through `@lilith/event-publisher` and react to upstream Bellona / Isis / Sophia
/ Yemaya events through `@lilith/event-handlers`, which translates them into
real-time client broadcasts. Front-ends and partners integrate through the two
SDK packages, and Lilith's knowledge surface reaches Sophia through
`@lilith/sophia-adapter`. The generative-video runtime enforces
`@lilith/continuous-video-policy` at frame-emission time. Walk the "used by"
edges on any node below to see exactly who depends on it.

## Entity reference

### @lilith/common

Small, mostly-standalone utility library shared across Lilith services
(`libs/lilith/common`, whose `sourceRoot` is the package root rather than a
`src/`). Its `index.ts` re-exports HTTP-status / port / time constants
(`http-status.ts`), an `AuditLogger`, a `LanguageDetector` with
`detectLanguage`/`getSupportedLanguages`, a `buildServer` Fastify factory
(`server-template.ts`), CSPRNG id helpers (`csprng-ids.ts` — real
`crypto.randomBytes`/`randomUUID`, explicitly replacing `Math.random` while
preserving the legacy `prefix-<base36>-<entropy>` id shape), and a
`SessionStore` for metaverse AI-teacher modules. Note the `README.md` is stale:
it describes `.js`/`.cjs` files, while the tracked source is TypeScript. Tagged
`layer:infra`.

### @lilith/continuous-video-policy

A pure-logic safety library implementing the §25.3 continuous/generative-video
policy (`libs/lilith/continuous-video-policy/src`, `layer:domain`). It is real,
domain-specific code, not a scaffold: `strobe/pse-detector.ts` is a
photosensitive-epilepsy detector modelling the ITU-R BT.1702-2 / WCAG flash
thresholds (sliding-window flash counting with luminance-delta, red-flash, and
sustained-pattern criteria and named constants like
`FLASH_RATE_PER_SECOND_LIMIT`); `persona-caps.ts` declares per-persona frame
envelopes (luminance/contrast/motion-density/color-cycle) and an
`enforcePersonaCaps` decision that passes, downscales, or replaces-with-still;
`narrative-cadence.ts` holds per-persona pacing bands and refuses to apply a
briefing persona to a meditation template; `crisis-frame.ts` swaps to a
non-overridable crisis still-frame and records `SafetyIncidentRecord`s; and
`sensitive-topic.ts` builds pre-roll content notices that disable autoplay.

### @lilith/event-handlers

Cross-domain event subscriptions for Lilith (`libs/lilith/event-handlers/src`,
`layer:integration`). `setupLilithEventHandlers` subscribes via
`@oshun/event-bus` to a fixed `LILITH_SUBSCRIPTIONS` map of Bellona
(`bellona.build.completed`, `bellona.export.ready`), Isis (`isis.job.*`,
`isis.asset.generated`), Sophia (`sophia.index.updated`), and Yemaya
(`yemaya.project.updated`) events, then fans each one out to connected clients
through injected `broadcast` / `sendToUser` functions plus a real services
bundle (cache, metrics, notifications, scheduler, rooms, projects). It is honest
about wiring: `assertServicesWired` fails loud at startup if any service slot is
missing a callable member, rather than silently dropping cache writes or
metrics. Individual handlers (e.g. `handlers/isis-job-completed.ts`) do real
broadcast + cache-invalidation + conditional push-notification work.

### @lilith/event-publisher

The outbound side of Lilith's event surface (`libs/lilith/event-publisher/src`).
`LilithEventPublisher` wraps an `@oshun/event-bus` instance (created over Redis
via `createEventBus`) and exposes typed `publish*` methods for the `lilith.*`
taxonomy declared in `LilithEventTypes` — meditation
started/completed/generated, journal created/updated, session started/ended,
progress updated, teacher interaction, content downloaded — each routing to
sensible default target domains (e.g. meditation-completed targets `hathor` and
`sophia`). It is fail-soft by design: `initialize` and `publishEvent` catch bus
errors, log, and return `null` rather than throwing, and a singleton accessor
(`getLilithEventPublisher`) plus `resetLilithEventPublisher` support reuse and
testing.

### @lilith/fastify-core

Shared Fastify service utilities for the Lilith fleet
(`libs/lilith/fastify-core/src`, `layer:infra`). Its `index.ts` exports a
`createServiceServer` / `quickStart` server factory plus standardized
Kubernetes-ready health routes (`health-routes.ts`), an error handler with a
family of typed errors (`ValidationError`, `UnauthorizedError`, `NotFoundError`,
`RateLimitError`, …), a `MiddlewareRegistry`, `registerGracefulShutdown`, a
`BoundedMap`, and `registerProcessErrorHandlers`. The factory's default logger
(`server-factory.ts`) lazily `import`s `LilithLogger` from `@lilith/service-lib`
and falls back to a structured console logger if that import fails — a real
dependency seam, not a stub. The exported comments tie several pieces to
specific audit-pass remediations (e.g. `#133`/`R1` graceful shutdown).

### @lilith/partner-sdk

The external-partner TypeScript SDK (`libs/lilith/partner-sdk/src`,
`layer:clients`). `index.ts` exports `LilithPartnerClient` (a real `fetch`-based
client in `client.ts` with a private `request<T>` helper, API-key / bearer auth,
and a configurable base URL defaulting to the placeholder
`https://api.lilith.example.com/partner`), the `PartnerAPIClientError` class
with `isRateLimitError()` / `isAuthError()` / `isScopeError()` /
`getRetryAfter()` helpers, and the `types.ts` request/response surface.
Documented methods (`README.md`) cover partner registration and approval,
API-key management, `chat`, `getContent`, `synthesizeSpeech`, analytics, and
webhook creation, with tiered rate limits. The `example.com` base URL signals
this targets a not-yet- public partner gateway.

### @lilith/sdk

The first-party TypeScript SDK for the Lilith API (`libs/lilith/sdk/src`,
`layer:clients`). The bulk lives in a large `index.ts` (~2,600 lines) whose
`APIClient` is a real `fetch`-based client: non-streaming `chat`, SSE
`streamChat` with a hand-rolled `parseSSE`, conversation CRUD,
`generateLecture`, `ttsSynthesize`, `ingest`, test notifications, and a wide
catalogue surface for the "consciousness"/"mythology" content families (vision
quests, ego-death simulations, collective-unconscious maps, noosphere,
divination, etc.) plus admin backup/restore endpoints. It also exports a second
`LilithApiClient` and re-exports `./auth`, `./seamless-auth` (a `SeamlessAuth`
`EventEmitter`-based session manager with social providers and trust levels),
and `./errors/SeamlessErrorClassifier`; `generated/openapi.ts` holds generated
types. Be aware the `README.md` is partly aspirational — it shows
`createLilithClient`, an `api.auth.*` namespace, and `generateMeditation`, which
do not all match the current exported surface (the concrete entry points are
`APIClient` / `LilithApiClient`).

### @lilith/service-lib

The platform infra toolkit and by far the largest package in the area
(`libs/lilith/service-lib`, `sourceRoot` at the package root, `layer:infra`).
Its `index.ts` re-exports a broad, real surface organized by concern: core
infrastructure (`DatabaseManager`, `VaultClient`, `LilithLogger`,
`ConfigManager`, a `TLSManager` backed by genuine certificate
crypto/issuer/storage/renewal modules under `tls-manager/`,
`ExternalCredentialManager`, `KubernetesDeploymentOrchestrator`), resilience
(`CircuitBreaker` + registry), service discovery/client/registry, graceful
shutdown, health aggregation, security middleware (auth, rate limiting, bot
detection, IP filtering, WAF), a `PIIDetector`, a large Zod input-validation
schema set (`input-validation/*`), API versioning, structured
logging/tracing/metrics, a Lilith error taxonomy layered over `@oshun/errors`,
AI error-recovery helpers, Vault config loading, and an extensive
testing-infrastructure surface. It is ESM with a few CommonJS shims pulled in
via `createRequire` (`create-fastify-server.cjs`, `middleware/common.cjs`); a
`SYNTAX_FIX_SUMMARY.md` and `scripts/fix-any-types.ts` are in-repo maintenance
tooling rather than runtime code.

### @lilith/sophia-adapter

The cross-domain bridge from Lilith to Sophia (`libs/lilith/sophia-adapter/src`,
`layer:adapters`). It builds on `@sophia/client` and exposes three real adapters
plus factory functions: `KnowledgeAccessAdapter` maps Lilith `ContentBundle` /
`AccessPolicy` / `AccessPass` onto Sophia's document ingestion, search, and
metadata APIs using an explicit tag-prefix scheme (`lilith:bundle:`,
`lilith:policy:`, `lilith:tier:`, `lilith:access:`, plus primary/lesson tags);
`KnowledgeGraphAdapter` maps Lilith entities/relations onto Sophia's
Entity/Relationship graph with entity resolution; and `EmbeddingAdapter` routes
embedding and similarity requests to Sophia's vector infrastructure. The module
documents its field-by-field mapping strategy at the top of
`knowledge-access-adapter.ts`, and surfaces a `SophiaAdapterError` for failures.
