Part of the RimBank constitution. See also mission.md and roadmap.md. Adding, replacing or removing a technology requires an ADR in
docs/adr/.
| Concern | Choice | Notes |
|---|---|---|
| Runtime / language | .NET (latest GA): currently .NET 10 LTS / C# 14 | Pinned via global.json. Move to each new GA release after the dependencies support it. |
| Solution format | RimBank.slnx |
|
| Build settings | Directory.Build.props / Directory.Build.targets |
Nullable=enable, TreatWarningsAsErrors=true, AnalysisLevel=latest-recommended, ImplicitUsings=enable. Diagnostic severities only in .editorconfig files, never suppressed in code (ADR 0013) |
| Package versions | Central Package Management (Directory.Packages.props) |
No versions in individual .csproj files, no VersionOverride; committed lock files, locked restore in CI, NuGet audit, nuget.org only via NuGet.config (ADR 0013) |
| Database | PostgreSQL | One schema per service domain |
| Event store & documents | Marten | Event-sourced aggregates (write side); inline and async projections for read models (query side). See §8 |
| Messaging / application pipeline | Wolverine | Command and query dispatch, transactional outbox/inbox, integration events, scheduled messages, sagas. Transport is local (in-process, durable) in the modular monolith and RabbitMQ when a context is extracted. |
| API | ASP.NET Core Minimal APIs | Built-in OpenAPI document generation and Scalar UI |
| AI agent interface | Model Context Protocol using the official C# SDK (ModelContextProtocol.AspNetCore) |
Streamable HTTP transport at /mcp. See §6 |
| Error contract | RFC 9457 Problem Details | See §5 and §6 |
| Identity | OpenID Connect / JWT bearer | Keycloak for local development via Aspire (Aspire.Hosting.Keycloak, Aspire.Keycloak.Authentication, previews pinned as AspireKeycloakVersion); Authentication:Authority (HTTPS) elsewhere (ADR 0019) |
| Local orchestration | .NET Aspire (AppHost + ServiceDefaults) | PostgreSQL, Keycloak and later RabbitMQ as Aspire resources |
| Observability | OpenTelemetry (traces, metrics, logs) | Aspire dashboard locally; OTLP exporter in other environments |
| CI | GitHub Actions | Build, test, format, CodeQL, Dependabot |
| Containers | dotnet publish container images |
Non-root, chiseled base images |
- One deployable host (
RimBank.Host) composes all service domains. - Each service domain is a fully isolated bounded context with its own PostgreSQL schema and database role (it has no grants on other schemas), its own Marten store (event streams, read models and async daemon), no shared tables or views, and no use of another context's core. Every context's core is a folder of the one
RimBank.Coreproject, so this isolation is enforced by namespace through the architecture tests, not by project references (ADR 0023). Every context's.Postgresqlregisters its store the same way, throughAddServiceDomainStore<TStore>inRimBank.Postgresql: schema<service_domain>, login rolerimbank_<service_domain>, connection stringConnectionStrings:<ServiceDomain>(ADR 0016). - Each context registers itself in the host through a single module entry point, so the host composes contexts without knowing their internals: one
IServiceDomainModuleclass per context underRimBank.Host/Modules/<BusinessDomain>/, listed explicitly inServiceDomainModules.All, which only calls the context's adapter extension methods (ADR 0014). - Contexts communicate asynchronously through integration events (Wolverine durable local queues with an outbox). The host runs one Wolverine bus; each context's outbox and inbox tables live in its own schema, its handlers commit through its own store, and its messages go to its own durable local queue. Wolverine's own node bookkeeping lives in the host's
wolverineschema, on which no context has grants (ADR 0017). Synchronous cross-context calls are allowed only through an explicit port and need an ADR. - Extracting a context into its own service changes only adapters and host wiring, never the core's code: the context's folder moves out of
RimBank.Coreinto the new service's own core project with unchanged namespaces (ADR 0023), and its HTTP and MCP folders move out ofRimBank.ApiandRimBank.Mcpthe same way (ADR 0025).
RimBank.<BusinessDomain>.<ServiceDomain>[.<Adapter>]
<BusinessDomain>and<ServiceDomain>use BIAN Service Landscape names in PascalCase.- One BIAN service domain = one bounded context.
- The core namespace has no suffix:
RimBank.Party.PartyReferenceDataDirectory. Every context's core (domain and application logic) lives in one project,RimBank.Core, in the folder<BusinessDomain>/<ServiceDomain>/. Its root namespace isRimBank, so the wordCorenever appears in a namespace (ADR 0023). - A context's namespace stops at the context or its adapter (ADR 0026): every core type is in
RimBank.<BusinessDomain>.<ServiceDomain>and every adapter type in….<Adapter>, whatever its folder. Aggregate, Behavior Qualifier and flow folders (§3.4) organise files but are never namespace segments, soRimBank.Party.PartyReferenceDataDirectory.Registrationor….Api.Retrievalis not allowed (context-namespaces-stop-at-the-adapter). A name clash is solved with a better type name, never a namespace segment. Composition projects (RimBank.Host,RimBank.Mcp,RimBank.Api,RimBank.SharedKernel, …) likewise have one namespace each, their own:Host/Security/is a folder of the namespaceRimBank.Host(assembly-names). - A context's adapters add a suffix to its namespace:
.PublishedLanguage,.Api,.Mcp,.Postgresql,.Subscriptions, and later.RabbitMqand so on. There is no per-context core project. - The driving adapters are folders of one shared project each (ADR 0025): every context's HTTP adapter is the folder
<BusinessDomain>/<ServiceDomain>/ofRimBank.Api(namespaceRimBank.<BusinessDomain>.<ServiceDomain>.Api), and its MCP adapter the same folder ofRimBank.Mcp(namespace….Mcp). Each of those projects keeps the conventions its adapters share at its root namespace. There is no per-context.Apior.Mcpproject..PublishedLanguage,.Postgresqland.Subscriptionsare projects of their own, named after their namespace. - Integration events that other contexts consume live in
.PublishedLanguage(a DDD term, and the only shared contract). It contains integration events only, never views or domain types. .Subscriptionsis the consuming side (DDD's anti-corruption layer): it subscribes to other contexts' published integration events and translates them into this context's own language (local commands or local reference events). It is the only part of a context allowed to use another context's.PublishedLanguage(RimBank.Corereferences every context's.PublishedLanguageproject, but each core may use only its own).
Before a service domain is created, its mapping must be checked against the BIAN v14 Service Landscape and recorded in an ADR.
| Service domain | Business domain | Core namespace |
|---|---|---|
| Party Reference Data Directory | Party | RimBank.Party.PartyReferenceDataDirectory |
| Product Directory | ProductManagement | RimBank.ProductManagement.ProductDirectory |
| Position Keeping | AccountManagement | RimBank.AccountManagement.PositionKeeping |
| Current Account | LoansAndDeposits | RimBank.LoansAndDeposits.CurrentAccount |
| Payment Order Initiation | Payments | RimBank.Payments.PaymentOrderInitiation |
| Financial Accounting | Finance | RimBank.Finance.FinancialAccounting |
/
├─ RimBank.slnx
├─ global.json
├─ Directory.Build.props # shared build settings, central product version
├─ Directory.Build.targets # build guards: no in-code warning suppression (ADR 0013)
├─ Directory.Packages.props # the only place package versions live
├─ NuGet.config # nuget.org only, package source mapping
├─ .editorconfig # code style + solution-wide diagnostic severities; nested ones per project
├─ scripts/ # repository tooling (roadmap board sync)
├─ specs/ # constitution (this folder)
├─ docs/adr/ # architecture decision records
├─ doc-0/ # project inputs (read-only)
│ ├─ ideas.MD # original project brief
│ └─ release14.0.0/ # BIAN v14 specs (ADR 0002)
├─ src/
│ ├─ RimBank.SharedKernel/ # Money, Currency, CountryCode, Result, typed ids, decider abstractions (no infra)
│ ├─ RimBank.Host/ # composition root: wires all contexts (Modules/, ADR 0014), ProblemDetails, the Wolverine bus (Messaging/, ADR 0017), authentication and the actor relay (Security/, ADR 0019), the /mcp endpoint (Mcp/, ADR 0021), OTel
│ ├─ RimBank.AppHost/ # .NET Aspire orchestration: PostgreSQL, Keycloak with the dev-only realm (Realms/, ADR 0019), the host
│ ├─ RimBank.ServiceDefaults/ # Aspire service defaults (OTel, health, resilience)
│ ├─ RimBank.Problems/ # Error → RFC 9457 Problem Details mapping, shared by .Api, .Mcp and the host (ADR 0015)
│ ├─ RimBank.Api/ # the HTTP API of every context, one folder per context (ADR 0025)
│ │ ├─ (root) # namespace RimBank.Api: the Idempotency-Key header (ADR 0018), stream-version entity tags (ETag, If-None-Match, If-Match: ADR 0027)
│ │ └─ Party/PartyReferenceDataDirectory/ # namespace RimBank.Party.PartyReferenceDataDirectory.Api for every folder: Registration/, Retrieval/, Update/, Demographics/, Reference/, Associations/, BankRelations/
│ ├─ RimBank.Mcp/ # MCP conventions at its root: Error → isError Problem Details, the tool error and authorisation filters (ADR 0022, ADR 0039); each context's tools as a folder <BusinessDomain>/<ServiceDomain>/ (ADR 0025)
│ ├─ RimBank.Postgresql/ # Marten conventions every .Postgresql uses: per-context store, role, views, rebuild (ADR 0016); Wolverine wiring with write and read ports (ADR 0017); command idempotency (ADR 0018); one retry on a lost concurrency race (ADR 0027); published-language message identities (ADR 0036)
│ ├─ RimBank.Core/ # the core of every context: domain + application logic, one folder per context (ADR 0023)
│ │ ├─ Party/PartyReferenceDataDirectory/ # namespace RimBank.Party.PartyReferenceDataDirectory for every folder (§3.4, ADR 0026)
│ │ └─ LoansAndDeposits/CurrentAccount/ # namespace RimBank.LoansAndDeposits.CurrentAccount
│ └─ Party/ # a context's own adapter projects, each referencing RimBank.Core
│ ├─ RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage/ # BCL only: the integration events, each declaring its Channel and MessageIdentity (ADR 0036)
│ ├─ RimBank.Party.PartyReferenceDataDirectory.Postgresql/
│ └─ RimBank.Party.PartyReferenceDataDirectory.Subscriptions/ # only when it consumes other contexts' events
└─ tests/
├─ RimBank.Host.Tests/ # host composition, module convention, message bus, health probes, authentication with test-signed tokens and the /mcp endpoint with the SDK client (in-process)
├─ RimBank.AppHost.Tests/ # Aspire resource model and a real startup with Docker (ADR 0014)
├─ RimBank.Architecture.Tests/ # ArchUnitNET rules (CONTRIBUTING "Architecture rules", ADR 0011, ADR 0012)
├─ RimBank.Architecture.Fixtures/ # good and bad fake contexts that prove each rule bites (never referenced by src/)
├─ RimBank.Problems.Tests/ # the Error → Problem Details mapping (ADR 0015)
├─ RimBank.Api.Tests/ # same folders as RimBank.Api (ADR 0025): the HTTP conventions at the root; per context, HTTP through the real host (Alba, Testcontainers), Problem Details and BIAN conformance
│ └─ Party/PartyReferenceDataDirectory/
├─ RimBank.Mcp.Tests/ # the Error → tool result mapping (ADR 0022); per context folder: MCP client → tools against the real host and PostgreSQL, Problem Details errors, authorisation, the tool catalog, parity with the HTTP API (ADR 0039)
├─ RimBank.Postgresql.Tests/ # store, messaging and idempotency conventions with two test-only fake contexts, Testcontainers (ADR 0016–0018)
├─ RimBank.Host.Testing/ # shared helpers for in-memory host tests: test-signed access tokens (ADR 0019), used by Host.Tests, Api.Tests and Mcp.Tests
├─ RimBank.SharedKernel.Testing/ # shared test helpers: typed ID contract (ADR 0008), FsCheck money generators (ADR 0009), decider/projection helpers (0.6)
├─ RimBank.Conformance.Testing/ # BIAN conformance harness used by RimBank.Api.Tests: spec loaders, route, channel, body, status and payload assertions, and each context's ADR catalogue in Catalogues/ (ADR 0020, ADR 0037)
├─ RimBank.Conformance.Tests/ # the harness on the real Party YAML, the catalogue tests, and a test-only fake context (ADR 0020, ADR 0037)
├─ RimBank.Core.Tests/ # domain + application of every context (no I/O), same folders as RimBank.Core (ADR 0023)
│ └─ Party/PartyReferenceDataDirectory/
└─ Party/
└─ RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/ # Testcontainers
Test namespaces: a test namespace follows the code under test and always ends with .Tests. Inside a context it is exactly the namespace under test plus .Tests, whatever the test folder: RimBank.Party.PartyReferenceDataDirectory.Tests (every folder of tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/), RimBank.Party.PartyReferenceDataDirectory.Api.Tests, RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests (ADR 0026). A composition project's tests are all in <project>.Tests (RimBank.SharedKernel.Tests, RimBank.Host.Tests), whatever the folder. A test-only fake context keeps its own namespace, <test project>.FakeContexts.<Name>.Tests, because handlers are bound to a store by namespace. Never ….Tests.<Folder>. Shared test libraries such as RimBank.SharedKernel.Testing keep their own name.
RimBank.Core has one folder per context, <BusinessDomain>/<ServiceDomain>/. Inside it, folders follow aggregates, BIAN Behavior Qualifiers and business flows. Generic technical folders (Services, Repositories, Helpers, Managers, Utils, Dtos) are forbidden.
RimBank.Core/Party/PartyReferenceDataDirectory/ # namespace RimBank.Party.PartyReferenceDataDirectory for every folder below (ADR 0026)
├─ PartyReferenceDataDirectoryEntry/ # Control Record (aggregate root)
│ ├─ PartyReferenceDataDirectoryEntry.cs # state + evolve
│ ├─ PartyReferenceDataDirectoryEntryId.cs
│ ├─ PartyType.cs # Person | Organisation (BIAN Partytypevalues)
│ ├─ Events.cs
│ └─ Decisions.cs # pure decide functions
├─ Registration/ # business flow (command side): Register / Initiate
│ ├─ RegisterParty.cs # command
│ ├─ RegisterPartyAcknowledged.cs # acknowledgement, built from the decided state
│ └─ RegisterPartyHandler.cs
├─ Update/ # business flow (command side): Update, with an expected version (ADR 0027)
│ ├─ UpdatePartyReferenceDataDirectoryEntry.cs # command
│ ├─ UpdatePartyReferenceDataDirectoryEntryAcknowledged.cs # acknowledgement, built from the decided state
│ └─ UpdatePartyReferenceDataDirectoryEntryHandler.cs
├─ Retrieval/ # business flow (query side): Retrieve
│ ├─ RetrievePartyReferenceDataDirectoryEntry.cs # query
│ ├─ RetrievePartyReferenceDataDirectoryEntryHandler.cs
│ ├─ PartyReferenceDataDirectoryEntryView.cs # read model (immutable record)
│ └─ PartyReferenceDataDirectoryEntryViewProjection.cs # pure evolve: event → view
├─ Demographics/ # Behavior Qualifier: entity of the entry (its own commands and queries)
│ ├─ DemographicsId.cs
│ ├─ PartyDemographics.cs # value objects: the details, Employment, the partial-update DemographicsChanges
│ ├─ DemographicsRecord.cs # details + verification status (ADR 0028), in the entry state and its view
│ ├─ Events.cs # DemographicsUpdated, DemographicsExchanged (decided by the entry's Decide)
│ ├─ UpdateDemographics.cs # command, with its acknowledgement and handler
│ ├─ ExchangeDemographics.cs # command (verify / reject), with its acknowledgement and handler
│ └─ RetrieveDemographics.cs # query over the entry's view, with its handler
├─ Reference/ # Behavior Qualifier: entity of the entry (its own commands and queries)
│ ├─ PartyReferenceId.cs
│ ├─ TaxIdentificationNumber.cs # identifier value objects (ADR 0029): Max35Text numbers, the ISO 17442 LEI,
│ ├─ NationalRegistrationNumber.cs # plain JSON strings through PartyReferenceTextJsonConverter
│ ├─ LegalEntityIdentifier.cs
│ ├─ PartyFullLegalName.cs # name value objects (1.18), the same text pattern
│ ├─ PartyNameSalutation.cs
│ ├─ PartyIdentifiers.cs # the identifiers, in PartyReferenceDetails (the entry state and its view)
│ ├─ PartyNames.cs # the names (1.18)
│ ├─ PartyResidency.cs # nationality and country of residence (CountryCode, ADR 0030), ResidencyStatus (1.18)
│ ├─ PostalAddress.cs # structured ISO 20022 postal address, town and country required (1.19, ADR 0031)
│ ├─ PartyAddresses.cs # the residential, party and corporate addresses (1.19)
│ ├─ EmailAddress.cs # contact point value objects (1.19, ADR 0031): email syntax, E.164 mobile number,
│ ├─ MobileNumber.cs # https profile URL, plain JSON strings through PartyReferenceTextJsonConverter
│ ├─ SocialNetworkAddress.cs
│ ├─ PartyContactPoints.cs # the email, mobile and social network contacts (1.19)
│ ├─ PartyLegalStructure.cs # declared legal standing (1.20, ADR 0032): the BIAN code lists as enums with their
│ ├─ PoliticalExposureType.cs # BIAN spelling (…s.cs), the Max350Text PoliticalExposureDescription,
│ ├─ PartyLegalStanding.cs # and PartyLegalStanding (legal structure, political exposure, customer-since date)
│ ├─ GovernmentIssuedDocument.cs # declared documents (1.20): type, number, name and validity period, the opaque
│ ├─ DocumentDirectoryEntryReference.cs # directory reference, and PartyDocuments
│ ├─ PartyDocuments.cs
│ ├─ CompanyOfficerRole.cs # corporate and officer references (1.21, ADR 0034): the officer's Max35Text role, and
│ ├─ PartyCorporateReferences.cs # the corporate customer, legal entity and officer as checked directory entry ids
│ ├─ PartyReferenceDetails.cs # identifiers, names, date of birth, residency, addresses, contact points, legal standing, documents, corporate references
│ ├─ PartyReferenceInput.cs # the raw values an adapter sends
│ ├─ PartyReferenceChanges.cs # the partial-update changes, and the entries they reference; refuses unrecorded BIAN parts
│ ├─ Events.cs # PartyReferenceUpdated
│ ├─ UpdatePartyReference.cs # command, with its acknowledgement and handler (which loads the referenced entries, 1.21)
│ └─ RetrievePartyReference.cs # query over the entry's view, with its handler
├─ Associations/ # Behavior Qualifier as its own aggregate (ADR 0024, 1.11, ADR 0033)
│ ├─ PartyAssociation.cs # state + evolve
│ ├─ PartyAssociationId.cs
│ ├─ PartyRelationshipType.cs # the 9 BIAN relationship types, BIAN names (…s.cs reads them in any case)
│ ├─ AssociationValidityPeriod.cs # FromDateTime / ToDateTime in UTC, from not after to
│ ├─ PartyAssociationInput.cs # the raw values an adapter sends
│ ├─ PartyAssociationTerms.cs # what Register records; refuses the fields in PartyAssociationFields.NotRecorded
│ ├─ PartyAssociationChanges.cs # the partial-update changes of Update
│ ├─ Events.cs # PartyAssociationRegistered, PartyAssociationUpdated
│ ├─ Decisions.cs # pure decide: the owner and associate checks come from the handler's write-side loads
│ ├─ RegisterPartyAssociation.cs # command, with its handler; PartyAssociationAcknowledged answers Register and Update
│ ├─ UpdatePartyAssociation.cs # command, with its handler
│ ├─ RetrievePartyAssociation.cs # query over the association's view, with its handler
│ ├─ PartyAssociationView.cs
│ └─ PartyAssociationViewProjection.cs
├─ BankRelations/ # Behavior Qualifier: entity of the entry (1.12, ADR 0035)
│ ├─ BankRelationsId.cs
│ ├─ BankRelationType.cs # employee roles (a person) and unit roles (an organisation), names read in any
│ ├─ BankRelationLifecycleStatus.cs # case by …s.cs; Active / Suspended / Ended
│ ├─ BankRelationsDetails.cs # type, checked employee or unit entry id, UTC start and end dates, status
│ ├─ BankRelationsChanges.cs # the raw input and the partial-update changes; refuses unrecorded BIAN parts
│ ├─ Events.cs # BankRelationsUpdated (decided by the entry's Decide)
│ ├─ UpdateBankRelations.cs # command, with its acknowledgement and handler (which loads the referenced entry)
│ └─ RetrieveBankRelations.cs # query over the entry's view, with its handler
├─ Publication/ # published language (1.13, ADR 0036)
│ └─ PartyReferenceDataDirectoryPublication.cs # pure mapper: decided entry events → .PublishedLanguage events, cascaded by the handlers
├─ IPartyDirectory.cs # write port: load and append the entry and association event streams
└─ IPartyDirectoryEnquiry.cs # read port: query the entry and association views
Commands and queries sit next to each other inside the business flow or Behavior Qualifier they belong to. They are told apart by name and by the port they use, not by technical Commands/ or Queries/ folders.
Value objects that belong to one context (for example party identifiers, names, addresses) live in the folder of the aggregate or Behavior Qualifier that owns them, never in a technical ValueObjects/ or Models/ folder. Value objects every context shares (Money, Currency, CountryCode (ADR 0030), the typed ID pattern, Result/Error) live in RimBank.SharedKernel.
| Project | May reference | Must not reference |
|---|---|---|
RimBank.SharedKernel |
BCL only | Everything else |
RimBank.Core |
SharedKernel, each context's own .PublishedLanguage. Inside it, a context's core (namespace RimBank.X.Y) uses only its own namespace, SharedKernel and its own .PublishedLanguage |
ASP.NET Core, Marten, Wolverine, Npgsql, any adapter; for each context, any other context's core or .PublishedLanguage |
.PublishedLanguage |
BCL only | Everything else |
.Subscriptions |
Its own core, SharedKernel, other contexts' .PublishedLanguage, Wolverine |
Other contexts' cores or adapters, its own .Api, .Mcp, .Postgresql |
.Api (a context's folder of RimBank.Api, ADR 0025) |
Its own core, SharedKernel, RimBank.Problems, the HTTP conventions (namespace RimBank.Api), ASP.NET Core, Wolverine (IMessageBus) |
.Postgresql, other contexts' adapters |
.Mcp (a context's folder of RimBank.Mcp from 1.16, ADR 0025) |
Its own core, SharedKernel, RimBank.Problems, RimBank.Mcp, MCP C# SDK, Wolverine (IMessageBus) |
.Api, .Postgresql, other contexts' adapters |
.Postgresql |
Its own core, SharedKernel, RimBank.Postgresql, Marten, Wolverine.Marten |
.Api, .Mcp, other contexts |
RimBank.Problems |
SharedKernel, ASP.NET Core | Cores, adapters, other composition projects (ADR 0015) |
RimBank.Api (root namespace: the HTTP conventions) |
SharedKernel, RimBank.Problems, ASP.NET Core; used only by .Api folders and RimBank.Host |
Cores, other adapters, Marten, Wolverine (ADR 0018, ADR 0025) |
RimBank.Mcp (its root namespace; the context folders follow the .Mcp row) |
SharedKernel, RimBank.Problems, ASP.NET Core, MCP C# SDK; used only by .Mcp adapters and RimBank.Host |
Cores, other adapters, Marten, Wolverine (ADR 0022, ADR 0039) |
RimBank.Postgresql |
SharedKernel, Marten (with JasperFx, Weasel, Npgsql), Wolverine (Wolverine.Marten, Wolverine.Postgresql), Microsoft.Extensions abstractions; used only by .Postgresql adapters and by RimBank.Host for its own message store. It also adds the idempotency policy to every command handler (ADR 0018) |
Cores, other adapters, other composition projects, ASP.NET Core (ADR 0016, ADR 0017) |
RimBank.Host |
All adapters and RimBank.Core (composition only) |
Business logic |
An adapter's own core is its context's namespace inside RimBank.Core: every adapter project references RimBank.Core, and the architecture tests (cross-context-isolation) keep it to its own context's types.
Core and Wolverine: handlers in the core are plain classes with Handle methods. They return events and messages (Wolverine's cascading convention) instead of taking framework services, so the core has no package reference to Wolverine or Marten. Persistence goes through ports in the core. The .Postgresql adapter implements those ports with Marten: the write port over event streams, and the read port over projected documents.
CQRS rules (also enforced by architecture tests):
| Type | May depend on | Must not depend on |
|---|---|---|
| Command handler | Write port, aggregate decisions, its own context's local reference read models used only as decision inputs (see §8.4) | The context's own query read models, query handlers |
| Query handler | Read port, views | Write port, aggregates, decisions |
Projection (…Projection) |
Domain events, views | Ports, handlers, TimeProvider (time comes from event data) |
The architecture tests tell these roles apart by SharedKernel markers (ADR 0012): commands implement ICommand, queries IQuery<TView>, write ports IWritePort and read ports IReadPort. A handler is a class with a Handle / HandleAsync method whose first parameter is a command or a query, and a view is a type returned by an IProjection. Until local reference read models exist (4.2), a command handler may use no read port or view at all.
-
Routes, operation names and resource names follow BIAN, for example
POST /PartyReferenceDataDirectory/RegisterandGET /PartyReferenceDataDirectory/{id}/Retrieve. -
Request and response models live in the context's
.Apifolder ofRimBank.Api(ADR 0025) and are mapped to and from the core. Domain types are never serialised directly. -
Commands vs queries over HTTP: BIAN
Retrieveoperations areGETendpoints that dispatch a query. All other BIAN operations (Register,Initiate,Update,Control,Execute,Exchange,Request, …) arePOST/PUTendpoints that dispatch a command. -
Command responses come from the command's outcome (the identifier, stream version and the state produced by the decision). They never read a read model, so they do not depend on projection lag. Where BIAN's response schema expects the full Control Record, it is built from the aggregate state produced by the decision.
-
Query responses come only from read models. A stream version is returned in an
ETagheader, and a command sends it back inIf-Matchfor optimistic concurrency. -
If-Matchis required on every command that changes an existing record (ADR 0027). It must be exactly one strong version tag:- missing → 428
shared.if-match-required; - malformed (weak,
*, a list) → 400shared.if-match-invalid; - stale → 409
<context>.version-conflict.
The command carries the version as
ExpectedVersion; the handler checks it against the loaded stream, and the write port appends with it. A commit that loses a race is retried once, so the conflict is always answered as a value. MCP tools takeexpectedVersionas a required argument. - missing → 428
-
Every non-2xx response is
application/problem+json(RFC 9457).type: a stable URN, for exampleurn:rimbank:problem:party:party-not-foundtitle,status,detail,instance- extensions:
errorCode,traceId, anderrors(field → messages) for validation failures
-
Each core
Errormaps to a Problem Details response in one place for the whole solution,RimBank.Problems, which every.Apiand.Mcpuses (error.ToHttpResult()); the host emitsshared.not-foundandshared.unexpecteditself (ADR 0015). Unhandled exceptions become a generic 500 Problem Details response with no internal details exposed. -
BIAN-declared statuses are honoured: 400, 401, 403, 404, 429 and 500, plus 409 for concurrency and idempotency conflicts. A missing or invalid token is a 401
shared.unauthenticatedand a refused policy a 403shared.forbidden(ADR 0019). -
Every state-changing endpoint requires an
Idempotency-Keyheader: a missing or invalid one is a 400, and a key reused with a different payload or still in use is a 409 (RequireIdempotencyKey()andIdempotencyKeyHeaderinRimBank.Api, ADR 0018).
- MCP is a driving adapter alongside
.Api. A context's.Mcpadapter (its folder ofRimBank.Mcp, ADR 0025) sends the same core commands and queries throughIMessageBus. It never calls the HTTP API and never contains business logic, so the HTTP and MCP channels cannot drift apart. - Hosting: all contexts' MCP tools are registered in
RimBank.Hostand exposed at a single/mcpendpoint over Streamable HTTP in stateless mode. Each context hands its tools to the host through its module'sAddMcpTools(IMcpServerBuilder), which calls the one extension its.Mcpadapter exposes; contexts never configure the transport or map the route, and a tool name registered twice stops the host (ADR 0021). When a context is extracted, its.Mcpadapter moves with it. - Naming: each tool maps 1:1 to a BIAN operation, named
<service_domain>_<operation>[_<behavior_qualifier>]in snake_case (for exampleparty_reference_data_directory_registerandcurrent_account_retrieve_payment). Descriptions come from the BIAN operation description. Arguments are the tool's camelCase parameters: the ids, and for a command a requiredidempotencyKey, a requiredexpectedVersionwhen it changes a record (HTTP'sIf-Match), and its BIAN request body as onerequestobject with BIAN's property names (ADR 0040). A result mirrors the.Apiresponse model with BIAN's property names plusversion, the stream version HTTP sends asETag..Mcpnever references.Api: parity tests prove both channels give the same JSON and Problem Details (ADR 0039). - Tool annotations: every tool sets
readOnly,destructive,idempotentandopenWorldexplicitly (table in ADR 0021). Retrieve tools dispatch queries and are markedreadOnly; every other tool dispatches a command. Operations that move money or close facilities are markeddestructiveand are notidempotentunless an idempotency key is supplied. - Security: the MCP endpoint follows the MCP authorization spec (OAuth 2.1, with Keycloak as the authorization server): a 401 on
/mcppoints to the RFC 9728 protected-resource metadata, which names the realm, and tokens carry the samerimbank-apiaudience as HTTP (ADR 0022). Tool calls go through the same per-BIAN-operation authorisation policies as HTTP: a tool carries the policy named by its operation id ([ToolOperation(OperationId)]), a caller without its scope does not see it intools/listand gets theshared.forbiddenProblem Details on a call, and the metadata lists every policy scope inscopes_supported(ADR 0038, ADR 0039). Money-moving tools need a dedicated scope and are disabled by default, so each deployment must turn them on explicitly. - Errors: a business or validation failure returns a tool result with
isError: truewhose content (andstructuredContent) is the Problem Details JSON (sametype,errorCodeandtraceIdas HTTP, ADR 0021). Adapters return failures withToToolResultfromRimBank.Mcp, whose call-tool filter turns unbindable arguments intoshared.tool-arguments-invalidand any exception intoshared.unexpected(ADR 0022). Stack traces and internal details are never exposed. - Audit: every tool call records the MCP client identity and a correlation ID in event metadata, as HTTP calls do.
- Aggregates: event-sourced through Marten. Each aggregate is a
sealed recordstate withEvolvefunctions, and decisions are pure static functions. - IDs: strongly typed
readonly record structwrappingGuidv7, implementingITypedId<TSelf>(ADR 0008). - Money:
Money(decimal Amount, Currency Currency)using ISO 4217 minor units, with explicit rounding policy.doubleandfloatare never used for amounts. - Time: always injected through
TimeProvider.DateTime.Nowis never used. - Failures:
Result<T>/Errorfor business rules. Exceptions are reserved for programmer errors and infrastructure faults. - Events: past tense, named in BIAN language (
PartyRegistered,CurrentAccountFacilityInitiated). Domain events are internal; integration events in.PublishedLanguageare versioned and backwards compatible. - Behavior Qualifiers: modelled as an entity inside the Control Record aggregate by default. A BQ becomes its own aggregate only when it has an independent lifecycle or concurrency hotspot, and that choice needs an ADR.
CQRS is applied logically everywhere and physically where needed. Every context separates its write side (commands → decisions → events) from its read side (events → projections → queries). Separate document shapes, asynchronous projections and dedicated read stores are added only when a query needs them.
- A command is an immutable record named as a BIAN operation in the imperative (
RegisterParty,UpdateDemographics,ExecutePayment). It carries an idempotency key (ICommand.IdempotencyKey) and, where it updates an existing record, an expected stream version. Each context handles a command once per key and caller (ADR 0019): the same key and payload return the first acknowledgement without running the handler again, and only successful outcomes are stored, in the same transaction as the events (ADR 0018). - A command handler loads the aggregate through the write port, calls a pure
Decide, appends the resulting events and returns an acknowledgement (id,version, and the decided state when BIAN requires it). It returnsResult<T>, never a read model. - Invariants that protect money (funds availability, closure rules, holds) are checked against the authoritative write-side state in the same stream and transaction. They are never checked against an eventually consistent projection.
- Decision inputs from another context (for example "is this party known?", "is this product launched?") come from local reference read models fed by integration events (see §8.4). Their staleness is acceptable and documented in the context's ADR.
- A query is an immutable record named
Retrieve<Thing>(orList<Things>for collections). A query handler reads views through the read port and returnsResult<TView>(NotFoundis anError, which becomes a 404 Problem Details response). - A view (read model) is an immutable record shaped for its consumers. It holds no behaviour and is never used to make decisions on the write side.
- A projection is a pure function
(view, event) → view, implemented with Marten projections in.Postgresql. The pure part lives in the core so it can be unit tested without a database.
| Need | Choice |
|---|---|
| Single-stream view that callers read right after writing (Retrieve a Control Record) | Inline projection, same transaction as the events |
| Cross-stream, list, search, history, reporting (product catalogue, transaction history, trial balance, audit) | Async projection run by Marten's async daemon |
| A query that needs another context's data | A local reference read model fed by that context's integration events (see §8.4); never a direct read of its tables or views |
| A query that combines several contexts (for example a customer overview) | A dedicated query-only context fed by integration events (for example BIAN Customer Position), or composition by the channel; never a cross-schema join |
- Async views expose their staleness (last processed event sequence) so that callers and tests can wait for or detect lag (
GetViewProgressAsync, ADR 0016). - A view is wired by lifecycle with
AddInlineView/AddAsyncView, which run the core's pure projection through a generic Marten adapter that holds no logic, and is rebuilt withRebuildViewAsync(ADR 0016). - Every projection is rebuildable from the event store. A projection change that alters its shape ships with a rebuild step, documented in the PR.
- Read models live in the context's own PostgreSQL schema, like its events, and each context runs its own async daemon, so a stuck projection in one context never blocks another.
- Ownership: a view belongs to exactly one context and is reachable only through that context's read port,
.Apiand.Mcp. Views are never shared, never put in.PublishedLanguage, and never read by another context. - Producer side: integration events are mapped from domain events (through the outbox), never from read models. They carry the state consumers need (event-carried state transfer), are versioned, and only change in backwards-compatible ways. A contract test pins each published event's schema. Each event declares its BIAN
Channeland a versionedMessageIdentity(for exampleparty-reference-data-directory-entry.created.v1); the command handler maps it from the decided events with a pure mapper in core and returns it as a cascaded message, so it commits with the events (ADR 0036). - Consumer side: the
.Subscriptionsadapter receives the integration event (idempotently, through Wolverine's durable inbox), translates it into the consumer's own types, and records it as a local reference event in the consumer's own store. The local reference read model is projected from those local events, so it can be rebuilt without the producer. - Cross-context requests are events, not commands. A context never sends another context's command, because commands are internal to the context that owns them and are never in
.PublishedLanguage. When context A needs context B to act, A publishes a request event in A's.PublishedLanguage(for examplePaymentOrderExecutionRequested). B's.Subscriptionsadapter turns it into one of B's own commands, decided by B's rules. B then publishes the outcome (for exampleCurrentAccountPaymentExecutedorCurrentAccountPaymentRejected), and A's.Subscriptionsadapter reacts to it. The requesting record's identifier (for example the payment order ID) is the correlation ID and the idempotency key of the translated command, so a redelivered request never moves money twice. - Minimal copies: a local reference read model keeps only the fields its context needs (for example "party is known and active", not the party's demographics). This also limits the spread of PII.
- Tolerant reader: consumers ignore unknown fields and accept events out of order or more than once.
- Enforcement: architecture tests forbid cross-context references other than
.Subscriptions→.PublishedLanguage, including between contexts insideRimBank.Core(ADR 0023). Database roles forbid cross-schema reads, and an integration test proves it.
| Kind | Tooling | Scope |
|---|---|---|
| Unit | xUnit v3, Shouldly | Pure domain decisions, projections (Given events → Then view) and handlers (no I/O) |
| Property-based | FsCheck | Money arithmetic, balance invariants, evolve/decide laws, projection/aggregate agreement |
| Integration | Testcontainers (PostgreSQL), Alba | Marten persistence and projections (inline and async daemon), Wolverine outbox, HTTP endpoints end to end |
| Architecture | ArchUnitNET | Dependency rules and CQRS rules in §4, naming rules in §3, cross-context isolation in §8.4 |
| Contract | OpenAPI/AsyncAPI conformance tests (RimBank.Conformance.Testing: Microsoft.OpenApi, YamlDotNet, ADR 0020; bodies, 2xx statuses and event payloads as a subset of the BIAN schemas, with ADR-cited deviations, ADR 0037); published-event schema snapshots (JsonSchemaExporter against committed approved files, ADR 0036) |
Implemented routes and channels exist in the BIAN v14 ext-DDD YAML with the spec's method, Retrieve is GET and nothing else is; request, response and event payload fields exist in the BIAN schema unless an ADR decided otherwise; published integration events stay backwards compatible |
| MCP | MCP C# SDK client in-process against the test host | Tool list, input schemas, results, Problem Details errors, and parity with the HTTP endpoint for the same operation |
| Mutation (later) | Stryker.NET | The RimBank.Core folders of money-moving domains (--mutate "<BusinessDomain>/<ServiceDomain>/**") |
- Every endpoint requires authentication by default: the authorization fallback policy requires an authenticated caller, and only the health probes of
RimBank.ServiceDefaultsare anonymous (and, in Development only, the OpenAPI document and Scalar UI it maps, roadmap 1.5), guarded by the architecture ruleallow-anonymous-only-in-service-defaults(ADR 0019). Authorisation policies are defined per BIAN operation (ADR 0038): each context has a read scope for its queries and a write scope for its commands (<service-domain-kebab>:read/:write, for exampleparty-reference-data-directory:read). Its host module registers one policy per operation, named by the operation id (AddOperationPolicies:AddCommand/AddQuery). Every BIAN endpoint callsRequireOperation(OperationId), and a token without the scope is a 403shared.forbidden, answered before the endpoint's other checks. - The caller is an
Actor(SharedKernel: the token'ssubandazp). The host relays its subject to the message bus as the Wolverine user name, which scopes idempotency keys and reaches Marten's last-modified-by and the trace. Cores and adapters never read the token. - PII is masked in logs, and sensitive fields are protected at rest.
- Secrets come from user-secrets locally and from a vault in deployed environments. They are never in source.
- GitHub: CodeQL, Dependabot, secret scanning, SBOM generation on release, and signed release tags.