# Shared Domain — Technical Specifications

> Technical specifications for the `@oshun/*` shared platform libraries at
> `libs/shared/`. Every type, schema, enum, constant, and function in this
> document is traceable to source under `libs/shared/<package>/src/`.

---

This document is the API reference companion to `features.md`. It lists the
exact exported names — types, classes, functions, constants, and enums — for
each of the 42 packages in `libs/shared/`. Use `features.md` to understand what
a library does and why; use this document to find the specific symbol you need
to import.

---

## Package Inventory

`libs/shared/` contains **42 workspace packages**, all published under the
`@oshun/*` npm scope. The table below maps every source directory to its package
name.

| Directory               | Package                       | Directory                  | Package                          |
| ----------------------- | ----------------------------- | -------------------------- | -------------------------------- |
| `ai/`                   | `@oshun/ai`                   | `layout-analyzer/`         | `@oshun/layout-analyzer`         |
| `ai-advanced/`          | `@oshun/ai-advanced`          | `logging/`                 | `@oshun/logging`                 |
| `audit-platform/`       | `@oshun/audit-platform`       | `metrics/`                 | `@oshun/metrics`                 |
| `auth/`                 | `@oshun/auth`                 | `migration/`               | `@oshun/migration`               |
| `auth-primitives/`      | `@oshun/auth-primitives`      | `ml/`                      | `@oshun/ml`                      |
| `cache/`                | `@oshun/cache`                | `native-libs/`             | `@oshun/native-libs`             |
| `config/`               | `@oshun/config`               | `ocr/`                     | `@oshun/ocr`                     |
| `crypto/`               | `@oshun/crypto`               | `queue/`                   | `@oshun/queue`                   |
| `data-residency/`       | `@oshun/data-residency`       | `rate-limit/`              | `@oshun/rate-limit`              |
| `database/`             | `@oshun/database`             | `region-rules/`            | `@oshun/region-rules`            |
| `documentation/`        | `@oshun/documentation`        | `release-management/`      | `@oshun/release-management`      |
| `errors/`               | `@oshun/errors`               | `review-persistence/`      | `@oshun/review-persistence`      |
| `event-bus/`            | `@oshun/event-bus`            | `runpod-client/`           | `@oshun/runpod-client`           |
| `gateway/`              | `@oshun/traefik-config`       | `security/`                | `@oshun/security`                |
| `gpu-dispatcher/`       | `@oshun/gpu-dispatcher`       | `service-discovery/`       | `@oshun/service-discovery`       |
| `health/`               | `@oshun/health`               | `storage/`                 | `@oshun/storage`                 |
| `http-client/`          | `@oshun/http-client`          | `tara-live-class-booking/` | `@oshun/tara-live-class-booking` |
| `identity/`             | `@oshun/identity`             | `testing/`                 | `@oshun/testing`                 |
| `inbound-integrations/` | `@oshun/inbound-integrations` | `tracing/`                 | `@oshun/tracing`                 |
| `infrastructure/`       | `@oshun/infrastructure`       | `types/`                   | `@oshun/types`                   |
| `vision-llm/`           | `@oshun/vision-llm`           | `websocket/`               | `@oshun/websocket`               |

---

## Technology Stack

All shared libraries use a consistent set of underlying technologies. The table
below shows the technology choice for each layer and which packages use it.

| Layer           | Technology                                         |
| --------------- | -------------------------------------------------- |
| Language        | TypeScript (ESM, `"type": "module"`)               |
| Runtime         | Node.js                                            |
| Validation      | Zod (`@oshun/config`, `release-management`, etc.)  |
| Database driver | `pg` (PostgreSQL pool + Drizzle base)              |
| Cache / Redis   | `ioredis`                                          |
| Event bus       | Redis pub/sub via `ioredis` (see below)            |
| Object storage  | AWS SDK S3 client (S3-compatible: MinIO / AWS S3)  |
| Job queue       | BullMQ (Redis-backed) + in-memory fallback         |
| Logging         | Pino                                               |
| Metrics         | `prom-client` + OpenTelemetry metrics              |
| Tracing         | OpenTelemetry SDK + Jaeger / AWS X-Ray exporters   |
| Crypto          | `@noble/hashes`, `@noble/curves`, `@noble/ciphers` |
| Testing         | Vitest                                             |
| Build           | tsup / `tsc` per package                           |

`@oshun/auth` and `@oshun/identity` ship framework-agnostic middleware with
Express-style and Hono adapters; `@oshun/rate-limit` and `@oshun/tracing`
provide Hono middleware factories. There is no `@oshun/traefik-config`-resident
HTTP server — `@oshun/traefik-config` generates **Traefik** configuration.

---

## Core Type System (`@oshun/types`)

Zero-dependency foundation package. Source: `libs/shared/types/src/`.

### Branded ID Types (`base.ts`)

`ID<T>` is a nominal string brand: `string & { readonly __brand: T }`. Concrete
aliases: `UserID`, `ProjectID`, `OrganizationID`, `TeamID`, `SessionID`,
`AssetID`, `ContentID`, `AgentID`, `RequestID`, `CorrelationID`.

### Timestamp Types

`Timestamp` (`Date | string | number`), `ISODateTime` (branded string),
`ISODate` (branded string).

### Result Types

The `Result` family encodes success and failure in the return type rather than
through exceptions. The `AsyncResult` alias wraps the same pattern in a
`Promise`.

```typescript
interface Success<T> {
  readonly success: true;
  readonly value: T;
}
interface Failure<E> {
  readonly success: false;
  readonly error: E;
}
type Result<T, E = Error> = Success<T> | Failure<E>;
type AsyncResult<T, E = Error> = Promise<Result<T, E>>;
interface ApiErrorResult {
  readonly code: string;
  readonly message: string;
  readonly details?: Record<string, unknown>;
}
type ApiResult<T> =
  | { success: true; data: T }
  | { success: false; error: ApiErrorResult };
```

### Entity Mixins

These mixins are composed onto domain model interfaces rather than duplicated in
every domain. `FullEntity` combines the four most common mixins.

`BaseEntity` (`id`, `createdAt`, `updatedAt`), `SoftDeletable`, `Versioned`,
`Auditable`, `Orderable`, `Taggable`, `Archivable`, and `FullEntity` (composes
`BaseEntity & SoftDeletable & Versioned & Auditable`).

### Utility Types

`Nullable`, `Optional`, `DeepPartial`, `DeepReadonly`, `PartialExcept`,
`RequiredExcept`, `RequireAtLeastOne`, `RequireExactlyOne`, `Awaited`,
`ValueOf`, `NonNullableFields`, `AtLeastOne`. JSON types: `JsonPrimitive`,
`JsonValue`, `JsonArray`, `JsonObject`. Function types: `AsyncFunction`,
`DisposeFn`, `UnsubscribeFn`. `VERSION` constant and `SemanticVersion`.

### Subpath Modules

`@oshun/types` organizes its exports into subpath modules for tree-shaking and
logical grouping. The primary subpaths are:

- **`contracts.ts`** — cross-domain contract versioning:
  `parseOshunContractVersion`, `compareOshunContractVersions`,
  `buildOshunContractVersionDescriptor`, `resolveOshunContractVersionSupport`,
  `isOshunContractVersionSupported`, `assertOshunContractVersionSupported`,
  `versionOshunContractPayload`, plus types `OshunContractCompatibilityMode`,
  `OshunContractStability`, `OshunVersionedContractEnvelope`, etc.
- **`user.ts`** — `User`, `UserSummary`, `UserPreferences`, `UserContext`,
  `JWTPayload`, `Session`, `DeviceInfo`, `TokenResponse`, `ApiKey`,
  `OAuthProvider`, `OAuthConnection`, `Organization`, `Team`, `TeamMember`,
  `UserRole`, `Permission`, `ProjectRole`, `UserStatus`.
- **`api.ts`** — `ApiResponse`, `ApiError`, `SuccessResponse`, `ErrorResponse`,
  `PaginationParams`, `SortParams`, `PaginationMeta`, `PaginatedResponse`,
  `CursorPaginationParams`, `CursorPaginatedResponse`, `ListResponse`,
  `BulkOperationResponse`, `HealthStatus`, `HealthCheck`, `ReadinessStatus`,
  `LivenessStatus`, `RequestContext`, `RateLimitInfo`, `WebhookPayload`,
  `WebhookDelivery`, `WebhookConfig`.
- **`events.ts`** — `DomainEvent`, `IntegrationEvent`, `EventMetadata`,
  `EventHandler`, `EventSubscription`, `EventBus`, `MessageEnvelope`,
  `DeadLetterEntry`, `JobStatus`, `Job`, `Notification`, `ActivityLog`,
  `AuditLog`, `Presence`, `RealtimeMessage`.
- **`config.ts`** — `Environment`, `LogLevel`, `LogFormat`, `ServiceConfig`,
  `DatabaseConfig`, `CacheConfig`, `StorageConfig`, `AuthConfig`,
  `LoggingConfig`, `TracingConfig`, `MetricsConfig`, `AIConfig`, `EmailConfig`,
  `FeatureFlag`, `AppConfig`, and provider sub-configs.
- **`creative/`** — `Asset`, `Script`, `Scene`, `Character`, `Storyboard`,
  `StoryboardPanel` and related branded IDs (re-exported via `@oshun/types`).

---

## Error Model (`@oshun/errors`)

Source: `libs/shared/errors/src/`.

### Base Class (`base.ts`)

Every platform error extends `OshunError`. The class carries both runtime
metadata (timestamp, operationality) and serialization methods for clients and
operators.

```typescript
class OshunError extends Error {
  readonly code: string; // ERROR_CODES value; defaults to UNKNOWN_ERROR
  readonly statusCode: number; // HTTP status; defaults to 500
  readonly details: ErrorDetails | undefined;
  readonly timestamp: Date;
  readonly isOperational: boolean;
  readonly expose: boolean; // defaults to statusCode < 500
  toJSON(): SerializedError; // name, code, message, statusCode, timestamp,
  // details/stack/cause as available
  toResponse(): { error: { message; code?; details? } }; // masks 5xx detail
  getRootCause(): Error;
}
```

`AppError` is a Lilith-compatibility alias accepting either a positional
`(message, statusCode, code, details)` signature or the options object.

> There is **no** `toProblemDetails()` / RFC 7807 serializer and **no** Hono
> error-handler middleware in this package. Serialization is `toJSON()` /
> `toResponse()`.

### HTTP Error Classes (`http.ts`)

One class per HTTP status, each with a default machine-readable error code.
Domain code throws these directly; the middleware layer calls `toResponse()` to
produce the client-safe body.

| Class                      | Status | Default code                          |
| -------------------------- | ------ | ------------------------------------- |
| `BadRequestError`          | 400    | `INVALID_INPUT`                       |
| `UnauthorizedError`        | 401    | `AUTH_REQUIRED`                       |
| `PaymentRequiredError`     | 402    | `SUBSCRIPTION_REQUIRED`               |
| `ForbiddenError`           | 403    | `FORBIDDEN`                           |
| `NotFoundError`            | 404    | `NOT_FOUND`                           |
| `MethodNotAllowedError`    | 405    | `METHOD_NOT_ALLOWED`                  |
| `ConflictError`            | 409    | `CONFLICT`                            |
| `GoneError`                | 410    | `GONE`                                |
| `UnprocessableEntityError` | 422    | `VALIDATION_FAILED`                   |
| `TooManyRequestsError`     | 429    | `RATE_LIMITED` (carries `retryAfter`) |
| `InternalServerError`      | 500    | `INTERNAL_ERROR`                      |
| `NotImplementedError`      | 501    | `NOT_IMPLEMENTED`                     |
| `BadGatewayError`          | 502    | `EXTERNAL_SERVICE_ERROR`              |
| `ServiceUnavailableError`  | 503    | `SERVICE_UNAVAILABLE`                 |
| `GatewayTimeoutError`      | 504    | `TIMEOUT`                             |

### Domain Error Classes (`domain.ts`)

Each domain error extends an HTTP error, inheriting its status code, and adds
domain-specific detail fields. The pattern allows callers to catch a base
`UnauthorizedError` without knowing which subclass was thrown.

- `ValidationError` extends `BadRequestError` (**400**) — adds a `fields` detail
  map.
- `AuthenticationError`, `TokenExpiredError`, `SessionError` extend
  `UnauthorizedError` (401).
- `AuthorizationError` extends `ForbiddenError` (403).
- `ResourceNotFoundError` extends `NotFoundError` (404).
- `DuplicateError`, `VersionConflictError` extend `ConflictError` (409).
- `RateLimitError` extends `TooManyRequestsError` (429) — accepts
  `retryAfter`/`limit`/`remaining`/`reset`.
- `ExternalServiceError` extends `BadGatewayError` (502); `AIServiceError`
  extends `ExternalServiceError`.
- `DatabaseError` extends `InternalServerError` (500, `isOperational: false`).
- `CacheError`, `QueueError`, `GenerationError` extend `OshunError` directly
  (500).
- `InvalidStateError`, `PreconditionError`, `LimitExceededError` extend
  `BadRequestError` (400).

### Error Code Registry (`codes.ts`)

Eight grouped constant objects are merged into `ERROR_CODES`. Clients switch on
these codes rather than parsing message strings, enabling localization and
programmatic recovery.

| Group               | Codes                                                                                                                                                                                                                                                             |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GENERAL_ERRORS`    | `UNKNOWN_ERROR`, `INTERNAL_ERROR`, `SERVICE_UNAVAILABLE`, `TIMEOUT`, `RATE_LIMITED`, `MAINTENANCE`                                                                                                                                                                |
| `VALIDATION_ERRORS` | `VALIDATION_FAILED`, `INVALID_INPUT`, `MISSING_REQUIRED_FIELD`, `INVALID_FORMAT`, `VALUE_OUT_OF_RANGE`, `INVALID_TYPE`, `CONSTRAINT_VIOLATION`                                                                                                                    |
| `AUTH_ERRORS`       | `AUTH_REQUIRED`, `INVALID_CREDENTIALS`, `TOKEN_EXPIRED`, `TOKEN_INVALID`, `TOKEN_REVOKED`, `SESSION_EXPIRED`, `SESSION_INVALID`, `MFA_REQUIRED`, `MFA_INVALID`, `ACCOUNT_LOCKED`, `ACCOUNT_DISABLED`, `ACCOUNT_NOT_VERIFIED`, `PASSWORD_EXPIRED`, `PASSWORD_WEAK` |
| `AUTHZ_ERRORS`      | `FORBIDDEN`, `INSUFFICIENT_PERMISSIONS`, `ROLE_REQUIRED`, `RESOURCE_ACCESS_DENIED`, `ACTION_NOT_ALLOWED`, `QUOTA_EXCEEDED`, `SUBSCRIPTION_REQUIRED`, `SUBSCRIPTION_EXPIRED`                                                                                       |
| `RESOURCE_ERRORS`   | `NOT_FOUND`, `ALREADY_EXISTS`, `CONFLICT`, `GONE`, `LOCKED`, `DELETED`, `ARCHIVED`, `VERSION_MISMATCH`                                                                                                                                                            |
| `EXTERNAL_ERRORS`   | `EXTERNAL_SERVICE_ERROR`, `EXTERNAL_SERVICE_TIMEOUT`, `EXTERNAL_SERVICE_UNAVAILABLE`, `DATABASE_ERROR`, `CACHE_ERROR`, `STORAGE_ERROR`, `QUEUE_ERROR`, `AI_SERVICE_ERROR`, `PAYMENT_ERROR`, `EMAIL_ERROR`                                                         |
| `BUSINESS_ERRORS`   | `OPERATION_FAILED`, `INVALID_STATE`, `PRECONDITION_FAILED`, `DEPENDENCY_FAILED`, `WORKFLOW_ERROR`, `LIMIT_EXCEEDED`                                                                                                                                               |
| `CONTENT_ERRORS`    | `UPLOAD_FAILED`, `PROCESSING_FAILED`, `INVALID_FILE_TYPE`, `FILE_TOO_LARGE`, `FILE_CORRUPTED`, `TRANSCODING_FAILED`, `GENERATION_FAILED`                                                                                                                          |

`HTTP_STATUS` exports named numeric constants for 2xx/3xx/4xx/5xx codes.

### Utilities (`utils.ts`)

Type guards `isOshunError`, `isAppError`, `isOperationalError`, `isClientError`,
`isServerError`; wrappers `wrapError`, `ensureError`; response helpers
`createErrorResponse`, `createSafeErrorResponse`; extractors `getStatusCode`,
`getErrorCode`, `getErrorMessage`, `getErrorStack`; chain helpers
`getErrorChain`, `findInChain`; `AggregateError`; async helpers `catchAsync`,
`tryCatch`; and `formatErrorForLogging`. Sentry integration is an optional peer
dependency (`@sentry/node`).

---

## Configuration (`@oshun/config`)

Source: `libs/shared/config/src/`. Depends on `zod`.

### Environment Helpers (`env.ts`)

Detection: `getEnvironment`, `isProduction`, `isDevelopment`, `isTest`. Typed
reads: `getEnv`, `getEnvRequired`, `getEnvNumber`, `getEnvNumberRequired`,
`getEnvBool`, `getEnvArray`, `getEnvJson`, `getEnvUrl`, `getEnvUrlRequired`.
Resolution: `getLogLevel`, `getPort`.

### Zod Schemas (`schemas.ts`)

Every config shape has a corresponding exported Zod schema so services can
compose validation rather than hand-rolling it. The schemas are:

`environmentSchema`, `logLevelSchema`, `logFormatSchema`, `portSchema`,
`hostSchema`, `urlSchema`, `corsOriginsSchema`, `serverConfigSchema`,
`databaseConfigSchema`, `sslConfigSchema`, `poolConfigSchema`,
`redisConfigSchema`, `redisClusterConfigSchema`, `redisSentinelConfigSchema`,
`storageConfigSchema`, `authConfigSchema`, `oauthConfigSchema`,
`oauthProviderConfigSchema`, `loggingConfigSchema`, `tracingConfigSchema`,
`metricsConfigSchema`, `errorTrackingConfigSchema`, `aiConfigSchema`,
`anthropicConfigSchema`, `openaiConfigSchema`, `googleAiConfigSchema`,
`emailConfigSchema`, `smtpConfigSchema`, `rateLimitConfigSchema`,
`serviceConfigSchema`.

### Loaders (`loader.ts`)

`validateConfig(schema, data, options)`, the factory `createConfigLoader`, and
eight loaders: `loadServiceConfig`, `loadServerConfig`, `loadDatabaseConfig`,
`loadRedisConfig`, `loadStorageConfig`, `loadAuthConfig`, `loadLoggingConfig`,
`loadAIConfig`. There are **no** per-domain database loaders; all domain
databases use `loadDatabaseConfig()` with the appropriate `DATABASE_URL`.

### Feature Flags (`features.ts`)

`FeatureFlags` registry, `isFeatureEnabled`, `getFeatureValue`,
`getAllFeatureFlags`, plus image-generation helpers `getComfyUIProvider`,
`getImageGenerationProvider`, `shouldUseRunPod`, `getRunPodConfig`,
`validateRunPodConfiguration`.

### Experiment Guardrails (`experiment-guardrails.ts`)

`ExperimentSchema`, `GuardrailMetricSchema`, `GuardrailOpSchema`,
`PolicyBundleSchema`; functions `evaluateGuardrails`, `evaluateMetric`,
`bundleIsGreen`, `loadPolicyBundle`.

---

## Event Bus (`@oshun/event-bus`)

Source: `libs/shared/event-bus/src/`. Dependencies: `ioredis`, `nanoid`,
`@oshun/logging`.

### Transport — Redis pub/sub (not Kafka, not Redis Streams)

`EventBus` constructs two `ioredis` connections (`pub`, `sub`). `publish()`
serialises an envelope, optionally stores it under a TTL-bounded key
(`oshun:events:event:<id>`, default TTL **86400 s**), and fans it out with Redis
`PUBLISH`. Subscribers use Redis pattern subscriptions (`PSUBSCRIBE`). The TTL
key — not a stream — is the replay source for `replayUnacked()`.
Delayed/`nack`ed events are durable via a Redis sorted set
(`oshun:events:scheduled`) drained by a scheduler loop every **250 ms**.

### Event Envelope (`types.ts`)

Every event published through the bus is wrapped in this envelope. The
`correlationId` and `causationId` fields are critical for cross-service tracing
and audit replay.

```typescript
interface EventEnvelope<T = unknown> {
  id: string; // nanoid
  type: string; // e.g. 'isis.asset.generated'
  source: DomainScope; // publisher domain
  targets?: DomainScope[]; // empty/undefined = broadcast
  correlationId?: string;
  causationId?: string; // id of the event that caused this one
  payload: T;
  timestamp: number; // epoch ms
  version: string; // schema version
  metadata?: Record<string, unknown>;
}
```

`DomainScope` is
`'yemaya' | 'lilith' | 'isis' | 'sophia' | 'hathor' | 'bellona' | 'aphrodite' | 'asase' | 'oshun'`.

### Configuration

The bus accepts a single config object at construction. The `topicRegistry` and
`registryMode` fields are optional but recommended for production use — they
enable schema validation and lifecycle enforcement on every published event.

```typescript
interface EventBusConfig {
  redisUrl: string;
  sourceDomain: DomainScope;
  keyPrefix?: string; // default 'oshun:events'
  defaultRetry?: RetryConfig;
  defaultDeadLetter?: DeadLetterConfig;
  persistence?: boolean; // default true
  eventTtl?: number; // seconds, default 86400
  topicRegistry?: EventTopicRegistry;
  registryMode?: 'advisory' | 'enforced'; // default 'advisory'
}
```

### `IEventBus` Contract

- `publish<T>(type, payload, options?): Promise<string>` — returns the event id.
  `PublishOptions`: `targets`, `correlationId`, `causationId`, `delay` (ms),
  `priority` (lower = higher), `schemaVersion`, `metadata`.
- `subscribe<T>(pattern, handler, options?): Promise<Subscription>` — `pattern`
  supports `*` wildcards. `SubscriptionOptions`: `group` (competing consumers),
  `sourceFilter`, `concurrency`, `retry`, `deadLetter`.
- `unsubscribeAll()`, `getDeadLetters(limit?, offset?)`,
  `replayDeadLetter(entryId)`, `removeDeadLetter(entryId)`, `replayUnacked()`,
  `close()`.

`EventHandler` receives `(event, context)` where `EventContext` exposes `ack`,
`nack(delay?)`, `deadLetter(reason)`, `reply(payload)`, and `publish(...)`.
`RetryConfig` supports `'exponential' | 'linear' | 'fixed'` strategies; default
is 3 attempts, 1000 ms initial, ×2 multiplier, 30000 ms cap.

### Consumer Groups and Delivery Semantics

When a subscription declares a `group`, members race for a
per-`(eventId, group)` claim key via `SET NX EX` — only the winner runs the
handler. Without a group every matching subscription runs (broadcast). A
per-`(eventId)` Redis HASH records processed subscriptions/groups;
`replayUnacked()` redelivers only persisted events still lacking a processed
marker. Delivery is at-least-once.

### `EventTypes` Constant

A frozen map of standard event-type strings organized by domain. These strings
are the canonical form for all inter-domain events.

- **Isis** — `isis.asset.generated`, `isis.job.*`, `isis.workflow.completed`
- **Sophia** — `sophia.document.ingested`, `sophia.index.updated`,
  `sophia.embeddings.generated`, `sophia.query.completed`
- **Hathor** — `hathor.world.*`, `hathor.character.created`,
  `hathor.narrative.generated`
- **Bellona** — `bellona.build.*`, `bellona.export.ready`,
  `bellona.asset.imported`
- **Yemaya** — `yemaya.project.*`, `yemaya.asset.uploaded`,
  `yemaya.collaboration.started`
- **Lilith** — `lilith.meditation.completed`, `lilith.content.published`,
  `lilith.user.progress`
- **Fighting game telemetry** — a large `v2.match.*` / `v2.player.*` /
  `v2.cosmetic.*` family

`StandardEventType` is the union of all these values.

### Topic Registry (`topic-registry.ts`)

`EventTopicRegistry` holds versioned `EventTopicDefinition`s. Each definition
declares `topic`, `ownerDomain`, `producerDomains`, `consumerDomains`,
`lifecycle` (`'active' | 'deprecated' | 'retired'`), `defaultSchemaVersion`, and
per-version `EventTopicSchemaVersion` records (with `compatibility`:
`'backward' | 'forward' | 'full' | 'none'`, `payloadSchema`, optional
`validate`). `resolveForPublish` validates payloads when a validator is present;
in `'enforced'` mode unregistered/retired topics throw. Exports:
`DEFAULT_EVENT_TOPIC_DEFINITIONS`, `DEFAULT_EVENT_TOPIC_REGISTRY`,
`OshunV1EventTopics`, `createEventTopicRegistry`.

### Outbound Delivery and Webhook Simulator

`outbound-delivery.ts` ships an `OutboundEventDispatcher`, signing key ring
(`OutboundSigningKeyRing`, HMAC/asymmetric signatures),
`MemoryOutboundDeliveryStore`, retry backoff (`calculateOutboundBackoffMs`), and
signature sign/verify helpers — for delivering events to external tenant
webhooks. `webhook-simulator.ts` provides `TenantWebhookSimulator` /
`createTenantWebhookDevSandbox` for local webhook testing.

---

## Database (`@oshun/database`)

Source: `libs/shared/database/src/`.

- **PostgreSQL** — `PostgresClient`, `createPostgresClient`,
  `createPostgresClientFromEnv`, `createPostgresClientFromUrl`. Config types
  `PostgresConfig`, `PostgresPoolStats`, `PostgresHealthInfo`;
  `DEFAULT_POSTGRES_CONFIG`.
- **PgBouncer** — `PgBouncerAdminConfig`, `PgBouncerAutoScalerConfig`,
  `PgBouncerPoolStats`, `PgBouncerDatabaseStats`.
- **Redis** — `RedisClient`, `RedisClusterClient`, `createRedisClient*`
  variants; `RedisConfig`, `RedisClusterConfig`, `RedisHealthInfo`.
- **Transactions** — `withTransaction`, `withReadOnlyTransaction`,
  `withSerializableTransaction`, `withRollbackTransaction`, savepoint helpers
  (`createSavepoint`, `withSavepoint`, …), advisory-lock helpers
  (`acquireAdvisoryLock`, `withAdvisoryLock`, …). `TransactionOptions`,
  `TransactionIsolationLevel`.
- **Query builder** — `sql` tagged template, `sqlJoin`, `sqlEmpty`, `sqlRaw`,
  `buildWhereClause`, `buildOrderByClause`, `buildPaginationClause`,
  `calculatePagination`, `buildInsertStatement`, `buildUpdateStatement`,
  `buildDeleteStatement`, `sanitizeIdentifier`, `quoteIdentifier`,
  `escapeLikePattern`. Types `WhereCondition`, `OrderByClause`,
  `ParameterizedQuery`, `ComparisonOperator`.
- **Health** — `checkPostgresHealth`, `checkRedisHealth`,
  `checkAllDatabasesHealth`, `HealthMonitor`, `clearHealthCache`.
- **Connection strings** — `parsePostgresConnectionString`,
  `buildPostgresConnectionString`, `maskPostgresConnectionString` and Redis
  equivalents; `detectDatabaseType`, `validateConnectionString`.
- **Migrations** — `MigrationRunner`, `createSqlMigration`, `createMigrationId`,
  `parseMigrationId`. (See `@oshun/migration` for the cross-domain framework — a
  separate package.)
- **Metrics** — `createPostgresMetrics`, `instrumentPostgresClient`,
  `InstrumentedPostgresClient`, `PoolStatsMonitor`, `DatabaseStatsTracker`.
- **Errors** — `DatabaseError`, `DatabaseErrorCodes`.

---

## Cache (`@oshun/cache`)

Source: `libs/shared/cache/src/`. Redis-backed (`ioredis`) plus in-memory.

- **Clients** — `OshunRedisClient`, `OshunRedisClusterClient`,
  `createRedisClient*`, `getCacheClient` / `setCacheClient` /
  `initializeCacheClient`. `CacheError`.
- **Memory cache** — `OshunMemoryCache`, `createMemoryCache`, `getMemoryCache`,
  `clearGlobalCache`.
- **Circuit breaker** — `OshunCircuitBreaker`, `CircuitOpenError`,
  `withCircuitBreaker`.
- **Distributed lock** — `OshunLockManager`, `createLockManager`, `LockError`,
  `LockExpiredError`.
- **Pub/Sub** — `OshunPubSubClient`, `createPubSubClient*`; `PUBSUB_CHANNELS`.
- **Invalidation** — `OshunInvalidationManager`, `invalidateKey`,
  `invalidatePattern`, `invalidateByPrefix`.
- **Cache wrappers** — `withRedisCache`, `withMemoryCache`,
  `withMemoryCacheSync`, `cachedMethod`, `createCacheWrapper`.
- **Key builders** — `cacheKey`, `prefixedKey`, `hashKey`, plus domain builders
  (`userKey`, `sessionKey`, `authKey`, `jwtKey`, `accessTokenKey`,
  `rateLimitKey`, `lockKey`, …) and pattern builders.
- **Constants** — `TTL`, `DOMAIN_TTL`, `KEY_PREFIX`.
- **Metrics** — `createCacheMetrics`, `instrumentCacheClient`,
  `InstrumentedCacheClient`, `CacheStatsTracker`.

---

## Job Queue (`@oshun/queue`)

Source: `libs/shared/queue/src/`. BullMQ-backed with in-memory fallback.

- **BullMQ** — `BullMQQueue`, `BullMQWorker`, `RedisDeadLetterQueue` (with
  `createQueue`, `createWorker`, `createDeadLetterQueue`).
- **In-memory** — `MemoryQueue`, `MemoryWorker`, `MemoryDeadLetterQueue`,
  `clearAllMemoryStores` for tests.
- **Durable queue substrate** — `DurableQueueSubstrate`,
  `createDurableQueueSubstrate`, `createDurableJobSubmitters`,
  `deriveDurableJobId`, with `DURABLE_JOB_CLASSES` / `DURABLE_JOB_CLASS_CONFIG`
  and an observability sink.
- **SLA monitor** — `DurableQueueSlaMonitor`, `buildSlaPolicies`,
  `DEFAULT_DURABLE_QUEUE_SLA_POLICIES`, with alert hooks and snapshots.
- **Types/constants** — `JobEnvelope<T>`, `JobOptions`, `JobResult`, `JobError`,
  `JobProgress`, `JobPriority`, `JobStatus`, `Queue`, `Worker`,
  `DeadLetterQueue`; `PRIORITY_VALUES`, `QUEUE_NAMES`, `DEFAULT_RETRY_CONFIG`,
  `DEFAULT_JOB_OPTIONS`, `DEFAULT_DLQ_CONFIG`.

---

## Object Storage (`@oshun/storage`)

Source: `libs/shared/storage/src/`. S3-compatible.

- **Clients** — `S3StorageClient` (`createS3Client`, `createMinioClient`),
  `LocalStorageClient` (`createLocalStorageClient`) for tests/dev.
- **Types** — `StorageClient`, `StorageProvider`, `S3Config`,
  `LocalStorageConfig`, `FileMetadata`, `FileManifest`, `UploadOptions`,
  `UploadResult`, `MultipartUploadConfig`/`State`/`Progress`,
  `SignedUrlOptions`, `SignedUrlResult`, `SignedPostPolicy`,
  `ListObjectsOptions`/`Result`, `CopyObjectOptions`, `RestoreObjectOptions`/
  `Result`, `RestoreTier`.
- **Constants** — `DEFAULT_SIGNED_URL_EXPIRATION`, `DEFAULT_PART_SIZE`,
  `MIN_PART_SIZE`, `MAX_PART_SIZE`, `MAX_PARTS`.
- **Utilities** — file-key (`generateFileKey`, `sanitizeFilename`, `joinKey`),
  MIME (`getMimeType`, `isImageMimeType`, …), size (`formatBytes`,
  `parseBytes`), checksum (`computeMd5`, `computeSha256`), manifest, and
  content-disposition helpers.
- **GPU presigned URLs** — `generateGpuUploadUrl`, `generateGpuDownloadUrl`,
  `generateBatchUploadUrls`, `createRunPodUploadInstructions`,
  `generateGpuResultKey`, `GPU_OUTPUT_CONTENT_TYPES`.

---

## Logging (`@oshun/logging`)

Source: `libs/shared/logging/src/`. Built on Pino.

`OshunLogger`, `createLogger({ service, version, level, transports })`,
`getLogger` / `setLogger` / `initializeLogger`, global `log`, `serializeError`.
Subpath modules: `transports` (console/file/HTTP/Elasticsearch/TCP), `sampling`
(fixed-rate / adaptive / priority / consistent-hash samplers), `middleware`
(Express, Fastify, Koa request loggers). Typed events via `createEventEmitter`.
Types: `Logger`, `LogContext`, `LogEntry`, `LoggerConfig`, transport configs,
sampler configs, `PrivacyConfig` (field redaction), `LOG_LEVELS`,
`LOG_LEVEL_NAMES`.

---

## Metrics (`@oshun/metrics`)

Source: `libs/shared/metrics/src/`. Prometheus + OpenTelemetry.

- **Instruments** — `Counter`, `Gauge`, `Histogram`, `Summary`; global helpers
  `counter`, `gauge`, `histogram`, `summary`.
- **Registry** — `OshunMetricsRegistry`, `createRegistry`, `getRegistry`,
  `setRegistry`, `initializeRegistry`.
- **Server** — `OshunMetricsServer`, `createMetricsServer`,
  `startMetricsServer`, `stopMetricsServer` (exposes `/metrics`).
- **Helpers** — `createHttpMetrics` / `recordHttpRequest`, `createDbMetrics` /
  `recordDbQuery`, `createCacheMetrics` / `recordCacheOperation`,
  `createAiMetrics` / `recordAiRequest`, `createQueueMetrics` /
  `recordJobCompletion`; `createTimer`, `measureDuration`.
- **Constants** — `HISTOGRAM_BUCKETS`, `SUMMARY_PERCENTILES`, `HTTP_METRICS`,
  `DB_METRICS`, `CACHE_METRICS`, `AI_METRICS`, `QUEUE_METRICS`.

---

## Distributed Tracing (`@oshun/tracing`)

Source: `libs/shared/tracing/src/`. OpenTelemetry-based.

- **Tracer** — `OshunTracer`, `LightweightTracer`, `createTracer`, `getTracer` /
  `setTracer` / `initializeTracer`.
- **W3C propagation** — `extractTraceContext`, `injectTraceContext`,
  `parseTraceparent`, `formatTraceparent`, trace-state and baggage helpers,
  `generateTraceId` / `generateSpanId` / `generateCorrelationId`.
- **Middleware** — `createExpressTracingMiddleware`,
  `createFastifyTracingPlugin`, `createKoaTracingMiddleware`,
  `createHonoTracingMiddleware`, plus `createTracedFetch` /
  `addTraceContextToFetch` for outbound calls.
- **Decorators** — `withSpan`, `traceMethod`, `traceServiceCall`,
  `traceDatabaseCall`, `traceExternalApiCall`, `traceMessage`, `traceJob`,
  `traceAiCall`, `traceBatch`, `traceWithRetry`.
- **AWS X-Ray** — `parseXRayHeader`, `formatXRayHeader`, X-Ray↔OTel trace-id
  conversion, `createXRayTracerConfig`, ECS metadata fetch, `toXRayAnnotations`.
- **Types** — branded `TraceId` / `SpanId` / `CorrelationId`; `SpanAttributes`,
  `HttpSpanAttributes`, `DbSpanAttributes`, `RpcSpanAttributes`, `SpanKind`,
  `SpanStatus`, `Sampler`, `TracerConfig`, `TracingMiddlewareConfig`.

---

## HTTP Client (`@oshun/http-client`)

Source: `libs/shared/http-client/src/`.

- **Client** — `HttpClient`, `createHttpClient`, `createSimpleHttpClient`,
  `createResilientHttpClient`, `createHttpError`.
- **Circuit breaker** — `CircuitBreaker`, `CircuitBreakerRegistry`,
  `CircuitOpenError`; `CircuitState` is `CLOSED | OPEN | HALF-OPEN`.
- **Retry** — `RetryPolicy`, `retry`, `retryWithAbort`, `withRetry`,
  `calculateBackoffDelay`, `isRetryableError`, preset policies
  (`defaultRetryPolicy`, `aggressiveRetryPolicy`, `conservativeRetryPolicy`,
  `noRetryPolicy`).
- **Interceptors** — `InterceptorChain` and factories for auth, logging, timing,
  correlation-id, base-url, default-params, user-agent, JSON content-type,
  retryable-error interceptors.
- **Timeout** — `TimeoutController`, `withTimeout`, `createTimeoutSignal`,
  `combineSignals`, deadline helpers.
- **Idempotency** — `IdempotencyMiddleware`, `createIdempotencyFingerprint`,
  `hashIdempotencyFingerprint`; idempotency-specific error classes.
- **Tenant context** — `runWithTenantContext`, `getTenantContext`,
  `createTenantPropagationInterceptor`, `injectTenantHeader`;
  `TENANT_ID_HEADER`, `MAX_TENANT_ID_LENGTH`.
- **SSRF guard** — `assertUrlAllowed`, `assertResolvedAddressAllowed`,
  `makeSsrfSafeLookup`, `classifyIp` / `classifyIpv4` / `classifyIpv6`,
  `isUnsafeIpClass`, `SsrfDeniedError`; `SsrfPolicy`, `SsrfDenialReason`.
- **Tracing** — `HttpTracing`, `tracedRequest`, `createTracingInterceptors`,
  `createTraceParent`.
- **Defaults** — `DEFAULT_RETRY_CONFIG`, `DEFAULT_CIRCUIT_BREAKER_CONFIG`,
  `DEFAULT_TIMEOUT_CONFIG`, `DEFAULT_CONNECTION_POOL_CONFIG`.

---

## Rate Limiting (`@oshun/rate-limit`)

Source: `libs/shared/rate-limit/src/`. Redis-backed (`ioredis`).

- **Limiters** — `SlidingWindowRateLimiter`, `FixedWindowRateLimiter`,
  `TokenBucketRateLimiter`, `InMemoryRateLimiter`, `GracefulRateLimiter`
  (Redis-failure fallback), `AdaptiveRateLimiter` (load-aware),
  `RequestThrottler`, plus `ExemptRateLimiter` / `ExemptionManager` (Redis or
  in-memory exemption stores) and `MonitoredRateLimiter`.
- **Middleware** — `createRateLimitMiddleware`, `createUserRateLimitMiddleware`,
  `createApiKeyRateLimitMiddleware`, `createEndpointRateLimitMiddleware`,
  `createRateLimitWithBypassMiddleware` with `BypassRule` / `checkBypass`.
- **Monitoring** — `AlertManager`, `createDefaultAlertRules`,
  `checkRateLimitHealth`, `metricsToSnapshot`.
- **Quotas** — `QuotaTracker`, `InMemoryQuotaStore`, `dayBucket`, `monthBucket`
  (daily/monthly budget counters).
- **Abuse controls** — `applyAbuseControls`, `applyPaginationCap`,
  `assertPayloadSize`, `assertArrayFieldLength`, `assertStringFieldLength`,
  `assertQueryCostBudget`, `estimateQueryCost`; `DEFAULT_SURFACE_LIMITS`.
- **Types** — `RateLimitResult`, `RateLimitInfo`, `RateLimiterInterface`,
  `ThrottleConfig`, `QuotaTier`, `QuotaStatus`, `AbuseSurface`, `AbuseDecision`.

---

## WebSocket (`@oshun/websocket`)

Source: `libs/shared/websocket/src/`. `ws`-based, Redis pub/sub for scaling.

- **Server** — `YemayaWSServer`, `createWSServer(httpServer, redis, config)`;
  attaches at a configurable path with optional JWT auth on upgrade.
- **Rooms** — `RoomManager`, `COMMON_CHANNEL_CONFIGS`; channel subscribe/
  unsubscribe with presence members.
- **Message queue** — `MessageQueue` for buffered delivery.
- **Connection limits** — `ConnectionLimiter`, `LIMIT_CLOSE_CODES`.
- **Message rate limiting** — `MessageRateLimiter`, `MESSAGE_RATE_PRESETS`.
- **Connection state** — `ConnectionStateManager` with quality tracking.
- **Redis adapter** — `RedisAdapter` for horizontal scaling (cross-node
  broadcast, sticky-session key generation).
- **Metrics** — `WSMetrics`.
- **Types** — `WSMessage`, `WSClient`, `WSServerConfig`, `ClientInfo`,
  `MessageType`, `AuthPayload`, `BroadcastPayload`, etc.

---

## Authentication and Identity

### `@oshun/auth`

Source: `libs/shared/auth/src/`. Storage-agnostic full auth service.

- **`AuthService`** (`createAuthService`) — registration, login, token
  management, account lockout, RBAC; injected `IUserRepository`,
  `ITokenRepository`, `IOAuthRepository`, `IAuditRepository`.
- **Lockout** — `AccountLockoutManager`, `DistributedLockoutManager` with
  `ILockoutStore`; `DEFAULT_LOCKOUT_CONFIG`.
- **RBAC** — `ROLE_HIERARCHY`, `ROLE_PERMISSIONS`, `ALL_PERMISSIONS`,
  `hasPermission`, `hasMinimumRole`, `hasAllPermissions`, `hasAnyPermission`.
- **Middleware** — framework-agnostic `authenticate` / `authorize` plus
  Express-style `createAuthMiddleware`, `requireAuth`, `optionalAuth`,
  `requireRole(s)`, `requirePermissions`, `requireAnyPermission`,
  `requireOwnership`, `denySelf`; token extractors for headers and cookies.
- Re-exports the full `@oshun/auth-primitives` surface.

### `@oshun/auth-primitives`

Source: `libs/shared/auth-primitives/src/`.

- **JWT** — `JwtService`, `createJwtService`, `createHmacJwtService`,
  `createRsaJwtService`; `KeyAlgorithm` (HS256/RS256/ES256), `JwkEntry`, `Jwks`,
  `DecodedToken`, `JwtClaims`, `JwtPayload`, `JwtHeader`; `DEFAULT_JWT_CONFIG`.
- **Session** — `SessionManager`, `InMemorySessionStore`, `generateSessionId`,
  `parseUserAgent`; `DeviceInfo`, `SessionStore`, `DEFAULT_SESSION_CONFIG`.
- **Token refresh** — `TokenRefreshManager`, `InMemoryRefreshTokenStore`,
  `generateTokenId`, `generateFamily` (rotation-family reuse detection).
- **Password** — `PasswordHasher`, `PasswordValidator`, `generatePassword`,
  `DEFAULT_PASSWORD_POLICY`.
- **API keys** — `ApiKeyManager`, `InMemoryApiKeyStore`, `extractApiKey`,
  `maskApiKey`.
- **OAuth client registry** — `OAuthClientRegistry`, `InMemoryOAuthClientStore`,
  `OAuthClientType`, `OAuthClientAuthMode`.
- **OAuth token revocation** (RFC 7009) — `createRevocationHandler`,
  `InMemoryAccessTokenBlocklist`.
- **Token-lifecycle audit** — `TokenAuditEmitter`, `InMemoryTokenAuditSink`.
- **Tenant isolation** — `TenantIsolationGuard` with denial/impersonation
  events.
- **TOTP / step-up** — `totp`, `hotp`, `verifyTotp`, `generateTotpSecret`,
  `buildProvisioningUri`, `generateBackupCodes`, `verifyBackupCode`,
  `isStepUpFresh`, `DEFAULT_STEP_UP_TTL_SECONDS`.
- **Platform roles** — `PlatformRole`, `PlatformScope`, `AdminWorkspace` enums;
  `authorize`, `effectiveScopes`, `scopesForWorkspace`, `parseScope`,
  `requiresStepUp`; `ALL_PLATFORM_ROLES`, `ALL_PLATFORM_SCOPES`,
  `DEFAULT_ROLE_SCOPES`, `SENSITIVE_SCOPES`.

### `@oshun/identity`

Source: `libs/shared/identity/src/`. Verify-only identity for gateways.

`JwtService` / `createJwtService` (verify-focused); middleware `authenticate`,
`authenticateService`, `createAuthChecker`, `extractBearerToken`,
`extractApiKey`; role helpers `hasRole`, `hasPermissions`, `hasAnyPermission`,
`getPermissionsForRole`; mTLS helpers `parsePeerCertificate`,
`verifyPeerIdentity`, `verifyForwardedClientCert` (`MtlsPolicy`,
`PeerIdentity`); `node:http` helpers `enforceHttpAuth`, `jwtServiceFromEnv`;
plus `v2-account-binding` and `v2-entitlement-claims` modules.

---

## API Gateway (`@oshun/traefik-config`)

Source: `libs/shared/traefik-config/src/`. Generates **Traefik v3**
configuration — not a runtime server.

`ServiceBuilder` / `service()`, `RouteBuilder` / `route()`,
`GatewayConfigBuilder` / `gateway()`, `createDefaultGatewayConfig`. Domain
registries `YEMAYA_SERVICES`/`ROUTES`, `ISIS_*`, `SOPHIA_*`, `HATHOR_*`,
`BELLONA_*`, `LILITH_*`, `SHARED_*`, with `getAllServices()` / `getAllRoutes()`.
Generators `generateStaticConfig`, `generateDynamicConfig`,
`generateTraefikConfigs` produce `TraefikStaticConfig` / `TraefikDynamicConfig`.

---

## Service Discovery (`@oshun/service-discovery`)

Source: `libs/shared/service-discovery/src/`. Redis-based registry.

`ServiceDiscovery` / `createServiceDiscovery`; `register(...)` returns an
`instanceId` heartbeating a TTL, `getServiceUrl(...)`, `watch(...)`. Load
balancing strategies are configurable (`LoadBalancingStrategy`). Pluggable
backends: `RedisRegistryBackend`, `DnsRegistryBackend`, `ConsulRegistryBackend`.
`HashRing` for consistent hashing; `probeInstance` for health probing.
`ServiceNames` constant of canonical identifiers.

---

## Health Checks (`@oshun/health`)

Source: `libs/shared/health/src/`. Kubernetes-compatible.

`HealthManager` / `createHealthManager` aggregates registered checks into a
`HealthReport` (`HealthStatus`: healthy/degraded/unhealthy; `BuildInfo`);
helpers `healthy`, `degraded`, `unhealthy`. `ProbeManager` /
`createProbeHandlers` for separate liveness/readiness probes.
`DependencyAggregator` with `createDatabaseCheck`, `createCacheCheck`,
`createQueueCheck`, `createApiCheck`, `createServiceCheck`. Constants:
`DEFAULT_HEALTH_TIMEOUT`, `DEFAULT_CACHE_DURATION`, `DEFAULT_FAILURE_THRESHOLD`,
`DEFAULT_RECOVERY_THRESHOLD`, `DEFAULT_CHECK_INTERVAL`.

---

## Security (`@oshun/security`)

Source: `libs/shared/security/src/`.

- **Audit logging** — `OshunAuditLogger` / `createAuditLogger` with
  `MemoryAuditStore` / `DatabaseAuditStore`; actor helpers `anonymousActor`,
  `userActor`, `serviceActor`, `systemActor`, `auditTarget`. Batched writes;
  query filters by actor/target/time/type. Types `AuditEntry`, `AuditEventType`,
  `AuditSeverity`, `AuditOutcome`.
- **Security scanning** — `BuiltinSecurityScanner`, `ClamAVScanner`,
  `createBuiltinScanner`; `scanFile` / `scanText` detect threats (`ThreatType`,
  `ThreatSeverity`, `ScanResult`, `Threat`).
- **Secret management** — `OshunSecretManager` / `createSecretManager` with
  `MemorySecretStore` / `DatabaseSecretStore`; create/get/rotate secrets,
  caching, auto-rotation. Types `Secret`, `SecretType`, `RotationConfig`,
  `RotationResult`.

---

## AI Integration (`@oshun/ai`)

Source: `libs/shared/ai/src/`.

- **Providers** — `AnthropicProvider`, `OpenAIProvider`, `GoogleProvider`,
  `XAIProvider`, `OllamaProvider`, each with a `create*Provider` factory; all
  implement `LLMProviderInterface` over `ChatCompletionRequest` /
  `ChatCompletionResponse`. Content blocks: text, image, tool-use, tool-result.
- **Routing** — `ModelRouter` (rule-based), `QualityRouter` (task/cost/speed
  weighted, `TASK_TYPE_PROFILES`, `MODEL_PROFILES`), `MLRouter`
  (history-trained); config factories `createCostOptimizedConfig`,
  `createQualityOptimizedConfig`, `createABTestConfig`.
- **Prompt templates** — `PromptTemplate`, `TemplateLibrary`,
  `createDefaultTemplateLibrary`, `CREATIVE_TEMPLATES`, `TECHNICAL_TEMPLATES`.
- **Response cache** — `ResponseCache`, `CachedProvider`,
  `InMemoryCacheStorage`, `generateCacheKey`.
- **Usage tracking** — `UsageTracker` with `BudgetConfig` / `BudgetStatus`,
  per-provider/model usage records.
- **Advanced** — `BatchProcessor`, `PromptCompressor`, `PromptABTester`,
  `PromptSanitizer` (injection detection), `PromptDebugger`.
- **Local LLM** — `ModelManager`, `InferenceEngine`, GGUF tooling (`GGUFParser`,
  `QuantizationAnalyzer`, `ConversionManager`, `QUANTIZATION_PROFILES`), VRAM
  estimation, `createLocalLLMStack`.

---

## Advanced AI (`@oshun/ai-advanced`)

Source: `libs/shared/ai-advanced/src/`.

`AdapterManager` (pluggable specialized-provider adapters,
`createBuiltInAdapters`); `BenchmarkManager` (`getStandardBenchmarkTasks`);
`ModelSelector` (benchmark-driven recommendation); `EdgeManager` with
`OnnxRuntimeProvider` / `MockOnnxRuntime` for on-device inference;
`ResearchManager` with `ArxivApiProvider` and `HuggingFaceApiProvider`. Each
manager ships an `InMemory*Storage` provider.

---

## GPU Dispatch

### `@oshun/gpu-dispatcher`

Source: `libs/shared/gpu-dispatcher/src/`.

`GpuDispatcher` / `createGpuDispatcher` —
`createJob({ type, input, priority })`, `waitForJob`, event callbacks
(`job:completed`, …), `startProcessing`. `InMemoryJobStore`. Resilience:
`CircuitBreaker` / `CircuitBreakerManager`, `CostTracker`
(`DEFAULT_GPU_PRICING`, budgets), `ResultValidator` (image/video/ audio
validation configs), `FallbackManager` (endpoint health + selection), retry
policies, `TimeoutManager` with per-job-type timeouts
(`IMAGE_GENERATION_TIMEOUT`, `VIDEO_GENERATION_TIMEOUT`, …), GPU metrics, and
trace-context injection. Error classes: `DispatcherError`, `JobNotFoundError`,
`EndpointNotFoundError`, `DispatchFailedError`, `QueueFullError`,
`BudgetExceededError`, `JobTimeoutError`, etc.

### `@oshun/runpod-client`

Source: `libs/shared/runpod-client/src/`. Typed RunPod Serverless REST client.

`RunPodClient` / `createRunPodClient` — `runAsync`, `runSync`, `runAndWait`,
`getJobStatus`, `cancel`, `purgeQueue`, `health`, `stream`. `JobStatus` covers
`IN_QUEUE`/`IN_PROGRESS`/`COMPLETED`/`FAILED`/`CANCELLED`/`TIMED_OUT`.
`WebhookConfig`, `S3OutputConfig`, `ExecutionPolicy`. Polling utilities
`pollUntilComplete`, `pollMultiple`, `addJitter`. Error classes `RunPodError`,
`AuthenticationError`, `RateLimitError`, `TimeoutError`, `JobFailedError`,
`PollingTimeoutError`, etc.

---

## Cryptography (`@oshun/crypto`)

Source: `libs/shared/crypto/src/`. Wrappers over `@noble/hashes`,
`@noble/curves`, `@noble/ciphers` — no in-house crypto.

Hashing: `sha256`, `sha512`, `keccak256`, `blake3`. Signing: secp256k1 and
ed25519 sign/verify (secp256k1 also recover). AEAD: `aesGcm`, `chacha20Poly1305`
encrypt/decrypt. KDFs: `hkdf`, `pbkdf2`, `scrypt`, `argon2id`. `ecdh` key
agreement. `randomBytes`. `Uint8Array` is the canonical buffer type. Additional
`keystore/` and `secrets/` modules.

---

## Testing Utilities (`@oshun/testing`)

Source: `libs/shared/testing/src/`.

- **Mocks** — `createMockLogger`, `createMockHttpClient`,
  `createMockRedisClient`, `createMockDatabaseClient`, `createMockEventEmitter`,
  `createMockTimers`.
- **Fixtures** — random generators (`randomString`, `randomEmail`, `randomUUID`,
  …), `createFixtureFactory`, user/content factories, `withTimestamps`,
  `withId`.
- **Helpers** — assertions (`assertDefined`, `assertRejects`, `assertAppError`,
  `assertApiSuccess`, `assertResultOk`/`Err`, …), async utilities (`waitFor`,
  `retryUntil`, `createDeferred`, `measureTime`, `assertExecutesWithin`),
  console capture, `createTestContext`.
- **Containers** — `PostgresTestContainer`, `RedisTestContainer`,
  `ContainerManager` for Docker-backed integration tests.
- **Config** — `createVitestConfig`, `createServiceVitestConfig`,
  `createIntegrationVitestConfig`, coverage thresholds, workspace-alias
  utilities, setup templates.
- **Fuzz** — malicious-input corpora (`MALICIOUS_CORPUS`, `UPLOAD_CORPUS`,
  `IMPORT_CORPUS`, `MARKDOWN_CORPUS`, `SEARCH_CORPUS`, `PROMPT_CORPUS`,
  `WEBHOOK_CORPUS`), `runFuzzCorpus`, adversarial-string generators.

---

## Infrastructure Primitives (`@oshun/infrastructure`)

Source: `libs/shared/infrastructure/src/`. (The source header still reads
`@yemaya/infrastructure`; the published package name is
`@oshun/infrastructure`.)

Three manager families with provider interfaces and both in-memory and real
implementations:

- **Performance** — `PerformanceManager` with `NodeAssetLoader`,
  `NodeMemoryMonitor`, `WorkerThreadTaskExecutor`, `SystemGPUProvider`; types
  `LazyLoadConfig`, `LODConfig`, `MemoryBudget`, `MemoryPressure`,
  `BackgroundTask`, `GPUComputeJob`.
- **Security** — `SecurityManager` with `NodeCryptoEncryptionProvider`,
  `CryptoAPIKeyProvider`; types `EncryptionConfig`, `EncryptedData`,
  `Vulnerability`, `SecurityScanResult`, `SecurityAuditLog`.
- **Monitoring** — `MonitoringManager` with `WebhookAlertingProvider` and
  in-memory tracing/metrics/alert/dashboard providers; types `Trace`, `Span`,
  `Metric`, `Alert`, `AlertRule`, `Dashboard`, `AnalyticsEvent`.

---

## Data Migration (`@oshun/migration`)

Source: `libs/shared/migration/src/`.

`MigrationRegistry`, `MigrationRunner` / `createMigrationRunner`; checkpoint
stores `FileCheckpointStore` / `MemoryCheckpointStore`; ID-mapping stores
`FileIdMappingStore` / `MemoryIdMappingStore`. Oshun V1 shared-object
sequencing: `OSHUN_V1_SHARED_OBJECT_FRAMEWORK_TASKS`,
`OSHUN_V1_SHARED_OBJECT_GLOBAL_VERIFICATION_GATES`,
`OSHUN_V1_SHARED_OBJECT_MIGRATION_STEPS`,
`buildOshunV1SharedObjectMigrationPlan`,
`createOshunV1SharedObjectMigrationRegistry`. Cross-domain reference resolution
and an HTTP resolver are present in `cross-domain-reference.ts` /
`http-resolver.ts`.

---

## Release Management (`@oshun/release-management`)

Source: `libs/shared/release-management/src/`. Depends on `zod`.

Surface-scoped rollback safety (V1/TODOS.md §28.8). `ReleaseSurface` enum covers
six v1 surfaces (shell, admin, grounding, assistant, persona, generation);
`RollbackMechanism` enum; Zod schemas `ReleaseSchema`, `RollbackPlanSchema`,
`RollbackStepSchema`, `SemverSchema`. Engine functions
`assertReleaseHasValidPlan`, `checkCoverage`, `loadAndValidatePlan`,
`planExecutionGraph`, `runRehearsal`. Canonical plans `ADMIN_ROLLBACK_PLAN`,
`ASSISTANT_ROLLBACK_PLAN`, `GENERATION_ROLLBACK_PLAN`,
`GROUNDING_ROLLBACK_PLAN`, `PERSONA_ROLLBACK_PLAN`, `SHELL_ROLLBACK_PLAN`,
aggregated in `CANONICAL_ROLLBACK_PLANS`.

> Scope note: this package implements rollback-plan validation and rehearsal
> only. It does not implement semantic-version bumping, changelog generation,
> beta-cohort management, or app-store submission workflows.

---

## Documentation Tooling (`@oshun/documentation`)

Source: `libs/shared/documentation/src/`.

The implemented surface is the **architecture-documentation** module
(`architecture/architecture.ts`): typed models for `ArchComponent`,
`ArchConnection`, and related structures, with enums `ArchComponentType`
(`service`, `library`, `database`, `queue`, `gateway`, `cache`, `external`,
`ui`), `DiagramFormat` (`mermaid`, `plantuml`, `d2`, `dot`, `ascii`), and
`ConnectionType` (`sync`, `async`, `event`, `stream`, `grpc`, `rest`, `graphql`,
`websocket`). The package `package.json` description mentions API references,
tutorials, and a certification system; those are **not present in the source**
and should be treated as planned, not implemented.

---

## Domain-Specific Shared Libraries

These packages live under `@oshun/*` because they are consumed across multiple
domains and apps, but they carry domain-shaped logic rather than generic
infrastructure. The boundary for inclusion in `shared` rather than a domain
package is: does more than one domain import it? If yes, it lives here.

- **`@oshun/vision-llm`** — convenience wrapper around `IsisLLMClient` for
  vision-locate tasks; owns prompt shaping, image normalisation, structured-
  output parsing, and the `VisionLocateResult` envelope. Per
  `docs/releases/p2/vision-llm-strategy.md` (V1-P2-0064). Exports
  `OshunVisionLLMClient` and the `Vision*` type family.
- **`@oshun/layout-analyzer`** — document layout analysis via the canonical
  vision LLM into the PubLayNet region taxonomy (`DOCUMENT_REGION_CLASSES`).
  `OshunLayoutAnalyzer`; mAP@0.5 evaluation (`computeMeanAveragePrecision`,
  `iou`). V1-P2-0064/0066.
- **`@oshun/ocr`** — canonical OCR client with three explicit tiers
  (`tier1_tesseract` Tesseract.js WASM, `tier2_vision_llm`, `tier3_cloud_ocr`).
  `OshunOCRClient`, `TesseractOCRBackend`. Tiers do not silently fail over.
  V1-P2-0060.
- **`@oshun/ml`** — `OshunMLRuntime`: ONNX model loading with SHA-256
  verification and execution-provider preference (`webgpu`/`webnn`/`wasm`);
  `loadModel`, `tensor`, `RuntimeAdapter`, `benchmark`. V1-P2.
- **`@oshun/native-libs`** — typed wrappers + acceptance tests over pinned
  audio/video/image native deps (`sharp`, `ffmpeg-static`, `fft.js`,
  `pdf-parse`, `mammoth`, `cheerio`, `pixelmatch`, `pdf-lib`, `imghash`, `pako`,
  `protobufjs`, `@peculiar/x509`). Helpers for PNG re-encode, FFT power
  spectrum, PDF/DOCX text extraction, HTML parsing, pixel diff, perceptual hash,
  gzip, protobuf varints, X.509 parsing, FFmpeg path resolution.
  V1-P2-0110..0121.
- **`@oshun/crypto`** — see Cryptography section above (V1-P2-0173).
- **`@oshun/audit-platform`** — canonical platform-wide audit event ingestion,
  append-only storage, and investigation queries. Validates every event against
  `CanonicalPlatformAuditEventSchema` from `@oshun/contracts` (ADR-0023,
  V1-GRC-009). `AuditEventIngestService`, `InMemoryCanonicalAuditEventStore` (no
  update/delete), agent-tool audit helpers, retention-tag enforcement, and V2
  audit-publication helpers.
- **`@oshun/data-residency`** — V1-PRIV-018 region and residency enforcement.
  `ResidencyEnforcementService` reads rule tables from `@oshun/contracts` and
  emits canonical audit events; `createDsrResidencyRoutingDecision`,
  `resolveHomeZoneFromClaim`, residency routing headers/context.
- **`@oshun/region-rules`** — V2 regional content rules
  (`v2-regional-content-rules`).
- **`@oshun/review-persistence`** — canonical persistence layer for Oshun review
  packages, mapping `@oshun/contracts` Zod contracts and the `ReviewPackage`
  Prisma model into a validated API (ADR-0023, ADR-0029, V1-GRC-001).
  `assembleReviewPackage`, `InMemoryReviewPackageRepository`, stage-graph
  persistence (`assembleStageGraph`, `InMemoryReviewStageGraphRepository`),
  template registry.
- **`@oshun/inbound-integrations`** — typed adapters for inbound external
  systems: LMS, OneRoster, identity, calendar, payment, telemetry, BYOM
  (bring-your-own-model), notification, and health modules.
- **`@oshun/tara-live-class-booking`** — Tara live-class booking primitives
  shared by Lilith and Oshun web/mobile surfaces: `TaraLiveClassListing`,
  `TaraLiveClassBookingInput`, `TaraLiveClassPaymentReceipt`, lineage disclosure
  types with citation trails.

---

## Environment Variables

The table below lists the representative environment variables read by shared
libraries. All variables are loaded and validated through `@oshun/config`
loaders at service startup. Missing or malformed required variables raise a
clear startup error from `validateConfig` — services never start with a
zero-value or undefined configuration.

| Variable                             | Library                                                                                                                 | Purpose                |
| ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | ---------------------- |
| `DATABASE_URL`                       | `@oshun/database`, `@oshun/config`                                                                                      | PostgreSQL connection  |
| `DB_HOST` / `DB_PORT` / …            | `@oshun/database`, `@oshun/config`                                                                                      | Discrete DB parameters |
| `REDIS_URL`                          | `@oshun/cache`, `@oshun/queue`, `@oshun/rate-limit`, `@oshun/event-bus`, `@oshun/websocket`, `@oshun/service-discovery` | Redis connection       |
| `STORAGE_ENDPOINT` / `MINIO_*`       | `@oshun/storage`, `@oshun/config`                                                                                       | S3 / MinIO endpoint    |
| `STORAGE_ACCESS_KEY` / `_SECRET_KEY` | `@oshun/storage`                                                                                                        | S3 credentials         |
| `JWT_SECRET` / `JWT_REFRESH_SECRET`  | `@oshun/auth`, `@oshun/config`                                                                                          | JWT signing keys       |
| `ANTHROPIC_API_KEY`                  | `@oshun/ai`, `@oshun/config`                                                                                            | Anthropic API key      |
| `OPENAI_API_KEY`                     | `@oshun/ai`, `@oshun/config`                                                                                            | OpenAI API key         |
| `GOOGLE_AI_API_KEY`                  | `@oshun/ai`, `@oshun/config`                                                                                            | Google AI API key      |
| `RUNPOD_API_KEY`                     | `@oshun/runpod-client`, `@oshun/gpu-dispatcher`                                                                         | RunPod Serverless key  |
| `LOG_LEVEL` / `LOG_FORMAT`           | `@oshun/logging`, `@oshun/config`                                                                                       | Logger configuration   |
