Version lock:
metarch-truthsrc@ab207e7(scala-cqrs-play-service:2·catalogSha256: 156b224f3614· 60 unified families / 14 producers / 64artifactKinds) ·bank-wealth-demo@b5cadc0· Controlled byassets/data/artifact-maps.lock.jsonand thesync-site-factsCI gate (cross-referenced withF-32/F-33on the status page).
Most code generators emit one giant OrderService.scala per model. That shortcut feels fast on day one, yet as soon as invariants, persistence adapters, authorization, read projections, and reactive policies evolve together, templates collapse into an untestable tangle where AI edits leak infrastructure into business rules and Onion boundaries erode silently.
scala-cqrs-play-service:2 inside metarch-truthsrc takes the opposite approach: fine-grained orthogonal decomposition (60 unified families across 64 artifactKinds — expanding the 54-family baseline with #55–#60 Reactive Policy families) + strict inward-only Onion dependencies + deterministic outer-edge re-assembly through Guice DI and ApplicationBootstrap. This guide walks from architectural philosophy → clickable interactive Onion & Wiring maps → layer-by-layer breakdown with real generated Scala → end-to-end transaction trace → the upgrade sync contract and Rust/Axum extension blueprint.
1. Architecture Philosophy: Why Decompose Into 60 Artifact Families Before Re-Assembling
1. First Principles: Partitioning Every Artifact Into Kernel, Seam, or Glue
Every Artifact Type in co-arising carries an explicit architectural role so neither humans nor agents mix business truth with framework plumbing:
| Role | Badge | Authority & Origin | Change Driver | Representative Artifact Types |
|---|---|---|---|---|
| Critical Business Kernel (Kernel) | KERNEL | Derived strictly from YAML structures + EARS behavioral specs + Z3 mathematical proofs (4A zero-token codegen or verified contract) | Domain rule changes | ValueObject, Entity, EventHandler, Rules, Axioms, PolicyOn<Cmd> |
| Isolation Boundary (Seam & Port) | SEAM | Compiler-derived typed interfaces (Port / Protocol / CallerContractSpec / Semantics) caging non-deterministic L2/L3/Infra code inside handwritten/ @cloze slots | Capability boundary changes | *Computations, *Protocol, *Repository, *Port.scala, ApplyEventSemantics, PolicyDlqSink |
| Wiring & Runtime Plumbing (Glue) | GLUE | Zero new business decisions — adapts Kernel and Seam contracts onto Akka Typed, ClusterSharding, Play HTTP, ScalaPB, and Guice DI | Target runtime/framework upgrades | *Aggregate, *Behaviors, *ProtoConverters, *Bootstrap, ApplicationBootstrap, GeneratedBindingsModule |
Core invariant — purity inside, plumbing outside: The innermost domain/ package contains zero akka.*, play.*, scalikejdbc.*, javax.inject.*, or Protobuf imports. That purity makes it possible for verify-gate.mjs to compile all Kernel + Seam Scala files via standalone offline scalac in milliseconds and execute a 100% domain mutation gate without booting an Akka cluster.
2. Why Decompose Thoroughly Before Re-Assembling?
- Ownership Separation (Overwrite vs. Never-Overwrite): Keeping compiler-owned
FundOrderRules.scalaseparate from human/AI-ownedFundOrderComputationsImpl.scalaallowsgenerated-scaffold/vs.handwritten/to live side by side and re-assemble cleanly viaGeneratedBindingsModulewithout regeneration ever clobbering handwritten@clozelogic. - Dual-Channel Verification (
4Avs.4B): Deterministic linear rules and folds stay in#45 Rules/#3 EventHandler/#48 Axioms; non-linear math and multi-step orchestration stay behind#51 ApplicationPortand*Computationssupervised by locked BDD oracles. - Cross-Stack Portability (Scala/Play → Rust/Axum): Once Kernel contracts and Port seams are separated, porting
metarch-truthsrcto another stack (see Section 9's Rust/Axum blueprint) primarily swaps Glue adapters while preserving the same semantic architecture.
2. Master Play CQRS Artifact Type Map & Wiring Topology
Click any node in Figure 1 to jump directly to that layer's Artifact Type breakdown and Scala code sample. Use the 2-level collapsible Onion-layer sidebar on the left to expand or collapse individual layers.
scala-cqrs-play-service:2). From outside in: Layer 4 Interfaces, Layer 3 Infrastructure (including the DI re-assembly hub), Layer 2 Application, and the innermost Layer 1 Domain Core, with the offline Layer 5 Verification & DIP Gate mounted below.How Decomposed Pieces Re-Assemble Into a Running Service
On first inspection, splitting a service into 60 artifact kinds raises an obvious question: who actually stitches FundQuotaRules, FundOrderComputationsImpl, CashFundPurchaseImpl, BankOrderApplyEventSemanticsImpl, and PolicyOn*Runner together at boot? Figure 2 shows both assembly backbones:
BootstrapModule → HandwrittenBindingsModule → GeneratedBindingsModule + ProjectionModule, while runtime startup executes inside ApplicationBootstrap mixing in aggregate, readside, and reactive policy bootstraps.3. Domain Core Layer (Innermost · Zero Framework Dependencies)
The domain/ package holds the highest-trust Kernel and Seam artifacts: zero HTTP, Akka, or database knowledge, compiling standalone via offline scalac.
Value Object & ExactType (#1)
KERNEL Problem solved: Eliminates raw BigDecimal / String currency mix-ups, precision drift, and unchecked domain enums. Generated from structures/exactTypes and valueObjects (Money, AmountDecimal, NavDecimal, BankCashAcknowledgement), enforcing scale/unit proofs at construction time.
// generated-scaffold/scala/example/bankwealth/v2/domain/values/Money.scala
sealed abstract case class Money private (amount: BigDecimal, currency: String) {
def isPositive: Boolean = amount > 0
def plus(other: Money): Either[iMadzError, Money] =
if (currency != other.currency) Left(iMadzError("EXACT_UNIT_MISMATCH", "exact units differ"))
else for {
lhs <- Money.checkedAmount(amount)
rhs <- Money.checkedAmount(other.amount)
result <- Money.checkedAmount(lhs + rhs)
} yield new Money(result, currency) {}
}
Domain Entity (#2)
KERNEL Problem solved: Defines each aggregate root's immutable State, empty baseline, and sealed trait Event extends CborSerializable vocabulary from a single structural truth.
// generated-scaffold/scala/example/bankwealth/v2/domain/entities/FundOrderEntity.scala
object FundOrderEntity {
final case class State(netAmount: BigDecimal, paymentOutcome: String, taStatus: String)
def empty: State = State(netAmount = BigDecimal("0.00"), paymentOutcome = "pending", taStatus = "pending")
sealed trait Event extends CborSerializable
final case class CashRequestSourceRecorded(principal: String, clientRequestId: String) extends Event
final case class FundTASharesConfirmed(shares: Long, nav: BigDecimal) extends Event
type EventHandler = (State, Event) => State
}
EventHandler (#3)
KERNEL Problem solved: Guarantees Event Sourcing state replay matches EARS post: assignments identically, preventing divergence between write guards and state folding.
// generated-scaffold/scala/example/bankwealth/v2/domain/entities/behaviors/FundQuotaEventHandler.scala
object FundQuotaEventHandler extends EventHandler {
override def apply(state: State, input: Event): State = input match {
case event: SubscriptionQuotaReserved =>
state.copy(
fundTotalUsed = (state.fundTotalUsed + event.amount),
accountUsed = state.accountUsed.updated(
event.accountId,
(state.accountUsed.getOrElse(event.accountId, BigDecimal("0")) + event.amount))
)
}
}
Aggregate Invariant Rules & RuleParams (#4 / #5 / #45)
KERNEL Problem solved: Encapsulates pure command inputs inside <Agg>RuleParams.<Cmd>Params and compiles EARS rules into InvariantRule[Event, State, Params] enforcing DMN FIRST-HIT order and checkEventPostconditions, each tagged with @knowledge provenance anchors.
// generated-scaffold/scala/example/bankwealth/v2/domain/invariants/FundQuotaRules.scala
final class ReserveSubscriptionQuotaRule(hosts: FundQuotaComputations)
extends InvariantRule[Event, State, ReserveSubscriptionQuotaParams] {
override def apply(state: State, p: ReserveSubscriptionQuotaParams): Either[iMadzError, List[Event]] = {
if ((p.amount < state.minPurchase || p.amount > state.maxSingleLimit)) Left(iMadzError("QUOTA_AMOUNT_RANGE", "QUOTA_AMOUNT_RANGE"))
else if (((state.fundTotalUsed + p.amount) > state.fundTotalCap)) Left(iMadzError("QUOTA_FUND_CAP", "QUOTA_FUND_CAP"))
else if (((state.accountUsed.getOrElse(p.accountId, BigDecimal("0")) + p.amount) > state.perAccountCap)) Left(iMadzError("QUOTA_ACCOUNT_CAP", "QUOTA_ACCOUNT_CAP"))
else Right(List(SubscriptionQuotaReserved(p.accountId, p.amount)))
}
}
Z3 Axioms & Replay (#48)
KERNEL Problem solved: Turns Z3 Prover-verified axioms: ALWAYS into executable runtime/test predicates (checkAxioms(state)) paired with deterministic replay(initial, events).
// generated-scaffold/scala/example/bankwealth/v2/domain/entities/FundQuotaAxioms.scala
object FundQuotaAxioms {
def replay(initial: State, events: Seq[Event]): State =
events.foldLeft(initial)(FundQuotaEventHandler.apply)
def checkAxioms(state: State): Seq[String] = {
val violated = scala.collection.mutable.ListBuffer.empty[String]
if (!(state.fundTotalUsed <= state.fundTotalCap)) violated += "AX-Q-1"
if (state.accountUsed.keys.exists(accountId => !(state.accountUsed.getOrElse(accountId, BigDecimal("0")) <= state.perAccountCap))) violated += "AX-Q-2"
violated.toSeq
}
}
Domain Computations Port & L2 @cloze Impl (#14 / #51)
SEAM Problem solved: L1 aggregates auto-bind Computations.Noop; L2 aggregates (e.g., non-linear shares * nav <= netAmount) get a typed domain/services/<Agg>Computations trait plus a never-overwritten handwritten/ *ComputationsImpl.scala @cloze slot wired via Guice.
4. Application Layer (Write Protocol, ReadSide, Reactive Policy & Orchestration)
The application ring turns pure domain kernels into scheduled CQRS endpoints, materialized views, reactive Event => Command projections, and cross-aggregate sagas.
Aggregate Protocol & CommandHelpers (#7 / #11)
SEAM GLUE Problem solved: Defines Akka Cluster Sharding command envelopes (replyTo: ActorRef[Reply], Accepted(events) / Refused(error)) and pure Command → RuleParams extractors so ActorRef never leaks into Domain Rules.
// generated-scaffold/scala/example/bankwealth/v2/application/aggregates/FundOrderProtocol.scala
object FundOrderProtocol {
sealed trait Command extends CborSerializable
final case class RecordFundTAConfirmed(shares: Long, nav: BigDecimal, replyTo: ActorRef[Reply]) extends Command
final case class RequestIndependentRefund(orderId: String, replyTo: ActorRef[Reply]) extends Command
final case class GetState(replyTo: ActorRef[State]) extends Command
sealed trait Reply extends CborSerializable
final case class Accepted(events: Vector[Event]) extends Reply
final case class Refused(error: iMadzError) extends Reply
type CommandHandler = (State, Command) => Effect[Event, State]
}
Aggregate, Factory & Behaviors (#6 / #8 / #9 / #10)
GLUE Problem solved: Pure framework Glue. <Agg>Aggregate exports EntityKey and tags; <Agg>Behaviors adapts pure Rules onto Akka persistence via runReplyingPolicy(rule, helper)(state, cmd).withPost(...).replyWith(cmd.replyTo).
// generated-scaffold/scala/example/bankwealth/v2/application/aggregates/behaviors/FundQuotaBehaviors.scala
private def executionBehavior(state: State, hosts: FundQuotaComputations): PartialFunction[Command, Effect[Event, State]] = {
case cmd: ReserveSubscriptionQuota =>
runReplyingPolicy(new FundQuotaRules.ReserveSubscriptionQuotaRule(hosts), ReserveSubscriptionQuotaHelper)(state, cmd)
.withPost(FundQuotaRules.checkEventPostconditions)
.replyWith(cmd.replyTo)
}
Aggregate Repository Port (#12)
SEAM Problem solved: Exposes <Agg>Repository traits to upper orchestration layers so callers never depend directly on ClusterSharding.
Application Story Port, CallerContractSpec & L3 @cloze Impl (#51 / #52)
KERNEL SEAM Problem solved: For layer: application EARS stories, generates typed Request, ExternPorts, EffectsPort, CallerContractSpec (replacing raw JSON strings with typed idempotency/retry/untrusted-field contracts), and <Story>Impl.scala inside handwritten/.
// generated-scaffold/scala/example/bankwealth/v2/application/services/CashFundPurchasePort.scala
trait CashFundPurchaseHandler extends ApplicationService {
def handle(req: CashFundPurchaseRequest, externs: CashFundPurchaseExternPorts, effects: CashFundPurchaseEffectsPort): Either[iMadzError, CashFundPurchaseSuccessResponse]
}
object CashFundPurchaseCallerContract {
val spec: CallerContractSpec = CallerContractSpec(
idempotencyKey = "(principal, clientRequestId)",
retryPolicy = "at-least-once safe; replayed identical payload must never re-dispatch settlement",
forbiddenUntrustedFields = Seq("operationId", "investorAccountId", "fundCollectionAccountId")
)
}
ReadModel View, QueryService & ReadSide Projection (#15 / #23 / #26 / #27 / #28)
KERNEL GLUE Problem solved: Realizes CQRS read models via <View>, <View>QueryService, ReadsideRepository, Akka Projection definitions, ProjectionHandler, and #26 ApplyEventSemantics (bound in <Context>ProjectionModule to handwritten ApplyEventSemanticsImpl).
// generated-scaffold/scala/example/bankwealth/v2/application/readmodels/bank_order_readside/BankOrderReadsideProjectionHandler.scala
override def process(envelope: EventEnvelope[Any]): Future[Done] =
envelope.event match {
case e: FundOrderEntity.CashRequestSourceRecorded =>
val base = BankOrderView(clientRequestId = envelope.persistenceId)
repository.upsert(base.copy(principal = e.principal, clientRequestId = e.clientRequestId)).map(_ => Done)
case _ => bindings.onUnmatchedEvent(envelope)
}
Reactive Policy & PolicyMachine (#55–#58 / #60)
KERNEL GLUE Problem solved: Wires WHEN event <SrcAgg>.<SrcEvent> SHALL dispatch <TargetAgg>.<TargetCmd> specs into fault-tolerant Event ⇒ Command projections — accounting for the 6 new families (#55–#60) added on top of the 54-family baseline:
#55 policy-decision(PolicyOn<Cmd>.scala): Pure(decide, dispose)kernel pair +DefaultSemanticswith zero Akka dependencies;#56 policy-mechanics(PolicyOn<Cmd>Mechanics.scala): Sends commands viaClusterSharding.entityRefFor(EntityKey, entityId).ask[Reply], translatingRefused(err)intoLeft(err);#57 policy-handler(PolicyOn<Cmd>Handler.scala): AkkaHandler[EventEnvelope[Any]]shell decoding events intoPolicyEnvelopeand delegating toPolicyMachine.run;#58 policy-runner(PolicyOn<Cmd>Runner.scala): OwnsEventSourcedProvider.eventsByTagandProjectionId;#60 projection-runtime-mechanism(PolicyMachine.scala/FailureVerdict.scala/PolicyEnvelope.scala/PolicyDlqBury.scala): Shared 4-stage execution pipeline inspecting everyLeft(err)insideFuture.traverse(commands)(execute)— buryingPermanentverdicts viaPolicyDlqSink.bury(advancing offsets) while failing theFutureonRetryableverdicts (blocking offset commits for at-least-once replay); daemon registration traits belong to#59 policy-bootstrap(Section 5.4).
// application/projection/policy/PolicyMachine.scala (metarch-truthsrc scala-cqrs-play-service:2 @ 8950ba3)
Future
.traverse(commands)(execute)
.flatMap { results =>
val verdicts = results.collect { case Left(err) => dispose(e, err) }
val permanents = verdicts.collect { case p: FailureVerdict.Permanent => p }
val retryables = verdicts.collect { case r: FailureVerdict.Retryable => r }
Future
.traverse(permanents)(p => bury(envelope, s"$aggType·${p.what}"))
.flatMap { _ =>
retryables.headOption match {
case Some(FailureVerdict.Retryable(err)) =>
Future.failed(new RuntimeException(s"[policy] $aggType retryable failure: err=${err.code}"))
case None => Future.successful(())
}
}
}
Orchestration, Saga, EffectFace & ExternalEventBridge (#13 / #16–#21 / #40–#44 / #46)
KERNEL SEAM Problem solved: Unifies multi-step Sagas (#40–#44 superseding legacy #16–#21), toolgate connectors, effect hosts, and cross-bounded-context ACL integration (#46 ExternalEventBridge).
5. Infrastructure Layer (Serialization, Persistence & Re-Assembly Wiring)
The outermost implementation ring handles Protobuf persistence, SQL/in-memory stores, external connectors, and—critically—re-assembling every decomposed Artifact Type into a live system.
Protobuf Schema, ProtoConverters & Serialization Adapters (#29–#33)
GLUE Problem solved: Protects Akka Persistence Typed event journals with schema-evolved ScalaPB Protobuf messages, converters, EventAdapter/SnapshotAdapter, and DomainProtoSerializer with explicit ClassTag registries.
// infrastructure/persistence/FundOrderEventAdapter.scala
class FundOrderEventAdapter extends EventAdapter[Event, pb.FundOrderEventPO] with FundOrderProtoConverters {
override def manifest(event: Event): String = "FundOrderEventPO"
override def toJournal(event: Event): pb.FundOrderEventPO = encodeFundOrderEventPO(event)
override def fromJournal(envelope: pb.FundOrderEventPO, manifest: String): EventSeq[Event] =
EventSeq.single(decodeFundOrderEventPO(envelope))
}
Repository Impl, ReadSide DDL & PolicyDlqBury (#12 / #24)
GLUE Problem solved: Emits SQL CREATE TABLE IF NOT EXISTS DDLs (<View>ReadsideSchema), ScalikeJDBC upsert repositories (<View>RepositoryImpl), aggregate repository sharding adapters, and PolicyDlqBury writing dead-letter rows to kn_projection_dlq.
Outbound Connectors & Effect Implementations (#25)
GLUE Problem solved: Supplies default runnable adapters (DefaultOutboundConnectors, InMemoryStore) and handwritten extension points (*ConnectorImpl, *EffectPortImpl).
Bootstrap Traits (#47 / #38b / #38c / #38d / #59 policy-bootstrap)
GLUE Problem solved: Isolates Akka cluster initialization ceremonies into composable traits (<Agg>Bootstrap, <View>ReadsideBootstrap, PolicyOn<Cmd>Bootstrap, SagaCoordinatorBootstrap) using EventSourcedBehavior and ShardedDaemonProcess.
// infrastructure/bootstrap/FundQuotaBootstrap.scala
EventSourcedBehavior[Command, Event, State](
persistenceId = PersistenceId.ofUniqueId(persistenceId),
emptyState = initial,
commandHandler = FundQuotaAggregate.commandHandler(hosts),
eventHandler = FundQuotaEventHandler.apply
).withTagger(_ => Set(tag))
.withRetention(RetentionCriteria.snapshotEvery(numberOfEvents = 100, keepNSnapshots = 3))
.eventAdapter(new FundQuotaEventAdapter)
.snapshotAdapter(new FundQuotaSnapshotAdapter)
Guice DI Wiring & ApplicationBootstrap (#38 / #50)
GLUE Problem solved: The global re-assembly switch chaining Google Guice and Play Framework modules in four clear hops:
BootstrapModule: Binds<Agg>RepositoryImpl, loadsHandwrittenBindingsModuleviainstallOptionalModule, and marksApplicationBootstrap.asEagerSingleton().HandwrittenBindingsModule(handwritten/never overwritten): InstallsGeneratedBindingsModuleand<Context>ProjectionModule, offering a single safe override point for custom production bindings.GeneratedBindingsModule: Closes all DI loops (L1 Computations → .Noop,L2 Computations → *Impl,L3 StoryHandler → *Impl,ReadsideRepositoryImpl,PolicyDlqSink,PolicyOn<Cmd>Semantics,HttpRouter).ApplicationBootstrap: Mixes in every<Agg>Bootstrap,<View>ReadsideBootstrap, andPolicyOn<Cmd>Bootstraptrait and initializes them at startup.
6. Interfaces & Service Runtime Layer (HTTP, 5-Layer Authz & Build Scaffold)
The service interface shell translates HTTP traffic, enforces 5-layer authorization, and packages the complete Play/sbt build.
5-Layer Authz PEP/PDP & ApiDto (#49)
KERNEL SEAM Problem solved: Standardizes Principal, AuthzDecisionQuery, AuthorizationPort, EntitlementPort, CSRF checks, and HTTP error status mapping.
HTTP Controllers, AggregateStateApiController & CommandDsl (#34–#36)
GLUE Problem solved: Thin Play controllers merge request inputs and Principal, invoke <Story>Handler, and enforce post-handler RowScope anti-IDOR verification (403 FORBIDDEN_ROW_SCOPE on mismatch), alongside #34 AggregateStateApiController read probes.
// interfaces/http/CashFundPurchaseController.scala
handler.handle(appReq, externs, effects) match {
case Left(err) => HttpResponse(status = HttpStatusMapper.statusForRejection(err.code), body = Map("ok" -> false, "code" -> err.code))
case Right(res) =>
if (rowScopeDenied) HttpResponse(status = 403, body = Map("ok" -> false, "code" -> "FORBIDDEN_ROW_SCOPE"))
else HttpResponse(status = 200, body = withView)
}
ServiceContract, ServiceLoader, PlayHttpBridge & Routes (#37 / #38)
GLUE Problem solved: Enforces startup endpoint pinning (requireInstalled) and routes HTTP verbs/paths (conf/routes) through PlayHttpBridge.
Project Scaffold & Runtime Configs (#39)
GLUE Problem solved: Emits build.sbt (mounting both generated-scaffold/scala and handwritten/scala plus sbt-protoc/ScalaPB), conf/serialization.conf, and self-contained conf/dev.conf.
7. Verification & BDD Oracle Layer (Executable Proof Gates)
Verification artifacts are first-class generated outputs—never afterthought prose.
Gherkin Features, Executable Oracles & Locked Manifest (#53)
KERNEL Problem solved: Materializes Z3 witnesses into Gherkin .feature files, TypeScript node:test specs, ScalaTest AnyFunSuite suites, and a SHA-256 anti-tamper lock manifest.sha256.json.
Mutation Gate & Onion DIP Gate (#54)
GLUE Problem solved: verify-v2 runs automated checkOnionDipBoundaries (verifying 0 inward-dependency violations across domain/ and application/) plus mutation-gate.mjs (requiring 100% mutant kill rates on guarded rules).
8. End-to-End Walkthrough: Tracing a Bank Wealth Purchase Through All 5 Onion Layers
Tracing bank-wealth-demo alongside the newly wired Reactive Policy loop shows how all 60 families (64 artifact kinds) collaborate at runtime:
- HTTP Ingress (Layer 4):
POST /api/v1/bankwealth/bank-cash-submit-port/submitentersCashFundPurchaseControllerviaPlayHttpBridgeandHttpRouter, authenticated and role-checked byApiDto(#49). - Application Seam (Layer 2):
CashFundPurchaseImplimplementsCashFundPurchaseHandler(#51), checksExternPorts.requestExists&payloadMatchesOriginalagainstCallerContractSpec((principal, clientRequestId), forbiddinginvestorAccountId), then executespinanddispatch. - Write Sharding → Domain Kernel (Layer 2 Glue → Layer 1 Kernel): Commands hit
FundQuotaAggregate.EntityKeyandFundQuotaBehaviors→FundQuotaRules.ReserveSubscriptionQuotaRule(#45) →Money(#1) arithmetic → emitsSubscriptionQuotaReserved(#2) →FundQuotaEventHandler(#3) updates state →FundQuotaAxioms.checkAxioms(#48) validatesALWAYSinvariants. - Journal & Reactive Consumers (Layer 3 + Layer 2):
FundQuotaEventAdapter+DomainProtoSerializer(#29–#33) persist Protobuf payloads and tags;ShardedDaemonProcessfeeds both:- ReadSide:
BankOrderReadsideProjectionHandler(#28) upserts rows viaBankOrderReadsideRepositoryImpl(#24) forBankOrderViewQueryService(#15); - Reactive Policy:
PolicyOn<Cmd>RunnerfeedsPolicyMachine.run→PolicyOn<Cmd>.DefaultSemantics.decide→PolicyOn<Cmd>Mechanics(EntityKey.ask), inspecting everyLeft(err)viadisposeto either buryPermanentfailures inPolicyDlqBuryor trigger at-least-once retries onRetryablefailures.
- ReadSide:
9. Artifact Type Upgrade Sync Contract & Future Target Blueprint (Rust / Axum)
To guarantee this map never drifts from metarch-truthsrc, CI enforces a machine-verifiable lock chain (documented in docs/artifact-map-authoring-contract.md):
- Upstream Catalog Hash (
metarch-truthsrc):lib/v2/surface-registry.mjsscansgenerators/*/generator.json(schemaVersion === "truthsrc.product-generator/v2"), hashesartifactFamilyCoverage,producers, andartifactKindsintocatalogSha256, and embedstargetArtifactCatalogsinexportCapabilitiesLock(). - Site Lock Synchronization:
tools/sync-site-facts.mjs --writesnapshotstargetArtifactCatalogsintoassets/data/facts.lock.json;assets/data/artifact-maps.lock.jsonmaps every target generator to its bilingual articleslug,catalogSha256,truthsrcShort, andbankShort. - CI Gate (
site_ci.yml):sync-site-facts.mjs --checkfails whenevermetarch-truthsrcupgrades any Artifact Type (changingcatalogSha256) or adds a new target generator without updating the corresponding bilingual map article (embedding matchingtruthsrcShort+ 12-charcatalogSha256) and lock files.
Future Target Requirement: Rust (rust-cqrs-axum-service:2) Blueprint
As introduced in our Extending metarch-truthsrc Code Generators guide, whenever a future Rust target generator (Axum + Tokio + SQLx + Prost + Tonic) is added under generators/, it MUST ship a companion bilingual Onion Architecture Map covering this exact 5-layer mapping:
| Onion Layer | Play / Scala Role | Rust Target Artifact Type (e.g. rust-cqrs-axum-service:2) | Role |
|---|---|---|---|
| Layer 1 · Domain Core | Money, *Entity, *EventHandler, *Rules, *Axioms, *Computations | Zero-dependency crate domain: Newtypes / rust_decimal, enum Event, fn apply(state, ev), fn handle(state, params) -> Result<Vec<Event>, DomainError>, trait Computations | KERNEL + SEAM |
| Layer 2 · Application | *Protocol, *StoryPort, *ReadsideProjection, PolicyMachine | Crate application: command/reply DTOs, async trait Repository, typed CallerContract, ReadsideProjector, and PolicyMachine::run effect loop | KERNEL + SEAM + GLUE |
| Layer 3 · Infrastructure | *.proto / *Serializer / *RepositoryImpl / GeneratedBindingsModule | Crate infrastructure: prost `.proto` codecs, sqlx Outbox/ReadSide/DLQ implementations, AppState DI container, and worker tasks | GLUE |
| Layer 4 · Interfaces & Runtime | *Controller, ApiDto, HttpRouter, build.sbt | Crate interfaces + binary entrypoint: axum::Router, Tower 5-layer Authz extractors, RowScope response guard, and Cargo.toml workspace | KERNEL + GLUE |
| Layer 5 · Verification | Gherkin + ScalaTest + Mutation Gate + DIP Check | cargo test BDD oracles, cargo-mutants guard kill gate, and workspace dependency checks forbidding tokio/axum/sqlx inside domain | KERNEL + GLUE |