Version lock: metarch-truthsrc @ ab207e7 (scala-cqrs-play-service:2 · catalogSha256: 156b224f3614 · 60 unified families / 14 producers / 64 artifactKinds) · bank-wealth-demo @ b5cadc0 · Controlled by assets/data/artifact-maps.lock.json and the sync-site-facts CI gate (cross-referenced with F-32 / F-33 on 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

60
Unified Families (54 Baseline + Policy #55–#60)
14
Registered Producers (manifest-backed)
64
Governed Artifact Kinds (Full Pipeline)
0
Onion DIP Violations (126 Scala files checked)

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:

RoleBadgeAuthority & OriginChange DriverRepresentative Artifact Types
Critical Business Kernel (Kernel)KERNELDerived strictly from YAML structures + EARS behavioral specs + Z3 mathematical proofs (4A zero-token codegen or verified contract)Domain rule changesValueObject, Entity, EventHandler, Rules, Axioms, PolicyOn<Cmd>
Isolation Boundary (Seam & Port)SEAMCompiler-derived typed interfaces (Port / Protocol / CallerContractSpec / Semantics) caging non-deterministic L2/L3/Infra code inside handwritten/ @cloze slotsCapability boundary changes*Computations, *Protocol, *Repository, *Port.scala, ApplyEventSemantics, PolicyDlqSink
Wiring & Runtime Plumbing (Glue)GLUEZero new business decisions — adapts Kernel and Seam contracts onto Akka Typed, ClusterSharding, Play HTTP, ScalaPB, and Guice DITarget 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?

  1. Ownership Separation (Overwrite vs. Never-Overwrite): Keeping compiler-owned FundOrderRules.scala separate from human/AI-owned FundOrderComputationsImpl.scala allows generated-scaffold/ vs. handwritten/ to live side by side and re-assemble cleanly via GeneratedBindingsModule without regeneration ever clobbering handwritten @cloze logic.
  2. Dual-Channel Verification (4A vs. 4B): Deterministic linear rules and folds stay in #45 Rules / #3 EventHandler / #48 Axioms; non-linear math and multi-step orchestration stay behind #51 ApplicationPort and *Computations supervised by locked BDD oracles.
  3. Cross-Stack Portability (Scala/Play → Rust/Axum): Once Kernel contracts and Port seams are separated, porting metarch-truthsrc to 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.

FIGURE 01 · PLAY CQRS (scala-cqrs-play-service:2 @ 8950ba3) ONION ARTIFACT TYPE MAP (CLICKABLE)
LAYER 4 · INTERFACES & PLAY RUNTIME HTTP Entry · 5-Layer Authz · Build Scaffold LAYER 3 · INFRASTRUCTURE & DI RE-ASSEMBLY LAYER 2 · APPLICATION LAYER LAYER 1 · DOMAIN CORE Zero Akka / Play / JDBC Deps KERNEL + SEAM · Standalone scalac #1 Value Objects Money · ExactTypes #2 Domain Entity State · sealed Event #3 EventHandler (State, Evt) => State #4/#5/#45 Rules Z3 Guard + Postcond #48 Axioms/Replay ALWAYS Invariants #14/#51 Compute L1 Noop / L2 Impl #7/#11 Protocol Command · Reply · Params #6/#8–#10 Behaviors EntityKey · Rules Host #12 Repo Port Repository trait SEAM · DIP #51/#52 Story ExternPorts/Impl KERNEL + SEAM #15/#26+ ReadSide View · Query · Proj #55–#60 Policy Event ⇒ Cmd Loop #13/#40–#46 Saga Cross-Agg · Bridge #29–#33 Protobuf Codec *.proto · SnapAdapter #12 / #24 Repo & DLQ ScalikeJDBC · DLQ Bury #25 Connectors & Effects Outbound · ServerSnapshot #38/#47/#50 DI & Boot ★ Guice + PolicyBootstrap #49 ApiDto & 5-Layer Authz Principal · PEP/PDP · RowScope KERNEL + SEAM #34–#36 Controllers & DSL PlayController · StateApi GLUE · HTTP → AppPort #37–#38 ServiceLoader ServiceContract · HttpBridge GLUE · Routes & Contract #39 Project Scaffold build.sbt · dev.conf · Akka GLUE · ScalaPB + Play DIP → ← DIP Teal = Kernel · Amber = Seam · Neutral = Glue · Dark ★ = DI Hub · → Inward DIP LAYER 5 · VERIFICATION & BDD ORACLE GATE (Independent Audit Bar · Never Enters Production Runtime) #53 Gherkin Features · TS/Scala Oracles · manifest.sha256.json KERNEL · Locked Oracles & Bidirectional Witness · Domain / App / HTTP #54 Mutation Gate · Onion DIP Gate · sbt/scalac Partition GLUE · 100% Guard Mutation Kill + 0 DIP Violations + Boundary Audit
Figure 1: Concentric five-layer Onion Architecture Artifact Type Map for Play CQRS (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:

FIGURE 02 · DECOMPOSITION & RE-ASSEMBLY WIRING TOPOLOGY (GUICE DI + AKKA RUNTIME)
1. PLAY / GUICE DI MODULE TREE (STATIC WIRING) BootstrapModule (modules/) Binds AggRepositories → HandwrittenBindingsModule → eager singleton ApplicationBootstrap HandwrittenBindingsModule (handwritten/) Safe zone · install(GeneratedBindingsModule) + install(<Ctx>ProjectionModule) GeneratedBindingsModule • L1 Computations → .Noop • L2 Computations → *Impl • L3 StoryHandler → *Impl • PolicySemantics + DlqSink • HttpRouter + ToolGates <Ctx>ProjectionModule #26 ApplyEventSemantics → ApplyEventSemanticsImpl handwritten/ ReadModel custom row fold hooks 2. AKKA RUNTIME BOOTSTRAP & REACTIVE LOOP (DYNAMIC) ApplicationBootstrap (*Bootstrap Traits) init<Agg>Aggregate + init<View>ReadsideProjection + initPolicyOn<Cmd>Projection ClusterSharding Write EventSourcedBehavior Behaviors → Rules + Fold EventAdapter → Protobuf ShardedDaemonProcess eventsByTag(ReadJournal) ① ReadSide → ViewTable ② PolicyMachine → ask PlayHttpBridge → StoryController → StoryImpl 5-Layer Authz (PEP/PDP + RowScope) → ExternPorts → EffectsPort → AggregateProtocol SagaCoordinatorBootstrap + #46 ExternalAuthority
Figure 2: Static assembly walks 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 + DefaultSemantics with zero Akka dependencies;
  • #56 policy-mechanics (PolicyOn<Cmd>Mechanics.scala): Sends commands via ClusterSharding.entityRefFor(EntityKey, entityId).ask[Reply], translating Refused(err) into Left(err);
  • #57 policy-handler (PolicyOn<Cmd>Handler.scala): Akka Handler[EventEnvelope[Any]] shell decoding events into PolicyEnvelope and delegating to PolicyMachine.run;
  • #58 policy-runner (PolicyOn<Cmd>Runner.scala): Owns EventSourcedProvider.eventsByTag and ProjectionId;
  • #60 projection-runtime-mechanism (PolicyMachine.scala / FailureVerdict.scala / PolicyEnvelope.scala / PolicyDlqBury.scala): Shared 4-stage execution pipeline inspecting every Left(err) inside Future.traverse(commands)(execute) — burying Permanent verdicts via PolicyDlqSink.bury (advancing offsets) while failing the Future on Retryable verdicts (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:

  1. BootstrapModule: Binds <Agg>RepositoryImpl, loads HandwrittenBindingsModule via installOptionalModule, and marks ApplicationBootstrap .asEagerSingleton().
  2. HandwrittenBindingsModule (handwritten/ never overwritten): Installs GeneratedBindingsModule and <Context>ProjectionModule, offering a single safe override point for custom production bindings.
  3. GeneratedBindingsModule: Closes all DI loops (L1 Computations → .Noop, L2 Computations → *Impl, L3 StoryHandler → *Impl, ReadsideRepositoryImpl, PolicyDlqSink, PolicyOn<Cmd>Semantics, HttpRouter).
  4. ApplicationBootstrap: Mixes in every <Agg>Bootstrap, <View>ReadsideBootstrap, and PolicyOn<Cmd>Bootstrap trait 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:

  1. HTTP Ingress (Layer 4): POST /api/v1/bankwealth/bank-cash-submit-port/submit enters CashFundPurchaseController via PlayHttpBridge and HttpRouter, authenticated and role-checked by ApiDto (#49).
  2. Application Seam (Layer 2): CashFundPurchaseImpl implements CashFundPurchaseHandler (#51), checks ExternPorts.requestExists & payloadMatchesOriginal against CallerContractSpec ((principal, clientRequestId), forbidding investorAccountId), then executes pin and dispatch.
  3. Write Sharding → Domain Kernel (Layer 2 Glue → Layer 1 Kernel): Commands hit FundQuotaAggregate.EntityKey and FundQuotaBehaviors → FundQuotaRules.ReserveSubscriptionQuotaRule (#45) → Money (#1) arithmetic → emits SubscriptionQuotaReserved (#2) → FundQuotaEventHandler (#3) updates state → FundQuotaAxioms.checkAxioms (#48) validates ALWAYS invariants.
  4. Journal & Reactive Consumers (Layer 3 + Layer 2): FundQuotaEventAdapter + DomainProtoSerializer (#29–#33) persist Protobuf payloads and tags; ShardedDaemonProcess feeds both:
    • ReadSide: BankOrderReadsideProjectionHandler (#28) upserts rows via BankOrderReadsideRepositoryImpl (#24) for BankOrderViewQueryService (#15);
    • Reactive Policy: PolicyOn<Cmd>Runner feeds PolicyMachine.run → PolicyOn<Cmd>.DefaultSemantics.decide → PolicyOn<Cmd>Mechanics (EntityKey.ask), inspecting every Left(err) via dispose to either bury Permanent failures in PolicyDlqBury or trigger at-least-once retries on Retryable failures.

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):

  1. Upstream Catalog Hash (metarch-truthsrc): lib/v2/surface-registry.mjs scans generators/*/generator.json (schemaVersion === "truthsrc.product-generator/v2"), hashes artifactFamilyCoverage, producers, and artifactKinds into catalogSha256, and embeds targetArtifactCatalogs in exportCapabilitiesLock().
  2. Site Lock Synchronization: tools/sync-site-facts.mjs --write snapshots targetArtifactCatalogs into assets/data/facts.lock.json; assets/data/artifact-maps.lock.json maps every target generator to its bilingual article slug, catalogSha256, truthsrcShort, and bankShort.
  3. CI Gate (site_ci.yml): sync-site-facts.mjs --check fails whenever metarch-truthsrc upgrades any Artifact Type (changing catalogSha256) or adds a new target generator without updating the corresponding bilingual map article (embedding matching truthsrcShort + 12-char catalogSha256) 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 LayerPlay / Scala RoleRust Target Artifact Type (e.g. rust-cqrs-axum-service:2)Role
Layer 1 · Domain CoreMoney, *Entity, *EventHandler, *Rules, *Axioms, *ComputationsZero-dependency crate domain: Newtypes / rust_decimal, enum Event, fn apply(state, ev), fn handle(state, params) -> Result<Vec<Event>, DomainError>, trait ComputationsKERNEL + SEAM
Layer 2 · Application*Protocol, *StoryPort, *ReadsideProjection, PolicyMachineCrate application: command/reply DTOs, async trait Repository, typed CallerContract, ReadsideProjector, and PolicyMachine::run effect loopKERNEL + SEAM + GLUE
Layer 3 · Infrastructure*.proto / *Serializer / *RepositoryImpl / GeneratedBindingsModuleCrate infrastructure: prost `.proto` codecs, sqlx Outbox/ReadSide/DLQ implementations, AppState DI container, and worker tasksGLUE
Layer 4 · Interfaces & Runtime*Controller, ApiDto, HttpRouter, build.sbtCrate interfaces + binary entrypoint: axum::Router, Tower 5-layer Authz extractors, RowScope response guard, and Cargo.toml workspaceKERNEL + GLUE
Layer 5 · VerificationGherkin + ScalaTest + Mutation Gate + DIP Checkcargo test BDD oracles, cargo-mutants guard kill gate, and workspace dependency checks forbidding tokio/axum/sqlx inside domainKERNEL + GLUE

Further Reading