From bfbc808e96f9b2e2aaf9a2471cce7ccf13e85828 Mon Sep 17 00:00:00 2001 From: LaBani Said Date: Mon, 9 Nov 2026 14:09:04 +0100 Subject: [PATCH 1/2] Document the architecture and the business of RimBank before Stage 2: C4, ERD, sequences, flows, data flow, dependencies, security, value streams and the Party glossary Adds docs/architecture (9 documents) and docs/business (5 documents) with 61 Mermaid diagrams, indexed from docs/README.md, and links them from the root README, whose status line now says Stages 0 and 1 are done. Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +- docs/README.md | 41 ++ docs/architecture/01-architecture-overview.md | 150 +++++++ docs/architecture/02-c4-model.md | 269 ++++++++++++ docs/architecture/03-data-model-erd.md | 270 ++++++++++++ docs/architecture/04-sequence-diagrams.md | 347 +++++++++++++++ docs/architecture/05-logic-flows.md | 251 +++++++++++ docs/architecture/06-data-flow.md | 153 +++++++ docs/architecture/07-dependencies.md | 158 +++++++ .../08-deployment-security-operations.md | 161 +++++++ docs/architecture/09-quality-risks-roadmap.md | 83 ++++ docs/business/01-business-architecture.md | 173 ++++++++ docs/business/02-party-domain-glossary.md | 406 ++++++++++++++++++ docs/business/03-entity-relationships.md | 212 +++++++++ docs/business/04-value-streams.md | 230 ++++++++++ docs/business/05-banking-use-cases.md | 184 ++++++++ docs/business/README.md | 27 ++ 17 files changed, 3117 insertions(+), 1 deletion(-) create mode 100644 docs/README.md create mode 100644 docs/architecture/01-architecture-overview.md create mode 100644 docs/architecture/02-c4-model.md create mode 100644 docs/architecture/03-data-model-erd.md create mode 100644 docs/architecture/04-sequence-diagrams.md create mode 100644 docs/architecture/05-logic-flows.md create mode 100644 docs/architecture/06-data-flow.md create mode 100644 docs/architecture/07-dependencies.md create mode 100644 docs/architecture/08-deployment-security-operations.md create mode 100644 docs/architecture/09-quality-risks-roadmap.md create mode 100644 docs/business/01-business-architecture.md create mode 100644 docs/business/02-party-domain-glossary.md create mode 100644 docs/business/03-entity-relationships.md create mode 100644 docs/business/04-value-streams.md create mode 100644 docs/business/05-banking-use-cases.md create mode 100644 docs/business/README.md diff --git a/README.md b/README.md index 4e17986..663c3f4 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ The code is meant to read like the business it serves. Every BIAN service domain becomes a bounded context, and its names, flows and capabilities come from BIAN and banking, not from frameworks. Every capability is available both as a BIAN HTTP API and as an [MCP](https://modelcontextprotocol.io) tool for AI agents, over the same core and with the same business rules. -> **Status:** early development, Stage 0 (Foundations). See the [roadmap](specs/roadmap.md). +> **Status:** early development. Stage 0 (Foundations) and Stage 1 (Party Reference Data Directory) are done; Stage 2 (Product Directory) is next. See the [roadmap](specs/roadmap.md). > RimBank is not a licensed bank and provides no regulatory certification. ## How BIAN maps to the code @@ -54,6 +54,7 @@ To run RimBank (Docker required): `dotnet run --project src/RimBank.AppHost`, th - [Mission](specs/mission.md): why RimBank exists, guiding principles, quality bar, non-goals - [Tech stack and architecture rules](specs/tech-stack.md) - [Roadmap](specs/roadmap.md) and its Definition of done +- [Architecture and business documentation](docs/README.md): C4, data model, sequences, flows, dependencies, security; BIAN positioning, party glossary, relationships, value streams, use cases - [Architecture decision records](docs/adr/) - [BIAN v14 specifications](doc-0/release14.0.0/) diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..f55cc71 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,41 @@ +# RimBank documentation + +Two views of the same platform. Start with the one that matches your question; each links to the other. + +| If you want to know… | Read | +|---|---| +| What RimBank does for a bank, where it fits in BIAN, what each party field means, which value streams it serves | [Business documentation](business/README.md) | +| How it is built: C4, data model, sequences, logic flows, data flow, dependencies, security, operations, risks | [Architecture documentation](#architecture-documentation) | +| Why a specific decision was made | [Architecture decision records](adr/) | +| The rules every change must follow | [Mission](../specs/mission.md), [tech stack](../specs/tech-stack.md), [roadmap](../specs/roadmap.md) | + +## Business documentation + +| # | Document | For | +|---|---|---| +| 1 | [Business architecture](business/01-business-architecture.md) | BIAN positioning, capability map, adoption patterns | +| 2 | [Party domain glossary](business/02-party-domain-glossary.md) | Every entity member, enumeration, event and error, with ISO / BIAN definitions | +| 3 | [Entity relationships](business/03-entity-relationships.md) | Business ERD, cardinalities, worked examples | +| 4 | [Value streams](business/04-value-streams.md) | End-to-end value delivery and which service domain serves each stage | +| 5 | [Banking use cases and integration guide](business/05-banking-use-cases.md) | KYC, PEP, beneficial ownership, FATCA/CRS, servicing, AI agents; consuming Party events | + +## Architecture documentation + +| # | Document | For | +|---|---|---| +| 1 | [Architecture overview](architecture/01-architecture-overview.md) | Drivers, quality priorities, styles, key decisions, BIAN → architecture mapping | +| 2 | [C4 model](architecture/02-c4-model.md) | System context, containers, components, code | +| 3 | [Data model and ERD](architecture/03-data-model-erd.md) | Logical ERD, event model, physical PostgreSQL model, published language, read models | +| 4 | [Sequence diagrams](architecture/04-sequence-diagrams.md) | Register, idempotent replay, Retrieve/ETag, Update/concurrency, cross-aggregate checks, associations, verification, MCP, errors, cross-context (target) | +| 5 | [Logic flows and state machines](architecture/05-logic-flows.md) | Request pipeline, every decision tree, lifecycles | +| 6 | [Data flow](architecture/06-data-flow.md) | DFD levels 0–1, CQRS paths, cross-context data, classification, lineage | +| 7 | [Dependencies](architecture/07-dependencies.md) | Project graph, dependency matrix, hexagon, packages, runtime, context map | +| 8 | [Deployment, security and operations](architecture/08-deployment-security-operations.md) | Aspire topology, reference production deployment, trust boundaries, STRIDE, observability, CI/CD | +| 9 | [Quality attributes, risks and roadmap](architecture/09-quality-risks-roadmap.md) | Quality scenarios with evidence, risks, deferrals, readiness for Stage 2 | + +## Conventions + +- Diagrams are [Mermaid](https://mermaid.js.org) in the Markdown, so they render on GitHub and change in the same pull request as the code. +- Every document states whether it describes `main` today or a *(target)* from the roadmap. +- When a document and the code or an ADR disagree, the code and the ADR win: fix the document in the same pull request. +- A phase that changes a diagrammed behaviour (a new context, operation, event, table or rule) updates the affected document as part of its definition of done. diff --git a/docs/architecture/01-architecture-overview.md b/docs/architecture/01-architecture-overview.md new file mode 100644 index 0000000..cf6ba0e --- /dev/null +++ b/docs/architecture/01-architecture-overview.md @@ -0,0 +1,150 @@ +# 01. Architecture overview + +> Status: describes `main` at the end of **Stage 1** (Party Reference Data Directory, roadmap 0.1–1.21), before Stage 2 (Product Directory). +> Normative sources: [mission](../../specs/mission.md), [tech stack](../../specs/tech-stack.md), [roadmap](../../specs/roadmap.md) and the [ADRs](../adr/). When this document and those disagree, they win and this document has a bug. + +## 1. Purpose and scope + +RimBank is an open-source core banking platform that turns the **BIAN Service Landscape v14 (ISO 20022 extended, DDD edition)** into running software. This architecture set explains *how* it is built, at the level an enterprise architect, a solution architect or a new contributor needs to reason about it, change it, or plug it into a bank. + +| Document | Question it answers | +|---|---| +| [01 Overview](01-architecture-overview.md) (this) | What are the drivers, principles, styles and building blocks? | +| [02 C4 model](02-c4-model.md) | What are the system's context, containers, components and code structure? | +| [03 Data model and ERD](03-data-model-erd.md) | What is stored, in which schema, with which keys and relationships? | +| [04 Sequence diagrams](04-sequence-diagrams.md) | What happens, step by step, for each operation and failure path? | +| [05 Logic flows and state machines](05-logic-flows.md) | How does each decision branch, and which lifecycle states exist? | +| [06 Data flow](06-data-flow.md) | Where does data enter, move, rest and leave; which of it is PII? | +| [07 Dependencies](07-dependencies.md) | Which project may depend on which, and how do contexts integrate? | +| [08 Deployment, security and operations](08-deployment-security-operations.md) | How does it run, how is it protected and observed? | +| [09 Quality attributes, risks and roadmap](09-quality-risks-roadmap.md) | Which qualities are guaranteed, by what evidence, and what is still open? | + +The business view (BIAN positioning, entity dictionary, relationships, value streams and use cases) is in [../business/](../business/README.md). + +## 2. Architecture drivers + +### 2.1 Business drivers + +| Driver | Consequence for the architecture | +|---|---| +| BIAN describes *what* a bank does, not *how* to build it | Each BIAN service domain is a bounded context; BIAN names are the code's names; BIAN YAMLs are tested against the code (conformance tests) | +| Core banking must be auditable | Event sourcing: state is derived from business events, every change has an actor, time, correlation id | +| Banks consume capabilities from many channels, including AI agents | Two driving adapters over one core: BIAN HTTP API and MCP tools, with proven parity | +| Adopters must be able to take one capability without the rest | Autonomous contexts, integration by published events only, modular monolith that can be split | + +### 2.2 Quality attribute priorities + +Ordered: when two collide, the higher one wins. + +1. **Correctness and integrity** (money is never created or lost; invariants checked on authoritative write-side state) +2. **Security and privacy** (authenticated by default, per-operation authorisation, PII protected) +3. **Auditability** (append-only event streams, actor and trace on every change) +4. **Evolvability** (contexts isolated by namespace, schema and database role; extraction changes no core code) +5. **Interoperability** (BIAN routes, ISO 20022 data types, RFC 9457 errors, MCP) +6. **Operability** (OpenTelemetry, health probes, rebuildable read models) +7. **Performance** (measured in Stage 7; CQRS allows physical separation later) + +### 2.3 Constraints + +- .NET 10 / C# 14, PostgreSQL, Marten, Wolverine, ASP.NET Core Minimal APIs, MCP C# SDK, Keycloak (OIDC), .NET Aspire ([tech-stack §1](../../specs/tech-stack.md#1-platform)). +- `TreatWarningsAsErrors`, central package management, locked restore, nuget.org only ([ADR 0013](../adr/0013-warning-and-package-governance.md)). +- MIT licence; RimBank is not a licensed bank and provides no regulatory certification. + +## 3. Architecture styles + +| Style | Where | Decision | +|---|---|---| +| **Domain-Driven Design** (strategic + tactical) | One BIAN service domain = one bounded context; Control Record = aggregate root; Behavior Qualifier = entity (or own aggregate by ADR) | [mission](../../specs/mission.md), [ADR 0024](../adr/0024-party-reference-data-directory-mapping.md) | +| **Hexagonal (ports and adapters)** | Core depends on nothing technical; adapters (`.Api`, `.Mcp`, `.Postgresql`, `.Subscriptions`) depend on the core | [tech-stack §4](../../specs/tech-stack.md#4-dependency-rules-enforced-by-architecture-tests) | +| **Functional core** | `Decide(command, state) → Result`, `Evolve(state, event) → state`, `Project(view, event) → view` are pure | [ADR 0010](../adr/0010-decider-and-projection-contracts.md) | +| **Event sourcing** | Aggregates persisted as Marten event streams | [ADR 0016](../adr/0016-per-context-marten-stores.md) | +| **CQRS** | Commands → write port → aggregate; queries → read port → views; enforced by architecture tests | [ADR 0003](../adr/0003-separate-commands-and-queries.md), [ADR 0012](../adr/0012-cqrs-role-markers.md) | +| **Event-driven integration** | Contexts communicate through versioned integration events via the transactional outbox | [ADR 0004](../adr/0004-loosely-coupled-contexts.md), [ADR 0036](../adr/0036-party-published-language.md) | +| **Modular monolith** | One deployable host composes all contexts; each context is extractable | [ADR 0014](../adr/0014-host-composition-and-module-entry-point.md), [ADR 0023](../adr/0023-one-core-project.md), [ADR 0025](../adr/0025-one-api-project.md) | + +## 4. Building blocks at a glance + +```mermaid +flowchart TB + subgraph Channels["Driving side (channels)"] + APP["Bank applications
BIAN HTTP clients"] + AGENT["AI agents
MCP clients"] + end + + subgraph Host["RimBank.Host (composition root, one process)"] + direction TB + SEC["Security
JWT, per-operation policies, actor relay"] + API["RimBank.Api
BIAN HTTP endpoints per context"] + MCP["RimBank.Mcp
MCP tools per context at /mcp"] + BUS["Wolverine bus
IMessageBus, outbox, inbox, durable local queues"] + subgraph Core["RimBank.Core (pure)"] + PARTY["Party / PartyReferenceDataDirectory
commands, decisions, events, queries, projections"] + NEXT["ProductManagement / ProductDirectory ...
(Stage 2+)"] + end + PG["…Postgresql adapters
Marten write and read ports"] + PL["…PublishedLanguage
integration events"] + end + + subgraph Infra["Infrastructure"] + DB[("PostgreSQL
one schema + role per context")] + KC["Keycloak
OIDC / OAuth 2.1"] + OTEL["OTLP collector
Aspire dashboard"] + end + + APP -->|HTTPS + JWT| SEC + AGENT -->|Streamable HTTP + JWT| SEC + SEC --> API + SEC --> MCP + API -->|InvokeAsync| BUS + MCP -->|InvokeAsync| BUS + BUS --> PARTY + PARTY -.->|ports| PG + PARTY -.->|maps to| PL + PG --> DB + BUS --> DB + SEC -.->|JWKS, metadata| KC + Host -.->|traces, metrics, logs| OTEL +``` + +## 5. Key architectural decisions (summary) + +| # | Decision | Why | ADR | +|---|---|---|---| +| 1 | Event-sourced aggregates with pure deciders | Audit trail by construction; decisions unit-testable without I/O | [0010](../adr/0010-decider-and-projection-contracts.md) | +| 2 | Logical CQRS everywhere, physical only where needed | Avoid premature read stores; keep read-your-write for Control Records (inline views) | [0003](../adr/0003-separate-commands-and-queries.md) | +| 3 | One Marten store, schema and DB role per context | Isolation enforced by the database, not only by convention | [0016](../adr/0016-per-context-marten-stores.md) | +| 4 | One `RimBank.Core`, one `RimBank.Api`, one `RimBank.Mcp` project, folders per context | Fewer projects; isolation by namespace rules in architecture tests | [0023](../adr/0023-one-core-project.md), [0025](../adr/0025-one-api-project.md), [0026](../adr/0026-flat-context-namespaces.md) | +| 5 | `Result`/`Error` for business failures, RFC 9457 at every edge | Uniform errors on HTTP and MCP from one mapping | [0006](../adr/0006-result-and-error-model.md), [0015](../adr/0015-problem-details-mapping.md) | +| 6 | Idempotency key on every command, stored with the events | Exactly-once business effect on retries | [0018](../adr/0018-idempotency-keys-for-commands.md) | +| 7 | Optimistic concurrency via stream version (`ETag` / `If-Match`) | Lost updates impossible; one automatic retry of a lost race | [0027](../adr/0027-optimistic-concurrency-for-commands.md) | +| 8 | Per-operation authorisation policies (read/write scopes per context) | Least privilege per BIAN operation, same on HTTP and MCP | [0038](../adr/0038-per-operation-authorisation-policies.md) | +| 9 | MCP as a first-class driving adapter | AI agents get the same rules, audit and errors | [0021](../adr/0021-mcp-wiring-and-tool-conventions.md), [0039](../adr/0039-party-mcp-tools.md), [0040](../adr/0040-party-mcp-command-tools.md) | +| 10 | Associations BQ as its own aggregate; other BQs as entities of the entry | Associations have their own lifecycle and many instances per party | [0024](../adr/0024-party-reference-data-directory-mapping.md), [0033](../adr/0033-party-associations.md) | +| 11 | Published language mapped from domain events, never read models | Producers can change their internal model freely | [0036](../adr/0036-party-published-language.md) | +| 12 | Conformance tests against the BIAN YAMLs | The API cannot silently drift from BIAN | [0020](../adr/0020-bian-conformance-harness.md), [0037](../adr/0037-bian-body-and-payload-conformance.md) | + +## 6. BIAN → architecture mapping + +| BIAN concept | Architecture element | Party example | +|---|---|---| +| Business Area / Business Domain | First namespace segment | `RimBank.Party` | +| Service Domain | Bounded context: core folder + adapters + schema + role + scopes | `RimBank.Party.PartyReferenceDataDirectory`, schema `party_reference_data_directory` | +| Control Record | Event-sourced aggregate root | `PartyReferenceDataDirectoryEntry` | +| Behavior Qualifier | Entity in the aggregate, or own aggregate by ADR | Demographics, Reference, BankRelations (entities); Associations (`PartyAssociation` aggregate) | +| Action term (Register, Update, Exchange, …) | Command + pure decision + domain events | `RegisterParty` → `PartyRegistered` | +| Retrieve | Query over an inline view | `RetrievePartyReferenceDataDirectoryEntry` | +| AsyncAPI channel | Integration event in `.PublishedLanguage` | `PartyReferenceDataDirectoryEntry/Created` | +| ISO 20022 data type | Value object with the type's constraints | `Max35Text` → `TaxIdentificationNumber` | + +## 7. Glossary of architecture terms + +| Term | Meaning in RimBank | +|---|---| +| Acknowledgement | A command's success result, built from the decided state and stream version, never from a read model | +| Decider | Aggregate state type implementing `IDecider` with static `Decide` and `Evolve` | +| Inline view | Read model updated in the same transaction as the events (read-your-write) | +| Async view | Read model updated by Marten's async daemon (eventually consistent) | +| Published language | A context's integration events: its only public contract besides its APIs | +| Write port / read port | Core interfaces (`IWritePort` / `IReadPort`) implemented by `.Postgresql` | +| Stream version | Number of events in an aggregate's stream; exposed as `ETag`, checked by `If-Match` | +| Operation id | BIAN operation name (`Demographics/Update`), also the authorisation policy name | diff --git a/docs/architecture/02-c4-model.md b/docs/architecture/02-c4-model.md new file mode 100644 index 0000000..bc2fdef --- /dev/null +++ b/docs/architecture/02-c4-model.md @@ -0,0 +1,269 @@ +# 02. C4 model + +The [C4 model](https://c4model.com) at four levels. Diagrams marked *(target)* include contexts from the roadmap that do not exist yet; all others describe `main` today. + +## Level 1: System context + +Who uses RimBank and what it relies on. + +```mermaid +C4Context + title System context: RimBank core banking platform + + Person(staff, "Bank staff", "Onboarding, operations and relationship managers using the bank's own front ends") + Person(customer, "Bank customer", "Uses the bank's digital channels") + + System_Ext(channels, "Bank channel applications", "Web, mobile, branch and back-office apps built by the bank") + System_Ext(agents, "AI agents", "Assistants and automations speaking the Model Context Protocol") + System(rimbank, "RimBank", "BIAN v14 core banking platform: party, product, account, position, payment and accounting capabilities") + System_Ext(idp, "Identity provider", "Keycloak or any OIDC / OAuth 2.1 authorization server") + System_Ext(consumers, "Downstream bank systems", "CRM, KYC/AML, data warehouse, regulatory reporting: consume integration events") + System_Ext(rails, "Payment rails (target)", "SEPA / ISO 20022 pacs schemes behind ports, Stage 8+") + System_Ext(obs, "Observability backend", "Any OTLP-compatible tracing, metrics and logging stack") + + Rel(customer, channels, "Uses") + Rel(staff, channels, "Uses") + Rel(staff, agents, "Asks") + Rel(channels, rimbank, "BIAN HTTP APIs", "HTTPS, JSON, JWT") + Rel(agents, rimbank, "MCP tools", "Streamable HTTP, JWT") + Rel(rimbank, idp, "Validates tokens, advertises authorization server", "OIDC") + Rel(channels, idp, "Obtains tokens", "OAuth 2.1") + Rel(rimbank, consumers, "Publishes integration events (target: RabbitMQ)", "AsyncAPI channels") + Rel(rimbank, rails, "Sends and receives payments (target)") + Rel(rimbank, obs, "Traces, metrics, logs", "OTLP") +``` + +**Key point:** RimBank has no end-user UI ([mission non-goals](../../specs/mission.md#non-goals)). Every human reaches it through a bank-built channel or an AI agent. Both channel types are equal citizens: same core, same policies, same errors. + +## Level 2: Containers + +```mermaid +C4Container + title Containers: RimBank modular monolith (today) + + System_Ext(channels, "Bank channel applications", "BIAN HTTP clients") + System_Ext(agents, "AI agents", "MCP clients") + System_Ext(idp, "Keycloak", "Realm rimbank, audience rimbank-api") + + System_Boundary(rb, "RimBank") { + Container(host, "RimBank.Host", ".NET 10, ASP.NET Core, Wolverine, Marten", "One deployable process: BIAN HTTP endpoints, /mcp endpoint, message bus, every context's core and adapters") + ContainerDb(pg, "PostgreSQL database rimbank", "PostgreSQL", "Schema per context: event streams, inline views, outbox, inbox, idempotency outcomes. Schema wolverine for node bookkeeping") + Container(apphost, "RimBank.AppHost", ".NET Aspire", "Local orchestration: PostgreSQL, Keycloak, per-context role connection strings, dashboard") + } + + System_Ext(otel, "OTLP backend", "Aspire dashboard locally") + + Rel(channels, host, "Register, Update, Retrieve …", "HTTPS /PartyReferenceDataDirectory/…") + Rel(agents, host, "tools/list, tools/call", "Streamable HTTP /mcp") + Rel(host, pg, "Reads and writes, one login role per context", "Npgsql") + Rel(host, idp, "JWKS, discovery", "HTTPS") + Rel(host, otel, "Telemetry", "OTLP") + Rel(apphost, host, "Starts, injects configuration") + Rel(apphost, pg, "Starts") + Rel(apphost, idp, "Starts with realm import") +``` + +| Container | Responsibility | Technology | Scales by | +|---|---|---|---| +| `RimBank.Host` | All request handling, decisions, persistence, messaging | ASP.NET Core Minimal APIs, MCP C# SDK, Wolverine, Marten | Horizontal instances; Wolverine `DurabilityMode.Balanced` shares durable work across nodes | +| PostgreSQL | System of record: events, views, outbox/inbox, idempotency | PostgreSQL | Vertical first; read replicas or dedicated read stores only by ADR (roadmap 7.6) | +| Keycloak | Tokens, scopes, MCP authorization server | Keycloak (dev); any OIDC provider elsewhere | External | +| `RimBank.AppHost` | Developer and test orchestration | .NET Aspire | Not deployed to production | + +### Container view after extraction *(target)* + +The modular-monolith promise ([tech-stack §2](../../specs/tech-stack.md#2-topology-modular-monolith-first)): extracting a context moves its core folder and adapters into a new service and swaps the local durable queue for RabbitMQ. No core code changes. + +```mermaid +flowchart LR + subgraph H1["RimBank.Host"] + P["Party context"] + PR["Product Directory context"] + end + subgraph H2["CurrentAccount service (extracted)"] + CA["Current Account context"] + end + MQ[["RabbitMQ
integration events"]] + DB1[("schemas: party_reference_data_directory,
product_directory")] + DB2[("schema: current_account")] + P -- "outbox → PartyReferenceDataDirectoryEntryCreated" --> MQ + PR -- "outbox → product events" --> MQ + MQ -- "inbox → .Subscriptions" --> CA + H1 --> DB1 + H2 --> DB2 +``` + +## Level 3: Components of `RimBank.Host` for the Party context + +```mermaid +C4Component + title Components: Party Reference Data Directory inside RimBank.Host + + Container_Boundary(host, "RimBank.Host") { + Component(auth, "Security", "JWT bearer, OperationPolicies, ActorRelay", "Authenticates, authorises per BIAN operation id, relays the caller subject to the bus") + Component(pd, "Problem Details", "RimBank.Problems + host handlers", "Maps Error → RFC 9457, unhandled exceptions → 500 shared.unexpected") + Component(module, "PartyReferenceDataDirectoryModule", "IServiceDomainModule", "Registers the context: store, ports, endpoints, MCP tools, policies, scopes") + + Component(api, "Party .Api folder", "RimBank.Api / Party / PartyReferenceDataDirectory", "13 BIAN endpoints: request/response models, Idempotency-Key, ETag/If-Match, dispatch") + Component(mcp, "Party .Mcp folder", "RimBank.Mcp / Party / PartyReferenceDataDirectory", "13 MCP tools: arguments, results, isError Problem Details, same policies") + + Component(bus, "Wolverine bus", "IMessageBus", "InvokeAsync dispatch, idempotency and concurrency-retry policies, transactional outbox") + + Component(cmd, "Command handlers", "RimBank.Core", "RegisterParty, Update*, Exchange*, Register/UpdatePartyAssociation: load → Decide → append → acknowledge → publish") + Component(qry, "Query handlers", "RimBank.Core", "Retrieve*: read the view through the read port") + Component(dom, "Aggregates and decisions", "RimBank.Core", "PartyReferenceDataDirectoryEntry, PartyAssociation: pure Decide / Evolve") + Component(proj, "Projections", "RimBank.Core", "Pure view evolve: entry view, association view") + Component(pub, "Publication mapper", "RimBank.Core", "Domain events → published language events") + + Component(wp, "MartenPartyDirectory", ".Postgresql", "IPartyDirectory write port over event streams") + Component(rp, "MartenPartyDirectoryEnquiry", ".Postgresql", "IPartyDirectoryEnquiry read port over inline views") + Component(pl, "PublishedLanguage", ".PublishedLanguage", "PartyReferenceDataDirectoryEntryCreated / Updated v1") + } + + ContainerDb(pg, "PostgreSQL", "schema party_reference_data_directory") + + Rel(auth, api, "Authorised requests") + Rel(auth, mcp, "Authorised tool calls") + Rel(api, bus, "InvokeAsync(command | query)") + Rel(mcp, bus, "InvokeAsync(command | query)") + Rel(bus, cmd, "Dispatches commands") + Rel(bus, qry, "Dispatches queries") + Rel(cmd, dom, "Decide / Evolve") + Rel(cmd, wp, "Load, start, append") + Rel(cmd, pub, "Map decided events") + Rel(pub, pl, "Creates") + Rel(qry, rp, "Find view") + Rel(wp, pg, "Event streams") + Rel(rp, pg, "View documents") + Rel(proj, pg, "Run inline by Marten on append") + Rel(api, pd, "error.ToHttpResult()") + Rel(mcp, pd, "error.ToToolResult()") +``` + +### Component catalogue + +| Component | Project / folder | Role (hexagonal) | Key types | +|---|---|---|---| +| Security | `RimBank.Host/Security` | Infrastructure (edge) | `AuthenticationComposition`, `OperationPolicies`, `OperationScopeRequirement`, `ActorRelay` | +| Module | `RimBank.Host/Modules/Party` | Composition | `PartyReferenceDataDirectoryModule` (scopes `party-reference-data-directory:read` / `:write`) | +| HTTP adapter | `RimBank.Api/Party/PartyReferenceDataDirectory/*` | Driving adapter | `RegisterPartyEndpoint`, `Update…Endpoint`, `Retrieve…Endpoint`, request/response records | +| HTTP conventions | `RimBank.Api` (root) | Driving adapter support | `IdempotencyKeyHeader`, `RequireIdempotencyKey()`, ETag / If-Match helpers | +| MCP adapter | `RimBank.Mcp/Party/PartyReferenceDataDirectory/*` | Driving adapter | 13 tools `party_reference_data_directory_*` | +| MCP conventions | `RimBank.Mcp` (root) | Driving adapter support | `ToToolResult`, tool error filter, authorisation filter, `[ToolOperation]` | +| Error mapping | `RimBank.Problems` | Shared edge | `Error` → Problem Details (`type`, `errorCode`, `traceId`, `errors`) | +| Core | `RimBank.Core/Party/PartyReferenceDataDirectory` | Domain + application | aggregates, commands, queries, handlers, views, projections, ports, publication | +| Persistence | `src/Party/…Postgresql` | Driven adapter | `MartenPartyDirectory`, `MartenPartyDirectoryEnquiry`, `PartyReferenceDataDirectoryPostgresql.Configure` | +| Persistence conventions | `RimBank.Postgresql` | Driven adapter support | `AddServiceDomainStore`, `IdempotencyGate`, `CommandConcurrencyRetryPolicy`, `AddInlineView` | +| Published language | `src/Party/…PublishedLanguage` | Contract | `PartyReferenceDataDirectoryEntryCreated`, `…Updated` | +| Shared kernel | `RimBank.SharedKernel` | Domain primitives | `Result`, `Error`, `ITypedId`, `Money`, `Currency`, `CountryCode`, `IDecider`, `IProjection`, `ICommand`, `IQuery`, `Actor` | + +## Level 4: Code (domain model of the Party core) + +```mermaid +classDiagram + direction LR + + class IDecider~TState,TCommand,TEvent~ { + <> + +Decide(command, state) Result~events~ + +Evolve(state, event) state + } + + class PartyReferenceDataDirectoryEntry { + <> + +PartyReferenceDataDirectoryEntryId? Id + +PartyType? PartyType + +DateTimeOffset? OpenDate + +DateTimeOffset? RefreshDate + +DemographicsId? DemographicsId + +PartyReferenceId? PartyReferenceId + +BankRelationsId? BankRelationsId + +DemographicsRecord? Demographics + +PartyReferenceDetails? Reference + +BankRelationsDetails? BankRelations + +Decide()$ + +Evolve()$ + } + + class DemographicsRecord { + <> + +PartyDemographics Details + +DemographicsVerificationStatus VerificationStatus + +DateTimeOffset? VerificationDate + } + class PartyDemographics { + <> + +string? SocioEconomicClassification + +Employment? Employment + +string? EmploymentHistory + +string? EducationHistory + +string? ServicingConstraints + } + + class PartyReferenceDetails { + <> + +PartyIdentifiers Identifiers + +PartyNames? Names + +DateOnly? DateOfBirth + +PartyResidency? Residency + +PartyAddresses? Addresses + +PartyContactPoints? ContactPoints + +PartyLegalStanding? LegalStanding + +PartyDocuments? Documents + +PartyCorporateReferences? CorporateReferences + } + + class BankRelationsDetails { + <> + +BankRelationType? Type + +EntryId? BusinessUnitEmployee + +DateTimeOffset? StartDate + +DateTimeOffset? EndDate + +BankRelationLifecycleStatus? LifecycleStatus + } + + class PartyAssociation { + <> + +PartyAssociationId? Id + +EntryId? OwnerId + +EntryId? AssociateId + +PartyRelationshipType? AssociateType + +AssociationValidityPeriod? ValidityPeriod + +Decide()$ + +Evolve()$ + } + + class IPartyDirectory { + <> + +LoadEntryAsync() + +StartEntry() + +AppendToEntry(expectedVersion) + +LoadAssociationAsync() + +StartAssociation() + +AppendToAssociation(expectedVersion) + } + class IPartyDirectoryEnquiry { + <> + +FindEntryAsync() + +FindAssociationAsync() + } + + IDecider <|.. PartyReferenceDataDirectoryEntry + IDecider <|.. PartyAssociation + PartyReferenceDataDirectoryEntry *-- "0..1" DemographicsRecord + DemographicsRecord *-- PartyDemographics + PartyReferenceDataDirectoryEntry *-- "0..1" PartyReferenceDetails + PartyReferenceDataDirectoryEntry *-- "0..1" BankRelationsDetails + PartyAssociation --> "1 owner" PartyReferenceDataDirectoryEntry : by id + PartyAssociation --> "1 associate" PartyReferenceDataDirectoryEntry : by id + PartyReferenceDetails ..> PartyReferenceDataDirectoryEntry : corporate and officer refs by id + BankRelationsDetails ..> PartyReferenceDataDirectoryEntry : employee or unit by id + IPartyDirectory ..> PartyReferenceDataDirectoryEntry : event stream + IPartyDirectory ..> PartyAssociation : event stream +``` + +Notes on level 4: + +- Aggregates reference each other **only by id**. The handler loads the referenced entry on the write side to check it exists and has the right party type before `Decide` runs ([ADR 0034](../adr/0034-reference-corporate-and-officer-references.md), [ADR 0035](../adr/0035-party-bank-relations.md)). +- `EntryId` in the diagram abbreviates `PartyReferenceDataDirectoryEntryId` (a Guid v7 `readonly record struct`, [ADR 0008](../adr/0008-typed-identifier-pattern.md)). +- The full member dictionary with business definitions is in [../business/02-party-domain-glossary.md](../business/02-party-domain-glossary.md). diff --git a/docs/architecture/03-data-model-erd.md b/docs/architecture/03-data-model-erd.md new file mode 100644 index 0000000..94f05ca --- /dev/null +++ b/docs/architecture/03-data-model-erd.md @@ -0,0 +1,270 @@ +# 03. Data model and entity-relationship diagrams + +RimBank is event-sourced, so there are three data models to understand, and they must not be confused: + +| Model | What it is | Authoritative? | Where | +|---|---|---|---| +| **Domain model** (conceptual / logical) | Aggregates, entities and value objects in the core | Yes: decisions run against it | `RimBank.Core/Party/PartyReferenceDataDirectory` | +| **Event model** | The append-only streams of domain events that *are* the state | **Yes: the system of record** | Marten event tables in schema `party_reference_data_directory` | +| **Read model** | Views projected from events, shaped for queries | No: disposable, rebuildable at any time | Marten document tables in the same schema | + +## 1. Logical domain ERD (Party Reference Data Directory) + +Cardinalities are what the decisions enforce. Value objects are shown as attributes of their owning entity; [the business glossary](../business/02-party-domain-glossary.md) defines every member. + +```mermaid +erDiagram + PARTY_REFERENCE_DATA_DIRECTORY_ENTRY { + guid EntryId PK "Guid v7, stream id" + enum PartyType "Person | Organisation" + datetime OpenDate "set at Register" + datetime RefreshDate "set at each entry Update" + guid DemographicsId UK "singleton BQ id" + guid PartyReferenceId UK "singleton BQ id" + guid BankRelationsId UK "singleton BQ id" + long Version "stream version, ETag" + } + + DEMOGRAPHICS { + guid DemographicsId PK + text SocioEconomicClassification "Max140Text" + text EmploymentPartyReference "Max140Text, free text" + text EmploymentInvolvementReference "Max140Text, free text" + text EmploymentHistory "Max2048Text" + text EducationHistory "Max2048Text" + text ServicingConstraints "Max2048Text" + enum VerificationStatus "Unverified | Verified | Rejected" + datetime VerificationDate + } + + REFERENCE { + guid PartyReferenceId PK + text TaxIdentificationNumber "Max35Text, PII" + text NationalRegistrationNumber "Max35Text, PII" + text LegalEntityIdentifier "ISO 17442 LEI" + text FullLegalName "PII" + text Salutation + date DateOfBirth "not after today, PII" + char2 Nationality "ISO 3166-1 alpha-2" + char2 CountryOfResidence "ISO 3166-1 alpha-2" + enum ResidencyStatusCode "Resident | NonResident" + datetime ResidencyStatusDateTime + enum LegalStructure "12 BIAN values" + enum PoliticalExposureType "Foreign | Domestic | NoExposure" + text PoliticalExposureDescription "Max350Text" + date CustomerSinceDate "not after today, not before birth" + text CompanyOfficerRole "Max35Text" + guid CorporateCustomerEntryId FK "Organisation" + guid LegalEntityEntryId FK "Organisation" + guid CompanyOfficerEntryId FK "Person" + } + + POSTAL_ADDRESS { + enum Usage "Residential | Party | Corporate" + text Department + text SubDepartment + text StreetName + text StreetBuildingIdentification + text BuildingName + text Floor + text PostOfficeBox + text PostCodeIdentification + text TownName "required" + char2 Country "required, ISO 3166" + } + + CONTACT_POINTS { + text EmailAddress "PII" + text MobileNumber "E.164, PII" + text SocialNetworkAddress "https URL" + } + + GOVERNMENT_ISSUED_DOCUMENT { + enum PartyDocumentType "Work | Certification | Personal" + text DocumentNumber "required, PII" + text DocumentName + date ValidFrom + date ValidTo "not before ValidFrom" + text DocumentDirectoryEntryReference "opaque ref to Document Directory" + } + + BANK_RELATIONS { + guid BankRelationsId PK + enum Type "RelationshipManager | AccountOfficer | ServicingBranch | ServicingBusinessUnit" + guid BusinessUnitEmployeeEntryId FK "Person or Organisation per Type" + datetime StartDate + datetime EndDate "not before StartDate" + enum LifecycleStatus "Active | Suspended | Ended" + } + + PARTY_ASSOCIATION { + guid AssociationId PK "Guid v7, own stream" + guid OwnerEntryId FK + guid AssociateEntryId FK "immutable after Register" + enum AssociateType "9 BIAN relationship types" + datetime ValidFrom + datetime ValidTo "not before ValidFrom" + long Version + } + + PARTY_REFERENCE_DATA_DIRECTORY_ENTRY ||--|| DEMOGRAPHICS : "has exactly one (empty until first Update)" + PARTY_REFERENCE_DATA_DIRECTORY_ENTRY ||--|| REFERENCE : "has exactly one" + PARTY_REFERENCE_DATA_DIRECTORY_ENTRY ||--|| BANK_RELATIONS : "has exactly one" + REFERENCE ||--o{ POSTAL_ADDRESS : "0..3, one per usage" + REFERENCE ||--o| CONTACT_POINTS : "0..1" + REFERENCE ||--o| GOVERNMENT_ISSUED_DOCUMENT : "0..1" + REFERENCE }o--o| PARTY_REFERENCE_DATA_DIRECTORY_ENTRY : "corporate customer, legal entity, officer" + BANK_RELATIONS }o--o| PARTY_REFERENCE_DATA_DIRECTORY_ENTRY : "employee or unit" + PARTY_REFERENCE_DATA_DIRECTORY_ENTRY ||--o{ PARTY_ASSOCIATION : "owns" + PARTY_REFERENCE_DATA_DIRECTORY_ENTRY ||--o{ PARTY_ASSOCIATION : "is associate in" +``` + +### Consistency boundaries + +| Boundary | Contains | Transactional guarantee | +|---|---|---| +| Entry stream | Entry + Demographics + Reference + BankRelations | Every rule inside it is checked atomically against the current version | +| Association stream | One association | Atomic per association; many per party without contention on the party's stream ([ADR 0024](../adr/0024-party-reference-data-directory-mapping.md)) | +| Cross-aggregate references (FK lines above) | Ids of other entries | Checked on the **write side** at decision time (the handler loads the referenced entry). Not a database foreign key: a later change to the referenced entry does not cascade | + +## 2. Event model + +Every state change is one of these events. The first column is the Marten event type name stored in the database (`PartyReferenceDataDirectoryPostgresql.Configure`). + +```mermaid +erDiagram + ENTRY_STREAM ||--|{ ENTRY_EVENT : "ordered by version" + ASSOCIATION_STREAM ||--|{ ASSOCIATION_EVENT : "ordered by version" + ENTRY_EVENT { + string party_registered "v1: EntryId, PartyType, OpenDate, DemographicsId, PartyReferenceId, BankRelationsId" + string party_reference_data_directory_entry_updated "EntryId, PartyType, RefreshDate" + string demographics_updated "EntryId, DemographicsId, Details, VerificationStatus, VerificationDate" + string demographics_exchanged "EntryId, DemographicsId, VerificationStatus, VerificationDate" + string party_reference_updated "EntryId, PartyReferenceId, Details (full snapshot of the BQ)" + string party_bank_relations_updated "EntryId, BankRelationsId, Details (full snapshot)" + } + ASSOCIATION_EVENT { + string party_association_registered "AssociationId, OwnerId, AssociateId, AssociateType, ValidityPeriod" + string party_association_updated "AssociationId, AssociateType, ValidityPeriod" + } +``` + +Design notes: + +- **BQ events carry the full BQ state after the change** (not a delta). `Evolve` replaces the BQ; projections stay trivial; replays are deterministic. +- Event type names are **mapped explicitly** so that renaming a C# type never breaks stored history. +- Events are internal. Only `.PublishedLanguage` events leave the context (section 4). + +## 3. Physical model (PostgreSQL) + +One database (`rimbank`), one schema and one login role per context ([ADR 0016](../adr/0016-per-context-marten-stores.md)). Tables are created and migrated by Marten and Wolverine; names below are the libraries' conventions and may vary with their versions. + +```mermaid +erDiagram + MT_STREAMS ||--o{ MT_EVENTS : "stream_id" + MT_STREAMS { + uuid id PK "EntryId or AssociationId" + string type "aggregate type" + bigint version "current stream version" + timestamptz created + timestamptz timestamp + } + MT_EVENTS { + bigint seq_id PK "global sequence in the schema" + uuid id UK "event id" + uuid stream_id FK + int version "position in stream, unique with stream_id" + string type "mapped event type name" + jsonb data "event payload" + timestamptz timestamp + } + MT_DOC_PARTYREFERENCEDATADIRECTORYENTRYVIEW { + uuid id PK "EntryId" + jsonb data "PartyReferenceDataDirectoryEntryView" + timestamptz mt_last_modified + } + MT_DOC_PARTYASSOCIATIONVIEW { + uuid id PK "AssociationId" + jsonb data "PartyAssociationView" + timestamptz mt_last_modified + } + MT_DOC_IDEMPOTENTOUTCOME { + string id PK "commandType:callerLength:caller:key" + string fingerprint "SHA-256 of payload without key" + jsonb acknowledgement "first successful result" + timestamptz mt_last_modified + } + WOLVERINE_OUTGOING_ENVELOPES { + uuid id PK + string message_type "party-reference-data-directory-entry.created.v1" + bytea body + string destination "local durable queue" + } + WOLVERINE_INCOMING_ENVELOPES { + uuid id PK + string status + bytea body + } + MT_STREAMS ||--o| MT_DOC_PARTYREFERENCEDATADIRECTORYENTRYVIEW : "inline projection" + MT_STREAMS ||--o| MT_DOC_PARTYASSOCIATIONVIEW : "inline projection" +``` + +| Object | Schema | Owner role | Written by | Read by | +|---|---|---|---|---| +| Event streams (`mt_events`, `mt_streams`) | `party_reference_data_directory` | `rimbank_party_reference_data_directory` | Write port (`AppendToEntry`, …) | Write port (load), projections | +| Entry and association views | same | same | Inline projections, in the append transaction | Read port only | +| Idempotent outcomes | same | same | `IdempotencyGate.Remember`, in the append transaction | `IdempotencyGate.EnterAsync` | +| Outbox / inbox envelopes | same | same | Wolverine, in the append transaction | Wolverine durability agent | +| Wolverine node bookkeeping | `wolverine` | `rimbank_wolverine` | Host | Host; **no context has grants** | + +**Isolation proof:** an integration test proves one context's role cannot read another context's schema (roadmap 0.10). When Stage 2 adds `product_directory`, Party's role still cannot see it, and vice versa. + +## 4. Published language (integration contract) + +```mermaid +erDiagram + PARTY_REFERENCE_DATA_DIRECTORY_ENTRY_CREATED_V1 { + guid EventId PK "Guid v7, dedup key for consumers" + datetime OccurredAt + guid PartyReferenceDataDirectoryEntryId + long Version "stream version after the event" + string PartyType "Person | Organisation" + string DirectoryEntryDateType "OpenDate" + datetime DirectoryEntryDate + } + PARTY_REFERENCE_DATA_DIRECTORY_ENTRY_UPDATED_V1 { + guid EventId PK + datetime OccurredAt + guid PartyReferenceDataDirectoryEntryId + long Version + string PartyType + string DirectoryEntryDateType "RefreshDate" + datetime DirectoryEntryDate + } +``` + +| Channel (BIAN AsyncAPI) | Message identity | Emitted when | +|---|---|---| +| `PartyReferenceDataDirectoryEntry/Created` | `party-reference-data-directory-entry.created.v1` | `PartyRegistered` | +| `PartyReferenceDataDirectoryEntry/Updated` | `party-reference-data-directory-entry.updated.v1` | `PartyReferenceDataDirectoryEntryUpdated` | + +The eight BQ channels (Demographics/Reference/Associations/BankRelations Created/Updated) are deferred ([ADR 0024](../adr/0024-party-reference-data-directory-mapping.md)). The contract deliberately carries **no PII**: it is enough for a consumer to know a party exists, its type and its version ([ADR 0036](../adr/0036-party-published-language.md)). A JSON-schema snapshot test pins each message so it can only evolve backwards-compatibly. + +## 5. Read models + +| View | Key | Lifecycle | Shape | Served operations | +|---|---|---|---|---| +| `PartyReferenceDataDirectoryEntryView` | EntryId | Inline | Entry header + version + Demographics + Reference + BankRelations | Entry, Demographics, Reference, BankRelations Retrieve | +| `PartyAssociationView` | AssociationId | Inline | Owner, associate, type, validity, version | Associations Retrieve | + +Both are inline because callers read their own writes immediately (ETag from the command, then Retrieve). Cross-stream views (search, lists, "all associations of a party") are async projections when a phase needs them ([tech-stack §8.3](../../specs/tech-stack.md#83-projection-lifecycle-when-to-use-which)). Every view is rebuildable with `RebuildViewAsync`. + +## 6. Shared kernel value types used in persistence + +| Type | Representation | Standard | +|---|---|---| +| Typed ids (`…Id`) | `uuid`, Guid **v7** (time-ordered) | RFC 9562 | +| `CountryCode` | 2-letter upper-case string | ISO 3166-1 alpha-2 | +| `Currency` / `Money` (Stage 3+) | ISO code + `decimal` amount, minor-unit rules | ISO 4217 | +| Dates | `DateOnly` → `YYYY-MM-DD`; instants `DateTimeOffset` in UTC | ISO 8601 | +| Reference texts | Plain JSON strings, validated on read | ISO 20022 `MaxNText` | diff --git a/docs/architecture/04-sequence-diagrams.md b/docs/architecture/04-sequence-diagrams.md new file mode 100644 index 0000000..534e689 --- /dev/null +++ b/docs/architecture/04-sequence-diagrams.md @@ -0,0 +1,347 @@ +# 04. Sequence diagrams + +Each diagram shows the real components and the order of checks. Participants: + +| Short name | Component | +|---|---| +| Client | A BIAN HTTP client (bank channel) | +| Agent | An MCP client (AI agent) | +| Auth | ASP.NET Core authentication + `OperationPolicies` + `ActorRelay` (`RimBank.Host/Security`) | +| Endpoint | The context's endpoint in `RimBank.Api` | +| Tool | The context's tool in `RimBank.Mcp` | +| Bus | Wolverine `IMessageBus` with the idempotency and concurrency-retry policies (`RimBank.Postgresql`) | +| Handler | Command or query handler in `RimBank.Core` | +| Decider | The aggregate's pure `Decide` / `Evolve` | +| WritePort / ReadPort | `MartenPartyDirectory` / `MartenPartyDirectoryEnquiry` | +| PG | PostgreSQL schema `party_reference_data_directory` | + +## 1. Register a party (command, happy path) + +```mermaid +sequenceDiagram + autonumber + actor Client + participant Auth + participant Endpoint as RegisterPartyEndpoint + participant Bus as Wolverine bus + participant Gate as IdempotencyGate + participant Handler as RegisterPartyHandler + participant Decider as PartyReferenceDataDirectoryEntry + participant WritePort as MartenPartyDirectory + participant PG as PostgreSQL + + Client->>Auth: POST /PartyReferenceDataDirectory/Register
Authorization: Bearer JWT, Idempotency-Key: K
{"PartyType":"Person"} + Auth->>Auth: validate JWT (issuer, audience rimbank-api) + Auth->>Auth: policy "PartyReferenceDataDirectoryEntry/Register"
requires scope party-reference-data-directory:write + Auth->>Auth: ActorRelay: sub → message context UserName + Auth->>Endpoint: authorised request + Endpoint->>Endpoint: RequireIdempotencyKey filter, map body → RegisterParty (PartyTypes.FromBianName) + Endpoint->>Bus: InvokeAsync>(RegisterParty) + Bus->>PG: BEGIN + Bus->>Gate: EnterAsync(command, caller, key) + Gate->>PG: pg_advisory_xact_lock(key), find IdempotentOutcome + PG-->>Gate: none + Gate-->>Bus: Proceed + Bus->>Handler: HandleAsync(command, directory, time) + Handler->>Handler: new EntryId, DemographicsId, PartyReferenceId, BankRelationsId (Guid v7)
OpenDate = time.GetUtcNow() + Handler->>WritePort: LoadEntryAsync(EntryId) + WritePort->>PG: read stream + PG-->>WritePort: [] + Handler->>Decider: Decide(RegisterPartyReferenceDataDirectoryEntry, Initial) + Decider-->>Handler: Ok([PartyRegistered]) + Handler->>WritePort: StartEntry(EntryId, events) + Handler->>Handler: Evolve → acknowledgement (version 1)
Publication.Created(...) → integration event + Handler-->>Bus: (Ok(Ack), PartyReferenceDataDirectoryEntryCreated) + Bus->>Gate: Remember(ticket, Ack) + Bus->>PG: append PartyRegistered, inline view upsert,
IdempotentOutcome insert, outbox envelope + Bus->>PG: COMMIT + Bus-->>Endpoint: Ok(Ack) + Endpoint-->>Client: 200 OK, ETag: "1"
{ ids, PartyType, OpenDate } + Note over Bus,PG: After commit, the durability agent delivers the outbox envelope
to the context's durable local queue (target: RabbitMQ) +``` + +Key properties: one database transaction holds events, view, idempotency outcome and outbox, so they are **all or nothing**. The response is built from the acknowledgement, never from the view. + +## 2. Same command retried (idempotent replay) and misuse + +```mermaid +sequenceDiagram + autonumber + actor Client + participant Bus as Wolverine bus + participant Gate as IdempotencyGate + participant Handler + participant PG as PostgreSQL + + Client->>Bus: RegisterParty, key K, same payload (e.g. network retry) + Bus->>Gate: EnterAsync + Gate->>PG: lock K, find outcome + PG-->>Gate: outcome, same fingerprint + Gate-->>Bus: replay stored acknowledgement + Bus-->>Client: 200, identical body and ETag (handler NOT run, no new events) + + Client->>Bus: RegisterParty, key K, different payload + Bus->>Gate: EnterAsync + Gate->>PG: find outcome + PG-->>Gate: outcome, different fingerprint + Gate-->>Client: 409 shared.idempotency-key-reused + + par two concurrent requests with key K + Client->>Bus: request A + Bus->>Gate: lock K acquired + and + Client->>Bus: request B + Bus->>Gate: lock K busy + Gate-->>Client: 409 shared.idempotency-key-in-use + end +``` + +Keys are scoped to *context + command type + caller subject*: two callers using the same key never interfere ([ADR 0018](../adr/0018-idempotency-keys-for-commands.md), [ADR 0019](../adr/0019-authentication-baseline.md)). Only successes are stored, so a failed command can be retried with the same key. + +## 3. Retrieve with ETag and conditional GET (query) + +```mermaid +sequenceDiagram + autonumber + actor Client + participant Auth + participant Endpoint as RetrievePartyReferenceDataDirectoryEntryEndpoint + participant Bus + participant Handler as RetrieveEntryHandler + participant ReadPort as MartenPartyDirectoryEnquiry + participant PG + + Client->>Auth: GET /PartyReferenceDataDirectory/{id}/Retrieve + Auth->>Auth: policy …/Retrieve requires party-reference-data-directory:read + Auth->>Endpoint: authorised + Endpoint->>Endpoint: parse {id}: not a Guid v7 → 400 shared.invalid-identifier + Endpoint->>Bus: InvokeAsync(RetrievePartyReferenceDataDirectoryEntry) + Bus->>Handler: Handle(query, enquiry) + Handler->>ReadPort: FindEntryAsync(id) + ReadPort->>PG: SELECT view document + alt view not found + PG-->>Handler: null + Handler-->>Endpoint: Error NotFound party.party-not-found + Endpoint-->>Client: 404 application/problem+json + else found + PG-->>Handler: view (Version = n) + Handler-->>Endpoint: Ok(view) + alt If-None-Match matches "n" + Endpoint-->>Client: 304 Not Modified, ETag "n" + else + Endpoint-->>Client: 200, ETag "n", BIAN response body + end + end +``` + +No idempotency, no transaction, no write port: the CQRS architecture rules forbid a query handler from touching aggregates or the write port. + +## 4. Update with optimistic concurrency and lost-race retry + +```mermaid +sequenceDiagram + autonumber + actor Client + participant Endpoint as Update…Endpoint + participant Bus + participant Retry as CommandConcurrencyRetryPolicy + participant Handler as Update…Handler + participant Decider + participant WritePort + participant PG + + Client->>Endpoint: PUT …/{id}/Update, If-Match: "3", Idempotency-Key: K + alt If-Match missing + Endpoint-->>Client: 428 shared.if-match-required + else weak, *, or list + Endpoint-->>Client: 400 shared.if-match-invalid + end + Endpoint->>Bus: InvokeAsync(Update… ExpectedVersion=3) + Bus->>Handler: attempt 1 + Handler->>WritePort: LoadEntryAsync(id) + WritePort-->>Handler: 3 events (version 3) + Handler->>Handler: version == ExpectedVersion ✔ + Handler->>Decider: Decide(update, state) + Decider-->>Handler: Ok([…Updated]) + Handler->>WritePort: AppendToEntry(id, expectedVersion 3, events) + Bus->>PG: COMMIT + PG-->>Bus: ConcurrencyException (another writer committed version 4) + Note over Bus,PG: nothing of attempt 1 is stored, idempotency lock released + Bus->>Retry: retry once + Retry->>Handler: attempt 2 + Handler->>WritePort: LoadEntryAsync(id) + WritePort-->>Handler: version 4 + Handler-->>Bus: Error Conflict party.version-conflict (value, not exception) + Bus-->>Endpoint: Error + Endpoint-->>Client: 409 party.version-conflict → client re-Retrieves and retries with If-Match "4" +``` + +## 5. Update Reference with corporate references (cross-aggregate check on the write side) + +```mermaid +sequenceDiagram + autonumber + actor Client + participant Handler as UpdatePartyReferenceHandler + participant WritePort + participant Decider as Entry.Decide + participant PG + + Client->>Handler: UpdatePartyReference(entry O, CorporateCustomer=C, CompanyOfficer=P, Role="Director") + Handler->>WritePort: LoadEntryAsync(O) + Handler->>WritePort: LoadEntryAsync(C), LoadEntryAsync(P) + WritePort->>PG: read streams O, C, P + Handler->>Handler: ReferencedParties = {C: Organisation, P: Person} + Handler->>Decider: Decide(UpdatePartyReferenceDetails{Changes, Today, ReferencedParties}, state O) + alt O is not an Organisation + Decider-->>Handler: party.corporate-references-need-organisation + else C == O + Decider-->>Handler: party.self-reference + else C not registered + Decider-->>Handler: party.referenced-party-not-registered + else P is an Organisation + Decider-->>Handler: party.referenced-party-type-mismatch + else Role without officer + Decider-->>Handler: party.reference-invalid (officer role without officer) + else valid + Decider-->>Handler: Ok([PartyReferenceUpdated(full Reference snapshot)]) + Handler->>WritePort: AppendToEntry(O, expectedVersion, events) + end +``` + +Only stream **O** is appended. C and P are read for validation only; their later changes do not cascade (documented staleness, [ADR 0034](../adr/0034-reference-corporate-and-officer-references.md)). + +## 6. Register a party association (own aggregate) + +```mermaid +sequenceDiagram + autonumber + actor Client + participant Endpoint as RegisterPartyAssociationEndpoint + participant Handler as RegisterPartyAssociationHandler + participant WritePort + participant Decider as PartyAssociation.Decide + participant PG + + Client->>Endpoint: POST /PartyReferenceDataDirectory/{owner}/Associations/Register
{AssociateReference, AssociateType, AssociationValidFromToDate} + Endpoint->>Endpoint: PartyAssociationTerms: refuse unrecorded BIAN fields,
parse type (9 values), validity period + Endpoint->>Handler: RegisterPartyAssociation + Handler->>WritePort: LoadEntryAsync(owner), LoadEntryAsync(associate) + Handler->>Decider: Decide(RegisterPartyAssociationDetails{OwnerIsRegistered, AssociateIsRegistered}, Initial) + alt owner unknown + Decider-->>Handler: party.party-not-found (404) + else associate == owner + Decider-->>Handler: party.self-association + else associate unknown + Decider-->>Handler: party.associate-not-registered + else ok + Decider-->>Handler: Ok([PartyAssociationRegistered]) + Handler->>WritePort: StartAssociation(newId, events) + WritePort->>PG: new stream + inline PartyAssociationView + Handler-->>Endpoint: PartyAssociationAcknowledged (id, version 1) + end +``` + +## 7. Demographics verification (Exchange) + +```mermaid +sequenceDiagram + autonumber + actor Officer as KYC officer (via channel) + participant Handler as ExchangeDemographicsHandler + participant Decider as Entry.Decide + + Officer->>Handler: ExchangeDemographics(Action = Verify | Reject), If-Match + Handler->>Decider: Decide(ExchangeDemographicsDetails, state) + alt demographics id not the entry's + Decider-->>Handler: party.behavior-qualifier-not-found + else nothing recorded yet + Decider-->>Handler: party.demographics-not-recorded + else + Decider-->>Handler: DemographicsExchanged(Verified | Rejected, VerificationDate = now) + end + Note over Officer,Decider: Any later DemographicsUpdated that changes the details
resets the status to Unverified (ADR 0028) +``` + +## 8. MCP tool call (AI agent), same core + +```mermaid +sequenceDiagram + autonumber + actor Agent as AI agent + participant MCP as /mcp (Streamable HTTP, stateless) + participant Auth + participant Filter as RimBank.Mcp filters + participant Tool as party_reference_data_directory_update_demographics + participant Bus + participant Core as Core handler + + Agent->>MCP: POST /mcp (no token) + MCP-->>Agent: 401 + WWW-Authenticate → RFC 9728 protected-resource metadata
(authorization server = Keycloak realm, scopes_supported) + Agent->>Agent: OAuth 2.1 with Keycloak → token (aud rimbank-api) + Agent->>MCP: tools/list (Bearer) + MCP->>Auth: authenticate + MCP->>Filter: hide tools whose operation policy the caller fails + MCP-->>Agent: tools the caller may use (read-only tools annotated readOnly) + Agent->>MCP: tools/call {partyReferenceDataDirectoryId, demographicsId,
idempotencyKey, expectedVersion, request:{…BIAN names…}} + MCP->>Filter: authorise [ToolOperation("Demographics/Update")] → write scope + alt arguments cannot bind + Filter-->>Agent: isError, Problem Details shared.tool-arguments-invalid + end + Filter->>Tool: invoke + Tool->>Bus: InvokeAsync(UpdateDemographics) – same command as HTTP + Bus->>Core: idempotency, concurrency, decide, append + Core-->>Tool: Result + alt failure + Tool-->>Agent: isError: true, structuredContent = same Problem Details as HTTP + else success + Tool-->>Agent: result = HTTP response body + version (HTTP's ETag) + end +``` + +Parity tests assert that HTTP and MCP return the same JSON and the same Problem Details for the same operation ([ADR 0039](../adr/0039-party-mcp-tools.md)). + +## 9. Error handling path (any request) + +```mermaid +sequenceDiagram + autonumber + actor Caller + participant Edge as Endpoint / Tool + participant Problems as RimBank.Problems + participant Host as Host exception handler + + Caller->>Edge: request + alt business or validation failure (Result.Error) + Edge->>Problems: error.ToHttpResult() / ToToolResult() + Problems-->>Caller: problem+json {type: urn:rimbank:problem:party:…, title, status, detail, instance, errorCode, traceId, errors?} + else unexpected exception + Edge->>Host: throws + Host-->>Caller: 500 shared.unexpected (no stack trace, traceId for support) + else unknown route + Host-->>Caller: 404 shared.not-found + end +``` + +## 10. Planned: cross-context integration (Stage 4, target) + +How Current Account will learn about parties without calling Party ([tech-stack §8.4](../../specs/tech-stack.md#84-read-models-across-contexts-loose-coupling)). + +```mermaid +sequenceDiagram + autonumber + participant Party as Party handler + participant Outbox as Party outbox (party schema) + participant Queue as Durable queue / RabbitMQ + participant Subs as CurrentAccount.Subscriptions + participant CAStore as CurrentAccount store + participant CA as InitiateFacility handler + + Party->>Outbox: PartyReferenceDataDirectoryEntryCreated.v1 (same txn as PartyRegistered) + Outbox->>Queue: deliver (at-least-once) + Queue->>Subs: message (inbox dedups by EventId) + Subs->>Subs: translate to local "KnownPartyRecorded" (tolerant reader) + Subs->>CAStore: append local reference event → "known party" view + Note over CA,CAStore: Later, InitiateFacility checks the LOCAL known-party view.
It never queries Party, staleness documented in an ADR. + CA->>CAStore: read known-party view, decide, append +``` diff --git a/docs/architecture/05-logic-flows.md b/docs/architecture/05-logic-flows.md new file mode 100644 index 0000000..00f2a3a --- /dev/null +++ b/docs/architecture/05-logic-flows.md @@ -0,0 +1,251 @@ +# 05. Logic flows and state machines + +Flowcharts of the request pipeline and of each decision, and state machines for every lifecycle in the Party context. Decision order matters: it defines *which* error a caller receives when several rules fail, and it is pinned by tests. + +## 1. Request pipeline (HTTP command) + +```mermaid +flowchart TD + A([HTTP request]) --> B{Route known?} + B -- no --> E404[404 shared.not-found] + B -- yes --> C{Valid JWT?} + C -- no --> E401[401 shared.unauthenticated] + C -- yes --> C2{Actor identifiable
sub and azp?} + C2 -- no --> E401b[401 shared.actor-invalid] + C2 -- yes --> D{Scope for this
operation id?} + D -- no --> E403[403 shared.forbidden] + D -- yes --> F{Idempotency-Key
present and valid?} + F -- missing --> E400a[400 shared.idempotency-key-missing] + F -- invalid --> E400b[400 shared.idempotency-key-invalid] + F -- yes --> I{Route ids valid Guid v7?} + I -- no --> E400d[400 shared.invalid-identifier] + I -- yes --> G{Changes an existing record?} + G -- yes --> H{If-Match?} + H -- missing --> E428[428 shared.if-match-required] + H -- weak, *, list --> E400c[400 shared.if-match-invalid] + H -- strong tag --> J + G -- no --> J{Body parses and
maps to command?} + J -- no --> E400e[400 validation Problem Details
with errors per BIAN field] + J -- yes --> K[[Bus: idempotency gate]] + K -- replay --> OK200r[200 stored acknowledgement] + K -- reused / in use --> E409a[409 shared.idempotency-key-*] + K -- proceed --> L[[Handler: load, version check, Decide]] + L -- Error --> M[Problems mapping → 4xx] + L -- events --> N[(Commit: events + view + outcome + outbox)] + N -- lost race --> L + N -- ok --> OK200[200 acknowledgement + ETag] +``` + +Queries follow the same pipeline up to the scope check (read scope), then skip idempotency, `If-Match` and the transaction; they add the `If-None-Match` → 304 branch. + +## 2. Entry decision (`PartyReferenceDataDirectoryEntry.Decide`) + +The `switch` in `Decisions.cs`, as a decision tree. First matching rule wins. + +```mermaid +flowchart TD + S([command, state]) --> R{Command type} + + R -- Register --> R1{PartyType defined?} + R1 -- no --> X1[party.party-type-invalid] + R1 -- yes --> R2{Already registered?} + R2 -- yes --> X2[party.party-already-registered] + R2 -- no --> OK1[PartyRegistered] + + R -- Update entry --> U1{Registered?} + U1 -- no --> X3[party.party-not-found] + U1 -- yes --> U2{New type defined?} + U2 -- no --> X1 + U2 -- yes --> U3{To Person while corporate
references are recorded?} + U3 -- yes --> X4[party.corporate-references-need-organisation] + U3 -- no --> OK2[PartyReferenceDataDirectoryEntryUpdated
type ?? current, RefreshDate] + + R -- BQ command --> B0{Registered?} + B0 -- no --> X3 + B0 -- yes --> B1{BQ id is the entry's?} + B1 -- no --> X5[party.behavior-qualifier-not-found] + B1 -- yes --> BQ{Which BQ} + BQ -- Demographics Update --> OK3[DemographicsUpdated
status reset to Unverified if details changed] + BQ -- Demographics Exchange --> D1{Action defined?} + D1 -- no --> X6[party.exchange-action-type-invalid] + D1 -- yes --> D2{Any details recorded?} + D2 -- no --> X7[party.demographics-not-recorded] + D2 -- yes --> OK4[DemographicsExchanged
Verified or Rejected] + BQ -- Reference Update --> RF[[Reference rules §3]] + BQ -- BankRelations Update --> BR[[BankRelations rules §4]] +``` + +## 3. Reference update rules + +```mermaid +flowchart TD + A([UpdatePartyReferenceDetails]) --> B{DateOfBirth after today?} + B -- yes --> X1[party.reference-invalid
date of birth after today] + B -- no --> C{CustomerSinceDate after today?} + C -- yes --> X2[party.reference-invalid
customer-since after today] + C -- no --> D[Apply partial changes → updated details] + D --> E{Corporate references present
and party not Organisation?} + E -- yes --> X3[party.corporate-references-need-organisation] + E -- no --> F{For each referenced entry} + F --> F1{Refers to itself?} + F1 -- yes --> X4[party.self-reference] + F1 -- no --> F2{Registered?} + F2 -- no --> X5[party.referenced-party-not-registered] + F2 -- yes --> F3{Expected type?
officer = Person,
customer and legal entity = Organisation} + F3 -- no --> X6[party.referenced-party-type-mismatch] + F3 -- yes --> G{PEP description without
Foreign or Domestic exposure?} + G -- yes --> X7[party.reference-invalid
PEP description without exposure] + G -- no --> H{CustomerSince before DateOfBirth?} + H -- yes --> X8[party.reference-invalid
customer-since before birth] + H -- no --> I{Officer role without officer?} + I -- yes --> X9[party.reference-invalid
officer role without officer] + I -- no --> OK[PartyReferenceUpdated
full Reference snapshot] +``` + +Field-level validation (ISO 20022 lengths, LEI check digits, E.164, ISO 3166, address town and country required, document validity order) runs **before** the decision when the adapter builds `PartyReferenceChanges`, returning `party.reference-invalid` with per-field `errors`. Fields BIAN defines but RimBank does not yet record are refused with `party.reference-field-not-supported` rather than silently dropped ([ADR 0029](../adr/0029-reference-fields-in-stages.md)). + +## 4. BankRelations update rules + +```mermaid +flowchart TD + A([UpdateBankRelationsDetails]) --> B[Apply partial changes] + B --> C{Employee or unit reference
without a relation type?} + C -- yes --> X1[party.bank-relations-invalid
reference without type] + C -- no --> D{EndDate before StartDate?} + D -- yes --> X2[party.bank-relations-invalid
end before start] + D -- no --> E{Reference to check?
reference or type changed} + E -- no --> OK + E -- yes --> F{Refers to itself?} + F -- yes --> X3[party.self-reference] + F -- no --> G{Registered?} + G -- no --> X4[party.referenced-party-not-registered] + G -- yes --> H{Party type matches relation?
RelationshipManager, AccountOfficer → Person
ServicingBranch, ServicingBusinessUnit → Organisation} + H -- no --> X5[party.referenced-party-type-mismatch] + H -- yes --> OK[BankRelationsUpdated] +``` + +## 5. Association decision + +```mermaid +flowchart TD + A([command, association state]) --> T{Type} + T -- Register --> R1{Association already registered?} + R1 -- yes --> X1[party.association-already-registered] + R1 -- no --> R2{AssociateType defined?} + R2 -- no --> X2[party.association-invalid] + R2 -- yes --> R3{Owner registered?} + R3 -- no --> X3[party.party-not-found] + R3 -- yes --> R4{Associate == owner?} + R4 -- yes --> X4[party.self-association] + R4 -- no --> R5{Associate registered?} + R5 -- no --> X5[party.associate-not-registered] + R5 -- yes --> OK1[PartyAssociationRegistered] + T -- Update --> U1{Registered and owned
by this entry?} + U1 -- no --> X6[party.association-not-found] + U1 -- yes --> U2{Type defined?} + U2 -- no --> X2 + U2 -- yes --> U3{Tries to change the associate?} + U3 -- yes --> X7[party.associate-cannot-change] + U3 -- no --> OK2[PartyAssociationUpdated] +``` + +## 6. State machines + +### 6.1 Directory entry lifecycle + +```mermaid +stateDiagram-v2 + [*] --> Unregistered + Unregistered --> Registered: Register / PartyRegistered + Registered --> Registered: Update / …EntryUpdated (RefreshDate) + Registered --> Registered: BQ Update or Exchange + note right of Registered + Control (suspend, terminate) is a deferred + BIAN operation: no closed state yet. + Lifecycle and KYC status belong to + Party Lifecycle Management (Stage 8+). + end note +``` + +### 6.2 Demographics verification ([ADR 0028](../adr/0028-demographics-exchange-as-verification.md)) + +```mermaid +stateDiagram-v2 + [*] --> Unverified: entry registered (no details) + Unverified --> Unverified: Update + Unverified --> Verified: Exchange Verify (details recorded) + Unverified --> Rejected: Exchange Reject (details recorded) + Verified --> Rejected: Exchange Reject + Rejected --> Verified: Exchange Verify + Verified --> Unverified: Update that changes details + Rejected --> Unverified: Update that changes details + Verified --> Verified: Update with identical details +``` + +### 6.3 Bank relation lifecycle ([ADR 0035](../adr/0035-party-bank-relations.md)) + +The status is **recorded**, not enforced as transitions: the bank declares it. The diagram shows the intended business meaning. + +```mermaid +stateDiagram-v2 + [*] --> NotRecorded + NotRecorded --> Active: Update (type, employee/unit, StartDate) + Active --> Suspended + Suspended --> Active + Active --> Ended: EndDate set + Suspended --> Ended + Ended --> Active: re-assigned (new Update) +``` + +### 6.4 Party association + +```mermaid +stateDiagram-v2 + [*] --> Registered: Associations/Register + Registered --> Registered: Update type or validity period + state Registered { + [*] --> Pending: now before From + Pending --> Effective: From reached + Effective --> Expired: To passed + } + note right of Registered + Effectiveness is derived from the validity + period at read time, the associate never changes. + end note +``` + +### 6.5 Command message (idempotency × concurrency) + +```mermaid +stateDiagram-v2 + [*] --> Received + Received --> Refused: key missing or invalid + Received --> Replayed: same key, same fingerprint + Received --> Refused: same key, other fingerprint or in use + Received --> Deciding: new key, lock taken + Deciding --> Rejected: Error (nothing stored, key reusable) + Deciding --> Committing: events decided + Committing --> Deciding: lost race (retry once) + Committing --> Committed: events, view, outcome, outbox + Committed --> Published: outbox delivered + Replayed --> [*] + Refused --> [*] + Rejected --> [*] + Published --> [*] +``` + +## 7. Read-model rebuild flow + +```mermaid +flowchart LR + A[Projection shape changes in a PR] --> B[Deploy new code] + B --> C[RebuildViewAsync for the view] + C --> D[(Drop view documents)] + D --> E[Replay every stream of the context
through the pure projection] + E --> F[(Views rebuilt)] + F --> G{GetViewProgressAsync
caught up?} + G -- no --> E + G -- yes --> H([Serve queries]) +``` + +The zero-downtime variant (blue/green view tables) is roadmap 7.4. diff --git a/docs/architecture/06-data-flow.md b/docs/architecture/06-data-flow.md new file mode 100644 index 0000000..c4f8af2 --- /dev/null +++ b/docs/architecture/06-data-flow.md @@ -0,0 +1,153 @@ +# 06. Data flow + +Data-flow diagrams (DFD) in the Gane–Sarson spirit: external entities, processes, data stores and flows, at increasing depth. Then data classification and lineage. + +## 1. DFD level 0 (context) + +```mermaid +flowchart LR + CH[/"Bank channels"/] + AG[/"AI agents"/] + IDP[/"Identity provider"/] + DS[/"Downstream systems
(CRM, KYC, DWH, reporting)"/] + OB[/"Observability backend"/] + + RB(("0
RimBank")) + + CH -- "commands: party data, ids, idempotency key, version" --> RB + RB -- "acknowledgements, views, ETag, Problem Details" --> CH + AG -- "tool calls (same commands and queries)" --> RB + RB -- "tool results / isError Problem Details" --> AG + IDP -- "signing keys, token claims: sub, azp, scope, aud" --> RB + RB -- "integration events: no PII" --> DS + RB -- "traces, metrics, logs (PII-masked, roadmap 7.2)" --> OB +``` + +## 2. DFD level 1 (inside RimBank, Party context) + +```mermaid +flowchart TB + CH[/"Channel / Agent"/] + + P1(("1.0
Authenticate
and authorise")) + P2(("2.0
Translate request
(.Api / .Mcp)")) + P3(("3.0
Guard command
(idempotency, version)")) + P4(("4.0
Decide
(pure core)")) + P5(("5.0
Project views
(inline)")) + P6(("6.0
Answer query")) + P7(("7.0
Publish integration
events (outbox)")) + + D1[("D1 Event streams
mt_events / mt_streams")] + D2[("D2 Views
entry, association")] + D3[("D3 Idempotent outcomes")] + D4[("D4 Outbox / inbox")] + + DS[/"Consumers"/] + + CH -- "request + JWT" --> P1 + P1 -- "authorised request + actor subject" --> P2 + P2 -- "command (typed values)" --> P3 + P2 -- "query (ids)" --> P6 + P3 -- "fingerprint, key" <--> D3 + P3 -- "command" --> P4 + D1 -- "stream history (own + referenced entries)" --> P4 + P4 -- "decided events" --> D1 + D1 -- "new events (same txn)" --> P5 + P5 -- "view documents" --> D2 + D2 -- "view" --> P6 + P6 -- "view + version" --> P2 + P4 -- "decided events" --> P7 + P7 -- "Created / Updated v1" --> D4 + D4 -- "after commit" --> DS + P2 -- "acknowledgement / view / Problem Details" --> CH +``` + +**Invariant flows:** + +- D1 is written **only** by process 4 through the write port. Nothing else writes events. +- D2 is written **only** by process 5. Queries (6) never read D1; commands (4) never read D2. +- D3, D1, D2 and D4 writes for a command share **one PostgreSQL transaction**. +- Process 7 maps from **decided events**, never from D2 ([ADR 0036](../adr/0036-party-published-language.md)). + +## 3. CQRS data paths + +```mermaid +flowchart LR + subgraph Write["Write side (consistent)"] + C[Command] --> H[Command handler] + H --> WP[Write port] + WP <--> ES[(Event stream)] + H --> DEC[Decide] + end + subgraph Read["Read side (inline today, async when needed)"] + PR[Projection] --> V[(View)] + Q[Query] --> QH[Query handler] --> RP[Read port] --> V + end + ES -- events --> PR + H -- ack built from decided state --> OUT1([Command response]) + QH -- view --> OUT2([Query response + ETag]) +``` + +## 4. Cross-context data flow *(target, Stages 2–6)* + +Each context owns its data; others receive only what they need, via events, and keep their own minimal copy ([tech-stack §8.4](../../specs/tech-stack.md#84-read-models-across-contexts-loose-coupling)). + +```mermaid +flowchart LR + PRDD["Party Reference
Data Directory"] + PD["Product Directory"] + CA["Current Account"] + PK["Position Keeping"] + POI["Payment Order
Initiation"] + FA["Financial Accounting"] + AR["Account
Reconciliation"] + CP["Customer Position
(query-only)"] + + PRDD -- "EntryCreated/Updated: id, type" --> CA + PD -- "product launched/withdrawn + terms" --> CA + CA -- "facility initiated → open position log" --> PK + POI -- "debit/credit/reversal requested" --> CA + CA -- "payment/deposit executed or rejected" --> POI + PK -- "FinancialTransactionCaptured" --> FA + PK -- "totals at checkpoint" --> AR + FA -- "GL totals at checkpoint" --> AR + PRDD -. "events" .-> CP + CA -. "events" .-> CP + POI -. "events" .-> CP +``` + +| Data | Owner (system of record) | Copies allowed | Copy content | +|---|---|---|---| +| Party identity and type | Party Reference Data Directory | Current Account, Customer Position | Entry id, party type, "known" flag; **no PII** | +| Party demographics, identifiers, addresses, contacts | Party Reference Data Directory | None by default | Consumers that need them get them through future BQ channels, with an ADR | +| Product terms | Product Directory | Current Account | Currency, fees, interest terms needed for decisions | +| Authoritative balance | Decided in ADR 3.1 (write-side) | Views only | Projections never used for funds checks | +| GL postings | Financial Accounting | Reconciliation | Totals at checkpoints | + +## 5. Data classification + +| Class | Examples in Party | Where it exists | Controls today | Planned | +|---|---|---|---|---| +| **Sensitive personal data** | Tax id, national registration number, date of birth, government document number, political exposure | D1 (event payloads), D2 (views) | Per-context DB role, TLS, authenticated and scoped access, no PII in integration events | Field protection at rest in streams and views, log masking (roadmap 7.2) | +| **Personal data** | Full legal name, salutation, addresses, email, mobile, social network, nationality, residency, employment, education, servicing constraints | D1, D2 | Same | Same | +| **Business reference** | Party type, LEI, legal structure, relationships, bank relations, dates | D1, D2, events (type only) | Same | — | +| **Operational** | Idempotency fingerprints (SHA-256, never the payload), envelopes, traces | D3, D4, telemetry | Fingerprint only; trace carries `enduser.id` (subject) | Audit query API (7.3) | +| **Secrets** | DB role passwords, client secrets | User secrets locally; vault elsewhere | Never in source; Aspire generates 32-char role passwords | — | + +### GDPR / privacy note + +Event sourcing makes the audit trail immutable, which conflicts with erasure requests on personal data. The planned approach (roadmap 7.2) is protection of sensitive fields at rest so personal data can be made unreadable without rewriting history (e.g. per-subject key "crypto-shredding"). It needs its own ADR before Stage 7; until then **RimBank must not hold production personal data**. + +## 6. Data lineage of a Retrieve response field + +```mermaid +flowchart LR + A["Channel sends Reference/Update
TaxIdentificationNumber = ' FR123 '"] --> B["Adapter: PartyReferenceChanges
trim, Max35Text check"] + B --> C["Decide: PartyReferenceUpdated
Details.Identifiers.TaxIdentificationNumber = 'FR123'"] + C --> D[("mt_events: party_reference_updated
data jsonb")] + D --> E["PartyReferenceDataDirectoryEntryViewProjection"] + E --> F[("view: Reference.Identifiers…")] + F --> G["Reference/Retrieve response
BIAN field name, ETag = stream version"] +``` + +Every value in a response can be traced back to one event in one stream, at one version, written by one actor at one time: that is the audit property the mission asks for. diff --git a/docs/architecture/07-dependencies.md b/docs/architecture/07-dependencies.md new file mode 100644 index 0000000..7afdfc8 --- /dev/null +++ b/docs/architecture/07-dependencies.md @@ -0,0 +1,158 @@ +# 07. Dependencies + +Three kinds of dependency, each governed differently: + +1. **Code dependencies** between projects and namespaces: enforced by ArchUnitNET tests (`RimBank.Architecture.Tests`), proven to bite by good/bad fixtures (`RimBank.Architecture.Fixtures`). +2. **Runtime dependencies** on infrastructure: PostgreSQL, the identity provider, telemetry. +3. **Context dependencies** between bounded contexts: only through published language, enforced by architecture tests and database roles. + +## 1. Project dependency graph (today) + +Arrows mean "references". Dashed = composition only. + +```mermaid +flowchart TB + SK["RimBank.SharedKernel
(BCL only)"] + PL["RimBank.Party.PartyReferenceDataDirectory
.PublishedLanguage
(BCL only)"] + CORE["RimBank.Core
Party/PartyReferenceDataDirectory/…"] + PROB["RimBank.Problems"] + API["RimBank.Api
root conventions + Party folder"] + MCP["RimBank.Mcp
root conventions + Party folder"] + PGC["RimBank.Postgresql
(store, messaging, idempotency conventions)"] + PPG["RimBank.Party.PartyReferenceDataDirectory
.Postgresql"] + SD["RimBank.ServiceDefaults"] + HOST["RimBank.Host"] + AH["RimBank.AppHost"] + + CORE --> SK + CORE --> PL + PROB --> SK + API --> CORE + API --> PROB + API --> SK + MCP --> CORE + MCP --> PROB + MCP --> SK + PGC --> SK + PPG --> CORE + PPG --> PGC + HOST -.-> API + HOST -.-> MCP + HOST -.-> PPG + HOST -.-> PGC + HOST -.-> SD + HOST -.-> CORE + AH -.-> HOST +``` + +## 2. Dependency rules + +The normative table is [tech-stack §4](../../specs/tech-stack.md#4-dependency-rules-enforced-by-architecture-tests). Summary as a matrix: ✅ allowed, ❌ forbidden (test fails), — not applicable. + +| From ↓ / To → | SharedKernel | Own core | Other core | Own PL | Other PL | Problems | ASP.NET | Marten / Npgsql | Wolverine | MCP SDK | +|---|---|---|---|---|---|---|---|---|---|---| +| SharedKernel | — | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | +| Core (a context) | ✅ | — | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | +| .PublishedLanguage | ❌ | ❌ | ❌ | — | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | +| .Api folder | ✅ | ✅ | ❌ | ✅ | ❌ | ✅ | ✅ | ❌ | ✅ `IMessageBus` | ❌ | +| .Mcp folder | ✅ | ✅ | ❌ | ✅ | ❌ | ✅ | ✅ | ❌ | ✅ `IMessageBus` | ✅ | +| .Postgresql | ✅ | ✅ | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ `Wolverine.Marten` | ❌ | +| .Subscriptions *(future)* | ✅ | ✅ | ❌ | ✅ | ✅ **only here** | ❌ | ❌ | ❌ | ✅ | ❌ | +| RimBank.Problems | ✅ | ❌ | ❌ | ❌ | ❌ | — | ✅ | ❌ | ❌ | ❌ | +| RimBank.Host | ✅ | ✅ composition | ✅ composition | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | + +Additional enforced rules: + +| Rule | What it prevents | +|---|---| +| `cross-context-isolation` | A context's code in `RimBank.Core` using another context's namespace | +| `context-namespaces-stop-at-the-adapter` | Folder names leaking into namespaces ([ADR 0026](../adr/0026-flat-context-namespaces.md)) | +| CQRS role rules ([ADR 0012](../adr/0012-cqrs-role-markers.md)) | Command handlers reading views; query handlers touching aggregates or write ports; projections using ports, handlers or `TimeProvider` | +| Forbidden folders | `Services`, `Repositories`, `Helpers`, `Managers`, `Utils`, `Dtos` in the core | +| Typed ids are `readonly record struct` | Reference-type ids and accidental nulls ([ADR 0008](../adr/0008-typed-identifier-pattern.md)) | +| No `double` / `float` in cores, SharedKernel, PublishedLanguage | Binary floating point for money ([ADR 0009](../adr/0009-money-and-currency.md)) | +| Deciders implement `IDecider`, projections `IProjection` | Bypassing the functional contracts ([ADR 0010](../adr/0010-decider-and-projection-contracts.md)) | +| `allow-anonymous-only-in-service-defaults` | Accidentally anonymous business endpoints ([ADR 0019](../adr/0019-authentication-baseline.md)) | +| Test namespaces end with `.Tests` | Test code drifting into production namespaces | + +## 3. Hexagonal view (ports and adapters) + +```mermaid +flowchart LR + subgraph Driving["Driving adapters"] + HTTP["HTTP (RimBank.Api)"] + MCPA["MCP (RimBank.Mcp)"] + SUBS["Subscriptions (future)"] + end + subgraph Hexagon["Core: RimBank.Party.PartyReferenceDataDirectory"] + CMDS["Commands / queries
(application API via IMessageBus)"] + DOMAIN["Aggregates, decisions,
projections, publication"] + WPORT{{"IPartyDirectory
write port"}} + RPORT{{"IPartyDirectoryEnquiry
read port"}} + end + subgraph Driven["Driven adapters"] + MW["MartenPartyDirectory"] + MR["MartenPartyDirectoryEnquiry"] + end + HTTP --> CMDS + MCPA --> CMDS + SUBS --> CMDS + CMDS --> DOMAIN + DOMAIN --> WPORT + DOMAIN --> RPORT + MW -. implements .-> WPORT + MR -. implements .-> RPORT +``` + +The core has **no package reference** to Wolverine or Marten: handlers are plain static classes with `Handle`/`HandleAsync` methods that return values (Wolverine's cascading convention); time comes from `TimeProvider`. + +## 4. Third-party package dependencies + +All versions are pinned centrally in `Directory.Packages.props`, with lock files and locked restore in CI; Dependabot proposes updates and NuGet audit fails on known vulnerabilities ([ADR 0013](../adr/0013-warning-and-package-governance.md)). + +| Package family | Used by | Purpose | Replaceability | +|---|---|---|---| +| ASP.NET Core (Minimal APIs, OpenAPI, JWT bearer) | Host, Api, Mcp, Problems | HTTP, auth, OpenAPI document | Platform | +| Scalar | Host (Development) | API reference UI | Trivial | +| `ModelContextProtocol.AspNetCore` | Mcp, Host | MCP server, Streamable HTTP | Adapter-local | +| WolverineFx (+ `.Marten`, `.Postgresql`) | Host, RimBank.Postgresql, adapters | Bus, outbox/inbox, retries, scheduled messages, sagas | Adapter-local: core is framework-free | +| Marten (+ Weasel, Npgsql, JasperFx) | RimBank.Postgresql, `.Postgresql` | Event store, documents, projections, async daemon | Adapter-local: ports in core | +| .NET Aspire (+ Keycloak hosting/auth previews, pinned as `AspireKeycloakVersion`) | AppHost, ServiceDefaults, Host | Orchestration, service defaults | Dev/test tooling | +| OpenTelemetry | ServiceDefaults | Traces, metrics, logs | Standard | +| xUnit v3, Shouldly, FsCheck, Alba, Testcontainers, ArchUnitNET, Microsoft.OpenApi, YamlDotNet | tests | Test platform ([ADR 0007](../adr/0007-test-platform.md)) | Test-only | + +## 5. Runtime dependencies + +| Dependency | Needed for | If unavailable | Health signal | +|---|---|---|---| +| PostgreSQL | Every command and query of a context | That context answers 500 `shared.unexpected`; other contexts with healthy stores keep working | `postgresql-` check, tag `ready` | +| Identity provider (JWKS) | Validating new tokens | Cached keys keep working until rotation; otherwise 401 | Startup / auth failures in telemetry | +| OTLP endpoint | Telemetry export | No functional impact | Exporter errors | +| RabbitMQ *(future)* | Inter-service events after extraction | Outbox buffers; delivery resumes | Wolverine transport health | + +## 6. Context dependency map *(target)* + +Upstream/downstream relationships in DDD context-mapping terms. Every arrow is **published language + conformist-free consumer** (the consumer translates in its own `.Subscriptions`: anticorruption layer). + +```mermaid +flowchart LR + PRDD["Party Reference Data Directory
(upstream: OHS + PL)"] + PD["Product Directory
(upstream: OHS + PL)"] + CA["Current Account
(downstream: ACL)"] + PK["Position Keeping"] + POI["Payment Order Initiation"] + FA["Financial Accounting"] + AR["Account Reconciliation"] + PLM["Party Lifecycle Management
(Stage 8+)"] + + PRDD -->|PL| CA + PD -->|PL| CA + CA -->|PL| PK + POI <-->|PL request / outcome events| CA + PK -->|PL| FA + PK -->|PL| AR + FA -->|PL| AR + PRDD -->|PL| PLM +``` + +OHS = open host service (BIAN API), PL = published language, ACL = anticorruption layer. There are **no** synchronous cross-context calls; adding one requires an explicit port and an ADR. diff --git a/docs/architecture/08-deployment-security-operations.md b/docs/architecture/08-deployment-security-operations.md new file mode 100644 index 0000000..07c72bc --- /dev/null +++ b/docs/architecture/08-deployment-security-operations.md @@ -0,0 +1,161 @@ +# 08. Deployment, security and operations + +## 1. Local / test topology (.NET Aspire) + +`dotnet run --project src/RimBank.AppHost` starts everything with Docker. + +```mermaid +flowchart TB + subgraph Aspire["RimBank.AppHost (Aspire)"] + DASH["Aspire dashboard
(OTLP receiver)"] + end + subgraph Containers["Docker"] + PG[("postgres
volume rimbank-postgres-data
database rimbank")] + KC["keycloak
volume rimbank-keycloak-data
realm import Realms/rimbank-realm.json"] + end + HOST["rimbank-host (project)
health check /health"] + + Aspire --> PG + Aspire --> KC + Aspire --> HOST + HOST -- "ConnectionStrings:PartyReferenceDataDirectory
login rimbank_party_reference_data_directory" --> PG + HOST -- "ConnectionStrings:Wolverine
login rimbank_wolverine" --> PG + HOST -- "ConnectionStrings:rimbank (admin, provisioning only)" --> PG + HOST -- "Mcp__AuthorizationServer = keycloak/realms/rimbank" --> KC + HOST -- OTLP --> DASH +``` + +- One connection string per context role; each password is an Aspire secret parameter (32 chars, persisted). +- Role and schema provisioning runs at startup only when `RimBank:Postgresql:ProvisionRoles` is on (default: Development only). In other environments, a DBA or migration pipeline creates roles. +- The host refuses to start if a context's connection string logs in as a different role than its own ([ADR 0016](../adr/0016-per-context-marten-stores.md)). + +## 2. Reference production deployment *(recommended, not yet shipped)* + +Container images and signing are roadmap 7.5. This is the target shape an adopter should implement. + +```mermaid +flowchart TB + subgraph Edge["Edge / DMZ"] + WAF["WAF + API gateway
TLS, rate limits (7.1)"] + end + subgraph App["Application tier (k8s / container apps)"] + H1["rimbank-host #1
non-root chiseled image"] + H2["rimbank-host #2"] + H3["rimbank-host #n"] + end + subgraph Data["Data tier (private network)"] + PGP[("PostgreSQL primary
HA, PITR backups")] + PGR[("Replica (DR)")] + MQ[["RabbitMQ (after first extraction)"]] + end + subgraph Platform["Platform services"] + IDP["OIDC provider"] + VAULT["Secret vault"] + OTEL["OTel collector → APM / SIEM"] + end + + WAF --> H1 & H2 & H3 + H1 & H2 & H3 --> PGP + PGP --> PGR + H1 & H2 & H3 -.-> MQ + H1 & H2 & H3 -.-> IDP + H1 & H2 & H3 -.-> VAULT + H1 & H2 & H3 -.-> OTEL +``` + +| Concern | Guidance | +|---|---| +| Scaling | Stateless hosts behind a load balancer; Wolverine `Balanced` durability distributes outbox/inbox work and async-daemon leadership across nodes | +| Readiness | Use the `ready`-tagged health checks (one per context store); liveness on `/health` | +| Database | One database, schema per context; contexts can later move to separate databases by changing only connection strings | +| Backups | PostgreSQL PITR. Event streams are the source of truth: views can be rebuilt, streams cannot | +| Secrets | From a vault; never in `appsettings` | +| Config | `Authentication:Authority` (HTTPS) outside Development; MCP authorization server URL | + +## 3. Security architecture + +### 3.1 Trust boundaries + +```mermaid +flowchart LR + subgraph Untrusted["Untrusted"] + C["Channels / agents"] + end + subgraph TB1["Boundary 1: edge (TLS, JWT)"] + AUTH["Authentication
fallback policy: authenticated"] + POL["Operation policy
scope per BIAN operation"] + end + subgraph TB2["Boundary 2: application"] + ADP["Adapters: validation,
idempotency, If-Match"] + CORE["Core: business rules"] + end + subgraph TB3["Boundary 3: data (per-context role)"] + S1[("party_reference_data_directory")] + S2[("product_directory (future)")] + end + C --> AUTH --> POL --> ADP --> CORE --> S1 + CORE -. "denied by DB grants" .-x S2 +``` + +### 3.2 Controls by layer + +| Layer | Control | Evidence | +|---|---|---| +| Identity | OIDC / JWT bearer, audience `rimbank-api`; Keycloak locally | [ADR 0019](../adr/0019-authentication-baseline.md), host tests with test-signed tokens | +| Default deny | Authorization fallback policy requires an authenticated caller; only health probes (and dev-only OpenAPI/Scalar) are anonymous | Architecture rule `allow-anonymous-only-in-service-defaults` | +| Authorisation | One policy per BIAN operation id; `:read` for queries, `:write` for commands; 403 before any other check | [ADR 0038](../adr/0038-per-operation-authorisation-policies.md), policy tests | +| MCP auth | OAuth 2.1 per the MCP authorization spec; 401 points to RFC 9728 protected-resource metadata; `scopes_supported` lists policy scopes; tools hidden from `tools/list` when the caller lacks the scope | [ADR 0022](../adr/0022-mcp-authorization-and-tool-errors.md), [ADR 0039](../adr/0039-party-mcp-tools.md) | +| Money-moving tools *(Stage 4)* | Dedicated scope, disabled by default, `destructive` annotation, idempotency key required | tech-stack §6 | +| Actor traceability | `sub` relayed as Wolverine user name → idempotency scope, Marten last-modified-by, trace `enduser.id` | `ActorRelay` | +| Input validation | Typed parsing at the edge (ids, ISO formats, lengths); unknown BIAN fields refused, not ignored, where RimBank does not record them | Conformance + API tests | +| Error hygiene | RFC 9457 only; no stack traces; `traceId` for support | [ADR 0015](../adr/0015-problem-details-mapping.md) | +| Data isolation | Per-context schema and login role with no grants elsewhere | Testcontainers isolation test | +| Integrity | Idempotency, optimistic concurrency, append-only events | [ADR 0018](../adr/0018-idempotency-keys-for-commands.md), [ADR 0027](../adr/0027-optimistic-concurrency-for-commands.md) | +| Supply chain | CodeQL, Dependabot, NuGet audit, locked restore, nuget.org-only source mapping; SBOM and signed releases planned (7.5) | [ADR 0005](../adr/0005-ci-and-supply-chain-policy.md), [ADR 0013](../adr/0013-warning-and-package-governance.md) | + +### 3.3 STRIDE summary (Party context) + +The full threat model is roadmap 7.8. Current position: + +| Threat | Example | Mitigation today | Residual / planned | +|---|---|---|---| +| **S**poofing | Forged token | JWT signature, issuer, audience validation | mTLS for service-to-service (with extraction) | +| **T**ampering | Replayed or reordered update | Idempotency key + `If-Match` stream version | — | +| **R**epudiation | "I never changed that address" | Append-only events with actor subject and trace id | Audit query API (7.3) | +| **I**nformation disclosure | PII in logs or events | No PII in integration events; scoped read access; DB role isolation | Log masking and field protection at rest (7.2) | +| **D**enial of service | Flooding Register | Idempotency-key locks bound duplicate work | Rate limiting, 429 Problem Details (7.1, 7.9) | +| **E**levation of privilege | Read-scope token calling Update, or agent calling a write tool | Per-operation policy on HTTP and MCP; tools hidden without scope | Fine-grained ABAC (e.g. per branch) not in scope yet | + +## 4. Observability + +| Signal | Source | Content | +|---|---|---| +| Traces | ASP.NET Core, Wolverine, Npgsql instrumentation via `RimBank.ServiceDefaults` | One trace per request through the bus to PostgreSQL; `traceId` also in every Problem Details | +| Metrics | Runtime, ASP.NET Core, Wolverine | Request rates, latencies, error rates; projection lag metrics planned (7.4) | +| Logs | Structured `ILogger` | Correlated by trace; PII masking planned (7.2) | +| Health | `/health` (liveness), `ready` per context store | Used by Aspire and orchestrators | + +### Operational runbooks (to be completed in Stage 7) + +| Situation | First response | +|---|---| +| `409 party.version-conflict` spikes | Expected under contention; check clients re-Retrieve before retrying | +| `409 shared.idempotency-key-in-use` | A duplicate is in flight; client should wait and retry with the same key | +| View out of date or corrupted | `RebuildViewAsync`; streams are untouched | +| Outbox backlog grows | Check consumers/queues; envelopes are durable and will be delivered once healthy | +| One context's DB down | Only that context fails; others keep serving ([mission principle 7](../../specs/mission.md#guiding-principles)) | + +## 5. CI/CD + +```mermaid +flowchart LR + PR[Pull request] --> B[Restore locked
Build warnings-as-errors] + B --> F[dotnet format verify] + F --> T[Tests: unit, property,
architecture, conformance,
Testcontainers, MCP parity] + T --> Q[CodeQL] + Q --> M[Merge to main] + M --> R["Release: SBOM, signed tag,
container image (7.5)"] + PR --> BOARD[Roadmap board sync] +``` + +Workflows: `.github/workflows/ci.yml`, `codeql.yml`, `roadmap-board.yml`. diff --git a/docs/architecture/09-quality-risks-roadmap.md b/docs/architecture/09-quality-risks-roadmap.md new file mode 100644 index 0000000..168b297 --- /dev/null +++ b/docs/architecture/09-quality-risks-roadmap.md @@ -0,0 +1,83 @@ +# 09. Quality attributes, risks and architecture roadmap + +## 1. Quality attribute scenarios + +Each scenario: *source → stimulus → response → measure*, and the evidence that it holds today. + +| # | Quality | Scenario | Response and measure | Evidence | +|---|---|---|---|---| +| Q1 | Integrity | A channel retries `Register` after a timeout | Exactly one party registered; the retry receives the identical acknowledgement | Idempotency tests (`RimBank.Postgresql.Tests`, Api tests) | +| Q2 | Integrity | Two operators update the same party's Reference concurrently | One succeeds; the other gets 409 `party.version-conflict`; no lost update | Concurrency tests ([ADR 0027](../adr/0027-optimistic-concurrency-for-commands.md)) | +| Q3 | Auditability | An auditor asks who changed a party's tax id and when | Every change is an event with actor, time and trace | Event streams; query API in 7.3 | +| Q4 | Security | A token with only the read scope calls an Update endpoint or tool | 403 `shared.forbidden` before any other check; tool not listed | Policy tests on HTTP and MCP | +| Q5 | Interoperability | BIAN publishes a route the code does not match | Conformance test fails in CI | `RimBank.Conformance.Tests`, Api conformance tests | +| Q6 | Interoperability | An AI agent and a web app perform the same update | Same JSON result and same Problem Details | MCP parity tests | +| Q7 | Evolvability | A developer references Current Account's core from Party | Build-time architecture test fails | `RimBank.Architecture.Tests` | +| Q8 | Evolvability | A consumer adds a field to the Party event contract | Snapshot test fails unless the change is backwards-compatible | Published-language schema snapshot | +| Q9 | Recoverability | A projection bug corrupts views | Fix and `RebuildViewAsync`; no data loss | Rebuild tests (0.10) | +| Q10 | Availability | Party's store is unreachable | Only Party operations fail (500 Problem Details); other contexts unaffected | Per-context store and daemon | +| Q11 | Correctness of money *(Stage 3+)* | Any sequence of debits/credits | Balance equals the sum of transactions | FsCheck property tests planned (3.3) | +| Q12 | Performance *(Stage 7)* | Load on deposit, withdrawal, transfer | Baseline to be defined | Roadmap 7.6 | + +## 2. Test pyramid as architecture fitness functions + +```mermaid +flowchart TB + A["Architecture tests (ArchUnitNET)
dependency, CQRS, naming, isolation rules"] + B["Conformance tests
routes, methods, bodies, statuses, channels vs BIAN YAML"] + C["MCP tests
tool catalogue = implemented operations, parity with HTTP"] + D["Integration tests (Testcontainers, Alba)
real PostgreSQL, real host, Problem Details"] + E["Unit and property tests
Given events / When command / Then events, Given events / Then view"] + A --- B --- C --- D --- E +``` + +## 3. Architecture risks + +| # | Risk | Likelihood | Impact | Mitigation | Owner phase | +|---|---|---|---|---|---| +| R1 | Personal data in immutable event streams vs right to erasure | High (any real deployment) | High (regulatory) | Field protection at rest / crypto-shredding ADR before production use | 7.2 | +| R2 | Single shared database is a blast radius for all contexts | Medium | High | Per-context roles and schemas now; separate databases by configuration later | 7.x / extraction | +| R3 | Long-lived streams (accounts, positions) slow to load | Medium (Stage 3+) | Medium | Snapshot strategy decided in ADR 3.1 | 3.1 | +| R4 | Projection lag misleads callers on async views | Medium | Medium | Inline views for read-your-write; `GetViewProgressAsync`; lag metrics | 7.4 | +| R5 | BIAN spec defects or ambiguities (e.g. wrong 200 schema) | High | Low | Recorded per case in ADRs and conformance catalogues ([ADR 0037](../adr/0037-bian-body-and-payload-conformance.md)) | Ongoing | +| R6 | Preview packages (Aspire Keycloak) change | Medium | Low | Pinned version, isolated to AppHost and auth wiring | Ongoing | +| R7 | Cross-aggregate references become stale (referenced party changes type later) | Low | Medium | Checked at write time; documented staleness; lifecycle events later | ADR 0034/0035 | +| R8 | AI agents performing harmful bulk actions | Medium | High | Scoped tools, read-only annotations, money tools off by default, per-client rate limits | 4.14, 7.9 | +| R9 | No rate limiting yet | High | Medium | Gateway rate limiting in deployments until 7.1 | 7.1 | + +## 4. Technical debt and deliberate deferrals + +| Item | Why deferred | Where recorded | +|---|---|---| +| BIAN CR operations Control, Request, Execute, Exchange | No business behaviour defined yet for the directory | [ADR 0024](../adr/0024-party-reference-data-directory-mapping.md) | +| Eight BQ AsyncAPI channels | No consumer needs them; avoid spreading PII | ADR 0024, [ADR 0036](../adr/0036-party-published-language.md) | +| List / search parties | Needs async cross-stream projection; no consumer yet | tech-stack §8.3 | +| "All associations of a party" query | Same | ADR 0033 | +| KYC status, screening results, risk rating | Belong to other BIAN domains (Party Lifecycle Management, Regulatory Compliance); RimBank stores the party's declarations only | [ADR 0032](../adr/0032-reference-legal-standing-and-documents.md) | +| Container images, SBOM, signed releases | Stage 7 | 7.5 | + +## 5. Readiness checklist before Stage 2 (Product Directory) + +| Area | Status | +|---|---| +| Slice pattern proven end to end (ADR → aggregate → command → Postgres → API → query → BQs → published language → conformance → policies → MCP) | ✅ Stage 1 | +| Conventions reusable by a second context (store, messaging, idempotency, Problem Details, policies, MCP filters) | ✅ in composition projects | +| Architecture tests ready for a second context (cross-context isolation inside `RimBank.Core`) | ✅ fixtures cover it | +| First consumer-side integration (`.Subscriptions`) | ⏳ Stage 4.1, needs an ADR | +| Async cross-stream projection in production code | ⏳ Stage 2.5 (product catalogue) | + +## 6. Architecture roadmap + +```mermaid +timeline + title RimBank architecture evolution + Stage 0 : Foundations : SharedKernel, Marten and Wolverine wiring, idempotency, auth, MCP, conformance harness + Stage 1 : Party Reference Data Directory : first full vertical slice, HTTP and MCP + Stage 2 : Product Directory : first async cross-stream view (catalogue) + Stage 3 : Position Keeping : authoritative balance, snapshots, property tests + Stage 4 : Current Account : first Subscriptions, local reference read models, money-moving MCP tools + Stage 5 : Payments : saga with request and outcome events, compensation + Stage 6 : Finance : double-entry GL, trial balance, reconciliation context + Stage 7 : Production hardening : rate limiting, PII protection, audit API, images, threat model, v0.1.0 + Stage 8+ : Growth : more BIAN domains, payment rails, Customer Position, first extracted service on RabbitMQ +``` diff --git a/docs/business/01-business-architecture.md b/docs/business/01-business-architecture.md new file mode 100644 index 0000000..493f884 --- /dev/null +++ b/docs/business/01-business-architecture.md @@ -0,0 +1,173 @@ +# 1. Business architecture + +> Audience: bank business analysts, product owners, enterprise and solution architects. +> Sources: the BIAN v14 ISO 20022 extended DDD specifications in [`doc-0/release14.0.0/`](../../doc-0/release14.0.0/), the [mission](../../specs/mission.md), the [roadmap](../../specs/roadmap.md) and the ADRs in [`docs/adr/`](../adr/). +> Definitions in quotation marks are quoted verbatim from the BIAN v14 OpenAPI files. Everything else is RimBank's reading and is marked as such. + +## 1.1 What RimBank is, in business terms + +RimBank is an open-source **core banking platform** whose building blocks are the **service domains** of the BIAN (Banking Industry Architecture Network) Service Landscape v14. Each BIAN service domain is one self-contained business capability, delivered as: + +- a **BIAN HTTP API** (the operations BIAN names: Register, Update, Exchange, Retrieve, …), +- a set of **MCP tools**, so that AI agents can use the same capability with the same rules and permissions, +- **business events** (BIAN's AsyncAPI channels) that tell the rest of the bank what happened. + +A bank can therefore adopt RimBank one capability at a time: each service domain owns its data, has its own contract and can sit next to the bank's existing systems. + +RimBank is **not a licensed bank** and provides no regulatory certification ([mission, non-goals](../../specs/mission.md#non-goals)). It records business facts correctly and auditably; the adopting institution remains accountable for its compliance. + +## 1.2 Where RimBank sits in the BIAN landscape + +BIAN organises a bank in three levels: + +| Level | Meaning | Example | +|---|---|---| +| **Business Area** | The broadest grouping of the bank's activities | *Reference Data* | +| **Business Domain** | A coherent set of capabilities within an area, with shared skills and knowledge | *Party* | +| **Service Domain** | The elementary, non-overlapping business capability. It owns one kind of **Control Record** and offers a fixed set of operations on it | *Party Reference Data Directory* | + +Inside a service domain: + +- the **Control Record (CR)** is the business record the capability manages over its whole life (for Party: the *Party Reference Data Directory Entry*); +- **Behavior Qualifiers (BQs)** are the parts of that record that have their own operations (for Party: *Demographics*, *Reference*, *Associations*, *BankRelations*); +- **operations** are the business actions on the record (Register, Update, Exchange, Retrieve, Control, …). + +RimBank maps them one to one: a service domain is a bounded context, a CR is an aggregate, a BQ is an entity or (by ADR) its own aggregate ([README](../../README.md#how-bian-maps-to-the-code), [ADR 0024](../adr/0024-party-reference-data-directory-mapping.md)). + +```mermaid +flowchart TB + subgraph BA["Business Area: Reference Data"] + subgraph BD["Business Domain: Party"] + SD["Service Domain: Party Reference Data Directory
IMPLEMENTED, Stage 1"] + SD2["Party Lifecycle Management
backlog, Stage 8+"] + SD3["Legal Entity Directory
not planned"] + SD4["Party Authentication
not planned"] + end + end + subgraph CR["Control Record: Party Reference Data Directory Entry"] + BQ1["BQ Demographics"] + BQ2["BQ Reference"] + BQ3["BQ Associations"] + BQ4["BQ BankRelations"] + end + SD --> CR +``` + +## 1.3 The retail-core capability chain + +The near-term scope of RimBank is one coherent retail core, end to end ([mission, scope](../../specs/mission.md#scope)): + +**Party → Product → Account → Ledger positions → Payments → General ledger.** + +```mermaid +flowchart LR + P["Party Reference Data Directory
WHO the bank deals with
Implemented"] + PD["Product Directory
WHAT the bank sells
Stage 2, planned"] + PK["Position Keeping
the VALUE log of every facility
Stage 3, planned"] + CA["Current Account
the PRODUCT FACILITY a customer holds
Stage 4, planned"] + POI["Payment Order Initiation
MOVING money on request
Stage 5, planned"] + FA["Financial Accounting
BOOKING the bank's ledger
Stage 6, planned"] + + P -- "party known and active" --> CA + PD -- "product launched, terms" --> CA + CA -- "opens and posts to" --> PK + POI -- "debit and credit requests" --> CA + PK -- "financial transactions captured" --> FA +``` + +Arrows are **business events**, not calls: each capability publishes what happened, and each consumer keeps its own minimal copy of what it needs ([tech-stack §8.4](../../specs/tech-stack.md#84-read-models-across-contexts-loose-coupling)). + +### Capability catalogue + +The business domain and namespace come from [tech-stack §3.2](../../specs/tech-stack.md#32-business-domain-mapping-initial). The BIAN definition is quoted verbatim from the v14 OpenAPI file of the service domain. + +| Service domain | Business domain | BIAN v14 definition (verbatim) | RimBank status | +|---|---|---|---| +| **Party Reference Data Directory** | Party | "This service domain maintains a range of party reference information covering aspects including general reference details, contacts and associations and demographic information" | **Implemented** (Stage 1, roadmap 1.1–1.21) | +| **Product Directory** | ProductManagement | "This service domain maintains a comprehensive directory of the bank's products and services. It can be referenced to obtain product details used to support activities including product selection, sales and marketing, on-boarding, servicing and product fulfillment." | Planned, Stage 2 | +| **Position Keeping** | AccountManagement | "This service domain maintains a log of monetary or value transactions and entitlements log posted to product facilities. Reconciled financial transactions are subsequently used for posting to the accounting systems." | Planned, Stage 3 | +| **Current Account** | LoansAndDeposits | "This service domain orchestrates a consumer checking/demand deposit account. The typical range of services and fees covers payments and deposits, standing orders, sweeps, liens, check and debit card access." | Planned, Stage 4 | +| **Payment Order Initiation** | Payments | "This service domain provides a customer payment service. It captures the payer and payee details and other key properties of the payment and initiates the orchestration of the transaction. It provides support for repeating/scheduled payments." | Planned, Stage 5 | +| **Financial Accounting** | Finance | "The Financial Accounting Service Domain takes in financial facts and based on these, creates accounting instructions that will update the general ledger and sub ledger accounts" | Planned, Stage 6 | + +Growth backlog (Stage 8+, order not decided): Savings Account, Term Deposit, Party Lifecycle Management (onboarding / KYC), Customer Agreement, Customer Product and Service Eligibility, Customer Offer, Sales Product Agreement, Consumer Loan, Loan, Fraud Evaluation, Regulatory Reporting, Payment Rail adapters, Customer Position ([roadmap, Stage 8+](../../specs/roadmap.md#stage-8-growth-backlog-order-to-be-decided-when-stage-7-is-done)). + +### Business value per capability + +| Capability | Business question it answers | Value to the bank | Typical consumers | +|---|---|---|---| +| Party Reference Data Directory | *Who is this party, how do we reach them, how are they related to other parties and to us?* | One authoritative, audited record per party; the reference every other capability relies on; lower onboarding and data-quality cost; regulatory inputs (identifiers, residency, PEP declaration) captured once | Onboarding/KYC, CRM, account opening, payments (payer/payee), regulatory and tax reporting, AI assistants | +| Product Directory | *What can we sell, on which terms?* | Faster product launch; one source for fees and interest terms; consistent pricing across channels | Current Account, sales channels, eligibility | +| Position Keeping | *What is the value position of this facility, transaction by transaction?* | Provable balances (balance = sum of transactions); the basis for funds checks and reconciliation | Current Account, Financial Accounting, reconciliation | +| Current Account | *What does this customer hold and what may they do with it?* | Deposits, withdrawals, holds, fees, interest and closure under explicit business rules | Payments, channels, customer position | +| Payment Order Initiation | *Move this amount from payer to payee, safely and once* | Idempotent, compensating transfers; status visible to the customer | Channels, standing orders, direct debits | +| Financial Accounting | *What is the bank's financial result?* | Double-entry GL derived from business facts; trial balance; reconciliation with positions | Finance, regulatory reporting, audit | + +## 1.4 Where each capability plugs into a bank's landscape + +Each capability is either the **system of record** for its data (the only place that may change it) or a **consumer** of other capabilities' events. RimBank never lets a consumer read a producer's database or views ([mission principle 7](../../specs/mission.md#guiding-principles)). + +| Capability | System of record for | Consumes (planned) | Publishes | +|---|---|---|---| +| Party Reference Data Directory | Party identity, reference data, demographics, party-to-party associations, party-to-bank relations | Nothing (it is the root of the chain) | `PartyReferenceDataDirectoryEntry/Created`, `…/Updated` (implemented) | +| Product Directory | Product definitions, lifecycle (launched / withdrawn), terms | — | Product events (2.6) | +| Position Keeping | Financial position logs and their transactions | Current Account's opening request (4.5) | `FinancialTransactionCaptured` (3.7) | +| Current Account | Current account facilities, deposits, payments, holds, charges, interest | Party and Product events (4.1), payment requests (5.4) | Payment and deposit outcomes (5.4) | +| Payment Order Initiation | Payment orders and their status | Current Account outcomes (5.3) | Debit / credit / reversal requests (5.3) | +| Financial Accounting | Chart of accounts, GL postings, trial balance | `FinancialTransactionCaptured` (6.2) | — | + +```mermaid +flowchart LR + subgraph CH["Channels, out of RimBank's scope"] + WEB["Web and mobile banking"] + BR["Branch and contact centre"] + AG["AI agents"] + end + subgraph RB["RimBank capabilities"] + API["BIAN HTTP APIs"] + MCP["MCP tools"] + CAPS["Service domains"] + EV["Business events"] + end + subgraph BANK["Bank's other systems"] + KYC["KYC and screening"] + CRM["CRM"] + DWH["Data warehouse and regulatory reporting"] + LEG["Legacy core"] + end + WEB --> API + BR --> API + AG --> MCP + API --> CAPS + MCP --> CAPS + CAPS --> EV + EV --> KYC + EV --> CRM + EV --> DWH + EV --> LEG +``` + +## 1.5 Adoption patterns + +These are RimBank's recommendations, not BIAN prescriptions. + +| Pattern | When it fits | How Party is used | Watch-outs | +|---|---|---|---| +| **Greenfield core** (digital bank, fintech, BaaS) | No legacy core to keep | Party is the first capability deployed; Product, Account and Payments follow the roadmap order | The chain is complete only after Stage 6; until then, money-moving capabilities come from elsewhere | +| **Strangler around a legacy core** | A bank modernises one capability at a time | Party Reference Data Directory becomes the new system of record for party data; the legacy core subscribes to `Created` / `Updated` events (or an adapter on the bank's side mirrors them) | During the transition, decide one direction of truth per field; do not dual-write | +| **Party master-data hub (MDM)** | Party data is duplicated across CRM, cards, lending and payments | The directory is the golden record; each system keeps its own minimal copy fed by events ([tech-stack §8.4](../../specs/tech-stack.md#84-read-models-across-contexts-loose-coupling)) | Today only the Control Record events are published; Behavior Qualifier channels are deferred ([ADR 0024](../adr/0024-party-reference-data-directory-mapping.md), [ADR 0036](../adr/0036-party-published-language.md)). Matching and de-duplication are not provided | +| **AI-agent channel** | Assistants for staff or customers | Agents call the `party_reference_data_directory_*` MCP tools with OAuth scopes; same rules, idempotency and audit as HTTP ([ADR 0039](../adr/0039-party-mcp-tools.md), [ADR 0040](../adr/0040-party-mcp-command-tools.md)) | No AI inside the core: models never make business decisions ([mission, non-goals](../../specs/mission.md#non-goals)). Grant `:write` scopes deliberately | + +## 1.6 Business principles that shape every capability + +| Principle | What it means for the business | Source | +|---|---|---| +| Business language first | APIs, events and code use BIAN and banking terms, so analysts can read them | [Mission 1](../../specs/mission.md#guiding-principles) | +| Event-sourced truth | Every change is a dated business event; the audit trail is the record itself | [Mission 4](../../specs/mission.md#guiding-principles) | +| Declarations, not assessments | Party records what the party declares; the bank's conclusions (KYC risk, screening hits) belong to other capabilities | [ADR 0032](../adr/0032-reference-legal-standing-and-documents.md) | +| Idempotency | A retried request never registers a party twice or moves money twice | [ADR 0018](../adr/0018-idempotency-keys-for-commands.md) | +| Optimistic concurrency | Two users editing the same party cannot silently overwrite each other (`If-Match`) | [ADR 0027](../adr/0027-optimistic-concurrency-for-commands.md) | +| Least privilege | Separate read and write permissions per capability (`party-reference-data-directory:read` / `:write`) | [ADR 0038](../adr/0038-per-operation-authorisation-policies.md) | +| One error language | Every refusal is an RFC 9457 Problem Details document with a stable code (for example `party.party-not-found`) | [ADR 0015](../adr/0015-problem-details-mapping.md) | + +Next: [the Party domain glossary](02-party-domain-glossary.md). diff --git a/docs/business/02-party-domain-glossary.md b/docs/business/02-party-domain-glossary.md new file mode 100644 index 0000000..612f1d8 --- /dev/null +++ b/docs/business/02-party-domain-glossary.md @@ -0,0 +1,406 @@ +# 2. Party domain glossary + +> The canonical dictionary of the **Party Reference Data Directory** service domain, as implemented at the end of Stage 1 (roadmap 1.1–1.21). +> Every member listed here exists in [`src/RimBank.Core/Party/PartyReferenceDataDirectory/`](../../src/RimBank.Core/Party/PartyReferenceDataDirectory/). BIAN names are the field names on the API; RimBank names are the names in the model. +> Text in quotation marks is quoted verbatim from the BIAN v14 OpenAPI file ([`PartyReferenceDataDirectory.yaml`](../../doc-0/release14.0.0/apis-iso20022_ext-ddd/oas3/yamls/PartyReferenceDataDirectory.yaml)). + +## 2.0 How to read this glossary + +**Status** of each element: + +| Status | Meaning | +|---|---| +| Implemented | Recorded, validated, returned by Retrieve, available on HTTP and MCP | +| Not recorded | A BIAN field RimBank deliberately does not keep. A request that sends it is refused with a `…-field-not-supported` error, or (where stated) ignored | +| Deferred | A BIAN operation or channel not built in Stage 1 | + +**Standards cited:** + +| Standard | Used for | +|---|---| +| ISO 20022 data types `Max16Text`, `Max35Text`, `Max70Text`, `Max140Text`, `Max256Text`, `Max350Text`, `Max2048Text` | Maximum lengths of text fields | +| ISO 17442 | Legal Entity Identifier (LEI), with check digits per ISO 7064 MOD 97-10 | +| ISO 3166-1 alpha-2 | Country codes (nationality, residence, address country) ([ADR 0030](../adr/0030-iso-3166-country-codes.md)) | +| ISO 8601 | Dates and date-times on the wire | +| ITU-T E.164 | International telephone numbers. **E.164 is an ITU-T recommendation, not an ISO standard.** | +| RFC 9457 | Problem Details, the format of every error | +| ISO 4217 | Currency codes (used by later capabilities; not by Party) | + +**PII classification** used below (RimBank's classification; protection at rest and in logs is roadmap 7.2): + +| Class | Meaning | +|---|---| +| None | Not personal data | +| Personal | Identifies or describes a natural person (or can, combined with other data) | +| Sensitive | Personal data whose misuse carries elevated risk (political exposure, identity documents) | +| Special category | GDPR Art. 9 data. **RimBank keeps none** (Demographics `EthnicityReligion` is not modelled, [ADR 0024](../adr/0024-party-reference-data-directory-mapping.md)) | + +**Partial update convention** (all Update operations): a field left out keeps its value, an empty value clears it, a given value replaces it. Every accepted Update is recorded as a business event, even when nothing changes. + +--- + +## 2.1 Party Reference Data Directory Entry (Control Record) + +**BIAN service domain definition:** "This service domain maintains a range of party reference information covering aspects including general reference details, contacts and associations and demographic information". + +**BIAN Register description:** "Register a customer entity in the catalog". + +**Business meaning.** One entry is the bank's single directory record for one **party**: a person or an organisation the bank deals with, whether a customer, a prospect, an employee, a branch or a counterparty. The entry is created once (Register), lives for as long as the bank knows the party, and holds three singleton parts (Demographics, Reference, BankRelations). Associations to other parties are separate records owned by the entry. + +| Member (BIAN name) | Business definition | Type / format / standard | Rules | Business use | PII | +|---|---|---|---|---|---| +| Entry id (`partyreferencedatadirectoryid`) | The directory's identifier of the party, issued at Register | UUID version 7 (time-ordered) | Issued by RimBank, never chosen by the caller. Any other value is `shared.invalid-identifier` | The key every other capability uses to name the party ("PartyReference" in their events) | None (pseudonymous key) | +| `PartyType` | Whether the party is a natural person or an organisation. BIAN: "`Person` - Human entity, as distinguished from a corporate entity (which is sometimes referred to as an 'artificial person'). ISO20022"; "`Organisation` - Organised structure that is set up for a particular purpose. For example, a business, government body, department, charity, or financial institution. ISO20022" | Enum `Person` \| `Organisation` | Required at Register. May change on Update, except that an organisation holding corporate references cannot become a `Person` ([ADR 0034](../adr/0034-reference-corporate-and-officer-references.md)) | Drives which rules apply (officer is a person, branch is an organisation); product eligibility; KYC regime (individual vs entity) | None | +| `DirectoryEntryDate` with type `OpenDate` | When the party was entered in the directory | ISO 8601 date-time, UTC | Set by RimBank to the time of Register; caller's value ignored | Data lineage, retention periods | None | +| `DirectoryEntryDate` with type `RefreshDate` | When the entry was last confirmed or updated | ISO 8601 date-time, UTC | Set by RimBank at every accepted Update of the entry; absent until the first one | Periodic review of party data (data freshness KPIs) | None | +| `DemographicsId` (`demographicsid`) | Identifier of the entry's Demographics part | UUID v7 | Issued at Register; one per entry | Addresses the Demographics operations | None | +| `PartyReferenceId` (`referenceid`) | Identifier of the entry's Reference part | UUID v7 | Issued at Register; one per entry | Addresses the Reference operations | None | +| `BankRelationsId` (`bankrelationsid`) | Identifier of the entry's BankRelations part | UUID v7 | Issued at Register; one per entry | Addresses the BankRelations operations | None | +| Version (`ETag`) | The number of business events recorded on the entry | Integer, sent as a strong HTTP `ETag`; MCP `version` | Required as `If-Match` / `expectedVersion` on every change ([ADR 0027](../adr/0027-optimistic-concurrency-for-commands.md)) | Prevents lost updates when two users edit one party | None | +| `PartyReference` (on Register / Update) | BIAN's embedded party details | — | **Accepted and ignored**: details are recorded through Demographics and Reference ([ADR 0024](../adr/0024-party-reference-data-directory-mapping.md)) | — | — | + +**Operations** ([ADR 0024](../adr/0024-party-reference-data-directory-mapping.md)): + +| BIAN operation | Kind | HTTP | MCP tool | Status | +|---|---|---|---|---| +| Register | Command | `POST /PartyReferenceDataDirectory/Register` | `party_reference_data_directory_register` | Implemented | +| Update | Command | `PUT /PartyReferenceDataDirectory/{id}/Update` | `party_reference_data_directory_update` | Implemented | +| Retrieve | Query | `GET /PartyReferenceDataDirectory/{id}/Retrieve` | `party_reference_data_directory_retrieve` | Implemented | +| Control, Request, Execute, Exchange | Command | — | — | Deferred | + +### Enumeration: `PartyType` + +| Value | Meaning | +|---|---| +| `Person` | A natural person (an individual customer, an employee acting as relationship manager, a company officer) | +| `Organisation` | Any legal or organisational structure (a company, a charity, a government body, a bank branch or business unit) | + +--- + +## 2.2 Demographics (Behavior Qualifier) + +**BIAN description (Update):** "Update details about a customer's demographic entry". + +**Business meaning.** Socio-economic and personal background the bank uses to understand and serve the party: classification, employment, education and servicing constraints. Unlike Reference, Demographics carries a **verification status**: the bank can verify or reject the details through the Exchange operation ([ADR 0028](../adr/0028-demographics-exchange-as-verification.md)). + +| Member (BIAN name) | Business definition (BIAN, verbatim where quoted) | Type / format / standard | Rules | Business use | PII | +|---|---|---|---|---|---| +| `Socio-EconomicClassification` | "A bank defined classification of the socio-economic rating and prospect" | Text, ISO 20022 Max140Text | Trimmed; empty clears | Segmentation, product suitability, pricing | Personal | +| `Employment.PartyReference` | "Reference to the customer's employer (company name)" | Text, Max140Text | Free text, **not** checked against the directory | Affordability, income source (CDD), corporate-employee offers | Personal | +| `Employment.InvolvementReference` | The party's involvement with the employer (for example a job title) | Text, Max140Text | Free text; a given `Employment` replaces the whole employment | Same as above | Personal | +| `EmploymentHistory` | "Details of the customer's employment history (e.g. employer, dates, job position, salary)" | Text, Max2048Text | Trimmed; empty clears | Credit assessment input, source of wealth | Personal | +| `EducationHistory` | "Customer's education (e.g. academic institutions attended, duration, qualifications and certifications)" | Text, Max2048Text | Trimmed; empty clears | Segmentation (for example student offers) | Personal | +| `ServicingConstraints` | "Description of any known constraints on servicing the customer (sight, hearing, religious considerations)" | Text, Max2048Text | Trimmed; empty clears | Accessibility and fair treatment of vulnerable customers; channel routing | Personal (may reveal health; handle with care) | +| `VerificationStatus` | RimBank extension: whether the bank has checked the current details | Enum, see below | Starts `Unverified`; set by Exchange; reset to `Unverified` by an Update that changes the details | Data-quality controls, KYC evidence | None | +| `VerificationDate` | RimBank extension: when the details were last verified or rejected | ISO 8601 date-time, UTC | Set by Exchange; cleared when details change | Review cycles | None | +| `EthnicityReligion` | "Where needed to ensure the bank's handling of the relationship follows legal and regulatory requirements" | — | **Not modelled**: special-category data; ignored in requests, never returned | — | Special category | +| `ExchangeActionType` | RimBank extension field on Exchange: what the bank concludes | Enum `Verify` \| `Reject` | Required on Exchange; case-sensitive | Records the bank's verification decision | None | + +**Operations:** `Demographics/Update` (command), `Demographics/Exchange` (command: verify or reject), `Demographics/Retrieve` (query). MCP: `…_update_demographics`, `…_exchange_demographics`, `…_retrieve_demographics`. All implemented. + +### Enumeration: `DemographicsVerificationStatus` + +| Value | Meaning | +|---|---| +| `Unverified` | The details have not been checked since they last changed (the initial state) | +| `Verified` | The bank has confirmed the current details | +| `Rejected` | The bank has found the current details not acceptable; they can be verified later | + +### Enumeration: `ExchangeActionType` + +| Value | Effect | +|---|---| +| `Verify` | Sets `VerificationStatus` to `Verified` and stamps `VerificationDate` | +| `Reject` | Sets `VerificationStatus` to `Rejected` and stamps `VerificationDate` | + +```mermaid +stateDiagram-v2 + [*] --> Unverified : Register + Unverified --> Verified : Exchange Verify + Unverified --> Rejected : Exchange Reject + Verified --> Rejected : Exchange Reject + Rejected --> Verified : Exchange Verify + Verified --> Unverified : Update that changes details + Rejected --> Unverified : Update that changes details +``` + +An Exchange on a party with no recorded demographic details is refused (`party.demographics-not-recorded`). + +--- + +## 2.3 Reference (Behavior Qualifier) + +**BIAN description (Update):** "Update details about a reference entry for the customer". + +**Business meaning.** The party's **identity and reference data**: identifiers, names, birth date, nationality and residency, addresses, contact points, legal standing, a government-issued document and, for organisations, references to the corporate customer, legal entity and a company officer. It is **what the party declares**, never the bank's assessment ([ADR 0032](../adr/0032-reference-legal-standing-and-documents.md)). Reference has no verification status. Fields were added in stages ([ADR 0029](../adr/0029-reference-fields-in-stages.md)). + +### 2.3.1 Identifiers (roadmap 1.10) + +| Member (BIAN path) | Business definition | Type / format / standard | Rules | Business use | PII | +|---|---|---|---|---|---| +| `GovernmentIssuedIdentityReference.TaxIdentificationNumber` | The number a tax authority assigned to the party (TIN) | Text, ISO 20022 Max35Text | Trimmed, not blank; country format **not** checked | FATCA / CRS reporting, tax withholding | Personal | +| `GovernmentIssuedIdentityReference.NationalRegistrationNumber` | The number a national registration authority assigned (for example a national identity number or company registration number) | Text, Max35Text | Same as TIN | Identification and verification (ID&V), de-duplication | Personal | +| `PartyLegalEntityReference.Identification` | The party's Legal Entity Identifier | ISO 17442 LEI: 20 characters, 18 alphanumerics + 2 check digits, upper-cased | Check digits must satisfy ISO 7064 MOD 97-10 | Entity identification for regulatory reporting (EMIR, MiFIR, AnaCredit-style), counterparty reference | None (identifies an entity) | + +### 2.3.2 Names, birth date and residency (roadmap 1.18) + +| Member (BIAN path) | Business definition | Type / format / standard | Rules | Business use | PII | +|---|---|---|---|---|---| +| `PartyFullLegalName` | The full legal name of the party | Text, Max140Text | Trimmed, not blank | Contracts, screening input, statements | Personal | +| `PartyNameSalutation` | The salutation the party prefers (for example `Ms`, `Dr`) | Text, Max35Text | Free text | Correspondence | Personal | +| `DateofBirth` | The party's date of birth | ISO 8601 calendar date (`YYYY-MM-DD`) | Between 1900-01-01 and today (UTC); a date-time is read as the date written, without time-zone conversion | Age-based eligibility (minors, seniors), ID&V | Personal | +| `Nationality.Code` | The party's nationality | ISO 3166-1 alpha-2 code | Officially assigned codes only | Sanctions/PEP context, CRS, FATCA (US persons) | Personal | +| `PartyCountryOfResidence.Code` | The country where the party lives (for an organisation: where its affairs are directed) | ISO 3166-1 alpha-2 | Same as nationality | Tax residency (CRS), cross-border rules | Personal | +| `ResidencyStatus.StatusDescription` | Whether the party is resident | Enum `Resident` \| `NonResident` | Any case on input | Exchange-control and tax treatment | Personal | +| `ResidencyStatus.StatusDateTime` | When the residency status was assigned | ISO 8601 date-time | Only with a status | Evidence for tax residency changes | Personal | + +### 2.3.3 Addresses and contact points (roadmap 1.19, [ADR 0031](../adr/0031-reference-contact-points-and-addresses.md)) + +The three addresses share one structure, the ISO 20022 **postal address**: + +| Address (BIAN field) | Business meaning | +|---|---| +| `ResidentialAddress` | Where a person lives | +| `PartyAddress` | The party's general (correspondence) address | +| `CorporateAddress` | An organisation's registered or business address | + +| Postal address part | Format | Rule | +|---|---|---| +| `Department`, `SubDepartment` | Max70Text | Optional | +| `StreetName`, `StreetBuildingIdentification`, `BuildingName` | Max35Text | Optional | +| `Floor`, `PostOfficeBox`, `PostCodeIdentification` | Max16Text | Optional | +| `TownName` | Max35Text | **Required** | +| `Country.Code` | ISO 3166-1 alpha-2 | **Required** | + +| Contact point (BIAN path) | Business definition (BIAN) | Format / standard | Rules | Business use | PII | +|---|---|---|---|---|---| +| `eMailAddress.EmailAddress` | "The given email address" | Max256Text, `local@domain.tld` | One `@`, no spaces or display name; kept as written | Servicing notifications, statements | Personal | +| `CellPhoneNumber.MobileNumber` | "Any given phone contact numbers" | ITU-T E.164 (`+` country code, 7–15 digits) | Spaces, hyphens and dots removed; stored normalised | SMS one-time passwords, servicing calls | Personal | +| `SocialNetworkContacts.URLAddress` | "Any given social network identifiers" | Absolute `https` URL, Max2048Text | Kept as written | Relationship context (for example corporate profile) | Personal | + +Other `PostalAddress` and `ContactPoint` parts (address type, validity period, …) are not recorded. + +### 2.3.4 Legal standing, political exposure and documents (roadmap 1.20, [ADR 0032](../adr/0032-reference-legal-standing-and-documents.md)) + +| Member (BIAN path) | Business definition | Type / format | Rules | Business use | PII | +|---|---|---|---|---|---| +| `PartyLegalStructure` | The legal form the party declares | Enum, see below | Read without regard to case, spaces or hyphens; answered in BIAN spelling | Entity KYC, product eligibility (for example business accounts), beneficial-ownership questionnaires | None | +| `PoliticalExposureType` | Whether the party declares itself a politically exposed person (PEP) | Enum, see below | — | Input to PEP screening and enhanced due diligence | Sensitive | +| `PoliticalExposureDescriptionRecord` | BIAN: "Detail of the customer's political exposure" | Max350Text | Only with a `Foreign` or `Domestic` exposure | EDD file | Sensitive | +| `CustomerSinceDate` | Since when the party has been a customer, as declared or migrated | ISO 8601 date | 1900-01-01 to today; not before `DateofBirth`; **not** compared with `OpenDate` (relationships can predate the directory, for example after migration) | Tenure-based offers, loyalty, risk scoring | None | +| `GovernmentIssuedDocumentDetails.PartyDocumentType` | BIAN: "Details about and extracted from government issued documents (e.g. driving license/passport details)" — the document category | Enum, see below | **Required** with a document | ID&V | Sensitive | +| `….DocumentReference.DocumentIdentification.IdentifierValue` | The document number (for example a passport number) | Max35Text | **Required**; no country format check | ID&V | Sensitive | +| `….DocumentReference.DocumentName` | The document's name (for example `Passport`) | Max140Text | Optional, free text | ID&V | None | +| `….DocumentValidityPeriod.FromDateTime` / `.ToDateTime` | The document's validity | ISO 8601 dates | `To` not before `From`. An expired document **can** be recorded: acting on expiry is a KYC concern | Periodic refresh triggers (in a KYC capability) | Personal | +| `DocumentDirectoryEntryInstanceReference.DocumentDirectoryEntryIdentification` | BIAN: "The document reference for associated documents" — where the scanned evidence is kept | Max35Text, opaque | Never resolved: BIAN Document Directory is not a RimBank capability | Link to the bank's document management system | None | + +One government-issued document per party, because BIAN gives a single object. + +### 2.3.5 Corporate and officer references (roadmap 1.21, [ADR 0034](../adr/0034-reference-corporate-and-officer-references.md)) + +Recorded **only on an organisation's** entry. Each reference is another registered entry of the directory, checked when it is set. + +| Member (BIAN path) | Business definition (BIAN) | Type | Rules | Business use | PII | +|---|---|---|---|---|---| +| `CorporateCustomerReference.PartyReference` | "Reference to the corporate entity (Company for company customers)" | Entry id | Registered, not the party itself, of type `Organisation` | Linking an organisational unit or account-holding entity to the corporate customer | None | +| `CorporateCustomerLegalEntityReference.PartyReference` | "The legal entity reference (for company customers)" | Entry id | Same; may be the same entry as the corporate customer | Contracting legal entity for agreements | None | +| `CompanyOfficerReference.PartyReference` | "Reference to one or more identified company officers for a corporate customer" | Entry id | Registered, not the party itself, of type `Person`. One officer (BIAN gives one object) | Authorised signatory / director for entity KYC | None (key) | +| `CompanyOfficerRole` | The role of the officer (for example `Director`) | Max35Text | Only with an officer | Mandate and signing authority context | None | + +### 2.3.6 Reference enumerations + +**`ResidencyStatusCode`** + +| Value | Meaning | +|---|---| +| `Resident` | Resident for the purposes of the bank's jurisdiction | +| `NonResident` | Not resident | + +**`PartyLegalStructure`** (11 BIAN values plus `CharitableIncorporatedOrganisation`, which BIAN's description lists; the vocabulary is UK-oriented) + +| Value (BIAN spelling) | Meaning | +|---|---| +| `Individual` | A natural person acting in a private capacity | +| `SoleTrader` (BIAN `Sole(SoleTrader)`) | An individual trading in their own name, with unlimited liability | +| `GeneralPartnership` | Partners share management and unlimited liability | +| `LimitedPartnership` | At least one general partner with unlimited liability and limited partners | +| `ScottishLimitedPartnership` | A limited partnership registered in Scotland, with its own legal personality | +| `LimitedLiabilityPartnership` | A partnership whose members have limited liability | +| `PrivateLimitedCompany` | A company limited by shares, not offered to the public | +| `PublicLimitedCompany` | A company limited by shares that may offer them to the public | +| `CommunityInterestCompany` | A limited company run for community benefit | +| `CharitableIncorporatedOrganisation` | An incorporated charity | +| `Charity` | A charitable organisation (unincorporated or other form) | +| `Co-Operative` | An organisation owned and run by its members | + +**`PoliticalExposureType`** (BIAN `Politicalexposuretypevalues`) + +| Value (stored / BIAN) | Meaning | +|---|---| +| `Foreign` / `Politicalexposureforeign` | Declares a prominent public function in a foreign country (or a close link to such a person) | +| `Domestic` / `Politicalexposuredomestic` | Declares a prominent public function in the bank's own country | +| `NoExposure` / `Nopoliticalexposure` | Declares no political exposure | + +**`PartyDocumentType`** (BIAN `Partydocumenttypevalues`) + +| Value | Meaning | +|---|---| +| `PersonalDocument` | A document that identifies a person (passport, identity card, driving licence) | +| `WorkDocument` | A document issued in a work context (work permit, employment document) | +| `CertificationDocument` | A certificate (for example certificate of incorporation, certified copy) | + +**Operations:** `Reference/Update` (command), `Reference/Retrieve` (query). MCP: `…_update_reference`, `…_retrieve_reference`. Implemented. BIAN Reference parts not listed above are refused with `party.reference-field-not-supported`. + +--- + +## 2.4 Associations (Behavior Qualifier, its own aggregate) + +**BIAN description (Update):** "Update details about an association entry for the customer". +**BIAN `AssociateType`:** "The type of association with the party (e.g. familial or corporate, includes household associations, for corporations allowed users/buyers)". +**BIAN `AssociateReference`:** "Associated individuals of interest". + +**Business meaning.** A **directed, dated relationship between two parties of the directory**: "the owner *type* the associate". A party can have many associations, and each one has its own identifier, version and lifecycle, which is why RimBank models Associations as a separate aggregate ([ADR 0024](../adr/0024-party-reference-data-directory-mapping.md), [ADR 0033](../adr/0033-party-associations.md)). + +| Member (BIAN path) | Business definition | Type / format | Rules | Business use | PII | +|---|---|---|---|---|---| +| Association id (`associationsid`) | Identifier of the association | UUID v7 | Issued at Register | Addresses Update / Retrieve | None | +| Owner | The entry the association belongs to (the path's `partyreferencedatadirectoryid`) | Entry id | Must be registered; never changes | — | None | +| `AssociateReference.PartyReference` | The other party | Entry id | Required at Register; registered; not the owner; **never changes** (a different associate is a new association) | Household, group and mandate structures | None (key) | +| `AssociateType` | The kind of relationship | Enum `PartyRelationshipType` | Required at Register; cannot be cleared | Drives KYC (who must be identified), mandates, consolidated exposure | None | +| `AssociationValidFromToDate.FromDateTime` / `.ToDateTime` | When the relationship starts / ends | ISO 8601 date-time, stored UTC | At least one bound; `From` ≤ `To`. Ending an association = recording `ToDateTime`; no "active" flag is derived | Historic structure ("who was director on date X") | None | + +**Not recorded** (refused with `party.association-field-not-supported`): `EmployeeReference`, `AssociateObligationorDependencyDescription`, `PreferredBeneficiary`, `ProxyRepresentativePowerofAttorneyReference`, `ProductInstanceReference`, `ProductInstanseInvolvementReference` (BIAN spelling), `AssociateReference.InvolvementReference`. A power of attorney is recordable as the type `PartyIsThePowerOfAttorneyForParty`. + +### Enumeration: `PartyRelationshipType` + +Read as "**owner** *relationship* **associate**". The meanings are RimBank's reading of the BIAN names. + +| Value | Meaning | Typical use | +|---|---|---| +| `PartyIsParentOfParty` | The owner is the parent of the associate (corporate parent, or parent in a family) | Group structures, consolidated exposure | +| `PartyIsSubsidiaryOfParty` | The owner is a subsidiary of the associate | Group structures | +| `PartyIsCertifiedByParty` | The owner is certified by the associate (for example by an auditor or certification body) | Entity due diligence | +| `PartyIsMarriedToParty` | The owner is married to the associate | Household view, joint products | +| `PartyActsOnBehalfOfParty` | The owner acts on behalf of the associate (agent, authorised user) | Mandates, delegated access | +| `PartyIsContactPointForParty` | The owner is the contact person for the associate | Corporate servicing | +| `PartyIsTrustedByParty` | The owner is a trusted contact of the associate | Vulnerable-customer protection | +| `PartyIsThePowerOfAttorneyForParty` | The owner holds a power of attorney for the associate | Legal representation | +| `PartyReceivesBenefitsFromAParty` | The owner benefits from the associate (beneficiary) | Beneficial ownership, trusts, insurance | + +**Operations:** `Associations/Register`, `Associations/Update` (commands), `Associations/Retrieve` (query). MCP: `…_register_associations`, `…_update_associations`, `…_retrieve_associations`. Implemented. + +--- + +## 2.5 BankRelations (Behavior Qualifier) + +**BIAN `BankRelationType`:** "The type of relationship (e.g. relationship manager)". +**BIAN `BusinessUnitEmployeeReference`:** "Reference to the associated employee or unit". + +**Business meaning.** The party's **servicing relationship with the bank itself**: who in the bank (an employee) or which unit (a branch or business unit) looks after the party, since when, until when, and in which lifecycle state. One relationship per entry in Stage 1 ([ADR 0035](../adr/0035-party-bank-relations.md)). The employee or unit is itself a registered party of the directory. + +| Member (BIAN path) | Business definition | Type / format | Rules | Business use | PII | +|---|---|---|---|---|---| +| `BankRelationType` | The role the bank plays for the party | Enum, see below | Required whenever an employee/unit is recorded | Servicing model, portfolio assignment | None | +| `BusinessUnitEmployeeReference.PartyReference` | The employee or unit | Entry id | Registered; not the party itself; a `Person` for employee roles, an `Organisation` for unit roles | Routing, RM dashboards, commissions | None (key) | +| `BankRelationReference.RelationshipStartDate.DateTimeContent` | When the relationship started | ISO 8601, stored UTC | — | Portfolio history | None | +| `BankRelationReference.RelationshipEndDate.DateTimeContent` | When the relationship ended | ISO 8601, stored UTC | Not before the start | Hand-over tracking | None | +| `BankRelationReference.RelationshipLifecycleStatus.StatusDescription` | The relationship's state | Enum, see below | Declared, not derived from dates (`Ended` does not require an end date) | Servicing workflow | None | + +### Enumeration: `BankRelationType` + +| Value | Referenced party type | Meaning | +|---|---|---| +| `RelationshipManager` | Person | The employee who owns the commercial relationship | +| `AccountOfficer` | Person | The employee responsible for the party's accounts / credit file | +| `ServicingBranch` | Organisation | The branch that services the party | +| `ServicingBusinessUnit` | Organisation | The business unit (for example private banking, SME desk) that services the party | + +### Enumeration: `BankRelationLifecycleStatus` + +| Value | Meaning | +|---|---| +| `Active` | The relationship is in force | +| `Suspended` | Temporarily not in force (for example during a hand-over or an investigation) | +| `Ended` | The relationship is over | + +**Operations:** `BankRelations/Update` (command), `BankRelations/Retrieve` (query). MCP: `…_update_bank_relations`, `…_retrieve_bank_relations`. Implemented. + +--- + +## 2.6 Business events + +### 2.6.1 Domain events (internal history of the record) + +These are the facts recorded in the party's event stream. They form the audit trail and are never shared with other capabilities directly. + +| Event | Recorded when | Carries | +|---|---|---| +| `PartyRegistered` | A party is registered | Entry id, party type, open date, the three BQ ids | +| `PartyReferenceDataDirectoryEntryUpdated` | The entry is updated | Entry id, party type, refresh date | +| `DemographicsUpdated` | Demographics are updated | The full resulting details and their verification status/date | +| `DemographicsExchanged` | Demographics are verified or rejected | Verification status, verification date | +| `PartyReferenceUpdated` | Reference is updated | The full resulting Reference | +| `BankRelationsUpdated` | BankRelations are updated | The full resulting BankRelations | +| `PartyAssociationRegistered` | An association is registered | Association id, owner, associate, type, validity period | +| `PartyAssociationUpdated` | An association is updated | Association id, type, validity period | + +### 2.6.2 Integration events (published to the rest of the bank) + +Published through a transactional outbox, versioned, and pinned by a schema contract test ([ADR 0036](../adr/0036-party-published-language.md)). + +| Integration event | BIAN channel | Message identity | Published on | +|---|---|---|---| +| `PartyReferenceDataDirectoryEntryCreated` | `PartyReferenceDataDirectoryEntry/Created` | `party-reference-data-directory-entry.created.v1` | Register | +| `PartyReferenceDataDirectoryEntryUpdated` | `PartyReferenceDataDirectoryEntry/Updated` | `party-reference-data-directory-entry.updated.v1` | Entry Update | + +Both carry the same payload: + +| Member | Meaning | +|---|---| +| `EventId` | Unique id of the event (UUID v7); consumers use it to de-duplicate | +| `OccurredAt` | When the business fact happened | +| `PartyReferenceDataDirectoryEntryId` | The party's directory id | +| `Version` | The entry's version after the fact (lets consumers ignore out-of-order deliveries) | +| `PartyType` | `Person` or `Organisation` | +| `DirectoryEntryDateType` | `OpenDate` (Created) or `RefreshDate` (Updated) | +| `DirectoryEntryDate` | The date named by the type | + +**Deferred:** the eight BIAN Behavior Qualifier channels (`Demographics/Created`, `Reference/Updated`, …). Consumers that need demographic or reference data cannot yet receive it by event. + +--- + +## 2.7 Business error codes + +Every refusal is an RFC 9457 Problem Details document with `type` `urn:rimbank:problem:party:` and the same content on HTTP and MCP. + +| Code | HTTP | Business meaning | +|---|---|---| +| `party.party-type-required` | 400 | Register without a party type | +| `party.party-type-invalid` | 400 | A party type other than Person or Organisation | +| `party.party-already-registered` | 409 | The entry already exists (only a replayed decision meets it) | +| `party.party-not-found` | 404 | No party with this id in the directory | +| `party.behavior-qualifier-not-found` | 404 | The Demographics, Reference or BankRelations id does not belong to this party | +| `party.version-conflict` | 409 | Someone changed the party since you read it; retrieve and retry | +| `party.demographics-invalid` | 400 | A demographic detail is too long | +| `party.demographics-not-recorded` | 422 | Nothing to verify or reject: record demographics first | +| `party.exchange-action-type-required` | 400 | Exchange without `Verify` / `Reject` | +| `party.exchange-action-type-invalid` | 400 | Exchange action other than `Verify` / `Reject` | +| `party.reference-invalid` | 400 | A reference value is malformed or breaks a cross-field rule (birth date in the future, customer-since before birth, description without exposure, officer role without officer, …) | +| `party.reference-field-not-supported` | 400 | A BIAN Reference field RimBank does not record; nothing was updated | +| `party.corporate-references-need-organisation` | 422 | Corporate / officer references only on an organisation; or an organisation with them cannot become a person | +| `party.self-reference` | 422 | A reference names the party itself | +| `party.referenced-party-not-registered` | 422 | A referenced party is not in the directory: register it first | +| `party.referenced-party-type-mismatch` | 422 | The referenced party has the wrong type (officer must be a person, branch an organisation, …) | +| `party.association-invalid` | 400 | Missing or malformed associate, type or validity period | +| `party.association-field-not-supported` | 400 | A BIAN Associations field RimBank does not record | +| `party.association-not-found` | 404 | No such association for this party | +| `party.association-already-registered` | 409 | The association already exists (replay only) | +| `party.self-association` | 422 | A party cannot be associated with itself | +| `party.associate-not-registered` | 422 | The associate is not in the directory | +| `party.associate-cannot-change` | 422 | An association's associate never changes: register a new association | +| `party.bank-relations-invalid` | 400 | Malformed value, employee/unit without a type, or end before start | +| `party.bank-relations-field-not-supported` | 400 | A BIAN BankRelations part RimBank does not record | + +Shared codes that every capability uses include `shared.unauthenticated` (401), `shared.forbidden` (403), `shared.invalid-identifier` (400), `shared.idempotency-key-missing` / `-invalid` (400), `shared.idempotency-key-reused` / `-in-use` (409), `shared.if-match-required` (428), `shared.if-match-invalid` (400), `shared.invalid-country` (400) and `shared.unexpected` (500). + +Next: [entity relationships](03-entity-relationships.md). diff --git a/docs/business/03-entity-relationships.md b/docs/business/03-entity-relationships.md new file mode 100644 index 0000000..845ab2f --- /dev/null +++ b/docs/business/03-entity-relationships.md @@ -0,0 +1,212 @@ +# 3. Entity relationships + +> How the parts of the Party Reference Data Directory relate to each other and how parties relate to other parties and to the bank. Member-level definitions are in the [glossary](02-party-domain-glossary.md). The physical/technical data model is in the architecture documentation ([`docs/architecture/`](../architecture/)). + +## 3.1 Business entity-relationship model + +```mermaid +erDiagram + PARTY_ENTRY ||--|| DEMOGRAPHICS : "has exactly one" + PARTY_ENTRY ||--|| REFERENCE : "has exactly one" + PARTY_ENTRY ||--|| BANK_RELATIONS : "has exactly one" + PARTY_ENTRY ||--o{ PARTY_ASSOCIATION : "owns" + PARTY_ASSOCIATION }o--|| PARTY_ENTRY : "names as associate" + REFERENCE }o--o| PARTY_ENTRY : "corporate customer" + REFERENCE }o--o| PARTY_ENTRY : "legal entity" + REFERENCE }o--o| PARTY_ENTRY : "company officer" + BANK_RELATIONS }o--o| PARTY_ENTRY : "employee or unit" + REFERENCE ||--o| GOVERNMENT_DOCUMENT : "declares" + REFERENCE ||--o{ POSTAL_ADDRESS : "residential, party, corporate" + DEMOGRAPHICS ||--o| EMPLOYMENT : "free text" + + PARTY_ENTRY { + uuid EntryId PK + enum PartyType "Person or Organisation" + datetime OpenDate + datetime RefreshDate + long Version + } + DEMOGRAPHICS { + uuid DemographicsId PK + text SocioEconomicClassification + text EmploymentHistory + text EducationHistory + text ServicingConstraints + enum VerificationStatus + datetime VerificationDate + } + EMPLOYMENT { + text PartyReference "employer name, not an entry" + text InvolvementReference + } + REFERENCE { + uuid PartyReferenceId PK + text TaxIdentificationNumber + text NationalRegistrationNumber + text LegalEntityIdentifier "ISO 17442" + text PartyFullLegalName + text PartyNameSalutation + date DateofBirth + text Nationality "ISO 3166-1 alpha-2" + text CountryOfResidence "ISO 3166-1 alpha-2" + enum ResidencyStatus + text EmailAddress + text MobileNumber "E.164" + text SocialNetwork + enum PartyLegalStructure + enum PoliticalExposureType + text PoliticalExposureDescription + date CustomerSinceDate + uuid CorporateCustomer FK + uuid LegalEntity FK + uuid CompanyOfficer FK + text CompanyOfficerRole + text DocumentDirectoryEntry "opaque" + } + POSTAL_ADDRESS { + text StreetName + text BuildingName + text PostCodeIdentification + text TownName "required" + text Country "required, ISO 3166-1" + } + GOVERNMENT_DOCUMENT { + enum PartyDocumentType + text DocumentNumber + text DocumentName + date ValidFrom + date ValidTo + } + BANK_RELATIONS { + uuid BankRelationsId PK + enum BankRelationType + uuid BusinessUnitEmployee FK + datetime StartDate + datetime EndDate + enum LifecycleStatus + } + PARTY_ASSOCIATION { + uuid AssociationId PK + uuid OwnerId FK + uuid AssociateId FK + enum AssociateType + datetime ValidFrom + datetime ValidTo + long Version + } +``` + +Notes on the model: + +- **Demographics, Reference and BankRelations** are *parts of the entry* (one each, created empty at Register, same version and history as the entry). They have their own ids only because BIAN routes address them by id. +- **Party Association** is a *record of its own*: many per party, own id, own version, own history ([ADR 0024](../adr/0024-party-reference-data-directory-mapping.md)). It is owned by one entry and names another. +- **Employment** in Demographics is **free text**: the employer is *not* checked against the directory. Use an association or a corporate reference when the employer must be a known party. +- **Document directory entry** is an opaque reference to the bank's document store; it is never resolved by RimBank. + +## 3.2 Cardinalities and constraining rules + +| Relationship | Cardinality | Rules (checked when recorded) | Source | +|---|---|---|---| +| Entry → Demographics / Reference / BankRelations | 1 : 1 each | A BQ id that is not the entry's is `party.behavior-qualifier-not-found` | [ADR 0024](../adr/0024-party-reference-data-directory-mapping.md) | +| Entry (owner) → Association | 1 : 0..n | Owner must be registered (`party.party-not-found`). Same owner, associate and type may be registered twice (for example two periods) | [ADR 0033](../adr/0033-party-associations.md) | +| Association → associate entry | n : 1 | Registered (`party.associate-not-registered`); not the owner (`party.self-association`); never changes (`party.associate-cannot-change`). Any party type | [ADR 0033](../adr/0033-party-associations.md) | +| Reference → corporate customer | 0..1 | Only on an `Organisation` entry; target registered, not self, an `Organisation` | [ADR 0034](../adr/0034-reference-corporate-and-officer-references.md) | +| Reference → legal entity | 0..1 | Same; may be the same entry as the corporate customer | [ADR 0034](../adr/0034-reference-corporate-and-officer-references.md) | +| Reference → company officer | 0..1 | Only on an `Organisation`; target a `Person`; a `CompanyOfficerRole` needs an officer | [ADR 0034](../adr/0034-reference-corporate-and-officer-references.md) | +| BankRelations → employee or unit | 0..1 | Needs a `BankRelationType`; `RelationshipManager` / `AccountOfficer` → a `Person`; `ServicingBranch` / `ServicingBusinessUnit` → an `Organisation`; not self; registered | [ADR 0035](../adr/0035-party-bank-relations.md) | +| Entry `PartyType` change | — | An organisation with corporate references cannot become a `Person` until they are cleared | [ADR 0034](../adr/0034-reference-corporate-and-officer-references.md) | + +**Accepted drift.** Rules about a *referenced* party are checked when the reference is recorded. If that party later changes its own type, references pointing at it are not re-checked (that would require a cross-record index on the write side). Consumers that need the current type read the referenced entry. + +**No derived "active" flags.** Validity periods and relationship dates are never compared with today by RimBank. A consumer compares them with its own business date. + +## 3.3 Three kinds of links — which one to use + +| | **Association** | **Corporate / officer reference** (in Reference) | **Bank relation** (BankRelations) | +|---|---|---|---| +| Connects | Party ↔ party | Organisation → its corporate customer, legal entity, one officer | Party ↔ the bank (an employee or unit, itself a party) | +| How many | Many per party | One of each per organisation | One per party (Stage 1) | +| Own lifecycle | Yes: own id, version, Register / Update / Retrieve | No: part of the entry's Reference | No: part of the entry | +| Dated | Validity period (from / to) | No | Start date, end date, lifecycle status | +| Typical question | "Who is married to whom? Who holds power of attorney? Who is the parent company?" | "Which legal entity contracts for this corporate customer? Who is its director?" | "Who is this customer's relationship manager? Which branch services them?" | +| BIAN source | Associations BQ | Reference BQ (`CorporateCustomerReference`, `CorporateCustomerLegalEntityReference`, `CompanyOfficerReference`) | BankRelations BQ | + +Rule of thumb: if the link has its own history or there may be several, use an **Association**. If it is the organisation's single statutory reference data, use **Reference**. If the other side is the bank's own staff or unit, use **BankRelations**. + +## 3.4 Worked example A — corporate group + +*Acme Holding plc* owns *Acme Retail Ltd*. Acme Retail is the bank's corporate customer; Jane Doe is its director. + +```mermaid +flowchart LR + H["Acme Holding plc
Organisation
PublicLimitedCompany
LEI 5299...ISO 17442"] + R["Acme Retail Ltd
Organisation
PrivateLimitedCompany
LEI and TIN"] + J["Jane Doe
Person"] + H -- "Association: PartyIsParentOfParty" --> R + R -- "Association: PartyIsSubsidiaryOfParty" --> H + R -.->|"Reference: CorporateCustomerLegalEntityReference"| H + R -.->|"Reference: CompanyOfficerReference, role Director"| J + J -- "Association: PartyActsOnBehalfOfParty" --> R +``` + +How it is recorded: + +1. Register three entries (two `Organisation`, one `Person`). +2. On Acme Retail's Reference: LEI, TIN, `PartyLegalStructure = PrivateLimitedCompany`, `CompanyOfficerReference = Jane`, `CompanyOfficerRole = Director`, and the legal entity reference to the holding if the holding is the contracting entity. +3. Associations: the holding registers `PartyIsParentOfParty` → Retail; Retail may register the inverse `PartyIsSubsidiaryOfParty` → Holding. **Inverses are not automatic**: each direction is its own association owned by its own party ([ADR 0033](../adr/0033-party-associations.md)). +4. Jane can also be linked by association (`PartyActsOnBehalfOfParty`) when the mandate needs a validity period or there are several signatories (the Reference holds only one officer). + +Business value: entity KYC (who controls, who signs), group exposure, LEI-based regulatory reporting. + +## 3.5 Worked example B — household and representation + +```mermaid +flowchart LR + A["Alex Martin
Person"] + S["Sam Martin
Person"] + L["Lee Martin
Person, minor"] + N["Notary Lawyer
Person"] + T["Martin Family Trust
Organisation"] + A -- "PartyIsMarriedToParty, from 2015-06-01" --> S + N -- "PartyIsThePowerOfAttorneyForParty, 2026-01-01 to 2027-01-01" --> A + L -- "PartyReceivesBenefitsFromAParty" --> T + S -- "PartyIsTrustedByParty" --> A +``` + +- Marriage and power of attorney are dated associations; the power of attorney **ends** when its `ToDateTime` passes, without an update. +- The beneficiary link supports beneficial-ownership and trust due diligence. +- "Sam is a trusted contact of Alex" supports vulnerable-customer procedures. +- RimBank does **not** record the obligations, the preferred beneficiary details or the proxy object of BIAN Associations (refused, [ADR 0033](../adr/0033-party-associations.md)). + +## 3.6 Worked example C — servicing model + +The bank's own staff and units are parties of the directory too. + +```mermaid +flowchart LR + C1["Customer: Acme Retail Ltd
Organisation"] + C2["Customer: Alex Martin
Person"] + RM["Maria Lopez
Person, bank employee"] + BR["Paris Opera Branch
Organisation, bank unit"] + C1 -- "BankRelations: RelationshipManager, Active, since 2024-03-01" --> RM + C2 -- "BankRelations: ServicingBranch, Active" --> BR +``` + +- A `RelationshipManager` or `AccountOfficer` must reference a `Person`; a `ServicingBranch` or `ServicingBusinessUnit` an `Organisation`. A mismatch is `party.referenced-party-type-mismatch`. +- A relationship that changes hands is updated (new reference, new start date) — the previous one stays in the party's event history. +- A party with **both** a relationship manager and a servicing branch needs more than one bank relation; that is a planned change of model (its own aggregate, a future ADR, [ADR 0035](../adr/0035-party-bank-relations.md)). + +## 3.7 How Party relates to the planned capabilities + +```mermaid +erDiagram + PARTY_ENTRY ||--o{ CURRENT_ACCOUNT_FACILITY : "holds, Stage 4" + PRODUCT_DIRECTORY_ENTRY ||--o{ CURRENT_ACCOUNT_FACILITY : "instance of, Stage 4" + CURRENT_ACCOUNT_FACILITY ||--|| FINANCIAL_POSITION_LOG : "posts to, Stage 3-4" + PARTY_ENTRY ||--o{ PAYMENT_ORDER : "payer or payee, Stage 5" + FINANCIAL_POSITION_LOG ||--o{ GL_POSTING : "derives, Stage 6" +``` + +These links cross capability boundaries, so they are **not** foreign keys: each consumer keeps its own minimal copy of "party is known and active", fed by Party's events, and never reads Party's data store ([tech-stack §8.4](../../specs/tech-stack.md#84-read-models-across-contexts-loose-coupling)). + +Next: [value streams](04-value-streams.md). diff --git a/docs/business/04-value-streams.md b/docs/business/04-value-streams.md new file mode 100644 index 0000000..7292e24 --- /dev/null +++ b/docs/business/04-value-streams.md @@ -0,0 +1,230 @@ +# 4. Business value streams + +> **Status of this document.** The value streams below are **RimBank's business modelling**. They follow value-stream practice (a trigger, a sequence of value-adding stages, a stakeholder who receives the value) and BIAN's business-scenario thinking (a scenario is a sequence of service-domain interactions), but BIAN v14 does not publish them in this form. The service domains named at each stage are BIAN v14 service domains; the RimBank status comes from the [roadmap](../../specs/roadmap.md). + +## 4.0 Overview + +| # | Value stream | Triggering stakeholder | Value delivered | RimBank coverage today | +|---|---|---|---|---| +| VS1 | **Onboard a party** (Know your customer) | Prospect, corporate client, bank staff | A known, identified party the bank may do business with | Party data capture implemented; KYC assessment not in scope (backlog) | +| VS2 | **Open a product** (current account) | Customer | A usable account on agreed terms | Party implemented; Product (Stage 2), Position Keeping (3), Current Account (4) planned | +| VS3 | **Move money** (internal transfer) | Customer, corporate treasurer | Funds moved once, correctly, with status | Planned (Stages 4–5) | +| VS4 | **Record and report** (books, reconciliation) | Finance, regulator, auditor | A ledger that reconciles with customer positions | Planned (Stage 6) | +| VS5 | **Service the relationship** | Customer, relationship manager, AI assistant | Up-to-date data, the right person servicing the customer | Party BankRelations, Associations, Update and MCP implemented | + +Legend used in the stage diagrams: **green** = implemented in RimBank, **amber** = planned on the roadmap, **grey** = outside RimBank (another system or a backlog capability). + +--- + +## VS1 — Onboard a party (Know your customer) + +| | | +|---|---| +| **Trigger** | A prospect applies (branch, web, partner, agent), or the bank needs to record a counterparty, employee or unit | +| **Stakeholders** | Prospect / customer; onboarding officer; compliance (KYC/AML); relationship manager | +| **Value proposition** | "We know who you are, we hold your data once, correctly, and you never have to repeat it." | +| **End state** | A registered party with identity, contact, legal-standing and relationship data, ready for KYC decisioning and product opening | + +```mermaid +flowchart LR + S1["1 Capture identity
Register entry"] + S2["2 Record reference data
identifiers, names, residency,
addresses, contacts"] + S3["3 Record declarations
legal structure, PEP, documents"] + S4["4 Link parties
associations, officers,
corporate references"] + S5["5 Verify demographics
Exchange Verify or Reject"] + S6["6 Assess KYC risk
screening, risk rating"] + S7["7 Assign servicing
relationship manager, branch"] + S1 --> S2 --> S3 --> S4 --> S5 --> S6 --> S7 + classDef done fill:#d4edda,stroke:#2e7d32,color:#000 + classDef out fill:#e0e0e0,stroke:#616161,color:#000 + class S1,S2,S3,S4,S5,S7 done + class S6 out +``` + +| Stage | BIAN service domain(s) | RimBank operation / status | Party data used | +|---|---|---|---| +| 1 Capture identity | Party Reference Data Directory | `Register` — implemented | `PartyType` | +| 2 Record reference data | Party Reference Data Directory | `Reference/Update` — implemented | TIN, national registration number, LEI, full legal name, date of birth, nationality, residence, addresses, email, mobile | +| 3 Record declarations | Party Reference Data Directory (+ Document Directory, not in RimBank) | `Reference/Update` — implemented | Legal structure, political exposure, customer-since, government-issued document, document directory reference | +| 4 Link parties | Party Reference Data Directory | `Associations/Register`, `Reference/Update` (officer) — implemented | Associations, corporate / officer references | +| 5 Verify demographics | Party Reference Data Directory | `Demographics/Update`, `Demographics/Exchange` — implemented | Demographics and verification status | +| 6 Assess KYC risk | Party Lifecycle Management, Regulatory Compliance, Fraud Evaluation | **Not in RimBank** (Party Lifecycle Management is Stage 8+ backlog) | Consumes declared values via Party events — never reads the directory ([ADR 0032](../adr/0032-reference-legal-standing-and-documents.md)) | +| 7 Assign servicing | Party Reference Data Directory | `BankRelations/Update` — implemented | Bank relation type, employee or unit | + +BIAN definition of the downstream KYC capability (verbatim): *Party Lifecycle Management* — "This service domain tracks the state of a party relationship with the bank from the initial checks made during the establishment of a new party connection and subsequently maintained as necessary over the duration of the relationship. The checks and the maintenance requirements will vary by party type and jurisdiction." + +**Value measures (KPIs):** time from application to registered party; first-time-right rate (share of Reference updates refused with `party.reference-invalid`); share of parties with verified demographics; duplicate-party rate; share of organisations with LEI and officer recorded. + +--- + +## VS2 — Open a product (current account) + +| | | +|---|---| +| **Trigger** | A registered customer asks for a current account | +| **Stakeholders** | Customer; sales/servicing channel; product management | +| **Value proposition** | "Open an account in minutes, on the published terms, with a correct balance from day one." | +| **End state** | An initiated current-account facility with its own position log | + +```mermaid +flowchart LR + S1["1 Confirm party known
Party events"] + S2["2 Select launched product
Product catalogue"] + S3["3 Check eligibility"] + S4["4 Initiate facility"] + S5["5 Open position log"] + S6["6 Fund account
first deposit"] + S1 --> S2 --> S3 --> S4 --> S5 --> S6 + classDef done fill:#d4edda,stroke:#2e7d32,color:#000 + classDef plan fill:#fff3cd,stroke:#b8860b,color:#000 + classDef out fill:#e0e0e0,stroke:#616161,color:#000 + class S1 done + class S2,S4,S5,S6 plan + class S3 out +``` + +| Stage | BIAN service domain(s) | RimBank status | How Party enables it | +|---|---|---|---| +| 1 Confirm party known | Party Reference Data Directory → Current Account | Party events implemented; Current Account's subscription is roadmap 4.1–4.2 | Current Account keeps its own "known party" copy from `Created` / `Updated` events — no call to Party | +| 2 Select launched product | Product Directory | Roadmap 2.4–2.5 | — | +| 3 Check eligibility | Customer Product and Service Eligibility | Backlog (Stage 8+) | Party type, date of birth, residency are typical inputs (requires the deferred BQ channels) | +| 4 Initiate facility | Current Account | Roadmap 4.3–4.4 (requires a known party and a launched product) | Party id is the facility holder | +| 5 Open position log | Position Keeping | Roadmap 4.5 | — | +| 6 Fund account | Current Account, Position Keeping | Roadmap 4.6 | — | + +**Value measures:** time to open; share of openings refused for unknown party or product; abandoned applications. + +--- + +## VS3 — Move money (internal book transfer) + +| | | +|---|---| +| **Trigger** | A customer orders a transfer between two accounts held at the bank | +| **Stakeholders** | Payer, payee, operations, compliance | +| **Value proposition** | "Your money moves exactly once, is never lost, and you can see where it is." | +| **End state** | Debit and credit executed (or the debit reversed), payment order status final | + +```mermaid +flowchart LR + S1["1 Capture payment order
payer, payee, amount"] + S2["2 Screen
sanctions port"] + S3["3 Debit payer
funds check"] + S4["4 Credit payee"] + S5["5 Compensate if credit fails"] + S6["6 Confirm status"] + S1 --> S2 --> S3 --> S4 --> S6 + S4 --> S5 --> S6 + classDef plan fill:#fff3cd,stroke:#b8860b,color:#000 + class S1,S2,S3,S4,S5,S6 plan +``` + +| Stage | BIAN service domain(s) | RimBank status | +|---|---|---| +| 1 Capture order | Payment Order Initiation | Roadmap 5.1 | +| 2 Screen | Payment Order Initiation (Compliance BQ) | Roadmap 5.2 (allow-list stub; no real screening engine) | +| 3 Debit payer | Current Account, Position Keeping | Roadmap 4.7, 5.3–5.4 (funds checked on authoritative write-side balance) | +| 4 Credit payee | Current Account, Position Keeping | Roadmap 5.4 | +| 5 Compensate | Payment Order Initiation, Current Account | Roadmap 5.3 (reversal request) | +| 6 Confirm | Payment Order Initiation (Confirmation BQ) | Roadmap 5.5 | + +**How Party enables it:** the payer and payee are parties; their names and identifiers are the inputs a sanctions-screening port needs; a party's lifecycle (for example an ended relationship) can block execution in later phases. + +**Value measures:** straight-through-processing rate; duplicate executions (target: zero, enforced by idempotency); compensations per thousand transfers; time to final status. + +--- + +## VS4 — Record and report + +| | | +|---|---| +| **Trigger** | Every captured financial transaction; period end | +| **Stakeholders** | Finance, risk, regulators, auditors | +| **Value proposition** | "The books are complete, balanced and reconcile with every customer position." | +| **End state** | Posted GL, trial balance, reconciled positions, regulatory reports | + +```mermaid +flowchart LR + S1["1 Capture transaction
Position Keeping"] + S2["2 Post double entry
Financial Accounting"] + S3["3 Trial balance"] + S4["4 Reconcile positions vs GL"] + S5["5 Report
regulatory, tax"] + S1 --> S2 --> S3 --> S4 --> S5 + classDef plan fill:#fff3cd,stroke:#b8860b,color:#000 + classDef out fill:#e0e0e0,stroke:#616161,color:#000 + class S1,S2,S3,S4 plan + class S5 out +``` + +| Stage | BIAN service domain(s) | RimBank status | +|---|---|---| +| 1 Capture | Position Keeping | Roadmap 3.3, 3.7 | +| 2 Post | Financial Accounting | Roadmap 6.2 (property test: debits = credits) | +| 3 Trial balance | Financial Accounting | Roadmap 6.3 | +| 4 Reconcile | Account Reconciliation | Roadmap 6.4 (own context, compared at matching event checkpoints) | +| 5 Report | Regulatory Reporting, Customer Tax Handling | Backlog (Stage 8+) | + +**How Party enables it:** regulatory and tax reports need the party's identifiers (LEI, TIN), residency and nationality (for example CRS / FATCA), and legal structure. Those come from the Reference BQ — today held in Party; their publication by event is a deferred BIAN channel. + +**Value measures:** unreconciled breaks; time to close; report resubmissions. + +--- + +## VS5 — Service the relationship + +| | | +|---|---| +| **Trigger** | A customer contacts the bank, data changes, or a periodic review falls due | +| **Stakeholders** | Customer, relationship manager, contact centre, AI assistant | +| **Value proposition** | "The person (or agent) serving you knows who you are, who you are linked to, and who looks after you." | +| **End state** | Current party data, correct servicing assignment, change history kept | + +```mermaid +flowchart LR + S1["1 Identify party
Retrieve"] + S2["2 Review data
Reference, Demographics"] + S3["3 Update changes
with If-Match"] + S4["4 Re-verify
Exchange"] + S5["5 Maintain links
associations, bank relations"] + S6["6 Notify consumers
Updated event"] + S1 --> S2 --> S3 --> S4 --> S5 --> S6 + classDef done fill:#d4edda,stroke:#2e7d32,color:#000 + class S1,S2,S3,S4,S5,S6 done +``` + +| Stage | RimBank operation (HTTP / MCP) | Status | +|---|---|---| +| 1 Identify | `Retrieve` / `party_reference_data_directory_retrieve` | Implemented | +| 2 Review | `Reference/Retrieve`, `Demographics/Retrieve` | Implemented | +| 3 Update | `Reference/Update`, `Demographics/Update`, entry `Update` (refresh date) | Implemented — stale data is refused with `party.version-conflict` | +| 4 Re-verify | `Demographics/Exchange` | Implemented — any change resets the status to `Unverified` | +| 5 Maintain links | `Associations/Register` / `Update`, `BankRelations/Update` | Implemented | +| 6 Notify | `PartyReferenceDataDirectoryEntry/Updated` | Implemented for the entry; BQ channels deferred | + +BIAN definition of the related CRM capability (verbatim): *Customer Relationship Management* — "This service domain develops and executes a customer plan to maintain and build a customer relationship. Activities include ongoing customer contact, tracking internal and external events and activity of interest and relevance, product and service matching and sales, processing ad-hoc queries, trouble shooting and issue resolution including the initial phases of troubled account recovery". It is not on RimBank's roadmap; a CRM system consumes Party's events. + +**Value measures:** data freshness (age of `RefreshDate`); share of parties with an `Active` bank relation; lost-update incidents (target: zero); share of interactions handled by an AI assistant without hand-off. + +--- + +## 4.6 Value stream × service domain matrix + +● = the service domain contributes a stage; status in brackets: **I** implemented, **P** planned (roadmap stage), **B** backlog, **X** outside RimBank. + +| Service domain | VS1 Onboard | VS2 Open product | VS3 Move money | VS4 Record & report | VS5 Service | +|---|---|---|---|---|---| +| Party Reference Data Directory (I) | ● | ● | ● (payer/payee) | ● (identifiers) | ● | +| Party Lifecycle Management (B) | ● | | | | ● | +| Product Directory (P2) | | ● | | | | +| Customer Product and Service Eligibility (B) | | ● | | | | +| Position Keeping (P3) | | ● | ● | ● | | +| Current Account (P4) | | ● | ● | | ● | +| Payment Order Initiation (P5) | | | ● | | | +| Financial Accounting (P6) | | | | ● | | +| Account Reconciliation (P6.4) | | | | ● | | +| Regulatory Reporting (B) | ● | | | ● | | +| Customer Relationship Management (X) | | | | | ● | +| Document Directory (X) | ● | | | | | + +Next: [banking use cases](05-banking-use-cases.md). diff --git a/docs/business/05-banking-use-cases.md b/docs/business/05-banking-use-cases.md new file mode 100644 index 0000000..35620ad --- /dev/null +++ b/docs/business/05-banking-use-cases.md @@ -0,0 +1,184 @@ +# 5. Banking use cases and integration guide + +> Concrete ways a bank uses the Party Reference Data Directory as implemented today, what each one delivers, and what stays out of scope. Field definitions are in the [glossary](02-party-domain-glossary.md); relationships in [entity relationships](03-entity-relationships.md). + +## 5.0 The scope line + +The directory **records what the party declares and what the bank has decided to keep as reference**. It does **not** assess, screen, score or decide ([ADR 0032](../adr/0032-reference-legal-standing-and-documents.md), [mission, non-goals](../../specs/mission.md#non-goals)): + +| RimBank Party does | RimBank Party does not | +|---|---| +| Hold identifiers, names, residency, addresses, contacts, legal structure, PEP declaration, one government-issued document reference | Screen against sanctions or PEP lists | +| Validate format and consistency (LEI check digits, ISO 3166 codes, E.164, dates, cross-field rules) | Validate a TIN or national number against a country's registry format | +| Keep a full, dated history of every change (event-sourced) | Compute a KYC risk rating, a refresh schedule or an "expired document" alert | +| Record the bank's verification of demographics (Verify / Reject) | Store scanned documents (it stores an opaque reference to the bank's document directory) | +| Link parties to parties and to bank staff and units | De-duplicate or match parties | +| Publish `Created` / `Updated` events of the entry | Publish the Behavior Qualifier events (deferred) | + +All operations below are available on HTTP and as MCP tools with identical rules and errors. Every command requires an `Idempotency-Key`; every change of an existing record requires `If-Match` (MCP: `expectedVersion`). + +--- + +## UC1 — KYC / CDD onboarding data capture + +| | | +|---|---| +| **Actor** | Onboarding officer, digital onboarding journey | +| **Goal** | Capture everything customer due diligence needs, once, in a structured, auditable record | +| **Operations** | `Register` → `Reference/Update` → `Demographics/Update` → `Demographics/Exchange` | +| **MCP tools** | `party_reference_data_directory_register`, `…_update_reference`, `…_update_demographics`, `…_exchange_demographics` | +| **Data** | `PartyType`; TIN, national registration number, LEI; full legal name, date of birth; nationality, residence, residency status; residential / party / corporate address; email, mobile; legal structure; document details; employment, socio-economic classification | +| **Business value** | Structured, validated CDD file; every value traceable to who recorded it and when; no duplicate entry on a retried submission (idempotency) | +| **Out of scope / deferred** | Identity verification against external sources; document image storage; the KYC decision (Party Lifecycle Management, Stage 8+ backlog) | + +```mermaid +sequenceDiagram + actor O as Onboarding officer + participant P as Party Reference Data Directory + participant K as KYC system, bank-owned + O->>P: Register PartyType Person + P-->>O: Entry id, BQ ids, version 1 + P-)K: PartyReferenceDataDirectoryEntry/Created + O->>P: Reference/Update identifiers, names, residency, addresses + P-->>O: Reference, version 2 + O->>P: Demographics/Update employment, classification + P-->>O: Demographics Unverified, version 3 + O->>P: Demographics/Exchange Verify + P-->>O: Demographics Verified, version 4 +``` + +## UC2 — PEP declaration as screening input + +| | | +|---|---| +| **Actor** | Customer (self-declaration), compliance analyst | +| **Goal** | Record whether the party declares a political exposure and its description | +| **Operations** | `Reference/Update` (`PoliticalExposureType`, `PoliticalExposureDescriptionRecord`) | +| **Data** | `Foreign`, `Domestic` or `NoExposure`; description up to 350 characters, only with an exposure | +| **Business value** | A clean, consistent declaration (no description without an exposure; no contradictory leftovers after partial updates) feeding enhanced due diligence | +| **Out of scope** | Screening against PEP lists, the bank's own PEP conclusion, EDD workflow — these belong to a KYC capability that would consume the declaration by event | + +## UC3 — Beneficial ownership and corporate structures + +| | | +|---|---| +| **Actor** | Corporate onboarding team, credit risk | +| **Goal** | Model who owns, controls and represents an organisation | +| **Operations** | `Register` (each person and organisation), `Reference/Update` (corporate customer, legal entity, company officer and role), `Associations/Register` / `Update` | +| **Data** | LEI, legal structure; `CorporateCustomerReference`, `CorporateCustomerLegalEntityReference`, `CompanyOfficerReference` (a `Person`), `CompanyOfficerRole`; associations `PartyIsParentOfParty`, `PartyIsSubsidiaryOfParty`, `PartyActsOnBehalfOfParty`, `PartyReceivesBenefitsFromAParty` with validity periods | +| **Business value** | Group and control structures built from **registered** parties only (no dangling names), with type rules enforced (an officer is a person, a corporate customer an organisation) and history preserved | +| **Out of scope** | Ownership percentages and control thresholds (not BIAN Party fields RimBank records); the `AssociateObligationorDependencyDescription` and `PreferredBeneficiary` objects (refused, [ADR 0033](../adr/0033-party-associations.md)); automatic inverse associations | + +## UC4 — FATCA / CRS tax-residency inputs + +| | | +|---|---| +| **Actor** | Tax operations, regulatory reporting | +| **Goal** | Hold the indicators that drive automatic exchange of information | +| **Operations** | `Reference/Update`, `Reference/Retrieve` | +| **Data** | `TaxIdentificationNumber` (Max35Text), `Nationality.Code` and `PartyCountryOfResidence.Code` (ISO 3166-1 alpha-2), `ResidencyStatus` with its date, addresses with country | +| **Business value** | Valid country codes everywhere; one TIN per party; dated residency status for evidence | +| **Out of scope / limits** | One TIN only (no TIN per jurisdiction); no self-certification form; no reportable-account determination; reporting itself (Customer Tax Handling / Regulatory Reporting, backlog). The Reference BQ channel that would carry these values by event is deferred | + +## UC5 — Relationship management and servicing assignment + +| | | +|---|---| +| **Actor** | Head of branch, private banking desk | +| **Goal** | Assign a relationship manager, account officer, servicing branch or business unit to each party | +| **Operations** | `BankRelations/Update`, `BankRelations/Retrieve` | +| **MCP tools** | `…_update_bank_relations`, `…_retrieve_bank_relations` | +| **Data** | `BankRelationType`, the employee (`Person`) or unit (`Organisation`) entry, start/end dates, `Active` / `Suspended` / `Ended` | +| **Business value** | Portfolio ownership is explicit and typed; reassignments are dated and kept in history | +| **Limits** | One bank relation per party in Stage 1 (a party cannot yet have both a relationship manager and a servicing branch, [ADR 0035](../adr/0035-party-bank-relations.md)) | + +## UC6 — Contact data for servicing + +| | | +|---|---| +| **Actor** | Contact centre, notification services | +| **Goal** | Reach the customer on the right channel | +| **Operations** | `Reference/Update`, `Reference/Retrieve` | +| **Data** | `eMailAddress` (Max256Text, syntax-checked), `CellPhoneNumber` (ITU-T E.164, normalised), `SocialNetworkContacts` (https URL), `PartyNameSalutation`, `ServicingConstraints` (Demographics) | +| **Business value** | Contact data in a single format usable by SMS and e-mail gateways; servicing constraints (sight, hearing, …) visible to whoever serves the customer | +| **Out of scope** | Marketing consent and communication preferences (not BIAN Party Reference fields; belong to CRM / consent capabilities); proof of deliverability (only a verification can prove it) | + +## UC7 — Document references for ID&V + +| | | +|---|---| +| **Actor** | Onboarding officer, periodic review | +| **Goal** | Record which identity document was presented and where its image lives | +| **Operations** | `Reference/Update` (`GovernmentIssuedDocumentDetails`, `DocumentDirectoryEntryInstanceReference`) | +| **Data** | Document type (`PersonalDocument`, `WorkDocument`, `CertificationDocument`), number, name, validity period; opaque document directory id | +| **Business value** | The evidence trail links the party to the bank's document store without copying images into the core | +| **Limits** | One document per party; an expired document is accepted (expiry handling is a KYC concern); the document directory reference is never resolved | + +## UC8 — AI assistant over MCP + +| | | +|---|---| +| **Actor** | Staff assistant (for example in a contact centre) or a customer-facing agent built by the bank | +| **Goal** | Let an agent look up and maintain party data in natural conversation, without bypassing controls | +| **Tools** | 13 tools, one per implemented BIAN operation: `party_reference_data_directory_register`, `_retrieve`, `_update`, `_update_demographics`, `_exchange_demographics`, `_retrieve_demographics`, `_update_reference`, `_retrieve_reference`, `_register_associations`, `_update_associations`, `_retrieve_associations`, `_update_bank_relations`, `_retrieve_bank_relations` | +| **Controls** | OAuth 2.1 through the bank's identity provider; `party-reference-data-directory:read` for Retrieve tools, `:write` for commands — a token without the scope does not even see the tool; required `idempotencyKey` and `expectedVersion`; same Problem Details errors as HTTP ([ADR 0022](../adr/0022-mcp-authorization-and-tool-errors.md), [ADR 0038](../adr/0038-per-operation-authorisation-policies.md), [ADR 0039](../adr/0039-party-mcp-tools.md), [ADR 0040](../adr/0040-party-mcp-command-tools.md)) | +| **Business value** | Faster servicing, with the agent bound by exactly the same business rules, permissions and audit as a human using the API | +| **Out of scope** | No AI inside the core; the model never decides — it calls tools whose rules decide. Read-only deployments simply grant only the `:read` scope | + +```mermaid +sequenceDiagram + actor U as Staff member + participant A as AI assistant + participant M as RimBank MCP endpoint + participant P as Party core + U->>A: Update Alex's mobile number + A->>M: party_reference_data_directory_retrieve + M->>P: Retrieve query + P-->>A: entry, version 7 + A->>M: party_reference_data_directory_update_reference, expectedVersion 7, idempotencyKey + M->>P: UpdatePartyReference command + P-->>A: Reference, version 8 + A-->>U: Done, number stored as E.164 +``` + +--- + +## 5.9 Integration guide for consumers + +### What is published today + +| Event | When | What a consumer gets | +|---|---|---| +| `PartyReferenceDataDirectoryEntryCreated` (`party-reference-data-directory-entry.created.v1`) | A party is registered | `EventId`, `OccurredAt`, entry id, `Version`, `PartyType`, `DirectoryEntryDateType = OpenDate`, `DirectoryEntryDate` | +| `PartyReferenceDataDirectoryEntryUpdated` (`party-reference-data-directory-entry.updated.v1`) | The entry is updated | Same payload with `RefreshDate` | + +Events are written in the same transaction as the business change (transactional outbox), so a consumer never sees an event for a change that was rolled back, and never misses one that was committed ([ADR 0036](../adr/0036-party-published-language.md)). + +### Typical subscribers + +| Subscriber | Uses the events to | Status | +|---|---|---| +| Current Account (RimBank) | Keep a minimal "known party" list for account opening decisions | Roadmap 4.1–4.2 | +| Payment Order Initiation (RimBank) | Know payer / payee parties | Roadmap Stage 5 | +| Bank's KYC / Party Lifecycle system | Start onboarding checks on `Created`, re-check on `Updated` | Bank-side | +| Bank's CRM | Create / refresh the customer record | Bank-side | +| Data warehouse / regulatory reporting | Build party dimensions with history | Bank-side | +| Legacy core (strangler) | Mirror new parties during migration | Bank-side | + +### Rules for consumers + +Consumers **must**: + +- keep **their own minimal copy** of what they need (for example "party known, type Person"), fed by the events, and rebuildable from them ([tech-stack §8.4](../../specs/tech-stack.md#84-read-models-across-contexts-loose-coupling)); +- be **idempotent** (de-duplicate on `EventId`) and **tolerant**: accept redelivery and out-of-order delivery (use `Version` to ignore older facts), ignore unknown fields; +- treat the event as **carrying the state they need** — no callback to Party to "complete" it. + +Consumers **must not**: + +- read Party's database schema, tables or views (database roles forbid it); +- send Party's internal commands; a request for Party to act would be a published request event, translated by Party itself; +- copy more personal data than they need (minimal copies also limit PII spread). + +Consumers that need demographic or reference values by event today cannot get them: the Behavior Qualifier channels are **deferred**. Until they are delivered, such consumers call the Retrieve operations through the API with a `:read` scope, as a channel would — and accept that this is a synchronous dependency. + +Back to the [business documentation index](README.md). diff --git a/docs/business/README.md b/docs/business/README.md new file mode 100644 index 0000000..0acee24 --- /dev/null +++ b/docs/business/README.md @@ -0,0 +1,27 @@ +# RimBank business documentation + +For bank business analysts, product owners, enterprise and solution architects, and new contributors who need to understand **what** RimBank does for a bank before reading **how** it is built (see [`docs/architecture/`](../architecture/)). + +| # | Document | Answers | +|---|---|---| +| 1 | [Business architecture](01-business-architecture.md) | Where RimBank sits in the BIAN v14 landscape; the retail-core capability chain with BIAN definitions and status; system of record vs consumer; adoption patterns (greenfield, strangler, party MDM, AI-agent channel) | +| 2 | [Party domain glossary](02-party-domain-glossary.md) | Every member of the Party Reference Data Directory Entry and its four Behavior Qualifiers: business definition, ISO / BIAN format, rules, business use, PII class; every enumeration; business events; error codes | +| 3 | [Entity relationships](03-entity-relationships.md) | The business ERD; cardinalities and rules; Associations vs corporate references vs bank relations; worked examples (corporate group, household, servicing model) | +| 4 | [Value streams](04-value-streams.md) | Onboard a party, open a product, move money, record and report, service the relationship: stages, service domains, status, KPIs; value stream × service domain matrix | +| 5 | [Banking use cases and integration guide](05-banking-use-cases.md) | KYC/CDD capture, PEP declaration, beneficial ownership, FATCA/CRS inputs, servicing assignment, contact data, ID&V document references, AI assistant via MCP; how consumers subscribe to Party events | + +## Status conventions + +- **Implemented** — in `main`, tested, on HTTP and MCP (Stage 1, roadmap 1.1–1.21). +- **Planned** — a numbered item of the [roadmap](../../specs/roadmap.md) (Stages 2–7). +- **Backlog** — Stage 8+, order not decided. +- **Deferred** — a BIAN operation or channel of an implemented service domain that is not built yet. +- **Not recorded** — a BIAN field deliberately not kept, by ADR. + +## Sources of truth + +1. BIAN v14 ISO 20022 extended DDD specifications: [`doc-0/release14.0.0/apis-iso20022_ext-ddd/`](../../doc-0/release14.0.0/apis-iso20022_ext-ddd/) (quoted verbatim in these documents). +2. The RimBank constitution: [mission](../../specs/mission.md), [tech stack](../../specs/tech-stack.md), [roadmap](../../specs/roadmap.md). +3. Architecture decision records: [`docs/adr/`](../adr/), in particular [0024](../adr/0024-party-reference-data-directory-mapping.md) (Party mapping), [0028](../adr/0028-demographics-exchange-as-verification.md)–[0035](../adr/0035-party-bank-relations.md) (Behavior Qualifier fields) and [0036](../adr/0036-party-published-language.md) (published events). + +When these documents and the code disagree, the code and the ADRs win; please open an issue. From 73904f8d01487524fa8df22fd0d417e2366e4c52 Mon Sep 17 00:00:00 2001 From: LaBani Said Date: Mon, 9 Nov 2026 14:19:32 +0100 Subject: [PATCH 2/2] Keep the documentation current on every pull request with an update-docs skill, run by open-phase-pr and planned by plan-feature The skill maps a change (service domain, operation, field, event, error, table, dependency, security, deployment) to the architecture and business documents it affects, updates them, renders every Mermaid diagram and checks every link. The PR template gains a documentation item. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/open-phase-pr/SKILL.md | 4 +- .claude/skills/plan-feature/SKILL.md | 5 +- .claude/skills/update-docs/SKILL.md | 97 +++++++++++++++++++++++++++ .github/pull_request_template.md | 1 + docs/README.md | 1 + 5 files changed, 106 insertions(+), 2 deletions(-) create mode 100644 .claude/skills/update-docs/SKILL.md diff --git a/.claude/skills/open-phase-pr/SKILL.md b/.claude/skills/open-phase-pr/SKILL.md index e93e6ac..57d5944 100644 --- a/.claude/skills/open-phase-pr/SKILL.md +++ b/.claude/skills/open-phase-pr/SKILL.md @@ -37,6 +37,8 @@ Stop and report if any check fails. Never open a PR on a red local build. If `scripts/` changed, also run `python -m unittest discover -s scripts`. +- **Documentation.** Invoke the `update-docs` skill on the branch, every time, before pushing. It maps the diff to `docs/architecture/*` and `docs/business/*`, updates them, renders every Mermaid diagram and checks the links. It then commits the documentation changes on the branch. Keep its report for the PR body. A phase is not ready if a diagram fails to render or a document still describes the old behaviour. + ## 3. Push and write the body - `git push -u origin `. @@ -44,7 +46,7 @@ Stop and report if any check fails. Never open a PR on a red local build. - **Roadmap phase:** `Phase: `, `Planning package: specs/<folder>/`, then `Closes #<issue>`. - **Summary:** what changed and why, in business language, grouped by type or concern. Name the commands vs queries (CQRS) and any ADR written or amended. - **Definition of done:** copy every item from the template. Tick what is met, write `N/A: <reason>` for items that do not apply, and leave **CI green** unticked (CI has not run yet). - - **Validation:** the commands from step 2 with their results (test counts), and the manual or break-on-purpose checks from `validation.md` that were run. + - **Validation:** the commands from step 2 with their results (test counts), and the manual or break-on-purpose checks from `validation.md` that were run. Add a **Documentation** line from the `update-docs` report: the documents updated and the diagram render count, or "No documentation impact" with the reason. - **Review focus:** the decisions a reviewer should challenge, and the open questions from `requirements.md`. - End with the attribution line from the session's system reminder, if there is one. - Title: imperative, describes the change, ends with `(roadmap <phase>)`. Look at `gh pr list --state merged --limit 5` for the house style. diff --git a/.claude/skills/plan-feature/SKILL.md b/.claude/skills/plan-feature/SKILL.md index f5098ab..37f087d 100644 --- a/.claude/skills/plan-feature/SKILL.md +++ b/.claude/skills/plan-feature/SKILL.md @@ -120,9 +120,12 @@ How we know the implementation succeeded and can be merged. Start from the phase - [ ] All checks above pass in CI - [ ] Roadmap checkbox ticked in the same PR - [ ] ADRs written for significant decisions -- [ ] ... (no secrets or PII in logs, docs updated, etc.) +- [ ] Documentation updated with the `update-docs` skill: every affected `docs/architecture/` and `docs/business/` document, all Mermaid diagrams render +- [ ] ... (no secrets or PII in logs, etc.) ``` +**Documentation tasks.** Before writing `plan.md`, use the `update-docs` skill's mapping table (`.claude/skills/update-docs/SKILL.md`, step 2) on the phase's scope. List the documents the phase will change as the last task group of `plan.md`, "Documentation". Name each document and what it gains, for example "Biz 02: glossary section for ProductDirectoryEntry" or "Arch 05: decision tree for Launch". If the phase has no documentation impact, say so there with the reason. + ## 6. Wrap up Summarise for the user: the phase, the branch name, the folder path, and one line per file on what it contains. Do not commit unless the user asks; offer to commit the three files on the planning branch. diff --git a/.claude/skills/update-docs/SKILL.md b/.claude/skills/update-docs/SKILL.md new file mode 100644 index 0000000..e23db35 --- /dev/null +++ b/.claude/skills/update-docs/SKILL.md @@ -0,0 +1,97 @@ +--- +name: update-docs +description: Keep RimBank's architecture and business documentation (docs/README.md, docs/architecture/*, docs/business/*) in step with the code. Works out which documents and Mermaid diagrams a change affects (a new service domain, BIAN operation, Behavior Qualifier, field, enum value, event, error code, table, dependency, policy, MCP tool, deployment or security change), updates or adds them, renders every diagram to prove it parses, and checks every link. Use this before any pull request is opened (open-phase-pr calls it), when a phase is planned (plan-feature lists its doc tasks), and whenever the user asks to add, update, refresh, check or review the documentation, the diagrams, the C4, ERD, sequence, flow, glossary or value streams, even if they don't say "update-docs". +--- + +# Update the architecture and business documentation + +`docs/` describes `main`. A pull request that changes behaviour shown in a document updates that document in the same pull request (`docs/README.md` "Conventions"). Code and ADRs win when they disagree with a document, so fix the document, never the other way round. + +## 1. Find what changed + +- Base: `git merge-base HEAD origin/main`. Read `git diff --stat <base>...HEAD` and `git log <base>..HEAD --oneline`. +- When planning (called from `plan-feature`), use the phase's `requirements.md` scope instead of a diff. +- Read the changed core, adapter and host files, and any new or changed ADR. Use the ADRs and code as the source of facts. Never use memory of earlier versions. + +## 2. Map the change to documents + +Use this table. A change usually touches several rows. "Arch" means `docs/architecture/`, "Biz" means `docs/business/`. + +| Change in the diff | Update | +|---|---| +| **New service domain** (new folder in `RimBank.Core`, new `.Postgresql` / `.PublishedLanguage`, new module) | Arch 02 (containers, a new component diagram for the context, the code-level class diagram), Arch 03 (logical ERD, event model, schema, role), Arch 06 (cross-context data flow: move it from *(target)* to today), Arch 07 (project graph, context map), Arch 08 (Aspire topology, role connection string), Arch 09 (readiness, timeline). Biz 01 (capability status), Biz 02 (**new glossary section** for its Control Record and BQs), Biz 03 (relationships to Party and others), Biz 04 (value stream stage status, matrix), Biz 05 (use cases it enables). `docs/README.md` if a new document is added | +| **New BIAN operation** (endpoint + command or query + MCP tool) | Arch 04 (sequence if it adds a new pattern, otherwise the operation table), Arch 05 (decision tree), Arch 08 (policy/scope table if new scopes). Biz 02 (operations, errors), Biz 05 (the use cases that use it) | +| **New or changed field, value object, enum value** | Arch 03 logical ERD attributes. Biz 02 member table or enum table (definition, ISO/BIAN format, rules, business use, PII class). Biz 03 if it links parties | +| **New domain event or event type name** | Arch 03 event model (with its Marten type name from `…Postgresql.Configure`) | +| **New or changed integration event / channel** | Arch 03 published language section, Arch 06 data flows, Arch 07 context map. Biz 02 events section, Biz 05 consumer guide | +| **New decision rule or error code** | Arch 05 decision tree, in the code's real order, with the exact error code. Biz 02 error table | +| **New lifecycle or status** | Arch 05 state machine. Biz 02 enum meaning | +| **New read model / projection** (inline or async) | Arch 03 read models table (and physical table), Arch 06 CQRS paths, Arch 05 rebuild if the procedure changes | +| **Project reference, package, dependency rule, architecture test** | Arch 07 graph, matrix, rules table, packages. Arch 01 decisions if an ADR changed | +| **Request pipeline** (headers, filters, idempotency, concurrency, auth order) | Arch 05 §1 pipeline, Arch 04 sequences 1–4 and 9 | +| **Security** (scopes, policies, MCP auth, PII handling, secrets) | Arch 08 controls and STRIDE, Arch 06 data classification | +| **Deployment / observability / CI** | Arch 08 | +| **New ADR** | Arch 01 key decisions table if it is architecturally significant. Any document that cites a superseded ADR | +| **Roadmap phase completed** | Status lines and *(target)* markers in every document that mentions it. Arch 09 readiness and risks. Biz 04 stage status. Root `README.md` status line | +| **Pure refactor, tests only, internal rename with no behaviour change** | Usually nothing. Still grep `docs/` for renamed type, file or route names | + +Then grep for stale names. Every type, route, tool, error code or table the diff renamed or removed must not survive in `docs/`: + +```bash +grep -rn "<old name>" docs/ README.md +``` + +## 3. Edit + +- Keep each document's structure and voice: tables, short sentences, and BIAN and banking vocabulary. The business documents are for bank analysts and architects, so explain business meaning there, not C# detail. +- Mark anything not yet on `main` as *(target)*, and remove the marker when it ships. +- Business definitions: quote BIAN verbatim from `doc-0/release14.0.0/apis-iso20022_ext-ddd/`. Cite the exact standard (ISO 20022 `MaxNText`, ISO 17442, ISO 3166-1 alpha-2, ISO 4217, ISO 8601, ITU-T E.164, RFC 9457). Say clearly when a meaning is RimBank's interpretation. +- Every new field gets a PII class in Biz 02 and, if personal, a row in the Arch 06 classification. +- Link ADRs and specs with relative paths, as the existing documents do. +- Add a new document only when no existing one fits, and then add it to `docs/README.md` and to the folder's own README. + +### Mermaid rules (GitHub renders these) + +- Never put `;` in sequence diagram messages or notes: it ends the statement. Use a comma. +- In flowcharts, quote a label that contains `(`, `)`, `[`, `]`, `{`, `}`, `:` or `#`: `A["text (detail)"]`. +- In `erDiagram`, entity names and attribute types are single tokens (letters, digits, `_`). Put explanations in the quoted comment. +- Use `<br/>` for line breaks in labels. + +## 4. Verify (mandatory) + +Render every Mermaid block in `docs/`. A diagram that does not parse shows as an error on GitHub. + +```bash +S=<scratchpad> +mkdir -p "$S/mmd" "$S/out" +for f in docs/architecture/*.md docs/business/*.md; do + awk -v base="$S/mmd/$(basename $f .md)" '/^```mermaid/{n++; out=base"__"n".mmd"; inb=1; next} /^```/{if(inb){inb=0; close(out)}; next} inb{print > out}' "$f" +done +# one-off install in the scratchpad: npm install @mermaid-js/mermaid-cli@11.4.2 +# no bundled Chrome: point puppeteer at Edge or Chrome, e.g. +# {"executablePath":"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe","headless":"new"} > "$S/pptr.json" +for f in "$S"/mmd/*.mmd; do + "$S/tool/node_modules/.bin/mmdc" -q -p "$S/pptr.json" -i "$f" -o "$S/out/$(basename $f .mmd).svg" || echo "FAIL $f" +done +``` + +Check that every relative link resolves: + +```bash +for f in docs/README.md docs/architecture/*.md docs/business/*.md README.md; do d=$(dirname $f) + grep -oE '\]\([^)#]+(#[^)]*)?\)' "$f" | sed -E 's/^\]\(//; s/\)$//; s/#.*//' | grep -v -E '^(https?:|mailto:)' | sort -u | + while read l; do [ -n "$l" ] && [ ! -e "$d/$l" ] && echo "BROKEN in $f: $l"; done; done +``` + +For a large diagram change, render it to PNG (`-o x.png -w 1800 -b white`) and look at it. + +## 5. Report + +Tell the caller, briefly: + +- the documents updated or added, with one line each on what changed; +- the rows of the table that applied but needed no change, and why; +- diagram render count (`n/n`) and link check result; +- any fact you could not confirm from code or ADRs (leave it out of the document, or mark it as an assumption). + +When called from `open-phase-pr`, commit the documentation changes on the phase branch before the push (message: what the docs now cover, ending with the session's attribution line), and add a **Documentation** line to the PR body's Validation section: the documents updated, or "No documentation impact" with the reason. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 854a84e..4012d88 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -20,6 +20,7 @@ Planning package: `specs/YYYY-MM-DD-<slug>/` - [ ] Every new BIAN operation exposed over HTTP is also exposed as an MCP tool, with a parity test - [ ] GitHub Actions CI green (build, test, format, CodeQL) - [ ] An ADR in `docs/adr/` for any significant or BIAN-interpretation decision +- [ ] Architecture and business documentation (`docs/architecture/`, `docs/business/`) updated for the change, with every Mermaid diagram rendering (the `update-docs` skill) - [ ] The roadmap checkbox ticked in the same PR ## Validation diff --git a/docs/README.md b/docs/README.md index f55cc71..cc33d20 100644 --- a/docs/README.md +++ b/docs/README.md @@ -39,3 +39,4 @@ Two views of the same platform. Start with the one that matches your question; e - Every document states whether it describes `main` today or a *(target)* from the roadmap. - When a document and the code or an ADR disagree, the code and the ADR win: fix the document in the same pull request. - A phase that changes a diagrammed behaviour (a new context, operation, event, table or rule) updates the affected document as part of its definition of done. +- The `update-docs` Claude Code skill ([`.claude/skills/update-docs/SKILL.md`](../.claude/skills/update-docs/SKILL.md)) maps a change to the documents it affects, updates them and renders every diagram. `plan-feature` uses it to plan the documentation tasks, and `open-phase-pr` runs it before every pull request.