# Proto Domain — Features

> **`@oshun/proto`** is the Protocol Buffer definition library for all Oshun
> inter-service gRPC communication. It defines every `.proto` service and
> message file, provides a runtime TypeScript loader, exports gRPC service
> metadata, and integrates with the `buf` toolchain for linting and breaking
> change detection. While REST over HTTP is used for external-facing APIs
> (documented in `@oshun/openapi`), gRPC is used for internal service-to-service
> communication where lower latency, bidirectional streaming, and strongly-typed
> binary serialization are critical. Protocol Buffers — the serialization format
> underlying gRPC — produce a substantially smaller wire size than JSON and can
> generate client code for every supported language from a single schema
> definition. The `src/` directory is organized by service domain.

---

## Protocol Buffer Service Definitions

Twenty-eight `.proto` files live in `libs/proto/src/`, organized one directory
per service domain. The `buf` tool (configured via `buf.work.yaml`,
`src/buf.yaml`, and `buf.gen.yaml`) validates proto syntax, checks for breaking
changes, and runs code generation. Every `.proto` is `syntax = "proto3"` with an
`oshun.<domain>` package; the runtime loader (`loadProto`) parses schemas with
`@grpc/proto-loader`.

The sections below walk through each service group, calling out the RPC
categories, streaming modes, and key message types a new engineer needs to
understand before using the service.

### Agent Services (`agent/`)

`agent.proto` defines `AgentService` (28 RPCs) for the lifecycle and
communication of autonomous AI agents within the platform. It covers everything
from spinning an agent up and monitoring its health, to routing tasks to it and
streaming its output back in real time.

- **Agent Registration & Management** — `RegisterAgent`, `GetAgent`,
  `UpdateAgent`, `DeregisterAgent`, `ListAgents`. Register an agent instance
  with its `AgentConfig` (concurrency, timeouts, allowed task types) and
  `AgentResources` (CPU/memory/disk/GPU), then look it up or retire it.
- **Agent Lifecycle** — `StartAgent`, `StopAgent`, `RestartAgent`, `Heartbeat`.
  Control lifecycle transitions; `Heartbeat` reports `AgentResourceUsage` and
  receives `AgentCommand`s back as the agent's control channel.
- **Task Management** — `AssignTask`, `GetTask`, `UpdateTaskStatus`,
  `CancelTask`, `ListTasks`. Distribute work across the pool, carrying free-form
  `google.protobuf.Struct` task input/output.
- **Task I/O Streaming** — `StreamTaskOutput` (server-streamed `TaskOutput`
  bytes) and `SendTaskInput`. Stream a running task's stdout/stderr-style output
  and push input back to it.
- **Agent Pools** — `CreatePool`, `GetPool`, `UpdatePool`, `DeletePool`,
  `ListPools`, `AddAgentToPool`, `RemoveAgentFromPool`. Autoscaling pools
  (`PoolConfig` with min/max agents, target utilization, scale thresholds).
- **Inter-Agent Messaging** — `SendMessage`, `StreamMessages` (server-streamed
  `AgentMessage`), `BroadcastMessage`. Typed message passing between agents.
- **Metrics** — `GetAgentMetrics`, `GetPoolMetrics`. Per-agent and per-pool
  throughput, utilization, and task-history metrics.

### AI Services (`ai/`)

`ai.proto` defines `AIService` (26 RPCs) — the cross-provider AI generation
surface for text, image, audio, speech, 3D, code, and embeddings. Most media
generation RPCs follow an async pattern: they return a job handle immediately,
and a separate result-fetch RPC retrieves the finished artifact once the job
completes.

- **Text Generation** — `GenerateText` and the server-streaming
  `StreamGenerateText` (emits `TextChunk`s). `GenerateTextRequest` carries the
  prompt, optional system prompt, provider/model selectors, and sampling
  controls (`max_tokens`, `temperature`, `top_p`, `stop_sequences`).
- **Async Media Generation** — `GenerateImage`, `GenerateAudio`,
  `GenerateSpeech`, `Generate3DModel` each return a `GenerateJobResponse` job
  handle; `GetImageResult`, `GetAudioResult`, `Get3DModelResult` retrieve the
  finished artifact once the job completes.
- **Code Generation** — `GenerateCode` and the server-streaming
  `StreamGenerateCode` (emits `CodeChunk`s).
- **Embeddings** — `GenerateEmbeddings` returns floating-point vectors;
  `SearchSimilar` does nearest-neighbour lookup against a vector collection.
- **Job Management** — `GetJob`, `ListJobs`, `CancelJob`, `RetryJob`.
- **Prompt Templates** — `ListPromptTemplates`, `CreatePromptTemplate`,
  `GetPromptTemplate`, `UpdatePromptTemplate`, `DeletePromptTemplate`,
  `RenderPromptTemplate`.
- **Usage & Providers** — `GetUsageStats`, `ListProviders`, `GetProviderStatus`.
  The `AIProvider` enum covers Anthropic, OpenAI, Google, Stability, ElevenLabs,
  Replicate, and a local provider.

### Asset Services (`asset/`)

`asset.proto` defines `AssetService` (23 RPCs) for asset management across the
platform's creative services and the shared storage layer. Rather than uploading
through the gRPC call itself, the service uses a two-phase upload pattern:
`CreateAsset` returns a pre-signed URL for direct-to-storage upload, then
`CompleteUpload` finalizes the record once the upload is done. This keeps large
binaries out of the gRPC message path.

- **Two-Phase Upload** — `CreateAsset` returns an `upload_url` (pre-signed,
  direct-to-storage) plus an expiry and size cap; the client uploads, then calls
  `CompleteUpload`. `CreateVersion` mirrors this flow for new versions.
- **Asset CRUD** — `GetAsset`, `UpdateAsset`, `DeleteAsset`, `ListAssets`,
  `GetDownloadUrl`. The `Asset` message carries type/status, size, mime,
  `Thumbnails`, and per-type `AssetMetadata`.
- **Locking** — `LockAsset`, `UnlockAsset`. Editorial locks recorded as
  `locked_by`/`locked_at` on the asset.
- **Versioning** — `ListVersions`, `GetVersion`, `RestoreVersion`.
- **Folders & Moves** — `ListFolders`, `CreateFolder`, `GetFolder`,
  `UpdateFolder`, `DeleteFolder`, `MoveFolder`, `MoveAsset`.
- **Bulk Operations & Search** — `BulkOperation` (move/delete/archive/tag) and
  `SearchAssets`.
- **Processing Callback** — `UpdateProcessingStatus` is the internal RPC the
  processing pipeline uses to push status, metadata, and thumbnails back.

### Authentication Services (`auth/`)

`auth.proto` defines `AuthService` (18 RPCs, all unary) — user-facing auth flows
plus the inter-service token-validation surface. The two token-validation RPCs
(`ValidateToken`, `GetTokenClaims`) are what allow other services to
authenticate an incoming gRPC call without making an HTTP round-trip to a
separate auth endpoint.

- **Token Validation** — `ValidateToken` returns a `ValidateTokenResponse`
  (valid flag + optional user id); `GetTokenClaims` returns full `TokenClaims`
  (user id, email, role, permissions, expiry, session id). These let service
  interceptors authenticate incoming gRPC calls without an HTTP round-trip.
- **Authentication Flows** — `Login`, `Register`, `Logout`, `RefreshToken`.
  `Login`/`Register` return an `AuthResponse` carrying the user and a
  `TokenPair`.
- **Password & Email** — `RequestPasswordReset`, `ConfirmPasswordReset`,
  `ChangePassword`, `VerifyEmail`, `ResendVerificationEmail`.
- **Session Management** — `ListSessions`, `RevokeSession`, `RevokeAllSessions`.
- **API Keys** — `ListApiKeys`, `CreateApiKey`, `DeleteApiKey`,
  `ValidateApiKey`. `CreateApiKey` returns the full key once; `ApiKey` records
  never carry the raw key thereafter.

### Bridge Services (`bridge/`)

The `bridge/` directory holds three engine and DCC (Digital Content Creation)
bridge services — gRPC control surfaces over a running Blender, Godot, or Unreal
Engine instance. An addon or plugin installed inside the DCC application
connects back over gRPC, and these service definitions describe the RPC surface
the platform uses to drive it programmatically.

- **Blender Bridge** — `blender.proto` defines `BlenderBridgeService` (32 RPCs):
  connection, scene/object/material/animation operations, frame and sequence
  rendering (`RenderSequence` server-streams `RenderProgress`), Python script
  execution (`ExecuteScript`, `StreamExecuteScript`), asset import/export, and
  an event stream.
- **Godot Bridge** — `godot.proto` defines `GodotBridgeService` (28 RPCs):
  connection, project/scene operations, scene-tree node CRUD, resources,
  scripts, signal emit/connect (`StreamSignals`), project run/export
  (`ExportProject` server-streams `ExportProgress`), and an event stream.
- **Unreal Bridge** — `unreal.proto` defines `UnrealBridgeService` (56 RPCs, the
  largest service in the library): connection, project build (`BuildProject`
  server-streams `BuildProgress`), level/actor/component operations, blueprints,
  materials, animation and sequencer control, asset import/export, viewport
  capture and sequence rendering, Play-In-Editor, console/Python execution, and
  event/log streams.

### Collaboration Services (`collaboration/`)

`collaboration.proto` defines `CollaborationService` (32 RPCs) for real-time
multi-user creative sessions. It is the only core service that uses a
bidirectional stream — `SyncDocument` exchanges operational-transform frames in
both directions simultaneously to keep all participants' document state
synchronized without a round-trip delay for each keystroke.

- **Sessions** — `CreateSession`, `GetSession`, `EndSession`, `ListSessions`,
  `JoinSession`, `LeaveSession`.
- **Real-Time Document Sync** — `SyncDocument` is a bidirectional stream of
  `DocumentUpdate` frames carrying operational-transform `Operation`s.
  `GetDocumentState` and `ApplyOperation` are the non-streaming counterparts.
- **Presence & Cursors** — `UpdatePresence`, `GetPresence`, `StreamPresence`
  (server-streamed `PresenceUpdate`); `UpdateCursor`, `StreamCursors`
  (server-streamed `CursorUpdate`).
- **Locks** — `AcquireLock`, `ReleaseLock`, `GetLocks`, `ForceReleaseLock`
  (`LockType` is exclusive or shared).
- **Comments & Threads** — `CreateThread`, `GetThread`, `ResolveThread`,
  `ListThreads`, `AddComment`, `UpdateComment`, `DeleteComment`.
- **Reviews** — `RequestReview`, `SubmitReview`, `GetReview`, `ListReviews`.
- **Activity Feed** — `LogActivity`, `StreamActivity` (server-streamed
  `Activity`), `GetActivityHistory`.

### Common and Shared Types (`common/`, `shared/`)

`@oshun/proto` has two distinct "shared" directories that serve different
purposes. Understanding the distinction is important: `common/` is a pure type
vocabulary, while `shared/` is a collection of product-facing service contracts.

**`common/types.proto`** (package `oshun.common`) — pure shared message types
imported by every domain `.proto`. Defining them once prevents drift between
service contracts:

- **`UUID`** — a string wrapper used as the branded identifier type across
  services.
- **Pagination** — `PaginationRequest` (page, limit, sort_by, order) and
  `PaginationMeta` (page/limit/total/total_pages/has_next/has_previous) shared
  by every list RPC.
- **`Error` / `FieldError`** — structured error with a code, message, request
  id, and field-level validation details.
- **`Empty` / `SuccessResponse`** — the no-payload request/response pair; most
  domain RPCs returning "no data" return `common.SuccessResponse`.
- **Health types** — `HealthCheckRequest`/`HealthCheckResponse` and
  `ServiceCheck`, with `HealthStatus` and `SortOrder` enums.

**`shared/*.proto`** — these are _not_ a type bag; they are five product-facing
substrate contracts (`shared/common.proto` plus the evidence, memory,
persona-policy, and generation-control services), described under "OSHUN Shared
Substrate Services" below.

### Generation Services (`generation3d/`, `procedural/`, `splatting/`)

Three services form the Isis generative factory's 3D content creation pipeline.
Each handles a different technique: `generation3d` creates geometry from text or
images using AI models, `splatting` reconstructs real-world scenes from photo
capture using Gaussian Splatting and NeRF, and `procedural` generates large
environments algorithmically using Houdini.

- **3D Content Generation** — `generation3d.proto` defines `Generation3DService`
  (23 RPCs): text-to-3D (`TextToModel`, `BatchTextToModel`), image-to-3D
  (`ImageToModel`, `MultiViewToModel`), mesh processing (`OptimizeMesh`,
  `GenerateLODs`, `AnalyzeMesh`, `UnwrapUVs`, `CleanupMesh`), auto-rigging
  (`AutoRig`, `GenerateWeights`, `SetupIKFK`), texture generation, and job
  management. Generation RPCs return job handles; three server-streams emit
  progress.
- **Gaussian Splatting Pipeline** — `gaussian_splatting.proto` defines
  `GaussianSplattingService` (37 RPCs) for the 3D Gaussian Splatting and NeRF
  pipeline (a photogrammetry technique that reconstructs 3D scenes from photos
  as a cloud of coloured 3D Gaussian functions): capture (`UploadFrames` is a
  client-stream), training (`TrainSplat`, `StreamTrainingProgress`), NeRF
  training/conversion, rendering, export, and model management.
- **Procedural Generation** — `procedural.proto` defines `ProceduralGenService`
  (41 RPCs) — Houdini-based procedural generation of terrain, cities, biomes,
  dungeons, space environments, and asset scatter (`GenerateTerrain`,
  `GenerateCity`, `GenerateBiome`, `GenerateDungeon`, `GenerateStarSystem`,
  `ScatterAssets`, …), each generation RPC returning a job handle with a
  server-streamed progress companion per category.

### Health Services (`health/`)

`health.proto` defines `HealthService` (2 RPCs) — the standard gRPC
health-checking pattern used by service meshes and load balancers to determine
whether an instance is ready to serve traffic. Two RPCs cover two different
consumption patterns: synchronous polling and a persistent push stream.

- **Liveness Check** — `Check(HealthCheckRequest) → HealthCheckResponse`.
  Modelled on the gRPC Health Checking Protocol. The `ServingStatus` enum is
  `SERVING`, `NOT_SERVING`, `SERVICE_UNKNOWN`, plus an `UNKNOWN` zero value.
- **Health Watch** — `Watch(HealthCheckRequest) → stream HealthCheckResponse`.
  Server-streams status updates whenever a service's health changes, rather than
  polling.

> Note: this `health/health.proto` `HealthCheckRequest`/`HealthCheckResponse`
> pair is distinct from the richer pair of the same names in
> `common/types.proto` — they are different messages.

### Isis Services (`isis/`)

`isis.proto` declares four services for the generative factory's internal
interface — the RPC surface used by the generation worker pool, the job queue,
and tooling that needs to inspect what the factory is producing.

- **`IsisJobService` (11 RPCs)** — job lifecycle (`SubmitJob`, `GetJob`,
  `ListJobs`, `CancelJob`, `RetryJob`), `StreamJobProgress` (server-streamed
  `JobProgressUpdate` for live UI progress bars), batch submission
  (`SubmitBatch`, `GetBatch`), and queue management (`GetQueueStats`,
  `PauseQueue`, `ResumeQueue`).
- **`IsisWorkflowService` (12 RPCs)** — workflow CRUD, versioning
  (`CreateWorkflowVersion`, `SetActiveVersion`, …), `ValidateWorkflow`, and
  templates.
- **`IsisOutputService` (7 RPCs)** — output retrieval, provenance
  (`GetProvenance`, `GetLineage`), and export (`ExportOutput`, `ExportBatch`
  which server-streams `ExportProgressUpdate`).
- **`IsisModelService` (8 RPCs)** — model registry CRUD and status, including
  `LoadModel` which server-streams `ModelLoadProgress`.

### Load Balancing (`loadbalancing/`)

`loadbalancing.proto` defines `LoadBalancingService` (5 RPCs) — dynamic load
balancing configuration for the platform's service mesh. Rather than relying
solely on static infrastructure configuration, this service lets the platform
report real latency observations and update routing policy in response.

- **Endpoint Discovery** — `GetEndpoints` returns healthy `Endpoint`s with their
  weights, priorities, and `Locality`; `WatchEndpoints` server-streams
  `EndpointUpdate`s as endpoints are added, removed, or reweighted.
- **Health Reporting** — `ReportHealth` lets a client report observed endpoint
  health and `LatencyStats` (p50/p90/p99/avg).
- **Policy** — `GetPolicy` and `UpdatePolicy` manage a `LoadBalancingPolicy`
  bundling a `LoadBalancingStrategy` (round-robin, weighted, pick-first, least-
  connections, random, ring-hash, locality-aware), retry policy, circuit
  breaker, outlier detection, and locality config.

### Pipeline Services (`pipeline/`)

`autonomous_pipeline.proto` defines `AutonomousPipelineService` (43 RPCs). This
service models the end-to-end lifecycle of an autonomous game or movie project —
not a generic data transformation pipeline. A project is created from a
free-text prompt; the service then drives it through pre-production, production,
and post-production phases, tracking quality gates and agent assignments along
the way.

- **Project Lifecycle** — `CreateProject` (from a free-text prompt + a
  `ProjectType`), `GetProject`, `ListProjects`, `UpdateProject`,
  `CancelProject`, `ArchiveProject`, `CloneProject`.
- **Phase Execution** — `ExecutePhase`, `GetPhase`, `ListPhases`, `SkipPhase`,
  `RetryPhase`, `PausePhase`, `ResumePhase`. The `PhaseType` enum spans 20
  pre-production, production, post-production, and movie-specific phases.
- **Task Management** — `GetTask`, `ListTasks`, `ExecuteTask`, `RetryTask`,
  `SkipTask`, `AddTask`, `UpdateTaskPriority`.
- **Progress & Streaming** — `GetProgress`, `GetTimeline`, plus `StreamUpdates`
  (server-streamed `PipelineUpdate`) and `StreamAgentActivity` (server-streamed
  `AgentActivity`).
- **Quality Gates, Agents, Assets, Metrics, Templates** — quality gates
  (`RunQualityCheck`, `OverrideQualityGate`, …), agent management, generated-
  asset tracking, metrics/cost/resource analytics, and project templates.

### Project Services (`project/`)

`project.proto` defines `ProjectService` (19 RPCs, all unary) — project
management shared across the platform's creative services. Two RPCs serve as the
internal authorization surface: other services call `CheckAccess` and
`GetUserRole` to verify that a calling user has permission on a given project
without duplicating membership logic in every service.

- **Project CRUD** — `CreateProject`, `GetProject`, `GetProjectBySlug`,
  `UpdateProject`, `DeleteProject`, `ListProjects`.
- **Project Membership** — `ListMembers`, `AddMember`, `UpdateMember`,
  `RemoveMember`.
- **Comments & Activity** — `ListComments`, `CreateComment`, `UpdateComment`,
  `DeleteComment`, `ResolveComment`; `ListActivity`, `LogActivity`.
- **Authorization Checks** — `CheckAccess` and `GetUserRole` are the internal
  authz surface other services call to verify project membership and
  permissions.

### Rendering Services (`rendering/`)

`rendering.proto` defines `RenderingService` (27 RPCs) — render job management
for the platform's asset rendering pipeline. A render job specifies a scene,
engine, resolution, frame range, and quality settings; the service then routes
it to an available render farm node and streams progress back.

- **Render Jobs** — `SubmitJob` (with `RenderSettings`, a `FrameRange`, and a
  `RenderEngine`), `GetJob`, `CancelJob`, `RetryJob`, `ListJobs`, and
  `StreamJobProgress` which server-streams `JobProgress` (frame counts, percent,
  latest `FrameResult`).
- **Previews** — `RequestPreview`, `GetPreviewStatus`.
- **Render Farms & Nodes** — farm CRUD (`ListFarms`, `CreateFarm`, …) and node
  registration (`RegisterNode`, `UpdateNodeStatus`, …).
- **Outputs & Presets** — `GetOutput`, `ListOutputs`, `DownloadOutput`; preset
  CRUD (`ListPresets`, `GetPreset`, `CreatePreset`, …).
- **Statistics** — `GetRenderStats` aggregates per-engine job/frame/time
  metrics.

### Sophia Services (`sophia/`)

`sophia.proto` declares five services for the knowledge engine — document
ingestion, semantic search, citations, and a knowledge graph. The five services
are split by function rather than lumped into one monolith, so a consuming
domain only needs to stand up the capabilities it uses.

- **`SophiaSearchService` (7 RPCs)** — `Search` and `SearchStreaming`
  (server-streamed `SearchResult`), `MultiSearch`, `HybridSearch` (semantic +
  keyword weighting), `AskQuestion` and `AskQuestionStreaming`, `FindSimilar`.
- **`SophiaDocumentService` (9 RPCs)** — `IngestDocument` (returns a
  `DocumentResponse`), `IngestBatch` (server-streams `IngestionProgress`),
  document CRUD, chunk access, and ingestion-job status.
- **`SophiaCitationService` (7 RPCs)** — citation CRUD, `VerifyCitation`,
  `GetCitationSources`.
- **`SophiaKnowledgeGraphService` (16 RPCs)** — entity and relation CRUD, graph
  queries (`GetSubgraph`, `FindPaths`, `GetNeighbors`), and entity resolution
  (`ResolveEntity`, `SuggestMerges`, `MergeEntities`).
- **`SophiaIndexService` (7 RPCs)** — index CRUD, `RebuildIndex` (server-streams
  `RebuildProgress`), `GetIndexStats`.

### Hathor Services (`hathor/`)

`hathor.proto` declares seven services for the worldbuilding and narrative
domain. Each service owns one slice of a world's fiction: the world itself,
factions, characters, locations, timeline, narrative quests, and simulation
runs. The clear split means a narrative editor UI only needs to call
`HathorNarrativeService`, while a procedural-world system can call
`HathorSimulationService` independently.

- **`HathorWorldService` (12 RPCs)** — world CRUD, versioning
  (`CreateWorldVersion`, `RevertToVersion`, …), export/import, `ValidateWorld`.
- **`HathorFactionService` (9 RPCs)** — faction CRUD, faction relations,
  `UpdateFactionResources`, `GetFactionHistory`.
- **`HathorCharacterService` (9 RPCs)** — character CRUD, character relations,
  and dialogue (`GenerateDialogue`, `StreamDialogue` which server-streams
  `DialogueChunk`).
- **`HathorLocationService` (9 RPCs)** — location CRUD, hierarchy, and
  connections.
- **`HathorTimelineService` (11 RPCs)** — timeline CRUD, event CRUD, and event
  dependencies.
- **`HathorNarrativeService` (12 RPCs)** — quest CRUD, quest generation,
  dialogue trees, `ValidateNarrative`.
- **`HathorSimulationService` (7 RPCs)** — simulation runs, `StreamSimulation`
  (server-streams `SimulationUpdate`), and scenario generation/evaluation.

### User Services (`user/`)

`user.proto` defines `UserService` (16 RPCs, all unary) — user profile and
identity operations. The `BatchGetUsers` RPC deserves special attention: it
accepts repeated `UUID`s and returns the corresponding `User` records in one
call, which is how other services hydrate user details (names, avatars, roles)
without making N individual lookups.

- **User Profile** — `GetUser`, `GetUserByEmail`, `GetUserProfile` (the public
  projection), `UpdateUser`, `DeleteUser`.
- **Internal Lookup** — `ListUsers` and `BatchGetUsers`, the cross-service
  user-hydration RPC that takes repeated `UUID` and returns repeated `User`.
- **Preferences & Stats** — `GetPreferences`, `UpdatePreferences`,
  `GetUserStats`.
- **Activity & Notifications** — `ListActivity`, `LogActivity`,
  `ListNotifications`, `MarkNotificationRead`, `MarkAllNotificationsRead`,
  `SendNotification`.

### Reflection Services (`reflection/`)

`reflection.proto` defines `ServerReflectionService` (package
`oshun.reflection`) — the gRPC Server Reflection pattern. This service allows
tools like `grpcurl` and Postman's gRPC client to discover a server's available
services and message types at runtime, without needing the `.proto` files
locally. It is especially useful for debugging and for building generic gRPC
proxies.

- **Server Reflection** — a single bidirectional-streaming RPC
  `ServerReflectionInfo(stream ServerReflectionRequest) → stream ServerReflectionResponse`.
  Lets any gRPC client with reflection support enumerate services, methods, and
  message types from a running server.

> Note: `SERVICE_NAMES.Reflection` in `services.ts` is the string
> `oshun.reflection.ReflectionService`, which does not match the `.proto`-
> declared service name `ServerReflectionService` — see `specifications.md` §13.

### Concordia Services (`concordia/`)

`concordia.proto` declares three streaming-oriented services for cooperative
mediation and negotiation. Because mediation involves multiple parties with
conflicting interests, the file enforces a hard privacy invariant at schema
level: every RPC that surfaces party-generated content is scoped by a viewer
role, and services must apply `@concordia/contracts` projections before emitting
any stream message — private caucus transcripts and internal strategy never
cross to an opposing party's stream.

- **`ConcordiaSessionService` (3 RPCs)** — `StreamSession` (a bidirectional
  stream of audio frames in, transcript/diarization/co-mediator-suggestion
  events out), `PauseSession`, `ResumeSession`.
- **`ConcordiaNegotiationService` (2 RPCs)** — `StreamNegotiation` (a
  bidirectional offer/counter/withdraw/accept stream) and `SubmitOffer`.
- **`ConcordiaSearchService` (2 RPCs)** — `StreamSearchProgress`
  (server-streamed agreement-search progress events) and `CancelSearch`.

### OSHUN Shared Substrate Services (`shared/`)

The `shared/*.proto` files serve a different purpose from the domain service
files above. Where domain services are consumed by platform infrastructure and
engineering backends, the shared substrate services are consumed directly by
OSHUN product domains (Tara, Arete, Veritas, Nyx, Nisaba, and the Assistant
shell). They express cross-cutting product concerns — evidence grounding, memory
continuity, persona policy, and generation control — that every product domain
needs but that no single product domain should own.

`shared/common.proto` carries no service — only cross-substrate enums and a
`SharedContractVersionDescriptor`. The four substrate _services_ are:

- **`OshunEvidenceService`** (`shared/evidence.proto`, 9 RPCs) — Sophia's
  product-facing evidence/grounding surface: `Search`, `Ground` (returns a
  `GroundedAnswer`), `AssembleEvidencePack`, `VerifyClaims`, `SaveToNotebook`,
  `ExportEvidenceTrace`.
- **`OshunMemoryService`** (`shared/memory.proto`, 11 RPCs) — the Iris
  memory/continuity substrate: `Search`, `PlanWrite`, `Remember`, `Forget`,
  `ExportMemory`, plus consent and continuity-state lookups.
- **`OshunPersonaPolicyService`** (`shared/persona_policy.proto`, 10 RPCs) — the
  Lilith persona-policy substrate: `ResolvePolicyPack`, `SelectPolicy`,
  `AssessSafety`, `CheckTopicScope`, `BuildPromptOverlay`,
  `EvaluateInteraction`.
- **`OshunGenerationControlService`** (`shared/generation_control.proto`, 14
  RPCs) — the Isis generation-control plane: `PlanGeneration`,
  `DispatchGeneration`, workflow/model catalogs, provenance, and release
  readiness.

### V2 Game Services (`oshun/v2/persistent_economy/`)

`economy.proto` declares three small services for Section-130 open-world game
systems. These live under a versioned package path
(`oshun.v2.persistent_economy`) to signal that they are part of a newer game
subsystem, separate from the platform infrastructure services above.

The three services are `Economy` (`GetShopInventory`, `GetPriceCurve`,
`RecordTransaction`), `NPCSchedule` (`GetActiveSchedule`), and `CrimeRate`
(`GetDistrictRate`).

---

## Loader and Runtime Utilities

`src/loader.ts` provides the runtime `.proto` loading layer on top of
`@grpc/proto-loader`. It is the bridge between the static schema files and the
live gRPC clients that services instantiate at startup. The key design decision
is that schemas are loaded at runtime from the source `.proto` files (rather
than from pre-generated JS) — this keeps the workflow simple and avoids
committing generated code, at the cost of a small async overhead at startup.

- **`loadProto(path)`** — Asynchronously load a single `.proto` file and return
  the gRPC package object that service constructors are read from. A relative
  path is resolved against `src/`; loader options default to
  `DEFAULT_LOADER_OPTIONS` and may be overridden per call.
- **`loadProtos(paths[])`** — Load several `.proto` files and merge them into
  one package object — every file shares the `oshun` package root.
- **`loadAllProtos()`** — Load every file registered in `PROTO_PATHS` in one
  call; used where a gRPC server registers all services at startup.
- **`getProtoPath(relativePath)`** — A pure path helper that joins a relative
  path onto the `src/` directory and returns the absolute path (it does not load
  or check existence).
- **`PROTO_PATHS`** — A typed `as const` registry mapping a stable key to a
  `.proto` path relative to `src/` (e.g. `PROTO_PATHS.isis` →
  `isis/isis.proto`).
- **`DEFAULT_LOADER_OPTIONS`** — The shared loader configuration:
  `keepCase: true` (field names stay `snake_case`), `longs: String`,
  `enums: String`, `defaults: true`, `oneofs: true`, and two `includeDirs` so
  cross-file imports resolve.

---

## Service Metadata and Channel Utilities

`src/services.ts` exposes the service registry and channel helpers. Together
with `loader.ts`, this module provides everything a consuming service needs to
establish a gRPC connection: the correct fully-qualified service name, the
security credentials, and the channel behavior options.

- **`SERVICE_NAMES`** — A typed `as const` registry mapping a key to a fully-
  qualified gRPC service name (e.g. `SERVICE_NAMES.IsisJob` →
  `oshun.isis.IsisJobService`). Packages carry no `.v1` suffix. Two entries
  (`Procedural`, `Reflection`) do not match their `.proto`-declared service
  names — see `specifications.md` §13.
- **`DEFAULT_CHANNEL_OPTIONS`** — Shared gRPC channel options: keepalive timing,
  HTTP/2 ping settings, and 50 MB inbound/outbound message-size limits. The 50
  MB ceiling accommodates large binary payloads such as captured frame bytes for
  Gaussian Splatting, viewport captures from the engine bridges, and inline
  document content for Sophia ingestion.
- **`createCredentials(secure, rootCerts?, privateKey?, certChain?)`** — A
  channel-credential factory. `secure: false` yields insecure credentials;
  `secure: true` yields server-authenticated TLS, or mutual TLS when a client
  key and chain are supplied.
- **`getServiceMetadata(name)`** — Returns a `ServiceMetadata` (proto path,
  package, and a method-name list) for a registered service. The `methods` lists
  are hand-maintained and have drifted from some `.proto` sources; the `.proto`
  files are authoritative for RPC rosters.

---

## Buf Toolchain Integration

The proto definitions are managed with `buf` for reproducible linting,
breaking-change detection, and code generation. Using `buf` rather than `protoc`
directly means there is no per-developer binary to install — `buf` is invoked
through pnpm, and the schema is linted and generated the same way on every
machine.

- **`buf.work.yaml`** — Declares the buf workspace; its single workspace
  directory is `src`.
- **`src/buf.yaml`** — The single buf module config (`buf.build/oshun/proto`)
  covering the whole `src/` tree. There are no per-domain `buf.yaml` files.
- **`buf.gen.yaml`** — Code-generation config running four plugins: `ts-proto`
  (TypeScript message types + `grpc-js` service stubs → `gen/ts`),
  `protocolbuffers/go` and `grpc/go` (Go types and gRPC stubs → `gen/go`), and
  `chrusty/protoc-gen-jsonschema` (JSON Schema → `gen/jsonschema`). These output
  directories are produced on demand and are not committed.
- **Lint Enforcement** — `buf lint` uses the `DEFAULT` + `COMMENTS` rule groups
  (five rules disabled, including `PACKAGE_VERSION_SUFFIX`), ensuring
  consistent, documented schemas.
- **Breaking Change Detection** — `buf breaking` uses the `FILE` rule group to
  catch breaking changes against a baseline.
- **`generated/buf-image.json`** — The one committed artifact under
  `generated/`: a serialized buf image (a dependency-resolved
  `FileDescriptorSet` of all 28 `.proto` files) used as input for
  breaking-change comparison and generation.
- **`scripts/generate.ts`** — A separate, protobufjs-based (`pbjs`/`pbts`)
  static- module type generator, independent of the buf pipeline.

## Concordia Mediation Streaming RPCs

The Concordia mediation streaming surface is **implemented**:
`libs/proto/src/concordia/concordia.proto` defines the three services described
under "Concordia Services" above, and `proto.spec.ts` loads it and asserts the
three service constructors and their streaming RPC names. The proto owns
streaming contracts for live mediation session transcription, real-time
co-mediator suggestions, offer/counteroffer exchange, and search-progress
updates; each RPC surfacing party content is viewer-role-scoped.

## Scope

This feature document is scoped to `libs/proto/*`. It captures protobuf schema
organization, the runtime loader, service/channel registries, the buf toolchain,
and the per-domain service surface. Proto owns RPC schema mechanics only;
product behaviour and REST contracts are owned by the relevant domain docs and
`DOMAINS/openapi/features.md`.
