Domain · Features

Contracts Domain — Features

When multiple domains reference the same concept — a User, an Asset, a Project — they import the canonical type from here rather than each defining their own.

5sections15 minread

On this page
Supporting documentation. This domain also carries 3 operational supporting docs under docs/domains/contracts/ (API notes, ADRs, deep topic guides) — reconciled here by linking, kept beside the code as supporting material rather than a second canonical source (§2, §13).

@oshun/contracts is the shared contract library for the Oshun platform. It defines the canonical data schemas, the event envelope, the per-domain event payloads, and the Zod runtime-validation utilities that keep cross-domain communication type-safe. Every domain that emits or consumes events, or shares an entity type across a service boundary, imports from here rather than defining its own equivalent. Without a contracts library, each domain invents a slightly different User, Asset, or event envelope, and integrating domains becomes a mapping exercise instead of a direct import. The library has two primary subpaths — @oshun/contracts/common for entity schemas and @oshun/contracts/events for the event envelope and domain event types — plus additional per-domain subpaths (llm, aja, arete, tara, nyx, metis, nisaba, veritas, v3, tts).

The directory libs/contracts/ also hosts several separate contract libraries — @iris/contracts, @psyche/contracts, @concordia/contracts, @freya/contracts, @contracts/brigid, @contracts/cybele, @contracts/saraswati, and the scaffold @maat/contracts — described in the final section.


Common Data Schemas (@oshun/contracts/common)#

When multiple domains reference the same concept — a User, an Asset, a Project — they import the canonical type from here rather than each defining their own. This ensures that serialization round-trips produce the same shape everywhere, and that a schema change in one place propagates automatically to all consumers. Every entity is defined as a Zod schema; the TypeScript type is z.infer-ed from it, so compile-time types and runtime validators are always in sync.

Core Entities#

These are the most widely-shared entity types in the platform. Most domain API handlers, database adapters, and event payloads reference at least one of them.

  • User — Canonical user record. The full UserSchema carries id (UUID), email, nullable username, firstName, lastName, displayName, nullable bio/avatarUrl, a role (user/creator/admin/super_admin), a status (pending/active/suspended/deleted), emailVerified, contact and profile fields, lastLoginAt, and createdAt/updatedAt. UserSummarySchema is the minimal embeddable form (id, displayName, avatarUrl); UserProfileSchema is the public profile view. Companion schemas cover preferences, stats, activity, and notifications.
  • Asset — Shared asset definition. AssetSchema carries a UUID id, name, filename, an asset-type enum (image, video, audio, model_3d, document, script, font, texture, material, animation, archive, other), a status enum, sizeBytes, mimeType, storage url, thumbnails, type-specific metadata, tags, version info, project/folder references, and — notably — optional license (AssetLicenseSchema) and provenance (AssetProvenanceSchema, including AI-generation details and a verification status). Used wherever generated content or uploads cross domain boundaries.
  • Project — Cross-domain project reference. ProjectSchema carries a UUID id, name, slug, a project-type enum (film, game, animation, commercial, …), status, visibility, thumbnails, tags, ProjectSettings, owner, organization, member/asset counts, and storage usage. Companion schemas cover members, invitations, comments (including spatial comment positions), and project activity.
  • Persona — AI persona definition shared across interaction domains. A large schema capturing role, lifecycle stage, approval status, supported modalities (text/voice/avatar/video), capabilities, a Big-Five personality model, a tone profile, disclosure rules, grounding rules, prompt templates, escalation triggers/targets, and content links.
  • Passage — Textual content block for scholarship. A passage carries text (with a format and reference scheme), provenance, translations, parallels, commentary, and annotations — shared across the contemplative-knowledge domains.
  • Source — Citation and source reference type. Covers source type, credibility tier (high/medium/low/unknown), contributors, partial dates, container, license, provenance, versions, formatted citations, and concept links.

AI and Knowledge Entities#

These entities are shared across the knowledge-layer domains (Sophia, Nisaba, Metis, Veritas) and are referenced in AI-pipeline workflows throughout the platform.

  • Concept — Knowledge concept node. ConceptSchema carries a UUID id, slug, name, summary, a category string, a complexity level (basic/intermediate/advanced), tags, and arrays of typed concept relationships and concept links.
  • Notebook — Research notebook entity. Aggregates notebook items, sections, and collaborators into a named research collection, and links to grounded-answer, grounded-report, evidence-pack, source-set, and citation-trail IDs.
  • ModelCard — AI model metadata: model type/format, source type, content rating, a safety class (safe/sensitive/restricted/blocked), review state, promotion decision, creator info, compute/carbon info, fairness metrics, bias info, and citations.
  • ModelVersion — Versioned model artifact: version status, format, engine, provider, deployment environment (preview/staging/production), file roles, scan status, deployment health, compatibility state, change type, and precision.

Compliance and Safety#

Consent and audit are treated as first-class cross-domain concerns rather than domain-specific features. This means every domain's consent flows produce a ConsentRecord with the same shape and the same lifecycle invariants enforced at schema level, and every audit trail entry is validated by the same canonical contract.

  • ConsentRecord — The platform's consent contract. ConsentRecordSchema governs a consent category (one of 20 — privacy, marketing, memory, voice, avatar, biometric, recording, …) for a typed subject and target, with a GDPR-style legal basis, a collection context, a verification block, permission grants, evidence, the full lifecycle-timestamp set, renewal fields, and a chronological history. Extensive validators enforce lifecycle-timestamp ordering and require verified verification plus traceable evidence for high-risk categories.
  • AuditEvent — Cross-domain audit trail entry. The legacy AuditEventSchema (in audit.ts) is permissive; the strict ADR-0023 contract CanonicalPlatformAuditEventSchema (in canonical-audit-event.ts, exported via the ./common/canonical-audit-event subpath) requires actor, action (dotted namespace), outcome, reason, trace identifiers, and target on every event, and is enforced at audit-platform ingestion.
  • Incident — Safety / operational incident documentation entity (IncidentSchema), used by moderation and safety-review workflows.
  • SupportCase — Support-ticket entity (SupportCaseSchema) shared between domains that generate support events and the platform's support tooling.

Creative and Content#

These entities are shared across domains that produce or handle creative media — voice synthesis, avatars, contemplative practices, and fact-checked content.

  • VoiceProfile — TTS voice synthesis profile: provider, origin, training status, gender/age category, style, use scopes, consent status, watermark status, safety controls, emotion presets, and a quality tier/grade.
  • Ritual — Cross-domain ceremonial/routine definition shared across the contemplative-knowledge domains (tara, arete, veritas, nyx, nisaba). Describes a kind, cadence, schedule, context signals, and an ordered set of ritual components.
  • Practice — Repeatable practice definition shared across the same five domains. Records a practice kind (meditation, breathwork, journaling, …), difficulty, intensity, cues, steps, tracking mode, safety metadata, and grounding mode.
  • AvatarPack — Avatar customization set: provider, origin, embodiment, style, render quality, training status, model format, still variants, preview video, consent status, watermark status/method, and a deception-risk level.
  • Claim — Factual claim type used in fact-checking. ClaimSchema carries a statement, a claim type, a verdict, a verification status, confidence and checkworthiness scores (0–1), speaker info, evidence, and typed claim-to-claim debate links.
  • EvidencePack — A collection of evidence used to package grounded research results; companion files cover evidence-pack assembly and assembly evaluation.

Workflows and Operations#

These entities coordinate long-running processes, platform governance, and AI session continuity across domain boundaries.

  • WorkflowTemplate — Reusable workflow definition (WorkflowTemplateSchema).
  • PolicyBundle — Content and governance policy definition (PolicyBundleSchema).
  • ReviewPackage — Peer-review submission (ReviewPackageSchema); review-stage-graph.ts defines the review-stage graph.
  • ProvenanceBundle — Content-provenance lineage for asset attribution (ProvenanceBundleSchema), with helper functions in provenance-bundle-helpers.ts.
  • ContinuityState — Assistant session continuity state: status, momentum, surface, journey kind/status, resume mode, reminders, checkpoints, and assistant mode (text/voice/multimodal).
  • MemoryScope — Memory-scope definition: scope kind, owner type, storage class, content type, sensitivity, privacy boundary, retention action, sharing/sync/consent modes, review state, and share targets.
  • Collection — Generic ordered collection of cross-domain content (CollectionSchema).
  • Tenant — Multi-tenant organisation entity (TenantSchema).

Admin, Privacy, and Governance Contracts#

Beyond the canonical entities above, common/ contains roughly 120 further schema files — the bulk of the directory. These define typed contracts for the admin console and compliance surfaces, ensuring that the admin UI, moderation workflows, and data-governance pipelines all share the same request/response shapes as the backend APIs.

The 120 files span approximately four categories. The admin console contracts comprise roughly 80 admin-* files covering moderation, inbox, notifications, incident management, model and persona governance/registry, editorial, billing, privacy/DSAR/retention/deletion workflows, research-integrity review, voice/avatar/watermark verification, bulk operations, readiness dashboards, universal search, copilot surfaces, and more — each is a typed Zod contract for the corresponding admin UI / API surface. The safety and moderation contracts (safety-* files) cover severity, appeals, crisis, repeat-offender, content policy, voice/avatar evaluations, and unified safety review. The privacy and data-rights contracts cover consent controls, data export/deletion, retention/residency/restore rules, and entitlements. Finally, the retrieval-grounded research contracts define the grounded answer/report, citation integrity, hallucination-risk, source sets, and unsupported-claim detection schemas shared by Sophia, Veritas, Nisaba, and Metis.


Event Schemas (@oshun/contracts/events)#

All cross-domain events use a typed envelope. The envelope carries the metadata needed for event routing, deduplication, and tracing, without the payload knowing anything about the infrastructure it travels through. This separation means a consumer can validate and route an event using only the envelope fields, and only deserialize the payload once it has confirmed the event type is one it handles.

Event Envelope#

The EventEnvelopeSchema wraps every event published on the event bus. The fields below are present on every event regardless of domain:

  • id — UUID v4 (UUIDSchema). Uniquely identifies the event for deduplication and idempotency checks.
  • type — Dotted domain.action string (e.g. isis.asset.generated), validated against a regex. The primary dispatch key for subscribers.
  • source — Source domain, one of 13 enum values (tara, isis, sophia, hathor, bellona, yemaya, lilith, aphrodite, nyx, psyche, veritas, concordia, system).
  • timestamp — ISO 8601 creation timestamp.
  • version — Semver schema-version string for the payload, defaulting to 1.0.0, so consumers can handle multiple payload versions during rolling deployments.
  • priority — Event priority (low/normal/high/critical, default normal).
  • payload — The event-specific payload (z.unknown() on the base envelope; typed via createEventSchema).
  • metadata — Optional EventMetadataSchema carrying correlationId, causationId, traceId, spanId, userId, projectId, organizationId, sessionId, requestId, ipAddress, userAgent, and a custom map. Correlation and causation IDs live here, not on the envelope root.
  • aggregate — Optional { type, id, version } block for event-sourced aggregates.

Typed per-event schemas are produced by createEventSchema(eventType, source, payloadSchema), which extends the base envelope with a literal type/source and a typed payload. The envelope file also defines publish/consume infrastructure contracts: EventPublishOptionsSchema, EventPublishResultSchema, EventConsumerConfigSchema, and DeadLetterEventSchema.

Domain Event Types#

AllEventTypes (in events/index.ts) is the central map of every event-type string. It currently registers 181 event types across 12 domains. Each domain module defines, per event, a *PayloadSchema, a *EventSchema, and an *EventTypes constant.

Isis Events (Generative Factory) — 10 types#

These events drive the AI generation workflow from job submission through to asset delivery. Payloads carry job IDs, a generation type (image/video/ audio/model_3d/texture/animation/avatar/world), workflow names, output asset references, and cost/GPU metrics on completion. The 10 types are: isis.job.queued, isis.job.started, isis.job.progress, isis.job.completed, isis.job.failed, isis.job.cancelled, isis.asset.generated, isis.workflow.registered, isis.workflow.updated, isis.model.loaded.

Sophia Events (Knowledge Engine) — 9 types#

sophia.document.ingested, sophia.document.updated, sophia.document.deleted, sophia.index.updated, sophia.index.rebuilt, sophia.search.performed, sophia.entity.extracted, sophia.relation.discovered, sophia.citation.created.

Hathor Events (World Builder) — 7 types#

hathor.world.created, hathor.world.published, hathor.world.validated, hathor.element.added, hathor.narrative.generated, hathor.simulation.started, hathor.simulation.completed.

Bellona Events (Engine/Build) — 8 types#

bellona.session.started, bellona.session.ended, bellona.build.started, bellona.build.progress, bellona.build.completed, bellona.export.started, bellona.export.ready, bellona.asset.synced.

Yemaya Events (Creative Studio) — 12 types#

Project lifecycle events (created/updated/archived), member events (joined/left), asset events (uploaded/processed/approved/rejected), comment events (created/resolved), and yemaya.session.joined.

Lilith Events — 10 types#

Meditation events (lilith.meditation.started/completed/generated), journal events (created/updated), session events (started/ended), lilith.progress.updated, lilith.teacher.interaction, lilith.content.downloaded.

Tara Events (Contemplative Practice) — 1 type#

A single event, tara.ritual.completed. Its payload is deliberately rich: it carries ritual identity, completion metrics, step accounting, reflection state, and exactly three cross-domain completion handoffs (to arete, nisaba, and nyx). The handoff count is enforced by schema (.min(3).max(3)), ensuring all three downstream domains always receive the signal.

Aphrodite Events (Creator Economy) — 24 types#

These 24 events span the full creator-economy lifecycle. Stream events cover stream.started/ended, stream.viewer_count_updated, and stream.goal_reached. Transaction events cover transaction.tip_received, tokens_purchased, subscription_created/cancelled, payout_requested/completed. User events cover user.registered/verified/followed/banned. Device events cover device.connected/control_sent/state_updated. Chat events cover chat.message_sent/user_muted. Moderation events cover moderation.content_flagged/content_reviewed. Content events cover content.recording_ended/vod_published/clip_created.

Nyx Events (Cosmic Observatory) — 24 types#

The 24 Nyx events are grouped by service area. Catalog events: nyx.object.viewed, nyx.observation.logged/updated, nyx.view.saved, nyx.list.created, nyx.list.item.observed, nyx.achievement.unlocked, nyx.tour.started/completed. Compute events: nyx.compute.ephemeris.updated, nyx.compute.event.predicted, nyx.compute.eclipse.predicted, nyx.compute.conjunction.predicted, nyx.compute.satellite.pass. Render events: nyx.render.tile.generated, nyx.render.export.ready, nyx.render.cache.invalidated. Realtime events: nyx.realtime.satellite.visible, nyx.realtime.iss.pass, nyx.realtime.meteor.peak, nyx.realtime.aurora.alert, nyx.realtime.event.imminent. Catalog-update events: nyx.catalog.tle.updated, nyx.catalog.orbital.updated.

Psyche Events (AI Embodiment) — 37 types#

Psyche's 37 events span every stage of an AI avatar interaction. Session lifecycle events cover started/ended/paused/resumed. Avatar events cover state, expression, animation, created, and trained. Voice events cover speaking, listening, interim/final transcript, and response generated. Memory events cover created/updated/retrieved/consolidated. Persona events cover created/updated/activated/deactivated. Tool-execution events cover started/completed/failed. Conferencing events cover participant joined/left, speaker changed, screen-share, and room started/ended. Emotion events are psyche.emotion.detected and psyche.emotion.sentiment_analyzed. An error event completes the set.

Veritas Events (AI News Agency) — 27 types#

Article lifecycle and processing events cover created/updated/published/ unpublished/ingested/processed/enriched/clustered. Claim and fact-check events cover claim.extracted, claim.verified, factcheck.started/completed. Additional events cover story clusters, feeds (feed.fetched/failed), media generation (video/audio), alerts (alert.breaking_news/moderation), analytics (trending_updated, engagement_recorded), and NLP processing (sentiment, topics, keywords, summary, entities).

Concordia Events (Cooperative Mediation) — 12 types#

These 12 events track a mediation case from creation to resolution. The types are: concordia.case.created, concordia.party.joined, concordia.intake.completed, concordia.issue.identified, concordia.preference.updated, concordia.offer.generated, concordia.offer.compared, concordia.search.completed, concordia.draft.reviewed, concordia.settlement.accepted, concordia.execution.completed, concordia.escalation.required. Payloads carry only identifiers and viewer-safe metadata — private party fields are never included. The module also exports a ConcordiaEventSchemaRegistry keyed by event type.


Validation Utilities#

A payload that is valid TypeScript at compile time can still fail at runtime if it arrives as raw JSON from Kafka or an HTTP body — the types are erased. The validation layer bridges this gap: every schema is also a Zod validator that can be called at a service boundary to confirm the incoming data matches what the types describe.

  • Zod Schema Exports — Every entity type has a corresponding Zod schema (e.g. UserSchema, AssetSchema, EventEnvelopeSchema). Consumers call .safeParse() / .parse() directly at API boundaries, queue consumers, and event handlers.
  • Event Validation API (events/validation.ts) — validateEvent(event) validates the envelope and, if the type is registered, the type-specific schema; validatePayload(eventType, payload) validates a payload alone. validateEventOrThrow / validatePayloadOrThrow throw an EventValidationError. Helpers getEventSchema, getPayloadSchema, getRegisteredEventTypes, getEventTypesByDomain, and isEventTypeRegistered query the EventSchemaRegistry.
  • Event Schema RegistryEventSchemaRegistry is a Map of EventSchemaEntry records (type, source, schema, payloadSchema, description). It registers the Isis, Sophia, Hathor, Bellona, Yemaya, Lilith, and Tara event schemas. The registry is partial — not all 12 domains' events are registered.
  • Middleware HelperscreateValidationMiddleware wraps event handlers and createPublishValidator wraps publishers, each in strict (throw) or non-strict (warn-and-continue) mode.
  • Schema Composition — Complex entity schemas are composed from constituent schemas (e.g. AssetSchema embeds AssetLicenseSchema and AssetProvenanceSchema), so a base type's change propagates automatically.
  • Contract↔Prisma Alignment Testscontract-prisma-alignment.test.ts and contract-prisma-migrations.test.ts verify that contract types stay structurally consistent with the Prisma database schema and that new required fields have matching migrations.

Additional Subpaths#

Beyond ./common and ./events, @oshun/contracts exposes several further per-domain canonical contract surfaces. These subpaths exist because some domains have rich enough contract requirements to warrant their own organized module, while still benefiting from living inside the zero-upstream contracts package.

  • @oshun/contracts/llm — The canonical LLM gateway contract: the IsisLLMClient interface plus request/response/streaming schemas, a typed error taxonomy, and pricing-unit primitives. A ./llm/test-utils subpath provides a gateway test double.
  • @oshun/contracts/aja — Motion-AI / embodied-instruction contracts: math/skeletal primitives, motion file formats (BVH/FBX/glTF/USD/Alembic/ C3D/CSV), job lifecycle, and embodied-instruction request/response contracts.
  • @oshun/contracts/arete — Habit and goal contracts (check-in status, habit cadence, goal timeframe/scope/status).
  • @oshun/contracts/tara — Contemplative-practice taxonomies (mood, theme, modality) plus a ./tara/playback-rate subpath.
  • @oshun/contracts/nyx — Sky-event canonical contracts (event families and specific event types) — distinct from the events/nyx.ts module.
  • @oshun/contracts/metis — Learning/tutoring contracts (course builds, grounding packs, assessment evidence, tutor persona/session memory).
  • @oshun/contracts/nisaba — Manuscript/scholarship contracts (manuscripts, editions, lexicon and morphology entries, concept graphs, study plans).
  • @oshun/contracts/veritas — Veritas fact-check canonical contracts (claims, sources, stories, timelines, retraction cascades) — distinct from the events/veritas.ts module.
  • @oshun/contracts/v3 — V3 Lilith/Tara/Saraswati contracts.
  • @oshun/contracts/tts — TTS gateway client and provider adapters.
  • The root barrel also re-exports the Living Scene score/technique contracts, the Iris memory entry/continuation contracts (IrisContracts), and the agent tool-catalog/grants contracts (AgentContracts).

Sibling Contract Libraries#

The directory libs/contracts/ also hosts several separate Nx libraries (each its own package), not subpaths of @oshun/contracts. The key distinction is organizational: a sibling package like @iris/contracts can be versioned and evolved independently, while still following the same zero-upstream-dependency rule so it can be safely imported anywhere in the monorepo.

@iris/contracts — Iris AI Assistant Contracts#

API contracts and Zod schemas for the Iris AI Assistant. The library is organized into four focused subpaths:

  • Conversation Contracts — message content blocks (text, image, tool-use, tool-result), MessageSchema, ConversationSchema, and streaming events.
  • Tiered Memory Contracts — a four-tier memory model: core memory blocks, working memory entries, archival memory (with search), and episodic memory (with query), plus memory operations and a full MemoryState.
  • Agent Contracts — tool definitions, agent config/status, agent execution, and a built-in MEMORY_TOOLS catalog.

Subpaths: ./common, ./conversation, ./memory, ./agent.

@psyche/contracts — Psyche AI Conferencing Contracts#

Domain contracts for Psyche, the hyper-realistic AI virtual assistant platform for video conferencing. Currently exports its common/ schema module; avatar, voice, behavior, perception, conferencing, knowledge, and persona modules are to be added as services are migrated.

@concordia/contracts — Cooperative Mediation Contracts#

API contracts for Concordia cooperative mediation and negotiation — a large library spanning ~100 feature directories (the case model, parties, issues, agreements, the agreement DSL, preference/utility models, settlement lifecycle, access/authority/consent, escalation, search, oversight, and cross-domain integrations). Its barrel currently exports the use-case classification surface (use-case classes, class profiles, eligibility helpers) and the hard-boundary surface (boundary kinds, rules, violations); Phase 179 follow-on tasks extend the exports.

Industrial / Commerce Contract Libraries#

These four packages provide the contract layer for the platform's physical and commercial domains. Each depends only on zod and follows the zero-upstream rule.

  • @freya/contracts — Freya luxury-goods domain: product, order, customer, and manufacturing schemas.
  • @contracts/brigid — Brigid industrial domain: events, API schemas, and cross-domain/integration contracts.
  • @contracts/cybele — Cybele construction/infrastructure domain: API schemas and events.
  • @contracts/saraswati — Saraswati cross-domain integration adapters connecting Saraswati to Brigid, Asase, Freya, Cybele, and Maat.
  • @maat/contracts — A scaffold package that exports only the MaatContractEnvelope interface; its subdirectories currently hold only .gitkeep files, so the Maat contract surface is not yet implemented.

libs/contracts/veritas/ is an empty placeholder directory (only .gitkeep); the implemented Veritas canonical contracts are the @oshun/contracts/veritas subpath.

Contracts does not own product behavior. Product features remain in domain feature files; Contracts owns the stable type and schema agreements those features depend on.