# Concordia — Systems Deep Dive

> The `services/concordia/` area: a single Nx **application** — the
> `@concordia/orchestrator` Fastify gateway — that coordinates the cooperative
> mediation and negotiation lifecycle (Phase 179), wrapping a set of pure,
> deterministic mediation worker algorithms behind a lane-aware event bus.

## What this area is

Concordia is the cooperative-mediation and negotiation domain. This service area
holds its runtime side: where the contracts package `@concordia/contracts` owns
the wire types, `services/concordia/orchestrator/` owns the **coordinating
service** that drives a mediation case from intake through preference learning,
agreement search, candidate validation, settlement drafting, review routing, and
execution export. It is one tracked Nx project — `@concordia/orchestrator`
(`services/concordia/orchestrator/project.json`, `projectType: "application"`,
tags `scope:concordia`, `type:app`, `layer:service`).

The README (`services/concordia/orchestrator/README.md`) records the Phase
`179.2.4.5` decision to build this gateway on **Fastify/TypeScript** rather than
Python FastAPI — for repo convention (every other gateway here is Fastify),
contract alignment (the Concordia OpenAPI/gRPC artifacts are TS), and runtime
homogeneity, with Python deliberately confined to future preference/eval/ML
workers and CP-SAT / NSGA-II numerics confined to future Rust/Python solver
sidecars. The orchestrator is explicitly "the coordinating layer, not the
numerics engine."

Internally the project is two layers. The **HTTP surface** (`src/app.ts`,
`src/server.ts`, `src/config.ts`, `src/routes/*`) is a working Fastify server
exposing liveness/readiness/startup health, the Concordia OpenAPI spec, and
service-discovery registration. The **mediation substrate** (`src/workers/*`,
`src/event-bus/*`, `src/observability/*`, `src/tenant-config/*`) is a set of
fully-implemented, unit-tested, pure/deterministic modules implementing the
actual domain logic. The substrate is real code with real algorithms, but —
importantly and honestly — it is **not yet mounted onto the running Fastify
server**: `app.ts` today registers only the health, OpenAPI, and
service-discovery routes. The README's "Next steps" confirms the case / intake /
preference / search routes (`179.3`–`179.4`) are the tasks that plug the
substrate into the gateway. So the substrate is exercised by its own test suites
(`src/workers/*.test.ts`, `src/event-bus/event-bus.test.ts`,
`src/observability/observability.test.ts`,
`src/tenant-config/tenant-config.test.ts`) rather than over HTTP.

## How it fits the wider system

As a `layer:service` application, the orchestrator is the runtime entry point
for Concordia. It serves the canonical Concordia OpenAPI document from
`libs/openapi/src/specs/concordia/concordia-api.yaml` (default resolved in
`src/config.ts`) and advertises itself to internal registries via
`/.well-known/concordia-orchestrator` with a fixed capability set —
`case.lifecycle`, `party.intake`, `preference.inference`, `agreement.search`,
`settlement.drafting`, `review.routing`, `execution.export`, `audit.export`
(`src/routes/service-discovery.ts`). Its event vocabulary mirrors the 12
canonical Concordia events defined in `libs/contracts/src/events/concordia.ts`;
`src/event-bus/types.ts` deliberately re-declares that union as a local string
union rather than importing `@oshun/contracts` at build time, keeping the
contracts library the schema authority while the production transport adapter
does the wiring. The in-memory bus and in-memory job queue are explicitly
documented as dev/test transports whose production swap-in (Redis Streams / NATS
/ Kafka) satisfies the same `ConcordiaEventBus` / `JobQueueSource` interfaces —
honest fail-forward seams, not fabricated success.

## Entity reference

### @concordia/orchestrator

The Concordia mediation orchestrator service (`services/concordia/orchestrator`,
package `@concordia/orchestrator`, `projectType: "application"`). It is both a
working Fastify gateway and the home of Concordia's pure mediation algorithms.

The **gateway** (`src/app.ts`) builds a Fastify instance with CORS, pino
logging, graceful SIGINT/SIGTERM shutdown, and three route groups: health
(`/health`, `/health/ready` with an `openapi_spec` dependency check via
`node:fs/promises` `access`, `/health/startup`), OpenAPI passthrough
(`/openapi.yaml`, `/openapi.json`, `/openapi/metadata` serving the spec from
`libs/openapi/src/specs/concordia/concordia-api.yaml`), and service discovery
(`src/routes/service-discovery.ts`, including a
`POST /service/discovery/register` that POSTs to `SERVICE_REGISTRY_URL` when set
and honestly returns `status: "noop"` when it is not). Config is Zod-validated
in `src/config.ts`.

The **mediation substrate** is where the real domain work lives, and it is
genuinely domain-specific rather than CRUD. `src/workers/runtime.ts` is a
transport-agnostic worker runtime with per-worker concurrency caps, exponential/
linear backoff (`backoffDelayMs`), and dead-letter handling, fed by a
`JobQueueSource` (in-memory `MemoryJobQueueSource`, production Redis-backed).
Six workers implement named algorithms: `intake-summarization.ts` does
**extractive TF-IDF** sentence ranking plus six-dimension intake-completeness
detection via regex patterns; `preference-comparison.ts` runs **Bradley-Terry**
online SGD rating updates with count-shrinkage uncertainty and inconsistent-pair
detection; `search-runs.ts` is a **best-first beam search** scoring candidates
by **geometric mean** of per-objective scores (so no single objective is
sacrificed) with seeded mulberry32 tie-breaking; `candidate-validation.ts` scans
clause text against a hard-boundary rule table (custody, criminal, immigration,
etc.) and PII detectors to emit a pass/flag/block verdict;
`template-matching.ts` ranks legal/policy templates by **k-shingle Jaccard**
similarity; and `settlement-drafting.ts` composes a structured five-section
draft (parties, recitals, obligations, execution, boilerplate) with per-kind
clause bodies and `pendingFields` tracking.

The **event-bus** layer (`src/event-bus/`) routes the 12 Concordia events to
those workers: `in-memory-bus.ts` is a deterministic dev/test bus,
`backpressure-scheduler.ts` enforces a high-lane/low-lane invariant so
long-running batch jobs (search, preference, template) cannot starve user-facing
jobs (intake, validation, drafting), and `orchestrator-bridge.ts` holds the
canonical event→worker routing table plus payload derivers. The
**observability** layer (`src/observability/`) provides a `MetricsRegistry`
(counters/gauges/histograms with p50/p95/p99 latency buckets and the phase's
named series like `concordia_privacy_gate_failures_total`), aggregate KPIs
(`aggregates.ts`: Simpson's diversity index, mean preference uncertainty,
agreement/escalation rates), and an OpenTelemetry-compatible per-case
`CaseTraceCollector`. The **tenant-config** layer (`src/tenant-config/`)
resolves per-tenant policy with
`tenant override > domain override > platform default` precedence, validates it
(`validateTenantConfig`), and runs a per-case `admitCase` admission check over
eligible use-cases, model-route cost caps, disclaimers, and execution-adapter
caps. All four substrate layers are fully implemented and covered by their own
`*.test.ts` suites; the honest gap is that they are not yet wired into the
Fastify routes (the `179.3`–`179.4` work the README flags), and the in-memory
bus/queue are documented dev/test transports pending their production
Redis/NATS/Kafka adapters.
