Technical specification for
@oshun/contracts(libs/contracts/): the canonical entity schemas, the event envelope, the per-domain event payloads, the Zod validation registry, and the additional subpath surfaces (LLM gateway, Aja, Arete, Tara, Nyx, Metis, Nisaba, Living Scene, Veritas, Iris, Agent, V3). The directorylibs/contracts/also hosts several separate Nx contract libraries (@iris/contracts,@psyche/contracts,@concordia/contracts,@freya/contracts,@contracts/brigid,@contracts/cybele,@contracts/saraswati,@maat/contracts); they are documented at the end.Every schema, field, enum value, and event in this document was read from source under
libs/contracts/src/andlibs/contracts/<sub>/. Field counts for very large files are described at category level rather than field-by-field.
This document is the authoritative field-level reference for the contracts layer. It complements the features and architecture docs: the architecture doc explains why contracts exists and how it fits in the dependency graph; the features doc explains what capabilities it provides; this document specifies exactly what each schema contains — every field, every enum value, every constraint. Engineers adding a new entity, extending an event payload, or auditing type compatibility should start here.
Package Layout#
libs/contracts/ contains the primary @oshun/contracts package plus eight
sibling contract packages. The sibling packages each have their own
package.json and project.json — they are independent Nx libraries that
happen to live in the same directory, not subpaths of @oshun/contracts.
libs/contracts/
├── package.json # @oshun/contracts (name, exports, deps)
├── project.json # Nx project: tags scope:shared, layer:contracts, type:lib
├── tsconfig.json / tsconfig.lib.json / tsconfig.spec.json
├── vitest.config.ts
├── src/ # @oshun/contracts source (see below)
│
├── iris/ # @iris/contracts (separate package)
├── psyche/ # @psyche/contracts (separate package)
├── concordia/ # @concordia/contracts (separate package)
├── freya/ # @freya/contracts (separate package)
├── brigid/ # @contracts/brigid (separate package)
├── cybele/ # @contracts/cybele (separate package)
├── saraswati/ # @contracts/saraswati (separate package)
├── maat/ # @maat/contracts (separate package, near-empty)
└── veritas/ # placeholder directory (only `.gitkeep`)
The src/ directory of @oshun/contracts is organized into these top-level
areas. The common/ directory is the largest, containing roughly 153 schema
files that span entity types, admin contracts, compliance workflows, and
grounded-research contracts.
src/
├── index.ts # Root barrel
├── contracts.spec.ts # Self-consistency tests for common + event schemas
├── common/ # ~153 entity / admin / safety / governance schema files
├── events/ # Event envelope + 12 per-domain event modules
├── llm/ # @oshun/contracts/llm — LLM gateway contract
├── aja/ # @oshun/contracts/aja — motion-AI / embodied instruction
├── arete/ # @oshun/contracts/arete — habit / goal contracts
├── tara/ # @oshun/contracts/tara — contemplative-practice contracts
├── nyx/ # @oshun/contracts/nyx — sky-event canonical contracts
├── metis/ # @oshun/contracts/metis — learning / tutoring contracts
├── nisaba/ # @oshun/contracts/nisaba — manuscript / scholarship contracts
├── living-scene/ # Living Scene score + technique contracts
├── veritas/ # @oshun/contracts/veritas — fact-check canonical contracts
├── iris/ # IrisContracts (memory entry + continuation re-export)
├── agent/ # AgentContracts — tool catalog + grants
└── v3/ # @oshun/contracts/v3 — Lilith/Tara/Saraswati V3 contracts
Package Exports#
The package.json exports map below lists every independently importable
subpath. Consumers should import from the most specific subpath they need — for
example, @oshun/contracts/events rather than the root @oshun/contracts — to
avoid pulling in the entire surface unnecessarily.
libs/contracts/package.json declares @oshun/contracts version 0.1.0,
"type": "module", and the following exports map:
| Subpath | Source |
|---|---|
. |
./src/index.ts |
./aja (and ./aja/index.js) |
./src/aja/index.ts |
./arete |
./src/arete/index.ts |
./common |
./src/common/index.ts |
./common/canonical-audit-event |
./src/common/canonical-audit-event.ts |
./events |
./src/events/index.ts |
./llm |
./src/llm/index.ts |
./llm/test-utils |
./src/llm/test-utils.ts |
./metis |
./src/metis/index.ts |
./nisaba |
./src/nisaba/index.ts |
./nyx |
./src/nyx/index.ts |
./tts |
./src/tts/index.ts |
./tts/reference-client |
./src/tts/reference-client.ts |
./tts/ssml-emotion |
./src/tts/ssml-emotion.ts |
./tts/providers |
./src/tts/providers/index.ts |
./tara (and ./tara/playback-rate) |
./src/tara/index.ts, ./src/tara/playback-rate.ts |
./v3 (and ./v3/index.js) |
./src/v3/index.ts |
./veritas |
./src/veritas/index.ts |
./iris |
./src/iris/index.ts |
Note: a
./ttssubpath andsrc/tts/directory exist inpackage.json's export map and on disk (TTS gateway client/provider adapters); they are part of the package surface. The rootindex.tsre-exportscommon,events,llm,aja,arete,tara,v3,nyx,living-scene,nisaba,metis,veritas,iris, andagent.
Dependencies#
The dependency declaration is intentionally minimal. Adding any @oshun/*
library here would risk creating circular dependencies that could affect the
entire monorepo.
"dependencies": { "zod": "catalog:" }
@oshun/contracts depends only on zod. It has no dependency on any other
@oshun/* library. devDependencies are @types/node, typescript, and
vitest (all catalog:).
Common Primitives (src/common/primitives.ts)#
These foundational schemas are imported by every other module in common/. They
establish the canonical wire format for identities, timestamps, pagination, and
HTTP responses. Using these shared primitives — rather than each module defining
its own z.string().uuid() — ensures that every part of the platform represents
these concepts identically.
Identity#
| Schema | Definition |
|---|---|
UUIDSchema |
z.string().uuid() — UUID v4 |
SlugSchema |
z.string().min(1).max(100) matching ^[a-z0-9]+(?:-[a-z0-9]+)*$ |
Timestamps#
| Schema | Definition |
|---|---|
TimestampSchema |
z.string().datetime() — ISO 8601 |
DateSchema |
z.string() matching ^\d{4}-\d{2}-\d{2}$ |
TimestampsSchema |
object { createdAt, updatedAt } |
SoftDeleteSchema |
object { deletedAt: Timestamp | null } |
Pagination#
Two pagination strategies are provided. Offset pagination is the default for admin and browse surfaces; cursor pagination is used for high-volume real-time feeds where consistent page boundaries matter.
SortOrderSchema— enumasc,desc.PaginationRequestSchema—{ page≥1 default 1, limit 1–100 default 20, sortBy?, order default desc }.PaginationMetaSchema—{ page, limit, total, totalPages, hasNext, hasPrevious }.createPaginatedSchema(itemSchema)— returns{ data: itemSchema[], meta: PaginationMetaSchema }.CursorPaginationRequestSchema—{ cursor?, limit 1–100 default 20, direction forward|backward default forward }.CursorPaginationMetaSchema—{ hasNextPage, hasPreviousPage, startCursor, endCursor, totalCount? }.
Errors and Responses#
The error and response schemas below are the canonical HTTP response shapes used
across all domain APIs. Using a single ErrorSchema means that client-side
error-handling logic written once works against any domain endpoint.
FieldErrorSchema—{ field, message, code? }.ErrorSchema—{ code, message, details?: FieldError[], requestId? }.ErrorCodes— const map. Client codes:BAD_REQUEST,VALIDATION_ERROR,UNAUTHORIZED,FORBIDDEN,NOT_FOUND,CONFLICT,RATE_LIMITED,PAYLOAD_TOO_LARGE,EMAIL_NOT_VERIFIED. Server codes:INTERNAL_ERROR,SERVICE_UNAVAILABLE,DATABASE_ERROR,EXTERNAL_SERVICE_ERROR.SuccessResponseSchema—{ success: true, message? }.ErrorResponseSchema—{ success: false, error: ErrorSchema }.createDataResponseSchema(dataSchema)—{ success: true, data: dataSchema }.
Metadata, Geographic, Contact#
MetadataSchema—z.record(z.string(), z.unknown()).StringMetadataSchema—z.record(z.string(), z.string()).CoordinatesSchema—{ latitude -90..90, longitude -180..180 }.AddressSchema—{ line1, line2?, city, state?, postalCode?, country (ISO 3166-1 alpha-2) }.EmailSchema—z.string().email().URLSchema—z.string().url().PhoneSchema—z.string()matching E.164^\+[1-9]\d{1,14}$.
Common Entity Schemas (src/common/)#
src/common/index.ts re-exports approximately 153 source files. The first group
are the canonical platform entities (User, Asset, Project, and others
described below); the remainder are admin-console, safety/compliance,
governance, and grounded-research contracts. The field-level detail for each
entity below represents the full schema as read from source.
User (user.ts)#
The UserSchema is the widest user representation — used by internal services
that need the full record. UserSummarySchema is the minimal embeddable form
used inside other entity schemas; UserProfileSchema is the shape returned by
public profile endpoints.
UserRoleSchema— enumuser,creator,admin,super_admin.UserStatusSchema— enumpending,active,suspended,deleted.UserSummarySchema—{ id, displayName, avatarUrl: URL\|null }.UserProfileSchema— public profile:id,username?,displayName,bio?,avatarUrl?,location?,website?,company?,jobTitle?,projectCount,followerCount,followingCount,createdAt.UserSchema— full private record:id,email,username(nullable),firstName,lastName,displayName,bio(nullable),avatarUrl,role,status,emailVerified,phone(nullable),location,website,company,jobTitle,lastLoginAt, pluscreatedAt/updatedAt.- Preferences:
ThemePreferenceSchema(light/dark/system),NotificationSettingsSchema,EditorSettingsSchema,UserPreferencesSchema. UserStatsSchema,UserActivitySchema,NotificationSchema.- Requests:
CreateUserRequestSchema,UpdateUserRequestSchema,UpdatePreferencesRequestSchema. Paginated:PaginatedUsersSchema,PaginatedActivitiesSchema,PaginatedNotificationsSchema.
Asset (asset.ts)#
The asset schema is shared between Isis (which generates assets), Yemaya (which manages them in projects), and any domain that needs to reference a generated or uploaded file. The provenance and license submodels carry the metadata needed to satisfy attribution and consent requirements for AI-generated content.
AssetTypeSchema— enumimage,video,audio,model_3d,document,script,font,texture,material,animation,archive,other.AssetStatusSchema— enumuploading,processing,ready,error,archived.LicenseTypeSchema— enum covering Creative Commons (cc0,cc-by,cc-by-sa,cc-by-nc,cc-by-nc-sa,cc-by-nd,cc-by-nc-nd), commercial (royalty-free,rights-managed,editorial-only), open-source (mit,apache-2.0,gpl-3.0,bsd-3-clause), proprietary (proprietary,custom,all-rights-reserved), andunknown.GenerationMethodSchema— enummanual,ai-generated,ai-assisted,procedural,captured,scanned,mixed,unknown.AssetLicenseSchema,AIGenerationDetailsSchema(model, prompt, seed, steps, guidanceScale, sampler, …),AssetProvenanceSchema(generation method, source links, modifications array,verificationStatusunverified/verified/disputed).- Type-specific metadata:
ImageMetadataSchema,VideoMetadataSchema,AudioMetadataSchema,Model3DMetadataSchema,DocumentMetadataSchema, plus the combinedAssetMetadataSchema. AssetThumbnailsSchema(small/medium/largeURLs).AssetSummarySchemaand fullAssetSchema— id, name, filename, description, type, status,sizeBytes,sizeFormatted,mimeType,url, thumbnails,previewUrl, metadata, tags,version/versionCount,projectId,folderId,path,license,provenance,uploadedBy,lockedBy/lockedAt, timestamps.AssetVersionSchema,AssetFolderSchema.- Requests:
CreateAssetRequestSchema,UpdateAssetRequestSchema,CreateFolderRequestSchema,MoveAssetRequestSchema,BulkOperationTypeSchema(move/delete/archive/tag/untag),BulkAssetOperationRequestSchema. Response:UploadUrlResponseSchema.
Project (project.ts)#
Projects are the primary unit of organization in Yemaya (the creative studio)
and serve as the cross-domain reference for grouping assets, members, and
activity. Any domain that needs to know "which project does this belong to?"
references the ProjectSchema.
ProjectTypeSchema— enumfilm,game,animation,commercial,music_video,documentary,short_film,vr_experience,ar_experience,live_event,other.ProjectStatusSchema—draft,active,on_hold,completed,archived.ProjectVisibilitySchema—private,team,organization,public.ProjectRoleSchema—owner,admin,editor,reviewer,viewer.ResolutionSchema,ProjectSettingsSchema(defaultBranch, versioning flags,frameRatedefault 24,resolutiondefault 1920×1080, …).ProjectSummarySchemaand fullProjectSchema— id, name, slug, description, type, status, visibility, thumbnail/cover URLs, tags, settings,ownerId/owner,organizationId,memberCount,assetCount,storageUsedBytes,lastActivityAt, timestamps.ProjectPermissionsSchema,ProjectMemberSchema,ProjectInvitationSchema,ProjectCommentSchema(withCommentPositionSchemafor spatial comments),ProjectActivitySchema.- Requests:
CreateProjectRequestSchema,UpdateProjectRequestSchema,AddMemberRequestSchema,UpdateMemberRequestSchema,CreateCommentRequestSchema,UpdateCommentRequestSchema. - Access control:
CheckAccessRequestSchema,CheckAccessResponseSchema,UserRoleResponseSchema.
Audit (audit.ts) and Canonical Audit Event (canonical-audit-event.ts)#
Two audit schemas coexist. The legacy AuditEventSchema in audit.ts is
permissive — it accepts partial records for backward compatibility. The strict
CanonicalPlatformAuditEventSchema defined in canonical-audit-event.ts (and
exported via the ./common/canonical-audit-event subpath) is the ADR-0023
contract enforced at audit-platform ingestion. New code should use the canonical
schema.
audit.ts (legacy, permissive):
AuditActionSchema— enum:create,read,update,delete,archive,restore,publish,unpublish,grant_access,revoke_access,login,logout,login_failed,export,import,transfer,approve,reject,submit,complete,system.AuditSeveritySchema—info,warning,error,critical.AuditEventSchema— immutable log entry: id, timestamp, action, severity, actor identity (actorId/actor/actorTypeenumuser/system/api_key/service), resource (resourceType/resourceId/resourceName), scope (projectId/organizationId), request evidence (ipAddress/userAgent/requestId/sessionId), state diffs, compliance fields.FieldChangeSchema,ChangeSetSchema,RetentionPolicySchema,ComplianceReportSchema(report typegdpr/soc2/hipaa/pci/custom),DataSubjectRequestTypeSchema(access/rectify/erase/restrict/portability/object),DataSubjectRequestSchema, plus query/create request schemas.
canonical-audit-event.ts (strict, ADR-0023 — exported via the
./common/canonical-audit-event subpath):
CanonicalAuditOutcomeSchema— enumsuccess,error,allowed,denied,warning.CanonicalAuditSeveritySchema—info,warning,error,critical.CanonicalAuditActorTypeSchema—user,service,system,api_key,agent,job.CanonicalAuditActorSchema—{ actorType, actorId\|null, actorRole\|null, label\|null, system }with asuperRefineenforcing actorId-or-system.CanonicalAuditTargetSchema—{ resourceType, resourceId, resourceName, domain, parentResourceType, parentResourceId, tenantId }.CanonicalAuditEvidenceSchema—{ ipAddress, userAgent, geo }.CanonicalPlatformAuditEventSchema— strict event witheventId,occurredAt,ingestedAt, dottedaction,outcome,severity,actor,target,reason,traceId, optionalspanId/requestId/sessionId/evidence/state-diffs/metadata(≤50 keys)/policyId/retentionTag, andschemaVersionliteral1.superRefineenforcesingestedAt ≥ occurredAt, critical events carry evidence, and denied/error events carry a ≥5-char reason.IngestCanonicalAuditEventRequestSchema— caller-supplied ingestion form.
Contemplative / Knowledge Entities#
These entities share a common cross-domain taxonomy — domain membership, origin, status, and visibility — that is defined once and re-exported by Practice, Concept, Passage, Source, and Notebook. The shared taxonomy ensures that a concept authored in Nisaba and referenced in Veritas uses exactly the same domain and status values.
The shared cross-domain enums are: RitualDomainSchema (enum tara, arete,
veritas, nyx, nisaba) and RitualOriginSchema (system, editorial,
assistant_generated, user_defined), RitualStatusSchema (draft, active,
archived), and RitualVisibilitySchema (private, shared, public,
system) — re-exported as the *Domain, *Origin, *Status, *Visibility
schemas of Practice, Concept, Passage, Source, and Notebook.
Ritual (ritual.ts) — RitualKindSchema (morning/midday/evening/
transition/study/reflection/seasonal/event_based/custom),
RitualCadenceSchema, RitualTimeOfDaySchema, RitualContextSignalSchema,
RitualClockTimeSchema, RitualScheduleSchema, RitualContextSchema,
RitualComponentKindSchema, RitualComponentSchema. RitualSchema /
RitualSummarySchema carry id, slug, title, summary, primaryDomain,
domains, origin, kind, status, visibility, schedule,
estimatedDurationMinutes, tags; the full schema adds description, context,
components, intendedOutcomes, owner. superRefine enforces
domain-set/primary-domain/component coherence.
Practice (practice.ts) — PracticeKindSchema (meditation, breathwork,
journaling, reflection, study, reading, movement, focus,
observation, compassion, sleep, custom), PracticeDifficultySchema,
PracticeIntensitySchema, PracticeTrackingModeSchema,
PracticeGroundingModeSchema, PracticeSafetyLevelSchema,
PracticeCueTypeSchema, PracticeResourceKindSchema. Submodels:
PracticeCueSchema, PracticeTrackingSchema, PracticeSafetySchema,
PracticeGroundingSchema, PracticeStepSchema. PracticeSchema adds cues,
steps, tracking, safety, grounding, prerequisites, intended outcomes.
Concept (concept.ts) — ConceptComplexitySchema
(basic/intermediate/advanced), ConceptRelationshipTypeSchema,
ConceptLinkKindSchema, ConceptRelationshipSchema, ConceptLinkSchema.
ConceptSchema fields: id, slug, name, summary, primaryDomain, domains,
origin, status, visibility, category, complexity, tags, lastPublishedAt,
timestamps; full schema adds relationships and links.
Passage (passage.ts) — textual content for scholarship. Enums:
PassageTextFormatSchema (plain_text/markdown/html/tei_xml),
PassageReferenceSchemeSchema (cts/osis/sefaria/custom),
PassageTranslationKindSchema, PassageCommentaryKindSchema,
PassageAnnotationKindSchema, PassageHighlightColorSchema,
PassageParallelRelationshipSchema. Submodels for references, provenance,
translations, parallels, commentary, annotations; full PassageSchema.
Source (source.ts) — citation sources. Enums: SourceTypeSchema,
SourceCredibilityTierSchema (high/medium/low/unknown),
SourceCitationStyleSchema, SourceContributorRoleSchema. Submodels for
contributors, partial dates, containers, license, provenance, versions,
formatted citations, concept links; full SourceSchema.
Notebook (notebook.ts) — research notebooks. Enums: NotebookKindSchema,
NotebookMethodologySchema, NotebookViewSchema
(document/board/timeline/split_view), NotebookCollaboratorRoleSchema,
NotebookItemKindSchema, NotebookItemLinkKindSchema. Submodels:
NotebookCollaboratorSchema, NotebookSectionSchema, NotebookItemSchema,
NotebookItemLinkSchema. NotebookSchema aggregates items plus arrays of
grounded-answer / grounded-report / evidence-pack / source-set / citation-trail
IDs.
Collection (collection.ts) — CollectionSchema /
CollectionSummarySchema for ordered curated lists of cross-domain content.
AI / Persona / Voice / Avatar Entities#
These entities are used wherever the platform renders, configures, or safeguards an AI-generated identity. The shared schemas ensure that consent and safety metadata (deception-risk level, watermark status, approval status) are represented consistently regardless of which domain is displaying the persona or avatar.
Persona (persona.ts, ~1.4k lines) — canonical AI persona definition. Enums
include PersonaRoleSchema, PersonaStatusSchema
(draft/review/published/archived/deleted),
PersonaLifecycleStageSchema, PersonaApprovalStatusSchema,
PersonaModalitySchema (text/voice/avatar/video),
PersonaCapabilitySchema, PersonaConsentStatusSchema,
PersonaCommunicationStyleSchema, PersonaToneSchema,
PersonaFormalitySchema, PersonaDirectnessSchema, PersonaPacingSchema,
PersonaEmotionalToneSchema, PersonaVocabularyLevelSchema,
PersonaMemoryModeSchema, PersonaGroundingModeSchema,
PersonaCitationStyleSchema, PersonaEscalationTriggerSchema,
PersonaEscalationTargetSchema. Submodels: PersonaBigFiveSchema
(personality), PersonaToneProfileSchema, PersonaDisclosureRulesSchema,
PersonaGroundingRulesSchema, PersonaPromptTemplatesSchema,
PersonaContentLinkSchema. PersonaSchema / PersonaSummarySchema.
VoiceProfile (voice-profile.ts) — TTS voice synthesis profiles. Enums:
VoiceProfileProviderSchema, VoiceProfileOriginSchema,
VoiceProfileStatusSchema, VoiceProfileLifecycleStageSchema,
VoiceProfileApprovalStatusSchema, VoiceProfileTrainingStatusSchema,
VoiceProfileGenderSchema, VoiceProfileAgeCategorySchema,
VoiceProfileStyleSchema, VoiceUseScopeSchema, VoiceConsentStatusSchema,
VoiceWatermarkStatusSchema, VoiceSafetyControlSchema,
VoiceEmotionPresetSchema, VoiceQualityTierSchema, VoiceQualityGradeSchema
(A–F). VoiceProfileSchema / VoiceProfileSummarySchema.
AvatarPack (avatar-pack.ts) — avatar customization sets. Enums:
AvatarPackStatusSchema, AvatarPackLifecycleStageSchema,
AvatarPackApprovalStatusSchema, AvatarPackProviderSchema,
AvatarPackOriginSchema, AvatarPackEmbodimentSchema, AvatarPackStyleSchema,
AvatarPackRenderQualitySchema (draft/standard/high/ultra),
AvatarPackTrainingStatusSchema, AvatarPackStateSchema,
AvatarPackFramingSchema, AvatarPackModelFormatSchema,
AvatarPackOverlayPlacementSchema, AvatarPackConsentStatusSchema,
AvatarPackUseScopeSchema, AvatarPackWatermarkStatusSchema,
AvatarPackWatermarkMethodSchema, AvatarPackQualityTierSchema,
AvatarPackDeceptionRiskLevelSchema (low/guarded/high/blocked).
Submodels: AvatarPackStillVariantSchema, AvatarPackPreviewVideoSchema.
AvatarPackSchema / AvatarPackSummarySchema.
ModelCard (model-card.ts) — AI model metadata. Enums:
ModelCardDomainSchema, ModelCardStatusSchema, ModelCardSourceTypeSchema,
ModelCardTypeSchema, ModelCardFormatSchema, ModelCardHashAlgorithmSchema
(sha256/sha512/md5/blake3), ModelCardContentRatingSchema,
ModelCardSafetyClassSchema (safe/sensitive/restricted/blocked),
ModelCardReviewStateSchema, ModelCardPromotionDecisionSchema,
ModelCardCitationTypeSchema. Submodels include ModelCardCreatorSchema,
ModelCardComputeInfoSchema, ModelCardCarbonInfoSchema,
ModelCardFairnessMetricSchema, ModelCardBiasInfoSchema,
ModelCardCitationSchema. ModelCardSchema / ModelCardSummarySchema.
ModelVersion (model-version.ts) — versioned model artifacts. Enums:
ModelVersionDomainSchema, ModelVersionStatusSchema,
ModelVersionSourceTypeSchema, ModelVersionTypeSchema,
ModelVersionFormatSchema, ModelVersionEngineSchema,
ModelVersionProviderSchema, ModelVersionEnvironmentSchema
(preview/staging/production), ModelVersionFileRoleSchema,
ModelVersionHashAlgorithmSchema, ModelVersionScanStatusSchema,
ModelVersionSafetyClassSchema, ModelVersionReviewStateSchema,
ModelVersionPromotionDecisionSchema, ModelVersionDeploymentHealthSchema,
ModelVersionCompatibilityStateSchema, ModelVersionChangeTypeSchema,
ModelVersionPrecisionSchema (fp16/fp32/bf16/int8/other),
ModelVersionPackageSizeSchema. ModelVersionSchema /
ModelVersionSummarySchema.
ContinuityState (continuity-state.ts) — assistant session continuity.
Enums: ContinuityStateStatusSchema, ContinuityMomentumSchema,
ContinuitySurfaceSchema, ContinuityJourneyKindSchema,
ContinuityJourneyStatusSchema, ContinuityResumeModeSchema
(resume/continue/review/revisit), ContinuityJourneySourceSchema,
ContinuityReminderKindSchema, ContinuityReminderPrioritySchema,
ContinuityCheckpointKindSchema, ContinuityAssistantModeSchema
(text/voice/multimodal).
MemoryScope (memory-scope.ts, ~1.5k lines) — memory-scope definitions.
Enums: MemoryScopeDomainSchema, MemoryScopeStatusSchema,
MemoryScopeKindSchema, MemoryScopeOwnerTypeSchema,
MemoryScopeSurfaceSchema, MemoryScopeStorageClassSchema,
MemoryScopeContentTypeSchema, MemoryScopeSensitiveCategorySchema,
MemoryScopePrivacyBoundarySchema, MemoryScopeSensitivitySchema,
MemoryScopeRetentionActionSchema, MemoryScopeSharingModeSchema,
MemoryScopeSyncModeSchema, MemoryScopeConsentModeSchema,
MemoryScopeReviewStateSchema, MemoryScopeResolutionStrategySchema,
MemoryScopeShareTargetTypeSchema, MemoryScopeSharePermissionSchema
(read/write), MemoryScopeRuntimeSchema. MemoryScopeSchema /
MemoryScopeSummarySchema, plus MemoryScopeShareTargetSchema.
Fact-Checking / Evidence Entities#
These entities are used by Veritas (the AI news agency) and by the retrieval-grounded research stack shared between Sophia, Nisaba, and Metis. They represent the platform's canonical contracts for handling evidence, claims, and their evaluation — ensuring that a claim verified by Veritas can be referenced by a Nisaba passage using the same type.
Claim (claim.ts) — ClaimTypeSchema, ClaimVerdictSchema,
ClaimVerificationStatusSchema, ClaimSpeakerTypeSchema,
ClaimEvidenceStanceSchema (supports/refutes/neutral/inconclusive),
ClaimEvidenceKindSchema, ClaimDebateRelationSchema. Submodels:
ClaimEvidenceSchema, ClaimDebateLinkSchema. ClaimSchema fields: id, slug,
statement, summary, primaryDomain, domains, origin, status, visibility, type,
verdict, verificationStatus, confidence (0–1), checkworthiness (0–1),
speakerName/speakerType, context, claimedAt, evidenceCount,
lastVerifiedAt, lastPublishedAt, tags, timestamps.
EvidencePack (evidence-pack.ts, ~1.5k lines) — EvidencePackSchema /
EvidencePackSummarySchema plus a superRefine for evidence-set coherence.
Companion files: evidence-pack-assembly.ts,
evidence-pack-assembly-evaluation.ts,
evidence-trace-completeness-evaluation.ts.
Grounded-research family — The following files define the canonical
contracts for retrieval-grounded answers, citation integrity, and
hallucination-risk scoring, shared between Sophia, Veritas, Nisaba, and Metis:
grounded-answer.ts, grounded-answer-evaluation.ts, grounded-report.ts,
grounding-state.ts, grounding-fallback.ts, citation.ts,
citation-integrity-evaluation.ts, citation-integrity-regression-gate.ts,
source-set.ts, retrieval-synthesis-labeling.ts,
hallucination-risk-evaluation.ts, unsupported-claim-detection.ts,
interruption-recovery-evaluation.ts, publication-release-gate.ts.
Operations / Governance Entities#
These entities underpin long-running platform processes such as moderation
reviews, peer-review workflows, and multi-tenant governance. They are shared
rather than domain-specific because multiple domains participate in the same
workflow — for example, a ReviewPackage may be submitted by Veritas and
evaluated by an admin console surface.
- Incident (
incident.ts, ~1.8k lines) —IncidentSchema/IncidentSummarySchemafor safety / operational incidents. - SupportCase (
support-case.ts) —SupportCaseSchema/SupportCaseSummarySchemasupport-ticket entity. - WorkflowTemplate (
workflow-template.ts, ~1.5k lines) —WorkflowTemplateSchemareusable workflow definition. - PolicyBundle (
policy-bundle.ts, ~1.7k lines) —PolicyBundleSchema/PolicyBundleSummarySchemacontent/governance policy definition. - ReviewPackage (
review-package.ts, ~2.5k lines) —ReviewPackageSchemapeer-review submission;review-stage-graph.tsdefines the review-stage graph. - ProvenanceBundle (
provenance-bundle.ts, ~1.6k lines) —ProvenanceBundleSchemacontent-provenance lineage;provenance-bundle-helpers.tssupplies helper functions. - Tenant (
tenant.ts) —TenantSchema/TenantSummarySchemamulti-tenant organisation entity. - ConsentRecord (
consent-record.ts, ~1.4k lines) — see below. - Other entities:
agent-run.ts,agentic-policy-bundle.ts,authoring-job.ts,authoring-templates.ts,research-job.ts,draft-lineage.ts,promotion-readiness-loops.ts,durable-job-orchestration.ts,partial-failure-envelope.ts,human-checkpoint-policy.ts,mass-assignment.ts.
ConsentRecord (consent-record.ts) — Detailed Specification#
ConsentRecord is the most heavily-refined entity in the contracts library. It
is the platform's formal consent contract — every user consent action anywhere
in the platform produces a record conforming to this schema. The Zod
superRefine validators embedded in the schema encode the platform's consent
lifecycle rules, so they are enforced at parse time rather than scattered across
service logic.
The taxonomy enums define the complete consent vocabulary:
ConsentRecordDomainSchema— 16 domains:tara,arete,veritas,nyx,nisaba,oshun,yemaya,isis,hathor,aja,bellona,sophia,iris,psyche,lilith,shared.ConsentCategorySchema— 20 categories:privacy,terms,marketing,analytics,cookie,personalization,memory,voice,avatar,recording,biometric,data_sharing,third_party_processing,research,notifications,support,education,synthetic_media,residency,custom.ConsentRecordStatusSchema—pending,granted,denied,withdrawn,revoked,expired,superseded.ConsentSubjectTypeSchema,ConsentTargetTypeSchema,ConsentCollectionMethodSchema,ConsentVerificationMethodSchema,ConsentVerificationStatusSchema,ConsentLegalBasisTypeSchema(six GDPR bases),ConsentDecisionSourceSchema,ConsentDecisionReasonCodeSchema,ConsentPermissionActionSchema,ConsentUseScopeSchema,ConsentEvidenceTypeSchema,ConsentHistoryEventTypeSchema.
Submodels compose the full record from its constituent parts:
ConsentSubjectSchema, ConsentTargetSchema, ConsentLegalBasisSchema,
ConsentEvidenceSchema, ConsentCollectionContextSchema,
ConsentVerificationSchema, ConsentPermissionGrantSchema,
ConsentHistoryEventSchema.
ConsentRecordSchema / ConsentRecordSummarySchema carry id, slug, title,
summary, description, primaryDomain, domains, subject, category, status,
target, version, legal basis, collection context, verification, permissions,
evidence, the full lifecycle-timestamp set
(requestedAt/decidedAt/grantedAt/deniedAt/withdrawnAt/revokedAt/
expiresAt), renewal fields, supersededById, history, metadata, timestamps.
Multiple superRefine validators enforce lifecycle-timestamp ordering,
status-specific timestamp presence, evidence-reference integrity, chronological
history, category↔target alignment, and verified-verification requirements for
high-risk categories (voice/avatar/biometric/ recording).
Privacy / Data-Rights / Safety / Admin Families#
The bulk of common/ — approximately 120 files — defines admin-console,
privacy, retention, and safety/compliance contracts. Each file exports a cluster
of z.enum schemas plus request/response and entity objects for the
corresponding admin UI or API surface. The categories are:
- Consent & privacy controls —
consent-taxonomy.ts,consent-state-display.ts,customer-consent-controls.ts,customer-data-export.ts,customer-data-deletion.ts,sensitive-data-access.ts,customer-message-center.ts. - Data governance —
data-rights-scopes.ts,data-retention-rules.ts,data-residency-rules.ts,data-residency-deployment-policy.ts,data-restore-policies.ts,rights-metadata-bundle.ts. - Entitlements —
entitlement-classes.ts,entitlement-inspection.ts,entitlement-exception-policy.ts,entitlement-lifecycle-policy.ts,premium-persona-access.ts. - Safety / moderation —
safety-taxonomy.ts,safety-severity.ts,safety-appeals.ts,safety-crisis.ts,safety-repeat-offender.ts,safety-repeat-offender-summary.ts,safety-dashboards.ts,safety-content-policy-evaluation.ts,safety-contemplative-evaluation.ts,safety-voice-abuse-evaluation.ts,safety-deceptive-avatar-evaluation.ts,unified-safety-review.ts. - Admin console — approximately 80
admin-*.tsfiles covering moderation, inbox, notifications, incident management, model governance/registry, persona governance/registry, editorial, billing, privacy/DSAR/retention/deletion workflows, research-integrity review, voice/avatar/watermark verification, bulk operations/exports, agentic operations, configuration center, readiness dashboards, universal search, cross-link/entity-comment/keyboard-shortcut/ saved-view utilities, and copilot surfaces.
Contract↔Prisma Alignment (contract-prisma-alignment.ts)#
Exports the alignment-checking schema and types consumed by
contract-prisma-alignment.test.ts and contract-prisma-migrations.test.ts.
These tests verify that contract schemas stay structurally consistent with
Prisma models, and that new required contract fields have matching migrations.
This prevents the class of runtime failure where a migration adds a non-nullable
column but the contract schema still treats the field as optional.
Event System (src/events/)#
Event Envelope (events/envelope.ts)#
The envelope schema below is the base type for every event in the platform. The
payload field is z.unknown() on the base schema; when a domain module calls
createEventSchema, the payload becomes a typed field matching the domain-
specific payload schema. This means the envelope can be deserialized and routed
by infrastructure code without knowing the payload type, while application code
that processes specific event types gets full type safety on the payload.
export const EventEnvelopeSchema = z.object({
id: UUIDSchema, // UUID v4
type: z
.string()
.min(3)
.max(100)
.regex(/^[a-z0-9]+(\.[a-z0-9_]+)+$/), // dotted domain.action
source: EventSourceSchema,
timestamp: TimestampSchema, // ISO 8601
version: z
.string()
.regex(/^\d+\.\d+\.\d+$/)
.default('1.0.0'),
priority: EventPrioritySchema.default('normal'),
payload: z.unknown(),
metadata: EventMetadataSchema.optional(),
aggregate: z
.object({
type: z.string().max(50),
id: UUIDSchema,
version: z.number().int().nonnegative(),
})
.optional(),
});
export type EventEnvelope = z.infer<typeof EventEnvelopeSchema>;
idis a UUID v4 (UUIDSchema), not a ULID. The envelope additionally carriespriority, structuredmetadata, and an optionalaggregateblock — there is no top-leveldomain,correlationId, orcausationIdfield; correlation/causation live insidemetadata.
The supporting schemas for the envelope are:
EventSourceSchema— enum of 13 sources:tara,isis,sophia,hathor,bellona,yemaya,lilith,aphrodite,nyx,psyche,veritas,concordia,system.EventPrioritySchema— enumlow,normal,high,critical.EventMetadataSchema—{ correlationId?, causationId?, traceId?, spanId?, userId?, projectId?, organizationId?, sessionId?, requestId?, ipAddress?, userAgent?, custom? }.createEventSchema(eventType, source, payloadSchema)— extends the envelope with literaltype/sourceand a typedpayload. Every per-domain event schema is built with this helper.EventPublishOptionsSchema,EventPublishResultSchema,EventConsumerConfigSchema,DeadLetterEventSchema— publish/consume infrastructure contracts.
Event Validation (events/validation.ts)#
The validation module provides both low-level Zod parsing and higher-level
middleware helpers. The EventSchemaRegistry is the bridge between the two: it
maps event-type strings to their full schemas, so validateEvent can validate
the envelope and the payload in a single call.
EventSchemaEntryinterface —{ type, source, schema, payloadSchema, description? }.EventSchemaRegistry: Map<string, EventSchemaEntry>— registers the Isis, Sophia, Hathor, Bellona, Yemaya, Lilith, and Tara event schemas. The registry is partial; not all 12 domains' events are registered in thisMap.ValidationIssueinterface,EventValidationResultunion,EventValidationErrorclass.- Functions:
getEventSchema,getPayloadSchema,getRegisteredEventTypes,getEventTypesByDomain,validateEvent,validatePayload,validateEventOrThrow,validatePayloadOrThrow,isEventTypeRegistered,isValidationSuccess,createValidationMiddleware,createPublishValidator.
AllEventTypes Registry (events/index.ts)#
AllEventTypes is a const object mapping every event-type string for all 12
domains. The table below gives the full count and the concrete event type
strings. The total is 181 event-type strings.
| Domain | Count | Event types |
|---|---|---|
isis |
10 | job.queued, job.started, job.progress, job.completed, job.failed, job.cancelled, asset.generated, workflow.registered, workflow.updated, model.loaded |
sophia |
9 | document.ingested, document.updated, document.deleted, index.updated, index.rebuilt, search.performed, entity.extracted, relation.discovered, citation.created |
hathor |
7 | world.created, world.published, element.added, narrative.generated, simulation.started, simulation.completed, world.validated |
bellona |
8 | session.started, session.ended, build.started, build.progress, build.completed, export.started, export.ready, asset.synced |
yemaya |
12 | project created/updated/archived, member joined/left, asset uploaded/processed/approved/rejected, comment created/resolved, session joined |
lilith |
10 | meditation started/completed/generated, journal created/updated, session started/ended, progress.updated, teacher.interaction, content.downloaded |
tara |
1 | ritual.completed |
aphrodite |
24 | stream, transaction, user, device, chat, moderation, and content events (see Aphrodite section) |
nyx |
24 | catalog, compute, render, realtime, and catalog-update events |
psyche |
37 | session, avatar, voice, memory, persona, tool, conferencing, emotion, error events |
veritas |
27 | article, claim/fact-check, story-cluster, feed, media-generation, alert, analytics, NLP events |
concordia |
12 | case, party, intake, issue, preference, offer, search, draft, settlement, execution, escalation events |
events/index.ts also re-exports each domain's *EventTypes constant, the
NyxContracts aggregate, and ConcordiaEventTypes /
ConcordiaEventSchemaRegistry / ConcordiaEventType.
Per-Domain Event Modules#
Each module under events/ defines, for every event, a *PayloadSchema
(z.object), a *EventSchema (built via createEventSchema), the inferred
types, and an *EventTypes constant. The field-level detail for each domain
module follows.
Isis (isis.ts) — GenerationTypeSchema (image, video, audio,
model_3d, texture, animation, avatar, world), GenerationStatusSchema
(queued, processing, completed, failed, cancelled). 10 events:
IsisJobQueued/Started/Progress/Completed/Failed/Cancelled,
IsisAssetGenerated, IsisWorkflowRegistered/Updated, IsisModelLoaded.
Example payload detail: IsisJobQueuedPayloadSchema =
{ jobId, projectId, userId, type, workflow, priority 0–10, estimatedDurationMs?, queuePosition?, parameters };
IsisJobCompletedPayloadSchema carries jobId, ids, type, workflow,
durationMs, an outputs[] array (assetId, type, url, filename, sizeBytes,
metadata), and optional metrics (gpuTimeMs, memoryPeakMb, modelLoadTimeMs).
Sophia (sophia.ts) — DocumentTypeSchema, IngestionStatusSchema
(pending/processing/indexed/failed). 9 events: document
ingested/updated/deleted, index updated/rebuilt, search performed, entity
extracted, relation discovered, citation created.
Hathor (hathor.ts) — WorldTypeSchema, WorldStatusSchema. 7 events:
world created/published/validated, element added, narrative generated,
simulation started/completed.
Bellona (bellona.ts) — GameEngineSchema, BuildPlatformSchema,
BuildStatusSchema. 8 events: session started/ended, build
started/progress/completed, export started/ready, asset synced.
Yemaya (yemaya.ts) — 12 events covering project, member, asset, comment,
and session lifecycle.
Lilith (lilith.ts) — MeditationTypeSchema, MeditationThemeSchema,
CompletionStatusSchema. 10 events: meditation started/completed/generated,
journal created/updated, session started/ended, progress updated, teacher
interaction, content downloaded.
Tara (tara.ts) — single event tara.ritual.completed. Enums:
TaraRitualMomentSchema, TaraRitualTemplateModeSchema
(guided/adaptive/recovery), TaraRitualCompletionStateSchema,
TaraRitualCompletionQualitySchema, TaraReflectionStateSchema,
TaraCompletionHandoffDomainSchema (arete/nisaba/nyx). The payload
carries ritual identity, completion metrics, step accounting, reflection state,
search text, and exactly three TaraRitualCompletionHandoffSchema cross-domain
handoffs (.min(3).max(3)) — one for each downstream domain.
Aphrodite (aphrodite.ts) — StreamTypeSchema
(public/private/ticket/group/fan_club), StreamStatusSchema,
DeviceCommandSchema (vibrate/rotate/stop/pattern),
DeviceTriggerTypeSchema. 24 events: stream started/ended, viewer-count
updated, goal reached; transaction events (tip received, tokens purchased,
subscription created/cancelled, payout requested/completed); user events
(registered, verified, followed, banned); device events (connected,
control-sent, state-updated); chat events (message-sent, user-muted); moderation
events (content-flagged, content-reviewed); content events (recording-ended,
vod-published, clip-created).
Nyx (nyx.ts) — common celestial schemas: CelestialObjectTypeSchema,
CoordinateSystemSchema, EquatorialCoordsSchema, HorizontalCoordsSchema,
ObserverLocationSchema, CelestialEventTypeSchema, LunarPhaseSchema,
SeeingConditionSchema. 24 events grouped by service — Catalog (object viewed,
observation logged/updated, view saved, list created, list-item observed,
achievement unlocked, tour started/completed), Compute (ephemeris updated,
event/eclipse/conjunction predicted, satellite pass), Render (tile generated,
export ready, cache invalidated), Realtime (satellite visible, ISS pass, meteor
peak, aurora alert, event imminent), Catalog updates (TLE updated, orbital
updated). Also defines request schemas (NyxConeSearchRequestSchema,
NyxEphemerisRequestSchema, NyxRiseSetRequestSchema,
NyxSatellitePassRequestSchema, NyxTileRequestSchema,
NyxWebSocketSubscriptionSchema) and the NyxContracts aggregate object.
Psyche (psyche.ts) — SessionChannelSchema, SessionEndReasonSchema,
MemoryTypeSchema, EmotionSchema, SentimentSchema
(positive/negative/neutral/mixed), EmotionSourceSchema
(voice/text/facial/multimodal), ToolExecutionStatusSchema,
ParticipantRoleSchema, ActionUnitChangeSchema, VisemeSchema. 37 events
across session, avatar, voice, memory, persona, tool-execution, conferencing,
emotion, and error categories. Exports PsycheEventType.
Veritas (veritas.ts) — ArticleStatusSchema, CredibilityRatingSchema,
SentimentLabelSchema, AlertSeveritySchema
(info/warning/critical/emergency), plus SourceInfoSchema,
AuthorInfoSchema, TopicScoreSchema, KeywordWeightSchema,
EntityRefSchema. 27 events covering article
lifecycle/ingestion/enrichment/clustering, claim/fact-check, story clusters,
feeds, video/audio generation, alerts, analytics, and NLP processing.
Concordia (concordia.ts) — events for the Concordia mediation substrate.
Enums: ConcordiaUseCaseClassSchema (14 classes from low_stakes_personal to
simulation_only), ConcordiaOperationalModeSchema (9 modes),
ConcordiaSearchKernelSchema (9 kernels: nash_genetic, nsga_ii,
map_elites, mcts_lats, cp_sat, milp, bayesian_optimization, psro,
coalition_stability), ConcordiaEscalationPrioritySchema (p0–p3). 12
events: case created, party joined, intake completed, issue identified,
preference updated, offer generated, offer compared, search completed, draft
reviewed, settlement accepted, execution completed, escalation required.
Payloads carry only identifiers and viewer-safe metadata — private party fields
are never included. Exports ConcordiaEventTypes, ConcordiaEventType, and
ConcordiaEventSchemaRegistry (every Concordia event schema keyed by type).
Additional @oshun/contracts Subpaths#
The following subpaths expose canonical contract surfaces for specific domains.
In each case, the contract is owned here — in the zero-upstream contracts layer
— rather than in the domain library itself, so the domain library can import
from it without risk of circular dependencies. Each section notes where the
subpath is distinct from the events/ module for the same domain.
@oshun/contracts/llm (src/llm/)#
Canonical LLM-gateway contract — the single source of truth for the
IsisLLMClient interface. Modules: primitives.ts, messages.ts, tools.ts,
request.ts, response.ts, stream.ts, errors.ts, client.ts. Exports the
request/response/streaming schemas, a typed error taxonomy, pricing-unit
primitives, LLMModelDescriptorSchema, LLMProviderStatusSchema, and the
IsisLLMClient interface. A ./llm/test-utils subpath provides a gateway test
double.
@oshun/contracts/aja (src/aja/)#
Canonical contract surface for the Aja domain (motion AI / embodied
instruction), MVP scope. Modules: primitives.ts (Quaternion, Vector3,
SkeletonPose), formats.ts (BVH / FBX / glTF / USD / Alembic / C3D / CSV motion
formats and asset references), jobs.ts (job status, priority,
submit/status/cancel lifecycle), embodied-instruction.ts (movement
demonstration, coaching overlay, session handoff, capability discovery).
@oshun/contracts/arete (src/arete/)#
Habit / goal canonical contracts. Enums include CheckInStatusSchema
(done/partial/skip/decline/miss), HabitCadenceKindSchema,
DeclaredDifficultySchema (tiny/easy/moderate/hard/stretch),
GoalTimeframeSchema, GoalScopeSchema, GoalStatusSchema.
@oshun/contracts/tara (src/tara/)#
Contemplative-practice canonical contracts. Enums include MoodTaxonomySchema
(12 moods), ThemeTaxonomySchema (15 themes), ModalityTaxonomySchema (silent,
guided, breathwork variants, sound variants). Re-exports ./playback-rate (also
a ./tara/playback-rate subpath).
@oshun/contracts/nyx (src/nyx/)#
Nyx V1 canonical contracts — distinct from the events/nyx.ts module. While
events/nyx.ts defines the Kafka event envelope types, this subpath defines the
domain-specific sky-event taxonomy used by the Nyx catalog and observation
services. Enums include SkyEventFamilySchema (11 families: meteor-shower,
eclipse, conjunction, occultation, transit, comet, aurora, satellite-pass,
supermoon, seasonal-marker, deep-sky-peak) and SkyEventTypeSchema (25 specific
event types).
@oshun/contracts/metis (src/metis/)#
Learning / tutoring canonical contracts. Enums include MetisDifficultySchema,
CourseStatusSchema (draft/review/published/archived),
ContentTypeSchema (text/video/interactive/quiz/code_exercise),
GroundingScopeKindSchema. The root barrel re-exports prefixed schemas:
MetisAcademicIntegrityVerdictSchema, MetisAssessmentEvidencePackSchema,
MetisCourseBuildSchema, MetisGroundingPackSchema,
MetisLearningObjectiveMapSchema, MetisLearningSourceBundleSchema,
MetisLearningTelemetryStatementSchema, MetisLessonAssetBundleSchema,
MetisPublicationPackageSchema, MetisTutorPersonaProfileSchema,
MetisTutorSessionMemorySchema (and the MetisContracts aggregate).
@oshun/contracts/nisaba (src/nisaba/)#
Manuscript / scholarship canonical contracts. Enums include
NisabaLanguageSchema, NisabaScriptSchema (latin, greek, hebrew, arabic,
devanagari, pali-sinhala, coptic, cuneiform, tibetan, chinese, japanese, syriac,
ethiopic, other), TextDirectionSchema
(ltr/rtl/vertical/boustrophedon), TextFormatSchema,
PassageStatusSchema, ReviewStateSchema, PartOfSpeechSchema. The root
barrel re-exports prefixed schemas: NisabaAnnotationSchema,
NisabaCitationSchema, NisabaConceptGraphEdgeSchema,
NisabaConceptGraphNodeSchema, NisabaEditionSchema,
NisabaLexiconEntrySchema, NisabaManuscriptSchema,
NisabaMorphologyEntrySchema, NisabaNotebookSchema, NisabaPassageSchema,
NisabaScholarProfileSchema, NisabaStudyPlanSchema, NisabaTranslationSchema
(and the NisabaContracts aggregate).
Living Scene (src/living-scene/)#
Living Scene canonical contracts (score schema and technique catalog). Modules
technique.ts and score.ts. The root barrel re-exports these under
LivingScene* prefixes: LivingSceneCinematographicTechniqueSchema,
LivingSceneTechniqueIdSchema, LivingSceneTechniqueToneBandSchema,
LivingScenePinnedTechniqueSchema, LivingSceneTechniqueCatalogVersionSchema,
LivingSceneScoreSchema, LivingSceneSegmentSpecSchema,
LivingSceneCueSpecSchema, LivingSceneRenderEnvelopeSchema, the
deepParseLivingSceneScore helper, and the LivingSceneContracts aggregate.
@oshun/contracts/veritas (src/veritas/)#
Veritas V1 canonical contracts — distinct from events/veritas.ts. Where
events/veritas.ts defines Kafka event types, this subpath defines the
domain-specific editorial and fact-check taxonomy used by Veritas article
processing. Modules index.ts and attestor.ts. Enums include
SourceKindSchema (peer-review, primary, secondary, press-release,
opinion, social, government, ngo, wire, dataset, …). The root barrel
re-exports prefixed schemas: VeritasClaimSchema,
VeritasClaimConfidenceBandSchema, VeritasCorrectionNoteSchema,
VeritasCounterclaimSchema, VeritasEvidencePackSchema,
VeritasRetractionCascadeSchema (plus its job-action/job-status/target-kind
enums), VeritasSourceSchema, VeritasSourceKindSchema, VeritasStorySchema,
VeritasStoryUpdateSchema, VeritasStoryUpdateKindSchema,
VeritasTimelineSchema, VeritasTopicHubSchema (and the VeritasContracts
aggregate).
Iris Memory Contracts (src/iris/)#
src/iris/ contains entry.ts and continuation.ts, re-exported from the root
barrel and as the IrisContracts aggregate. This is distinct from the separate
@iris/contracts package in libs/contracts/iris/ — the subpath here covers
the Iris memory entry and continuation contracts that other domains may
reference; the sibling package covers the full Iris AI Assistant contract
surface.
Agent Contracts (src/agent/)#
AgentContracts aggregate — modules tools.ts (tool catalog) and
tool-grants.ts (grants). These define the cross-domain contract for which
tools are available to agents and what permission grants govern their use.
@oshun/contracts/v3 (src/v3/)#
V3 Lilith metaverse / Tara Studio / Saraswati Stage contracts. Modules:
primitives.ts, lilith.ts, tara.ts, saraswati.ts, commons.ts,
consent.ts, fixtures.ts, registry.ts, openapi.ts. Re-exported from the
root barrel both flat and under the V3Contracts namespace.
Sibling Contract Packages (libs/contracts/<sub>/)#
The directory libs/contracts/ hosts the following separate Nx libraries,
each with its own package.json, project.json, and tsconfig. They are not
subpaths of @oshun/contracts. Each depends only on zod and follows the same
zero-upstream-dependency rule.
@iris/contracts (libs/contracts/iris/)#
API contracts and Zod schemas for the Iris AI Assistant. Organized into four
subpaths (./common, ./conversation, ./memory, ./agent), each covering a
distinct concern:
- Common — identifier schemas (
IdSchema,ConversationIdSchema,MessageIdSchema,UserIdSchema,AgentIdSchema,MemoryIdSchema), timestamps, pagination,ApiErrorSchema/ErrorCodeSchema, health checks,TokenUsageSchema/CostSchema,ModelProviderSchema/ModelConfigSchema. - Conversation — message content blocks (
TextContentBlockSchema,ImageContentBlockSchema,ToolUseContentBlockSchema,ToolResultContentBlockSchema),MessageSchema,ConversationSchema(with status/settings),ConversationWithMessagesSchema, list request/response, streaming (StreamEventTypeSchema,StreamEventSchema). - Memory — tiered memory model:
MemoryTierSchema,MemoryTypeSchema, Core memory (CoreMemoryBlockSchema,CoreMemoryStateSchema), Working memory (WorkingMemoryEntrySchema,WorkingMemoryStateSchema), Archival memory (ArchivalMemoryEntrySchema,SearchArchivalMemory*), Episodic memory (EpisodicMemoryEntrySchema,QueryEpisodicMemory*),MemoryOperationSchema, fullMemoryStateSchema. - Agent — tool definitions (
JsonSchemaSchema,ToolDefinitionSchema,ToolExecutionRequestSchema/ToolExecutionResultSchema), agent config (AgentSchema,AgentTypeSchema,AgentCapabilitySchema,AgentStatusSchema), agent execution (AgentExecutionSchema,ExecutionStepSchema,RunAgentRequest/Response), built-inMEMORY_TOOLS/MemoryToolNameSchema.
Depends only on zod.
@psyche/contracts (libs/contracts/psyche/)#
Domain contracts for Psyche — the hyper-realistic AI virtual assistant
platform for video conferencing. src/index.ts currently re-exports
./common/index.js only; the comment notes that avatar/voice/behavior/
perception/conferencing/knowledge/persona modules will be added as services are
migrated. Depends only on zod.
@concordia/contracts (libs/contracts/concordia/)#
API contracts for Concordia cooperative mediation and negotiation — a large
library (~100 feature directories under src/). The barrel currently exports
two surfaces. The use-case classification surface exports
ConcordiaUseCaseClassSchema, UseCaseClassProfileSchema,
USE_CASE_CLASS_PROFILES, getUseCaseClassProfile,
allowsAutonomousAcceptance, isEligibleForConcordia, and related helpers. The
hard-boundary surface exports HardBoundaryKindSchema, HARD_BOUNDARY_RULES,
HardBoundaryRuleSchema, HardBoundaryViolationSchema, getHardBoundaryRule,
getPresumptivelyActiveBoundaries, mayFacilitateUnderBoundary, and related
helpers. The src/ tree additionally contains directories for the case model,
parties, issues, agreements, the agreement DSL (dsl/), preferences, settlement
lifecycle, access/authority/consent, escalation, search, oversight, and many
domain-integration modules. Phase 179 follow-on tasks extend the barrel exports.
Depends only on zod.
@freya/contracts (libs/contracts/freya/)#
API contracts and Zod schemas for the Freya luxury goods domain. Modules:
product-schemas.ts, order-schemas.ts, customer-schemas.ts,
manufacturing-schemas.ts.
@contracts/brigid (libs/contracts/brigid/)#
Cross-domain API contracts for the Brigid industrial domain. Modules:
events.ts, api-schemas.ts, cross-domain.ts, integration.ts.
@contracts/cybele (libs/contracts/cybele/)#
Contracts for the Cybele domain (construction / infrastructure). Modules:
api-schemas.ts, events.ts.
@contracts/saraswati (libs/contracts/saraswati/)#
Cross-domain integration contracts connecting Saraswati to other Oshun
domains. Each module defines the integration adapter for one pairing:
brigid.ts (Saraswati↔Brigid manufacturing), asase.ts (↔Asase
agriculture/food), freya.ts (↔Freya e-commerce/retail), cybele.ts (↔Cybele
construction/infrastructure), and maat.ts (↔Maat knowledge/IP).
@maat/contracts (libs/contracts/maat/)#
Near-empty package. src/index.ts exports only the
MaatContractEnvelope<TPayload> interface ({ type, version, payload }). The
subdirectories (agents/, compliance/, core/, dashboard/,
digital-twin/, finance/, intelligence/, knowledge/, strategy/,
supply-chain/) contain only .gitkeep files. The Maat contract surface is
effectively a scaffold awaiting implementation.
libs/contracts/veritas/#
Contains only a .gitkeep file — an empty placeholder directory. The
implemented Veritas canonical contracts live in @oshun/contracts/veritas, i.e.
libs/contracts/src/veritas/.
Validation Usage#
The following code examples show the three most common patterns for using the contracts validation layer at a service boundary. Each pattern corresponds to a different trust context: validating a full inbound event from Kafka, validating a payload by known type, and validating an entity at an HTTP API boundary.
// Validate an event envelope and (if registered) its specific schema
import { validateEvent } from '@oshun/contracts/events';
const result = validateEvent(rawEvent);
if (!result.success) console.error(result.errors);
// Validate just a payload by event type
import { validatePayload } from '@oshun/contracts/events';
const r = validatePayload('isis.job.completed', payload);
// Build a typed event schema
import { createEventSchema } from '@oshun/contracts/events';
// Validate a common entity at an API boundary
import { UserSchema } from '@oshun/contracts/common';
const parsed = UserSchema.safeParse(req.body);
createValidationMiddleware and createPublishValidator wrap validateEvent /
validatePayload for consumer and publisher integration, in strict or
non-strict (warn-and-continue) mode.
Contract Alignment Testing#
The contracts package ships its own test suite to verify that schemas stay correct as the platform evolves. These tests catch two common classes of schema drift: a Prisma migration that changes a column type without updating the contract, and a new required contract field that has no corresponding database migration.
src/contracts.spec.ts— self-consistency tests over common primitives and the User/Asset/event schemas.src/common/contract-prisma-alignment.test.ts— verifies contract schema types stay structurally consistent with Prisma models.src/common/contract-prisma-migrations.test.ts— verifies new required contract fields have corresponding database migrations.src/common/domain-to-substrate-compatibility.test.ts,src/common/job-orchestration.integration.test.ts,src/common/claim-passage-source-linkage.integration.test.ts, and the per-file*.spec.ts/*.test.tssuites validate domain-correct behaviour of the individual entity contracts.- Each sibling package (
iris,concordia,brigid,cybele,freya,saraswati) carries its own*.test.ts/contracts.test.ts/cross-domain.test.tssuites.