From fee8c3fb2ab847f950a21e00d1a9ad2215666bcb Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Thu, 15 Oct 2026 18:11:09 +1300
Subject: [PATCH 01/55] Prepare complete selected owner publication closure
---
.../api-contracts.md | 2 +
.../api-contracts.md | 2 +
.../game-design-service/version-control.md | 10 +
.../game-logic-service/api-contracts.md | 2 +-
...ame-authoring-publishing-and-activation.md | 8 +
...ation_selected_source_intake_command.proto | 30 +
...ntity_selected_source_intake_command.proto | 30 +
.../build.gradle.kts | 14 +
...onEmptySelectedSourceIntakeRepository.java | 556 ++++++++
...ationEmptySelectedSourceIntakeService.java | 167 +++
...lectedSourceIntakeTerminalReadService.java | 80 ++
...tedEmptyPublicationDigestGrpcReceiver.java | 103 ++
...SelectedEmptyPublicationDigestService.java | 199 +++
...electedSourceIntakeCommandGrpcService.java | 101 ++
...edSourceIntakeTerminalReadGrpcService.java | 53 +
.../V1003__selected_empty_source_intake.sql | 334 +++++
...tySelectedSourceIntakePostgresFixture.java | 463 +++++++
...edSourceIntakePostgresIntegrationTest.java | 378 ++++++
...takeRepositoryPostgresIntegrationTest.java | 553 ++++++++
...tedSourceIntakeServiceIntegrationTest.java | 323 +++++
...rminalReadMtlsPostgresIntegrationTest.java | 455 +++++++
...ionEmptySelectedSourceIntakeValueTest.java | 292 ++++
...mptyPublicationDigestGrpcReceiverTest.java | 173 +++
...tedSourceIntakeCommandGrpcServiceTest.java | 146 ++
...edSourceIntakeTerminalReadServiceTest.java | 253 ++++
...onSelectedSourceIntakeCommandEvidence.java | 171 +++
...nSelectedSourceIntakeCommandGrpcCodec.java | 177 +++
...tySelectedSourceIntakeCommandEvidence.java | 171 +++
...ySelectedSourceIntakeCommandGrpcCodec.java | 193 +++
...thoredWorldReleaseAttestationEvidence.java | 71 +-
...GameDesignPublicationTerminalEvidence.java | 6 +-
...ectedSourceIntakeCommandGrpcCodecTest.java | 213 +++
...edWorldReleaseAttestationSelectorTest.java | 91 ++
...ectedSourceIntakeCommandGrpcCodecTest.java | 279 ++++
...nPublicationTerminalEvidenceCodecTest.java | 123 ++
...tionSelectedSourceIntakeCommandClient.java | 189 +++
...titySelectedSourceIntakeCommandClient.java | 187 +++
...SelectedSourceIntakeCommandClientTest.java | 145 ++
...ctedSourceIntakeCommandClientMtlsTest.java | 511 +++++++
...ourceIntakeCommandClientLifecycleTest.java | 274 ++++
...ectedSourceIntakeTerminalReadFixtures.java | 562 ++++++++
.../build.gradle.kts | 14 +
...tyEmptySelectedSourceIntakeRepository.java | 917 +++++++++++++
...ntityEmptySelectedSourceIntakeService.java | 205 +++
...lectedSourceIntakeTerminalReadService.java | 83 ++
...etainedAuthoredActorCoreSourceService.java | 216 +++
...tedEmptyPublicationDigestGrpcReceiver.java | 103 ++
...SelectedEmptyPublicationDigestService.java | 186 +++
...electedSourceIntakeCommandGrpcService.java | 101 ++
...edSourceIntakeTerminalReadGrpcService.java | 53 +
..._fresh_selected_empty_source_catalogue.sql | 1074 +++++++++++++++
.../RetainedActorIdentityIntegrationTest.java | 14 +-
...ntakeMigrationPostgresIntegrationTest.java | 222 ++++
...tySelectedSourceIntakePostgresFixture.java | 468 +++++++
...takeRepositoryPostgresIntegrationTest.java | 516 ++++++++
...ptySelectedSourceIntakeRepositoryTest.java | 89 ++
...yEmptySelectedSourceIntakeServiceTest.java | 47 +
...nedAuthoredActorCoreSourceServiceTest.java | 264 ++++
...mptyPublicationDigestGrpcReceiverTest.java | 145 ++
...tedSourceIntakeCommandGrpcServiceTest.java | 232 ++++
...edSourceIntakeTerminalReadServiceTest.java | 295 +++++
services/game-design-service/build.gradle.kts | 21 +-
.../gamedesign/client/GameLogicClient.java | 183 ++-
...lectedDraftPublicationReadGrpcService.java | 114 ++
.../dto/PublishedReleaseBundleDto.java | 6 +-
.../SelectedDraftControlPlaneDigest.java | 121 ++
...ctedDraftPublicationDigestReadService.java | 336 +++++
.../StartSessionLaunchDescriptorProducer.java | 6 +-
...SessionTemplateAssociationReadService.java | 3 +-
.../service/PublishGateService.java | 13 +
.../CompleteLaunchBindingServiceImpl.java | 28 +
.../service/impl/PublishGateServiceImpl.java | 235 +++-
.../impl/PublishedReleaseBundleContract.java | 115 +-
.../PublishedReleaseBundleServiceImpl.java | 7 +-
.../VersionPublishCommandServiceImpl.java | 40 +-
...nerPublicationPostgresIntegrationTest.java | 1177 +++++++++++++++++
...edDraftPublicationReadGrpcServiceTest.java | 297 +++++
.../publication/GameLogicClientTest.java | 358 +++++
.../SelectedDraftControlPlaneDigestTest.java | 216 +++
...DraftPublicationDigestReadServiceTest.java | 325 +++++
...rtSessionLaunchDescriptorProducerTest.java | 19 +
...ionTemplateAssociationReadServiceTest.java | 20 +
.../CompleteLaunchBindingServiceImplTest.java | 82 ++
.../impl/PublishGateServiceImplTest.java | 413 +++++-
.../PublishedReleaseBundleContractTest.java | 68 +
...PublishedReleaseBundleServiceImplTest.java | 112 +-
.../VersionPublishCommandServiceImplTest.java | 188 ++-
.../GameLogicDraftDesignDigestService.java | 13 +-
...GameLogicDraftDesignDigestServiceImpl.java | 30 +-
.../service/impl/GameLogicGrpcService.java | 56 +-
...tionDigestReadPostgresIntegrationTest.java | 275 ++++
...LogicDraftDesignDigestServiceImplTest.java | 30 +-
.../impl/GameLogicGrpcServiceTest.java | 256 +++-
.../world-management-service/build.gradle.kts | 16 +
...onicalInstanceLifecycleReadRepository.java | 3 +-
...electedFullPublicationEvidenceFixture.java | 565 ++++++++
...alInstanceLifecycleReadRepositoryTest.java | 73 +-
97 files changed, 18913 insertions(+), 241 deletions(-)
create mode 100644 protos/automation-scripting/v1/automation_selected_source_intake_command.proto
create mode 100644 protos/entity-management/v1/entity_selected_source_intake_command.proto
create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java
create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java
create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java
create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiver.java
create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java
create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcService.java
create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcService.java
create mode 100644 services/automation-scripting-service/src/main/resources/db/migration/V1003__selected_empty_source_intake.sql
create mode 100644 services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresFixture.java
create mode 100644 services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java
create mode 100644 services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java
create mode 100644 services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java
create mode 100644 services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java
create mode 100644 services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java
create mode 100644 services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java
create mode 100644 services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcServiceTest.java
create mode 100644 services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadServiceTest.java
create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandEvidence.java
create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandGrpcCodec.java
create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandEvidence.java
create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodec.java
create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodecTest.java
create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AutomationSelectedSourceIntakeCommandGrpcCodecTest.java
create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClient.java
create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClient.java
create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java
create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java
create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandClientLifecycleTest.java
create mode 100644 services/common-test-support/src/testFixtures/java/net/firedevops/firemud/testsupport/entity/EntitySelectedSourceIntakeTerminalReadFixtures.java
create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java
create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java
create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java
create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceService.java
create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiver.java
create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java
create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcService.java
create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcService.java
create mode 100644 services/entity-management-service/src/main/resources/db/migration/V1011__fresh_selected_empty_source_catalogue.sql
create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java
create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java
create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java
create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepositoryTest.java
create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeServiceTest.java
create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceServiceTest.java
create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java
create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcServiceTest.java
create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadServiceTest.java
create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java
create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java
create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java
create mode 100644 services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java
create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java
create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
create mode 100644 services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java
create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java
diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md
index 6839cc3dc8..6c560f05ef 100644
--- a/design/architecture/microservices/automation-scripting-service/api-contracts.md
+++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md
@@ -12,6 +12,8 @@ For `ListScriptHandoffEvents`, the target command identity is the complete Comma
## Implementation Status
+The prepared empty selected-source command and immutable receipt/digest reads remain standalone, unregistered and unqualified. Forward V1003 retains empty selected source over the current combined Automation/Saga parent; it neither attests arbitrary scripts nor enables evaluation, dispatch or runtime publication. Its publication consumption follows the [canonical Game Design profile](../game-design-service/version-control.md#selected-full-publication-profile); current controlled-input proof limits and pending cross-owner qualification belong to the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation).
+
This section records the current implementation boundary only. The API sections below remain normative target contracts; a current implementation note does not relax those contracts, and a target-only surface must not be inferred as shipped.
The unsupported NPC formation REST family has been removed from the runtime and authoritative OpenAPI. Formation operations remain available only through the authenticated internal gRPC control-plane path; no REST caller can supply a tenant or NPC identifier to reach the formation service. The gRPC path retains its existing global admin guard, which is neither tenant-bound `tenantAdmin` authorization nor Entity-owned NPC namespace/ownership proof; formation behavior remains partial until those target checks are implemented and proven.
diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md
index 8d5e80bed4..40efc3b992 100644
--- a/design/architecture/microservices/entity-management-service/api-contracts.md
+++ b/design/architecture/microservices/entity-management-service/api-contracts.md
@@ -6,6 +6,8 @@ The authoritative REST schema source lives in [../../../../services/entity-manag
## Implementation Status
+The prepared selected-source command and immutable receipt/digest reads remain standalone, unregistered and unqualified. Forward V1011 adds the empty selected source catalogue over the current combined Entity/Saga parent, retaining explicit family and equipment evidence; this does not enable arbitrary authored templates, placement or gameplay admission. Its publication consumption follows the [canonical Game Design profile](../game-design-service/version-control.md#selected-full-publication-profile); current controlled-input proof limits and pending cross-owner qualification belong to the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation).
+
Entity V1003–V1010 and the manually composed, unregistered assignment/receipt/roster services are passive source and storage preparation. The canonical roster proto has no runtime handler, authenticated client, peer interceptor, or bean registration in this boundary. Legacy adapters and consumers retain develop behavior. The qualified immutable donor contains the complete migration tail; focused qualification of this recut, including the default combined Entity/Saga locations and actual-parent upgrade, is recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). Neither storage fixtures nor discovery references establish actual owner provenance, fresh Account eligibility, gameplay admission, or PLAY. Authenticated owner handoff and real caller/execution replacement remain required.
The target read semantics are: any policy other than `PRESEEDED_ONLY` is non-authorizing and returns `FAILED_PRECONDITION`; `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. PRESEEDED_ONLY actor display names are nonblank, trimmed, control-free text bounded to 100 Unicode code points, matching the accepted assignment core. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes the exact request/account/selected-character/target/snapshot bindings, and returns `FAILED_PRECONDITION` if the snapshot is stale or the selected actor is absent from it. It also returns the original non-nil assignment operation UUID and immutable intent digest from the unique matching committed `ASSIGNED` `PRESEEDED_ONLY` `PLAYER` receipt. Entity resolves that receipt only for the exact account, selected actor, complete expected target, current owner counters, and published owner-proof digest; zero or multiple matches disclose no reference, and readback must match the same receipt. The response is persisted owner evidence, not a newly minted identity, an admission grant, or proof that Account eligibility remains current. Both methods require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. Context `playable_state_scope` is exactly the text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay.
diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md
index de2be5395b..069f79abff 100644
--- a/design/architecture/microservices/game-design-service/version-control.md
+++ b/design/architecture/microservices/game-design-service/version-control.md
@@ -6,6 +6,8 @@ Game Design is the canonical authored-history, publication-coordination, release
## Implementation Status
+The selected-full owner closure is prepared as unqualified source: exact selected digest collection and retained Game Logic reads feed the existing guarded release storage, while public fresh/PENDING publication remains denied. All new owner components remain standalone and unregistered, and the default Game Logic Spring composition remains denied. No fresh schema-4 writer/readback or native cross-owner passing result is claimed; current scope and qualification limits are recorded in the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation).
+
The recipient-intake preparation adds an unregistered Account-authenticated read of all six selected source families. Its required branding source owner uses existing V1007 storage, and command snapshot parsing converges on the shared typed contract while retaining owner-local capture context. No retained source is inferred or upgraded to complete. Qualification and selected-owner producer dependencies remain in the [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation).
Standalone Template source/reference owners, selected-publication reservation and the exact original StartSession template read are prepared over existing guarded storage. They remain unregistered; qualified owner-local storage does not supply genuine Account, World or immutable-release authority. Current source, proof and retention limitations belong to [the authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-template-publication-and-original-launch-reads).
@@ -36,6 +38,14 @@ Game Design retains the exact selected publication operation, source captures an
Original retained three-frame v1 bytes remain readable with their original row and request checksums. They do not establish inventory completeness and cannot authorize a new operation reservation, capture or terminal seal after the v2 storage guards apply. Forward migrations do not rewrite those bytes or fabricate source history. Forward migrations also preserve original `game-design-reviewed-draft-base/v1` rows and their exact bytes. Fresh reviewed-base v2 evidence binds the original policy, command and ordinary asset genesis, or the exact synchronized snapshots and complete owner vector for an authored base. An old review without ordinary asset lineage remains readable and cannot authorize a fresh source write. The database independently reconstructs fresh review bytes from the retained owner records before accepting the claim. Source-family inventories, exact Game Logic and World associations, normalized template references, original Account owner schema and candidate projection remain separate retained owner facts; installing their tables and guards does not produce those facts or enable publication.
+### Selected Full Publication Profile
+
+Fresh selected-full publication uses Game Design attestation schema 4 (`v4`) and one complete ordered participant vector: `WORLD_MANAGEMENT` digest schema 4, `ENTITY_MANAGEMENT` schema 3, `GAME_LOGIC` schema 1, `AUTOMATION_SCRIPTING` schema 6 and `GAME_DESIGN_CONTROL_PLANE` schema 2. Every participant must report successful evidence for the same exact full-Version row and selected authored commit, with no script-patch/base-Version scope, missing participant, duplicate, reordered participant or substituted digest schema. Game Logic additionally supplies its independently scoped ability-schema digest. A legacy or partial vector cannot be relabeled as this profile.
+
+The selected collector binds the canonical tenant UUID, exact full-Version row, original publication request and derived workflow to the immutable selected operation. World evidence must retain its exact selected selector and complete inventory, and the collector must independently read the actual retained recipient and Game Logic receipts; a generic publication Account binding, identifier lookup, latest owner state or copied response cannot replace recipient-bound evidence. Game Design's participant covers all six immutable selected source families. The current Entity recipient profile requires explicit zero counts for all 23 supported source catalogue families and equipment `NOT_APPLICABLE`; the Automation recipient profile is empty-only and cannot attest arbitrary authored scripts. Owner-local source and receipt validation remains mandatory before accepting either digest.
+
+Fresh writes and schema-4 readback use the selected publication gate and exact immutable bundle/World joins. Historical attestation schemas 1–3 preserve their original bytes and only their already-supported reads and retries. They do not acquire missing source completeness, recipient receipts or schema-4 authority, and this profile does not widen consumers that do not already support an older schema. The existing V1020 storage owner is used without rewriting retained history or introducing a new Game Design migration. Publication evidence does not grant activation, actor placement or delivery authority.
+
## Approach
- Each asset revision already stores author and timestamp metadata.
diff --git a/design/architecture/microservices/game-logic-service/api-contracts.md b/design/architecture/microservices/game-logic-service/api-contracts.md
index 1c9ef57cab..d2f24a2288 100644
--- a/design/architecture/microservices/game-logic-service/api-contracts.md
+++ b/design/architecture/microservices/game-logic-service/api-contracts.md
@@ -6,7 +6,7 @@ This document defines the Game Logic Service REST and gRPC surfaces, exposure cl
- The current Game Logic adapters still return `shared.v1.ErrorDetail` for many failures and record `grpc.app_error`; that is implementation drift and a migration/proof gap, not a second contract.
- Causal-read status is target-only: the complete `CausalReadFence` and participant-proof enforcement described below are not current behavior. The live `ResolveLook` request/proto and World/Entity adapters remain floor-free, so protobuf propagation, adapter evidence, and focused causal-floor proof are implementation gaps.
-- The publish-gate digest handler enforces the distinct workload/method authorization and exact Game Design publication binding implemented by `PublicationReadGuard` and `PublicationDigestRequestBinding` (tenant, version scope, stable publish request, derived workflow identity, and request digest), with focused denial and response-scope checks. For a full-version request, the owner digest fails closed because Game Logic has no owner-local manifest and provenance sufficient to attest the version's rule inputs; it does not attest those inputs as an empty manifest. End-to-end full-version publication therefore remains blocked. The target workload, tenant/scope/request/workflow/digest context, exact response identity comparison, and denial proof are canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity).
+- The prepared publish-gate adapter can read the exact retained owner terminal, selected source and manifest through `GameLogicPublicationSourceReadService`, preserving the original authorization and both manifest/ability digests. The default Spring composition and the no-receipt lookup remain denied; the standalone adapter and focused proof are unqualified and establish no genuine upstream authority or publication enablement. The canonical selected contract is owned by [Game Design Version Control](../game-design-service/version-control.md#selected-full-publication-profile), with source and composition limits in the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation).
### Player execution context
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index 688cace40c..76f70c0609 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -6,6 +6,14 @@ This is a non-normative implementation tracker for game authoring, publishing, a
## Current Status
+### Selected-full owner publication preparation
+
+The source candidate prepares complete selected-owner publication consumption under the [canonical selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile). It reuses the actual parent World closure producer, adds its full-profile consumer mapping, and composes the selected Game Design digest read/collector with independently retained Entity, Automation and Game Logic receipts. The Game Logic adapter reads the exact retained terminal, selected source and manifest through the existing owner repository and returns both manifest and ability projections; its default Spring composition remains denied. Private selected writer mechanics use the exact canonical selection/request binding and selected gate. Public Game Design fresh/PENDING publication remains denied. Existing Game Design V1020 storage is reused; no Game Design migration is added.
+
+Entity's new V1011 prepares the freshly founded empty selected source catalogue and its complete explicit family/equipment evidence; Automation's new V1003 prepares empty selected source retention. Both are forward additions over their current combined service/Saga parents. Their command/read transports and owner services remain standalone and unregistered. These are bounded empty-source components, not arbitrary Entity authoring, script publication or runtime rule execution. Inherited Account migration history and numbering are unchanged by this candidate.
+
+Current source and focused proof are unqualified and unrun. The native cross-owner composition is in preparation; no passing fresh full-profile writer, immutable readback or authenticated cross-owner result is claimed. Unit carriers, source/provenance inputs, creator/issuer/environment and PKI remain explicitly controlled where used. Retained historical release bytes keep their existing scoped read/retry meaning and are not upgraded into the new profile. Genuine creator, issuer, environment, immutable release and continuous-protection authority, runtime placement and operational delivery remain unavailable; all four genuine Gameplay handoffs remain open and broader Unit 1B stays paused. Consolidated source, migration, native composition, formatting and documentation qualification belongs to the lane orchestrator.
+
### Selected template publication and original launch reads
The prepared source adds owner-local Template configuration genesis, synchronized revision/application, selected source capture and normalized tenant reference-phase owners over the already guarded tables. `SelectedDraftPublicationOwner` retains the exact selection, pending attempt, complete source capture and immutable template/World relation in one caller-owned writable transaction; existing operation bytes are never upgraded and old descriptor or reference provenance is not backfilled. The original StartSession template-association read authenticates Game Session and independently verifies Account’s exact redeemed operation before its read-only snapshot. It accepts only current selector-bound release-v2 evidence for the configured path and refuses older non-selector releases rather than fabricating later bundles. These components are unregistered and add no migration or runtime enabling flag.
diff --git a/protos/automation-scripting/v1/automation_selected_source_intake_command.proto b/protos/automation-scripting/v1/automation_selected_source_intake_command.proto
new file mode 100644
index 0000000000..2454b5a8b7
--- /dev/null
+++ b/protos/automation-scripting/v1/automation_selected_source_intake_command.proto
@@ -0,0 +1,30 @@
+syntax = "proto3";
+
+package automation_scripting.v1;
+option java_package = "net.firedevops.firemud.automationscripting.v1";
+option java_multiple_files = true;
+
+import "world-management/v1/world_selected_draft_publication_freeze_service.proto";
+
+// Standalone and unregistered. Authenticated same-namespace Game Design may retain its exact
+// Account-authorized selected-source intake after the exact World freeze has committed.
+service AutomationSelectedSourceIntakeCommandService {
+ rpc RetainSelectedSource(RetainSelectedSourceRequest)
+ returns (RetainSelectedSourceResponse);
+}
+
+message RetainSelectedSourceRequest {
+ uint32 schema_version = 1;
+ string target_namespace = 2;
+ string transport_request_id = 3;
+ bytes original_intake_authorization_binding = 4;
+ string intake_authorization_digest = 5;
+ world_management.v1.BeginVersionPublicationFreezeRequest freeze_request = 6;
+ world_management.v1.BeginVersionPublicationFreezeResponse freeze_acknowledgement = 7;
+}
+
+message RetainSelectedSourceResponse {
+ RetainSelectedSourceRequest request = 1;
+ bytes committed_empty_receipt = 2;
+ string receipt_digest = 3;
+}
diff --git a/protos/entity-management/v1/entity_selected_source_intake_command.proto b/protos/entity-management/v1/entity_selected_source_intake_command.proto
new file mode 100644
index 0000000000..a29f838b30
--- /dev/null
+++ b/protos/entity-management/v1/entity_selected_source_intake_command.proto
@@ -0,0 +1,30 @@
+syntax = "proto3";
+
+package entity_management.v1;
+option java_package = "net.firedevops.firemud.entitymanagement.v1";
+option java_multiple_files = true;
+
+import "world-management/v1/world_selected_draft_publication_freeze_service.proto";
+
+// Standalone and unregistered. Authenticated same-namespace Game Design may retain its exact
+// Account-authorized selected Entity inputs after the exact World freeze has committed.
+service EntitySelectedSourceIntakeCommandService {
+ rpc RetainSelectedEntitySource(RetainSelectedEntitySourceRequest)
+ returns (RetainSelectedEntitySourceResponse);
+}
+
+message RetainSelectedEntitySourceRequest {
+ uint32 schema_version = 1;
+ string target_namespace = 2;
+ string transport_request_id = 3;
+ bytes original_intake_authorization_binding = 4;
+ string intake_authorization_digest = 5;
+ world_management.v1.BeginVersionPublicationFreezeRequest freeze_request = 6;
+ world_management.v1.BeginVersionPublicationFreezeResponse freeze_acknowledgement = 7;
+}
+
+message RetainSelectedEntitySourceResponse {
+ RetainSelectedEntitySourceRequest request = 1;
+ bytes committed_empty_receipt = 2;
+ string receipt_digest = 3;
+}
diff --git a/services/automation-scripting-service/build.gradle.kts b/services/automation-scripting-service/build.gradle.kts
index 50a061526d..e907342a8e 100644
--- a/services/automation-scripting-service/build.gradle.kts
+++ b/services/automation-scripting-service/build.gradle.kts
@@ -10,3 +10,17 @@ plugins {
dependencies {
compileOnly(libs.spotbugs.annotations)
}
+
+// Export only owner classes for composed proofs; application and Flyway resources stay local.
+val automationClassesProofJar by tasks.registering(Jar::class) {
+ archiveClassifier.set("classes-proof")
+ dependsOn(tasks.named("classes"))
+ from(sourceSets.main.get().output.classesDirs)
+}
+
+val automationClassesProof by configurations.creating {
+ isCanBeConsumed = true
+ isCanBeResolved = false
+ extendsFrom(configurations.implementation.get())
+ outgoing.artifact(automationClassesProofJar)
+}
diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java
new file mode 100644
index 0000000000..d8c33f3cc7
--- /dev/null
+++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java
@@ -0,0 +1,556 @@
+package net.firedevops.firemud.automationscripting.sourceintake;
+
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.jooq.impl.DSL;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/**
+ * Unregistered persistence boundary for immutable, freshly founded empty Automation receipts.
+ *
+ *
The source-family census is deliberately direct: absent associations never prove empty
+ * storage. This bounded schema only creates empty-source associations, so any row matching one of
+ * them is also a contradiction; rows without such a positive association are unqualified and deny a
+ * new founding.
+ */
+public final class AutomationEmptySelectedSourceIntakeRepository {
+ private static final String ASSOCIATION = "automation_empty_selected_source_association";
+ private static final String RECEIPT = "automation_empty_selected_source_receipt";
+ private static final String RESERVATION = "automation_empty_source_numeric_key_reservation";
+
+ private static final String READ_RECEIPT =
+ "SELECT a.target_namespace, a.operation_id, a.fence_id, a.intake_request_id, "
+ + "a.canonical_tenant_id, a.canonical_version_id, a.selected_commit_id, "
+ + "a.source_revision_id, a.source_revision_order, a.local_tenant_key, "
+ + "a.local_version_key, a.request_digest, a.authorization_binding_digest, "
+ + "a.receipt_digest, a.associated_at, r.request_digest, r.receipt_digest, "
+ + "r.receipt_bytes, r.retained_at FROM "
+ + ASSOCIATION
+ + " a LEFT JOIN "
+ + RECEIPT
+ + " r ON r.target_namespace = a.target_namespace "
+ + "AND r.intake_request_id = a.intake_request_id "
+ + "WHERE a.target_namespace = ? AND a.intake_request_id = ?";
+
+ private final DSLContext dsl;
+
+ public AutomationEmptySelectedSourceIntakeRepository(DSLContext dsl) {
+ this.dsl = Objects.requireNonNull(dsl, "dsl");
+ }
+
+ /** Reads only a committed receipt; absence is not interpreted as abort or terminal settlement. */
+ public Optional read(
+ String targetNamespace, UUID intakeRequestId) {
+ requireNoAmbientOwnerSql("Automation source receipt read");
+ requireReadKey(targetNamespace, intakeRequestId);
+ return readValidated(dsl, targetNamespace, intakeRequestId);
+ }
+
+ /**
+ * Resolves the one immutable selected-empty receipt for a canonical tenant and Game Design
+ * Version row. Every association in the tenant prefix is fully read back before its retained
+ * original TargetProof is considered; owner-local numeric keys are not publication identity.
+ */
+ public AutomationEmptySelectedSourceIntakeReceipt readPublicationScope(
+ String targetNamespace, UUID canonicalTenantId, long gameDesignVersionRowId) {
+ requireNoAmbientOwnerSql("Automation publication receipt read");
+ requirePublicationScopeKey(targetNamespace, canonicalTenantId, gameDesignVersionRowId);
+
+ return dsl.transactionResult(
+ configuration -> {
+ DSLContext tx = DSL.using(configuration);
+ tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY");
+ var associations =
+ tx.fetch(
+ "SELECT canonical_version_id, intake_request_id FROM "
+ + ASSOCIATION
+ + " WHERE target_namespace = ? AND canonical_tenant_id = ? "
+ + "ORDER BY canonical_version_id",
+ targetNamespace,
+ canonicalTenantId);
+ if (associations.isEmpty()) {
+ throw new IllegalStateException(
+ "Automation selected-empty publication receipt is unavailable");
+ }
+
+ var matches = new ArrayList();
+ for (Record association : associations) {
+ UUID associatedCanonicalVersionId = association.get(0, UUID.class);
+ UUID intakeRequestId = association.get(1, UUID.class);
+ if (associatedCanonicalVersionId == null || intakeRequestId == null) {
+ throw new IllegalStateException(
+ "Automation publication association identity is corrupt");
+ }
+ AutomationEmptySelectedSourceIntakeReceipt receipt =
+ readValidated(tx, targetNamespace, intakeRequestId)
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Automation publication association has no committed receipt"));
+ var target = receipt.authorizationBinding().selected().target();
+ if (!canonicalTenantId.equals(receipt.canonicalTenantId())
+ || !associatedCanonicalVersionId.equals(receipt.canonicalVersionId())
+ || !canonicalTenantId.equals(target.canonicalTenantId())
+ || !associatedCanonicalVersionId.equals(target.canonicalVersionId())) {
+ throw new IllegalStateException(
+ "Automation publication association differs from the retained selected target");
+ }
+ if (target.gameDesignVersionRowId() == gameDesignVersionRowId) {
+ matches.add(receipt);
+ }
+ }
+ if (matches.size() != 1) {
+ throw new IllegalStateException(
+ "Automation selected-empty publication scope is missing or ambiguous");
+ }
+ return matches.get(0);
+ });
+ }
+
+ /**
+ * Reads the original committed receipt for an exact finalized Account authorization. A missing
+ * result remains absence; it is never converted into an abort or another terminal value.
+ */
+ public Optional readCommittedTerminal(
+ SelectedOwnerIntakeAuthorizationBinding originalBinding) {
+ Objects.requireNonNull(originalBinding, "original Account authorization binding is required");
+ if (originalBinding.owner() != Owner.AUTOMATION_SCRIPTING
+ || !"account-automation-intake-authorization/v1".equals(originalBinding.schema())
+ || !"AUTOMATION_INTAKE_RETENTION".equals(originalBinding.purpose())) {
+ throw new IllegalArgumentException("Exact original Automation authorization is required");
+ }
+ requireNoAmbientOwnerSql("Automation source terminal read");
+ requireReadKey(originalBinding.targetNamespace(), originalBinding.intakeRequestId());
+ var receipt =
+ readValidated(dsl, originalBinding.targetNamespace(), originalBinding.intakeRequestId());
+ if (receipt.isPresent()
+ && !Arrays.equals(
+ originalBinding.canonicalBytes(), receipt.orElseThrow().authorizationBindingBytes())) {
+ throw new IntakeConflictException(
+ "Automation committed receipt differs from the complete original authorization");
+ }
+ return receipt;
+ }
+
+ /**
+ * Persists one fresh empty-source receipt in an independent local transaction, then reads it back
+ * after commit using a separate non-transactional owner read.
+ */
+ public AutomationEmptySelectedSourceIntakeReceipt retainFresh(
+ SelectedOwnerEmptySourceInputs inputs, String requestDigest) {
+ Objects.requireNonNull(inputs, "validated selected empty-source inputs are required");
+ SelectedOwnerIntakeAuthorizationBinding binding = inputs.authorizationBinding();
+ String expectedDigest =
+ AutomationEmptySelectedSourceIntakeReceipt.requestDigest(
+ binding.targetNamespace(),
+ binding,
+ inputs.worldInventoryReadEvidence().request().freezeEvidence());
+ if (!expectedDigest.equals(requestDigest)) {
+ throw new IllegalArgumentException("Automation source intake request digest differs");
+ }
+ if (binding.owner() != Owner.AUTOMATION_SCRIPTING) {
+ throw new IllegalArgumentException("Automation owner evidence is required");
+ }
+ requireNoAmbientOwnerSql("Automation source intake transaction");
+
+ AutomationEmptySelectedSourceIntakeReceipt committed =
+ dsl.transactionResult(
+ configuration -> {
+ DSLContext tx = DSL.using(configuration);
+ tx.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
+ lockAllocatorAndAssociations(tx);
+ lockSourceFamilies(tx);
+
+ // This is the exact request/operation/scope phase of the lock order. A competing
+ // local founder has already completed its source census before these rows are read.
+ var previous =
+ readValidated(tx, binding.targetNamespace(), binding.intakeRequestId());
+ if (previous.isPresent()) {
+ AutomationEmptySelectedSourceIntakeReceipt receipt = previous.orElseThrow();
+ receipt.requireSameInputs(inputs);
+ return receipt;
+ }
+ requireNoPriorScopeOrOperation(tx, binding);
+
+ Census census = censusAllSourceFamilies(tx);
+ census.requireFreshFoundingAllowed();
+
+ long maximumOccupiedKey = maximumOccupiedNumericKey(tx);
+ long localTenantKey = Math.addExact(maximumOccupiedKey, 1L);
+ long localVersionKey = Math.addExact(maximumOccupiedKey, 2L);
+ Census selectedScope =
+ censusSelectedNumericScope(tx, localTenantKey, localVersionKey);
+ selectedScope.requireSelectedScopeEmpty();
+
+ reserveCanonicalKey(tx, "TENANT", localTenantKey);
+ reserveCanonicalKey(tx, "VERSION", localVersionKey);
+ OffsetDateTime retainedAt =
+ requiredScalar(tx, "SELECT CURRENT_TIMESTAMP", OffsetDateTime.class)
+ .withOffsetSameInstant(ZoneOffset.UTC);
+ AutomationEmptySelectedSourceIntakeReceipt receipt =
+ AutomationEmptySelectedSourceIntakeReceipt.create(
+ inputs,
+ localTenantKey,
+ localVersionKey,
+ requestDigest,
+ census.scriptsRows(),
+ census.eventBindingRows(),
+ census.patchBaseBindingRows(),
+ census.unqualifiedScriptsRows(),
+ census.unqualifiedEventBindingRows(),
+ census.unqualifiedPatchBaseBindingRows(),
+ census.emptyAssociatedScriptsRows(),
+ census.emptyAssociatedEventBindingRows(),
+ census.emptyAssociatedPatchBaseBindingRows(),
+ selectedScope.scriptsRows(),
+ selectedScope.eventBindingRows(),
+ selectedScope.patchBaseBindingRows(),
+ retainedAt);
+
+ insertAssociation(tx, receipt, retainedAt);
+ insertReceipt(tx, receipt, retainedAt);
+ return receipt;
+ });
+
+ AutomationEmptySelectedSourceIntakeReceipt readBack =
+ read(committed.targetNamespace(), committed.intakeRequestId())
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Committed Automation source receipt is unavailable"));
+ if (!Arrays.equals(committed.canonicalBytes(), readBack.canonicalBytes())
+ || !committed.receiptDigest().equals(readBack.receiptDigest())
+ || !committed.requestDigest().equals(readBack.requestDigest())) {
+ throw new IllegalStateException("Committed Automation source receipt readback differs");
+ }
+ return readBack;
+ }
+
+ private static void lockAllocatorAndAssociations(DSLContext tx) {
+ tx.execute(
+ "LOCK TABLE "
+ + RESERVATION
+ + ", "
+ + ASSOCIATION
+ + ", "
+ + RECEIPT
+ + " IN SHARE ROW EXCLUSIVE MODE");
+ }
+
+ private static void lockSourceFamilies(DSLContext tx) {
+ // Fixed order shared with the source-owner allocation protocol.
+ tx.execute(
+ "LOCK TABLE script_event_bindings, script_patch_base_bindings, scripts IN SHARE MODE");
+ }
+
+ private static void requireNoPriorScopeOrOperation(
+ DSLContext tx, SelectedOwnerIntakeAuthorizationBinding binding) {
+ Record prior =
+ tx.fetchOne(
+ "SELECT intake_request_id FROM "
+ + ASSOCIATION
+ + " WHERE target_namespace = ? AND (canonical_tenant_id = ? "
+ + "OR canonical_version_id = ? OR operation_id = ?)",
+ binding.targetNamespace(),
+ binding.tenantId(),
+ binding.versionId(),
+ binding.operationId());
+ if (prior != null) {
+ throw new IntakeConflictException(
+ "Automation canonical scope or owner operation is already associated");
+ }
+ }
+
+ private static Census censusAllSourceFamilies(DSLContext tx) {
+ long scripts = count(tx, "SELECT COUNT(*) FROM scripts");
+ long eventBindings = count(tx, "SELECT COUNT(*) FROM script_event_bindings");
+ long patchBaseBindings = count(tx, "SELECT COUNT(*) FROM script_patch_base_bindings");
+
+ long unqualifiedScripts =
+ count(
+ tx,
+ "SELECT COUNT(*) FROM scripts s WHERE NOT EXISTS (SELECT 1 FROM "
+ + ASSOCIATION
+ + " a WHERE a.local_tenant_key = s.tenant_id "
+ + "AND a.local_version_key = s.base_version_id)");
+ long unqualifiedEventBindings =
+ count(
+ tx,
+ "SELECT COUNT(*) FROM script_event_bindings b WHERE NOT EXISTS (SELECT 1 FROM "
+ + ASSOCIATION
+ + " a WHERE a.local_tenant_key = b.tenant_id "
+ + "AND a.local_version_key = b.base_version_id)");
+ long unqualifiedPatchBaseBindings =
+ count(
+ tx,
+ "SELECT COUNT(*) FROM script_patch_base_bindings b WHERE NOT EXISTS (SELECT 1 FROM "
+ + ASSOCIATION
+ + " a WHERE a.local_tenant_key = "
+ + "automation_source_positive_numeric_key(b.tenant_id) "
+ + "AND a.local_version_key = b.base_version_id)");
+
+ return new Census(
+ scripts,
+ eventBindings,
+ patchBaseBindings,
+ unqualifiedScripts,
+ unqualifiedEventBindings,
+ unqualifiedPatchBaseBindings,
+ scripts - unqualifiedScripts,
+ eventBindings - unqualifiedEventBindings,
+ patchBaseBindings - unqualifiedPatchBaseBindings);
+ }
+
+ private static Census censusSelectedNumericScope(DSLContext tx, long tenantKey, long versionKey) {
+ long scripts =
+ count(
+ tx,
+ "SELECT COUNT(*) FROM scripts WHERE tenant_id = ? OR base_version_id = ?",
+ tenantKey,
+ versionKey);
+ long eventBindings =
+ count(
+ tx,
+ "SELECT COUNT(*) FROM script_event_bindings WHERE tenant_id = ? "
+ + "OR base_version_id = ?",
+ tenantKey,
+ versionKey);
+ long patchBaseBindings =
+ count(
+ tx,
+ "SELECT COUNT(*) FROM script_patch_base_bindings WHERE "
+ + "automation_source_positive_numeric_key(tenant_id) = ? "
+ + "OR base_version_id = ?",
+ tenantKey,
+ versionKey);
+ return new Census(scripts, eventBindings, patchBaseBindings, 0L, 0L, 0L, 0L, 0L, 0L);
+ }
+
+ private static long maximumOccupiedNumericKey(DSLContext tx) {
+ return requiredScalar(
+ tx,
+ "SELECT COALESCE(MAX(occupied_key), 0) FROM ("
+ + "SELECT numeric_key AS occupied_key FROM "
+ + RESERVATION
+ + " UNION ALL SELECT tenant_id FROM scripts"
+ + " UNION ALL SELECT base_version_id FROM scripts WHERE base_version_id IS NOT NULL"
+ + " UNION ALL SELECT tenant_id FROM script_event_bindings"
+ + " UNION ALL SELECT base_version_id FROM script_event_bindings "
+ + "WHERE base_version_id IS NOT NULL"
+ + " UNION ALL SELECT automation_source_positive_numeric_key(tenant_id) "
+ + "FROM script_patch_base_bindings"
+ + " UNION ALL SELECT base_version_id FROM script_patch_base_bindings"
+ + ") AS occupied",
+ Long.class);
+ }
+
+ private static void reserveCanonicalKey(DSLContext tx, String kind, long key) {
+ int inserted =
+ tx.execute(
+ "INSERT INTO "
+ + RESERVATION
+ + " (key_kind, numeric_key, claim_kind) VALUES (?, ?, 'CANONICAL_EMPTY_SOURCE')",
+ kind,
+ key);
+ if (inserted != 1) {
+ throw new IntakeConflictException("Automation source numeric key was not reserved");
+ }
+ }
+
+ private static void insertAssociation(
+ DSLContext tx,
+ AutomationEmptySelectedSourceIntakeReceipt receipt,
+ OffsetDateTime retainedAt) {
+ int inserted =
+ tx.execute(
+ "INSERT INTO "
+ + ASSOCIATION
+ + " (target_namespace, operation_id, fence_id, intake_request_id, "
+ + "canonical_tenant_id, canonical_version_id, selected_commit_id, "
+ + "source_revision_id, source_revision_order, local_tenant_key, "
+ + "local_version_key, request_digest, authorization_binding_digest, "
+ + "receipt_digest, associated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "
+ + "CAST(? AS TIMESTAMPTZ))",
+ receipt.targetNamespace(),
+ receipt.operationId(),
+ receipt.fenceId(),
+ receipt.intakeRequestId(),
+ receipt.canonicalTenantId(),
+ receipt.canonicalVersionId(),
+ receipt.selectedCommitId(),
+ receipt.sourceRevisionId(),
+ receipt.sourceRevisionOrder(),
+ receipt.localTenantKey(),
+ receipt.localVersionKey(),
+ receipt.requestDigest(),
+ receipt.authorizationBindingDigest(),
+ receipt.receiptDigest(),
+ retainedAt);
+ if (inserted != 1) {
+ throw new IntakeConflictException("Automation source scope association was not inserted");
+ }
+ }
+
+ private static void insertReceipt(
+ DSLContext tx,
+ AutomationEmptySelectedSourceIntakeReceipt receipt,
+ OffsetDateTime retainedAt) {
+ int inserted =
+ tx.execute(
+ "INSERT INTO "
+ + RECEIPT
+ + " (target_namespace, intake_request_id, request_digest, receipt_digest, "
+ + "receipt_bytes, retained_at) VALUES (?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ))",
+ receipt.targetNamespace(),
+ receipt.intakeRequestId(),
+ receipt.requestDigest(),
+ receipt.receiptDigest(),
+ receipt.canonicalBytes(),
+ retainedAt);
+ if (inserted != 1) {
+ throw new IntakeConflictException("Automation source receipt was not inserted");
+ }
+ }
+
+ private static Optional readValidated(
+ DSLContext context, String namespace, UUID requestId) {
+ Record record = context.fetchOne(READ_RECEIPT, namespace, requestId);
+ if (record == null) {
+ return Optional.empty();
+ }
+ byte[] receiptBytes = record.get(17, byte[].class);
+ if (receiptBytes == null) {
+ throw new IllegalStateException("Automation source association has no retained receipt");
+ }
+ AutomationEmptySelectedSourceIntakeReceipt receipt =
+ AutomationEmptySelectedSourceIntakeReceipt.fromStored(receiptBytes);
+ if (!Objects.equals(record.get(0, String.class), receipt.targetNamespace())
+ || !Objects.equals(record.get(1, UUID.class), receipt.operationId())
+ || !Objects.equals(record.get(2, UUID.class), receipt.fenceId())
+ || !Objects.equals(record.get(3, UUID.class), receipt.intakeRequestId())
+ || !Objects.equals(record.get(4, UUID.class), receipt.canonicalTenantId())
+ || !Objects.equals(record.get(5, UUID.class), receipt.canonicalVersionId())
+ || !Objects.equals(record.get(6, UUID.class), receipt.selectedCommitId())
+ || !Objects.equals(record.get(7, UUID.class), receipt.sourceRevisionId())
+ || !Objects.equals(record.get(8, String.class), receipt.sourceRevisionOrder())
+ || !Objects.equals(record.get(9, Long.class), receipt.localTenantKey())
+ || !Objects.equals(record.get(10, Long.class), receipt.localVersionKey())
+ || !Objects.equals(record.get(11, String.class), receipt.requestDigest())
+ || !Objects.equals(record.get(12, String.class), receipt.authorizationBindingDigest())
+ || !Objects.equals(record.get(13, String.class), receipt.receiptDigest())
+ || !Objects.equals(record.get(15, String.class), receipt.requestDigest())
+ || !Objects.equals(record.get(16, String.class), receipt.receiptDigest())
+ || !Objects.equals(
+ record.get(18, OffsetDateTime.class).toInstant(), receipt.retainedAt().toInstant())
+ || !Objects.equals(
+ record.get(14, OffsetDateTime.class).toInstant(), receipt.retainedAt().toInstant())
+ || !Arrays.equals(receipt.canonicalBytes(), receiptBytes)) {
+ throw new IllegalStateException(
+ "Automation source receipt differs from its owner association");
+ }
+ return Optional.of(receipt);
+ }
+
+ private static long count(DSLContext context, String sql, Object... parameters) {
+ long value = requiredScalar(context, sql, Long.class, parameters);
+ if (value < 0L) {
+ throw new IllegalStateException("Automation source census returned an invalid count");
+ }
+ return value;
+ }
+
+ private static T requiredScalar(
+ DSLContext context, String sql, Class valueType, Object... parameters) {
+ Record record = context.fetchOne(sql, parameters);
+ if (record == null) {
+ throw new IllegalStateException("Automation owner query returned no row");
+ }
+ T value = record.get(0, valueType);
+ if (value == null) {
+ throw new IllegalStateException("Automation owner query returned a null value");
+ }
+ return value;
+ }
+
+ private static void requireReadKey(String namespace, UUID requestId) {
+ if (!GrpcPeerIdentity.isValidNamespace(namespace) || requestId == null) {
+ throw new IllegalArgumentException("Automation source receipt lookup identity is required");
+ }
+ DraftAuthorizationFenceBinding.requireUuid(requestId);
+ }
+
+ private static void requirePublicationScopeKey(
+ String namespace, UUID canonicalTenantId, long gameDesignVersionRowId) {
+ if (!GrpcPeerIdentity.isValidNamespace(namespace)
+ || canonicalTenantId == null
+ || new UUID(0L, 0L).equals(canonicalTenantId)
+ || gameDesignVersionRowId <= 0L) {
+ throw new IllegalArgumentException("Automation publication scope identity is required");
+ }
+ }
+
+ private static void requireNoAmbientOwnerSql(String action) {
+ if (TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isSynchronizationActive()) {
+ throw new IllegalStateException(action + " requires no ambient owner SQL");
+ }
+ }
+
+ private record Census(
+ long scriptsRows,
+ long eventBindingRows,
+ long patchBaseBindingRows,
+ long unqualifiedScriptsRows,
+ long unqualifiedEventBindingRows,
+ long unqualifiedPatchBaseBindingRows,
+ long emptyAssociatedScriptsRows,
+ long emptyAssociatedEventBindingRows,
+ long emptyAssociatedPatchBaseBindingRows) {
+ private void requireFreshFoundingAllowed() {
+ if (unqualifiedScriptsRows != 0L
+ || unqualifiedEventBindingRows != 0L
+ || unqualifiedPatchBaseBindingRows != 0L) {
+ throw new UnqualifiedSourceRowsException(
+ "Fresh Automation founding requires a positively owned empty source inventory");
+ }
+ if (emptyAssociatedScriptsRows != 0L
+ || emptyAssociatedEventBindingRows != 0L
+ || emptyAssociatedPatchBaseBindingRows != 0L) {
+ throw new IntakeConflictException(
+ "An existing empty Automation association contains authored source rows");
+ }
+ }
+
+ private void requireSelectedScopeEmpty() {
+ if (scriptsRows != 0L || eventBindingRows != 0L || patchBaseBindingRows != 0L) {
+ throw new IntakeConflictException(
+ "Allocated Automation source scope is not empty across all source families");
+ }
+ }
+ }
+
+ public static class IntakeConflictException extends IllegalStateException {
+ public IntakeConflictException(String message) {
+ super(message);
+ }
+ }
+
+ public static final class UnqualifiedSourceRowsException extends IntakeConflictException {
+ public UnqualifiedSourceRowsException(String message) {
+ super(message);
+ }
+ }
+}
diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java
new file mode 100644
index 0000000000..ebc13edf76
--- /dev/null
+++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java
@@ -0,0 +1,167 @@
+package net.firedevops.firemud.automationscripting.sourceintake;
+
+import java.util.Objects;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
+import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
+import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient;
+import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence;
+import net.firedevops.firemud.common.security.SessionContext;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/**
+ * Unregistered preparation service for authenticated, freshly founded empty Automation scopes.
+ *
+ * Account's HELD reads are point-in-time samples. They do not extend through Automation's local
+ * commit and do not settle the original Account source participation.
+ *
+ *
The shared selected-source value checks exact canonical bytes and typed snapshots for all six
+ * existing Game Design source families. Authenticated Account and World clients establish the
+ * remote read identities and HELD/inventory results; typed integrity alone does not authenticate
+ * either producer or establish continuous source-writer protection.
+ */
+public final class AutomationEmptySelectedSourceIntakeService {
+ private final AutomationEmptySelectedSourceIntakeRepository repository;
+ private final SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient;
+ private final SelectedOwnerWorldInventoryReadClient worldInventoryReadClient;
+
+ public AutomationEmptySelectedSourceIntakeService(
+ AutomationEmptySelectedSourceIntakeRepository repository,
+ SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient,
+ SelectedOwnerWorldInventoryReadClient worldInventoryReadClient) {
+ this.repository = Objects.requireNonNull(repository, "repository");
+ this.authorizationReadClient =
+ Objects.requireNonNull(authorizationReadClient, "authorizationReadClient");
+ this.worldInventoryReadClient =
+ Objects.requireNonNull(worldInventoryReadClient, "worldInventoryReadClient");
+ }
+
+ /**
+ * Returns an exact prior receipt for a lost-response retry, or prepares a fresh retention
+ * attempt. This operation does not create scripts, bindings, runtime markers, or activation
+ * state.
+ */
+ public AutomationEmptySelectedSourceIntakeReceipt retain(
+ String targetNamespace,
+ SelectedOwnerIntakeAuthorizationBinding originalBinding,
+ WorldSelectedDraftPublicationFreezeEvidence exactFreeze) {
+ requireAuthenticatedGameDesignCaller(targetNamespace);
+ requireNoAmbientOwnerSql();
+ requireRequest(targetNamespace, originalBinding, exactFreeze);
+ String requestDigest =
+ AutomationEmptySelectedSourceIntakeReceipt.requestDigest(
+ targetNamespace, originalBinding, exactFreeze);
+
+ // A committed receipt is authoritative for exact lost-response retries, even after Account's
+ // temporary HELD state has subsequently settled. It never implies that an unrecorded request
+ // was aborted.
+ var retained = repository.read(targetNamespace, originalBinding.intakeRequestId());
+ if (retained.isPresent()) {
+ AutomationEmptySelectedSourceIntakeReceipt receipt = retained.orElseThrow();
+ receipt.requireSameRequest(targetNamespace, originalBinding, exactFreeze);
+ return receipt;
+ }
+
+ SelectedOwnerIntakeAuthorizationReadEvidence.Request authorizationReadRequest =
+ SelectedOwnerIntakeAuthorizationReadEvidence.Request.create(
+ targetNamespace, originalBinding);
+ var authorizationEvidence = authorizationReadClient.read(authorizationReadRequest);
+ if (authorizationEvidence == null
+ || !authorizationReadRequest.equals(authorizationEvidence.request())) {
+ throw new IllegalStateException("Account did not echo the exact selected-owner read request");
+ }
+
+ SelectedOwnerWorldInventoryReadEvidence.Request worldReadRequest =
+ SelectedOwnerWorldInventoryReadEvidence.Request.create(
+ targetNamespace, originalBinding, exactFreeze);
+ var worldEvidence = worldInventoryReadClient.read(worldReadRequest);
+ if (worldEvidence == null || !worldReadRequest.equals(worldEvidence.request())) {
+ throw new IllegalStateException("World did not echo the exact selected-owner read request");
+ }
+
+ // This shared value validates only exact evidence integrity, complete supported inbound World
+ // closure, and the typed empty Automation declaration. The authenticated clients above—not
+ // the value itself—supply producer identity and HELD authorization.
+ SelectedOwnerEmptySourceInputs inputs =
+ new SelectedOwnerEmptySourceInputs(originalBinding, worldEvidence);
+
+ // Re-sample HELD after the remote World read to reduce the gap before local commit. This is
+ // only a point-in-time observation: finalized pending Account source participation remains
+ // under its source-writer exclusion guards. This preparation neither extends nor settles or
+ // releases them. Account's separate exact Automation terminal settlement owns that release;
+ // this intake method does not invoke it, and unregistered construction is not activation proof.
+ SelectedOwnerIntakeAuthorizationReadEvidence.Request finalAuthorizationReadRequest =
+ SelectedOwnerIntakeAuthorizationReadEvidence.Request.create(
+ targetNamespace, originalBinding);
+ var finalAuthorizationEvidence = authorizationReadClient.read(finalAuthorizationReadRequest);
+ if (finalAuthorizationEvidence == null
+ || !finalAuthorizationReadRequest.equals(finalAuthorizationEvidence.request())) {
+ throw new IllegalStateException("Account did not echo the exact final HELD read request");
+ }
+
+ AutomationEmptySelectedSourceIntakeReceipt receipt =
+ repository.retainFresh(inputs, requestDigest);
+ receipt.requireSameRequest(targetNamespace, originalBinding, exactFreeze);
+ return receipt;
+ }
+
+ private static void requireAuthenticatedGameDesignCaller(String targetNamespace) {
+ var peer = GrpcPeerIdentity.current();
+ if (peer == null) {
+ throw new SecurityException("Authenticated same-namespace Game Design peer is required");
+ }
+ if (AccountOriginalDraftOrderCredentials.CONTEXT_KEY.get() != null
+ || SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY.get() != null
+ || AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY.get() != null
+ || SessionContext.hasAuthenticatedCallerContext()
+ || !GrpcPeerIdentity.isValidNamespace(targetNamespace)
+ || !targetNamespace.equals(peer.namespace())
+ || !("spiffe://firemud/ns/" + targetNamespace + "/sa/game-design-service")
+ .equals(peer.uri())) {
+ throw new SecurityException(
+ "Selected Automation intake requires the exact same-namespace Game Design peer");
+ }
+ }
+
+ private static void requireRequest(
+ String targetNamespace,
+ SelectedOwnerIntakeAuthorizationBinding binding,
+ WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) {
+ Objects.requireNonNull(binding, "original Account authorization binding is required");
+ Objects.requireNonNull(freezeEvidence, "exact World freeze is required");
+ if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)
+ || !targetNamespace.equals(binding.targetNamespace())
+ || binding.owner() != Owner.AUTOMATION_SCRIPTING
+ || !binding.schema().equals("account-automation-intake-authorization/v1")
+ || !binding.purpose().equals("AUTOMATION_INTAKE_RETENTION")) {
+ throw new IllegalArgumentException(
+ "Fresh Automation intake requires its exact finalized Account owner binding");
+ }
+ var freeze = freezeEvidence.request();
+ if (!targetNamespace.equals(freeze.targetNamespace())
+ || !binding.tenantId().equals(freeze.canonicalTenantId())
+ || !binding.versionId().equals(freeze.canonicalVersionId())
+ || !binding
+ .selected()
+ .equals(freeze.accountBinding().input().selection().selectedCommit())) {
+ throw new IllegalArgumentException(
+ "Automation owner binding differs from the exact selected World freeze");
+ }
+ }
+
+ private static void requireNoAmbientOwnerSql() {
+ if (TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isSynchronizationActive()) {
+ throw new IllegalStateException(
+ "Account and World evidence reads must run outside Automation owner SQL");
+ }
+ }
+}
diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java
new file mode 100644
index 0000000000..8c4b867d75
--- /dev/null
+++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java
@@ -0,0 +1,80 @@
+package net.firedevops.firemud.automationscripting.sourceintake;
+
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import java.util.Objects;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.security.SessionContext;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Standalone Account-only lookup over Automation's immutable selected-source receipt. */
+public final class AutomationEmptySelectedSourceIntakeTerminalReadService {
+ private final AutomationEmptySelectedSourceIntakeRepository repository;
+ private final String namespace;
+
+ public AutomationEmptySelectedSourceIntakeTerminalReadService(
+ AutomationEmptySelectedSourceIntakeRepository repository, String namespace) {
+ this.repository = Objects.requireNonNull(repository, "repository");
+ if (!GrpcPeerIdentity.isValidNamespace(namespace)) {
+ throw new IllegalArgumentException("Canonical namespace required");
+ }
+ this.namespace = namespace;
+ }
+
+ /** Called by the transport before request decoding so unauthorized peers never reach a lookup. */
+ void requireAuthenticatedAccountCaller() {
+ if (SessionContext.hasAuthenticatedCallerContext()) {
+ throw Status.PERMISSION_DENIED.asRuntimeException();
+ }
+ var peer = GrpcPeerIdentity.current();
+ if (peer == null) {
+ throw Status.UNAUTHENTICATED.asRuntimeException();
+ }
+ if (!namespace.equals(peer.namespace())
+ || !"account-service".equals(peer.service())
+ || !("spiffe://firemud/ns/" + namespace + "/sa/account-service").equals(peer.uri())) {
+ throw Status.PERMISSION_DENIED.asRuntimeException();
+ }
+ }
+
+ public AutomationSelectedSourceIntakeTerminalReadEvidence read(
+ AutomationSelectedSourceIntakeTerminalReadEvidence.Request request) {
+ requireAuthenticatedAccountCaller();
+ Objects.requireNonNull(request, "terminal-read request is required");
+ if (!namespace.equals(request.targetNamespace())) {
+ throw Status.PERMISSION_DENIED.asRuntimeException();
+ }
+ if (TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isSynchronizationActive()) {
+ throw Status.FAILED_PRECONDITION.asRuntimeException();
+ }
+
+ final AutomationEmptySelectedSourceIntakeReceipt receipt;
+ try {
+ receipt =
+ repository
+ .readCommittedTerminal(request.binding())
+ .orElseThrow(() -> Status.NOT_FOUND.asRuntimeException());
+ } catch (StatusRuntimeException denied) {
+ throw denied;
+ } catch (AutomationEmptySelectedSourceIntakeRepository.IntakeConflictException changed) {
+ throw Status.ALREADY_EXISTS
+ .withDescription("Automation receipt differs from the complete original authorization")
+ .asRuntimeException();
+ } catch (RuntimeException corrupt) {
+ throw Status.DATA_LOSS
+ .withDescription("Automation committed receipt is invalid")
+ .asRuntimeException();
+ }
+
+ try {
+ return new AutomationSelectedSourceIntakeTerminalReadEvidence(request, receipt);
+ } catch (IllegalArgumentException invalid) {
+ throw Status.DATA_LOSS
+ .withDescription("Automation receipt differs from its original order")
+ .asRuntimeException();
+ }
+ }
+}
diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiver.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiver.java
new file mode 100644
index 0000000000..ca2788778c
--- /dev/null
+++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiver.java
@@ -0,0 +1,103 @@
+package net.firedevops.firemud.automationscripting.sourceintake;
+
+import io.grpc.stub.StreamObserver;
+import io.micrometer.core.instrument.MeterRegistry;
+import java.util.Objects;
+import net.firedevops.firemud.automationscripting.service.ScriptDesignDigestService.ScriptDraftDesignDigest;
+import net.firedevops.firemud.automationscripting.v1.AutomationScriptingServiceGrpc;
+import net.firedevops.firemud.automationscripting.v1.GetDraftDesignDigestRequest;
+import net.firedevops.firemud.automationscripting.v1.GetDraftDesignDigestResponse;
+import net.firedevops.firemud.common.grpc.GrpcAppErrors;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import net.firedevops.firemud.common.security.AdminAuthorizationException;
+import net.firedevops.firemud.common.security.PublicationReadGuard;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Unregistered native receiver for the selected-empty Automation publication digest path. */
+public final class AutomationSelectedEmptyPublicationDigestGrpcReceiver
+ extends AutomationScriptingServiceGrpc.AutomationScriptingServiceImplBase {
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(AutomationSelectedEmptyPublicationDigestGrpcReceiver.class);
+
+ private final AutomationSelectedEmptyPublicationDigestService digestService;
+ private final PublicationReadGuard publicationReadGuard;
+ private final MeterRegistry meterRegistry;
+
+ public AutomationSelectedEmptyPublicationDigestGrpcReceiver(
+ AutomationSelectedEmptyPublicationDigestService digestService,
+ String configuredNamespace,
+ MeterRegistry meterRegistry) {
+ this.digestService = Objects.requireNonNull(digestService, "digestService");
+ this.publicationReadGuard = PublicationReadGuard.configured(configuredNamespace);
+ this.meterRegistry = Objects.requireNonNull(meterRegistry, "meterRegistry");
+ }
+
+ @Override
+ public void getDraftDesignDigest(
+ GetDraftDesignDigestRequest request,
+ StreamObserver responseObserver) {
+ try {
+ requirePublicationRead();
+ if (request.getScopeCase() != GetDraftDesignDigestRequest.ScopeCase.VERSION_ID) {
+ responseObserver.onNext(
+ error(
+ "UNSUPPORTED_SCOPE",
+ "Automation selected-empty publication supports version_id scope only"));
+ responseObserver.onCompleted();
+ return;
+ }
+ PublicationDigestRequestBinding binding =
+ PublicationDigestRequestBinding.forScope(
+ PublicationDigestRequestBinding.ScopeKind.FULL_VERSION,
+ request.getTenantId(),
+ request.getVersionId(),
+ request.getBaseVersionId(),
+ request.getScriptPatchVersion(),
+ request.getPublishRequestId());
+ binding.validateSupplied(request.getDerivedWorkflowIdentity(), request.getRequestDigest());
+
+ ScriptDraftDesignDigest digest = digestService.getDraftDesignDigest(binding);
+ binding.requireOwnerScope(digest.tenantId(), digest.scopeValue());
+ responseObserver.onNext(
+ GetDraftDesignDigestResponse.newBuilder()
+ .setTenantId(binding.tenantId())
+ .setVersionId(binding.versionId())
+ .setAppliedCommitId(digest.appliedCommitId())
+ .setContentDigest(digest.contentDigest())
+ .setDigestSchemaVersion(digest.digestSchemaVersion())
+ .build());
+ responseObserver.onCompleted();
+ } catch (AdminAuthorizationException denied) {
+ responseObserver.onNext(error("PERMISSION_DENIED", denied.getMessage()));
+ responseObserver.onCompleted();
+ } catch (IllegalArgumentException invalid) {
+ responseObserver.onNext(error("INVALID_ARGUMENT", invalid.getMessage()));
+ responseObserver.onCompleted();
+ } catch (IllegalStateException unavailable) {
+ responseObserver.onNext(error("FAILED_PRECONDITION", unavailable.getMessage()));
+ responseObserver.onCompleted();
+ } catch (RuntimeException failure) {
+ responseObserver.onNext(
+ GetDraftDesignDigestResponse.newBuilder()
+ .setError(
+ GrpcAppErrors.internal(meterRegistry, LOGGER, "GetDraftDesignDigest", failure))
+ .build());
+ responseObserver.onCompleted();
+ }
+ }
+
+ private void requirePublicationRead() {
+ if (publicationReadGuard == null) {
+ throw new AdminAuthorizationException("Publication read authorization is not configured");
+ }
+ publicationReadGuard.requirePublicationRead(
+ PublicationReadGuard.AUTOMATION_SCRIPTING_DIGEST_METHOD);
+ }
+
+ private GetDraftDesignDigestResponse error(String code, String message) {
+ return GetDraftDesignDigestResponse.newBuilder()
+ .setError(GrpcAppErrors.error(meterRegistry, LOGGER, "GetDraftDesignDigest", code, message))
+ .build();
+ }
+}
diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java
new file mode 100644
index 0000000000..cb8f34f820
--- /dev/null
+++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java
@@ -0,0 +1,199 @@
+package net.firedevops.firemud.automationscripting.sourceintake;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.automationscripting.service.ScriptDesignDigestService.ScriptDraftDesignDigest;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+
+/**
+ * Unregistered selected-empty full-version digest reader over Automation's retained owner receipt.
+ */
+public final class AutomationSelectedEmptyPublicationDigestService {
+ public static final int DIGEST_SCHEMA_VERSION = 6;
+ private static final String DIGEST_DOMAIN = "automation-selected-empty-publication-digest/v1";
+
+ private final String configuredNamespace;
+ private final AutomationEmptySelectedSourceIntakeRepository repository;
+
+ public AutomationSelectedEmptyPublicationDigestService(
+ String configuredNamespace, AutomationEmptySelectedSourceIntakeRepository repository) {
+ if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) {
+ throw new IllegalArgumentException("Configured Automation namespace is required");
+ }
+ this.configuredNamespace = configuredNamespace;
+ this.repository = Objects.requireNonNull(repository, "repository");
+ }
+
+ /** Returns a selected-empty digest only for one exact canonical tenant and GD Version row. */
+ public ScriptDraftDesignDigest getDraftDesignDigest(
+ PublicationDigestRequestBinding publicationRequest) {
+ Objects.requireNonNull(publicationRequest, "publication request is required");
+ if (publicationRequest.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) {
+ throw new IllegalArgumentException(
+ "Automation selected-empty publication supports full versions only");
+ }
+ UUID canonicalTenantId = canonicalUuid(publicationRequest.tenantId(), "tenantId");
+ long gameDesignVersionRowId =
+ canonicalPositiveLong(publicationRequest.versionId(), "versionId");
+
+ AutomationEmptySelectedSourceIntakeReceipt receipt =
+ repository.readPublicationScope(
+ configuredNamespace, canonicalTenantId, gameDesignVersionRowId);
+ var target = receipt.authorizationBinding().selected().target();
+ if (!configuredNamespace.equals(receipt.targetNamespace())
+ || !canonicalTenantId.equals(receipt.canonicalTenantId())
+ || !canonicalTenantId.equals(target.canonicalTenantId())
+ || target.gameDesignVersionRowId() != gameDesignVersionRowId
+ || !receipt.canonicalVersionId().equals(target.canonicalVersionId())) {
+ throw new IllegalStateException(
+ "Automation selected-empty receipt differs from publication scope");
+ }
+ requireOriginalPublicationRequest(
+ publicationRequest,
+ canonicalTenantId,
+ gameDesignVersionRowId,
+ receipt.canonicalVersionId(),
+ receipt.selectedCommitId(),
+ receipt.worldInventoryReadEvidence().request().freezeEvidence());
+ if (receipt.authorizationBinding().owner() != Owner.AUTOMATION_SCRIPTING) {
+ throw new IllegalStateException("Automation receipt contains a different owner declaration");
+ }
+ requireEmptyReceipt(receipt);
+
+ SelectedOwnerEmptySourceInputs inputs =
+ new SelectedOwnerEmptySourceInputs(
+ receipt.authorizationBinding(), receipt.worldInventoryReadEvidence());
+ if (inputs.ownerSourceInventoryDeclaration().owner() != Owner.AUTOMATION_SCRIPTING) {
+ throw new IllegalStateException(
+ "Automation receipt has no exact owner inventory declaration");
+ }
+ String inventoryJson = inputs.ownerSourceInventoryDeclaration().inventory().canonicalJson();
+ String contentDigest =
+ contentDigest(
+ canonicalTenantId, gameDesignVersionRowId, receipt.canonicalVersionId(), inventoryJson);
+ return new ScriptDraftDesignDigest(
+ publicationRequest.tenantId(),
+ publicationRequest.versionId(),
+ 0L,
+ receipt.selectedCommitId().toString(),
+ contentDigest,
+ DIGEST_SCHEMA_VERSION);
+ }
+
+ private static void requireOriginalPublicationRequest(
+ PublicationDigestRequestBinding requested,
+ UUID canonicalTenantId,
+ long gameDesignVersionRowId,
+ UUID canonicalVersionId,
+ UUID selectedCommitId,
+ net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence
+ retainedFreeze) {
+ var freezeRequest = retainedFreeze.request();
+ var retainedSelection = freezeRequest.accountBinding().input().selection();
+ var retainedPublicationRequest =
+ PublicationDigestRequestBinding.full(
+ freezeRequest.canonicalTenantId().toString(),
+ Long.toString(gameDesignVersionRowId),
+ freezeRequest.publicationRequestId());
+ if (!canonicalTenantId.equals(freezeRequest.canonicalTenantId())
+ || !canonicalVersionId.equals(freezeRequest.canonicalVersionId())
+ || !selectedCommitId.equals(retainedSelection.selectedCommit().commitId())
+ || !selectedCommitId.toString().equals(retainedFreeze.acknowledgement().appliedCommitId())
+ || requested.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION
+ || !requested.tenantId().equals(retainedPublicationRequest.tenantId())
+ || !requested.versionId().equals(retainedPublicationRequest.versionId())
+ || !requested.publishRequestId().equals(retainedPublicationRequest.publishRequestId())
+ || !requested.derivedWorkflowIdentity()
+ .equals(retainedPublicationRequest.derivedWorkflowIdentity())
+ || !requested.requestDigest().equals(retainedPublicationRequest.requestDigest())) {
+ throw new IllegalStateException(
+ "Automation publication request differs from the original retained World freeze");
+ }
+ }
+
+ static String contentDigest(
+ UUID canonicalTenantId,
+ long gameDesignVersionRowId,
+ UUID canonicalVersionId,
+ String canonicalInventoryJson) {
+ if (gameDesignVersionRowId <= 0L) {
+ throw new IllegalArgumentException("Game Design Version row must be positive");
+ }
+ Objects.requireNonNull(canonicalTenantId, "canonicalTenantId");
+ Objects.requireNonNull(canonicalVersionId, "canonicalVersionId");
+ Objects.requireNonNull(canonicalInventoryJson, "canonicalInventoryJson");
+ ByteArrayOutputStream preimage = new ByteArrayOutputStream();
+ appendSegment(preimage, DIGEST_DOMAIN);
+ appendSegment(preimage, Integer.toString(DIGEST_SCHEMA_VERSION));
+ appendSegment(preimage, canonicalTenantId.toString());
+ appendSegment(preimage, Long.toString(gameDesignVersionRowId));
+ appendSegment(preimage, canonicalVersionId.toString());
+ appendSegment(preimage, canonicalInventoryJson);
+ try {
+ return HexFormat.of()
+ .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray()));
+ } catch (NoSuchAlgorithmException impossible) {
+ throw new IllegalStateException("SHA-256 is unavailable", impossible);
+ }
+ }
+
+ private static void requireEmptyReceipt(AutomationEmptySelectedSourceIntakeReceipt receipt) {
+ if (!"COMMITTED_EMPTY".equals(receipt.outcome())
+ || receipt.scriptsRowCount() != 0L
+ || receipt.eventBindingsRowCount() != 0L
+ || receipt.patchBaseBindingsRowCount() != 0L
+ || receipt.unqualifiedScriptsRowCount() != 0L
+ || receipt.unqualifiedEventBindingsRowCount() != 0L
+ || receipt.unqualifiedPatchBaseBindingsRowCount() != 0L
+ || receipt.emptyAssociatedScriptsRowCount() != 0L
+ || receipt.emptyAssociatedEventBindingsRowCount() != 0L
+ || receipt.emptyAssociatedPatchBaseBindingsRowCount() != 0L
+ || receipt.selectedScopeScriptsRowCount() != 0L
+ || receipt.selectedScopeEventBindingsRowCount() != 0L
+ || receipt.selectedScopePatchBaseBindingsRowCount() != 0L) {
+ throw new IllegalStateException(
+ "Automation selected-empty receipt is incomplete or nonempty");
+ }
+ }
+
+ private static UUID canonicalUuid(String value, String field) {
+ try {
+ UUID parsed = UUID.fromString(value);
+ if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) {
+ throw new IllegalArgumentException(field + " must be a canonical nonzero UUID");
+ }
+ return parsed;
+ } catch (RuntimeException malformed) {
+ throw new IllegalArgumentException(field + " must be a canonical nonzero UUID", malformed);
+ }
+ }
+
+ private static long canonicalPositiveLong(String value, String field) {
+ try {
+ long parsed = Long.parseLong(value);
+ if (parsed <= 0L || !Long.toString(parsed).equals(value)) {
+ throw new IllegalArgumentException(field + " must be a canonical positive decimal");
+ }
+ return parsed;
+ } catch (RuntimeException malformed) {
+ throw new IllegalArgumentException(
+ field + " must be a canonical positive decimal", malformed);
+ }
+ }
+
+ private static void appendSegment(ByteArrayOutputStream output, String value) {
+ byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
+ output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII));
+ output.write(':');
+ output.writeBytes(bytes);
+ }
+}
diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcService.java
new file mode 100644
index 0000000000..af2636c5b4
--- /dev/null
+++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcService.java
@@ -0,0 +1,101 @@
+package net.firedevops.firemud.automationscripting.sourceintake;
+
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import io.grpc.stub.StreamObserver;
+import java.util.Objects;
+import net.firedevops.firemud.automationscripting.v1.AutomationSelectedSourceIntakeCommandServiceGrpc;
+import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceRequest;
+import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceResponse;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandGrpcCodec;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
+import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
+import net.firedevops.firemud.common.security.SessionContext;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Unregistered Game Design command boundary for retaining exact selected Automation inputs. */
+public final class AutomationSelectedSourceIntakeCommandGrpcService
+ extends AutomationSelectedSourceIntakeCommandServiceGrpc
+ .AutomationSelectedSourceIntakeCommandServiceImplBase {
+ private final AutomationEmptySelectedSourceIntakeService owner;
+ private final String namespace;
+
+ public AutomationSelectedSourceIntakeCommandGrpcService(
+ AutomationEmptySelectedSourceIntakeService owner, String namespace) {
+ this.owner = Objects.requireNonNull(owner, "selected-source intake owner is required");
+ if (!GrpcPeerIdentity.isValidNamespace(namespace)) {
+ throw new IllegalArgumentException("configured namespace is invalid");
+ }
+ this.namespace = namespace;
+ }
+
+ @Override
+ public void retainSelectedSource(
+ RetainSelectedSourceRequest request, StreamObserver observer) {
+ try {
+ requireAuthenticatedGameDesignCaller();
+ } catch (StatusRuntimeException denied) {
+ observer.onError(denied);
+ return;
+ }
+ if (!namespace.equals(request.getTargetNamespace())) {
+ observer.onError(Status.PERMISSION_DENIED.asRuntimeException());
+ return;
+ }
+ if (TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isSynchronizationActive()) {
+ observer.onError(Status.FAILED_PRECONDITION.asRuntimeException());
+ return;
+ }
+
+ final AutomationSelectedSourceIntakeCommandEvidence.Request decoded;
+ try {
+ decoded = AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest(request);
+ } catch (RuntimeException malformed) {
+ observer.onError(Status.INVALID_ARGUMENT.asRuntimeException());
+ return;
+ }
+
+ try {
+ var receipt =
+ owner.retain(
+ decoded.targetNamespace(),
+ decoded.originalAuthorizationBinding(),
+ decoded.freezeEvidence());
+ var evidence = new AutomationSelectedSourceIntakeCommandEvidence(decoded, receipt);
+ observer.onNext(AutomationSelectedSourceIntakeCommandGrpcCodec.toResponse(evidence));
+ observer.onCompleted();
+ } catch (StatusRuntimeException denied) {
+ observer.onError(Status.fromCode(denied.getStatus().getCode()).asRuntimeException());
+ } catch (SecurityException denied) {
+ observer.onError(Status.PERMISSION_DENIED.asRuntimeException());
+ } catch (AutomationEmptySelectedSourceIntakeRepository.IntakeConflictException conflict) {
+ observer.onError(Status.ALREADY_EXISTS.asRuntimeException());
+ } catch (IllegalArgumentException | IllegalStateException unavailable) {
+ observer.onError(Status.FAILED_PRECONDITION.asRuntimeException());
+ } catch (RuntimeException failure) {
+ observer.onError(Status.INTERNAL.asRuntimeException());
+ }
+ }
+
+ /** Authenticate the exact same-namespace workload and reject user context before decoding. */
+ private void requireAuthenticatedGameDesignCaller() {
+ if (SessionContext.hasAuthenticatedCallerContext()
+ || AccountOriginalDraftOrderCredentials.CONTEXT_KEY.get() != null
+ || SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY.get() != null
+ || AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY.get() != null) {
+ throw Status.PERMISSION_DENIED.asRuntimeException();
+ }
+ var peer = GrpcPeerIdentity.current();
+ if (peer == null) {
+ throw Status.UNAUTHENTICATED.asRuntimeException();
+ }
+ if (!namespace.equals(peer.namespace())
+ || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) {
+ throw Status.PERMISSION_DENIED.asRuntimeException();
+ }
+ }
+}
diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcService.java
new file mode 100644
index 0000000000..a723e72dc9
--- /dev/null
+++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcService.java
@@ -0,0 +1,53 @@
+package net.firedevops.firemud.automationscripting.sourceintake;
+
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import io.grpc.stub.StreamObserver;
+import java.util.Objects;
+import net.firedevops.firemud.automationscripting.v1.AutomationSelectedSourceIntakeTerminalReadServiceGrpc;
+import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalRequest;
+import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalResponse;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadGrpcCodec;
+
+/** No automatic registration; authenticate Account before parsing caller-carried evidence. */
+public final class AutomationSelectedSourceIntakeTerminalReadGrpcService
+ extends AutomationSelectedSourceIntakeTerminalReadServiceGrpc
+ .AutomationSelectedSourceIntakeTerminalReadServiceImplBase {
+ private final AutomationEmptySelectedSourceIntakeTerminalReadService owner;
+
+ public AutomationSelectedSourceIntakeTerminalReadGrpcService(
+ AutomationEmptySelectedSourceIntakeTerminalReadService owner) {
+ this.owner = Objects.requireNonNull(owner, "terminal-read owner is required");
+ }
+
+ @Override
+ public void readSelectedSourceIntakeTerminal(
+ ReadSelectedSourceIntakeTerminalRequest request,
+ StreamObserver observer) {
+ try {
+ owner.requireAuthenticatedAccountCaller();
+ } catch (StatusRuntimeException denied) {
+ observer.onError(denied);
+ return;
+ }
+
+ final net.firedevops.firemud.common.automation.sourceintake
+ .AutomationSelectedSourceIntakeTerminalReadEvidence.Request
+ decoded;
+ try {
+ decoded = AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(request);
+ } catch (RuntimeException malformed) {
+ observer.onError(Status.INVALID_ARGUMENT.asRuntimeException());
+ return;
+ }
+ try {
+ var evidence = owner.read(decoded);
+ observer.onNext(AutomationSelectedSourceIntakeTerminalReadGrpcCodec.toResponse(evidence));
+ observer.onCompleted();
+ } catch (StatusRuntimeException denied) {
+ observer.onError(denied);
+ } catch (RuntimeException invalid) {
+ observer.onError(Status.DATA_LOSS.asRuntimeException());
+ }
+ }
+}
diff --git a/services/automation-scripting-service/src/main/resources/db/migration/V1003__selected_empty_source_intake.sql b/services/automation-scripting-service/src/main/resources/db/migration/V1003__selected_empty_source_intake.sql
new file mode 100644
index 0000000000..e43eb6aa7a
--- /dev/null
+++ b/services/automation-scripting-service/src/main/resources/db/migration/V1003__selected_empty_source_intake.sql
@@ -0,0 +1,334 @@
+-- This migration installs only the storage and writer guards for a fresh, explicitly empty
+-- Automation source scope. Existing rows remain legacy/unqualified; no numeric ID is adopted.
+CREATE TABLE automation_empty_source_numeric_key_reservation (
+ key_kind VARCHAR(16) NOT NULL,
+ numeric_key BIGINT NOT NULL,
+ claim_kind VARCHAR(32) NOT NULL,
+ CONSTRAINT pk_automation_empty_source_numeric_key_reservation
+ PRIMARY KEY (key_kind, numeric_key),
+ CONSTRAINT uq_automation_empty_source_numeric_key_kind_value
+ UNIQUE (numeric_key, key_kind),
+ CONSTRAINT uq_automation_empty_source_numeric_key_claim
+ UNIQUE (numeric_key, key_kind, claim_kind),
+ CONSTRAINT ck_automation_empty_source_numeric_key_kind
+ CHECK (key_kind IN ('TENANT', 'VERSION')),
+ CONSTRAINT ck_automation_empty_source_numeric_key_positive
+ CHECK (numeric_key > 0),
+ CONSTRAINT ck_automation_empty_source_numeric_key_claim
+ CHECK (claim_kind IN ('LEGACY_NUMERIC', 'CANONICAL_EMPTY_SOURCE'))
+);
+
+CREATE TABLE automation_empty_selected_source_association (
+ target_namespace VARCHAR(63) NOT NULL,
+ operation_id UUID NOT NULL,
+ fence_id UUID NOT NULL,
+ intake_request_id UUID NOT NULL,
+ canonical_tenant_id UUID NOT NULL,
+ canonical_version_id UUID NOT NULL,
+ selected_commit_id UUID NOT NULL,
+ source_revision_id UUID NOT NULL,
+ source_revision_order VARCHAR(32) NOT NULL,
+ local_tenant_key BIGINT NOT NULL,
+ local_tenant_key_kind VARCHAR(16) NOT NULL DEFAULT 'TENANT',
+ local_tenant_key_claim_kind VARCHAR(32) NOT NULL DEFAULT 'CANONICAL_EMPTY_SOURCE',
+ local_version_key BIGINT NOT NULL,
+ local_version_key_kind VARCHAR(16) NOT NULL DEFAULT 'VERSION',
+ local_version_key_claim_kind VARCHAR(32) NOT NULL DEFAULT 'CANONICAL_EMPTY_SOURCE',
+ request_digest VARCHAR(71) NOT NULL,
+ authorization_binding_digest VARCHAR(71) NOT NULL,
+ receipt_digest VARCHAR(71) NOT NULL,
+ associated_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_automation_empty_selected_source_association
+ PRIMARY KEY (target_namespace, canonical_tenant_id, canonical_version_id),
+ CONSTRAINT uq_automation_empty_selected_source_request
+ UNIQUE (target_namespace, intake_request_id),
+ CONSTRAINT uq_automation_empty_selected_source_operation
+ UNIQUE (target_namespace, operation_id),
+ CONSTRAINT uq_automation_empty_selected_source_local_tenant
+ UNIQUE (local_tenant_key),
+ CONSTRAINT uq_automation_empty_selected_source_local_version
+ UNIQUE (local_version_key),
+ CONSTRAINT ck_automation_empty_selected_source_namespace
+ CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'),
+ CONSTRAINT ck_automation_empty_selected_source_ids_nonzero
+ CHECK (
+ operation_id <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND fence_id <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND selected_commit_id <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND source_revision_id <> '00000000-0000-0000-0000-000000000000'::UUID
+ ),
+ CONSTRAINT ck_automation_empty_selected_source_local_keys
+ CHECK (
+ local_tenant_key > 0
+ AND local_version_key > 0
+ AND local_tenant_key <> local_version_key
+ AND local_tenant_key_kind = 'TENANT'
+ AND local_tenant_key_claim_kind = 'CANONICAL_EMPTY_SOURCE'
+ AND local_version_key_kind = 'VERSION'
+ AND local_version_key_claim_kind = 'CANONICAL_EMPTY_SOURCE'
+ ),
+ CONSTRAINT ck_automation_empty_selected_source_revision_order
+ CHECK (source_revision_order ~ '^(0|[1-9][0-9]*)$'),
+ CONSTRAINT ck_automation_empty_selected_source_digests
+ CHECK (
+ request_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND receipt_digest ~ '^sha256:[0-9a-f]{64}$'
+ ),
+ CONSTRAINT fk_automation_empty_selected_source_tenant_key
+ FOREIGN KEY (local_tenant_key, local_tenant_key_kind, local_tenant_key_claim_kind)
+ REFERENCES automation_empty_source_numeric_key_reservation
+ (numeric_key, key_kind, claim_kind),
+ CONSTRAINT fk_automation_empty_selected_source_version_key
+ FOREIGN KEY (local_version_key, local_version_key_kind, local_version_key_claim_kind)
+ REFERENCES automation_empty_source_numeric_key_reservation
+ (numeric_key, key_kind, claim_kind)
+);
+
+CREATE TABLE automation_empty_selected_source_receipt (
+ target_namespace VARCHAR(63) NOT NULL,
+ intake_request_id UUID NOT NULL,
+ request_digest VARCHAR(71) NOT NULL,
+ receipt_digest VARCHAR(71) NOT NULL,
+ receipt_bytes BYTEA NOT NULL,
+ retained_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_automation_empty_selected_source_receipt
+ PRIMARY KEY (target_namespace, intake_request_id),
+ CONSTRAINT fk_automation_empty_selected_source_receipt_association
+ FOREIGN KEY (target_namespace, intake_request_id)
+ REFERENCES automation_empty_selected_source_association (target_namespace, intake_request_id)
+ ON DELETE RESTRICT,
+ CONSTRAINT ck_automation_empty_selected_source_receipt_digests
+ CHECK (
+ request_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND receipt_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND octet_length(receipt_bytes) BETWEEN 1 AND 58736640
+ )
+);
+
+CREATE INDEX idx_automation_empty_source_key_claim_kind
+ ON automation_empty_source_numeric_key_reservation (claim_kind, key_kind, numeric_key);
+
+/* [jooq ignore start] */
+CREATE FUNCTION automation_source_positive_numeric_key(value_text TEXT)
+RETURNS BIGINT
+LANGUAGE plpgsql
+IMMUTABLE
+STRICT
+SET search_path = pg_catalog
+AS $$
+DECLARE
+ parsed_value NUMERIC;
+BEGIN
+ IF value_text !~ '^[0-9]+$' THEN
+ RETURN NULL;
+ END IF;
+ parsed_value := value_text::NUMERIC;
+ IF parsed_value <= 0 OR parsed_value > 9223372036854775807 THEN
+ RETURN NULL;
+ END IF;
+ RETURN parsed_value::BIGINT;
+END;
+$$;
+/* [jooq ignore stop] */
+
+-- Lock allocator/association rows before source families, matching the owner allocation order.
+-- Old writers can finish before the family locks and are included in this seed; later writes see
+-- the reservation triggers installed below.
+/* [jooq ignore start] */
+LOCK TABLE automation_empty_source_numeric_key_reservation,
+ automation_empty_selected_source_association,
+ automation_empty_selected_source_receipt IN SHARE ROW EXCLUSIVE MODE;
+LOCK TABLE script_event_bindings, script_patch_base_bindings, scripts IN SHARE MODE;
+/* [jooq ignore stop] */
+
+-- Data-only PostgreSQL seeding uses the procedural parser above and ON CONFLICT; the jOOQ H2
+-- simulator cannot execute that seed. All table definitions remain in generation scope.
+/* [jooq ignore start] */
+INSERT INTO automation_empty_source_numeric_key_reservation (key_kind, numeric_key, claim_kind)
+SELECT DISTINCT key_kind, numeric_key, 'LEGACY_NUMERIC'
+FROM (
+ SELECT 'TENANT'::VARCHAR(16) AS key_kind, tenant_id AS numeric_key
+ FROM scripts WHERE tenant_id > 0
+ UNION ALL
+ SELECT 'TENANT', tenant_id
+ FROM script_event_bindings WHERE tenant_id > 0
+ UNION ALL
+ SELECT 'TENANT', automation_source_positive_numeric_key(tenant_id)
+ FROM script_patch_base_bindings
+ WHERE automation_source_positive_numeric_key(tenant_id) IS NOT NULL
+ UNION ALL
+ SELECT 'VERSION', base_version_id
+ FROM scripts WHERE base_version_id > 0
+ UNION ALL
+ SELECT 'VERSION', base_version_id
+ FROM script_event_bindings WHERE base_version_id > 0
+ UNION ALL
+ SELECT 'VERSION', base_version_id
+ FROM script_patch_base_bindings WHERE base_version_id > 0
+) AS existing_source_keys
+ON CONFLICT (key_kind, numeric_key) DO NOTHING;
+/* [jooq ignore stop] */
+
+/* [jooq ignore start] */
+DO $automation_empty_source_functions$
+DECLARE
+ owner_schema TEXT := current_schema();
+BEGIN
+ IF owner_schema IS NULL THEN
+ RAISE EXCEPTION 'Automation empty-source functions require an explicit installation schema';
+ END IF;
+
+ EXECUTE format($function$
+ CREATE FUNCTION %I.automation_require_source_numeric_key_unreserved(
+ requested_kind TEXT, requested_key BIGINT
+ ) RETURNS VOID
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path = pg_catalog, %I
+ AS $body$
+ DECLARE
+ retained_claim TEXT;
+ BEGIN
+ IF current_setting('transaction_isolation') <> 'read committed' THEN
+ RAISE EXCEPTION 'Automation authored-source row writes require READ COMMITTED isolation';
+ END IF;
+ IF requested_key IS NULL OR requested_key <= 0 THEN
+ RETURN;
+ END IF;
+ SELECT claim_kind INTO retained_claim
+ FROM %I.automation_empty_source_numeric_key_reservation
+ WHERE key_kind = requested_kind AND numeric_key = requested_key;
+ IF retained_claim = 'CANONICAL_EMPTY_SOURCE' THEN
+ RAISE EXCEPTION 'Automation numeric source key is reserved by an immutable empty-source receipt';
+ END IF;
+ END;
+ $body$
+ $function$, owner_schema, owner_schema, owner_schema);
+
+ EXECUTE format($function$
+ CREATE FUNCTION %I.automation_guard_authored_source_row()
+ RETURNS TRIGGER
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path = pg_catalog, %I
+ AS $body$
+ DECLARE
+ old_value JSONB;
+ new_value JSONB;
+ old_tenant_key BIGINT;
+ new_tenant_key BIGINT;
+ old_version_key BIGINT;
+ new_version_key BIGINT;
+ BEGIN
+ IF TG_OP IN ('UPDATE', 'DELETE') THEN
+ old_value := to_jsonb(OLD);
+ old_tenant_key := automation_source_positive_numeric_key(old_value->>'tenant_id');
+ old_version_key := automation_source_positive_numeric_key(old_value->>'base_version_id');
+ PERFORM automation_require_source_numeric_key_unreserved('TENANT', old_tenant_key);
+ PERFORM automation_require_source_numeric_key_unreserved('VERSION', old_version_key);
+ END IF;
+ IF TG_OP IN ('INSERT', 'UPDATE') THEN
+ new_value := to_jsonb(NEW);
+ new_tenant_key := automation_source_positive_numeric_key(new_value->>'tenant_id');
+ new_version_key := automation_source_positive_numeric_key(new_value->>'base_version_id');
+ -- Do not mutate the allocator table from a source-row trigger. PostgreSQL has already
+ -- acquired the source table's ROW EXCLUSIVE lock before firing this trigger, while the
+ -- founding path intentionally locks allocator tables first. A read-only reservation
+ -- check keeps that global lock order acyclic; new allocations also census every source
+ -- family while holding the source locks, so unreserved legacy keys cannot be missed.
+ PERFORM automation_require_source_numeric_key_unreserved('TENANT', new_tenant_key);
+ PERFORM automation_require_source_numeric_key_unreserved('VERSION', new_version_key);
+ END IF;
+ IF TG_OP = 'DELETE' THEN
+ RETURN OLD;
+ END IF;
+ RETURN NEW;
+ END;
+ $body$
+ $function$, owner_schema, owner_schema);
+
+ EXECUTE format($function$
+ CREATE FUNCTION %I.automation_reject_authored_source_truncate()
+ RETURNS TRIGGER
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path = pg_catalog, %I
+ AS $body$
+ BEGIN
+ IF current_setting('transaction_isolation') <> 'read committed' THEN
+ RAISE EXCEPTION 'Automation authored-source TRUNCATE requires READ COMMITTED isolation';
+ END IF;
+ IF EXISTS (
+ SELECT 1 FROM %I.automation_empty_source_numeric_key_reservation
+ WHERE claim_kind = 'CANONICAL_EMPTY_SOURCE'
+ ) THEN
+ RAISE EXCEPTION 'Automation authored source TRUNCATE is forbidden after canonical intake';
+ END IF;
+ RETURN NULL;
+ END;
+ $body$
+ $function$, owner_schema, owner_schema, owner_schema);
+
+ EXECUTE format($function$
+ CREATE FUNCTION %I.automation_reject_empty_source_intake_mutation()
+ RETURNS TRIGGER
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path = pg_catalog, %I
+ AS $body$
+ BEGIN
+ RAISE EXCEPTION 'Automation empty-source intake records are immutable';
+ END;
+ $body$
+ $function$, owner_schema, owner_schema);
+END;
+$automation_empty_source_functions$;
+
+REVOKE ALL ON FUNCTION automation_require_source_numeric_key_unreserved(TEXT, BIGINT) FROM PUBLIC;
+REVOKE ALL ON FUNCTION automation_guard_authored_source_row() FROM PUBLIC;
+REVOKE ALL ON FUNCTION automation_reject_authored_source_truncate() FROM PUBLIC;
+REVOKE ALL ON FUNCTION automation_reject_empty_source_intake_mutation() FROM PUBLIC;
+
+CREATE TRIGGER trg_automation_scripts_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON scripts
+ FOR EACH ROW EXECUTE FUNCTION automation_guard_authored_source_row();
+CREATE TRIGGER trg_automation_event_bindings_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON script_event_bindings
+ FOR EACH ROW EXECUTE FUNCTION automation_guard_authored_source_row();
+CREATE TRIGGER trg_automation_patch_base_bindings_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON script_patch_base_bindings
+ FOR EACH ROW EXECUTE FUNCTION automation_guard_authored_source_row();
+
+CREATE TRIGGER trg_automation_scripts_source_no_truncate
+ BEFORE TRUNCATE ON scripts
+ FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_authored_source_truncate();
+CREATE TRIGGER trg_automation_event_bindings_source_no_truncate
+ BEFORE TRUNCATE ON script_event_bindings
+ FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_authored_source_truncate();
+CREATE TRIGGER trg_automation_patch_base_bindings_source_no_truncate
+ BEFORE TRUNCATE ON script_patch_base_bindings
+ FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_authored_source_truncate();
+
+CREATE TRIGGER trg_automation_empty_source_key_reservation_immutable
+ BEFORE UPDATE OR DELETE ON automation_empty_source_numeric_key_reservation
+ FOR EACH ROW EXECUTE FUNCTION automation_reject_empty_source_intake_mutation();
+CREATE TRIGGER trg_automation_empty_source_key_reservation_no_truncate
+ BEFORE TRUNCATE ON automation_empty_source_numeric_key_reservation
+ FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_empty_source_intake_mutation();
+CREATE TRIGGER trg_automation_empty_source_association_immutable
+ BEFORE UPDATE OR DELETE ON automation_empty_selected_source_association
+ FOR EACH ROW EXECUTE FUNCTION automation_reject_empty_source_intake_mutation();
+CREATE TRIGGER trg_automation_empty_source_association_no_truncate
+ BEFORE TRUNCATE ON automation_empty_selected_source_association
+ FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_empty_source_intake_mutation();
+CREATE TRIGGER trg_automation_empty_source_receipt_immutable
+ BEFORE UPDATE OR DELETE ON automation_empty_selected_source_receipt
+ FOR EACH ROW EXECUTE FUNCTION automation_reject_empty_source_intake_mutation();
+CREATE TRIGGER trg_automation_empty_source_receipt_no_truncate
+ BEFORE TRUNCATE ON automation_empty_selected_source_receipt
+ FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_empty_source_intake_mutation();
+/* [jooq ignore stop] */
diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresFixture.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresFixture.java
new file mode 100644
index 0000000000..e193216ed5
--- /dev/null
+++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresFixture.java
@@ -0,0 +1,463 @@
+package net.firedevops.firemud.automationscripting.repository;
+
+import java.io.ByteArrayOutputStream;
+import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.time.OffsetDateTime;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof;
+import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration;
+import net.firedevops.firemud.common.gamedesign.AssetSnapshot;
+import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot;
+import net.firedevops.firemud.common.gamedesign.CommandSnapshot;
+import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch;
+import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot;
+import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent;
+import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration;
+import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot;
+import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues;
+import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest;
+import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource;
+import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel;
+
+/**
+ * Test-only synthetic inputs built through the same typed Common decoders as the shared fixture.
+ * They are not authenticated Account or World producer evidence or physical owner proof.
+ */
+final class AutomationEmptySelectedSourceIntakePostgresFixture {
+ static final String NAMESPACE = "test";
+ static final UUID TENANT = id("11111111-1111-4111-8111-111111111111");
+ static final UUID VERSION = id("22222222-2222-4222-8222-222222222222");
+ static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999");
+
+ private static final UUID OPERATION = id("55555555-5555-4555-8555-555555555555");
+ private static final UUID FENCE = id("66666666-6666-4666-8666-666666666666");
+ private static final UUID INTAKE_REQUEST = id("77777777-7777-4777-8777-777777777777");
+ private static final UUID GENESIS_RECEIPT = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa");
+
+ private static final String TEMPLATE_CONFIG =
+ "{\"schemaVersion\":1,\"baseVersionId\":\""
+ + VERSION
+ + "\",\"world\":{\"regions\":[],\"rooms\":[]},"
+ + "\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":[]},"
+ + "\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}},"
+ + "\"supportedSettings\":[]}";
+
+ private AutomationEmptySelectedSourceIntakePostgresFixture() {}
+
+ static Fixture create(String sourceEpoch) {
+ DraftCommitBinding selected = selected();
+ var scope =
+ new net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope(
+ Owner.AUTOMATION_SCRIPTING,
+ NAMESPACE,
+ OPERATION,
+ FENCE,
+ INTAKE_REQUEST,
+ ACTOR,
+ selected);
+ TemplateConfigSourceSnapshot templateSnapshot = templateSnapshot(selected, sourceEpoch);
+ SelectedOwnerIntakeAuthorizationBinding authorization =
+ new SelectedOwnerIntakeAuthorizationBinding(
+ sourceContent(scope, templateSnapshot), accountSources());
+ WorldSelectedDraftPublicationFreezeEvidence freeze = freezeEvidence(selected);
+ var inventory =
+ WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence(
+ freeze, publicInventory(freeze));
+ var worldRequest =
+ SelectedOwnerWorldInventoryReadEvidence.create(NAMESPACE, authorization, freeze);
+ var worldEvidence = new SelectedOwnerWorldInventoryReadEvidence(worldRequest, inventory);
+ return new Fixture(
+ authorization,
+ freeze,
+ worldEvidence,
+ new SelectedOwnerEmptySourceInputs(authorization, worldEvidence));
+ }
+
+ static Fixture withFreshWorldReadCorrelation(Fixture original) {
+ var request =
+ SelectedOwnerWorldInventoryReadEvidence.create(
+ NAMESPACE, original.authorization(), original.freezeEvidence());
+ var evidence =
+ new SelectedOwnerWorldInventoryReadEvidence(request, original.worldEvidence().inventory());
+ return new Fixture(
+ original.authorization(),
+ original.freezeEvidence(),
+ evidence,
+ new SelectedOwnerEmptySourceInputs(original.authorization(), evidence));
+ }
+
+ private static TemplateConfigSourceSnapshot templateSnapshot(
+ DraftCommitBinding selected, String sourceEpoch) {
+ var declaration =
+ AutomationAuthoredSourceInventoryDeclaration.parse(
+ "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{"
+ + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[],"
+ + "\"SCRIPT_PATCH_SOURCES\":[]}}");
+ String declarationPayload =
+ TemplateConfigSourceValues.ownerInventoryPayload(Owner.AUTOMATION_SCRIPTING, declaration);
+ DraftCommitBinding authored = authoredBinding(declarationPayload);
+ TemplateConfigOwnerSourceInventoryDeclaration ownerDeclaration =
+ TemplateConfigSourceValues.mutations(authored).stream()
+ .filter(
+ mutation ->
+ mutation.operation()
+ == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY)
+ .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration)
+ .findFirst()
+ .orElseThrow();
+ return new TemplateConfigSourceSnapshot(
+ selected,
+ sourceEpoch,
+ authored.commitId(),
+ GENESIS_RECEIPT,
+ List.of(),
+ List.of(ownerDeclaration));
+ }
+
+ private static DraftCommitBinding authoredBinding(String payload) {
+ return DraftCommitBinding.create(
+ target(),
+ id("51515151-5151-4151-8151-515151515151"),
+ id("52525252-5252-4252-8252-525252525252"),
+ "base-commit-0",
+ List.of(
+ new RevisionPayload(
+ "0",
+ id("53535353-5353-4353-8353-535353535353"),
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ payload)),
+ List.of(
+ new DraftCommitBinding.AffectedUnit(
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ TemplateConfigSourceValues.SCOPE,
+ VERSION.toString(),
+ TemplateConfigSourceValues.SCOPE,
+ TemplateConfigSourceValues.SCOPE_ID,
+ "0")));
+ }
+
+ private static SelectedOwnerIntakeSourceContent sourceContent(
+ net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope scope,
+ TemplateConfigSourceSnapshot templateSnapshot) {
+ var out = new ByteArrayOutputStream();
+ frame(out, SelectedOwnerIntakeSourceContent.DOMAIN);
+ frame(out, scope.canonicalBytes());
+ frame(out, scope.digest());
+ for (String family :
+ List.of(
+ "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) {
+ byte[] snapshot =
+ "TEMPLATE_CONFIG".equals(family)
+ ? templateSnapshot.canonicalBytes()
+ : sourceSnapshot(family, scope.selected());
+ frame(out, family);
+ frame(out, snapshot);
+ frame(out, DraftAuthorizationFenceBinding.digest(snapshot));
+ }
+ byte[] bytes = out.toByteArray();
+ return SelectedOwnerIntakeSourceContent.fromStored(
+ bytes, scope, DraftAuthorizationFenceBinding.digest(bytes));
+ }
+
+ private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) {
+ // These values exercise exact stored-byte decoding only; they are synthetic, not owner proof.
+ return switch (family) {
+ case "COMMAND" ->
+ new CommandSnapshot(selected, "0", null, "sha256:" + "0".repeat(64), List.of())
+ .canonicalBytes();
+ case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes();
+ case "ASSET" ->
+ new AssetSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()).canonicalBytes();
+ case "GAMEPLAY_RULE" ->
+ new GameplayRuleSelectedSource(
+ GameplayRuleManifest.canonical(
+ Map.of(
+ "schema",
+ "game-design-gameplay-rule-source-snapshot/v1",
+ "bindingJson",
+ selected.canonicalJson(),
+ "bindingDigest",
+ selected.digest(),
+ "sourceEpoch",
+ "0",
+ "inheritedCommitId",
+ "",
+ "genesisReceiptId",
+ GENESIS_RECEIPT.toString(),
+ "manifestJson",
+ GameplayRuleManifest.explicitEmpty().canonicalJson(),
+ "entries",
+ List.of())))
+ .canonicalBytes();
+ case "BRANDING" ->
+ new BrandingSourceSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of())
+ .canonicalBytes();
+ default -> throw new IllegalArgumentException("Unsupported source family fixture: " + family);
+ };
+ }
+
+ private static List accountSources() {
+ return List.of(
+ source(SourceKind.TENANT, TENANT.toString(), "tenant"),
+ source(SourceKind.ACCOUNT, ACTOR.toString(), "account"),
+ source(SourceKind.MEMBERSHIP, ACTOR + "/" + TENANT, "membership"));
+ }
+
+ private static SourceEvidence source(SourceKind kind, String scope, String marker) {
+ return new SourceEvidence(
+ kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8));
+ }
+
+ private static DraftCommitBinding selected() {
+ return DraftCommitBinding.create(
+ target(),
+ id("33333333-3333-4333-8333-333333333333"),
+ id("44444444-4444-4444-8444-444444444444"),
+ "base-commit-0",
+ List.of(
+ new RevisionPayload(
+ "0", id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), Owner.WORLD_MANAGEMENT, "{}")),
+ List.of(
+ new DraftCommitBinding.AffectedUnit(
+ Owner.WORLD_MANAGEMENT, "REGION", "region-1", "AGGREGATE", "region-1", "0")));
+ }
+
+ private static TargetProof target() {
+ return new TargetProof(TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW");
+ }
+
+ private static WorldSelectedDraftPublicationFreezeEvidence freezeEvidence(
+ DraftCommitBinding selected) {
+ var selection =
+ AuthoredDraftPublishSelectionBinding.capture(
+ new PublishIntent(
+ TENANT,
+ VERSION,
+ "publication-request",
+ "9",
+ "synthetic selected-owner intake fixture",
+ selected.requestId(),
+ selected.commitId(),
+ selected.digest()),
+ selected.target(),
+ selected,
+ new VisibilityFence(
+ selected.target(),
+ selected.requestId(),
+ selected.commitId(),
+ selected.digest(),
+ "[]",
+ OffsetDateTime.parse("2026-10-01T00:00:00Z")));
+ var account =
+ new AccountPublicationAuthorizationBinding(
+ id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"),
+ id("ffffffff-ffff-4fff-8fff-ffffffffffff"),
+ new AccountPublicationAuthorizationBinding.PreallocationInput(ACTOR, selection),
+ List.of(source(SourceKind.ACCOUNT, ACTOR.toString(), "account-publication")));
+ var request =
+ WorldSelectedDraftPublicationFreezeEvidence.Request.create(
+ NAMESPACE,
+ TENANT,
+ VERSION,
+ selection.intent().publishRequestId(),
+ 9,
+ selection.digest().substring("sha256:".length()),
+ account);
+ var acknowledgement =
+ new Acknowledgement(
+ request,
+ id("12121212-1212-4212-8212-121212121212"),
+ 9,
+ id("13131313-1313-4313-8313-131313131313"),
+ OwnerFreezePhase.FROZEN,
+ selected.commitId().toString(),
+ "a".repeat(64),
+ 4);
+ return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse(
+ request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement));
+ }
+
+ private static PublicEvidence publicInventory(
+ WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) {
+ var request = freezeEvidence.request();
+ var acknowledgement = freezeEvidence.acknowledgement();
+ var account = request.accountBinding();
+ var selection = account.input().selection();
+ var selected = selection.selectedCommit();
+ var sourceModel =
+ new SourceModel(
+ WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL,
+ WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION,
+ "sha256:" + "4".repeat(64),
+ "sha256:" + "5".repeat(64),
+ List.of(
+ new FamilyCount("REGION", 1),
+ new FamilyCount("ZONE", 1),
+ new FamilyCount("ROOM", 1),
+ new FamilyCount("ROOM_EXIT", 1),
+ new FamilyCount("GENERATION_RULE", 0),
+ new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)),
+ List.of(new RegionGeneratorInput(id("15151515-1515-4515-8515-151515151515"), "", "")),
+ List.of("id", "name", "scopeType", "scopeId", "value"),
+ List.of(
+ "id",
+ "shardId",
+ "name",
+ "weather",
+ "generationSeed",
+ "generatorType",
+ "generatorParams",
+ "spacingMultiplier"),
+ List.of("id", "regionId", "name"),
+ List.of(
+ "id",
+ "zoneId",
+ "name",
+ "description",
+ "nameLocalizedVariantsJson",
+ "descriptionLocalizedVariantsJson"),
+ List.of("id", "fromRoomId", "toRoomId", "direction", "cost"),
+ List.of(
+ "id",
+ "roomId",
+ "entityTemplateType",
+ "entityReference.kind",
+ "entityReference.tenantId",
+ "entityReference.versionId",
+ "entityReference.templateId",
+ "spawnCount",
+ "respawnDelaySeconds"),
+ List.of(),
+ 0,
+ 0,
+ selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream()
+ .map(
+ unit ->
+ new AppliedEpoch(
+ unit.aggregateType(),
+ unit.aggregateId(),
+ unit.scopeType(),
+ unit.scopeId(),
+ unit.expectedEpoch(),
+ new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString()))
+ .toList(),
+ emptyInboundClosure());
+ var ownerScope =
+ new PublicOwnerScope(
+ request.targetNamespace(),
+ TENANT,
+ VERSION,
+ id("14141414-1414-4414-8414-141414141414"),
+ acknowledgement.intakeRequestId(),
+ id("13131313-1313-4313-8313-131313131313"),
+ "sha256:" + "1".repeat(64),
+ id("17171717-1717-4717-8717-171717171717"),
+ "sha256:" + "2".repeat(64),
+ "sha256:" + "3".repeat(64));
+ return new PublicEvidence(
+ WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA,
+ WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION,
+ "COMPLETE",
+ ownerScope,
+ new SelectedApplication(
+ id("16161616-1616-4616-8616-161616161616"),
+ selected.requestId(),
+ selected.commitId().toString(),
+ selected.digest(),
+ "sha256:" + "6".repeat(64)),
+ new PublicAccountOrder(
+ account.operationId(),
+ account.fenceId(),
+ account.input().actorAccountId(),
+ selection.intent().publishRequestId(),
+ selection.digest(),
+ selected.commitId().toString(),
+ DraftAuthorizationFenceBinding.digest(account.canonicalBytes())),
+ new Freeze(
+ acknowledgement.publicationFence(),
+ request.publicationRequestId(),
+ request.requestDigest(),
+ Long.toString(acknowledgement.versionStateEpoch()),
+ PublicationDigestRequestBinding.full(
+ request.canonicalTenantId().toString(),
+ Long.toString(selection.target().gameDesignVersionRowId()),
+ request.publicationRequestId())
+ .derivedWorkflowIdentity()),
+ new Checkpoint(acknowledgement.appliedCommitId(), acknowledgement.contentDigest(), 4),
+ sourceModel,
+ List.of(
+ new ArtifactDecision(
+ "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"),
+ new ArtifactDecision(
+ "PATH_GRAPH",
+ "NOT_REQUIRED",
+ "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH")));
+ }
+
+ private static InboundSourceClosureDeclaration emptyInboundClosure() {
+ return new InboundSourceClosureDeclaration(
+ 1,
+ List.of(
+ new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0),
+ new InboundSourceFamilyCount(
+ "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0),
+ new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0),
+ new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0),
+ new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0),
+ new InboundSourceFamilyCount(
+ "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0),
+ new InboundSourceFamilyCount(
+ "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0)));
+ }
+
+ private static void frame(ByteArrayOutputStream out, String value) {
+ DraftAuthorizationFenceBinding.frame(out, value);
+ }
+
+ private static void frame(ByteArrayOutputStream out, byte[] value) {
+ DraftAuthorizationFenceBinding.frame(out, value);
+ }
+
+ private static UUID id(String value) {
+ return UUID.fromString(value);
+ }
+
+ record Fixture(
+ SelectedOwnerIntakeAuthorizationBinding authorization,
+ WorldSelectedDraftPublicationFreezeEvidence freezeEvidence,
+ SelectedOwnerWorldInventoryReadEvidence worldEvidence,
+ SelectedOwnerEmptySourceInputs inputs) {}
+}
diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java
new file mode 100644
index 0000000000..15fc641e55
--- /dev/null
+++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java
@@ -0,0 +1,378 @@
+package net.firedevops.firemud.automationscripting.repository;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.nio.file.Path;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.UUID;
+import java.util.List;
+import java.util.Map;
+import net.firedevops.firemud.test.TestContainerImages;
+import org.flywaydb.core.Flyway;
+import org.jooq.DSLContext;
+import org.jooq.SQLDialect;
+import org.jooq.exception.DataAccessException;
+import org.jooq.impl.DSL;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.testcontainers.containers.PostgreSQLContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+@Testcontainers(disabledWithoutDocker = true)
+@SuppressWarnings("resource")
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+class AutomationEmptySelectedSourceIntakePostgresIntegrationTest {
+ private static final String MIGRATION_LOCATION =
+ "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize();
+
+ @Container
+ static PostgreSQLContainer> postgres =
+ new PostgreSQLContainer<>(TestContainerImages.postgres());
+
+ private String schema;
+ private DSLContext dsl;
+
+ @BeforeAll
+ void migrateWithRetainedLegacyAuthoredRows() {
+ schema = "automation_empty_source_" + UUID.randomUUID().toString().replace("-", "");
+ DriverManagerDataSource dataSource = dataSource(schema);
+ Flyway.configure()
+ .dataSource(dataSource)
+ .locations(MIGRATION_LOCATION, "classpath:db/migration/saga")
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema))
+ .target("1002")
+ .load()
+ .migrate();
+
+ DSLContext upgradeDsl = DSL.using(dataSource, SQLDialect.POSTGRES);
+ upgradeDsl.execute(
+ "INSERT INTO scripts (tenant_id, name, version, definition, base_version_id) "
+ + "VALUES (101, 'retained-script', 'legacy-patch', '{}', 201)");
+ upgradeDsl.execute(
+ "INSERT INTO script_event_bindings (tenant_id, script_patch_version, event_type, "
+ + "event_schema_version, script_id, target_scope_type, target_scope_id, base_version_id) "
+ + "VALUES (102, 'legacy-patch', 'legacy-event', 'v1', 'retained-script', "
+ + "'TENANT', 'legacy', 202)");
+ upgradeDsl.execute(
+ "INSERT INTO script_patch_base_bindings (tenant_id, script_patch_version, base_version_id) "
+ + "VALUES ('103', 'legacy-patch', 203)");
+
+ upgradeDsl.execute("INSERT INTO script_work_items (tenant_id, game_instance_id, region_id, region_epoch, entity_id, script_id, event_type, event_schema_version, script_patch_version, script_event_id, source_service, trigger_mode, failure_generation, next_eligible_at) VALUES ('retained-tenant', 'retained-instance', 'region', 1, 'entity', 'script', 'event', 'v1', 'retained-patch', 'retained-event', 'test-only', 'EXTERNAL', 7, NULL)");
+ upgradeDsl.execute("INSERT INTO saga_instance (saga_name, state) VALUES ('retained-automation-source', 'PENDING')");
+ upgradeDsl.execute("INSERT INTO saga_step (instance_id, name, status) SELECT id, 'retained-step', 'PENDING' FROM saga_instance WHERE saga_name = 'retained-automation-source'");
+ var parentRows = retainedParentRows(upgradeDsl);
+ var parentHistory = migrationHistory(upgradeDsl);
+ assertThat(upgradeDsl.fetch("SELECT version FROM flyway_schema_history WHERE success ORDER BY installed_rank").getValues(0, String.class))
+ .containsExactly("1", "2", "3", "3.1", "3.2", "4", "1000", "1001", "1002");
+
+ Flyway.configure()
+ .dataSource(dataSource)
+ .locations(MIGRATION_LOCATION, "classpath:db/migration/saga")
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema))
+ .load()
+ .migrate();
+ dsl = DSL.using(dataSource, SQLDialect.POSTGRES);
+ assertThat(retainedParentRows(dsl)).isEqualTo(parentRows);
+ assertThat(migrationHistory(dsl).subList(0, parentHistory.size())).containsExactlyElementsOf(parentHistory);
+ assertThat(dsl.fetchSingle("SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1").get(0, String.class)).isEqualTo("1003");
+
+ }
+
+ /** Synthetic retained SQL state only; no genuine script or runtime admission authority. */
+ private static Map> retainedParentRows(DSLContext source) {
+ Map> rows = new java.util.LinkedHashMap<>();
+ for (String table : List.of("scripts", "script_event_bindings", "script_patch_base_bindings", "script_work_items", "saga_instance", "saga_step")) {
+ rows.put(table, source.fetch("SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM " + table + " t ORDER BY to_jsonb(t)::TEXT").getValues(0, String.class));
+ }
+ return rows;
+ }
+
+ private static List migrationHistory(DSLContext source) {
+ return source.fetch("SELECT to_jsonb(t)::TEXT || ':' || t.xmin::TEXT FROM flyway_schema_history t ORDER BY installed_rank").getValues(0, String.class);
+ }
+
+ @AfterAll
+ void dropIsolatedSchema() {
+ if (schema != null) {
+ String checkedSchema = schema.replaceAll("[^a-zA-Z0-9_]", "");
+ DSL.using(dataSource(null), SQLDialect.POSTGRES)
+ .execute("DROP SCHEMA IF EXISTS \"" + checkedSchema + "\" CASCADE");
+ schema = null;
+ }
+ }
+
+ @Test
+ void migrationSeedsLegacyKeysAndGuardsAllThreeAuthoredSourceFamilies() {
+ assertThat(
+ dsl.fetchValue(
+ "SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation "
+ + "WHERE claim_kind = 'LEGACY_NUMERIC'",
+ Long.class))
+ .isEqualTo(6L);
+ assertThat(
+ dsl.fetchValue(
+ "SELECT claim_kind FROM automation_empty_source_numeric_key_reservation "
+ + "WHERE key_kind = 'TENANT' AND numeric_key = 101",
+ String.class))
+ .isEqualTo("LEGACY_NUMERIC");
+
+ reserveCanonicalScope(9001L, 9002L);
+
+ // NEW-side guards deny writes that target either locally reserved numeric dimension.
+ assertRejected(
+ "INSERT INTO scripts (tenant_id, name, version, definition) "
+ + "VALUES (9001, 'blocked-script', 'v1', '{}')");
+ assertRejected(
+ "INSERT INTO script_event_bindings (tenant_id, script_patch_version, event_type, "
+ + "event_schema_version, script_id, target_scope_type, target_scope_id, base_version_id) "
+ + "VALUES (400, 'blocked-patch', 'blocked-event', 'v1', 'blocked-script', "
+ + "'TENANT', 'one', 9002)");
+ assertRejected(
+ "INSERT INTO script_patch_base_bindings (tenant_id, script_patch_version, base_version_id) "
+ + "VALUES ('9001', 'blocked-patch', 400)");
+
+ // UPDATE checks both sides: legacy rows cannot be moved into a canonical scope.
+ upgradeLegacyRowsForUpdate();
+ assertRejected("UPDATE scripts SET tenant_id = 9001 WHERE name = 'update-script'");
+ assertRejected(
+ "UPDATE script_event_bindings SET base_version_id = 9002 "
+ + "WHERE script_patch_version = 'update-patch'");
+ assertRejected(
+ "UPDATE script_patch_base_bindings SET tenant_id = '9001' "
+ + "WHERE script_patch_version = 'update-patch'");
+
+ // Fixture-only trigger bypass seeds rows already inside the protected scope so OLD-side
+ // UPDATE/DELETE rejection is exercised independently of the NEW-side checks above.
+ seedCanonicalRowsForOldSideChecks();
+ assertRejected("DELETE FROM scripts WHERE name = 'old-side-script'");
+ assertRejected("UPDATE scripts SET tenant_id = 9101 WHERE name = 'old-side-script'");
+ assertRejected(
+ "DELETE FROM script_event_bindings WHERE script_patch_version = 'old-side-patch'");
+ assertRejected(
+ "UPDATE script_event_bindings SET base_version_id = 9102 "
+ + "WHERE script_patch_version = 'old-side-patch'");
+ assertRejected(
+ "DELETE FROM script_patch_base_bindings WHERE script_patch_version = 'old-side-patch'");
+ assertRejected(
+ "UPDATE script_patch_base_bindings SET tenant_id = '9103' "
+ + "WHERE script_patch_version = 'old-side-patch'");
+
+ assertRejected("TRUNCATE TABLE scripts");
+ assertRejected("TRUNCATE TABLE script_event_bindings");
+ assertRejected("TRUNCATE TABLE script_patch_base_bindings");
+ }
+
+ @Test
+ void securityDefinerFunctionsUseTheExactInstalledSchemaInTheirFixedSearchPath() {
+ assertThat(
+ dsl.fetchSingle(
+ "SELECT COUNT(*) FROM pg_proc AS p "
+ + "JOIN pg_namespace AS n ON n.oid = p.pronamespace "
+ + "WHERE n.nspname = ? "
+ + "AND p.proname IN ("
+ + "'automation_require_source_numeric_key_unreserved', "
+ + "'automation_guard_authored_source_row', "
+ + "'automation_reject_authored_source_truncate', "
+ + "'automation_reject_empty_source_intake_mutation') "
+ + "AND p.prosecdef "
+ + "AND p.proconfig @> ARRAY[format('search_path=pg_catalog, %I', ?)]",
+ schema, schema)
+ .get(0, Integer.class))
+ .isEqualTo(4);
+ }
+
+ @Test
+ void staleRepeatableReadWritersCannotMissACommittedCanonicalReservation() throws SQLException {
+ try (Connection staleRowWriter = repeatableReadSnapshot()) {
+ commitCanonicalEmptySourceFixture(9301L, 9302L);
+ try {
+ assertThatThrownBy(
+ () ->
+ execute(
+ staleRowWriter,
+ "INSERT INTO scripts (tenant_id, name, version, definition) "
+ + "VALUES (9301, 'stale-snapshot-script', 'v1', '{}')"))
+ .isInstanceOf(SQLException.class);
+ } finally {
+ staleRowWriter.rollback();
+ }
+ }
+
+ try (Connection staleTruncator = repeatableReadSnapshot()) {
+ commitCanonicalEmptySourceFixture(9401L, 9402L);
+ try {
+ assertThatThrownBy(() -> execute(staleTruncator, "TRUNCATE TABLE scripts"))
+ .isInstanceOf(SQLException.class);
+ } finally {
+ staleTruncator.rollback();
+ }
+ }
+ }
+
+ private void reserveCanonicalScope(long tenantKey, long versionKey) {
+ dsl.execute(
+ "INSERT INTO automation_empty_source_numeric_key_reservation "
+ + "(key_kind, numeric_key, claim_kind) VALUES "
+ + "('TENANT', ?, 'CANONICAL_EMPTY_SOURCE'), "
+ + "('VERSION', ?, 'CANONICAL_EMPTY_SOURCE')",
+ tenantKey,
+ versionKey);
+ }
+
+ private void upgradeLegacyRowsForUpdate() {
+ dsl.execute(
+ "INSERT INTO scripts (tenant_id, name, version, definition) "
+ + "VALUES (410, 'update-script', 'v1', '{}')");
+ dsl.execute(
+ "INSERT INTO script_event_bindings (tenant_id, script_patch_version, event_type, "
+ + "event_schema_version, script_id, target_scope_type, target_scope_id, base_version_id) "
+ + "VALUES (411, 'update-patch', 'update-event', 'v1', 'update-script', "
+ + "'TENANT', 'one', 412)");
+ dsl.execute(
+ "INSERT INTO script_patch_base_bindings (tenant_id, script_patch_version, base_version_id) "
+ + "VALUES ('413', 'update-patch', 414)");
+ }
+
+ private void seedCanonicalRowsForOldSideChecks() {
+ dsl.execute("ALTER TABLE scripts DISABLE TRIGGER trg_automation_scripts_source_reservation");
+ dsl.execute(
+ "INSERT INTO scripts (tenant_id, name, version, definition) "
+ + "VALUES (9001, 'old-side-script', 'v1', '{}')");
+ dsl.execute("ALTER TABLE scripts ENABLE TRIGGER trg_automation_scripts_source_reservation");
+
+ dsl.execute(
+ "ALTER TABLE script_event_bindings "
+ + "DISABLE TRIGGER trg_automation_event_bindings_source_reservation");
+ dsl.execute(
+ "INSERT INTO script_event_bindings (tenant_id, script_patch_version, event_type, "
+ + "event_schema_version, script_id, target_scope_type, target_scope_id, base_version_id) "
+ + "VALUES (420, 'old-side-patch', 'old-side-event', 'v1', 'old-side-script', "
+ + "'TENANT', 'one', 9002)");
+ dsl.execute(
+ "ALTER TABLE script_event_bindings "
+ + "ENABLE TRIGGER trg_automation_event_bindings_source_reservation");
+
+ dsl.execute(
+ "ALTER TABLE script_patch_base_bindings "
+ + "DISABLE TRIGGER trg_automation_patch_base_bindings_source_reservation");
+ dsl.execute(
+ "INSERT INTO script_patch_base_bindings (tenant_id, script_patch_version, base_version_id) "
+ + "VALUES ('9001', 'old-side-patch', 420)");
+ dsl.execute(
+ "ALTER TABLE script_patch_base_bindings "
+ + "ENABLE TRIGGER trg_automation_patch_base_bindings_source_reservation");
+ }
+
+ private void assertRejected(String sql) {
+ assertThatThrownBy(() -> dsl.execute(sql)).isInstanceOf(DataAccessException.class);
+ }
+
+ private Connection repeatableReadSnapshot() throws SQLException {
+ Connection connection = dataSource(schema).getConnection();
+ connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
+ connection.setAutoCommit(false);
+ try (Statement statement = connection.createStatement()) {
+ statement
+ .executeQuery("SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation")
+ .close();
+ }
+ return connection;
+ }
+
+ private void commitCanonicalEmptySourceFixture(long tenantKey, long versionKey)
+ throws SQLException {
+ // Synthetic SQL-only rows exercise the database fence; they do not authenticate Account or
+ // World producers and are not proof of the physical owner path.
+ try (Connection founder = dataSource(schema).getConnection()) {
+ founder.setAutoCommit(false);
+ try (PreparedStatement reservation =
+ founder.prepareStatement(
+ "INSERT INTO automation_empty_source_numeric_key_reservation "
+ + "(key_kind, numeric_key, claim_kind) VALUES "
+ + "('TENANT', ?, 'CANONICAL_EMPTY_SOURCE'), "
+ + "('VERSION', ?, 'CANONICAL_EMPTY_SOURCE')")) {
+ reservation.setLong(1, tenantKey);
+ reservation.setLong(2, versionKey);
+ reservation.executeUpdate();
+ }
+
+ UUID operationId = UUID.randomUUID();
+ UUID fenceId = UUID.randomUUID();
+ UUID intakeRequestId = UUID.randomUUID();
+ UUID canonicalTenantId = UUID.randomUUID();
+ UUID canonicalVersionId = UUID.randomUUID();
+ UUID selectedCommitId = UUID.randomUUID();
+ UUID sourceRevisionId = UUID.randomUUID();
+ String digest = "sha256:" + "c".repeat(64);
+ try (var association =
+ founder.prepareStatement(
+ "INSERT INTO automation_empty_selected_source_association "
+ + "(target_namespace, operation_id, fence_id, intake_request_id, "
+ + "canonical_tenant_id, canonical_version_id, selected_commit_id, "
+ + "source_revision_id, source_revision_order, local_tenant_key, "
+ + "local_tenant_key_kind, local_tenant_key_claim_kind, local_version_key, "
+ + "local_version_key_kind, local_version_key_claim_kind, request_digest, "
+ + "authorization_binding_digest, receipt_digest, associated_at) "
+ + "VALUES ('example', ?, ?, ?, ?, ?, ?, ?, '1', ?, 'TENANT', "
+ + "'CANONICAL_EMPTY_SOURCE', ?, 'VERSION', 'CANONICAL_EMPTY_SOURCE', "
+ + "?, ?, ?, CURRENT_TIMESTAMP)")) {
+ association.setObject(1, operationId);
+ association.setObject(2, fenceId);
+ association.setObject(3, intakeRequestId);
+ association.setObject(4, canonicalTenantId);
+ association.setObject(5, canonicalVersionId);
+ association.setObject(6, selectedCommitId);
+ association.setObject(7, sourceRevisionId);
+ association.setLong(8, tenantKey);
+ association.setLong(9, versionKey);
+ association.setString(10, digest);
+ association.setString(11, digest);
+ association.setString(12, digest);
+ association.executeUpdate();
+ }
+ try (var receipt =
+ founder.prepareStatement(
+ "INSERT INTO automation_empty_selected_source_receipt "
+ + "(target_namespace, intake_request_id, request_digest, receipt_digest, "
+ + "receipt_bytes, retained_at) VALUES ('example', ?, ?, ?, decode('01', 'hex'), "
+ + "CURRENT_TIMESTAMP)")) {
+ receipt.setObject(1, intakeRequestId);
+ receipt.setString(2, digest);
+ receipt.setString(3, digest);
+ receipt.executeUpdate();
+ }
+ founder.commit();
+ }
+ }
+
+ private static void execute(Connection connection, String sql) throws SQLException {
+ try (Statement statement = connection.createStatement()) {
+ statement.execute(sql);
+ }
+ }
+
+ private DriverManagerDataSource dataSource(String schemaName) {
+ DriverManagerDataSource dataSource = new DriverManagerDataSource();
+ dataSource.setDriverClassName(postgres.getDriverClassName());
+ String baseUrl = postgres.getJdbcUrl();
+ dataSource.setUrl(
+ schemaName == null
+ ? baseUrl
+ : baseUrl + (baseUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName);
+ dataSource.setUsername(postgres.getUsername());
+ dataSource.setPassword(postgres.getPassword());
+ return dataSource;
+ }
+}
diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java
new file mode 100644
index 0000000000..5a39dbc9c6
--- /dev/null
+++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java
@@ -0,0 +1,553 @@
+package net.firedevops.firemud.automationscripting.repository;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+import java.util.Locale;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository;
+import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedEmptyPublicationDigestService;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import net.firedevops.firemud.test.TestContainerImages;
+import org.flywaydb.core.Flyway;
+import org.jooq.DSLContext;
+import org.jooq.ExecuteContext;
+import org.jooq.Record;
+import org.jooq.SQLDialect;
+import org.jooq.impl.DSL;
+import org.jooq.impl.DefaultExecuteListener;
+import org.jooq.impl.DefaultExecuteListenerProvider;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.testcontainers.containers.PostgreSQLContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+/** Real PostgreSQL proof of Automation's bounded local repository persistence and census path. */
+@Testcontainers(disabledWithoutDocker = true)
+@SuppressWarnings("resource")
+class AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest {
+ private static final String MIGRATION_LOCATION =
+ "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize();
+
+ @Container
+ static PostgreSQLContainer> postgres =
+ new PostgreSQLContainer<>(TestContainerImages.postgres());
+
+ private String schema;
+ private DSLContext dsl;
+ private AutomationEmptySelectedSourceIntakeRepository repository;
+
+ @BeforeEach
+ void migrateFreshIsolatedSchema() {
+ schema = "automation_empty_source_repo_" + UUID.randomUUID().toString().replace("-", "");
+ DriverManagerDataSource dataSource = dataSource(schema);
+ Flyway.configure()
+ .dataSource(dataSource)
+ .locations(MIGRATION_LOCATION, "classpath:db/migration/saga")
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema))
+ .target("1002")
+ .load()
+ .migrate();
+ Flyway.configure()
+ .dataSource(dataSource)
+ .locations(MIGRATION_LOCATION, "classpath:db/migration/saga")
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema))
+ .load()
+ .migrate();
+ dsl = DSL.using(dataSource, SQLDialect.POSTGRES);
+ repository = new AutomationEmptySelectedSourceIntakeRepository(dsl);
+ }
+
+ @AfterEach
+ void dropIsolatedSchema() {
+ if (schema != null) {
+ String checkedSchema = schema.replaceAll("[^a-zA-Z0-9_]", "");
+ DSL.using(dataSource(null), SQLDialect.POSTGRES)
+ .execute("DROP SCHEMA IF EXISTS \"" + checkedSchema + "\" CASCADE");
+ schema = null;
+ }
+ }
+
+ @Test
+ void retainsCanonicalEmptyCensusAndExactReadbackAcrossCorrelationIndependentRetry() {
+ AutomationEmptySelectedSourceIntakePostgresFixture.Fixture fixture =
+ AutomationEmptySelectedSourceIntakePostgresFixture.create("1");
+ var inputs = fixture.inputs();
+ String requestDigest = requestDigest(fixture);
+
+ // This validates typed synthetic Common inputs; it does not authenticate either producer.
+ assertThat(inputs.authorizationBinding().targetNamespace())
+ .isEqualTo(AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE);
+ assertThat(inputs.authorizationBinding().tenantId())
+ .isEqualTo(AutomationEmptySelectedSourceIntakePostgresFixture.TENANT);
+ assertThat(inputs.authorizationBinding().versionId())
+ .isEqualTo(AutomationEmptySelectedSourceIntakePostgresFixture.VERSION);
+ assertThat(inputs.ownerSourceInventoryDeclaration().owner())
+ .isEqualTo(
+ net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner.AUTOMATION_SCRIPTING);
+ assertThat(
+ inputs
+ .worldInventoryReadEvidence()
+ .inventory()
+ .publicEvidence()
+ .sourceModel()
+ .inboundSourceClosure()
+ .familyCounts())
+ .allSatisfy(count -> assertThat(count.count()).isZero());
+
+ AutomationEmptySelectedSourceIntakeReceipt first =
+ repository.retainFresh(inputs, requestDigest);
+
+ assertThat(first.targetNamespace()).isEqualTo(inputs.authorizationBinding().targetNamespace());
+ assertThat(first.canonicalTenantId()).isEqualTo(inputs.authorizationBinding().tenantId());
+ assertThat(first.canonicalVersionId()).isEqualTo(inputs.authorizationBinding().versionId());
+ assertThat(first.selectedCommitId())
+ .isEqualTo(inputs.authorizationBinding().selected().commitId());
+ assertThat(first.sourceRevisionId())
+ .isEqualTo(inputs.ownerSourceInventoryDeclaration().revisionId());
+ assertThat(first.sourceRevisionOrder())
+ .isEqualTo(inputs.ownerSourceInventoryDeclaration().revisionOrder());
+ assertThat(first.localTenantKey()).isPositive();
+ assertThat(first.localVersionKey()).isPositive().isNotEqualTo(first.localTenantKey());
+ assertThat(first.outcome()).isEqualTo("COMMITTED_EMPTY");
+ assertThat(first.scriptsRowCount()).isZero();
+ assertThat(first.eventBindingsRowCount()).isZero();
+ assertThat(first.patchBaseBindingsRowCount()).isZero();
+ assertThat(first.unqualifiedScriptsRowCount()).isZero();
+ assertThat(first.unqualifiedEventBindingsRowCount()).isZero();
+ assertThat(first.unqualifiedPatchBaseBindingsRowCount()).isZero();
+ assertThat(first.emptyAssociatedScriptsRowCount()).isZero();
+ assertThat(first.emptyAssociatedEventBindingsRowCount()).isZero();
+ assertThat(first.emptyAssociatedPatchBaseBindingsRowCount()).isZero();
+ assertThat(first.selectedScopeScriptsRowCount()).isZero();
+ assertThat(first.selectedScopeEventBindingsRowCount()).isZero();
+ assertThat(first.selectedScopePatchBaseBindingsRowCount()).isZero();
+ assertThat(first.authorizationBindingBytes())
+ .containsExactly(inputs.authorizationBinding().canonicalBytes());
+ assertThat(first.worldInventoryBytes())
+ .containsExactly(inputs.worldInventoryReadEvidence().inventory().canonicalBytes());
+ assertThat(first.worldReadRequestId())
+ .isEqualTo(inputs.worldInventoryReadEvidence().request().readRequestId());
+
+ assertThat(rowCount("SELECT COUNT(*) FROM scripts")).isZero();
+ assertThat(rowCount("SELECT COUNT(*) FROM script_event_bindings")).isZero();
+ assertThat(rowCount("SELECT COUNT(*) FROM script_patch_base_bindings")).isZero();
+ assertThat(
+ rowCount(
+ "SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation "
+ + "WHERE claim_kind = 'CANONICAL_EMPTY_SOURCE'"))
+ .isEqualTo(2L);
+ assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_association"))
+ .isEqualTo(1L);
+ assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_receipt"))
+ .isEqualTo(1L);
+
+ Record storedReceipt =
+ dsl.fetchOne(
+ "SELECT receipt_bytes, receipt_digest, request_digest FROM "
+ + "automation_empty_selected_source_receipt "
+ + "WHERE target_namespace = ? AND intake_request_id = ?",
+ first.targetNamespace(),
+ first.intakeRequestId());
+ assertThat(storedReceipt).isNotNull();
+ assertThat(storedReceipt.get(0, byte[].class)).containsExactly(first.canonicalBytes());
+ assertThat(storedReceipt.get(1, String.class)).isEqualTo(first.receiptDigest());
+ assertThat(storedReceipt.get(2, String.class)).isEqualTo(first.requestDigest());
+
+ Record storedAssociation =
+ dsl.fetchOne(
+ "SELECT canonical_tenant_id, canonical_version_id, selected_commit_id, "
+ + "source_revision_id, source_revision_order, local_tenant_key, local_version_key, "
+ + "request_digest, authorization_binding_digest, receipt_digest "
+ + "FROM automation_empty_selected_source_association "
+ + "WHERE target_namespace = ? AND intake_request_id = ?",
+ first.targetNamespace(),
+ first.intakeRequestId());
+ assertThat(storedAssociation).isNotNull();
+ assertThat(storedAssociation.get(0, UUID.class)).isEqualTo(first.canonicalTenantId());
+ assertThat(storedAssociation.get(1, UUID.class)).isEqualTo(first.canonicalVersionId());
+ assertThat(storedAssociation.get(2, UUID.class)).isEqualTo(first.selectedCommitId());
+ assertThat(storedAssociation.get(3, UUID.class)).isEqualTo(first.sourceRevisionId());
+ assertThat(storedAssociation.get(4, String.class)).isEqualTo(first.sourceRevisionOrder());
+ assertThat(storedAssociation.get(5, Long.class)).isEqualTo(first.localTenantKey());
+ assertThat(storedAssociation.get(6, Long.class)).isEqualTo(first.localVersionKey());
+ assertThat(storedAssociation.get(7, String.class)).isEqualTo(first.requestDigest());
+ assertThat(storedAssociation.get(8, String.class))
+ .isEqualTo(first.authorizationBindingDigest());
+ assertThat(storedAssociation.get(9, String.class)).isEqualTo(first.receiptDigest());
+
+ var readBack = repository.read(first.targetNamespace(), first.intakeRequestId()).orElseThrow();
+ assertThat(readBack.canonicalBytes()).containsExactly(first.canonicalBytes());
+ assertThat(readBack.receiptDigest()).isEqualTo(first.receiptDigest());
+ var terminalRead = repository.readCommittedTerminal(fixture.authorization()).orElseThrow();
+ assertThat(terminalRead.canonicalBytes()).containsExactly(first.canonicalBytes());
+ assertThat(terminalRead.authorizationBindingBytes())
+ .containsExactly(fixture.authorization().canonicalBytes());
+
+ var retry =
+ AutomationEmptySelectedSourceIntakePostgresFixture.withFreshWorldReadCorrelation(fixture);
+ assertThat(retry.worldEvidence().request().readRequestId())
+ .isNotEqualTo(fixture.worldEvidence().request().readRequestId());
+ String retryDigest = requestDigest(retry);
+ assertThat(retryDigest).isEqualTo(requestDigest);
+ var retryReceipt = repository.retainFresh(retry.inputs(), retryDigest);
+ assertThat(retryReceipt.canonicalBytes()).containsExactly(first.canonicalBytes());
+ assertThat(retryReceipt.worldReadRequestId()).isEqualTo(first.worldReadRequestId());
+
+ var altered = AutomationEmptySelectedSourceIntakePostgresFixture.create("2");
+ assertThat(altered.authorization().intakeRequestId())
+ .isEqualTo(fixture.authorization().intakeRequestId());
+ assertThat(altered.authorization().canonicalBytes())
+ .isNotEqualTo(fixture.authorization().canonicalBytes());
+ assertThatThrownBy(() -> repository.readCommittedTerminal(altered.authorization()))
+ .isInstanceOf(AutomationEmptySelectedSourceIntakeRepository.IntakeConflictException.class)
+ .hasMessageContaining("complete original authorization");
+ String alteredDigest = requestDigest(altered);
+ assertThat(alteredDigest).isNotEqualTo(requestDigest);
+ assertThatThrownBy(() -> repository.retainFresh(altered.inputs(), alteredDigest))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("already records different selected evidence");
+
+ assertThat(
+ rowCount(
+ "SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation "
+ + "WHERE claim_kind = 'CANONICAL_EMPTY_SOURCE'"))
+ .isEqualTo(2L);
+ assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_association"))
+ .isEqualTo(1L);
+ assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_receipt"))
+ .isEqualTo(1L);
+ Record unchangedReceipt =
+ dsl.fetchOne(
+ "SELECT receipt_bytes FROM automation_empty_selected_source_receipt "
+ + "WHERE target_namespace = ? AND intake_request_id = ?",
+ first.targetNamespace(),
+ first.intakeRequestId());
+ assertThat(unchangedReceipt).isNotNull();
+ assertThat(unchangedReceipt.get(0, byte[].class)).containsExactly(first.canonicalBytes());
+
+ assertThatThrownBy(
+ () ->
+ dsl.execute(
+ "UPDATE automation_empty_selected_source_receipt SET receipt_bytes = ? "
+ + "WHERE target_namespace = ? AND intake_request_id = ?",
+ first.canonicalBytes(),
+ first.targetNamespace(),
+ first.intakeRequestId()))
+ .rootCause()
+ .hasMessageContaining("Automation empty-source intake records are immutable");
+
+ byte[] corruptBytes = first.canonicalBytes();
+ corruptBytes[0] ^= 1;
+ // The isolated test owner bypasses only V1003's immutable receipt-row trigger to model corruption.
+ dsl.execute(
+ "ALTER TABLE automation_empty_selected_source_receipt "
+ + "DISABLE TRIGGER trg_automation_empty_source_receipt_immutable");
+ try {
+ assertThat(
+ dsl.execute(
+ "UPDATE automation_empty_selected_source_receipt SET receipt_bytes = ? "
+ + "WHERE target_namespace = ? AND intake_request_id = ?",
+ corruptBytes,
+ first.targetNamespace(),
+ first.intakeRequestId()))
+ .isEqualTo(1);
+ } finally {
+ dsl.execute(
+ "ALTER TABLE automation_empty_selected_source_receipt "
+ + "ENABLE TRIGGER trg_automation_empty_source_receipt_immutable");
+ }
+ assertThatThrownBy(() -> repository.readCommittedTerminal(fixture.authorization()))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ repository.readPublicationScope(
+ AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE,
+ AutomationEmptySelectedSourceIntakePostgresFixture.TENANT,
+ fixture.authorization().selected().target().gameDesignVersionRowId()))
+ .isInstanceOf(RuntimeException.class);
+ }
+
+ @Test
+ void selectedEmptyPublicationReaderUsesTheRetainedTargetProofAndReturnsSchemaSixDigest() {
+ AutomationEmptySelectedSourceIntakePostgresFixture.Fixture fixture =
+ AutomationEmptySelectedSourceIntakePostgresFixture.create("1");
+ AutomationEmptySelectedSourceIntakeReceipt receipt =
+ repository.retainFresh(fixture.inputs(), requestDigest(fixture));
+ long gameDesignVersionRowId =
+ fixture.authorization().selected().target().gameDesignVersionRowId();
+
+ assertThat(
+ repository
+ .readPublicationScope(
+ AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE,
+ AutomationEmptySelectedSourceIntakePostgresFixture.TENANT,
+ gameDesignVersionRowId)
+ .canonicalBytes())
+ .containsExactly(receipt.canonicalBytes());
+ assertThatThrownBy(
+ () ->
+ repository.readPublicationScope(
+ AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE,
+ AutomationEmptySelectedSourceIntakePostgresFixture.TENANT,
+ gameDesignVersionRowId + 1L))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("missing or ambiguous");
+
+ var digest =
+ new AutomationSelectedEmptyPublicationDigestService(
+ AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, repository)
+ .getDraftDesignDigest(
+ PublicationDigestRequestBinding.full(
+ AutomationEmptySelectedSourceIntakePostgresFixture.TENANT.toString(),
+ Long.toString(gameDesignVersionRowId),
+ fixture.freezeEvidence().request().publicationRequestId()));
+ assertThat(digest.tenantId())
+ .isEqualTo(AutomationEmptySelectedSourceIntakePostgresFixture.TENANT.toString());
+ assertThat(digest.scopeValue()).isEqualTo(Long.toString(gameDesignVersionRowId));
+ assertThat(digest.baseVersionId()).isZero();
+ assertThat(digest.appliedCommitId()).isEqualTo(receipt.selectedCommitId().toString());
+ String canonicalInventoryJson =
+ fixture.inputs().ownerSourceInventoryDeclaration().inventory().canonicalJson();
+ assertThat(digest.contentDigest())
+ .isEqualTo(
+ expectedSelectedEmptyDigest(
+ "automation-selected-empty-publication-digest/v1",
+ "6",
+ AutomationEmptySelectedSourceIntakePostgresFixture.TENANT,
+ gameDesignVersionRowId,
+ receipt.canonicalVersionId(),
+ canonicalInventoryJson));
+ assertThat(digest.digestSchemaVersion())
+ .isEqualTo(AutomationSelectedEmptyPublicationDigestService.DIGEST_SCHEMA_VERSION);
+
+ String rowBeforeMismatchedPublicationRead =
+ dsl.fetchSingle(
+ "SELECT encode(receipt_bytes, 'hex') || ':' || xmin::text "
+ + "FROM automation_empty_selected_source_receipt "
+ + "WHERE target_namespace = ? AND intake_request_id = ?",
+ receipt.targetNamespace(),
+ receipt.intakeRequestId())
+ .get(0, String.class);
+ assertThatThrownBy(
+ () ->
+ new AutomationSelectedEmptyPublicationDigestService(
+ AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, repository)
+ .getDraftDesignDigest(
+ PublicationDigestRequestBinding.full(
+ AutomationEmptySelectedSourceIntakePostgresFixture.TENANT.toString(),
+ Long.toString(gameDesignVersionRowId),
+ "publish-request-2")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("original retained World freeze");
+ String rowAfterMismatchedPublicationRead =
+ dsl.fetchSingle(
+ "SELECT encode(receipt_bytes, 'hex') || ':' || xmin::text "
+ + "FROM automation_empty_selected_source_receipt "
+ + "WHERE target_namespace = ? AND intake_request_id = ?",
+ receipt.targetNamespace(),
+ receipt.intakeRequestId())
+ .get(0, String.class);
+ assertThat(rowAfterMismatchedPublicationRead)
+ .isEqualTo(rowBeforeMismatchedPublicationRead);
+ }
+
+ @Test
+ void publicationScopeScanAndReceiptReadbackUseOneRepeatableReadSnapshot() {
+ AutomationEmptySelectedSourceIntakePostgresFixture.Fixture fixture =
+ AutomationEmptySelectedSourceIntakePostgresFixture.create("1");
+ AutomationEmptySelectedSourceIntakeReceipt receipt =
+ repository.retainFresh(fixture.inputs(), requestDigest(fixture));
+ byte[] concurrentlyCorruptedBytes = receipt.canonicalBytes();
+ concurrentlyCorruptedBytes[0] ^= 1;
+ AtomicBoolean concurrentMutationApplied = new AtomicBoolean();
+ dsl.configuration()
+ .set(
+ new DefaultExecuteListenerProvider(
+ new DefaultExecuteListener() {
+ @Override
+ public void executeEnd(ExecuteContext context) {
+ String sql = context.sql();
+ if (sql == null
+ || !sql.toLowerCase(Locale.ROOT)
+ .contains("from automation_empty_selected_source_association")
+ || !concurrentMutationApplied.compareAndSet(false, true)) {
+ return;
+ }
+ DSLContext concurrentDsl = DSL.using(dataSource(schema), SQLDialect.POSTGRES);
+ concurrentDsl.execute(
+ "ALTER TABLE automation_empty_selected_source_receipt "
+ + "DISABLE TRIGGER trg_automation_empty_source_receipt_immutable");
+ try {
+ assertThat(
+ concurrentDsl.execute(
+ "UPDATE automation_empty_selected_source_receipt "
+ + "SET receipt_bytes = ? WHERE target_namespace = ? "
+ + "AND intake_request_id = ?",
+ concurrentlyCorruptedBytes,
+ receipt.targetNamespace(),
+ receipt.intakeRequestId()))
+ .isEqualTo(1);
+ } finally {
+ concurrentDsl.execute(
+ "ALTER TABLE automation_empty_selected_source_receipt "
+ + "ENABLE TRIGGER trg_automation_empty_source_receipt_immutable");
+ }
+ }
+ }));
+
+ AutomationEmptySelectedSourceIntakeReceipt read =
+ repository.readPublicationScope(
+ receipt.targetNamespace(),
+ receipt.canonicalTenantId(),
+ fixture.authorization().selected().target().gameDesignVersionRowId());
+
+ assertThat(read.canonicalBytes()).containsExactly(receipt.canonicalBytes());
+ assertThat(concurrentMutationApplied).isTrue();
+ Record storedReceipt =
+ dsl.fetchOne(
+ "SELECT receipt_bytes FROM automation_empty_selected_source_receipt "
+ + "WHERE target_namespace = ? AND intake_request_id = ?",
+ receipt.targetNamespace(),
+ receipt.intakeRequestId());
+ assertThat(storedReceipt).isNotNull();
+ assertThat(storedReceipt.get(0, byte[].class)).containsExactly(concurrentlyCorruptedBytes);
+ }
+
+ @Test
+ void deniesUnqualifiedRowsInEachAuthoredFamilyWithoutCreatingOwnerRecords() {
+ var fixture = AutomationEmptySelectedSourceIntakePostgresFixture.create("1");
+ String requestDigest = requestDigest(fixture);
+
+ dsl.execute(
+ "INSERT INTO scripts (tenant_id, name, version, definition) VALUES (?, ?, ?, ?)",
+ 501L,
+ "unqualified-script",
+ "legacy-patch",
+ "{}");
+ assertUnqualifiedDenial(fixture, requestDigest);
+ dsl.execute("DELETE FROM scripts WHERE name = ?", "unqualified-script");
+
+ dsl.execute(
+ "INSERT INTO script_event_bindings (tenant_id, script_patch_version, event_type, "
+ + "event_schema_version, script_id, target_scope_type, target_scope_id) "
+ + "VALUES (?, ?, ?, ?, ?, ?, ?)",
+ 502L,
+ "unqualified-event-patch",
+ "unqualified-event",
+ "v1",
+ "unqualified-script",
+ "TENANT",
+ "test");
+ assertUnqualifiedDenial(fixture, requestDigest);
+ dsl.execute(
+ "DELETE FROM script_event_bindings WHERE script_patch_version = ?",
+ "unqualified-event-patch");
+
+ dsl.execute(
+ "INSERT INTO script_patch_base_bindings (tenant_id, script_patch_version, base_version_id) "
+ + "VALUES (?, ?, ?)",
+ "unqualified-tenant-key",
+ "unqualified-patch",
+ 503L);
+ assertUnqualifiedDenial(fixture, requestDigest);
+ dsl.execute(
+ "DELETE FROM script_patch_base_bindings WHERE script_patch_version = ?",
+ "unqualified-patch");
+
+ assertThat(rowCount("SELECT COUNT(*) FROM scripts")).isZero();
+ assertThat(rowCount("SELECT COUNT(*) FROM script_event_bindings")).isZero();
+ assertThat(rowCount("SELECT COUNT(*) FROM script_patch_base_bindings")).isZero();
+ assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation"))
+ .isZero();
+ assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_association"))
+ .isZero();
+ assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_receipt")).isZero();
+ }
+
+ private void assertUnqualifiedDenial(
+ AutomationEmptySelectedSourceIntakePostgresFixture.Fixture fixture, String requestDigest) {
+ assertThatThrownBy(() -> repository.retainFresh(fixture.inputs(), requestDigest))
+ .isInstanceOf(
+ AutomationEmptySelectedSourceIntakeRepository.UnqualifiedSourceRowsException.class);
+ assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation"))
+ .isZero();
+ assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_association"))
+ .isZero();
+ assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_receipt")).isZero();
+ }
+
+ private static String requestDigest(
+ AutomationEmptySelectedSourceIntakePostgresFixture.Fixture fixture) {
+ return AutomationEmptySelectedSourceIntakeReceipt.requestDigest(
+ AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE,
+ fixture.authorization(),
+ fixture.freezeEvidence());
+ }
+
+ private static String expectedSelectedEmptyDigest(
+ String domain,
+ String schemaVersion,
+ UUID canonicalTenantId,
+ long gameDesignVersionRowId,
+ UUID canonicalVersionId,
+ String canonicalInventoryJson) {
+ ByteArrayOutputStream preimage = new ByteArrayOutputStream();
+ appendDigestSegment(preimage, domain);
+ appendDigestSegment(preimage, schemaVersion);
+ appendDigestSegment(preimage, canonicalTenantId.toString());
+ appendDigestSegment(preimage, Long.toString(gameDesignVersionRowId));
+ appendDigestSegment(preimage, canonicalVersionId.toString());
+ appendDigestSegment(preimage, canonicalInventoryJson);
+ try {
+ return HexFormat.of()
+ .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray()));
+ } catch (NoSuchAlgorithmException impossible) {
+ throw new AssertionError(impossible);
+ }
+ }
+
+ private static void appendDigestSegment(ByteArrayOutputStream output, String value) {
+ byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
+ output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII));
+ output.write(':');
+ output.writeBytes(bytes);
+ }
+
+ private long rowCount(String sql, Object... parameters) {
+ Record record = dsl.fetchOne(sql, parameters);
+ assertThat(record).isNotNull();
+ Long value = record.get(0, Long.class);
+ assertThat(value).isNotNull();
+ return value;
+ }
+
+ private DriverManagerDataSource dataSource(String schemaName) {
+ DriverManagerDataSource dataSource = new DriverManagerDataSource();
+ dataSource.setDriverClassName(postgres.getDriverClassName());
+ String baseUrl = postgres.getJdbcUrl();
+ dataSource.setUrl(
+ schemaName == null
+ ? baseUrl
+ : baseUrl + (baseUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName);
+ dataSource.setUsername(postgres.getUsername());
+ dataSource.setPassword(postgres.getPassword());
+ return dataSource;
+ }
+}
diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java
new file mode 100644
index 0000000000..1ffe6fb46a
--- /dev/null
+++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java
@@ -0,0 +1,323 @@
+package net.firedevops.firemud.automationscripting.repository;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import io.grpc.Context;
+import java.util.List;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Supplier;
+import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository;
+import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeService;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient;
+import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence;
+import net.firedevops.firemud.common.security.SessionContext;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InOrder;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/**
+ * Mocked service ordering proof using exact typed, synthetic Common owner-input fixtures.
+ * Collaborator echoes here are not authenticated producer or physical owner proof.
+ */
+class AutomationEmptySelectedSourceIntakeServiceIntegrationTest {
+ private static final String NAMESPACE =
+ AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE;
+
+ @BeforeEach
+ void clearPriorContexts() {
+ SessionContext.clear();
+ TransactionSynchronizationManager.setActualTransactionActive(false);
+ if (TransactionSynchronizationManager.isSynchronizationActive()) {
+ TransactionSynchronizationManager.clearSynchronization();
+ }
+ }
+
+ @AfterEach
+ void clearContexts() {
+ SessionContext.clear();
+ TransactionSynchronizationManager.setActualTransactionActive(false);
+ if (TransactionSynchronizationManager.isSynchronizationActive()) {
+ TransactionSynchronizationManager.clearSynchronization();
+ }
+ }
+
+ @Test
+ void freshTypedInputsReachRepositoryOnlyAfterTwoAccountEchoesAndWorldEcho() {
+ var fixture = AutomationEmptySelectedSourceIntakePostgresFixture.create("1");
+ var inputs = fixture.inputs();
+ var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class);
+ var accountClient = mock(SelectedOwnerIntakeAuthorizationReadClient.class);
+ var worldClient = mock(SelectedOwnerWorldInventoryReadClient.class);
+ var receipt = mock(AutomationEmptySelectedSourceIntakeReceipt.class);
+ when(repository.read(NAMESPACE, inputs.authorizationBinding().intakeRequestId()))
+ .thenReturn(Optional.empty());
+ when(repository.retainFresh(any(SelectedOwnerEmptySourceInputs.class), anyString()))
+ .thenReturn(receipt);
+ when(accountClient.read(any()))
+ .thenAnswer(
+ invocation ->
+ new SelectedOwnerIntakeAuthorizationReadEvidence(invocation.getArgument(0)));
+ when(worldClient.read(any()))
+ .thenAnswer(
+ invocation ->
+ new SelectedOwnerWorldInventoryReadEvidence(
+ invocation.getArgument(0), fixture.worldEvidence().inventory()));
+
+ var service =
+ new AutomationEmptySelectedSourceIntakeService(repository, accountClient, worldClient);
+ String requestDigest =
+ AutomationEmptySelectedSourceIntakeReceipt.requestDigest(
+ NAMESPACE, fixture.authorization(), fixture.freezeEvidence());
+
+ AutomationEmptySelectedSourceIntakeReceipt returned =
+ withGameDesignPeer(
+ () -> service.retain(NAMESPACE, fixture.authorization(), fixture.freezeEvidence()));
+
+ assertThat(returned).isSameAs(receipt);
+ ArgumentCaptor accountRequests =
+ ArgumentCaptor.forClass(SelectedOwnerIntakeAuthorizationReadEvidence.Request.class);
+ ArgumentCaptor worldRequests =
+ ArgumentCaptor.forClass(SelectedOwnerWorldInventoryReadEvidence.Request.class);
+ ArgumentCaptor retainedInputs =
+ ArgumentCaptor.forClass(SelectedOwnerEmptySourceInputs.class);
+ InOrder order = inOrder(repository, accountClient, worldClient, receipt);
+ order.verify(repository).read(NAMESPACE, inputs.authorizationBinding().intakeRequestId());
+ order.verify(accountClient).read(accountRequests.capture());
+ order.verify(worldClient).read(worldRequests.capture());
+ order.verify(accountClient).read(accountRequests.capture());
+ order.verify(repository).retainFresh(retainedInputs.capture(), eq(requestDigest));
+ order
+ .verify(receipt)
+ .requireSameRequest(NAMESPACE, fixture.authorization(), fixture.freezeEvidence());
+
+ assertThat(accountRequests.getAllValues()).hasSize(2);
+ assertThat(accountRequests.getAllValues().get(0).binding()).isEqualTo(fixture.authorization());
+ assertThat(accountRequests.getAllValues().get(1).binding()).isEqualTo(fixture.authorization());
+ assertThat(accountRequests.getAllValues().get(0).readRequestId())
+ .isNotEqualTo(accountRequests.getAllValues().get(1).readRequestId());
+ assertThat(worldRequests.getValue().authorizationBinding()).isEqualTo(fixture.authorization());
+ assertThat(worldRequests.getValue().freezeEvidence()).isEqualTo(fixture.freezeEvidence());
+
+ SelectedOwnerEmptySourceInputs actualInputs = retainedInputs.getValue();
+ assertThat(actualInputs.authorizationBinding().canonicalBytes())
+ .containsExactly(fixture.authorization().canonicalBytes());
+ assertThat(actualInputs.authorizationBinding().digest())
+ .isEqualTo(fixture.authorization().digest());
+ assertThat(actualInputs.sourceContent().canonicalBytes())
+ .containsExactly(fixture.authorization().content().canonicalBytes());
+ assertThat(actualInputs.sourceContent().digest())
+ .isEqualTo(fixture.authorization().content().digest());
+ for (String family :
+ List.of(
+ "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) {
+ assertThat(actualInputs.sourceContent().snapshotBytes(family))
+ .containsExactly(fixture.authorization().content().snapshotBytes(family));
+ }
+ var actualDeclaration = actualInputs.ownerSourceInventoryDeclaration();
+ var expectedDeclaration = inputs.ownerSourceInventoryDeclaration();
+ assertThat(actualDeclaration.owner()).isEqualTo(expectedDeclaration.owner());
+ assertThat(actualDeclaration.inventory().canonicalJson())
+ .isEqualTo(expectedDeclaration.inventory().canonicalJson());
+ assertThat(actualDeclaration.sourceBinding().canonicalBytes())
+ .containsExactly(expectedDeclaration.sourceBinding().canonicalBytes());
+ assertThat(actualDeclaration.revisionOrder()).isEqualTo(expectedDeclaration.revisionOrder());
+ assertThat(actualDeclaration.revisionId()).isEqualTo(expectedDeclaration.revisionId());
+ assertThat(actualInputs.worldInventoryReadEvidence().request())
+ .isEqualTo(worldRequests.getValue());
+ assertThat(actualInputs.worldInventoryReadEvidence().inventory().canonicalBytes())
+ .containsExactly(fixture.worldEvidence().inventory().canonicalBytes());
+ assertThat(actualInputs.worldInventoryReadEvidence().inventory().digest())
+ .isEqualTo(fixture.worldEvidence().inventory().digest());
+ }
+
+ @Test
+ void unavailableOrMismatchedAccountAndWorldEchoesNeverReachFreshRetention() {
+ var fixture = AutomationEmptySelectedSourceIntakePostgresFixture.create("1");
+ for (ReadFailure failure : ReadFailure.values()) {
+ var inputs = fixture.inputs();
+ var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class);
+ var accountClient = mock(SelectedOwnerIntakeAuthorizationReadClient.class);
+ var worldClient = mock(SelectedOwnerWorldInventoryReadClient.class);
+ when(repository.read(NAMESPACE, inputs.authorizationBinding().intakeRequestId()))
+ .thenReturn(Optional.empty());
+
+ AtomicInteger accountReads = new AtomicInteger();
+ when(accountClient.read(any()))
+ .thenAnswer(
+ invocation -> {
+ var request =
+ invocation.getArgument(
+ 0, SelectedOwnerIntakeAuthorizationReadEvidence.Request.class);
+ int call = accountReads.incrementAndGet();
+ if (failure == ReadFailure.FIRST_ACCOUNT_UNAVAILABLE && call == 1
+ || failure == ReadFailure.FINAL_ACCOUNT_UNAVAILABLE && call == 2) {
+ return null;
+ }
+ if (failure == ReadFailure.FIRST_ACCOUNT_MISMATCH && call == 1
+ || failure == ReadFailure.FINAL_ACCOUNT_MISMATCH && call == 2) {
+ request = mismatched(request);
+ }
+ return new SelectedOwnerIntakeAuthorizationReadEvidence(request);
+ });
+
+ AtomicInteger worldReads = new AtomicInteger();
+ when(worldClient.read(any()))
+ .thenAnswer(
+ invocation -> {
+ var request =
+ invocation.getArgument(
+ 0, SelectedOwnerWorldInventoryReadEvidence.Request.class);
+ worldReads.incrementAndGet();
+ if (failure == ReadFailure.WORLD_UNAVAILABLE) return null;
+ if (failure == ReadFailure.WORLD_MISMATCH) request = mismatched(request);
+ return new SelectedOwnerWorldInventoryReadEvidence(
+ request, fixture.worldEvidence().inventory());
+ });
+
+ var service =
+ new AutomationEmptySelectedSourceIntakeService(repository, accountClient, worldClient);
+ assertThatThrownBy(
+ () ->
+ withGameDesignPeer(
+ () ->
+ service.retain(
+ NAMESPACE, fixture.authorization(), fixture.freezeEvidence())))
+ .as(failure.name())
+ .isInstanceOf(IllegalStateException.class);
+
+ verify(repository).read(NAMESPACE, inputs.authorizationBinding().intakeRequestId());
+ verify(repository, never())
+ .retainFresh(any(SelectedOwnerEmptySourceInputs.class), anyString());
+ int expectedAccountReads =
+ failure == ReadFailure.FINAL_ACCOUNT_UNAVAILABLE
+ || failure == ReadFailure.FINAL_ACCOUNT_MISMATCH
+ ? 2
+ : 1;
+ int expectedWorldReads =
+ failure == ReadFailure.FIRST_ACCOUNT_UNAVAILABLE
+ || failure == ReadFailure.FIRST_ACCOUNT_MISMATCH
+ ? 0
+ : 1;
+ assertThat(accountReads.get()).isEqualTo(expectedAccountReads);
+ assertThat(worldReads.get()).isEqualTo(expectedWorldReads);
+ }
+ }
+
+ @Test
+ void exactStoredRetryReturnsBeforeRemoteOwnerReads() {
+ var fixture = AutomationEmptySelectedSourceIntakePostgresFixture.create("1");
+ var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class);
+ var accountClient = mock(SelectedOwnerIntakeAuthorizationReadClient.class);
+ var worldClient = mock(SelectedOwnerWorldInventoryReadClient.class);
+ var retained = mock(AutomationEmptySelectedSourceIntakeReceipt.class);
+ when(repository.read(NAMESPACE, fixture.authorization().intakeRequestId()))
+ .thenReturn(Optional.of(retained));
+ var service =
+ new AutomationEmptySelectedSourceIntakeService(repository, accountClient, worldClient);
+
+ var returned =
+ withGameDesignPeer(
+ () -> service.retain(NAMESPACE, fixture.authorization(), fixture.freezeEvidence()));
+
+ assertThat(returned).isSameAs(retained);
+ verify(repository).read(NAMESPACE, fixture.authorization().intakeRequestId());
+ verify(retained)
+ .requireSameRequest(NAMESPACE, fixture.authorization(), fixture.freezeEvidence());
+ verify(repository, never()).retainFresh(any(SelectedOwnerEmptySourceInputs.class), anyString());
+ verifyNoInteractions(accountClient, worldClient);
+ }
+
+ private static SelectedOwnerIntakeAuthorizationReadEvidence.Request mismatched(
+ SelectedOwnerIntakeAuthorizationReadEvidence.Request request) {
+ UUID differentId =
+ differentReadId(
+ request.readRequestId(),
+ request.binding().operationId(),
+ request.binding().fenceId(),
+ request.binding().intakeRequestId());
+ return new SelectedOwnerIntakeAuthorizationReadEvidence.Request(
+ request.schemaVersion(), request.targetNamespace(), differentId, request.binding());
+ }
+
+ private static SelectedOwnerWorldInventoryReadEvidence.Request mismatched(
+ SelectedOwnerWorldInventoryReadEvidence.Request request) {
+ var binding = request.authorizationBinding();
+ var accountBinding = request.freezeEvidence().request().accountBinding();
+ var acknowledgement = request.freezeEvidence().acknowledgement();
+ UUID differentId =
+ differentReadId(
+ request.readRequestId(),
+ binding.operationId(),
+ binding.fenceId(),
+ binding.intakeRequestId(),
+ accountBinding.operationId(),
+ accountBinding.fenceId(),
+ acknowledgement.intakeRequestId(),
+ acknowledgement.publicationFence());
+ return new SelectedOwnerWorldInventoryReadEvidence.Request(
+ request.schemaVersion(),
+ request.targetNamespace(),
+ differentId,
+ binding,
+ request.freezeEvidence());
+ }
+
+ private static UUID differentReadId(UUID original, UUID... reserved) {
+ UUID candidate;
+ do {
+ candidate = UUID.randomUUID();
+ } while (candidate.equals(original) || contains(reserved, candidate));
+ return candidate;
+ }
+
+ private static boolean contains(UUID[] values, UUID candidate) {
+ for (UUID value : values) {
+ if (candidate.equals(value)) return true;
+ }
+ return false;
+ }
+
+ private static T withGameDesignPeer(Supplier action) {
+ GrpcPeerIdentity peer =
+ new GrpcPeerIdentity(
+ "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service",
+ NAMESPACE,
+ "game-design-service");
+ Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer);
+ Context previous = context.attach();
+ try {
+ return action.get();
+ } finally {
+ context.detach(previous);
+ }
+ }
+
+ private enum ReadFailure {
+ FIRST_ACCOUNT_UNAVAILABLE,
+ FIRST_ACCOUNT_MISMATCH,
+ WORLD_UNAVAILABLE,
+ WORLD_MISMATCH,
+ FINAL_ACCOUNT_UNAVAILABLE,
+ FINAL_ACCOUNT_MISMATCH
+ }
+}
diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java
new file mode 100644
index 0000000000..362bc66c08
--- /dev/null
+++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java
@@ -0,0 +1,455 @@
+package net.firedevops.firemud.automationscripting.repository;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import io.grpc.Server;
+import io.grpc.ServerInterceptors;
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
+import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
+import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth;
+import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository;
+import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeTerminalReadService;
+import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedSourceIntakeTerminalReadGrpcService;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence;
+import net.firedevops.firemud.common.config.ServiceEndpointsProperties;
+import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties;
+import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor;
+import net.firedevops.firemud.test.TestContainerImages;
+import org.flywaydb.core.Flyway;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.jooq.SQLDialect;
+import org.jooq.impl.DSL;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.testcontainers.containers.PostgreSQLContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+/**
+ * Native Account mTLS proof for Automation's owner edge; upstream fixture evidence stays synthetic.
+ */
+@Testcontainers(disabledWithoutDocker = true)
+@SuppressWarnings("resource")
+class AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest {
+ private static final String NS = "test";
+ private static final String ACCOUNT = "spiffe://firemud/ns/test/sa/account-service";
+ private static final String AUTOMATION =
+ "spiffe://firemud/ns/test/sa/automation-scripting-service";
+ private static final String WRONG_ACCOUNT = "spiffe://firemud/ns/other/sa/account-service";
+ private static final String PASSWORD = "test-only-store-password";
+ private static final String MIGRATIONS =
+ "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize();
+
+ @TempDir static Path temp;
+
+ @Container
+ static PostgreSQLContainer> postgres =
+ new PostgreSQLContainer<>(TestContainerImages.postgres());
+
+ private static Pki pki;
+ private static Identity serverIdentity;
+ private static Identity accountIdentity;
+ private static Identity wrongIdentity;
+
+ private String schema;
+ private DSLContext dsl;
+ private AutomationEmptySelectedSourceIntakeRepository repository;
+ private Server server;
+ private AutomationSelectedSourceIntakeTerminalReadClient client;
+
+ @BeforeAll
+ static void issueCertificates() throws Exception {
+ pki = Pki.create(temp);
+ serverIdentity = Pki.issue(temp, pki.store(), pki.caFile(), "automation", AUTOMATION, true);
+ accountIdentity = Pki.issue(temp, pki.store(), pki.caFile(), "account", ACCOUNT, false);
+ wrongIdentity =
+ Pki.issue(temp, pki.store(), pki.caFile(), "wrong-account", WRONG_ACCOUNT, false);
+ }
+
+ @BeforeEach
+ void migrateIsolatedSchema() {
+ schema = "automation_terminal_read_" + UUID.randomUUID().toString().replace("-", "");
+ DriverManagerDataSource ds = dataSource(schema);
+ Flyway.configure()
+ .dataSource(ds)
+ .locations(MIGRATIONS, "classpath:db/migration/saga")
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema))
+ .target("1002")
+ .load()
+ .migrate();
+ Flyway.configure()
+ .dataSource(ds)
+ .locations(MIGRATIONS, "classpath:db/migration/saga")
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema))
+ .load()
+ .migrate();
+ dsl = DSL.using(ds, SQLDialect.POSTGRES);
+ repository = new AutomationEmptySelectedSourceIntakeRepository(dsl);
+ }
+
+ @AfterEach
+ void cleanup() throws Exception {
+ if (client != null) {
+ client.close();
+ client = null;
+ }
+ if (server != null) {
+ server.shutdownNow();
+ assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue();
+ server = null;
+ }
+ if (schema != null) {
+ String safeSchema = schema.replaceAll("[^a-zA-Z0-9_]", "");
+ DSL.using(dataSource(null), SQLDialect.POSTGRES)
+ .execute("DROP SCHEMA IF EXISTS \"" + safeSchema + "\" CASCADE");
+ schema = null;
+ }
+ }
+
+ @Test
+ void readsStoredCommittedEmptyReceiptOverAccountMtlsAndRejectsWrongNamespace() throws Exception {
+ var fixture = AutomationEmptySelectedSourceIntakePostgresFixture.create("1");
+ String digest =
+ AutomationEmptySelectedSourceIntakeReceipt.requestDigest(
+ NS, fixture.authorization(), fixture.freezeEvidence());
+
+ // These typed Common inputs are synthetic; proof covers only Automation's owner edge.
+ var committed = repository.retainFresh(fixture.inputs(), digest);
+ assertThat(committed.outcome()).isEqualTo("COMMITTED_EMPTY");
+ Record stored =
+ dsl.fetchSingle(
+ "SELECT receipt_bytes, receipt_digest FROM automation_empty_selected_source_receipt "
+ + "WHERE target_namespace = ? AND intake_request_id = ?",
+ committed.targetNamespace(),
+ committed.intakeRequestId());
+ assertThat(stored).isNotNull();
+ assertThat(stored.get(0, byte[].class)).containsExactly(committed.canonicalBytes());
+ assertThat(stored.get(1, String.class)).isEqualTo(committed.receiptDigest());
+
+ startReceiver();
+ client = newClient(accountIdentity);
+ client.init();
+ var request =
+ AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(
+ NS, fixture.authorization());
+ var first = client.read(request);
+ assertThat(first.receipt().canonicalBytes()).containsExactly(stored.get(0, byte[].class));
+ assertThat(first.receipt().receiptDigest()).isEqualTo(stored.get(1, String.class));
+ assertThat(first.receipt().outcome()).isEqualTo("COMMITTED_EMPTY");
+
+ var replayRequest =
+ AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(
+ NS, fixture.authorization());
+ assertThat(replayRequest.readRequestId()).isNotEqualTo(request.readRequestId());
+ var replay = client.read(replayRequest);
+ assertThat(replay.request()).isEqualTo(replayRequest);
+ assertThat(replay.receipt().canonicalBytes()).containsExactly(first.receipt().canonicalBytes());
+ assertThat(replay.receipt().receiptDigest()).isEqualTo(first.receipt().receiptDigest());
+
+ var wrongClient = newClient(wrongIdentity);
+ try {
+ wrongClient.init();
+ assertThatThrownBy(() -> wrongClient.read(request))
+ .isInstanceOf(StatusRuntimeException.class)
+ .satisfies(
+ e ->
+ assertThat(Status.fromThrowable(e).getCode())
+ .isEqualTo(Status.Code.PERMISSION_DENIED));
+ } finally {
+ wrongClient.close();
+ }
+ assertThat(count("SELECT COUNT(*) FROM automation_empty_selected_source_association"))
+ .isEqualTo(1);
+ assertThat(count("SELECT COUNT(*) FROM automation_empty_selected_source_receipt")).isEqualTo(1);
+ Record unchanged =
+ dsl.fetchSingle(
+ "SELECT receipt_bytes, receipt_digest FROM automation_empty_selected_source_receipt "
+ + "WHERE target_namespace = ? AND intake_request_id = ?",
+ committed.targetNamespace(),
+ committed.intakeRequestId());
+ assertThat(unchanged).isNotNull();
+ assertThat(unchanged.get(0, byte[].class)).containsExactly(first.receipt().canonicalBytes());
+ assertThat(unchanged.get(1, String.class)).isEqualTo(first.receipt().receiptDigest());
+ }
+
+ private void startReceiver() throws Exception {
+ var owner = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NS);
+ var service = new AutomationSelectedSourceIntakeTerminalReadGrpcService(owner);
+ server =
+ NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0))
+ .maxInboundMessageSize(
+ net.firedevops.firemud.common.automation.sourceintake
+ .AutomationSelectedSourceIntakeTerminalReadGrpcCodec.MAX_WIRE_BYTES)
+ .sslContext(
+ GrpcSslContexts.configure(
+ SslContextBuilder.forServer(serverIdentity.key(), serverIdentity.cert()))
+ .trustManager(pki.caCert())
+ .clientAuth(ClientAuth.REQUIRE)
+ .build())
+ .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor()))
+ .build()
+ .start();
+ }
+
+ private AutomationSelectedSourceIntakeTerminalReadClient newClient(Identity identity)
+ throws Exception {
+ var endpoints = new ServiceEndpointsProperties();
+ endpoints.setAutomationScriptingService("127.0.0.1:" + server.getPort());
+ return new AutomationSelectedSourceIntakeTerminalReadClient(
+ endpoints, pki.clientProperties(temp, identity), new GrpcChannelFactory(), NS);
+ }
+
+ private DriverManagerDataSource dataSource(String schemaName) {
+ var ds = new DriverManagerDataSource();
+ ds.setDriverClassName(postgres.getDriverClassName());
+ String base = postgres.getJdbcUrl();
+ ds.setUrl(
+ schemaName == null
+ ? base
+ : base + (base.contains("?") ? "&" : "?") + "currentSchema=" + schemaName);
+ ds.setUsername(postgres.getUsername());
+ ds.setPassword(postgres.getPassword());
+ return ds;
+ }
+
+ private long count(String sql) {
+ return dsl.fetchSingle(sql).get(0, Long.class);
+ }
+
+ private record Identity(PrivateKey key, X509Certificate cert) {}
+
+ private record Pki(X509Certificate caCert, Path store, Path caFile) {
+ static Pki create(Path dir) throws Exception {
+ Path store = dir.resolve("native-test-ca.p12");
+ Path ca = dir.resolve("native-test-ca.crt");
+ keytool(
+ "-genkeypair",
+ "-alias",
+ "test-ca",
+ "-keyalg",
+ "RSA",
+ "-keysize",
+ "2048",
+ "-dname",
+ "CN=FireMUD test CA",
+ "-validity",
+ "30",
+ "-ext",
+ "BC=ca:true",
+ "-ext",
+ "KU=keyCertSign,cRLSign",
+ "-storetype",
+ "PKCS12",
+ "-keystore",
+ store.toString(),
+ "-storepass",
+ PASSWORD,
+ "-keypass",
+ PASSWORD);
+ keytool(
+ "-exportcert",
+ "-alias",
+ "test-ca",
+ "-keystore",
+ store.toString(),
+ "-storetype",
+ "PKCS12",
+ "-storepass",
+ PASSWORD,
+ "-file",
+ ca.toString(),
+ "-rfc");
+ try (var in = Files.newInputStream(ca)) {
+ return new Pki(
+ (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(in),
+ store,
+ ca);
+ }
+ }
+
+ static Identity issue(
+ Path dir, Path caStore, Path caFile, String alias, String uri, boolean server)
+ throws Exception {
+ Path store = dir.resolve(alias + ".p12");
+ Path csr = dir.resolve(alias + ".csr");
+ Path cert = dir.resolve(alias + ".crt");
+ String san = "URI:" + uri + ",DNS:localhost,IP:127.0.0.1";
+ keytool(
+ "-genkeypair",
+ "-alias",
+ alias,
+ "-keyalg",
+ "RSA",
+ "-keysize",
+ "2048",
+ "-dname",
+ "CN=" + alias,
+ "-validity",
+ "30",
+ "-ext",
+ "KU=digitalSignature,keyEncipherment",
+ "-ext",
+ "EKU=" + (server ? "serverAuth" : "clientAuth"),
+ "-ext",
+ "SAN=" + san,
+ "-storetype",
+ "PKCS12",
+ "-keystore",
+ store.toString(),
+ "-storepass",
+ PASSWORD,
+ "-keypass",
+ PASSWORD);
+ keytool(
+ "-certreq",
+ "-alias",
+ alias,
+ "-keystore",
+ store.toString(),
+ "-storetype",
+ "PKCS12",
+ "-storepass",
+ PASSWORD,
+ "-file",
+ csr.toString(),
+ "-ext",
+ "SAN=" + san);
+ keytool(
+ "-gencert",
+ "-alias",
+ "test-ca",
+ "-keystore",
+ caStore.toString(),
+ "-storetype",
+ "PKCS12",
+ "-storepass",
+ PASSWORD,
+ "-infile",
+ csr.toString(),
+ "-outfile",
+ cert.toString(),
+ "-validity",
+ "30",
+ "-rfc",
+ "-ext",
+ "BC=ca:false",
+ "-ext",
+ "KU=digitalSignature,keyEncipherment",
+ "-ext",
+ "EKU=" + (server ? "serverAuth" : "clientAuth"),
+ "-ext",
+ "SAN=" + san);
+ keytool(
+ "-importcert",
+ "-alias",
+ "test-ca",
+ "-keystore",
+ store.toString(),
+ "-storetype",
+ "PKCS12",
+ "-storepass",
+ PASSWORD,
+ "-file",
+ caFile.toString(),
+ "-noprompt");
+ keytool(
+ "-importcert",
+ "-alias",
+ alias,
+ "-keystore",
+ store.toString(),
+ "-storetype",
+ "PKCS12",
+ "-storepass",
+ PASSWORD,
+ "-file",
+ cert.toString(),
+ "-noprompt");
+ KeyStore keys = KeyStore.getInstance("PKCS12");
+ try (var in = Files.newInputStream(store)) {
+ keys.load(in, PASSWORD.toCharArray());
+ }
+ return new Identity(
+ (PrivateKey) keys.getKey(alias, PASSWORD.toCharArray()),
+ (X509Certificate) keys.getCertificate(alias));
+ }
+
+ CommonGrpcClientProperties clientProperties(Path dir, Identity identity) throws Exception {
+ Path clientDir = Files.createTempDirectory(dir, "terminal-client-");
+ Path chain =
+ pem(clientDir.resolve("client.crt"), "CERTIFICATE", identity.cert().getEncoded());
+ Path key = pem(clientDir.resolve("client.key"), "PRIVATE KEY", identity.key().getEncoded());
+ Path ca = pem(clientDir.resolve("client-ca.crt"), "CERTIFICATE", caCert.getEncoded());
+ var props = new CommonGrpcClientProperties();
+ props.setCertChain(chain.toString());
+ props.setPrivateKey(key.toString());
+ props.setCaCert(ca.toString());
+ return props;
+ }
+
+ private static void keytool(String... args) throws Exception {
+ Path bin =
+ Path.of(
+ System.getProperty("java.home"),
+ "bin",
+ System.getProperty("os.name").toLowerCase().contains("windows")
+ ? "keytool.exe"
+ : "keytool");
+ var command = new ArrayList();
+ command.add(bin.toString());
+ command.addAll(List.of(args));
+ Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
+ if (!process.waitFor(30, TimeUnit.SECONDS)) {
+ process.destroyForcibly();
+ process.waitFor(5, TimeUnit.SECONDS);
+ throw new IllegalStateException("keytool timed out");
+ }
+ String output;
+ try (var stream = process.getInputStream()) {
+ output = new String(stream.readAllBytes(), StandardCharsets.UTF_8);
+ }
+ if (process.exitValue() != 0) {
+ throw new IllegalStateException("keytool failed: " + output);
+ }
+ }
+
+ private static Path pem(Path path, String label, byte[] bytes) throws IOException {
+ String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes);
+ return Files.writeString(
+ path,
+ "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n",
+ StandardCharsets.US_ASCII);
+ }
+ }
+}
diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java
new file mode 100644
index 0000000000..25dc6fd16e
--- /dev/null
+++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java
@@ -0,0 +1,292 @@
+package net.firedevops.firemud.automationscripting.sourceintake;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import io.grpc.Context;
+import java.time.OffsetDateTime;
+import java.util.UUID;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding;
+import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence;
+import net.firedevops.firemud.common.security.SessionContext;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.springframework.stereotype.Component;
+import org.springframework.stereotype.Repository;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+class AutomationEmptySelectedSourceIntakeValueTest {
+ @BeforeEach
+ void clearCallerContext() {
+ SessionContext.clear();
+ }
+
+ @AfterEach
+ void clearCallerAndTransactionContext() {
+ SessionContext.clear();
+ TransactionSynchronizationManager.setActualTransactionActive(false);
+ if (TransactionSynchronizationManager.isSynchronizationActive()) {
+ TransactionSynchronizationManager.clearSynchronization();
+ }
+ }
+
+ @Test
+ void storedReceiptDecoderRejectsMalformedValues() {
+ assertThatThrownBy(() -> AutomationEmptySelectedSourceIntakeReceipt.fromStored(null))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> AutomationEmptySelectedSourceIntakeReceipt.fromStored(new byte[0]))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () -> AutomationEmptySelectedSourceIntakeReceipt.fromStored(new byte[] {1, 2, 3}))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ void intakePreparationTypesAreNotLiveSpringComponents() {
+ assertThat(
+ AutomationEmptySelectedSourceIntakeRepository.class.isAnnotationPresent(
+ Component.class))
+ .isFalse();
+ assertThat(
+ AutomationEmptySelectedSourceIntakeRepository.class.isAnnotationPresent(
+ Repository.class))
+ .isFalse();
+ assertThat(
+ AutomationEmptySelectedSourceIntakeService.class.isAnnotationPresent(Component.class))
+ .isFalse();
+ assertThat(AutomationEmptySelectedSourceIntakeService.class.isAnnotationPresent(Service.class))
+ .isFalse();
+ }
+
+ @Test
+ void retainRejectsMissingAndWrongSameNamespaceWorkloadPeersBeforeInputOrOwnerRead() {
+ AutomationEmptySelectedSourceIntakeRepository repository =
+ mock(AutomationEmptySelectedSourceIntakeRepository.class);
+ SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient =
+ mock(SelectedOwnerIntakeAuthorizationReadClient.class);
+ SelectedOwnerWorldInventoryReadClient worldInventoryReadClient =
+ mock(SelectedOwnerWorldInventoryReadClient.class);
+ AutomationEmptySelectedSourceIntakeService service =
+ new AutomationEmptySelectedSourceIntakeService(
+ repository, authorizationReadClient, worldInventoryReadClient);
+
+ assertThatThrownBy(() -> service.retain("example", null, null))
+ .isInstanceOf(SecurityException.class)
+ .hasMessageContaining("Game Design peer");
+
+ GrpcPeerIdentity wrongPeer =
+ new GrpcPeerIdentity(
+ "spiffe://firemud/ns/example/sa/account-service", "example", "account-service");
+ Context wrongPeerContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, wrongPeer);
+ Context previous = wrongPeerContext.attach();
+ try {
+ assertThatThrownBy(() -> service.retain("example", null, null))
+ .isInstanceOf(SecurityException.class)
+ .hasMessageContaining("same-namespace Game Design peer");
+ } finally {
+ wrongPeerContext.detach(previous);
+ }
+ GrpcPeerIdentity correctPeer =
+ new GrpcPeerIdentity(
+ "spiffe://firemud/ns/example/sa/game-design-service", "example", "game-design-service");
+ Context correctPeerContext =
+ Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, correctPeer);
+ previous = correctPeerContext.attach();
+ try {
+ SessionContext.setContext("1001", java.util.List.of(), java.util.Map.of());
+ assertThatThrownBy(() -> service.retain("example", null, null))
+ .isInstanceOf(SecurityException.class)
+ .hasMessageContaining("same-namespace Game Design peer");
+ } finally {
+ SessionContext.clear();
+ correctPeerContext.detach(previous);
+ }
+ verifyNoInteractions(repository, authorizationReadClient, worldInventoryReadClient);
+ }
+
+ @Test
+ void retainRejectsAmbientOwnerSqlBeforeReadingAnyOwnerEvidence() {
+ AutomationEmptySelectedSourceIntakeRepository repository =
+ mock(AutomationEmptySelectedSourceIntakeRepository.class);
+ SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient =
+ mock(SelectedOwnerIntakeAuthorizationReadClient.class);
+ SelectedOwnerWorldInventoryReadClient worldInventoryReadClient =
+ mock(SelectedOwnerWorldInventoryReadClient.class);
+ AutomationEmptySelectedSourceIntakeService service =
+ new AutomationEmptySelectedSourceIntakeService(
+ repository, authorizationReadClient, worldInventoryReadClient);
+ GrpcPeerIdentity peer =
+ new GrpcPeerIdentity(
+ "spiffe://firemud/ns/example/sa/game-design-service", "example", "game-design-service");
+ Context peerContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer);
+ Context previous = peerContext.attach();
+ TransactionSynchronizationManager.setActualTransactionActive(true);
+ try {
+ assertThatThrownBy(() -> service.retain("example", null, null))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("outside Automation owner SQL");
+ } finally {
+ peerContext.detach(previous);
+ }
+ verifyNoInteractions(repository, authorizationReadClient, worldInventoryReadClient);
+ }
+
+ @Test
+ void exactCommittedRequestRetryReturnsReceiptBeforeConsultingSettledAuthority() {
+ String namespace = "example";
+ UUID requestId = UUID.randomUUID();
+ UUID tenantId = UUID.randomUUID();
+ UUID versionId = UUID.randomUUID();
+ String requestDigest = "sha256:" + "b".repeat(64);
+ SelectedOwnerIntakeAuthorizationBinding binding =
+ mock(SelectedOwnerIntakeAuthorizationBinding.class);
+ DraftCommitBinding selectedCommit = mock(DraftCommitBinding.class);
+ when(binding.targetNamespace()).thenReturn(namespace);
+ when(binding.owner()).thenReturn(Owner.AUTOMATION_SCRIPTING);
+ when(binding.schema()).thenReturn("account-automation-intake-authorization/v1");
+ when(binding.purpose()).thenReturn("AUTOMATION_INTAKE_RETENTION");
+ when(binding.intakeRequestId()).thenReturn(requestId);
+ when(binding.tenantId()).thenReturn(tenantId);
+ when(binding.versionId()).thenReturn(versionId);
+ when(binding.selected()).thenReturn(selectedCommit);
+
+ WorldSelectedDraftPublicationFreezeEvidence freeze =
+ mock(WorldSelectedDraftPublicationFreezeEvidence.class);
+ WorldSelectedDraftPublicationFreezeEvidence.Request freezeRequest =
+ mock(WorldSelectedDraftPublicationFreezeEvidence.Request.class);
+ AccountPublicationAuthorizationBinding publicationBinding =
+ mock(AccountPublicationAuthorizationBinding.class);
+ AccountPublicationAuthorizationBinding.PreallocationInput publicationInput =
+ mock(AccountPublicationAuthorizationBinding.PreallocationInput.class);
+ AuthoredDraftPublishSelectionBinding selection =
+ mock(AuthoredDraftPublishSelectionBinding.class);
+ when(freeze.request()).thenReturn(freezeRequest);
+ when(freezeRequest.targetNamespace()).thenReturn(namespace);
+ when(freezeRequest.canonicalTenantId()).thenReturn(tenantId);
+ when(freezeRequest.canonicalVersionId()).thenReturn(versionId);
+ when(freezeRequest.accountBinding()).thenReturn(publicationBinding);
+ when(publicationBinding.input()).thenReturn(publicationInput);
+ when(publicationInput.selection()).thenReturn(selection);
+ when(selection.selectedCommit()).thenReturn(selectedCommit);
+
+ AutomationEmptySelectedSourceIntakeRepository repository =
+ mock(AutomationEmptySelectedSourceIntakeRepository.class);
+ SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient =
+ mock(SelectedOwnerIntakeAuthorizationReadClient.class);
+ SelectedOwnerWorldInventoryReadClient worldInventoryReadClient =
+ mock(SelectedOwnerWorldInventoryReadClient.class);
+ AutomationEmptySelectedSourceIntakeReceipt receipt =
+ mock(AutomationEmptySelectedSourceIntakeReceipt.class);
+ when(repository.read(namespace, requestId)).thenReturn(java.util.Optional.of(receipt));
+ AutomationEmptySelectedSourceIntakeService service =
+ new AutomationEmptySelectedSourceIntakeService(
+ repository, authorizationReadClient, worldInventoryReadClient);
+ GrpcPeerIdentity peer =
+ new GrpcPeerIdentity(
+ "spiffe://firemud/ns/example/sa/game-design-service", "example", "game-design-service");
+ Context peerContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer);
+ Context previous = peerContext.attach();
+ try (MockedStatic receiptStatic =
+ mockStatic(AutomationEmptySelectedSourceIntakeReceipt.class)) {
+ receiptStatic
+ .when(
+ () ->
+ AutomationEmptySelectedSourceIntakeReceipt.requestDigest(
+ namespace, binding, freeze))
+ .thenReturn(requestDigest);
+ assertThat(service.retain(namespace, binding, freeze)).isSameAs(receipt);
+ } finally {
+ peerContext.detach(previous);
+ }
+ verify(repository).read(namespace, requestId);
+ verify(receipt).requireSameRequest(namespace, binding, freeze);
+ verifyNoInteractions(authorizationReadClient, worldInventoryReadClient);
+ }
+
+ @Test
+ void committedReceiptLookupReturnsTheExactStoredReceiptBytes() {
+ DSLContext dsl = mock(DSLContext.class);
+ Record record = mock(Record.class);
+ String namespace = "example";
+ UUID operationId = UUID.randomUUID();
+ UUID fenceId = UUID.randomUUID();
+ UUID intakeRequestId = UUID.randomUUID();
+ UUID tenantId = UUID.randomUUID();
+ UUID versionId = UUID.randomUUID();
+ UUID selectedCommitId = UUID.randomUUID();
+ UUID sourceRevisionId = UUID.randomUUID();
+ String digest = "sha256:" + "a".repeat(64);
+ OffsetDateTime retainedAt = OffsetDateTime.parse("2026-10-10T00:00:00Z");
+ byte[] canonicalBytes = new byte[] {1, 2, 3};
+ AutomationEmptySelectedSourceIntakeReceipt receipt =
+ mock(AutomationEmptySelectedSourceIntakeReceipt.class);
+ when(receipt.targetNamespace()).thenReturn(namespace);
+ when(receipt.operationId()).thenReturn(operationId);
+ when(receipt.fenceId()).thenReturn(fenceId);
+ when(receipt.intakeRequestId()).thenReturn(intakeRequestId);
+ when(receipt.canonicalTenantId()).thenReturn(tenantId);
+ when(receipt.canonicalVersionId()).thenReturn(versionId);
+ when(receipt.selectedCommitId()).thenReturn(selectedCommitId);
+ when(receipt.sourceRevisionId()).thenReturn(sourceRevisionId);
+ when(receipt.sourceRevisionOrder()).thenReturn("7");
+ when(receipt.localTenantKey()).thenReturn(9001L);
+ when(receipt.localVersionKey()).thenReturn(9002L);
+ when(receipt.requestDigest()).thenReturn(digest);
+ when(receipt.authorizationBindingDigest()).thenReturn(digest);
+ when(receipt.receiptDigest()).thenReturn(digest);
+ when(receipt.retainedAt()).thenReturn(retainedAt);
+ when(receipt.canonicalBytes()).thenReturn(canonicalBytes);
+
+ when(record.get(0, String.class)).thenReturn(namespace);
+ when(record.get(1, UUID.class)).thenReturn(operationId);
+ when(record.get(2, UUID.class)).thenReturn(fenceId);
+ when(record.get(3, UUID.class)).thenReturn(intakeRequestId);
+ when(record.get(4, UUID.class)).thenReturn(tenantId);
+ when(record.get(5, UUID.class)).thenReturn(versionId);
+ when(record.get(6, UUID.class)).thenReturn(selectedCommitId);
+ when(record.get(7, UUID.class)).thenReturn(sourceRevisionId);
+ when(record.get(8, String.class)).thenReturn("7");
+ when(record.get(9, Long.class)).thenReturn(9001L);
+ when(record.get(10, Long.class)).thenReturn(9002L);
+ when(record.get(11, String.class)).thenReturn(digest);
+ when(record.get(12, String.class)).thenReturn(digest);
+ when(record.get(13, String.class)).thenReturn(digest);
+ when(record.get(14, OffsetDateTime.class)).thenReturn(retainedAt);
+ when(record.get(15, String.class)).thenReturn(digest);
+ when(record.get(16, String.class)).thenReturn(digest);
+ when(record.get(17, byte[].class)).thenReturn(canonicalBytes);
+ when(record.get(18, OffsetDateTime.class)).thenReturn(retainedAt);
+ when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(record);
+
+ try (MockedStatic decoder =
+ mockStatic(AutomationEmptySelectedSourceIntakeReceipt.class)) {
+ decoder
+ .when(() -> AutomationEmptySelectedSourceIntakeReceipt.fromStored(canonicalBytes))
+ .thenReturn(receipt);
+ var result =
+ new AutomationEmptySelectedSourceIntakeRepository(dsl).read(namespace, intakeRequestId);
+ assertThat(result).isPresent();
+ assertThat(result.orElseThrow()).isSameAs(receipt);
+ }
+ }
+}
diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java
new file mode 100644
index 0000000000..bed367ea99
--- /dev/null
+++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java
@@ -0,0 +1,173 @@
+package net.firedevops.firemud.automationscripting.sourceintake;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+
+import io.grpc.Context;
+import io.grpc.stub.StreamObserver;
+import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+import net.firedevops.firemud.automationscripting.service.ScriptDesignDigestService.ScriptDraftDesignDigest;
+import net.firedevops.firemud.automationscripting.v1.GetDraftDesignDigestRequest;
+import net.firedevops.firemud.automationscripting.v1.GetDraftDesignDigestResponse;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import net.firedevops.firemud.common.security.SessionContext;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+class AutomationSelectedEmptyPublicationDigestGrpcReceiverTest {
+ private static final String NAMESPACE = "test";
+ private static final String TENANT = "11111111-1111-4111-8111-111111111111";
+ private static final String VERSION_ROW = "23";
+
+ @AfterEach
+ void clearSessionContext() {
+ SessionContext.clear();
+ }
+
+ @Test
+ void exactGameDesignPeerWithoutSessionContextCanReadValidatedFullVersionBinding() {
+ SessionContext.clear();
+ AutomationSelectedEmptyPublicationDigestService digestService =
+ Mockito.mock(AutomationSelectedEmptyPublicationDigestService.class);
+ PublicationDigestRequestBinding binding =
+ PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7");
+ Mockito.when(digestService.getDraftDesignDigest(any(PublicationDigestRequestBinding.class)))
+ .thenReturn(
+ new ScriptDraftDesignDigest(
+ TENANT, VERSION_ROW, 0L, "selected-commit", "b".repeat(64), 6));
+ AutomationSelectedEmptyPublicationDigestGrpcReceiver receiver =
+ new AutomationSelectedEmptyPublicationDigestGrpcReceiver(
+ digestService, NAMESPACE, new SimpleMeterRegistry());
+
+ GetDraftDesignDigestResponse response = invokeAsGameDesign(receiver, request(binding));
+
+ assertEquals("", response.getError().getCode());
+ assertEquals(TENANT, response.getTenantId());
+ assertEquals(VERSION_ROW, response.getVersionId());
+ assertEquals("", response.getBaseVersionId());
+ assertEquals("selected-commit", response.getAppliedCommitId());
+ assertEquals("b".repeat(64), response.getContentDigest());
+ assertEquals(6, response.getDigestSchemaVersion());
+ verify(digestService).getDraftDesignDigest(any(PublicationDigestRequestBinding.class));
+ }
+
+ @Test
+ void accountOrGlobalOrScopedRoleContextDeniesEvenTheExactGameDesignPeer() {
+ AutomationSelectedEmptyPublicationDigestService digestService =
+ Mockito.mock(AutomationSelectedEmptyPublicationDigestService.class);
+ AutomationSelectedEmptyPublicationDigestGrpcReceiver receiver =
+ new AutomationSelectedEmptyPublicationDigestGrpcReceiver(
+ digestService, NAMESPACE, new SimpleMeterRegistry());
+ List deniedContexts =
+ List.of(
+ () -> SessionContext.setContext("user-1", List.of("player"), Map.of()),
+ () -> SessionContext.setContext(null, List.of("platformAdmin"), Map.of()),
+ () ->
+ SessionContext.setContext(
+ null, List.of(), Map.of("tenant-1", List.of("designer"))));
+ for (Runnable setDeniedContext : deniedContexts) {
+ SessionContext.clear();
+ setDeniedContext.run();
+ GetDraftDesignDigestResponse response =
+ invokeAsGameDesign(
+ receiver,
+ request(PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7")));
+ assertEquals("PERMISSION_DENIED", response.getError().getCode());
+ }
+ verifyNoInteractions(digestService);
+ }
+
+ @Test
+ void changedCompleteRequestBindingIsRejectedBeforeReceiptLookup() {
+ SessionContext.clear();
+ AutomationSelectedEmptyPublicationDigestService digestService =
+ Mockito.mock(AutomationSelectedEmptyPublicationDigestService.class);
+ AutomationSelectedEmptyPublicationDigestGrpcReceiver receiver =
+ new AutomationSelectedEmptyPublicationDigestGrpcReceiver(
+ digestService, NAMESPACE, new SimpleMeterRegistry());
+ GetDraftDesignDigestRequest changedRequest =
+ request(PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7")).toBuilder()
+ .setRequestDigest("0".repeat(64))
+ .build();
+
+ GetDraftDesignDigestResponse response = invokeAsGameDesign(receiver, changedRequest);
+
+ assertEquals("INVALID_ARGUMENT", response.getError().getCode());
+ verifyNoInteractions(digestService);
+ }
+
+ @Test
+ void patchScopeIsUnsupportedAndDoesNotReadTheSelectedEmptyReceipt() {
+ SessionContext.clear();
+ AutomationSelectedEmptyPublicationDigestService digestService =
+ Mockito.mock(AutomationSelectedEmptyPublicationDigestService.class);
+ AutomationSelectedEmptyPublicationDigestGrpcReceiver receiver =
+ new AutomationSelectedEmptyPublicationDigestGrpcReceiver(
+ digestService, NAMESPACE, new SimpleMeterRegistry());
+ PublicationDigestRequestBinding binding =
+ PublicationDigestRequestBinding.patch(TENANT, VERSION_ROW, "patch-1", "request-7");
+ GetDraftDesignDigestRequest request =
+ GetDraftDesignDigestRequest.newBuilder()
+ .setTenantId(binding.tenantId())
+ .setBaseVersionId(binding.baseVersionId())
+ .setScriptPatchVersion(binding.scriptPatchVersion())
+ .setPublishRequestId(binding.publishRequestId())
+ .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity())
+ .setRequestDigest(binding.requestDigest())
+ .build();
+
+ GetDraftDesignDigestResponse response = invokeAsGameDesign(receiver, request);
+
+ assertEquals("UNSUPPORTED_SCOPE", response.getError().getCode());
+ verifyNoInteractions(digestService);
+ }
+
+ private static GetDraftDesignDigestRequest request(PublicationDigestRequestBinding binding) {
+ return GetDraftDesignDigestRequest.newBuilder()
+ .setTenantId(binding.tenantId())
+ .setVersionId(binding.versionId())
+ .setPublishRequestId(binding.publishRequestId())
+ .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity())
+ .setRequestDigest(binding.requestDigest())
+ .build();
+ }
+
+ private static GetDraftDesignDigestResponse invokeAsGameDesign(
+ AutomationSelectedEmptyPublicationDigestGrpcReceiver receiver,
+ GetDraftDesignDigestRequest request) {
+ AtomicReference response = new AtomicReference<>();
+ Context.current()
+ .withValue(
+ GrpcPeerIdentity.CONTEXT_KEY,
+ new GrpcPeerIdentity(
+ "spiffe://firemud/ns/test/sa/game-design-service",
+ NAMESPACE,
+ "game-design-service"))
+ .run(
+ () ->
+ receiver.getDraftDesignDigest(
+ request,
+ new StreamObserver<>() {
+ @Override
+ public void onNext(GetDraftDesignDigestResponse value) {
+ response.set(value);
+ }
+
+ @Override
+ public void onError(Throwable error) {
+ throw new AssertionError(error);
+ }
+
+ @Override
+ public void onCompleted() {}
+ }));
+ return response.get();
+ }
+}
diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcServiceTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcServiceTest.java
new file mode 100644
index 0000000000..ca3c5a3be4
--- /dev/null
+++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcServiceTest.java
@@ -0,0 +1,146 @@
+package unit.net.firedevops.firemud.automationscripting.sourceintake;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+
+import io.grpc.Context;
+import io.grpc.Status;
+import io.grpc.stub.StreamObserver;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeService;
+import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedSourceIntakeCommandGrpcService;
+import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceRequest;
+import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceResponse;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.security.SessionContext;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/**
+ * Receiver gate tests use mocked owner storage and do not claim physical mTLS or PostgreSQL proof.
+ */
+class AutomationSelectedSourceIntakeCommandGrpcServiceTest {
+ private static final String NAMESPACE = "example";
+ private static final String GAME_DESIGN_URI =
+ "spiffe://firemud/ns/example/sa/game-design-service";
+
+ @AfterEach
+ void clearContexts() {
+ SessionContext.clear();
+ TransactionSynchronizationManager.clear();
+ }
+
+ @Test
+ void rejectsMissingOrWrongPeerBeforeRequestDecodeOrOwnerInvocation() {
+ var owner = mock(AutomationEmptySelectedSourceIntakeService.class);
+ var service = new AutomationSelectedSourceIntakeCommandGrpcService(owner, NAMESPACE);
+ var response = new CapturingObserver();
+
+ service.retainSelectedSource(RetainSelectedSourceRequest.getDefaultInstance(), response);
+
+ assertThat(Status.fromThrowable(response.failure()).getCode())
+ .isEqualTo(Status.Code.UNAUTHENTICATED);
+ verifyNoInteractions(owner);
+
+ var wrongPeer =
+ new GrpcPeerIdentity(
+ "spiffe://firemud/ns/example/sa/account-service", NAMESPACE, "account-service");
+ var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, wrongPeer);
+ var previous = context.attach();
+ try {
+ var denied = new CapturingObserver();
+ service.retainSelectedSource(RetainSelectedSourceRequest.getDefaultInstance(), denied);
+ assertThat(Status.fromThrowable(denied.failure()).getCode())
+ .isEqualTo(Status.Code.PERMISSION_DENIED);
+ verifyNoInteractions(owner);
+ } finally {
+ context.detach(previous);
+ }
+
+ var wrongNamespacePeer =
+ new GrpcPeerIdentity(
+ "spiffe://firemud/ns/other/sa/game-design-service", "other", "game-design-service");
+ var wrongNamespaceContext =
+ Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, wrongNamespacePeer);
+ previous = wrongNamespaceContext.attach();
+ try {
+ var denied = new CapturingObserver();
+ service.retainSelectedSource(
+ RetainSelectedSourceRequest.newBuilder().setTargetNamespace(NAMESPACE).build(), denied);
+ assertThat(Status.fromThrowable(denied.failure()).getCode())
+ .isEqualTo(Status.Code.PERMISSION_DENIED);
+ verifyNoInteractions(owner);
+ } finally {
+ wrongNamespaceContext.detach(previous);
+ }
+ }
+
+ @Test
+ void rejectsEndUserAndAmbientSqlBeforeMalformedEvidenceCanBeDecoded() {
+ var owner = mock(AutomationEmptySelectedSourceIntakeService.class);
+ var service = new AutomationSelectedSourceIntakeCommandGrpcService(owner, NAMESPACE);
+ var peer = new GrpcPeerIdentity(GAME_DESIGN_URI, NAMESPACE, "game-design-service");
+ var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer);
+ var malformedRequest =
+ RetainSelectedSourceRequest.newBuilder().setTargetNamespace(NAMESPACE).build();
+ var previous = context.attach();
+ try {
+ SessionContext.setContext("101", List.of(), Map.of());
+ var userDenied = new CapturingObserver();
+ service.retainSelectedSource(malformedRequest, userDenied);
+ assertThat(Status.fromThrowable(userDenied.failure()).getCode())
+ .isEqualTo(Status.Code.PERMISSION_DENIED);
+ SessionContext.clear();
+
+ TransactionSynchronizationManager.setActualTransactionActive(true);
+ var sqlDenied = new CapturingObserver();
+ service.retainSelectedSource(malformedRequest, sqlDenied);
+ assertThat(Status.fromThrowable(sqlDenied.failure()).getCode())
+ .isEqualTo(Status.Code.FAILED_PRECONDITION);
+ TransactionSynchronizationManager.clear();
+
+ var malformed = new CapturingObserver();
+ service.retainSelectedSource(malformedRequest, malformed);
+ assertThat(Status.fromThrowable(malformed.failure()).getCode())
+ .isEqualTo(Status.Code.INVALID_ARGUMENT);
+
+ var mismatchedTarget = new CapturingObserver();
+ service.retainSelectedSource(
+ RetainSelectedSourceRequest.newBuilder().setTargetNamespace("other").build(),
+ mismatchedTarget);
+ assertThat(Status.fromThrowable(mismatchedTarget.failure()).getCode())
+ .isEqualTo(Status.Code.PERMISSION_DENIED);
+ verifyNoInteractions(owner);
+ } finally {
+ context.detach(previous);
+ }
+ }
+
+ private static final class CapturingObserver
+ implements StreamObserver {
+ private final AtomicReference failure = new AtomicReference<>();
+
+ @Override
+ public void onNext(RetainSelectedSourceResponse value) {
+ throw new AssertionError("Malformed or unauthorized request unexpectedly returned evidence");
+ }
+
+ @Override
+ public void onError(Throwable error) {
+ failure.set(error);
+ }
+
+ @Override
+ public void onCompleted() {
+ throw new AssertionError("Malformed or unauthorized request unexpectedly completed");
+ }
+
+ Throwable failure() {
+ return failure.get();
+ }
+ }
+}
diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadServiceTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadServiceTest.java
new file mode 100644
index 0000000000..c6291ba1b3
--- /dev/null
+++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadServiceTest.java
@@ -0,0 +1,253 @@
+package net.firedevops.firemud.automationscripting.sourceintake;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import io.grpc.Context;
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import io.grpc.stub.StreamObserver;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicReference;
+import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalRequest;
+import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalResponse;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.security.SessionContext;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Mocked owner-storage and peer tests do not establish physical Automation owner proof. */
+class AutomationSelectedSourceIntakeTerminalReadServiceTest {
+ private static final String NAMESPACE = "example";
+ private static final String ACCOUNT_URI = "spiffe://firemud/ns/example/sa/account-service";
+ private static final byte[] BINDING_BYTES = {1, 2, 3, 4};
+
+ @AfterEach
+ void clearContexts() {
+ SessionContext.clear();
+ TransactionSynchronizationManager.setActualTransactionActive(false);
+ if (TransactionSynchronizationManager.isSynchronizationActive()) {
+ TransactionSynchronizationManager.clearSynchronization();
+ }
+ }
+
+ @Test
+ void exactRetriesReturnOnlyTheOriginalCommittedEmptyReceipt() {
+ var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class);
+ var binding = binding();
+ var receipt = receipt(BINDING_BYTES);
+ when(repository.readCommittedTerminal(binding)).thenReturn(Optional.of(receipt));
+ var service = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE);
+ var accountContext = accountPeer();
+ var previous = accountContext.attach();
+ try {
+ var first = service.read(request(binding));
+ var retry = service.read(request(binding));
+
+ assertThat(first.receipt()).isSameAs(receipt);
+ assertThat(retry.receipt()).isSameAs(receipt);
+ assertThat(first.request().readRequestId()).isNotEqualTo(retry.request().readRequestId());
+ verify(repository, org.mockito.Mockito.times(2)).readCommittedTerminal(binding);
+ } finally {
+ accountContext.detach(previous);
+ }
+ }
+
+ @Test
+ void missingReceiptIsNotConvertedToTerminalEvidence() {
+ var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class);
+ var binding = binding();
+ when(repository.readCommittedTerminal(binding)).thenReturn(Optional.empty());
+ var service = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE);
+ var accountContext = accountPeer();
+ var previous = accountContext.attach();
+ try {
+ assertThatThrownBy(() -> service.read(request(binding)))
+ .isInstanceOf(StatusRuntimeException.class)
+ .satisfies(
+ error ->
+ assertThat(Status.fromThrowable(error).getCode())
+ .isEqualTo(Status.Code.NOT_FOUND));
+ } finally {
+ accountContext.detach(previous);
+ }
+ }
+
+ @Test
+ void rejectsChangedTupleAndCorruptStoredReceipt() {
+ var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class);
+ var binding = binding();
+ when(repository.readCommittedTerminal(binding))
+ .thenThrow(
+ new AutomationEmptySelectedSourceIntakeRepository.IntakeConflictException(
+ "changed exact authorization"));
+ var service = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE);
+ var accountContext = accountPeer();
+ var previous = accountContext.attach();
+ try {
+ assertThatThrownBy(() -> service.read(request(binding)))
+ .isInstanceOf(StatusRuntimeException.class)
+ .satisfies(
+ error ->
+ assertThat(Status.fromThrowable(error).getCode())
+ .isEqualTo(Status.Code.ALREADY_EXISTS));
+
+ doThrow(new IllegalArgumentException("corrupt canonical receipt"))
+ .when(repository)
+ .readCommittedTerminal(binding);
+ assertThatThrownBy(() -> service.read(request(binding)))
+ .isInstanceOf(StatusRuntimeException.class)
+ .satisfies(
+ error ->
+ assertThat(Status.fromThrowable(error).getCode())
+ .isEqualTo(Status.Code.DATA_LOSS));
+ } finally {
+ accountContext.detach(previous);
+ }
+ }
+
+ @Test
+ void rejectsWrongPeerEndUserAndAmbientSqlBeforeRepositoryLookup() {
+ var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class);
+ var binding = binding();
+ var request = request(binding);
+ var service = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE);
+
+ assertThatThrownBy(() -> service.read(request))
+ .isInstanceOf(StatusRuntimeException.class)
+ .satisfies(
+ error ->
+ assertThat(Status.fromThrowable(error).getCode())
+ .isEqualTo(Status.Code.UNAUTHENTICATED));
+
+ var wrongPeer =
+ new GrpcPeerIdentity(
+ "spiffe://firemud/ns/example/sa/game-design-service", NAMESPACE, "game-design-service");
+ var wrongContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, wrongPeer);
+ var previous = wrongContext.attach();
+ try {
+ assertThatThrownBy(() -> service.read(request))
+ .isInstanceOf(StatusRuntimeException.class)
+ .satisfies(
+ error ->
+ assertThat(Status.fromThrowable(error).getCode())
+ .isEqualTo(Status.Code.PERMISSION_DENIED));
+ } finally {
+ wrongContext.detach(previous);
+ }
+
+ var accountContext = accountPeer();
+ previous = accountContext.attach();
+ try {
+ SessionContext.setContext("1001", List.of(), Map.of());
+ assertThatThrownBy(() -> service.read(request))
+ .isInstanceOf(StatusRuntimeException.class)
+ .satisfies(
+ error ->
+ assertThat(Status.fromThrowable(error).getCode())
+ .isEqualTo(Status.Code.PERMISSION_DENIED));
+ SessionContext.clear();
+
+ TransactionSynchronizationManager.setActualTransactionActive(true);
+ assertThatThrownBy(() -> service.read(request))
+ .isInstanceOf(StatusRuntimeException.class)
+ .satisfies(
+ error ->
+ assertThat(Status.fromThrowable(error).getCode())
+ .isEqualTo(Status.Code.FAILED_PRECONDITION));
+ TransactionSynchronizationManager.setActualTransactionActive(false);
+
+ TransactionSynchronizationManager.initSynchronization();
+ assertThatThrownBy(() -> service.read(request))
+ .isInstanceOf(StatusRuntimeException.class)
+ .satisfies(
+ error ->
+ assertThat(Status.fromThrowable(error).getCode())
+ .isEqualTo(Status.Code.FAILED_PRECONDITION));
+ TransactionSynchronizationManager.clearSynchronization();
+ } finally {
+ accountContext.detach(previous);
+ }
+ verifyNoInteractions(repository);
+ }
+
+ @Test
+ void transportAuthenticatesBeforeDecodingOrLookup() {
+ var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class);
+ var service = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE);
+ var grpc = new AutomationSelectedSourceIntakeTerminalReadGrpcService(service);
+ var observedError = new AtomicReference();
+ StreamObserver observer =
+ new StreamObserver<>() {
+ @Override
+ public void onNext(ReadSelectedSourceIntakeTerminalResponse value) {
+ throw new AssertionError("Unauthenticated caller received a response");
+ }
+
+ @Override
+ public void onError(Throwable error) {
+ observedError.set(error);
+ }
+
+ @Override
+ public void onCompleted() {
+ throw new AssertionError("Unauthenticated caller completed a response");
+ }
+ };
+
+ grpc.readSelectedSourceIntakeTerminal(
+ ReadSelectedSourceIntakeTerminalRequest.getDefaultInstance(), observer);
+
+ assertThat(observedError.get()).isInstanceOf(StatusRuntimeException.class);
+ assertThat(Status.fromThrowable(observedError.get()).getCode())
+ .isEqualTo(Status.Code.UNAUTHENTICATED);
+ verifyNoInteractions(repository);
+ }
+
+ private static SelectedOwnerIntakeAuthorizationBinding binding() {
+ var binding = mock(SelectedOwnerIntakeAuthorizationBinding.class);
+ when(binding.owner())
+ .thenReturn(
+ net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner.AUTOMATION_SCRIPTING);
+ when(binding.targetNamespace()).thenReturn(NAMESPACE);
+ when(binding.schema()).thenReturn("account-automation-intake-authorization/v1");
+ when(binding.purpose()).thenReturn("AUTOMATION_INTAKE_RETENTION");
+ when(binding.canonicalBytes()).thenReturn(BINDING_BYTES.clone());
+ when(binding.operationId()).thenReturn(UUID.randomUUID());
+ when(binding.fenceId()).thenReturn(UUID.randomUUID());
+ when(binding.intakeRequestId()).thenReturn(UUID.randomUUID());
+ return binding;
+ }
+
+ private static AutomationSelectedSourceIntakeTerminalReadEvidence.Request request(
+ SelectedOwnerIntakeAuthorizationBinding binding) {
+ return AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, binding);
+ }
+
+ private static AutomationEmptySelectedSourceIntakeReceipt receipt(byte[] bindingBytes) {
+ var receipt = mock(AutomationEmptySelectedSourceIntakeReceipt.class);
+ when(receipt.targetNamespace()).thenReturn(NAMESPACE);
+ when(receipt.authorizationBindingBytes()).thenReturn(bindingBytes.clone());
+ when(receipt.outcome()).thenReturn("COMMITTED_EMPTY");
+ return receipt;
+ }
+
+ private static Context accountPeer() {
+ return Context.current()
+ .withValue(
+ GrpcPeerIdentity.CONTEXT_KEY,
+ new GrpcPeerIdentity(ACCOUNT_URI, NAMESPACE, "account-service"));
+ }
+}
diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandEvidence.java
new file mode 100644
index 0000000000..9e36d9d88e
--- /dev/null
+++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandEvidence.java
@@ -0,0 +1,171 @@
+package net.firedevops.firemud.common.automation.sourceintake;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence;
+
+/** Exact Game Design command correlation and the immutable Automation receipt. */
+public record AutomationSelectedSourceIntakeCommandEvidence(
+ Request request, AutomationEmptySelectedSourceIntakeReceipt receipt) {
+ public AutomationSelectedSourceIntakeCommandEvidence {
+ Objects.requireNonNull(request, "selected-source command request is required");
+ Objects.requireNonNull(receipt, "committed Automation receipt is required");
+ try {
+ receipt.requireSameRequest(
+ request.targetNamespace(),
+ request.originalAuthorizationBinding(),
+ request.freezeEvidence());
+ } catch (RuntimeException mismatch) {
+ throw new IllegalArgumentException(
+ "Automation receipt differs from the complete selected-source command", mismatch);
+ }
+ if (!Arrays.equals(
+ request.originalIntakeAuthorizationBinding(), receipt.authorizationBindingBytes())
+ || !request.intakeAuthorizationDigest().equals(receipt.authorizationBindingDigest())) {
+ throw new IllegalArgumentException(
+ "Automation receipt differs from the original Account authorization bytes");
+ }
+ }
+
+ /** Caller-generated transport correlation; all retained inputs remain the original values. */
+ public record Request(
+ int schemaVersion,
+ String targetNamespace,
+ UUID transportRequestId,
+ SelectedOwnerIntakeAuthorizationBinding originalAuthorizationBinding,
+ WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) {
+ public static final int SCHEMA_VERSION = 1;
+ private static final UUID NIL_UUID = new UUID(0L, 0L);
+
+ public Request {
+ Objects.requireNonNull(
+ originalAuthorizationBinding, "original Account authorization is required");
+ Objects.requireNonNull(freezeEvidence, "complete World freeze evidence is required");
+ if (schemaVersion != SCHEMA_VERSION
+ || !net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace)
+ || !targetNamespace.equals(originalAuthorizationBinding.targetNamespace())
+ || originalAuthorizationBinding.canonicalBytes().length == 0
+ || originalAuthorizationBinding.canonicalBytes().length
+ > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES
+ || originalAuthorizationBinding.owner() != Owner.AUTOMATION_SCRIPTING
+ || !"account-automation-intake-authorization/v1"
+ .equals(originalAuthorizationBinding.schema())
+ || !"AUTOMATION_INTAKE_RETENTION".equals(originalAuthorizationBinding.purpose())
+ || !targetNamespace.equals(freezeEvidence.request().targetNamespace())
+ || !originalAuthorizationBinding
+ .tenantId()
+ .equals(freezeEvidence.request().canonicalTenantId())
+ || !originalAuthorizationBinding
+ .versionId()
+ .equals(freezeEvidence.request().canonicalVersionId())
+ || !originalAuthorizationBinding
+ .selected()
+ .equals(
+ freezeEvidence.request().accountBinding().input().selection().selectedCommit())
+ || !originalAuthorizationBinding
+ .selected()
+ .commitId()
+ .toString()
+ .equals(freezeEvidence.acknowledgement().appliedCommitId())) {
+ throw invalid();
+ }
+ DraftAuthorizationFenceBinding.requireUuid(transportRequestId);
+ if (NIL_UUID.equals(transportRequestId)
+ || collidesWithRetainedIdentity(
+ transportRequestId, originalAuthorizationBinding, freezeEvidence)) {
+ throw invalid();
+ }
+ }
+
+ public static Request create(
+ String namespace,
+ SelectedOwnerIntakeAuthorizationBinding originalAuthorizationBinding,
+ WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) {
+ Objects.requireNonNull(
+ originalAuthorizationBinding, "original Account authorization is required");
+ Objects.requireNonNull(freezeEvidence, "complete World freeze evidence is required");
+ UUID correlation;
+ do {
+ correlation = UUID.randomUUID();
+ } while (collidesWithRetainedIdentity(
+ correlation, originalAuthorizationBinding, freezeEvidence));
+ return new Request(
+ SCHEMA_VERSION, namespace, correlation, originalAuthorizationBinding, freezeEvidence);
+ }
+
+ public byte[] originalIntakeAuthorizationBinding() {
+ return originalAuthorizationBinding.canonicalBytes();
+ }
+
+ public String intakeAuthorizationDigest() {
+ return originalAuthorizationBinding.digest();
+ }
+
+ @Override
+ public boolean equals(Object value) {
+ return value instanceof Request other
+ && schemaVersion == other.schemaVersion
+ && targetNamespace.equals(other.targetNamespace)
+ && transportRequestId.equals(other.transportRequestId)
+ && Arrays.equals(
+ originalIntakeAuthorizationBinding(), other.originalIntakeAuthorizationBinding())
+ && intakeAuthorizationDigest().equals(other.intakeAuthorizationDigest())
+ && freezeEvidence.equals(other.freezeEvidence);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(
+ schemaVersion,
+ targetNamespace,
+ transportRequestId,
+ Arrays.hashCode(originalIntakeAuthorizationBinding()),
+ intakeAuthorizationDigest(),
+ freezeEvidence);
+ }
+
+ private static boolean collidesWithRetainedIdentity(
+ UUID candidate,
+ SelectedOwnerIntakeAuthorizationBinding binding,
+ WorldSelectedDraftPublicationFreezeEvidence freeze) {
+ if (candidate.equals(binding.operationId())
+ || candidate.equals(binding.fenceId())
+ || candidate.equals(binding.intakeRequestId())
+ || candidate.equals(binding.selected().requestId())
+ || candidate.equals(binding.selected().commitId())) {
+ return true;
+ }
+ var account = freeze.request().accountBinding();
+ var selection = account.input().selection();
+ List freezeIds =
+ new ArrayList<>(
+ List.of(
+ account.operationId(),
+ account.fenceId(),
+ selection.fenceRequestId(),
+ selection.fenceCommitId(),
+ selection.selectedCommit().requestId(),
+ selection.selectedCommit().commitId(),
+ freeze.acknowledgement().intakeRequestId(),
+ freeze.acknowledgement().publicationFence()));
+ if (freezeIds.contains(candidate)) return true;
+ try {
+ UUID publicationRequestId = UUID.fromString(freeze.request().publicationRequestId());
+ return publicationRequestId.toString().equals(freeze.request().publicationRequestId())
+ && publicationRequestId.equals(candidate);
+ } catch (IllegalArgumentException notUuid) {
+ return false;
+ }
+ }
+
+ private static IllegalArgumentException invalid() {
+ return new IllegalArgumentException("Invalid Automation selected-source command request");
+ }
+ }
+}
diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandGrpcCodec.java
new file mode 100644
index 0000000000..223ce89e55
--- /dev/null
+++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandGrpcCodec.java
@@ -0,0 +1,177 @@
+package net.firedevops.firemud.common.automation.sourceintake;
+
+import com.google.protobuf.ByteString;
+import com.google.protobuf.Message;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceRequest;
+import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceResponse;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence.Request;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec;
+
+/** Closed mapping for selected-source retention with exact Account and World evidence echoes. */
+public final class AutomationSelectedSourceIntakeCommandGrpcCodec {
+ private static final int MAX_REQUEST_FRAMING_BYTES = 64 * 1024;
+
+ /** Authorization plus complete freeze request and acknowledgement Account bindings. */
+ public static final int MAX_REQUEST_WIRE_BYTES =
+ SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES
+ + 2 * WorldSelectedDraftPublicationFreezeEvidence.Request.MAX_ACCOUNT_BINDING_BYTES
+ + MAX_REQUEST_FRAMING_BYTES;
+
+ /** Complete receipt, complete echoed request, and bounded outer response framing. */
+ public static final int MAX_RESPONSE_WIRE_BYTES =
+ AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES
+ + MAX_REQUEST_WIRE_BYTES
+ + MAX_REQUEST_FRAMING_BYTES;
+
+ private AutomationSelectedSourceIntakeCommandGrpcCodec() {}
+
+ public static RetainSelectedSourceRequest toRequest(Request request) {
+ Objects.requireNonNull(request, "selected-source command request is required");
+ byte[] authorizationBytes = request.originalIntakeAuthorizationBinding();
+ if (authorizationBytes.length == 0
+ || authorizationBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) {
+ throw invalid("Original Account authorization exceeds its 16 MiB limit");
+ }
+ var freeze = request.freezeEvidence();
+ var wire =
+ RetainSelectedSourceRequest.newBuilder()
+ .setSchemaVersion(request.schemaVersion())
+ .setTargetNamespace(request.targetNamespace())
+ .setTransportRequestId(request.transportRequestId().toString())
+ .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(authorizationBytes))
+ .setIntakeAuthorizationDigest(request.intakeAuthorizationDigest())
+ .setFreezeRequest(
+ WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freeze.request()))
+ .setFreezeAcknowledgement(
+ WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freeze.acknowledgement()))
+ .build();
+ requireWithinBudget(wire, MAX_REQUEST_WIRE_BYTES, "request");
+ return wire;
+ }
+
+ /** Decode after the receiver authenticates the exact same-namespace Game Design peer. */
+ public static Request fromRequest(RetainSelectedSourceRequest wire) {
+ requireKnownAndWithinBudget(wire, MAX_REQUEST_WIRE_BYTES, "request");
+ if (!wire.hasFreezeRequest() || !wire.hasFreezeAcknowledgement()) {
+ throw invalid("Complete original World freeze request and acknowledgement are required");
+ }
+ UUID transportRequestId = canonicalUuid(wire.getTransportRequestId());
+ int authorizationSize = wire.getOriginalIntakeAuthorizationBinding().size();
+ if (authorizationSize == 0
+ || authorizationSize > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) {
+ throw invalid("Original Account authorization size is invalid");
+ }
+ byte[] authorizationBytes = wire.getOriginalIntakeAuthorizationBinding().toByteArray();
+ SelectedOwnerIntakeAuthorizationBinding authorization;
+ try {
+ authorization = SelectedOwnerIntakeAuthorizationBinding.fromStored(authorizationBytes);
+ } catch (RuntimeException malformed) {
+ throw invalid("Original Account authorization is invalid", malformed);
+ }
+ if (!authorization.digest().equals(wire.getIntakeAuthorizationDigest())) {
+ throw invalid("Original Account authorization digest differs");
+ }
+ var freezeRequest =
+ WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest(wire.getFreezeRequest());
+ WorldSelectedDraftPublicationFreezeEvidence freezeEvidence =
+ WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse(
+ freezeRequest, wire.getFreezeAcknowledgement());
+ Request request =
+ new Request(
+ wire.getSchemaVersion(),
+ wire.getTargetNamespace(),
+ transportRequestId,
+ authorization,
+ freezeEvidence);
+ if (!toRequest(request).equals(wire)) {
+ throw invalid("Selected-source command request is not an exact canonical echo");
+ }
+ return request;
+ }
+
+ public static RetainSelectedSourceResponse toResponse(
+ AutomationSelectedSourceIntakeCommandEvidence evidence) {
+ Objects.requireNonNull(evidence, "selected-source command evidence is required");
+ byte[] receiptBytes = evidence.receipt().canonicalBytes();
+ if (receiptBytes.length == 0
+ || receiptBytes.length > AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES) {
+ throw invalid("Committed Automation receipt size is invalid");
+ }
+ var response =
+ RetainSelectedSourceResponse.newBuilder()
+ .setRequest(toRequest(evidence.request()))
+ .setCommittedEmptyReceipt(ByteString.copyFrom(receiptBytes))
+ .setReceiptDigest(evidence.receipt().receiptDigest())
+ .build();
+ requireWithinBudget(response, MAX_RESPONSE_WIRE_BYTES, "response");
+ return response;
+ }
+
+ /** Requires the exact complete request echo and verifies the canonical retained receipt. */
+ public static AutomationSelectedSourceIntakeCommandEvidence fromResponse(
+ Request expected, RetainSelectedSourceResponse response) {
+ Objects.requireNonNull(expected, "selected-source command request is required");
+ requireKnownAndWithinBudget(response, MAX_RESPONSE_WIRE_BYTES, "response");
+ if (!response.hasRequest()) {
+ throw invalid("Exact selected-source command request echo is required");
+ }
+ RetainSelectedSourceRequest expectedWire = toRequest(expected);
+ if (!response.getRequest().equals(expectedWire)) {
+ throw invalid("Automation changed the exact selected-source command request");
+ }
+ int receiptSize = response.getCommittedEmptyReceipt().size();
+ if (receiptSize == 0 || receiptSize > AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES) {
+ throw invalid("Missing or oversized committed Automation receipt");
+ }
+ byte[] receiptBytes = response.getCommittedEmptyReceipt().toByteArray();
+ AutomationEmptySelectedSourceIntakeReceipt receipt;
+ try {
+ receipt = AutomationEmptySelectedSourceIntakeReceipt.fromStored(receiptBytes);
+ } catch (RuntimeException malformed) {
+ throw invalid("Committed Automation receipt is invalid", malformed);
+ }
+ if (!receipt.receiptDigest().equals(response.getReceiptDigest())) {
+ throw invalid("Automation receipt digest differs");
+ }
+ return new AutomationSelectedSourceIntakeCommandEvidence(expected, receipt);
+ }
+
+ private static UUID canonicalUuid(String value) {
+ try {
+ UUID parsed = UUID.fromString(value);
+ if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) {
+ throw invalid("Canonical nonzero transport request UUID required");
+ }
+ return parsed;
+ } catch (IllegalArgumentException malformed) {
+ throw invalid("Canonical nonzero transport request UUID required", malformed);
+ }
+ }
+
+ private static void requireKnownAndWithinBudget(Message message, int budget, String label) {
+ if (message == null || message.getSerializedSize() > budget) {
+ throw invalid("Automation selected-source command " + label + " exceeds its wire budget");
+ }
+ if (!message.getUnknownFields().asMap().isEmpty()) {
+ throw invalid("Unknown Automation selected-source command " + label + " fields");
+ }
+ }
+
+ private static void requireWithinBudget(Message message, int budget, String label) {
+ if (message.getSerializedSize() > budget) {
+ throw invalid("Automation selected-source command " + label + " exceeds its wire budget");
+ }
+ }
+
+ private static IllegalArgumentException invalid(String message) {
+ return new IllegalArgumentException(message);
+ }
+
+ private static IllegalArgumentException invalid(String message, Throwable cause) {
+ return new IllegalArgumentException(message, cause);
+ }
+}
diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandEvidence.java
new file mode 100644
index 0000000000..fa7082e0ba
--- /dev/null
+++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandEvidence.java
@@ -0,0 +1,171 @@
+package net.firedevops.firemud.common.entity.sourceintake;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence;
+
+/** Exact Game Design command correlation and the immutable Entity receipt. */
+public record EntitySelectedSourceIntakeCommandEvidence(
+ Request request, EntityEmptySelectedSourceIntakeReceipt receipt) {
+ public EntitySelectedSourceIntakeCommandEvidence {
+ Objects.requireNonNull(request, "selected-source command request is required");
+ Objects.requireNonNull(receipt, "committed Entity receipt is required");
+ try {
+ receipt.requireSameRequest(
+ request.targetNamespace(),
+ request.originalAuthorizationBinding(),
+ request.freezeEvidence());
+ } catch (RuntimeException mismatch) {
+ throw new IllegalArgumentException(
+ "Entity receipt differs from the complete selected-source command", mismatch);
+ }
+ if (!Arrays.equals(
+ request.originalIntakeAuthorizationBinding(), receipt.authorizationBindingBytes())
+ || !request.intakeAuthorizationDigest().equals(receipt.authorizationBindingDigest())) {
+ throw new IllegalArgumentException(
+ "Entity receipt differs from the original Account authorization bytes");
+ }
+ }
+
+ /** Caller-generated transport correlation; all retained inputs remain the original values. */
+ public record Request(
+ int schemaVersion,
+ String targetNamespace,
+ UUID transportRequestId,
+ SelectedOwnerIntakeAuthorizationBinding originalAuthorizationBinding,
+ WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) {
+ public static final int SCHEMA_VERSION = 1;
+ private static final UUID NIL_UUID = new UUID(0L, 0L);
+
+ public Request {
+ Objects.requireNonNull(
+ originalAuthorizationBinding, "original Account authorization is required");
+ Objects.requireNonNull(freezeEvidence, "complete World freeze evidence is required");
+ if (schemaVersion != SCHEMA_VERSION
+ || !GrpcPeerIdentity.isValidNamespace(targetNamespace)
+ || !targetNamespace.equals(originalAuthorizationBinding.targetNamespace())
+ || originalAuthorizationBinding.canonicalBytes().length == 0
+ || originalAuthorizationBinding.canonicalBytes().length
+ > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES
+ || originalAuthorizationBinding.owner() != Owner.ENTITY_MANAGEMENT
+ || !"account-entity-intake-authorization/v1".equals(originalAuthorizationBinding.schema())
+ || !"ENTITY_INTAKE_RETENTION".equals(originalAuthorizationBinding.purpose())
+ || !targetNamespace.equals(freezeEvidence.request().targetNamespace())
+ || !originalAuthorizationBinding
+ .tenantId()
+ .equals(freezeEvidence.request().canonicalTenantId())
+ || !originalAuthorizationBinding
+ .versionId()
+ .equals(freezeEvidence.request().canonicalVersionId())
+ || !originalAuthorizationBinding
+ .selected()
+ .equals(
+ freezeEvidence.request().accountBinding().input().selection().selectedCommit())
+ || !originalAuthorizationBinding
+ .selected()
+ .commitId()
+ .toString()
+ .equals(freezeEvidence.acknowledgement().appliedCommitId())) {
+ throw invalid();
+ }
+ DraftAuthorizationFenceBinding.requireUuid(transportRequestId);
+ if (NIL_UUID.equals(transportRequestId)
+ || collidesWithRetainedIdentity(
+ transportRequestId, originalAuthorizationBinding, freezeEvidence)) {
+ throw invalid();
+ }
+ }
+
+ public static Request create(
+ String namespace,
+ SelectedOwnerIntakeAuthorizationBinding originalAuthorizationBinding,
+ WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) {
+ Objects.requireNonNull(
+ originalAuthorizationBinding, "original Account authorization is required");
+ Objects.requireNonNull(freezeEvidence, "complete World freeze evidence is required");
+ UUID correlation;
+ do {
+ correlation = UUID.randomUUID();
+ } while (collidesWithRetainedIdentity(
+ correlation, originalAuthorizationBinding, freezeEvidence));
+ return new Request(
+ SCHEMA_VERSION, namespace, correlation, originalAuthorizationBinding, freezeEvidence);
+ }
+
+ public byte[] originalIntakeAuthorizationBinding() {
+ return originalAuthorizationBinding.canonicalBytes();
+ }
+
+ public String intakeAuthorizationDigest() {
+ return originalAuthorizationBinding.digest();
+ }
+
+ @Override
+ public boolean equals(Object value) {
+ return value instanceof Request other
+ && schemaVersion == other.schemaVersion
+ && targetNamespace.equals(other.targetNamespace)
+ && transportRequestId.equals(other.transportRequestId)
+ && Arrays.equals(
+ originalIntakeAuthorizationBinding(), other.originalIntakeAuthorizationBinding())
+ && intakeAuthorizationDigest().equals(other.intakeAuthorizationDigest())
+ && freezeEvidence.equals(other.freezeEvidence);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(
+ schemaVersion,
+ targetNamespace,
+ transportRequestId,
+ Arrays.hashCode(originalIntakeAuthorizationBinding()),
+ intakeAuthorizationDigest(),
+ freezeEvidence);
+ }
+
+ private static boolean collidesWithRetainedIdentity(
+ UUID candidate,
+ SelectedOwnerIntakeAuthorizationBinding binding,
+ WorldSelectedDraftPublicationFreezeEvidence freeze) {
+ if (candidate.equals(binding.operationId())
+ || candidate.equals(binding.fenceId())
+ || candidate.equals(binding.intakeRequestId())
+ || candidate.equals(binding.selected().requestId())
+ || candidate.equals(binding.selected().commitId())) {
+ return true;
+ }
+ var account = freeze.request().accountBinding();
+ var selection = account.input().selection();
+ List freezeIds =
+ new ArrayList<>(
+ List.of(
+ account.operationId(),
+ account.fenceId(),
+ selection.fenceRequestId(),
+ selection.fenceCommitId(),
+ selection.selectedCommit().requestId(),
+ selection.selectedCommit().commitId(),
+ freeze.acknowledgement().intakeRequestId(),
+ freeze.acknowledgement().publicationFence()));
+ if (freezeIds.contains(candidate)) return true;
+ try {
+ UUID publicationRequestId = UUID.fromString(freeze.request().publicationRequestId());
+ return publicationRequestId.toString().equals(freeze.request().publicationRequestId())
+ && publicationRequestId.equals(candidate);
+ } catch (IllegalArgumentException notUuid) {
+ return false;
+ }
+ }
+
+ private static IllegalArgumentException invalid() {
+ return new IllegalArgumentException("Invalid Entity selected-source command request");
+ }
+ }
+}
diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodec.java
new file mode 100644
index 0000000000..47e71734fc
--- /dev/null
+++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodec.java
@@ -0,0 +1,193 @@
+package net.firedevops.firemud.common.entity.sourceintake;
+
+import com.google.protobuf.ByteString;
+import com.google.protobuf.Message;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence.Request;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec;
+import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceRequest;
+import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceResponse;
+
+/** Closed Entity mapping with complete original Account/World evidence and exact receipt echo. */
+public final class EntitySelectedSourceIntakeCommandGrpcCodec {
+ private static final int MAX_REQUEST_FRAMING_BYTES = 64 * 1024;
+
+ /** Original authorization, complete freeze request and acknowledgement, and outer framing. */
+ public static final int MAX_REQUEST_WIRE_BYTES =
+ SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES
+ + 2 * WorldSelectedDraftPublicationFreezeEvidence.Request.MAX_ACCOUNT_BINDING_BYTES
+ + MAX_REQUEST_FRAMING_BYTES;
+
+ /** Full Entity receipt, full echoed request and bounded response framing. */
+ public static final int MAX_RESPONSE_WIRE_BYTES =
+ EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES
+ + MAX_REQUEST_WIRE_BYTES
+ + MAX_REQUEST_FRAMING_BYTES;
+
+ private EntitySelectedSourceIntakeCommandGrpcCodec() {}
+
+ public static RetainSelectedEntitySourceRequest toRequest(Request request) {
+ Objects.requireNonNull(request, "selected-source command request is required");
+ byte[] authorizationBytes = request.originalIntakeAuthorizationBinding();
+ if (authorizationBytes.length == 0
+ || authorizationBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) {
+ throw invalid("Original Account authorization exceeds its 16 MiB limit");
+ }
+ var freeze = request.freezeEvidence();
+ var wire =
+ RetainSelectedEntitySourceRequest.newBuilder()
+ .setSchemaVersion(request.schemaVersion())
+ .setTargetNamespace(request.targetNamespace())
+ .setTransportRequestId(request.transportRequestId().toString())
+ .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(authorizationBytes))
+ .setIntakeAuthorizationDigest(request.intakeAuthorizationDigest())
+ .setFreezeRequest(
+ WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freeze.request()))
+ .setFreezeAcknowledgement(
+ WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freeze.acknowledgement()))
+ .build();
+ requireWithinBudget(wire, MAX_REQUEST_WIRE_BYTES, "request");
+ return wire;
+ }
+
+ /** Decode only after the receiver authenticates the exact same-namespace Game Design peer. */
+ public static Request fromRequest(RetainSelectedEntitySourceRequest wire) {
+ requireKnownAndWithinBudget(wire, MAX_REQUEST_WIRE_BYTES, "request");
+ if (!wire.hasFreezeRequest() || !wire.hasFreezeAcknowledgement()) {
+ throw invalid("Complete original World freeze request and acknowledgement are required");
+ }
+ UUID transportRequestId = canonicalUuid(wire.getTransportRequestId());
+ int authorizationSize = wire.getOriginalIntakeAuthorizationBinding().size();
+ if (authorizationSize == 0
+ || authorizationSize > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) {
+ throw invalid("Original Account authorization size is invalid");
+ }
+ byte[] authorizationBytes = wire.getOriginalIntakeAuthorizationBinding().toByteArray();
+ final SelectedOwnerIntakeAuthorizationBinding authorization;
+ try {
+ authorization = SelectedOwnerIntakeAuthorizationBinding.fromStored(authorizationBytes);
+ } catch (RuntimeException malformed) {
+ throw invalid("Original Account authorization is invalid", malformed);
+ }
+ if (!authorization.digest().equals(wire.getIntakeAuthorizationDigest())) {
+ throw invalid("Original Account authorization digest differs");
+ }
+ final WorldSelectedDraftPublicationFreezeEvidence freezeEvidence;
+ try {
+ var freezeRequest =
+ WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest(wire.getFreezeRequest());
+ freezeEvidence =
+ WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse(
+ freezeRequest, wire.getFreezeAcknowledgement());
+ } catch (RuntimeException malformed) {
+ throw invalid("Complete original World freeze evidence is invalid", malformed);
+ }
+ final Request request;
+ try {
+ request =
+ new Request(
+ wire.getSchemaVersion(),
+ wire.getTargetNamespace(),
+ transportRequestId,
+ authorization,
+ freezeEvidence);
+ } catch (RuntimeException malformed) {
+ throw invalid("Entity selected-source command binding is invalid", malformed);
+ }
+ if (!toRequest(request).equals(wire)) {
+ throw invalid("Selected-source command request is not an exact canonical echo");
+ }
+ return request;
+ }
+
+ public static RetainSelectedEntitySourceResponse toResponse(
+ EntitySelectedSourceIntakeCommandEvidence evidence) {
+ Objects.requireNonNull(evidence, "selected-source command evidence is required");
+ byte[] receiptBytes = evidence.receipt().canonicalBytes();
+ if (receiptBytes.length == 0
+ || receiptBytes.length > EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES) {
+ throw invalid("Committed Entity receipt size is invalid");
+ }
+ var response =
+ RetainSelectedEntitySourceResponse.newBuilder()
+ .setRequest(toRequest(evidence.request()))
+ .setCommittedEmptyReceipt(ByteString.copyFrom(receiptBytes))
+ .setReceiptDigest(evidence.receipt().receiptDigest())
+ .build();
+ requireWithinBudget(response, MAX_RESPONSE_WIRE_BYTES, "response");
+ return response;
+ }
+
+ /**
+ * Requires the exact complete request echo and verifies the canonical retained Entity receipt.
+ */
+ public static EntitySelectedSourceIntakeCommandEvidence fromResponse(
+ Request expected, RetainSelectedEntitySourceResponse response) {
+ Objects.requireNonNull(expected, "selected-source command request is required");
+ requireKnownAndWithinBudget(response, MAX_RESPONSE_WIRE_BYTES, "response");
+ if (!response.hasRequest()) {
+ throw invalid("Exact selected-source command request echo is required");
+ }
+ if (!response.getRequest().equals(toRequest(expected))) {
+ throw invalid("Entity changed the exact selected-source command request");
+ }
+ int receiptSize = response.getCommittedEmptyReceipt().size();
+ if (receiptSize == 0 || receiptSize > EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES) {
+ throw invalid("Missing or oversized committed Entity receipt");
+ }
+ final EntityEmptySelectedSourceIntakeReceipt receipt;
+ try {
+ receipt =
+ EntityEmptySelectedSourceIntakeReceipt.fromStored(
+ response.getCommittedEmptyReceipt().toByteArray());
+ } catch (RuntimeException malformed) {
+ throw invalid("Committed Entity receipt is invalid", malformed);
+ }
+ if (!receipt.receiptDigest().equals(response.getReceiptDigest())) {
+ throw invalid("Entity receipt digest differs");
+ }
+ try {
+ return new EntitySelectedSourceIntakeCommandEvidence(expected, receipt);
+ } catch (RuntimeException mismatch) {
+ throw invalid("Entity receipt differs from the complete original command", mismatch);
+ }
+ }
+
+ private static UUID canonicalUuid(String value) {
+ try {
+ UUID parsed = UUID.fromString(value);
+ if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) {
+ throw invalid("Canonical nonzero transport request UUID required");
+ }
+ return parsed;
+ } catch (IllegalArgumentException malformed) {
+ throw invalid("Canonical nonzero transport request UUID required", malformed);
+ }
+ }
+
+ private static void requireKnownAndWithinBudget(Message wire, int budget, String label) {
+ if (wire == null || wire.getSerializedSize() > budget) {
+ throw invalid("Entity selected-source command " + label + " exceeds its wire budget");
+ }
+ if (!wire.getUnknownFields().asMap().isEmpty()) {
+ throw invalid("Unknown Entity selected-source command " + label + " fields");
+ }
+ }
+
+ private static void requireWithinBudget(Message wire, int budget, String label) {
+ if (wire.getSerializedSize() > budget) {
+ throw invalid("Entity selected-source command " + label + " exceeds its wire budget");
+ }
+ }
+
+ private static IllegalArgumentException invalid(String message) {
+ return new IllegalArgumentException(message);
+ }
+
+ private static IllegalArgumentException invalid(String message, Throwable cause) {
+ return new IllegalArgumentException(message, cause);
+ }
+}
diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java
index d87b9417d5..ffd4b2585e 100644
--- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java
+++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java
@@ -50,11 +50,14 @@ public record AuthoredWorldReleaseAttestationEvidence(
public static final int SCHEMA_VERSION = 1;
public static final int SELECTOR_SCHEMA_VERSION = 2;
public static final int CLOSURE_SELECTOR_SCHEMA_VERSION = 3;
+ public static final int SELECTED_FULL_SCHEMA_VERSION = 4;
private static final String EVIDENCE_DOMAIN = "game-design-authored-world-release-attestation/v1";
private static final String SELECTOR_EVIDENCE_DOMAIN =
"game-design-authored-world-release-attestation/v2";
private static final String CLOSURE_SELECTOR_EVIDENCE_DOMAIN =
"game-design-authored-world-release-attestation/v3";
+ private static final String SELECTED_FULL_EVIDENCE_DOMAIN =
+ "game-design-authored-world-release-attestation/v4";
private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}");
private static final Pattern PARTICIPANT_CONTENT_DIGEST = Pattern.compile("[0-9a-f]{64}");
private static final Pattern CANONICAL_POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*");
@@ -93,12 +96,13 @@ public static int supportedParticipantDigestSchema(String participantKey) {
return supportedParticipantDigestSchema(participantKey, SCHEMA_VERSION);
}
- /** Selects owner schemas from the retained-v1, selected-v2, or closure-selected-v3 contract. */
+ /** Selects owner schemas from the retained-v1, selected-v2, closure-selected-v3, or full-v4 contract. */
public static int supportedParticipantDigestSchema(
String participantKey, int attestationSchemaVersion) {
if (attestationSchemaVersion != SCHEMA_VERSION
&& attestationSchemaVersion != SELECTOR_SCHEMA_VERSION
- && attestationSchemaVersion != CLOSURE_SELECTOR_SCHEMA_VERSION) {
+ && attestationSchemaVersion != CLOSURE_SELECTOR_SCHEMA_VERSION
+ && attestationSchemaVersion != SELECTED_FULL_SCHEMA_VERSION) {
throw new IllegalArgumentException("Unsupported authored-world release-attestation schema");
}
Objects.requireNonNull(participantKey, "participantKey");
@@ -110,6 +114,16 @@ public static int supportedParticipantDigestSchema(
&& "WORLD_MANAGEMENT".equals(participantKey)) {
return 4;
}
+ if (attestationSchemaVersion == SELECTED_FULL_SCHEMA_VERSION) {
+ return switch (participantKey) {
+ case "WORLD_MANAGEMENT" -> 4;
+ case "ENTITY_MANAGEMENT" -> 3;
+ case "GAME_LOGIC" -> 1;
+ case "AUTOMATION_SCRIPTING" -> 6;
+ case "GAME_DESIGN_CONTROL_PLANE" -> 2;
+ default -> throw new IllegalArgumentException("Unsupported full-Version participant owner");
+ };
+ }
return (attestationSchemaVersion == SELECTOR_SCHEMA_VERSION
|| attestationSchemaVersion == CLOSURE_SELECTOR_SCHEMA_VERSION)
&& "GAME_DESIGN_CONTROL_PLANE".equals(participantKey)
@@ -119,7 +133,8 @@ public static int supportedParticipantDigestSchema(
public static boolean requiresWorldStartLocationEvidence(int attestationSchemaVersion) {
return attestationSchemaVersion == SELECTOR_SCHEMA_VERSION
- || attestationSchemaVersion == CLOSURE_SELECTOR_SCHEMA_VERSION;
+ || attestationSchemaVersion == CLOSURE_SELECTOR_SCHEMA_VERSION
+ || attestationSchemaVersion == SELECTED_FULL_SCHEMA_VERSION;
}
/** One successful, immutable owner digest included in the release attestation. */
@@ -177,7 +192,8 @@ public record Artifact(
public AuthoredWorldReleaseAttestationEvidence {
if (schemaVersion != SCHEMA_VERSION
&& schemaVersion != SELECTOR_SCHEMA_VERSION
- && schemaVersion != CLOSURE_SELECTOR_SCHEMA_VERSION) {
+ && schemaVersion != CLOSURE_SELECTOR_SCHEMA_VERSION
+ && schemaVersion != SELECTED_FULL_SCHEMA_VERSION) {
throw new IllegalArgumentException("Unsupported authored-world release-attestation schema");
}
Objects.requireNonNull(targetNamespace, "targetNamespace");
@@ -375,6 +391,52 @@ public static AuthoredWorldReleaseAttestationEvidence createClosureSelector(
worldStartLocationEvidence);
}
+ /** Creates v4 from the exact selector and complete selected-full participant vector. */
+ public static AuthoredWorldReleaseAttestationEvidence createSelectedFull(
+ String targetNamespace,
+ String descriptorResultDigest,
+ UUID canonicalTenantId,
+ UUID canonicalVersionId,
+ String worldSlug,
+ UUID authoredWorldSourceOperationId,
+ String authoredWorldSourceEvidenceDigest,
+ String launchDescriptorId,
+ String publishedReleaseBundleRef,
+ long versionStateEpoch,
+ String publishWorkflowId,
+ String commitId,
+ List participantDigests,
+ String manifestHash,
+ int manifestSchemaVersion,
+ List requiredManifestAssetKeys,
+ List artifactDigests,
+ List commandDefinitions,
+ String generationConfigRevision,
+ WorldPublishedStartLocationEvidence worldStartLocationEvidence) {
+ return createSelected(
+ SELECTED_FULL_SCHEMA_VERSION,
+ targetNamespace,
+ descriptorResultDigest,
+ canonicalTenantId,
+ canonicalVersionId,
+ worldSlug,
+ authoredWorldSourceOperationId,
+ authoredWorldSourceEvidenceDigest,
+ launchDescriptorId,
+ publishedReleaseBundleRef,
+ versionStateEpoch,
+ publishWorkflowId,
+ commitId,
+ participantDigests,
+ manifestHash,
+ manifestSchemaVersion,
+ requiredManifestAssetKeys,
+ artifactDigests,
+ commandDefinitions,
+ generationConfigRevision,
+ worldStartLocationEvidence);
+ }
+
private static AuthoredWorldReleaseAttestationEvidence createSelected(
int schemaVersion,
String targetNamespace,
@@ -652,6 +714,7 @@ public static byte[] evidencePreimage(AuthoredWorldReleaseAttestationEvidence ev
case SCHEMA_VERSION -> EVIDENCE_DOMAIN;
case SELECTOR_SCHEMA_VERSION -> SELECTOR_EVIDENCE_DOMAIN;
case CLOSURE_SELECTOR_SCHEMA_VERSION -> CLOSURE_SELECTOR_EVIDENCE_DOMAIN;
+ case SELECTED_FULL_SCHEMA_VERSION -> SELECTED_FULL_EVIDENCE_DOMAIN;
default -> throw new IllegalArgumentException("Unsupported release-attestation schema");
};
return preimage(domain, fields.toArray(Field[]::new));
diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java
index a0e29e8e4f..dc088b1a07 100644
--- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java
+++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java
@@ -83,12 +83,14 @@ public record ReleaseContent(
switch (attestationSchemaVersion) {
case "v2" -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION;
case "v3" -> AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION;
+ case "v4" -> AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION;
default ->
throw new IllegalArgumentException(
- "Complete full-Version bundle/v2 or bundle/v3 required");
+ "Complete full-Version bundle/v2, bundle/v3, or bundle/v4 required");
};
if (versionNumber <= 0 || manifestSchemaVersion != 1) {
- throw new IllegalArgumentException("Complete full-Version bundle/v2 or bundle/v3 required");
+ throw new IllegalArgumentException(
+ "Complete full-Version bundle/v2, bundle/v3, or bundle/v4 required");
}
digest(manifestHash);
artifactDigests = List.copyOf(artifactDigests);
diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodecTest.java
new file mode 100644
index 0000000000..1061b90c2c
--- /dev/null
+++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodecTest.java
@@ -0,0 +1,213 @@
+package net.firedevops.firemud.common.entity.sourceintake;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import com.google.protobuf.ByteString;
+import com.google.protobuf.UnknownFieldSet;
+import java.util.UUID;
+import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence.Request;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec;
+import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceRequest;
+import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceResponse;
+import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures;
+import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+/** Synthetic fixture codec proof does not establish Entity producer or physical census proof. */
+class EntitySelectedSourceIntakeCommandGrpcCodecTest {
+ private static final String NAMESPACE = "test";
+ private static Fixture fixture;
+
+ @BeforeAll
+ static void createSyntheticEntityInputs() {
+ fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create();
+ }
+
+ @Test
+ void roundTripsCompleteOriginalAuthorizationFreezeAndCanonicalReceiptOnDistinctCorrelations() {
+ var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence();
+ var binding = fixture.authorization();
+ var first = Request.create(NAMESPACE, binding, freeze);
+ var retry = Request.create(NAMESPACE, binding, freeze);
+
+ var firstWire = EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(first);
+ var retryWire = EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(retry);
+ assertThat(first.transportRequestId()).isNotEqualTo(retry.transportRequestId());
+ assertThat(first.transportRequestId())
+ .isNotIn(
+ binding.operationId(),
+ binding.fenceId(),
+ binding.intakeRequestId(),
+ binding.selected().requestId(),
+ binding.selected().commitId(),
+ freeze.acknowledgement().intakeRequestId(),
+ freeze.acknowledgement().publicationFence());
+ assertThat(EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(firstWire)).isEqualTo(first);
+ assertThat(EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(retryWire)).isEqualTo(retry);
+ assertThat(firstWire.getOriginalIntakeAuthorizationBinding().toByteArray())
+ .isEqualTo(binding.canonicalBytes());
+ assertThat(firstWire.getIntakeAuthorizationDigest()).isEqualTo(binding.digest());
+ assertThat(firstWire.getFreezeRequest())
+ .isEqualTo(WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freeze.request()));
+ assertThat(firstWire.getFreezeAcknowledgement())
+ .isEqualTo(
+ WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freeze.acknowledgement()));
+ assertThat(firstWire.getSerializedSize())
+ .isLessThanOrEqualTo(EntitySelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES);
+
+ var evidence = new EntitySelectedSourceIntakeCommandEvidence(first, fixture.receipt());
+ RetainSelectedEntitySourceResponse response =
+ EntitySelectedSourceIntakeCommandGrpcCodec.toResponse(evidence);
+ assertThat(response.getRequest()).isEqualTo(firstWire);
+ assertThat(response.getCommittedEmptyReceipt().toByteArray())
+ .isEqualTo(fixture.receipt().canonicalBytes());
+ assertThat(response.getReceiptDigest()).isEqualTo(fixture.receipt().receiptDigest());
+ assertThat(response.getSerializedSize())
+ .isLessThanOrEqualTo(EntitySelectedSourceIntakeCommandGrpcCodec.MAX_RESPONSE_WIRE_BYTES);
+ var decoded = EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse(first, response);
+ assertThat(decoded.request()).isEqualTo(first);
+ assertThat(decoded.receipt().canonicalBytes()).isEqualTo(fixture.receipt().canonicalBytes());
+ assertThat(decoded.receipt().authorizationBindingBytes()).isEqualTo(binding.canonicalBytes());
+ }
+
+ @Test
+ void rejectsWrongOwnerNamespaceAndChangedOriginalBindingOrFreeze() {
+ var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence();
+ assertThatThrownBy(() -> Request.create(NAMESPACE, fixture.wrongOwnerAuthorization(), freeze))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> Request.create("other", fixture.authorization(), freeze))
+ .isInstanceOf(IllegalArgumentException.class);
+
+ var request = Request.create(NAMESPACE, fixture.authorization(), freeze);
+ var wire = EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(request);
+ assertThatThrownBy(
+ () ->
+ EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(
+ wire.toBuilder().setIntakeAuthorizationDigest("0".repeat(64)).build()))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("digest");
+
+ byte[] changedBinding = fixture.authorization().canonicalBytes();
+ changedBinding[changedBinding.length - 1] ^= 1;
+ assertThatThrownBy(
+ () ->
+ EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(
+ wire.toBuilder()
+ .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(changedBinding))
+ .build()))
+ .isInstanceOf(IllegalArgumentException.class);
+
+ var changedFreezeRequest =
+ wire.getFreezeRequest().toBuilder().setRequestDigest("0".repeat(64)).build();
+ assertThatThrownBy(
+ () ->
+ EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(
+ wire.toBuilder().setFreezeRequest(changedFreezeRequest).build()))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("freeze");
+ var changedFreezeAck =
+ wire.getFreezeAcknowledgement().toBuilder().setAppliedCommitId("0".repeat(36)).build();
+ assertThatThrownBy(
+ () ->
+ EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(
+ wire.toBuilder().setFreezeAcknowledgement(changedFreezeAck).build()))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("freeze");
+ }
+
+ @Test
+ void rejectsUnknownFieldsOversizedWireAndChangedFullResponseEchoOrDigest() {
+ var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence();
+ var request = Request.create(NAMESPACE, fixture.authorization(), freeze);
+ var requestWire = EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(request);
+ var unknown =
+ UnknownFieldSet.newBuilder()
+ .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build())
+ .build();
+ assertThatThrownBy(
+ () ->
+ EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(
+ requestWire.toBuilder().setUnknownFields(unknown).build()))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Unknown");
+ assertThatThrownBy(
+ () ->
+ EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(
+ requestWire.toBuilder()
+ .setFreezeAcknowledgement(
+ requestWire.getFreezeAcknowledgement().toBuilder()
+ .setUnknownFields(unknown)
+ .build())
+ .build()))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(
+ RetainSelectedEntitySourceRequest.newBuilder()
+ .setOriginalIntakeAuthorizationBinding(
+ ByteString.copyFrom(
+ new byte
+ [EntitySelectedSourceIntakeCommandGrpcCodec
+ .MAX_REQUEST_WIRE_BYTES
+ + 1]))
+ .build()))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("wire budget");
+
+ var response =
+ EntitySelectedSourceIntakeCommandGrpcCodec.toResponse(
+ new EntitySelectedSourceIntakeCommandEvidence(request, fixture.receipt()));
+ assertThatThrownBy(
+ () ->
+ EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse(
+ request,
+ response.toBuilder()
+ .setRequest(
+ response.getRequest().toBuilder()
+ .setTransportRequestId(UUID.randomUUID().toString())
+ .build())
+ .build()))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("changed");
+ assertThatThrownBy(
+ () ->
+ EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse(
+ request, response.toBuilder().setReceiptDigest("0".repeat(64)).build()))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("digest");
+ assertThatThrownBy(
+ () ->
+ EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse(
+ request, response.toBuilder().setUnknownFields(unknown).build()))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Unknown");
+
+ var changedRequest = Request.create(NAMESPACE, fixture.authorization(), freeze);
+ assertThatThrownBy(
+ () -> EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse(changedRequest, response))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("changed");
+ }
+
+ @Test
+ void transportCorrelationMustBeCanonicalNonzeroAndNotReuseRetainedIdentity() {
+ var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence();
+ var binding = fixture.authorization();
+ assertThatThrownBy(
+ () ->
+ new Request(
+ Request.SCHEMA_VERSION, NAMESPACE, binding.operationId(), binding, freeze))
+ .isInstanceOf(IllegalArgumentException.class);
+ var valid = Request.create(NAMESPACE, binding, freeze);
+ assertThatThrownBy(
+ () ->
+ EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(
+ EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(valid).toBuilder()
+ .setTransportRequestId("00000000-0000-0000-0000-000000000000")
+ .build()))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("UUID");
+ }
+}
diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java
index a0d3a67a2c..d6281522c7 100644
--- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java
+++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java
@@ -108,6 +108,73 @@ void v3BindsClosureQualifiedWorldSchema4InItsOwnDomainAndSurvivesStoredReadback(
.hasMessageContaining("Participant digest schema is unsupported");
}
+ @Test
+ void v4BindsTheExactSelectedFullParticipantVectorInANewDomain() throws Exception {
+ var selector = selectorEvidence(4);
+ var descriptor = descriptor(selector);
+ var release = release(descriptor, selector, AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
+ var stored = JSON.writeValueAsString(release);
+ var readback = JSON.readValue(stored, AuthoredWorldReleaseAttestationEvidence.class);
+
+ assertThat(release.schemaVersion())
+ .isEqualTo(AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
+ assertThat(release.participantDigests())
+ .extracting(AuthoredWorldReleaseAttestationEvidence.Participant::digestSchemaVersion)
+ .containsExactly(4, 3, 1, 6, 2);
+ assertThat(readback).isEqualTo(release);
+ readback.requireValid(descriptor);
+ assertThat(
+ new String(
+ AuthoredWorldReleaseAttestationEvidence.evidencePreimage(release),
+ StandardCharsets.UTF_8))
+ .startsWith("49:game-design-authored-world-release-attestation/v4")
+ .contains("worldStartLocationEvidence.canonicalBytesBase64")
+ .endsWith(Base64.getEncoder().encodeToString(selector.canonicalBytes()));
+
+ var mixedParticipants =
+ release.participantDigests().stream()
+ .map(
+ participant ->
+ new AuthoredWorldReleaseAttestationEvidence.Participant(
+ participant.participantKey(),
+ participant.scopeValue(),
+ participant.baseVersionIdPresent(),
+ participant.baseVersionId(),
+ participant.appliedCommitId(),
+ participant.contentDigest(),
+ "AUTOMATION_SCRIPTING".equals(participant.participantKey())
+ ? 5
+ : participant.digestSchemaVersion(),
+ participant.abilitySchemaDigestPresent(),
+ participant.abilitySchemaDigest()))
+ .toList();
+ assertThatThrownBy(
+ () ->
+ AuthoredWorldReleaseAttestationEvidence.createSelectedFull(
+ release.targetNamespace(),
+ release.descriptorResultDigest(),
+ release.canonicalTenantId(),
+ release.canonicalVersionId(),
+ release.worldSlug(),
+ release.authoredWorldSourceOperationId(),
+ release.authoredWorldSourceEvidenceDigest(),
+ release.launchDescriptorId(),
+ release.publishedReleaseBundleRef(),
+ release.versionStateEpoch(),
+ release.publishWorkflowId(),
+ release.commitId(),
+ mixedParticipants,
+ release.manifestHash(),
+ release.manifestSchemaVersion(),
+ release.requiredManifestAssetKeys(),
+ release.artifactDigests(),
+ release.commandDefinitions(),
+ release.generationConfigRevision(),
+ selector))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Participant digest schema is unsupported");
+ }
+
@Test
void terminalReleaseProjectionAcceptsExactV2AndV3OwnerSchemasAndRejectsMixedSchemas()
throws Exception {
@@ -448,6 +515,30 @@ private static AuthoredWorldReleaseAttestationEvidence release(
descriptor.generationConfigRevision(),
selector);
}
+ if (attestationSchemaVersion
+ == AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION) {
+ return AuthoredWorldReleaseAttestationEvidence.createSelectedFull(
+ descriptor.targetNamespace(),
+ descriptor.resultDigest(),
+ descriptor.canonicalTenantId(),
+ selector.request().canonicalVersionId(),
+ descriptor.worldSlug(),
+ descriptor.authoredWorldSourceOperationId(),
+ descriptor.authoredWorldSourceEvidenceDigest(),
+ descriptor.launchDescriptorId(),
+ descriptor.publishedReleaseBundleRef(),
+ descriptor.versionStateEpoch(),
+ selector.request().publishWorkflowId(),
+ selector.request().appliedCommitId(),
+ participants,
+ "sha256:" + "d".repeat(64),
+ 1,
+ List.of(),
+ List.of(),
+ List.of("LOOK"),
+ descriptor.generationConfigRevision(),
+ selector);
+ }
return AuthoredWorldReleaseAttestationEvidence.create(
descriptor.targetNamespace(),
descriptor.resultDigest(),
diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AutomationSelectedSourceIntakeCommandGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AutomationSelectedSourceIntakeCommandGrpcCodecTest.java
new file mode 100644
index 0000000000..8b3007c481
--- /dev/null
+++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AutomationSelectedSourceIntakeCommandGrpcCodecTest.java
@@ -0,0 +1,279 @@
+package net.firedevops.firemud.common.publication;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.protobuf.ByteString;
+import com.google.protobuf.UnknownFieldSet;
+import java.io.ByteArrayOutputStream;
+import java.util.List;
+import java.util.UUID;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandGrpcCodec;
+import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent;
+import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceTestFixtures;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase;
+import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeResponse;
+import org.junit.jupiter.api.Test;
+
+class AutomationSelectedSourceIntakeCommandGrpcCodecTest {
+ private static final UUID ACTOR = id("dddddddd-dddd-4ddd-8ddd-dddddddddddd");
+
+ @Test
+ void roundTripsOriginalAutomationAuthorizationAndCompleteWorldFreezeOnDistinctCorrelations() {
+ var freeze = freeze();
+ var binding =
+ authorization(freeze.request().accountBinding().input().selection().selectedCommit());
+ var first =
+ AutomationSelectedSourceIntakeCommandEvidence.Request.create("test", binding, freeze);
+ var retry =
+ AutomationSelectedSourceIntakeCommandEvidence.Request.create("test", binding, freeze);
+
+ var firstWire = AutomationSelectedSourceIntakeCommandGrpcCodec.toRequest(first);
+ var retryWire = AutomationSelectedSourceIntakeCommandGrpcCodec.toRequest(retry);
+
+ assertThat(first.transportRequestId()).isNotEqualTo(retry.transportRequestId());
+ assertThat(first.transportRequestId())
+ .isNotIn(
+ binding.operationId(),
+ binding.fenceId(),
+ binding.intakeRequestId(),
+ binding.selected().requestId(),
+ binding.selected().commitId(),
+ freeze.acknowledgement().intakeRequestId(),
+ freeze.acknowledgement().publicationFence());
+ assertThat(AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest(firstWire))
+ .isEqualTo(first);
+ assertThat(AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest(retryWire))
+ .isEqualTo(retry);
+ assertThat(firstWire.getOriginalIntakeAuthorizationBinding().toByteArray())
+ .isEqualTo(binding.canonicalBytes());
+ assertThat(firstWire.getIntakeAuthorizationDigest()).isEqualTo(binding.digest());
+ assertThat(firstWire.getFreezeRequest())
+ .isEqualTo(WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freeze.request()));
+ assertThat(firstWire.getFreezeAcknowledgement())
+ .isEqualTo(
+ WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freeze.acknowledgement()));
+ assertThat(firstWire.getSerializedSize())
+ .isLessThanOrEqualTo(AutomationSelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES);
+ }
+
+ @Test
+ void rejectsUnknownFieldsOversizedWireAndChangedFreezeOrAuthorizationScope() {
+ var freeze = freeze();
+ var binding =
+ authorization(freeze.request().accountBinding().input().selection().selectedCommit());
+ var request =
+ AutomationSelectedSourceIntakeCommandEvidence.Request.create("test", binding, freeze);
+ var wire = AutomationSelectedSourceIntakeCommandGrpcCodec.toRequest(request);
+ var unknown =
+ UnknownFieldSet.newBuilder()
+ .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build())
+ .build();
+
+ assertThatThrownBy(
+ () ->
+ AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest(
+ wire.toBuilder().setUnknownFields(unknown).build()))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Unknown");
+ assertThatThrownBy(
+ () ->
+ AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest(
+ wire.toBuilder().setIntakeAuthorizationDigest("0".repeat(64)).build()))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("digest");
+ assertThatThrownBy(
+ () ->
+ AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest(
+ wire.toBuilder()
+ .setFreezeRequest(
+ wire.getFreezeRequest().toBuilder().setUnknownFields(unknown).build())
+ .build()))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest(
+ wire.toBuilder()
+ .setOriginalIntakeAuthorizationBinding(
+ ByteString.copyFrom(
+ new byte
+ [AutomationSelectedSourceIntakeCommandGrpcCodec
+ .MAX_REQUEST_WIRE_BYTES
+ + 1]))
+ .build()))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("wire budget");
+
+ var otherNamespaceFreeze = freeze("other");
+ assertThatThrownBy(
+ () ->
+ new AutomationSelectedSourceIntakeCommandEvidence.Request(
+ AutomationSelectedSourceIntakeCommandEvidence.Request.SCHEMA_VERSION,
+ "test",
+ id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"),
+ binding,
+ otherNamespaceFreeze))
+ .isInstanceOf(IllegalArgumentException.class);
+ var wrongOwner =
+ authorization(
+ freeze.request().accountBinding().input().selection().selectedCommit(),
+ Owner.ENTITY_MANAGEMENT);
+ assertThatThrownBy(
+ () ->
+ AutomationSelectedSourceIntakeCommandEvidence.Request.create(
+ "test", wrongOwner, freeze))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ void responseRequiresExactFullRequestEchoAndEncodesReceiptBytesAndDigest() {
+ var freeze = freeze();
+ var binding =
+ authorization(freeze.request().accountBinding().input().selection().selectedCommit());
+ var request =
+ AutomationSelectedSourceIntakeCommandEvidence.Request.create("test", binding, freeze);
+ var receipt = mock(AutomationEmptySelectedSourceIntakeReceipt.class);
+ byte[] storedReceipt = {1, 2, 3};
+ when(receipt.canonicalBytes()).thenReturn(storedReceipt);
+ when(receipt.receiptDigest()).thenReturn("a".repeat(64));
+ when(receipt.authorizationBindingBytes()).thenReturn(binding.canonicalBytes());
+ when(receipt.authorizationBindingDigest()).thenReturn(binding.digest());
+ var evidence = new AutomationSelectedSourceIntakeCommandEvidence(request, receipt);
+ var response = AutomationSelectedSourceIntakeCommandGrpcCodec.toResponse(evidence);
+
+ assertThat(response.getRequest())
+ .isEqualTo(AutomationSelectedSourceIntakeCommandGrpcCodec.toRequest(request));
+ assertThat(response.getCommittedEmptyReceipt().toByteArray()).isEqualTo(storedReceipt);
+ assertThat(response.getReceiptDigest()).isEqualTo("a".repeat(64));
+
+ var changedFreeze =
+ response.toBuilder()
+ .setRequest(
+ response.getRequest().toBuilder()
+ .setFreezeAcknowledgement(
+ response.getRequest().getFreezeAcknowledgement().toBuilder()
+ .setContentDigest("b".repeat(64)))
+ .build())
+ .build();
+ assertThatThrownBy(
+ () ->
+ AutomationSelectedSourceIntakeCommandGrpcCodec.fromResponse(request, changedFreeze))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("changed");
+ assertThatThrownBy(
+ () ->
+ AutomationSelectedSourceIntakeCommandGrpcCodec.fromResponse(
+ request,
+ response.toBuilder()
+ .setUnknownFields(
+ UnknownFieldSet.newBuilder()
+ .addField(
+ 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build())
+ .build())
+ .build()))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Unknown");
+ }
+
+ private static SelectedOwnerIntakeAuthorizationBinding authorization(
+ DraftCommitBinding selected) {
+ return authorization(selected, Owner.AUTOMATION_SCRIPTING);
+ }
+
+ private static SelectedOwnerIntakeAuthorizationBinding authorization(
+ DraftCommitBinding selected, Owner owner) {
+ var scope =
+ new SelectedOwnerIntakeSourceReadScope(
+ owner,
+ "test",
+ id("66666666-6666-4666-8666-666666666666"),
+ id("77777777-7777-4777-8777-777777777777"),
+ id("88888888-8888-4888-8888-888888888888"),
+ ACTOR,
+ selected);
+ var contentBytes = new ByteArrayOutputStream();
+ frame(contentBytes, SelectedOwnerIntakeSourceContent.DOMAIN);
+ frame(contentBytes, scope.canonicalBytes());
+ frame(contentBytes, scope.digest());
+ for (String family :
+ List.of(
+ "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) {
+ byte[] snapshot = SelectedOwnerIntakeSourceTestFixtures.snapshot(family, selected);
+ frame(contentBytes, family);
+ frame(contentBytes, snapshot);
+ frame(contentBytes, DraftAuthorizationFenceBinding.digest(snapshot));
+ }
+ byte[] canonicalContent = contentBytes.toByteArray();
+ var content =
+ SelectedOwnerIntakeSourceContent.fromStored(
+ canonicalContent, scope, DraftAuthorizationFenceBinding.digest(canonicalContent));
+ return new SelectedOwnerIntakeAuthorizationBinding(
+ content,
+ List.of(
+ source(SourceKind.ACCOUNT, ACTOR.toString()),
+ source(SourceKind.TENANT, selected.target().canonicalTenantId().toString()),
+ source(SourceKind.MEMBERSHIP, ACTOR + "/" + selected.target().canonicalTenantId())));
+ }
+
+ private static SourceEvidence source(SourceKind kind, String scope) {
+ return new SourceEvidence(kind, scope, null, "1", null, null, new byte[] {1});
+ }
+
+ private static WorldSelectedDraftPublicationFreezeEvidence freeze() {
+ return freeze("test");
+ }
+
+ private static WorldSelectedDraftPublicationFreezeEvidence freeze(String namespace) {
+ var original = WorldSelectedDraftPublicationFreezeGrpcCodecTest.request();
+ if (!namespace.equals(original.targetNamespace())) {
+ // The fixture's Account publication binding is namespace-independent; rebuild only its
+ // request tuple through the same constructor used by the production value.
+ original =
+ WorldSelectedDraftPublicationFreezeEvidence.Request.create(
+ namespace,
+ original.canonicalTenantId(),
+ original.canonicalVersionId(),
+ original.publicationRequestId(),
+ original.expectedVersionStateEpoch(),
+ original.requestDigest(),
+ original.accountBinding());
+ }
+ var acknowledgement =
+ new Acknowledgement(
+ original,
+ id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"),
+ original.expectedVersionStateEpoch(),
+ id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"),
+ OwnerFreezePhase.FROZEN,
+ original.accountBinding().input().selection().selectedCommit().commitId().toString(),
+ "a".repeat(64),
+ 3);
+ BeginVersionPublicationFreezeResponse response =
+ WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement);
+ return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse(original, response);
+ }
+
+ private static void frame(ByteArrayOutputStream output, String value) {
+ DraftAuthorizationFenceBinding.frame(output, value);
+ }
+
+ private static void frame(ByteArrayOutputStream output, byte[] value) {
+ DraftAuthorizationFenceBinding.frame(output, value);
+ }
+
+ private static UUID id(String value) {
+ return UUID.fromString(value);
+ }
+}
diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java
index 6763a55fbe..413c70a3c6 100644
--- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java
+++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java
@@ -9,6 +9,7 @@
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding;
+import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence;
import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence;
import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest;
import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult;
@@ -18,6 +19,128 @@
import org.junit.jupiter.api.Test;
class GameDesignPublicationTerminalEvidenceCodecTest {
+ @Test
+ void selectedFullV4TerminalRoundTripsOnlyTheExactCompleteParticipantVector() throws Exception {
+ var fixture = PublishedRealmEntryPolicySetEvidenceTest.fixture(false);
+ var previous = fixture.terminal().releaseContent();
+ var previousSelector = previous.worldStartLocationEvidence();
+ var oldRequest = previousSelector.request();
+ var selectorRequest =
+ new WorldPublishedStartLocationEvidence.Request(
+ oldRequest.targetNamespace(),
+ oldRequest.canonicalTenantId(),
+ oldRequest.canonicalVersionId(),
+ oldRequest.intakeRequestId(),
+ oldRequest.publicationFence(),
+ oldRequest.publicationRequestId(),
+ oldRequest.requestDigest(),
+ oldRequest.versionStateEpoch(),
+ oldRequest.publishWorkflowId(),
+ oldRequest.appliedCommitId(),
+ oldRequest.contentDigest(),
+ AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION,
+ oldRequest.worldAffectedTuples());
+ var selector =
+ new WorldPublishedStartLocationEvidence(
+ selectorRequest,
+ previousSelector.selectorReceiptBytes(),
+ previousSelector.originalAccountBindingBytes(),
+ previousSelector.appliedResultBytes());
+ var operation =
+ new GameDesignPublicationOperationBinding(
+ fixture.operation().account(),
+ selector,
+ net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures.stipulated(
+ fixture.operation().account(), selector));
+ var participants =
+ previous.participantDigests().stream()
+ .map(
+ participant ->
+ new GameDesignPublicationTerminalEvidence.Participant(
+ participant.participantKey(),
+ participant.scopeValue(),
+ participant.baseVersionId(),
+ participant.appliedCommitId(),
+ participant.contentDigest(),
+ AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema(
+ participant.participantKey(),
+ AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION),
+ participant.abilitySchemaDigest(),
+ participant.errorCode(),
+ participant.errorMessage()))
+ .toList();
+ var release =
+ new GameDesignPublicationTerminalEvidence.ReleaseContent(
+ previous.canonicalTenantId(),
+ previous.canonicalVersionId(),
+ previous.publishedReleaseBundleRef(),
+ previous.versionNumber(),
+ "v4",
+ previous.publishWorkflowId(),
+ previous.manifestHash(),
+ previous.manifestSchemaVersion(),
+ previous.artifactDigests(),
+ previous.requiredManifestAssetKeys(),
+ participants,
+ previous.commandDefinitions(),
+ previous.generationConfigRevision(),
+ selector);
+ assertThat(participants)
+ .extracting(GameDesignPublicationTerminalEvidence.Participant::digestSchemaVersion)
+ .containsExactly(4, 3, 1, 6, 2);
+
+ var terminal =
+ new GameDesignPublicationTerminalEvidence(
+ operation.canonicalBytes(),
+ GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED,
+ release,
+ fixture.terminal().publicationVersionStateEpoch());
+ var request =
+ new ReadRequest(
+ ReadRequest.SCHEMA_VERSION,
+ operation.world().request().targetNamespace(),
+ java.util.UUID.fromString("30303030-3030-4030-8030-303030303030"),
+ operation.canonicalBytes());
+ var result = new ReadResult(request, Status.PUBLISHED, Optional.of(terminal));
+ var response = GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result);
+
+ assertThat(GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, response))
+ .isEqualTo(result);
+
+ var mixedParticipants = new java.util.ArrayList<>(participants);
+ mixedParticipants.set(
+ 3,
+ new GameDesignPublicationTerminalEvidence.Participant(
+ "AUTOMATION_SCRIPTING",
+ participants.get(3).scopeValue(),
+ null,
+ participants.get(3).appliedCommitId(),
+ participants.get(3).contentDigest(),
+ 5,
+ null,
+ null,
+ null));
+ assertThatThrownBy(
+ () ->
+ new GameDesignPublicationTerminalEvidence.ReleaseContent(
+ previous.canonicalTenantId(),
+ previous.canonicalVersionId(),
+ previous.publishedReleaseBundleRef(),
+ previous.versionNumber(),
+ "v4",
+ previous.publishWorkflowId(),
+ previous.manifestHash(),
+ previous.manifestSchemaVersion(),
+ previous.artifactDigests(),
+ previous.requiredManifestAssetKeys(),
+ mixedParticipants,
+ previous.commandDefinitions(),
+ previous.generationConfigRevision(),
+ selector))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Incomplete or changed required participant proof");
+ }
+
@Test
void maximumFrozenEpochIsRejectedAsInvalidEvidenceAndOrdinaryEpochRoundTrips() throws Exception {
var ordinary = PublishedRealmEntryPolicySetEvidenceTest.fixture(false);
diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClient.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClient.java
new file mode 100644
index 0000000000..a7e3bfccb7
--- /dev/null
+++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClient.java
@@ -0,0 +1,189 @@
+package net.firedevops.firemud.common.security.sourceintake;
+
+import io.grpc.ManagedChannel;
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Objects;
+import java.util.concurrent.TimeUnit;
+import javax.net.ssl.SSLException;
+import net.firedevops.firemud.automationscripting.v1.AutomationSelectedSourceIntakeCommandServiceGrpc;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence.Request;
+import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandGrpcCodec;
+import net.firedevops.firemud.common.config.ServiceEndpointsProperties;
+import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient;
+import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties;
+import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials;
+import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
+import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
+import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
+import net.firedevops.firemud.common.security.SessionContext;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** File-backed mTLS client for Automation's unregistered selected-source command. */
+public final class GrpcAutomationSelectedSourceIntakeCommandClient
+ extends AbstractReloadingBlockingGrpcClient<
+ AutomationSelectedSourceIntakeCommandServiceGrpc
+ .AutomationSelectedSourceIntakeCommandServiceBlockingStub> {
+ private static final long CALL_DEADLINE_SECONDS = 5L;
+
+ private final String workloadNamespace;
+ private volatile boolean initialized;
+ private volatile boolean closed;
+
+ public GrpcAutomationSelectedSourceIntakeCommandClient(
+ ServiceEndpointsProperties endpoints,
+ CommonGrpcClientProperties tlsProperties,
+ GrpcChannelFactory channelFactory,
+ String workloadNamespace) {
+ super(
+ endpoints,
+ requireFileBackedMtls(tlsProperties),
+ channelFactory,
+ GrpcAutomationSelectedSourceIntakeCommandClient.class);
+ if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) {
+ throw new IllegalArgumentException("Canonical workload namespace required");
+ }
+ this.workloadNamespace = workloadNamespace;
+ }
+
+ public synchronized void init() throws SSLException, IOException {
+ if (closed) {
+ throw new IllegalStateException("Automation selected-source command client is closed");
+ }
+ if (initialized) return;
+ initReloadingClient();
+ if (stub() == null) {
+ throw new IllegalStateException("Automation selected-source command stub unavailable");
+ }
+ initialized = true;
+ }
+
+ /** Returns only the exact immutable receipt echoed for this complete original request. */
+ public AutomationSelectedSourceIntakeCommandEvidence retain(Request request) {
+ requireWorkloadOnlyContext();
+ Objects.requireNonNull(request, "selected-source command request is required");
+ if (!workloadNamespace.equals(request.targetNamespace())) {
+ throw new IllegalArgumentException(
+ "Automation selected-source command must use the configured workload namespace");
+ }
+ var wireRequest = AutomationSelectedSourceIntakeCommandGrpcCodec.toRequest(request);
+ var current = requireStub();
+ try {
+ var response =
+ current
+ .withMaxOutboundMessageSize(
+ AutomationSelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES)
+ .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS)
+ .retainSelectedSource(wireRequest);
+ return AutomationSelectedSourceIntakeCommandGrpcCodec.fromResponse(request, response);
+ } catch (StatusRuntimeException denied) {
+ throw Status.fromCode(denied.getStatus().getCode()).asRuntimeException();
+ } catch (IllegalArgumentException malformed) {
+ throw new IllegalStateException(
+ "Automation returned invalid selected-source receipt evidence");
+ }
+ }
+
+ @Override
+ protected String configuredTarget(ServiceEndpointsProperties endpoints) {
+ return endpoints.getAutomationScriptingService();
+ }
+
+ @Override
+ protected String defaultTarget() {
+ return "automation-scripting-service:6565";
+ }
+
+ @Override
+ protected AutomationSelectedSourceIntakeCommandServiceGrpc
+ .AutomationSelectedSourceIntakeCommandServiceBlockingStub
+ buildStub(ManagedChannel channel) {
+ String expectedPeerUri = automationServerPeerUri(workloadNamespace);
+ return AutomationSelectedSourceIntakeCommandServiceGrpc.newBlockingStub(channel)
+ .withMaxInboundMessageSize(
+ AutomationSelectedSourceIntakeCommandGrpcCodec.MAX_RESPONSE_WIRE_BYTES)
+ .withMaxOutboundMessageSize(
+ AutomationSelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES)
+ .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri))
+ .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri))
+ .withCompression("gzip");
+ }
+
+ @Override
+ public void close() throws IOException {
+ synchronized (this) {
+ closed = true;
+ initialized = false;
+ }
+ super.close();
+ }
+
+ private AutomationSelectedSourceIntakeCommandServiceGrpc
+ .AutomationSelectedSourceIntakeCommandServiceBlockingStub
+ requireStub() {
+ var currentStub = stub();
+ if (closed || !initialized || currentStub == null) {
+ throw new IllegalStateException(
+ "Automation selected-source command client is not initialized and available");
+ }
+ return currentStub;
+ }
+
+ private static void requireWorkloadOnlyContext() {
+ if (TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isSynchronizationActive()) {
+ throw new IllegalStateException(
+ "Automation selected-source command requires no ambient SQL or synchronization");
+ }
+ if (SessionContext.hasAuthenticatedCallerContext()
+ || AccountOriginalDraftOrderCredentials.CONTEXT_KEY.get() != null
+ || AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY.get() != null
+ || SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY.get() != null) {
+ throw new IllegalStateException(
+ "Automation selected-source command requires workload-only context");
+ }
+ }
+
+ private static String automationServerPeerUri(String namespace) {
+ return "spiffe://firemud/ns/" + namespace + "/sa/automation-scripting-service";
+ }
+
+ private static CommonGrpcClientProperties requireFileBackedMtls(
+ CommonGrpcClientProperties tlsProperties) {
+ if (tlsProperties == null || tlsProperties.isPlaintext()) {
+ throw new IllegalArgumentException(
+ "Automation selected-source command requires workload mTLS");
+ }
+ requireReadableFile(tlsProperties.getCertChain(), "certificate chain");
+ requireReadableFile(tlsProperties.getPrivateKey(), "private key");
+ requireReadableFile(tlsProperties.getCaCert(), "CA certificate");
+ return tlsProperties;
+ }
+
+ private static void requireReadableFile(String configuredPath, String label) {
+ if (configuredPath == null
+ || configuredPath.isBlank()
+ || configuredPath.trim().startsWith("classpath:")) {
+ throw new IllegalArgumentException(
+ "Automation selected-source command requires file-backed certificate, key, and CA material");
+ }
+ Path path;
+ try {
+ path = Path.of(configuredPath.trim());
+ } catch (RuntimeException invalid) {
+ throw new IllegalArgumentException(
+ "Invalid Automation selected-source command " + label + " path");
+ }
+ if (!Files.isRegularFile(path) || !Files.isReadable(path)) {
+ throw new IllegalArgumentException(
+ "Automation selected-source command " + label + " must be an existing readable file");
+ }
+ }
+}
diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClient.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClient.java
new file mode 100644
index 0000000000..8095d0c4f7
--- /dev/null
+++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClient.java
@@ -0,0 +1,187 @@
+package net.firedevops.firemud.common.security.sourceintake;
+
+import io.grpc.ManagedChannel;
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Objects;
+import java.util.concurrent.TimeUnit;
+import javax.net.ssl.SSLException;
+import net.firedevops.firemud.common.config.ServiceEndpointsProperties;
+import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence;
+import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandGrpcCodec;
+import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient;
+import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties;
+import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials;
+import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
+import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
+import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
+import net.firedevops.firemud.common.security.SessionContext;
+import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeCommandServiceGrpc;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** File-backed mTLS client for Entity's unregistered selected-source command. */
+public final class GrpcEntitySelectedSourceIntakeCommandClient
+ extends AbstractReloadingBlockingGrpcClient<
+ EntitySelectedSourceIntakeCommandServiceGrpc
+ .EntitySelectedSourceIntakeCommandServiceBlockingStub> {
+ private static final long CALL_DEADLINE_SECONDS = 5L;
+
+ private final String workloadNamespace;
+ private volatile boolean initialized;
+ private volatile boolean closed;
+
+ public GrpcEntitySelectedSourceIntakeCommandClient(
+ ServiceEndpointsProperties endpoints,
+ CommonGrpcClientProperties tlsProperties,
+ GrpcChannelFactory channelFactory,
+ String workloadNamespace) {
+ super(
+ endpoints,
+ requireFileBackedMtls(tlsProperties),
+ channelFactory,
+ GrpcEntitySelectedSourceIntakeCommandClient.class);
+ if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) {
+ throw new IllegalArgumentException("Canonical workload namespace required");
+ }
+ this.workloadNamespace = workloadNamespace;
+ }
+
+ public synchronized void init() throws SSLException, IOException {
+ if (closed) {
+ throw new IllegalStateException("Entity selected-source command client is closed");
+ }
+ if (initialized) return;
+ initReloadingClient();
+ if (stub() == null) {
+ throw new IllegalStateException("Entity selected-source command stub unavailable");
+ }
+ initialized = true;
+ }
+
+ /** Returns only the exact immutable Entity receipt echoed for this complete original request. */
+ public EntitySelectedSourceIntakeCommandEvidence retain(
+ EntitySelectedSourceIntakeCommandEvidence.Request request) {
+ requireWorkloadOnlyContext();
+ Objects.requireNonNull(request, "selected-source command request is required");
+ if (!workloadNamespace.equals(request.targetNamespace())) {
+ throw new IllegalArgumentException(
+ "Entity selected-source command must use the configured workload namespace");
+ }
+ var wireRequest = EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(request);
+ var current = requireStub();
+ try {
+ var response =
+ current
+ .withMaxOutboundMessageSize(
+ EntitySelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES)
+ .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS)
+ .retainSelectedEntitySource(wireRequest);
+ return EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse(request, response);
+ } catch (StatusRuntimeException denied) {
+ throw Status.fromCode(denied.getStatus().getCode()).asRuntimeException();
+ } catch (IllegalArgumentException malformed) {
+ throw new IllegalStateException("Entity returned invalid selected-source receipt evidence");
+ }
+ }
+
+ @Override
+ protected String configuredTarget(ServiceEndpointsProperties endpoints) {
+ return endpoints.getEntityManagementService();
+ }
+
+ @Override
+ protected String defaultTarget() {
+ return "entity-management-service:6565";
+ }
+
+ @Override
+ protected EntitySelectedSourceIntakeCommandServiceGrpc
+ .EntitySelectedSourceIntakeCommandServiceBlockingStub
+ buildStub(ManagedChannel channel) {
+ String expectedPeerUri = entityServerPeerUri(workloadNamespace);
+ return EntitySelectedSourceIntakeCommandServiceGrpc.newBlockingStub(channel)
+ .withMaxInboundMessageSize(
+ EntitySelectedSourceIntakeCommandGrpcCodec.MAX_RESPONSE_WIRE_BYTES)
+ .withMaxOutboundMessageSize(
+ EntitySelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES)
+ .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri))
+ .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri))
+ .withCompression("gzip");
+ }
+
+ @Override
+ public void close() throws IOException {
+ synchronized (this) {
+ closed = true;
+ initialized = false;
+ }
+ super.close();
+ }
+
+ private EntitySelectedSourceIntakeCommandServiceGrpc
+ .EntitySelectedSourceIntakeCommandServiceBlockingStub
+ requireStub() {
+ var currentStub = stub();
+ if (closed || !initialized || currentStub == null) {
+ throw new IllegalStateException(
+ "Entity selected-source command client is not initialized and available");
+ }
+ return currentStub;
+ }
+
+ private static void requireWorkloadOnlyContext() {
+ if (TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isSynchronizationActive()) {
+ throw new IllegalStateException(
+ "Entity selected-source command requires no ambient SQL or synchronization");
+ }
+ if (SessionContext.hasAuthenticatedCallerContext()
+ || AccountOriginalDraftOrderCredentials.CONTEXT_KEY.get() != null
+ || AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY.get() != null
+ || SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY.get() != null) {
+ throw new IllegalStateException(
+ "Entity selected-source command requires workload-only context");
+ }
+ }
+
+ private static String entityServerPeerUri(String namespace) {
+ return "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service";
+ }
+
+ private static CommonGrpcClientProperties requireFileBackedMtls(
+ CommonGrpcClientProperties tlsProperties) {
+ if (tlsProperties == null || tlsProperties.isPlaintext()) {
+ throw new IllegalArgumentException("Entity selected-source command requires workload mTLS");
+ }
+ requireReadableFile(tlsProperties.getCertChain(), "certificate chain");
+ requireReadableFile(tlsProperties.getPrivateKey(), "private key");
+ requireReadableFile(tlsProperties.getCaCert(), "CA certificate");
+ return tlsProperties;
+ }
+
+ private static void requireReadableFile(String configuredPath, String label) {
+ if (configuredPath == null
+ || configuredPath.isBlank()
+ || configuredPath.trim().startsWith("classpath:")) {
+ throw new IllegalArgumentException(
+ "Entity selected-source command requires file-backed certificate, key, and CA material");
+ }
+ Path path;
+ try {
+ path = Path.of(configuredPath.trim());
+ } catch (RuntimeException invalid) {
+ throw new IllegalArgumentException(
+ "Invalid Entity selected-source command " + label + " path");
+ }
+ if (!Files.isRegularFile(path) || !Files.isReadable(path)) {
+ throw new IllegalArgumentException(
+ "Entity selected-source command " + label + " must be an existing readable file");
+ }
+ }
+}
diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java
new file mode 100644
index 0000000000..6f11cf35c3
--- /dev/null
+++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java
@@ -0,0 +1,145 @@
+package net.firedevops.firemud.common.security.sourceintake;
+
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+
+import io.grpc.Context;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+import net.firedevops.firemud.common.config.ServiceEndpointsProperties;
+import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties;
+import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
+import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
+import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
+import net.firedevops.firemud.common.security.SessionContext;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Constructor and pre-transport gates only; placeholder files do not prove an mTLS handshake. */
+class GrpcAutomationSelectedSourceIntakeCommandClientTest {
+ @AfterEach
+ void clearAmbientContext() {
+ TransactionSynchronizationManager.clear();
+ SessionContext.clear();
+ }
+
+ @Test
+ void requiresReadableFileBackedMtlsAndCanonicalNamespace(@TempDir Path directory)
+ throws IOException {
+ var channelFactory = mock(GrpcChannelFactory.class);
+ var plaintext = tls(directory);
+ plaintext.setPlaintext(true);
+ assertThatThrownBy(
+ () ->
+ new GrpcAutomationSelectedSourceIntakeCommandClient(
+ new ServiceEndpointsProperties(), plaintext, channelFactory, "test"))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("mTLS");
+
+ for (String invalidPath :
+ new String[] {
+ null,
+ "",
+ "classpath:credential.pem",
+ directory.toString(),
+ directory.resolve("missing.pem").toString()
+ }) {
+ var invalidCertificate = tls(directory);
+ invalidCertificate.setCertChain(invalidPath);
+ assertThatThrownBy(
+ () ->
+ new GrpcAutomationSelectedSourceIntakeCommandClient(
+ new ServiceEndpointsProperties(), invalidCertificate, channelFactory, "test"))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+ var invalidKey = tls(directory);
+ invalidKey.setPrivateKey(directory.resolve("missing-key.pem").toString());
+ assertThatThrownBy(
+ () ->
+ new GrpcAutomationSelectedSourceIntakeCommandClient(
+ new ServiceEndpointsProperties(), invalidKey, channelFactory, "test"))
+ .isInstanceOf(IllegalArgumentException.class);
+ var invalidCa = tls(directory);
+ invalidCa.setCaCert(directory.resolve("missing-ca.pem").toString());
+ assertThatThrownBy(
+ () ->
+ new GrpcAutomationSelectedSourceIntakeCommandClient(
+ new ServiceEndpointsProperties(), invalidCa, channelFactory, "test"))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ new GrpcAutomationSelectedSourceIntakeCommandClient(
+ new ServiceEndpointsProperties(), tls(directory), channelFactory, "Test"))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("namespace");
+
+ verifyNoInteractions(channelFactory);
+ }
+
+ @Test
+ void rejectsAmbientSqlSynchronizationAndEndUserContextBeforeTransport(@TempDir Path directory)
+ throws IOException {
+ var channelFactory = mock(GrpcChannelFactory.class);
+ var client =
+ new GrpcAutomationSelectedSourceIntakeCommandClient(
+ new ServiceEndpointsProperties(), tls(directory), channelFactory, "test");
+ try {
+ TransactionSynchronizationManager.setActualTransactionActive(true);
+ assertThatThrownBy(() -> client.retain(null))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("ambient SQL");
+ TransactionSynchronizationManager.setActualTransactionActive(false);
+
+ TransactionSynchronizationManager.initSynchronization();
+ assertThatThrownBy(() -> client.retain(null))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("ambient SQL");
+ TransactionSynchronizationManager.clearSynchronization();
+
+ SessionContext.setContext("101", List.of(), Map.of());
+ assertThatThrownBy(() -> client.retain(null))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("workload-only context");
+ SessionContext.clear();
+ for (var producerContext : List.of(
+ Context.current().withValue(AccountOriginalDraftOrderCredentials.CONTEXT_KEY,
+ AccountOriginalDraftOrderCredentials.Credential.of("controlled-original-author")),
+ Context.current().withValue(AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY,
+ AccountGameLogicIntakeAuthorizationCredentials.Credential.of("controlled-game-logic-author")),
+ Context.current().withValue(SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY,
+ SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of("controlled-selected-intake-author")))) {
+ var previous = producerContext.attach();
+ try {
+ assertThatThrownBy(() -> client.retain(null))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("workload-only context");
+ } finally {
+ producerContext.detach(previous);
+ }
+ }
+ verifyNoInteractions(channelFactory);
+ } finally {
+ client.close();
+ TransactionSynchronizationManager.clear();
+ SessionContext.clear();
+ }
+ }
+
+ private static CommonGrpcClientProperties tls(Path directory) throws IOException {
+ var tls = new CommonGrpcClientProperties();
+ tls.setPlaintext(false);
+ tls.setCertChain(
+ Files.writeString(directory.resolve("client.crt"), "placeholder cert").toString());
+ tls.setPrivateKey(
+ Files.writeString(directory.resolve("client.key"), "placeholder key").toString());
+ tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "placeholder CA").toString());
+ return tls;
+ }
+}
diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java
new file mode 100644
index 0000000000..9ca9565e18
--- /dev/null
+++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java
@@ -0,0 +1,511 @@
+package net.firedevops.firemud.common.security.sourceintake;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+
+import io.grpc.Context;
+import io.grpc.Deadline;
+import io.grpc.Metadata;
+import io.grpc.Server;
+import io.grpc.ServerCall;
+import io.grpc.ServerCallHandler;
+import io.grpc.ServerInterceptor;
+import io.grpc.ServerInterceptors;
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
+import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
+import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth;
+import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder;
+import io.grpc.stub.StreamObserver;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import net.firedevops.firemud.common.config.ServiceEndpointsProperties;
+import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence;
+import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandGrpcCodec;
+import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties;
+import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
+import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
+import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
+import net.firedevops.firemud.common.security.SessionContext;
+import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeCommandServiceGrpc;
+import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceRequest;
+import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceResponse;
+import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures;
+import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/**
+ * Positive command mTLS proof; synthetic fixture is not Entity producer or physical census proof.
+ */
+class GrpcEntitySelectedSourceIntakeCommandClientMtlsTest {
+ private static final String NAMESPACE = "test";
+ private static final String ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-management-service";
+ private static final String WRONG_ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-other";
+ private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service";
+ private static final String STORE_PASSWORD = "synthetic-test-store-password";
+
+ @TempDir static Path tempDirectory;
+ private static Fixture fixture;
+ private static TestPki pki;
+ private Server server;
+ private GrpcEntitySelectedSourceIntakeCommandClient client;
+ private AtomicInteger headers;
+ private AtomicInteger bodies;
+ private AtomicReference deadline;
+
+ @BeforeAll
+ static void createSyntheticInputsAndTrustedCertificates() throws Exception {
+ fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create();
+ pki = TestPki.create(tempDirectory);
+ }
+
+ @AfterEach
+ void stopTransportAndClearAmbientContext() throws Exception {
+ if (client != null) {
+ client.close();
+ client = null;
+ }
+ if (server != null) {
+ server.shutdownNow();
+ assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue();
+ server = null;
+ }
+ TransactionSynchronizationManager.clear();
+ SessionContext.clear();
+ }
+
+ @Test
+ void loopbackMtlsReturnsExactReceiptAndPinsEntityServerWithBoundedDeadline() throws Exception {
+ var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence();
+ var request =
+ EntitySelectedSourceIntakeCommandEvidence.Request.create(
+ NAMESPACE, fixture.authorization(), freeze);
+ byte[] receiptBytes = fixture.receipt().canonicalBytes();
+
+ startServer(pki.entityServer());
+ client = newClient(server, pki.gameDesignClient());
+ client.init();
+ var actual = client.retain(request);
+ assertThat(actual.request()).isEqualTo(request);
+ assertThat(actual.receipt().canonicalBytes()).isEqualTo(receiptBytes);
+ assertThat(actual.receipt().authorizationBindingBytes())
+ .isEqualTo(fixture.authorization().canonicalBytes());
+ assertThat(headers).hasValue(1);
+ assertThat(bodies).hasValue(1);
+ assertThat(deadline.get()).isNotNull();
+ assertThat(deadline.get().timeRemaining(TimeUnit.SECONDS)).isBetween(1L, 5L);
+
+ stopCurrentTransport();
+ startServer(pki.wrongServer());
+ client = newClient(server, pki.gameDesignClient());
+ client.init();
+ assertThatThrownBy(() -> client.retain(request))
+ .isInstanceOf(StatusRuntimeException.class)
+ .satisfies(
+ failure ->
+ assertThat(Status.fromThrowable(failure).getCode())
+ .isEqualTo(Status.Code.UNAUTHENTICATED));
+ assertThat(headers).hasValue(0);
+ assertThat(bodies).hasValue(0);
+ }
+
+ @Test
+ void namespaceSqlSynchronizationEndUserAndSelectedOrderAreDeniedBeforeTransport(@TempDir Path dir)
+ throws Exception {
+ var factory = mock(GrpcChannelFactory.class);
+ var request =
+ EntitySelectedSourceIntakeCommandEvidence.Request.create(
+ NAMESPACE,
+ fixture.authorization(),
+ fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence());
+ var wrongNamespaceClient =
+ new GrpcEntitySelectedSourceIntakeCommandClient(
+ new ServiceEndpointsProperties(), placeholderTls(dir), factory, "other");
+ try {
+ assertThatThrownBy(() -> wrongNamespaceClient.retain(request))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("configured workload namespace");
+ verifyNoInteractions(factory);
+ } finally {
+ wrongNamespaceClient.close();
+ }
+
+ var client =
+ new GrpcEntitySelectedSourceIntakeCommandClient(
+ new ServiceEndpointsProperties(), placeholderTls(dir), factory, NAMESPACE);
+ try {
+ TransactionSynchronizationManager.setActualTransactionActive(true);
+ assertThatThrownBy(() -> client.retain(null))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("ambient SQL");
+ TransactionSynchronizationManager.setActualTransactionActive(false);
+
+ TransactionSynchronizationManager.initSynchronization();
+ assertThatThrownBy(() -> client.retain(null))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("ambient SQL");
+ TransactionSynchronizationManager.clearSynchronization();
+
+ SessionContext.setContext("101", List.of(), Map.of());
+ assertThatThrownBy(() -> client.retain(null))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("workload-only context");
+ SessionContext.clear();
+
+ for (var producerContext : List.of(
+ Context.current().withValue(AccountOriginalDraftOrderCredentials.CONTEXT_KEY,
+ AccountOriginalDraftOrderCredentials.Credential.of("controlled-original-author")),
+ Context.current().withValue(AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY,
+ AccountGameLogicIntakeAuthorizationCredentials.Credential.of("controlled-game-logic-author")),
+ Context.current().withValue(SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY,
+ SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of("controlled-selected-intake-author")))) {
+ var previous = producerContext.attach();
+ try {
+ assertThatThrownBy(() -> client.retain(null))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("workload-only context");
+ } finally {
+ producerContext.detach(previous);
+ }
+ }
+ verifyNoInteractions(factory);
+ } finally {
+ client.close();
+ TransactionSynchronizationManager.clear();
+ SessionContext.clear();
+ }
+ }
+
+ private void startServer(TestIdentity identity) throws Exception {
+ headers = new AtomicInteger();
+ bodies = new AtomicInteger();
+ deadline = new AtomicReference<>();
+ var service =
+ new EntitySelectedSourceIntakeCommandServiceGrpc
+ .EntitySelectedSourceIntakeCommandServiceImplBase() {
+ @Override
+ public void retainSelectedEntitySource(
+ RetainSelectedEntitySourceRequest wire,
+ StreamObserver observer) {
+ bodies.incrementAndGet();
+ assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(GAME_DESIGN_URI);
+ deadline.set(Context.current().getDeadline());
+ var request = EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(wire);
+ assertThat(request.originalAuthorizationBinding().canonicalBytes())
+ .isEqualTo(fixture.authorization().canonicalBytes());
+ assertThat(request.freezeEvidence())
+ .isEqualTo(
+ fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence());
+ observer.onNext(
+ EntitySelectedSourceIntakeCommandGrpcCodec.toResponse(
+ new EntitySelectedSourceIntakeCommandEvidence(request, fixture.receipt())));
+ observer.onCompleted();
+ }
+ };
+ ServerInterceptor countHeaders =
+ new ServerInterceptor() {
+ @Override
+ public ServerCall.Listener interceptCall(
+ ServerCall call,
+ Metadata metadata,
+ ServerCallHandler next) {
+ headers.incrementAndGet();
+ return next.startCall(call, metadata);
+ }
+ };
+ server =
+ NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0))
+ .maxInboundMessageSize(
+ EntitySelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES)
+ .sslContext(
+ GrpcSslContexts.configure(
+ SslContextBuilder.forServer(identity.privateKey(), identity.certificate()))
+ .trustManager(pki.caCertificate())
+ .clientAuth(ClientAuth.REQUIRE)
+ .build())
+ .addService(
+ ServerInterceptors.intercept(
+ service, countHeaders, new GrpcPeerIdentityInterceptor()))
+ .build()
+ .start();
+ }
+
+ private GrpcEntitySelectedSourceIntakeCommandClient newClient(Server target, TestIdentity local)
+ throws Exception {
+ var endpoints = new ServiceEndpointsProperties();
+ endpoints.setEntityManagementService("localhost:" + target.getPort());
+ return new GrpcEntitySelectedSourceIntakeCommandClient(
+ endpoints, pki.clientProperties(tempDirectory, local), new GrpcChannelFactory(), NAMESPACE);
+ }
+
+ private void stopCurrentTransport() throws Exception {
+ if (client != null) {
+ client.close();
+ client = null;
+ }
+ if (server != null) {
+ server.shutdownNow();
+ assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue();
+ server = null;
+ }
+ }
+
+ private static CommonGrpcClientProperties placeholderTls(Path directory) throws IOException {
+ var tls = new CommonGrpcClientProperties();
+ tls.setPlaintext(false);
+ tls.setCertChain(
+ Files.writeString(directory.resolve("client.crt"), "synthetic cert").toString());
+ tls.setPrivateKey(
+ Files.writeString(directory.resolve("client.key"), "synthetic key").toString());
+ tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "synthetic CA").toString());
+ return tls;
+ }
+
+ private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {}
+
+ private record TestPki(
+ X509Certificate caCertificate,
+ TestIdentity entityServer,
+ TestIdentity wrongServer,
+ TestIdentity gameDesignClient) {
+ private static TestPki create(Path directory) throws Exception {
+ Path caStore = directory.resolve("entity-command-test-ca.p12");
+ runKeytool(
+ "-genkeypair",
+ "-alias",
+ "test-ca",
+ "-keyalg",
+ "RSA",
+ "-keysize",
+ "2048",
+ "-dname",
+ "CN=FireMUD Entity command test CA",
+ "-validity",
+ "30",
+ "-ext",
+ "BC=ca:true",
+ "-ext",
+ "KU=keyCertSign,cRLSign",
+ "-storetype",
+ "PKCS12",
+ "-keystore",
+ caStore.toString(),
+ "-storepass",
+ STORE_PASSWORD,
+ "-keypass",
+ STORE_PASSWORD);
+ Path caFile = directory.resolve("entity-command-test-ca.crt");
+ runKeytool(
+ "-exportcert",
+ "-alias",
+ "test-ca",
+ "-keystore",
+ caStore.toString(),
+ "-storetype",
+ "PKCS12",
+ "-storepass",
+ STORE_PASSWORD,
+ "-file",
+ caFile.toString(),
+ "-rfc");
+ var caCertificate = readCertificate(caFile);
+ return new TestPki(
+ caCertificate,
+ issueIdentity(directory, caStore, caFile, "entity-server", ENTITY_URI, true),
+ issueIdentity(directory, caStore, caFile, "wrong-entity-server", WRONG_ENTITY_URI, true),
+ issueIdentity(directory, caStore, caFile, "game-design-client", GAME_DESIGN_URI, false));
+ }
+
+ private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity)
+ throws Exception {
+ Path certificate =
+ writePem(
+ directory.resolve("game-design-client.crt"),
+ "CERTIFICATE",
+ identity.certificate().getEncoded());
+ Path privateKey =
+ writePem(
+ directory.resolve("game-design-client.key"),
+ "PRIVATE KEY",
+ identity.privateKey().getEncoded());
+ Path caFile =
+ writePem(
+ directory.resolve("entity-command-client-ca.crt"),
+ "CERTIFICATE",
+ caCertificate.getEncoded());
+ var properties = new CommonGrpcClientProperties();
+ properties.setPlaintext(false);
+ properties.setCertChain(certificate.toString());
+ properties.setPrivateKey(privateKey.toString());
+ properties.setCaCert(caFile.toString());
+ return properties;
+ }
+
+ private static TestIdentity issueIdentity(
+ Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server)
+ throws Exception {
+ Path store = directory.resolve(alias + ".p12");
+ Path request = directory.resolve(alias + ".csr");
+ Path certificate = directory.resolve(alias + ".crt");
+ String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1";
+ runKeytool(
+ "-genkeypair",
+ "-alias",
+ alias,
+ "-keyalg",
+ "RSA",
+ "-keysize",
+ "2048",
+ "-dname",
+ "CN=" + alias,
+ "-validity",
+ "30",
+ "-ext",
+ "KU=digitalSignature,keyEncipherment",
+ "-ext",
+ "EKU=" + (server ? "serverAuth" : "clientAuth"),
+ "-ext",
+ "SAN=" + san,
+ "-storetype",
+ "PKCS12",
+ "-keystore",
+ store.toString(),
+ "-storepass",
+ STORE_PASSWORD,
+ "-keypass",
+ STORE_PASSWORD);
+ runKeytool(
+ "-certreq",
+ "-alias",
+ alias,
+ "-keystore",
+ store.toString(),
+ "-storetype",
+ "PKCS12",
+ "-storepass",
+ STORE_PASSWORD,
+ "-file",
+ request.toString(),
+ "-ext",
+ "SAN=" + san);
+ runKeytool(
+ "-gencert",
+ "-alias",
+ "test-ca",
+ "-keystore",
+ caStore.toString(),
+ "-storetype",
+ "PKCS12",
+ "-storepass",
+ STORE_PASSWORD,
+ "-infile",
+ request.toString(),
+ "-outfile",
+ certificate.toString(),
+ "-validity",
+ "30",
+ "-rfc",
+ "-ext",
+ "BC=ca:false",
+ "-ext",
+ "KU=digitalSignature,keyEncipherment",
+ "-ext",
+ "EKU=" + (server ? "serverAuth" : "clientAuth"),
+ "-ext",
+ "SAN=" + san);
+ runKeytool(
+ "-importcert",
+ "-alias",
+ "test-ca",
+ "-keystore",
+ store.toString(),
+ "-storetype",
+ "PKCS12",
+ "-storepass",
+ STORE_PASSWORD,
+ "-file",
+ caFile.toString(),
+ "-noprompt");
+ runKeytool(
+ "-importcert",
+ "-alias",
+ alias,
+ "-keystore",
+ store.toString(),
+ "-storetype",
+ "PKCS12",
+ "-storepass",
+ STORE_PASSWORD,
+ "-file",
+ certificate.toString(),
+ "-noprompt");
+ KeyStore keyStore = KeyStore.getInstance("PKCS12");
+ try (var input = Files.newInputStream(store)) {
+ keyStore.load(input, STORE_PASSWORD.toCharArray());
+ }
+ return new TestIdentity(
+ (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()),
+ (X509Certificate) keyStore.getCertificate(alias));
+ }
+
+ private static void runKeytool(String... arguments) throws Exception {
+ Path keytool =
+ Path.of(
+ System.getProperty("java.home"),
+ "bin",
+ System.getProperty("os.name").toLowerCase().contains("windows")
+ ? "keytool.exe"
+ : "keytool");
+ var command = new ArrayList();
+ command.add(keytool.toString());
+ command.addAll(List.of(arguments));
+ Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
+ String output;
+ try (var stream = process.getInputStream()) {
+ output = new String(stream.readAllBytes(), StandardCharsets.UTF_8);
+ }
+ if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) {
+ process.destroyForcibly();
+ throw new IllegalStateException("keytool failed: " + output);
+ }
+ }
+
+ private static X509Certificate readCertificate(Path path) throws Exception {
+ try (var input = Files.newInputStream(path)) {
+ return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input);
+ }
+ }
+
+ private static Path writePem(Path path, String label, byte[] bytes) throws IOException {
+ String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes);
+ return Files.writeString(
+ path,
+ "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n",
+ StandardCharsets.US_ASCII);
+ }
+ }
+}
diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandClientLifecycleTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandClientLifecycleTest.java
new file mode 100644
index 0000000000..08d4370664
--- /dev/null
+++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandClientLifecycleTest.java
@@ -0,0 +1,274 @@
+package net.firedevops.firemud.common.security.sourceintake;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import io.grpc.ManagedChannel;
+import java.lang.reflect.Field;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.BooleanSupplier;
+import net.firedevops.firemud.common.config.ServiceEndpointsProperties;
+import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient;
+import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties;
+import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
+import net.firedevops.firemud.common.grpc.TlsCertificateWatcher;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.api.parallel.ResourceLock;
+import org.junit.jupiter.api.parallel.Resources;
+
+/**
+ * Actual file-watcher lifecycle proof with readable placeholder certificate files and mocked
+ * channels. This does not exercise a TLS handshake or establish workload/creator authority.
+ */
+class SelectedSourceIntakeCommandClientLifecycleTest {
+ private static final String TLS_RELOAD_PROPERTY = "firemud.grpc.tls-reload.enabled";
+
+ @ParameterizedTest
+ @EnumSource(ClientKind.class)
+ @Timeout(15)
+ @ResourceLock(Resources.SYSTEM_PROPERTIES)
+ void closeReleasesClientMonitorBeforeDrainingCertificateCallback(
+ ClientKind kind, @TempDir Path directory)
+ throws Exception {
+ String previousReloadPolicy = System.getProperty(TLS_RELOAD_PROPERTY);
+ System.setProperty(TLS_RELOAD_PROPERTY, "true");
+ CountDownLatch releaseClientMonitor = new CountDownLatch(1);
+ AtomicReference closeFailure = new AtomicReference<>();
+ Thread monitorHolder = null;
+ Thread closeThread = null;
+ AbstractReloadingBlockingGrpcClient> client = null;
+ TlsCertificateWatcher originalWatcher = null;
+ List channels = new CopyOnWriteArrayList<>();
+ try {
+ ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties();
+ endpoints.setWorldManagementService("world.internal:6565");
+ CommonGrpcClientProperties tls = tls(directory);
+ GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class);
+ when(channelFactory.buildChannel(
+ any(String.class), eq(6565), any(CommonGrpcClientProperties.class), eq(true)))
+ .thenAnswer(
+ invocation -> {
+ ManagedChannel channel = mock(ManagedChannel.class);
+ channels.add(channel);
+ return channel;
+ });
+ ClientHandle handle = kind.create(endpoints, tls, channelFactory);
+ client = handle.client();
+ handle.initialize().run();
+ AbstractReloadingBlockingGrpcClient> clientUnderTest = client;
+
+ originalWatcher = watcher(client);
+ Set activeCallbacks = activeCallbacks(originalWatcher);
+ TlsCertificateWatcher closeBoundary = mock(TlsCertificateWatcher.class);
+ TlsCertificateWatcher delegatedWatcher = originalWatcher;
+ doAnswer(
+ invocation -> {
+ assertThat(Thread.holdsLock(clientUnderTest))
+ .as("the client monitor must be released before watcher shutdown")
+ .isFalse();
+ delegatedWatcher.close();
+ return null;
+ })
+ .when(closeBoundary)
+ .close();
+ setWatcher(clientUnderTest, closeBoundary);
+ CountDownLatch clientMonitorHeld = new CountDownLatch(1);
+ monitorHolder =
+ new Thread(
+ () -> {
+ synchronized (clientUnderTest) {
+ clientMonitorHeld.countDown();
+ awaitLatch(releaseClientMonitor);
+ }
+ },
+ "selected-intake-command-client-monitor-holder");
+ monitorHolder.start();
+ assertThat(clientMonitorHeld.await(5, TimeUnit.SECONDS)).isTrue();
+
+ CountDownLatch closeStarted = new CountDownLatch(1);
+ Thread closeWorker =
+ new Thread(
+ () -> {
+ closeStarted.countDown();
+ try {
+ clientUnderTest.close();
+ } catch (Throwable failure) {
+ closeFailure.set(failure);
+ }
+ },
+ "selected-intake-command-client-close");
+ closeThread = closeWorker;
+ closeWorker.start();
+ assertThat(closeStarted.await(5, TimeUnit.SECONDS)).isTrue();
+ awaitCondition(() -> closeWorker.getState() == Thread.State.BLOCKED);
+
+ Files.writeString(Path.of(tls.getCertChain()), "certificate-rotated");
+ Thread callback = awaitBlockedReloadCallback(activeCallbacks);
+ assertThat(callback).isNotNull();
+
+ releaseClientMonitor.countDown();
+ closeWorker.join(TimeUnit.SECONDS.toMillis(4));
+ assertThat(closeWorker.isAlive())
+ .as("close must not hold the client monitor while the watcher drains its callback")
+ .isFalse();
+ assertThat(closeFailure.get()).isNull();
+
+ clientUnderTest.close();
+ assertThatThrownBy(() -> handle.initialize().run())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("closed");
+ assertThat(channels).isNotEmpty();
+ for (ManagedChannel channel : channels) {
+ verify(channel, times(1)).shutdown();
+ }
+ } finally {
+ releaseClientMonitor.countDown();
+ if (monitorHolder != null) {
+ monitorHolder.join(TimeUnit.SECONDS.toMillis(5));
+ }
+ if (closeThread != null) {
+ closeThread.join(TimeUnit.SECONDS.toMillis(7));
+ }
+ try {
+ if (originalWatcher != null) {
+ originalWatcher.close();
+ }
+ } finally {
+ try {
+ if (client != null) {
+ if (originalWatcher != null) {
+ setWatcher(client, originalWatcher);
+ }
+ client.close();
+ }
+ } finally {
+ restoreReloadPolicy(previousReloadPolicy);
+ }
+ }
+ }
+ }
+
+ @FunctionalInterface
+ private interface Initialize {
+ void run() throws Exception;
+ }
+
+ private record ClientHandle(AbstractReloadingBlockingGrpcClient> client, Initialize initialize) {}
+
+ private enum ClientKind {
+ ENTITY,
+ AUTOMATION;
+
+ ClientHandle create(
+ ServiceEndpointsProperties endpoints,
+ CommonGrpcClientProperties tls,
+ GrpcChannelFactory factory) {
+ return switch (this) {
+ case ENTITY -> {
+ var client = new GrpcEntitySelectedSourceIntakeCommandClient(endpoints, tls, factory, "test");
+ yield new ClientHandle(client, client::init);
+ }
+ case AUTOMATION -> {
+ var client = new GrpcAutomationSelectedSourceIntakeCommandClient(endpoints, tls, factory, "test");
+ yield new ClientHandle(client, client::init);
+ }
+ };
+ }
+ }
+
+ private static Thread awaitBlockedReloadCallback(Set activeCallbacks)
+ throws InterruptedException {
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
+ while (System.nanoTime() < deadline) {
+ for (Thread callback : activeCallbacks) {
+ if (callback.getState() == Thread.State.BLOCKED
+ && hasFrame(callback, "AbstractReloadingBlockingGrpcClient", "reloadChannel")) {
+ return callback;
+ }
+ }
+ Thread.sleep(10);
+ }
+ return null;
+ }
+
+ private static boolean hasFrame(Thread thread, String className, String methodName) {
+ for (StackTraceElement frame : thread.getStackTrace()) {
+ if (frame.getClassName().endsWith(className) && frame.getMethodName().equals(methodName)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static void awaitCondition(BooleanSupplier condition) throws InterruptedException {
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
+ while (!condition.getAsBoolean() && System.nanoTime() < deadline) {
+ Thread.sleep(10);
+ }
+ assertThat(condition.getAsBoolean()).isTrue();
+ }
+
+ private static void awaitLatch(CountDownLatch latch) {
+ try {
+ latch.await();
+ } catch (InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ private static TlsCertificateWatcher watcher(AbstractReloadingBlockingGrpcClient> client)
+ throws ReflectiveOperationException {
+ Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher");
+ field.setAccessible(true);
+ return (TlsCertificateWatcher) field.get(client);
+ }
+
+ private static void setWatcher(
+ AbstractReloadingBlockingGrpcClient> client, TlsCertificateWatcher watcher)
+ throws ReflectiveOperationException {
+ Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher");
+ field.setAccessible(true);
+ field.set(client, watcher);
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Set activeCallbacks(TlsCertificateWatcher watcher)
+ throws ReflectiveOperationException {
+ Field field = TlsCertificateWatcher.class.getDeclaredField("activeCallbacks");
+ field.setAccessible(true);
+ return (Set) field.get(watcher);
+ }
+
+ private static CommonGrpcClientProperties tls(Path directory) throws Exception {
+ CommonGrpcClientProperties tls = new CommonGrpcClientProperties();
+ tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString());
+ tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString());
+ tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "CA certificate").toString());
+ return tls;
+ }
+
+ private static void restoreReloadPolicy(String previousValue) {
+ if (previousValue == null) {
+ System.clearProperty(TLS_RELOAD_PROPERTY);
+ } else {
+ System.setProperty(TLS_RELOAD_PROPERTY, previousValue);
+ }
+ }
+}
diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/testsupport/entity/EntitySelectedSourceIntakeTerminalReadFixtures.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/testsupport/entity/EntitySelectedSourceIntakeTerminalReadFixtures.java
new file mode 100644
index 0000000000..c352de61a5
--- /dev/null
+++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/testsupport/entity/EntitySelectedSourceIntakeTerminalReadFixtures.java
@@ -0,0 +1,562 @@
+package net.firedevops.firemud.testsupport.entity;
+
+import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.time.OffsetDateTime;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload;
+import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration;
+import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.gamedesign.AssetSnapshot;
+import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot;
+import net.firedevops.firemud.common.gamedesign.CommandSnapshot;
+import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch;
+import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot;
+import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent;
+import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot;
+import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues;
+import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel;
+
+/**
+ * Synthetic input values for canonical codec and loopback-mTLS tests only.
+ *
+ * The all-zero Entity family rows are deliberately fabricated constructor inputs. They do not
+ * prove an Entity provider census, physical persistence, fresh-empty admission, or retained
+ * production receipt.
+ */
+public final class EntitySelectedSourceIntakeTerminalReadFixtures {
+ private static final UUID TENANT = id("11111111-1111-4111-8111-111111111111");
+ private static final UUID VERSION = id("22222222-2222-4222-8222-222222222222");
+ private static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999");
+ private static final String NAMESPACE = "test";
+
+ private EntitySelectedSourceIntakeTerminalReadFixtures() {}
+
+ public static Fixture create() {
+ OwnerFixture entity = ownerFixture(Owner.ENTITY_MANAGEMENT);
+ OwnerFixture automation = ownerFixture(Owner.AUTOMATION_SCRIPTING);
+ var binding = entity.authorization();
+ var inputs = entity.inputs();
+ String requestDigest =
+ EntityEmptySelectedSourceIntakeReceipt.requestDigest(
+ NAMESPACE, binding, inputs.worldInventoryReadEvidence().request().freezeEvidence());
+ var receipt =
+ EntityEmptySelectedSourceIntakeReceipt.create(
+ inputs,
+ id("88888888-8888-4888-8888-888888888888"),
+ 9001L,
+ 9002L,
+ requestDigest,
+ syntheticZeroFamilyRows(),
+ OffsetDateTime.parse("2026-10-01T00:00:00Z"));
+ return new Fixture(binding, automation.authorization(), inputs, receipt);
+ }
+
+ private static OwnerFixture ownerFixture(Owner owner) {
+ DraftCommitBinding selected = selected();
+ var scope =
+ new SelectedOwnerIntakeSourceReadScope(
+ owner,
+ NAMESPACE,
+ id("55555555-5555-4555-8555-555555555555"),
+ id("66666666-6666-4666-8666-666666666666"),
+ id("77777777-7777-4777-8777-777777777777"),
+ ACTOR,
+ selected);
+ var sourceContent = sourceContent(scope, templateSnapshot(selected));
+ var authorization =
+ new SelectedOwnerIntakeAuthorizationBinding(sourceContent, accountSources());
+ var freezeEvidence = freezeEvidence(selected);
+ var worldRequest =
+ SelectedOwnerWorldInventoryReadEvidence.create(NAMESPACE, authorization, freezeEvidence);
+ var worldInventory =
+ WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence(
+ freezeEvidence, publicInventory(freezeEvidence));
+ var worldEvidence = new SelectedOwnerWorldInventoryReadEvidence(worldRequest, worldInventory);
+ return new OwnerFixture(
+ authorization, new SelectedOwnerEmptySourceInputs(authorization, worldEvidence));
+ }
+
+ private static TemplateConfigSourceSnapshot templateSnapshot(DraftCommitBinding selected) {
+ var payloads = new ArrayList();
+ for (Owner owner :
+ List.of(Owner.AUTOMATION_SCRIPTING, Owner.ENTITY_MANAGEMENT).stream().sorted().toList()) {
+ if (owner == Owner.AUTOMATION_SCRIPTING) {
+ payloads.add(
+ TemplateConfigSourceValues.ownerInventoryPayload(
+ owner,
+ net.firedevops.firemud.common.automation
+ .AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory())));
+ } else {
+ payloads.add(
+ TemplateConfigSourceValues.ownerInventoryPayload(
+ owner, EntityAuthoredSourceInventoryDeclaration.parse(entityInventory())));
+ }
+ }
+ DraftCommitBinding authored = authoredBinding(payloads);
+ var mutations = TemplateConfigSourceValues.mutations(authored);
+ var declarations =
+ mutations.stream()
+ .filter(
+ mutation ->
+ mutation.operation()
+ == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY)
+ .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration)
+ .sorted(java.util.Comparator.comparing(declaration -> declaration.owner().name()))
+ .toList();
+ return new TemplateConfigSourceSnapshot(
+ selected,
+ "1",
+ authored.commitId(),
+ id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"),
+ List.of(),
+ declarations);
+ }
+
+ private static DraftCommitBinding authoredBinding(List payloads) {
+ List revisions = new ArrayList<>();
+ for (int index = 0; index < payloads.size(); index++) {
+ revisions.add(
+ new RevisionPayload(
+ Integer.toString(index),
+ UUID.randomUUID(),
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ payloads.get(index)));
+ }
+ return DraftCommitBinding.create(
+ target(),
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ "base-commit-0",
+ revisions,
+ List.of(
+ new DraftCommitBinding.AffectedUnit(
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ TemplateConfigSourceValues.SCOPE,
+ VERSION.toString(),
+ TemplateConfigSourceValues.SCOPE,
+ TemplateConfigSourceValues.SCOPE_ID,
+ "0")));
+ }
+
+ private static SelectedOwnerIntakeSourceContent sourceContent(
+ SelectedOwnerIntakeSourceReadScope scope, TemplateConfigSourceSnapshot templateSnapshot) {
+ var out = new java.io.ByteArrayOutputStream();
+ frame(out, SelectedOwnerIntakeSourceContent.DOMAIN);
+ frame(out, scope.canonicalBytes());
+ frame(out, scope.digest());
+ for (String family :
+ List.of(
+ "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) {
+ byte[] snapshot =
+ "TEMPLATE_CONFIG".equals(family)
+ ? templateSnapshot.canonicalBytes()
+ : sourceSnapshot(family, scope.selected());
+ frame(out, family);
+ frame(out, snapshot);
+ frame(out, DraftAuthorizationFenceBinding.digest(snapshot));
+ }
+ byte[] bytes = out.toByteArray();
+ return SelectedOwnerIntakeSourceContent.fromStored(
+ bytes, scope, DraftAuthorizationFenceBinding.digest(bytes));
+ }
+
+ private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) {
+ if ("GAMEPLAY_RULE".equals(family)) {
+ return new net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource(
+ net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.canonical(
+ Map.of(
+ "schema",
+ "game-design-gameplay-rule-source-snapshot/v1",
+ "bindingJson",
+ selected.canonicalJson(),
+ "bindingDigest",
+ selected.digest(),
+ "sourceEpoch",
+ "0",
+ "inheritedCommitId",
+ "",
+ "genesisReceiptId",
+ "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
+ "manifestJson",
+ net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.explicitEmpty()
+ .canonicalJson(),
+ "entries",
+ List.of())))
+ .canonicalBytes();
+ }
+ UUID genesis = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa");
+ return switch (family) {
+ case "COMMAND" ->
+ new CommandSnapshot(selected, "0", null, "sha256:" + "a".repeat(64), List.of())
+ .canonicalBytes();
+ case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes();
+ case "ASSET" -> new AssetSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes();
+ case "BRANDING" ->
+ new BrandingSourceSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes();
+ default -> throw new IllegalArgumentException("Unsupported synthetic source family");
+ };
+ }
+
+ private static List accountSources() {
+ return List.of(
+ new SourceEvidence(
+ SourceKind.TENANT,
+ TENANT.toString(),
+ null,
+ "1",
+ null,
+ null,
+ syntheticLargeSourceBytes()),
+ source(SourceKind.ACCOUNT, ACTOR.toString(), "account"),
+ source(SourceKind.MEMBERSHIP, ACTOR + "/" + TENANT, "membership"));
+ }
+
+ private static byte[] syntheticLargeSourceBytes() {
+ byte[] bytes = new byte[4 * 1024 * 1024 + 1024];
+ java.util.Arrays.fill(bytes, (byte) 'S');
+ return bytes;
+ }
+
+ private static SourceEvidence source(SourceKind kind, String scope, String marker) {
+ return new SourceEvidence(
+ kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8));
+ }
+
+ private static DraftCommitBinding selected() {
+ return DraftCommitBinding.create(
+ target(),
+ id("33333333-3333-4333-8333-333333333333"),
+ id("44444444-4444-4444-8444-444444444444"),
+ "base-commit-0",
+ List.of(
+ new RevisionPayload(
+ "0", id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), Owner.WORLD_MANAGEMENT, "{}")),
+ List.of(
+ new DraftCommitBinding.AffectedUnit(
+ Owner.WORLD_MANAGEMENT, "REGION", "region-1", "AGGREGATE", "region-1", "0")));
+ }
+
+ private static DraftCommitBinding.TargetProof target() {
+ return new DraftCommitBinding.TargetProof(
+ TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW");
+ }
+
+ private static WorldSelectedDraftPublicationFreezeEvidence freezeEvidence(
+ DraftCommitBinding selected) {
+ var selection =
+ AuthoredDraftPublishSelectionBinding.capture(
+ new PublishIntent(
+ TENANT,
+ VERSION,
+ "publication-request",
+ "9",
+ "synthetic selected-owner intake fixture",
+ selected.requestId(),
+ selected.commitId(),
+ selected.digest()),
+ selected.target(),
+ selected,
+ new VisibilityFence(
+ selected.target(),
+ selected.requestId(),
+ selected.commitId(),
+ selected.digest(),
+ "[]",
+ OffsetDateTime.parse("2026-10-01T00:00:00Z")));
+ var account =
+ new AccountPublicationAuthorizationBinding(
+ id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"),
+ id("ffffffff-ffff-4fff-8fff-ffffffffffff"),
+ new AccountPublicationAuthorizationBinding.PreallocationInput(ACTOR, selection),
+ List.of(source(SourceKind.ACCOUNT, ACTOR.toString(), "synthetic-publication")));
+ var request =
+ WorldSelectedDraftPublicationFreezeEvidence.Request.create(
+ NAMESPACE,
+ TENANT,
+ VERSION,
+ selection.intent().publishRequestId(),
+ 9,
+ selection.digest().substring("sha256:".length()),
+ account);
+ var acknowledgement =
+ new Acknowledgement(
+ request,
+ id("12121212-1212-4212-8212-121212121212"),
+ 9,
+ id("13131313-1313-4313-8313-131313131313"),
+ OwnerFreezePhase.FROZEN,
+ selected.commitId().toString(),
+ "a".repeat(64),
+ 4);
+ return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse(
+ request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement));
+ }
+
+ private static PublicEvidence publicInventory(
+ WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) {
+ var request = freezeEvidence.request();
+ var acknowledgement = freezeEvidence.acknowledgement();
+ var account = request.accountBinding();
+ var selection = account.input().selection();
+ var selected = selection.selectedCommit();
+ var sourceModel =
+ new SourceModel(
+ WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL,
+ WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION,
+ "sha256:" + "4".repeat(64),
+ "sha256:" + "5".repeat(64),
+ List.of(
+ new FamilyCount("REGION", 1),
+ new FamilyCount("ZONE", 1),
+ new FamilyCount("ROOM", 1),
+ new FamilyCount("ROOM_EXIT", 0),
+ new FamilyCount("GENERATION_RULE", 0),
+ new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)),
+ List.of(new RegionGeneratorInput(id("15151515-1515-4515-8515-151515151515"), "", "")),
+ List.of("id", "name", "scopeType", "scopeId", "value"),
+ List.of(
+ "id",
+ "shardId",
+ "name",
+ "weather",
+ "generationSeed",
+ "generatorType",
+ "generatorParams",
+ "spacingMultiplier"),
+ List.of("id", "regionId", "name"),
+ List.of(
+ "id",
+ "zoneId",
+ "name",
+ "description",
+ "nameLocalizedVariantsJson",
+ "descriptionLocalizedVariantsJson"),
+ List.of("id", "fromRoomId", "toRoomId", "direction", "cost"),
+ List.of(
+ "id",
+ "roomId",
+ "entityTemplateType",
+ "entityReference.kind",
+ "entityReference.tenantId",
+ "entityReference.versionId",
+ "entityReference.templateId",
+ "spawnCount",
+ "respawnDelaySeconds"),
+ List.of(),
+ 0,
+ 0,
+ selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream()
+ .map(
+ unit ->
+ new AppliedEpoch(
+ unit.aggregateType(),
+ unit.aggregateId(),
+ unit.scopeType(),
+ unit.scopeId(),
+ unit.expectedEpoch(),
+ new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString()))
+ .toList(),
+ emptyInboundClosure());
+ return new PublicEvidence(
+ WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA,
+ WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION,
+ "COMPLETE",
+ new PublicOwnerScope(
+ request.targetNamespace(),
+ TENANT,
+ VERSION,
+ id("14141414-1414-4414-8414-141414141414"),
+ acknowledgement.intakeRequestId(),
+ id("13131313-1313-4313-8313-131313131313"),
+ "sha256:" + "1".repeat(64),
+ id("17171717-1717-4717-8717-171717171717"),
+ "sha256:" + "2".repeat(64),
+ "sha256:" + "3".repeat(64)),
+ new SelectedApplication(
+ id("16161616-1616-4616-8616-161616161616"),
+ selected.requestId(),
+ selected.commitId().toString(),
+ selected.digest(),
+ "sha256:" + "6".repeat(64)),
+ new PublicAccountOrder(
+ account.operationId(),
+ account.fenceId(),
+ account.input().actorAccountId(),
+ selection.intent().publishRequestId(),
+ selection.digest(),
+ selected.commitId().toString(),
+ DraftAuthorizationFenceBinding.digest(account.canonicalBytes())),
+ new Freeze(
+ acknowledgement.publicationFence(),
+ request.publicationRequestId(),
+ request.requestDigest(),
+ Long.toString(acknowledgement.versionStateEpoch()),
+ PublicationDigestRequestBinding.full(
+ request.canonicalTenantId().toString(),
+ Long.toString(selection.target().gameDesignVersionRowId()),
+ request.publicationRequestId())
+ .derivedWorkflowIdentity()),
+ new Checkpoint(acknowledgement.appliedCommitId(), acknowledgement.contentDigest(), 4),
+ sourceModel,
+ List.of(
+ new ArtifactDecision(
+ "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"),
+ new ArtifactDecision(
+ "PATH_GRAPH",
+ "NOT_REQUIRED",
+ "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH")));
+ }
+
+ private static InboundSourceClosureDeclaration emptyInboundClosure() {
+ return new InboundSourceClosureDeclaration(
+ 1,
+ List.of(
+ new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0),
+ new InboundSourceFamilyCount(
+ "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0),
+ new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0),
+ new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0),
+ new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0),
+ new InboundSourceFamilyCount(
+ "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0),
+ new InboundSourceFamilyCount(
+ "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0)));
+ }
+
+ private static List
+ syntheticZeroFamilyRows() {
+ List families =
+ List.of(
+ "ACTOR_BODY_LAYOUT_ASSIGNMENTS",
+ "ARCHETYPE_ASSIGNMENTS",
+ "ARCHETYPE_CONSTRAINTS",
+ "ARCHETYPE_ROOTS",
+ "BALANCE_CURVE_ATTACHMENTS",
+ "BALANCE_CURVE_ROOTS",
+ "BODY_LAYOUT_MEMBERSHIPS",
+ "BODY_LAYOUT_ROOTS",
+ "CRAFTING_INGREDIENT_BINDINGS",
+ "CRAFTING_RECIPE_RESULT_BINDINGS",
+ "CRAFTING_RECIPE_ROOTS",
+ "EQUIPMENT_ATTACHMENT_RULES",
+ "EQUIPMENT_CAPABILITIES",
+ "EQUIPMENT_COMPATIBILITY_RULES",
+ "EQUIPMENT_OCCUPANCY_RULES",
+ "EQUIPMENT_SLOT_GROUPS",
+ "EQUIPMENT_SLOT_ROOTS",
+ "INBOUND_LOOT_BINDINGS",
+ "ITEM_TEMPLATE_ROOTS",
+ "LOOT_ITEM_MAPPINGS",
+ "LOOT_TABLE_ROOTS",
+ "NPC_TEMPLATE_ROOTS",
+ "OTHER_ACTOR_TEMPLATE_ROOTS");
+ return families.stream()
+ .map(
+ family ->
+ new EntityEmptySelectedSourceIntakeReceipt.FamilyCensus(
+ family,
+ EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY,
+ v1CensusFamily(family)
+ ? EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS
+ : EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind
+ .EMPTY_ONLY_OWNER_PROVIDER,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0))
+ .toList();
+ }
+
+ private static boolean v1CensusFamily(String family) {
+ return List.of(
+ "ITEM_TEMPLATE_ROOTS",
+ "NPC_TEMPLATE_ROOTS",
+ "CRAFTING_RECIPE_ROOTS",
+ "CRAFTING_RECIPE_RESULT_BINDINGS",
+ "CRAFTING_INGREDIENT_BINDINGS",
+ "EQUIPMENT_SLOT_ROOTS",
+ "EQUIPMENT_SLOT_GROUPS",
+ "BODY_LAYOUT_ROOTS",
+ "BODY_LAYOUT_MEMBERSHIPS")
+ .contains(family);
+ }
+
+ private static String automationInventory() {
+ return "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{"
+ + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[],\"SCRIPT_PATCH_SOURCES\":[]}}";
+ }
+
+ private static String entityInventory() {
+ return "{\"schema\":\"entity-authored-source-inventory/v1\","
+ + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{"
+ + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[],"
+ + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[],"
+ + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[],"
+ + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[],"
+ + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[],"
+ + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[],"
+ + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[],"
+ + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[],"
+ + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[],"
+ + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[],"
+ + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[],"
+ + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}";
+ }
+
+ private static void frame(java.io.ByteArrayOutputStream out, String value) {
+ DraftAuthorizationFenceBinding.frame(out, value);
+ }
+
+ private static void frame(java.io.ByteArrayOutputStream out, byte[] value) {
+ DraftAuthorizationFenceBinding.frame(out, value);
+ }
+
+ private static UUID id(String value) {
+ return UUID.fromString(value);
+ }
+
+ public record Fixture(
+ SelectedOwnerIntakeAuthorizationBinding authorization,
+ SelectedOwnerIntakeAuthorizationBinding wrongOwnerAuthorization,
+ SelectedOwnerEmptySourceInputs inputs,
+ EntityEmptySelectedSourceIntakeReceipt receipt) {}
+
+ private record OwnerFixture(
+ SelectedOwnerIntakeAuthorizationBinding authorization,
+ SelectedOwnerEmptySourceInputs inputs) {}
+}
diff --git a/services/entity-management-service/build.gradle.kts b/services/entity-management-service/build.gradle.kts
index f83aff8cf7..548b296313 100644
--- a/services/entity-management-service/build.gradle.kts
+++ b/services/entity-management-service/build.gradle.kts
@@ -15,3 +15,17 @@ dependencies {
implementation(project(":common-security"))
implementation(libs.spring.boot.starter.cache)
}
+
+// Export only owner classes for composed proofs; application and Flyway resources stay local.
+val entityClassesProofJar by tasks.registering(Jar::class) {
+ archiveClassifier.set("classes-proof")
+ dependsOn(tasks.named("classes"))
+ from(sourceSets.main.get().output.classesDirs)
+}
+
+val entityClassesProof by configurations.creating {
+ isCanBeConsumed = true
+ isCanBeResolved = false
+ extendsFrom(configurations.implementation.get())
+ outgoing.artifact(entityClassesProofJar)
+}
diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java
new file mode 100644
index 0000000000..bd1bd518e7
--- /dev/null
+++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java
@@ -0,0 +1,917 @@
+package net.firedevops.firemud.entitymanagement.sourceintake;
+
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.jooq.impl.DSL;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Unregistered Entity persistence boundary for immutable, freshly founded empty catalogues. */
+public final class EntityEmptySelectedSourceIntakeRepository {
+ private static final String KEY_RESERVATION = "entity_empty_source_numeric_key_reservation";
+ private static final String ASSOCIATION = "entity_empty_selected_source_association";
+ private static final String FAMILY_STATE = "entity_empty_selected_source_family_state";
+ private static final String RECEIPT = "entity_empty_selected_source_receipt";
+ private static final Map EMPTY_ONLY_PROVIDER_TABLES =
+ Map.ofEntries(
+ Map.entry(
+ "ACTOR_BODY_LAYOUT_ASSIGNMENTS", "entity_empty_source_actor_body_layout_assignments"),
+ Map.entry("ARCHETYPE_ASSIGNMENTS", "entity_empty_source_archetype_assignments"),
+ Map.entry("ARCHETYPE_CONSTRAINTS", "entity_empty_source_archetype_constraints"),
+ Map.entry("ARCHETYPE_ROOTS", "entity_empty_source_archetype_roots"),
+ Map.entry("BALANCE_CURVE_ATTACHMENTS", "entity_empty_source_balance_curve_attachments"),
+ Map.entry("BALANCE_CURVE_ROOTS", "entity_empty_source_balance_curve_roots"),
+ Map.entry("EQUIPMENT_ATTACHMENT_RULES", "entity_empty_source_equipment_attachment_rules"),
+ Map.entry("EQUIPMENT_CAPABILITIES", "entity_empty_source_equipment_capabilities"),
+ Map.entry(
+ "EQUIPMENT_COMPATIBILITY_RULES", "entity_empty_source_equipment_compatibility_rules"),
+ Map.entry("EQUIPMENT_OCCUPANCY_RULES", "entity_empty_source_equipment_occupancy_rules"),
+ Map.entry("INBOUND_LOOT_BINDINGS", "entity_empty_source_inbound_loot_bindings"),
+ Map.entry("LOOT_ITEM_MAPPINGS", "entity_empty_source_loot_item_mappings"),
+ Map.entry("LOOT_TABLE_ROOTS", "entity_empty_source_loot_table_roots"),
+ Map.entry(
+ "OTHER_ACTOR_TEMPLATE_ROOTS", "entity_empty_source_other_actor_template_roots"));
+ private static final List EMPTY_ONLY_PROVIDER_LOCKS =
+ List.of(
+ "entity_empty_source_other_actor_template_roots",
+ "entity_empty_source_equipment_capabilities",
+ "entity_empty_source_equipment_attachment_rules",
+ "entity_empty_source_equipment_compatibility_rules",
+ "entity_empty_source_equipment_occupancy_rules",
+ "entity_empty_source_actor_body_layout_assignments",
+ "entity_empty_source_loot_table_roots",
+ "entity_empty_source_loot_item_mappings",
+ "entity_empty_source_inbound_loot_bindings",
+ "entity_empty_source_balance_curve_roots",
+ "entity_empty_source_balance_curve_attachments",
+ "entity_empty_source_archetype_roots",
+ "entity_empty_source_archetype_constraints",
+ "entity_empty_source_archetype_assignments");
+
+ private static final String READ_RECEIPT =
+ "SELECT a.target_namespace, a.genesis_id, a.operation_id, a.fence_id, "
+ + "a.intake_request_id, a.canonical_tenant_id, a.canonical_version_id, "
+ + "a.local_tenant_key, a.local_version_key, a.request_digest, a.schema_digest, "
+ + "a.authorization_binding_digest, a.selected_source_digest, a.world_read_request_id, "
+ + "a.world_read_request_digest, a.world_closure_digest, a.receipt_digest, a.associated_at, "
+ + "r.request_digest, r.schema_digest, r.receipt_digest, r.receipt_bytes, r.retained_at "
+ + "FROM "
+ + ASSOCIATION
+ + " a LEFT JOIN "
+ + RECEIPT
+ + " r ON r.target_namespace = a.target_namespace "
+ + "AND r.intake_request_id = a.intake_request_id "
+ + "WHERE a.target_namespace = ? AND a.intake_request_id = ?";
+
+ private static final String SOURCE_TABLE_LOCKS =
+ "LOCK TABLE actor_active_conditions, actor_resource_states, body_layout_slot_definitions, "
+ + "character_equipment, character_friend, characters, container_instances, "
+ + "crafting_ingredients, crafting_recipes, entity_mutation_effects, "
+ + "equipment_slot_definitions, inventory, item_instances, item_stacks, "
+ + "item_transfer_audits, item_visible_ref_counters, items, npcs, room_ground_inventory IN SHARE MODE";
+
+ private final DSLContext dsl;
+
+ public EntityEmptySelectedSourceIntakeRepository(DSLContext dsl) {
+ this.dsl = Objects.requireNonNull(dsl, "dsl");
+ }
+
+ /**
+ * Reads only a committed exact receipt; absence is not interpreted as abort or source absence.
+ */
+ public Optional read(
+ String targetNamespace, UUID intakeRequestId) {
+ requireNoAmbientOwnerSql("Entity source receipt read");
+ requireReadKey(targetNamespace, intakeRequestId);
+ return readValidated(dsl, targetNamespace, intakeRequestId);
+ }
+
+ /**
+ * Resolves the one immutable selected-empty receipt for a canonical tenant and Game Design
+ * Version row. Every association in the tenant prefix is fully read back before its retained
+ * original TargetProof is considered; owner-local numeric keys are not publication identity.
+ */
+ public EntityEmptySelectedSourceIntakeReceipt readPublicationScope(
+ String targetNamespace, UUID canonicalTenantId, long gameDesignVersionRowId) {
+ requireNoAmbientOwnerSql("Entity publication receipt read");
+ requirePublicationScopeKey(targetNamespace, canonicalTenantId, gameDesignVersionRowId);
+
+ return dsl.transactionResult(
+ configuration -> {
+ DSLContext tx = DSL.using(configuration);
+ tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY");
+ var associations =
+ tx.fetch(
+ "SELECT canonical_version_id, intake_request_id FROM "
+ + ASSOCIATION
+ + " WHERE target_namespace = ? AND canonical_tenant_id = ? "
+ + "ORDER BY canonical_version_id",
+ targetNamespace,
+ canonicalTenantId);
+ if (associations.isEmpty()) {
+ throw new IllegalStateException(
+ "Entity selected-empty publication receipt is unavailable");
+ }
+
+ var matches = new ArrayList();
+ for (Record association : associations) {
+ UUID associatedCanonicalVersionId = association.get(0, UUID.class);
+ UUID intakeRequestId = association.get(1, UUID.class);
+ if (associatedCanonicalVersionId == null || intakeRequestId == null) {
+ throw new IllegalStateException("Entity publication association identity is corrupt");
+ }
+ EntityEmptySelectedSourceIntakeReceipt receipt =
+ readValidated(tx, targetNamespace, intakeRequestId)
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Entity publication association has no committed receipt"));
+ var target = receipt.authorizationBinding().selected().target();
+ if (!canonicalTenantId.equals(receipt.canonicalTenantId())
+ || !associatedCanonicalVersionId.equals(receipt.canonicalVersionId())
+ || !canonicalTenantId.equals(target.canonicalTenantId())
+ || !associatedCanonicalVersionId.equals(target.canonicalVersionId())) {
+ throw new IllegalStateException(
+ "Entity publication association differs from the retained selected target");
+ }
+ if (target.gameDesignVersionRowId() == gameDesignVersionRowId) {
+ matches.add(receipt);
+ }
+ }
+ if (matches.size() != 1) {
+ throw new IllegalStateException(
+ "Entity selected-empty publication scope is missing or ambiguous");
+ }
+ return matches.get(0);
+ });
+ }
+
+ /**
+ * Commits a fresh empty catalogue and reads it back independently. A provider missing from the
+ * current Entity schema blocks founding, even if its creator declaration says the family is
+ * empty.
+ */
+ public EntityEmptySelectedSourceIntakeReceipt retainFresh(
+ SelectedOwnerEmptySourceInputs inputs, String requestDigest) {
+ Objects.requireNonNull(inputs, "validated selected empty-source inputs are required");
+ SelectedOwnerIntakeAuthorizationBinding binding = inputs.authorizationBinding();
+ String expectedDigest =
+ EntityEmptySelectedSourceIntakeReceipt.requestDigest(
+ binding.targetNamespace(),
+ binding,
+ inputs.worldInventoryReadEvidence().request().freezeEvidence());
+ if (!expectedDigest.equals(requestDigest)) {
+ throw new IllegalArgumentException("Entity source intake request digest differs");
+ }
+ requireExactEntityBinding(binding);
+ requireNoAmbientOwnerSql("Entity source catalogue transaction");
+
+ UUID genesisId = UUID.randomUUID();
+ EntityEmptySelectedSourceIntakeReceipt committed =
+ dsl.transactionResult(
+ configuration -> {
+ DSLContext tx = DSL.using(configuration);
+ tx.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
+ lockOwnerRecords(tx);
+ lockSourceAndInboundTables(tx);
+
+ Optional previous =
+ readValidated(tx, binding.targetNamespace(), binding.intakeRequestId());
+ if (previous.isPresent()) {
+ EntityEmptySelectedSourceIntakeReceipt receipt = previous.orElseThrow();
+ receipt.requireSameInputs(inputs);
+ return receipt;
+ }
+ requireNoPriorScopeOrOperation(tx, binding);
+
+ long maximumOccupiedKey = maximumOccupiedSourceKey(tx);
+ long localTenantKey = Math.addExact(maximumOccupiedKey, 1L);
+ long localVersionKey = Math.addExact(maximumOccupiedKey, 2L);
+ List familyStates =
+ censusEveryDeclaredFamily(tx, inputs, localTenantKey, localVersionKey);
+
+ reserveCanonicalKey(tx, "TENANT", localTenantKey);
+ reserveCanonicalKey(tx, "VERSION", localVersionKey);
+ OffsetDateTime retainedAt =
+ requiredScalar(tx, "SELECT CURRENT_TIMESTAMP", OffsetDateTime.class)
+ .withOffsetSameInstant(ZoneOffset.UTC);
+ EntityEmptySelectedSourceIntakeReceipt receipt =
+ EntityEmptySelectedSourceIntakeReceipt.create(
+ inputs,
+ genesisId,
+ localTenantKey,
+ localVersionKey,
+ requestDigest,
+ familyStates,
+ retainedAt);
+ insertAssociation(tx, receipt);
+ insertEmptyOnlyProviderStates(tx, receipt);
+ insertFamilyStates(tx, receipt);
+ insertReceipt(tx, receipt);
+ return receipt;
+ });
+
+ EntityEmptySelectedSourceIntakeReceipt readBack =
+ read(committed.targetNamespace(), committed.intakeRequestId())
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Committed Entity source catalogue receipt is unavailable"));
+ if (!Arrays.equals(committed.canonicalBytes(), readBack.canonicalBytes())
+ || !committed.receiptDigest().equals(readBack.receiptDigest())
+ || !committed.requestDigest().equals(readBack.requestDigest())
+ || !committed.genesisId().equals(readBack.genesisId())) {
+ throw new IllegalStateException("Committed Entity source receipt readback differs");
+ }
+ return readBack;
+ }
+
+ private static void lockOwnerRecords(DSLContext tx) {
+ tx.execute(
+ "LOCK TABLE "
+ + KEY_RESERVATION
+ + ", "
+ + ASSOCIATION
+ + ", "
+ + FAMILY_STATE
+ + ", "
+ + RECEIPT
+ + ", "
+ + String.join(", ", EMPTY_ONLY_PROVIDER_LOCKS)
+ + " IN SHARE ROW EXCLUSIVE MODE");
+ }
+
+ private static void lockSourceAndInboundTables(DSLContext tx) {
+ // Locks cover every source row, Entity item FK, actor/holder path, and logical slot/layout
+ // reference read by the conservative census. SHARE is held until the catalogue commit.
+ tx.execute(SOURCE_TABLE_LOCKS);
+ }
+
+ private static void requireNoPriorScopeOrOperation(
+ DSLContext tx, SelectedOwnerIntakeAuthorizationBinding binding) {
+ Record prior =
+ tx.fetchOne(
+ "SELECT intake_request_id FROM "
+ + ASSOCIATION
+ + " WHERE target_namespace = ? AND ("
+ + "(canonical_tenant_id = ? AND canonical_version_id = ?) OR operation_id = ?) ",
+ binding.targetNamespace(),
+ binding.tenantId(),
+ binding.versionId(),
+ binding.operationId());
+ if (prior != null) {
+ throw new IntakeConflictException(
+ "Entity selected scope or owner operation is already associated");
+ }
+ }
+
+ private static List
+ censusEveryDeclaredFamily(
+ DSLContext tx,
+ SelectedOwnerEmptySourceInputs inputs,
+ long localTenantKey,
+ long localVersionKey) {
+ List declaredFamilies =
+ declaredFamilies(
+ inputs.ownerSourceInventoryDeclaration().entityInventory().canonicalJson());
+ var result = new ArrayList(23);
+ for (String family : declaredFamilies) {
+ requireReadableProvider(family);
+ Census counts =
+ EMPTY_ONLY_PROVIDER_TABLES.containsKey(family)
+ ? Census.emptyOnlyProviderState()
+ : switch (family) {
+ case "ITEM_TEMPLATE_ROOTS" -> censusItems(tx, localTenantKey, localVersionKey);
+ case "NPC_TEMPLATE_ROOTS" -> censusNpcs(tx, localTenantKey, localVersionKey);
+ case "CRAFTING_RECIPE_ROOTS" ->
+ censusRecipes(tx, localTenantKey, localVersionKey, false);
+ case "CRAFTING_RECIPE_RESULT_BINDINGS" ->
+ censusRecipes(tx, localTenantKey, localVersionKey, true);
+ case "CRAFTING_INGREDIENT_BINDINGS" ->
+ censusIngredients(tx, localTenantKey, localVersionKey);
+ case "EQUIPMENT_SLOT_ROOTS" ->
+ censusEquipmentSlots(tx, localTenantKey, localVersionKey, false);
+ case "EQUIPMENT_SLOT_GROUPS" ->
+ censusEquipmentSlots(tx, localTenantKey, localVersionKey, true);
+ case "BODY_LAYOUT_ROOTS" ->
+ censusBodyLayouts(tx, localTenantKey, localVersionKey, true);
+ case "BODY_LAYOUT_MEMBERSHIPS" ->
+ censusBodyLayouts(tx, localTenantKey, localVersionKey, false);
+ default ->
+ throw new IllegalStateException(
+ "No readable persisted Entity source provider for family " + family);
+ };
+ if (!counts.isZero()) {
+ throw new IntakeConflictException(
+ "Entity source family or inbound reference census is not freshly empty: " + family);
+ }
+ result.add(
+ new EntityEmptySelectedSourceIntakeReceipt.FamilyCensus(
+ family,
+ EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY,
+ EMPTY_ONLY_PROVIDER_TABLES.containsKey(family)
+ ? EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind
+ .EMPTY_ONLY_OWNER_PROVIDER
+ : EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS,
+ counts.rows(),
+ counts.unqualifiedRows(),
+ counts.retainedRows(),
+ counts.selectedScopeRows(),
+ counts.references()));
+ }
+ if (result.size() != 23) {
+ throw new IllegalStateException("Entity source census did not read all 23 declared families");
+ }
+ return List.copyOf(result);
+ }
+
+ static void requireReadableProvider(String family) {
+ if (!EMPTY_ONLY_PROVIDER_TABLES.containsKey(family)
+ && !List.of(
+ "ITEM_TEMPLATE_ROOTS",
+ "NPC_TEMPLATE_ROOTS",
+ "CRAFTING_RECIPE_ROOTS",
+ "CRAFTING_RECIPE_RESULT_BINDINGS",
+ "CRAFTING_INGREDIENT_BINDINGS",
+ "EQUIPMENT_SLOT_ROOTS",
+ "EQUIPMENT_SLOT_GROUPS",
+ "BODY_LAYOUT_ROOTS",
+ "BODY_LAYOUT_MEMBERSHIPS")
+ .contains(family)) {
+ throw new IllegalStateException(
+ "No readable persisted Entity source provider for family " + family);
+ }
+ }
+
+ private static Census censusItems(DSLContext tx, long tenantKey, long versionKey) {
+ return new Census(
+ count(tx, "SELECT COUNT(*) FROM items"),
+ count(
+ tx,
+ "SELECT COUNT(*) FROM items i WHERE NOT EXISTS (SELECT 1 FROM "
+ + ASSOCIATION
+ + " a WHERE a.local_tenant_key = i.tenant_id AND a.local_version_key = i.version_id)"),
+ count(
+ tx,
+ "SELECT COUNT(*) FROM items i WHERE EXISTS (SELECT 1 FROM "
+ + ASSOCIATION
+ + " a WHERE a.local_tenant_key = i.tenant_id AND a.local_version_key = i.version_id)"),
+ count(
+ tx,
+ "SELECT COUNT(*) FROM items WHERE tenant_id = ? OR version_id = ?",
+ tenantKey,
+ versionKey),
+ countItemReferenceEdges(tx));
+ }
+
+ private static Census censusNpcs(DSLContext tx, long tenantKey, long versionKey) {
+ return new Census(
+ count(tx, "SELECT COUNT(*) FROM npcs"),
+ count(
+ tx,
+ "SELECT COUNT(*) FROM npcs n WHERE NOT EXISTS (SELECT 1 FROM "
+ + ASSOCIATION
+ + " a WHERE a.local_tenant_key = n.tenant_id AND a.local_version_key = n.version_id)"),
+ count(
+ tx,
+ "SELECT COUNT(*) FROM npcs n WHERE EXISTS (SELECT 1 FROM "
+ + ASSOCIATION
+ + " a WHERE a.local_tenant_key = n.tenant_id AND a.local_version_key = n.version_id)"),
+ count(
+ tx,
+ "SELECT COUNT(*) FROM npcs WHERE tenant_id = ? OR version_id = ?",
+ tenantKey,
+ versionKey),
+ 0L);
+ }
+
+ private static Census censusRecipes(
+ DSLContext tx, long tenantKey, long versionKey, boolean resultBinding) {
+ String nonnullResult = resultBinding ? " WHERE result_item_id IS NOT NULL" : "";
+ String aliasFilter = resultBinding ? " AND r.result_item_id IS NOT NULL" : "";
+ return new Census(
+ count(tx, "SELECT COUNT(*) FROM crafting_recipes" + nonnullResult),
+ count(
+ tx,
+ "SELECT COUNT(*) FROM crafting_recipes r WHERE NOT EXISTS (SELECT 1 FROM "
+ + ASSOCIATION
+ + " a WHERE a.local_tenant_key = r.tenant_id AND a.local_version_key = r.version_id)"
+ + aliasFilter),
+ count(
+ tx,
+ "SELECT COUNT(*) FROM crafting_recipes r WHERE EXISTS (SELECT 1 FROM "
+ + ASSOCIATION
+ + " a WHERE a.local_tenant_key = r.tenant_id AND a.local_version_key = r.version_id)"
+ + aliasFilter),
+ count(
+ tx,
+ "SELECT COUNT(*) FROM crafting_recipes r WHERE (r.tenant_id = ? OR r.version_id = ?)"
+ + aliasFilter,
+ tenantKey,
+ versionKey),
+ resultBinding
+ ? count(tx, "SELECT COUNT(*) FROM crafting_recipes WHERE result_item_id IS NOT NULL")
+ : count(tx, "SELECT COUNT(*) FROM crafting_ingredients"));
+ }
+
+ private static Census censusIngredients(DSLContext tx, long tenantKey, long versionKey) {
+ String recipeAssociation =
+ "SELECT COUNT(*) FROM crafting_ingredients i JOIN crafting_recipes r ON r.id = i.recipe_id ";
+ return new Census(
+ count(tx, "SELECT COUNT(*) FROM crafting_ingredients"),
+ count(
+ tx,
+ recipeAssociation
+ + "WHERE NOT EXISTS (SELECT 1 FROM "
+ + ASSOCIATION
+ + " a WHERE a.local_tenant_key = r.tenant_id AND a.local_version_key = r.version_id)"),
+ count(
+ tx,
+ recipeAssociation
+ + "WHERE EXISTS (SELECT 1 FROM "
+ + ASSOCIATION
+ + " a WHERE a.local_tenant_key = r.tenant_id AND a.local_version_key = r.version_id)"),
+ count(
+ tx,
+ recipeAssociation + "WHERE r.tenant_id = ? OR r.version_id = ?",
+ tenantKey,
+ versionKey),
+ count(tx, "SELECT COUNT(*) FROM crafting_ingredients"));
+ }
+
+ private static Census censusEquipmentSlots(
+ DSLContext tx, long tenantKey, long versionKey, boolean groups) {
+ String identity =
+ groups
+ ? "SELECT DISTINCT tenant_id, version_id, slot_group_key AS source_key "
+ + "FROM equipment_slot_definitions WHERE slot_group_key IS NOT NULL"
+ : "SELECT tenant_id, version_id, slot_key AS source_key FROM equipment_slot_definitions";
+ String itemReferences =
+ "SELECT COUNT(*) FROM ("
+ + "SELECT equipment_slot AS source_key FROM items WHERE equipment_slot IS NOT NULL "
+ + "UNION ALL SELECT slot FROM character_equipment WHERE slot IS NOT NULL "
+ + "UNION ALL SELECT equipment_slot FROM item_instances WHERE equipment_slot IS NOT NULL "
+ + "UNION ALL SELECT equipment_slot FROM item_stacks WHERE equipment_slot IS NOT NULL "
+ + "UNION ALL SELECT equipment_slot FROM container_instances WHERE equipment_slot IS NOT NULL"
+ + ") slot_refs";
+ String groupReferences =
+ "SELECT COUNT(*) FROM items WHERE equipment_slot_group_key IS NOT NULL";
+ String total = "SELECT COUNT(*) FROM (" + identity + ") entity_family";
+ String unqualified =
+ "SELECT COUNT(*) FROM (SELECT f.* FROM ("
+ + identity
+ + ") f WHERE NOT EXISTS (SELECT 1 FROM "
+ + ASSOCIATION
+ + " a WHERE a.local_tenant_key = f.tenant_id AND a.local_version_key = f.version_id)) q";
+ String retained =
+ "SELECT COUNT(*) FROM (SELECT f.* FROM ("
+ + identity
+ + ") f WHERE EXISTS (SELECT 1 FROM "
+ + ASSOCIATION
+ + " a WHERE a.local_tenant_key = f.tenant_id AND a.local_version_key = f.version_id)) q";
+ String selected =
+ "SELECT COUNT(*) FROM (" + identity + ") f WHERE f.tenant_id = ? OR f.version_id = ?";
+ return new Census(
+ count(tx, total),
+ count(tx, unqualified),
+ count(tx, retained),
+ count(tx, selected, tenantKey, versionKey),
+ groups ? count(tx, groupReferences) : count(tx, itemReferences));
+ }
+
+ private static Census censusBodyLayouts(
+ DSLContext tx, long tenantKey, long versionKey, boolean roots) {
+ String identity =
+ roots
+ ? "SELECT DISTINCT tenant_id, version_id, body_layout_key AS source_key "
+ + "FROM body_layout_slot_definitions"
+ : "SELECT tenant_id, version_id, body_layout_key, slot_key "
+ + "FROM body_layout_slot_definitions";
+ String total = "SELECT COUNT(*) FROM (" + identity + ") entity_family";
+ String unqualified =
+ "SELECT COUNT(*) FROM (SELECT f.* FROM ("
+ + identity
+ + ") f WHERE NOT EXISTS (SELECT 1 FROM "
+ + ASSOCIATION
+ + " a WHERE a.local_tenant_key = f.tenant_id AND a.local_version_key = f.version_id)) q";
+ String retained =
+ "SELECT COUNT(*) FROM (SELECT f.* FROM ("
+ + identity
+ + ") f WHERE EXISTS (SELECT 1 FROM "
+ + ASSOCIATION
+ + " a WHERE a.local_tenant_key = f.tenant_id AND a.local_version_key = f.version_id)) q";
+ String selected =
+ "SELECT COUNT(*) FROM (" + identity + ") f WHERE f.tenant_id = ? OR f.version_id = ?";
+ return new Census(
+ count(tx, total),
+ count(tx, unqualified),
+ count(tx, retained),
+ count(tx, selected, tenantKey, versionKey),
+ roots
+ ? count(tx, "SELECT COUNT(*) FROM characters WHERE body_layout_key IS NOT NULL")
+ : count(
+ tx,
+ "SELECT COUNT(*) FROM characters c JOIN character_equipment e "
+ + "ON e.character_id = c.id WHERE c.body_layout_key IS NOT NULL"));
+ }
+
+ private static long countItemReferenceEdges(DSLContext tx) {
+ return count(
+ tx,
+ "SELECT COUNT(*) FROM ("
+ + "SELECT item_id FROM inventory "
+ + "UNION ALL SELECT result_item_id FROM crafting_recipes "
+ + "UNION ALL SELECT item_id FROM crafting_ingredients "
+ + "UNION ALL SELECT item_id FROM room_ground_inventory "
+ + "UNION ALL SELECT item_id FROM character_equipment "
+ + "UNION ALL SELECT item_id FROM container_instances "
+ + "UNION ALL SELECT item_id FROM item_instances "
+ + "UNION ALL SELECT item_id FROM item_stacks "
+ + "UNION ALL SELECT item_id FROM item_transfer_audits "
+ + "UNION ALL SELECT item_instance_id FROM item_transfer_audits WHERE item_instance_id IS NOT NULL"
+ + ") item_refs");
+ }
+
+ private static long maximumOccupiedSourceKey(DSLContext tx) {
+ return requiredScalar(
+ tx,
+ "SELECT COALESCE(MAX(key_value), 0) FROM ("
+ + "SELECT numeric_key AS key_value FROM "
+ + KEY_RESERVATION
+ + " UNION ALL SELECT tenant_id FROM items WHERE tenant_id > 0"
+ + " UNION ALL SELECT tenant_id FROM npcs WHERE tenant_id > 0"
+ + " UNION ALL SELECT tenant_id FROM crafting_recipes WHERE tenant_id > 0"
+ + " UNION ALL SELECT tenant_id FROM equipment_slot_definitions WHERE tenant_id > 0"
+ + " UNION ALL SELECT tenant_id FROM body_layout_slot_definitions WHERE tenant_id > 0"
+ + " UNION ALL SELECT tenant_id FROM room_ground_inventory WHERE tenant_id > 0"
+ + " UNION ALL SELECT tenant_id FROM container_instances WHERE tenant_id > 0"
+ + " UNION ALL SELECT tenant_id FROM item_instances WHERE tenant_id > 0"
+ + " UNION ALL SELECT tenant_id FROM item_stacks WHERE tenant_id > 0"
+ + " UNION ALL SELECT tenant_id FROM characters WHERE tenant_id > 0"
+ + " UNION ALL SELECT tenant_id FROM character_friend WHERE tenant_id > 0"
+ + " UNION ALL SELECT tenant_id FROM item_visible_ref_counters WHERE tenant_id > 0"
+ + " UNION ALL SELECT tenant_id FROM entity_mutation_effects WHERE tenant_id > 0"
+ + " UNION ALL SELECT tenant_id FROM item_transfer_audits WHERE tenant_id > 0"
+ + " UNION ALL SELECT tenant_id FROM actor_resource_states WHERE tenant_id > 0"
+ + " UNION ALL SELECT tenant_id FROM actor_active_conditions WHERE tenant_id > 0"
+ + " UNION ALL SELECT version_id FROM items WHERE version_id > 0"
+ + " UNION ALL SELECT version_id FROM npcs WHERE version_id > 0"
+ + " UNION ALL SELECT version_id FROM crafting_recipes WHERE version_id > 0"
+ + " UNION ALL SELECT version_id FROM equipment_slot_definitions WHERE version_id > 0"
+ + " UNION ALL SELECT version_id FROM body_layout_slot_definitions WHERE version_id > 0"
+ + ") occupied_entity_source_keys",
+ Long.class);
+ }
+
+ private static void reserveCanonicalKey(DSLContext tx, String kind, long key) {
+ int inserted =
+ tx.execute(
+ "INSERT INTO "
+ + KEY_RESERVATION
+ + " (key_kind, numeric_key, claim_kind) VALUES (?, ?, 'CANONICAL_EMPTY_SOURCE')",
+ kind,
+ key);
+ if (inserted != 1) {
+ throw new IllegalStateException("Entity allocated numeric source key was not reserved");
+ }
+ }
+
+ private static void insertAssociation(
+ DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) {
+ int inserted =
+ tx.execute(
+ "INSERT INTO "
+ + ASSOCIATION
+ + " (target_namespace, genesis_id, operation_id, fence_id, intake_request_id, "
+ + "canonical_tenant_id, canonical_version_id, selected_commit_id, "
+ + "source_revision_id, source_revision_order, local_tenant_key, local_version_key, "
+ + "request_digest, schema_digest, authorization_binding_digest, selected_source_digest, "
+ + "world_read_request_id, world_read_request_digest, world_closure_digest, receipt_digest, "
+ + "associated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "
+ + "CAST(? AS TIMESTAMPTZ))",
+ receipt.targetNamespace(),
+ receipt.genesisId(),
+ receipt.operationId(),
+ receipt.fenceId(),
+ receipt.intakeRequestId(),
+ receipt.canonicalTenantId(),
+ receipt.canonicalVersionId(),
+ receipt.selectedCommitId(),
+ receipt.sourceRevisionId(),
+ receipt.sourceRevisionOrder(),
+ receipt.localTenantKey(),
+ receipt.localVersionKey(),
+ receipt.requestDigest(),
+ receipt.schemaDigest(),
+ receipt.authorizationBindingDigest(),
+ receipt.selectedSourceDigest(),
+ receipt.worldReadRequestId(),
+ receipt.worldReadRequestDigest(),
+ receipt.worldClosureDigest(),
+ receipt.receiptDigest(),
+ receipt.retainedAt());
+ if (inserted != 1)
+ throw new IllegalStateException("Entity source association was not inserted");
+ }
+
+ private static void insertFamilyStates(
+ DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) {
+ for (var state : receipt.familyStates()) {
+ int inserted =
+ tx.execute(
+ "INSERT INTO "
+ + FAMILY_STATE
+ + " (target_namespace, intake_request_id, family_name, owner_state, evidence_kind, row_count, "
+ + "unqualified_row_count, retained_row_count, selected_scope_row_count, reference_count) "
+ + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ receipt.targetNamespace(),
+ receipt.intakeRequestId(),
+ state.family(),
+ state.state().name(),
+ state.evidenceKind().name(),
+ state.rowCount(),
+ state.unqualifiedRowCount(),
+ state.retainedRowCount(),
+ state.selectedScopeRowCount(),
+ state.referenceCount());
+ if (inserted != 1) {
+ throw new IllegalStateException("Entity source family state was not retained");
+ }
+ }
+ }
+
+ private static void insertEmptyOnlyProviderStates(
+ DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) {
+ for (var state : receipt.familyStates()) {
+ if (state.evidenceKind()
+ != EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.EMPTY_ONLY_OWNER_PROVIDER) {
+ continue;
+ }
+ String table = EMPTY_ONLY_PROVIDER_TABLES.get(state.family());
+ if (table == null) {
+ throw new IllegalStateException("Entity EMPTY-only family has no owner table");
+ }
+ int inserted =
+ tx.execute(
+ "INSERT INTO "
+ + table
+ + " (target_namespace, intake_request_id, provider_schema_version, owner_state, "
+ + "row_count, reference_count, authorization_binding_digest, selected_source_digest, "
+ + "source_revision_binding_digest, world_closure_digest, provider_state_digest, observed_at) "
+ + "VALUES (?, ?, 1, ?, 0, 0, ?, ?, ?, ?, ?, "
+ + "CAST(? AS TIMESTAMPTZ))",
+ receipt.targetNamespace(),
+ receipt.intakeRequestId(),
+ state.state().name(),
+ receipt.authorizationBindingDigest(),
+ receipt.selectedSourceDigest(),
+ receipt.selectedSourceRevisionBindingDigest(),
+ receipt.worldClosureDigest(),
+ receipt.providerStateDigest(state.family()),
+ receipt.retainedAt());
+ if (inserted != 1) {
+ throw new IllegalStateException("Entity EMPTY-only provider state was not retained");
+ }
+ }
+ }
+
+ private static void insertReceipt(DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) {
+ int inserted =
+ tx.execute(
+ "INSERT INTO "
+ + RECEIPT
+ + " (target_namespace, intake_request_id, request_digest, schema_digest, "
+ + "receipt_digest, receipt_bytes, retained_at) VALUES (?, ?, ?, ?, ?, ?, "
+ + "CAST(? AS TIMESTAMPTZ))",
+ receipt.targetNamespace(),
+ receipt.intakeRequestId(),
+ receipt.requestDigest(),
+ receipt.schemaDigest(),
+ receipt.receiptDigest(),
+ receipt.canonicalBytes(),
+ receipt.retainedAt());
+ if (inserted != 1) throw new IllegalStateException("Entity source receipt was not inserted");
+ }
+
+ private static Optional readValidated(
+ DSLContext tx, String targetNamespace, UUID intakeRequestId) {
+ Record row = tx.fetchOne(READ_RECEIPT, targetNamespace, intakeRequestId);
+ if (row == null) return Optional.empty();
+ byte[] receiptBytes = row.get(21, byte[].class);
+ if (receiptBytes == null || row.get(22, OffsetDateTime.class) == null) {
+ throw new IllegalStateException("Entity source association has no committed receipt");
+ }
+ EntityEmptySelectedSourceIntakeReceipt receipt =
+ EntityEmptySelectedSourceIntakeReceipt.fromStored(receiptBytes);
+ if (!Objects.equals(row.get(0, String.class), receipt.targetNamespace())
+ || !Objects.equals(row.get(1, UUID.class), receipt.genesisId())
+ || !Objects.equals(row.get(2, UUID.class), receipt.operationId())
+ || !Objects.equals(row.get(3, UUID.class), receipt.fenceId())
+ || !Objects.equals(row.get(4, UUID.class), receipt.intakeRequestId())
+ || !Objects.equals(row.get(5, UUID.class), receipt.canonicalTenantId())
+ || !Objects.equals(row.get(6, UUID.class), receipt.canonicalVersionId())
+ || !Objects.equals(row.get(7, Long.class), receipt.localTenantKey())
+ || !Objects.equals(row.get(8, Long.class), receipt.localVersionKey())
+ || !Objects.equals(row.get(9, String.class), receipt.requestDigest())
+ || !Objects.equals(row.get(10, String.class), receipt.schemaDigest())
+ || !Objects.equals(row.get(11, String.class), receipt.authorizationBindingDigest())
+ || !Objects.equals(row.get(12, String.class), receipt.selectedSourceDigest())
+ || !Objects.equals(row.get(13, UUID.class), receipt.worldReadRequestId())
+ || !Objects.equals(row.get(14, String.class), receipt.worldReadRequestDigest())
+ || !Objects.equals(row.get(15, String.class), receipt.worldClosureDigest())
+ || !Objects.equals(row.get(16, String.class), receipt.receiptDigest())
+ || !sameInstant(row.get(17, OffsetDateTime.class), receipt.retainedAt())
+ || !Objects.equals(row.get(18, String.class), receipt.requestDigest())
+ || !Objects.equals(row.get(19, String.class), receipt.schemaDigest())
+ || !Objects.equals(row.get(20, String.class), receipt.receiptDigest())
+ || !sameInstant(row.get(22, OffsetDateTime.class), receipt.retainedAt())) {
+ throw new IllegalStateException("Entity association differs from its immutable receipt");
+ }
+ requirePersistedEmptyOnlyProviderStates(tx, receipt);
+ requirePersistedFamilyStates(tx, receipt);
+ return Optional.of(receipt);
+ }
+
+ private static boolean sameInstant(OffsetDateTime actual, OffsetDateTime expected) {
+ return actual != null && expected != null && actual.toInstant().equals(expected.toInstant());
+ }
+
+ private static void requirePersistedEmptyOnlyProviderStates(
+ DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) {
+ for (var state : receipt.familyStates()) {
+ if (state.evidenceKind()
+ != EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.EMPTY_ONLY_OWNER_PROVIDER) {
+ continue;
+ }
+ String table = EMPTY_ONLY_PROVIDER_TABLES.get(state.family());
+ if (table == null) {
+ throw new IllegalStateException("Entity EMPTY-only family has no owner table");
+ }
+ Record row =
+ tx.fetchOne(
+ "SELECT provider_schema_version, owner_state, row_count, reference_count, "
+ + "authorization_binding_digest, selected_source_digest, "
+ + "source_revision_binding_digest, world_closure_digest, provider_state_digest, observed_at "
+ + "FROM "
+ + table
+ + " WHERE target_namespace = ? AND intake_request_id = ?",
+ receipt.targetNamespace(),
+ receipt.intakeRequestId());
+ if (row == null
+ || !Objects.equals(row.get(0, Short.class), (short) 1)
+ || !Objects.equals(row.get(1, String.class), state.state().name())
+ || !Objects.equals(row.get(2, Long.class), state.rowCount())
+ || !Objects.equals(row.get(3, Long.class), state.referenceCount())
+ || !Objects.equals(row.get(4, String.class), receipt.authorizationBindingDigest())
+ || !Objects.equals(row.get(5, String.class), receipt.selectedSourceDigest())
+ || !Objects.equals(
+ row.get(6, String.class), receipt.selectedSourceRevisionBindingDigest())
+ || !Objects.equals(row.get(7, String.class), receipt.worldClosureDigest())
+ || !Objects.equals(row.get(8, String.class), receipt.providerStateDigest(state.family()))
+ || !sameInstant(row.get(9, OffsetDateTime.class), receipt.retainedAt())) {
+ throw new IllegalStateException(
+ "Entity EMPTY-only provider readback is missing or differs for " + state.family());
+ }
+ }
+ }
+
+ private static void requirePersistedFamilyStates(
+ DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) {
+ var rows =
+ tx.fetch(
+ "SELECT family_name, owner_state, evidence_kind, row_count, unqualified_row_count, retained_row_count, "
+ + "selected_scope_row_count, reference_count FROM "
+ + FAMILY_STATE
+ + " WHERE target_namespace = ? AND intake_request_id = ? ORDER BY family_name",
+ receipt.targetNamespace(),
+ receipt.intakeRequestId());
+ if (rows.size() != receipt.familyStates().size()) {
+ throw new IllegalStateException("Entity retained family-state vector is incomplete");
+ }
+ var expected =
+ receipt.familyStates().stream()
+ .sorted(
+ java.util.Comparator.comparing(
+ EntityEmptySelectedSourceIntakeReceipt.FamilyCensus::family))
+ .toList();
+ for (int index = 0; index < expected.size(); index++) {
+ Record row = rows.get(index);
+ var state = expected.get(index);
+ if (!Objects.equals(row.get(0, String.class), state.family())
+ || !Objects.equals(row.get(1, String.class), state.state().name())
+ || !Objects.equals(row.get(2, String.class), state.evidenceKind().name())
+ || !Objects.equals(row.get(3, Long.class), state.rowCount())
+ || !Objects.equals(row.get(4, Long.class), state.unqualifiedRowCount())
+ || !Objects.equals(row.get(5, Long.class), state.retainedRowCount())
+ || !Objects.equals(row.get(6, Long.class), state.selectedScopeRowCount())
+ || !Objects.equals(row.get(7, Long.class), state.referenceCount())) {
+ throw new IllegalStateException("Entity retained family state differs from its receipt");
+ }
+ }
+ }
+
+ private static List declaredFamilies(String canonicalDeclaration) {
+ return EntityEmptySelectedSourceIntakeReceipt.familyNames(canonicalDeclaration);
+ }
+
+ private static void requireExactEntityBinding(SelectedOwnerIntakeAuthorizationBinding binding) {
+ if (binding.owner() != Owner.ENTITY_MANAGEMENT
+ || !"account-entity-intake-authorization/v1".equals(binding.schema())
+ || !"ENTITY_INTAKE_RETENTION".equals(binding.purpose())
+ || !binding
+ .intendedReader()
+ .equals(
+ "spiffe://firemud/ns/"
+ + binding.targetNamespace()
+ + "/sa/entity-management-service")) {
+ throw new IllegalArgumentException("Exact original Entity Account authorization is required");
+ }
+ }
+
+ private static long count(DSLContext tx, String sql, Object... arguments) {
+ return requiredScalar(tx, sql, Long.class, arguments);
+ }
+
+ private static T requiredScalar(
+ DSLContext tx, String sql, Class type, Object... arguments) {
+ Record result = tx.fetchOne(sql, arguments);
+ if (result == null || result.get(0, type) == null) {
+ throw new IllegalStateException("Entity source census query returned no scalar value");
+ }
+ return result.get(0, type);
+ }
+
+ private static void requireReadKey(String targetNamespace, UUID intakeRequestId) {
+ if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) || intakeRequestId == null) {
+ throw new IllegalArgumentException(
+ "Canonical Entity source receipt read identity is required");
+ }
+ DraftAuthorizationFenceBinding.requireUuid(intakeRequestId);
+ }
+
+ private static void requirePublicationScopeKey(
+ String targetNamespace, UUID canonicalTenantId, long gameDesignVersionRowId) {
+ if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)
+ || canonicalTenantId == null
+ || new UUID(0L, 0L).equals(canonicalTenantId)
+ || gameDesignVersionRowId <= 0L) {
+ throw new IllegalArgumentException("Entity publication scope identity is required");
+ }
+ }
+
+ private static void requireNoAmbientOwnerSql(String label) {
+ if (TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isSynchronizationActive()) {
+ throw new IllegalStateException(
+ label + " requires an independent Entity transaction boundary");
+ }
+ }
+
+ private record Census(
+ long rows, long unqualifiedRows, long retainedRows, long selectedScopeRows, long references) {
+ private Census {
+ if (rows < 0L
+ || unqualifiedRows < 0L
+ || retainedRows < 0L
+ || selectedScopeRows < 0L
+ || references < 0L
+ || Math.addExact(unqualifiedRows, retainedRows) != rows) {
+ throw new IllegalStateException("Entity census partitions are invalid");
+ }
+ }
+
+ private static Census emptyOnlyProviderState() {
+ // This is not inferred from missing legacy storage: the caller persists a typed, immutable
+ // EMPTY provider record for this exact newly authorized source and independently reads it.
+ return new Census(0L, 0L, 0L, 0L, 0L);
+ }
+
+ private boolean isZero() {
+ return rows == 0L
+ && unqualifiedRows == 0L
+ && retainedRows == 0L
+ && selectedScopeRows == 0L
+ && references == 0L;
+ }
+ }
+
+ private static final class IntakeConflictException extends IllegalStateException {
+ private IntakeConflictException(String message) {
+ super(message);
+ }
+ }
+}
diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java
new file mode 100644
index 0000000000..4eed02753a
--- /dev/null
+++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java
@@ -0,0 +1,205 @@
+package net.firedevops.firemud.entitymanagement.sourceintake;
+
+import java.util.Objects;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
+import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
+import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient;
+import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence;
+import net.firedevops.firemud.common.security.SessionContext;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Unregistered preparation service for authenticated, freshly founded empty Entity scopes. */
+public final class EntityEmptySelectedSourceIntakeService {
+ private final String configuredNamespace;
+ private final EntityEmptySelectedSourceIntakeRepository repository;
+ private final SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient;
+ private final SelectedOwnerWorldInventoryReadClient worldInventoryReadClient;
+
+ public EntityEmptySelectedSourceIntakeService(
+ String configuredNamespace,
+ EntityEmptySelectedSourceIntakeRepository repository,
+ SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient,
+ SelectedOwnerWorldInventoryReadClient worldInventoryReadClient) {
+ if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) {
+ throw new IllegalArgumentException("Configured Entity namespace is required");
+ }
+ this.configuredNamespace = configuredNamespace;
+ this.repository = Objects.requireNonNull(repository, "repository");
+ this.authorizationReadClient =
+ Objects.requireNonNull(authorizationReadClient, "authorizationReadClient");
+ this.worldInventoryReadClient =
+ Objects.requireNonNull(worldInventoryReadClient, "worldInventoryReadClient");
+ }
+
+ /**
+ * Replays an exact retained receipt or prepares a fresh owner-local retention attempt. This
+ * method does not publish, activate, create nonempty templates, or settle Account participation.
+ */
+ public EntityEmptySelectedSourceIntakeReceipt retain(
+ String targetNamespace,
+ SelectedOwnerIntakeAuthorizationBinding originalBinding,
+ WorldSelectedDraftPublicationFreezeEvidence exactFreeze) {
+ requireConfiguredNamespace(targetNamespace);
+ requireAuthenticatedGameDesignCaller(targetNamespace);
+ requireNoAmbientOwnerSql();
+ requireRequest(targetNamespace, originalBinding, exactFreeze);
+ String requestDigest =
+ EntityEmptySelectedSourceIntakeReceipt.requestDigest(
+ targetNamespace, originalBinding, exactFreeze);
+
+ var retained = repository.read(targetNamespace, originalBinding.intakeRequestId());
+ if (retained.isPresent()) {
+ EntityEmptySelectedSourceIntakeReceipt receipt = retained.orElseThrow();
+ receipt.requireSameRequest(targetNamespace, originalBinding, exactFreeze);
+ return receipt;
+ }
+
+ SelectedOwnerIntakeAuthorizationReadEvidence.Request authorizationRequest =
+ SelectedOwnerIntakeAuthorizationReadEvidence.Request.create(
+ targetNamespace, originalBinding);
+ var authorizationEvidence = authorizationReadClient.read(authorizationRequest);
+ if (authorizationEvidence == null
+ || !authorizationRequest.equals(authorizationEvidence.request())) {
+ throw new IllegalStateException("Account did not echo the exact selected-owner read request");
+ }
+
+ SelectedOwnerWorldInventoryReadEvidence.Request worldRequest =
+ SelectedOwnerWorldInventoryReadEvidence.Request.create(
+ targetNamespace, originalBinding, exactFreeze);
+ var worldEvidence = worldInventoryReadClient.read(worldRequest);
+ if (worldEvidence == null || !worldRequest.equals(worldEvidence.request())) {
+ throw new IllegalStateException("World did not echo the exact selected-owner read request");
+ }
+
+ // Typed inputs bind bytes only. The authenticated clients supply producer identity; Account's
+ // distinct source participation remains protected until an exact owner terminal is settled.
+ SelectedOwnerEmptySourceInputs inputs =
+ new SelectedOwnerEmptySourceInputs(originalBinding, worldEvidence);
+ requireEmptyWorldEntityClosure(worldEvidence.inventory().publicEvidence());
+
+ // A second HELD sample narrows the gap after the remote World read. It does not extend or prove
+ // continuous Account protection through Entity's local commit.
+ SelectedOwnerIntakeAuthorizationReadEvidence.Request finalAuthorizationRequest =
+ SelectedOwnerIntakeAuthorizationReadEvidence.Request.create(
+ targetNamespace, originalBinding);
+ var finalAuthorizationEvidence = authorizationReadClient.read(finalAuthorizationRequest);
+ if (finalAuthorizationEvidence == null
+ || !finalAuthorizationRequest.equals(finalAuthorizationEvidence.request())) {
+ throw new IllegalStateException("Account did not echo the final selected-owner read request");
+ }
+
+ EntityEmptySelectedSourceIntakeReceipt receipt = repository.retainFresh(inputs, requestDigest);
+ receipt.requireSameRequest(targetNamespace, originalBinding, exactFreeze);
+ return receipt;
+ }
+
+ private void requireConfiguredNamespace(String targetNamespace) {
+ if (!configuredNamespace.equals(targetNamespace)) {
+ throw new SecurityException(
+ "Selected Entity intake namespace differs from the configured Entity owner namespace");
+ }
+ }
+
+ private static void requireAuthenticatedGameDesignCaller(String targetNamespace) {
+ var peer = GrpcPeerIdentity.current();
+ if (peer == null) {
+ throw new SecurityException("Authenticated same-namespace Game Design peer is required");
+ }
+ if (AccountOriginalDraftOrderCredentials.CONTEXT_KEY.get() != null
+ || SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY.get() != null
+ || AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY.get() != null
+ || SessionContext.hasAuthenticatedCallerContext()
+ || !GrpcPeerIdentity.isValidNamespace(targetNamespace)
+ || !targetNamespace.equals(peer.namespace())
+ || !("spiffe://firemud/ns/" + targetNamespace + "/sa/game-design-service")
+ .equals(peer.uri())) {
+ throw new SecurityException(
+ "Selected Entity intake requires the exact same-namespace Game Design peer");
+ }
+ }
+
+ private static void requireRequest(
+ String targetNamespace,
+ SelectedOwnerIntakeAuthorizationBinding binding,
+ WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) {
+ Objects.requireNonNull(binding, "original Account authorization binding is required");
+ Objects.requireNonNull(freezeEvidence, "exact World freeze is required");
+ if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)
+ || !targetNamespace.equals(binding.targetNamespace())
+ || binding.owner() != Owner.ENTITY_MANAGEMENT
+ || !binding.schema().equals("account-entity-intake-authorization/v1")
+ || !binding.purpose().equals("ENTITY_INTAKE_RETENTION")) {
+ throw new IllegalArgumentException(
+ "Fresh Entity intake requires its exact finalized Account owner binding");
+ }
+ var freeze = freezeEvidence.request();
+ if (!targetNamespace.equals(freeze.targetNamespace())
+ || !binding.tenantId().equals(freeze.canonicalTenantId())
+ || !binding.versionId().equals(freeze.canonicalVersionId())
+ || !binding
+ .selected()
+ .equals(freeze.accountBinding().input().selection().selectedCommit())) {
+ throw new IllegalArgumentException(
+ "Entity owner binding differs from the exact selected World freeze");
+ }
+ }
+
+ private static void requireEmptyWorldEntityClosure(
+ WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence inventory) {
+ if (!WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA.equals(
+ inventory.schema())
+ || inventory.schemaVersion()
+ != WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION
+ || !WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL.equals(
+ inventory.sourceModel().modelId())
+ || inventory.sourceModel().graphSchemaVersion()
+ != WorldSelectedPublicationArtifactInventoryEvidence
+ .INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION
+ || inventory.sourceModel().inboundSourceClosure() == null) {
+ throw new IllegalArgumentException(
+ "Entity empty-source intake requires the complete supported World closure");
+ }
+ var sourceModel = inventory.sourceModel();
+ int spawnCount =
+ sourceModel.familyCounts().stream()
+ .filter(family -> "WORLD_ENTITY_SPAWN_BINDING".equals(family.family()))
+ .mapToInt(WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount::rowCount)
+ .findFirst()
+ .orElseThrow(
+ () -> new IllegalArgumentException("World population family state is unavailable"));
+ if (spawnCount != 0
+ || sourceModel.spawnBindingCount() != 0
+ || !sourceModel.spawnBindingInputs().isEmpty()) {
+ throw new IllegalArgumentException(
+ "Entity empty-source intake cannot retain World population bindings");
+ }
+ var closure = sourceModel.inboundSourceClosure();
+ if (closure.schemaVersion() != 1 || closure.familyCounts().size() != 7) {
+ throw new IllegalArgumentException("World inbound closure family vector is incomplete");
+ }
+ for (var family : closure.familyCounts()) {
+ if (family.count() != 0) {
+ throw new IllegalArgumentException(
+ "Entity empty-source intake cannot retain World item, loot, behavior, or hook references");
+ }
+ }
+ }
+
+ private static void requireNoAmbientOwnerSql() {
+ if (TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isSynchronizationActive()) {
+ throw new IllegalStateException(
+ "Account and World evidence reads must run outside Entity SQL");
+ }
+ }
+}
diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java
new file mode 100644
index 0000000000..163256d712
--- /dev/null
+++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java
@@ -0,0 +1,83 @@
+package net.firedevops.firemud.entitymanagement.sourceintake;
+
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import java.util.Arrays;
+import java.util.Objects;
+import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.security.SessionContext;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Account-only lookup over Entity's immutable selected-source terminal receipt. */
+public final class EntityEmptySelectedSourceIntakeTerminalReadService {
+ private final EntityEmptySelectedSourceIntakeRepository repository;
+ private final String namespace;
+
+ public EntityEmptySelectedSourceIntakeTerminalReadService(
+ EntityEmptySelectedSourceIntakeRepository repository, String namespace) {
+ this.repository = Objects.requireNonNull(repository, "repository");
+ if (!GrpcPeerIdentity.isValidNamespace(namespace)) {
+ throw new IllegalArgumentException("Canonical namespace required");
+ }
+ this.namespace = namespace;
+ }
+
+ /** Called by the transport before decoding caller-carried evidence or touching owner storage. */
+ void requireAuthenticatedAccountCaller() {
+ if (SessionContext.hasAuthenticatedCallerContext()) {
+ throw Status.PERMISSION_DENIED.asRuntimeException();
+ }
+ var peer = GrpcPeerIdentity.current();
+ if (peer == null) {
+ throw Status.UNAUTHENTICATED.asRuntimeException();
+ }
+ if (!namespace.equals(peer.namespace())
+ || !"account-service".equals(peer.service())
+ || !("spiffe://firemud/ns/" + namespace + "/sa/account-service").equals(peer.uri())) {
+ throw Status.PERMISSION_DENIED.asRuntimeException();
+ }
+ }
+
+ /** Reads only the exact original COMMITTED_EMPTY receipt; absence is not terminal abort. */
+ public EntitySelectedSourceIntakeTerminalReadEvidence read(
+ EntitySelectedSourceIntakeTerminalReadEvidence.Request request) {
+ requireAuthenticatedAccountCaller();
+ Objects.requireNonNull(request, "terminal-read request is required");
+ if (!namespace.equals(request.targetNamespace())) {
+ throw Status.PERMISSION_DENIED.asRuntimeException();
+ }
+ if (TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isSynchronizationActive()) {
+ throw Status.FAILED_PRECONDITION.asRuntimeException();
+ }
+
+ final net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt
+ receipt;
+ try {
+ receipt =
+ repository
+ .read(namespace, request.binding().intakeRequestId())
+ .orElseThrow(() -> Status.NOT_FOUND.asRuntimeException());
+ } catch (StatusRuntimeException denied) {
+ throw denied;
+ } catch (RuntimeException corrupt) {
+ throw Status.DATA_LOSS
+ .withDescription("Entity committed receipt is invalid")
+ .asRuntimeException();
+ }
+
+ if (!Arrays.equals(request.binding().canonicalBytes(), receipt.authorizationBindingBytes())) {
+ throw Status.ALREADY_EXISTS
+ .withDescription("Entity receipt differs from the complete original authorization")
+ .asRuntimeException();
+ }
+ try {
+ return new EntitySelectedSourceIntakeTerminalReadEvidence(request, receipt);
+ } catch (RuntimeException corrupt) {
+ throw Status.DATA_LOSS
+ .withDescription("Entity receipt differs from its original order")
+ .asRuntimeException();
+ }
+ }
+}
diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceService.java
new file mode 100644
index 0000000000..22a8e3b96b
--- /dev/null
+++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceService.java
@@ -0,0 +1,216 @@
+package net.firedevops.firemud.entitymanagement.sourceintake;
+
+import java.util.List;
+import java.util.Objects;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection;
+import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient;
+import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence;
+import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence;
+import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association;
+import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay;
+import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request;
+import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.gamedesign.v1.ParticipantDigest;
+import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/**
+ * Unregistered Entity consumer for Game Design's independently authenticated authored-core read.
+ */
+public final class EntityRetainedAuthoredActorCoreSourceService {
+ private static final String ENTITY_RELEASE_SCHEMA =
+ "v" + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION;
+
+ private final String configuredNamespace;
+ private final AuthoredInitialActorCoreReadClient gameDesignClient;
+ private final EntityEmptySelectedSourceIntakeRepository repository;
+
+ public EntityRetainedAuthoredActorCoreSourceService(
+ String configuredNamespace,
+ AuthoredInitialActorCoreReadClient gameDesignClient,
+ EntityEmptySelectedSourceIntakeRepository repository) {
+ if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) {
+ throw new IllegalArgumentException("Configured Entity namespace is required");
+ }
+ this.configuredNamespace = configuredNamespace;
+ this.gameDesignClient = Objects.requireNonNull(gameDesignClient, "gameDesignClient");
+ this.repository = Objects.requireNonNull(repository, "repository");
+ }
+
+ /**
+ * Obtains the exact already-pinned read directly from Game Design, then corroborates it against
+ * Entity's retained selected source and the immutable Entity participant in that selected
+ * release. The returned object is the unchanged public result from the authenticated client.
+ */
+ public AuthoredInitialActorCoreReadEvidence.ReadResult read(
+ AuthoredInitialActorCoreReadEvidence.ReadRequest request) {
+ Objects.requireNonNull(request, "authored-core read request is required");
+ requireNoAmbientOwnerSql();
+
+ Request associationRequest = request.associationRequest();
+ if (!configuredNamespace.equals(associationRequest.targetNamespace())
+ || !(associationRequest.selection() instanceof ExactReplay)) {
+ throw denied("Exact same-namespace pinned Game Design read is required");
+ }
+
+ // This is a direct workload-authenticated read. No Entity owner transaction may surround it.
+ AuthoredInitialActorCoreReadEvidence.ReadResult publicResult = gameDesignClient.read(request);
+ if (publicResult == null || !associationRequest.equals(publicResult.request())) {
+ throw denied("Game Design authored-core read differs from the exact original request");
+ }
+ Result associationRead = publicResult.associationRead();
+ if (associationRead == null || !associationRequest.equals(associationRead.request())) {
+ throw denied("Game Design association read differs from the exact original request");
+ }
+
+ Association association = associationRead.association();
+ PublishedReleaseBundle release = associationRead.releaseBundle();
+ if (association == null || release == null) {
+ throw denied("Game Design selected association or release is unavailable");
+ }
+ if (release.getVersionId() <= 0L) {
+ throw denied("Selected release has no canonical Version row");
+ }
+
+ // COMMITTED_EMPTY is only Entity's pre-publication source receipt. The public Game Design read
+ // remains the independent authored-core evidence; this receipt only correlates its selection.
+ // The repository resolves every association in a read-only repeatable-read snapshot.
+ EntityEmptySelectedSourceIntakeReceipt receipt =
+ repository.readPublicationScope(
+ configuredNamespace, association.canonicalTenantId(), release.getVersionId());
+ requireExactReleaseAndSource(associationRequest, association, release, receipt);
+ requireExactProjections(publicResult.projections(), association, receipt);
+ return publicResult;
+ }
+
+ private void requireExactReleaseAndSource(
+ Request request,
+ Association association,
+ PublishedReleaseBundle release,
+ EntityEmptySelectedSourceIntakeReceipt receipt) {
+ if (receipt == null) {
+ throw denied("Entity retained selected-source receipt is unavailable");
+ }
+ ExactReplay replay = (ExactReplay) request.selection();
+ var authorization = receipt.authorizationBinding();
+ var selected = authorization.selected();
+ var target = selected.target();
+ var worldRead = receipt.inputs().worldInventoryReadEvidence();
+ var worldInventory = worldRead.inventory();
+ var worldOwner = worldInventory.publicEvidence().ownerScope();
+ var worldReceipt = association.worldReceipt();
+ var worldSelection =
+ worldRead.request().freezeEvidence().request().accountBinding().input().selection();
+
+ if (!configuredNamespace.equals(receipt.targetNamespace())
+ || !configuredNamespace.equals(authorization.targetNamespace())
+ || authorization.owner() != Owner.ENTITY_MANAGEMENT
+ || !association.canonicalTenantId().equals(receipt.canonicalTenantId())
+ || !association.canonicalVersionId().equals(receipt.canonicalVersionId())
+ || !association.selectedCommitId().equals(receipt.selectedCommitId())
+ || !replay.canonicalVersionId().equals(receipt.canonicalVersionId())
+ || !replay.selectedCommitId().equals(receipt.selectedCommitId())
+ || !replay.publishWorkflowId().equals(association.publishWorkflowId())
+ || !replay.associationDigest().equals(association.associationDigest())
+ || !receipt.canonicalTenantId().equals(target.canonicalTenantId())
+ || !receipt.canonicalVersionId().equals(target.canonicalVersionId())
+ || target.gameDesignVersionRowId() != release.getVersionId()
+ || !selected.commitId().equals(receipt.selectedCommitId())
+ || !configuredNamespace.equals(association.targetNamespace())
+ || !association.intakeRequestId().equals(worldOwner.intakeRequestId())
+ || !association.worldOperationId().equals(worldOwner.intakeOperationId())
+ || !association.publicationSelectionDigest().equals(worldSelection.digest())
+ || !worldReceipt.targetNamespace().equals(worldOwner.targetNamespace())
+ || !worldReceipt.canonicalTenantId().equals(worldOwner.canonicalTenantId())
+ || !worldReceipt.intakeRequestId().equals(worldOwner.intakeRequestId())
+ || !worldReceipt.operationId().equals(worldOwner.intakeOperationId())
+ || !worldReceipt.sourceOperationId().equals(worldOwner.sourceOperationId())
+ || !worldReceipt.sourceEvidenceDigest().equals(worldOwner.sourceEvidenceDigest())
+ || !worldReceipt.receiptDigest().equals(worldOwner.intakeReceiptDigest())
+ || !release.getCanonicalTenantId().equals(receipt.canonicalTenantId().toString())
+ || !release.getCanonicalVersionId().equals(receipt.canonicalVersionId().toString())
+ || release.getVersionId() != target.gameDesignVersionRowId()
+ || !release.getPublishWorkflowId().equals(association.publishWorkflowId())
+ || !ENTITY_RELEASE_SCHEMA.equals(release.getAttestationSchemaVersion())
+ || !association.sourceOperationId().equals(worldOwner.sourceOperationId())
+ || !association.sourceEvidenceDigest().equals(worldOwner.sourceEvidenceDigest())
+ || !receipt.canonicalTenantId().equals(worldOwner.canonicalTenantId())
+ || !receipt.canonicalVersionId().equals(worldOwner.canonicalVersionId())
+ || !receipt
+ .selectedCommitId()
+ .toString()
+ .equals(
+ receipt
+ .inputs()
+ .worldInventoryReadEvidence()
+ .request()
+ .freezeEvidence()
+ .acknowledgement()
+ .appliedCommitId())
+ || !receipt.operationId().equals(authorization.operationId())
+ || !receipt.fenceId().equals(authorization.fenceId())
+ || !receipt.intakeRequestId().equals(authorization.intakeRequestId())) {
+ throw denied("Entity receipt differs from the exact selected source operation or release");
+ }
+
+ String expectedEntityDigest =
+ EntitySelectedEmptyPublicationDigestService.contentDigest(
+ receipt.canonicalTenantId(),
+ target.gameDesignVersionRowId(),
+ receipt.canonicalVersionId(),
+ receipt.inputs().ownerSourceInventoryDeclaration().entityInventory().canonicalJson());
+ List matchingEntityParticipants =
+ release.getParticipantDigestsList().stream()
+ .filter(value -> "ENTITY_MANAGEMENT".equals(value.getParticipantKey()))
+ .toList();
+ if (matchingEntityParticipants.size() != 1) {
+ throw denied("Selected release has no unique immutable Entity participant digest");
+ }
+ ParticipantDigest entityParticipant = matchingEntityParticipants.getFirst();
+ if (!Long.toString(target.gameDesignVersionRowId()).equals(entityParticipant.getScopeValue())
+ || !receipt.selectedCommitId().toString().equals(entityParticipant.getAppliedCommitId())
+ || entityParticipant.getDigestSchemaVersion()
+ != EntitySelectedEmptyPublicationDigestService.DIGEST_SCHEMA_VERSION
+ || !expectedEntityDigest.equals(entityParticipant.getContentDigest())
+ || entityParticipant.hasAbilitySchemaDigest()) {
+ throw denied("Selected release Entity digest differs from the retained Entity receipt");
+ }
+ }
+
+ private static void requireExactProjections(
+ List projections,
+ Association association,
+ EntityEmptySelectedSourceIntakeReceipt receipt) {
+ if (projections == null) {
+ throw denied("Game Design authored-core projection list is unavailable");
+ }
+ String selectedCommitDigest = receipt.authorizationBinding().selected().digest();
+ for (AuthoredInitialActorCoreProjection projection : projections) {
+ if (projection == null
+ || !projection.canonicalTenantId().equals(receipt.canonicalTenantId())
+ || !projection.canonicalVersionId().equals(receipt.canonicalVersionId())
+ || !projection.selectedCommitId().equals(receipt.selectedCommitId())
+ || !projection.selectedCommitDigest().equals(selectedCommitDigest)
+ || !projection.worldSourceOperationId().equals(association.sourceOperationId())
+ || !projection.worldSourceEvidenceDigest().equals(association.sourceEvidenceDigest())
+ || !projection.worldSlug().equals(association.worldSlug())
+ || !projection.publicationWorkflowId().equals(association.publishWorkflowId())) {
+ throw denied("Authored-core projection differs from Entity's exact retained source");
+ }
+ }
+ }
+
+ private static void requireNoAmbientOwnerSql() {
+ if (TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isSynchronizationActive()) {
+ throw denied("Entity authored-core consumption requires no ambient owner SQL");
+ }
+ }
+
+ private static IllegalStateException denied(String message) {
+ return new IllegalStateException(message);
+ }
+}
diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiver.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiver.java
new file mode 100644
index 0000000000..48545091c9
--- /dev/null
+++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiver.java
@@ -0,0 +1,103 @@
+package net.firedevops.firemud.entitymanagement.sourceintake;
+
+import io.grpc.stub.StreamObserver;
+import io.micrometer.core.instrument.MeterRegistry;
+import java.util.Objects;
+import net.firedevops.firemud.common.grpc.GrpcAppErrors;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import net.firedevops.firemud.common.security.AdminAuthorizationException;
+import net.firedevops.firemud.common.security.PublicationReadGuard;
+import net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService.EntityDraftDesignDigest;
+import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc;
+import net.firedevops.firemud.entitymanagement.v1.GetDraftDesignDigestRequest;
+import net.firedevops.firemud.entitymanagement.v1.GetDraftDesignDigestResponse;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Unregistered native receiver for the selected-empty Entity publication digest path. */
+public final class EntitySelectedEmptyPublicationDigestGrpcReceiver
+ extends EntityManagementServiceGrpc.EntityManagementServiceImplBase {
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(EntitySelectedEmptyPublicationDigestGrpcReceiver.class);
+
+ private final EntitySelectedEmptyPublicationDigestService digestService;
+ private final PublicationReadGuard publicationReadGuard;
+ private final MeterRegistry meterRegistry;
+
+ public EntitySelectedEmptyPublicationDigestGrpcReceiver(
+ EntitySelectedEmptyPublicationDigestService digestService,
+ String configuredNamespace,
+ MeterRegistry meterRegistry) {
+ this.digestService = Objects.requireNonNull(digestService, "digestService");
+ this.publicationReadGuard = PublicationReadGuard.configured(configuredNamespace);
+ this.meterRegistry = Objects.requireNonNull(meterRegistry, "meterRegistry");
+ }
+
+ @Override
+ public void getDraftDesignDigest(
+ GetDraftDesignDigestRequest request,
+ StreamObserver responseObserver) {
+ try {
+ requirePublicationRead();
+ if (request.getScopeCase() != GetDraftDesignDigestRequest.ScopeCase.VERSION_ID) {
+ responseObserver.onNext(
+ error(
+ "UNSUPPORTED_SCOPE",
+ "Entity selected-empty publication supports version_id scope only"));
+ responseObserver.onCompleted();
+ return;
+ }
+ PublicationDigestRequestBinding binding =
+ PublicationDigestRequestBinding.forScope(
+ PublicationDigestRequestBinding.ScopeKind.FULL_VERSION,
+ request.getTenantId(),
+ request.getVersionId(),
+ request.getBaseVersionId(),
+ request.getScriptPatchVersion(),
+ request.getPublishRequestId());
+ binding.validateSupplied(request.getDerivedWorkflowIdentity(), request.getRequestDigest());
+
+ EntityDraftDesignDigest digest = digestService.getDraftDesignDigest(binding);
+ binding.requireOwnerScope(digest.tenantId(), digest.scopeValue());
+ responseObserver.onNext(
+ GetDraftDesignDigestResponse.newBuilder()
+ .setTenantId(binding.tenantId())
+ .setVersionId(binding.versionId())
+ .setAppliedCommitId(digest.appliedCommitId())
+ .setContentDigest(digest.contentDigest())
+ .setDigestSchemaVersion(digest.digestSchemaVersion())
+ .build());
+ responseObserver.onCompleted();
+ } catch (AdminAuthorizationException denied) {
+ responseObserver.onNext(error("PERMISSION_DENIED", denied.getMessage()));
+ responseObserver.onCompleted();
+ } catch (IllegalArgumentException invalid) {
+ responseObserver.onNext(error("INVALID_ARGUMENT", invalid.getMessage()));
+ responseObserver.onCompleted();
+ } catch (IllegalStateException unavailable) {
+ responseObserver.onNext(error("FAILED_PRECONDITION", unavailable.getMessage()));
+ responseObserver.onCompleted();
+ } catch (RuntimeException failure) {
+ responseObserver.onNext(
+ GetDraftDesignDigestResponse.newBuilder()
+ .setError(
+ GrpcAppErrors.internal(meterRegistry, LOGGER, "GetDraftDesignDigest", failure))
+ .build());
+ responseObserver.onCompleted();
+ }
+ }
+
+ private void requirePublicationRead() {
+ if (publicationReadGuard == null) {
+ throw new AdminAuthorizationException("Publication read authorization is not configured");
+ }
+ publicationReadGuard.requirePublicationRead(
+ PublicationReadGuard.ENTITY_MANAGEMENT_DIGEST_METHOD);
+ }
+
+ private GetDraftDesignDigestResponse error(String code, String message) {
+ return GetDraftDesignDigestResponse.newBuilder()
+ .setError(GrpcAppErrors.error(meterRegistry, LOGGER, "GetDraftDesignDigest", code, message))
+ .build();
+ }
+}
diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java
new file mode 100644
index 0000000000..0514ab806d
--- /dev/null
+++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java
@@ -0,0 +1,186 @@
+package net.firedevops.firemud.entitymanagement.sourceintake;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService.EntityDraftDesignDigest;
+
+/** Unregistered selected-empty full-version digest reader over Entity's retained owner receipt. */
+public final class EntitySelectedEmptyPublicationDigestService {
+ public static final int DIGEST_SCHEMA_VERSION = 3;
+ private static final String DIGEST_DOMAIN = "entity-selected-empty-publication-digest/v1";
+
+ private final String configuredNamespace;
+ private final EntityEmptySelectedSourceIntakeRepository repository;
+
+ public EntitySelectedEmptyPublicationDigestService(
+ String configuredNamespace, EntityEmptySelectedSourceIntakeRepository repository) {
+ if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) {
+ throw new IllegalArgumentException("Configured Entity namespace is required");
+ }
+ this.configuredNamespace = configuredNamespace;
+ this.repository = Objects.requireNonNull(repository, "repository");
+ }
+
+ /** Returns a selected-empty digest only for one exact canonical tenant and GD Version row. */
+ public EntityDraftDesignDigest getDraftDesignDigest(
+ PublicationDigestRequestBinding publicationRequest) {
+ Objects.requireNonNull(publicationRequest, "publication request is required");
+ if (publicationRequest.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) {
+ throw new IllegalArgumentException(
+ "Entity selected-empty publication supports full versions only");
+ }
+ UUID canonicalTenantId = canonicalUuid(publicationRequest.tenantId(), "tenantId");
+ long gameDesignVersionRowId =
+ canonicalPositiveLong(publicationRequest.versionId(), "versionId");
+
+ EntityEmptySelectedSourceIntakeReceipt receipt =
+ repository.readPublicationScope(
+ configuredNamespace, canonicalTenantId, gameDesignVersionRowId);
+ var target = receipt.authorizationBinding().selected().target();
+ if (!configuredNamespace.equals(receipt.targetNamespace())
+ || !canonicalTenantId.equals(receipt.canonicalTenantId())
+ || !canonicalTenantId.equals(target.canonicalTenantId())
+ || target.gameDesignVersionRowId() != gameDesignVersionRowId
+ || !receipt.canonicalVersionId().equals(target.canonicalVersionId())) {
+ throw new IllegalStateException(
+ "Entity selected-empty receipt differs from publication scope");
+ }
+
+ var inputs = receipt.inputs();
+ requireOriginalPublicationRequest(
+ publicationRequest,
+ canonicalTenantId,
+ gameDesignVersionRowId,
+ receipt.canonicalVersionId(),
+ receipt.selectedCommitId(),
+ inputs.worldInventoryReadEvidence().request().freezeEvidence());
+ if (inputs.authorizationBinding().owner() != Owner.ENTITY_MANAGEMENT) {
+ throw new IllegalStateException("Entity receipt contains a different owner declaration");
+ }
+ requireEmptyReceipt(receipt);
+ String inventoryJson =
+ inputs.ownerSourceInventoryDeclaration().entityInventory().canonicalJson();
+ String contentDigest =
+ contentDigest(
+ canonicalTenantId, gameDesignVersionRowId, receipt.canonicalVersionId(), inventoryJson);
+ return new EntityDraftDesignDigest(
+ publicationRequest.tenantId(),
+ publicationRequest.versionId(),
+ receipt.selectedCommitId().toString(),
+ contentDigest,
+ DIGEST_SCHEMA_VERSION);
+ }
+
+ private static void requireOriginalPublicationRequest(
+ PublicationDigestRequestBinding requested,
+ UUID canonicalTenantId,
+ long gameDesignVersionRowId,
+ UUID canonicalVersionId,
+ UUID selectedCommitId,
+ net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence
+ retainedFreeze) {
+ var freezeRequest = retainedFreeze.request();
+ var retainedSelection = freezeRequest.accountBinding().input().selection();
+ var retainedPublicationRequest =
+ PublicationDigestRequestBinding.full(
+ freezeRequest.canonicalTenantId().toString(),
+ Long.toString(gameDesignVersionRowId),
+ freezeRequest.publicationRequestId());
+ if (!canonicalTenantId.equals(freezeRequest.canonicalTenantId())
+ || !canonicalVersionId.equals(freezeRequest.canonicalVersionId())
+ || !selectedCommitId.equals(retainedSelection.selectedCommit().commitId())
+ || !selectedCommitId.toString().equals(retainedFreeze.acknowledgement().appliedCommitId())
+ || requested.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION
+ || !requested.tenantId().equals(retainedPublicationRequest.tenantId())
+ || !requested.versionId().equals(retainedPublicationRequest.versionId())
+ || !requested.publishRequestId().equals(retainedPublicationRequest.publishRequestId())
+ || !requested.derivedWorkflowIdentity()
+ .equals(retainedPublicationRequest.derivedWorkflowIdentity())
+ || !requested.requestDigest().equals(retainedPublicationRequest.requestDigest())) {
+ throw new IllegalStateException(
+ "Entity publication request differs from the original retained World freeze");
+ }
+ }
+
+ static String contentDigest(
+ UUID canonicalTenantId,
+ long gameDesignVersionRowId,
+ UUID canonicalVersionId,
+ String canonicalInventoryJson) {
+ if (gameDesignVersionRowId <= 0L) {
+ throw new IllegalArgumentException("Game Design Version row must be positive");
+ }
+ Objects.requireNonNull(canonicalTenantId, "canonicalTenantId");
+ Objects.requireNonNull(canonicalVersionId, "canonicalVersionId");
+ Objects.requireNonNull(canonicalInventoryJson, "canonicalInventoryJson");
+ ByteArrayOutputStream preimage = new ByteArrayOutputStream();
+ appendSegment(preimage, DIGEST_DOMAIN);
+ appendSegment(preimage, Integer.toString(DIGEST_SCHEMA_VERSION));
+ appendSegment(preimage, canonicalTenantId.toString());
+ appendSegment(preimage, Long.toString(gameDesignVersionRowId));
+ appendSegment(preimage, canonicalVersionId.toString());
+ appendSegment(preimage, canonicalInventoryJson);
+ try {
+ return HexFormat.of()
+ .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray()));
+ } catch (NoSuchAlgorithmException impossible) {
+ throw new IllegalStateException("SHA-256 is unavailable", impossible);
+ }
+ }
+
+ private static void requireEmptyReceipt(EntityEmptySelectedSourceIntakeReceipt receipt) {
+ if (receipt.familyStates().size() != 23
+ || receipt.familyStates().stream()
+ .anyMatch(
+ state ->
+ state.state() != EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY
+ || state.rowCount() != 0L
+ || state.unqualifiedRowCount() != 0L
+ || state.retainedRowCount() != 0L
+ || state.selectedScopeRowCount() != 0L
+ || state.referenceCount() != 0L)) {
+ throw new IllegalStateException("Entity selected-empty receipt is incomplete or nonempty");
+ }
+ }
+
+ private static UUID canonicalUuid(String value, String field) {
+ try {
+ UUID parsed = UUID.fromString(value);
+ if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) {
+ throw new IllegalArgumentException(field + " must be a canonical nonzero UUID");
+ }
+ return parsed;
+ } catch (RuntimeException malformed) {
+ throw new IllegalArgumentException(field + " must be a canonical nonzero UUID", malformed);
+ }
+ }
+
+ private static long canonicalPositiveLong(String value, String field) {
+ try {
+ long parsed = Long.parseLong(value);
+ if (parsed <= 0L || !Long.toString(parsed).equals(value)) {
+ throw new IllegalArgumentException(field + " must be a canonical positive decimal");
+ }
+ return parsed;
+ } catch (RuntimeException malformed) {
+ throw new IllegalArgumentException(
+ field + " must be a canonical positive decimal", malformed);
+ }
+ }
+
+ private static void appendSegment(ByteArrayOutputStream output, String value) {
+ byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
+ output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII));
+ output.write(':');
+ output.writeBytes(bytes);
+ }
+}
diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcService.java
new file mode 100644
index 0000000000..56a872405c
--- /dev/null
+++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcService.java
@@ -0,0 +1,101 @@
+package net.firedevops.firemud.entitymanagement.sourceintake;
+
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import io.grpc.stub.StreamObserver;
+import java.util.Objects;
+import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence;
+import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandGrpcCodec;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
+import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
+import net.firedevops.firemud.common.security.SessionContext;
+import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeCommandServiceGrpc;
+import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceRequest;
+import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceResponse;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Unregistered Game Design command boundary for retaining exact selected Entity inputs. */
+public final class EntitySelectedSourceIntakeCommandGrpcService
+ extends EntitySelectedSourceIntakeCommandServiceGrpc
+ .EntitySelectedSourceIntakeCommandServiceImplBase {
+ private final EntityEmptySelectedSourceIntakeService owner;
+ private final String namespace;
+
+ public EntitySelectedSourceIntakeCommandGrpcService(
+ EntityEmptySelectedSourceIntakeService owner, String namespace) {
+ this.owner = Objects.requireNonNull(owner, "selected-source intake owner is required");
+ if (!GrpcPeerIdentity.isValidNamespace(namespace)) {
+ throw new IllegalArgumentException("configured namespace is invalid");
+ }
+ this.namespace = namespace;
+ }
+
+ @Override
+ public void retainSelectedEntitySource(
+ RetainSelectedEntitySourceRequest request,
+ StreamObserver observer) {
+ try {
+ requireAuthenticatedGameDesignCaller();
+ } catch (StatusRuntimeException denied) {
+ observer.onError(denied);
+ return;
+ }
+ if (!namespace.equals(request.getTargetNamespace())) {
+ observer.onError(Status.PERMISSION_DENIED.asRuntimeException());
+ return;
+ }
+ if (TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isSynchronizationActive()) {
+ observer.onError(Status.FAILED_PRECONDITION.asRuntimeException());
+ return;
+ }
+
+ final EntitySelectedSourceIntakeCommandEvidence.Request decoded;
+ try {
+ decoded = EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(request);
+ } catch (RuntimeException malformed) {
+ observer.onError(Status.INVALID_ARGUMENT.asRuntimeException());
+ return;
+ }
+
+ try {
+ var receipt =
+ owner.retain(
+ decoded.targetNamespace(),
+ decoded.originalAuthorizationBinding(),
+ decoded.freezeEvidence());
+ var evidence = new EntitySelectedSourceIntakeCommandEvidence(decoded, receipt);
+ observer.onNext(EntitySelectedSourceIntakeCommandGrpcCodec.toResponse(evidence));
+ observer.onCompleted();
+ } catch (StatusRuntimeException denied) {
+ observer.onError(Status.fromCode(denied.getStatus().getCode()).asRuntimeException());
+ } catch (SecurityException denied) {
+ observer.onError(Status.PERMISSION_DENIED.asRuntimeException());
+ } catch (IllegalArgumentException | IllegalStateException unavailable) {
+ observer.onError(Status.FAILED_PRECONDITION.asRuntimeException());
+ } catch (RuntimeException failure) {
+ observer.onError(Status.INTERNAL.asRuntimeException());
+ }
+ }
+
+ /** Authenticate the exact same-namespace workload and reject user context before decoding. */
+ private void requireAuthenticatedGameDesignCaller() {
+ if (SessionContext.hasAuthenticatedCallerContext()
+ || AccountOriginalDraftOrderCredentials.CONTEXT_KEY.get() != null
+ || SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY.get() != null
+ || AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY.get() != null) {
+ throw Status.PERMISSION_DENIED.asRuntimeException();
+ }
+ var peer = GrpcPeerIdentity.current();
+ if (peer == null) {
+ throw Status.UNAUTHENTICATED.asRuntimeException();
+ }
+ if (!namespace.equals(peer.namespace())
+ || !"game-design-service".equals(peer.service())
+ || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) {
+ throw Status.PERMISSION_DENIED.asRuntimeException();
+ }
+ }
+}
diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcService.java
new file mode 100644
index 0000000000..1b58c29642
--- /dev/null
+++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcService.java
@@ -0,0 +1,53 @@
+package net.firedevops.firemud.entitymanagement.sourceintake;
+
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import io.grpc.stub.StreamObserver;
+import java.util.Objects;
+import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadGrpcCodec;
+import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeTerminalReadServiceGrpc;
+import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalRequest;
+import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalResponse;
+
+/** No automatic registration; authenticate Account before parsing its claimed original binding. */
+public final class EntitySelectedSourceIntakeTerminalReadGrpcService
+ extends EntitySelectedSourceIntakeTerminalReadServiceGrpc
+ .EntitySelectedSourceIntakeTerminalReadServiceImplBase {
+ private final EntityEmptySelectedSourceIntakeTerminalReadService owner;
+
+ public EntitySelectedSourceIntakeTerminalReadGrpcService(
+ EntityEmptySelectedSourceIntakeTerminalReadService owner) {
+ this.owner = Objects.requireNonNull(owner, "terminal-read owner is required");
+ }
+
+ @Override
+ public void readSelectedSourceIntakeTerminal(
+ ReadSelectedSourceIntakeTerminalRequest request,
+ StreamObserver observer) {
+ try {
+ owner.requireAuthenticatedAccountCaller();
+ } catch (StatusRuntimeException denied) {
+ observer.onError(denied);
+ return;
+ }
+
+ final net.firedevops.firemud.common.entity.sourceintake
+ .EntitySelectedSourceIntakeTerminalReadEvidence.Request
+ decoded;
+ try {
+ decoded = EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(request);
+ } catch (RuntimeException malformed) {
+ observer.onError(Status.INVALID_ARGUMENT.asRuntimeException());
+ return;
+ }
+ try {
+ var evidence = owner.read(decoded);
+ observer.onNext(EntitySelectedSourceIntakeTerminalReadGrpcCodec.toResponse(evidence));
+ observer.onCompleted();
+ } catch (StatusRuntimeException denied) {
+ observer.onError(denied);
+ } catch (RuntimeException corrupt) {
+ observer.onError(Status.DATA_LOSS.asRuntimeException());
+ }
+ }
+}
diff --git a/services/entity-management-service/src/main/resources/db/migration/V1011__fresh_selected_empty_source_catalogue.sql b/services/entity-management-service/src/main/resources/db/migration/V1011__fresh_selected_empty_source_catalogue.sql
new file mode 100644
index 0000000000..5d6a33692f
--- /dev/null
+++ b/services/entity-management-service/src/main/resources/db/migration/V1011__fresh_selected_empty_source_catalogue.sql
@@ -0,0 +1,1074 @@
+-- Fresh-only selected-source retention. Existing Entity rows are never adopted as a selected
+-- source; they are reserved as occupied numeric keys and deny a fresh empty-source census.
+CREATE TABLE entity_empty_source_numeric_key_reservation (
+ key_kind VARCHAR(16) NOT NULL,
+ numeric_key BIGINT NOT NULL,
+ claim_kind VARCHAR(32) NOT NULL,
+ CONSTRAINT pk_entity_empty_source_numeric_key_reservation
+ PRIMARY KEY (key_kind, numeric_key),
+ CONSTRAINT uq_entity_empty_source_numeric_key_claim
+ UNIQUE (numeric_key, key_kind, claim_kind),
+ CONSTRAINT ck_entity_empty_source_numeric_key_kind
+ CHECK (key_kind IN ('TENANT', 'VERSION')),
+ CONSTRAINT ck_entity_empty_source_numeric_key_positive
+ CHECK (numeric_key > 0),
+ CONSTRAINT ck_entity_empty_source_numeric_key_claim
+ CHECK (claim_kind IN ('LEGACY_NUMERIC', 'CANONICAL_EMPTY_SOURCE'))
+);
+
+CREATE TABLE entity_empty_selected_source_association (
+ target_namespace VARCHAR(63) NOT NULL,
+ genesis_id UUID NOT NULL,
+ operation_id UUID NOT NULL,
+ fence_id UUID NOT NULL,
+ intake_request_id UUID NOT NULL,
+ canonical_tenant_id UUID NOT NULL,
+ canonical_version_id UUID NOT NULL,
+ selected_commit_id UUID NOT NULL,
+ source_revision_id UUID NOT NULL,
+ source_revision_order VARCHAR(32) NOT NULL,
+ local_tenant_key BIGINT NOT NULL,
+ local_tenant_key_kind VARCHAR(16) NOT NULL DEFAULT 'TENANT',
+ local_tenant_key_claim_kind VARCHAR(32) NOT NULL DEFAULT 'CANONICAL_EMPTY_SOURCE',
+ local_version_key BIGINT NOT NULL,
+ local_version_key_kind VARCHAR(16) NOT NULL DEFAULT 'VERSION',
+ local_version_key_claim_kind VARCHAR(32) NOT NULL DEFAULT 'CANONICAL_EMPTY_SOURCE',
+ request_digest VARCHAR(71) NOT NULL,
+ schema_digest VARCHAR(71) NOT NULL,
+ authorization_binding_digest VARCHAR(71) NOT NULL,
+ selected_source_digest VARCHAR(71) NOT NULL,
+ world_read_request_id UUID NOT NULL,
+ world_read_request_digest VARCHAR(71) NOT NULL,
+ world_closure_digest VARCHAR(71) NOT NULL,
+ receipt_digest VARCHAR(71) NOT NULL,
+ associated_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_entity_empty_selected_source_association
+ PRIMARY KEY (target_namespace, canonical_tenant_id, canonical_version_id),
+ CONSTRAINT uq_entity_empty_selected_source_request
+ UNIQUE (target_namespace, intake_request_id),
+ CONSTRAINT uq_entity_empty_selected_source_operation
+ UNIQUE (target_namespace, operation_id),
+ CONSTRAINT uq_entity_empty_selected_source_genesis
+ UNIQUE (genesis_id),
+ CONSTRAINT uq_entity_empty_selected_source_local_tenant
+ UNIQUE (local_tenant_key),
+ CONSTRAINT uq_entity_empty_selected_source_local_version
+ UNIQUE (local_version_key),
+ CONSTRAINT ck_entity_empty_selected_source_namespace
+ CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'),
+ CONSTRAINT ck_entity_empty_selected_source_ids_nonzero
+ CHECK (
+ genesis_id <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND operation_id <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND fence_id <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND selected_commit_id <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND source_revision_id <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND world_read_request_id <> '00000000-0000-0000-0000-000000000000'::UUID
+ ),
+ CONSTRAINT ck_entity_empty_selected_source_local_keys
+ CHECK (
+ local_tenant_key > 0
+ AND local_version_key > 0
+ AND local_tenant_key <> local_version_key
+ AND local_tenant_key_kind = 'TENANT'
+ AND local_tenant_key_claim_kind = 'CANONICAL_EMPTY_SOURCE'
+ AND local_version_key_kind = 'VERSION'
+ AND local_version_key_claim_kind = 'CANONICAL_EMPTY_SOURCE'
+ ),
+ CONSTRAINT ck_entity_empty_selected_source_revision_order
+ CHECK (source_revision_order ~ '^(0|[1-9][0-9]*)$'),
+ CONSTRAINT ck_entity_empty_selected_source_digests
+ CHECK (
+ request_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND schema_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND world_read_request_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND receipt_digest ~ '^sha256:[0-9a-f]{64}$'
+ ),
+ CONSTRAINT fk_entity_empty_selected_source_tenant_key
+ FOREIGN KEY (local_tenant_key, local_tenant_key_kind, local_tenant_key_claim_kind)
+ REFERENCES entity_empty_source_numeric_key_reservation
+ (numeric_key, key_kind, claim_kind),
+ CONSTRAINT fk_entity_empty_selected_source_version_key
+ FOREIGN KEY (local_version_key, local_version_key_kind, local_version_key_claim_kind)
+ REFERENCES entity_empty_source_numeric_key_reservation
+ (numeric_key, key_kind, claim_kind)
+);
+
+-- These fourteen owner-local providers deliberately support only an explicit EMPTY state.
+-- Each has its own persisted typed table; the receipt family-state ledger is not a provider.
+CREATE TABLE entity_empty_source_other_actor_template_roots (
+ target_namespace VARCHAR(63) NOT NULL,
+ intake_request_id UUID NOT NULL,
+ provider_schema_version SMALLINT NOT NULL,
+ owner_state VARCHAR(16) NOT NULL,
+ row_count BIGINT NOT NULL,
+ reference_count BIGINT NOT NULL,
+ authorization_binding_digest VARCHAR(71) NOT NULL,
+ selected_source_digest VARCHAR(71) NOT NULL,
+ source_revision_binding_digest VARCHAR(71) NOT NULL,
+ world_closure_digest VARCHAR(71) NOT NULL,
+ provider_state_digest VARCHAR(71) NOT NULL,
+ observed_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_entity_empty_source_other_actor_template_roots PRIMARY KEY (target_namespace, intake_request_id),
+ CONSTRAINT fk_entity_empty_source_other_actor_template_roots_association FOREIGN KEY (target_namespace, intake_request_id)
+ REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id)
+ ON DELETE RESTRICT,
+ CONSTRAINT ck_entity_empty_source_other_actor_template_roots_schema CHECK (provider_schema_version = 1),
+ CONSTRAINT ck_entity_empty_source_other_actor_template_roots_state CHECK (owner_state = 'EMPTY'),
+ CONSTRAINT ck_entity_empty_source_other_actor_template_roots_counts CHECK (row_count = 0 AND reference_count = 0),
+ CONSTRAINT ck_entity_empty_source_other_actor_template_roots_digests CHECK (
+ authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$'
+ )
+);
+
+CREATE TABLE entity_empty_source_equipment_capabilities (
+ target_namespace VARCHAR(63) NOT NULL,
+ intake_request_id UUID NOT NULL,
+ provider_schema_version SMALLINT NOT NULL,
+ owner_state VARCHAR(16) NOT NULL,
+ row_count BIGINT NOT NULL,
+ reference_count BIGINT NOT NULL,
+ authorization_binding_digest VARCHAR(71) NOT NULL,
+ selected_source_digest VARCHAR(71) NOT NULL,
+ source_revision_binding_digest VARCHAR(71) NOT NULL,
+ world_closure_digest VARCHAR(71) NOT NULL,
+ provider_state_digest VARCHAR(71) NOT NULL,
+ observed_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_entity_empty_source_equipment_capabilities PRIMARY KEY (target_namespace, intake_request_id),
+ CONSTRAINT fk_entity_empty_source_equipment_capabilities_association FOREIGN KEY (target_namespace, intake_request_id)
+ REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id)
+ ON DELETE RESTRICT,
+ CONSTRAINT ck_entity_empty_source_equipment_capabilities_schema CHECK (provider_schema_version = 1),
+ CONSTRAINT ck_entity_empty_source_equipment_capabilities_state CHECK (owner_state = 'EMPTY'),
+ CONSTRAINT ck_entity_empty_source_equipment_capabilities_counts CHECK (row_count = 0 AND reference_count = 0),
+ CONSTRAINT ck_entity_empty_source_equipment_capabilities_digests CHECK (
+ authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$'
+ )
+);
+
+CREATE TABLE entity_empty_source_equipment_attachment_rules (
+ target_namespace VARCHAR(63) NOT NULL,
+ intake_request_id UUID NOT NULL,
+ provider_schema_version SMALLINT NOT NULL,
+ owner_state VARCHAR(16) NOT NULL,
+ row_count BIGINT NOT NULL,
+ reference_count BIGINT NOT NULL,
+ authorization_binding_digest VARCHAR(71) NOT NULL,
+ selected_source_digest VARCHAR(71) NOT NULL,
+ source_revision_binding_digest VARCHAR(71) NOT NULL,
+ world_closure_digest VARCHAR(71) NOT NULL,
+ provider_state_digest VARCHAR(71) NOT NULL,
+ observed_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_entity_empty_source_equipment_attachment_rules PRIMARY KEY (target_namespace, intake_request_id),
+ CONSTRAINT fk_entity_empty_source_equipment_attachment_rules_association FOREIGN KEY (target_namespace, intake_request_id)
+ REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id)
+ ON DELETE RESTRICT,
+ CONSTRAINT ck_entity_empty_source_equipment_attachment_rules_schema CHECK (provider_schema_version = 1),
+ CONSTRAINT ck_entity_empty_source_equipment_attachment_rules_state CHECK (owner_state = 'EMPTY'),
+ CONSTRAINT ck_entity_empty_source_equipment_attachment_rules_counts CHECK (row_count = 0 AND reference_count = 0),
+ CONSTRAINT ck_entity_empty_source_equipment_attachment_rules_digests CHECK (
+ authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$'
+ )
+);
+
+CREATE TABLE entity_empty_source_equipment_compatibility_rules (
+ target_namespace VARCHAR(63) NOT NULL,
+ intake_request_id UUID NOT NULL,
+ provider_schema_version SMALLINT NOT NULL,
+ owner_state VARCHAR(16) NOT NULL,
+ row_count BIGINT NOT NULL,
+ reference_count BIGINT NOT NULL,
+ authorization_binding_digest VARCHAR(71) NOT NULL,
+ selected_source_digest VARCHAR(71) NOT NULL,
+ source_revision_binding_digest VARCHAR(71) NOT NULL,
+ world_closure_digest VARCHAR(71) NOT NULL,
+ provider_state_digest VARCHAR(71) NOT NULL,
+ observed_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_entity_empty_source_equipment_compatibility_rules PRIMARY KEY (target_namespace, intake_request_id),
+ CONSTRAINT fk_entity_empty_source_equipment_compatibility_rules_association FOREIGN KEY (target_namespace, intake_request_id)
+ REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id)
+ ON DELETE RESTRICT,
+ CONSTRAINT ck_entity_empty_source_equipment_compatibility_rules_schema CHECK (provider_schema_version = 1),
+ CONSTRAINT ck_entity_empty_source_equipment_compatibility_rules_state CHECK (owner_state = 'EMPTY'),
+ CONSTRAINT ck_entity_empty_source_equipment_compatibility_rules_counts CHECK (row_count = 0 AND reference_count = 0),
+ CONSTRAINT ck_entity_empty_source_equipment_compatibility_rules_digests CHECK (
+ authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$'
+ )
+);
+
+CREATE TABLE entity_empty_source_equipment_occupancy_rules (
+ target_namespace VARCHAR(63) NOT NULL,
+ intake_request_id UUID NOT NULL,
+ provider_schema_version SMALLINT NOT NULL,
+ owner_state VARCHAR(16) NOT NULL,
+ row_count BIGINT NOT NULL,
+ reference_count BIGINT NOT NULL,
+ authorization_binding_digest VARCHAR(71) NOT NULL,
+ selected_source_digest VARCHAR(71) NOT NULL,
+ source_revision_binding_digest VARCHAR(71) NOT NULL,
+ world_closure_digest VARCHAR(71) NOT NULL,
+ provider_state_digest VARCHAR(71) NOT NULL,
+ observed_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_entity_empty_source_equipment_occupancy_rules PRIMARY KEY (target_namespace, intake_request_id),
+ CONSTRAINT fk_entity_empty_source_equipment_occupancy_rules_association FOREIGN KEY (target_namespace, intake_request_id)
+ REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id)
+ ON DELETE RESTRICT,
+ CONSTRAINT ck_entity_empty_source_equipment_occupancy_rules_schema CHECK (provider_schema_version = 1),
+ CONSTRAINT ck_entity_empty_source_equipment_occupancy_rules_state CHECK (owner_state = 'EMPTY'),
+ CONSTRAINT ck_entity_empty_source_equipment_occupancy_rules_counts CHECK (row_count = 0 AND reference_count = 0),
+ CONSTRAINT ck_entity_empty_source_equipment_occupancy_rules_digests CHECK (
+ authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$'
+ )
+);
+
+CREATE TABLE entity_empty_source_actor_body_layout_assignments (
+ target_namespace VARCHAR(63) NOT NULL,
+ intake_request_id UUID NOT NULL,
+ provider_schema_version SMALLINT NOT NULL,
+ owner_state VARCHAR(16) NOT NULL,
+ row_count BIGINT NOT NULL,
+ reference_count BIGINT NOT NULL,
+ authorization_binding_digest VARCHAR(71) NOT NULL,
+ selected_source_digest VARCHAR(71) NOT NULL,
+ source_revision_binding_digest VARCHAR(71) NOT NULL,
+ world_closure_digest VARCHAR(71) NOT NULL,
+ provider_state_digest VARCHAR(71) NOT NULL,
+ observed_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_entity_empty_source_actor_body_layout_assignments PRIMARY KEY (target_namespace, intake_request_id),
+ CONSTRAINT fk_entity_empty_source_actor_body_layout_assignments_association FOREIGN KEY (target_namespace, intake_request_id)
+ REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id)
+ ON DELETE RESTRICT,
+ CONSTRAINT ck_entity_empty_source_actor_body_layout_assignments_schema CHECK (provider_schema_version = 1),
+ CONSTRAINT ck_entity_empty_source_actor_body_layout_assignments_state CHECK (owner_state = 'EMPTY'),
+ CONSTRAINT ck_entity_empty_source_actor_body_layout_assignments_counts CHECK (row_count = 0 AND reference_count = 0),
+ CONSTRAINT ck_entity_empty_source_actor_body_layout_assignments_digests CHECK (
+ authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$'
+ )
+);
+
+CREATE TABLE entity_empty_source_loot_table_roots (
+ target_namespace VARCHAR(63) NOT NULL,
+ intake_request_id UUID NOT NULL,
+ provider_schema_version SMALLINT NOT NULL,
+ owner_state VARCHAR(16) NOT NULL,
+ row_count BIGINT NOT NULL,
+ reference_count BIGINT NOT NULL,
+ authorization_binding_digest VARCHAR(71) NOT NULL,
+ selected_source_digest VARCHAR(71) NOT NULL,
+ source_revision_binding_digest VARCHAR(71) NOT NULL,
+ world_closure_digest VARCHAR(71) NOT NULL,
+ provider_state_digest VARCHAR(71) NOT NULL,
+ observed_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_entity_empty_source_loot_table_roots PRIMARY KEY (target_namespace, intake_request_id),
+ CONSTRAINT fk_entity_empty_source_loot_table_roots_association FOREIGN KEY (target_namespace, intake_request_id)
+ REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id)
+ ON DELETE RESTRICT,
+ CONSTRAINT ck_entity_empty_source_loot_table_roots_schema CHECK (provider_schema_version = 1),
+ CONSTRAINT ck_entity_empty_source_loot_table_roots_state CHECK (owner_state = 'EMPTY'),
+ CONSTRAINT ck_entity_empty_source_loot_table_roots_counts CHECK (row_count = 0 AND reference_count = 0),
+ CONSTRAINT ck_entity_empty_source_loot_table_roots_digests CHECK (
+ authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$'
+ )
+);
+
+CREATE TABLE entity_empty_source_loot_item_mappings (
+ target_namespace VARCHAR(63) NOT NULL,
+ intake_request_id UUID NOT NULL,
+ provider_schema_version SMALLINT NOT NULL,
+ owner_state VARCHAR(16) NOT NULL,
+ row_count BIGINT NOT NULL,
+ reference_count BIGINT NOT NULL,
+ authorization_binding_digest VARCHAR(71) NOT NULL,
+ selected_source_digest VARCHAR(71) NOT NULL,
+ source_revision_binding_digest VARCHAR(71) NOT NULL,
+ world_closure_digest VARCHAR(71) NOT NULL,
+ provider_state_digest VARCHAR(71) NOT NULL,
+ observed_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_entity_empty_source_loot_item_mappings PRIMARY KEY (target_namespace, intake_request_id),
+ CONSTRAINT fk_entity_empty_source_loot_item_mappings_association FOREIGN KEY (target_namespace, intake_request_id)
+ REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id)
+ ON DELETE RESTRICT,
+ CONSTRAINT ck_entity_empty_source_loot_item_mappings_schema CHECK (provider_schema_version = 1),
+ CONSTRAINT ck_entity_empty_source_loot_item_mappings_state CHECK (owner_state = 'EMPTY'),
+ CONSTRAINT ck_entity_empty_source_loot_item_mappings_counts CHECK (row_count = 0 AND reference_count = 0),
+ CONSTRAINT ck_entity_empty_source_loot_item_mappings_digests CHECK (
+ authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$'
+ )
+);
+
+CREATE TABLE entity_empty_source_inbound_loot_bindings (
+ target_namespace VARCHAR(63) NOT NULL,
+ intake_request_id UUID NOT NULL,
+ provider_schema_version SMALLINT NOT NULL,
+ owner_state VARCHAR(16) NOT NULL,
+ row_count BIGINT NOT NULL,
+ reference_count BIGINT NOT NULL,
+ authorization_binding_digest VARCHAR(71) NOT NULL,
+ selected_source_digest VARCHAR(71) NOT NULL,
+ source_revision_binding_digest VARCHAR(71) NOT NULL,
+ world_closure_digest VARCHAR(71) NOT NULL,
+ provider_state_digest VARCHAR(71) NOT NULL,
+ observed_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_entity_empty_source_inbound_loot_bindings PRIMARY KEY (target_namespace, intake_request_id),
+ CONSTRAINT fk_entity_empty_source_inbound_loot_bindings_association FOREIGN KEY (target_namespace, intake_request_id)
+ REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id)
+ ON DELETE RESTRICT,
+ CONSTRAINT ck_entity_empty_source_inbound_loot_bindings_schema CHECK (provider_schema_version = 1),
+ CONSTRAINT ck_entity_empty_source_inbound_loot_bindings_state CHECK (owner_state = 'EMPTY'),
+ CONSTRAINT ck_entity_empty_source_inbound_loot_bindings_counts CHECK (row_count = 0 AND reference_count = 0),
+ CONSTRAINT ck_entity_empty_source_inbound_loot_bindings_digests CHECK (
+ authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$'
+ )
+);
+
+CREATE TABLE entity_empty_source_balance_curve_roots (
+ target_namespace VARCHAR(63) NOT NULL,
+ intake_request_id UUID NOT NULL,
+ provider_schema_version SMALLINT NOT NULL,
+ owner_state VARCHAR(16) NOT NULL,
+ row_count BIGINT NOT NULL,
+ reference_count BIGINT NOT NULL,
+ authorization_binding_digest VARCHAR(71) NOT NULL,
+ selected_source_digest VARCHAR(71) NOT NULL,
+ source_revision_binding_digest VARCHAR(71) NOT NULL,
+ world_closure_digest VARCHAR(71) NOT NULL,
+ provider_state_digest VARCHAR(71) NOT NULL,
+ observed_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_entity_empty_source_balance_curve_roots PRIMARY KEY (target_namespace, intake_request_id),
+ CONSTRAINT fk_entity_empty_source_balance_curve_roots_association FOREIGN KEY (target_namespace, intake_request_id)
+ REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id)
+ ON DELETE RESTRICT,
+ CONSTRAINT ck_entity_empty_source_balance_curve_roots_schema CHECK (provider_schema_version = 1),
+ CONSTRAINT ck_entity_empty_source_balance_curve_roots_state CHECK (owner_state = 'EMPTY'),
+ CONSTRAINT ck_entity_empty_source_balance_curve_roots_counts CHECK (row_count = 0 AND reference_count = 0),
+ CONSTRAINT ck_entity_empty_source_balance_curve_roots_digests CHECK (
+ authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$'
+ )
+);
+
+CREATE TABLE entity_empty_source_balance_curve_attachments (
+ target_namespace VARCHAR(63) NOT NULL,
+ intake_request_id UUID NOT NULL,
+ provider_schema_version SMALLINT NOT NULL,
+ owner_state VARCHAR(16) NOT NULL,
+ row_count BIGINT NOT NULL,
+ reference_count BIGINT NOT NULL,
+ authorization_binding_digest VARCHAR(71) NOT NULL,
+ selected_source_digest VARCHAR(71) NOT NULL,
+ source_revision_binding_digest VARCHAR(71) NOT NULL,
+ world_closure_digest VARCHAR(71) NOT NULL,
+ provider_state_digest VARCHAR(71) NOT NULL,
+ observed_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_entity_empty_source_balance_curve_attachments PRIMARY KEY (target_namespace, intake_request_id),
+ CONSTRAINT fk_entity_empty_source_balance_curve_attachments_association FOREIGN KEY (target_namespace, intake_request_id)
+ REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id)
+ ON DELETE RESTRICT,
+ CONSTRAINT ck_entity_empty_source_balance_curve_attachments_schema CHECK (provider_schema_version = 1),
+ CONSTRAINT ck_entity_empty_source_balance_curve_attachments_state CHECK (owner_state = 'EMPTY'),
+ CONSTRAINT ck_entity_empty_source_balance_curve_attachments_counts CHECK (row_count = 0 AND reference_count = 0),
+ CONSTRAINT ck_entity_empty_source_balance_curve_attachments_digests CHECK (
+ authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$'
+ )
+);
+
+CREATE TABLE entity_empty_source_archetype_roots (
+ target_namespace VARCHAR(63) NOT NULL,
+ intake_request_id UUID NOT NULL,
+ provider_schema_version SMALLINT NOT NULL,
+ owner_state VARCHAR(16) NOT NULL,
+ row_count BIGINT NOT NULL,
+ reference_count BIGINT NOT NULL,
+ authorization_binding_digest VARCHAR(71) NOT NULL,
+ selected_source_digest VARCHAR(71) NOT NULL,
+ source_revision_binding_digest VARCHAR(71) NOT NULL,
+ world_closure_digest VARCHAR(71) NOT NULL,
+ provider_state_digest VARCHAR(71) NOT NULL,
+ observed_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_entity_empty_source_archetype_roots PRIMARY KEY (target_namespace, intake_request_id),
+ CONSTRAINT fk_entity_empty_source_archetype_roots_association FOREIGN KEY (target_namespace, intake_request_id)
+ REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id)
+ ON DELETE RESTRICT,
+ CONSTRAINT ck_entity_empty_source_archetype_roots_schema CHECK (provider_schema_version = 1),
+ CONSTRAINT ck_entity_empty_source_archetype_roots_state CHECK (owner_state = 'EMPTY'),
+ CONSTRAINT ck_entity_empty_source_archetype_roots_counts CHECK (row_count = 0 AND reference_count = 0),
+ CONSTRAINT ck_entity_empty_source_archetype_roots_digests CHECK (
+ authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$'
+ )
+);
+
+CREATE TABLE entity_empty_source_archetype_constraints (
+ target_namespace VARCHAR(63) NOT NULL,
+ intake_request_id UUID NOT NULL,
+ provider_schema_version SMALLINT NOT NULL,
+ owner_state VARCHAR(16) NOT NULL,
+ row_count BIGINT NOT NULL,
+ reference_count BIGINT NOT NULL,
+ authorization_binding_digest VARCHAR(71) NOT NULL,
+ selected_source_digest VARCHAR(71) NOT NULL,
+ source_revision_binding_digest VARCHAR(71) NOT NULL,
+ world_closure_digest VARCHAR(71) NOT NULL,
+ provider_state_digest VARCHAR(71) NOT NULL,
+ observed_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_entity_empty_source_archetype_constraints PRIMARY KEY (target_namespace, intake_request_id),
+ CONSTRAINT fk_entity_empty_source_archetype_constraints_association FOREIGN KEY (target_namespace, intake_request_id)
+ REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id)
+ ON DELETE RESTRICT,
+ CONSTRAINT ck_entity_empty_source_archetype_constraints_schema CHECK (provider_schema_version = 1),
+ CONSTRAINT ck_entity_empty_source_archetype_constraints_state CHECK (owner_state = 'EMPTY'),
+ CONSTRAINT ck_entity_empty_source_archetype_constraints_counts CHECK (row_count = 0 AND reference_count = 0),
+ CONSTRAINT ck_entity_empty_source_archetype_constraints_digests CHECK (
+ authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$'
+ )
+);
+
+CREATE TABLE entity_empty_source_archetype_assignments (
+ target_namespace VARCHAR(63) NOT NULL,
+ intake_request_id UUID NOT NULL,
+ provider_schema_version SMALLINT NOT NULL,
+ owner_state VARCHAR(16) NOT NULL,
+ row_count BIGINT NOT NULL,
+ reference_count BIGINT NOT NULL,
+ authorization_binding_digest VARCHAR(71) NOT NULL,
+ selected_source_digest VARCHAR(71) NOT NULL,
+ source_revision_binding_digest VARCHAR(71) NOT NULL,
+ world_closure_digest VARCHAR(71) NOT NULL,
+ provider_state_digest VARCHAR(71) NOT NULL,
+ observed_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_entity_empty_source_archetype_assignments PRIMARY KEY (target_namespace, intake_request_id),
+ CONSTRAINT fk_entity_empty_source_archetype_assignments_association FOREIGN KEY (target_namespace, intake_request_id)
+ REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id)
+ ON DELETE RESTRICT,
+ CONSTRAINT ck_entity_empty_source_archetype_assignments_schema CHECK (provider_schema_version = 1),
+ CONSTRAINT ck_entity_empty_source_archetype_assignments_state CHECK (owner_state = 'EMPTY'),
+ CONSTRAINT ck_entity_empty_source_archetype_assignments_counts CHECK (row_count = 0 AND reference_count = 0),
+ CONSTRAINT ck_entity_empty_source_archetype_assignments_digests CHECK (
+ authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$'
+ )
+);
+CREATE TABLE entity_empty_selected_source_family_state (
+ target_namespace VARCHAR(63) NOT NULL,
+ intake_request_id UUID NOT NULL,
+ family_name VARCHAR(64) NOT NULL,
+ owner_state VARCHAR(16) NOT NULL,
+ evidence_kind VARCHAR(32) NOT NULL,
+ row_count BIGINT NOT NULL,
+ unqualified_row_count BIGINT NOT NULL,
+ retained_row_count BIGINT NOT NULL,
+ selected_scope_row_count BIGINT NOT NULL,
+ reference_count BIGINT NOT NULL,
+ CONSTRAINT pk_entity_empty_selected_source_family_state
+ PRIMARY KEY (target_namespace, intake_request_id, family_name),
+ CONSTRAINT fk_entity_empty_selected_source_family_association
+ FOREIGN KEY (target_namespace, intake_request_id)
+ REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id)
+ ON DELETE RESTRICT,
+ CONSTRAINT ck_entity_empty_selected_source_family_name
+ CHECK (family_name IN (
+ 'ACTOR_BODY_LAYOUT_ASSIGNMENTS',
+ 'ARCHETYPE_ASSIGNMENTS',
+ 'ARCHETYPE_CONSTRAINTS',
+ 'ARCHETYPE_ROOTS',
+ 'BALANCE_CURVE_ATTACHMENTS',
+ 'BALANCE_CURVE_ROOTS',
+ 'BODY_LAYOUT_MEMBERSHIPS',
+ 'BODY_LAYOUT_ROOTS',
+ 'CRAFTING_INGREDIENT_BINDINGS',
+ 'CRAFTING_RECIPE_RESULT_BINDINGS',
+ 'CRAFTING_RECIPE_ROOTS',
+ 'EQUIPMENT_ATTACHMENT_RULES',
+ 'EQUIPMENT_CAPABILITIES',
+ 'EQUIPMENT_COMPATIBILITY_RULES',
+ 'EQUIPMENT_OCCUPANCY_RULES',
+ 'EQUIPMENT_SLOT_GROUPS',
+ 'EQUIPMENT_SLOT_ROOTS',
+ 'INBOUND_LOOT_BINDINGS',
+ 'ITEM_TEMPLATE_ROOTS',
+ 'LOOT_ITEM_MAPPINGS',
+ 'LOOT_TABLE_ROOTS',
+ 'NPC_TEMPLATE_ROOTS',
+ 'OTHER_ACTOR_TEMPLATE_ROOTS'
+ )),
+ CONSTRAINT ck_entity_empty_selected_source_family_state
+ CHECK (owner_state = 'EMPTY'),
+ CONSTRAINT ck_entity_empty_selected_source_family_evidence_kind
+ CHECK (
+ (family_name IN (
+ 'ITEM_TEMPLATE_ROOTS', 'NPC_TEMPLATE_ROOTS', 'CRAFTING_RECIPE_ROOTS',
+ 'CRAFTING_RECIPE_RESULT_BINDINGS', 'CRAFTING_INGREDIENT_BINDINGS',
+ 'EQUIPMENT_SLOT_ROOTS', 'EQUIPMENT_SLOT_GROUPS', 'BODY_LAYOUT_ROOTS',
+ 'BODY_LAYOUT_MEMBERSHIPS'
+ ) AND evidence_kind = 'V1_SOURCE_CENSUS')
+ OR (family_name IN (
+ 'ACTOR_BODY_LAYOUT_ASSIGNMENTS', 'ARCHETYPE_ASSIGNMENTS',
+ 'ARCHETYPE_CONSTRAINTS', 'ARCHETYPE_ROOTS', 'BALANCE_CURVE_ATTACHMENTS',
+ 'BALANCE_CURVE_ROOTS', 'EQUIPMENT_ATTACHMENT_RULES',
+ 'EQUIPMENT_CAPABILITIES', 'EQUIPMENT_COMPATIBILITY_RULES',
+ 'EQUIPMENT_OCCUPANCY_RULES', 'INBOUND_LOOT_BINDINGS', 'LOOT_ITEM_MAPPINGS',
+ 'LOOT_TABLE_ROOTS', 'OTHER_ACTOR_TEMPLATE_ROOTS'
+ ) AND evidence_kind = 'EMPTY_ONLY_OWNER_PROVIDER')
+ ),
+ CONSTRAINT ck_entity_empty_selected_source_family_counts
+ CHECK (
+ row_count = 0
+ AND unqualified_row_count = 0
+ AND retained_row_count = 0
+ AND selected_scope_row_count = 0
+ AND reference_count = 0
+ )
+);
+
+CREATE TABLE entity_empty_selected_source_receipt (
+ target_namespace VARCHAR(63) NOT NULL,
+ intake_request_id UUID NOT NULL,
+ request_digest VARCHAR(71) NOT NULL,
+ schema_digest VARCHAR(71) NOT NULL,
+ receipt_digest VARCHAR(71) NOT NULL,
+ receipt_bytes BYTEA NOT NULL,
+ retained_at TIMESTAMPTZ NOT NULL,
+ CONSTRAINT pk_entity_empty_selected_source_receipt
+ PRIMARY KEY (target_namespace, intake_request_id),
+ CONSTRAINT fk_entity_empty_selected_source_receipt_association
+ FOREIGN KEY (target_namespace, intake_request_id)
+ REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id)
+ ON DELETE RESTRICT,
+ CONSTRAINT ck_entity_empty_selected_source_receipt_digests
+ CHECK (
+ request_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND schema_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND receipt_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND octet_length(receipt_bytes) BETWEEN 1 AND 83886080
+ )
+);
+
+CREATE INDEX idx_entity_empty_source_key_claim_kind
+ ON entity_empty_source_numeric_key_reservation (claim_kind, key_kind, numeric_key);
+
+/* [jooq ignore start] */
+CREATE FUNCTION entity_source_positive_numeric_key(value_text TEXT)
+RETURNS BIGINT
+LANGUAGE plpgsql
+IMMUTABLE
+STRICT
+SET search_path = pg_catalog
+AS $$
+DECLARE
+ parsed_value NUMERIC;
+BEGIN
+ IF value_text !~ '^[0-9]+$' THEN
+ RETURN NULL;
+ END IF;
+ parsed_value := value_text::NUMERIC;
+ IF parsed_value <= 0 OR parsed_value > 9223372036854775807 THEN
+ RETURN NULL;
+ END IF;
+ RETURN parsed_value::BIGINT;
+END;
+$$;
+/* [jooq ignore stop] */
+
+-- Lock the receipt/key tables first and then every V1 tenant/version holder and source/reference
+-- relation. This both seeds real occupied keys and closes insert/update phantoms for the same
+-- fixed order used by the owner-local founding transaction.
+/* [jooq ignore start] */
+LOCK TABLE entity_empty_source_numeric_key_reservation,
+ entity_empty_selected_source_association,
+ entity_empty_selected_source_family_state,
+ entity_empty_selected_source_receipt,
+ entity_empty_source_other_actor_template_roots,
+ entity_empty_source_equipment_capabilities,
+ entity_empty_source_equipment_attachment_rules,
+ entity_empty_source_equipment_compatibility_rules,
+ entity_empty_source_equipment_occupancy_rules,
+ entity_empty_source_actor_body_layout_assignments,
+ entity_empty_source_loot_table_roots,
+ entity_empty_source_loot_item_mappings,
+ entity_empty_source_inbound_loot_bindings,
+ entity_empty_source_balance_curve_roots,
+ entity_empty_source_balance_curve_attachments,
+ entity_empty_source_archetype_roots,
+ entity_empty_source_archetype_constraints,
+ entity_empty_source_archetype_assignments
+ IN SHARE ROW EXCLUSIVE MODE;
+/* [jooq ignore stop] */
+/* [jooq ignore start] */
+LOCK TABLE actor_active_conditions, actor_resource_states, body_layout_slot_definitions,
+ character_equipment, character_friend, characters, container_instances,
+ crafting_ingredients, crafting_recipes, entity_mutation_effects,
+ equipment_slot_definitions, inventory, item_instances, item_stacks,
+ item_transfer_audits, item_visible_ref_counters, items, npcs, room_ground_inventory
+ IN SHARE MODE;
+/* [jooq ignore stop] */
+
+/* [jooq ignore start] */
+INSERT INTO entity_empty_source_numeric_key_reservation (key_kind, numeric_key, claim_kind)
+SELECT DISTINCT key_kind, numeric_key, 'LEGACY_NUMERIC'
+FROM (
+ SELECT 'TENANT'::VARCHAR(16) AS key_kind, tenant_id AS numeric_key FROM characters
+ UNION ALL SELECT 'TENANT', tenant_id FROM npcs
+ UNION ALL SELECT 'TENANT', tenant_id FROM items
+ UNION ALL SELECT 'TENANT', tenant_id FROM crafting_recipes
+ UNION ALL SELECT 'TENANT', tenant_id FROM character_friend
+ UNION ALL SELECT 'TENANT', tenant_id FROM room_ground_inventory
+ UNION ALL SELECT 'TENANT', tenant_id FROM container_instances
+ UNION ALL SELECT 'TENANT', tenant_id FROM item_instances
+ UNION ALL SELECT 'TENANT', tenant_id FROM item_visible_ref_counters
+ UNION ALL SELECT 'TENANT', tenant_id FROM item_stacks
+ UNION ALL SELECT 'TENANT', tenant_id FROM entity_mutation_effects
+ UNION ALL SELECT 'TENANT', tenant_id FROM item_transfer_audits
+ UNION ALL SELECT 'TENANT', tenant_id FROM equipment_slot_definitions
+ UNION ALL SELECT 'TENANT', tenant_id FROM body_layout_slot_definitions
+ UNION ALL SELECT 'TENANT', tenant_id FROM actor_resource_states
+ UNION ALL SELECT 'TENANT', tenant_id FROM actor_active_conditions
+ UNION ALL SELECT 'VERSION', version_id FROM items
+ UNION ALL SELECT 'VERSION', version_id FROM npcs
+ UNION ALL SELECT 'VERSION', version_id FROM crafting_recipes
+ UNION ALL SELECT 'VERSION', version_id FROM equipment_slot_definitions
+ UNION ALL SELECT 'VERSION', version_id FROM body_layout_slot_definitions
+) AS existing_entity_keys
+WHERE numeric_key > 0
+ON CONFLICT (key_kind, numeric_key) DO NOTHING;
+/* [jooq ignore stop] */
+
+/* [jooq ignore start] */
+DO $entity_empty_source_functions$
+DECLARE
+ owner_schema TEXT := current_schema();
+BEGIN
+ IF owner_schema IS NULL THEN
+ RAISE EXCEPTION 'Entity empty-source functions require an explicit installation schema';
+ END IF;
+
+ EXECUTE format($function$
+ CREATE FUNCTION %I.entity_require_source_numeric_key_unreserved(
+ requested_kind TEXT, requested_key BIGINT
+ ) RETURNS VOID
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path = pg_catalog, %I
+ AS $body$
+ DECLARE
+ retained_claim TEXT;
+ BEGIN
+ IF requested_key IS NULL OR requested_key <= 0 THEN
+ RETURN;
+ END IF;
+ SELECT claim_kind INTO retained_claim
+ FROM %I.entity_empty_source_numeric_key_reservation
+ WHERE key_kind = requested_kind AND numeric_key = requested_key;
+ IF retained_claim = 'CANONICAL_EMPTY_SOURCE' THEN
+ RAISE EXCEPTION 'Entity numeric source key is reserved by an immutable empty-source receipt';
+ END IF;
+ END;
+ $body$
+ $function$, owner_schema, owner_schema, owner_schema);
+
+ EXECUTE format($function$
+ CREATE FUNCTION %I.entity_guard_source_owner_row()
+ RETURNS TRIGGER
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path = pg_catalog, %I
+ AS $body$
+ DECLARE
+ old_value JSONB;
+ new_value JSONB;
+ old_tenant_key BIGINT;
+ new_tenant_key BIGINT;
+ old_version_key BIGINT;
+ new_version_key BIGINT;
+ BEGIN
+ IF TG_OP IN ('UPDATE', 'DELETE') THEN
+ old_value := to_jsonb(OLD);
+ old_tenant_key := %I.entity_source_positive_numeric_key(old_value->>'tenant_id');
+ old_version_key := %I.entity_source_positive_numeric_key(old_value->>'version_id');
+ PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', old_tenant_key);
+ PERFORM %I.entity_require_source_numeric_key_unreserved('VERSION', old_version_key);
+ END IF;
+ IF TG_OP IN ('INSERT', 'UPDATE') THEN
+ new_value := to_jsonb(NEW);
+ new_tenant_key := %I.entity_source_positive_numeric_key(new_value->>'tenant_id');
+ new_version_key := %I.entity_source_positive_numeric_key(new_value->>'version_id');
+ PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', new_tenant_key);
+ PERFORM %I.entity_require_source_numeric_key_unreserved('VERSION', new_version_key);
+ END IF;
+ IF TG_OP = 'DELETE' THEN
+ RETURN OLD;
+ END IF;
+ RETURN NEW;
+ END;
+ $body$
+ $function$, owner_schema, owner_schema, owner_schema, owner_schema,
+ owner_schema, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema);
+
+ EXECUTE format($function$
+ CREATE FUNCTION %I.entity_guard_character_template_reference()
+ RETURNS TRIGGER
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path = pg_catalog, %I
+ AS $body$
+ DECLARE
+ old_character_id BIGINT;
+ new_character_id BIGINT;
+ referenced_tenant BIGINT;
+ BEGIN
+ IF TG_OP IN ('UPDATE', 'DELETE') THEN
+ old_character_id := (to_jsonb(OLD)->>'character_id')::BIGINT;
+ SELECT tenant_id INTO referenced_tenant FROM %I.characters WHERE id = old_character_id;
+ IF NOT FOUND THEN
+ RAISE EXCEPTION 'Entity character reference owner is unavailable';
+ END IF;
+ PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant);
+ END IF;
+ IF TG_OP IN ('INSERT', 'UPDATE') THEN
+ new_character_id := (to_jsonb(NEW)->>'character_id')::BIGINT;
+ SELECT tenant_id INTO referenced_tenant FROM %I.characters WHERE id = new_character_id;
+ IF NOT FOUND THEN
+ RAISE EXCEPTION 'Entity character reference owner is unavailable';
+ END IF;
+ PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant);
+ END IF;
+ IF TG_OP = 'DELETE' THEN
+ RETURN OLD;
+ END IF;
+ RETURN NEW;
+ END;
+ $body$
+ $function$, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema);
+
+ EXECUTE format($function$
+ CREATE FUNCTION %I.entity_guard_recipe_ingredient_reference()
+ RETURNS TRIGGER
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path = pg_catalog, %I
+ AS $body$
+ DECLARE
+ old_recipe_id BIGINT;
+ new_recipe_id BIGINT;
+ referenced_tenant BIGINT;
+ referenced_version BIGINT;
+ BEGIN
+ IF TG_OP IN ('UPDATE', 'DELETE') THEN
+ old_recipe_id := (to_jsonb(OLD)->>'recipe_id')::BIGINT;
+ SELECT tenant_id, version_id INTO referenced_tenant, referenced_version
+ FROM %I.crafting_recipes WHERE id = old_recipe_id;
+ IF NOT FOUND THEN
+ RAISE EXCEPTION 'Entity crafting recipe reference owner is unavailable';
+ END IF;
+ PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant);
+ PERFORM %I.entity_require_source_numeric_key_unreserved('VERSION', referenced_version);
+ END IF;
+ IF TG_OP IN ('INSERT', 'UPDATE') THEN
+ new_recipe_id := (to_jsonb(NEW)->>'recipe_id')::BIGINT;
+ SELECT tenant_id, version_id INTO referenced_tenant, referenced_version
+ FROM %I.crafting_recipes WHERE id = new_recipe_id;
+ IF NOT FOUND THEN
+ RAISE EXCEPTION 'Entity crafting recipe reference owner is unavailable';
+ END IF;
+ PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant);
+ PERFORM %I.entity_require_source_numeric_key_unreserved('VERSION', referenced_version);
+ END IF;
+ IF TG_OP = 'DELETE' THEN
+ RETURN OLD;
+ END IF;
+ RETURN NEW;
+ END;
+ $body$
+ $function$, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema,
+ owner_schema, owner_schema, owner_schema);
+
+ EXECUTE format($function$
+ CREATE FUNCTION %I.entity_reject_source_truncate()
+ RETURNS TRIGGER
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path = pg_catalog, %I
+ AS $body$
+ BEGIN
+ IF EXISTS (
+ SELECT 1 FROM %I.entity_empty_source_numeric_key_reservation
+ WHERE claim_kind = 'CANONICAL_EMPTY_SOURCE'
+ ) THEN
+ RAISE EXCEPTION 'Entity authored-source TRUNCATE is forbidden after canonical intake';
+ END IF;
+ RETURN NULL;
+ END;
+ $body$
+ $function$, owner_schema, owner_schema, owner_schema);
+
+ EXECUTE format($function$
+ CREATE FUNCTION %I.entity_reject_empty_source_record_mutation()
+ RETURNS TRIGGER
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path = pg_catalog, %I
+ AS $body$
+ BEGIN
+ RAISE EXCEPTION 'Entity empty-source intake records are immutable';
+ END;
+ $body$
+ $function$, owner_schema, owner_schema);
+END;
+$entity_empty_source_functions$;
+/* [jooq ignore stop] */
+
+/* [jooq ignore start] */
+REVOKE ALL ON FUNCTION entity_source_positive_numeric_key(TEXT) FROM PUBLIC;
+REVOKE ALL ON FUNCTION entity_require_source_numeric_key_unreserved(TEXT, BIGINT) FROM PUBLIC;
+REVOKE ALL ON FUNCTION entity_guard_source_owner_row() FROM PUBLIC;
+REVOKE ALL ON FUNCTION entity_guard_character_template_reference() FROM PUBLIC;
+REVOKE ALL ON FUNCTION entity_guard_recipe_ingredient_reference() FROM PUBLIC;
+REVOKE ALL ON FUNCTION entity_reject_source_truncate() FROM PUBLIC;
+REVOKE ALL ON FUNCTION entity_reject_empty_source_record_mutation() FROM PUBLIC;
+
+CREATE TRIGGER trg_entity_items_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON items
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row();
+CREATE TRIGGER trg_entity_npcs_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON npcs
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row();
+CREATE TRIGGER trg_entity_recipes_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON crafting_recipes
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row();
+CREATE TRIGGER trg_entity_equipment_slots_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON equipment_slot_definitions
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row();
+CREATE TRIGGER trg_entity_body_layouts_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON body_layout_slot_definitions
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row();
+
+CREATE TRIGGER trg_entity_character_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON characters
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row();
+CREATE TRIGGER trg_entity_character_friend_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON character_friend
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row();
+CREATE TRIGGER trg_entity_room_ground_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON room_ground_inventory
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row();
+CREATE TRIGGER trg_entity_container_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON container_instances
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row();
+CREATE TRIGGER trg_entity_item_instance_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON item_instances
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row();
+CREATE TRIGGER trg_entity_item_stack_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON item_stacks
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row();
+CREATE TRIGGER trg_entity_item_audit_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON item_transfer_audits
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row();
+CREATE TRIGGER trg_entity_item_reference_counter_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON item_visible_ref_counters
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row();
+CREATE TRIGGER trg_entity_mutation_effect_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON entity_mutation_effects
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row();
+CREATE TRIGGER trg_entity_actor_resource_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON actor_resource_states
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row();
+CREATE TRIGGER trg_entity_actor_condition_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON actor_active_conditions
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row();
+
+CREATE TRIGGER trg_entity_inventory_character_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON inventory
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_character_template_reference();
+CREATE TRIGGER trg_entity_character_equipment_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON character_equipment
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_character_template_reference();
+CREATE TRIGGER trg_entity_crafting_ingredient_source_reservation
+ BEFORE INSERT OR UPDATE OR DELETE ON crafting_ingredients
+ FOR EACH ROW EXECUTE FUNCTION entity_guard_recipe_ingredient_reference();
+
+CREATE TRIGGER trg_entity_items_source_no_truncate
+ BEFORE TRUNCATE ON items
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate();
+CREATE TRIGGER trg_entity_npcs_source_no_truncate
+ BEFORE TRUNCATE ON npcs
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate();
+CREATE TRIGGER trg_entity_recipes_source_no_truncate
+ BEFORE TRUNCATE ON crafting_recipes
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate();
+CREATE TRIGGER trg_entity_ingredients_source_no_truncate
+ BEFORE TRUNCATE ON crafting_ingredients
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate();
+CREATE TRIGGER trg_entity_equipment_slots_source_no_truncate
+ BEFORE TRUNCATE ON equipment_slot_definitions
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate();
+CREATE TRIGGER trg_entity_body_layouts_source_no_truncate
+ BEFORE TRUNCATE ON body_layout_slot_definitions
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate();
+
+CREATE TRIGGER trg_entity_empty_source_key_reservation_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_source_numeric_key_reservation
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_key_reservation_no_truncate
+ BEFORE TRUNCATE ON entity_empty_source_numeric_key_reservation
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_association_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_selected_source_association
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_association_no_truncate
+ BEFORE TRUNCATE ON entity_empty_selected_source_association
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_family_state_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_selected_source_family_state
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_family_state_no_truncate
+ BEFORE TRUNCATE ON entity_empty_selected_source_family_state
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_receipt_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_selected_source_receipt
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_receipt_no_truncate
+ BEFORE TRUNCATE ON entity_empty_selected_source_receipt
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_other_actor_template_roots_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_source_other_actor_template_roots
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_other_actor_template_roots_no_truncate
+ BEFORE TRUNCATE ON entity_empty_source_other_actor_template_roots
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_equipment_capabilities_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_source_equipment_capabilities
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_equipment_capabilities_no_truncate
+ BEFORE TRUNCATE ON entity_empty_source_equipment_capabilities
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_equipment_attachment_rules_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_source_equipment_attachment_rules
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_equipment_attachment_rules_no_truncate
+ BEFORE TRUNCATE ON entity_empty_source_equipment_attachment_rules
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_equipment_compatibility_rules_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_source_equipment_compatibility_rules
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_equipment_compatibility_rules_no_truncate
+ BEFORE TRUNCATE ON entity_empty_source_equipment_compatibility_rules
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_equipment_occupancy_rules_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_source_equipment_occupancy_rules
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_equipment_occupancy_rules_no_truncate
+ BEFORE TRUNCATE ON entity_empty_source_equipment_occupancy_rules
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_actor_body_layout_assignments_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_source_actor_body_layout_assignments
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_actor_body_layout_assignments_no_truncate
+ BEFORE TRUNCATE ON entity_empty_source_actor_body_layout_assignments
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_loot_table_roots_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_source_loot_table_roots
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_loot_table_roots_no_truncate
+ BEFORE TRUNCATE ON entity_empty_source_loot_table_roots
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_loot_item_mappings_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_source_loot_item_mappings
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_loot_item_mappings_no_truncate
+ BEFORE TRUNCATE ON entity_empty_source_loot_item_mappings
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_inbound_loot_bindings_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_source_inbound_loot_bindings
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_inbound_loot_bindings_no_truncate
+ BEFORE TRUNCATE ON entity_empty_source_inbound_loot_bindings
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_balance_curve_roots_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_source_balance_curve_roots
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_balance_curve_roots_no_truncate
+ BEFORE TRUNCATE ON entity_empty_source_balance_curve_roots
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_balance_curve_attachments_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_source_balance_curve_attachments
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_balance_curve_attachments_no_truncate
+ BEFORE TRUNCATE ON entity_empty_source_balance_curve_attachments
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_archetype_roots_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_source_archetype_roots
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_archetype_roots_no_truncate
+ BEFORE TRUNCATE ON entity_empty_source_archetype_roots
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_archetype_constraints_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_source_archetype_constraints
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_archetype_constraints_no_truncate
+ BEFORE TRUNCATE ON entity_empty_source_archetype_constraints
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_archetype_assignments_immutable
+ BEFORE UPDATE OR DELETE ON entity_empty_source_archetype_assignments
+ FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+CREATE TRIGGER trg_entity_empty_source_archetype_assignments_no_truncate
+ BEFORE TRUNCATE ON entity_empty_source_archetype_assignments
+ FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation();
+/* [jooq ignore stop] */
diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java
index df51b1a7b4..e1d4434505 100644
--- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java
+++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java
@@ -461,7 +461,7 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() {
.extracting(migration -> migration.getVersion().getVersion())
.containsExactly(
"1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009",
- "1010");
+ "1010", "1011");
assertThat(flyway.info().applied())
.filteredOn(migration -> migration.getVersion() != null)
.extracting(migration -> migration.getScript())
@@ -477,9 +477,10 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() {
"V1007__preseeded_assignment_owner_snapshot.sql",
"V1008__canonical_gameplay_roster_snapshots.sql",
"V1009__canonical_publication_uuid_actor_evidence.sql",
- "V1010__canonical_roster_owner_counters.sql");
+ "V1010__canonical_roster_owner_counters.sql",
+ "V1011__fresh_selected_empty_source_catalogue.sql");
assertThat(flyway.info().current().getVersion())
- .isEqualTo(MigrationVersion.fromVersion("1010"));
+ .isEqualTo(MigrationVersion.fromVersion("1011"));
assertThat(flyway.info().applied())
.extracting(migration -> migration.getState())
.doesNotContain(MigrationState.OUT_OF_ORDER);
@@ -552,7 +553,7 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro
.extracting(MigrationHistoryEntry::version)
.containsExactly(
"1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009",
- "1010");
+ "1010", "1011");
assertThat(upgradedHistory)
.extracting(MigrationHistoryEntry::script)
.containsExactly(
@@ -567,7 +568,8 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro
"V1007__preseeded_assignment_owner_snapshot.sql",
"V1008__canonical_gameplay_roster_snapshots.sql",
"V1009__canonical_publication_uuid_actor_evidence.sql",
- "V1010__canonical_roster_owner_counters.sql");
+ "V1010__canonical_roster_owner_counters.sql",
+ "V1011__fresh_selected_empty_source_catalogue.sql");
assertThat(upgradedHistory).allSatisfy(entry -> assertThat(entry.success()).isTrue());
try (Connection connection = connectToMigrationSchema();
@@ -830,7 +832,7 @@ private void migrateLegacySchemaToLatest() {
assertThat(upgradeFlyway.getConfiguration().isOutOfOrder()).isFalse();
upgradeFlyway.migrate();
assertThat(upgradeFlyway.info().current().getVersion())
- .isEqualTo(MigrationVersion.fromVersion("1010"));
+ .isEqualTo(MigrationVersion.fromVersion("1011"));
assertThat(upgradeFlyway.info().applied())
.extracting(migration -> migration.getState())
.doesNotContain(MigrationState.OUT_OF_ORDER);
diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java
new file mode 100644
index 0000000000..41f1550fbb
--- /dev/null
+++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java
@@ -0,0 +1,222 @@
+package net.firedevops.firemud.entitymanagement.repository;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import net.firedevops.firemud.test.TestContainerImages;
+import org.flywaydb.core.Flyway;
+import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension;
+import org.jooq.DSLContext;
+import org.jooq.SQLDialect;
+import org.jooq.exception.DataAccessException;
+import org.jooq.impl.DSL;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.testcontainers.containers.PostgreSQLContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+/** PostgreSQL proof for V1011's actual-parent legacy-key seed and retained-key writer guards. */
+@Testcontainers(disabledWithoutDocker = true)
+@SuppressWarnings("resource")
+class EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest {
+ private static final String MIGRATION_LOCATION =
+ "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize();
+
+ @Container
+ static PostgreSQLContainer> postgres =
+ new PostgreSQLContainer<>(TestContainerImages.postgres());
+
+ private String schema;
+ private DSLContext dsl;
+
+ @BeforeEach
+ void seedLegacyRowsBeforeV1011() {
+ schema = "entity_empty_source_" + UUID.randomUUID().toString().replace("-", "");
+ DriverManagerDataSource dataSource = dataSource(schema);
+ var legacyFlywayConfiguration =
+ Flyway.configure()
+ .dataSource(dataSource)
+ .locations(MIGRATION_LOCATION, "classpath:db/migration/saga")
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema))
+ .target("1010");
+ legacyFlywayConfiguration
+ .getConfigurationExtension(PostgreSQLConfigurationExtension.class)
+ .setTransactionalLock(false);
+ legacyFlywayConfiguration.load().migrate();
+
+ DSLContext legacyDsl = DSL.using(dataSource, SQLDialect.POSTGRES);
+ // Synthetic V1010 parent rows exercise migration occupancy only. They are not selected-source
+ // evidence and do not authenticate Account, Game Design, or World producers.
+ legacyDsl.execute(
+ "INSERT INTO characters (account_id, name, tenant_id) VALUES (1, 'legacy', 31001)");
+ legacyDsl.execute(
+ "INSERT INTO items (name, tenant_id, version_id) VALUES ('legacy', 41001, 51001)");
+ legacyDsl.execute(
+ "INSERT INTO item_transfer_audits (tenant_id, item_id, quantity, verb, correlation_key, "
+ + "source_holder_kind, destination_holder_kind) "
+ + "VALUES (61001, 99001, 1, 'MOVE', 'legacy-audit', 'UNKNOWN', 'UNKNOWN')");
+
+ legacyDsl.execute("INSERT INTO entity_tenant_identities (canonical_tenant_uuid) VALUES (?)", UUID.randomUUID());
+ legacyDsl.execute("INSERT INTO saga_instance (saga_name, state) VALUES ('retained-entity-source', 'PENDING')");
+ legacyDsl.execute("INSERT INTO saga_step (instance_id, name, status) SELECT id, 'retained-step', 'PENDING' FROM saga_instance WHERE saga_name = 'retained-entity-source'");
+ var parentRows = retainedParentRows(legacyDsl);
+ var parentHistory = history(legacyDsl);
+ assertThat(legacyDsl.fetch("SELECT version FROM flyway_schema_history WHERE success ORDER BY installed_rank")
+ .getValues(0, String.class)).containsExactly("1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010");
+
+ var flywayConfiguration =
+ Flyway.configure()
+ .dataSource(dataSource)
+ .locations(MIGRATION_LOCATION, "classpath:db/migration/saga")
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema));
+ flywayConfiguration
+ .getConfigurationExtension(PostgreSQLConfigurationExtension.class)
+ .setTransactionalLock(false);
+ flywayConfiguration.load().migrate();
+ dsl = DSL.using(dataSource, SQLDialect.POSTGRES);
+ assertThat(retainedParentRows(dsl)).isEqualTo(parentRows);
+ assertThat(history(dsl).subList(0, parentHistory.size())).containsExactlyElementsOf(parentHistory);
+ assertThat(dsl.fetchSingle("SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1").get(0, String.class)).isEqualTo("1011");
+
+ }
+
+ @AfterEach
+ void dropIsolatedSchema() {
+ if (schema != null) {
+ String checkedSchema = schema.replaceAll("[^a-zA-Z0-9_]", "");
+ DSL.using(dataSource(null), SQLDialect.POSTGRES)
+ .execute("DROP SCHEMA IF EXISTS \"" + checkedSchema + "\" CASCADE");
+ schema = null;
+ }
+ }
+
+ @Test
+ void migrationSeedsActualLegacySourceAndAuditTenantVersionKeys() {
+ List legacyKeys =
+ dsl.fetch(
+ "SELECT key_kind, numeric_key, claim_kind "
+ + "FROM entity_empty_source_numeric_key_reservation "
+ + "WHERE claim_kind = 'LEGACY_NUMERIC' ORDER BY key_kind, numeric_key")
+ .map(
+ row ->
+ new ReservedNumericKey(
+ row.get(0, String.class),
+ row.get(1, Long.class),
+ row.get(2, String.class)));
+ assertThat(legacyKeys)
+ .containsExactly(
+ new ReservedNumericKey("TENANT", 31001L, "LEGACY_NUMERIC"),
+ new ReservedNumericKey("TENANT", 41001L, "LEGACY_NUMERIC"),
+ new ReservedNumericKey("TENANT", 61001L, "LEGACY_NUMERIC"),
+ new ReservedNumericKey("VERSION", 51001L, "LEGACY_NUMERIC"));
+ assertLegacyKey("TENANT", 31001L);
+ assertLegacyKey("TENANT", 41001L);
+ assertLegacyKey("TENANT", 61001L);
+ assertLegacyKey("VERSION", 51001L);
+ assertThat(
+ dsl.fetchSingle(
+ "SELECT COUNT(*) FROM entity_empty_source_numeric_key_reservation "
+ + "WHERE key_kind = 'VERSION' AND numeric_key = 51001 "
+ + "AND claim_kind = 'LEGACY_NUMERIC'")
+ .get(0, Long.class))
+ .isEqualTo(1L);
+ }
+
+ @Test
+ void retainedNumericKeysRejectLaterSourceRuntimeAndAuditWriters() {
+ dsl.execute(
+ "INSERT INTO entity_empty_source_numeric_key_reservation "
+ + "(key_kind, numeric_key, claim_kind) VALUES "
+ + "('TENANT', 99001, 'CANONICAL_EMPTY_SOURCE'), "
+ + "('VERSION', 99002, 'CANONICAL_EMPTY_SOURCE')");
+
+ assertRejected(
+ "INSERT INTO items (name, tenant_id, version_id) VALUES ('blocked', 99001, 99002)");
+ assertRejected("UPDATE items SET tenant_id = 99001 WHERE tenant_id = 41001");
+ assertRejected(
+ "INSERT INTO characters (account_id, name, tenant_id) VALUES (2, 'blocked', 99001)");
+ assertRejected("UPDATE characters SET tenant_id = 99001 WHERE tenant_id = 31001");
+ assertRejected(
+ "INSERT INTO item_transfer_audits (tenant_id, item_id, quantity, verb, correlation_key, "
+ + "source_holder_kind, destination_holder_kind) "
+ + "VALUES (99001, 99003, 1, 'MOVE', 'blocked-audit', 'UNKNOWN', 'UNKNOWN')");
+ }
+
+ @Test
+ void unassociatedLegacyKeysRemainWritable() {
+ dsl.execute(
+ "INSERT INTO items (name, tenant_id, version_id) "
+ + "VALUES ('unassociated legacy item', 71001, 71002)");
+ dsl.execute(
+ "INSERT INTO characters (account_id, name, tenant_id) "
+ + "VALUES (3, 'unassociated legacy character', 72001)");
+
+ assertThat(
+ dsl.fetchSingle("SELECT COUNT(*) FROM items WHERE tenant_id = 71001")
+ .get(0, Long.class))
+ .isEqualTo(1L);
+ assertThat(
+ dsl.fetchSingle("SELECT COUNT(*) FROM characters WHERE tenant_id = 72001")
+ .get(0, Long.class))
+ .isEqualTo(1L);
+ }
+
+ /** Storage retention only; synthetic parent rows establish no authenticated owner authority. */
+ private static Map> retainedParentRows(DSLContext source) {
+ Map> rows = new java.util.LinkedHashMap<>();
+ for (String table : List.of("characters", "items", "item_transfer_audits",
+ "entity_tenant_identities", "entity_playable_state_namespace_scopes",
+ "entity_preseeded_actor_assignment_operations", "entity_canonical_gameplay_roster_snapshots",
+ "entity_canonical_gameplay_roster_snapshot_actors", "saga_instance", "saga_step")) {
+ rows.put(table, source.fetch("SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM "
+ + table + " t ORDER BY to_jsonb(t)::TEXT").getValues(0, String.class));
+ }
+ return rows;
+ }
+
+ private static List history(DSLContext source) {
+ return source.fetch("SELECT to_jsonb(t)::TEXT || ':' || t.xmin::TEXT FROM flyway_schema_history t ORDER BY installed_rank")
+ .getValues(0, String.class);
+ }
+
+ private void assertLegacyKey(String kind, long key) {
+ assertThat(
+ dsl.fetchSingle(
+ "SELECT claim_kind FROM entity_empty_source_numeric_key_reservation "
+ + "WHERE key_kind = ? AND numeric_key = ?",
+ kind,
+ key)
+ .get(0, String.class))
+ .isEqualTo("LEGACY_NUMERIC");
+ }
+
+ private void assertRejected(String sql) {
+ assertThatThrownBy(() -> dsl.execute(sql)).isInstanceOf(DataAccessException.class);
+ }
+
+ private record ReservedNumericKey(String keyKind, Long numericKey, String claimKind) {}
+
+ private DriverManagerDataSource dataSource(String schemaName) {
+ DriverManagerDataSource dataSource = new DriverManagerDataSource();
+ dataSource.setDriverClassName(postgres.getDriverClassName());
+ String baseUrl = postgres.getJdbcUrl();
+ dataSource.setUrl(
+ schemaName == null
+ ? baseUrl
+ : baseUrl + (baseUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName);
+ dataSource.setUsername(postgres.getUsername());
+ dataSource.setPassword(postgres.getPassword());
+ return dataSource;
+ }
+}
diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java
new file mode 100644
index 0000000000..13c9d1f222
--- /dev/null
+++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java
@@ -0,0 +1,468 @@
+package net.firedevops.firemud.entitymanagement.repository;
+
+import java.io.ByteArrayOutputStream;
+import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.time.OffsetDateTime;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof;
+import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration;
+import net.firedevops.firemud.common.gamedesign.AssetSnapshot;
+import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot;
+import net.firedevops.firemud.common.gamedesign.CommandSnapshot;
+import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch;
+import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot;
+import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent;
+import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration;
+import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot;
+import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues;
+import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest;
+import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource;
+import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel;
+
+/**
+ * Test-only synthetic inputs built through the same typed Common decoders as the shared fixture.
+ * They are not authenticated Account or World producer evidence or physical owner proof.
+ */
+final class EntityEmptySelectedSourceIntakePostgresFixture {
+ static final String NAMESPACE = "test";
+ static final UUID TENANT = id("11111111-1111-4111-8111-111111111111");
+ static final UUID VERSION = id("22222222-2222-4222-8222-222222222222");
+ static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999");
+
+ private static final UUID OPERATION = id("55555555-5555-4555-8555-555555555555");
+ private static final UUID FENCE = id("66666666-6666-4666-8666-666666666666");
+ private static final UUID INTAKE_REQUEST = id("77777777-7777-4777-8777-777777777777");
+ private static final UUID GENESIS_RECEIPT = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa");
+
+ private static final String TEMPLATE_CONFIG =
+ "{\"schemaVersion\":1,\"baseVersionId\":\""
+ + VERSION
+ + "\",\"world\":{\"regions\":[],\"rooms\":[]},"
+ + "\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":[]},"
+ + "\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}},"
+ + "\"supportedSettings\":[]}";
+
+ private EntityEmptySelectedSourceIntakePostgresFixture() {}
+
+ static Fixture create(String sourceEpoch) {
+ DraftCommitBinding selected = selected();
+ var scope =
+ new net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope(
+ Owner.ENTITY_MANAGEMENT, NAMESPACE, OPERATION, FENCE, INTAKE_REQUEST, ACTOR, selected);
+ TemplateConfigSourceSnapshot templateSnapshot = templateSnapshot(selected, sourceEpoch);
+ SelectedOwnerIntakeAuthorizationBinding authorization =
+ new SelectedOwnerIntakeAuthorizationBinding(
+ sourceContent(scope, templateSnapshot), accountSources());
+ WorldSelectedDraftPublicationFreezeEvidence freeze = freezeEvidence(selected);
+ var inventory =
+ WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence(
+ freeze, publicInventory(freeze));
+ var worldRequest =
+ SelectedOwnerWorldInventoryReadEvidence.create(NAMESPACE, authorization, freeze);
+ var worldEvidence = new SelectedOwnerWorldInventoryReadEvidence(worldRequest, inventory);
+ return new Fixture(
+ authorization,
+ freeze,
+ worldEvidence,
+ new SelectedOwnerEmptySourceInputs(authorization, worldEvidence));
+ }
+
+ static Fixture withFreshWorldReadCorrelation(Fixture original) {
+ var request =
+ SelectedOwnerWorldInventoryReadEvidence.create(
+ NAMESPACE, original.authorization(), original.freezeEvidence());
+ var evidence =
+ new SelectedOwnerWorldInventoryReadEvidence(request, original.worldEvidence().inventory());
+ return new Fixture(
+ original.authorization(),
+ original.freezeEvidence(),
+ evidence,
+ new SelectedOwnerEmptySourceInputs(original.authorization(), evidence));
+ }
+
+ private static TemplateConfigSourceSnapshot templateSnapshot(
+ DraftCommitBinding selected, String sourceEpoch) {
+ var declaration =
+ EntityAuthoredSourceInventoryDeclaration.parse(
+ "{\"schema\":\"entity-authored-source-inventory/v1\","
+ + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{"
+ + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[],"
+ + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[],"
+ + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[],"
+ + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[],"
+ + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[],"
+ + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[],"
+ + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[],"
+ + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[],"
+ + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[],"
+ + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[],"
+ + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[],"
+ + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}");
+ String declarationPayload =
+ TemplateConfigSourceValues.ownerInventoryPayload(Owner.ENTITY_MANAGEMENT, declaration);
+ DraftCommitBinding authored = authoredBinding(declarationPayload);
+ TemplateConfigOwnerSourceInventoryDeclaration ownerDeclaration =
+ TemplateConfigSourceValues.mutations(authored).stream()
+ .filter(
+ mutation ->
+ mutation.operation()
+ == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY)
+ .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration)
+ .findFirst()
+ .orElseThrow();
+ return new TemplateConfigSourceSnapshot(
+ selected,
+ sourceEpoch,
+ authored.commitId(),
+ GENESIS_RECEIPT,
+ List.of(),
+ List.of(ownerDeclaration));
+ }
+
+ private static DraftCommitBinding authoredBinding(String payload) {
+ return DraftCommitBinding.create(
+ target(),
+ id("51515151-5151-4151-8151-515151515151"),
+ id("52525252-5252-4252-8252-525252525252"),
+ "base-commit-0",
+ List.of(
+ new RevisionPayload(
+ "0",
+ id("53535353-5353-4353-8353-535353535353"),
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ payload)),
+ List.of(
+ new DraftCommitBinding.AffectedUnit(
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ TemplateConfigSourceValues.SCOPE,
+ VERSION.toString(),
+ TemplateConfigSourceValues.SCOPE,
+ TemplateConfigSourceValues.SCOPE_ID,
+ "0")));
+ }
+
+ private static SelectedOwnerIntakeSourceContent sourceContent(
+ net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope scope,
+ TemplateConfigSourceSnapshot templateSnapshot) {
+ var out = new ByteArrayOutputStream();
+ frame(out, SelectedOwnerIntakeSourceContent.DOMAIN);
+ frame(out, scope.canonicalBytes());
+ frame(out, scope.digest());
+ for (String family :
+ List.of(
+ "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) {
+ byte[] snapshot =
+ "TEMPLATE_CONFIG".equals(family)
+ ? templateSnapshot.canonicalBytes()
+ : sourceSnapshot(family, scope.selected());
+ frame(out, family);
+ frame(out, snapshot);
+ frame(out, DraftAuthorizationFenceBinding.digest(snapshot));
+ }
+ byte[] bytes = out.toByteArray();
+ return SelectedOwnerIntakeSourceContent.fromStored(
+ bytes, scope, DraftAuthorizationFenceBinding.digest(bytes));
+ }
+
+ private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) {
+ // These values exercise exact stored-byte decoding only; they are synthetic, not owner proof.
+ return switch (family) {
+ case "COMMAND" ->
+ new CommandSnapshot(selected, "0", null, "sha256:" + "0".repeat(64), List.of())
+ .canonicalBytes();
+ case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes();
+ case "ASSET" ->
+ new AssetSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()).canonicalBytes();
+ case "GAMEPLAY_RULE" ->
+ new GameplayRuleSelectedSource(
+ GameplayRuleManifest.canonical(
+ Map.of(
+ "schema",
+ "game-design-gameplay-rule-source-snapshot/v1",
+ "bindingJson",
+ selected.canonicalJson(),
+ "bindingDigest",
+ selected.digest(),
+ "sourceEpoch",
+ "0",
+ "inheritedCommitId",
+ "",
+ "genesisReceiptId",
+ GENESIS_RECEIPT.toString(),
+ "manifestJson",
+ GameplayRuleManifest.explicitEmpty().canonicalJson(),
+ "entries",
+ List.of())))
+ .canonicalBytes();
+ case "BRANDING" ->
+ new BrandingSourceSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of())
+ .canonicalBytes();
+ default -> throw new IllegalArgumentException("Unsupported source family fixture: " + family);
+ };
+ }
+
+ private static List accountSources() {
+ return List.of(
+ source(SourceKind.TENANT, TENANT.toString(), "tenant"),
+ source(SourceKind.ACCOUNT, ACTOR.toString(), "account"),
+ source(SourceKind.MEMBERSHIP, ACTOR + "/" + TENANT, "membership"));
+ }
+
+ private static SourceEvidence source(SourceKind kind, String scope, String marker) {
+ return new SourceEvidence(
+ kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8));
+ }
+
+ private static DraftCommitBinding selected() {
+ return DraftCommitBinding.create(
+ target(),
+ id("33333333-3333-4333-8333-333333333333"),
+ id("44444444-4444-4444-8444-444444444444"),
+ "base-commit-0",
+ List.of(
+ new RevisionPayload(
+ "0", id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), Owner.WORLD_MANAGEMENT, "{}")),
+ List.of(
+ new DraftCommitBinding.AffectedUnit(
+ Owner.WORLD_MANAGEMENT, "REGION", "region-1", "AGGREGATE", "region-1", "0")));
+ }
+
+ private static TargetProof target() {
+ return new TargetProof(TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW");
+ }
+
+ private static WorldSelectedDraftPublicationFreezeEvidence freezeEvidence(
+ DraftCommitBinding selected) {
+ var selection =
+ AuthoredDraftPublishSelectionBinding.capture(
+ new PublishIntent(
+ TENANT,
+ VERSION,
+ "publication-request",
+ "9",
+ "synthetic selected-owner intake fixture",
+ selected.requestId(),
+ selected.commitId(),
+ selected.digest()),
+ selected.target(),
+ selected,
+ new VisibilityFence(
+ selected.target(),
+ selected.requestId(),
+ selected.commitId(),
+ selected.digest(),
+ "[]",
+ OffsetDateTime.parse("2026-10-01T00:00:00Z")));
+ var account =
+ new AccountPublicationAuthorizationBinding(
+ id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"),
+ id("ffffffff-ffff-4fff-8fff-ffffffffffff"),
+ new AccountPublicationAuthorizationBinding.PreallocationInput(ACTOR, selection),
+ List.of(source(SourceKind.ACCOUNT, ACTOR.toString(), "account-publication")));
+ var request =
+ WorldSelectedDraftPublicationFreezeEvidence.Request.create(
+ NAMESPACE,
+ TENANT,
+ VERSION,
+ selection.intent().publishRequestId(),
+ 9,
+ selection.digest().substring("sha256:".length()),
+ account);
+ var acknowledgement =
+ new Acknowledgement(
+ request,
+ id("12121212-1212-4212-8212-121212121212"),
+ 9,
+ id("13131313-1313-4313-8313-131313131313"),
+ OwnerFreezePhase.FROZEN,
+ selected.commitId().toString(),
+ "a".repeat(64),
+ 4);
+ return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse(
+ request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement));
+ }
+
+ private static PublicEvidence publicInventory(
+ WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) {
+ var request = freezeEvidence.request();
+ var acknowledgement = freezeEvidence.acknowledgement();
+ var account = request.accountBinding();
+ var selection = account.input().selection();
+ var selected = selection.selectedCommit();
+ var sourceModel =
+ new SourceModel(
+ WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL,
+ WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION,
+ "sha256:" + "4".repeat(64),
+ "sha256:" + "5".repeat(64),
+ List.of(
+ new FamilyCount("REGION", 1),
+ new FamilyCount("ZONE", 1),
+ new FamilyCount("ROOM", 1),
+ new FamilyCount("ROOM_EXIT", 1),
+ new FamilyCount("GENERATION_RULE", 0),
+ new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)),
+ List.of(new RegionGeneratorInput(id("15151515-1515-4515-8515-151515151515"), "", "")),
+ List.of("id", "name", "scopeType", "scopeId", "value"),
+ List.of(
+ "id",
+ "shardId",
+ "name",
+ "weather",
+ "generationSeed",
+ "generatorType",
+ "generatorParams",
+ "spacingMultiplier"),
+ List.of("id", "regionId", "name"),
+ List.of(
+ "id",
+ "zoneId",
+ "name",
+ "description",
+ "nameLocalizedVariantsJson",
+ "descriptionLocalizedVariantsJson"),
+ List.of("id", "fromRoomId", "toRoomId", "direction", "cost"),
+ List.of(
+ "id",
+ "roomId",
+ "entityTemplateType",
+ "entityReference.kind",
+ "entityReference.tenantId",
+ "entityReference.versionId",
+ "entityReference.templateId",
+ "spawnCount",
+ "respawnDelaySeconds"),
+ List.of(),
+ 0,
+ 0,
+ selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream()
+ .map(
+ unit ->
+ new AppliedEpoch(
+ unit.aggregateType(),
+ unit.aggregateId(),
+ unit.scopeType(),
+ unit.scopeId(),
+ unit.expectedEpoch(),
+ new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString()))
+ .toList(),
+ emptyInboundClosure());
+ var ownerScope =
+ new PublicOwnerScope(
+ request.targetNamespace(),
+ TENANT,
+ VERSION,
+ id("14141414-1414-4414-8414-141414141414"),
+ acknowledgement.intakeRequestId(),
+ id("13131313-1313-4313-8313-131313131313"),
+ "sha256:" + "1".repeat(64),
+ id("17171717-1717-4717-8717-171717171717"),
+ "sha256:" + "2".repeat(64),
+ "sha256:" + "3".repeat(64));
+ return new PublicEvidence(
+ WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA,
+ WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION,
+ "COMPLETE",
+ ownerScope,
+ new SelectedApplication(
+ id("16161616-1616-4616-8616-161616161616"),
+ selected.requestId(),
+ selected.commitId().toString(),
+ selected.digest(),
+ "sha256:" + "6".repeat(64)),
+ new PublicAccountOrder(
+ account.operationId(),
+ account.fenceId(),
+ account.input().actorAccountId(),
+ selection.intent().publishRequestId(),
+ selection.digest(),
+ selected.commitId().toString(),
+ DraftAuthorizationFenceBinding.digest(account.canonicalBytes())),
+ new Freeze(
+ acknowledgement.publicationFence(),
+ request.publicationRequestId(),
+ request.requestDigest(),
+ Long.toString(acknowledgement.versionStateEpoch()),
+ PublicationDigestRequestBinding.full(
+ request.canonicalTenantId().toString(),
+ Long.toString(selection.target().gameDesignVersionRowId()),
+ request.publicationRequestId())
+ .derivedWorkflowIdentity()),
+ new Checkpoint(acknowledgement.appliedCommitId(), acknowledgement.contentDigest(), 4),
+ sourceModel,
+ List.of(
+ new ArtifactDecision(
+ "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"),
+ new ArtifactDecision(
+ "PATH_GRAPH",
+ "NOT_REQUIRED",
+ "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH")));
+ }
+
+ private static InboundSourceClosureDeclaration emptyInboundClosure() {
+ return new InboundSourceClosureDeclaration(
+ 1,
+ List.of(
+ new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0),
+ new InboundSourceFamilyCount(
+ "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0),
+ new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0),
+ new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0),
+ new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0),
+ new InboundSourceFamilyCount(
+ "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0),
+ new InboundSourceFamilyCount(
+ "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0)));
+ }
+
+ private static void frame(ByteArrayOutputStream out, String value) {
+ DraftAuthorizationFenceBinding.frame(out, value);
+ }
+
+ private static void frame(ByteArrayOutputStream out, byte[] value) {
+ DraftAuthorizationFenceBinding.frame(out, value);
+ }
+
+ private static UUID id(String value) {
+ return UUID.fromString(value);
+ }
+
+ record Fixture(
+ SelectedOwnerIntakeAuthorizationBinding authorization,
+ WorldSelectedDraftPublicationFreezeEvidence freezeEvidence,
+ SelectedOwnerWorldInventoryReadEvidence worldEvidence,
+ SelectedOwnerEmptySourceInputs inputs) {}
+}
diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java
new file mode 100644
index 0000000000..b10cd5545e
--- /dev/null
+++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java
@@ -0,0 +1,516 @@
+package net.firedevops.firemud.entitymanagement.repository;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.TimeZone;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository;
+import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedEmptyPublicationDigestService;
+import net.firedevops.firemud.test.TestContainerImages;
+import org.flywaydb.core.Flyway;
+import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension;
+import org.jooq.DSLContext;
+import org.jooq.ExecuteContext;
+import org.jooq.SQLDialect;
+import org.jooq.exception.DataAccessException;
+import org.jooq.impl.DSL;
+import org.jooq.impl.DefaultExecuteListener;
+import org.jooq.impl.DefaultExecuteListenerProvider;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.parallel.ResourceLock;
+import org.junit.jupiter.api.parallel.Resources;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.testcontainers.containers.PostgreSQLContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+/** Physical PostgreSQL proof for Entity's synthetic-input fresh EMPTY-only retention boundary. */
+@Testcontainers(disabledWithoutDocker = true)
+@SuppressWarnings("resource")
+class EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest {
+ private static final String MIGRATION_LOCATION =
+ "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize();
+ private static final List EMPTY_ONLY_TABLES =
+ List.of(
+ "entity_empty_source_actor_body_layout_assignments",
+ "entity_empty_source_archetype_assignments",
+ "entity_empty_source_archetype_constraints",
+ "entity_empty_source_archetype_roots",
+ "entity_empty_source_balance_curve_attachments",
+ "entity_empty_source_balance_curve_roots",
+ "entity_empty_source_equipment_attachment_rules",
+ "entity_empty_source_equipment_capabilities",
+ "entity_empty_source_equipment_compatibility_rules",
+ "entity_empty_source_equipment_occupancy_rules",
+ "entity_empty_source_inbound_loot_bindings",
+ "entity_empty_source_loot_item_mappings",
+ "entity_empty_source_loot_table_roots",
+ "entity_empty_source_other_actor_template_roots");
+
+ @Container
+ static PostgreSQLContainer> postgres =
+ new PostgreSQLContainer<>(TestContainerImages.postgres());
+
+ private String schema;
+ private DSLContext dsl;
+ private EntityEmptySelectedSourceIntakeRepository repository;
+
+ @BeforeEach
+ void migrateFreshIsolatedSchema() {
+ schema = "entity_empty_source_repo_" + UUID.randomUUID().toString().replace("-", "");
+ DriverManagerDataSource dataSource = dataSource(schema);
+ var flywayConfiguration =
+ Flyway.configure()
+ .dataSource(dataSource)
+ .locations(MIGRATION_LOCATION, "classpath:db/migration/saga")
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema));
+ flywayConfiguration
+ .getConfigurationExtension(PostgreSQLConfigurationExtension.class)
+ .setTransactionalLock(false);
+ flywayConfiguration.load().migrate();
+ dsl = DSL.using(dataSource, SQLDialect.POSTGRES);
+ repository = new EntityEmptySelectedSourceIntakeRepository(dsl);
+ }
+
+ @AfterEach
+ void dropIsolatedSchema() {
+ if (schema != null) {
+ String checkedSchema = schema.replaceAll("[^a-zA-Z0-9_]", "");
+ DSL.using(dataSource(null), SQLDialect.POSTGRES)
+ .execute("DROP SCHEMA IF EXISTS \"" + checkedSchema + "\" CASCADE");
+ schema = null;
+ }
+ }
+
+ @Test
+ @ResourceLock(Resources.TIME_ZONE)
+ void persistsAllTwentyThreeExplicitEmptyStatesAndReplaysOriginalReceiptBytes() {
+ var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1");
+ var inputs = fixture.inputs();
+ assertThat(inputs.ownerSourceInventoryDeclaration().owner()).isEqualTo(Owner.ENTITY_MANAGEMENT);
+ assertThat(
+ inputs
+ .worldInventoryReadEvidence()
+ .inventory()
+ .publicEvidence()
+ .sourceModel()
+ .inboundSourceClosure()
+ .familyCounts())
+ .allSatisfy(count -> assertThat(count.count()).isZero());
+ String requestDigest = requestDigest(fixture);
+
+ TimeZone originalTimeZone = TimeZone.getDefault();
+ EntityEmptySelectedSourceIntakeReceipt first;
+ try {
+ TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
+ first = repository.retainFresh(inputs, requestDigest);
+ } finally {
+ TimeZone.setDefault(originalTimeZone);
+ }
+ assertThat(first.familyStates())
+ .hasSize(23)
+ .allSatisfy(
+ state -> {
+ assertThat(state.state())
+ .isEqualTo(EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY);
+ assertThat(state.rowCount()).isZero();
+ assertThat(state.referenceCount()).isZero();
+ });
+ assertThat(first.familyStates())
+ .filteredOn(
+ state ->
+ state.evidenceKind()
+ == EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind
+ .EMPTY_ONLY_OWNER_PROVIDER)
+ .hasSize(14);
+ assertThat(first.familyStates())
+ .filteredOn(
+ state ->
+ state.evidenceKind()
+ == EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS)
+ .hasSize(9);
+ assertThat(first.localTenantKey()).isPositive();
+ assertThat(first.localVersionKey()).isPositive().isNotEqualTo(first.localTenantKey());
+ assertThat(first.authorizationBindingBytes())
+ .containsExactly(inputs.authorizationBinding().canonicalBytes());
+ assertThat(first.selectedSourceBytes())
+ .containsExactly(inputs.sourceContent().canonicalBytes());
+ assertThat(first.worldClosureBytes())
+ .containsExactly(inputs.worldInventoryReadEvidence().inventory().canonicalBytes());
+
+ assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_association"))
+ .isEqualTo(1L);
+ assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_family_state"))
+ .isEqualTo(23L);
+ assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_receipt")).isEqualTo(1L);
+ for (String table : EMPTY_ONLY_TABLES) {
+ assertThat(rowCount("SELECT COUNT(*) FROM " + table)).as(table).isEqualTo(1L);
+ }
+ EntityEmptySelectedSourceIntakeReceipt readBack;
+ try {
+ TimeZone.setDefault(TimeZone.getTimeZone("Pacific/Auckland"));
+ readBack = repository.read(first.targetNamespace(), first.intakeRequestId()).orElseThrow();
+ } finally {
+ TimeZone.setDefault(originalTimeZone);
+ }
+ assertThat(readBack.canonicalBytes()).containsExactly(first.canonicalBytes());
+ assertThat(readBack.receiptDigest()).isEqualTo(first.receiptDigest());
+ assertThat(readBack.retainedAt().toInstant()).isEqualTo(first.retainedAt().toInstant());
+
+ assertThatThrownBy(
+ () ->
+ dsl.execute(
+ "INSERT INTO items (name, tenant_id, version_id) VALUES ('blocked', ?, ?)",
+ first.localTenantKey(),
+ first.localVersionKey()))
+ .isInstanceOf(DataAccessException.class);
+ dsl.execute(
+ "INSERT INTO items (name, tenant_id, version_id) VALUES ('unassociated', 81001, 81002)");
+ assertThat(rowCount("SELECT COUNT(*) FROM items WHERE tenant_id = 81001")).isEqualTo(1L);
+
+ var retry =
+ EntityEmptySelectedSourceIntakePostgresFixture.withFreshWorldReadCorrelation(fixture);
+ assertThat(retry.worldEvidence().request().readRequestId())
+ .isNotEqualTo(fixture.worldEvidence().request().readRequestId());
+ EntityEmptySelectedSourceIntakeReceipt replay;
+ try {
+ TimeZone.setDefault(TimeZone.getTimeZone("Pacific/Auckland"));
+ replay = repository.retainFresh(retry.inputs(), requestDigest(retry));
+ } finally {
+ TimeZone.setDefault(originalTimeZone);
+ }
+ assertThat(replay.canonicalBytes()).containsExactly(first.canonicalBytes());
+ assertThat(replay.receiptDigest()).isEqualTo(first.receiptDigest());
+ assertThat(replay.retainedAt().toInstant()).isEqualTo(first.retainedAt().toInstant());
+ assertThat(replay.worldReadRequestId()).isEqualTo(first.worldReadRequestId());
+
+ var changed = EntityEmptySelectedSourceIntakePostgresFixture.create("2");
+ assertThatThrownBy(() -> repository.retainFresh(changed.inputs(), requestDigest(changed)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("different selected evidence");
+ assertThat(
+ repository
+ .read(first.targetNamespace(), first.intakeRequestId())
+ .orElseThrow()
+ .canonicalBytes())
+ .containsExactly(first.canonicalBytes());
+ }
+
+ @Test
+ void existingGlobalEntityRowsAndReferencesDenyFreshGenesisAndRollBackOwnerRecords() {
+ var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1");
+ dsl.execute("INSERT INTO items (name, tenant_id, version_id) VALUES ('legacy', 72001, 72002)");
+
+ assertThatThrownBy(() -> repository.retainFresh(fixture.inputs(), requestDigest(fixture)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("not freshly empty");
+ assertNoCanonicalOwnerRecords();
+ }
+
+ @Test
+ void selectedEmptyPublicationReaderResolvesOnlyTheValidatedReceiptForTenantAndGameDesignRow() {
+ var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1");
+ EntityEmptySelectedSourceIntakeReceipt receipt =
+ repository.retainFresh(fixture.inputs(), requestDigest(fixture));
+ long gameDesignVersionRowId =
+ fixture.authorization().selected().target().gameDesignVersionRowId();
+
+ assertThat(
+ repository
+ .readPublicationScope(
+ EntityEmptySelectedSourceIntakePostgresFixture.NAMESPACE,
+ EntityEmptySelectedSourceIntakePostgresFixture.TENANT,
+ gameDesignVersionRowId)
+ .canonicalBytes())
+ .containsExactly(receipt.canonicalBytes());
+ assertThatThrownBy(
+ () ->
+ repository.readPublicationScope(
+ EntityEmptySelectedSourceIntakePostgresFixture.NAMESPACE,
+ EntityEmptySelectedSourceIntakePostgresFixture.TENANT,
+ gameDesignVersionRowId + 1L))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("missing or ambiguous");
+
+ var digest =
+ new EntitySelectedEmptyPublicationDigestService(
+ EntityEmptySelectedSourceIntakePostgresFixture.NAMESPACE, repository)
+ .getDraftDesignDigest(
+ PublicationDigestRequestBinding.full(
+ EntityEmptySelectedSourceIntakePostgresFixture.TENANT.toString(),
+ Long.toString(gameDesignVersionRowId),
+ fixture.freezeEvidence().request().publicationRequestId()));
+ assertThat(digest.tenantId())
+ .isEqualTo(EntityEmptySelectedSourceIntakePostgresFixture.TENANT.toString());
+ assertThat(digest.scopeValue()).isEqualTo(Long.toString(gameDesignVersionRowId));
+ assertThat(digest.appliedCommitId()).isEqualTo(receipt.selectedCommitId().toString());
+ String canonicalInventoryJson =
+ fixture.inputs().ownerSourceInventoryDeclaration().entityInventory().canonicalJson();
+ assertThat(digest.contentDigest())
+ .isEqualTo(
+ expectedSelectedEmptyDigest(
+ "entity-selected-empty-publication-digest/v1",
+ "3",
+ EntityEmptySelectedSourceIntakePostgresFixture.TENANT,
+ gameDesignVersionRowId,
+ receipt.canonicalVersionId(),
+ canonicalInventoryJson));
+ assertThat(digest.digestSchemaVersion())
+ .isEqualTo(EntitySelectedEmptyPublicationDigestService.DIGEST_SCHEMA_VERSION);
+
+ String rowBeforeMismatchedPublicationRead =
+ dsl.fetchSingle(
+ "SELECT encode(receipt_bytes, 'hex') || ':' || xmin::text "
+ + "FROM entity_empty_selected_source_receipt "
+ + "WHERE target_namespace = ? AND intake_request_id = ?",
+ receipt.targetNamespace(),
+ receipt.intakeRequestId())
+ .get(0, String.class);
+ assertThatThrownBy(
+ () ->
+ new EntitySelectedEmptyPublicationDigestService(
+ EntityEmptySelectedSourceIntakePostgresFixture.NAMESPACE, repository)
+ .getDraftDesignDigest(
+ PublicationDigestRequestBinding.full(
+ EntityEmptySelectedSourceIntakePostgresFixture.TENANT.toString(),
+ Long.toString(gameDesignVersionRowId),
+ "publish-request-2")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("original retained World freeze");
+ String rowAfterMismatchedPublicationRead =
+ dsl.fetchSingle(
+ "SELECT encode(receipt_bytes, 'hex') || ':' || xmin::text "
+ + "FROM entity_empty_selected_source_receipt "
+ + "WHERE target_namespace = ? AND intake_request_id = ?",
+ receipt.targetNamespace(),
+ receipt.intakeRequestId())
+ .get(0, String.class);
+ assertThat(rowAfterMismatchedPublicationRead)
+ .isEqualTo(rowBeforeMismatchedPublicationRead);
+ }
+
+ @Test
+ void publicationScopeScanAndReceiptReadbackUseOneRepeatableReadSnapshot() {
+ var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1");
+ EntityEmptySelectedSourceIntakeReceipt receipt =
+ repository.retainFresh(fixture.inputs(), requestDigest(fixture));
+ byte[] concurrentlyCorruptedBytes = receipt.canonicalBytes();
+ concurrentlyCorruptedBytes[0] ^= 1;
+ AtomicBoolean concurrentMutationApplied = new AtomicBoolean();
+ dsl.configuration()
+ .set(
+ new DefaultExecuteListenerProvider(
+ new DefaultExecuteListener() {
+ @Override
+ public void executeEnd(ExecuteContext context) {
+ String sql = context.sql();
+ if (sql == null
+ || !sql.toLowerCase(Locale.ROOT)
+ .contains("from entity_empty_selected_source_association")
+ || !concurrentMutationApplied.compareAndSet(false, true)) {
+ return;
+ }
+ DSLContext concurrentDsl = DSL.using(dataSource(schema), SQLDialect.POSTGRES);
+ concurrentDsl.execute(
+ "ALTER TABLE entity_empty_selected_source_receipt "
+ + "DISABLE TRIGGER trg_entity_empty_source_receipt_immutable");
+ try {
+ assertThat(
+ concurrentDsl.execute(
+ "UPDATE entity_empty_selected_source_receipt "
+ + "SET receipt_bytes = ? WHERE target_namespace = ? "
+ + "AND intake_request_id = ?",
+ concurrentlyCorruptedBytes,
+ receipt.targetNamespace(),
+ receipt.intakeRequestId()))
+ .isEqualTo(1);
+ } finally {
+ concurrentDsl.execute(
+ "ALTER TABLE entity_empty_selected_source_receipt "
+ + "ENABLE TRIGGER trg_entity_empty_source_receipt_immutable");
+ }
+ }
+ }));
+
+ EntityEmptySelectedSourceIntakeReceipt read =
+ repository.readPublicationScope(
+ receipt.targetNamespace(),
+ receipt.canonicalTenantId(),
+ fixture.authorization().selected().target().gameDesignVersionRowId());
+
+ assertThat(read.canonicalBytes()).containsExactly(receipt.canonicalBytes());
+ assertThat(concurrentMutationApplied).isTrue();
+ var storedReceipt =
+ dsl.fetchOne(
+ "SELECT receipt_bytes FROM entity_empty_selected_source_receipt "
+ + "WHERE target_namespace = ? AND intake_request_id = ?",
+ receipt.targetNamespace(),
+ receipt.intakeRequestId());
+ assertThat(storedReceipt).isNotNull();
+ assertThat(storedReceipt.get(0, byte[].class)).containsExactly(concurrentlyCorruptedBytes);
+ }
+
+ @Test
+ void retainedAuditReferenceWithoutAnItemDeniesFreshGenesis() {
+ var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1");
+ dsl.execute(
+ "INSERT INTO item_transfer_audits (tenant_id, item_id, quantity, verb, correlation_key, "
+ + "source_holder_kind, destination_holder_kind) "
+ + "VALUES (73001, 999999, 1, 'MOVE', 'retained-audit', 'UNKNOWN', 'UNKNOWN')");
+
+ assertThatThrownBy(() -> repository.retainFresh(fixture.inputs(), requestDigest(fixture)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("not freshly empty");
+ assertNoCanonicalOwnerRecords();
+ }
+
+ @Test
+ void providerWriteFailureRollsBackAssociationKeysAndAllTypedStates() {
+ var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1");
+ dsl.execute(
+ "ALTER TABLE entity_empty_source_archetype_roots "
+ + "ADD CONSTRAINT test_force_empty_provider_failure CHECK (FALSE)");
+
+ assertThatThrownBy(() -> repository.retainFresh(fixture.inputs(), requestDigest(fixture)))
+ .isInstanceOf(DataAccessException.class);
+ assertNoCanonicalOwnerRecords();
+ }
+
+ @Test
+ void absentEmptyOnlyProviderFailsClosedBeforeAnyAssociationIsCommitted() {
+ var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1");
+ dsl.execute("DROP TABLE entity_empty_source_archetype_roots");
+
+ assertThatThrownBy(() -> repository.retainFresh(fixture.inputs(), requestDigest(fixture)))
+ .isInstanceOf(DataAccessException.class);
+ assertNoCanonicalOwnerRecords("entity_empty_source_archetype_roots");
+ }
+
+ @Test
+ void providerConstraintsAndImmutableReadbackRejectUnknownNonemptyOrChangedState() {
+ var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1");
+ EntityEmptySelectedSourceIntakeReceipt receipt =
+ repository.retainFresh(fixture.inputs(), requestDigest(fixture));
+ String table = "entity_empty_source_archetype_roots";
+
+ dsl.execute("ALTER TABLE " + table + " DISABLE TRIGGER USER");
+ try {
+ assertThatThrownBy(
+ () ->
+ dsl.execute(
+ "UPDATE " + table + " SET row_count = 1 WHERE target_namespace = ?",
+ receipt.targetNamespace()))
+ .isInstanceOf(DataAccessException.class);
+ assertThatThrownBy(
+ () ->
+ dsl.execute(
+ "UPDATE " + table + " SET owner_state = 'UNKNOWN' WHERE target_namespace = ?",
+ receipt.targetNamespace()))
+ .isInstanceOf(DataAccessException.class);
+ dsl.execute(
+ "DELETE FROM " + table + " WHERE target_namespace = ? AND intake_request_id = ?",
+ receipt.targetNamespace(),
+ receipt.intakeRequestId());
+ } finally {
+ dsl.execute("ALTER TABLE " + table + " ENABLE TRIGGER USER");
+ }
+ assertThatThrownBy(() -> repository.read(receipt.targetNamespace(), receipt.intakeRequestId()))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("provider readback is missing or differs");
+ assertThatThrownBy(
+ () ->
+ repository.readPublicationScope(
+ receipt.targetNamespace(),
+ receipt.canonicalTenantId(),
+ fixture.authorization().selected().target().gameDesignVersionRowId()))
+ .isInstanceOf(IllegalStateException.class);
+ }
+
+ private static String expectedSelectedEmptyDigest(
+ String domain,
+ String schemaVersion,
+ UUID canonicalTenantId,
+ long gameDesignVersionRowId,
+ UUID canonicalVersionId,
+ String canonicalInventoryJson) {
+ ByteArrayOutputStream preimage = new ByteArrayOutputStream();
+ appendDigestSegment(preimage, domain);
+ appendDigestSegment(preimage, schemaVersion);
+ appendDigestSegment(preimage, canonicalTenantId.toString());
+ appendDigestSegment(preimage, Long.toString(gameDesignVersionRowId));
+ appendDigestSegment(preimage, canonicalVersionId.toString());
+ appendDigestSegment(preimage, canonicalInventoryJson);
+ try {
+ return HexFormat.of()
+ .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray()));
+ } catch (NoSuchAlgorithmException impossible) {
+ throw new AssertionError(impossible);
+ }
+ }
+
+ private static void appendDigestSegment(ByteArrayOutputStream output, String value) {
+ byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
+ output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII));
+ output.write(':');
+ output.writeBytes(bytes);
+ }
+
+ private String requestDigest(EntityEmptySelectedSourceIntakePostgresFixture.Fixture fixture) {
+ return EntityEmptySelectedSourceIntakeReceipt.requestDigest(
+ fixture.authorization().targetNamespace(),
+ fixture.authorization(),
+ fixture.freezeEvidence());
+ }
+
+ private long rowCount(String sql) {
+ var row = Objects.requireNonNull(dsl.fetchOne(sql), "count query returned no row");
+ return Objects.requireNonNull(row.get(0, Long.class), "count query returned no value");
+ }
+
+ private void assertNoCanonicalOwnerRecords(String... unavailableProviderTables) {
+ assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_association")).isZero();
+ assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_family_state")).isZero();
+ assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_receipt")).isZero();
+ assertThat(
+ rowCount(
+ "SELECT COUNT(*) FROM entity_empty_source_numeric_key_reservation "
+ + "WHERE claim_kind = 'CANONICAL_EMPTY_SOURCE'"))
+ .isZero();
+ for (String table : EMPTY_ONLY_TABLES) {
+ if (List.of(unavailableProviderTables).contains(table)) continue;
+ assertThat(rowCount("SELECT COUNT(*) FROM " + table)).as(table).isZero();
+ }
+ }
+
+ private DriverManagerDataSource dataSource(String schemaName) {
+ DriverManagerDataSource dataSource = new DriverManagerDataSource();
+ dataSource.setDriverClassName(postgres.getDriverClassName());
+ String baseUrl = postgres.getJdbcUrl();
+ dataSource.setUrl(
+ schemaName == null
+ ? baseUrl
+ : baseUrl + (baseUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName);
+ dataSource.setUsername(postgres.getUsername());
+ dataSource.setPassword(postgres.getPassword());
+ return dataSource;
+ }
+}
diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepositoryTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepositoryTest.java
new file mode 100644
index 0000000000..725aced55d
--- /dev/null
+++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepositoryTest.java
@@ -0,0 +1,89 @@
+package net.firedevops.firemud.entitymanagement.sourceintake;
+
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt;
+import org.junit.jupiter.api.Test;
+
+class EntityEmptySelectedSourceIntakeRepositoryTest {
+ @Test
+ void recognizesAllFourteenExplicitFreshEmptyOwnerProviders() {
+ for (String family :
+ java.util.List.of(
+ "ACTOR_BODY_LAYOUT_ASSIGNMENTS",
+ "ARCHETYPE_ASSIGNMENTS",
+ "ARCHETYPE_CONSTRAINTS",
+ "ARCHETYPE_ROOTS",
+ "BALANCE_CURVE_ATTACHMENTS",
+ "BALANCE_CURVE_ROOTS",
+ "EQUIPMENT_ATTACHMENT_RULES",
+ "EQUIPMENT_CAPABILITIES",
+ "EQUIPMENT_COMPATIBILITY_RULES",
+ "EQUIPMENT_OCCUPANCY_RULES",
+ "INBOUND_LOOT_BINDINGS",
+ "LOOT_ITEM_MAPPINGS",
+ "LOOT_TABLE_ROOTS",
+ "OTHER_ACTOR_TEMPLATE_ROOTS")) {
+ EntityEmptySelectedSourceIntakeRepository.requireReadableProvider(family);
+ }
+ }
+
+ @Test
+ void recognizesAllNineExistingV1CensusFamilies() {
+ for (String family :
+ java.util.List.of(
+ "ITEM_TEMPLATE_ROOTS",
+ "NPC_TEMPLATE_ROOTS",
+ "CRAFTING_RECIPE_ROOTS",
+ "CRAFTING_RECIPE_RESULT_BINDINGS",
+ "CRAFTING_INGREDIENT_BINDINGS",
+ "EQUIPMENT_SLOT_ROOTS",
+ "EQUIPMENT_SLOT_GROUPS",
+ "BODY_LAYOUT_ROOTS",
+ "BODY_LAYOUT_MEMBERSHIPS")) {
+ EntityEmptySelectedSourceIntakeRepository.requireReadableProvider(family);
+ }
+ }
+
+ @Test
+ void rejectsFamiliesWithNoDeclaredOwnerProvider() {
+ assertThatThrownBy(
+ () -> EntityEmptySelectedSourceIntakeRepository.requireReadableProvider("UNKNOWN"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("No readable persisted Entity source provider");
+ }
+
+ @Test
+ void anEmptyFamilyStateCannotCarryRowsOrReferences() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ new EntityEmptySelectedSourceIntakeReceipt.FamilyCensus(
+ "ITEM_TEMPLATE_ROOTS",
+ EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY,
+ EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS,
+ 0L,
+ 0L,
+ 0L,
+ 0L,
+ 1L));
+ }
+
+ @Test
+ void rejectsEvidenceKindThatDoesNotMatchFamilyProvider() {
+ assertThatThrownBy(
+ () ->
+ new EntityEmptySelectedSourceIntakeReceipt.FamilyCensus(
+ "ARCHETYPE_ROOTS",
+ EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY,
+ EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS,
+ 0L,
+ 0L,
+ 0L,
+ 0L,
+ 0L))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("evidence kind differs");
+ }
+}
diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeServiceTest.java
new file mode 100644
index 0000000000..8e95b351e4
--- /dev/null
+++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeServiceTest.java
@@ -0,0 +1,47 @@
+package net.firedevops.firemud.entitymanagement.sourceintake;
+
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient;
+import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient;
+import org.jooq.DSLContext;
+import org.junit.jupiter.api.Test;
+
+class EntityEmptySelectedSourceIntakeServiceTest {
+ @Test
+ void rejectsCallerSelectedNamespaceBeforeReceiptReplayOrRemoteReads() {
+ DSLContext dsl = mock(DSLContext.class);
+ SelectedOwnerIntakeAuthorizationReadClient authorizationClient =
+ mock(SelectedOwnerIntakeAuthorizationReadClient.class);
+ SelectedOwnerWorldInventoryReadClient worldClient =
+ mock(SelectedOwnerWorldInventoryReadClient.class);
+ var service =
+ new EntityEmptySelectedSourceIntakeService(
+ "configured",
+ new EntityEmptySelectedSourceIntakeRepository(dsl),
+ authorizationClient,
+ worldClient);
+
+ assertThatThrownBy(() -> service.retain("attacker-selected", null, null))
+ .isInstanceOf(SecurityException.class)
+ .hasMessageContaining("configured Entity owner namespace");
+
+ verifyNoInteractions(dsl, authorizationClient, worldClient);
+ }
+
+ @Test
+ void rejectsInvalidConfiguredNamespaceAtConstruction() {
+ DSLContext dsl = mock(DSLContext.class);
+ assertThatThrownBy(
+ () ->
+ new EntityEmptySelectedSourceIntakeService(
+ "Invalid_Namespace",
+ new EntityEmptySelectedSourceIntakeRepository(dsl),
+ mock(SelectedOwnerIntakeAuthorizationReadClient.class),
+ mock(SelectedOwnerWorldInventoryReadClient.class)))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Configured Entity namespace");
+ }
+}
diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceServiceTest.java
new file mode 100644
index 0000000000..de9f583b39
--- /dev/null
+++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceServiceTest.java
@@ -0,0 +1,264 @@
+package net.firedevops.firemud.entitymanagement.sourceintake;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+import java.util.List;
+import java.util.UUID;
+import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection;
+import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient;
+import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence;
+import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association;
+import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay;
+import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request;
+import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope;
+import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt;
+import net.firedevops.firemud.gamedesign.v1.ParticipantDigest;
+import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle;
+import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures;
+import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture;
+import org.junit.jupiter.api.Test;
+
+class EntityRetainedAuthoredActorCoreSourceServiceTest {
+ private static final String NAMESPACE = "test";
+ private static final String WORKFLOW = "selected-publish-workflow";
+ private static final String WORLD_SLUG = "retained-world";
+ private static final String ASSOCIATION_DIGEST = "sha256:" + "a".repeat(64);
+
+ @Test
+ void exactRetryReturnsUnchangedDirectResultAfterIndependentOwnerSnapshotRead() {
+ Fixture fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create();
+ ReadSetup setup = readSetup(fixture);
+ AuthoredInitialActorCoreReadClient client = mock(AuthoredInitialActorCoreReadClient.class);
+ EntityEmptySelectedSourceIntakeRepository repository =
+ mock(EntityEmptySelectedSourceIntakeRepository.class);
+ when(client.read(setup.request())).thenReturn(setup.result());
+ when(repository.readPublicationScope(
+ NAMESPACE,
+ fixture.receipt().canonicalTenantId(),
+ fixture.receipt().authorizationBinding().selected().target().gameDesignVersionRowId()))
+ .thenReturn(fixture.receipt());
+ var service = new EntityRetainedAuthoredActorCoreSourceService(NAMESPACE, client, repository);
+
+ var first = service.read(setup.request());
+ var retry = service.read(setup.request());
+
+ assertThat(first).isSameAs(setup.result());
+ assertThat(retry).isSameAs(setup.result());
+ var inOrder = inOrder(client, repository);
+ inOrder.verify(client).read(setup.request());
+ inOrder
+ .verify(repository)
+ .readPublicationScope(
+ NAMESPACE,
+ fixture.receipt().canonicalTenantId(),
+ fixture.receipt().authorizationBinding().selected().target().gameDesignVersionRowId());
+ inOrder.verify(client).read(setup.request());
+ inOrder
+ .verify(repository)
+ .readPublicationScope(
+ NAMESPACE,
+ fixture.receipt().canonicalTenantId(),
+ fixture.receipt().authorizationBinding().selected().target().gameDesignVersionRowId());
+ verifyNoMoreInteractions(client, repository);
+ }
+
+ @Test
+ void deniesAReadResultThatSubstitutesTheOriginalOperationBeforeEntitySql() {
+ Fixture fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create();
+ ReadSetup setup = readSetup(fixture);
+ AuthoredInitialActorCoreReadClient client = mock(AuthoredInitialActorCoreReadClient.class);
+ EntityEmptySelectedSourceIntakeRepository repository =
+ mock(EntityEmptySelectedSourceIntakeRepository.class);
+ var substituted = mock(AuthoredInitialActorCoreReadEvidence.ReadResult.class);
+ when(substituted.request()).thenReturn(mock(Request.class));
+ when(client.read(setup.request())).thenReturn(substituted);
+ var service = new EntityRetainedAuthoredActorCoreSourceService(NAMESPACE, client, repository);
+
+ assertThatThrownBy(() -> service.read(setup.request()))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("exact original request");
+
+ verify(client).read(setup.request());
+ verifyNoInteractions(repository);
+ }
+
+ @Test
+ void deniesMixedProjectionSourceEvenWhenTheEntityReleaseDigestMatches() {
+ Fixture fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create();
+ ReadSetup setup = readSetup(fixture);
+ when(setup.projection().worldSourceOperationId()).thenReturn(UUID.randomUUID());
+ AuthoredInitialActorCoreReadClient client = mock(AuthoredInitialActorCoreReadClient.class);
+ EntityEmptySelectedSourceIntakeRepository repository =
+ mock(EntityEmptySelectedSourceIntakeRepository.class);
+ when(client.read(setup.request())).thenReturn(setup.result());
+ when(repository.readPublicationScope(
+ NAMESPACE,
+ fixture.receipt().canonicalTenantId(),
+ fixture.receipt().authorizationBinding().selected().target().gameDesignVersionRowId()))
+ .thenReturn(fixture.receipt());
+ var service = new EntityRetainedAuthoredActorCoreSourceService(NAMESPACE, client, repository);
+
+ assertThatThrownBy(() -> service.read(setup.request()))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("exact retained source");
+ }
+
+ @Test
+ void deniesReleaseWithDifferentImmutableEntityRecipientDigest() {
+ Fixture fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create();
+ ReadSetup setup = readSetup(fixture);
+ PublishedReleaseBundle changedRelease =
+ setup.release().toBuilder()
+ .clearParticipantDigests()
+ .addParticipantDigests(entityParticipant(fixture.receipt(), "0".repeat(64)))
+ .build();
+ when(setup.associationRead().releaseBundle()).thenReturn(changedRelease);
+ AuthoredInitialActorCoreReadClient client = mock(AuthoredInitialActorCoreReadClient.class);
+ EntityEmptySelectedSourceIntakeRepository repository =
+ mock(EntityEmptySelectedSourceIntakeRepository.class);
+ when(client.read(setup.request())).thenReturn(setup.result());
+ when(repository.readPublicationScope(
+ NAMESPACE,
+ fixture.receipt().canonicalTenantId(),
+ fixture.receipt().authorizationBinding().selected().target().gameDesignVersionRowId()))
+ .thenReturn(fixture.receipt());
+ var service = new EntityRetainedAuthoredActorCoreSourceService(NAMESPACE, client, repository);
+
+ assertThatThrownBy(() -> service.read(setup.request()))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("release Entity digest");
+ }
+
+ @Test
+ void deniesUnavailableAuthenticatedGameDesignEvidenceWithoutLocalRead() {
+ ReadSetup setup = readSetup(EntitySelectedSourceIntakeTerminalReadFixtures.create());
+ AuthoredInitialActorCoreReadClient client = mock(AuthoredInitialActorCoreReadClient.class);
+ EntityEmptySelectedSourceIntakeRepository repository =
+ mock(EntityEmptySelectedSourceIntakeRepository.class);
+ when(client.read(setup.request())).thenThrow(new IllegalStateException("read unavailable"));
+ var service = new EntityRetainedAuthoredActorCoreSourceService(NAMESPACE, client, repository);
+
+ assertThatThrownBy(() -> service.read(setup.request()))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("read unavailable");
+
+ verifyNoInteractions(repository);
+ }
+
+ private static ReadSetup readSetup(Fixture fixture) {
+ EntityEmptySelectedSourceIntakeReceipt receipt = fixture.receipt();
+ ExactReplay replay =
+ new ExactReplay(
+ receipt.canonicalVersionId(), receipt.selectedCommitId(), WORKFLOW, ASSOCIATION_DIGEST);
+ Request originalRequest = mock(Request.class);
+ when(originalRequest.targetNamespace()).thenReturn(NAMESPACE);
+ when(originalRequest.selection()).thenReturn(replay);
+ var request = new AuthoredInitialActorCoreReadEvidence.ReadRequest(originalRequest);
+
+ PublicOwnerScope worldOwner =
+ receipt.inputs().worldInventoryReadEvidence().inventory().publicEvidence().ownerScope();
+ Association association = mock(Association.class);
+ when(association.canonicalTenantId()).thenReturn(receipt.canonicalTenantId());
+ when(association.canonicalVersionId()).thenReturn(receipt.canonicalVersionId());
+ when(association.selectedCommitId()).thenReturn(receipt.selectedCommitId());
+ when(association.publishWorkflowId()).thenReturn(WORKFLOW);
+ when(association.associationDigest()).thenReturn(ASSOCIATION_DIGEST);
+ when(association.targetNamespace()).thenReturn(NAMESPACE);
+ when(association.intakeRequestId()).thenReturn(worldOwner.intakeRequestId());
+ when(association.worldOperationId()).thenReturn(worldOwner.intakeOperationId());
+ when(association.publicationSelectionDigest())
+ .thenReturn(
+ receipt
+ .inputs()
+ .worldInventoryReadEvidence()
+ .request()
+ .freezeEvidence()
+ .request()
+ .accountBinding()
+ .input()
+ .selection()
+ .digest());
+ when(association.sourceOperationId()).thenReturn(worldOwner.sourceOperationId());
+ when(association.sourceEvidenceDigest()).thenReturn(worldOwner.sourceEvidenceDigest());
+ when(association.worldSlug()).thenReturn(WORLD_SLUG);
+ PublicReceipt worldReceipt = mock(PublicReceipt.class);
+ when(worldReceipt.targetNamespace()).thenReturn(worldOwner.targetNamespace());
+ when(worldReceipt.canonicalTenantId()).thenReturn(worldOwner.canonicalTenantId());
+ when(worldReceipt.intakeRequestId()).thenReturn(worldOwner.intakeRequestId());
+ when(worldReceipt.operationId()).thenReturn(worldOwner.intakeOperationId());
+ when(worldReceipt.sourceOperationId()).thenReturn(worldOwner.sourceOperationId());
+ when(worldReceipt.sourceEvidenceDigest()).thenReturn(worldOwner.sourceEvidenceDigest());
+ when(worldReceipt.receiptDigest()).thenReturn(worldOwner.intakeReceiptDigest());
+ when(association.worldReceipt()).thenReturn(worldReceipt);
+
+ ParticipantDigest entityParticipant = entityParticipant(receipt, null);
+ PublishedReleaseBundle release =
+ PublishedReleaseBundle.newBuilder()
+ .setVersionId(
+ receipt.authorizationBinding().selected().target().gameDesignVersionRowId())
+ .setAttestationSchemaVersion("v4")
+ .setPublishWorkflowId(WORKFLOW)
+ .setCanonicalTenantId(receipt.canonicalTenantId().toString())
+ .setCanonicalVersionId(receipt.canonicalVersionId().toString())
+ .addParticipantDigests(entityParticipant)
+ .build();
+ Result associationRead = mock(Result.class);
+ when(associationRead.request()).thenReturn(originalRequest);
+ when(associationRead.association()).thenReturn(association);
+ when(associationRead.releaseBundle()).thenReturn(release);
+
+ AuthoredInitialActorCoreProjection projection = mock(AuthoredInitialActorCoreProjection.class);
+ when(projection.canonicalTenantId()).thenReturn(receipt.canonicalTenantId());
+ when(projection.canonicalVersionId()).thenReturn(receipt.canonicalVersionId());
+ when(projection.selectedCommitId()).thenReturn(receipt.selectedCommitId());
+ when(projection.selectedCommitDigest())
+ .thenReturn(receipt.authorizationBinding().selected().digest());
+ when(projection.worldSourceOperationId()).thenReturn(worldOwner.sourceOperationId());
+ when(projection.worldSourceEvidenceDigest()).thenReturn(worldOwner.sourceEvidenceDigest());
+ when(projection.worldSlug()).thenReturn(WORLD_SLUG);
+ when(projection.publicationWorkflowId()).thenReturn(WORKFLOW);
+
+ AuthoredInitialActorCoreReadEvidence.ReadResult result =
+ mock(AuthoredInitialActorCoreReadEvidence.ReadResult.class);
+ when(result.request()).thenReturn(originalRequest);
+ when(result.associationRead()).thenReturn(associationRead);
+ when(result.projections()).thenReturn(List.of(projection));
+ return new ReadSetup(request, result, associationRead, release, projection);
+ }
+
+ private static ParticipantDigest entityParticipant(
+ EntityEmptySelectedSourceIntakeReceipt receipt, String replacementDigest) {
+ var target = receipt.authorizationBinding().selected().target();
+ String inventoryJson =
+ receipt.inputs().ownerSourceInventoryDeclaration().entityInventory().canonicalJson();
+ String contentDigest =
+ EntitySelectedEmptyPublicationDigestService.contentDigest(
+ receipt.canonicalTenantId(),
+ target.gameDesignVersionRowId(),
+ receipt.canonicalVersionId(),
+ inventoryJson);
+ return ParticipantDigest.newBuilder()
+ .setParticipantKey("ENTITY_MANAGEMENT")
+ .setScopeValue(Long.toString(target.gameDesignVersionRowId()))
+ .setAppliedCommitId(receipt.selectedCommitId().toString())
+ .setContentDigest(replacementDigest == null ? contentDigest : replacementDigest)
+ .setDigestSchemaVersion(EntitySelectedEmptyPublicationDigestService.DIGEST_SCHEMA_VERSION)
+ .build();
+ }
+
+ private record ReadSetup(
+ AuthoredInitialActorCoreReadEvidence.ReadRequest request,
+ AuthoredInitialActorCoreReadEvidence.ReadResult result,
+ Result associationRead,
+ PublishedReleaseBundle release,
+ AuthoredInitialActorCoreProjection projection) {}
+}
diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java
new file mode 100644
index 0000000000..a13d9a401a
--- /dev/null
+++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java
@@ -0,0 +1,145 @@
+package net.firedevops.firemud.entitymanagement.sourceintake;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+
+import io.grpc.Context;
+import io.grpc.stub.StreamObserver;
+import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import net.firedevops.firemud.common.security.SessionContext;
+import net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService.EntityDraftDesignDigest;
+import net.firedevops.firemud.entitymanagement.v1.GetDraftDesignDigestRequest;
+import net.firedevops.firemud.entitymanagement.v1.GetDraftDesignDigestResponse;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+class EntitySelectedEmptyPublicationDigestGrpcReceiverTest {
+ private static final String NAMESPACE = "test";
+ private static final String TENANT = "11111111-1111-4111-8111-111111111111";
+ private static final String VERSION_ROW = "23";
+
+ @AfterEach
+ void clearSessionContext() {
+ SessionContext.clear();
+ }
+
+ @Test
+ void exactGameDesignPeerWithoutSessionContextCanReadValidatedFullVersionBinding() {
+ SessionContext.clear();
+ EntitySelectedEmptyPublicationDigestService digestService =
+ Mockito.mock(EntitySelectedEmptyPublicationDigestService.class);
+ PublicationDigestRequestBinding binding =
+ PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7");
+ Mockito.when(digestService.getDraftDesignDigest(any(PublicationDigestRequestBinding.class)))
+ .thenReturn(
+ new EntityDraftDesignDigest(TENANT, VERSION_ROW, "selected-commit", "a".repeat(64), 3));
+ EntitySelectedEmptyPublicationDigestGrpcReceiver receiver =
+ new EntitySelectedEmptyPublicationDigestGrpcReceiver(
+ digestService, NAMESPACE, new SimpleMeterRegistry());
+
+ GetDraftDesignDigestResponse response = invokeAsGameDesign(receiver, request(binding));
+
+ assertEquals("", response.getError().getCode());
+ assertEquals(TENANT, response.getTenantId());
+ assertEquals(VERSION_ROW, response.getVersionId());
+ assertEquals("selected-commit", response.getAppliedCommitId());
+ assertEquals("a".repeat(64), response.getContentDigest());
+ assertEquals(3, response.getDigestSchemaVersion());
+ verify(digestService).getDraftDesignDigest(any(PublicationDigestRequestBinding.class));
+ }
+
+ @Test
+ void accountOrGlobalOrScopedRoleContextDeniesEvenTheExactGameDesignPeer() {
+ EntitySelectedEmptyPublicationDigestService digestService =
+ Mockito.mock(EntitySelectedEmptyPublicationDigestService.class);
+ EntitySelectedEmptyPublicationDigestGrpcReceiver receiver =
+ new EntitySelectedEmptyPublicationDigestGrpcReceiver(
+ digestService, NAMESPACE, new SimpleMeterRegistry());
+ List deniedContexts =
+ List.of(
+ () -> SessionContext.setContext("user-1", List.of("player"), Map.of()),
+ () -> SessionContext.setContext(null, List.of("platformAdmin"), Map.of()),
+ () ->
+ SessionContext.setContext(
+ null, List.of(), Map.of("tenant-1", List.of("designer"))));
+ for (Runnable setDeniedContext : deniedContexts) {
+ SessionContext.clear();
+ setDeniedContext.run();
+ GetDraftDesignDigestResponse response =
+ invokeAsGameDesign(
+ receiver,
+ request(PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7")));
+ assertEquals("PERMISSION_DENIED", response.getError().getCode());
+ }
+ verifyNoInteractions(digestService);
+ }
+
+ @Test
+ void changedCompleteRequestBindingIsRejectedBeforeReceiptLookup() {
+ SessionContext.clear();
+ EntitySelectedEmptyPublicationDigestService digestService =
+ Mockito.mock(EntitySelectedEmptyPublicationDigestService.class);
+ EntitySelectedEmptyPublicationDigestGrpcReceiver receiver =
+ new EntitySelectedEmptyPublicationDigestGrpcReceiver(
+ digestService, NAMESPACE, new SimpleMeterRegistry());
+ GetDraftDesignDigestRequest changedRequest =
+ request(PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7")).toBuilder()
+ .setRequestDigest("0".repeat(64))
+ .build();
+
+ GetDraftDesignDigestResponse response = invokeAsGameDesign(receiver, changedRequest);
+
+ assertEquals("INVALID_ARGUMENT", response.getError().getCode());
+ verifyNoInteractions(digestService);
+ }
+
+ private static GetDraftDesignDigestRequest request(PublicationDigestRequestBinding binding) {
+ return GetDraftDesignDigestRequest.newBuilder()
+ .setTenantId(binding.tenantId())
+ .setVersionId(binding.versionId())
+ .setPublishRequestId(binding.publishRequestId())
+ .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity())
+ .setRequestDigest(binding.requestDigest())
+ .build();
+ }
+
+ private static GetDraftDesignDigestResponse invokeAsGameDesign(
+ EntitySelectedEmptyPublicationDigestGrpcReceiver receiver,
+ GetDraftDesignDigestRequest request) {
+ AtomicReference response = new AtomicReference<>();
+ Context.current()
+ .withValue(
+ GrpcPeerIdentity.CONTEXT_KEY,
+ new GrpcPeerIdentity(
+ "spiffe://firemud/ns/test/sa/game-design-service",
+ NAMESPACE,
+ "game-design-service"))
+ .run(
+ () ->
+ receiver.getDraftDesignDigest(
+ request,
+ new StreamObserver<>() {
+ @Override
+ public void onNext(GetDraftDesignDigestResponse value) {
+ response.set(value);
+ }
+
+ @Override
+ public void onError(Throwable error) {
+ throw new AssertionError(error);
+ }
+
+ @Override
+ public void onCompleted() {}
+ }));
+ return response.get();
+ }
+}
diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcServiceTest.java
new file mode 100644
index 0000000000..36b567d15d
--- /dev/null
+++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcServiceTest.java
@@ -0,0 +1,232 @@
+package unit.net.firedevops.firemud.entitymanagement.sourceintake;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import io.grpc.Context;
+import io.grpc.Status;
+import io.grpc.stub.StreamObserver;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence;
+import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandGrpcCodec;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
+import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec;
+import net.firedevops.firemud.common.security.SessionContext;
+import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeService;
+import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedSourceIntakeCommandGrpcService;
+import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceRequest;
+import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceResponse;
+import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures;
+import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Mocked owner tests verify gates and delegation, not native producer or physical census proof. */
+class EntitySelectedSourceIntakeCommandGrpcServiceTest {
+ private static final String NAMESPACE = "test";
+ private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service";
+ private static Fixture fixture;
+
+ @BeforeAll
+ static void createSyntheticEntityInputs() {
+ fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create();
+ }
+
+ @BeforeEach
+ @AfterEach
+ void clearContexts() {
+ SessionContext.clear();
+ TransactionSynchronizationManager.clear();
+ }
+
+ @Test
+ void authenticatedGameDesignGetsExactRetainedReceiptFromOwner() {
+ var owner = mock(EntityEmptySelectedSourceIntakeService.class);
+ var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence();
+ var request =
+ EntitySelectedSourceIntakeCommandEvidence.Request.create(
+ NAMESPACE, fixture.authorization(), freeze);
+ when(owner.retain(
+ eq(NAMESPACE),
+ any(SelectedOwnerIntakeAuthorizationBinding.class),
+ any(WorldSelectedDraftPublicationFreezeEvidence.class)))
+ .thenReturn(fixture.receipt());
+ var service = new EntitySelectedSourceIntakeCommandGrpcService(owner, NAMESPACE);
+ var observedResponse = new AtomicReference();
+ var observer = new CapturingObserver(observedResponse);
+ var accountContext = gameDesignPeer(NAMESPACE);
+ var previous = accountContext.attach();
+ try {
+ service.retainSelectedEntitySource(
+ EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(request), observer);
+ } finally {
+ accountContext.detach(previous);
+ }
+
+ assertThat(observer.failure()).isNull();
+ assertThat(observedResponse.get()).isNotNull();
+ assertThat(observedResponse.get().getRequest())
+ .isEqualTo(EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(request));
+ var evidence =
+ EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse(request, observedResponse.get());
+ assertThat(evidence.receipt().canonicalBytes()).isEqualTo(fixture.receipt().canonicalBytes());
+ var authorizationArgument =
+ ArgumentCaptor.forClass(SelectedOwnerIntakeAuthorizationBinding.class);
+ var freezeArgument = ArgumentCaptor.forClass(WorldSelectedDraftPublicationFreezeEvidence.class);
+ verify(owner).retain(eq(NAMESPACE), authorizationArgument.capture(), freezeArgument.capture());
+ assertThat(authorizationArgument.getValue().canonicalBytes())
+ .isEqualTo(fixture.authorization().canonicalBytes());
+ assertThat(
+ WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(
+ freezeArgument.getValue().request()))
+ .isEqualTo(WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freeze.request()));
+ assertThat(
+ WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(
+ freezeArgument.getValue().acknowledgement()))
+ .isEqualTo(
+ WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freeze.acknowledgement()));
+ }
+
+ @Test
+ void rejectsMissingWrongPeerAndWrongNamespaceBeforeDecodeOrOwnerInvocation() {
+ var owner = mock(EntityEmptySelectedSourceIntakeService.class);
+ var service = new EntitySelectedSourceIntakeCommandGrpcService(owner, NAMESPACE);
+
+ var missingPeer = new CapturingObserver(new AtomicReference<>());
+ service.retainSelectedEntitySource(
+ RetainSelectedEntitySourceRequest.getDefaultInstance(), missingPeer);
+ assertCode(missingPeer.failure(), Status.Code.UNAUTHENTICATED);
+
+ var wrongPeer = gameDesignPeer("other");
+ var previous = wrongPeer.attach();
+ try {
+ var denied = new CapturingObserver(new AtomicReference<>());
+ service.retainSelectedEntitySource(
+ RetainSelectedEntitySourceRequest.getDefaultInstance(), denied);
+ assertCode(denied.failure(), Status.Code.PERMISSION_DENIED);
+ } finally {
+ wrongPeer.detach(previous);
+ }
+
+ var goodPeer = gameDesignPeer(NAMESPACE);
+ previous = goodPeer.attach();
+ try {
+ var mismatchedTarget = new CapturingObserver(new AtomicReference<>());
+ service.retainSelectedEntitySource(
+ RetainSelectedEntitySourceRequest.newBuilder().setTargetNamespace("other").build(),
+ mismatchedTarget);
+ assertCode(mismatchedTarget.failure(), Status.Code.PERMISSION_DENIED);
+ } finally {
+ goodPeer.detach(previous);
+ }
+ verifyNoInteractions(owner);
+ }
+
+ @Test
+ void rejectsEndUserSelectedOrderAndAmbientSqlBeforeMalformedEvidenceDecode() {
+ var owner = mock(EntityEmptySelectedSourceIntakeService.class);
+ var service = new EntitySelectedSourceIntakeCommandGrpcService(owner, NAMESPACE);
+ var peer = gameDesignPeer(NAMESPACE);
+ var malformed = RetainSelectedEntitySourceRequest.getDefaultInstance();
+ var previous = peer.attach();
+ try {
+ SessionContext.setContext("101", List.of(), Map.of());
+ var endUser = new CapturingObserver(new AtomicReference<>());
+ service.retainSelectedEntitySource(malformed, endUser);
+ assertCode(endUser.failure(), Status.Code.PERMISSION_DENIED);
+ SessionContext.clear();
+
+ for (Context credentialContext : List.of(
+ Context.current().withValue(AccountOriginalDraftOrderCredentials.CONTEXT_KEY,
+ AccountOriginalDraftOrderCredentials.Credential.of("synthetic-original-order")),
+ Context.current().withValue(SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY,
+ SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of("synthetic-owner-intake")),
+ Context.current().withValue(AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY,
+ AccountGameLogicIntakeAuthorizationCredentials.Credential.of("synthetic-logic-intake")))) {
+ var credentialPrevious = credentialContext.attach();
+ try {
+ var denied = new CapturingObserver(new AtomicReference<>());
+ service.retainSelectedEntitySource(malformed, denied);
+ assertCode(denied.failure(), Status.Code.PERMISSION_DENIED);
+ } finally {
+ credentialContext.detach(credentialPrevious);
+ }
+ }
+
+ var malformedEvidence =
+ RetainSelectedEntitySourceRequest.newBuilder().setTargetNamespace(NAMESPACE).build();
+ TransactionSynchronizationManager.setActualTransactionActive(true);
+ var activeSql = new CapturingObserver(new AtomicReference<>());
+ service.retainSelectedEntitySource(malformedEvidence, activeSql);
+ assertCode(activeSql.failure(), Status.Code.FAILED_PRECONDITION);
+ TransactionSynchronizationManager.clear();
+
+ TransactionSynchronizationManager.initSynchronization();
+ var synchronizedSql = new CapturingObserver(new AtomicReference<>());
+ service.retainSelectedEntitySource(malformedEvidence, synchronizedSql);
+ assertCode(synchronizedSql.failure(), Status.Code.FAILED_PRECONDITION);
+ TransactionSynchronizationManager.clear();
+
+ var invalidEvidence = new CapturingObserver(new AtomicReference<>());
+ service.retainSelectedEntitySource(malformedEvidence, invalidEvidence);
+ assertCode(invalidEvidence.failure(), Status.Code.INVALID_ARGUMENT);
+ } finally {
+ peer.detach(previous);
+ }
+ verifyNoInteractions(owner);
+ }
+
+ private static void assertCode(Throwable error, Status.Code expected) {
+ assertThat(error).isNotNull();
+ assertThat(Status.fromThrowable(error).getCode()).isEqualTo(expected);
+ }
+
+ private static Context gameDesignPeer(String namespace) {
+ String uri = "spiffe://firemud/ns/" + namespace + "/sa/game-design-service";
+ return Context.ROOT.withValue(
+ GrpcPeerIdentity.CONTEXT_KEY, new GrpcPeerIdentity(uri, namespace, "game-design-service"));
+ }
+
+ private static final class CapturingObserver
+ implements StreamObserver {
+ private final AtomicReference response;
+ private final AtomicReference failure = new AtomicReference<>();
+
+ private CapturingObserver(AtomicReference response) {
+ this.response = response;
+ }
+
+ @Override
+ public void onNext(RetainSelectedEntitySourceResponse value) {
+ response.set(value);
+ }
+
+ @Override
+ public void onError(Throwable error) {
+ failure.set(error);
+ }
+
+ @Override
+ public void onCompleted() {}
+
+ Throwable failure() {
+ return failure.get();
+ }
+ }
+}
diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadServiceTest.java
new file mode 100644
index 0000000000..62602d2c15
--- /dev/null
+++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadServiceTest.java
@@ -0,0 +1,295 @@
+package net.firedevops.firemud.entitymanagement.sourceintake;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import io.grpc.Context;
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import io.grpc.stub.StreamObserver;
+import java.util.Optional;
+import java.util.concurrent.atomic.AtomicReference;
+import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence;
+import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadGrpcCodec;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.security.SessionContext;
+import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalRequest;
+import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalResponse;
+import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures;
+import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Synthetic receipt/peer tests do not establish Entity producer or database proof. */
+class EntitySelectedSourceIntakeTerminalReadServiceTest {
+ private static final String NAMESPACE = "test";
+ private static Fixture fixture;
+
+ @BeforeAll
+ static void createSyntheticReceiptFixture() {
+ fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create();
+ }
+
+ @BeforeEach
+ @AfterEach
+ void clearContexts() {
+ SessionContext.clear();
+ TransactionSynchronizationManager.clear();
+ }
+
+ @Test
+ void exactRetriesReadOnlyTheCommittedReceiptAndUseDistinctReadCorrelations() {
+ var repository = mock(EntityEmptySelectedSourceIntakeRepository.class);
+ var binding = fixture.authorization();
+ when(repository.read(NAMESPACE, binding.intakeRequestId()))
+ .thenReturn(Optional.of(fixture.receipt()));
+ var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE);
+ var accountContext = accountPeer(NAMESPACE);
+ var previous = accountContext.attach();
+ try {
+ var first = service.read(request(binding));
+ var retry = service.read(request(binding));
+
+ assertThat(first.receipt()).isSameAs(fixture.receipt());
+ assertThat(retry.receipt()).isSameAs(fixture.receipt());
+ assertThat(first.request().readRequestId()).isNotEqualTo(retry.request().readRequestId());
+ assertThat(first.receipt().canonicalBytes()).isEqualTo(fixture.receipt().canonicalBytes());
+ verify(repository, times(2)).read(NAMESPACE, binding.intakeRequestId());
+ } finally {
+ accountContext.detach(previous);
+ }
+ }
+
+ @Test
+ void grpcReturnsTheExactFullReceiptWithoutRemintingIt() {
+ var repository = mock(EntityEmptySelectedSourceIntakeRepository.class);
+ var binding = fixture.authorization();
+ when(repository.read(NAMESPACE, binding.intakeRequestId()))
+ .thenReturn(Optional.of(fixture.receipt()));
+ var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE);
+ var grpc = new EntitySelectedSourceIntakeTerminalReadGrpcService(service);
+ var request = request(binding);
+ var observedResponse = new AtomicReference();
+ var observedError = new AtomicReference();
+ var observer = responseObserver(observedResponse, observedError);
+ var accountContext = accountPeer(NAMESPACE);
+ var previous = accountContext.attach();
+ try {
+ grpc.readSelectedSourceIntakeTerminal(
+ EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request), observer);
+ } finally {
+ accountContext.detach(previous);
+ }
+
+ assertThat(observedError.get()).isNull();
+ var response = observedResponse.get();
+ assertThat(response).isNotNull();
+ assertThat(response.getRequest())
+ .isEqualTo(EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request));
+ var decoded = EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse(request, response);
+ assertThat(decoded.receipt().canonicalBytes()).isEqualTo(fixture.receipt().canonicalBytes());
+ assertThat(decoded.receipt().authorizationBindingBytes())
+ .isEqualTo(fixture.authorization().canonicalBytes());
+ verify(repository).read(NAMESPACE, binding.intakeRequestId());
+ }
+
+ @Test
+ void absentReceiptIsNotConvertedToAnAbortOrAnyTerminalEvidence() {
+ var repository = mock(EntityEmptySelectedSourceIntakeRepository.class);
+ var binding = fixture.authorization();
+ when(repository.read(NAMESPACE, binding.intakeRequestId())).thenReturn(Optional.empty());
+ var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE);
+ var accountContext = accountPeer(NAMESPACE);
+ var previous = accountContext.attach();
+ try {
+ assertStatus(() -> service.read(request(binding)), Status.Code.NOT_FOUND);
+ } finally {
+ accountContext.detach(previous);
+ }
+ verify(repository).read(NAMESPACE, binding.intakeRequestId());
+ }
+
+ @Test
+ void changedCompleteOriginalAuthorizationIsAlreadyExistsAndCorruptReadbackIsDataLoss() {
+ var repository = mock(EntityEmptySelectedSourceIntakeRepository.class);
+ var changedAuthorization =
+ EntitySelectedSourceIntakeTerminalReadFixtures.create().authorization();
+ assertThat(changedAuthorization.intakeRequestId())
+ .isEqualTo(fixture.authorization().intakeRequestId());
+ assertThat(changedAuthorization.canonicalBytes())
+ .isNotEqualTo(fixture.authorization().canonicalBytes());
+ when(repository.read(NAMESPACE, fixture.authorization().intakeRequestId()))
+ .thenReturn(Optional.of(fixture.receipt()));
+ var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE);
+ var accountContext = accountPeer(NAMESPACE);
+ var previous = accountContext.attach();
+ try {
+ assertStatus(() -> service.read(request(changedAuthorization)), Status.Code.ALREADY_EXISTS);
+
+ when(repository.read(NAMESPACE, fixture.authorization().intakeRequestId()))
+ .thenThrow(new IllegalArgumentException("corrupt stored Entity receipt"));
+ assertStatus(() -> service.read(request(fixture.authorization())), Status.Code.DATA_LOSS);
+ } finally {
+ accountContext.detach(previous);
+ }
+ }
+
+ @Test
+ void rejectsWrongPeerNamespaceOwnerEndUserAndAmbientSqlBeforeRepositoryRead() {
+ var repository = mock(EntityEmptySelectedSourceIntakeRepository.class);
+ var request = request(fixture.authorization());
+ var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE);
+
+ assertStatus(() -> service.read(request), Status.Code.UNAUTHENTICATED);
+
+ var wrongPeer =
+ Context.current()
+ .withValue(
+ GrpcPeerIdentity.CONTEXT_KEY,
+ new GrpcPeerIdentity(
+ "spiffe://firemud/ns/test/sa/game-design-service",
+ NAMESPACE,
+ "game-design-service"));
+ var previous = wrongPeer.attach();
+ try {
+ assertStatus(() -> service.read(request), Status.Code.PERMISSION_DENIED);
+ } finally {
+ wrongPeer.detach(previous);
+ }
+
+ var otherNamespaceService =
+ new EntityEmptySelectedSourceIntakeTerminalReadService(repository, "other");
+ var otherAccount = accountPeer("other");
+ previous = otherAccount.attach();
+ try {
+ assertStatus(() -> otherNamespaceService.read(request), Status.Code.PERMISSION_DENIED);
+ } finally {
+ otherAccount.detach(previous);
+ }
+
+ assertThatThrownBy(
+ () ->
+ EntitySelectedSourceIntakeTerminalReadEvidence.Request.create(
+ NAMESPACE, fixture.wrongOwnerAuthorization()))
+ .isInstanceOf(IllegalArgumentException.class);
+
+ var accountContext = accountPeer(NAMESPACE);
+ previous = accountContext.attach();
+ try {
+ SessionContext.setContext("101", java.util.List.of(), java.util.Map.of());
+ assertStatus(() -> service.read(request), Status.Code.PERMISSION_DENIED);
+ SessionContext.clear();
+
+ TransactionSynchronizationManager.setActualTransactionActive(true);
+ assertStatus(() -> service.read(request), Status.Code.FAILED_PRECONDITION);
+ TransactionSynchronizationManager.setActualTransactionActive(false);
+
+ TransactionSynchronizationManager.initSynchronization();
+ assertStatus(() -> service.read(request), Status.Code.FAILED_PRECONDITION);
+ TransactionSynchronizationManager.clearSynchronization();
+ } finally {
+ accountContext.detach(previous);
+ }
+ verifyNoInteractions(repository);
+ }
+
+ @Test
+ void grpcAuthenticatesBeforeMalformedRequestDecodeOrRepositoryLookup() {
+ var repository = mock(EntityEmptySelectedSourceIntakeRepository.class);
+ var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE);
+ var grpc = new EntitySelectedSourceIntakeTerminalReadGrpcService(service);
+
+ var unauthenticatedError = invokeMalformed(grpc, null);
+ assertThat(Status.fromThrowable(unauthenticatedError).getCode())
+ .isEqualTo(Status.Code.UNAUTHENTICATED);
+
+ var wrongPeer =
+ Context.current()
+ .withValue(
+ GrpcPeerIdentity.CONTEXT_KEY,
+ new GrpcPeerIdentity(
+ "spiffe://firemud/ns/test/sa/game-design-service",
+ NAMESPACE,
+ "game-design-service"));
+ var previous = wrongPeer.attach();
+ try {
+ assertThat(Status.fromThrowable(invokeMalformed(grpc, null)).getCode())
+ .isEqualTo(Status.Code.PERMISSION_DENIED);
+ } finally {
+ wrongPeer.detach(previous);
+ }
+
+ var accountContext = accountPeer(NAMESPACE);
+ previous = accountContext.attach();
+ try {
+ assertThat(
+ Status.fromThrowable(
+ invokeMalformed(
+ grpc, ReadSelectedSourceIntakeTerminalRequest.getDefaultInstance()))
+ .getCode())
+ .isEqualTo(Status.Code.INVALID_ARGUMENT);
+ } finally {
+ accountContext.detach(previous);
+ }
+ verifyNoInteractions(repository);
+ }
+
+ private static EntitySelectedSourceIntakeTerminalReadEvidence.Request request(
+ net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding
+ binding) {
+ return EntitySelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, binding);
+ }
+
+ private static void assertStatus(Runnable action, Status.Code expected) {
+ assertThatThrownBy(action::run)
+ .isInstanceOf(StatusRuntimeException.class)
+ .satisfies(
+ failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected));
+ }
+
+ private static Context accountPeer(String namespace) {
+ String uri = "spiffe://firemud/ns/" + namespace + "/sa/account-service";
+ return Context.ROOT.withValue(
+ GrpcPeerIdentity.CONTEXT_KEY, new GrpcPeerIdentity(uri, namespace, "account-service"));
+ }
+
+ private static Throwable invokeMalformed(
+ EntitySelectedSourceIntakeTerminalReadGrpcService grpc,
+ ReadSelectedSourceIntakeTerminalRequest request) {
+ var observedResponse = new AtomicReference();
+ var observedError = new AtomicReference();
+ grpc.readSelectedSourceIntakeTerminal(
+ request == null ? ReadSelectedSourceIntakeTerminalRequest.getDefaultInstance() : request,
+ responseObserver(observedResponse, observedError));
+ assertThat(observedResponse.get()).isNull();
+ assertThat(observedError.get()).isNotNull();
+ return observedError.get();
+ }
+
+ private static StreamObserver responseObserver(
+ AtomicReference response,
+ AtomicReference error) {
+ return new StreamObserver<>() {
+ @Override
+ public void onNext(ReadSelectedSourceIntakeTerminalResponse value) {
+ response.set(value);
+ }
+
+ @Override
+ public void onError(Throwable failure) {
+ error.set(failure);
+ }
+
+ @Override
+ public void onCompleted() {}
+ };
+ }
+}
diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts
index 2487dd676f..e72218dafb 100644
--- a/services/game-design-service/build.gradle.kts
+++ b/services/game-design-service/build.gradle.kts
@@ -31,11 +31,26 @@ dependencies {
implementation(libs.aws.sdk.s3)
testCompileOnly(libs.spotbugs.annotations)
add("integrationTestCompileOnly", libs.spotbugs.annotations)
- add("crossServiceTestImplementation", project(":game-session-service"))
+ add(
+ "crossServiceTestImplementation",
+ project(mapOf("path" to ":game-session-service", "configuration" to "gameSessionClassesProof"))
+ )
+ add(
+ "crossServiceTestImplementation",
+ project(mapOf("path" to ":entity-management-service", "configuration" to "entityClassesProof"))
+ )
+ add(
+ "crossServiceTestImplementation",
+ project(mapOf("path" to ":automation-scripting-service", "configuration" to "automationClassesProof"))
+ )
add(
"crossServiceTestImplementation",
project(mapOf("path" to ":world-management-service", "configuration" to "worldClassesProof"))
)
+ add(
+ "crossServiceTestImplementation",
+ project(mapOf("path" to ":world-management-service", "configuration" to "worldSelectedPublicationProof"))
+ )
add(
"crossServiceTestImplementation",
project(mapOf("path" to ":account-service", "configuration" to "accountOriginalOrderProof"))
@@ -66,6 +81,10 @@ val gameDesignClassesProof by configurations.creating {
// Composed owner proofs load foreign migrations from disk; classes-only artifacts omit them.
tasks.named("crossServiceTest") {
+ inputs.dir(rootProject.layout.projectDirectory.dir("services/entity-management-service/src/main/resources/db/migration"))
+ .withPropertyName("entityOwnerMigrations")
+ inputs.dir(rootProject.layout.projectDirectory.dir("services/automation-scripting-service/src/main/resources/db/migration"))
+ .withPropertyName("automationOwnerMigrations")
inputs.dir(rootProject.layout.projectDirectory.dir("services/account-service/src/main/resources/db/migration"))
.withPropertyName("accountOwnerMigrations")
inputs.dir(rootProject.layout.projectDirectory.dir("services/game-logic-service/src/main/resources/db/migration"))
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java
index 534d5011b6..040bb66cc3 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java
@@ -1,28 +1,49 @@
package net.firedevops.firemud.gamedesign.client;
+import io.grpc.ManagedChannel;
import jakarta.annotation.PostConstruct;
import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLException;
import net.firedevops.firemud.common.config.ServiceEndpointsProperties;
+import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding;
+import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadGrpcCodec;
import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient;
import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer;
import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties;
import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials;
+import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor;
import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto;
+import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt;
import net.firedevops.firemud.gamelogic.v1.GameLogicServiceGrpc;
-import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestRequest;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
@Component
public class GameLogicClient
extends AbstractReloadingBlockingGrpcClient {
+ private static final long CALL_DEADLINE_SECONDS = 5L;
+
+ private final CommonGrpcClientProperties tlsProps;
+
+ @Value("${firemud.grpc.workload-namespace:}")
+ private String workloadNamespace;
+
public GameLogicClient(
ServiceEndpointsProperties endpoints,
CommonGrpcClientProperties tlsProps,
GrpcChannelFactory channelFactory,
BlockingGrpcStubCustomizer stubCustomizer) {
super(endpoints, tlsProps, channelFactory, stubCustomizer, GameLogicClient.class);
+ this.tlsProps = tlsProps.copy();
}
@PostConstruct
@@ -41,57 +62,147 @@ protected String defaultTarget() {
}
@Override
- protected GameLogicServiceGrpc.GameLogicServiceBlockingStub buildStub(
- io.grpc.ManagedChannel channel) {
+ protected GameLogicServiceGrpc.GameLogicServiceBlockingStub buildStub(ManagedChannel channel) {
return applyStubCustomizer(
GameLogicServiceGrpc.newBlockingStub(channel).withCompression("gzip"));
}
+ /**
+ * Legacy publication read cannot prove the selected Account authorization and is deliberately
+ * closed. Full-version publication must use the immutable-receipt overload below.
+ */
public PublishParticipantDigestDto getDraftDesignDigestForVersion(
PublicationDigestRequestBinding binding) {
+ Objects.requireNonNull(binding, "binding");
+ String versionId = requireFullVersionId(binding);
+ return failure(
+ versionId,
+ "SELECTED_GAME_LOGIC_RECEIPT_REQUIRED",
+ "exact retained Game Logic receipt is required for a full-version publication read");
+ }
+
+ /** Reads the retained full-version digest selected by the original Account receipt. */
+ public PublishParticipantDigestDto getDraftDesignDigestForVersion(
+ PublicationDigestRequestBinding binding, SelectedDraftGameLogicReceipt receipt) {
+ Objects.requireNonNull(binding, "binding");
+ Objects.requireNonNull(receipt, "receipt");
+ String versionId = requireFullVersionId(binding);
+ requireOutsideSql();
+ if (!receipt.selection().intent().publishRequestId().equals(binding.publishRequestId())
+ || !receipt.workflowIdentity().equals(binding.derivedWorkflowIdentity())) {
+ throw new IllegalArgumentException(
+ "publication request differs from immutable selected Game Logic receipt");
+ }
+
+ // The receipt constructor enforces the Account-finalized RETAINED terminal. Use its exact
+ // original authorization, never IDs or bytes from an ambient/latest source lookup.
+ GameLogicPublicationSourceReadBinding expectedBinding =
+ new GameLogicPublicationSourceReadBinding(binding, receipt.authorization());
+ var request = GameLogicPublicationSourceReadGrpcCodec.toRequest(expectedBinding);
var response =
- stub()
- .getDraftDesignDigest(
- GetDraftDesignDigestRequest.newBuilder()
- .setTenantId(binding.tenantId())
- .setVersionId(requireFullVersionId(binding))
- .setPublishRequestId(binding.publishRequestId())
- .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity())
- .setRequestDigest(binding.requestDigest())
- .build());
+ requirePublicationReadStub()
+ .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS)
+ .getDraftDesignDigest(request);
if (response.hasError() && !response.getError().getCode().isBlank()) {
- return new PublishParticipantDigestDto(
- "GAME_LOGIC",
- binding.versionId(),
- null,
- null,
- null,
- response.getError().getCode(),
- response.getError().getMessage());
+ return failure(versionId, response.getError().getCode(), response.getError().getMessage());
}
- if (!binding.tenantId().equals(response.getTenantId())
- || !response.hasVersionId()
- || !binding.versionId().equals(response.getVersionId())
- || !response.getBaseVersionId().isEmpty()) {
- return new PublishParticipantDigestDto(
- "GAME_LOGIC",
- binding.versionId(),
- null,
- null,
- null,
- "RESPONSE_BINDING_MISMATCH",
- "owner returned tenant or typed full-version scope that does not match request");
+
+ GameLogicPublicationSourceReadGrpcCodec.Evidence evidence;
+ try {
+ evidence =
+ GameLogicPublicationSourceReadGrpcCodec.fromResponse(
+ expectedBinding, response, workloadNamespace);
+ } catch (IllegalArgumentException invalid) {
+ return failure(versionId, "RESPONSE_BINDING_MISMATCH", invalid.getMessage());
+ }
+ if (!Arrays.equals(
+ receipt.receipt().terminal().canonicalBytes(), evidence.terminal().canonicalBytes())) {
+ return failure(
+ versionId,
+ "RESPONSE_TERMINAL_MISMATCH",
+ "owner terminal differs from the immutable Account-finalized receipt");
}
+
+ // The authenticated owner response remains sha256:-prefixed. Release participants carry the
+ // same aggregate hash as bare hex; keep the separately scoped ability digest unchanged.
return new PublishParticipantDigestDto(
"GAME_LOGIC",
- response.getVersionId(),
- response.getAppliedCommitId(),
- response.getContentDigest(),
- response.getDigestSchemaVersion(),
+ versionId,
+ null,
+ receipt.authorization().source().binding().commitId().toString(),
+ evidence.manifestDigest().substring("sha256:".length()),
+ evidence.digestSchemaVersion(),
+ evidence.abilitySchemaDigest(),
null,
null);
}
+ private GameLogicServiceGrpc.GameLogicServiceBlockingStub requirePublicationReadStub() {
+ requireFileBackedMtls(tlsProps);
+ if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) {
+ throw new IllegalStateException(
+ "Game Logic publication reads require the configured workload namespace");
+ }
+ var current = stub();
+ if (current == null) {
+ throw new IllegalStateException("Game Logic publication client is not initialized");
+ }
+ String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-logic-service";
+ return current
+ .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri))
+ .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri))
+ .withMaxInboundMessageSize(GameLogicPublicationSourceReadGrpcCodec.MAX_WIRE_BYTES);
+ }
+
+ private static void requireOutsideSql() {
+ if (TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isSynchronizationActive()) {
+ throw new IllegalStateException(
+ "Game Logic publication source reads require no ambient SQL transaction");
+ }
+ }
+
+ private static CommonGrpcClientProperties requireFileBackedMtls(
+ CommonGrpcClientProperties tlsProperties) {
+ if (tlsProperties == null || tlsProperties.isPlaintext()) {
+ throw new IllegalStateException(
+ "Game Logic publication source reads require file-backed workload mTLS");
+ }
+ requireReadableFile(tlsProperties.getCertChain(), "certificate chain");
+ requireReadableFile(tlsProperties.getPrivateKey(), "private key");
+ requireReadableFile(tlsProperties.getCaCert(), "CA certificate");
+ return tlsProperties;
+ }
+
+ private static void requireReadableFile(String configuredPath, String label) {
+ if (configuredPath == null || configuredPath.isBlank()) {
+ throw new IllegalStateException(
+ "Game Logic publication source reads require file-backed TLS certificate, key, and CA");
+ }
+ String pathText = configuredPath.trim();
+ if (pathText.startsWith("classpath:")) {
+ throw new IllegalStateException(
+ "Game Logic publication source reads require file-backed TLS certificate, key, and CA");
+ }
+ Path path;
+ try {
+ path = Path.of(pathText);
+ } catch (RuntimeException invalid) {
+ throw new IllegalStateException(
+ "Game Logic publication source-read " + label + " must be a file-backed path", invalid);
+ }
+ if (!Files.isRegularFile(path) || !Files.isReadable(path)) {
+ throw new IllegalStateException(
+ "Game Logic publication source-read " + label + " must be an existing readable file");
+ }
+ }
+
+ private static PublishParticipantDigestDto failure(
+ String versionId, String errorCode, String errorMessage) {
+ return new PublishParticipantDigestDto(
+ "GAME_LOGIC", versionId, null, null, null, null, errorCode, errorMessage);
+ }
+
private String requireFullVersionId(PublicationDigestRequestBinding binding) {
if (binding.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) {
throw new IllegalArgumentException("full-version binding required");
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java
new file mode 100644
index 0000000000..a089d40757
--- /dev/null
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java
@@ -0,0 +1,114 @@
+package net.firedevops.firemud.gamedesign.draft;
+
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import io.grpc.stub.StreamObserver;
+import java.util.Arrays;
+import java.util.Objects;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.security.SessionContext;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec;
+import net.firedevops.firemud.gamedesign.v1.GameDesignSelectedDraftPublicationReadServiceGrpc;
+import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationRequest;
+import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationResponse;
+
+/**
+ * Standalone, unregistered immutable selection owner read. Does not inspect mutable Version state
+ * or establish actor authorization, source holds, World freeze, release, or runtime admission.
+ */
+public final class GameDesignSelectedDraftPublicationReadGrpcService
+ extends GameDesignSelectedDraftPublicationReadServiceGrpc
+ .GameDesignSelectedDraftPublicationReadServiceImplBase {
+ private final AuthoredDraftPublishSelectionRepository repository;
+ private final String trustedNamespace;
+
+ public GameDesignSelectedDraftPublicationReadGrpcService(
+ AuthoredDraftPublishSelectionRepository repository, String trustedNamespace) {
+ this.repository = Objects.requireNonNull(repository, "repository");
+ if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) {
+ throw new IllegalArgumentException("Canonical Game Design workload namespace required");
+ }
+ this.trustedNamespace = trustedNamespace;
+ }
+
+ @Override
+ public void readSelectedDraftPublication(
+ ReadSelectedDraftPublicationRequest request,
+ StreamObserver observer) {
+ try {
+ requirePeer();
+ } catch (StatusRuntimeException denied) {
+ observer.onError(denied);
+ return;
+ }
+ final AuthoredDraftPublishSelectionReadEvidence.Request decoded;
+ try {
+ decoded = AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest(request);
+ } catch (IllegalArgumentException malformed) {
+ observer.onError(
+ Status.INVALID_ARGUMENT
+ .withDescription("Canonical selected Draft publication read required")
+ .asRuntimeException());
+ return;
+ }
+ if (!trustedNamespace.equals(decoded.targetNamespace())) {
+ observer.onError(
+ Status.PERMISSION_DENIED
+ .withDescription("Selection namespace differs from peer")
+ .asRuntimeException());
+ return;
+ }
+ final ReadSelectedDraftPublicationResponse response;
+ try {
+ var intent = decoded.binding().intent();
+ var retained =
+ repository.read(
+ intent.canonicalTenantId(), intent.canonicalVersionId(), intent.publishRequestId());
+ if (retained.isEmpty()) {
+ throw Status.NOT_FOUND
+ .withDescription("Exact selected Draft publication unavailable")
+ .asRuntimeException();
+ }
+ var selection = retained.orElseThrow().selection();
+ if (!Arrays.equals(selection.canonicalBytes(), decoded.originalSelection())
+ || !selection.digest().equals(decoded.selectionDigest())) {
+ throw Status.FAILED_PRECONDITION
+ .withDescription("Retained selection differs from request")
+ .asRuntimeException();
+ }
+ response = AuthoredDraftPublishSelectionReadGrpcCodec.toSelectedResponse(decoded);
+ } catch (StatusRuntimeException failure) {
+ observer.onError(
+ Status.fromCode(Status.fromThrowable(failure).getCode())
+ .withDescription("Selected Draft publication read denied or unavailable")
+ .asRuntimeException());
+ return;
+ } catch (RuntimeException unavailable) {
+ observer.onError(
+ Status.UNAVAILABLE
+ .withDescription("Game Design selection storage unavailable")
+ .asRuntimeException());
+ return;
+ }
+ observer.onNext(response);
+ observer.onCompleted();
+ }
+
+ private void requirePeer() {
+ var peer = GrpcPeerIdentity.current();
+ if (peer == null) {
+ throw Status.UNAUTHENTICATED
+ .withDescription("Verified workload identity required")
+ .asRuntimeException();
+ }
+ if (SessionContext.hasAuthenticatedCallerContext()
+ || (!("spiffe://firemud/ns/" + trustedNamespace + "/sa/account-service").equals(peer.uri())
+ && !("spiffe://firemud/ns/" + trustedNamespace + "/sa/world-management-service")
+ .equals(peer.uri()))) {
+ throw Status.PERMISSION_DENIED
+ .withDescription("Exact same-namespace Account or World Management workload required")
+ .asRuntimeException();
+ }
+ }
+}
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java
index b8cd545f21..e3d108989f 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java
@@ -37,9 +37,11 @@ public record PublishedReleaseBundleDto(
"Manifest schema and artifact proof must be present together");
}
artifactDigests = artifactDigests == null ? null : List.copyOf(artifactDigests);
- if ("v2".equals(attestationSchemaVersion) != (worldPublishedStartLocationEvidence != null)) {
+ boolean selectedRelease =
+ "v2".equals(attestationSchemaVersion) || "v4".equals(attestationSchemaVersion);
+ if (selectedRelease != (worldPublishedStartLocationEvidence != null)) {
throw new IllegalArgumentException(
- "Selector evidence requires bundle v2 and is mandatory for v2");
+ "Selector evidence requires bundle v2 or v4 and is mandatory for both");
}
}
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java
new file mode 100644
index 0000000000..f6afc9aa30
--- /dev/null
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java
@@ -0,0 +1,121 @@
+package net.firedevops.firemud.gamedesign.publication;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Objects;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding;
+import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto;
+
+/** Schema-2 digest over every exact Game Design source family at one selected Draft commit. */
+public record SelectedDraftControlPlaneDigest(
+ String tenantId,
+ String scopeValue,
+ String appliedCommitId,
+ String contentDigest,
+ int digestSchemaVersion) {
+ public static final int SCHEMA_VERSION = 2;
+ private static final String DOMAIN = "game-design-selected-draft-control-plane-digest/v2";
+
+ public SelectedDraftControlPlaneDigest {
+ Objects.requireNonNull(tenantId, "tenantId");
+ Objects.requireNonNull(scopeValue, "scopeValue");
+ Objects.requireNonNull(appliedCommitId, "appliedCommitId");
+ if (contentDigest == null
+ || !contentDigest.matches("[0-9a-f]{64}")
+ || digestSchemaVersion != SCHEMA_VERSION) {
+ throw new IllegalArgumentException(
+ "Canonical schema-2 selected control-plane digest required");
+ }
+ }
+
+ /** Publication request identity is echoed separately and is not part of this content digest. */
+ public static SelectedDraftControlPlaneDigest compute(
+ DraftCommitBinding selectedCommit, GameDesignSourceRepository.SynchronizedSources sources) {
+ Objects.requireNonNull(selectedCommit, "selectedCommit");
+ Objects.requireNonNull(sources, "sources");
+ BrandingSourceSnapshot branding =
+ sources
+ .branding()
+ .orElseThrow(
+ () -> new IllegalStateException("Selected branding source snapshot unavailable"));
+ TemplateConfigSourceSnapshot templateConfig =
+ sources
+ .templateConfig()
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Selected template-config source snapshot unavailable"));
+ List snapshots =
+ List.of(
+ new Snapshot(
+ "COMMAND", sources.command().binding(), sources.command().canonicalBytes()),
+ new Snapshot(
+ "REALM_POLICY", sources.policy().binding(), sources.policy().canonicalBytes()),
+ new Snapshot("ASSET", sources.asset().binding(), sources.asset().canonicalBytes()),
+ new Snapshot(
+ "GAMEPLAY_SOURCE",
+ sources.gameplayEvidence().orElseThrow(() -> new IllegalStateException("Selected gameplay source unavailable")).binding(),
+ sources.gameplayEvidence().orElseThrow(() -> new IllegalStateException("Selected gameplay source unavailable")).canonicalBytes()),
+ new Snapshot("BRANDING", branding.binding(), branding.canonicalBytes()),
+ new Snapshot(
+ "TEMPLATE_CONFIG", templateConfig.binding(), templateConfig.canonicalBytes()));
+
+ var preimage = new ByteArrayOutputStream();
+ frame(preimage, DOMAIN);
+ frame(preimage, selectedCommit.canonicalBytes());
+ for (Snapshot source : snapshots) {
+ if (!selectedCommit.equals(source.binding())) {
+ throw new IllegalStateException(
+ "Every selected Game Design source family must bind the exact Draft commit");
+ }
+ frame(preimage, source.family());
+ frame(preimage, source.canonicalBytes());
+ }
+ return new SelectedDraftControlPlaneDigest(
+ selectedCommit.target().canonicalTenantId().toString(),
+ Long.toString(selectedCommit.target().gameDesignVersionRowId()),
+ selectedCommit.commitId().toString(),
+ sha256(preimage.toByteArray()),
+ SCHEMA_VERSION);
+ }
+
+ public DesignControlPlaneDigestDto toDto() {
+ return new DesignControlPlaneDigestDto(
+ tenantId, scopeValue, appliedCommitId, contentDigest, digestSchemaVersion);
+ }
+
+ private static void frame(ByteArrayOutputStream output, String value) {
+ frame(output, value.getBytes(StandardCharsets.UTF_8));
+ }
+
+ private static void frame(ByteArrayOutputStream output, byte[] value) {
+ output.writeBytes(Integer.toString(value.length).getBytes(StandardCharsets.US_ASCII));
+ output.write(':');
+ output.writeBytes(value);
+ }
+
+ private static String sha256(byte[] bytes) {
+ try {
+ return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
+ } catch (NoSuchAlgorithmException impossible) {
+ throw new AssertionError("SHA-256 is required by the Java platform", impossible);
+ }
+ }
+
+ private record Snapshot(String family, DraftCommitBinding binding, byte[] canonicalBytes) {
+ private Snapshot {
+ Objects.requireNonNull(family, "family");
+ Objects.requireNonNull(binding, "binding");
+ canonicalBytes = Objects.requireNonNull(canonicalBytes, "canonicalBytes").clone();
+ }
+
+ @Override
+ public byte[] canonicalBytes() {
+ return canonicalBytes.clone();
+ }
+ }
+}
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java
new file mode 100644
index 0000000000..62d86584fa
--- /dev/null
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java
@@ -0,0 +1,336 @@
+package net.firedevops.firemud.gamedesign.publication;
+
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto;
+import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto;
+import net.firedevops.firemud.gamedesign.model.PublishParticipantKey;
+import org.jooq.DSLContext;
+import org.jooq.exception.DataAccessException;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.transaction.support.TransactionTemplate;
+
+/**
+ * Unregistered exact selected-publication source read; it does not authorize publication itself.
+ */
+public final class SelectedDraftPublicationDigestReadService {
+ private final OwnerRead owner;
+ private final TransactionTemplate snapshot;
+ private final String workloadNamespace;
+
+ public SelectedDraftPublicationDigestReadService(
+ DSLContext dsl, PlatformTransactionManager transactions, String workloadNamespace) {
+ this(
+ new RepositoryOwnerRead(
+ new GameDesignPublicationOperationRepository(Objects.requireNonNull(dsl, "dsl")),
+ new GameDesignSourceRepository(dsl)),
+ transactions,
+ workloadNamespace);
+ }
+
+ SelectedDraftPublicationDigestReadService(
+ OwnerRead owner, PlatformTransactionManager transactions, String workloadNamespace) {
+ this.owner = Objects.requireNonNull(owner, "owner");
+ if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) {
+ throw new IllegalArgumentException("Canonical Game Design workload namespace required");
+ }
+ this.workloadNamespace = workloadNamespace;
+ snapshot = new TransactionTemplate(Objects.requireNonNull(transactions, "transactions"));
+ snapshot.setName("game-design-selected-publication-digest-read");
+ snapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
+ snapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
+ snapshot.setReadOnly(true);
+ }
+
+ /** Returns exact local GD and retained World digests for one canonical full-version request. */
+ public ReadResult read(
+ String targetNamespace, PublicationDigestRequestBinding publicationRequest) {
+ if (!workloadNamespace.equals(targetNamespace)) {
+ throw Status.PERMISSION_DENIED
+ .withDescription("Selected publication namespace differs from configured owner")
+ .asRuntimeException();
+ }
+ if (TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isSynchronizationActive()) {
+ throw Status.FAILED_PRECONDITION
+ .withDescription("Independent selected publication digest snapshot required")
+ .asRuntimeException();
+ }
+ validateRequest(publicationRequest);
+ try {
+ return Objects.requireNonNull(
+ snapshot.execute(ignored -> readSnapshot(publicationRequest)),
+ "Selected publication digest snapshot returned no result");
+ } catch (StatusRuntimeException failure) {
+ throw failure;
+ } catch (DataAccessException unavailable) {
+ throw Status.UNAVAILABLE
+ .withDescription("Selected publication source readback unavailable")
+ .withCause(unavailable)
+ .asRuntimeException();
+ } catch (RuntimeException invalid) {
+ throw Status.FAILED_PRECONDITION
+ .withDescription("Exact selected publication source evidence unavailable")
+ .withCause(invalid)
+ .asRuntimeException();
+ }
+ }
+
+ private ReadResult readSnapshot(PublicationDigestRequestBinding publicationRequest) {
+ GameDesignPublicationOperationRepository.Readback readback =
+ owner
+ .read(publicationRequest.derivedWorkflowIdentity())
+ .orElseThrow(
+ () ->
+ Status.NOT_FOUND
+ .withDescription("Selected publication operation unavailable")
+ .asRuntimeException());
+ GameDesignPublicationOperation operation = readback.operation();
+ requireOperationCorrelation(operation, publicationRequest);
+
+ // Exact durable selection comparison precedes any source snapshot read.
+ owner.requireExactSelection(operation);
+ GameDesignSourceRepository.Capture frozen =
+ owner
+ .readSourceCapture(operation)
+ .orElseThrow(
+ () ->
+ Status.FAILED_PRECONDITION
+ .withDescription("Complete selected source capture unavailable")
+ .asRuntimeException());
+ requireCapture(operation, frozen);
+
+ DraftCommitBinding selected = operation.account().input().selection().selectedCommit();
+ GameDesignSourceRepository.SynchronizedSources synchronizedSources =
+ owner
+ .readSynchronized(selected.target(), selected.commitId())
+ .orElseThrow(
+ () ->
+ Status.FAILED_PRECONDITION
+ .withDescription("Complete synchronized selected sources unavailable")
+ .asRuntimeException());
+ requireFrozenSources(selected, frozen, synchronizedSources);
+
+ DesignControlPlaneDigestDto designDigest =
+ SelectedDraftControlPlaneDigest.compute(selected, synchronizedSources).toDto();
+ var worldAcknowledgement = operation.inventory().freezeEvidence().acknowledgement();
+ if (!selected.commitId().toString().equals(worldAcknowledgement.appliedCommitId())) {
+ throw new IllegalStateException("Retained World freeze differs from selected Draft commit");
+ }
+ var worldDigest =
+ new PublishParticipantDigestDto(
+ PublishParticipantKey.WORLD_MANAGEMENT.name(),
+ publicationRequest.versionId(),
+ null,
+ worldAcknowledgement.appliedCommitId(),
+ worldAcknowledgement.contentDigest(),
+ worldAcknowledgement.digestSchemaVersion(),
+ null,
+ null,
+ null);
+ return new ReadResult(
+ publicationRequest, publicationRequest.requestDigest(), designDigest, worldDigest);
+ }
+
+ private void requireOperationCorrelation(
+ GameDesignPublicationOperation operation,
+ PublicationDigestRequestBinding publicationRequest) {
+ var selection = operation.account().input().selection();
+ var intent = selection.intent();
+ TargetProof target = selection.target();
+ DraftCommitBinding selected = selection.selectedCommit();
+ var world = operation.world().request();
+ UUID tenant;
+ long numericVersion;
+ try {
+ tenant = UUID.fromString(publicationRequest.tenantId());
+ numericVersion = Long.parseLong(publicationRequest.versionId());
+ } catch (RuntimeException malformed) {
+ throw new IllegalArgumentException(
+ "Canonical tenant UUID and numeric version required", malformed);
+ }
+ if (!tenant.toString().equals(publicationRequest.tenantId())
+ || numericVersion <= 0
+ || !tenant.equals(target.canonicalTenantId())
+ || !tenant.equals(intent.canonicalTenantId())
+ || target.gameDesignVersionRowId() != numericVersion
+ || operation.versionId() != numericVersion
+ || !operation.tenantKey().equals(target.gameDesignVersionTenantKey())
+ || !operation.selectionDigest().equals(selection.digest())
+ || !intent.canonicalVersionId().equals(target.canonicalVersionId())
+ || !intent.canonicalVersionId().equals(selected.target().canonicalVersionId())
+ || !publicationRequest.publishRequestId().equals(intent.publishRequestId())
+ || !publicationRequest.derivedWorkflowIdentity().equals(operation.workflowId())
+ || !workloadNamespace.equals(world.targetNamespace())
+ || !tenant.equals(world.canonicalTenantId())
+ || !intent.canonicalVersionId().equals(world.canonicalVersionId())
+ || !intent.publishRequestId().equals(world.publicationRequestId())
+ || !publicationRequest.derivedWorkflowIdentity().equals(world.publishWorkflowId())
+ || !selection.digest().substring("sha256:".length()).equals(world.requestDigest())
+ || !intent.expectedVersionStateEpoch().equals(Long.toString(world.versionStateEpoch()))
+ || !selected.commitId().toString().equals(world.appliedCommitId())) {
+ throw new IllegalStateException(
+ "Publication operation differs from canonical selected request");
+ }
+ }
+
+ private static void requireCapture(
+ GameDesignPublicationOperation operation, GameDesignSourceRepository.Capture capture) {
+ byte[] operationBytes = operation.canonicalBytes();
+ for (byte[] retainedOperation :
+ new byte[][] {
+ capture.command().operation().canonicalBytes(),
+ capture.policy().operation().canonicalBytes(),
+ capture.asset().operation().canonicalBytes(),
+ capture.branding().operation().canonicalBytes(),
+ capture.templateConfig().operation().canonicalBytes()
+ }) {
+ if (!Arrays.equals(operationBytes, retainedOperation)) {
+ throw new IllegalStateException("Frozen source capture differs from exact operation");
+ }
+ }
+ }
+
+ private static void requireFrozenSources(
+ DraftCommitBinding selected,
+ GameDesignSourceRepository.Capture frozen,
+ GameDesignSourceRepository.SynchronizedSources synchronizedSources) {
+ BrandingSourceSnapshot branding =
+ synchronizedSources
+ .branding()
+ .orElseThrow(
+ () -> new IllegalStateException("Selected branding source snapshot unavailable"));
+ TemplateConfigSourceSnapshot templateConfig =
+ synchronizedSources
+ .templateConfig()
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Selected template-config source snapshot unavailable"));
+ if (!selected.equals(synchronizedSources.command().binding())
+ || !selected.equals(synchronizedSources.policy().binding())
+ || !selected.equals(synchronizedSources.asset().binding())
+ || !selected.equals(synchronizedSources.gameplayEvidence().orElseThrow(() -> new IllegalStateException("Selected gameplay source unavailable")).binding())
+ || !selected.equals(branding.binding())
+ || !selected.equals(templateConfig.binding())
+ || !Arrays.equals(
+ frozen.command().snapshot().canonicalBytes(),
+ synchronizedSources.command().canonicalBytes())
+ || !Arrays.equals(
+ frozen.policy().snapshot().canonicalBytes(),
+ synchronizedSources.policy().canonicalBytes())
+ || !Arrays.equals(
+ frozen.asset().snapshot().canonicalBytes(),
+ synchronizedSources.asset().canonicalBytes())
+ || !Arrays.equals(frozen.branding().snapshot().canonicalBytes(), branding.canonicalBytes())
+ || !Arrays.equals(
+ frozen.templateConfig().snapshot().canonicalBytes(), templateConfig.canonicalBytes())) {
+ throw new IllegalStateException(
+ "Frozen and synchronized source snapshots differ from the complete selected commit");
+ }
+ }
+
+ private static void validateRequest(PublicationDigestRequestBinding request) {
+ if (request == null
+ || request.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) {
+ throw Status.INVALID_ARGUMENT
+ .withDescription("Canonical full-version publication binding required")
+ .asRuntimeException();
+ }
+ try {
+ var canonical =
+ PublicationDigestRequestBinding.full(
+ request.tenantId(), request.versionId(), request.publishRequestId());
+ UUID tenant = UUID.fromString(request.tenantId());
+ if (!Arrays.equals(canonical.canonicalPreimage(), request.canonicalPreimage())
+ || !canonical.requestDigest().equals(request.requestDigest())
+ || !canonical.derivedWorkflowIdentity().equals(request.derivedWorkflowIdentity())
+ || !tenant.toString().equals(request.tenantId())) {
+ throw new IllegalArgumentException("Publication request binding is not canonical");
+ }
+ } catch (RuntimeException malformed) {
+ throw Status.INVALID_ARGUMENT
+ .withDescription("Canonical full-version publication binding required")
+ .withCause(malformed)
+ .asRuntimeException();
+ }
+ }
+
+ public record ReadResult(
+ PublicationDigestRequestBinding requestBinding,
+ String requestDigest,
+ DesignControlPlaneDigestDto gameDesignDigest,
+ PublishParticipantDigestDto worldManagementDigest) {
+ public ReadResult {
+ Objects.requireNonNull(requestBinding, "requestBinding");
+ Objects.requireNonNull(gameDesignDigest, "gameDesignDigest");
+ Objects.requireNonNull(worldManagementDigest, "worldManagementDigest");
+ requestBinding.validateSupplied(requestBinding.derivedWorkflowIdentity(), requestDigest);
+ requestBinding.requireOwnerScope(gameDesignDigest.tenantId(), gameDesignDigest.scopeValue());
+ if (!requestBinding.versionId().equals(worldManagementDigest.scopeValue())
+ || !gameDesignDigest.appliedCommitId().equals(worldManagementDigest.appliedCommitId())
+ || gameDesignDigest.digestSchemaVersion()
+ != SelectedDraftControlPlaneDigest.SCHEMA_VERSION
+ || !PublishParticipantKey.WORLD_MANAGEMENT
+ .name()
+ .equals(worldManagementDigest.participantKey())
+ || worldManagementDigest.baseVersionId() != null
+ || worldManagementDigest.contentDigest() == null
+ || !worldManagementDigest.contentDigest().matches("[0-9a-f]{64}")
+ || worldManagementDigest.digestSchemaVersion() == null
+ || worldManagementDigest.digestSchemaVersion() <= 0
+ || !worldManagementDigest.succeeded()) {
+ throw new IllegalArgumentException("Paired selected publication digest scopes differ");
+ }
+ }
+ }
+
+ interface OwnerRead {
+ Optional read(String workflowIdentity);
+
+ void requireExactSelection(GameDesignPublicationOperation operation);
+
+ Optional readSourceCapture(
+ GameDesignPublicationOperation operation);
+
+ Optional readSynchronized(
+ TargetProof target, UUID selectedCommitId);
+ }
+
+ private record RepositoryOwnerRead(
+ GameDesignPublicationOperationRepository operations, GameDesignSourceRepository sources)
+ implements OwnerRead {
+ @Override
+ public Optional read(
+ String workflowIdentity) {
+ return operations.read(workflowIdentity);
+ }
+
+ @Override
+ public void requireExactSelection(GameDesignPublicationOperation operation) {
+ operations.requireExactSelection(operation);
+ }
+
+ @Override
+ public Optional readSourceCapture(
+ GameDesignPublicationOperation operation) {
+ return operations.readSourceCapture(operation);
+ }
+
+ @Override
+ public Optional readSynchronized(
+ TargetProof target, UUID selectedCommitId) {
+ return sources.readSynchronized(target, selectedCommitId);
+ }
+ }
+}
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java
index 1f48c2e364..ba99ae57ec 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java
@@ -557,7 +557,7 @@ private void requireReleaseMatches(
|| !Objects.equals(release.canonicalTenantId(), exact.association().canonicalTenantId())
|| !Objects.equals(release.canonicalVersionId(), exact.association().canonicalVersionId())
|| !Objects.equals(release.publishWorkflowId(), exact.association().publishWorkflowId())
- || !"v2".equals(release.attestationSchemaVersion())
+ || !isSelectedReleaseBundleSchema(release.attestationSchemaVersion())
|| !Objects.equals(
release.worldPublishedStartLocationEvidence(),
exact.worldPublishedStartLocationEvidence())
@@ -582,6 +582,10 @@ private void requireReleaseMatches(
}
}
+ static boolean isSelectedReleaseBundleSchema(String schemaVersion) {
+ return "v2".equals(schemaVersion) || "v4".equals(schemaVersion);
+ }
+
private void lockAndReloadSelectedVersion(
Version version, UUID canonicalTenantId, UUID canonicalVersionId) {
Record row =
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java
index 34b64751e6..f8c5898fa2 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java
@@ -249,7 +249,8 @@ private Result readSnapshot(Request request, StartSessionPostAuthorizationExecut
.asRuntimeException());
if (!canonicalTenantId.equals(configuredRelease.canonicalTenantId())
|| !canonicalVersionId.equals(configuredRelease.canonicalVersionId())
- || !"v2".equals(configuredRelease.attestationSchemaVersion())) {
+ || !StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema(
+ configuredRelease.attestationSchemaVersion())) {
throw new IllegalStateException("START_SESSION_CONFIGURED_RELEASE_IDENTITY_CONFLICT");
}
workflowId = configuredRelease.publishWorkflowId();
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishGateService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishGateService.java
index 60c070ccad..6f5f7b0911 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishGateService.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishGateService.java
@@ -1,6 +1,7 @@
package net.firedevops.firemud.gamedesign.service;
import java.util.List;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto;
import net.firedevops.firemud.gamedesign.dto.VersionDto;
@@ -8,8 +9,20 @@ public interface PublishGateService {
List collectFullVersionParticipantDigests(
VersionDto version, String publishRequestId, String publishWorkflowId);
+ /** Collects owner digests using the canonical binding read from the exact selected operation. */
+ List collectSelectedFullVersionParticipantDigests(
+ VersionDto version,
+ PublicationDigestRequestBinding canonicalBinding,
+ String publishWorkflowId);
+
List collectScriptPatchParticipantDigests(
VersionDto version, String publishRequestId, String publishWorkflowId);
void assertGatePassed(VersionDto version, List participantDigests);
+
+ /**
+ * Requires the selected full-publication digest schemas, including all six GD source families.
+ */
+ void assertSelectedGatePassed(
+ VersionDto version, List participantDigests);
}
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java
index 7e7301172e..6e6e708175 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java
@@ -157,6 +157,30 @@ public CompleteLaunchBindingDto getCompleteLaunchBinding(
bundle.commandDefinitions(),
bundle.generationConfigRevision(),
bundle.worldPublishedStartLocationEvidence());
+ } else if (PublishedReleaseBundleContract.SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(
+ bundle.attestationSchemaVersion())) {
+ releaseAttestation =
+ AuthoredWorldReleaseAttestationEvidence.createSelectedFull(
+ descriptor.targetNamespace(),
+ descriptor.resultDigest(),
+ source.canonicalTenantId(),
+ canonicalVersion.getCanonicalVersionId(),
+ source.worldSlug(),
+ source.operationId(),
+ source.evidenceDigest(),
+ descriptor.launchDescriptorId(),
+ descriptor.publishedReleaseBundleRef(),
+ descriptor.versionStateEpoch(),
+ bundle.publishWorkflowId(),
+ commitId,
+ participants,
+ bundle.manifestHash(),
+ bundle.manifestSchemaVersion(),
+ bundle.requiredManifestAssetKeys(),
+ artifacts,
+ bundle.commandDefinitions(),
+ bundle.generationConfigRevision(),
+ bundle.worldPublishedStartLocationEvidence());
} else {
releaseAttestation =
AuthoredWorldReleaseAttestationEvidence.create(
@@ -274,6 +298,9 @@ private void requireExactBundleBinding(
|| !("v1".equals(bundle.attestationSchemaVersion())
&& bundle.worldPublishedStartLocationEvidence() == null
|| "v2".equals(bundle.attestationSchemaVersion())
+ && bundle.worldPublishedStartLocationEvidence() != null
+ || PublishedReleaseBundleContract.SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(
+ bundle.attestationSchemaVersion())
&& bundle.worldPublishedStartLocationEvidence() != null)
|| !Objects.equals(bundle.id(), descriptor.releaseBundleId())
|| !Objects.equals(bundle.versionId(), descriptor.versionId())
@@ -351,6 +378,7 @@ private List requirePartici
switch (bundle.attestationSchemaVersion()) {
case "v1" -> AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION;
case "v2" -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION;
+ case "v4" -> AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION;
default ->
throw deny(
"RELEASE_ATTESTATION_SCHEMA_UNSUPPORTED",
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java
index a70eb5a7f4..9741f63ff2 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java
@@ -1,10 +1,16 @@
package net.firedevops.firemud.gamedesign.service.impl;
+import io.grpc.StatusRuntimeException;
+import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.Optional;
import java.util.Set;
+import java.util.UUID;
+import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient;
import net.firedevops.firemud.gamedesign.client.EntityManagementClient;
@@ -15,13 +21,20 @@
import net.firedevops.firemud.gamedesign.dto.VersionDto;
import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode;
import net.firedevops.firemud.gamedesign.model.PublishParticipantKey;
+import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt;
+import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository;
+import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationDigestReadService;
import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService;
import net.firedevops.firemud.gamedesign.service.PublishGateFailureException;
import net.firedevops.firemud.gamedesign.service.PublishGateService;
+import org.jooq.DSLContext;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
+import org.springframework.transaction.PlatformTransactionManager;
@Service
-public class PublishGateServiceImpl implements PublishGateService {
+public final class PublishGateServiceImpl implements PublishGateService {
private static final Map SUPPORTED_DIGEST_SCHEMA_VERSIONS =
Map.of(
PublishParticipantKey.WORLD_MANAGEMENT.name(), 3,
@@ -47,18 +60,69 @@ public class PublishGateServiceImpl implements PublishGateService {
private final EntityManagementClient entityManagementClient;
private final GameLogicClient gameLogicClient;
private final AutomationScriptingClient automationScriptingClient;
+ private final SelectedDraftGameLogicReceiptRepository selectedGameLogicReceiptRepository;
+ private final SelectedDraftPublicationDigestReadService selectedPublicationDigestReader;
+ private final String workloadNamespace;
+ @Autowired
public PublishGateServiceImpl(
ControlPlaneDigestService controlPlaneDigestService,
WorldManagementClient worldManagementClient,
EntityManagementClient entityManagementClient,
GameLogicClient gameLogicClient,
- AutomationScriptingClient automationScriptingClient) {
+ AutomationScriptingClient automationScriptingClient,
+ DSLContext dsl,
+ PlatformTransactionManager transactions,
+ @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) {
+ this(
+ controlPlaneDigestService,
+ worldManagementClient,
+ entityManagementClient,
+ gameLogicClient,
+ automationScriptingClient,
+ new SelectedDraftGameLogicReceiptRepository(dsl),
+ GrpcPeerIdentity.isValidNamespace(workloadNamespace)
+ ? new SelectedDraftPublicationDigestReadService(dsl, transactions, workloadNamespace)
+ : null,
+ workloadNamespace);
+ }
+
+ PublishGateServiceImpl(
+ ControlPlaneDigestService controlPlaneDigestService,
+ WorldManagementClient worldManagementClient,
+ EntityManagementClient entityManagementClient,
+ GameLogicClient gameLogicClient,
+ AutomationScriptingClient automationScriptingClient,
+ SelectedDraftGameLogicReceiptRepository selectedGameLogicReceiptRepository) {
+ this(
+ controlPlaneDigestService,
+ worldManagementClient,
+ entityManagementClient,
+ gameLogicClient,
+ automationScriptingClient,
+ selectedGameLogicReceiptRepository,
+ null,
+ null);
+ }
+
+ PublishGateServiceImpl(
+ ControlPlaneDigestService controlPlaneDigestService,
+ WorldManagementClient worldManagementClient,
+ EntityManagementClient entityManagementClient,
+ GameLogicClient gameLogicClient,
+ AutomationScriptingClient automationScriptingClient,
+ SelectedDraftGameLogicReceiptRepository selectedGameLogicReceiptRepository,
+ SelectedDraftPublicationDigestReadService selectedPublicationDigestReader,
+ String workloadNamespace) {
this.controlPlaneDigestService = controlPlaneDigestService;
this.worldManagementClient = worldManagementClient;
this.entityManagementClient = entityManagementClient;
this.gameLogicClient = gameLogicClient;
this.automationScriptingClient = automationScriptingClient;
+ this.selectedGameLogicReceiptRepository =
+ Objects.requireNonNull(selectedGameLogicReceiptRepository);
+ this.selectedPublicationDigestReader = selectedPublicationDigestReader;
+ this.workloadNamespace = workloadNamespace;
}
@Override
@@ -69,8 +133,92 @@ public List collectFullVersionParticipantDigests(
PublicationDigestRequestBinding.full(
version.tenantId(), String.valueOf(version.id()), publishRequestId);
requireWorkflowIdentity(binding, publishWorkflowId);
+ return collectFullVersionParticipantDigests(version, binding, false);
+ }
+
+ @Override
+ public List collectSelectedFullVersionParticipantDigests(
+ VersionDto version,
+ PublicationDigestRequestBinding canonicalBinding,
+ String publishWorkflowId) {
+ Objects.requireNonNull(version, "version must not be null");
+ Objects.requireNonNull(canonicalBinding, "canonicalBinding must not be null");
+ if (version.scriptOnly()
+ || version.id() == null
+ || canonicalBinding.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION
+ || !String.valueOf(version.id()).equals(canonicalBinding.versionId())) {
+ throw new IllegalArgumentException(
+ "selected publication requires the exact full-version Game Design row binding");
+ }
+ UUID canonicalTenant;
+ try {
+ canonicalTenant = UUID.fromString(canonicalBinding.tenantId());
+ } catch (IllegalArgumentException malformed) {
+ throw new IllegalArgumentException(
+ "selected publication tenant must be its canonical UUID", malformed);
+ }
+ if (!canonicalTenant.toString().equals(canonicalBinding.tenantId())) {
+ throw new IllegalArgumentException("selected publication tenant must be its canonical UUID");
+ }
+ requireWorkflowIdentity(canonicalBinding, publishWorkflowId);
+ SelectedDraftPublicationDigestReadService.ReadResult selected = null;
+ String failureCode = "PARTICIPANT_UNAVAILABLE";
+ try {
+ if (selectedPublicationDigestReader == null
+ || !GrpcPeerIdentity.isValidNamespace(workloadNamespace)) {
+ throw new IllegalStateException("Selected publication digest reader unavailable");
+ }
+ selected = selectedPublicationDigestReader.read(workloadNamespace, canonicalBinding);
+ if (selected == null
+ || !Arrays.equals(
+ canonicalBinding.canonicalPreimage(), selected.requestBinding().canonicalPreimage())
+ || !canonicalBinding.requestDigest().equals(selected.requestDigest())
+ || !canonicalBinding
+ .derivedWorkflowIdentity()
+ .equals(selected.requestBinding().derivedWorkflowIdentity())) {
+ throw new IllegalStateException("Selected publication digest request echo differs");
+ }
+ } catch (RuntimeException unavailable) {
+ selected = null;
+ failureCode =
+ unavailable instanceof StatusRuntimeException grpcFailure
+ ? grpcFailure.getStatus().getCode().name()
+ : "FAILED_PRECONDITION";
+ if (selectedPublicationDigestReader == null
+ || !GrpcPeerIdentity.isValidNamespace(workloadNamespace)) {
+ failureCode = "PARTICIPANT_UNAVAILABLE";
+ }
+ }
+ var snapshot = selected;
+ String snapshotFailureCode = failureCode;
+ return FULL_VERSION_PARTICIPANTS.stream()
+ .map(
+ participant -> {
+ if (participant == PublishParticipantKey.WORLD_MANAGEMENT
+ || participant == PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE) {
+ if (snapshot == null) {
+ return failedObservation(
+ participant,
+ canonicalBinding.versionId(),
+ null,
+ snapshotFailureCode,
+ "Exact selected publication source evidence unavailable");
+ }
+ return participant == PublishParticipantKey.WORLD_MANAGEMENT
+ ? snapshot.worldManagementDigest()
+ : toParticipantDigest(participant, version, snapshot.gameDesignDigest());
+ }
+ return observeFullVersionParticipant(version, canonicalBinding, participant, true);
+ })
+ .toList();
+ }
+
+ private List collectFullVersionParticipantDigests(
+ VersionDto version, PublicationDigestRequestBinding binding, boolean selectedPublication) {
return FULL_VERSION_PARTICIPANTS.stream()
- .map(participant -> observeFullVersionParticipant(version, binding, participant))
+ .map(
+ participant ->
+ observeFullVersionParticipant(version, binding, participant, selectedPublication))
.toList();
}
@@ -96,6 +244,42 @@ public List collectScriptPatchParticipantDigests(
@Override
public void assertGatePassed(
VersionDto version, List participantDigests) {
+ assertGatePassed(version, participantDigests, null);
+ }
+
+ @Override
+ public void assertSelectedGatePassed(
+ VersionDto version, List participantDigests) {
+ if (version.scriptOnly()) {
+ throw new IllegalArgumentException("Selected publication requires a full version");
+ }
+ List worldDigests =
+ participantDigests == null
+ ? List.of()
+ : participantDigests.stream()
+ .filter(digest -> "WORLD_MANAGEMENT".equals(digest.participantKey()))
+ .toList();
+ if (worldDigests.size() != 1 || worldDigests.getFirst().digestSchemaVersion() == null) {
+ throw new PublishGateFailureException(
+ PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA,
+ "publish gate failed: exact selected World digest schema is required");
+ }
+ int selectedAttestationSchema =
+ switch (worldDigests.getFirst().digestSchemaVersion()) {
+ case 3 -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION;
+ case 4 -> AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION;
+ default ->
+ throw new PublishGateFailureException(
+ PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA,
+ "publish gate failed: unsupported selected World digest schema");
+ };
+ assertGatePassed(version, participantDigests, selectedAttestationSchema);
+ }
+
+ private void assertGatePassed(
+ VersionDto version,
+ List participantDigests,
+ Integer selectedAttestationSchema) {
List expectedParticipants =
version.scriptOnly() ? SCRIPT_PATCH_PARTICIPANTS : FULL_VERSION_PARTICIPANTS;
List expectedParticipantKeyList =
@@ -144,8 +328,17 @@ public void assertGatePassed(
"publish gate failed: wrong scope from " + digest.participantKey());
}
String participantKey = digest.participantKey();
- Integer supportedSchemaVersion =
- participantKey == null ? null : SUPPORTED_DIGEST_SCHEMA_VERSIONS.get(participantKey);
+ Integer supportedSchemaVersion;
+ if (selectedAttestationSchema != null) {
+ supportedSchemaVersion =
+ AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema(
+ participantKey, selectedAttestationSchema);
+ } else {
+ supportedSchemaVersion =
+ participantKey == null
+ ? null
+ : SUPPORTED_DIGEST_SCHEMA_VERSIONS.get(participantKey);
+ }
if (digest.digestSchemaVersion() == null
|| !digest.digestSchemaVersion().equals(supportedSchemaVersion)) {
throw new PublishGateFailureException(
@@ -178,11 +371,15 @@ public void assertGatePassed(
private PublishParticipantDigestDto observeFullVersionParticipant(
VersionDto version,
PublicationDigestRequestBinding binding,
- PublishParticipantKey participantKey) {
+ PublishParticipantKey participantKey,
+ boolean selectedPublication) {
return switch (participantKey) {
case WORLD_MANAGEMENT -> worldManagementClient.getDraftDesignDigestForVersion(binding);
case ENTITY_MANAGEMENT -> entityManagementClient.getDraftDesignDigestForVersion(binding);
- case GAME_LOGIC -> gameLogicClient.getDraftDesignDigestForVersion(binding);
+ case GAME_LOGIC ->
+ selectedPublication
+ ? observeSelectedGameLogicParticipant(binding)
+ : gameLogicClient.getDraftDesignDigestForVersion(binding);
case AUTOMATION_SCRIPTING ->
automationScriptingClient.getDraftDesignDigestForVersion(binding);
case GAME_DESIGN_CONTROL_PLANE ->
@@ -191,6 +388,30 @@ private PublishParticipantDigestDto observeFullVersionParticipant(
};
}
+ private PublishParticipantDigestDto observeSelectedGameLogicParticipant(
+ PublicationDigestRequestBinding binding) {
+ Optional receipt;
+ try {
+ receipt = selectedGameLogicReceiptRepository.readForPublication(binding);
+ } catch (org.jooq.exception.DataAccessException unavailable) {
+ return failedObservation(
+ PublishParticipantKey.GAME_LOGIC,
+ binding.versionId(),
+ null,
+ "UNAVAILABLE",
+ "immutable selected Game Logic receipt readback is temporarily unavailable");
+ }
+ if (receipt.isEmpty()) {
+ return failedObservation(
+ PublishParticipantKey.GAME_LOGIC,
+ binding.versionId(),
+ null,
+ "PARTICIPANT_UNAVAILABLE",
+ "immutable selected Game Logic receipt is not available yet");
+ }
+ return gameLogicClient.getDraftDesignDigestForVersion(binding, receipt.orElseThrow());
+ }
+
private void requireWorkflowIdentity(
PublicationDigestRequestBinding binding, String suppliedWorkflowIdentity) {
if (!binding.derivedWorkflowIdentity().equals(suppliedWorkflowIdentity)) {
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java
index f40b92aa71..318c586490 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java
@@ -13,6 +13,7 @@
final class PublishedReleaseBundleContract {
static final String SUPPORTED_ATTESTATION_SCHEMA_VERSION = "v1";
static final String SELECTOR_ATTESTATION_SCHEMA_VERSION = "v2";
+ static final String SELECTED_FULL_ATTESTATION_SCHEMA_VERSION = "v4";
static final int SUPPORTED_MANIFEST_SCHEMA_VERSION = 1;
static final int SUPPORTED_ARTIFACT_SCHEMA_VERSION = 1;
static final String SCHEMA_VERSION_UNSUPPORTED = "SCHEMA_VERSION_UNSUPPORTED";
@@ -22,10 +23,30 @@ final class PublishedReleaseBundleContract {
private PublishedReleaseBundleContract() {}
static void requireSelectorBinding(PublishedReleaseBundleDto bundle) {
+ requireSelectedBinding(
+ bundle,
+ SELECTOR_ATTESTATION_SCHEMA_VERSION,
+ AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION,
+ "World selector");
+ }
+
+ static void requireSelectedFullBinding(PublishedReleaseBundleDto bundle) {
+ requireSelectedBinding(
+ bundle,
+ SELECTED_FULL_ATTESTATION_SCHEMA_VERSION,
+ AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION,
+ "Selected-full release");
+ }
+
+ private static void requireSelectedBinding(
+ PublishedReleaseBundleDto bundle,
+ String expectedBundleSchema,
+ int evidenceSchema,
+ String description) {
var evidence =
Objects.requireNonNull(bundle.worldPublishedStartLocationEvidence(), "World evidence");
var request = evidence.request();
- if (!SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())
+ if (!expectedBundleSchema.equals(bundle.attestationSchemaVersion())
|| bundle.scriptOnly()
|| bundle.scriptPatchVersion() != null
|| !request.canonicalTenantId().equals(bundle.canonicalTenantId())
@@ -37,7 +58,7 @@ static void requireSelectorBinding(PublishedReleaseBundleDto bundle) {
|| request.appliedCommitId() == null
|| request.appliedCommitId().isBlank()) {
throw new IllegalArgumentException(
- "World selector differs from complete immutable release binding");
+ description + " differs from complete immutable release binding");
}
new ExportedAssetManifest(
bundle.manifestHash(),
@@ -51,7 +72,7 @@ static void requireSelectorBinding(PublishedReleaseBundleDto bundle) {
}
var required = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder();
if (bundle.participantDigests().size() != required.size()) {
- throw new IllegalArgumentException("World selector release lacks required participants");
+ throw new IllegalArgumentException(description + " release lacks required participants");
}
for (int index = 0; index < required.size(); index++) {
var participant = bundle.participantDigests().get(index);
@@ -67,27 +88,65 @@ static void requireSelectorBinding(PublishedReleaseBundleDto bundle) {
|| !Objects.equals(
participant.digestSchemaVersion(),
AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema(
- participant.participantKey(),
- AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION))) {
+ participant.participantKey(), evidenceSchema))) {
throw new IllegalArgumentException(
- "World selector requires all exact successful ordered release participants");
+ description + " requires all exact successful ordered release participants");
}
if ("WORLD_MANAGEMENT".equals(participant.participantKey())
&& (!request.contentDigest().equals(participant.contentDigest())
|| request.digestSchemaVersion() != participant.digestSchemaVersion())) {
throw new IllegalArgumentException(
- "World selector differs from World participant digest/schema");
+ description + " differs from World participant digest/schema");
}
if ("GAME_LOGIC".equals(participant.participantKey())
&& (participant.abilitySchemaDigest() == null
|| !participant.abilitySchemaDigest().matches("sha256:[0-9a-f]{64}"))) {
throw new IllegalArgumentException(
- "World selector release lacks Game Logic ability schema proof");
+ description + " release lacks Game Logic ability schema proof");
}
if (!"GAME_LOGIC".equals(participant.participantKey())
&& participant.abilitySchemaDigest() != null) {
throw new IllegalArgumentException(
- "World selector ability schema proof must be owned by Game Logic");
+ description + " ability schema proof must be owned by Game Logic");
+ }
+ }
+ }
+
+ static void requireFreshSelectedFullParticipantVector(
+ long versionId, String appliedCommitId, List participants) {
+ if (versionId <= 0 || appliedCommitId == null || appliedCommitId.isBlank()) {
+ throw new IllegalArgumentException("Selected-full participant scope is invalid");
+ }
+ var required = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder();
+ if (participants == null || participants.size() != required.size()) {
+ throw new IllegalArgumentException(
+ "Selected-full release requires all five exact participants");
+ }
+ String expectedScope = Long.toString(versionId);
+ for (int index = 0; index < required.size(); index++) {
+ var participant = participants.get(index);
+ String participantKey = required.get(index);
+ boolean gameLogic = "GAME_LOGIC".equals(participantKey);
+ if (participant == null
+ || !participantKey.equals(participant.participantKey())
+ || !expectedScope.equals(participant.scopeValue())
+ || participant.baseVersionId() != null
+ || !appliedCommitId.equals(participant.appliedCommitId())
+ || !participant.succeeded()
+ || (participant.errorMessage() != null && !participant.errorMessage().isBlank())
+ || participant.contentDigest() == null
+ || !participant.contentDigest().matches("[0-9a-f]{64}")
+ || participant.digestSchemaVersion() == null
+ || participant.digestSchemaVersion()
+ != AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema(
+ participantKey,
+ AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION)
+ || (gameLogic
+ ? participant.abilitySchemaDigest() == null
+ || !participant.abilitySchemaDigest().matches("sha256:[0-9a-f]{64}")
+ : participant.abilitySchemaDigest() != null)) {
+ throw new IllegalArgumentException(
+ "Selected-full release requires the exact 4/3/1/6/2 successful participant vector");
}
}
}
@@ -100,11 +159,15 @@ static void requireExactSelectorRetry(
String generationRevision,
List participants,
WorldPublishedStartLocationEvidence evidence) {
- if (!SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(stored.attestationSchemaVersion())) {
+ if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(stored.attestationSchemaVersion())) {
+ requireSelectorBinding(stored);
+ } else if (SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(
+ stored.attestationSchemaVersion())) {
+ requireSelectedFullBinding(stored);
+ } else {
throw new IllegalStateException(
"IDEMPOTENCY_CONFLICT: historical release is selector-ineligible");
}
- requireSelectorBinding(stored);
if (stored.versionNumber() != version.versionNumber()
|| version.scriptOnly()
|| version.scriptPatchVersion() != null
@@ -124,6 +187,14 @@ static void requireExactSelectorRetry(
}
static void requireSupportedSchemaForRead(PublishedReleaseBundleDto bundle) {
+ if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) {
+ requireSelectorBinding(bundle);
+ return;
+ }
+ if (SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) {
+ requireSelectedFullBinding(bundle);
+ return;
+ }
if (!SUPPORTED_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) {
throw new IllegalStateException(
SCHEMA_VERSION_UNSUPPORTED
@@ -140,10 +211,22 @@ static void requireSupportedSchemaForPublicationRead(PublishedReleaseBundleDto b
requireSelectorBinding(bundle);
return;
}
+ if (SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) {
+ requireSelectedFullBinding(bundle);
+ return;
+ }
requireSupportedSchemaForRead(bundle);
}
static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto bundle) {
+ if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) {
+ requireSelectorBinding(bundle);
+ return;
+ }
+ if (SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) {
+ requireSelectedFullBinding(bundle);
+ return;
+ }
if (!SUPPORTED_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) {
throw new IllegalArgumentException(
SCHEMA_VERSION_UNSUPPORTED
@@ -156,8 +239,9 @@ static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto bundle) {
* Descriptor resolution only; descriptor/v1 remains separate from the complete release carrier.
*/
static void requireSupportedSchemaForLaunchDescriptor(PublishedReleaseBundleDto bundle) {
- if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) {
- requireSelectorBinding(bundle);
+ if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())
+ || SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) {
+ requireSupportedSchemaForLaunch(bundle);
return;
}
requireSupportedSchemaForLaunch(bundle);
@@ -165,8 +249,9 @@ static void requireSupportedSchemaForLaunchDescriptor(PublishedReleaseBundleDto
static void requireExactRepairMatch(
PublishedReleaseBundleDto bundle, ExportedAssetManifest exportedManifest) {
- if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) {
- requireSelectorBinding(bundle);
+ if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())
+ || SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) {
+ requireSupportedSchemaForPublicationRead(bundle);
} else {
requireSupportedSchemaForRead(bundle);
}
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java
index f0551d3cc8..cf00f2ea3e 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java
@@ -111,6 +111,8 @@ private PublishedReleaseBundleDto createBundle(
}
return stored;
}
+ PublishedReleaseBundleContract.requireFreshSelectedFullParticipantVector(
+ version.id(), worldEvidence.request().appliedCommitId(), participantDigests);
var identitySource =
versionRepository
.findByTenantIdAndId(version.tenantId(), version.id())
@@ -133,7 +135,7 @@ private PublishedReleaseBundleDto createBundle(
entity.setCanonicalVersionId(canonicalVersionId);
entity.setVersionNumber(version.versionNumber());
entity.setAttestationSchemaVersion(
- PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION);
+ PublishedReleaseBundleContract.SELECTED_FULL_ATTESTATION_SCHEMA_VERSION);
entity.setWorldPublishedStartLocationEvidenceJson(
new String(worldEvidence.canonicalBytes(), StandardCharsets.UTF_8));
entity.setPublishWorkflowId(publishWorkflowId);
@@ -201,6 +203,9 @@ private PublishedReleaseBundleDto toDto(PublishedReleaseBundle entity) {
if (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(
dto.attestationSchemaVersion())) {
PublishedReleaseBundleContract.requireSelectorBinding(dto);
+ } else if (PublishedReleaseBundleContract.SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(
+ dto.attestationSchemaVersion())) {
+ PublishedReleaseBundleContract.requireSelectedFullBinding(dto);
}
return dto;
}
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java
index 46166dca49..7febbd4dbb 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java
@@ -267,8 +267,13 @@ private PublishWorkflowSnapshot reconcileSelectedPublicationMechanicsLocal(
try {
dto = versionMapper.toDto(version);
participantDigests =
- publishGateService.collectFullVersionParticipantDigests(
- dto, request.publishRequestId(), request.publishWorkflowId());
+ publishGateService.collectSelectedFullVersionParticipantDigests(
+ dto,
+ PublicationDigestRequestBinding.full(
+ requireSelectedIntent(request).intent().canonicalTenantId().toString(),
+ String.valueOf(version.getId()),
+ request.publishRequestId()),
+ request.publishWorkflowId());
} catch (RuntimeException ex) {
if (PublicationFailureClassifier.isRetryableParticipantDependencyFailure(ex)) {
throw pendingReconciliation(
@@ -279,7 +284,11 @@ private PublishWorkflowSnapshot reconcileSelectedPublicationMechanicsLocal(
}
try {
assertSelectedCommit(request, participantDigests);
- publishGateService.assertGatePassed(dto, participantDigests);
+ PublishedReleaseBundleContract.requireFreshSelectedFullParticipantVector(
+ dto.id(),
+ requireSelectedIntent(request).selectedCommit().commitId().toString(),
+ participantDigests);
+ publishGateService.assertSelectedGatePassed(dto, participantDigests);
} catch (RuntimeException ex) {
if (PublicationFailureClassifier.isRetryableParticipantDependencyFailure(ex)) {
throw pendingReconciliation(
@@ -502,7 +511,11 @@ private PublishWorkflowSnapshot finalizeFullVersion(
VersionDto dto = versionMapper.toDto(version);
requireSelectedDraftEpoch(request, version);
assertSelectedCommit(request, participantDigests);
- publishGateService.assertGatePassed(dto, participantDigests);
+ PublishedReleaseBundleContract.requireFreshSelectedFullParticipantVector(
+ dto.id(),
+ requireSelectedIntent(request).selectedCommit().commitId().toString(),
+ participantDigests);
+ publishGateService.assertSelectedGatePassed(dto, participantDigests);
publishAttemptService.recordFullVersionParticipantDigests(
request.publishWorkflowId(), participantDigests);
VersionAssetArtifactStateDto exportedState =
@@ -646,7 +659,11 @@ private void assertCommittedBundleEvidence(
VersionDto versionDto = versionMapper.toDto(readback.version());
PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(readback.bundle());
assertSelectedCommit(request, readback.bundle().participantDigests());
- publishGateService.assertGatePassed(versionDto, readback.bundle().participantDigests());
+ if (isSelectedReleaseBundle(readback.bundle())) {
+ publishGateService.assertSelectedGatePassed(versionDto, readback.bundle().participantDigests());
+ } else {
+ publishGateService.assertGatePassed(versionDto, readback.bundle().participantDigests());
+ }
recordedParticipantDigestService.assertMatchesRecordedDigests(
request.tenantId(), PublishType.FULL_VERSION, readback.bundle().participantDigests());
}
@@ -933,8 +950,7 @@ private void requireExactBundleEvidence(
if (!Objects.equals(version.getTenantId(), bundle.tenantId())
|| version.getVersionNumber() != bundle.versionNumber()
|| version.isScriptOnly()
- || (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(
- bundle.attestationSchemaVersion())
+ || (isSelectedReleaseBundle(bundle)
&& (!Objects.equals(version.getCanonicalTenantId(), bundle.canonicalTenantId())
|| !Objects.equals(
version.getCanonicalVersionId(), bundle.canonicalVersionId())))) {
@@ -952,13 +968,19 @@ private void requireExactCommittedBundleIdentity(
|| bundle.scriptPatchVersion() != null) {
throw new IllegalStateException("PUBLISH_ATTEMPT_BUNDLE_SCOPE_MISMATCH");
}
- if (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(
- bundle.attestationSchemaVersion())) {
+ if (isSelectedReleaseBundle(bundle)) {
PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(bundle);
requireExactSelectedWorldEvidence(request, bundle);
}
}
+ private boolean isSelectedReleaseBundle(PublishedReleaseBundleDto bundle) {
+ return PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(
+ bundle.attestationSchemaVersion())
+ || PublishedReleaseBundleContract.SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(
+ bundle.attestationSchemaVersion());
+ }
+
private void requireExactSelectedWorldEvidence(
PublishWorkflowRequest request, PublishedReleaseBundleDto bundle) {
// The stored owner payload is historical readback. It does not reconstruct a missing current
diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
new file mode 100644
index 0000000000..2e28934359
--- /dev/null
+++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
@@ -0,0 +1,1177 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import com.google.protobuf.util.JsonFormat;
+import io.grpc.Server;
+import io.grpc.ServerInterceptors;
+import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
+import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
+import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.SecureRandom;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository;
+import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedEmptyPublicationDigestGrpcReceiver;
+import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedEmptyPublicationDigestService;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding;
+import net.firedevops.firemud.common.authoring.DraftBaseReference;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof;
+import net.firedevops.firemud.common.config.ServiceEndpointsProperties;
+import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.gamedesign.CommandSource;
+import net.firedevops.firemud.common.gamedesign.GameplayRuleSource;
+import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence;
+import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation;
+import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal;
+import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest;
+import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource;
+import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer;
+import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties;
+import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor;
+import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence;
+import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence;
+import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository;
+import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedEmptyPublicationDigestGrpcReceiver;
+import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedEmptyPublicationDigestService;
+import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient;
+import net.firedevops.firemud.gamedesign.client.EntityManagementClient;
+import net.firedevops.firemud.gamedesign.client.GameLogicClient;
+import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection;
+import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository;
+import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository;
+import net.firedevops.firemud.gamedesign.draft.GameDesignReviewedBaseRepository;
+import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto;
+import net.firedevops.firemud.gamedesign.dto.VersionDto;
+import net.firedevops.firemud.gamedesign.entity.Game;
+import net.firedevops.firemud.gamedesign.entity.Version;
+import net.firedevops.firemud.gamedesign.model.VersionLifecycleState;
+import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository;
+import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt;
+import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository;
+import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner;
+import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation;
+import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository;
+import net.firedevops.firemud.gamedesign.repository.GameRepository;
+import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository;
+import net.firedevops.firemud.gamedesign.repository.VersionRepository;
+import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest;
+import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService;
+import net.firedevops.firemud.gamedesign.service.impl.PublishGateServiceImpl;
+import net.firedevops.firemud.gamedesign.service.impl.PublishedReleaseBundleServiceImpl;
+import net.firedevops.firemud.gamelogic.service.impl.GameLogicDraftDesignDigestServiceImpl;
+import net.firedevops.firemud.gamelogic.service.impl.GameLogicGrpcService;
+import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeRepository;
+import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService;
+import net.firedevops.firemud.test.TestContainerImages;
+import net.firedevops.firemud.worldmanagement.tenant.WorldSelectedFullPublicationEvidenceFixture;
+import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation;
+import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation;
+import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType;
+import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation;
+import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationRevision;
+import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType;
+import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration;
+import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount;
+import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceClosureDeclaration;
+import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily;
+import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamilyCount;
+import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation;
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.asn1.x509.BasicConstraints;
+import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
+import org.bouncycastle.asn1.x509.Extension;
+import org.bouncycastle.asn1.x509.GeneralName;
+import org.bouncycastle.asn1.x509.GeneralNames;
+import org.bouncycastle.asn1.x509.KeyPurposeId;
+import org.bouncycastle.asn1.x509.KeyUsage;
+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
+import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
+import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import org.flywaydb.core.Flyway;
+import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension;
+import org.jooq.DSLContext;
+import org.jooq.SQLDialect;
+import org.jooq.impl.DSL;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.support.TransactionTemplate;
+import org.testcontainers.containers.PostgreSQLContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import tools.jackson.databind.ObjectMapper;
+
+/**
+ * Actual current-default GDS bundle, Entity, Automation, Game Logic, and World owner storage and
+ * readbacks. Account participation/source inputs, original creator authority, World source
+ * provenance, Game Logic settlement input, asset manifest, and ephemeral PKI are explicitly
+ * controlled. This is a component composition proof; it does not establish genuine Account or
+ * creator authority, registered ingress, or runtime activation/admission/delivery.
+ */
+@Testcontainers(disabledWithoutDocker = true)
+@SuppressWarnings("resource")
+class SelectedFullOwnerPublicationPostgresIntegrationTest {
+ private static final String NAMESPACE = "firemud";
+
+ @Container
+ static final PostgreSQLContainer> GDS_POSTGRES =
+ new PostgreSQLContainer<>(TestContainerImages.postgres());
+
+ @Container
+ static final PostgreSQLContainer> WORLD_POSTGRES =
+ new PostgreSQLContainer<>(TestContainerImages.postgres());
+
+ @Container
+ static final PostgreSQLContainer> ENTITY_POSTGRES =
+ new PostgreSQLContainer<>(TestContainerImages.postgres());
+
+ @Container
+ static final PostgreSQLContainer> AUTOMATION_POSTGRES =
+ new PostgreSQLContainer<>(TestContainerImages.postgres());
+
+ @Container
+ static final PostgreSQLContainer> GAME_LOGIC_POSTGRES =
+ new PostgreSQLContainer<>(TestContainerImages.postgres());
+
+ @TempDir Path temporary;
+
+ @Test
+ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchemaFourBundle()
+ throws Exception {
+ Store gds = store("game-design", "selected_full_gds", GDS_POSTGRES, false);
+ Store world = store("world-management", "selected_full_world", WORLD_POSTGRES, false);
+ Store entity = store("entity-management", "selected_full_entity", ENTITY_POSTGRES, true);
+ Store automation =
+ store("automation-scripting", "selected_full_automation", AUTOMATION_POSTGRES, true);
+ Store gameLogic = store("game-logic", "selected_full_gl", GAME_LOGIC_POSTGRES, false);
+
+ Draft draft = createDraft(gds);
+ var worldSource = registerControlledWorldSource(gds, draft.target());
+ DraftCommitBinding commit = selectedCommit(gds, draft.target());
+ applyGameDesignCommit(gds, commit);
+ var worldGraph =
+ WorldSelectedFullPublicationEvidenceFixture.applyGraph(
+ world.dsl(), world.transactions(), NAMESPACE, commit, worldSource);
+ completeGameDesignCommit(gds, commit, worldGraph.applied());
+
+ String publishRequestId = "selected-full-" + UUID.randomUUID();
+ var intent =
+ new AuthoredDraftPublishSelection.PublishIntent(
+ draft.target().canonicalTenantId(),
+ draft.target().canonicalVersionId(),
+ publishRequestId,
+ "1",
+ "controlled selected-full owner composition",
+ commit.requestId(),
+ commit.commitId(),
+ commit.digest());
+ var selection =
+ gds.write()
+ .execute(
+ ignored ->
+ new AuthoredDraftPublishSelectionRepository(
+ gds.dsl(), new DraftCommitCoordinatorRepository(gds.dsl()))
+ .reserve(intent)
+ .selection());
+ var worldOwners =
+ WorldSelectedFullPublicationEvidenceFixture.applyFreezeAndCapture(
+ world.dsl(),
+ world.transactions(),
+ NAMESPACE,
+ AuthoredDraftPublishSelectionBinding.fromStored(
+ selection.canonicalJson(), selection.digest()),
+ worldGraph,
+ SelectedFullOwnerPublicationPostgresIntegrationTest::controlledAccountBinding);
+ assertThat(worldOwners.selectedWorldDigest().digestSchemaVersion()).isEqualTo(4);
+ assertThat(worldOwners.appliedResultBytes()).isNotEmpty();
+ assertThat(worldOwners.graphBytes()).isNotEmpty();
+ assertThat(worldOwners.inventoryEvidence().freezeEvidence())
+ .isEqualTo(worldOwners.freezeEvidence());
+
+ var sourceScopeActor = UUID.randomUUID();
+ var entityAuthorization =
+ selectedOwnerAuthorization(gds, selection, Owner.ENTITY_MANAGEMENT, sourceScopeActor);
+ var entityWorldRead =
+ SelectedOwnerWorldInventoryReadEvidence.create(
+ NAMESPACE, entityAuthorization, worldOwners.freezeEvidence())
+ .request();
+ var entityInputs =
+ new SelectedOwnerEmptySourceInputs(
+ entityAuthorization,
+ new SelectedOwnerWorldInventoryReadEvidence(
+ entityWorldRead, worldOwners.inventoryEvidence()));
+ var entityRepository = new EntityEmptySelectedSourceIntakeRepository(entity.dsl());
+ var entityReceipt =
+ entityRepository.retainFresh(
+ entityInputs,
+ EntityEmptySelectedSourceIntakeReceipt.requestDigest(
+ NAMESPACE, entityAuthorization, worldOwners.freezeEvidence()));
+ assertThat(
+ entityRepository
+ .read(entityReceipt.targetNamespace(), entityReceipt.intakeRequestId())
+ .orElseThrow()
+ .canonicalBytes())
+ .containsExactly(entityReceipt.canonicalBytes());
+ assertThat(
+ entityRepository
+ .retainFresh(
+ entityInputs,
+ EntityEmptySelectedSourceIntakeReceipt.requestDigest(
+ NAMESPACE, entityAuthorization, worldOwners.freezeEvidence()))
+ .canonicalBytes())
+ .containsExactly(entityReceipt.canonicalBytes());
+
+ var automationAuthorization =
+ selectedOwnerAuthorization(gds, selection, Owner.AUTOMATION_SCRIPTING, sourceScopeActor);
+ var automationWorldRead =
+ SelectedOwnerWorldInventoryReadEvidence.create(
+ NAMESPACE, automationAuthorization, worldOwners.freezeEvidence())
+ .request();
+ var automationInputs =
+ new SelectedOwnerEmptySourceInputs(
+ automationAuthorization,
+ new SelectedOwnerWorldInventoryReadEvidence(
+ automationWorldRead, worldOwners.inventoryEvidence()));
+ var automationRepository =
+ new AutomationEmptySelectedSourceIntakeRepository(automation.dsl());
+ var automationReceipt =
+ automationRepository.retainFresh(
+ automationInputs,
+ net.firedevops.firemud.common.automation.sourceintake
+ .AutomationEmptySelectedSourceIntakeReceipt.requestDigest(
+ NAMESPACE, automationAuthorization, worldOwners.freezeEvidence()));
+ assertThat(
+ automationRepository
+ .read(automationReceipt.targetNamespace(), automationReceipt.intakeRequestId())
+ .orElseThrow()
+ .canonicalBytes())
+ .containsExactly(automationReceipt.canonicalBytes());
+ assertThat(
+ automationRepository
+ .retainFresh(
+ automationInputs,
+ net.firedevops.firemud.common.automation.sourceintake
+ .AutomationEmptySelectedSourceIntakeReceipt.requestDigest(
+ NAMESPACE, automationAuthorization, worldOwners.freezeEvidence()))
+ .canonicalBytes())
+ .containsExactly(automationReceipt.canonicalBytes());
+
+ var synchronizedSources =
+ new GameDesignSourceRepository(gds.dsl())
+ .readSynchronized(draft.target(), commit.commitId())
+ .orElseThrow();
+ var gameplaySnapshot = synchronizedSources.gameplayEvidence().orElseThrow();
+ var gameplaySource = new GameplayRuleSelectedSource(gameplaySnapshot.canonicalJson());
+ var glAuthorization =
+ new GameLogicIntakeAuthorizationBinding(
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ sourceScopeActor,
+ gameplaySource,
+ controlledAccountSources(sourceScopeActor, draft.target().canonicalTenantId()));
+ var glOperation = new GameLogicGameplayRuleIntakeOperation(NAMESPACE, glAuthorization);
+ var glTerminal =
+ GameLogicGameplayRuleIntakeTerminal.retained(
+ glOperation,
+ gameplaySource.canonicalBytes(),
+ gameplaySource.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8));
+ var glOwner = new GameLogicGameplayRuleIntakeRepository(gameLogic.dsl());
+ gameLogic
+ .write()
+ .execute(
+ ignored -> {
+ glOwner.lockOperation(glAuthorization.operationId());
+ glOwner.insertTerminal(glTerminal);
+ return null;
+ });
+ var committedGlTerminal = glOwner.findTerminal(glAuthorization.operationId()).orElseThrow();
+ assertThat(committedGlTerminal.canonicalBytes()).containsExactly(glTerminal.canonicalBytes());
+
+ var selectedReceiptRepository = new SelectedDraftGameLogicReceiptRepository(gds.dsl());
+ var glReceiptCandidate =
+ new SelectedDraftGameLogicReceipt(
+ selection,
+ glAuthorization,
+ new AccountGameLogicIntakeSettlementEvidence(committedGlTerminal));
+ var glReceipt =
+ gds.write().execute(ignored -> selectedReceiptRepository.retain(glReceiptCandidate));
+ assertThat(
+ selectedReceiptRepository
+ .readForPublication(
+ PublicationDigestRequestBinding.full(
+ draft.target().canonicalTenantId().toString(),
+ Long.toString(draft.version().getId()),
+ publishRequestId))
+ .orElseThrow()
+ .receipt()
+ .canonicalBytes())
+ .containsExactly(glReceipt.receipt().canonicalBytes());
+
+ var selectionBinding =
+ AuthoredDraftPublishSelectionBinding.fromStored(
+ selection.canonicalJson(), selection.digest());
+ var accountBinding = worldOwners.accountBinding();
+ var templateSourceRead =
+ new SelectedDraftTemplateWorldSourceAssociation.SourceRead(
+ worldOwners.sourceReadRequest(), worldOwners.sourceReadReceipt());
+ var selectedOwnerReservation =
+ gds.write()
+ .execute(
+ ignored ->
+ new SelectedDraftPublicationOwner(gds.dsl())
+ .reserve(
+ intent,
+ accountBinding,
+ worldOwners.startLocationEvidence(),
+ worldOwners.inventoryEvidence(),
+ templateSourceRead));
+ assertThat(selectedOwnerReservation.selection().canonicalBytes())
+ .containsExactly(selectionBinding.canonicalBytes());
+
+ Long gdsBundleBefore =
+ gds.dsl()
+ .fetchSingle(
+ "SELECT count(*) FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?",
+ draft.version().getTenantId(),
+ draft.version().getId())
+ .get(0, Long.class);
+ assertThat(gdsBundleBefore).isZero();
+
+ ProofPki pki = new ProofPki(temporary.resolve("selected-full-pki"));
+ Server entityServer = null;
+ Server automationServer = null;
+ Server gameLogicServer = null;
+ try {
+ entityServer =
+ ownerServer(
+ pki,
+ "entity-management-service",
+ new EntitySelectedEmptyPublicationDigestGrpcReceiver(
+ new EntitySelectedEmptyPublicationDigestService(NAMESPACE, entityRepository),
+ NAMESPACE,
+ new io.micrometer.core.instrument.simple.SimpleMeterRegistry()));
+ automationServer =
+ ownerServer(
+ pki,
+ "automation-scripting-service",
+ new AutomationSelectedEmptyPublicationDigestGrpcReceiver(
+ new AutomationSelectedEmptyPublicationDigestService(
+ NAMESPACE, automationRepository),
+ NAMESPACE,
+ new io.micrometer.core.instrument.simple.SimpleMeterRegistry()));
+ gameLogicServer =
+ ownerServer(
+ pki,
+ "game-logic-service",
+ new GameLogicGrpcService(
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ new GameLogicDraftDesignDigestServiceImpl(
+ new GameLogicPublicationSourceReadService(glOwner, NAMESPACE)),
+ null,
+ new io.micrometer.core.instrument.simple.SimpleMeterRegistry(),
+ new net.firedevops.firemud.common.security.PublicationReadGuard(NAMESPACE)));
+
+ var endpoints = new ServiceEndpointsProperties();
+ endpoints.setEntityManagementService(loopback(entityServer));
+ endpoints.setAutomationScriptingService(loopback(automationServer));
+ endpoints.setGameLogicService(loopback(gameLogicServer));
+ var channelFactory = new GrpcChannelFactory();
+ try (var entityClient =
+ new ReadyEntityManagementClient(
+ endpoints, pki.client("game-design-service"), channelFactory);
+ var automationClient =
+ new ReadyAutomationScriptingClient(
+ endpoints, pki.client("game-design-service"), channelFactory);
+ var gameLogicClient =
+ new ReadyGameLogicClient(
+ endpoints, pki.client("game-design-service"), channelFactory)) {
+ ReflectionTestUtils.setField(gameLogicClient, "workloadNamespace", NAMESPACE);
+ entityClient.connect();
+ automationClient.connect();
+ gameLogicClient.connect();
+ var gate =
+ new PublishGateServiceImpl(
+ null,
+ null,
+ entityClient,
+ gameLogicClient,
+ automationClient,
+ gds.dsl(),
+ gds.transactions(),
+ NAMESPACE);
+ VersionDto versionDto = versionDto(draft.version());
+ var publicationRequest =
+ PublicationDigestRequestBinding.full(
+ draft.target().canonicalTenantId().toString(),
+ Long.toString(draft.version().getId()),
+ publishRequestId);
+ var participantDigests =
+ gate.collectSelectedFullVersionParticipantDigests(
+ versionDto, publicationRequest, publicationRequest.derivedWorkflowIdentity());
+ assertThat(participantDigests)
+ .extracting(PublishParticipantDigestDto::participantKey)
+ .containsExactly(
+ "WORLD_MANAGEMENT",
+ "ENTITY_MANAGEMENT",
+ "GAME_LOGIC",
+ "AUTOMATION_SCRIPTING",
+ "GAME_DESIGN_CONTROL_PLANE");
+ assertThat(participantDigests)
+ .extracting(PublishParticipantDigestDto::digestSchemaVersion)
+ .containsExactly(4, 3, 1, 6, 2);
+ assertThat(participantDigests)
+ .filteredOn(digest -> "WORLD_MANAGEMENT".equals(digest.participantKey()))
+ .singleElement()
+ .satisfies(
+ digest ->
+ assertThat(digest.contentDigest())
+ .isEqualTo(worldOwners.selectedWorldDigest().contentDigest()));
+ assertThat(participantDigests)
+ .filteredOn(digest -> "GAME_LOGIC".equals(digest.participantKey()))
+ .singleElement()
+ .satisfies(digest -> assertThat(digest.abilitySchemaDigest()).startsWith("sha256:"));
+ gate.assertSelectedGatePassed(versionDto, participantDigests);
+
+ var altered = new ArrayList<>(participantDigests);
+ int automationIndex = 3;
+ var validAutomation = altered.get(automationIndex);
+ altered.set(
+ automationIndex,
+ new PublishParticipantDigestDto(
+ validAutomation.participantKey(),
+ validAutomation.scopeValue(),
+ validAutomation.baseVersionId(),
+ validAutomation.appliedCommitId(),
+ validAutomation.contentDigest(),
+ 5,
+ validAutomation.abilitySchemaDigest(),
+ validAutomation.errorCode(),
+ validAutomation.errorMessage()));
+ gate.assertSelectedGatePassed(versionDto, participantDigests);
+ assertThatThrownBy(() -> gate.assertSelectedGatePassed(versionDto, altered))
+ .isInstanceOf(RuntimeException.class);
+
+ var releaseService =
+ new PublishedReleaseBundleServiceImpl(
+ new PublishedReleaseBundleRepository(gds.dsl()),
+ new VersionRepository(gds.dsl()),
+ new ObjectMapper());
+ var controlledEmptyManifest = controlledEmptyManifest();
+ assertThatThrownBy(
+ () ->
+ gds.write()
+ .execute(
+ ignored ->
+ releaseService.createFullVersionBundle(
+ versionDto,
+ publicationRequest.derivedWorkflowIdentity(),
+ controlledEmptyManifest,
+ "controlled-generation-input",
+ altered,
+ worldOwners.startLocationEvidence())))
+ .isInstanceOf(RuntimeException.class);
+ assertThat(
+ gds.dsl()
+ .fetchSingle(
+ "SELECT count(*) FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?",
+ draft.version().getTenantId(),
+ draft.version().getId())
+ .get(0, Long.class))
+ .isZero();
+
+ PublishedReleaseBundleService releaseOwner = releaseService;
+ var written =
+ gds.write()
+ .execute(
+ ignored ->
+ releaseOwner.createFullVersionBundle(
+ versionDto,
+ publicationRequest.derivedWorkflowIdentity(),
+ controlledEmptyManifest,
+ "controlled-generation-input",
+ participantDigests,
+ worldOwners.startLocationEvidence()));
+ assertThat(written.attestationSchemaVersion()).isEqualTo("v4");
+ assertThat(written.participantDigests()).containsExactlyElementsOf(participantDigests);
+ assertThat(written.worldPublishedStartLocationEvidence().canonicalBytes())
+ .containsExactly(worldOwners.startLocationEvidence().canonicalBytes());
+ String committedBundleRow = bundleOwnerRow(gds, draft.version());
+ var independentRead =
+ new PublishedReleaseBundleServiceImpl(
+ new PublishedReleaseBundleRepository(gds.dsl()),
+ new VersionRepository(gds.dsl()),
+ new ObjectMapper())
+ .findPublishedReleaseBundle(draft.version().getTenantId(), draft.version().getId())
+ .orElseThrow();
+ assertThat(independentRead).isEqualTo(written);
+ assertThat(independentRead.attestationSchemaVersion()).isEqualTo("v4");
+ assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow);
+
+ var replay =
+ gds.write()
+ .execute(
+ ignored ->
+ releaseOwner.createFullVersionBundle(
+ versionDto,
+ publicationRequest.derivedWorkflowIdentity(),
+ controlledEmptyManifest,
+ "controlled-generation-input",
+ participantDigests,
+ worldOwners.startLocationEvidence()));
+ assertThat(replay).isEqualTo(written);
+ assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow);
+ }
+ } finally {
+ stop(entityServer);
+ stop(automationServer);
+ stop(gameLogicServer);
+ }
+ }
+
+ private static Draft createDraft(Store gds) {
+ Version savedVersion =
+ gds.write()
+ .execute(
+ ignored -> {
+ Game game = new Game();
+ game.setTenantId(UUID.randomUUID().toString());
+ game.setName("Controlled selected full owner proof");
+ Game savedGame = new GameRepository(gds.dsl()).save(game);
+ Version version = new Version();
+ version.setTenantId(savedGame.getTenantId());
+ version.setVersionNumber(1);
+ version.setVersionState(VersionLifecycleState.DRAFT);
+ version.setVersionStateEpoch(1L);
+ return new VersionRepository(gds.dsl()).save(version);
+ });
+ var target =
+ new TargetProof(
+ savedVersion.getCanonicalTenantId(),
+ savedVersion.getCanonicalVersionId(),
+ savedVersion.getId(),
+ savedVersion.getTenantId(),
+ savedVersion.getIdentitySourceGameRowId(),
+ savedVersion.getIdentitySourceGameTenantKey(),
+ savedVersion.getIdentitySourceProvenanceKind());
+ return new Draft(savedVersion, target);
+ }
+
+ private static AuthoredWorldSourceEvidence registerControlledWorldSource(
+ Store gds, TargetProof target) {
+ var repository = new GameAuthoredWorldSourceRepository(gds.dsl());
+ return gds
+ .write()
+ .execute(
+ ignored ->
+ repository.register(
+ NAMESPACE,
+ UUID.randomUUID(),
+ target.canonicalTenantId(),
+ "controlled-selected-tenant",
+ "controlled-selected-world",
+ "Controlled selected World source"));
+ }
+
+ private static DraftCommitBinding selectedCommit(Store gds, TargetProof target)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ var genesis = new GameDesignSourceRepository(gds.dsl()).readGenesis(target).orElseThrow();
+ UUID commitId = UUID.randomUUID();
+ UUID regionId = UUID.randomUUID();
+ UUID zoneId = UUID.randomUUID();
+ UUID roomId = UUID.randomUUID();
+ var counts = new ArrayList();
+ for (var family :
+ List.of(
+ WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION,
+ WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE,
+ WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM,
+ WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT,
+ WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE,
+ WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING)) {
+ counts.add(
+ WorldFreshGraphFamilyCount.newBuilder()
+ .setFamily(family)
+ .setCount(
+ family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION
+ || family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE
+ || family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM
+ ? 1
+ : 0)
+ .build());
+ }
+ var inbound = WorldInboundSourceClosureDeclaration.newBuilder().setSchemaVersion(1);
+ for (WorldInboundSourceFamily family :
+ List.of(
+ WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT,
+ WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT,
+ WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION,
+ WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING,
+ WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK,
+ WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE,
+ WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING)) {
+ inbound.addFamilyCounts(WorldInboundSourceFamilyCount.newBuilder().setFamily(family).setCount(0));
+ }
+ var declaration =
+ WorldFreshGraphDeclaration.newBuilder()
+ .setTenantId(target.canonicalTenantId().toString())
+ .setVersionId(target.canonicalVersionId().toString())
+ .addAllFamilyCounts(counts)
+ .setInboundSourceClosure(inbound.build())
+ .setStartLocation(
+ net.firedevops.firemud.worldmanagement.v1.RoomTemplateRef.newBuilder()
+ .setTenantId(target.canonicalTenantId().toString())
+ .setVersionId(target.canonicalVersionId().toString())
+ .setRoomTemplateId(roomId.toString()))
+ .build();
+ var mutations =
+ List.of(
+ mutation(commitId, roomId, regionId, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM)
+ .setRoom(
+ RoomDesignMutation.newBuilder()
+ .setName("Controlled starting room")
+ .setZoneId(zoneId.toString())
+ .setDescription("Controlled World owner input"))
+ .build(),
+ mutation(commitId, zoneId, regionId, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE)
+ .setZone(ZoneDesignMutation.newBuilder().setName("Controlled zone").setRegionId(regionId.toString()))
+ .build(),
+ mutation(commitId, regionId, regionId, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION)
+ .setRegion(
+ RegionDesignMutation.newBuilder()
+ .setName("Controlled region")
+ .setWeather("clear")
+ .setShardId(1))
+ .setFreshGraphDeclaration(declaration)
+ .build());
+
+ var revisions = new ArrayList();
+ var units = new ArrayList();
+ String commandJson =
+ "{\"schemaVersion\":1,\"commandId\":\"LOOK\",\"semanticOwner\":\"WORLD\","
+ + "\"executionDiscipline\":\"DURABLE_GAMEPLAY\",\"stageRequirement\":\"GAMEPLAY\","
+ + "\"promptPolicy\":\"NEVER\",\"actionCategory\":\"GAMEPLAY\","
+ + "\"historyRecordable\":true,\"aliases\":[],\"actionTags\":[\"WORLD_BROWSE\"],"
+ + "\"effects\":[]}";
+ revisions.add(
+ new RevisionPayload(
+ "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, CommandSource.upsertPayload(commandJson)));
+ units.add(
+ new AffectedUnit(
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ CommandSource.SCOPE,
+ target.canonicalVersionId().toString(),
+ CommandSource.SCOPE,
+ CommandSource.SCOPE_ID,
+ "0"));
+ revisions.add(
+ new RevisionPayload(
+ "1",
+ UUID.randomUUID(),
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ GameplayRuleSource.upsertPayload(
+ new GameplayRuleManifest.AdmissionTag("selected-world-admission"))));
+ units.add(
+ new AffectedUnit(
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ GameplayRuleSource.SCOPE,
+ target.canonicalVersionId().toString(),
+ GameplayRuleSource.SCOPE,
+ "effective",
+ "0"));
+ for (var mutation : mutations) {
+ revisions.add(
+ new RevisionPayload(
+ Integer.toString(revisions.size()),
+ UUID.fromString(mutation.getLogicalRevisionId()),
+ Owner.WORLD_MANAGEMENT,
+ JsonFormat.printer().omittingInsignificantWhitespace().print(mutation)));
+ String family = mutation.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", "");
+ units.add(
+ new AffectedUnit(
+ Owner.WORLD_MANAGEMENT,
+ family,
+ mutation.getAggregateId(),
+ "AGGREGATE",
+ mutation.getAggregateId(),
+ "0"));
+ units.add(
+ new AffectedUnit(
+ Owner.WORLD_MANAGEMENT,
+ family,
+ mutation.getAggregateId(),
+ "REGION_SUBTREE",
+ mutation.getScopeId(),
+ "0"));
+ }
+ return DraftCommitBinding.create(
+ target,
+ UUID.randomUUID(),
+ commitId,
+ "genesis:" + genesis.policy().receiptId(),
+ revisions,
+ units);
+ }
+
+ private static WorldDesignMutationRevision.Builder mutation(
+ UUID commitId, UUID aggregateId, UUID regionId, WorldDesignAggregateType aggregateType) {
+ return WorldDesignMutationRevision.newBuilder()
+ .setCommitId(commitId.toString())
+ .setLogicalRevisionId(UUID.randomUUID().toString())
+ .setAggregateId(aggregateId.toString())
+ .setAggregateType(aggregateType)
+ .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT)
+ .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE)
+ .setScopeId(regionId.toString());
+ }
+
+ private static void applyGameDesignCommit(Store gds, DraftCommitBinding binding) {
+ var coordinator = new DraftCommitCoordinatorRepository(gds.dsl());
+ var sources = new GameDesignSourceRepository(gds.dsl());
+ gds.write()
+ .execute(
+ ignored -> {
+ var reviewed =
+ new GameDesignReviewedBaseRepository(gds.dsl())
+ .resolve(binding.target(), DraftBaseReference.parse(binding.baseCommitId()));
+ sources.claimReviewed(binding, reviewed);
+ coordinator.claimApplicationSlot(binding);
+ for (Owner owner : binding.requiredOwners()) coordinator.markOwnerInProgress(binding, owner);
+ return null;
+ });
+ }
+
+ private static void completeGameDesignCommit(
+ Store gds,
+ DraftCommitBinding binding,
+ net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphAppliedResult worldApplied) {
+ var coordinator = new DraftCommitCoordinatorRepository(gds.dsl());
+ var sources = new GameDesignSourceRepository(gds.dsl());
+ var gameDesignApplied =
+ gds.write().execute(ignored -> sources.apply(binding));
+ var worldOutcome =
+ new DraftCommitCoordinatorRepository.OwnerOutcome(
+ Owner.WORLD_MANAGEMENT,
+ DraftCommitCoordinatorRepository.OwnerStatus.APPLIED,
+ binding.commitId(),
+ binding.digest(),
+ worldApplied.resultIdentity(),
+ worldApplied.canonicalBytes(),
+ worldApplied.appliedEpochs().stream()
+ .map(
+ epoch ->
+ new DraftCommitCoordinatorRepository.AppliedEpoch(
+ epoch.aggregateType(),
+ epoch.aggregateId(),
+ epoch.scopeType(),
+ epoch.scopeId(),
+ epoch.expectedEpoch(),
+ epoch.appliedEpoch()))
+ .toList());
+ gds.write()
+ .execute(
+ ignored -> {
+ coordinator.recordOwnerOutcome(binding, gameDesignApplied.ownerOutcome());
+ coordinator.recordOwnerOutcome(binding, worldOutcome);
+ List outcomes =
+ binding.requiredOwners().stream()
+ .map(
+ owner ->
+ owner == Owner.WORLD_MANAGEMENT
+ ? worldOutcome
+ : gameDesignApplied.ownerOutcome())
+ .toList();
+ coordinator.advanceSourceVisibilityFence(
+ binding, new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes));
+ coordinator.releaseApplicationSlot(binding);
+ return null;
+ });
+ }
+
+ private static AccountPublicationAuthorizationBinding controlledAccountBinding(
+ AuthoredDraftPublishSelectionBinding selection) {
+ UUID actor = UUID.randomUUID();
+ var input = new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection);
+ return new AccountPublicationAuthorizationBinding(
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ input,
+ controlledAccountSources(actor, selection.intent().canonicalTenantId()));
+ }
+
+ private static SelectedOwnerIntakeAuthorizationBinding selectedOwnerAuthorization(
+ Store gds,
+ AuthoredDraftPublishSelection selection,
+ Owner recipient,
+ UUID actor) {
+ var scope =
+ new SelectedOwnerIntakeSourceReadScope(
+ recipient,
+ NAMESPACE,
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ actor,
+ selection.selectedCommit());
+ var content =
+ new GameDesignSourceRepository(gds.dsl()).requireSelectedOwnerIntakeSource(scope);
+ return new SelectedOwnerIntakeAuthorizationBinding(
+ content, controlledAccountSources(actor, selection.target().canonicalTenantId()));
+ }
+
+ private static List controlledAccountSources(
+ UUID actor, UUID tenant) {
+ byte[] evidence = "TEST_ONLY controlled upstream Account source input".getBytes(StandardCharsets.UTF_8);
+ return List.of(
+ new DraftAuthorizationFenceBinding.SourceEvidence(
+ DraftAuthorizationFenceBinding.SourceKind.ACCOUNT,
+ actor.toString(),
+ "1",
+ "1",
+ null,
+ null,
+ evidence),
+ new DraftAuthorizationFenceBinding.SourceEvidence(
+ DraftAuthorizationFenceBinding.SourceKind.TENANT,
+ tenant.toString(),
+ "1",
+ "1",
+ null,
+ null,
+ evidence),
+ new DraftAuthorizationFenceBinding.SourceEvidence(
+ DraftAuthorizationFenceBinding.SourceKind.MEMBERSHIP,
+ actor + "/" + tenant,
+ "1",
+ "1",
+ null,
+ null,
+ evidence),
+ new DraftAuthorizationFenceBinding.SourceEvidence(
+ DraftAuthorizationFenceBinding.SourceKind.GLOBAL_ROLES,
+ actor.toString(),
+ "1",
+ "1",
+ null,
+ null,
+ evidence));
+ }
+
+ private static VersionDto versionDto(Version version) {
+ return new VersionDto(
+ version.getId(),
+ version.getTenantId(),
+ version.getVersionNumber(),
+ version.getVersionState(),
+ version.getVersionStateEpoch(),
+ version.getScriptPatchVersion(),
+ version.getBaseVersionId(),
+ version.isScriptOnly(),
+ version.getNotes(),
+ version.getCreatedAt(),
+ version.getUpdatedAt());
+ }
+
+ private static ExportedAssetManifest controlledEmptyManifest() throws Exception {
+ String hash =
+ HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest("[]".getBytes(StandardCharsets.UTF_8)));
+ return new ExportedAssetManifest("sha256:" + hash, 1, List.of(), List.of());
+ }
+
+ private static String bundleOwnerRow(Store gds, Version version) {
+ return gds.dsl()
+ .fetchSingle(
+ "SELECT row_to_json(t)::TEXT || ':' || t.xmin::TEXT FROM published_release_bundle t WHERE tenant_id = ? AND version_id = ?",
+ version.getTenantId(),
+ version.getId())
+ .get(0, String.class);
+ }
+
+ private static String loopback(Server server) {
+ return "127.0.0.1:" + server.getPort();
+ }
+
+ private static Server ownerServer(ProofPki pki, String service, io.grpc.BindableService handler)
+ throws Exception {
+ var identity = pki.server(service);
+ return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0))
+ .sslContext(
+ GrpcSslContexts.forServer(
+ identity.certificate().toFile(), identity.key().toFile())
+ .trustManager(pki.ca().toFile())
+ .clientAuth(ClientAuth.REQUIRE)
+ .build())
+ .addService(ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor()))
+ .build()
+ .start();
+ }
+
+ private static void stop(Server server) throws InterruptedException {
+ if (server == null) return;
+ server.shutdownNow();
+ assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue();
+ }
+
+ private static Store store(
+ String service, String schemaPrefix, PostgreSQLContainer> postgres, boolean saga) {
+ String schema = schemaPrefix + "_" + UUID.randomUUID().toString().replace("-", "");
+ var dataSource =
+ new DriverManagerDataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword());
+ dataSource.setSchema(schema);
+ String history = "flyway_schema_history_" + service.replace('-', '_');
+ var flyway =
+ Flyway.configure()
+ .dataSource(dataSource)
+ .schemas(schema)
+ .defaultSchema(schema)
+ .table(history)
+ .placeholders(Map.of("serviceSchema", schema))
+ .locations(migrationLocation(service));
+ if (saga) {
+ flyway.locations(migrationLocation(service), sagaMigrationLocation());
+ }
+ if ("entity-management".equals(service)) {
+ flyway
+ .getConfigurationExtension(PostgreSQLConfigurationExtension.class)
+ .setTransactionalLock(false);
+ }
+ flyway.load().migrate();
+ DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES);
+ var manager = new DataSourceTransactionManager(dataSource);
+ return new Store(schema, dsl, manager);
+ }
+
+ private static String migrationLocation(String service) {
+ return "filesystem:"
+ + repositoryRoot()
+ .resolve("services")
+ .resolve(service + "-service")
+ .resolve("src/main/resources/db/migration")
+ .toAbsolutePath()
+ .normalize();
+ }
+
+ private static String sagaMigrationLocation() {
+ return "filesystem:"
+ + repositoryRoot()
+ .resolve("services/common-saga/src/main/resources/db/migration/saga")
+ .toAbsolutePath()
+ .normalize();
+ }
+
+ private static Path repositoryRoot() {
+ Path current = Path.of("").toAbsolutePath();
+ while (current != null) {
+ if (Files.isDirectory(current.resolve("services/game-design-service"))) return current;
+ current = current.getParent();
+ }
+ throw new IllegalStateException("Repository root is unavailable for current-default migrations");
+ }
+
+ private record Draft(Version version, TargetProof target) {}
+
+ private record Store(String schema, DSLContext dsl, DataSourceTransactionManager transactions) {
+ TransactionTemplate write() {
+ var transaction = new TransactionTemplate(transactions);
+ transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
+ return transaction;
+ }
+ }
+
+ private static final class ReadyEntityManagementClient extends EntityManagementClient {
+ ReadyEntityManagementClient(
+ ServiceEndpointsProperties endpoints,
+ CommonGrpcClientProperties tls,
+ GrpcChannelFactory channels) {
+ super(endpoints, tls, channels, BlockingGrpcStubCustomizer.noop());
+ }
+
+ void connect() throws javax.net.ssl.SSLException, IOException {
+ initReloadingClient();
+ }
+ }
+
+ private static final class ReadyAutomationScriptingClient extends AutomationScriptingClient {
+ ReadyAutomationScriptingClient(
+ ServiceEndpointsProperties endpoints,
+ CommonGrpcClientProperties tls,
+ GrpcChannelFactory channels) {
+ super(endpoints, tls, channels, BlockingGrpcStubCustomizer.noop());
+ }
+
+ void connect() throws javax.net.ssl.SSLException, IOException {
+ initReloadingClient();
+ }
+ }
+
+ private static final class ReadyGameLogicClient extends GameLogicClient {
+ ReadyGameLogicClient(
+ ServiceEndpointsProperties endpoints,
+ CommonGrpcClientProperties tls,
+ GrpcChannelFactory channels) {
+ super(endpoints, tls, channels, BlockingGrpcStubCustomizer.noop());
+ }
+
+ void connect() throws javax.net.ssl.SSLException, IOException {
+ initReloadingClient();
+ }
+ }
+
+ private static final class ProofPki {
+ private final Path ca;
+ private final Map servers = new java.util.HashMap<>();
+ private final Map clients = new java.util.HashMap<>();
+
+ ProofPki(Path root) throws Exception {
+ Files.createDirectories(root);
+ KeyPair caKeys = keys();
+ var now = java.time.Instant.now();
+ var caName = new X500Name("CN=Controlled selected full owner proof CA");
+ var caBuilder =
+ new JcaX509v3CertificateBuilder(
+ caName,
+ BigInteger.ONE,
+ Date.from(now.minusSeconds(60)),
+ Date.from(now.plusSeconds(3600)),
+ caName,
+ caKeys.getPublic());
+ caBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
+ caBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign));
+ X509Certificate certificate =
+ new JcaX509CertificateConverter()
+ .getCertificate(
+ caBuilder.build(
+ new JcaContentSignerBuilder("SHA256withRSA").build(caKeys.getPrivate())));
+ ca = pem(root.resolve("ca.pem"), certificate);
+ for (String service :
+ List.of(
+ "game-design-service",
+ "entity-management-service",
+ "automation-scripting-service",
+ "game-logic-service")) {
+ servers.put(service, issue(root, service, true, caKeys, certificate));
+ clients.put(service, issue(root, service, false, caKeys, certificate));
+ }
+ }
+
+ Path ca() {
+ return ca;
+ }
+
+ Identity server(String service) {
+ return java.util.Objects.requireNonNull(servers.get(service));
+ }
+
+ CommonGrpcClientProperties client(String service) {
+ Identity identity = java.util.Objects.requireNonNull(clients.get(service));
+ var properties = new CommonGrpcClientProperties();
+ properties.setPlaintext(false);
+ properties.setCertChain(identity.certificate().toString());
+ properties.setPrivateKey(identity.key().toString());
+ properties.setCaCert(ca.toString());
+ return properties;
+ }
+
+ private static Identity issue(
+ Path root,
+ String service,
+ boolean server,
+ KeyPair caKeys,
+ X509Certificate caCertificate)
+ throws Exception {
+ KeyPair pair = keys();
+ var now = java.time.Instant.now();
+ var builder =
+ new JcaX509v3CertificateBuilder(
+ caCertificate,
+ new BigInteger(120, new SecureRandom()),
+ Date.from(now.minusSeconds(60)),
+ Date.from(now.plusSeconds(3600)),
+ new X500Name("CN=" + service),
+ pair.getPublic());
+ builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
+ builder.addExtension(
+ Extension.keyUsage,
+ false,
+ new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
+ builder.addExtension(
+ Extension.extendedKeyUsage,
+ false,
+ new ExtendedKeyUsage(server ? KeyPurposeId.id_kp_serverAuth : KeyPurposeId.id_kp_clientAuth));
+ builder.addExtension(
+ Extension.subjectAlternativeName,
+ false,
+ new GeneralNames(
+ new GeneralName[] {
+ new GeneralName(
+ GeneralName.uniformResourceIdentifier,
+ "spiffe://firemud/ns/" + NAMESPACE + "/sa/" + service),
+ new GeneralName(GeneralName.dNSName, "localhost"),
+ new GeneralName(GeneralName.iPAddress, "127.0.0.1")
+ }));
+ X509Certificate cert =
+ new JcaX509CertificateConverter()
+ .getCertificate(
+ builder.build(
+ new JcaContentSignerBuilder("SHA256withRSA").build(caKeys.getPrivate())));
+ String prefix = service + (server ? "-server" : "-client");
+ return new Identity(
+ pem(root.resolve(prefix + ".crt"), cert),
+ pem(root.resolve(prefix + ".key"), pair.getPrivate()));
+ }
+
+ private static KeyPair keys() throws Exception {
+ var generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(2048);
+ return generator.generateKeyPair();
+ }
+
+ private static Path pem(Path path, Object value) throws Exception {
+ try (var writer = new JcaPEMWriter(Files.newBufferedWriter(path))) {
+ writer.writeObject(value);
+ }
+ return path;
+ }
+
+ record Identity(Path certificate, Path key) {}
+ }
+}
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java
new file mode 100644
index 0000000000..5d01a70df2
--- /dev/null
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java
@@ -0,0 +1,297 @@
+package net.firedevops.firemud.gamedesign.draft;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.google.protobuf.UnknownFieldSet;
+import io.grpc.Context;
+import io.grpc.Status;
+import io.grpc.stub.StreamObserver;
+import java.time.OffsetDateTime;
+import java.util.List;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.security.SessionContext;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec;
+import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationRequest;
+import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationResponse;
+import net.firedevops.firemud.gamedesign.v1.SelectedDraftPublicationStatus;
+import org.junit.jupiter.api.Test;
+
+/** Receiver unit proof uses stipulated verified peer context and mocked selection storage. */
+class GameDesignSelectedDraftPublicationReadGrpcServiceTest {
+ private static final String NAMESPACE = "test";
+
+ @Test
+ void rejectsMissingWrongServiceAndWrongNamespacePeersBeforeDecodingAndStorage() {
+ var repository = mock(AuthoredDraftPublishSelectionRepository.class);
+ var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE);
+ var malformed = ReadSelectedDraftPublicationRequest.getDefaultInstance();
+ var absent = new Collector();
+ service.readSelectedDraftPublication(malformed, absent);
+ assertFailure(absent, Status.Code.UNAUTHENTICATED);
+ for (var peer :
+ List.of(
+ peer("game-design-service", NAMESPACE),
+ peer("account-service", "other"),
+ peer("world-management-service", "other"))) {
+ var denied = invokeAs(service, malformed, peer);
+ assertFailure(denied, Status.Code.PERMISSION_DENIED);
+ }
+ verifyNoInteractions(repository);
+ }
+
+ @Test
+ void rejectsMalformedUnknownAndCrossNamespaceRequestsBeforeStorage() {
+ var repository = mock(AuthoredDraftPublishSelectionRepository.class);
+ var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE);
+ var request = wireRequest();
+ var unknown =
+ UnknownFieldSet.newBuilder()
+ .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build())
+ .build();
+ for (var invalid :
+ List.of(
+ ReadSelectedDraftPublicationRequest.getDefaultInstance(),
+ request.toBuilder().setUnknownFields(unknown).build(),
+ request.toBuilder().setSelectionDigest("sha256:" + "0".repeat(64)).build())) {
+ assertFailure(
+ invokeAs(service, invalid, peer("account-service", NAMESPACE)),
+ Status.Code.INVALID_ARGUMENT);
+ }
+ assertFailure(
+ invokeAs(
+ service,
+ request.toBuilder().setTargetNamespace("other").build(),
+ peer("account-service", NAMESPACE)),
+ Status.Code.PERMISSION_DENIED);
+ verifyNoInteractions(repository);
+ }
+
+ @Test
+ void bothAllowedWorkloadPeersRejectAuthenticatedCallerContextBeforeDecodeOrStorage() {
+ var repository = mock(AuthoredDraftPublishSelectionRepository.class);
+ var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE);
+ try {
+ for (String caller : List.of("account-service", "world-management-service")) {
+ for (var roles : List.of(List.of(), List.of("ROLE_ADMIN"))) {
+ SessionContext.setContext("controlled-authenticated-user", roles, java.util.Map.of());
+ assertFailure(invokeAs(service, wireRequest(), peer(caller, NAMESPACE)),
+ Status.Code.PERMISSION_DENIED);
+ // Malformed bytes cannot reach decoding through an otherwise admitted workload peer.
+ assertFailure(invokeAs(service, ReadSelectedDraftPublicationRequest.getDefaultInstance(),
+ peer(caller, NAMESPACE)), Status.Code.PERMISSION_DENIED);
+ }
+ }
+ verifyNoInteractions(repository);
+ } finally {
+ SessionContext.clear();
+ }
+ }
+
+ @Test
+ void readsExactCanonicalIdentityAndReturnsOnlyExactRetainedSelectionForBothCallers() {
+ for (String caller : List.of("account-service", "world-management-service")) {
+ var repository = mock(AuthoredDraftPublishSelectionRepository.class);
+ var binding = binding();
+ when(repository.read(any(), any(), any())).thenReturn(Optional.of(snapshot(binding)));
+ var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE);
+ var request = wireRequest();
+ var response = invokeAs(service, request, peer(caller, NAMESPACE));
+ var intent = binding.intent();
+ verify(repository)
+ .read(intent.canonicalTenantId(), intent.canonicalVersionId(), intent.publishRequestId());
+ assertThat(response.errorCode).isNull();
+ assertThat(response.completed).isTrue();
+ assertThat(response.value)
+ .isEqualTo(
+ AuthoredDraftPublishSelectionReadGrpcCodec.toSelectedResponse(
+ AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest(request)));
+ assertThat(response.value.getStatus())
+ .isEqualTo(SelectedDraftPublicationStatus.SELECTED_DRAFT_PUBLICATION_STATUS_SELECTED);
+ }
+ }
+
+ @Test
+ void missingSelectionDoesNotInventSuccessfulOrTerminalEvidence() {
+ var repository = mock(AuthoredDraftPublishSelectionRepository.class);
+ when(repository.read(any(), any(), any())).thenReturn(Optional.empty());
+ var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE);
+ assertFailure(
+ invokeAs(service, wireRequest(), peer("account-service", NAMESPACE)),
+ Status.Code.NOT_FOUND);
+ }
+
+ @Test
+ void changedStoredSelectionFailsWithoutPartialBytes() {
+ var repository = mock(AuthoredDraftPublishSelectionRepository.class);
+ var original = binding();
+ var intent = original.intent();
+ var changed =
+ AuthoredDraftPublishSelectionBinding.capture(
+ new PublishIntent(
+ intent.canonicalTenantId(),
+ intent.canonicalVersionId(),
+ intent.publishRequestId(),
+ intent.expectedVersionStateEpoch(),
+ "changed notes",
+ intent.selectedCommitRequestId(),
+ intent.selectedCommitId(),
+ intent.selectedCommitDigest()),
+ original.target(),
+ original.selectedCommit(),
+ new VisibilityFence(
+ original.target(),
+ original.fenceRequestId(),
+ original.fenceCommitId(),
+ original.fenceInputDigest(),
+ original.fenceResultVectorJson(),
+ OffsetDateTime.parse(original.fenceCreatedAt())));
+ when(repository.read(any(), any(), any())).thenReturn(Optional.of(snapshot(changed)));
+ var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE);
+ assertFailure(
+ invokeAs(service, wireRequest(), peer("world-management-service", NAMESPACE)),
+ Status.Code.FAILED_PRECONDITION);
+ }
+
+ @Test
+ void corruptOrUnavailableStorageReturnsNoEvidence() {
+ for (RuntimeException failure :
+ List.of(
+ new IllegalStateException("corrupt retained selection"),
+ new org.jooq.exception.DataAccessException("storage unavailable"))) {
+ var repository = mock(AuthoredDraftPublishSelectionRepository.class);
+ when(repository.read(any(), any(), any())).thenThrow(failure);
+ var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE);
+ assertFailure(
+ invokeAs(service, wireRequest(), peer("account-service", NAMESPACE)),
+ Status.Code.UNAVAILABLE);
+ }
+ }
+
+ private static AuthoredDraftPublishSelectionRepository.SelectionSnapshot snapshot(
+ AuthoredDraftPublishSelectionBinding binding) {
+ return new AuthoredDraftPublishSelectionRepository.SelectionSnapshot(
+ AuthoredDraftPublishSelection.fromStored(binding.canonicalJson(), binding.digest()),
+ OffsetDateTime.parse("2026-10-01T00:00:00Z"));
+ }
+
+ private static ReadSelectedDraftPublicationRequest wireRequest() {
+ return AuthoredDraftPublishSelectionReadGrpcCodec.toRequest(
+ AuthoredDraftPublishSelectionReadEvidence.Request.create(NAMESPACE, binding()));
+ }
+
+ private static void assertFailure(Collector collector, Status.Code expected) {
+ assertThat(collector.errorCode).isEqualTo(expected);
+ assertThat(collector.value).isNull();
+ assertThat(collector.completed).isFalse();
+ }
+
+ private static Collector invokeAs(
+ GameDesignSelectedDraftPublicationReadGrpcService service,
+ ReadSelectedDraftPublicationRequest request,
+ GrpcPeerIdentity peer) {
+ var result = new Collector();
+ Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer);
+ Context previous = context.attach();
+ try {
+ service.readSelectedDraftPublication(request, result);
+ return result;
+ } finally {
+ context.detach(previous);
+ }
+ }
+
+ private static GrpcPeerIdentity peer(String service, String namespace) {
+ return new GrpcPeerIdentity(
+ "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service);
+ }
+
+ private static AuthoredDraftPublishSelectionBinding binding() {
+ UUID tenant = uuid("22222222-2222-4222-8222-222222222222");
+ UUID version = uuid("33333333-3333-4333-8333-333333333333");
+ var target =
+ new DraftCommitBinding.TargetProof(
+ tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW");
+ var commit =
+ DraftCommitBinding.create(
+ target,
+ uuid("44444444-4444-4444-8444-444444444444"),
+ uuid("55555555-5555-4555-8555-555555555555"),
+ "base-1",
+ List.of(
+ new RevisionPayload(
+ "0",
+ uuid("66666666-6666-4666-8666-666666666666"),
+ Owner.WORLD_MANAGEMENT,
+ "{}")),
+ List.of(
+ new AffectedUnit(
+ Owner.WORLD_MANAGEMENT,
+ "WORLD_TEMPLATE",
+ "world-1",
+ "ROOM_SCOPE",
+ "room-1",
+ "0")));
+ var selected =
+ AuthoredDraftPublishSelectionBinding.capture(
+ new PublishIntent(
+ tenant,
+ version,
+ "publication-request",
+ "5",
+ "test selection",
+ commit.requestId(),
+ commit.commitId(),
+ commit.digest()),
+ target,
+ commit,
+ new VisibilityFence(
+ target,
+ commit.requestId(),
+ commit.commitId(),
+ commit.digest(),
+ "[]",
+ OffsetDateTime.parse("2026-10-01T00:00:00Z")));
+ return selected;
+ }
+
+ private static UUID uuid(String value) {
+ return UUID.fromString(value);
+ }
+
+ private static final class Collector
+ implements StreamObserver {
+ private ReadSelectedDraftPublicationResponse value;
+ private Status.Code errorCode;
+ private boolean completed;
+
+ @Override
+ public void onNext(ReadSelectedDraftPublicationResponse response) {
+ value = response;
+ }
+
+ @Override
+ public void onError(Throwable failure) {
+ errorCode = Status.fromThrowable(failure).getCode();
+ }
+
+ @Override
+ public void onCompleted() {
+ completed = true;
+ }
+ }
+}
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java
new file mode 100644
index 0000000000..eb7e95bca3
--- /dev/null
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java
@@ -0,0 +1,358 @@
+package net.firedevops.firemud.gamedesign.publication;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.clearInvocations;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import io.grpc.ClientInterceptor;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.concurrent.TimeUnit;
+import net.firedevops.firemud.common.config.ServiceEndpointsProperties;
+import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation;
+import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal;
+import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding;
+import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadGrpcCodec;
+import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer;
+import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties;
+import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import net.firedevops.firemud.gamedesign.client.GameLogicClient;
+import net.firedevops.firemud.gamelogic.v1.GameLogicServiceGrpc;
+import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestRequest;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+class GameLogicClientTest {
+ private static final String WORKLOAD_NAMESPACE = "test";
+
+ @Test
+ void readsExactRetainedSelectionAndReturnsBothDigestProjections(@TempDir Path tlsDirectory)
+ throws IOException {
+ var receipt = SelectedDraftGameLogicReceiptTest.fixture();
+ var publication = publicationBinding(receipt);
+ var sourceRead =
+ new GameLogicPublicationSourceReadBinding(publication, receipt.authorization());
+ var response =
+ GameLogicPublicationSourceReadGrpcCodec.toResponse(
+ sourceRead, receipt.receipt().terminal());
+ var clientAndStub = client(tlsDirectory);
+ var client = clientAndStub.client();
+ var stub = clientAndStub.stub();
+ when(stub.getDraftDesignDigest(any(GetDraftDesignDigestRequest.class))).thenReturn(response);
+
+ var result = client.getDraftDesignDigestForVersion(publication, receipt);
+
+ assertThat(result.succeeded()).isTrue();
+ assertThat(result.participantKey()).isEqualTo("GAME_LOGIC");
+ assertThat(result.scopeValue()).isEqualTo(publication.versionId());
+ assertThat(result.baseVersionId()).isNull();
+ assertThat(result.appliedCommitId())
+ .isEqualTo(receipt.authorization().source().binding().commitId().toString());
+ assertThat(response.getContentDigest()).matches("sha256:[0-9a-f]{64}");
+ assertThat(result.contentDigest())
+ .isEqualTo(response.getContentDigest().substring("sha256:".length()))
+ .matches("[0-9a-f]{64}")
+ .isNotEqualTo(response.getContentDigest());
+ assertThat(result.digestSchemaVersion()).isEqualTo(response.getDigestSchemaVersion());
+ assertThat(result.abilitySchemaDigest()).isEqualTo(response.getAbilitySchemaDigest());
+ assertThat(result.abilitySchemaDigest()).matches("sha256:[0-9a-f]{64}");
+
+ var request = org.mockito.ArgumentCaptor.forClass(GetDraftDesignDigestRequest.class);
+ verify(stub).getDraftDesignDigest(request.capture());
+ assertThat(request.getValue().getTenantId()).isEqualTo(publication.tenantId());
+ assertThat(request.getValue().getVersionId()).isEqualTo(publication.versionId());
+ assertThat(request.getValue().getPublishRequestId()).isEqualTo(publication.publishRequestId());
+ assertThat(request.getValue().getDerivedWorkflowIdentity())
+ .isEqualTo(publication.derivedWorkflowIdentity());
+ assertThat(request.getValue().getRequestDigest()).isEqualTo(publication.requestDigest());
+ var decoded = GameLogicPublicationSourceReadGrpcCodec.fromRequest(request.getValue());
+ assertThat(decoded.canonicalBytes()).containsExactly(sourceRead.canonicalBytes());
+ assertThat(decoded.authorization().canonicalBytes())
+ .containsExactly(receipt.authorization().canonicalBytes());
+ verify(stub).withCallCredentials(any());
+ verify(stub).withInterceptors(any(ClientInterceptor[].class));
+ verify(stub).withMaxInboundMessageSize(GameLogicPublicationSourceReadGrpcCodec.MAX_WIRE_BYTES);
+ verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS);
+ }
+
+ @Test
+ void rejectsAValidButDifferentTerminalFromTheImmutableReceipt(@TempDir Path tlsDirectory)
+ throws IOException {
+ var receipt = SelectedDraftGameLogicReceiptTest.fixture();
+ var publication = publicationBinding(receipt);
+ var sourceRead =
+ new GameLogicPublicationSourceReadBinding(publication, receipt.authorization());
+ var retained = receipt.receipt().terminal();
+ var differentTerminal =
+ GameLogicGameplayRuleIntakeTerminal.retained(
+ new GameLogicGameplayRuleIntakeOperation("other", receipt.authorization()),
+ retained.selectedSourceBytes(),
+ retained.manifestBytes());
+ assertThat(Arrays.equals(differentTerminal.canonicalBytes(), retained.canonicalBytes()))
+ .isFalse();
+ var response =
+ GameLogicPublicationSourceReadGrpcCodec.toResponse(sourceRead, differentTerminal);
+ var clientAndStub = client(tlsDirectory);
+ ReflectionTestUtils.setField(clientAndStub.client(), "workloadNamespace", "other");
+ when(clientAndStub.stub().getDraftDesignDigest(any(GetDraftDesignDigestRequest.class)))
+ .thenReturn(response);
+
+ var result = clientAndStub.client().getDraftDesignDigestForVersion(publication, receipt);
+
+ assertThat(result.succeeded()).isFalse();
+ assertThat(result.errorCode()).isEqualTo("RESPONSE_TERMINAL_MISMATCH");
+ assertThat(result.contentDigest()).isNull();
+ assertThat(result.abilitySchemaDigest()).isNull();
+ }
+
+ @Test
+ void rejectsMalformedManifestDigestFromPublicationResponse(@TempDir Path tlsDirectory)
+ throws IOException {
+ var receipt = SelectedDraftGameLogicReceiptTest.fixture();
+ var publication = publicationBinding(receipt);
+ var sourceRead =
+ new GameLogicPublicationSourceReadBinding(publication, receipt.authorization());
+ var validResponse =
+ GameLogicPublicationSourceReadGrpcCodec.toResponse(
+ sourceRead, receipt.receipt().terminal());
+ var response =
+ validResponse.toBuilder()
+ .setContentDigest(validResponse.getContentDigest().substring("sha256:".length()))
+ .build();
+ var clientAndStub = client(tlsDirectory);
+ when(clientAndStub.stub().getDraftDesignDigest(any(GetDraftDesignDigestRequest.class)))
+ .thenReturn(response);
+
+ var result = clientAndStub.client().getDraftDesignDigestForVersion(publication, receipt);
+
+ assertThat(result.succeeded()).isFalse();
+ assertThat(result.errorCode()).isEqualTo("RESPONSE_BINDING_MISMATCH");
+ assertThat(result.contentDigest()).isNull();
+ assertThat(result.abilitySchemaDigest()).isNull();
+ }
+
+ @Test
+ void rejectsSwappedManifestAndAbilityDigestsFromPublicationResponse(@TempDir Path tlsDirectory)
+ throws IOException {
+ var receipt = SelectedDraftGameLogicReceiptTest.fixture();
+ var publication = publicationBinding(receipt);
+ var sourceRead =
+ new GameLogicPublicationSourceReadBinding(publication, receipt.authorization());
+ var validResponse =
+ GameLogicPublicationSourceReadGrpcCodec.toResponse(
+ sourceRead, receipt.receipt().terminal());
+ assertThat(validResponse.getContentDigest())
+ .isNotEqualTo(validResponse.getAbilitySchemaDigest());
+ var response =
+ validResponse.toBuilder()
+ .setContentDigest(validResponse.getAbilitySchemaDigest())
+ .setAbilitySchemaDigest(validResponse.getContentDigest())
+ .build();
+ var clientAndStub = client(tlsDirectory);
+ when(clientAndStub.stub().getDraftDesignDigest(any(GetDraftDesignDigestRequest.class)))
+ .thenReturn(response);
+
+ var result = clientAndStub.client().getDraftDesignDigestForVersion(publication, receipt);
+
+ assertThat(result.succeeded()).isFalse();
+ assertThat(result.errorCode()).isEqualTo("RESPONSE_BINDING_MISMATCH");
+ assertThat(result.contentDigest()).isNull();
+ assertThat(result.abilitySchemaDigest()).isNull();
+ }
+
+ @Test
+ void missingReceiptLegacyPathFailsClosedWithoutCallingGameLogic(@TempDir Path tlsDirectory)
+ throws IOException {
+ var receipt = SelectedDraftGameLogicReceiptTest.fixture();
+ var clientAndStub = client(tlsDirectory);
+
+ var result = clientAndStub.client().getDraftDesignDigestForVersion(publicationBinding(receipt));
+
+ assertThat(result.succeeded()).isFalse();
+ assertThat(result.errorCode()).isEqualTo("SELECTED_GAME_LOGIC_RECEIPT_REQUIRED");
+ verifyNoInteractions(clientAndStub.stub());
+ }
+
+ @Test
+ void rejectsPublicationRequestThatDoesNotMatchTheReceiptSelection(@TempDir Path tlsDirectory)
+ throws IOException {
+ var receipt = SelectedDraftGameLogicReceiptTest.fixture();
+ var publication = publicationBinding(receipt);
+ var changedPublication =
+ PublicationDigestRequestBinding.full(
+ publication.tenantId(),
+ publication.versionId(),
+ publication.publishRequestId() + "-different");
+ var clientAndStub = client(tlsDirectory);
+
+ assertThatThrownBy(
+ () ->
+ clientAndStub.client().getDraftDesignDigestForVersion(changedPublication, receipt))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("differs from immutable selected Game Logic receipt");
+ verifyNoInteractions(clientAndStub.stub());
+ }
+
+ @Test
+ void missingWorkloadNamespaceDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException {
+ var receipt = SelectedDraftGameLogicReceiptTest.fixture();
+ var clientAndStub = client(tlsDirectory);
+ ReflectionTestUtils.setField(clientAndStub.client(), "workloadNamespace", "");
+
+ assertThatThrownBy(
+ () ->
+ clientAndStub
+ .client()
+ .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("configured workload namespace");
+ verifyNoInteractions(clientAndStub.stub());
+ }
+
+ @Test
+ void invalidWorkloadNamespaceDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException {
+ var receipt = SelectedDraftGameLogicReceiptTest.fixture();
+ var clientAndStub = client(tlsDirectory);
+ ReflectionTestUtils.setField(clientAndStub.client(), "workloadNamespace", "Not_A_Namespace");
+
+ assertThatThrownBy(
+ () ->
+ clientAndStub
+ .client()
+ .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("configured workload namespace");
+ verifyNoInteractions(clientAndStub.stub());
+ }
+
+ @Test
+ void plaintextTlsConfigurationDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException {
+ var receipt = SelectedDraftGameLogicReceiptTest.fixture();
+ var tls = new CommonGrpcClientProperties();
+ tls.setPlaintext(true);
+ var clientAndStub = client(tlsDirectory, tls);
+
+ assertThatThrownBy(
+ () ->
+ clientAndStub
+ .client()
+ .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("file-backed workload mTLS");
+ verifyNoInteractions(clientAndStub.stub());
+ }
+
+ @Test
+ void unreadableTlsMaterialDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException {
+ var receipt = SelectedDraftGameLogicReceiptTest.fixture();
+ var tls = fileBackedTls(tlsDirectory);
+ tls.setCaCert(tlsDirectory.resolve("missing-ca.crt").toString());
+ var clientAndStub = client(tlsDirectory, tls);
+
+ assertThatThrownBy(
+ () ->
+ clientAndStub
+ .client()
+ .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("CA certificate")
+ .hasMessageContaining("readable file");
+ verifyNoInteractions(clientAndStub.stub());
+ }
+
+ @Test
+ void activeSqlTransactionDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException {
+ var receipt = SelectedDraftGameLogicReceiptTest.fixture();
+ var clientAndStub = client(tlsDirectory);
+ TransactionSynchronizationManager.setActualTransactionActive(true);
+ try {
+ assertThatThrownBy(
+ () ->
+ clientAndStub
+ .client()
+ .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("no ambient SQL transaction");
+ } finally {
+ TransactionSynchronizationManager.setActualTransactionActive(false);
+ }
+ verifyNoInteractions(clientAndStub.stub());
+ }
+
+ @Test
+ void activeSqlSynchronizationDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException {
+ var receipt = SelectedDraftGameLogicReceiptTest.fixture();
+ var clientAndStub = client(tlsDirectory);
+ TransactionSynchronizationManager.initSynchronization();
+ try {
+ assertThatThrownBy(
+ () ->
+ clientAndStub
+ .client()
+ .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("no ambient SQL transaction");
+ } finally {
+ TransactionSynchronizationManager.clearSynchronization();
+ }
+ verifyNoInteractions(clientAndStub.stub());
+ }
+
+ private static PublicationDigestRequestBinding publicationBinding(
+ SelectedDraftGameLogicReceipt receipt) {
+ return PublicationDigestRequestBinding.full(
+ receipt.selection().intent().canonicalTenantId().toString(),
+ Long.toString(receipt.selection().target().gameDesignVersionRowId()),
+ receipt.selection().intent().publishRequestId());
+ }
+
+ private static ClientAndStub client(Path tlsDirectory) throws IOException {
+ return client(tlsDirectory, fileBackedTls(tlsDirectory));
+ }
+
+ private static ClientAndStub client(Path tlsDirectory, CommonGrpcClientProperties tls) {
+ var client =
+ new GameLogicClient(
+ new ServiceEndpointsProperties(),
+ tls,
+ mock(GrpcChannelFactory.class),
+ BlockingGrpcStubCustomizer.noop());
+ ReflectionTestUtils.setField(client, "workloadNamespace", WORKLOAD_NAMESPACE);
+
+ var stub = mock(GameLogicServiceGrpc.GameLogicServiceBlockingStub.class);
+ when(stub.withCallCredentials(any())).thenReturn(stub);
+ when(stub.withInterceptors(any(ClientInterceptor[].class))).thenReturn(stub);
+ when(stub.withMaxInboundMessageSize(GameLogicPublicationSourceReadGrpcCodec.MAX_WIRE_BYTES))
+ .thenReturn(stub);
+ when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub);
+ clearInvocations(stub);
+ ReflectionTestUtils.setField(client, "stub", stub);
+ return new ClientAndStub(client, stub);
+ }
+
+ private static CommonGrpcClientProperties fileBackedTls(Path tlsDirectory) throws IOException {
+ var tls = new CommonGrpcClientProperties();
+ tls.setCertChain(write(tlsDirectory.resolve("client.crt")));
+ tls.setPrivateKey(write(tlsDirectory.resolve("client.key")));
+ tls.setCaCert(write(tlsDirectory.resolve("ca.crt")));
+ return tls;
+ }
+
+ private static String write(Path path) throws IOException {
+ Files.writeString(path, "test material");
+ return path.toString();
+ }
+
+ private record ClientAndStub(
+ GameLogicClient client, GameLogicServiceGrpc.GameLogicServiceBlockingStub stub) {}
+}
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
new file mode 100644
index 0000000000..7481d9a05f
--- /dev/null
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
@@ -0,0 +1,216 @@
+package net.firedevops.firemud.gamedesign.publication;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof;
+import net.firedevops.firemud.common.gamedesign.RealmPolicySource;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import org.junit.jupiter.api.Test;
+
+/** Structural digest vectors only; synthetic source rows do not prove physical owner provenance. */
+class SelectedDraftControlPlaneDigestTest {
+ @Test
+ void exactSixFamilyPreimageIsDeterministicAndDoesNotIncludePublicationRequestIdentity()
+ throws Exception {
+ var selected = selectedBinding();
+ var sources = sources(selected);
+
+ var firstRequest =
+ PublicationDigestRequestBinding.full(
+ selected.target().canonicalTenantId().toString(),
+ Long.toString(selected.target().gameDesignVersionRowId()),
+ "publish-one");
+ var retryRequest =
+ PublicationDigestRequestBinding.full(
+ selected.target().canonicalTenantId().toString(),
+ Long.toString(selected.target().gameDesignVersionRowId()),
+ "publish-two");
+
+ var first = SelectedDraftControlPlaneDigest.compute(selected, sources);
+ var replay = SelectedDraftControlPlaneDigest.compute(selected, sources);
+ var otherRequest = SelectedDraftControlPlaneDigest.compute(selected, sources);
+
+ assertThat(first).isEqualTo(replay);
+ assertThat(first).isEqualTo(otherRequest);
+ assertThat(firstRequest.requestDigest()).isNotEqualTo(retryRequest.requestDigest());
+ assertThat(first.digestSchemaVersion()).isEqualTo(2);
+ assertThat(first.tenantId()).isEqualTo(selected.target().canonicalTenantId().toString());
+ assertThat(first.scopeValue())
+ .isEqualTo(Long.toString(selected.target().gameDesignVersionRowId()));
+ assertThat(first.appliedCommitId()).isEqualTo(selected.commitId().toString());
+ assertThat(first.contentDigest())
+ .isEqualTo("08584ce89ee924b5d8b5b613ee60ccc0780716ba43cc7671fd5735b4b5e8015b");
+ }
+
+ @Test
+ void changedSnapshotOrSelectedBindingChangesContentDigest() throws Exception {
+ var selected = selectedBinding();
+ var originalSources = sources(selected);
+ var original = SelectedDraftControlPlaneDigest.compute(selected, originalSources);
+
+ var changedAsset =
+ new AssetSnapshot(
+ selected,
+ "1",
+ null,
+ UUID.fromString("11111111-1111-4111-8111-111111111111"),
+ List.of());
+ var changedSnapshot =
+ new GameDesignSourceRepository.SynchronizedSources(
+ originalSources.command(),
+ originalSources.policy(),
+ changedAsset,
+ originalSources.gameplay(),
+ originalSources.branding(),
+ originalSources.templateConfig());
+ assertThat(SelectedDraftControlPlaneDigest.compute(selected, changedSnapshot).contentDigest())
+ .isNotEqualTo(original.contentDigest());
+
+ var changedBinding =
+ DraftCommitBinding.create(
+ selected.target(),
+ selected.requestId(),
+ UUID.fromString("99999999-9999-4999-8999-999999999999"),
+ selected.baseCommitId(),
+ selected.revisions(),
+ selected.affectedUnits());
+ var changedInput =
+ SelectedDraftControlPlaneDigest.compute(changedBinding, sources(changedBinding));
+ assertThat(changedInput.contentDigest()).isNotEqualTo(original.contentDigest());
+ }
+
+ @Test
+ void missingBrandingOrTemplateFamilyCannotBeTreatedAsAnEmptySnapshot() throws Exception {
+ var selected = selectedBinding();
+ var complete = sources(selected);
+ var missingBrand =
+ new GameDesignSourceRepository.SynchronizedSources(
+ complete.command(),
+ complete.policy(),
+ complete.asset(),
+ complete.gameplay(),
+ Optional.empty(),
+ complete.templateConfig());
+ var missingTemplate =
+ new GameDesignSourceRepository.SynchronizedSources(
+ complete.command(),
+ complete.policy(),
+ complete.asset(),
+ complete.gameplay(),
+ complete.branding(),
+ Optional.empty());
+
+ assertThatThrownBy(() -> SelectedDraftControlPlaneDigest.compute(selected, missingBrand))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("branding");
+ assertThatThrownBy(() -> SelectedDraftControlPlaneDigest.compute(selected, missingTemplate))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("template-config");
+ }
+
+ @Test
+ void sourceBindingMustExactlyEqualSelectedDraftBinding() throws Exception {
+ var selected = selectedBinding();
+ var otherBinding =
+ DraftCommitBinding.create(
+ selected.target(),
+ selected.requestId(),
+ UUID.fromString("99999999-9999-4999-8999-999999999999"),
+ selected.baseCommitId(),
+ selected.revisions(),
+ selected.affectedUnits());
+
+ assertThatThrownBy(
+ () -> SelectedDraftControlPlaneDigest.compute(selected, sources(otherBinding)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("exact Draft commit");
+ }
+
+ private static GameDesignPublicationOperation operation() throws Exception {
+ return IsolatedPublicationOperationFixtures.fresh(
+ new TargetProof(
+ UUID.fromString("11111111-1111-4111-8111-111111111111"),
+ UUID.fromString("22222222-2222-4222-8222-222222222222"),
+ 19L,
+ "tenant-key",
+ 42L,
+ "tenant-key",
+ "NEW_GAME_ROW"));
+ }
+
+ private static DraftCommitBinding selectedBinding() throws Exception {
+ var selected = operation().account().input().selection().selectedCommit();
+ var policyRevisions =
+ selected.revisions().stream()
+ .filter(
+ revision -> revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE)
+ .filter(RealmPolicySource::isPolicyRevision)
+ .toList();
+ if (policyRevisions.size() != 1) {
+ throw new IllegalStateException("Expected exactly one selected policy revision");
+ }
+ var policyRevision = policyRevisions.getFirst();
+ var fixedRevisionId = UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee");
+ var oldRevisionId = policyRevision.revisionId().toString();
+ var revisions = new java.util.ArrayList();
+ for (var revision : selected.revisions()) {
+ var payload =
+ new String(
+ Rfc8785CanonicalJson.canonicalizeUtf8(revision.payload()),
+ java.nio.charset.StandardCharsets.UTF_8);
+ var revisionId = revision.revisionId();
+ if (revision == policyRevision) {
+ if (payload.indexOf(oldRevisionId) < 0
+ || payload.indexOf(oldRevisionId) != payload.lastIndexOf(oldRevisionId)) {
+ throw new IllegalStateException(
+ "Expected policy revision identity exactly once in payload");
+ }
+ payload = payload.replace(oldRevisionId, fixedRevisionId.toString());
+ revisionId = fixedRevisionId;
+ }
+ revisions.add(
+ new RevisionPayload(revision.revisionOrder(), revisionId, revision.owner(), payload));
+ }
+ return DraftCommitBinding.create(
+ selected.target(),
+ selected.requestId(),
+ selected.commitId(),
+ selected.baseCommitId(),
+ revisions,
+ selected.affectedUnits());
+ }
+
+ private static GameDesignSourceRepository.SynchronizedSources sources(
+ DraftCommitBinding binding) {
+ var command = new CommandSnapshot(binding, "0", null, "sha256:" + "a".repeat(64), List.of());
+ var policies =
+ binding.revisions().stream()
+ .filter(
+ revision -> revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE)
+ .filter(RealmPolicySource::isPolicyRevision)
+ .map(revision -> RealmPolicySource.revision(binding, revision))
+ .toList();
+ var policy = new RealmPolicySnapshot(binding, "1", policies);
+ var asset =
+ new AssetSnapshot(
+ binding, "0", null, UUID.fromString("33333333-3333-4333-8333-333333333333"), List.of());
+ var gameplay =
+ new GameplayRuleSnapshot(
+ binding, "0", null, UUID.fromString("44444444-4444-4444-8444-444444444444"), List.of());
+ var branding =
+ new BrandingSourceSnapshot(
+ binding, "0", null, UUID.fromString("55555555-5555-4555-8555-555555555555"), List.of());
+ var template =
+ new TemplateConfigSourceSnapshot(
+ binding, "0", null, UUID.fromString("66666666-6666-4666-8666-666666666666"), List.of());
+ return new GameDesignSourceRepository.SynchronizedSources(
+ command, policy, asset, gameplay, Optional.of(branding), Optional.of(template));
+ }
+}
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
new file mode 100644
index 0000000000..fc3d6a7ab8
--- /dev/null
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
@@ -0,0 +1,325 @@
+package net.firedevops.firemud.gamedesign.publication;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import java.util.List;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof;
+import net.firedevops.firemud.common.gamedesign.RealmPolicySource;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.TransactionStatus;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Structural owner-read proof; mocks do not establish physical PostgreSQL source provenance. */
+class SelectedDraftPublicationDigestReadServiceTest {
+ private static final String NAMESPACE = "test";
+
+ private final SelectedDraftPublicationDigestReadService.OwnerRead owner =
+ mock(SelectedDraftPublicationDigestReadService.OwnerRead.class);
+ private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class);
+ private final TransactionStatus transactionStatus = mock(TransactionStatus.class);
+
+ @AfterEach
+ void clearTransactionState() {
+ TransactionSynchronizationManager.clear();
+ }
+
+ @Test
+ void readsExactSelectionFrozenAndSynchronizedSourcesInOneReadOnlyRepeatableReadSnapshot()
+ throws Exception {
+ var fixture = fixture();
+ var request = request(fixture.operation());
+ when(transactions.getTransaction(any())).thenReturn(transactionStatus);
+ when(owner.read(request.derivedWorkflowIdentity()))
+ .thenReturn(
+ Optional.of(
+ new GameDesignPublicationOperationRepository.Readback(
+ fixture.operation(), "PENDING", new byte[] {1})));
+ when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture()));
+ when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId()))
+ .thenReturn(Optional.of(fixture.sources()));
+
+ var result =
+ new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE)
+ .read(NAMESPACE, request);
+
+ assertThat(result.requestBinding()).isSameAs(request);
+ assertThat(result.requestDigest()).isEqualTo(request.requestDigest());
+ assertThat(result.gameDesignDigest().tenantId()).isEqualTo(request.tenantId());
+ assertThat(result.gameDesignDigest().scopeValue()).isEqualTo(request.versionId());
+ assertThat(result.gameDesignDigest().appliedCommitId())
+ .isEqualTo(fixture.binding().commitId().toString());
+ assertThat(result.gameDesignDigest().digestSchemaVersion()).isEqualTo(2);
+ assertThat(result.worldManagementDigest().participantKey()).isEqualTo("WORLD_MANAGEMENT");
+ assertThat(result.worldManagementDigest().contentDigest())
+ .isEqualTo(fixture.operation().world().request().contentDigest());
+ assertThat(result.worldManagementDigest().digestSchemaVersion())
+ .isEqualTo(fixture.operation().world().request().digestSchemaVersion());
+
+ var definition = ArgumentCaptor.forClass(TransactionDefinition.class);
+ var order = inOrder(transactions, owner);
+ order.verify(transactions).getTransaction(definition.capture());
+ order.verify(owner).read(request.derivedWorkflowIdentity());
+ order.verify(owner).requireExactSelection(fixture.operation());
+ order.verify(owner).readSourceCapture(fixture.operation());
+ order.verify(owner).readSynchronized(fixture.binding().target(), fixture.binding().commitId());
+ order.verify(transactions).commit(transactionStatus);
+ assertThat(definition.getValue().getPropagationBehavior())
+ .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
+ assertThat(definition.getValue().getIsolationLevel())
+ .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ);
+ assertThat(definition.getValue().isReadOnly()).isTrue();
+ }
+
+ @Test
+ void namespaceMalformedScopeAndAmbientSqlAreRejectedBeforeOwnerReads() throws Exception {
+ var fixture = fixture();
+ var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE);
+
+ assertCode(
+ Status.Code.PERMISSION_DENIED, () -> service.read("other", request(fixture.operation())));
+ assertCode(Status.Code.INVALID_ARGUMENT, () -> service.read(NAMESPACE, null));
+ assertCode(
+ Status.Code.INVALID_ARGUMENT,
+ () ->
+ service.read(
+ NAMESPACE,
+ PublicationDigestRequestBinding.patch(
+ UUID.randomUUID().toString(), "19", "patch", "publish-id")));
+ assertCode(
+ Status.Code.INVALID_ARGUMENT,
+ () ->
+ service.read(
+ NAMESPACE,
+ PublicationDigestRequestBinding.full("not-a-canonical-uuid", "19", "publish-id")));
+
+ TransactionSynchronizationManager.setActualTransactionActive(true);
+ assertCode(
+ Status.Code.FAILED_PRECONDITION,
+ () -> service.read(NAMESPACE, request(fixture.operation())));
+ TransactionSynchronizationManager.setActualTransactionActive(false);
+ TransactionSynchronizationManager.initSynchronization();
+ assertCode(
+ Status.Code.FAILED_PRECONDITION,
+ () -> service.read(NAMESPACE, request(fixture.operation())));
+
+ verifyNoInteractions(owner, transactions);
+ }
+
+ @Test
+ void wrongActualVersionOrPublicationRequestCannotReuseAnotherOriginalOperation()
+ throws Exception {
+ var fixture = fixture();
+ var validRequest = request(fixture.operation());
+ when(transactions.getTransaction(any())).thenReturn(transactionStatus);
+ when(owner.read(any()))
+ .thenReturn(
+ Optional.of(
+ new GameDesignPublicationOperationRepository.Readback(
+ fixture.operation(), "PENDING", new byte[] {1})));
+ var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE);
+
+ var wrongVersion =
+ PublicationDigestRequestBinding.full(
+ validRequest.tenantId(), "20", validRequest.publishRequestId());
+ assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, wrongVersion));
+ var wrongTenant =
+ PublicationDigestRequestBinding.full(
+ "33333333-3333-4333-8333-333333333333",
+ validRequest.versionId(),
+ validRequest.publishRequestId());
+ assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, wrongTenant));
+ var wrongRequest =
+ PublicationDigestRequestBinding.full(
+ validRequest.tenantId(), validRequest.versionId(), "different-request");
+ assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, wrongRequest));
+
+ verify(owner, never()).requireExactSelection(any());
+ verify(owner, never()).readSourceCapture(any());
+ verify(owner, never()).readSynchronized(any(), any());
+ }
+
+ @Test
+ void missingOperationOrRetainedSelectionFailsBeforeSourceReads() throws Exception {
+ var fixture = fixture();
+ var request = request(fixture.operation());
+ when(transactions.getTransaction(any())).thenReturn(transactionStatus);
+ when(owner.read(request.derivedWorkflowIdentity())).thenReturn(Optional.empty());
+ var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE);
+ assertCode(Status.Code.NOT_FOUND, () -> service.read(NAMESPACE, request));
+ verify(owner, never()).requireExactSelection(any());
+ verify(owner, never()).readSourceCapture(any());
+
+ org.mockito.Mockito.reset(owner);
+ when(owner.read(request.derivedWorkflowIdentity()))
+ .thenReturn(
+ Optional.of(
+ new GameDesignPublicationOperationRepository.Readback(
+ fixture.operation(), "PENDING", new byte[] {1})));
+ org.mockito.Mockito.doThrow(new IllegalStateException("selection readback unavailable"))
+ .when(owner)
+ .requireExactSelection(fixture.operation());
+ assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, request));
+ verify(owner, never()).readSourceCapture(any());
+ }
+
+ @Test
+ void missingSourceFamiliesAndFrozenSnapshotMismatchCannotProveAnEmptyOrDifferentSource()
+ throws Exception {
+ var fixture = fixture();
+ var request = request(fixture.operation());
+ when(transactions.getTransaction(any())).thenReturn(transactionStatus);
+ when(owner.read(request.derivedWorkflowIdentity()))
+ .thenReturn(
+ Optional.of(
+ new GameDesignPublicationOperationRepository.Readback(
+ fixture.operation(), "PENDING", new byte[] {1})));
+ when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture()));
+ var missingBranding =
+ new GameDesignSourceRepository.SynchronizedSources(
+ fixture.sources().command(),
+ fixture.sources().policy(),
+ fixture.sources().asset(),
+ fixture.sources().gameplay(),
+ Optional.empty(),
+ fixture.sources().templateConfig());
+ when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId()))
+ .thenReturn(Optional.of(missingBranding));
+ var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE);
+ assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, request));
+
+ org.mockito.Mockito.reset(owner);
+ when(owner.read(request.derivedWorkflowIdentity()))
+ .thenReturn(
+ Optional.of(
+ new GameDesignPublicationOperationRepository.Readback(
+ fixture.operation(), "PENDING", new byte[] {1})));
+ when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture()));
+ var changedAsset =
+ new AssetSnapshot(
+ fixture.binding(),
+ "1",
+ null,
+ UUID.fromString("77777777-7777-4777-8777-777777777777"),
+ List.of());
+ var changedSources =
+ new GameDesignSourceRepository.SynchronizedSources(
+ fixture.sources().command(),
+ fixture.sources().policy(),
+ changedAsset,
+ fixture.sources().gameplay(),
+ fixture.sources().branding(),
+ fixture.sources().templateConfig());
+ when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId()))
+ .thenReturn(Optional.of(changedSources));
+ assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, request));
+
+ org.mockito.Mockito.reset(owner);
+ when(owner.read(request.derivedWorkflowIdentity()))
+ .thenReturn(
+ Optional.of(
+ new GameDesignPublicationOperationRepository.Readback(
+ fixture.operation(), "PENDING", new byte[] {1})));
+ when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture()));
+ var anotherCommit =
+ DraftCommitBinding.create(
+ fixture.binding().target(),
+ fixture.binding().requestId(),
+ UUID.fromString("99999999-9999-4999-8999-999999999999"),
+ fixture.binding().baseCommitId(),
+ fixture.binding().revisions(),
+ fixture.binding().affectedUnits());
+ when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId()))
+ .thenReturn(Optional.of(sources(anotherCommit)));
+ assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, request));
+ }
+
+ private static PublicationDigestRequestBinding request(GameDesignPublicationOperation operation) {
+ var selection = operation.account().input().selection();
+ return PublicationDigestRequestBinding.full(
+ selection.intent().canonicalTenantId().toString(),
+ Long.toString(selection.target().gameDesignVersionRowId()),
+ selection.intent().publishRequestId());
+ }
+
+ private static Fixture fixture() throws Exception {
+ var operation =
+ IsolatedPublicationOperationFixtures.fresh(
+ new TargetProof(
+ UUID.fromString("11111111-1111-4111-8111-111111111111"),
+ UUID.fromString("22222222-2222-4222-8222-222222222222"),
+ 19L,
+ "tenant-key",
+ 42L,
+ "tenant-key",
+ "NEW_GAME_ROW"));
+ var binding = operation.account().input().selection().selectedCommit();
+ var sources = sources(binding);
+ var capture =
+ new GameDesignSourceRepository.Capture(
+ new CommandSnapshot.Capture(operation, sources.command()),
+ new RealmPolicySnapshot.Capture(operation, sources.policy()),
+ new AssetSnapshot.Capture(operation, sources.asset()),
+ new BrandingSourceSnapshot.Capture(operation, sources.branding().orElseThrow()),
+ new TemplateConfigSourceSnapshot.Capture(
+ operation, sources.templateConfig().orElseThrow()));
+ return new Fixture(operation, binding, sources, capture);
+ }
+
+ private static GameDesignSourceRepository.SynchronizedSources sources(
+ DraftCommitBinding binding) {
+ var command = new CommandSnapshot(binding, "0", null, "sha256:" + "a".repeat(64), List.of());
+ var policies =
+ binding.revisions().stream()
+ .filter(
+ revision -> revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE)
+ .filter(RealmPolicySource::isPolicyRevision)
+ .map(revision -> RealmPolicySource.revision(binding, revision))
+ .toList();
+ var policy = new RealmPolicySnapshot(binding, "1", policies);
+ var asset =
+ new AssetSnapshot(
+ binding, "0", null, UUID.fromString("33333333-3333-4333-8333-333333333333"), List.of());
+ var gameplay =
+ new GameplayRuleSnapshot(
+ binding, "0", null, UUID.fromString("44444444-4444-4444-8444-444444444444"), List.of());
+ var branding =
+ new BrandingSourceSnapshot(
+ binding, "0", null, UUID.fromString("55555555-5555-4555-8555-555555555555"), List.of());
+ var template =
+ new TemplateConfigSourceSnapshot(
+ binding, "0", null, UUID.fromString("66666666-6666-4666-8666-666666666666"), List.of());
+ return new GameDesignSourceRepository.SynchronizedSources(
+ command, policy, asset, gameplay, Optional.of(branding), Optional.of(template));
+ }
+
+ private static void assertCode(Status.Code expected, Runnable action) {
+ assertThatThrownBy(action::run)
+ .isInstanceOf(StatusRuntimeException.class)
+ .satisfies(
+ failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected));
+ }
+
+ private record Fixture(
+ GameDesignPublicationOperation operation,
+ DraftCommitBinding binding,
+ GameDesignSourceRepository.SynchronizedSources sources,
+ GameDesignSourceRepository.Capture capture) {}
+}
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java
index dac2bbfc24..dc2d8722bb 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java
@@ -60,6 +60,25 @@ class StartSessionLaunchDescriptorProducerTest {
private static final long FENCE = 8L;
private static final JsonMapper JSON = JsonMapper.builder().build();
+ @Test
+ void selectedReleaseMatchingRetainsV2AndAcceptsOnlyFullV4() {
+ assertThat(
+ StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v2"))
+ .isTrue();
+ assertThat(
+ StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v4"))
+ .isTrue();
+ assertThat(
+ StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v1"))
+ .isFalse();
+ assertThat(
+ StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v3"))
+ .isFalse();
+ assertThat(
+ StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema(null))
+ .isFalse();
+ }
+
@Test
void requiresExactReplayAndSameNamespacePeerBeforeOwnerWork() {
var associationReader = mock(StartSessionTemplateAssociationReadService.class);
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java
index b403b6aae1..847eee28b3 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java
@@ -1,5 +1,6 @@
package net.firedevops.firemud.gamedesign.publication;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
@@ -43,6 +44,25 @@ class StartSessionTemplateAssociationReadServiceTest {
private final DSLContext dsl = mock(DSLContext.class);
private final PublishedReleaseBundleService releases = mock(PublishedReleaseBundleService.class);
+ @Test
+ void configuredReleaseSelectionRetainsV2AndAcceptsOnlyFullV4() {
+ assertThat(
+ StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v2"))
+ .isTrue();
+ assertThat(
+ StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v4"))
+ .isTrue();
+ assertThat(
+ StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v1"))
+ .isFalse();
+ assertThat(
+ StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v3"))
+ .isFalse();
+ assertThat(
+ StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema(null))
+ .isFalse();
+ }
+
@Test
void independentlyChecksExactAccountAttemptBeforeOpeningAnyLocalSnapshot() {
var tuple = postTuple("account-before-local-snapshot");
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java
index 714e30c47f..261e398e65 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java
@@ -56,6 +56,36 @@ void selectorReleaseIsAssembledFromImmutableLocalBundleWithoutMutableOwnerReads(
verifyReadOnlyCallsOnly();
}
+ @Test
+ void selectedFullV4ReadbackUsesExactEntityAndAutomationSchemas() throws Exception {
+ var selector = selectorEvidence(4);
+ var participants =
+ PublishedWorldSelectorFixtures.participants(
+ VERSION_ID,
+ selector,
+ AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
+ givenBundle(selectedFullBundle(selector, participants));
+
+ var result =
+ service.getCompleteLaunchBinding(
+ READ_REQUEST_ID,
+ CANONICAL_TENANT_ID,
+ WORLD_SLUG,
+ CONTROL_PLANE_REQUEST_ID,
+ descriptor.requestDigest(),
+ descriptor.resultDigest());
+
+ assertEquals(
+ AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION,
+ result.releaseAttestation().schemaVersion());
+ assertEquals(List.of(4, 3, 1, 6, 2), result.releaseAttestation().participantDigests().stream()
+ .map(AuthoredWorldReleaseAttestationEvidence.Participant::digestSchemaVersion)
+ .toList());
+ assertEquals(selector, result.releaseAttestation().worldStartLocationEvidence());
+ result.releaseAttestation().requireValid(descriptor);
+ verifyReadOnlyCallsOnly();
+ }
+
@Test
void completeLaunchBindingRejectsObsoleteOrUnselectedWorldSchemas() {
for (int schema : List.of(2, 4)) {
@@ -1003,6 +1033,32 @@ private WorldPublishedStartLocationEvidence selectorEvidence() throws Exception
source.provenanceKind()));
}
+ private WorldPublishedStartLocationEvidence selectorEvidence(int digestSchemaVersion)
+ throws Exception {
+ var base = selectorEvidence();
+ var original = base.request();
+ var request =
+ new WorldPublishedStartLocationEvidence.Request(
+ original.targetNamespace(),
+ original.canonicalTenantId(),
+ original.canonicalVersionId(),
+ original.intakeRequestId(),
+ original.publicationFence(),
+ original.publicationRequestId(),
+ original.requestDigest(),
+ original.versionStateEpoch(),
+ original.publishWorkflowId(),
+ original.appliedCommitId(),
+ original.contentDigest(),
+ digestSchemaVersion,
+ original.worldAffectedTuples());
+ return new WorldPublishedStartLocationEvidence(
+ request,
+ base.selectorReceiptBytes(),
+ base.originalAccountBindingBytes(),
+ base.appliedResultBytes());
+ }
+
private PublishedReleaseBundleDto selectorBundle(
WorldPublishedStartLocationEvidence selector,
List participants) {
@@ -1029,6 +1085,32 @@ private PublishedReleaseBundleDto selectorBundle(
selector);
}
+ private PublishedReleaseBundleDto selectedFullBundle(
+ WorldPublishedStartLocationEvidence selector,
+ List participants) {
+ return new PublishedReleaseBundleDto(
+ bundle.id(),
+ bundle.tenantId(),
+ bundle.versionId(),
+ bundle.versionNumber(),
+ PublishedReleaseBundleContract.SELECTED_FULL_ATTESTATION_SCHEMA_VERSION,
+ selector.request().publishWorkflowId(),
+ bundle.manifestHash(),
+ bundle.requiredManifestAssetKeys(),
+ participants,
+ bundle.commandDefinitions(),
+ bundle.generationConfigRevision(),
+ bundle.scriptOnly(),
+ bundle.scriptPatchVersion(),
+ bundle.publishedAt(),
+ bundle.canonicalTenantId(),
+ bundle.canonicalVersionId(),
+ bundle.publishedReleaseBundleRef(),
+ bundle.manifestSchemaVersion(),
+ bundle.artifactDigests(),
+ selector);
+ }
+
private List selectorParticipants(
WorldPublishedStartLocationEvidence selector) {
return PublishedWorldSelectorFixtures.participants(VERSION_ID, selector).stream()
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java
index 1c54a243b1..e64e9f6b04 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java
@@ -5,11 +5,14 @@
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.time.LocalDateTime;
import java.util.List;
+import java.util.Optional;
+import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence;
import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient;
import net.firedevops.firemud.gamedesign.client.EntityManagementClient;
@@ -20,10 +23,16 @@
import net.firedevops.firemud.gamedesign.dto.VersionDto;
import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode;
import net.firedevops.firemud.gamedesign.model.VersionLifecycleState;
+import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt;
+import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository;
+import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationDigestReadService;
import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService;
+import net.firedevops.firemud.gamedesign.service.PublicationFailureClassifier;
import net.firedevops.firemud.gamedesign.service.PublishGateFailureException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@@ -34,6 +43,8 @@ class PublishGateServiceImplTest {
@Mock private EntityManagementClient entityManagementClient;
@Mock private GameLogicClient gameLogicClient;
@Mock private AutomationScriptingClient automationScriptingClient;
+ @Mock private SelectedDraftGameLogicReceiptRepository selectedGameLogicReceiptRepository;
+ @Mock private SelectedDraftPublicationDigestReadService selectedPublicationDigestReader;
private PublishGateServiceImpl service;
@@ -46,7 +57,10 @@ void setUp() {
worldManagementClient,
entityManagementClient,
gameLogicClient,
- automationScriptingClient);
+ automationScriptingClient,
+ selectedGameLogicReceiptRepository,
+ selectedPublicationDigestReader,
+ "test");
}
@Test
@@ -92,6 +106,10 @@ void collectFullVersionParticipantDigestsPassesWhenParticipantsConverge() {
assertEquals(5, digests.size());
assertEquals("WORLD_MANAGEMENT", digests.get(0).participantKey());
+ assertEquals(
+ AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema(
+ "WORLD_MANAGEMENT"),
+ digests.get(0).digestSchemaVersion());
assertDoesNotThrow(() -> service.assertGatePassed(version, digests));
PublicationDigestRequestBinding expectedBinding =
@@ -102,6 +120,162 @@ void collectFullVersionParticipantDigestsPassesWhenParticipantsConverge() {
assertBinding(captureVersionBinding(automationScriptingClient), expectedBinding);
}
+ @Test
+ void selectedFullVersionGateUsesCanonicalBindingAndExactReceiptForOwnerReads() {
+ VersionDto version = selectedVersion();
+ PublicationDigestRequestBinding binding = selectedBinding(version);
+ SelectedDraftGameLogicReceipt receipt =
+ org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class);
+ stubSelectedParticipantDigests(version, binding, receipt);
+
+ List digests =
+ service.collectSelectedFullVersionParticipantDigests(
+ version, binding, binding.derivedWorkflowIdentity());
+
+ assertEquals(5, digests.size());
+ assertDoesNotThrow(() -> service.assertSelectedGatePassed(version, digests));
+ assertEquals(2, digests.get(4).digestSchemaVersion());
+ assertEquals(6, digests.get(3).digestSchemaVersion());
+ assertEquals("b".repeat(64), digests.getFirst().contentDigest());
+ assertEquals("c".repeat(64), digests.get(4).contentDigest());
+ verify(selectedPublicationDigestReader).read("test", binding);
+ org.mockito.Mockito.verifyNoInteractions(worldManagementClient, controlPlaneDigestService);
+ assertBinding(captureVersionBinding(entityManagementClient), binding);
+ ArgumentCaptor gameLogicBinding =
+ ArgumentCaptor.forClass(PublicationDigestRequestBinding.class);
+ verify(gameLogicClient)
+ .getDraftDesignDigestForVersion(gameLogicBinding.capture(), same(receipt));
+ assertBinding(gameLogicBinding.getValue(), binding);
+ assertBinding(captureVersionBinding(automationScriptingClient), binding);
+
+ var publicationOrder =
+ org.mockito.Mockito.inOrder(selectedGameLogicReceiptRepository, gameLogicClient);
+ publicationOrder.verify(selectedGameLogicReceiptRepository).readForPublication(binding);
+ publicationOrder.verify(gameLogicClient).getDraftDesignDigestForVersion(binding, receipt);
+ verify(gameLogicClient, org.mockito.Mockito.never())
+ .getDraftDesignDigestForVersion(any(PublicationDigestRequestBinding.class));
+ }
+
+ @Test
+ void selectedFullGateRejectsEveryMixedParticipantProfile() {
+ var version = selectedVersion();
+ var binding = selectedBinding(version);
+ var receipt = org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class);
+ stubSelectedParticipantDigests(version, binding, receipt);
+ var participants =
+ service.collectSelectedFullVersionParticipantDigests(
+ version, binding, binding.derivedWorkflowIdentity());
+ for (int index = 0; index < participants.size(); index++) {
+ var mixed = new java.util.ArrayList<>(participants);
+ var participant = mixed.get(index);
+ mixed.set(
+ index,
+ new PublishParticipantDigestDto(
+ participant.participantKey(),
+ participant.scopeValue(),
+ participant.baseVersionId(),
+ participant.appliedCommitId(),
+ participant.contentDigest(),
+ participant.digestSchemaVersion() == 1 ? 2 : participant.digestSchemaVersion() - 1,
+ participant.abilitySchemaDigest(),
+ participant.errorCode(),
+ participant.errorMessage()));
+ assertThrows(
+ PublishGateFailureException.class,
+ () -> service.assertSelectedGatePassed(version, mixed),
+ "mixed profile for " + participant.participantKey());
+ }
+ }
+
+ @Test
+ void closureQualifiedSelectedGateRequiresWorldDigestSchemaFour() {
+ VersionDto version = selectedVersion();
+ PublicationDigestRequestBinding binding = selectedBinding(version);
+ SelectedDraftGameLogicReceipt receipt =
+ org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class);
+ stubSelectedParticipantDigests(version, binding, receipt);
+ when(selectedPublicationDigestReader.read("test", binding))
+ .thenReturn(
+ new SelectedDraftPublicationDigestReadService.ReadResult(
+ binding,
+ binding.requestDigest(),
+ new DesignControlPlaneDigestDto(
+ binding.tenantId(), "7", "selected-commit", "c".repeat(64), 2),
+ new PublishParticipantDigestDto(
+ "WORLD_MANAGEMENT", "7", "selected-commit", "b".repeat(64), 4, null, null)));
+
+ List digests =
+ service.collectSelectedFullVersionParticipantDigests(
+ version, binding, binding.derivedWorkflowIdentity());
+
+ assertEquals(4, digests.getFirst().digestSchemaVersion());
+ assertEquals(2, digests.getLast().digestSchemaVersion());
+ assertDoesNotThrow(() -> service.assertSelectedGatePassed(version, digests));
+ }
+
+ @Test
+ void selectedFullVersionGateKeepsMissingReceiptPendingAndNeverUsesLegacyRead() {
+ VersionDto version = selectedVersion();
+ PublicationDigestRequestBinding binding = selectedBinding(version);
+ when(selectedGameLogicReceiptRepository.readForPublication(binding))
+ .thenReturn(Optional.empty());
+ stubNonGameLogicParticipants(version, binding);
+
+ List digests =
+ service.collectSelectedFullVersionParticipantDigests(
+ version, binding, binding.derivedWorkflowIdentity());
+
+ assertEquals("PARTICIPANT_UNAVAILABLE", digests.get(2).errorCode());
+ PublishGateFailureException thrown =
+ assertThrows(
+ PublishGateFailureException.class,
+ () -> service.assertSelectedGatePassed(version, digests));
+ assertTrue(PublicationFailureClassifier.isRetryableParticipantDependencyFailure(thrown));
+ verify(gameLogicClient, org.mockito.Mockito.never())
+ .getDraftDesignDigestForVersion(any(PublicationDigestRequestBinding.class));
+ verify(gameLogicClient, org.mockito.Mockito.never())
+ .getDraftDesignDigestForVersion(
+ any(PublicationDigestRequestBinding.class), any(SelectedDraftGameLogicReceipt.class));
+ }
+
+ @Test
+ void selectedReceiptStorageInterruptionRemainsRetryable() {
+ VersionDto version = selectedVersion();
+ PublicationDigestRequestBinding binding = selectedBinding(version);
+ when(selectedGameLogicReceiptRepository.readForPublication(binding))
+ .thenThrow(new org.jooq.exception.DataAccessException("database unavailable"));
+ stubNonGameLogicParticipants(version, binding);
+
+ List digests =
+ service.collectSelectedFullVersionParticipantDigests(
+ version, binding, binding.derivedWorkflowIdentity());
+
+ assertEquals("UNAVAILABLE", digests.get(2).errorCode());
+ PublishGateFailureException thrown =
+ assertThrows(
+ PublishGateFailureException.class, () -> service.assertGatePassed(version, digests));
+ assertTrue(PublicationFailureClassifier.isRetryableParticipantDependencyFailure(thrown));
+ }
+
+ @Test
+ void selectedFullVersionGateRejectsPrivateTenantKeyAsPublicationIdentity() {
+ VersionDto version = selectedVersion();
+ PublicationDigestRequestBinding privateTenantBinding =
+ PublicationDigestRequestBinding.full("private-tenant-key", "7", "selected-request-1");
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ service.collectSelectedFullVersionParticipantDigests(
+ version, privateTenantBinding, privateTenantBinding.derivedWorkflowIdentity()));
+ org.mockito.Mockito.verifyNoInteractions(
+ worldManagementClient,
+ entityManagementClient,
+ gameLogicClient,
+ automationScriptingClient,
+ selectedGameLogicReceiptRepository);
+ }
+
@Test
void fullVersionGateRejectsUnavailableGameLogicManifest() {
VersionDto version =
@@ -139,8 +313,9 @@ void fullVersionGateRejectsUnavailableGameLogicManifest() {
assertTrue(thrown.getMessage().contains("GAME_LOGIC"));
}
- @Test
- void fullVersionGateRejectsObsoleteWorldDigestSchema() {
+ @ParameterizedTest
+ @ValueSource(ints = {2, 4})
+ void fullVersionGateRejectsObsoleteAndUnknownWorldSchemas(int worldSchema) {
VersionDto version =
new VersionDto(
7L,
@@ -157,13 +332,13 @@ void fullVersionGateRejectsObsoleteWorldDigestSchema() {
List digests =
List.of(
new PublishParticipantDigestDto(
- "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null),
+ "WORLD_MANAGEMENT", "7", "version:7", "digest-world", worldSchema, null, null),
new PublishParticipantDigestDto(
"ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null),
new PublishParticipantDigestDto(
"GAME_LOGIC", "7", "version:7", "digest-logic", 1, null, null),
new PublishParticipantDigestDto(
- "AUTOMATION_SCRIPTING", "7", "version:7", "digest-script", 4, null, null),
+ "AUTOMATION_SCRIPTING", "7", "version:7", "digest-script", 5, null, null),
new PublishParticipantDigestDto(
"GAME_DESIGN_CONTROL_PLANE", "7", "version:7", "digest-design", 1, null, null));
@@ -456,6 +631,232 @@ void scriptPatchGatePassesWhenParticipantsConverge() {
PublicationDigestRequestBinding.patch("tenant-1", "7", "patch-1", "publish-request-1"));
}
+ @Test
+ void unavailableSelectedReaderFailsBothOwnersWithoutLegacyFallback() {
+ VersionDto version = selectedVersion();
+ var binding = selectedBinding(version);
+ var receipt = org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class);
+ stubSelectedParticipantDigests(version, binding, receipt);
+ when(selectedPublicationDigestReader.read("test", binding))
+ .thenThrow(io.grpc.Status.UNAVAILABLE.asRuntimeException());
+
+ var digests =
+ service.collectSelectedFullVersionParticipantDigests(
+ version, binding, binding.derivedWorkflowIdentity());
+
+ assertEquals(5, digests.size());
+ assertEquals("UNAVAILABLE", digests.getFirst().errorCode());
+ assertEquals("UNAVAILABLE", digests.get(4).errorCode());
+ assertThrows(
+ PublishGateFailureException.class,
+ () -> service.assertSelectedGatePassed(version, digests));
+ org.mockito.Mockito.verifyNoInteractions(worldManagementClient, controlPlaneDigestService);
+ verify(gameLogicClient).getDraftDesignDigestForVersion(binding, receipt);
+ }
+
+ @Test
+ void missingSelectedReaderFailsClosed() {
+ VersionDto version = selectedVersion();
+ var binding = selectedBinding(version);
+ service =
+ new PublishGateServiceImpl(
+ controlPlaneDigestService,
+ worldManagementClient,
+ entityManagementClient,
+ gameLogicClient,
+ automationScriptingClient,
+ selectedGameLogicReceiptRepository);
+ when(selectedGameLogicReceiptRepository.readForPublication(binding))
+ .thenReturn(Optional.empty());
+ when(entityManagementClient.getDraftDesignDigestForVersion(binding))
+ .thenReturn(
+ new PublishParticipantDigestDto(
+ "ENTITY_MANAGEMENT",
+ "7",
+ null,
+ null,
+ null,
+ "UNSUPPORTED_SCOPE",
+ "selected Entity evidence unavailable"));
+ when(automationScriptingClient.getDraftDesignDigestForVersion(binding))
+ .thenReturn(
+ new PublishParticipantDigestDto(
+ "AUTOMATION_SCRIPTING",
+ "7",
+ null,
+ null,
+ null,
+ "UNSUPPORTED_SCOPE",
+ "selected Automation evidence unavailable"));
+
+ var digests =
+ service.collectSelectedFullVersionParticipantDigests(
+ version, binding, binding.derivedWorkflowIdentity());
+
+ assertEquals(5, digests.size());
+ assertEquals("PARTICIPANT_UNAVAILABLE", digests.getFirst().errorCode());
+ assertEquals("PARTICIPANT_UNAVAILABLE", digests.get(4).errorCode());
+ assertThrows(
+ PublishGateFailureException.class,
+ () -> service.assertSelectedGatePassed(version, digests));
+ org.mockito.Mockito.verifyNoInteractions(worldManagementClient, controlPlaneDigestService);
+ }
+
+ @Test
+ void selectedSnapshotForAnotherRequestCannotSatisfyEitherOwner() {
+ VersionDto version = selectedVersion();
+ var binding = selectedBinding(version);
+ var other = PublicationDigestRequestBinding.full(binding.tenantId(), "7", "other-request");
+ when(selectedPublicationDigestReader.read("test", binding)).thenReturn(selectedSnapshot(other));
+ when(selectedGameLogicReceiptRepository.readForPublication(binding))
+ .thenReturn(Optional.empty());
+
+ var digests =
+ service.collectSelectedFullVersionParticipantDigests(
+ version, binding, binding.derivedWorkflowIdentity());
+
+ assertEquals("FAILED_PRECONDITION", digests.getFirst().errorCode());
+ assertEquals("FAILED_PRECONDITION", digests.get(4).errorCode());
+ org.mockito.Mockito.verifyNoInteractions(worldManagementClient, controlPlaneDigestService);
+ }
+
+ @Test
+ void selectedGateRequiresSchemaTwoAndPreservesUnsupportedOwnerDenial() {
+ VersionDto version = selectedVersion();
+ var binding = selectedBinding(version);
+ var receipt = org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class);
+ stubSelectedParticipantDigests(version, binding, receipt);
+ var digests =
+ new java.util.ArrayList<>(
+ service.collectSelectedFullVersionParticipantDigests(
+ version, binding, binding.derivedWorkflowIdentity()));
+ var selected = digests.get(4);
+ digests.set(
+ 4,
+ new PublishParticipantDigestDto(
+ selected.participantKey(),
+ selected.scopeValue(),
+ selected.appliedCommitId(),
+ selected.contentDigest(),
+ 1,
+ null,
+ null));
+ var unsupported =
+ assertThrows(
+ PublishGateFailureException.class,
+ () -> service.assertSelectedGatePassed(version, digests));
+ assertEquals(PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA, unsupported.failureCode());
+ assertTrue(unsupported.getMessage().contains("GAME_DESIGN_CONTROL_PLANE"));
+
+ when(entityManagementClient.getDraftDesignDigestForVersion(binding))
+ .thenReturn(
+ new PublishParticipantDigestDto(
+ "ENTITY_MANAGEMENT",
+ "7",
+ null,
+ null,
+ null,
+ "UNSUPPORTED_SCOPE",
+ "selected owner evidence unavailable"));
+ var denied =
+ service.collectSelectedFullVersionParticipantDigests(
+ version, binding, binding.derivedWorkflowIdentity());
+ assertEquals(5, denied.size());
+ var failure =
+ assertThrows(
+ PublishGateFailureException.class,
+ () -> service.assertSelectedGatePassed(version, denied));
+ assertEquals(PublishGateFailureCode.PARTICIPANT_UNAVAILABLE, failure.failureCode());
+ assertEquals("UNSUPPORTED_SCOPE", failure.participantFailureCode());
+
+ when(entityManagementClient.getDraftDesignDigestForVersion(binding))
+ .thenReturn(
+ new PublishParticipantDigestDto(
+ "ENTITY_MANAGEMENT", "7", "selected-commit", "entity-digest", 3, null, null));
+ when(automationScriptingClient.getDraftDesignDigestForVersion(binding))
+ .thenReturn(
+ new PublishParticipantDigestDto(
+ "AUTOMATION_SCRIPTING",
+ "7",
+ null,
+ null,
+ null,
+ "UNSUPPORTED_SCOPE",
+ "selected Automation evidence unavailable"));
+ var automationDenied =
+ service.collectSelectedFullVersionParticipantDigests(
+ version, binding, binding.derivedWorkflowIdentity());
+ var automationFailure =
+ assertThrows(
+ PublishGateFailureException.class,
+ () -> service.assertSelectedGatePassed(version, automationDenied));
+ assertEquals("UNSUPPORTED_SCOPE", automationFailure.participantFailureCode());
+ }
+
+ private void stubSelectedParticipantDigests(
+ VersionDto version,
+ PublicationDigestRequestBinding binding,
+ SelectedDraftGameLogicReceipt receipt) {
+ stubNonGameLogicParticipants(version, binding);
+ when(selectedGameLogicReceiptRepository.readForPublication(binding))
+ .thenReturn(Optional.of(receipt));
+ when(gameLogicClient.getDraftDesignDigestForVersion(binding, receipt))
+ .thenReturn(
+ new PublishParticipantDigestDto(
+ "GAME_LOGIC", "7", "selected-commit", "logic-digest", 1, null, null));
+ }
+
+ private void stubNonGameLogicParticipants(
+ VersionDto version, PublicationDigestRequestBinding binding) {
+ when(selectedPublicationDigestReader.read("test", binding))
+ .thenReturn(selectedSnapshot(binding));
+ when(entityManagementClient.getDraftDesignDigestForVersion(binding))
+ .thenReturn(
+ new PublishParticipantDigestDto(
+ "ENTITY_MANAGEMENT", "7", "selected-commit", "entity-digest", 3, null, null));
+ when(automationScriptingClient.getDraftDesignDigestForVersion(binding))
+ .thenReturn(
+ new PublishParticipantDigestDto(
+ "AUTOMATION_SCRIPTING",
+ "7",
+ "selected-commit",
+ "automation-digest",
+ 6,
+ null,
+ null));
+ }
+
+ private static SelectedDraftPublicationDigestReadService.ReadResult selectedSnapshot(
+ PublicationDigestRequestBinding binding) {
+ return new SelectedDraftPublicationDigestReadService.ReadResult(
+ binding,
+ binding.requestDigest(),
+ new DesignControlPlaneDigestDto(
+ binding.tenantId(), "7", "selected-commit", "c".repeat(64), 2),
+ new PublishParticipantDigestDto(
+ "WORLD_MANAGEMENT", "7", "selected-commit", "b".repeat(64), 4, null, null));
+ }
+
+ private static VersionDto selectedVersion() {
+ return new VersionDto(
+ 7L,
+ "private-tenant-key",
+ 8,
+ VersionLifecycleState.DRAFT,
+ 2L,
+ null,
+ null,
+ false,
+ "selected notes",
+ LocalDateTime.now(),
+ LocalDateTime.now());
+ }
+
+ private static PublicationDigestRequestBinding selectedBinding(VersionDto version) {
+ return PublicationDigestRequestBinding.full(
+ "11111111-1111-4111-8111-111111111111", String.valueOf(version.id()), "selected-request-1");
+ }
+
private static PublicationDigestRequestBinding captureVersionBinding(
WorldManagementClient client) {
ArgumentCaptor captor =
@@ -531,7 +932,7 @@ void scriptPatchGateFailsClosedForWrongParticipantSet() {
7L,
"script-patch:patch-1",
"digest-world",
- 2,
+ 3,
null,
null));
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java
index 4b656d76aa..a05b606e34 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java
@@ -37,6 +37,48 @@ void exactRepairAcceptsCompleteSelectorV2Bundle() throws Exception {
selectorBundle(selector, selectorParticipants(selector)), exportedManifest));
}
+ @Test
+ void exactRepairAcceptsFull4VectorAndRejectsLegacyParticipantSchemas() throws Exception {
+ var selector = selectorEvidence(4);
+ var participants =
+ PublishedWorldSelectorFixtures.participants(
+ VERSION_ID,
+ selector,
+ AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
+ var full = bundle("v4", selector, participants);
+ assertDoesNotThrow(
+ () -> PublishedReleaseBundleContract.requireExactRepairMatch(full, exportedManifest));
+
+ var legacyAutomation = participants.get(3);
+ var mixed =
+ replaceParticipant(
+ participants,
+ 3,
+ new PublishParticipantDigestDto(
+ legacyAutomation.participantKey(),
+ legacyAutomation.scopeValue(),
+ legacyAutomation.baseVersionId(),
+ legacyAutomation.appliedCommitId(),
+ legacyAutomation.contentDigest(),
+ 5,
+ legacyAutomation.abilitySchemaDigest(),
+ legacyAutomation.errorCode(),
+ legacyAutomation.errorMessage()));
+ assertSelectorRepairRejected(
+ bundle("v4", selector, mixed),
+ "Selected-full release requires all exact successful ordered release participants");
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ PublishedReleaseBundleContract.requireFreshSelectedFullParticipantVector(
+ VERSION_ID,
+ selector.request().appliedCommitId(),
+ PublishedWorldSelectorFixtures.participants(
+ VERSION_ID,
+ selector,
+ AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION)));
+ }
+
@Test
void exactRepairRejectsMalformedSelectorV2Binding() throws Exception {
WorldPublishedStartLocationEvidence selector = selectorEvidence();
@@ -294,6 +336,32 @@ private static WorldPublishedStartLocationEvidence selectorEvidence() throws Exc
"NEW_GAME_ROW"));
}
+ private static WorldPublishedStartLocationEvidence selectorEvidence(int digestSchemaVersion)
+ throws Exception {
+ var base = selectorEvidence();
+ var original = base.request();
+ var request =
+ new WorldPublishedStartLocationEvidence.Request(
+ original.targetNamespace(),
+ original.canonicalTenantId(),
+ original.canonicalVersionId(),
+ original.intakeRequestId(),
+ original.publicationFence(),
+ original.publicationRequestId(),
+ original.requestDigest(),
+ original.versionStateEpoch(),
+ original.publishWorkflowId(),
+ original.appliedCommitId(),
+ original.contentDigest(),
+ digestSchemaVersion,
+ original.worldAffectedTuples());
+ return new WorldPublishedStartLocationEvidence(
+ request,
+ base.selectorReceiptBytes(),
+ base.originalAccountBindingBytes(),
+ base.appliedResultBytes());
+ }
+
private static List selectorParticipants(
WorldPublishedStartLocationEvidence selector) {
return PublishedWorldSelectorFixtures.participants(VERSION_ID, selector).stream()
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
index 20de82ffc8..c8e5b18710 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
@@ -43,12 +43,12 @@ class PublishedReleaseBundleServiceImplTest {
private PublishedReleaseBundleServiceImpl service;
@Test
- void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutResolvingDefaults()
+ void selectedFullV4PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutResolvingDefaults()
throws Exception {
var evidence = selectorEvidence();
var participants =
PublishedWorldSelectorFixtures.participants(
- 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION);
+ 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
// ISOLATED source-repository response; this test covers service assembly only.
when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any()))
.thenReturn(List.of(validCommandDefinition()));
@@ -70,7 +70,7 @@ void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutRe
"genrev-1",
participants,
evidence);
- assertEquals("v2", first.attestationSchemaVersion());
+ assertEquals("v4", first.attestationSchemaVersion());
assertThat(first.worldPublishedStartLocationEvidence().canonicalBytes())
.containsExactly(evidence.canonicalBytes());
assertThat(first.commandDefinitions()).containsExactly(validCommandDefinition());
@@ -113,12 +113,59 @@ void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutRe
}
@Test
- void selectorV2RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorldDigest()
+ void exactRetainedV2RetryStillReturnsItsOriginalSelectorWithoutWriting() throws Exception {
+ var evidence = selectorEvidence(3);
+ var participants =
+ PublishedWorldSelectorFixtures.participants(
+ 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
+ var retained = new PublishedReleaseBundle();
+ retained.setId(11L);
+ retained.setPublishedReleaseBundleRef("retained-v2-release");
+ retained.setTenantId("tenant-1");
+ retained.setVersionId(7L);
+ retained.setCanonicalTenantId(sourceIdentity().getCanonicalTenantId());
+ retained.setCanonicalVersionId(sourceIdentity().getCanonicalVersionId());
+ retained.setVersionNumber(selectorVersion().versionNumber());
+ retained.setAttestationSchemaVersion("v2");
+ retained.setPublishWorkflowId("publish-workflow");
+ retained.setManifestHash(MANIFEST_HASH);
+ retained.setManifestSchemaVersion(1);
+ retained.setArtifactDigestsJson("[]");
+ retained.setGenerationConfigRevision("genrev-1");
+ retained.setRequiredManifestAssetKeysJson("[]");
+ retained.setParticipantDigestsJson(new ObjectMapper().writeValueAsString(participants));
+ retained.setCommandDefinitionsJson(
+ new ObjectMapper().writeValueAsString(List.of(validCommandDefinition())));
+ retained.setWorldPublishedStartLocationEvidenceJson(
+ new String(evidence.canonicalBytes(), StandardCharsets.UTF_8));
+ when(repository.findByTenantIdAndVersionId("tenant-1", 7L))
+ .thenReturn(Optional.of(retained));
+ when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any()))
+ .thenReturn(List.of(validCommandDefinition()));
+
+ var retry =
+ service.createFullVersionBundle(
+ selectorVersion(),
+ "publish-workflow",
+ emptyManifest(),
+ "genrev-1",
+ participants,
+ evidence);
+
+ assertEquals("v2", retry.attestationSchemaVersion());
+ assertThat(retry.worldPublishedStartLocationEvidence().canonicalBytes())
+ .containsExactly(evidence.canonicalBytes());
+ org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any());
+ org.mockito.Mockito.verifyNoInteractions(versionRepository);
+ }
+
+ @Test
+ void selectedFullV4RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorldDigest()
throws Exception {
var evidence = selectorEvidence();
var participants =
PublishedWorldSelectorFixtures.participants(
- 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION);
+ 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
assertThatThrownBy(
() ->
service.createFullVersionBundle(
@@ -173,11 +220,23 @@ void selectorV2RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorl
changed,
evidence))
.isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ service.createFullVersionBundle(
+ selectorVersion(),
+ "publish-workflow",
+ emptyManifest(),
+ "genrev-1",
+ PublishedWorldSelectorFixtures.participants(
+ 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION),
+ evidence))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Selected-full");
org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any());
}
@Test
- void selectorV2RequiresSelectedSourceCaptureBeforeBundleWrite() throws Exception {
+ void selectedFullV4RequiresSelectedSourceCaptureBeforeBundleWrite() throws Exception {
var evidence = selectorEvidence();
when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any()))
.thenThrow(new IllegalStateException("SELECTED_SOURCE_CAPTURE_UNAVAILABLE"));
@@ -192,7 +251,7 @@ void selectorV2RequiresSelectedSourceCaptureBeforeBundleWrite() throws Exception
PublishedWorldSelectorFixtures.participants(
7L,
evidence,
- AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION),
+ AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION),
evidence))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("SELECTED_SOURCE_CAPTURE_UNAVAILABLE");
@@ -220,7 +279,7 @@ void historicalReleaseNeverGainsSelectorAndCorruptedStoredCarrierFailsReadback()
PublishedWorldSelectorFixtures.participants(
7L,
evidence,
- AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION),
+ AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION),
evidence))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("selector-ineligible");
@@ -235,7 +294,13 @@ void historicalReleaseNeverGainsSelectorAndCorruptedStoredCarrierFailsReadback()
}
private WorldPublishedStartLocationEvidence selectorEvidence() throws Exception {
- return PublishedWorldSelectorFixtures.evidence(
+ return selectorEvidence(4);
+ }
+
+ private WorldPublishedStartLocationEvidence selectorEvidence(int digestSchemaVersion)
+ throws Exception {
+ var base =
+ PublishedWorldSelectorFixtures.evidence(
new TargetProof(
sourceIdentity().getCanonicalTenantId(),
sourceIdentity().getCanonicalVersionId(),
@@ -244,6 +309,27 @@ private WorldPublishedStartLocationEvidence selectorEvidence() throws Exception
42L,
"tenant-1",
"NEW_GAME_ROW"));
+ var original = base.request();
+ var request =
+ new WorldPublishedStartLocationEvidence.Request(
+ original.targetNamespace(),
+ original.canonicalTenantId(),
+ original.canonicalVersionId(),
+ original.intakeRequestId(),
+ original.publicationFence(),
+ original.publicationRequestId(),
+ original.requestDigest(),
+ original.versionStateEpoch(),
+ original.publishWorkflowId(),
+ original.appliedCommitId(),
+ original.contentDigest(),
+ digestSchemaVersion,
+ original.worldAffectedTuples());
+ return new WorldPublishedStartLocationEvidence(
+ request,
+ base.selectorReceiptBytes(),
+ base.originalAccountBindingBytes(),
+ base.appliedResultBytes());
}
private VersionDto selectorVersion() {
@@ -406,7 +492,7 @@ void selectedBundleEntryPointRequiresCapturedCommandAndPolicySources() throws Ex
var evidence = selectorEvidence();
var participants =
PublishedWorldSelectorFixtures.participants(
- 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION);
+ 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty());
when(versionRepository.findByTenantIdAndId("tenant-1", 7L))
.thenReturn(Optional.of(sourceIdentity()));
@@ -447,7 +533,7 @@ void selectedFullVersionBundlePersistsImmutableAttestation() throws Exception {
var evidence = selectorEvidence();
var participants =
PublishedWorldSelectorFixtures.participants(
- 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION);
+ 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any()))
.thenReturn(List.of(validCommandDefinition()));
when(repository.save(any(PublishedReleaseBundle.class)))
@@ -479,7 +565,7 @@ void selectedFullVersionBundlePersistsImmutableAttestation() throws Exception {
assertEquals(List.of("logo.png"), dto.requiredManifestAssetKeys());
assertEquals(participants, dto.participantDigests());
assertEquals(List.of(validCommandDefinition()), dto.commandDefinitions());
- assertEquals("v2", dto.attestationSchemaVersion());
+ assertEquals("v4", dto.attestationSchemaVersion());
assertEquals("owner-issued-reference-11", dto.publishedReleaseBundleRef());
assertEquals(sourceIdentity().getCanonicalTenantId(), dto.canonicalTenantId());
assertEquals(sourceIdentity().getCanonicalVersionId(), dto.canonicalVersionId());
@@ -531,7 +617,7 @@ private void assertSelectedCommandsRejected(
emptyManifest(),
"genrev-1",
PublishedWorldSelectorFixtures.participants(
- 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION),
+ 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION),
evidence));
org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any());
}
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java
index c580adb9a5..cad1e4f037 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java
@@ -65,6 +65,7 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.junit.jupiter.params.provider.EnumSource;
import org.mapstruct.factory.Mappers;
import org.mockito.InOrder;
@@ -247,6 +248,8 @@ void legacyPendingAttemptIsDeniedBeforeReadbackOrMutation() {
assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus());
verify(publishAttemptRepository, never()).save(any(PublishAttempt.class));
verify(authoredSelections, never()).reserve(any(PublishIntent.class));
+ verify(publishGateService, never()).collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class));
verify(publishGateService, never())
.collectFullVersionParticipantDigests(
any(VersionDto.class), any(String.class), any(String.class));
@@ -814,8 +817,8 @@ void bundleFailureAfterExternalExportRemainsPendingWithoutDeletingSharedAssets()
when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, request.publishWorkflowId()))
.thenReturn(staged);
when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest);
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(participantDigests());
when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class)))
.thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest", 1));
@@ -858,8 +861,8 @@ void bundleFailureAfterExternalExportRemainsPendingWithoutDeletingSharedAssets()
names = {"UNAVAILABLE", "DEADLINE_EXCEEDED"})
void transientParticipantReadLeavesSelectedFullAttemptPending(Status.Code statusCode) {
SelectedPublishFixture fixture = selectedPublishFixture(1);
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenThrow(new StatusRuntimeException(Status.fromCode(statusCode)));
VersionPublishCommandServiceImpl.PendingReconciliationException thrown =
@@ -887,8 +890,8 @@ void uncertainAssetExportRemainsPendingForExactRetry() {
.thenReturn(Optional.empty(), Optional.of(staged));
when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, request.publishWorkflowId()))
.thenReturn(staged);
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(participantDigests());
when(assetExportService.exportAssets("tenant-1", 1))
.thenThrow(new AssetExportOutcomePendingException("exact object readback is unavailable"));
@@ -911,8 +914,8 @@ void uncertainAssetExportRemainsPendingForExactRetry() {
void uncertainAssetStagingRemainsPendingBeforeAnyExternalExportOrFinalization() {
SelectedPublishFixture fixture = selectedPublishFixture(1);
PublishWorkflowRequest request = fixture.request();
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(participantDigests());
when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, request.publishWorkflowId()))
.thenThrow(new IllegalStateException("stage commit outcome is unknown"));
@@ -1089,8 +1092,8 @@ void selectedStagedArtifactWithExactPersistedCandidateRetriesWithoutTreatingItAs
when(versionAssetArtifactService.findState("tenant-1", 10L))
.thenReturn(Optional.of(stagedCandidate));
when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)).thenReturn(candidate);
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(participantDigests());
when(assetExportService.exportAssets("tenant-1", 1))
.thenThrow(new AssetExportOutcomePendingException("exact export readback is unavailable"));
@@ -1193,8 +1196,8 @@ void selectedStagedCandidateRetryAttestsTheExactFullManifestBeforeSuccess() {
.thenReturn(Optional.of(stagedCandidate));
when(versionAssetArtifactService.getExportCandidate("tenant-1", version.getId()))
.thenReturn(candidate);
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(participantDigests);
when(assetExportService.exportAssets("tenant-1", version.getVersionNumber()))
.thenReturn(candidate);
@@ -1508,8 +1511,8 @@ void postBundleFailureAfterRollbackLeavesAttemptPendingWithoutCleaningAssets() {
Optional.empty(), Optional.of(staged), Optional.of(staged), Optional.of(exportedState));
when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId))
.thenReturn(staged);
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(participantDigests);
when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest);
when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class)))
@@ -1581,8 +1584,8 @@ void finalizationFailureWithFailedReadbackLeavesAttemptPending() {
IllegalStateException operationFailure =
new IllegalStateException("version finalization failed");
IllegalStateException readFailure = new IllegalStateException("publication read failed");
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(participantDigests());
when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest);
when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L))
@@ -1621,8 +1624,8 @@ void ambiguousFinalizationLeavesPendingAttemptAndDoesNotCleanAssets() {
when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId))
.thenReturn(staged);
ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json"));
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(participantDigests());
when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest);
when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L))
@@ -1656,8 +1659,8 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() {
ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json"));
IllegalStateException ambiguousCommit = new IllegalStateException("commit outcome unknown");
IllegalStateException readFailure = new IllegalStateException("publication read failed");
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(participantDigests());
when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest);
when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L))
@@ -1688,15 +1691,15 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() {
void preExportFailureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() {
SelectedPublishFixture fixture = selectedPublishFixture(1);
PublishWorkflowRequest request = fixture.request();
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(participantDigests());
org.mockito.Mockito.doThrow(
new PublishGateFailureException(
PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH,
"recorded digest mismatch"))
.when(publishGateService)
- .assertGatePassed(any(VersionDto.class), any(List.class));
+ .assertSelectedGatePassed(any(VersionDto.class), any(List.class));
org.mockito.Mockito.doAnswer(
invocation -> {
((java.util.function.Supplier>) invocation.getArgument(0)).get();
@@ -1730,15 +1733,15 @@ void failureMarkingReadbackFailureKeepsPendingContractAndOriginalFailure() {
PublishWorkflowRequest request = fixture.request();
IllegalStateException operationFailure = new IllegalStateException("failure mark uncertain");
IllegalStateException readFailure = new IllegalStateException("publication read failed");
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(participantDigests());
org.mockito.Mockito.doThrow(
new PublishGateFailureException(
PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH,
"recorded digest mismatch"))
.when(publishGateService)
- .assertGatePassed(any(VersionDto.class), any(List.class));
+ .assertSelectedGatePassed(any(VersionDto.class), any(List.class));
when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L))
.thenReturn(Optional.empty())
.thenThrow(readFailure);
@@ -1795,6 +1798,8 @@ void freshFullVersionPublishIsDeniedBeforeAnyMutation() {
verify(publishAttemptService, never()).executeFullVersionTransaction(any());
verify(publishAttemptService, never())
.createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class));
+ verify(publishGateService, never()).collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class));
verify(publishGateService, never())
.collectFullVersionParticipantDigests(
any(VersionDto.class), any(String.class), any(String.class));
@@ -1843,8 +1848,8 @@ void privateMechanicsUsesDurablySelectedVersionWithoutSequenceReservation() {
when(versionAssetArtifactService.stageExport("tenant-1", 10L, 8, request.publishWorkflowId()))
.thenReturn(staged);
when(assetExportService.exportAssets("tenant-1", 8)).thenReturn(exportedManifest);
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(participantDigests);
when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class)))
.thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest-1", 1));
@@ -1913,6 +1918,22 @@ void privateMechanicsUsesDurablySelectedVersionWithoutSequenceReservation() {
reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request);
assertEquals("SUCCEEDED", snapshot.status());
+ var selectedBinding = org.mockito.ArgumentCaptor.forClass(PublicationDigestRequestBinding.class);
+ verify(publishGateService).collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), selectedBinding.capture(),
+ org.mockito.ArgumentMatchers.eq(request.publishWorkflowId()));
+ var expectedBinding = PublicationDigestRequestBinding.full(
+ fixture.reservation().selection().intent().canonicalTenantId().toString(),
+ version.getId().toString(), request.publishRequestId());
+ assertEquals(expectedBinding.tenantId(), selectedBinding.getValue().tenantId());
+ assertEquals(expectedBinding.versionId(), selectedBinding.getValue().versionId());
+ assertEquals(expectedBinding.scopeKind(), selectedBinding.getValue().scopeKind());
+ assertEquals(expectedBinding.requestDigest(), selectedBinding.getValue().requestDigest());
+ assertEquals(request.publishWorkflowId(), selectedBinding.getValue().derivedWorkflowIdentity());
+ verify(publishGateService, never()).collectFullVersionParticipantDigests(
+ any(VersionDto.class), any(String.class), any(String.class));
+ verify(publishGateService, never()).assertGatePassed(any(VersionDto.class), any(List.class));
+
assertEquals(10L, snapshot.versionId());
assertEquals(VersionLifecycleState.PUBLISHED, version.getVersionState());
assertEquals(2L, version.getVersionStateEpoch());
@@ -1962,7 +1983,7 @@ void privateMechanicsUsesDurablySelectedVersionWithoutSequenceReservation() {
publishAttemptRepository);
publishOrder
.verify(publishGateService)
- .assertGatePassed(
+ .assertSelectedGatePassed(
any(VersionDto.class), org.mockito.ArgumentMatchers.eq(participantDigests));
publishOrder
.verify(recordedParticipantDigestService)
@@ -1994,8 +2015,8 @@ void privateMechanicsUsesDurablySelectedVersionWithoutSequenceReservation() {
@Test
void privateMechanicsRecordsTypedPublishGateFailures() {
SelectedPublishFixture fixture = selectedPublishFixture(1);
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(participantDigests());
org.mockito.Mockito.doThrow(
new PublishGateFailureException(
@@ -2031,14 +2052,14 @@ void privateMechanicsRecordsTypedPublishGateFailures() {
void privateMechanicsGateRejectionDoesNotRecordDigestsOrExportAssets() {
SelectedPublishFixture fixture = selectedPublishFixture(1);
List participantDigests = participantDigests();
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(participantDigests);
org.mockito.Mockito.doThrow(
new PublishGateFailureException(
PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, "gate rejected"))
.when(publishGateService)
- .assertGatePassed(any(VersionDto.class), any(List.class));
+ .assertSelectedGatePassed(any(VersionDto.class), any(List.class));
PublishWorkflowSnapshot snapshot =
reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request());
@@ -2060,6 +2081,68 @@ void privateMechanicsGateRejectionDoesNotRecordDigestsOrExportAssets() {
.NO_PUBLICATION);
}
+ @Test
+ void freshSelectedPublishRejectsLegacyOwnerVectorBeforeGateOrAssetEffects() throws Exception {
+ SelectedPublishFixture fixture = selectedPublishFixture(1);
+ var fullVector = participantDigests();
+ var legacySchemas = List.of(3, 2, 1, 5, 2);
+ List legacyVector =
+ java.util.stream.IntStream.range(0, fullVector.size())
+ .mapToObj(
+ index -> {
+ var participant = fullVector.get(index);
+ return new PublishParticipantDigestDto(
+ participant.participantKey(),
+ participant.scopeValue(),
+ participant.baseVersionId(),
+ participant.appliedCommitId(),
+ participant.contentDigest(),
+ legacySchemas.get(index),
+ participant.abilitySchemaDigest(),
+ participant.errorCode(),
+ participant.errorMessage());
+ })
+ .toList();
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
+ .thenReturn(legacyVector);
+
+ PublishWorkflowSnapshot snapshot =
+ reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request());
+
+ assertEquals("FAILED", snapshot.status());
+ verify(publishGateService, never()).assertSelectedGatePassed(any(VersionDto.class), any(List.class));
+ verify(versionAssetArtifactService, never())
+ .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class));
+ verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class));
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {0, 1, 2, 3, 4})
+ void freshSelectedPublishRefusesEachNoncanonicalParticipantSchemaBeforeEffects(int index)
+ throws Exception {
+ // These unit carriers are controlled; the actual contract validator must reject every downgrade.
+ SelectedPublishFixture fixture = selectedPublishFixture(1);
+ var vector = new java.util.ArrayList<>(participantDigests());
+ var original = vector.get(index);
+ vector.set(index, new PublishParticipantDigestDto(
+ original.participantKey(), original.scopeValue(), original.baseVersionId(),
+ original.appliedCommitId(), original.contentDigest(), original.digestSchemaVersion() + 1,
+ original.abilitySchemaDigest(), original.errorCode(), original.errorMessage()));
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
+ .thenReturn(vector);
+
+ var result = reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request());
+
+ assertEquals("FAILED", result.status());
+ verify(publishGateService, never()).assertSelectedGatePassed(any(VersionDto.class), any(List.class));
+ verify(publishGateService, never()).assertGatePassed(any(VersionDto.class), any(List.class));
+ verify(versionAssetArtifactService, never()).stageExport(
+ any(String.class), any(Long.class), any(Integer.class), any(String.class));
+ verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class));
+ }
+
@Test
void privateMechanicsPreservesSharedAssetsWhenAttestationWriteIsUncertain() {
SelectedPublishFixture fixture = selectedPublishFixture(1);
@@ -2090,8 +2173,8 @@ void privateMechanicsPreservesSharedAssetsWhenAttestationWriteIsUncertain() {
when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, request.publishWorkflowId()))
.thenReturn(staged);
when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest);
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(participantDigests());
org.mockito.Mockito.doThrow(new IllegalStateException("attestation write outcome is unknown"))
.when(versionAssetArtifactService)
@@ -2334,8 +2417,8 @@ void candidateRecordedBeforeConflictReadbackKeepsAttemptPendingForReconciliation
org.mockito.Mockito.doReturn(null, manifest)
.when(versionAssetArtifactService)
.getExportCandidate("tenant-1", 10L);
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(participantDigests());
org.mockito.Mockito.doAnswer(
ignored -> {
@@ -2419,8 +2502,8 @@ void postExportFinalizationFailureWithExactCandidateRemainsPendingWithoutCleanup
.thenReturn(null, manifest, manifest);
when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId))
.thenReturn(staged);
- when(publishGateService.collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class)))
+ when(publishGateService.collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(participantDigests);
when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest);
when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class)))
@@ -2852,13 +2935,32 @@ private Version fullVersion(long versionId, int versionNumber, VersionLifecycleS
}
private List participantDigests() {
+ String appliedCommitId = selectedIntent().selectedCommitId().toString();
return List.of(
new PublishParticipantDigestDto(
- "GAME_DESIGN_CONTROL_PLANE",
+ "WORLD_MANAGEMENT", "10", null, appliedCommitId, "a".repeat(64), 4, null, null, null),
+ new PublishParticipantDigestDto(
+ "ENTITY_MANAGEMENT", "10", null, appliedCommitId, "b".repeat(64), 3, null, null, null),
+ new PublishParticipantDigestDto(
+ "GAME_LOGIC",
"10",
- selectedIntent().selectedCommitId().toString(),
- "digest",
+ null,
+ appliedCommitId,
+ "c".repeat(64),
1,
+ "sha256:" + "d".repeat(64),
+ null,
+ null),
+ new PublishParticipantDigestDto(
+ "AUTOMATION_SCRIPTING", "10", null, appliedCommitId, "e".repeat(64), 6, null, null, null),
+ new PublishParticipantDigestDto(
+ "GAME_DESIGN_CONTROL_PLANE",
+ "10",
+ null,
+ appliedCommitId,
+ "f".repeat(64),
+ 2,
+ null,
null,
null));
}
diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/GameLogicDraftDesignDigestService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/GameLogicDraftDesignDigestService.java
index 45de4c801c..019db94ed1 100644
--- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/GameLogicDraftDesignDigestService.java
+++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/GameLogicDraftDesignDigestService.java
@@ -1,7 +1,11 @@
package net.firedevops.firemud.gamelogic.service;
+import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding;
+import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService;
+
public interface GameLogicDraftDesignDigestService {
- GameLogicDraftDesignDigest getDraftDesignDigest(String tenantId, String versionId);
+ GameLogicPublicationSourceReadService.Result getDraftDesignDigest(
+ GameLogicPublicationSourceReadBinding binding);
final class UnsupportedDigestScopeException extends RuntimeException {
private static final long serialVersionUID = 1L;
@@ -10,11 +14,4 @@ public UnsupportedDigestScopeException(String message) {
super(message);
}
}
-
- record GameLogicDraftDesignDigest(
- String tenantId,
- String scopeValue,
- String appliedCommitId,
- String contentDigest,
- int digestSchemaVersion) {}
}
diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImpl.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImpl.java
index c9e218a577..4c97c0a228 100644
--- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImpl.java
+++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImpl.java
@@ -1,17 +1,35 @@
package net.firedevops.firemud.gamelogic.service.impl;
+import java.util.Objects;
+import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding;
import net.firedevops.firemud.gamelogic.service.GameLogicDraftDesignDigestService;
+import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService;
import org.springframework.stereotype.Service;
@Service
-public class GameLogicDraftDesignDigestServiceImpl implements GameLogicDraftDesignDigestService {
+public final class GameLogicDraftDesignDigestServiceImpl
+ implements GameLogicDraftDesignDigestService {
+ private final GameLogicPublicationSourceReadService publicationSourceReadService;
+
+ /** Spring's default owner keeps this route denied until explicit composition provides storage. */
+ public GameLogicDraftDesignDigestServiceImpl() {
+ publicationSourceReadService = null;
+ }
+
+ /** Explicit composition for owner-local proofs and tests; this constructor is not auto-wired. */
+ public GameLogicDraftDesignDigestServiceImpl(
+ GameLogicPublicationSourceReadService publicationSourceReadService) {
+ this.publicationSourceReadService =
+ Objects.requireNonNull(publicationSourceReadService, "publicationSourceReadService");
+ }
@Override
- public GameLogicDraftDesignDigest getDraftDesignDigest(String tenantId, String versionId) {
- if (versionId == null || versionId.isBlank()) {
- throw new IllegalArgumentException("version_id is required");
+ public GameLogicPublicationSourceReadService.Result getDraftDesignDigest(
+ GameLogicPublicationSourceReadBinding binding) {
+ if (publicationSourceReadService == null) {
+ throw new UnsupportedDigestScopeException(
+ "Game Logic retained publication source reader is not configured");
}
- throw new UnsupportedDigestScopeException(
- "Game Logic owner-local manifest and provenance are unavailable");
+ return publicationSourceReadService.read(binding);
}
}
diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java
index fca017ad10..7569ea5a1d 100644
--- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java
+++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java
@@ -7,7 +7,7 @@
import io.micrometer.core.annotation.Timed;
import io.micrometer.core.instrument.MeterRegistry;
import net.firedevops.firemud.common.grpc.GrpcAppErrors;
-import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadGrpcCodec;
import net.firedevops.firemud.common.security.AdminAuthorizationException;
import net.firedevops.firemud.common.security.GameplaySessionAttestationException;
import net.firedevops.firemud.common.security.GameplaySessionAttestationService;
@@ -169,41 +169,10 @@ public void getDraftDesignDigest(
StreamObserver responseObserver) {
try {
requirePublicationRead();
- if (request.getScopeCase() != GetDraftDesignDigestRequest.ScopeCase.VERSION_ID) {
- responseObserver.onNext(
- GetDraftDesignDigestResponse.newBuilder()
- .setError(
- GrpcAppErrors.error(
- meterRegistry,
- logger,
- "GetDraftDesignDigest",
- "UNSUPPORTED_SCOPE",
- "game logic supports version_id scope only"))
- .build());
- responseObserver.onCompleted();
- return;
- }
- PublicationDigestRequestBinding binding =
- PublicationDigestRequestBinding.forScope(
- PublicationDigestRequestBinding.ScopeKind.FULL_VERSION,
- request.getTenantId(),
- request.getVersionId(),
- request.getBaseVersionId(),
- request.getScriptPatchVersion(),
- request.getPublishRequestId());
- binding.validateSupplied(request.getDerivedWorkflowIdentity(), request.getRequestDigest());
- var digest =
- gameLogicDraftDesignDigestService.getDraftDesignDigest(
- request.getTenantId(), request.getVersionId());
- binding.requireOwnerScope(digest.tenantId(), digest.scopeValue());
+ var binding = GameLogicPublicationSourceReadGrpcCodec.fromRequest(request);
+ var retainedRead = gameLogicDraftDesignDigestService.getDraftDesignDigest(binding);
responseObserver.onNext(
- GetDraftDesignDigestResponse.newBuilder()
- .setTenantId(binding.tenantId())
- .setVersionId(binding.versionId())
- .setAppliedCommitId(digest.appliedCommitId())
- .setContentDigest(digest.contentDigest())
- .setDigestSchemaVersion(digest.digestSchemaVersion())
- .build());
+ GameLogicPublicationSourceReadGrpcCodec.toResponse(binding, retainedRead.terminal()));
responseObserver.onCompleted();
} catch (AdminAuthorizationException ex) {
responseObserver.onNext(
@@ -241,6 +210,23 @@ public void getDraftDesignDigest(
ex.getMessage()))
.build());
responseObserver.onCompleted();
+ } catch (StatusRuntimeException ex) {
+ Status status = ex.getStatus();
+ String description =
+ status.getDescription() == null
+ ? "Exact retained publication source read was denied"
+ : status.getDescription();
+ responseObserver.onNext(
+ GetDraftDesignDigestResponse.newBuilder()
+ .setError(
+ GrpcAppErrors.error(
+ meterRegistry,
+ logger,
+ "GetDraftDesignDigest",
+ status.getCode().name(),
+ description))
+ .build());
+ responseObserver.onCompleted();
} catch (Exception ex) {
responseObserver.onNext(
GetDraftDesignDigestResponse.newBuilder()
diff --git a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java
new file mode 100644
index 0000000000..4992a3887d
--- /dev/null
+++ b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java
@@ -0,0 +1,275 @@
+package net.firedevops.firemud.gamelogic.sourceintake;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import io.grpc.Context;
+import io.grpc.stub.StreamObserver;
+import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicReference;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding;
+import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence;
+import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding;
+import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadGrpcCodec;
+import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest;
+import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource;
+import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import net.firedevops.firemud.common.security.PublicationReadGuard;
+import net.firedevops.firemud.common.security.SessionContext;
+import net.firedevops.firemud.gamelogic.service.impl.GameLogicDraftDesignDigestServiceImpl;
+import net.firedevops.firemud.gamelogic.service.impl.GameLogicGrpcService;
+import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestRequest;
+import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestResponse;
+import net.firedevops.firemud.test.TestContainerImages;
+import org.jooq.DSLContext;
+import org.jooq.SQLDialect;
+import org.jooq.impl.DSL;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.testcontainers.containers.PostgreSQLContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+/**
+ * Actual current-default GL retention, immutable owner read, digest service and receiver.
+ * Account authorization and GD source responses are explicitly controlled upstream inputs;
+ * direct handler invocation supplies controlled peer context, not authenticated socket/TLS proof.
+ * No production composition, genuine upstream authority or registration is established.
+ */
+@Testcontainers(disabledWithoutDocker = true)
+@SuppressWarnings("resource")
+class GameLogicPublicationDigestReadPostgresIntegrationTest {
+ private static final String NAMESPACE = "test";
+ @Container static final PostgreSQLContainer> POSTGRES =
+ new PostgreSQLContainer<>(TestContainerImages.postgres());
+
+ @AfterEach
+ void clearContext() {
+ SessionContext.clear();
+ TransactionSynchronizationManager.setActualTransactionActive(false);
+ if (TransactionSynchronizationManager.isSynchronizationActive())
+ TransactionSynchronizationManager.clearSynchronization();
+ }
+
+ @Test
+ void actualRetainedOwnerFlowsThroughDigestServiceAndReceiverWithExactReplayAndRefusals()
+ throws Exception {
+ var f = fixture();
+ var authorization = authorization();
+ var intake = new GameLogicGameplayRuleIntakeService(f.repository(), f.manager(),
+ request -> {
+ assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
+ return new GameLogicIntakeAuthorizationReadEvidence(request);
+ },
+ request -> {
+ assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
+ assertThat(request.proof()).isInstanceOf(GameplayRuleSourceReadEvidence.Finalized.class);
+ assertThat(request.proof().canonicalBytes()).isEqualTo(authorization.canonicalBytes());
+ return new GameplayRuleSourceReadEvidence(request, authorization.source());
+ }, NAMESPACE);
+ var terminal = asGameDesign(() -> intake.retain(authorization));
+ var reader = new GameLogicPublicationSourceReadService(f.repository(), NAMESPACE);
+ var digest = new GameLogicDraftDesignDigestServiceImpl(reader);
+ var receiver = receiver(digest);
+ var binding = publicationBinding(authorization);
+ var request = GameLogicPublicationSourceReadGrpcCodec.toRequest(binding);
+ String retained = row(f, authorization.operationId());
+
+ var response = asGameDesign(() -> invoke(receiver, request));
+ assertThat(response.hasError()).isFalse();
+ var evidence = GameLogicPublicationSourceReadGrpcCodec.fromResponse(binding, response, NAMESPACE);
+ assertThat(evidence.terminal().canonicalBytes()).isEqualTo(terminal.canonicalBytes());
+ assertThat(evidence.terminal().selectedSourceBytes()).isEqualTo(authorization.source().canonicalBytes());
+ assertThat(evidence.manifestDigest()).isEqualTo(authorization.source().manifest().digest());
+ assertThat(asGameDesign(() -> digest.getDraftDesignDigest(binding)).terminalBytes()).isEqualTo(terminal.canonicalBytes());
+ assertThat(asGameDesign(() -> invoke(receiver, request))).isEqualTo(response);
+
+ var missing = copyAuthorization(authorization, UUID.randomUUID(), authorization.fenceId(), authorization.intakeRequestId(), authorization.source());
+ assertError(receiver, GameLogicPublicationSourceReadGrpcCodec.toRequest(publicationBinding(missing)), "FAILED_PRECONDITION");
+ var changed = copyAuthorization(authorization, authorization.operationId(), UUID.randomUUID(), authorization.intakeRequestId(), authorization.source());
+ assertError(receiver, GameLogicPublicationSourceReadGrpcCodec.toRequest(publicationBinding(changed)), "ALREADY_EXISTS");
+ assertError(receiver, request.toBuilder().clearSourceReadBinding().clearSourceReadBindingDigest().build(), "INVALID_ARGUMENT");
+ assertError(receiver(new GameLogicDraftDesignDigestServiceImpl()), request, "UNSUPPORTED_SCOPE");
+
+ var wrongPeer = GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/world-management-service").orElseThrow();
+ var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, wrongPeer);
+ var previous = context.attach();
+ try { assertThat(invoke(receiver, request).getError().getCode()).isEqualTo("PERMISSION_DENIED"); }
+ finally { context.detach(previous); }
+ SessionContext.setContext("controlled-user", List.of(), Map.of());
+ assertError(receiver, request, "PERMISSION_DENIED");
+ SessionContext.clear();
+ TransactionSynchronizationManager.setActualTransactionActive(true);
+ try { assertError(receiver, request, "FAILED_PRECONDITION"); }
+ finally { TransactionSynchronizationManager.setActualTransactionActive(false); }
+ assertThat(row(f, authorization.operationId())).isEqualTo(retained);
+
+ var abortedAuthorization = authorization();
+ var abortOwner = new GameLogicGameplayRuleIntakeService(f.repository(), f.manager(),
+ ignored -> { throw new AssertionError("Abort must not read Account"); },
+ ignored -> { throw new AssertionError("Abort must not read GD source"); }, NAMESPACE);
+ asGameDesign(() -> abortOwner.abort(abortedAuthorization));
+ String aborted = row(f, abortedAuthorization.operationId());
+ assertError(receiver, GameLogicPublicationSourceReadGrpcCodec.toRequest(publicationBinding(abortedAuthorization)), "FAILED_PRECONDITION");
+ assertThat(row(f, abortedAuthorization.operationId())).isEqualTo(aborted);
+ assertThat(row(f, authorization.operationId())).isEqualTo(retained);
+ }
+
+ private static GameLogicGrpcService receiver(GameLogicDraftDesignDigestServiceImpl digest) {
+ // Unrelated gameplay owners are unused by this focused direct receiver composition.
+ return new GameLogicGrpcService(null, null, null, null, null, null, digest, null,
+ new SimpleMeterRegistry(), new PublicationReadGuard(NAMESPACE));
+ }
+
+ private static GetDraftDesignDigestResponse invoke(GameLogicGrpcService receiver,
+ GetDraftDesignDigestRequest request) {
+ var result = new AtomicReference();
+ receiver.getDraftDesignDigest(request, new StreamObserver<>() {
+ @Override public void onNext(GetDraftDesignDigestResponse value) { result.set(value); }
+ @Override public void onError(Throwable failure) { throw new AssertionError(failure); }
+ @Override public void onCompleted() {}
+ });
+ assertThat(result.get()).isNotNull();
+ return result.get();
+ }
+
+ private static void assertError(GameLogicGrpcService receiver, GetDraftDesignDigestRequest request,
+ String code) throws Exception {
+ var response = asGameDesign(() -> invoke(receiver, request));
+ assertThat(response.getError().getCode()).isEqualTo(code);
+ assertThat(response.getRetainedIntakeTerminal().isEmpty()).isTrue();
+ assertThat(response.getContentDigest()).isEmpty();
+ assertThat(response.getAbilitySchemaDigest()).isEmpty();
+ }
+
+ private static String row(Fixture f, UUID operation) {
+ return f.dsl().fetchSingle("SELECT row_to_json(t)::TEXT || ':' || t.xmin::TEXT FROM game_logic_gameplay_rule_intake_terminal t WHERE operation_id = ?", operation).get(0, String.class);
+ }
+
+ private static Fixture fixture() {
+ String schema = "gl_intake_" + UUID.randomUUID().toString().replace("-", "");
+ var dataSource = new DriverManagerDataSource();
+ dataSource.setUrl(POSTGRES.getJdbcUrl());
+ dataSource.setUsername(POSTGRES.getUsername());
+ dataSource.setPassword(POSTGRES.getPassword());
+ dataSource.setSchema(schema);
+ org.flywaydb.core.Flyway.configure()
+ .dataSource(dataSource)
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema))
+ .table("flyway_schema_history")
+ .locations("classpath:db/migration")
+ .load()
+ .migrate();
+ var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES);
+ var transactionManager = new DataSourceTransactionManager(dataSource);
+ return new Fixture(dsl, transactionManager, new GameLogicGameplayRuleIntakeRepository(dsl));
+ }
+
+ private static T asGameDesign(java.util.concurrent.Callable action) throws Exception {
+ var peer =
+ new GrpcPeerIdentity(
+ "spiffe://firemud/ns/test/sa/game-design-service", NAMESPACE, "game-design-service");
+ Context previous = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).attach();
+ try {
+ return action.call();
+ } finally {
+ Context.current().detach(previous);
+ }
+ }
+
+ private static GameLogicIntakeAuthorizationBinding authorization() {
+ var actor = UUID.randomUUID();
+ var target =
+ new DraftCommitBinding.TargetProof(
+ UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW");
+ var binding =
+ DraftCommitBinding.create(
+ target,
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ "genesis",
+ List.of(
+ new DraftCommitBinding.RevisionPayload(
+ "0",
+ UUID.randomUUID(),
+ DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE,
+ "{}")),
+ List.of(
+ new DraftCommitBinding.AffectedUnit(
+ DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE,
+ "GAMEPLAY_RULE_SET",
+ target.canonicalVersionId().toString(),
+ "GAMEPLAY_RULE_SET",
+ "effective",
+ "0")));
+ var source =
+ new GameplayRuleSelectedSource(
+ GameplayRuleManifest.canonical(
+ Map.of(
+ "schema", "game-design-gameplay-rule-source-snapshot/v1",
+ "bindingJson", binding.canonicalJson(),
+ "bindingDigest", binding.digest(),
+ "sourceEpoch", "1",
+ "inheritedCommitId", "",
+ "genesisReceiptId", UUID.randomUUID().toString(),
+ "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(),
+ "entries", List.of())));
+ var accountSource =
+ new DraftAuthorizationFenceBinding.SourceEvidence(
+ DraftAuthorizationFenceBinding.SourceKind.ACCOUNT,
+ actor.toString(),
+ "1",
+ "1",
+ null,
+ null,
+ new byte[] {4, 5, 6});
+ return new GameLogicIntakeAuthorizationBinding(
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ actor,
+ source,
+ List.of(accountSource));
+ }
+
+ private static GameLogicIntakeAuthorizationBinding copyAuthorization(
+ GameLogicIntakeAuthorizationBinding original,
+ UUID operationId,
+ UUID fenceId,
+ UUID intakeRequestId,
+ GameplayRuleSelectedSource source) {
+ return new GameLogicIntakeAuthorizationBinding(
+ operationId,
+ fenceId,
+ intakeRequestId,
+ original.actorAccountId(),
+ source,
+ original.sources());
+ }
+
+ private static GameLogicPublicationSourceReadBinding publicationBinding(
+ GameLogicIntakeAuthorizationBinding authorization) {
+ var target = authorization.source().binding().target();
+ return new GameLogicPublicationSourceReadBinding(
+ PublicationDigestRequestBinding.full(
+ authorization.tenantId().toString(),
+ Long.toString(target.gameDesignVersionRowId()),
+ "publication-read"),
+ authorization);
+ }
+
+ private record Fixture(DSLContext dsl, DataSourceTransactionManager manager,
+ GameLogicGameplayRuleIntakeRepository repository) {}
+}
diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImplTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImplTest.java
index ef11de7c7d..7cdec12c0b 100644
--- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImplTest.java
+++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImplTest.java
@@ -1,29 +1,41 @@
package net.firedevops.firemud.gamelogic.service.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding;
import net.firedevops.firemud.gamelogic.service.GameLogicDraftDesignDigestService;
+import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService;
import org.junit.jupiter.api.Test;
class GameLogicDraftDesignDigestServiceImplTest {
- private final GameLogicDraftDesignDigestServiceImpl service =
- new GameLogicDraftDesignDigestServiceImpl();
-
@Test
- void getDraftDesignDigestFailsWhenOwnerManifestAndProvenanceAreUnavailable() {
+ void defaultSpringCompositionRemainsDeniedWithoutAConfiguredOwnerReader() {
+ var service = new GameLogicDraftDesignDigestServiceImpl();
+
GameLogicDraftDesignDigestService.UnsupportedDigestScopeException thrown =
assertThrows(
GameLogicDraftDesignDigestService.UnsupportedDigestScopeException.class,
- () -> service.getDraftDesignDigest("tenant-1", "7"));
+ () -> service.getDraftDesignDigest(null));
assertEquals(
- "Game Logic owner-local manifest and provenance are unavailable", thrown.getMessage());
+ "Game Logic retained publication source reader is not configured", thrown.getMessage());
}
@Test
- void getDraftDesignDigestRejectsMissingVersionBeforeManifestCheck() {
- assertThrows(
- IllegalArgumentException.class, () -> service.getDraftDesignDigest("tenant-1", " "));
+ void explicitlyComposedServiceReturnsTheExactRetainedReadResultForTheLookupBinding() {
+ var sourceReader = mock(GameLogicPublicationSourceReadService.class);
+ var binding = mock(GameLogicPublicationSourceReadBinding.class);
+ var expected = mock(GameLogicPublicationSourceReadService.Result.class);
+ when(sourceReader.read(binding)).thenReturn(expected);
+ var service = new GameLogicDraftDesignDigestServiceImpl(sourceReader);
+
+ assertSame(expected, service.getDraftDesignDigest(binding));
+
+ verify(sourceReader).read(binding);
}
}
diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java
index 10f908bd74..1c81951446 100644
--- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java
+++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java
@@ -1,10 +1,12 @@
package net.firedevops.firemud.gamelogic.service.impl;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
+import com.google.protobuf.ByteString;
import io.grpc.Context;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
@@ -12,7 +14,18 @@
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding;
+import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation;
+import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal;
+import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding;
+import net.firedevops.firemud.common.gamelogic.GameplayAbilitySchemaProjection;
+import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest;
+import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource;
import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
import net.firedevops.firemud.common.security.GameplaySessionAttestationException;
@@ -38,6 +51,8 @@
import net.firedevops.firemud.gamelogic.service.LookAggregationService;
import net.firedevops.firemud.gamelogic.service.MoveAggregationService;
import net.firedevops.firemud.gamelogic.service.PingService;
+import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeRepository;
+import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService;
import net.firedevops.firemud.gamelogic.v1.DropCarriedItemRequest;
import net.firedevops.firemud.gamelogic.v1.ExecuteCommandRequest;
import net.firedevops.firemud.gamelogic.v1.ExecuteCommandResponse;
@@ -57,6 +72,7 @@
class GameLogicGrpcServiceTest {
private static final String TEST_NAMESPACE = "test";
+ private static final UUID TEST_TENANT = UUID.fromString("00000000-0000-0000-0000-000000000001");
private static final GrpcPeerIdentity WRONG_PEER =
new GrpcPeerIdentity(
"spiffe://firemud/ns/test/sa/world-management-service",
@@ -79,17 +95,105 @@ private static void runAsGameDesign(Runnable action) {
}
private static GetDraftDesignDigestRequest fullDigestRequest(String tenantId, String versionId) {
- PublicationDigestRequestBinding binding =
- PublicationDigestRequestBinding.full(tenantId, versionId, "request-7");
+ var authorization = digestAuthorization(UUID.fromString(tenantId), Long.parseLong(versionId));
+ return fullDigestRequest(publicationBinding(authorization, "request-7"));
+ }
+
+ private static GetDraftDesignDigestRequest fullDigestRequest(
+ GameLogicPublicationSourceReadBinding binding) {
+ PublicationDigestRequestBinding publicationRequest = binding.publicationRequest();
return GetDraftDesignDigestRequest.newBuilder()
- .setTenantId(binding.tenantId())
- .setVersionId(binding.versionId())
- .setPublishRequestId(binding.publishRequestId())
- .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity())
- .setRequestDigest(binding.requestDigest())
+ .setTenantId(publicationRequest.tenantId())
+ .setVersionId(publicationRequest.versionId())
+ .setPublishRequestId(publicationRequest.publishRequestId())
+ .setDerivedWorkflowIdentity(publicationRequest.derivedWorkflowIdentity())
+ .setRequestDigest(publicationRequest.requestDigest())
+ .setSourceReadBinding(ByteString.copyFrom(binding.canonicalBytes()))
+ .setSourceReadBindingDigest(binding.digest())
.build();
}
+ private static GameLogicPublicationSourceReadBinding publicationBinding(
+ GameLogicIntakeAuthorizationBinding authorization, String publishRequestId) {
+ var target = authorization.source().binding().target();
+ return new GameLogicPublicationSourceReadBinding(
+ PublicationDigestRequestBinding.full(
+ authorization.tenantId().toString(),
+ Long.toString(target.gameDesignVersionRowId()),
+ publishRequestId),
+ authorization);
+ }
+
+ private static GameLogicIntakeAuthorizationBinding digestAuthorization(
+ UUID tenantId, long gameDesignVersionRowId) {
+ var actor = UUID.randomUUID();
+ var target =
+ new DraftCommitBinding.TargetProof(
+ tenantId,
+ UUID.randomUUID(),
+ gameDesignVersionRowId,
+ "private",
+ 29,
+ "private",
+ "NEW_GAME_ROW");
+ var commit =
+ DraftCommitBinding.create(
+ target,
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ "genesis",
+ List.of(
+ new DraftCommitBinding.RevisionPayload(
+ "0",
+ UUID.randomUUID(),
+ DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE,
+ "{}")),
+ List.of(
+ new DraftCommitBinding.AffectedUnit(
+ DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE,
+ "GAMEPLAY_RULE_SET",
+ target.canonicalVersionId().toString(),
+ "GAMEPLAY_RULE_SET",
+ "effective",
+ "0")));
+ var source =
+ new GameplayRuleSelectedSource(
+ GameplayRuleManifest.canonical(
+ Map.of(
+ "schema", "game-design-gameplay-rule-source-snapshot/v1",
+ "bindingJson", commit.canonicalJson(),
+ "bindingDigest", commit.digest(),
+ "sourceEpoch", "1",
+ "inheritedCommitId", "",
+ "genesisReceiptId", UUID.randomUUID().toString(),
+ "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(),
+ "entries", List.of())));
+ var accountSource =
+ new DraftAuthorizationFenceBinding.SourceEvidence(
+ DraftAuthorizationFenceBinding.SourceKind.ACCOUNT,
+ actor.toString(),
+ "1",
+ "1",
+ null,
+ null,
+ new byte[] {1, 2, 3});
+ return new GameLogicIntakeAuthorizationBinding(
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ actor,
+ source,
+ List.of(accountSource));
+ }
+
+ private static GameLogicGameplayRuleIntakeTerminal retainedTerminal(
+ GameLogicIntakeAuthorizationBinding authorization) {
+ return GameLogicGameplayRuleIntakeTerminal.retained(
+ new GameLogicGameplayRuleIntakeOperation(TEST_NAMESPACE, authorization),
+ authorization.source().canonicalBytes(),
+ authorization.source().manifest().canonicalBytes());
+ }
+
private GameLogicDraftDesignDigestService mockDigestService() {
return Mockito.mock(GameLogicDraftDesignDigestService.class);
}
@@ -257,7 +361,7 @@ public void onCompleted() {}
}
@Test
- void getDraftDesignDigestMapsUnavailableManifestToErrorResponse() {
+ void getDraftDesignDigestMapsUnconfiguredRetainedSourceToErrorResponse() {
PingService pingService = new PingServiceImpl();
var dispatcher = new EventDispatcher();
var processor = new SimpleCommandProcessor(dispatcher, new NoOpScriptingHook());
@@ -267,10 +371,11 @@ void getDraftDesignDigestMapsUnavailableManifestToErrorResponse() {
Mockito.mock(CommunicationAggregationService.class);
MoveAggregationService moveAggregationService = Mockito.mock(MoveAggregationService.class);
GameLogicDraftDesignDigestService digestService = mockDigestService();
- Mockito.when(digestService.getDraftDesignDigest("1", "7"))
+ Mockito.when(
+ digestService.getDraftDesignDigest(any(GameLogicPublicationSourceReadBinding.class)))
.thenThrow(
new GameLogicDraftDesignDigestService.UnsupportedDigestScopeException(
- "Game Logic owner-local manifest and provenance are unavailable"));
+ "Game Logic retained publication source reader is not configured"));
SessionContext.setContext(
null, List.of(), Map.of(), true, "game-design-service", "test-instance");
GameLogicGrpcService service =
@@ -290,7 +395,7 @@ void getDraftDesignDigestMapsUnavailableManifestToErrorResponse() {
runAsGameDesign(
() ->
service.getDraftDesignDigest(
- fullDigestRequest("1", "7"),
+ fullDigestRequest(TEST_TENANT.toString(), "7"),
new StreamObserver<>() {
@Override
public void onNext(GetDraftDesignDigestResponse value) {
@@ -316,17 +421,118 @@ public void onCompleted() {}
assertEquals(0, ref.get().getDigestSchemaVersion());
}
+ @Test
+ void getDraftDesignDigestEchoesTheExactRetainedSourceAndCanonicalDigests() {
+ var authorization = digestAuthorization(TEST_TENANT, 7);
+ var binding = publicationBinding(authorization, "request-7");
+ var terminal = retainedTerminal(authorization);
+ var repository = Mockito.mock(GameLogicGameplayRuleIntakeRepository.class);
+ Mockito.when(repository.findTerminal(authorization.operationId()))
+ .thenReturn(Optional.of(terminal));
+ var digestService =
+ new GameLogicDraftDesignDigestServiceImpl(
+ new GameLogicPublicationSourceReadService(repository, TEST_NAMESPACE));
+ var service = newDigestService(digestService);
+ SessionContext.setContext(
+ null, List.of(), Map.of(), true, "game-design-service", "test-instance");
+
+ AtomicReference responseReference = new AtomicReference<>();
+ runAsGameDesign(() -> responseReference.set(invokeDigest(service, fullDigestRequest(binding))));
+ GetDraftDesignDigestResponse response = responseReference.get();
+
+ assertEquals("", response.getError().getCode());
+ assertEquals(TEST_TENANT.toString(), response.getTenantId());
+ assertEquals("7", response.getVersionId());
+ assertEquals(
+ authorization.source().binding().commitId().toString(), response.getAppliedCommitId());
+ assertEquals(authorization.source().manifest().digest(), response.getContentDigest());
+ assertEquals(1, response.getDigestSchemaVersion());
+ assertEquals(
+ GameplayAbilitySchemaProjection.digest(authorization.source().manifest()),
+ response.getAbilitySchemaDigest());
+ assertEquals("RFC8785", response.getCanonicalization());
+ assertEquals(binding.digest(), response.getSourceReadBindingDigest());
+ assertArrayEquals(binding.canonicalBytes(), response.getSourceReadBinding().toByteArray());
+ assertEquals(terminal.digest(), response.getRetainedIntakeTerminalDigest());
+ assertArrayEquals(
+ terminal.canonicalBytes(), response.getRetainedIntakeTerminal().toByteArray());
+ Mockito.verify(repository).findTerminal(authorization.operationId());
+ }
+
+ @Test
+ void getDraftDesignDigestRejectsMissingBindingAndUnversionedScopeBeforeServiceCall() {
+ var digestService = mockDigestService();
+ var service = newDigestService(digestService);
+ SessionContext.setContext(
+ null, List.of(), Map.of(), true, "game-design-service", "test-instance");
+ var valid = fullDigestRequest(TEST_TENANT.toString(), "7");
+ var missingBinding =
+ valid.toBuilder().clearSourceReadBinding().clearSourceReadBindingDigest().build();
+ var unversionedScope = valid.toBuilder().clearScope().build();
+
+ runAsGameDesign(
+ () -> {
+ var missingResponse = invokeDigest(service, missingBinding);
+ assertEquals("INVALID_ARGUMENT", missingResponse.getError().getCode());
+ assertEquals("", missingResponse.getContentDigest());
+ assertEquals(0, missingResponse.getDigestSchemaVersion());
+ var scopeResponse = invokeDigest(service, unversionedScope);
+ assertEquals("INVALID_ARGUMENT", scopeResponse.getError().getCode());
+ assertEquals("", scopeResponse.getContentDigest());
+ assertEquals(0, scopeResponse.getDigestSchemaVersion());
+ });
+ Mockito.verifyNoInteractions(digestService);
+ }
+
+ @Test
+ void getDraftDesignDigestDeniesSourceBindingThatDiffersFromRetainedOperation() {
+ var authorization = digestAuthorization(TEST_TENANT, 7);
+ var stored = retainedTerminal(authorization);
+ var changedAuthorization =
+ new GameLogicIntakeAuthorizationBinding(
+ authorization.operationId(),
+ UUID.randomUUID(),
+ authorization.intakeRequestId(),
+ authorization.actorAccountId(),
+ authorization.source(),
+ authorization.sources());
+ var changedBinding = publicationBinding(changedAuthorization, "request-7");
+ var repository = Mockito.mock(GameLogicGameplayRuleIntakeRepository.class);
+ Mockito.when(repository.findTerminal(authorization.operationId()))
+ .thenReturn(Optional.of(stored));
+ var service =
+ newDigestService(
+ new GameLogicDraftDesignDigestServiceImpl(
+ new GameLogicPublicationSourceReadService(repository, TEST_NAMESPACE)));
+ SessionContext.setContext(
+ null, List.of(), Map.of(), true, "game-design-service", "test-instance");
+
+ AtomicReference responseReference = new AtomicReference<>();
+ runAsGameDesign(
+ () -> responseReference.set(invokeDigest(service, fullDigestRequest(changedBinding))));
+ GetDraftDesignDigestResponse response = responseReference.get();
+
+ assertEquals("ALREADY_EXISTS", response.getError().getCode());
+ assertEquals("", response.getContentDigest());
+ assertEquals("", response.getAbilitySchemaDigest());
+ assertEquals(0, response.getDigestSchemaVersion());
+ assertEquals(ByteString.EMPTY, response.getRetainedIntakeTerminal());
+ Mockito.verify(repository).findTerminal(authorization.operationId());
+ }
+
@Test
void getDraftDesignDigestMapsUnexpectedUnsupportedOperationToInternalError() {
GameLogicDraftDesignDigestService digestService = mockDigestService();
- Mockito.when(digestService.getDraftDesignDigest("1", "7"))
+ Mockito.when(
+ digestService.getDraftDesignDigest(any(GameLogicPublicationSourceReadBinding.class)))
.thenThrow(new UnsupportedOperationException("unexpected implementation failure"));
SessionContext.setContext(
null, List.of(), Map.of(), true, "game-design-service", "test-instance");
GameLogicGrpcService service = newDigestService(digestService);
AtomicReference response = new AtomicReference<>();
- runAsGameDesign(() -> response.set(invokeDigest(service, fullDigestRequest("1", "7"))));
+ runAsGameDesign(
+ () -> response.set(invokeDigest(service, fullDigestRequest(TEST_TENANT.toString(), "7"))));
assertTrue(response.get().hasError());
assertEquals("INTERNAL", response.get().getError().getCode());
@@ -358,7 +564,7 @@ void getDraftDesignDigestRejectsMissingPeerIdentityForInternalCaller() {
.run(
() ->
service.getDraftDesignDigest(
- fullDigestRequest("1", "7"),
+ fullDigestRequest(TEST_TENANT.toString(), "7"),
new StreamObserver<>() {
@Override
public void onNext(GetDraftDesignDigestResponse value) {
@@ -379,7 +585,7 @@ public void onCompleted() {}
void getDraftDesignDigestRejectsWrongPeerAndUserOrAdminJwt() {
GameLogicDraftDesignDigestService digestService = mockDigestService();
GameLogicGrpcService service = newDigestService(digestService);
- GetDraftDesignDigestRequest request = fullDigestRequest("1", "7");
+ GetDraftDesignDigestRequest request = fullDigestRequest(TEST_TENANT.toString(), "7");
SessionContext.setContext(null, List.of(), Map.of(), true, "game-design-service", "instance-1");
withPeer(
@@ -435,25 +641,11 @@ void getDraftDesignDigestFailsClosedWhenWorkloadNamespaceIsMissingOrInvalid() {
() ->
assertEquals(
"PERMISSION_DENIED",
- invokeDigest(service, fullDigestRequest("1", "7")).getError().getCode()));
+ invokeDigest(service, fullDigestRequest(TEST_TENANT.toString(), "7"))
+ .getError()
+ .getCode()));
}
Mockito.verifyNoInteractions(digestService);
-
- GameLogicDraftDesignDigestService configuredDigestService = mockDigestService();
- Mockito.when(configuredDigestService.getDraftDesignDigest("1", "7"))
- .thenReturn(
- new GameLogicDraftDesignDigestService.GameLogicDraftDesignDigest(
- "1", "7", "version:7", "digest-game-logic", 1));
- GameLogicGrpcService configuredService =
- newDigestService(configuredDigestService, TEST_NAMESPACE);
- AtomicReference configuredResponse = new AtomicReference<>();
- runAsGameDesign(
- () -> configuredResponse.set(invokeDigest(configuredService, fullDigestRequest("1", "7"))));
-
- assertTrue(configuredResponse.get().getError().getCode().isEmpty());
- assertEquals("1", configuredResponse.get().getTenantId());
- assertEquals("7", configuredResponse.get().getVersionId());
- Mockito.verify(configuredDigestService).getDraftDesignDigest("1", "7");
}
private GetDraftDesignDigestResponse invokeDigest(
diff --git a/services/world-management-service/build.gradle.kts b/services/world-management-service/build.gradle.kts
index a1eabcc8b1..5eae6d8481 100644
--- a/services/world-management-service/build.gradle.kts
+++ b/services/world-management-service/build.gradle.kts
@@ -44,3 +44,19 @@ val worldClassesProof by configurations.creating {
extendsFrom(configurations.implementation.get())
outgoing.artifact(worldClassesProofJar)
}
+
+// Only the selected-publication fixture classes cross the proof boundary; service resources stay local.
+val worldSelectedPublicationProofJar by tasks.registering(Jar::class) {
+ archiveClassifier.set("selected-publication-proof")
+ dependsOn(tasks.named("integrationTestClasses"))
+ from(sourceSets["integrationTest"].output.classesDirs) {
+ include("net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture*.class")
+ }
+}
+
+val worldSelectedPublicationProof by configurations.creating {
+ isCanBeConsumed = true
+ isCanBeResolved = false
+ extendsFrom(configurations.implementation.get())
+ outgoing.artifact(worldSelectedPublicationProofJar)
+}
diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java
index 5c833e18a5..e2481ab4db 100644
--- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java
+++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java
@@ -462,7 +462,8 @@ private static int expectedFrozenGraphSchemaVersion(
int expectedWorldDigestSchema =
switch (release.schemaVersion()) {
case AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION -> 3;
- case AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION -> 4;
+ case AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION,
+ AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION -> 4;
default ->
throw invalid("Retained release has no supported selected World graph profile");
};
diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java
new file mode 100644
index 0000000000..b4bc5e9492
--- /dev/null
+++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java
@@ -0,0 +1,565 @@
+package net.firedevops.firemud.worldmanagement.tenant;
+
+import java.util.List;
+import java.util.Objects;
+import java.util.UUID;
+import java.util.function.Function;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
+import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence;
+import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding;
+import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding;
+import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase;
+import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence;
+import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence;
+import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec;
+import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest;
+import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt;
+import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence;
+import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec;
+import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState;
+import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService;
+import net.firedevops.firemud.worldmanagement.service.impl.WorldDraftDesignDigestServiceImpl;
+import net.firedevops.firemud.worldmanagement.repository.GenerationRuleRepository;
+import net.firedevops.firemud.worldmanagement.repository.RegionRepository;
+import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository;
+import net.firedevops.firemud.worldmanagement.repository.RoomRepository;
+import net.firedevops.firemud.worldmanagement.repository.WorldEntitySpawnBindingRepository;
+import net.firedevops.firemud.worldmanagement.repository.ZoneRepository;
+import org.jooq.DSLContext;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.support.TransactionTemplate;
+import tools.jackson.databind.ObjectMapper;
+
+/**
+ * Package-local access to the actual World selected-freeze owner path for the GDS schema-4 proof.
+ *
+ * Inputs from the original Account authorization and authored-world producer are controlled
+ * test evidence. This fixture does not establish production authority. Every World source,
+ * Version, graph application, first-freeze checkpoint, inventory, frozen-graph capture, and
+ * committed readback below goes through the current World SQL owners with their guards enabled.
+ */
+public final class WorldSelectedFullPublicationEvidenceFixture {
+ private static final ObjectMapper JSON = new ObjectMapper();
+
+ private WorldSelectedFullPublicationEvidenceFixture() {}
+
+ /** Exact retained World evidence consumed by the actual GDS selected-publication owner. */
+ public record Result(
+ AuthoredDraftPublishSelectionBinding selection,
+ AccountPublicationAuthorizationBinding accountBinding,
+ WorldSelectedDraftPublicationFreezeEvidence freezeEvidence,
+ WorldSelectedPublicationArtifactInventoryEvidence inventoryEvidence,
+ WorldPublishedStartLocationEvidence startLocationEvidence,
+ ByIdReadRequest sourceReadRequest,
+ PublicReceipt sourceReadReceipt,
+ WorldDraftDesignDigestService.WorldDraftDesignDigest selectedWorldDigest,
+ byte[] appliedResultBytes,
+ byte[] graphBytes) {
+ public Result {
+ Objects.requireNonNull(selection, "selection");
+ Objects.requireNonNull(accountBinding, "accountBinding");
+ Objects.requireNonNull(freezeEvidence, "freezeEvidence");
+ Objects.requireNonNull(inventoryEvidence, "inventoryEvidence");
+ Objects.requireNonNull(startLocationEvidence, "startLocationEvidence");
+ Objects.requireNonNull(sourceReadRequest, "sourceReadRequest");
+ Objects.requireNonNull(sourceReadReceipt, "sourceReadReceipt");
+ Objects.requireNonNull(selectedWorldDigest, "selectedWorldDigest");
+ appliedResultBytes = Objects.requireNonNull(appliedResultBytes, "appliedResultBytes").clone();
+ graphBytes = Objects.requireNonNull(graphBytes, "graphBytes").clone();
+ }
+
+ @Override
+ public byte[] appliedResultBytes() {
+ return appliedResultBytes.clone();
+ }
+
+ @Override
+ public byte[] graphBytes() {
+ return graphBytes.clone();
+ }
+ }
+
+ /** Actual World source/version and APPLIED graph owner rows for one exact full Draft binding. */
+ public record AppliedGraph(
+ AuthoredWorldSourceEvidence controlledWorldSource,
+ WorldAuthoredSourceIntakeReceipt sourceIntake,
+ WorldAuthoredVersionIdentityReceipt versionIdentity,
+ WorldDraftTopologyCommitPlan plan,
+ WorldDraftGraphApplication application,
+ WorldDraftGraphAppliedResult applied) {
+ public AppliedGraph {
+ Objects.requireNonNull(controlledWorldSource, "controlledWorldSource");
+ Objects.requireNonNull(sourceIntake, "sourceIntake");
+ Objects.requireNonNull(versionIdentity, "versionIdentity");
+ Objects.requireNonNull(plan, "plan");
+ Objects.requireNonNull(application, "application");
+ Objects.requireNonNull(applied, "applied");
+ if (!plan.binding().equals(application.plan().binding())
+ || !application.operation().equals(applied.application().operation())) {
+ throw new IllegalArgumentException("World APPLIED graph does not match its selected plan");
+ }
+ }
+
+ public DraftCommitBinding selectedCommit() {
+ return plan.binding();
+ }
+ }
+
+ /**
+ * Applies and freezes the exact already-retained GDS selection in current World owners.
+ *
+ *
The supplied selection is read from GDS's synchronized Version/commit owner before this
+ * method is called. The callback supplies only controlled upstream Account authorization bytes;
+ * its selected binding must be byte-for-byte that retained selection.
+ */
+ public static Result applyFreezeAndCapture(
+ DSLContext worldDsl,
+ PlatformTransactionManager worldTransactions,
+ String namespace,
+ AuthoredDraftPublishSelectionBinding selection,
+ AppliedGraph worldGraph,
+ Function
+ controlledAccountBindingFactory) {
+ Objects.requireNonNull(worldDsl, "worldDsl");
+ Objects.requireNonNull(worldTransactions, "worldTransactions");
+ Objects.requireNonNull(selection, "selection");
+ Objects.requireNonNull(worldGraph, "worldGraph");
+ Objects.requireNonNull(controlledAccountBindingFactory, "controlledAccountBindingFactory");
+
+ var target = selection.target();
+ DraftCommitBinding binding = selection.selectedCommit();
+ if (!binding.equals(worldGraph.selectedCommit())
+ || !namespace.equals(worldGraph.sourceIntake().targetNamespace())
+ || !target.canonicalTenantId().equals(worldGraph.sourceIntake().canonicalTenantId())
+ || !target.canonicalVersionId().equals(worldGraph.versionIdentity().canonicalVersionId())
+ || target.gameDesignVersionRowId() != worldGraph.versionIdentity().gameDesignVersionId()) {
+ throw new IllegalArgumentException(
+ "World freeze does not target the exact previously applied GDS Draft and World identity");
+ }
+ long expectedStateEpoch =
+ Long.parseLong(selection.intent().expectedVersionStateEpoch());
+ var intake = worldGraph.sourceIntake();
+ var version = worldGraph.versionIdentity();
+ var controlledWorldSource = worldGraph.controlledWorldSource();
+ var plan = worldGraph.plan();
+ var application = worldGraph.application();
+ var intakeRepository = new WorldAuthoredSourceIntakeRepository(worldDsl);
+ var fence = new WorldDesignPublicationFenceRepository(worldDsl, intakeRepository);
+ var topology = new WorldDraftTopologyCommitRepository(worldDsl, fence, JSON);
+ var applications = new WorldDraftGraphApplicationRepository(worldDsl, fence, JSON);
+ var applied = worldGraph.applied();
+ requireExactAppliedReadback(applications, topology, application, plan, applied);
+
+ AccountPublicationAuthorizationBinding accountBinding =
+ Objects.requireNonNull(
+ controlledAccountBindingFactory.apply(selection), "controlled Account binding");
+ if (!selection.equals(accountBinding.input().selection())) {
+ throw new IllegalArgumentException(
+ "Controlled Account binding does not retain the exact GDS synchronized selection");
+ }
+ String publicationId = selection.intent().publishRequestId();
+ String workflow =
+ PublicationDigestRequestBinding.full(
+ target.canonicalTenantId().toString(),
+ Long.toString(target.gameDesignVersionRowId()),
+ publicationId)
+ .derivedWorkflowIdentity();
+ var freeze =
+ new WorldDesignPublicationFenceEvidence(
+ namespace,
+ target.canonicalTenantId(),
+ target.canonicalVersionId(),
+ version.operationId(),
+ target.gameDesignVersionRowId(),
+ intake.intakeRequestId(),
+ intake.operationId(),
+ intake.requestDigest(),
+ controlledWorldSource.operationId(),
+ controlledWorldSource.evidenceDigest(),
+ intake.receiptDigest(),
+ publicationId,
+ selection.digest().substring("sha256:".length()),
+ expectedStateEpoch,
+ workflow);
+ var digestService = digestService(worldDsl);
+ var authorizationRepository = new WorldSelectedDraftPublicationAuthorizationRepository(worldDsl);
+ var inventoryRepository = new WorldSelectedPublicationArtifactInventoryRepository(worldDsl);
+ var checkpointRepository =
+ new WorldSelectedDraftPublicationCheckpointRepository(
+ fence, applications, topology, digestService);
+ var capturedCheckpoint =
+ new java.util.concurrent.atomic.AtomicReference<
+ WorldSelectedDraftPublicationCheckpointRepository.CapturedCheckpoint>();
+ var createdCheckpointInTransaction = new java.util.concurrent.atomic.AtomicBoolean();
+ var frozenAttempt =
+ Objects.requireNonNull(
+ new TransactionTemplate(worldTransactions).execute(
+ status -> {
+ createdCheckpointInTransaction.set(false);
+ var attempt =
+ fence.claimFreeze(
+ freeze,
+ () -> {
+ var captured = checkpointRepository.captureWithSource(freeze, plan);
+ capturedCheckpoint.set(captured);
+ createdCheckpointInTransaction.set(true);
+ return captured.checkpoint();
+ });
+ var retainedAccount =
+ authorizationRepository.retainOrRequireExact(
+ attempt, accountBinding, createdCheckpointInTransaction.get());
+ if (!java.util.Arrays.equals(
+ retainedAccount.canonicalBytes(), accountBinding.canonicalBytes())) {
+ throw new IllegalStateException(
+ "World did not retain the exact original Account publication binding");
+ }
+ inventoryRepository.retainOrRequireExact(
+ attempt,
+ retainedAccount,
+ createdCheckpointInTransaction.get(),
+ capturedCheckpoint.get());
+ return attempt;
+ }));
+
+ var retainedAccount =
+ authorizationRepository.readCommitted(frozenAttempt).orElseThrow();
+ if (!java.util.Arrays.equals(retainedAccount.canonicalBytes(), accountBinding.canonicalBytes())) {
+ throw new IllegalStateException("Committed World Account-binding readback changed bytes");
+ }
+ var freezeRequest =
+ WorldSelectedDraftPublicationFreezeEvidence.Request.create(
+ namespace,
+ target.canonicalTenantId(),
+ target.canonicalVersionId(),
+ publicationId,
+ expectedStateEpoch,
+ selection.digest().substring("sha256:".length()),
+ accountBinding);
+ var acknowledgement =
+ new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement(
+ freezeRequest,
+ intake.intakeRequestId(),
+ expectedStateEpoch,
+ frozenAttempt.publicationFence(),
+ OwnerFreezePhase.FROZEN,
+ frozenAttempt.checkpoint().appliedCommitId(),
+ frozenAttempt.checkpoint().contentDigest(),
+ frozenAttempt.checkpoint().digestSchemaVersion());
+ var freezeEvidence =
+ WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse(
+ freezeRequest, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement));
+ var inventoryEvidence =
+ new WorldSelectedPublicationArtifactInventoryReadService(
+ namespace, fence, authorizationRepository, inventoryRepository)
+ .readRetained(freezeEvidence);
+
+ var captureRequest =
+ captureRequest(plan, freeze, frozenAttempt);
+ var frozenRepository =
+ new WorldCanonicalFrozenTopologyRepository(
+ worldDsl,
+ new WorldAuthoredGraphSnapshotRepository(worldDsl),
+ topology,
+ digestService);
+ var captured =
+ new WorldCanonicalFrozenTopologyService(frozenRepository, worldTransactions)
+ .capture(new WorldCanonicalFrozenTopology.Request(plan, captureRequest));
+ var committedCapture = frozenRepository.readCommitted(captureRequest).orElseThrow();
+ if (!java.util.Arrays.equals(committedCapture.graphBytes(), captured.graphBytes())) {
+ throw new IllegalStateException("Committed World frozen-graph readback changed bytes");
+ }
+ var publishedSource =
+ new WorldPublishedStartLocationRepository(worldDsl, frozenRepository, applications)
+ .readCommitted(captureRequest)
+ .orElseThrow();
+ var worldEvidence = publishedStartLocationEvidence(publishedSource);
+ var worldDigest =
+ new WorldDraftDesignDigestService.WorldDraftDesignDigest(
+ Long.toString(capturedCheckpoint.get().owner().localTenantKey()),
+ Long.toString(capturedCheckpoint.get().owner().localVersionKey()),
+ frozenAttempt.checkpoint().appliedCommitId(),
+ frozenAttempt.checkpoint().contentDigest(),
+ frozenAttempt.checkpoint().digestSchemaVersion());
+ if (worldDigest.digestSchemaVersion() != 4) {
+ throw new IllegalStateException("World selected freeze did not retain current digest schema 4");
+ }
+
+ var committedIntake = intakeRepository.read(namespace, intake.intakeRequestId()).orElseThrow();
+ var sourceReadRequest =
+ new ByIdReadRequest(
+ 1, namespace, UUID.randomUUID(), committedIntake.intakeRequestId(), target.canonicalTenantId());
+ var sourceReadReceipt =
+ new PublicReceipt(
+ committedIntake.schemaVersion(),
+ committedIntake.targetNamespace(),
+ committedIntake.intakeRequestId(),
+ committedIntake.operationId(),
+ committedIntake.canonicalTenantId(),
+ committedIntake.worldSlug(),
+ committedIntake.sourceOperationId(),
+ committedIntake.sourceEvidenceDigest(),
+ committedIntake.requestDigest(),
+ committedIntake.receiptDigest(),
+ committedIntake.source());
+ WorldAuthoredSourceIntakeGrpcCodec.toReadByIdResponse(sourceReadRequest, sourceReadReceipt);
+
+ return new Result(
+ selection,
+ accountBinding,
+ freezeEvidence,
+ inventoryEvidence,
+ worldEvidence,
+ sourceReadRequest,
+ sourceReadReceipt,
+ worldDigest,
+ applied.canonicalBytes(),
+ captured.graphBytes());
+ }
+
+ /** Applies the exact World payloads in a selected GDS binding before its sync fence is advanced. */
+ public static AppliedGraph applyGraph(
+ DSLContext worldDsl,
+ PlatformTransactionManager worldTransactions,
+ String namespace,
+ DraftCommitBinding selectedCommit,
+ AuthoredWorldSourceEvidence controlledWorldSource) {
+ Objects.requireNonNull(worldDsl, "worldDsl");
+ Objects.requireNonNull(worldTransactions, "worldTransactions");
+ Objects.requireNonNull(selectedCommit, "selectedCommit");
+ Objects.requireNonNull(controlledWorldSource, "controlledWorldSource");
+ requireExactControlledSource(namespace, selectedCommit.target(), controlledWorldSource);
+ var intakeRepository = new WorldAuthoredSourceIntakeRepository(worldDsl);
+ var versionRepository = new WorldAuthoredVersionIdentityRepository(worldDsl);
+ var write = new TransactionTemplate(worldTransactions);
+ var intake =
+ Objects.requireNonNull(
+ write.execute(
+ status ->
+ intakeRepository.acceptFresh(
+ namespace, UUID.randomUUID(), controlledWorldSource)));
+ var versionStateRequest =
+ new AuthoredWorldVersionStateEvidence.Request(
+ 1,
+ namespace,
+ UUID.randomUUID(),
+ selectedCommit.target().canonicalTenantId(),
+ controlledWorldSource.worldSlug(),
+ controlledWorldSource.operationId(),
+ controlledWorldSource.evidenceDigest(),
+ selectedCommit.target().gameDesignVersionRowId());
+ var versionState =
+ AuthoredWorldVersionStateEvidence.create(
+ versionStateRequest,
+ controlledWorldSource,
+ selectedCommit.target().canonicalVersionId(),
+ VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT,
+ 1L);
+ var version =
+ Objects.requireNonNull(
+ write.execute(status -> versionRepository.acceptFresh(intake, versionState)));
+ if (!selectedCommit.target().canonicalTenantId().equals(version.canonicalTenantId())
+ || !selectedCommit.target().canonicalVersionId().equals(version.canonicalVersionId())
+ || selectedCommit.target().gameDesignVersionRowId() != version.gameDesignVersionId()) {
+ throw new IllegalStateException(
+ "World source/version owner rows differ from the selected GDS target mapping");
+ }
+ var ownerBinding =
+ new WorldDesignPublicationFenceEvidence.OwnerBinding(
+ namespace,
+ selectedCommit.target().canonicalTenantId(),
+ selectedCommit.target().canonicalVersionId(),
+ version.operationId(),
+ selectedCommit.target().gameDesignVersionRowId(),
+ intake.intakeRequestId(),
+ intake.operationId(),
+ intake.requestDigest(),
+ controlledWorldSource.operationId(),
+ controlledWorldSource.evidenceDigest(),
+ intake.receiptDigest());
+ var plan = WorldDraftTopologyCommitPlan.create(selectedCommit, ownerBinding);
+ var application = controlledGraphApplication(plan);
+ var fence = new WorldDesignPublicationFenceRepository(worldDsl, intakeRepository);
+ var topology = new WorldDraftTopologyCommitRepository(worldDsl, fence, JSON);
+ var applications = new WorldDraftGraphApplicationRepository(worldDsl, fence, JSON);
+ var applied =
+ new WorldDraftGraphApplicationService(
+ applications,
+ worldTransactions,
+ operation -> new WorldDraftGraphApplicationService.CommitOrderProof(operation))
+ .apply(application);
+ requireExactAppliedReadback(applications, topology, application, plan, applied);
+ return new AppliedGraph(
+ controlledWorldSource, intake, version, plan, application, applied);
+ }
+
+ private static void requireExactControlledSource(
+ String namespace,
+ DraftCommitBinding.TargetProof target,
+ AuthoredWorldSourceEvidence source) {
+ if (!namespace.equals(source.targetNamespace())
+ || !target.canonicalTenantId().equals(source.canonicalTenantId())
+ || target.sourceGameRowId() != source.sourceGameRowId()
+ || !target.sourceGameTenantKey().equals(source.sourceGameTenantKey())
+ || !target.sourceProvenanceKind().equals(source.provenanceKind())) {
+ throw new IllegalArgumentException(
+ "Controlled World source differs from the exact retained GDS selected target");
+ }
+ }
+
+ private static void requireExactVersionIdentity(
+ AuthoredDraftPublishSelectionBinding selection,
+ WorldAuthoredSourceIntakeReceipt intake,
+ WorldAuthoredVersionIdentityReceipt version) {
+ if (!selection.target().canonicalTenantId().equals(version.canonicalTenantId())
+ || !selection.target().canonicalVersionId().equals(version.canonicalVersionId())
+ || selection.target().gameDesignVersionRowId() != version.gameDesignVersionId()
+ || !intake.operationId().equals(version.sourceIntakeReceipt().operationId())
+ || !selection.target().canonicalTenantId().equals(intake.canonicalTenantId())) {
+ throw new IllegalStateException(
+ "World retained source/Version rows differ from the selected GDS target mapping");
+ }
+ }
+
+ private static WorldDraftGraphApplication controlledGraphApplication(
+ WorldDraftTopologyCommitPlan plan) {
+ DraftCommitBinding binding = plan.binding();
+ UUID operationId = UUID.randomUUID();
+ UUID authorizationFenceId = UUID.randomUUID();
+ UUID actorId = UUID.randomUUID();
+ byte[] accountBytes =
+ new DraftAuthorizationFenceBinding(
+ operationId,
+ binding.requestId(),
+ binding.commitId(),
+ authorizationFenceId,
+ actorId,
+ binding.target().canonicalTenantId(),
+ binding.target().canonicalVersionId(),
+ binding.baseCommitId(),
+ "0",
+ binding.canonicalBytes(),
+ binding.canonicalBytes(),
+ binding.digest(),
+ List.of(
+ new DraftAuthorizationFenceBinding.SourceEvidence(
+ DraftAuthorizationFenceBinding.SourceKind.GLOBAL_ROLES,
+ actorId.toString(),
+ null,
+ "1",
+ null,
+ null,
+ "TEST_ONLY controlled original COMMIT_ORDER input"
+ .getBytes(java.nio.charset.StandardCharsets.UTF_8))))
+ .withRequiredOwners()
+ .canonicalBytes();
+ var operation =
+ new WorldDraftTerminalOperation(
+ operationId,
+ binding.requestId(),
+ binding.commitId(),
+ authorizationFenceId,
+ binding.target().canonicalTenantId(),
+ binding.target().canonicalVersionId(),
+ binding,
+ plan.ownerBinding(),
+ accountBytes);
+ return new WorldDraftGraphApplication(operation, plan);
+ }
+
+ private static void requireExactAppliedReadback(
+ WorldDraftGraphApplicationRepository applications,
+ WorldDraftTopologyCommitRepository topology,
+ WorldDraftGraphApplication application,
+ WorldDraftTopologyCommitPlan plan,
+ WorldDraftGraphAppliedResult applied) {
+ var committedApplication = applications.readCommitted(application).orElseThrow();
+ var committedTopology = topology.readCommitted(plan).orElseThrow();
+ if (!java.util.Arrays.equals(committedApplication.canonicalBytes(), applied.canonicalBytes())
+ || !java.util.Arrays.equals(committedTopology.graphBytes(), applied.graphBytes())) {
+ throw new IllegalStateException("World graph application committed readback changed bytes");
+ }
+ }
+
+ private static WorldAuthoredGraphSnapshot.CaptureRequest captureRequest(
+ WorldDraftTopologyCommitPlan plan,
+ WorldDesignPublicationFenceEvidence freeze,
+ WorldDesignPublicationFenceRepository.FrozenAttempt attempt) {
+ List tuples =
+ plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream()
+ .map(
+ unit ->
+ new WorldAuthoredGraphSnapshot.OwnedAffectedTuple(
+ unit.owner().name(),
+ unit.aggregateType(),
+ unit.aggregateId(),
+ unit.scopeType(),
+ unit.scopeId(),
+ unit.expectedEpoch()))
+ .toList();
+ return new WorldAuthoredGraphSnapshot.CaptureRequest(
+ freeze.targetNamespace(),
+ freeze.canonicalTenantId(),
+ freeze.canonicalVersionId(),
+ freeze.intakeRequestId(),
+ attempt.publicationFence(),
+ freeze.publicationRequestId(),
+ freeze.requestDigest(),
+ freeze.versionStateEpoch(),
+ freeze.publishWorkflowId(),
+ plan.binding().commitId().toString(),
+ attempt.checkpoint().contentDigest(),
+ attempt.checkpoint().digestSchemaVersion(),
+ tuples);
+ }
+
+ private static WorldDraftDesignDigestServiceImpl digestService(DSLContext dsl) {
+ return new WorldDraftDesignDigestServiceImpl(
+ new RegionRepository(dsl),
+ new ZoneRepository(dsl),
+ new RoomRepository(dsl),
+ new RoomExitRepository(dsl),
+ new GenerationRuleRepository(dsl),
+ new WorldEntitySpawnBindingRepository(dsl));
+ }
+
+ private static WorldPublishedStartLocationEvidence publishedStartLocationEvidence(
+ WorldPublishedStartLocationSource source) {
+ var freeze = source.frozenTopology().request().freeze();
+ var tuples =
+ freeze.suppliedOwnedAffectedTuples().stream()
+ .map(
+ tuple ->
+ new WorldPublishedStartLocationEvidence.OwnedAffectedTuple(
+ tuple.owner(),
+ tuple.aggregateType(),
+ tuple.aggregateId(),
+ tuple.scopeType(),
+ tuple.scopeId(),
+ tuple.expectedEpoch()))
+ .toList();
+ var request =
+ new WorldPublishedStartLocationEvidence.Request(
+ freeze.targetNamespace(),
+ freeze.canonicalTenantId(),
+ freeze.canonicalVersionId(),
+ freeze.intakeRequestId(),
+ freeze.publicationFence(),
+ freeze.publicationRequestId(),
+ freeze.requestDigest(),
+ freeze.versionStateEpoch(),
+ freeze.publishWorkflowId(),
+ freeze.appliedCommitId(),
+ freeze.contentDigest(),
+ freeze.digestSchemaVersion(),
+ tuples);
+ return new WorldPublishedStartLocationEvidence(
+ request,
+ source.selectorReceipt().canonicalBytes(),
+ source.appliedResult().application().operation().accountBindingBytes(),
+ source.appliedResult().canonicalBytes());
+ }
+}
diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java
index 0565321746..ce83e573db 100644
--- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java
+++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java
@@ -119,6 +119,27 @@ void rejectsUnsupportedOrMixedCurrentSelectorAttestationProfiles() throws Except
.hasMessageContaining("Participant digest schema is unsupported");
}
+ @Test
+ void selectedFullAttestationUsesTheExistingWorld4FrozenGraphProfile() throws Exception {
+ var full = release(AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
+ assertThat(full.participantDigests())
+ .extracting(AuthoredWorldReleaseAttestationEvidence.Participant::digestSchemaVersion)
+ .containsExactly(4, 3, 1, 6, 2);
+ assertThat(full.worldStartLocationEvidence().request().digestSchemaVersion()).isEqualTo(4);
+ assertThat(expectedFrozenGraphSchemaVersion(full)).isEqualTo(3);
+
+ for (String owner : List.of("WORLD_MANAGEMENT", "ENTITY_MANAGEMENT", "AUTOMATION_SCRIPTING")) {
+ int staleSchema = switch (owner) {
+ case "WORLD_MANAGEMENT" -> 3;
+ case "ENTITY_MANAGEMENT" -> 2;
+ default -> 5;
+ };
+ assertThatThrownBy(() -> selectedFull(full, participantDigestsWithSchema(full, owner, staleSchema)))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Participant digest schema is unsupported");
+ }
+ }
+
private static int expectedFrozenGraphSchemaVersion(
AuthoredWorldReleaseAttestationEvidence release) {
try {
@@ -140,8 +161,8 @@ private static AuthoredWorldReleaseAttestationEvidence release(int schemaVersion
WorldPublishedStartLocationEvidence selector =
AuthoredWorldReleaseAttestationEvidence.requiresWorldStartLocationEvidence(schemaVersion)
? selectedWorldEvidence(
- schemaVersion
- == AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION
+ (schemaVersion == AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION
+ || schemaVersion == AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION)
? 4
: 3)
: null;
@@ -248,6 +269,28 @@ private static AuthoredWorldReleaseAttestationEvidence release(int schemaVersion
List.of(),
"test-generation-config",
selector);
+ case AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION ->
+ AuthoredWorldReleaseAttestationEvidence.createSelectedFull(
+ namespace,
+ descriptorDigest,
+ tenantId,
+ versionId,
+ "synthetic-world",
+ UUID.fromString("33333333-3333-4333-8333-333333333333"),
+ "sha256:" + "e".repeat(64),
+ "test-descriptor",
+ "test-release",
+ 1,
+ workflow,
+ commitId,
+ participants,
+ manifestHash,
+ 1,
+ List.of(),
+ List.of(),
+ List.of(),
+ "test-generation-config",
+ selector);
default -> throw new IllegalArgumentException("Unsupported test release schema");
};
}
@@ -328,6 +371,32 @@ private static AuthoredWorldReleaseAttestationEvidence closureSelector(
basis.worldStartLocationEvidence());
}
+ private static AuthoredWorldReleaseAttestationEvidence selectedFull(
+ AuthoredWorldReleaseAttestationEvidence basis,
+ List participants) {
+ return AuthoredWorldReleaseAttestationEvidence.createSelectedFull(
+ basis.targetNamespace(),
+ basis.descriptorResultDigest(),
+ basis.canonicalTenantId(),
+ basis.canonicalVersionId(),
+ basis.worldSlug(),
+ basis.authoredWorldSourceOperationId(),
+ basis.authoredWorldSourceEvidenceDigest(),
+ basis.launchDescriptorId(),
+ basis.publishedReleaseBundleRef(),
+ basis.versionStateEpoch(),
+ basis.publishWorkflowId(),
+ basis.commitId(),
+ participants,
+ basis.manifestHash(),
+ basis.manifestSchemaVersion(),
+ basis.requiredManifestAssetKeys(),
+ basis.artifactDigests(),
+ basis.commandDefinitions(),
+ basis.generationConfigRevision(),
+ basis.worldStartLocationEvidence());
+ }
+
private static void validateFrozenGraphProfile(JsonNode graph, int expectedSchemaVersion) {
try {
Method validator =
From a3969b00efe2b3477d6140b15d321972c455f70a Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Thu, 15 Oct 2026 23:51:31 +1300
Subject: [PATCH 02/55] docs: carry R21 selected release proof attribution
---
.../game-authoring-publishing-and-activation.md | 10 ++++------
1 file changed, 4 insertions(+), 6 deletions(-)
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index 5237194929..680d672375 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -22,15 +22,13 @@ The same closure prepares the actual Game Design original launch-descriptor and
This read-stage preparation also carries the strict shared attestation and terminal codecs, read-only World lifecycle support for the [canonical selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile), and a class-only guarded World fixture. The eight prepared code paths comprise the two shared models and their focused proofs, the World lifecycle reader and its unit proof, the guarded native fixture and its class-only build export. These postimages are source-prepared and unqualified; no factory execution or passing fresh writer/readback is claimed. Actual Game Design writer/storage integration and five-store proof remain in the full selected-owner successor. Public fresh/PENDING publication remains default-denied; no registration, activation or genuine creator, issuer, environment, release or continuous-protection authority is granted. All four genuine Gameplay handoffs remain open and broader Unit 1B remains paused.
-Qualification remains partial. R20 runs two focused native classes: all three Game Session authored-core cases pass with zero skips, while the 12-case Game Design Template configuration class has two failures and zero skips. Game Session proves the actual V37/V38 immutable pins, exact original live owner selectors, constructor and repository denials, foreign-key and cascading-truncate refusal, unchanged owner/launch/pin row bytes and versions, live-read expiry and V1013 retention/upgrade. These three focused cases do not constitute a fresh execution of all 325 Game Session native cases.
+Qualification remains partial. R21's focused gate freshly passes all 12 Game Design Template configuration cases with zero skips; the three Game Session authored-core cases retain their R20 pass and also pass in R21's fresh unfiltered native execution. Game Session proves the actual V37/V38 immutable pins, exact original live owner selectors, constructor and repository denials, foreign-key and cascading-truncate refusal, unchanged owner/launch/pin row bytes and versions, live-read expiry and V1013 retention/upgrade. Game Design now proves first publication reservation, concurrent winning read correlation, exact replay, association-conflict denial and original Template provenance using a real visible public-production `REALM_ENTRY_POLICY` mutation before its complete World-only successor. Upstream Account and World inputs remain stipulated component evidence; these tests do not establish genuine authority.
-The two Game Design cases reach first selected-owner reservation and correctly fail the full-Version requirement for one visible public-production realm policy. Their corrected fixture adds a real `REALM_ENTRY_POLICY` mutation and exact affected-scope epoch to each original Game Design binding. The actual source owner applies it before the complete World-only successor inherits the selected source. The first publication reservation, concurrent winning read correlation, exact replay, association-conflict denial and original Template provenance remain under test. Upstream Account and World inputs remain stipulated component evidence. Command and asset genesis, current selected snapshots and the qualified Template row are retained; the publication policy requirement is unchanged.
+Fresh tenant creation initializes persisted phase to `BACKFILLING`; ordinary synchronized source capture preserves that phase. The existing owner-local full-inventory validator explicitly performs persisted cutover, while a registered cutover owner and tenant-scoped phase RPC remain unimplemented. Empty or incomplete inventory refuses cutover. This internal primitive does not establish production launch enforcement. The explicit cutover, actual V1025 retained v1/v2 history and exact replay, strict command payload, frozen source provenance and typed SQL-read corrections pass in the native suite.
-Fresh tenant creation initializes persisted phase to `BACKFILLING`; ordinary synchronized source capture preserves that phase. The existing owner-local full-inventory validator explicitly performs persisted cutover, while a registered cutover owner and tenant-scoped phase RPC remain unimplemented. Empty or incomplete inventory refuses cutover. This internal primitive does not establish production launch enforcement. The explicit cutover, actual V1025 retained v1/v2 history and exact replay, strict command payload, frozen source provenance and typed SQL-read corrections retain their passing native attribution.
+R21's unfiltered gate terminates with failure after freshly executing 159 Game Design native cases with six failures and 325 Game Session native cases with 34 failures, all with zero skips. All 40 failures are PostgreSQL connection refusals at four mapped endpoints, including a Spring application-context failure cascade; the corrected owner cases pass. Game Design cross-service and static checks do not execute in this invocation. Archived cross-service 25 cases and one PostgreSQL refusal retain R15 attribution. Game Design's 616 units retain R17, Game Session's 2,389 units and 36 cross-service cases retain R14, World retains R13's 90 PostgreSQL cases and R12's 589 units and four compositions, and Common's 706 units retain R11. Documentation checks execute and pass. The remaining independent static and Game Design cross-service gates are pending; full-native qualification remains held.
-R20's full gate does not execute after the focused failure. The latest unfiltered R19 invocation executes 159 Game Design native cases with two failures and 325 Game Session native cases with one failure; it does not execute Game Design cross-service tests. Archived cross-service 25 cases and one PostgreSQL refusal retain R15 attribution. Game Design's 616 units retain R17, Game Session's 2,389 units and 36 cross-service cases retain R14, World retains R13's 90 PostgreSQL cases and R12's 589 units and four compositions, and Common's 706 units retain R11. The corrected focused and required unfiltered gates remain pending.
-
-The bounded R17 PostgreSQL diagnosis observes 60 exact run-owned endpoints. All 124 samples whose containers remain running before and after observation pass internal read-only SQL and host TCP/JDBC through localhost, IPv4 and IPv6. All probe failures overlap teardown, and none of the nine fresh native failures is a connection refusal. This does not establish a repair of the intermittent R15/R16 refusal: sparse probes can perturb the forwarding path, and historical failure windows remain unexplained. No readiness-policy or host-settings change is selected. A subsequent canonical gate remains pending; failed, stale and skipped results establish no qualification. The guarded World class-only artifact remains compiled and inspected, while its actual factory execution stays with the full-owner successor. Genuine immutable release production, current Account authority, World activation, actor placement and operational delivery remain open; broader Unit 1B stays paused. Canonical authoring and retention behavior remains owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations), and explicit cutover behavior by [Game Templates](../../architecture/microservices/game-design-service/game-templates.md#backfill-validation-and-runtime-usage).
+The bounded R17 PostgreSQL diagnosis observes 60 exact run-owned endpoints. All 124 samples whose containers remain running before and after observation pass internal read-only SQL and host TCP/JDBC through localhost, IPv4 and IPv6. All probe failures overlap teardown. This does not establish a repair: sparse probes can perturb the forwarding path, and historical failure windows remain unexplained. R21 uses no extra endpoint probes. Its passive exact-container evidence records Testcontainers' log-ready declaration followed by immediate host refusal and a passing adjacent endpoint, but the containers are removed before PID1, mapping and stop state can be recovered. The cause remains unknown; no readiness-policy or host-settings change is selected. Failed, stale and skipped results establish no qualification. The guarded World class-only artifact remains compiled and inspected, while its actual factory execution stays with the full-owner successor. Genuine immutable release production, current Account authority, World activation, actor placement and operational delivery remain open; broader Unit 1B stays paused. Canonical authoring and retention behavior remains owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations), and explicit cutover behavior by [Game Templates](../../architecture/microservices/game-design-service/game-templates.md#backfill-validation-and-runtime-usage).
### Original Account-ordered World source caller
From db38c928f603485ebd88626b8b5793b1b01bb9b6 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 00:00:34 +1300
Subject: [PATCH 03/55] test: carry safe retention trigger extraction and cross
proof
---
.../game-authoring-publishing-and-activation.md | 4 ++--
.../CanonicalInitialAdmissionRepositoryIntegrationTest.java | 2 +-
2 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index 680d672375..5b09c30058 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -26,9 +26,9 @@ Qualification remains partial. R21's focused gate freshly passes all 12 Game Des
Fresh tenant creation initializes persisted phase to `BACKFILLING`; ordinary synchronized source capture preserves that phase. The existing owner-local full-inventory validator explicitly performs persisted cutover, while a registered cutover owner and tenant-scoped phase RPC remain unimplemented. Empty or incomplete inventory refuses cutover. This internal primitive does not establish production launch enforcement. The explicit cutover, actual V1025 retained v1/v2 history and exact replay, strict command payload, frozen source provenance and typed SQL-read corrections pass in the native suite.
-R21's unfiltered gate terminates with failure after freshly executing 159 Game Design native cases with six failures and 325 Game Session native cases with 34 failures, all with zero skips. All 40 failures are PostgreSQL connection refusals at four mapped endpoints, including a Spring application-context failure cascade; the corrected owner cases pass. Game Design cross-service and static checks do not execute in this invocation. Archived cross-service 25 cases and one PostgreSQL refusal retain R15 attribution. Game Design's 616 units retain R17, Game Session's 2,389 units and 36 cross-service cases retain R14, World retains R13's 90 PostgreSQL cases and R12's 589 units and four compositions, and Common's 706 units retain R11. Documentation checks execute and pass. The remaining independent static and Game Design cross-service gates are pending; full-native qualification remains held.
+R21's unfiltered gate terminates with failure after freshly executing 159 Game Design native cases with six failures and 325 Game Session native cases with 34 failures, all with zero skips. All 40 failures are PostgreSQL connection refusals at four mapped endpoints, including a Spring application-context failure cascade; the corrected owner cases pass. Game Design cross-service and static checks do not execute in that invocation. R22 independently executes all 25 Game Design cross-service cases with zero failures, errors or skips and passes the previously missing Game Design static checks, formatting and documentation gates. Its only build failure is a nullable generic SQL extraction in the Game Session V1013 foreign-key test helper; a typed read preserves the exact trigger assertions, with its affected static recheck pending. Game Design's 616 units retain R17, Game Session's 2,389 units and 36 cross-service cases retain R14, World retains R13's 90 PostgreSQL cases and R12's 589 units and four compositions, and Common's 706 units retain R11. Documentation checks execute and pass. The remaining Game Session static checks pass apart from that single helper finding; full-native qualification remains held.
-The bounded R17 PostgreSQL diagnosis observes 60 exact run-owned endpoints. All 124 samples whose containers remain running before and after observation pass internal read-only SQL and host TCP/JDBC through localhost, IPv4 and IPv6. All probe failures overlap teardown. This does not establish a repair: sparse probes can perturb the forwarding path, and historical failure windows remain unexplained. R21 uses no extra endpoint probes. Its passive exact-container evidence records Testcontainers' log-ready declaration followed by immediate host refusal and a passing adjacent endpoint, but the containers are removed before PID1, mapping and stop state can be recovered. The cause remains unknown; no readiness-policy or host-settings change is selected. Failed, stale and skipped results establish no qualification. The guarded World class-only artifact remains compiled and inspected, while its actual factory execution stays with the full-owner successor. Genuine immutable release production, current Account authority, World activation, actor placement and operational delivery remain open; broader Unit 1B stays paused. Canonical authoring and retention behavior remains owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations), and explicit cutover behavior by [Game Templates](../../architecture/microservices/game-design-service/game-templates.md#backfill-validation-and-runtime-usage).
+The bounded R17 PostgreSQL diagnosis observes 60 exact run-owned endpoints. All 124 samples whose containers remain running before and after observation pass internal read-only SQL and host TCP/JDBC through localhost, IPv4 and IPv6. All probe failures overlap teardown. This does not establish a repair: sparse probes can perturb the forwarding path, and historical failure windows remain unexplained. R21 uses no extra endpoint probes. Its passive exact-container evidence records Testcontainers' log-ready declaration followed by immediate host refusal and a passing adjacent endpoint, but the containers are removed before PID1, mapping and stop state can be recovered. R22 passively captures all ten exact run-owned PostgreSQL lifecycles with no ownership gaps or observer errors; its passing cross-service run does not reproduce the refusal. The cause remains unknown; no readiness-policy or host-settings change is selected. Failed, stale and skipped results establish no qualification. The guarded World class-only artifact remains compiled and inspected, while its actual factory execution stays with the full-owner successor. Genuine immutable release production, current Account authority, World activation, actor placement and operational delivery remain open; broader Unit 1B stays paused. Canonical authoring and retention behavior remains owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations), and explicit cutover behavior by [Game Templates](../../architecture/microservices/game-design-service/game-templates.md#backfill-validation-and-runtime-usage).
### Original Account-ordered World source caller
diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java
index fbc3afa0eb..670e0fa2d3 100644
--- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java
+++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java
@@ -1522,7 +1522,7 @@ private static void assertV1013RetentionLaunchForeignKey(Fixture fixture) {
+ "AND launch_trigger.tgrelid = parent.oid ORDER BY launch_trigger.tgtype");
assertThat(launchTriggers).hasSize(2);
assertThat(launchTriggers)
- .extracting(row -> ((Number) row.get("tgtype")).intValue())
+ .extracting(row -> row.get("tgtype", Integer.class))
.containsExactly(9, 17);
assertThat(launchTriggers)
.allSatisfy(
From 8993cee4d5f7877b36f776ddf4931623dd4bb6ee Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 01:45:20 +1300
Subject: [PATCH 04/55] Use existing isolated visibility fixture for full owner
proof
---
.../SelectedFullOwnerPublicationPostgresIntegrationTest.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
index 2e28934359..4686907b49 100644
--- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
+++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
@@ -820,8 +820,8 @@ private static void completeGameDesignCommit(
? worldOutcome
: gameDesignApplied.ownerOutcome())
.toList();
- coordinator.advanceSourceVisibilityFence(
- binding, new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes));
+ net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup
+ .advanceIsolatedSourceVisibility(gds.dsl(), binding, outcomes);
coordinator.releaseApplicationSlot(binding);
return null;
});
From c267e55edde4426f97c4252cd493400362cd552c Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 02:21:59 +1300
Subject: [PATCH 05/55] Align full owner proof with retained source and client
APIs
---
...ame-authoring-publishing-and-activation.md | 2 +-
...ationEmptySelectedSourceIntakeService.java | 6 +-
...SelectedEmptyPublicationDigestService.java | 3 +-
...electedSourceIntakeCommandGrpcService.java | 6 +-
...edSourceIntakePostgresIntegrationTest.java | 50 ++++++++---
...takeRepositoryPostgresIntegrationTest.java | 6 +-
services/common-security/build.gradle.kts | 1 +
...tionSelectedSourceIntakeCommandClient.java | 6 +-
...titySelectedSourceIntakeCommandClient.java | 6 +-
...SelectedSourceIntakeCommandClientTest.java | 30 ++++---
...ctedSourceIntakeCommandClientMtlsTest.java | 30 ++++---
...ourceIntakeCommandClientLifecycleTest.java | 16 ++--
...ntityEmptySelectedSourceIntakeService.java | 6 +-
...SelectedEmptyPublicationDigestService.java | 3 +-
...electedSourceIntakeCommandGrpcService.java | 6 +-
...ntakeMigrationPostgresIntegrationTest.java | 60 +++++++++----
...takeRepositoryPostgresIntegrationTest.java | 3 +-
...tedSourceIntakeCommandGrpcServiceTest.java | 30 ++++---
...lectedDraftPublicationReadGrpcService.java | 2 +-
.../SelectedDraftControlPlaneDigest.java | 12 ++-
...ctedDraftPublicationDigestReadService.java | 19 ++--
.../impl/PublishedReleaseBundleContract.java | 3 +-
.../VersionPublishCommandServiceImpl.java | 3 +-
...nerPublicationPostgresIntegrationTest.java | 88 +++++++++++--------
...edDraftPublicationReadGrpcServiceTest.java | 13 ++-
.../SelectedDraftControlPlaneDigestTest.java | 14 +--
...DraftPublicationDigestReadServiceTest.java | 42 +++++++--
...rtSessionLaunchDescriptorProducerTest.java | 20 ++---
...ionTemplateAssociationReadServiceTest.java | 20 ++---
.../CompleteLaunchBindingServiceImplTest.java | 8 +-
...PublishedReleaseBundleServiceImplTest.java | 32 ++++---
.../VersionPublishCommandServiceImplTest.java | 77 ++++++++++------
...tionDigestReadPostgresIntegrationTest.java | 51 ++++++++---
33 files changed, 430 insertions(+), 244 deletions(-)
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index f0af29bbab..5e3ef5a910 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -12,7 +12,7 @@ The source candidate prepares complete selected-owner publication consumption un
Entity's new V1011 prepares the freshly founded empty selected source catalogue and its complete explicit family/equipment evidence; Automation's new V1003 prepares empty selected source retention. Both are forward additions over their current combined service/Saga parents. Their command/read transports and owner services remain standalone and unregistered. These are bounded empty-source components, not arbitrary Entity authoring, script publication or runtime rule execution. Inherited Account migration history and numbering are unchanged by this candidate.
-Current source and focused proof are unqualified and unrun. The native cross-owner composition is in preparation; no passing fresh full-profile writer, immutable readback or authenticated cross-owner result is claimed. Unit carriers, source/provenance inputs, creator/issuer/environment and PKI remain explicitly controlled where used. Retained historical release bytes keep their existing scoped read/retry meaning and are not upgraded into the new profile. Genuine creator, issuer, environment, immutable release and continuous-protection authority, runtime placement and operational delivery remain unavailable; all four genuine Gameplay handoffs remain open and broader Unit 1B stays paused. Consolidated source, migration, native composition, formatting and documentation qualification belongs to the lane orchestrator.
+The first R36 affected gate passes Automation 1,206, Common 818, shared-test-support 55, Entity 261 and Game Logic 117 unit cases with zero skips. Entity executes 11 native cases with three retained-upgrade setup failures; Automation executes nine cases with one initialization failure before its three migration cases. Those failures are numbered-version assertions encountering Flyway's null-version schema marker; the full row/xmin history assertions remain preserved. Common Security unit proof is blocked by a missing existing shared-fixture dependency; Game Design owner and Game Logic native proof are blocked by source/fixture API alignment errors. Corrected dependency, required Optional captures, typed client doubles and version-list fixtures are prepared but unqualified. The native five-store writer/readback composition has not run; no passing fresh full-profile writer, immutable readback or authenticated cross-owner result is claimed. Unit carriers, source/provenance inputs, creator/issuer/environment and PKI remain explicitly controlled where used. Retained historical release bytes keep their existing scoped read/retry meaning and are not upgraded into the new profile. Genuine creator, issuer, environment, immutable release and continuous-protection authority, runtime placement and operational delivery remain unavailable; all four genuine Gameplay handoffs remain open and broader Unit 1B stays paused. Consolidated source, migration, native composition, formatting and documentation qualification belongs to the lane orchestrator.
### Selected template publication and original launch reads
diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java
index ebc13edf76..60bd18b724 100644
--- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java
+++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java
@@ -3,14 +3,14 @@
import java.util.Objects;
import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs;
import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient;
import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence;
+import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt;
-import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
-import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
-import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient;
import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence;
import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence;
diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java
index cb8f34f820..b8a303c5ce 100644
--- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java
+++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java
@@ -112,7 +112,8 @@ private static void requireOriginalPublicationRequest(
|| !requested.tenantId().equals(retainedPublicationRequest.tenantId())
|| !requested.versionId().equals(retainedPublicationRequest.versionId())
|| !requested.publishRequestId().equals(retainedPublicationRequest.publishRequestId())
- || !requested.derivedWorkflowIdentity()
+ || !requested
+ .derivedWorkflowIdentity()
.equals(retainedPublicationRequest.derivedWorkflowIdentity())
|| !requested.requestDigest().equals(retainedPublicationRequest.requestDigest())) {
throw new IllegalStateException(
diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcService.java
index af2636c5b4..861a26db95 100644
--- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcService.java
+++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcService.java
@@ -7,12 +7,12 @@
import net.firedevops.firemud.automationscripting.v1.AutomationSelectedSourceIntakeCommandServiceGrpc;
import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceRequest;
import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceResponse;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
+import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence;
import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandGrpcCodec;
-import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
-import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
-import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
import net.firedevops.firemud.common.security.SessionContext;
import org.springframework.transaction.support.TransactionSynchronizationManager;
diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java
index 15fc641e55..481fd1c500 100644
--- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java
+++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java
@@ -8,9 +8,9 @@
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
-import java.util.UUID;
import java.util.List;
import java.util.Map;
+import java.util.UUID;
import net.firedevops.firemud.test.TestContainerImages;
import org.flywaydb.core.Flyway;
import org.jooq.DSLContext;
@@ -67,12 +67,19 @@ void migrateWithRetainedLegacyAuthoredRows() {
"INSERT INTO script_patch_base_bindings (tenant_id, script_patch_version, base_version_id) "
+ "VALUES ('103', 'legacy-patch', 203)");
- upgradeDsl.execute("INSERT INTO script_work_items (tenant_id, game_instance_id, region_id, region_epoch, entity_id, script_id, event_type, event_schema_version, script_patch_version, script_event_id, source_service, trigger_mode, failure_generation, next_eligible_at) VALUES ('retained-tenant', 'retained-instance', 'region', 1, 'entity', 'script', 'event', 'v1', 'retained-patch', 'retained-event', 'test-only', 'EXTERNAL', 7, NULL)");
- upgradeDsl.execute("INSERT INTO saga_instance (saga_name, state) VALUES ('retained-automation-source', 'PENDING')");
- upgradeDsl.execute("INSERT INTO saga_step (instance_id, name, status) SELECT id, 'retained-step', 'PENDING' FROM saga_instance WHERE saga_name = 'retained-automation-source'");
+ upgradeDsl.execute(
+ "INSERT INTO script_work_items (tenant_id, game_instance_id, region_id, region_epoch, entity_id, script_id, event_type, event_schema_version, script_patch_version, script_event_id, source_service, trigger_mode, failure_generation, next_eligible_at) VALUES ('retained-tenant', 'retained-instance', 'region', 1, 'entity', 'script', 'event', 'v1', 'retained-patch', 'retained-event', 'test-only', 'EXTERNAL', 7, NULL)");
+ upgradeDsl.execute(
+ "INSERT INTO saga_instance (saga_name, state) VALUES ('retained-automation-source', 'PENDING')");
+ upgradeDsl.execute(
+ "INSERT INTO saga_step (instance_id, name, status) SELECT id, 'retained-step', 'PENDING' FROM saga_instance WHERE saga_name = 'retained-automation-source'");
var parentRows = retainedParentRows(upgradeDsl);
var parentHistory = migrationHistory(upgradeDsl);
- assertThat(upgradeDsl.fetch("SELECT version FROM flyway_schema_history WHERE success ORDER BY installed_rank").getValues(0, String.class))
+ assertThat(
+ upgradeDsl
+ .fetch(
+ "SELECT version FROM flyway_schema_history WHERE success AND version IS NOT NULL ORDER BY installed_rank")
+ .getValues(0, String.class))
.containsExactly("1", "2", "3", "3.1", "3.2", "4", "1000", "1001", "1002");
Flyway.configure()
@@ -85,22 +92,43 @@ void migrateWithRetainedLegacyAuthoredRows() {
.migrate();
dsl = DSL.using(dataSource, SQLDialect.POSTGRES);
assertThat(retainedParentRows(dsl)).isEqualTo(parentRows);
- assertThat(migrationHistory(dsl).subList(0, parentHistory.size())).containsExactlyElementsOf(parentHistory);
- assertThat(dsl.fetchSingle("SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1").get(0, String.class)).isEqualTo("1003");
-
+ assertThat(migrationHistory(dsl).subList(0, parentHistory.size()))
+ .containsExactlyElementsOf(parentHistory);
+ assertThat(
+ dsl.fetchSingle(
+ "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1")
+ .get(0, String.class))
+ .isEqualTo("1003");
}
/** Synthetic retained SQL state only; no genuine script or runtime admission authority. */
private static Map> retainedParentRows(DSLContext source) {
Map> rows = new java.util.LinkedHashMap<>();
- for (String table : List.of("scripts", "script_event_bindings", "script_patch_base_bindings", "script_work_items", "saga_instance", "saga_step")) {
- rows.put(table, source.fetch("SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM " + table + " t ORDER BY to_jsonb(t)::TEXT").getValues(0, String.class));
+ for (String table :
+ List.of(
+ "scripts",
+ "script_event_bindings",
+ "script_patch_base_bindings",
+ "script_work_items",
+ "saga_instance",
+ "saga_step")) {
+ rows.put(
+ table,
+ source
+ .fetch(
+ "SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM "
+ + table
+ + " t ORDER BY to_jsonb(t)::TEXT")
+ .getValues(0, String.class));
}
return rows;
}
private static List migrationHistory(DSLContext source) {
- return source.fetch("SELECT to_jsonb(t)::TEXT || ':' || t.xmin::TEXT FROM flyway_schema_history t ORDER BY installed_rank").getValues(0, String.class);
+ return source
+ .fetch(
+ "SELECT to_jsonb(t)::TEXT || ':' || t.xmin::TEXT FROM flyway_schema_history t ORDER BY installed_rank")
+ .getValues(0, String.class);
}
@AfterAll
diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java
index 5a39dbc9c6..47f5380a92 100644
--- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java
+++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java
@@ -255,7 +255,8 @@ void retainsCanonicalEmptyCensusAndExactReadbackAcrossCorrelationIndependentRetr
byte[] corruptBytes = first.canonicalBytes();
corruptBytes[0] ^= 1;
- // The isolated test owner bypasses only V1003's immutable receipt-row trigger to model corruption.
+ // The isolated test owner bypasses only V1003's immutable receipt-row trigger to model
+ // corruption.
dsl.execute(
"ALTER TABLE automation_empty_selected_source_receipt "
+ "DISABLE TRIGGER trg_automation_empty_source_receipt_immutable");
@@ -364,8 +365,7 @@ void selectedEmptyPublicationReaderUsesTheRetainedTargetProofAndReturnsSchemaSix
receipt.targetNamespace(),
receipt.intakeRequestId())
.get(0, String.class);
- assertThat(rowAfterMismatchedPublicationRead)
- .isEqualTo(rowBeforeMismatchedPublicationRead);
+ assertThat(rowAfterMismatchedPublicationRead).isEqualTo(rowBeforeMismatchedPublicationRead);
}
@Test
diff --git a/services/common-security/build.gradle.kts b/services/common-security/build.gradle.kts
index ae0af42f53..d81fe85929 100644
--- a/services/common-security/build.gradle.kts
+++ b/services/common-security/build.gradle.kts
@@ -19,4 +19,5 @@ dependencies {
testImplementation(libs.spring.boot.starter.test)
testImplementation(testFixtures(project(":common-platform-core")))
+ testImplementation(testFixtures(project(":common-test-support")))
}
diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClient.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClient.java
index a7e3bfccb7..3d66af8cc7 100644
--- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClient.java
+++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClient.java
@@ -10,19 +10,19 @@
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLException;
import net.firedevops.firemud.automationscripting.v1.AutomationSelectedSourceIntakeCommandServiceGrpc;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
+import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence;
import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence.Request;
import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandGrpcCodec;
import net.firedevops.firemud.common.config.ServiceEndpointsProperties;
+import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient;
import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties;
import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials;
import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor;
-import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
-import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
-import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
import net.firedevops.firemud.common.security.SessionContext;
import org.springframework.transaction.support.TransactionSynchronizationManager;
diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClient.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClient.java
index 8095d0c4f7..40c8362216 100644
--- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClient.java
+++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClient.java
@@ -9,18 +9,18 @@
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLException;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
+import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
import net.firedevops.firemud.common.config.ServiceEndpointsProperties;
import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence;
import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandGrpcCodec;
+import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient;
import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties;
import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials;
import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor;
-import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
-import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
-import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
import net.firedevops.firemud.common.security.SessionContext;
import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeCommandServiceGrpc;
import org.springframework.transaction.support.TransactionSynchronizationManager;
diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java
index 6f11cf35c3..c147e4bb4b 100644
--- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java
+++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java
@@ -10,12 +10,12 @@
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
-import net.firedevops.firemud.common.config.ServiceEndpointsProperties;
-import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties;
-import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
+import net.firedevops.firemud.common.config.ServiceEndpointsProperties;
import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
+import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties;
+import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
import net.firedevops.firemud.common.security.SessionContext;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
@@ -108,13 +108,23 @@ void rejectsAmbientSqlSynchronizationAndEndUserContextBeforeTransport(@TempDir P
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("workload-only context");
SessionContext.clear();
- for (var producerContext : List.of(
- Context.current().withValue(AccountOriginalDraftOrderCredentials.CONTEXT_KEY,
- AccountOriginalDraftOrderCredentials.Credential.of("controlled-original-author")),
- Context.current().withValue(AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY,
- AccountGameLogicIntakeAuthorizationCredentials.Credential.of("controlled-game-logic-author")),
- Context.current().withValue(SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY,
- SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of("controlled-selected-intake-author")))) {
+ for (var producerContext :
+ List.of(
+ Context.current()
+ .withValue(
+ AccountOriginalDraftOrderCredentials.CONTEXT_KEY,
+ AccountOriginalDraftOrderCredentials.Credential.of(
+ "controlled-original-author")),
+ Context.current()
+ .withValue(
+ AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY,
+ AccountGameLogicIntakeAuthorizationCredentials.Credential.of(
+ "controlled-game-logic-author")),
+ Context.current()
+ .withValue(
+ SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY,
+ SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of(
+ "controlled-selected-intake-author")))) {
var previous = producerContext.attach();
try {
assertThatThrownBy(() -> client.retain(null))
diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java
index 9ca9565e18..dc224cc4d8 100644
--- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java
+++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java
@@ -36,16 +36,16 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
+import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
import net.firedevops.firemud.common.config.ServiceEndpointsProperties;
import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence;
import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandGrpcCodec;
+import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties;
import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor;
-import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
-import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
-import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
import net.firedevops.firemud.common.security.SessionContext;
import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeCommandServiceGrpc;
import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceRequest;
@@ -176,13 +176,23 @@ void namespaceSqlSynchronizationEndUserAndSelectedOrderAreDeniedBeforeTransport(
.hasMessageContaining("workload-only context");
SessionContext.clear();
- for (var producerContext : List.of(
- Context.current().withValue(AccountOriginalDraftOrderCredentials.CONTEXT_KEY,
- AccountOriginalDraftOrderCredentials.Credential.of("controlled-original-author")),
- Context.current().withValue(AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY,
- AccountGameLogicIntakeAuthorizationCredentials.Credential.of("controlled-game-logic-author")),
- Context.current().withValue(SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY,
- SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of("controlled-selected-intake-author")))) {
+ for (var producerContext :
+ List.of(
+ Context.current()
+ .withValue(
+ AccountOriginalDraftOrderCredentials.CONTEXT_KEY,
+ AccountOriginalDraftOrderCredentials.Credential.of(
+ "controlled-original-author")),
+ Context.current()
+ .withValue(
+ AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY,
+ AccountGameLogicIntakeAuthorizationCredentials.Credential.of(
+ "controlled-game-logic-author")),
+ Context.current()
+ .withValue(
+ SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY,
+ SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of(
+ "controlled-selected-intake-author")))) {
var previous = producerContext.attach();
try {
assertThatThrownBy(() -> client.retain(null))
diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandClientLifecycleTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandClientLifecycleTest.java
index 08d4370664..0d4d9bdacd 100644
--- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandClientLifecycleTest.java
+++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandClientLifecycleTest.java
@@ -27,11 +27,11 @@
import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
import net.firedevops.firemud.common.grpc.TlsCertificateWatcher;
import org.junit.jupiter.api.Timeout;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.junit.jupiter.api.parallel.Resources;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
/**
* Actual file-watcher lifecycle proof with readable placeholder certificate files and mocked
@@ -45,8 +45,7 @@ class SelectedSourceIntakeCommandClientLifecycleTest {
@Timeout(15)
@ResourceLock(Resources.SYSTEM_PROPERTIES)
void closeReleasesClientMonitorBeforeDrainingCertificateCallback(
- ClientKind kind, @TempDir Path directory)
- throws Exception {
+ ClientKind kind, @TempDir Path directory) throws Exception {
String previousReloadPolicy = System.getProperty(TLS_RELOAD_PROPERTY);
System.setProperty(TLS_RELOAD_PROPERTY, "true");
CountDownLatch releaseClientMonitor = new CountDownLatch(1);
@@ -170,7 +169,8 @@ private interface Initialize {
void run() throws Exception;
}
- private record ClientHandle(AbstractReloadingBlockingGrpcClient> client, Initialize initialize) {}
+ private record ClientHandle(
+ AbstractReloadingBlockingGrpcClient> client, Initialize initialize) {}
private enum ClientKind {
ENTITY,
@@ -182,11 +182,13 @@ ClientHandle create(
GrpcChannelFactory factory) {
return switch (this) {
case ENTITY -> {
- var client = new GrpcEntitySelectedSourceIntakeCommandClient(endpoints, tls, factory, "test");
+ var client =
+ new GrpcEntitySelectedSourceIntakeCommandClient(endpoints, tls, factory, "test");
yield new ClientHandle(client, client::init);
}
case AUTOMATION -> {
- var client = new GrpcAutomationSelectedSourceIntakeCommandClient(endpoints, tls, factory, "test");
+ var client =
+ new GrpcAutomationSelectedSourceIntakeCommandClient(endpoints, tls, factory, "test");
yield new ClientHandle(client, client::init);
}
};
diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java
index 4eed02753a..68345b3919 100644
--- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java
+++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java
@@ -2,15 +2,15 @@
import java.util.Objects;
import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs;
-import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
-import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient;
import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence;
+import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt;
+import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
-import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient;
import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence;
import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence;
diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java
index 0514ab806d..44104d5886 100644
--- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java
+++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java
@@ -103,7 +103,8 @@ private static void requireOriginalPublicationRequest(
|| !requested.tenantId().equals(retainedPublicationRequest.tenantId())
|| !requested.versionId().equals(retainedPublicationRequest.versionId())
|| !requested.publishRequestId().equals(retainedPublicationRequest.publishRequestId())
- || !requested.derivedWorkflowIdentity()
+ || !requested
+ .derivedWorkflowIdentity()
.equals(retainedPublicationRequest.derivedWorkflowIdentity())
|| !requested.requestDigest().equals(retainedPublicationRequest.requestDigest())) {
throw new IllegalStateException(
diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcService.java
index 56a872405c..a972bba35d 100644
--- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcService.java
+++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcService.java
@@ -4,12 +4,12 @@
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import java.util.Objects;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
+import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence;
import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandGrpcCodec;
-import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
-import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
-import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
import net.firedevops.firemud.common.security.SessionContext;
import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeCommandServiceGrpc;
import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceRequest;
diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java
index 41f1550fbb..826c325534 100644
--- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java
+++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java
@@ -65,13 +65,23 @@ void seedLegacyRowsBeforeV1011() {
+ "source_holder_kind, destination_holder_kind) "
+ "VALUES (61001, 99001, 1, 'MOVE', 'legacy-audit', 'UNKNOWN', 'UNKNOWN')");
- legacyDsl.execute("INSERT INTO entity_tenant_identities (canonical_tenant_uuid) VALUES (?)", UUID.randomUUID());
- legacyDsl.execute("INSERT INTO saga_instance (saga_name, state) VALUES ('retained-entity-source', 'PENDING')");
- legacyDsl.execute("INSERT INTO saga_step (instance_id, name, status) SELECT id, 'retained-step', 'PENDING' FROM saga_instance WHERE saga_name = 'retained-entity-source'");
+ legacyDsl.execute(
+ "INSERT INTO entity_tenant_identities (canonical_tenant_uuid) VALUES (?)",
+ UUID.randomUUID());
+ legacyDsl.execute(
+ "INSERT INTO saga_instance (saga_name, state) VALUES ('retained-entity-source', 'PENDING')");
+ legacyDsl.execute(
+ "INSERT INTO saga_step (instance_id, name, status) SELECT id, 'retained-step', 'PENDING' FROM saga_instance WHERE saga_name = 'retained-entity-source'");
var parentRows = retainedParentRows(legacyDsl);
var parentHistory = history(legacyDsl);
- assertThat(legacyDsl.fetch("SELECT version FROM flyway_schema_history WHERE success ORDER BY installed_rank")
- .getValues(0, String.class)).containsExactly("1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010");
+ assertThat(
+ legacyDsl
+ .fetch(
+ "SELECT version FROM flyway_schema_history WHERE success AND version IS NOT NULL ORDER BY installed_rank")
+ .getValues(0, String.class))
+ .containsExactly(
+ "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009",
+ "1010");
var flywayConfiguration =
Flyway.configure()
@@ -86,9 +96,13 @@ void seedLegacyRowsBeforeV1011() {
flywayConfiguration.load().migrate();
dsl = DSL.using(dataSource, SQLDialect.POSTGRES);
assertThat(retainedParentRows(dsl)).isEqualTo(parentRows);
- assertThat(history(dsl).subList(0, parentHistory.size())).containsExactlyElementsOf(parentHistory);
- assertThat(dsl.fetchSingle("SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1").get(0, String.class)).isEqualTo("1011");
-
+ assertThat(history(dsl).subList(0, parentHistory.size()))
+ .containsExactlyElementsOf(parentHistory);
+ assertThat(
+ dsl.fetchSingle(
+ "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1")
+ .get(0, String.class))
+ .isEqualTo("1011");
}
@AfterEach
@@ -175,18 +189,34 @@ void unassociatedLegacyKeysRemainWritable() {
/** Storage retention only; synthetic parent rows establish no authenticated owner authority. */
private static Map> retainedParentRows(DSLContext source) {
Map> rows = new java.util.LinkedHashMap<>();
- for (String table : List.of("characters", "items", "item_transfer_audits",
- "entity_tenant_identities", "entity_playable_state_namespace_scopes",
- "entity_preseeded_actor_assignment_operations", "entity_canonical_gameplay_roster_snapshots",
- "entity_canonical_gameplay_roster_snapshot_actors", "saga_instance", "saga_step")) {
- rows.put(table, source.fetch("SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM "
- + table + " t ORDER BY to_jsonb(t)::TEXT").getValues(0, String.class));
+ for (String table :
+ List.of(
+ "characters",
+ "items",
+ "item_transfer_audits",
+ "entity_tenant_identities",
+ "entity_playable_state_namespace_scopes",
+ "entity_preseeded_actor_assignment_operations",
+ "entity_canonical_gameplay_roster_snapshots",
+ "entity_canonical_gameplay_roster_snapshot_actors",
+ "saga_instance",
+ "saga_step")) {
+ rows.put(
+ table,
+ source
+ .fetch(
+ "SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM "
+ + table
+ + " t ORDER BY to_jsonb(t)::TEXT")
+ .getValues(0, String.class));
}
return rows;
}
private static List history(DSLContext source) {
- return source.fetch("SELECT to_jsonb(t)::TEXT || ':' || t.xmin::TEXT FROM flyway_schema_history t ORDER BY installed_rank")
+ return source
+ .fetch(
+ "SELECT to_jsonb(t)::TEXT || ':' || t.xmin::TEXT FROM flyway_schema_history t ORDER BY installed_rank")
.getValues(0, String.class);
}
diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java
index b10cd5545e..b999ef1e24 100644
--- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java
+++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java
@@ -304,8 +304,7 @@ void selectedEmptyPublicationReaderResolvesOnlyTheValidatedReceiptForTenantAndGa
receipt.targetNamespace(),
receipt.intakeRequestId())
.get(0, String.class);
- assertThat(rowAfterMismatchedPublicationRead)
- .isEqualTo(rowBeforeMismatchedPublicationRead);
+ assertThat(rowAfterMismatchedPublicationRead).isEqualTo(rowBeforeMismatchedPublicationRead);
}
@Test
diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcServiceTest.java
index 36b567d15d..8751bada9b 100644
--- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcServiceTest.java
+++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcServiceTest.java
@@ -15,12 +15,12 @@
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding;
+import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
+import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence;
import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandGrpcCodec;
-import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
-import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials;
-import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials;
import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence;
import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec;
import net.firedevops.firemud.common.security.SessionContext;
@@ -152,13 +152,23 @@ void rejectsEndUserSelectedOrderAndAmbientSqlBeforeMalformedEvidenceDecode() {
assertCode(endUser.failure(), Status.Code.PERMISSION_DENIED);
SessionContext.clear();
- for (Context credentialContext : List.of(
- Context.current().withValue(AccountOriginalDraftOrderCredentials.CONTEXT_KEY,
- AccountOriginalDraftOrderCredentials.Credential.of("synthetic-original-order")),
- Context.current().withValue(SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY,
- SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of("synthetic-owner-intake")),
- Context.current().withValue(AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY,
- AccountGameLogicIntakeAuthorizationCredentials.Credential.of("synthetic-logic-intake")))) {
+ for (Context credentialContext :
+ List.of(
+ Context.current()
+ .withValue(
+ AccountOriginalDraftOrderCredentials.CONTEXT_KEY,
+ AccountOriginalDraftOrderCredentials.Credential.of(
+ "synthetic-original-order")),
+ Context.current()
+ .withValue(
+ SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY,
+ SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of(
+ "synthetic-owner-intake")),
+ Context.current()
+ .withValue(
+ AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY,
+ AccountGameLogicIntakeAuthorizationCredentials.Credential.of(
+ "synthetic-logic-intake")))) {
var credentialPrevious = credentialContext.attach();
try {
var denied = new CapturingObserver(new AtomicReference<>());
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java
index a089d40757..ab1a45a9c8 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java
@@ -6,9 +6,9 @@
import java.util.Arrays;
import java.util.Objects;
import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
-import net.firedevops.firemud.common.security.SessionContext;
import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence;
import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec;
+import net.firedevops.firemud.common.security.SessionContext;
import net.firedevops.firemud.gamedesign.v1.GameDesignSelectedDraftPublicationReadServiceGrpc;
import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationRequest;
import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationResponse;
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java
index f6afc9aa30..77d9cc1e30 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java
@@ -58,8 +58,16 @@ public static SelectedDraftControlPlaneDigest compute(
new Snapshot("ASSET", sources.asset().binding(), sources.asset().canonicalBytes()),
new Snapshot(
"GAMEPLAY_SOURCE",
- sources.gameplayEvidence().orElseThrow(() -> new IllegalStateException("Selected gameplay source unavailable")).binding(),
- sources.gameplayEvidence().orElseThrow(() -> new IllegalStateException("Selected gameplay source unavailable")).canonicalBytes()),
+ sources
+ .gameplayEvidence()
+ .orElseThrow(
+ () -> new IllegalStateException("Selected gameplay source unavailable"))
+ .binding(),
+ sources
+ .gameplayEvidence()
+ .orElseThrow(
+ () -> new IllegalStateException("Selected gameplay source unavailable"))
+ .canonicalBytes()),
new Snapshot("BRANDING", branding.binding(), branding.canonicalBytes()),
new Snapshot(
"TEMPLATE_CONFIG", templateConfig.binding(), templateConfig.canonicalBytes()));
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java
index 62d86584fa..b654b1a691 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java
@@ -191,9 +191,9 @@ private static void requireCapture(
new byte[][] {
capture.command().operation().canonicalBytes(),
capture.policy().operation().canonicalBytes(),
- capture.asset().operation().canonicalBytes(),
- capture.branding().operation().canonicalBytes(),
- capture.templateConfig().operation().canonicalBytes()
+ capture.asset().orElseThrow(() -> new IllegalStateException("Complete frozen asset source capture unavailable")).operation().canonicalBytes(),
+ capture.branding().orElseThrow(() -> new IllegalStateException("Complete frozen branding source capture unavailable")).operation().canonicalBytes(),
+ capture.templateConfig().orElseThrow(() -> new IllegalStateException("Complete frozen templateConfig source capture unavailable")).operation().canonicalBytes()
}) {
if (!Arrays.equals(operationBytes, retainedOperation)) {
throw new IllegalStateException("Frozen source capture differs from exact operation");
@@ -220,7 +220,12 @@ private static void requireFrozenSources(
if (!selected.equals(synchronizedSources.command().binding())
|| !selected.equals(synchronizedSources.policy().binding())
|| !selected.equals(synchronizedSources.asset().binding())
- || !selected.equals(synchronizedSources.gameplayEvidence().orElseThrow(() -> new IllegalStateException("Selected gameplay source unavailable")).binding())
+ || !selected.equals(
+ synchronizedSources
+ .gameplayEvidence()
+ .orElseThrow(
+ () -> new IllegalStateException("Selected gameplay source unavailable"))
+ .binding())
|| !selected.equals(branding.binding())
|| !selected.equals(templateConfig.binding())
|| !Arrays.equals(
@@ -230,11 +235,11 @@ private static void requireFrozenSources(
frozen.policy().snapshot().canonicalBytes(),
synchronizedSources.policy().canonicalBytes())
|| !Arrays.equals(
- frozen.asset().snapshot().canonicalBytes(),
+ frozen.asset().orElseThrow(() -> new IllegalStateException("Complete frozen asset source capture unavailable")).snapshot().canonicalBytes(),
synchronizedSources.asset().canonicalBytes())
- || !Arrays.equals(frozen.branding().snapshot().canonicalBytes(), branding.canonicalBytes())
+ || !Arrays.equals(frozen.branding().orElseThrow(() -> new IllegalStateException("Complete frozen branding source capture unavailable")).snapshot().canonicalBytes(), branding.canonicalBytes())
|| !Arrays.equals(
- frozen.templateConfig().snapshot().canonicalBytes(), templateConfig.canonicalBytes())) {
+ frozen.templateConfig().orElseThrow(() -> new IllegalStateException("Complete frozen templateConfig source capture unavailable")).snapshot().canonicalBytes(), templateConfig.canonicalBytes())) {
throw new IllegalStateException(
"Frozen and synchronized source snapshots differ from the complete selected commit");
}
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java
index 318c586490..e17e9956de 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java
@@ -161,8 +161,7 @@ static void requireExactSelectorRetry(
WorldPublishedStartLocationEvidence evidence) {
if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(stored.attestationSchemaVersion())) {
requireSelectorBinding(stored);
- } else if (SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(
- stored.attestationSchemaVersion())) {
+ } else if (SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(stored.attestationSchemaVersion())) {
requireSelectedFullBinding(stored);
} else {
throw new IllegalStateException(
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java
index 7febbd4dbb..f10dcf70c9 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java
@@ -660,7 +660,8 @@ private void assertCommittedBundleEvidence(
PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(readback.bundle());
assertSelectedCommit(request, readback.bundle().participantDigests());
if (isSelectedReleaseBundle(readback.bundle())) {
- publishGateService.assertSelectedGatePassed(versionDto, readback.bundle().participantDigests());
+ publishGateService.assertSelectedGatePassed(
+ versionDto, readback.bundle().participantDigests());
} else {
publishGateService.assertGatePassed(versionDto, readback.bundle().participantDigests());
}
diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
index 4686907b49..635f40aff7 100644
--- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
+++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
@@ -57,7 +57,6 @@
import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding;
import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence;
-import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence;
import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence;
import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository;
import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedEmptyPublicationDigestGrpcReceiver;
@@ -266,14 +265,13 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema
automationAuthorization,
new SelectedOwnerWorldInventoryReadEvidence(
automationWorldRead, worldOwners.inventoryEvidence()));
- var automationRepository =
- new AutomationEmptySelectedSourceIntakeRepository(automation.dsl());
+ var automationRepository = new AutomationEmptySelectedSourceIntakeRepository(automation.dsl());
var automationReceipt =
automationRepository.retainFresh(
automationInputs,
net.firedevops.firemud.common.automation.sourceintake
.AutomationEmptySelectedSourceIntakeReceipt.requestDigest(
- NAMESPACE, automationAuthorization, worldOwners.freezeEvidence()));
+ NAMESPACE, automationAuthorization, worldOwners.freezeEvidence()));
assertThat(
automationRepository
.read(automationReceipt.targetNamespace(), automationReceipt.intakeRequestId())
@@ -286,7 +284,7 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema
automationInputs,
net.firedevops.firemud.common.automation.sourceintake
.AutomationEmptySelectedSourceIntakeReceipt.requestDigest(
- NAMESPACE, automationAuthorization, worldOwners.freezeEvidence()))
+ NAMESPACE, automationAuthorization, worldOwners.freezeEvidence()))
.canonicalBytes())
.containsExactly(automationReceipt.canonicalBytes());
@@ -599,8 +597,7 @@ private static Draft createDraft(Store gds) {
private static AuthoredWorldSourceEvidence registerControlledWorldSource(
Store gds, TargetProof target) {
var repository = new GameAuthoredWorldSourceRepository(gds.dsl());
- return gds
- .write()
+ return gds.write()
.execute(
ignored ->
repository.register(
@@ -649,7 +646,8 @@ private static DraftCommitBinding selectedCommit(Store gds, TargetProof target)
WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK,
WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE,
WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING)) {
- inbound.addFamilyCounts(WorldInboundSourceFamilyCount.newBuilder().setFamily(family).setCount(0));
+ inbound.addFamilyCounts(
+ WorldInboundSourceFamilyCount.newBuilder().setFamily(family).setCount(0));
}
var declaration =
WorldFreshGraphDeclaration.newBuilder()
@@ -665,17 +663,32 @@ private static DraftCommitBinding selectedCommit(Store gds, TargetProof target)
.build();
var mutations =
List.of(
- mutation(commitId, roomId, regionId, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM)
+ mutation(
+ commitId,
+ roomId,
+ regionId,
+ WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM)
.setRoom(
RoomDesignMutation.newBuilder()
.setName("Controlled starting room")
.setZoneId(zoneId.toString())
.setDescription("Controlled World owner input"))
.build(),
- mutation(commitId, zoneId, regionId, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE)
- .setZone(ZoneDesignMutation.newBuilder().setName("Controlled zone").setRegionId(regionId.toString()))
+ mutation(
+ commitId,
+ zoneId,
+ regionId,
+ WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE)
+ .setZone(
+ ZoneDesignMutation.newBuilder()
+ .setName("Controlled zone")
+ .setRegionId(regionId.toString()))
.build(),
- mutation(commitId, regionId, regionId, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION)
+ mutation(
+ commitId,
+ regionId,
+ regionId,
+ WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION)
.setRegion(
RegionDesignMutation.newBuilder()
.setName("Controlled region")
@@ -694,7 +707,10 @@ private static DraftCommitBinding selectedCommit(Store gds, TargetProof target)
+ "\"effects\":[]}";
revisions.add(
new RevisionPayload(
- "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, CommandSource.upsertPayload(commandJson)));
+ "0",
+ UUID.randomUUID(),
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ CommandSource.upsertPayload(commandJson)));
units.add(
new AffectedUnit(
Owner.GAME_DESIGN_CONTROL_PLANE,
@@ -725,7 +741,8 @@ private static DraftCommitBinding selectedCommit(Store gds, TargetProof target)
UUID.fromString(mutation.getLogicalRevisionId()),
Owner.WORLD_MANAGEMENT,
JsonFormat.printer().omittingInsignificantWhitespace().print(mutation)));
- String family = mutation.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", "");
+ String family =
+ mutation.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", "");
units.add(
new AffectedUnit(
Owner.WORLD_MANAGEMENT,
@@ -775,7 +792,8 @@ private static void applyGameDesignCommit(Store gds, DraftCommitBinding binding)
.resolve(binding.target(), DraftBaseReference.parse(binding.baseCommitId()));
sources.claimReviewed(binding, reviewed);
coordinator.claimApplicationSlot(binding);
- for (Owner owner : binding.requiredOwners()) coordinator.markOwnerInProgress(binding, owner);
+ for (Owner owner : binding.requiredOwners())
+ coordinator.markOwnerInProgress(binding, owner);
return null;
});
}
@@ -786,8 +804,7 @@ private static void completeGameDesignCommit(
net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphAppliedResult worldApplied) {
var coordinator = new DraftCommitCoordinatorRepository(gds.dsl());
var sources = new GameDesignSourceRepository(gds.dsl());
- var gameDesignApplied =
- gds.write().execute(ignored -> sources.apply(binding));
+ var gameDesignApplied = gds.write().execute(ignored -> sources.apply(binding));
var worldOutcome =
new DraftCommitCoordinatorRepository.OwnerOutcome(
Owner.WORLD_MANAGEMENT,
@@ -839,10 +856,7 @@ private static AccountPublicationAuthorizationBinding controlledAccountBinding(
}
private static SelectedOwnerIntakeAuthorizationBinding selectedOwnerAuthorization(
- Store gds,
- AuthoredDraftPublishSelection selection,
- Owner recipient,
- UUID actor) {
+ Store gds, AuthoredDraftPublishSelection selection, Owner recipient, UUID actor) {
var scope =
new SelectedOwnerIntakeSourceReadScope(
recipient,
@@ -852,15 +866,15 @@ private static SelectedOwnerIntakeAuthorizationBinding selectedOwnerAuthorizatio
UUID.randomUUID(),
actor,
selection.selectedCommit());
- var content =
- new GameDesignSourceRepository(gds.dsl()).requireSelectedOwnerIntakeSource(scope);
+ var content = new GameDesignSourceRepository(gds.dsl()).requireSelectedOwnerIntakeSource(scope);
return new SelectedOwnerIntakeAuthorizationBinding(
content, controlledAccountSources(actor, selection.target().canonicalTenantId()));
}
private static List controlledAccountSources(
UUID actor, UUID tenant) {
- byte[] evidence = "TEST_ONLY controlled upstream Account source input".getBytes(StandardCharsets.UTF_8);
+ byte[] evidence =
+ "TEST_ONLY controlled upstream Account source input".getBytes(StandardCharsets.UTF_8);
return List.of(
new DraftAuthorizationFenceBinding.SourceEvidence(
DraftAuthorizationFenceBinding.SourceKind.ACCOUNT,
@@ -913,7 +927,10 @@ private static VersionDto versionDto(Version version) {
private static ExportedAssetManifest controlledEmptyManifest() throws Exception {
String hash =
- HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest("[]".getBytes(StandardCharsets.UTF_8)));
+ HexFormat.of()
+ .formatHex(
+ java.security.MessageDigest.getInstance("SHA-256")
+ .digest("[]".getBytes(StandardCharsets.UTF_8)));
return new ExportedAssetManifest("sha256:" + hash, 1, List.of(), List.of());
}
@@ -935,8 +952,7 @@ private static Server ownerServer(ProofPki pki, String service, io.grpc.Bindable
var identity = pki.server(service);
return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0))
.sslContext(
- GrpcSslContexts.forServer(
- identity.certificate().toFile(), identity.key().toFile())
+ GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile())
.trustManager(pki.ca().toFile())
.clientAuth(ClientAuth.REQUIRE)
.build())
@@ -955,7 +971,8 @@ private static Store store(
String service, String schemaPrefix, PostgreSQLContainer> postgres, boolean saga) {
String schema = schemaPrefix + "_" + UUID.randomUUID().toString().replace("-", "");
var dataSource =
- new DriverManagerDataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword());
+ new DriverManagerDataSource(
+ postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword());
dataSource.setSchema(schema);
String history = "flyway_schema_history_" + service.replace('-', '_');
var flyway =
@@ -975,7 +992,8 @@ private static Store store(
.setTransactionalLock(false);
}
flyway.load().migrate();
- DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES);
+ DSLContext dsl =
+ DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES);
var manager = new DataSourceTransactionManager(dataSource);
return new Store(schema, dsl, manager);
}
@@ -1004,7 +1022,8 @@ private static Path repositoryRoot() {
if (Files.isDirectory(current.resolve("services/game-design-service"))) return current;
current = current.getParent();
}
- throw new IllegalStateException("Repository root is unavailable for current-default migrations");
+ throw new IllegalStateException(
+ "Repository root is unavailable for current-default migrations");
}
private record Draft(Version version, TargetProof target) {}
@@ -1112,11 +1131,7 @@ CommonGrpcClientProperties client(String service) {
}
private static Identity issue(
- Path root,
- String service,
- boolean server,
- KeyPair caKeys,
- X509Certificate caCertificate)
+ Path root, String service, boolean server, KeyPair caKeys, X509Certificate caCertificate)
throws Exception {
KeyPair pair = keys();
var now = java.time.Instant.now();
@@ -1136,7 +1151,8 @@ private static Identity issue(
builder.addExtension(
Extension.extendedKeyUsage,
false,
- new ExtendedKeyUsage(server ? KeyPurposeId.id_kp_serverAuth : KeyPurposeId.id_kp_clientAuth));
+ new ExtendedKeyUsage(
+ server ? KeyPurposeId.id_kp_serverAuth : KeyPurposeId.id_kp_clientAuth));
builder.addExtension(
Extension.subjectAlternativeName,
false,
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java
index 5d01a70df2..f80e35ae13 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java
@@ -20,12 +20,12 @@
import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload;
import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
-import net.firedevops.firemud.common.security.SessionContext;
import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding;
import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent;
import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence;
import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence;
import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec;
+import net.firedevops.firemud.common.security.SessionContext;
import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationRequest;
import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationResponse;
import net.firedevops.firemud.gamedesign.v1.SelectedDraftPublicationStatus;
@@ -89,11 +89,16 @@ void bothAllowedWorkloadPeersRejectAuthenticatedCallerContextBeforeDecodeOrStora
for (String caller : List.of("account-service", "world-management-service")) {
for (var roles : List.of(List.of(), List.of("ROLE_ADMIN"))) {
SessionContext.setContext("controlled-authenticated-user", roles, java.util.Map.of());
- assertFailure(invokeAs(service, wireRequest(), peer(caller, NAMESPACE)),
+ assertFailure(
+ invokeAs(service, wireRequest(), peer(caller, NAMESPACE)),
Status.Code.PERMISSION_DENIED);
// Malformed bytes cannot reach decoding through an otherwise admitted workload peer.
- assertFailure(invokeAs(service, ReadSelectedDraftPublicationRequest.getDefaultInstance(),
- peer(caller, NAMESPACE)), Status.Code.PERMISSION_DENIED);
+ assertFailure(
+ invokeAs(
+ service,
+ ReadSelectedDraftPublicationRequest.getDefaultInstance(),
+ peer(caller, NAMESPACE)),
+ Status.Code.PERMISSION_DENIED);
}
}
verifyNoInteractions(repository);
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
index 7481d9a05f..ad260f1929 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
@@ -66,8 +66,8 @@ void changedSnapshotOrSelectedBindingChangesContentDigest() throws Exception {
new GameDesignSourceRepository.SynchronizedSources(
originalSources.command(),
originalSources.policy(),
- changedAsset,
- originalSources.gameplay(),
+ Optional.of(changedAsset),
+ originalSources.gameplayEvidence(),
originalSources.branding(),
originalSources.templateConfig());
assertThat(SelectedDraftControlPlaneDigest.compute(selected, changedSnapshot).contentDigest())
@@ -94,16 +94,16 @@ void missingBrandingOrTemplateFamilyCannotBeTreatedAsAnEmptySnapshot() throws Ex
new GameDesignSourceRepository.SynchronizedSources(
complete.command(),
complete.policy(),
- complete.asset(),
- complete.gameplay(),
+ complete.assetEvidence(),
+ complete.gameplayEvidence(),
Optional.empty(),
complete.templateConfig());
var missingTemplate =
new GameDesignSourceRepository.SynchronizedSources(
complete.command(),
complete.policy(),
- complete.asset(),
- complete.gameplay(),
+ complete.assetEvidence(),
+ complete.gameplayEvidence(),
complete.branding(),
Optional.empty());
@@ -211,6 +211,6 @@ private static GameDesignSourceRepository.SynchronizedSources sources(
new TemplateConfigSourceSnapshot(
binding, "0", null, UUID.fromString("66666666-6666-4666-8666-666666666666"), List.of());
return new GameDesignSourceRepository.SynchronizedSources(
- command, policy, asset, gameplay, Optional.of(branding), Optional.of(template));
+ command, policy, Optional.of(asset), Optional.of(gameplay), Optional.of(branding), Optional.of(template));
}
}
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
index fc3d6a7ab8..2bb3ee9ee7 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
@@ -196,8 +196,8 @@ void missingSourceFamiliesAndFrozenSnapshotMismatchCannotProveAnEmptyOrDifferent
new GameDesignSourceRepository.SynchronizedSources(
fixture.sources().command(),
fixture.sources().policy(),
- fixture.sources().asset(),
- fixture.sources().gameplay(),
+ fixture.sources().assetEvidence(),
+ fixture.sources().gameplayEvidence(),
Optional.empty(),
fixture.sources().templateConfig());
when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId()))
@@ -223,8 +223,8 @@ void missingSourceFamiliesAndFrozenSnapshotMismatchCannotProveAnEmptyOrDifferent
new GameDesignSourceRepository.SynchronizedSources(
fixture.sources().command(),
fixture.sources().policy(),
- changedAsset,
- fixture.sources().gameplay(),
+ Optional.of(changedAsset),
+ fixture.sources().gameplayEvidence(),
fixture.sources().branding(),
fixture.sources().templateConfig());
when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId()))
@@ -251,6 +251,30 @@ void missingSourceFamiliesAndFrozenSnapshotMismatchCannotProveAnEmptyOrDifferent
assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, request));
}
+ @Test
+ void absentFrozenFamilyDeniesBeforeSynchronizedSourceRead() throws Exception {
+ var fixture = fixture();
+ var request = request(fixture.operation());
+ when(transactions.getTransaction(any())).thenReturn(transactionStatus);
+ when(owner.read(request.derivedWorkflowIdentity()))
+ .thenReturn(Optional.of(new GameDesignPublicationOperationRepository.Readback(
+ fixture.operation(), "PENDING", new byte[] {1})));
+ var complete = fixture.capture();
+ var missingFamilies = List.of(
+ new GameDesignSourceRepository.Capture(complete.command(), complete.policy(),
+ Optional.empty(), complete.branding(), complete.templateConfig()),
+ new GameDesignSourceRepository.Capture(complete.command(), complete.policy(),
+ complete.asset(), Optional.empty(), complete.templateConfig()),
+ new GameDesignSourceRepository.Capture(complete.command(), complete.policy(),
+ complete.asset(), complete.branding(), Optional.empty()));
+ var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE);
+ for (var missing : missingFamilies) {
+ when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(missing));
+ assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, request));
+ }
+ verify(owner, never()).readSynchronized(any(), any());
+ }
+
private static PublicationDigestRequestBinding request(GameDesignPublicationOperation operation) {
var selection = operation.account().input().selection();
return PublicationDigestRequestBinding.full(
@@ -276,10 +300,10 @@ private static Fixture fixture() throws Exception {
new GameDesignSourceRepository.Capture(
new CommandSnapshot.Capture(operation, sources.command()),
new RealmPolicySnapshot.Capture(operation, sources.policy()),
- new AssetSnapshot.Capture(operation, sources.asset()),
- new BrandingSourceSnapshot.Capture(operation, sources.branding().orElseThrow()),
- new TemplateConfigSourceSnapshot.Capture(
- operation, sources.templateConfig().orElseThrow()));
+ Optional.of(new AssetSnapshot.Capture(operation, sources.asset())),
+ Optional.of(new BrandingSourceSnapshot.Capture(operation, sources.branding().orElseThrow())),
+ Optional.of(new TemplateConfigSourceSnapshot.Capture(
+ operation, sources.templateConfig().orElseThrow())));
return new Fixture(operation, binding, sources, capture);
}
@@ -307,7 +331,7 @@ private static GameDesignSourceRepository.SynchronizedSources sources(
new TemplateConfigSourceSnapshot(
binding, "0", null, UUID.fromString("66666666-6666-4666-8666-666666666666"), List.of());
return new GameDesignSourceRepository.SynchronizedSources(
- command, policy, asset, gameplay, Optional.of(branding), Optional.of(template));
+ command, policy, Optional.of(asset), Optional.of(gameplay), Optional.of(branding), Optional.of(template));
}
private static void assertCode(Status.Code expected, Runnable action) {
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java
index dc2d8722bb..3686134d19 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java
@@ -62,21 +62,11 @@ class StartSessionLaunchDescriptorProducerTest {
@Test
void selectedReleaseMatchingRetainsV2AndAcceptsOnlyFullV4() {
- assertThat(
- StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v2"))
- .isTrue();
- assertThat(
- StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v4"))
- .isTrue();
- assertThat(
- StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v1"))
- .isFalse();
- assertThat(
- StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v3"))
- .isFalse();
- assertThat(
- StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema(null))
- .isFalse();
+ assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v2")).isTrue();
+ assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v4")).isTrue();
+ assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v1")).isFalse();
+ assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v3")).isFalse();
+ assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema(null)).isFalse();
}
@Test
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java
index 847eee28b3..0c1087186f 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java
@@ -46,21 +46,11 @@ class StartSessionTemplateAssociationReadServiceTest {
@Test
void configuredReleaseSelectionRetainsV2AndAcceptsOnlyFullV4() {
- assertThat(
- StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v2"))
- .isTrue();
- assertThat(
- StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v4"))
- .isTrue();
- assertThat(
- StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v1"))
- .isFalse();
- assertThat(
- StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v3"))
- .isFalse();
- assertThat(
- StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema(null))
- .isFalse();
+ assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v2")).isTrue();
+ assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v4")).isTrue();
+ assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v1")).isFalse();
+ assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v3")).isFalse();
+ assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema(null)).isFalse();
}
@Test
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java
index 261e398e65..83970e9071 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java
@@ -78,9 +78,11 @@ void selectedFullV4ReadbackUsesExactEntityAndAutomationSchemas() throws Exceptio
assertEquals(
AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION,
result.releaseAttestation().schemaVersion());
- assertEquals(List.of(4, 3, 1, 6, 2), result.releaseAttestation().participantDigests().stream()
- .map(AuthoredWorldReleaseAttestationEvidence.Participant::digestSchemaVersion)
- .toList());
+ assertEquals(
+ List.of(4, 3, 1, 6, 2),
+ result.releaseAttestation().participantDigests().stream()
+ .map(AuthoredWorldReleaseAttestationEvidence.Participant::digestSchemaVersion)
+ .toList());
assertEquals(selector, result.releaseAttestation().worldStartLocationEvidence());
result.releaseAttestation().requireValid(descriptor);
verifyReadOnlyCallsOnly();
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
index c8e5b18710..4e8d17d95e 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
@@ -43,8 +43,9 @@ class PublishedReleaseBundleServiceImplTest {
private PublishedReleaseBundleServiceImpl service;
@Test
- void selectedFullV4PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutResolvingDefaults()
- throws Exception {
+ void
+ selectedFullV4PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutResolvingDefaults()
+ throws Exception {
var evidence = selectorEvidence();
var participants =
PublishedWorldSelectorFixtures.participants(
@@ -138,8 +139,7 @@ void exactRetainedV2RetryStillReturnsItsOriginalSelectorWithoutWriting() throws
new ObjectMapper().writeValueAsString(List.of(validCommandDefinition())));
retained.setWorldPublishedStartLocationEvidenceJson(
new String(evidence.canonicalBytes(), StandardCharsets.UTF_8));
- when(repository.findByTenantIdAndVersionId("tenant-1", 7L))
- .thenReturn(Optional.of(retained));
+ when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(retained));
when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any()))
.thenReturn(List.of(validCommandDefinition()));
@@ -228,7 +228,9 @@ void selectedFullV4RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChanged
emptyManifest(),
"genrev-1",
PublishedWorldSelectorFixtures.participants(
- 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION),
+ 7L,
+ evidence,
+ AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION),
evidence))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Selected-full");
@@ -301,14 +303,14 @@ private WorldPublishedStartLocationEvidence selectorEvidence(int digestSchemaVer
throws Exception {
var base =
PublishedWorldSelectorFixtures.evidence(
- new TargetProof(
- sourceIdentity().getCanonicalTenantId(),
- sourceIdentity().getCanonicalVersionId(),
- 7L,
- "tenant-1",
- 42L,
- "tenant-1",
- "NEW_GAME_ROW"));
+ new TargetProof(
+ sourceIdentity().getCanonicalTenantId(),
+ sourceIdentity().getCanonicalVersionId(),
+ 7L,
+ "tenant-1",
+ 42L,
+ "tenant-1",
+ "NEW_GAME_ROW"));
var original = base.request();
var request =
new WorldPublishedStartLocationEvidence.Request(
@@ -617,7 +619,9 @@ private void assertSelectedCommandsRejected(
emptyManifest(),
"genrev-1",
PublishedWorldSelectorFixtures.participants(
- 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION),
+ 7L,
+ evidence,
+ AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION),
evidence));
org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any());
}
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java
index cad1e4f037..b4f8b9d525 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java
@@ -65,8 +65,8 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.ValueSource;
import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mapstruct.factory.Mappers;
import org.mockito.InOrder;
import org.mockito.Mock;
@@ -248,8 +248,9 @@ void legacyPendingAttemptIsDeniedBeforeReadbackOrMutation() {
assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus());
verify(publishAttemptRepository, never()).save(any(PublishAttempt.class));
verify(authoredSelections, never()).reserve(any(PublishIntent.class));
- verify(publishGateService, never()).collectSelectedFullVersionParticipantDigests(
- any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class));
+ verify(publishGateService, never())
+ .collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class));
verify(publishGateService, never())
.collectFullVersionParticipantDigests(
any(VersionDto.class), any(String.class), any(String.class));
@@ -1798,8 +1799,9 @@ void freshFullVersionPublishIsDeniedBeforeAnyMutation() {
verify(publishAttemptService, never()).executeFullVersionTransaction(any());
verify(publishAttemptService, never())
.createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class));
- verify(publishGateService, never()).collectSelectedFullVersionParticipantDigests(
- any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class));
+ verify(publishGateService, never())
+ .collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class));
verify(publishGateService, never())
.collectFullVersionParticipantDigests(
any(VersionDto.class), any(String.class), any(String.class));
@@ -1918,20 +1920,26 @@ void privateMechanicsUsesDurablySelectedVersionWithoutSequenceReservation() {
reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request);
assertEquals("SUCCEEDED", snapshot.status());
- var selectedBinding = org.mockito.ArgumentCaptor.forClass(PublicationDigestRequestBinding.class);
- verify(publishGateService).collectSelectedFullVersionParticipantDigests(
- any(VersionDto.class), selectedBinding.capture(),
- org.mockito.ArgumentMatchers.eq(request.publishWorkflowId()));
- var expectedBinding = PublicationDigestRequestBinding.full(
- fixture.reservation().selection().intent().canonicalTenantId().toString(),
- version.getId().toString(), request.publishRequestId());
+ var selectedBinding =
+ org.mockito.ArgumentCaptor.forClass(PublicationDigestRequestBinding.class);
+ verify(publishGateService)
+ .collectSelectedFullVersionParticipantDigests(
+ any(VersionDto.class),
+ selectedBinding.capture(),
+ org.mockito.ArgumentMatchers.eq(request.publishWorkflowId()));
+ var expectedBinding =
+ PublicationDigestRequestBinding.full(
+ fixture.reservation().selection().intent().canonicalTenantId().toString(),
+ version.getId().toString(),
+ request.publishRequestId());
assertEquals(expectedBinding.tenantId(), selectedBinding.getValue().tenantId());
assertEquals(expectedBinding.versionId(), selectedBinding.getValue().versionId());
assertEquals(expectedBinding.scopeKind(), selectedBinding.getValue().scopeKind());
assertEquals(expectedBinding.requestDigest(), selectedBinding.getValue().requestDigest());
assertEquals(request.publishWorkflowId(), selectedBinding.getValue().derivedWorkflowIdentity());
- verify(publishGateService, never()).collectFullVersionParticipantDigests(
- any(VersionDto.class), any(String.class), any(String.class));
+ verify(publishGateService, never())
+ .collectFullVersionParticipantDigests(
+ any(VersionDto.class), any(String.class), any(String.class));
verify(publishGateService, never()).assertGatePassed(any(VersionDto.class), any(List.class));
assertEquals(10L, snapshot.versionId());
@@ -2111,7 +2119,8 @@ void freshSelectedPublishRejectsLegacyOwnerVectorBeforeGateOrAssetEffects() thro
reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request());
assertEquals("FAILED", snapshot.status());
- verify(publishGateService, never()).assertSelectedGatePassed(any(VersionDto.class), any(List.class));
+ verify(publishGateService, never())
+ .assertSelectedGatePassed(any(VersionDto.class), any(List.class));
verify(versionAssetArtifactService, never())
.stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class));
verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class));
@@ -2121,25 +2130,35 @@ void freshSelectedPublishRejectsLegacyOwnerVectorBeforeGateOrAssetEffects() thro
@ValueSource(ints = {0, 1, 2, 3, 4})
void freshSelectedPublishRefusesEachNoncanonicalParticipantSchemaBeforeEffects(int index)
throws Exception {
- // These unit carriers are controlled; the actual contract validator must reject every downgrade.
+ // These unit carriers are controlled; the actual contract validator must reject every
+ // downgrade.
SelectedPublishFixture fixture = selectedPublishFixture(1);
var vector = new java.util.ArrayList<>(participantDigests());
var original = vector.get(index);
- vector.set(index, new PublishParticipantDigestDto(
- original.participantKey(), original.scopeValue(), original.baseVersionId(),
- original.appliedCommitId(), original.contentDigest(), original.digestSchemaVersion() + 1,
- original.abilitySchemaDigest(), original.errorCode(), original.errorMessage()));
+ vector.set(
+ index,
+ new PublishParticipantDigestDto(
+ original.participantKey(),
+ original.scopeValue(),
+ original.baseVersionId(),
+ original.appliedCommitId(),
+ original.contentDigest(),
+ original.digestSchemaVersion() + 1,
+ original.abilitySchemaDigest(),
+ original.errorCode(),
+ original.errorMessage()));
when(publishGateService.collectSelectedFullVersionParticipantDigests(
- any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
+ any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)))
.thenReturn(vector);
var result = reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request());
assertEquals("FAILED", result.status());
- verify(publishGateService, never()).assertSelectedGatePassed(any(VersionDto.class), any(List.class));
+ verify(publishGateService, never())
+ .assertSelectedGatePassed(any(VersionDto.class), any(List.class));
verify(publishGateService, never()).assertGatePassed(any(VersionDto.class), any(List.class));
- verify(versionAssetArtifactService, never()).stageExport(
- any(String.class), any(Long.class), any(Integer.class), any(String.class));
+ verify(versionAssetArtifactService, never())
+ .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class));
verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class));
}
@@ -2952,7 +2971,15 @@ private List participantDigests() {
null,
null),
new PublishParticipantDigestDto(
- "AUTOMATION_SCRIPTING", "10", null, appliedCommitId, "e".repeat(64), 6, null, null, null),
+ "AUTOMATION_SCRIPTING",
+ "10",
+ null,
+ appliedCommitId,
+ "e".repeat(64),
+ 6,
+ null,
+ null,
+ null),
new PublishParticipantDigestDto(
"GAME_DESIGN_CONTROL_PLANE",
"10",
diff --git a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java
index 4992a3887d..ae394a1aa5 100644
--- a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java
+++ b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java
@@ -1,6 +1,11 @@
package net.firedevops.firemud.gamelogic.sourceintake;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
import io.grpc.Context;
import io.grpc.stub.StreamObserver;
@@ -13,6 +18,8 @@
import net.firedevops.firemud.common.authoring.DraftCommitBinding;
import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding;
import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence;
+import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient;
+import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient;
import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding;
import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadGrpcCodec;
import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest;
@@ -66,17 +73,23 @@ void actualRetainedOwnerFlowsThroughDigestServiceAndReceiverWithExactReplayAndRe
throws Exception {
var f = fixture();
var authorization = authorization();
- var intake = new GameLogicGameplayRuleIntakeService(f.repository(), f.manager(),
- request -> {
- assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
- return new GameLogicIntakeAuthorizationReadEvidence(request);
- },
- request -> {
- assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
- assertThat(request.proof()).isInstanceOf(GameplayRuleSourceReadEvidence.Finalized.class);
- assertThat(request.proof().canonicalBytes()).isEqualTo(authorization.canonicalBytes());
- return new GameplayRuleSourceReadEvidence(request, authorization.source());
- }, NAMESPACE);
+ var accountReader = mock(GameLogicIntakeAuthorizationReadClient.class);
+ when(accountReader.read(any())).thenAnswer(invocation -> {
+ GameLogicIntakeAuthorizationReadEvidence.Request request = invocation.getArgument(0);
+ assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
+ assertThat(request.binding().canonicalBytes()).isEqualTo(authorization.canonicalBytes());
+ return new GameLogicIntakeAuthorizationReadEvidence(request);
+ });
+ var sourceReader = mock(GameplayRuleSourceReadClient.class);
+ when(sourceReader.read(any())).thenAnswer(invocation -> {
+ GameplayRuleSourceReadEvidence.Request request = invocation.getArgument(0);
+ assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
+ assertThat(request.proof()).isInstanceOf(GameplayRuleSourceReadEvidence.Finalized.class);
+ assertThat(request.proof().canonicalBytes()).isEqualTo(authorization.canonicalBytes());
+ return new GameplayRuleSourceReadEvidence(request, authorization.source());
+ });
+ var intake = new GameLogicGameplayRuleIntakeService(
+ f.repository(), f.manager(), accountReader, sourceReader, NAMESPACE);
var terminal = asGameDesign(() -> intake.retain(authorization));
var reader = new GameLogicPublicationSourceReadService(f.repository(), NAMESPACE);
var digest = new GameLogicDraftDesignDigestServiceImpl(reader);
@@ -115,10 +128,20 @@ void actualRetainedOwnerFlowsThroughDigestServiceAndReceiverWithExactReplayAndRe
assertThat(row(f, authorization.operationId())).isEqualTo(retained);
var abortedAuthorization = authorization();
- var abortOwner = new GameLogicGameplayRuleIntakeService(f.repository(), f.manager(),
- ignored -> { throw new AssertionError("Abort must not read Account"); },
- ignored -> { throw new AssertionError("Abort must not read GD source"); }, NAMESPACE);
+ var abortAccountReader = mock(GameLogicIntakeAuthorizationReadClient.class);
+ when(abortAccountReader.read(any())).thenAnswer(invocation -> {
+ GameLogicIntakeAuthorizationReadEvidence.Request heldRequest = invocation.getArgument(0);
+ assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
+ assertThat(heldRequest.binding().canonicalBytes())
+ .isEqualTo(abortedAuthorization.canonicalBytes());
+ return new GameLogicIntakeAuthorizationReadEvidence(heldRequest);
+ });
+ var unusedAbortSourceReader = mock(GameplayRuleSourceReadClient.class);
+ var abortOwner = new GameLogicGameplayRuleIntakeService(
+ f.repository(), f.manager(), abortAccountReader, unusedAbortSourceReader, NAMESPACE);
asGameDesign(() -> abortOwner.abort(abortedAuthorization));
+ verify(abortAccountReader).read(any());
+ verify(unusedAbortSourceReader, never()).read(any());
String aborted = row(f, abortedAuthorization.operationId());
assertError(receiver, GameLogicPublicationSourceReadGrpcCodec.toRequest(publicationBinding(abortedAuthorization)), "FAILED_PRECONDITION");
assertThat(row(f, abortedAuthorization.operationId())).isEqualTo(aborted);
From 3b8c3465236c4175ed8c38d5f41add2b1220070f Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 02:47:34 +1300
Subject: [PATCH 06/55] Align selected-full GDS proof fixtures with canonical
owner APIs
---
...ame-authoring-publishing-and-activation.md | 2 +-
...ctedDraftPublicationDigestReadService.java | 56 ++++-
...nerPublicationPostgresIntegrationTest.java | 14 +-
.../client/WorldManagementClientTest.java | 5 +-
.../SelectedDraftControlPlaneDigestTest.java | 8 +-
...DraftPublicationDigestReadServiceTest.java | 49 +++--
.../service/impl/GameLogicGrpcService.java | 2 +-
...tionDigestReadPostgresIntegrationTest.java | 195 ++++++++++++------
8 files changed, 240 insertions(+), 91 deletions(-)
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index 5e3ef5a910..01abdbc882 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -12,7 +12,7 @@ The source candidate prepares complete selected-owner publication consumption un
Entity's new V1011 prepares the freshly founded empty selected source catalogue and its complete explicit family/equipment evidence; Automation's new V1003 prepares empty selected source retention. Both are forward additions over their current combined service/Saga parents. Their command/read transports and owner services remain standalone and unregistered. These are bounded empty-source components, not arbitrary Entity authoring, script publication or runtime rule execution. Inherited Account migration history and numbering are unchanged by this candidate.
-The first R36 affected gate passes Automation 1,206, Common 818, shared-test-support 55, Entity 261 and Game Logic 117 unit cases with zero skips. Entity executes 11 native cases with three retained-upgrade setup failures; Automation executes nine cases with one initialization failure before its three migration cases. Those failures are numbered-version assertions encountering Flyway's null-version schema marker; the full row/xmin history assertions remain preserved. Common Security unit proof is blocked by a missing existing shared-fixture dependency; Game Design owner and Game Logic native proof are blocked by source/fixture API alignment errors. Corrected dependency, required Optional captures, typed client doubles and version-list fixtures are prepared but unqualified. The native five-store writer/readback composition has not run; no passing fresh full-profile writer, immutable readback or authenticated cross-owner result is claimed. Unit carriers, source/provenance inputs, creator/issuer/environment and PKI remain explicitly controlled where used. Retained historical release bytes keep their existing scoped read/retry meaning and are not upgraded into the new profile. Genuine creator, issuer, environment, immutable release and continuous-protection authority, runtime placement and operational delivery remain unavailable; all four genuine Gameplay handoffs remain open and broader Unit 1B stays paused. Consolidated source, migration, native composition, formatting and documentation qualification belongs to the lane orchestrator.
+The first R36 affected gate passes Automation 1,206, Common 818, shared-test-support 55, Entity 261 and Game Logic 117 unit cases with zero skips; those unchanged scopes remain up-to-date in R38. R38 freshly passes all 178 Common Security unit cases and 23 native PostgreSQL cases: Entity 11, Automation 11 and Game Logic one, with zero failures, errors or skips. The corrected numbered migration checks exclude Flyway's null-version schema marker while complete pre/post row and xmin history assertions retain it. Passive capture identifies all six run-owned PostgreSQL containers without ownership gaps or observer errors. Game Design unit and five-store cross-service proof remain unrun because fixture compilation exposes three unit and seven cross-service API alignment errors. Corrections use the existing public gate constructor, owner policy type, Game Design mutation proto, exact request/epoch accessors and canonical source-content decoder; no owner authority or proof assertion is weakened. The native five-store writer/readback composition has not run; no passing fresh full-profile writer, immutable readback or authenticated cross-owner result is claimed. Unit carriers, source/provenance inputs, creator/issuer/environment and PKI remain explicitly controlled where used. Retained historical release bytes keep their existing scoped read/retry meaning and are not upgraded into the new profile. Genuine creator, issuer, environment, immutable release and continuous-protection authority, runtime placement and operational delivery remain unavailable; all four genuine Gameplay handoffs remain open and broader Unit 1B/corpus stays paused.
### Selected template publication and original launch reads
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java
index b654b1a691..34515ff8a2 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java
@@ -191,9 +191,29 @@ private static void requireCapture(
new byte[][] {
capture.command().operation().canonicalBytes(),
capture.policy().operation().canonicalBytes(),
- capture.asset().orElseThrow(() -> new IllegalStateException("Complete frozen asset source capture unavailable")).operation().canonicalBytes(),
- capture.branding().orElseThrow(() -> new IllegalStateException("Complete frozen branding source capture unavailable")).operation().canonicalBytes(),
- capture.templateConfig().orElseThrow(() -> new IllegalStateException("Complete frozen templateConfig source capture unavailable")).operation().canonicalBytes()
+ capture
+ .asset()
+ .orElseThrow(
+ () ->
+ new IllegalStateException("Complete frozen asset source capture unavailable"))
+ .operation()
+ .canonicalBytes(),
+ capture
+ .branding()
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Complete frozen branding source capture unavailable"))
+ .operation()
+ .canonicalBytes(),
+ capture
+ .templateConfig()
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Complete frozen templateConfig source capture unavailable"))
+ .operation()
+ .canonicalBytes()
}) {
if (!Arrays.equals(operationBytes, retainedOperation)) {
throw new IllegalStateException("Frozen source capture differs from exact operation");
@@ -235,11 +255,35 @@ private static void requireFrozenSources(
frozen.policy().snapshot().canonicalBytes(),
synchronizedSources.policy().canonicalBytes())
|| !Arrays.equals(
- frozen.asset().orElseThrow(() -> new IllegalStateException("Complete frozen asset source capture unavailable")).snapshot().canonicalBytes(),
+ frozen
+ .asset()
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Complete frozen asset source capture unavailable"))
+ .snapshot()
+ .canonicalBytes(),
synchronizedSources.asset().canonicalBytes())
- || !Arrays.equals(frozen.branding().orElseThrow(() -> new IllegalStateException("Complete frozen branding source capture unavailable")).snapshot().canonicalBytes(), branding.canonicalBytes())
|| !Arrays.equals(
- frozen.templateConfig().orElseThrow(() -> new IllegalStateException("Complete frozen templateConfig source capture unavailable")).snapshot().canonicalBytes(), templateConfig.canonicalBytes())) {
+ frozen
+ .branding()
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Complete frozen branding source capture unavailable"))
+ .snapshot()
+ .canonicalBytes(),
+ branding.canonicalBytes())
+ || !Arrays.equals(
+ frozen
+ .templateConfig()
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Complete frozen templateConfig source capture unavailable"))
+ .snapshot()
+ .canonicalBytes(),
+ templateConfig.canonicalBytes())) {
throw new IllegalStateException(
"Frozen and synchronized source snapshots differ from the complete selected commit");
}
diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
index 635f40aff7..d1cbe6704a 100644
--- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
+++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
@@ -96,7 +96,7 @@
import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation;
import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType;
import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation;
-import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationRevision;
+import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision;
import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType;
import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration;
import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount;
@@ -226,8 +226,7 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema
selectedOwnerAuthorization(gds, selection, Owner.ENTITY_MANAGEMENT, sourceScopeActor);
var entityWorldRead =
SelectedOwnerWorldInventoryReadEvidence.create(
- NAMESPACE, entityAuthorization, worldOwners.freezeEvidence())
- .request();
+ NAMESPACE, entityAuthorization, worldOwners.freezeEvidence());
var entityInputs =
new SelectedOwnerEmptySourceInputs(
entityAuthorization,
@@ -258,8 +257,7 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema
selectedOwnerAuthorization(gds, selection, Owner.AUTOMATION_SCRIPTING, sourceScopeActor);
var automationWorldRead =
SelectedOwnerWorldInventoryReadEvidence.create(
- NAMESPACE, automationAuthorization, worldOwners.freezeEvidence())
- .request();
+ NAMESPACE, automationAuthorization, worldOwners.freezeEvidence());
var automationInputs =
new SelectedOwnerEmptySourceInputs(
automationAuthorization,
@@ -822,7 +820,7 @@ private static void completeGameDesignCommit(
epoch.scopeType(),
epoch.scopeId(),
epoch.expectedEpoch(),
- epoch.appliedEpoch()))
+ epoch.resultingEpoch()))
.toList());
gds.write()
.execute(
@@ -866,7 +864,9 @@ private static SelectedOwnerIntakeAuthorizationBinding selectedOwnerAuthorizatio
UUID.randomUUID(),
actor,
selection.selectedCommit());
- var content = new GameDesignSourceRepository(gds.dsl()).requireSelectedOwnerIntakeSource(scope);
+ var export = new GameDesignSourceRepository(gds.dsl()).requireSelectedOwnerIntakeSource(scope);
+ var content = net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent.fromStored(
+ export.canonicalBytes(), scope, export.digest());
return new SelectedOwnerIntakeAuthorizationBinding(
content, controlledAccountSources(actor, selection.target().canonicalTenantId()));
}
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldManagementClientTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldManagementClientTest.java
index 751407ebb9..c6965d8f0f 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldManagementClientTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldManagementClientTest.java
@@ -122,7 +122,10 @@ private static List participants(PublishParticipant
}
private static PublishGateServiceImpl gate() {
- return new PublishGateServiceImpl(null, null, null, null, null);
+ return new PublishGateServiceImpl(
+ null, null, null, null, null,
+ mock(org.jooq.DSLContext.class),
+ mock(org.springframework.transaction.PlatformTransactionManager.class), "");
}
private static VersionDto version() {
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
index ad260f1929..d8e2cb94f0 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
@@ -9,7 +9,6 @@
import net.firedevops.firemud.common.authoring.DraftCommitBinding;
import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload;
import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof;
-import net.firedevops.firemud.common.gamedesign.RealmPolicySource;
import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
import org.junit.jupiter.api.Test;
@@ -211,6 +210,11 @@ private static GameDesignSourceRepository.SynchronizedSources sources(
new TemplateConfigSourceSnapshot(
binding, "0", null, UUID.fromString("66666666-6666-4666-8666-666666666666"), List.of());
return new GameDesignSourceRepository.SynchronizedSources(
- command, policy, Optional.of(asset), Optional.of(gameplay), Optional.of(branding), Optional.of(template));
+ command,
+ policy,
+ Optional.of(asset),
+ Optional.of(gameplay),
+ Optional.of(branding),
+ Optional.of(template));
}
}
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
index 2bb3ee9ee7..0f07102dd3 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
@@ -17,7 +17,6 @@
import java.util.UUID;
import net.firedevops.firemud.common.authoring.DraftCommitBinding;
import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof;
-import net.firedevops.firemud.common.gamedesign.RealmPolicySource;
import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
@@ -257,16 +256,31 @@ void absentFrozenFamilyDeniesBeforeSynchronizedSourceRead() throws Exception {
var request = request(fixture.operation());
when(transactions.getTransaction(any())).thenReturn(transactionStatus);
when(owner.read(request.derivedWorkflowIdentity()))
- .thenReturn(Optional.of(new GameDesignPublicationOperationRepository.Readback(
- fixture.operation(), "PENDING", new byte[] {1})));
+ .thenReturn(
+ Optional.of(
+ new GameDesignPublicationOperationRepository.Readback(
+ fixture.operation(), "PENDING", new byte[] {1})));
var complete = fixture.capture();
- var missingFamilies = List.of(
- new GameDesignSourceRepository.Capture(complete.command(), complete.policy(),
- Optional.empty(), complete.branding(), complete.templateConfig()),
- new GameDesignSourceRepository.Capture(complete.command(), complete.policy(),
- complete.asset(), Optional.empty(), complete.templateConfig()),
- new GameDesignSourceRepository.Capture(complete.command(), complete.policy(),
- complete.asset(), complete.branding(), Optional.empty()));
+ var missingFamilies =
+ List.of(
+ new GameDesignSourceRepository.Capture(
+ complete.command(),
+ complete.policy(),
+ Optional.empty(),
+ complete.branding(),
+ complete.templateConfig()),
+ new GameDesignSourceRepository.Capture(
+ complete.command(),
+ complete.policy(),
+ complete.asset(),
+ Optional.empty(),
+ complete.templateConfig()),
+ new GameDesignSourceRepository.Capture(
+ complete.command(),
+ complete.policy(),
+ complete.asset(),
+ complete.branding(),
+ Optional.empty()));
var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE);
for (var missing : missingFamilies) {
when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(missing));
@@ -301,9 +315,11 @@ private static Fixture fixture() throws Exception {
new CommandSnapshot.Capture(operation, sources.command()),
new RealmPolicySnapshot.Capture(operation, sources.policy()),
Optional.of(new AssetSnapshot.Capture(operation, sources.asset())),
- Optional.of(new BrandingSourceSnapshot.Capture(operation, sources.branding().orElseThrow())),
- Optional.of(new TemplateConfigSourceSnapshot.Capture(
- operation, sources.templateConfig().orElseThrow())));
+ Optional.of(
+ new BrandingSourceSnapshot.Capture(operation, sources.branding().orElseThrow())),
+ Optional.of(
+ new TemplateConfigSourceSnapshot.Capture(
+ operation, sources.templateConfig().orElseThrow())));
return new Fixture(operation, binding, sources, capture);
}
@@ -331,7 +347,12 @@ private static GameDesignSourceRepository.SynchronizedSources sources(
new TemplateConfigSourceSnapshot(
binding, "0", null, UUID.fromString("66666666-6666-4666-8666-666666666666"), List.of());
return new GameDesignSourceRepository.SynchronizedSources(
- command, policy, Optional.of(asset), Optional.of(gameplay), Optional.of(branding), Optional.of(template));
+ command,
+ policy,
+ Optional.of(asset),
+ Optional.of(gameplay),
+ Optional.of(branding),
+ Optional.of(template));
}
private static void assertCode(Status.Code expected, Runnable action) {
diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java
index 7569ea5a1d..0a934af274 100644
--- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java
+++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java
@@ -6,8 +6,8 @@
import io.grpc.stub.StreamObserver;
import io.micrometer.core.annotation.Timed;
import io.micrometer.core.instrument.MeterRegistry;
-import net.firedevops.firemud.common.grpc.GrpcAppErrors;
import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadGrpcCodec;
+import net.firedevops.firemud.common.grpc.GrpcAppErrors;
import net.firedevops.firemud.common.security.AdminAuthorizationException;
import net.firedevops.firemud.common.security.GameplaySessionAttestationException;
import net.firedevops.firemud.common.security.GameplaySessionAttestationService;
diff --git a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java
index ae394a1aa5..def0bf73a4 100644
--- a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java
+++ b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java
@@ -17,13 +17,13 @@
import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding;
import net.firedevops.firemud.common.authoring.DraftCommitBinding;
import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding;
-import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence;
import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient;
-import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient;
+import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence;
import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding;
import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadGrpcCodec;
import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest;
import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource;
+import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient;
import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence;
import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
@@ -48,16 +48,18 @@
import org.testcontainers.junit.jupiter.Testcontainers;
/**
- * Actual current-default GL retention, immutable owner read, digest service and receiver.
- * Account authorization and GD source responses are explicitly controlled upstream inputs;
- * direct handler invocation supplies controlled peer context, not authenticated socket/TLS proof.
- * No production composition, genuine upstream authority or registration is established.
+ * Actual current-default GL retention, immutable owner read, digest service and receiver. Account
+ * authorization and GD source responses are explicitly controlled upstream inputs; direct handler
+ * invocation supplies controlled peer context, not authenticated socket/TLS proof. No production
+ * composition, genuine upstream authority or registration is established.
*/
@Testcontainers(disabledWithoutDocker = true)
@SuppressWarnings("resource")
class GameLogicPublicationDigestReadPostgresIntegrationTest {
private static final String NAMESPACE = "test";
- @Container static final PostgreSQLContainer> POSTGRES =
+
+ @Container
+ static final PostgreSQLContainer> POSTGRES =
new PostgreSQLContainer<>(TestContainerImages.postgres());
@AfterEach
@@ -74,22 +76,30 @@ void actualRetainedOwnerFlowsThroughDigestServiceAndReceiverWithExactReplayAndRe
var f = fixture();
var authorization = authorization();
var accountReader = mock(GameLogicIntakeAuthorizationReadClient.class);
- when(accountReader.read(any())).thenAnswer(invocation -> {
- GameLogicIntakeAuthorizationReadEvidence.Request request = invocation.getArgument(0);
- assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
- assertThat(request.binding().canonicalBytes()).isEqualTo(authorization.canonicalBytes());
- return new GameLogicIntakeAuthorizationReadEvidence(request);
- });
+ when(accountReader.read(any()))
+ .thenAnswer(
+ invocation -> {
+ GameLogicIntakeAuthorizationReadEvidence.Request request = invocation.getArgument(0);
+ assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
+ assertThat(request.binding().canonicalBytes())
+ .isEqualTo(authorization.canonicalBytes());
+ return new GameLogicIntakeAuthorizationReadEvidence(request);
+ });
var sourceReader = mock(GameplayRuleSourceReadClient.class);
- when(sourceReader.read(any())).thenAnswer(invocation -> {
- GameplayRuleSourceReadEvidence.Request request = invocation.getArgument(0);
- assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
- assertThat(request.proof()).isInstanceOf(GameplayRuleSourceReadEvidence.Finalized.class);
- assertThat(request.proof().canonicalBytes()).isEqualTo(authorization.canonicalBytes());
- return new GameplayRuleSourceReadEvidence(request, authorization.source());
- });
- var intake = new GameLogicGameplayRuleIntakeService(
- f.repository(), f.manager(), accountReader, sourceReader, NAMESPACE);
+ when(sourceReader.read(any()))
+ .thenAnswer(
+ invocation -> {
+ GameplayRuleSourceReadEvidence.Request request = invocation.getArgument(0);
+ assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
+ assertThat(request.proof())
+ .isInstanceOf(GameplayRuleSourceReadEvidence.Finalized.class);
+ assertThat(request.proof().canonicalBytes())
+ .isEqualTo(authorization.canonicalBytes());
+ return new GameplayRuleSourceReadEvidence(request, authorization.source());
+ });
+ var intake =
+ new GameLogicGameplayRuleIntakeService(
+ f.repository(), f.manager(), accountReader, sourceReader, NAMESPACE);
var terminal = asGameDesign(() -> intake.retain(authorization));
var reader = new GameLogicPublicationSourceReadService(f.repository(), NAMESPACE);
var digest = new GameLogicDraftDesignDigestServiceImpl(reader);
@@ -100,74 +110,135 @@ void actualRetainedOwnerFlowsThroughDigestServiceAndReceiverWithExactReplayAndRe
var response = asGameDesign(() -> invoke(receiver, request));
assertThat(response.hasError()).isFalse();
- var evidence = GameLogicPublicationSourceReadGrpcCodec.fromResponse(binding, response, NAMESPACE);
+ var evidence =
+ GameLogicPublicationSourceReadGrpcCodec.fromResponse(binding, response, NAMESPACE);
assertThat(evidence.terminal().canonicalBytes()).isEqualTo(terminal.canonicalBytes());
- assertThat(evidence.terminal().selectedSourceBytes()).isEqualTo(authorization.source().canonicalBytes());
+ assertThat(evidence.terminal().selectedSourceBytes())
+ .isEqualTo(authorization.source().canonicalBytes());
assertThat(evidence.manifestDigest()).isEqualTo(authorization.source().manifest().digest());
- assertThat(asGameDesign(() -> digest.getDraftDesignDigest(binding)).terminalBytes()).isEqualTo(terminal.canonicalBytes());
+ assertThat(asGameDesign(() -> digest.getDraftDesignDigest(binding)).terminalBytes())
+ .isEqualTo(terminal.canonicalBytes());
assertThat(asGameDesign(() -> invoke(receiver, request))).isEqualTo(response);
- var missing = copyAuthorization(authorization, UUID.randomUUID(), authorization.fenceId(), authorization.intakeRequestId(), authorization.source());
- assertError(receiver, GameLogicPublicationSourceReadGrpcCodec.toRequest(publicationBinding(missing)), "FAILED_PRECONDITION");
- var changed = copyAuthorization(authorization, authorization.operationId(), UUID.randomUUID(), authorization.intakeRequestId(), authorization.source());
- assertError(receiver, GameLogicPublicationSourceReadGrpcCodec.toRequest(publicationBinding(changed)), "ALREADY_EXISTS");
- assertError(receiver, request.toBuilder().clearSourceReadBinding().clearSourceReadBindingDigest().build(), "INVALID_ARGUMENT");
- assertError(receiver(new GameLogicDraftDesignDigestServiceImpl()), request, "UNSUPPORTED_SCOPE");
+ var missing =
+ copyAuthorization(
+ authorization,
+ UUID.randomUUID(),
+ authorization.fenceId(),
+ authorization.intakeRequestId(),
+ authorization.source());
+ assertError(
+ receiver,
+ GameLogicPublicationSourceReadGrpcCodec.toRequest(publicationBinding(missing)),
+ "FAILED_PRECONDITION");
+ var changed =
+ copyAuthorization(
+ authorization,
+ authorization.operationId(),
+ UUID.randomUUID(),
+ authorization.intakeRequestId(),
+ authorization.source());
+ assertError(
+ receiver,
+ GameLogicPublicationSourceReadGrpcCodec.toRequest(publicationBinding(changed)),
+ "ALREADY_EXISTS");
+ assertError(
+ receiver,
+ request.toBuilder().clearSourceReadBinding().clearSourceReadBindingDigest().build(),
+ "INVALID_ARGUMENT");
+ assertError(
+ receiver(new GameLogicDraftDesignDigestServiceImpl()), request, "UNSUPPORTED_SCOPE");
- var wrongPeer = GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/world-management-service").orElseThrow();
+ var wrongPeer =
+ GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/world-management-service")
+ .orElseThrow();
var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, wrongPeer);
var previous = context.attach();
- try { assertThat(invoke(receiver, request).getError().getCode()).isEqualTo("PERMISSION_DENIED"); }
- finally { context.detach(previous); }
+ try {
+ assertThat(invoke(receiver, request).getError().getCode()).isEqualTo("PERMISSION_DENIED");
+ } finally {
+ context.detach(previous);
+ }
SessionContext.setContext("controlled-user", List.of(), Map.of());
assertError(receiver, request, "PERMISSION_DENIED");
SessionContext.clear();
TransactionSynchronizationManager.setActualTransactionActive(true);
- try { assertError(receiver, request, "FAILED_PRECONDITION"); }
- finally { TransactionSynchronizationManager.setActualTransactionActive(false); }
+ try {
+ assertError(receiver, request, "FAILED_PRECONDITION");
+ } finally {
+ TransactionSynchronizationManager.setActualTransactionActive(false);
+ }
assertThat(row(f, authorization.operationId())).isEqualTo(retained);
var abortedAuthorization = authorization();
var abortAccountReader = mock(GameLogicIntakeAuthorizationReadClient.class);
- when(abortAccountReader.read(any())).thenAnswer(invocation -> {
- GameLogicIntakeAuthorizationReadEvidence.Request heldRequest = invocation.getArgument(0);
- assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
- assertThat(heldRequest.binding().canonicalBytes())
- .isEqualTo(abortedAuthorization.canonicalBytes());
- return new GameLogicIntakeAuthorizationReadEvidence(heldRequest);
- });
+ when(abortAccountReader.read(any()))
+ .thenAnswer(
+ invocation -> {
+ GameLogicIntakeAuthorizationReadEvidence.Request heldRequest =
+ invocation.getArgument(0);
+ assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
+ assertThat(heldRequest.binding().canonicalBytes())
+ .isEqualTo(abortedAuthorization.canonicalBytes());
+ return new GameLogicIntakeAuthorizationReadEvidence(heldRequest);
+ });
var unusedAbortSourceReader = mock(GameplayRuleSourceReadClient.class);
- var abortOwner = new GameLogicGameplayRuleIntakeService(
- f.repository(), f.manager(), abortAccountReader, unusedAbortSourceReader, NAMESPACE);
+ var abortOwner =
+ new GameLogicGameplayRuleIntakeService(
+ f.repository(), f.manager(), abortAccountReader, unusedAbortSourceReader, NAMESPACE);
asGameDesign(() -> abortOwner.abort(abortedAuthorization));
verify(abortAccountReader).read(any());
verify(unusedAbortSourceReader, never()).read(any());
String aborted = row(f, abortedAuthorization.operationId());
- assertError(receiver, GameLogicPublicationSourceReadGrpcCodec.toRequest(publicationBinding(abortedAuthorization)), "FAILED_PRECONDITION");
+ assertError(
+ receiver,
+ GameLogicPublicationSourceReadGrpcCodec.toRequest(publicationBinding(abortedAuthorization)),
+ "FAILED_PRECONDITION");
assertThat(row(f, abortedAuthorization.operationId())).isEqualTo(aborted);
assertThat(row(f, authorization.operationId())).isEqualTo(retained);
}
private static GameLogicGrpcService receiver(GameLogicDraftDesignDigestServiceImpl digest) {
// Unrelated gameplay owners are unused by this focused direct receiver composition.
- return new GameLogicGrpcService(null, null, null, null, null, null, digest, null,
- new SimpleMeterRegistry(), new PublicationReadGuard(NAMESPACE));
+ return new GameLogicGrpcService(
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ digest,
+ null,
+ new SimpleMeterRegistry(),
+ new PublicationReadGuard(NAMESPACE));
}
- private static GetDraftDesignDigestResponse invoke(GameLogicGrpcService receiver,
- GetDraftDesignDigestRequest request) {
+ private static GetDraftDesignDigestResponse invoke(
+ GameLogicGrpcService receiver, GetDraftDesignDigestRequest request) {
var result = new AtomicReference();
- receiver.getDraftDesignDigest(request, new StreamObserver<>() {
- @Override public void onNext(GetDraftDesignDigestResponse value) { result.set(value); }
- @Override public void onError(Throwable failure) { throw new AssertionError(failure); }
- @Override public void onCompleted() {}
- });
+ receiver.getDraftDesignDigest(
+ request,
+ new StreamObserver<>() {
+ @Override
+ public void onNext(GetDraftDesignDigestResponse value) {
+ result.set(value);
+ }
+
+ @Override
+ public void onError(Throwable failure) {
+ throw new AssertionError(failure);
+ }
+
+ @Override
+ public void onCompleted() {}
+ });
assertThat(result.get()).isNotNull();
return result.get();
}
- private static void assertError(GameLogicGrpcService receiver, GetDraftDesignDigestRequest request,
- String code) throws Exception {
+ private static void assertError(
+ GameLogicGrpcService receiver, GetDraftDesignDigestRequest request, String code)
+ throws Exception {
var response = asGameDesign(() -> invoke(receiver, request));
assertThat(response.getError().getCode()).isEqualTo(code);
assertThat(response.getRetainedIntakeTerminal().isEmpty()).isTrue();
@@ -176,7 +247,11 @@ private static void assertError(GameLogicGrpcService receiver, GetDraftDesignDig
}
private static String row(Fixture f, UUID operation) {
- return f.dsl().fetchSingle("SELECT row_to_json(t)::TEXT || ':' || t.xmin::TEXT FROM game_logic_gameplay_rule_intake_terminal t WHERE operation_id = ?", operation).get(0, String.class);
+ return f.dsl()
+ .fetchSingle(
+ "SELECT row_to_json(t)::TEXT || ':' || t.xmin::TEXT FROM game_logic_gameplay_rule_intake_terminal t WHERE operation_id = ?",
+ operation)
+ .get(0, String.class);
}
private static Fixture fixture() {
@@ -293,6 +368,8 @@ private static GameLogicPublicationSourceReadBinding publicationBinding(
authorization);
}
- private record Fixture(DSLContext dsl, DataSourceTransactionManager manager,
+ private record Fixture(
+ DSLContext dsl,
+ DataSourceTransactionManager manager,
GameLogicGameplayRuleIntakeRepository repository) {}
}
From e64443e0c86e1e0b402664ecc04ad6c5bf1fd9de Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 03:17:04 +1300
Subject: [PATCH 07/55] Correct selected-full owner proof preconditions and
retained profile fixtures
---
...ame-authoring-publishing-and-activation.md | 2 +-
...nerPublicationPostgresIntegrationTest.java | 11 ++--
.../client/WorldManagementClientTest.java | 9 ++-
.../SelectedDraftControlPlaneDigestTest.java | 60 ++++---------------
...DraftPublicationDigestReadServiceTest.java | 18 +++---
...PublishedReleaseBundleServiceImplTest.java | 7 +--
.../VersionPublishCommandServiceImplTest.java | 8 +--
...electedFullPublicationEvidenceFixture.java | 8 ++-
8 files changed, 48 insertions(+), 75 deletions(-)
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index 01abdbc882..e7f31624dc 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -12,7 +12,7 @@ The source candidate prepares complete selected-owner publication consumption un
Entity's new V1011 prepares the freshly founded empty selected source catalogue and its complete explicit family/equipment evidence; Automation's new V1003 prepares empty selected source retention. Both are forward additions over their current combined service/Saga parents. Their command/read transports and owner services remain standalone and unregistered. These are bounded empty-source components, not arbitrary Entity authoring, script publication or runtime rule execution. Inherited Account migration history and numbering are unchanged by this candidate.
-The first R36 affected gate passes Automation 1,206, Common 818, shared-test-support 55, Entity 261 and Game Logic 117 unit cases with zero skips; those unchanged scopes remain up-to-date in R38. R38 freshly passes all 178 Common Security unit cases and 23 native PostgreSQL cases: Entity 11, Automation 11 and Game Logic one, with zero failures, errors or skips. The corrected numbered migration checks exclude Flyway's null-version schema marker while complete pre/post row and xmin history assertions retain it. Passive capture identifies all six run-owned PostgreSQL containers without ownership gaps or observer errors. Game Design unit and five-store cross-service proof remain unrun because fixture compilation exposes three unit and seven cross-service API alignment errors. Corrections use the existing public gate constructor, owner policy type, Game Design mutation proto, exact request/epoch accessors and canonical source-content decoder; no owner authority or proof assertion is weakened. The native five-store writer/readback composition has not run; no passing fresh full-profile writer, immutable readback or authenticated cross-owner result is claimed. Unit carriers, source/provenance inputs, creator/issuer/environment and PKI remain explicitly controlled where used. Retained historical release bytes keep their existing scoped read/retry meaning and are not upgraded into the new profile. Genuine creator, issuer, environment, immutable release and continuous-protection authority, runtime placement and operational delivery remain unavailable; all four genuine Gameplay handoffs remain open and broader Unit 1B/corpus stays paused.
+The first R36 affected gate passes Automation 1,206, Common 818, shared-test-support 55, Entity 261 and Game Logic 117 unit cases with zero skips; those unchanged scopes remain up-to-date in R38. R38 freshly passes all 178 Common Security unit cases and 23 native PostgreSQL cases: Entity 11, Automation 11 and Game Logic one, with zero failures, errors or skips. The corrected numbered migration checks exclude Flyway's null-version schema marker while complete pre/post row and xmin history assertions retain it. Passive capture identifies all six run-owned PostgreSQL containers without ownership gaps or observer errors. R40 first executes all 686 Game Design unit cases with 17 failures and the five-store composition with one failure. These expose fixture assumptions about inherited policy snapshots, the selected replay gate, retained v2 participant schemas and v4 launch support; the World freeze fixture also omitted the explicitly required READ COMMITTED transaction declaration. Corrections preserve exact historical vectors, current selected gate semantics, complete policy provenance and physical owner transaction guards. The five-store composition has not yet reached publication or immutable readback; no passing full-profile writer or authenticated cross-owner result is claimed. Unit carriers, source/provenance inputs, creator/issuer/environment and PKI remain explicitly controlled where used. Retained historical release bytes keep their existing scoped read/retry meaning and are not upgraded into the new profile. Genuine creator, issuer, environment, immutable release and continuous-protection authority, runtime placement and operational delivery remain unavailable; all four genuine Gameplay handoffs remain open and broader Unit 1B/corpus stays paused.
### Selected template publication and original launch reads
diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
index d1cbe6704a..cabced100c 100644
--- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
+++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
@@ -86,6 +86,7 @@
import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService;
import net.firedevops.firemud.gamedesign.service.impl.PublishGateServiceImpl;
import net.firedevops.firemud.gamedesign.service.impl.PublishedReleaseBundleServiceImpl;
+import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision;
import net.firedevops.firemud.gamelogic.service.impl.GameLogicDraftDesignDigestServiceImpl;
import net.firedevops.firemud.gamelogic.service.impl.GameLogicGrpcService;
import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeRepository;
@@ -96,7 +97,6 @@
import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation;
import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType;
import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation;
-import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision;
import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType;
import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration;
import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount;
@@ -226,7 +226,7 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema
selectedOwnerAuthorization(gds, selection, Owner.ENTITY_MANAGEMENT, sourceScopeActor);
var entityWorldRead =
SelectedOwnerWorldInventoryReadEvidence.create(
- NAMESPACE, entityAuthorization, worldOwners.freezeEvidence());
+ NAMESPACE, entityAuthorization, worldOwners.freezeEvidence());
var entityInputs =
new SelectedOwnerEmptySourceInputs(
entityAuthorization,
@@ -257,7 +257,7 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema
selectedOwnerAuthorization(gds, selection, Owner.AUTOMATION_SCRIPTING, sourceScopeActor);
var automationWorldRead =
SelectedOwnerWorldInventoryReadEvidence.create(
- NAMESPACE, automationAuthorization, worldOwners.freezeEvidence());
+ NAMESPACE, automationAuthorization, worldOwners.freezeEvidence());
var automationInputs =
new SelectedOwnerEmptySourceInputs(
automationAuthorization,
@@ -865,8 +865,9 @@ private static SelectedOwnerIntakeAuthorizationBinding selectedOwnerAuthorizatio
actor,
selection.selectedCommit());
var export = new GameDesignSourceRepository(gds.dsl()).requireSelectedOwnerIntakeSource(scope);
- var content = net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent.fromStored(
- export.canonicalBytes(), scope, export.digest());
+ var content =
+ net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent.fromStored(
+ export.canonicalBytes(), scope, export.digest());
return new SelectedOwnerIntakeAuthorizationBinding(
content, controlledAccountSources(actor, selection.target().canonicalTenantId()));
}
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldManagementClientTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldManagementClientTest.java
index c6965d8f0f..6353cb3e24 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldManagementClientTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldManagementClientTest.java
@@ -123,9 +123,14 @@ private static List participants(PublishParticipant
private static PublishGateServiceImpl gate() {
return new PublishGateServiceImpl(
- null, null, null, null, null,
+ null,
+ null,
+ null,
+ null,
+ null,
mock(org.jooq.DSLContext.class),
- mock(org.springframework.transaction.PlatformTransactionManager.class), "");
+ mock(org.springframework.transaction.PlatformTransactionManager.class),
+ "");
}
private static VersionDto version() {
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
index d8e2cb94f0..281577e513 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
@@ -7,9 +7,7 @@
import java.util.Optional;
import java.util.UUID;
import net.firedevops.firemud.common.authoring.DraftCommitBinding;
-import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload;
import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof;
-import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
import org.junit.jupiter.api.Test;
@@ -145,58 +143,22 @@ private static GameDesignPublicationOperation operation() throws Exception {
}
private static DraftCommitBinding selectedBinding() throws Exception {
- var selected = operation().account().input().selection().selectedCommit();
- var policyRevisions =
- selected.revisions().stream()
- .filter(
- revision -> revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE)
- .filter(RealmPolicySource::isPolicyRevision)
- .toList();
- if (policyRevisions.size() != 1) {
- throw new IllegalStateException("Expected exactly one selected policy revision");
- }
- var policyRevision = policyRevisions.getFirst();
- var fixedRevisionId = UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee");
- var oldRevisionId = policyRevision.revisionId().toString();
- var revisions = new java.util.ArrayList();
- for (var revision : selected.revisions()) {
- var payload =
- new String(
- Rfc8785CanonicalJson.canonicalizeUtf8(revision.payload()),
- java.nio.charset.StandardCharsets.UTF_8);
- var revisionId = revision.revisionId();
- if (revision == policyRevision) {
- if (payload.indexOf(oldRevisionId) < 0
- || payload.indexOf(oldRevisionId) != payload.lastIndexOf(oldRevisionId)) {
- throw new IllegalStateException(
- "Expected policy revision identity exactly once in payload");
- }
- payload = payload.replace(oldRevisionId, fixedRevisionId.toString());
- revisionId = fixedRevisionId;
- }
- revisions.add(
- new RevisionPayload(revision.revisionOrder(), revisionId, revision.owner(), payload));
- }
- return DraftCommitBinding.create(
- selected.target(),
- selected.requestId(),
- selected.commitId(),
- selected.baseCommitId(),
- revisions,
- selected.affectedUnits());
+ return operation().account().input().selection().selectedCommit();
}
private static GameDesignSourceRepository.SynchronizedSources sources(
DraftCommitBinding binding) {
var command = new CommandSnapshot(binding, "0", null, "sha256:" + "a".repeat(64), List.of());
- var policies =
- binding.revisions().stream()
- .filter(
- revision -> revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE)
- .filter(RealmPolicySource::isPolicyRevision)
- .map(revision -> RealmPolicySource.revision(binding, revision))
- .toList();
- var policy = new RealmPolicySnapshot(binding, "1", policies);
+ // Controlled inherited policy provenance; this World-only commit need not mutate policy.
+ var policy = new RealmPolicySnapshot(binding, "1", List.of(
+ new RealmPolicySource.Policy(
+ UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"),
+ UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), "inherited-policy",
+ net.firedevops.firemud.common.publication.RealmEntryPolicy.parse(
+ "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\","
+ + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true,"
+ + "\"publicProduction\":false,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}",
+ new tools.jackson.databind.ObjectMapper()))));
var asset =
new AssetSnapshot(
binding, "0", null, UUID.fromString("33333333-3333-4333-8333-333333333333"), List.of());
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
index 0f07102dd3..0936f66cf3 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
@@ -326,14 +326,16 @@ private static Fixture fixture() throws Exception {
private static GameDesignSourceRepository.SynchronizedSources sources(
DraftCommitBinding binding) {
var command = new CommandSnapshot(binding, "0", null, "sha256:" + "a".repeat(64), List.of());
- var policies =
- binding.revisions().stream()
- .filter(
- revision -> revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE)
- .filter(RealmPolicySource::isPolicyRevision)
- .map(revision -> RealmPolicySource.revision(binding, revision))
- .toList();
- var policy = new RealmPolicySnapshot(binding, "1", policies);
+ // Controlled inherited policy provenance; this World-only commit need not mutate policy.
+ var policy = new RealmPolicySnapshot(binding, "1", List.of(
+ new RealmPolicySource.Policy(
+ UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"),
+ UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), "inherited-policy",
+ net.firedevops.firemud.common.publication.RealmEntryPolicy.parse(
+ "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\","
+ + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true,"
+ + "\"publicProduction\":false,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}",
+ new tools.jackson.databind.ObjectMapper()))));
var asset =
new AssetSnapshot(
binding, "0", null, UUID.fromString("33333333-3333-4333-8333-333333333333"), List.of());
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
index 4e8d17d95e..63835d0239 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
@@ -103,9 +103,8 @@ class PublishedReleaseBundleServiceImplTest {
evidence))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("IDEMPOTENCY_CONFLICT");
- assertThatThrownBy(() -> PublishedReleaseBundleContract.requireSupportedSchemaForLaunch(first))
- .isInstanceOf(IllegalArgumentException.class)
- .hasMessageContaining("SCHEMA_VERSION_UNSUPPORTED");
+ PublishedReleaseBundleContract.requireSelectedFullBinding(first);
+ PublishedReleaseBundleContract.requireSupportedSchemaForLaunch(first);
PublishedReleaseBundleContract.requireExactRepairMatch(first, emptyManifest());
assertThatThrownBy(
() -> PublishedReleaseBundleContract.requireExactRepairMatch(first, logoManifest()))
@@ -118,7 +117,7 @@ void exactRetainedV2RetryStillReturnsItsOriginalSelectorWithoutWriting() throws
var evidence = selectorEvidence(3);
var participants =
PublishedWorldSelectorFixtures.participants(
- 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
+ 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION);
var retained = new PublishedReleaseBundle();
retained.setId(11L);
retained.setPublishedReleaseBundleRef("retained-v2-release");
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java
index b4f8b9d525..41ed08de3b 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java
@@ -429,7 +429,7 @@ void selectedSucceededReplayRevalidatesExactTerminalEvidenceWithoutWriting(
.PUBLISHED);
verify(publishAttemptRepository).requirePublishedOperation(fixture.attempt());
verify(publishGateService)
- .assertGatePassed(
+ .assertSelectedGatePassed(
any(VersionDto.class), org.mockito.ArgumentMatchers.eq(fixture.participantDigests()));
verify(recordedParticipantDigestService)
.assertMatchesRecordedDigests(
@@ -510,7 +510,7 @@ void selectedSucceededReplayRejectsPublicationGateMismatch() throws Exception {
org.mockito.Mockito.doThrow(
new IllegalStateException("ISOLATED retained publication gate mismatch"))
.when(publishGateService)
- .assertGatePassed(
+ .assertSelectedGatePassed(
any(VersionDto.class), org.mockito.ArgumentMatchers.eq(fixture.participantDigests()));
assertThrows(
@@ -518,7 +518,7 @@ void selectedSucceededReplayRejectsPublicationGateMismatch() throws Exception {
() -> service.reconcileFullVersionPublish(fixture.request()));
verify(publishGateService)
- .assertGatePassed(
+ .assertSelectedGatePassed(
any(VersionDto.class), org.mockito.ArgumentMatchers.eq(fixture.participantDigests()));
assertNoPublicationWrites();
}
@@ -2380,7 +2380,7 @@ void privateMechanicsReconcilesPendingAttemptThroughCurrentGates() throws Except
assertEquals("SUCCEEDED", snapshot.status());
verify(publishGateService)
- .assertGatePassed(
+ .assertSelectedGatePassed(
any(VersionDto.class), org.mockito.ArgumentMatchers.eq(participantDigests));
verify(recordedParticipantDigestService)
.assertMatchesRecordedDigests("tenant-1", PublishType.FULL_VERSION, participantDigests);
diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java
index cbbaea541e..347ba99038 100644
--- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java
+++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java
@@ -195,10 +195,12 @@ public static Result applyFreezeAndCapture(
new java.util.concurrent.atomic.AtomicReference<
WorldSelectedDraftPublicationCheckpointRepository.CapturedCheckpoint>();
var createdCheckpointInTransaction = new java.util.concurrent.atomic.AtomicBoolean();
+ var freezeTransaction = new TransactionTemplate(worldTransactions);
+ freezeTransaction.setIsolationLevel(
+ org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED);
var frozenAttempt =
Objects.requireNonNull(
- new TransactionTemplate(worldTransactions)
- .execute(
+ freezeTransaction.execute(
status -> {
createdCheckpointInTransaction.set(false);
var attempt =
@@ -340,6 +342,8 @@ public static AppliedGraph applyGraph(
var intakeRepository = new WorldAuthoredSourceIntakeRepository(worldDsl);
var versionRepository = new WorldAuthoredVersionIdentityRepository(worldDsl);
var write = new TransactionTemplate(worldTransactions);
+ write.setIsolationLevel(
+ org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED);
var intake =
Objects.requireNonNull(
write.execute(
From 4530274748a6f156d5b353ebe78e924ec6979ba4 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 03:24:09 +1300
Subject: [PATCH 08/55] Provide exact authored owner declarations in full
publication composition
---
...nerPublicationPostgresIntegrationTest.java | 39 ++++++++++++++
.../SelectedDraftControlPlaneDigestTest.java | 25 +++++----
...DraftPublicationDigestReadServiceTest.java | 23 ++++----
...electedFullPublicationEvidenceFixture.java | 52 +++++++++----------
4 files changed, 94 insertions(+), 45 deletions(-)
diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
index cabced100c..486c8e765a 100644
--- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
+++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
@@ -732,6 +732,22 @@ private static DraftCommitBinding selectedCommit(Store gds, TargetProof target)
GameplayRuleSource.SCOPE,
"effective",
"0"));
+ // Authored declarations are content only; each real owner independently proves emptiness.
+ revisions.add(new RevisionPayload(Integer.toString(revisions.size()), UUID.randomUUID(),
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ net.firedevops.firemud.gamedesign.publication.TemplateConfigSource.ownerInventoryPayload(
+ Owner.ENTITY_MANAGEMENT,
+ net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()))));
+ revisions.add(new RevisionPayload(Integer.toString(revisions.size()), UUID.randomUUID(),
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ net.firedevops.firemud.gamedesign.publication.TemplateConfigSource.ownerInventoryPayload(
+ Owner.AUTOMATION_SCRIPTING,
+ net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()))));
+ units.add(new AffectedUnit(Owner.GAME_DESIGN_CONTROL_PLANE,
+ net.firedevops.firemud.gamedesign.publication.TemplateConfigSource.SCOPE,
+ target.canonicalVersionId().toString(),
+ net.firedevops.firemud.gamedesign.publication.TemplateConfigSource.SCOPE,
+ net.firedevops.firemud.gamedesign.publication.TemplateConfigSource.SCOPE_ID, "0"));
for (var mutation : mutations) {
revisions.add(
new RevisionPayload(
@@ -1191,4 +1207,27 @@ private static Path pem(Path path, Object value) throws Exception {
record Identity(Path certificate, Path key) {}
}
+
+ private static String automationInventory() {
+ return "{\"schema\":\"automation-authored-source-inventory/v1\","
+ + "\"families\":{\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[],"
+ + "\"SCRIPT_PATCH_SOURCES\":[]}}";
+ }
+
+ private static String entityInventory() {
+ return "{\"schema\":\"entity-authored-source-inventory/v1\","
+ + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{"
+ + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[],"
+ + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[],"
+ + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[],"
+ + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[],"
+ + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[],"
+ + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[],"
+ + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[],"
+ + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[],"
+ + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[],"
+ + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[],"
+ + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[],"
+ + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}";
+ }
}
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
index 281577e513..171f247f17 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
@@ -43,7 +43,7 @@ void exactSixFamilyPreimageIsDeterministicAndDoesNotIncludePublicationRequestIde
.isEqualTo(Long.toString(selected.target().gameDesignVersionRowId()));
assertThat(first.appliedCommitId()).isEqualTo(selected.commitId().toString());
assertThat(first.contentDigest())
- .isEqualTo("08584ce89ee924b5d8b5b613ee60ccc0780716ba43cc7671fd5735b4b5e8015b");
+ .isEqualTo("414e333c7a695aa81cfe86d39eda7adb13cd3e16b78d2e2bed5df67b08181a5a");
}
@Test
@@ -150,15 +150,20 @@ private static GameDesignSourceRepository.SynchronizedSources sources(
DraftCommitBinding binding) {
var command = new CommandSnapshot(binding, "0", null, "sha256:" + "a".repeat(64), List.of());
// Controlled inherited policy provenance; this World-only commit need not mutate policy.
- var policy = new RealmPolicySnapshot(binding, "1", List.of(
- new RealmPolicySource.Policy(
- UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"),
- UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), "inherited-policy",
- net.firedevops.firemud.common.publication.RealmEntryPolicy.parse(
- "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\","
- + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true,"
- + "\"publicProduction\":false,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}",
- new tools.jackson.databind.ObjectMapper()))));
+ var policy =
+ new RealmPolicySnapshot(
+ binding,
+ "1",
+ List.of(
+ new RealmPolicySource.Policy(
+ UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"),
+ UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"),
+ "inherited-policy",
+ net.firedevops.firemud.common.publication.RealmEntryPolicy.parse(
+ "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\","
+ + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true,"
+ + "\"publicProduction\":false,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}",
+ new tools.jackson.databind.ObjectMapper()))));
var asset =
new AssetSnapshot(
binding, "0", null, UUID.fromString("33333333-3333-4333-8333-333333333333"), List.of());
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
index 0936f66cf3..691688e088 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
@@ -327,15 +327,20 @@ private static GameDesignSourceRepository.SynchronizedSources sources(
DraftCommitBinding binding) {
var command = new CommandSnapshot(binding, "0", null, "sha256:" + "a".repeat(64), List.of());
// Controlled inherited policy provenance; this World-only commit need not mutate policy.
- var policy = new RealmPolicySnapshot(binding, "1", List.of(
- new RealmPolicySource.Policy(
- UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"),
- UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), "inherited-policy",
- net.firedevops.firemud.common.publication.RealmEntryPolicy.parse(
- "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\","
- + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true,"
- + "\"publicProduction\":false,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}",
- new tools.jackson.databind.ObjectMapper()))));
+ var policy =
+ new RealmPolicySnapshot(
+ binding,
+ "1",
+ List.of(
+ new RealmPolicySource.Policy(
+ UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"),
+ UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"),
+ "inherited-policy",
+ net.firedevops.firemud.common.publication.RealmEntryPolicy.parse(
+ "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\","
+ + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true,"
+ + "\"publicProduction\":true,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}",
+ new tools.jackson.databind.ObjectMapper()))));
var asset =
new AssetSnapshot(
binding, "0", null, UUID.fromString("33333333-3333-4333-8333-333333333333"), List.of());
diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java
index 347ba99038..5e2a083f46 100644
--- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java
+++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java
@@ -201,32 +201,32 @@ public static Result applyFreezeAndCapture(
var frozenAttempt =
Objects.requireNonNull(
freezeTransaction.execute(
- status -> {
- createdCheckpointInTransaction.set(false);
- var attempt =
- fence.claimFreeze(
- freeze,
- () -> {
- var captured = checkpointRepository.captureWithSource(freeze, plan);
- capturedCheckpoint.set(captured);
- createdCheckpointInTransaction.set(true);
- return captured.checkpoint();
- });
- var retainedAccount =
- authorizationRepository.retainOrRequireExact(
- attempt, accountBinding, createdCheckpointInTransaction.get());
- if (!java.util.Arrays.equals(
- retainedAccount.canonicalBytes(), accountBinding.canonicalBytes())) {
- throw new IllegalStateException(
- "World did not retain the exact original Account publication binding");
- }
- inventoryRepository.retainOrRequireExact(
- attempt,
- retainedAccount,
- createdCheckpointInTransaction.get(),
- capturedCheckpoint.get());
- return attempt;
- }));
+ status -> {
+ createdCheckpointInTransaction.set(false);
+ var attempt =
+ fence.claimFreeze(
+ freeze,
+ () -> {
+ var captured = checkpointRepository.captureWithSource(freeze, plan);
+ capturedCheckpoint.set(captured);
+ createdCheckpointInTransaction.set(true);
+ return captured.checkpoint();
+ });
+ var retainedAccount =
+ authorizationRepository.retainOrRequireExact(
+ attempt, accountBinding, createdCheckpointInTransaction.get());
+ if (!java.util.Arrays.equals(
+ retainedAccount.canonicalBytes(), accountBinding.canonicalBytes())) {
+ throw new IllegalStateException(
+ "World did not retain the exact original Account publication binding");
+ }
+ inventoryRepository.retainOrRequireExact(
+ attempt,
+ retainedAccount,
+ createdCheckpointInTransaction.get(),
+ capturedCheckpoint.get());
+ return attempt;
+ }));
var retainedAccount = authorizationRepository.readCommitted(frozenAttempt).orElseThrow();
if (!java.util.Arrays.equals(
From fe642fc3bb443e6071c7781467aac2b358765de2 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 03:35:51 +1300
Subject: [PATCH 09/55] Complete authored policy fixture and normalize digest
vector payloads
---
design/project-management/ai-observations.md | 3 ++
...ame-authoring-publishing-and-activation.md | 2 +-
...nerPublicationPostgresIntegrationTest.java | 51 ++++++++++++++-----
.../SelectedDraftControlPlaneDigestTest.java | 10 +++-
4 files changed, 51 insertions(+), 15 deletions(-)
diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md
index 4152de8640..629a0e28fd 100644
--- a/design/project-management/ai-observations.md
+++ b/design/project-management/ai-observations.md
@@ -344,3 +344,6 @@ Entry format:
- `2026-10-16`: The canonical local resource lock already serializes eligible heavy runs across worktrees. Ordinary workers can submit through supported bounded admission and retry a busy result without peer permission or an idle reservation between scheduled wake-ups. A Document source gate automatically acquired the lock before its delayed peer completion message arrived; busy admission remains unrun proof.
- `2026-10-16`: A multiline conflict-marker resolver truncated three trailing file portions during an unpublished selected-owner carry. Native `git merge-file` reconstruction from the exact parents recovered the complete files. Bound marker lines explicitly, verify conflict counts and file tails, and inspect the final net diff against both original parents before committing; a clean whitespace check alone cannot detect lost content.
+
+
+- 2026-10-15: Selected-full digest fixture R41/R42 produced different fixed-golden values from otherwise unchanged source. The fixture serialized `Map.of` payloads into strings inside a canonical binding; outer canonicalization preserves string contents and therefore does not normalize the inner map order. Restored explicit RFC 8785 normalization of each fixture payload before binding creation. Updating a golden from one failing run alone did not establish a stable vector; retain equality/mutation checks and verify the normalized vector before claiming deterministic proof. No production digest or retained bytes were changed.
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index e7f31624dc..bd12998f17 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -12,7 +12,7 @@ The source candidate prepares complete selected-owner publication consumption un
Entity's new V1011 prepares the freshly founded empty selected source catalogue and its complete explicit family/equipment evidence; Automation's new V1003 prepares empty selected source retention. Both are forward additions over their current combined service/Saga parents. Their command/read transports and owner services remain standalone and unregistered. These are bounded empty-source components, not arbitrary Entity authoring, script publication or runtime rule execution. Inherited Account migration history and numbering are unchanged by this candidate.
-The first R36 affected gate passes Automation 1,206, Common 818, shared-test-support 55, Entity 261 and Game Logic 117 unit cases with zero skips; those unchanged scopes remain up-to-date in R38. R38 freshly passes all 178 Common Security unit cases and 23 native PostgreSQL cases: Entity 11, Automation 11 and Game Logic one, with zero failures, errors or skips. The corrected numbered migration checks exclude Flyway's null-version schema marker while complete pre/post row and xmin history assertions retain it. Passive capture identifies all six run-owned PostgreSQL containers without ownership gaps or observer errors. R40 first executes all 686 Game Design unit cases with 17 failures and the five-store composition with one failure. These expose fixture assumptions about inherited policy snapshots, the selected replay gate, retained v2 participant schemas and v4 launch support; the World freeze fixture also omitted the explicitly required READ COMMITTED transaction declaration. Corrections preserve exact historical vectors, current selected gate semantics, complete policy provenance and physical owner transaction guards. The five-store composition has not yet reached publication or immutable readback; no passing full-profile writer or authenticated cross-owner result is claimed. Unit carriers, source/provenance inputs, creator/issuer/environment and PKI remain explicitly controlled where used. Retained historical release bytes keep their existing scoped read/retry meaning and are not upgraded into the new profile. Genuine creator, issuer, environment, immutable release and continuous-protection authority, runtime placement and operational delivery remain unavailable; all four genuine Gameplay handoffs remain open and broader Unit 1B/corpus stays paused.
+The first R36 affected gate passes Automation 1,206, Common 818, shared-test-support 55, Entity 261 and Game Logic 117 unit cases with zero skips; those unchanged scopes remain up-to-date in R38. R38 freshly passes all 178 Common Security unit cases and 23 native PostgreSQL cases: Entity 11, Automation 11 and Game Logic one, with zero failures, errors or skips. The corrected numbered migration checks exclude Flyway's null-version schema marker while complete pre/post row and xmin history assertions retain it. Passive capture identifies all six run-owned PostgreSQL containers without ownership gaps or observer errors. R42 executes all 686 Game Design unit cases with one remaining deterministic-fixture golden failure; its five-store case reaches the publication policy guard after actual Entity and Automation receipts are retained. The remaining fixture corrections normalize nested JSON payload text before binding creation and author the required visible public-production realm policy through the selected Draft commit. Previous selected replay, historical v2 vector, current v4 launch, owner inventory declaration and physical transaction preconditions now pass. The five-store composition has not yet reached successful publication or immutable readback; no passing full-profile writer or authenticated complete owner result is claimed. Unit carriers, source/provenance inputs, creator/issuer/environment and PKI remain explicitly controlled where used. Retained historical release bytes keep their existing scoped read/retry meaning and are not upgraded into the new profile. Genuine creator, issuer, environment, immutable release and continuous-protection authority, runtime placement and operational delivery remain unavailable; all four genuine Gameplay handoffs remain open and broader Unit 1B/corpus stays paused.
### Selected template publication and original launch reads
diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
index 486c8e765a..c910905565 100644
--- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
+++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
@@ -732,22 +732,47 @@ private static DraftCommitBinding selectedCommit(Store gds, TargetProof target)
GameplayRuleSource.SCOPE,
"effective",
"0"));
- // Authored declarations are content only; each real owner independently proves emptiness.
- revisions.add(new RevisionPayload(Integer.toString(revisions.size()), UUID.randomUUID(),
- Owner.GAME_DESIGN_CONTROL_PLANE,
- net.firedevops.firemud.gamedesign.publication.TemplateConfigSource.ownerInventoryPayload(
- Owner.ENTITY_MANAGEMENT,
- net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()))));
+ String policyPayload =
+ "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"selected-public-realm\",\"policy\":{"
+ + "\"schemaVersion\":1,\"worldSlug\":\"controlled-selected-world\",\"worldDisplayName\":\"World\","
+ + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main\",\"visible\":true,"
+ + "\"publicProduction\":true,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}}";
revisions.add(new RevisionPayload(Integer.toString(revisions.size()), UUID.randomUUID(),
- Owner.GAME_DESIGN_CONTROL_PLANE,
- net.firedevops.firemud.gamedesign.publication.TemplateConfigSource.ownerInventoryPayload(
- Owner.AUTOMATION_SCRIPTING,
- net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()))));
+ Owner.GAME_DESIGN_CONTROL_PLANE, policyPayload));
units.add(new AffectedUnit(Owner.GAME_DESIGN_CONTROL_PLANE,
- net.firedevops.firemud.gamedesign.publication.TemplateConfigSource.SCOPE,
+ net.firedevops.firemud.gamedesign.publication.RealmPolicySource.SCOPE,
target.canonicalVersionId().toString(),
- net.firedevops.firemud.gamedesign.publication.TemplateConfigSource.SCOPE,
- net.firedevops.firemud.gamedesign.publication.TemplateConfigSource.SCOPE_ID, "0"));
+ net.firedevops.firemud.gamedesign.publication.RealmPolicySource.SCOPE, "effective", "0"));
+ // Authored declarations are content only; each real owner independently proves emptiness.
+ revisions.add(
+ new RevisionPayload(
+ Integer.toString(revisions.size()),
+ UUID.randomUUID(),
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ net.firedevops.firemud.gamedesign.publication.TemplateConfigSource
+ .ownerInventoryPayload(
+ Owner.ENTITY_MANAGEMENT,
+ net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration
+ .parse(entityInventory()))));
+ revisions.add(
+ new RevisionPayload(
+ Integer.toString(revisions.size()),
+ UUID.randomUUID(),
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ net.firedevops.firemud.gamedesign.publication.TemplateConfigSource
+ .ownerInventoryPayload(
+ Owner.AUTOMATION_SCRIPTING,
+ net.firedevops.firemud.common.automation
+ .AutomationAuthoredSourceInventoryDeclaration.parse(
+ automationInventory()))));
+ units.add(
+ new AffectedUnit(
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ net.firedevops.firemud.gamedesign.publication.TemplateConfigSource.SCOPE,
+ target.canonicalVersionId().toString(),
+ net.firedevops.firemud.gamedesign.publication.TemplateConfigSource.SCOPE,
+ net.firedevops.firemud.gamedesign.publication.TemplateConfigSource.SCOPE_ID,
+ "0"));
for (var mutation : mutations) {
revisions.add(
new RevisionPayload(
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
index 171f247f17..abfe5399c2 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
@@ -143,7 +143,15 @@ private static GameDesignPublicationOperation operation() throws Exception {
}
private static DraftCommitBinding selectedBinding() throws Exception {
- return operation().account().input().selection().selectedCommit();
+ var selected = operation().account().input().selection().selectedCommit();
+ // Payload JSON is stored as text in the binding; normalize unordered fixture maps first.
+ var revisions = selected.revisions().stream().map(revision ->
+ new DraftCommitBinding.RevisionPayload(revision.revisionOrder(), revision.revisionId(),
+ revision.owner(), new String(
+ net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8(revision.payload()),
+ java.nio.charset.StandardCharsets.UTF_8))).toList();
+ return DraftCommitBinding.create(selected.target(), selected.requestId(), selected.commitId(),
+ selected.baseCommitId(), revisions, selected.affectedUnits());
}
private static GameDesignSourceRepository.SynchronizedSources sources(
From 928c6dfbf9025aa2b6f197e834a9065c3adc6504 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 03:41:28 +1300
Subject: [PATCH 10/55] Support canonical selected-full profile at immutable
bundle repository boundary
---
design/project-management/ai-observations.md | 1 -
...ame-authoring-publishing-and-activation.md | 2 +-
.../PublishedReleaseBundleRepository.java | 15 ++++++++-----
...nerPublicationPostgresIntegrationTest.java | 20 ++++++++++++------
.../SelectedDraftControlPlaneDigestTest.java | 21 ++++++++++++-------
5 files changed, 39 insertions(+), 20 deletions(-)
diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md
index 629a0e28fd..43f2e8d947 100644
--- a/design/project-management/ai-observations.md
+++ b/design/project-management/ai-observations.md
@@ -345,5 +345,4 @@ Entry format:
- `2026-10-16`: A multiline conflict-marker resolver truncated three trailing file portions during an unpublished selected-owner carry. Native `git merge-file` reconstruction from the exact parents recovered the complete files. Bound marker lines explicitly, verify conflict counts and file tails, and inspect the final net diff against both original parents before committing; a clean whitespace check alone cannot detect lost content.
-
- 2026-10-15: Selected-full digest fixture R41/R42 produced different fixed-golden values from otherwise unchanged source. The fixture serialized `Map.of` payloads into strings inside a canonical binding; outer canonicalization preserves string contents and therefore does not normalize the inner map order. Restored explicit RFC 8785 normalization of each fixture payload before binding creation. Updating a golden from one failing run alone did not establish a stable vector; retain equality/mutation checks and verify the normalized vector before claiming deterministic proof. No production digest or retained bytes were changed.
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index bd12998f17..b09b9a83bb 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -12,7 +12,7 @@ The source candidate prepares complete selected-owner publication consumption un
Entity's new V1011 prepares the freshly founded empty selected source catalogue and its complete explicit family/equipment evidence; Automation's new V1003 prepares empty selected source retention. Both are forward additions over their current combined service/Saga parents. Their command/read transports and owner services remain standalone and unregistered. These are bounded empty-source components, not arbitrary Entity authoring, script publication or runtime rule execution. Inherited Account migration history and numbering are unchanged by this candidate.
-The first R36 affected gate passes Automation 1,206, Common 818, shared-test-support 55, Entity 261 and Game Logic 117 unit cases with zero skips; those unchanged scopes remain up-to-date in R38. R38 freshly passes all 178 Common Security unit cases and 23 native PostgreSQL cases: Entity 11, Automation 11 and Game Logic one, with zero failures, errors or skips. The corrected numbered migration checks exclude Flyway's null-version schema marker while complete pre/post row and xmin history assertions retain it. Passive capture identifies all six run-owned PostgreSQL containers without ownership gaps or observer errors. R42 executes all 686 Game Design unit cases with one remaining deterministic-fixture golden failure; its five-store case reaches the publication policy guard after actual Entity and Automation receipts are retained. The remaining fixture corrections normalize nested JSON payload text before binding creation and author the required visible public-production realm policy through the selected Draft commit. Previous selected replay, historical v2 vector, current v4 launch, owner inventory declaration and physical transaction preconditions now pass. The five-store composition has not yet reached successful publication or immutable readback; no passing full-profile writer or authenticated complete owner result is claimed. Unit carriers, source/provenance inputs, creator/issuer/environment and PKI remain explicitly controlled where used. Retained historical release bytes keep their existing scoped read/retry meaning and are not upgraded into the new profile. Genuine creator, issuer, environment, immutable release and continuous-protection authority, runtime placement and operational delivery remain unavailable; all four genuine Gameplay handoffs remain open and broader Unit 1B/corpus stays paused.
+The first R36 affected gate passes Automation 1,206, Common 818, shared-test-support 55, Entity 261 and Game Logic 117 unit cases with zero skips; those unchanged scopes remain up-to-date in R38. R38 freshly passes all 178 Common Security unit cases and 23 native PostgreSQL cases: Entity 11, Automation 11 and Game Logic one, with zero failures, errors or skips. The corrected numbered migration checks exclude Flyway's null-version schema marker while complete pre/post row and xmin history assertions retain it. Passive capture identifies all six run-owned PostgreSQL containers without ownership gaps or observer errors. R43 reaches the actual bundle repository after the selected policy, frozen six-family source and authenticated participant gate pass. The repository still rejects v4 selector evidence despite existing V1020 storage support; its Java insert/read/idempotency checks now explicitly accept v4 with World schema 4 while preserving exact v2/World-3 history and refusing selector bytes on historical schemas. Physical storage, immutable readback and retry qualification remain pending. The unit digest fixture normalization requires a checked-exception-safe loop; its fixed golden remains to be qualified. No passing full-profile writer or complete authenticated cross-owner result is claimed. Unit carriers, source/provenance inputs, creator/issuer/environment and PKI remain explicitly controlled where used. Retained historical release bytes keep their existing scoped read/retry meaning and are not upgraded into the new profile. Genuine creator, issuer, environment, immutable release and continuous-protection authority, runtime placement and operational delivery remain unavailable; all four genuine Gameplay handoffs remain open and broader Unit 1B/corpus stays paused.
### Selected template publication and original launch reads
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java
index 723b6d8ac8..b7c3d4c7e2 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java
@@ -182,12 +182,14 @@ private PublishedReleaseBundle insertNewBundle(
rejectCallerIdentitySubstitution(bundle, source);
verifySelectorSource(bundle, source);
if (!"v1".equals(bundle.getAttestationSchemaVersion())
- && !"v2".equals(bundle.getAttestationSchemaVersion())) {
+ && !"v2".equals(bundle.getAttestationSchemaVersion())
+ && !"v4".equals(bundle.getAttestationSchemaVersion())) {
throw new IllegalArgumentException(
"Unsupported published release bundle attestation schema "
+ bundle.getAttestationSchemaVersion());
}
- if ("v2".equals(bundle.getAttestationSchemaVersion())) {
+ if ("v2".equals(bundle.getAttestationSchemaVersion())
+ || "v4".equals(bundle.getAttestationSchemaVersion())) {
PublishedReleaseBundle existing =
tx.selectFrom(TABLE_REF)
.where(TENANT_ID.eq(bundle.getTenantId()).and(VERSION_ID.eq(bundle.getVersionId())))
@@ -363,7 +365,8 @@ private PublishedReleaseBundle toEntity(Record record) {
private static void verifySelectorSource(PublishedReleaseBundle bundle, CanonicalSource source) {
String bytes = bundle.getWorldPublishedStartLocationEvidenceJson();
- if (!"v2".equals(bundle.getAttestationSchemaVersion())) {
+ if (!"v2".equals(bundle.getAttestationSchemaVersion())
+ && !"v4".equals(bundle.getAttestationSchemaVersion())) {
if (bytes != null) {
throw new IllegalArgumentException(
"Selector evidence is forbidden on historical release schemas");
@@ -371,14 +374,16 @@ private static void verifySelectorSource(PublishedReleaseBundle bundle, Canonica
return;
}
if (bytes == null) {
- throw new IllegalArgumentException("World selector evidence is mandatory for release v2");
+ throw new IllegalArgumentException("World selector evidence is mandatory for selected release v2/v4");
}
var request =
WorldPublishedStartLocationEvidence.fromStored(bytes.getBytes(StandardCharsets.UTF_8))
.request();
if (!request.canonicalTenantId().equals(source.canonicalTenantId())
|| !request.canonicalVersionId().equals(source.canonicalVersionId())
- || !request.publishWorkflowId().equals(bundle.getPublishWorkflowId())) {
+ || !request.publishWorkflowId().equals(bundle.getPublishWorkflowId())
+ || request.digestSchemaVersion()
+ != ("v4".equals(bundle.getAttestationSchemaVersion()) ? 4 : 3)) {
throw new IllegalArgumentException(
"World selector differs from exact Version source/workflow");
}
diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
index c910905565..252c9a6942 100644
--- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
+++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
@@ -737,12 +737,20 @@ private static DraftCommitBinding selectedCommit(Store gds, TargetProof target)
+ "\"schemaVersion\":1,\"worldSlug\":\"controlled-selected-world\",\"worldDisplayName\":\"World\","
+ "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main\",\"visible\":true,"
+ "\"publicProduction\":true,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}}";
- revisions.add(new RevisionPayload(Integer.toString(revisions.size()), UUID.randomUUID(),
- Owner.GAME_DESIGN_CONTROL_PLANE, policyPayload));
- units.add(new AffectedUnit(Owner.GAME_DESIGN_CONTROL_PLANE,
- net.firedevops.firemud.gamedesign.publication.RealmPolicySource.SCOPE,
- target.canonicalVersionId().toString(),
- net.firedevops.firemud.gamedesign.publication.RealmPolicySource.SCOPE, "effective", "0"));
+ revisions.add(
+ new RevisionPayload(
+ Integer.toString(revisions.size()),
+ UUID.randomUUID(),
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ policyPayload));
+ units.add(
+ new AffectedUnit(
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ net.firedevops.firemud.gamedesign.publication.RealmPolicySource.SCOPE,
+ target.canonicalVersionId().toString(),
+ net.firedevops.firemud.gamedesign.publication.RealmPolicySource.SCOPE,
+ "effective",
+ "0"));
// Authored declarations are content only; each real owner independently proves emptiness.
revisions.add(
new RevisionPayload(
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
index abfe5399c2..62aa38b41e 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
@@ -145,13 +145,20 @@ private static GameDesignPublicationOperation operation() throws Exception {
private static DraftCommitBinding selectedBinding() throws Exception {
var selected = operation().account().input().selection().selectedCommit();
// Payload JSON is stored as text in the binding; normalize unordered fixture maps first.
- var revisions = selected.revisions().stream().map(revision ->
- new DraftCommitBinding.RevisionPayload(revision.revisionOrder(), revision.revisionId(),
- revision.owner(), new String(
- net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8(revision.payload()),
- java.nio.charset.StandardCharsets.UTF_8))).toList();
- return DraftCommitBinding.create(selected.target(), selected.requestId(), selected.commitId(),
- selected.baseCommitId(), revisions, selected.affectedUnits());
+ var revisions = new java.util.ArrayList();
+ for (var revision : selected.revisions()) {
+ revisions.add(new DraftCommitBinding.RevisionPayload(
+ revision.revisionOrder(), revision.revisionId(), revision.owner(),
+ new String(net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8(
+ revision.payload()), java.nio.charset.StandardCharsets.UTF_8)));
+ }
+ return DraftCommitBinding.create(
+ selected.target(),
+ selected.requestId(),
+ selected.commitId(),
+ selected.baseCommitId(),
+ revisions,
+ selected.affectedUnits());
}
private static GameDesignSourceRepository.SynchronizedSources sources(
From 6b790aed05504b436af3e9ce9b5827551ce5805b Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 03:46:51 +1300
Subject: [PATCH 11/55] Compose full publication with actual atomic owner
terminal and artifact candidate
---
...ame-authoring-publishing-and-activation.md | 2 +-
.../PublishedReleaseBundleRepository.java | 3 +-
...nerPublicationPostgresIntegrationTest.java | 61 +++++++++++++++----
.../SelectedDraftControlPlaneDigestTest.java | 15 +++--
4 files changed, 63 insertions(+), 18 deletions(-)
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index b09b9a83bb..013777639c 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -12,7 +12,7 @@ The source candidate prepares complete selected-owner publication consumption un
Entity's new V1011 prepares the freshly founded empty selected source catalogue and its complete explicit family/equipment evidence; Automation's new V1003 prepares empty selected source retention. Both are forward additions over their current combined service/Saga parents. Their command/read transports and owner services remain standalone and unregistered. These are bounded empty-source components, not arbitrary Entity authoring, script publication or runtime rule execution. Inherited Account migration history and numbering are unchanged by this candidate.
-The first R36 affected gate passes Automation 1,206, Common 818, shared-test-support 55, Entity 261 and Game Logic 117 unit cases with zero skips; those unchanged scopes remain up-to-date in R38. R38 freshly passes all 178 Common Security unit cases and 23 native PostgreSQL cases: Entity 11, Automation 11 and Game Logic one, with zero failures, errors or skips. The corrected numbered migration checks exclude Flyway's null-version schema marker while complete pre/post row and xmin history assertions retain it. Passive capture identifies all six run-owned PostgreSQL containers without ownership gaps or observer errors. R43 reaches the actual bundle repository after the selected policy, frozen six-family source and authenticated participant gate pass. The repository still rejects v4 selector evidence despite existing V1020 storage support; its Java insert/read/idempotency checks now explicitly accept v4 with World schema 4 while preserving exact v2/World-3 history and refusing selector bytes on historical schemas. Physical storage, immutable readback and retry qualification remain pending. The unit digest fixture normalization requires a checked-exception-safe loop; its fixed golden remains to be qualified. No passing full-profile writer or complete authenticated cross-owner result is claimed. Unit carriers, source/provenance inputs, creator/issuer/environment and PKI remain explicitly controlled where used. Retained historical release bytes keep their existing scoped read/retry meaning and are not upgraded into the new profile. Genuine creator, issuer, environment, immutable release and continuous-protection authority, runtime placement and operational delivery remain unavailable; all four genuine Gameplay handoffs remain open and broader Unit 1B/corpus stays paused.
+The first R36 affected gate passes Automation 1,206, Common 818, shared-test-support 55, Entity 261 and Game Logic 117 unit cases with zero skips; those unchanged scopes remain up-to-date in R38. R38 freshly passes all 178 Common Security unit cases and 23 native PostgreSQL cases: Entity 11, Automation 11 and Game Logic one, with zero failures, errors or skips. The corrected numbered migration checks exclude Flyway's null-version schema marker while complete pre/post row and xmin history assertions retain it. Passive capture identifies all six run-owned PostgreSQL containers without ownership gaps or observer errors. R44 reaches the actual v4 insert and preserves the deferred SQL atomicity guard: committing a release while its operation remains pending is refused. The composition now uses the existing Spring jOOQ transaction provider, retains the actual empty asset snapshot/candidate through existing owner services, and commits Version/artifact state, successful attempt and original operation seal with the bundle in one transaction. Candidate origin and manifest metadata remain controlled; no object-store delivery is proved. The normalized deterministic unit vector and physical atomic publication/readback/retry remain under qualification. No passing full-profile writer or complete authenticated cross-owner result is claimed. Unit carriers, source/provenance inputs, creator/issuer/environment and PKI remain explicitly controlled where used. Retained historical release bytes keep their existing scoped read/retry meaning and are not upgraded into the new profile. Genuine creator, issuer, environment, immutable release and continuous-protection authority, runtime placement and operational delivery remain unavailable; all four genuine Gameplay handoffs remain open and broader Unit 1B/corpus stays paused.
### Selected template publication and original launch reads
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java
index b7c3d4c7e2..437fd8101e 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java
@@ -374,7 +374,8 @@ private static void verifySelectorSource(PublishedReleaseBundle bundle, Canonica
return;
}
if (bytes == null) {
- throw new IllegalArgumentException("World selector evidence is mandatory for selected release v2/v4");
+ throw new IllegalArgumentException(
+ "World selector evidence is mandatory for selected release v2/v4");
}
var request =
WorldPublishedStartLocationEvidence.fromStored(bytes.getBytes(StandardCharsets.UTF_8))
diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
index 252c9a6942..1fe5d6485f 100644
--- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
+++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
@@ -493,6 +493,27 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema
new VersionRepository(gds.dsl()),
new ObjectMapper());
var controlledEmptyManifest = controlledEmptyManifest();
+ var artifactRepository = new net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository(gds.dsl());
+ var versions = new VersionRepository(gds.dsl());
+ var artifactService = new net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl(
+ artifactRepository, null, versions, null, null, null, null, null, new ObjectMapper());
+ var assetPublication = new net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository(gds.dsl());
+ var exportSnapshot = gds.write().execute(ignored -> assetPublication.freezeOrReadSnapshot(
+ versionDto.tenantId(), versionDto.versionNumber()));
+ assertThat(exportSnapshot.items()).isEmpty();
+ gds.write().execute(ignored -> artifactService.stageExport(versionDto.tenantId(), versionDto.id(),
+ versionDto.versionNumber(), publicationRequest.derivedWorkflowIdentity()));
+ var candidateService = new net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceImpl(
+ versions, new GameRepository(gds.dsl()),
+ new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository(gds.dsl()),
+ artifactRepository, assetPublication, gds.transactions(), new ObjectMapper());
+ // Controlled delivery origin and manifest metadata; no object-store or public delivery proof.
+ var candidate = new net.firedevops.firemud.gamedesign.service.FrozenAssetExportCandidate(
+ controlledEmptyManifest, "https://controlled.invalid/assets");
+ assertThat(candidateService.recordExportCandidate(versionDto.tenantId(), versionDto.versionNumber(), candidate))
+ .isEqualTo(candidate);
+ assertThat(candidateService.readExportCandidate(versionDto.tenantId(), versionDto.versionNumber()))
+ .isEqualTo(candidate);
assertThatThrownBy(
() ->
gds.write()
@@ -519,14 +540,28 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema
var written =
gds.write()
.execute(
- ignored ->
- releaseOwner.createFullVersionBundle(
- versionDto,
- publicationRequest.derivedWorkflowIdentity(),
- controlledEmptyManifest,
- "controlled-generation-input",
- participantDigests,
- worldOwners.startLocationEvidence()));
+ ignored -> {
+ String workflow = publicationRequest.derivedWorkflowIdentity();
+ var exported = artifactService.markExportedUnattested(versionDto.tenantId(), versionDto.id(),
+ versionDto.versionNumber(), workflow, controlledEmptyManifest);
+ var result = releaseOwner.createFullVersionBundle(
+ versionDto, workflow, controlledEmptyManifest, "controlled-generation-input",
+ participantDigests, worldOwners.startLocationEvidence());
+ var version = versions.findByTenantIdAndIdForUpdate(versionDto.tenantId(), versionDto.id()).orElseThrow();
+ version.setVersionState(VersionLifecycleState.PUBLISHED);
+ version.setVersionStateEpoch(Math.addExact(version.getVersionStateEpoch(), 1L));
+ versions.save(version);
+ artifactService.markPublished(versionDto.tenantId(), versionDto.id(), exported.stateEpoch(),
+ workflow, controlledEmptyManifest.manifestHash());
+ var attempts = new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository(gds.dsl());
+ var attempt = attempts.findByPublishWorkflowIdForUpdate(workflow).orElseThrow();
+ attempt.setStatus(net.firedevops.firemud.gamedesign.model.PublishAttemptStatus.SUCCEEDED);
+ attempts.save(attempt);
+ var operation = selectedOwnerReservation.operation();
+ new net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository(gds.dsl())
+ .seal(operation.tenantKey(), workflow, operation.versionId(), operation.selectionDigest(), true);
+ return result;
+ });
assertThat(written.attestationSchemaVersion()).isEqualTo("v4");
assertThat(written.participantDigests()).containsExactlyElementsOf(participantDigests);
assertThat(written.worldPublishedStartLocationEvidence().canonicalBytes())
@@ -980,7 +1015,7 @@ private static ExportedAssetManifest controlledEmptyManifest() throws Exception
HexFormat.of()
.formatHex(
java.security.MessageDigest.getInstance("SHA-256")
- .digest("[]".getBytes(StandardCharsets.UTF_8)));
+ .digest("{\"assets\":{},\"schemaVersion\":1}".getBytes(StandardCharsets.UTF_8)));
return new ExportedAssetManifest("sha256:" + hash, 1, List.of(), List.of());
}
@@ -1042,9 +1077,13 @@ private static Store store(
.setTransactionalLock(false);
}
flyway.load().migrate();
- DSLContext dsl =
- DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES);
var manager = new DataSourceTransactionManager(dataSource);
+ var configuration = new org.jooq.impl.DefaultConfiguration();
+ configuration.set(SQLDialect.POSTGRES);
+ configuration.set(new org.jooq.impl.DataSourceConnectionProvider(
+ new TransactionAwareDataSourceProxy(dataSource)));
+ configuration.set(new org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider(manager));
+ DSLContext dsl = DSL.using(configuration);
return new Store(schema, dsl, manager);
}
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
index 62aa38b41e..2802b62262 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
@@ -43,7 +43,7 @@ void exactSixFamilyPreimageIsDeterministicAndDoesNotIncludePublicationRequestIde
.isEqualTo(Long.toString(selected.target().gameDesignVersionRowId()));
assertThat(first.appliedCommitId()).isEqualTo(selected.commitId().toString());
assertThat(first.contentDigest())
- .isEqualTo("414e333c7a695aa81cfe86d39eda7adb13cd3e16b78d2e2bed5df67b08181a5a");
+ .isEqualTo("72f88d8fe8ad3d7f99a83e8cf0bb394fba649cae7e3e96da8567ad7de141cf01");
}
@Test
@@ -147,10 +147,15 @@ private static DraftCommitBinding selectedBinding() throws Exception {
// Payload JSON is stored as text in the binding; normalize unordered fixture maps first.
var revisions = new java.util.ArrayList();
for (var revision : selected.revisions()) {
- revisions.add(new DraftCommitBinding.RevisionPayload(
- revision.revisionOrder(), revision.revisionId(), revision.owner(),
- new String(net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8(
- revision.payload()), java.nio.charset.StandardCharsets.UTF_8)));
+ revisions.add(
+ new DraftCommitBinding.RevisionPayload(
+ revision.revisionOrder(),
+ revision.revisionId(),
+ revision.owner(),
+ new String(
+ net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8(
+ revision.payload()),
+ java.nio.charset.StandardCharsets.UTF_8)));
}
return DraftCommitBinding.create(
selected.target(),
From 0bd753beb117952d9a1dd97e1dc61f273044e55d Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 03:54:56 +1300
Subject: [PATCH 12/55] Record passing physical selected-full publication and
immutable readback proof
---
design/project-management/ai-observations.md | 2 +-
...ame-authoring-publishing-and-activation.md | 6 +-
...nerPublicationPostgresIntegrationTest.java | 137 +++++++++++++-----
3 files changed, 108 insertions(+), 37 deletions(-)
diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md
index 43f2e8d947..1fa88444b2 100644
--- a/design/project-management/ai-observations.md
+++ b/design/project-management/ai-observations.md
@@ -345,4 +345,4 @@ Entry format:
- `2026-10-16`: A multiline conflict-marker resolver truncated three trailing file portions during an unpublished selected-owner carry. Native `git merge-file` reconstruction from the exact parents recovered the complete files. Bound marker lines explicitly, verify conflict counts and file tails, and inspect the final net diff against both original parents before committing; a clean whitespace check alone cannot detect lost content.
-- 2026-10-15: Selected-full digest fixture R41/R42 produced different fixed-golden values from otherwise unchanged source. The fixture serialized `Map.of` payloads into strings inside a canonical binding; outer canonicalization preserves string contents and therefore does not normalize the inner map order. Restored explicit RFC 8785 normalization of each fixture payload before binding creation. Updating a golden from one failing run alone did not establish a stable vector; retain equality/mutation checks and verify the normalized vector before claiming deterministic proof. No production digest or retained bytes were changed.
+- 2026-10-15: Selected-full digest fixture R41/R42 produced different fixed-golden values from otherwise unchanged source. The fixture serialized `Map.of` payloads into strings inside a canonical binding; outer canonicalization preserves string contents and therefore does not normalize the inner map order. Restored explicit RFC 8785 normalization of each fixture payload before binding creation. Updating a golden from one failing run alone did not establish a stable vector; retain equality/mutation checks and verify the normalized vector before claiming deterministic proof. No production digest or retained bytes were changed. R44 and the fresh R45 JVM agree on the normalized vector; all 686 GDS unit cases pass in R45.
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index 013777639c..ac6fd0e46f 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -12,7 +12,11 @@ The source candidate prepares complete selected-owner publication consumption un
Entity's new V1011 prepares the freshly founded empty selected source catalogue and its complete explicit family/equipment evidence; Automation's new V1003 prepares empty selected source retention. Both are forward additions over their current combined service/Saga parents. Their command/read transports and owner services remain standalone and unregistered. These are bounded empty-source components, not arbitrary Entity authoring, script publication or runtime rule execution. Inherited Account migration history and numbering are unchanged by this candidate.
-The first R36 affected gate passes Automation 1,206, Common 818, shared-test-support 55, Entity 261 and Game Logic 117 unit cases with zero skips; those unchanged scopes remain up-to-date in R38. R38 freshly passes all 178 Common Security unit cases and 23 native PostgreSQL cases: Entity 11, Automation 11 and Game Logic one, with zero failures, errors or skips. The corrected numbered migration checks exclude Flyway's null-version schema marker while complete pre/post row and xmin history assertions retain it. Passive capture identifies all six run-owned PostgreSQL containers without ownership gaps or observer errors. R44 reaches the actual v4 insert and preserves the deferred SQL atomicity guard: committing a release while its operation remains pending is refused. The composition now uses the existing Spring jOOQ transaction provider, retains the actual empty asset snapshot/candidate through existing owner services, and commits Version/artifact state, successful attempt and original operation seal with the bundle in one transaction. Candidate origin and manifest metadata remain controlled; no object-store delivery is proved. The normalized deterministic unit vector and physical atomic publication/readback/retry remain under qualification. No passing full-profile writer or complete authenticated cross-owner result is claimed. Unit carriers, source/provenance inputs, creator/issuer/environment and PKI remain explicitly controlled where used. Retained historical release bytes keep their existing scoped read/retry meaning and are not upgraded into the new profile. Genuine creator, issuer, environment, immutable release and continuous-protection authority, runtime placement and operational delivery remain unavailable; all four genuine Gameplay handoffs remain open and broader Unit 1B/corpus stays paused.
+Focused component qualification passes. R45 freshly executes all 686 Game Design unit cases and the five-store PostgreSQL composition with zero failures, errors or skips; GDS static analysis, formatting and documentation checks pass. The composition uses real Game Design, World, Entity, Automation and Game Logic stores, actual empty Entity/Automation source receipts, a retained Game Logic terminal and authenticated participant digest reads. Existing owner services retain an empty asset snapshot and exact candidate; one owner transaction commits the selected v4 bundle, Version and artifact publication states, successful attempt and original operation seal. Independent immutable bundle readback and exact retry preserve stored bytes and row versions. The Java bundle repository now accepts canonical v4/World-4 alongside exact retained v2/World-3, using existing V1020 SQL guards without a migration change.
+
+R38 freshly passes 178 Common Security units and 23 native PostgreSQL cases: Entity 11, Automation 11 and Game Logic one, with zero skips. Automation 1,206, Common 818, shared-test-support 55, Entity 261 and Game Logic 117 units retain their original R36 passing attribution; their unchanged scopes are up-to-date in R38. Complete retained migration rows/xmin, including Flyway's null-version marker, and source/Saga retention assertions remain preserved. R45 passive capture owns all five run-created PostgreSQL containers without ownership gaps or observer errors; this focused success does not release inherited broader PostgreSQL/Redis infrastructure holds.
+
+Upstream Account authorization, source/provenance inputs, creator, issuer, environment and PKI remain explicitly controlled where used. Empty asset manifest metadata and the candidate delivery origin are controlled; no object-store write or public delivery is proved. These standalone unregistered owner components do not establish genuine authority, current or continuous protection, runtime activation, actor placement or operational delivery. Historical release bytes retain their original scoped read/retry meaning. All four genuine Gameplay handoffs remain open and broader Unit 1B/corpus stays paused.
### Selected template publication and original launch reads
diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
index 1fe5d6485f..2f2d3ca395 100644
--- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
+++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
@@ -493,26 +493,62 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema
new VersionRepository(gds.dsl()),
new ObjectMapper());
var controlledEmptyManifest = controlledEmptyManifest();
- var artifactRepository = new net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository(gds.dsl());
+ var artifactRepository =
+ new net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository(
+ gds.dsl());
var versions = new VersionRepository(gds.dsl());
- var artifactService = new net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl(
- artifactRepository, null, versions, null, null, null, null, null, new ObjectMapper());
- var assetPublication = new net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository(gds.dsl());
- var exportSnapshot = gds.write().execute(ignored -> assetPublication.freezeOrReadSnapshot(
- versionDto.tenantId(), versionDto.versionNumber()));
+ var artifactService =
+ new net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl(
+ artifactRepository,
+ null,
+ versions,
+ null,
+ null,
+ null,
+ null,
+ null,
+ new ObjectMapper());
+ var assetPublication =
+ new net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository(
+ gds.dsl());
+ var exportSnapshot =
+ gds.write()
+ .execute(
+ ignored ->
+ assetPublication.freezeOrReadSnapshot(
+ versionDto.tenantId(), versionDto.versionNumber()));
assertThat(exportSnapshot.items()).isEmpty();
- gds.write().execute(ignored -> artifactService.stageExport(versionDto.tenantId(), versionDto.id(),
- versionDto.versionNumber(), publicationRequest.derivedWorkflowIdentity()));
- var candidateService = new net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceImpl(
- versions, new GameRepository(gds.dsl()),
- new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository(gds.dsl()),
- artifactRepository, assetPublication, gds.transactions(), new ObjectMapper());
- // Controlled delivery origin and manifest metadata; no object-store or public delivery proof.
- var candidate = new net.firedevops.firemud.gamedesign.service.FrozenAssetExportCandidate(
- controlledEmptyManifest, "https://controlled.invalid/assets");
- assertThat(candidateService.recordExportCandidate(versionDto.tenantId(), versionDto.versionNumber(), candidate))
+ gds.write()
+ .execute(
+ ignored ->
+ artifactService.stageExport(
+ versionDto.tenantId(),
+ versionDto.id(),
+ versionDto.versionNumber(),
+ publicationRequest.derivedWorkflowIdentity()));
+ var candidateService =
+ new net.firedevops.firemud.gamedesign.service.impl
+ .VersionAssetExportCandidateServiceImpl(
+ versions,
+ new GameRepository(gds.dsl()),
+ new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository(
+ gds.dsl()),
+ artifactRepository,
+ assetPublication,
+ gds.transactions(),
+ new ObjectMapper());
+ // Controlled delivery origin and manifest metadata; no object-store or public delivery
+ // proof.
+ var candidate =
+ new net.firedevops.firemud.gamedesign.service.FrozenAssetExportCandidate(
+ controlledEmptyManifest, "https://controlled.invalid/assets");
+ assertThat(
+ candidateService.recordExportCandidate(
+ versionDto.tenantId(), versionDto.versionNumber(), candidate))
.isEqualTo(candidate);
- assertThat(candidateService.readExportCandidate(versionDto.tenantId(), versionDto.versionNumber()))
+ assertThat(
+ candidateService.readExportCandidate(
+ versionDto.tenantId(), versionDto.versionNumber()))
.isEqualTo(candidate);
assertThatThrownBy(
() ->
@@ -542,24 +578,52 @@ versions, new GameRepository(gds.dsl()),
.execute(
ignored -> {
String workflow = publicationRequest.derivedWorkflowIdentity();
- var exported = artifactService.markExportedUnattested(versionDto.tenantId(), versionDto.id(),
- versionDto.versionNumber(), workflow, controlledEmptyManifest);
- var result = releaseOwner.createFullVersionBundle(
- versionDto, workflow, controlledEmptyManifest, "controlled-generation-input",
- participantDigests, worldOwners.startLocationEvidence());
- var version = versions.findByTenantIdAndIdForUpdate(versionDto.tenantId(), versionDto.id()).orElseThrow();
+ var exported =
+ artifactService.markExportedUnattested(
+ versionDto.tenantId(),
+ versionDto.id(),
+ versionDto.versionNumber(),
+ workflow,
+ controlledEmptyManifest);
+ var result =
+ releaseOwner.createFullVersionBundle(
+ versionDto,
+ workflow,
+ controlledEmptyManifest,
+ "controlled-generation-input",
+ participantDigests,
+ worldOwners.startLocationEvidence());
+ var version =
+ versions
+ .findByTenantIdAndIdForUpdate(versionDto.tenantId(), versionDto.id())
+ .orElseThrow();
version.setVersionState(VersionLifecycleState.PUBLISHED);
- version.setVersionStateEpoch(Math.addExact(version.getVersionStateEpoch(), 1L));
+ version.setVersionStateEpoch(
+ Math.addExact(version.getVersionStateEpoch(), 1L));
versions.save(version);
- artifactService.markPublished(versionDto.tenantId(), versionDto.id(), exported.stateEpoch(),
- workflow, controlledEmptyManifest.manifestHash());
- var attempts = new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository(gds.dsl());
- var attempt = attempts.findByPublishWorkflowIdForUpdate(workflow).orElseThrow();
- attempt.setStatus(net.firedevops.firemud.gamedesign.model.PublishAttemptStatus.SUCCEEDED);
+ artifactService.markPublished(
+ versionDto.tenantId(),
+ versionDto.id(),
+ exported.stateEpoch(),
+ workflow,
+ controlledEmptyManifest.manifestHash());
+ var attempts =
+ new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository(
+ gds.dsl());
+ var attempt =
+ attempts.findByPublishWorkflowIdForUpdate(workflow).orElseThrow();
+ attempt.setStatus(
+ net.firedevops.firemud.gamedesign.model.PublishAttemptStatus.SUCCEEDED);
attempts.save(attempt);
var operation = selectedOwnerReservation.operation();
- new net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository(gds.dsl())
- .seal(operation.tenantKey(), workflow, operation.versionId(), operation.selectionDigest(), true);
+ new net.firedevops.firemud.gamedesign.publication
+ .GameDesignPublicationOperationRepository(gds.dsl())
+ .seal(
+ operation.tenantKey(),
+ workflow,
+ operation.versionId(),
+ operation.selectionDigest(),
+ true);
return result;
});
assertThat(written.attestationSchemaVersion()).isEqualTo("v4");
@@ -1015,7 +1079,8 @@ private static ExportedAssetManifest controlledEmptyManifest() throws Exception
HexFormat.of()
.formatHex(
java.security.MessageDigest.getInstance("SHA-256")
- .digest("{\"assets\":{},\"schemaVersion\":1}".getBytes(StandardCharsets.UTF_8)));
+ .digest(
+ "{\"assets\":{},\"schemaVersion\":1}".getBytes(StandardCharsets.UTF_8)));
return new ExportedAssetManifest("sha256:" + hash, 1, List.of(), List.of());
}
@@ -1080,9 +1145,11 @@ private static Store store(
var manager = new DataSourceTransactionManager(dataSource);
var configuration = new org.jooq.impl.DefaultConfiguration();
configuration.set(SQLDialect.POSTGRES);
- configuration.set(new org.jooq.impl.DataSourceConnectionProvider(
- new TransactionAwareDataSourceProxy(dataSource)));
- configuration.set(new org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider(manager));
+ configuration.set(
+ new org.jooq.impl.DataSourceConnectionProvider(
+ new TransactionAwareDataSourceProxy(dataSource)));
+ configuration.set(
+ new org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider(manager));
DSLContext dsl = DSL.using(configuration);
return new Store(schema, dsl, manager);
}
From c7587f32f4beda6d601afe545030ba872cf32122 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 04:13:47 +1300
Subject: [PATCH 13/55] Include selected-source migration in Entity upgrade
history
---
.../PreseededActorAssignmentIntegrationTest.java | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java
index 5726f1b3a9..17e4e1d591 100644
--- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java
+++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java
@@ -403,7 +403,7 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace(
upgradedHistory.subList(parentHistory.size(), upgradedHistory.size());
assertThat(successorHistory)
.extracting(AppliedMigration::version)
- .containsExactly("1006", "1007", "1008", "1009", "1010");
+ .containsExactly("1006", "1007", "1008", "1009", "1010", "1011");
assertThat(successorHistory)
.extracting(AppliedMigration::script)
.containsExactly(
@@ -411,7 +411,8 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace(
"V1007__preseeded_assignment_owner_snapshot.sql",
"V1008__canonical_gameplay_roster_snapshots.sql",
"V1009__canonical_publication_uuid_actor_evidence.sql",
- "V1010__canonical_roster_owner_counters.sql");
+ "V1010__canonical_roster_owner_counters.sql",
+ "V1011__fresh_selected_empty_source_catalogue.sql");
assertThat(successorHistory).extracting(AppliedMigration::checksum).doesNotContainNull();
try (Connection connection = connectToSchema(schema)) {
From 3f7b8528e6545706919b9807f0b95876ed523beb Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 17:33:56 +1300
Subject: [PATCH 14/55] test(game-design): restore every-participant release
profile refusal proof
---
...ame-authoring-publishing-and-activation.md | 6 ++++
...PublishedReleaseBundleServiceImplTest.java | 36 +++++++++++++++++++
2 files changed, 42 insertions(+)
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index ff4b118847..808dac1d9e 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -18,6 +18,12 @@ R38 freshly passes 178 Common Security units and 23 native PostgreSQL cases: Ent
Upstream Account authorization, source/provenance inputs, creator, issuer, environment and PKI remain explicitly controlled where used. Empty asset manifest metadata and the candidate delivery origin are controlled; no object-store write or public delivery is proved. These standalone unregistered owner components do not establish genuine authority, current or continuous protection, runtime activation, actor placement or operational delivery. Historical release bytes retain their original scoped read/retry meaning. All four genuine Gameplay handoffs remain open and broader Unit 1B/corpus stays paused.
+### Selected-full release service refusal proof
+
+The existing release-bundle service test independently substitutes each of the five participant digest schemas and verifies that the service refuses the mixed vector before saving a release. The current full `4/3/1/6/2` positive, immutable selected retry, source-capture and command validation cases remain intact; historical schema-3 consumer support is not widened.
+
+The focused release service, release contract, complete-binding and descriptor owner classes freshly pass 72 unit cases with zero failures, errors or skips. Canonical formatting, style, Test Checkstyle and SpotBugs pass. These tests use controlled evidence and mocked owner repositories or services; they do not execute SQL or establish a genuine immutable release, creator or issuer authority, currentness, publication enablement, activation or a Gameplay handoff.
+
### Selected template publication and original launch reads
The prepared source adds owner-local Template configuration genesis, synchronized revision/application, selected source capture and normalized tenant reference-phase owners over the already guarded tables. `SelectedDraftPublicationOwner` retains the exact selection, pending attempt, complete source capture and immutable template/World relation in one caller-owned writable transaction; existing operation bytes are never upgraded and old descriptor or reference provenance is not backfilled. The original StartSession template-association read authenticates Game Session and independently verifies Account’s exact redeemed operation before its read-only snapshot. It accepts only current selector-bound release-v2 evidence for the configured path and refuses older non-selector releases rather than fabricating later bundles. These components are unregistered and add no migration or runtime enabling flag.
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
index 63835d0239..be1631932c 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
@@ -236,6 +236,42 @@ void selectedFullV4RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChanged
org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any());
}
+ @Test
+ void selectedFullV4RejectsEveryMixedParticipantSchemaBeforeWrite() throws Exception {
+ var evidence = selectorEvidence();
+ var participants =
+ PublishedWorldSelectorFixtures.participants(
+ 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
+ for (int index = 0; index < participants.size(); index++) {
+ var mixed = new java.util.ArrayList<>(participants);
+ var participant = mixed.get(index);
+ mixed.set(
+ index,
+ new PublishParticipantDigestDto(
+ participant.participantKey(),
+ participant.scopeValue(),
+ participant.baseVersionId(),
+ participant.appliedCommitId(),
+ participant.contentDigest(),
+ participant.digestSchemaVersion() == 1 ? 2 : participant.digestSchemaVersion() - 1,
+ participant.abilitySchemaDigest(),
+ participant.errorCode(),
+ participant.errorMessage()));
+ assertThatThrownBy(
+ () ->
+ service.createFullVersionBundle(
+ selectorVersion(),
+ "publish-workflow",
+ emptyManifest(),
+ "genrev-1",
+ mixed,
+ evidence))
+ .as("mixed profile for %s", participant.participantKey())
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+ org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any());
+ }
+
@Test
void selectedFullV4RequiresSelectedSourceCaptureBeforeBundleWrite() throws Exception {
var evidence = selectorEvidence();
From 9abc3040fa67001fbf780c45071e2eb761bc7ccc Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 18:11:33 +1300
Subject: [PATCH 15/55] test: restore canonical Version identity storage proof
---
...ame-authoring-publishing-and-activation.md | 6 +
...rsionCanonicalIdentityIntegrationTest.java | 514 ++++++++++++++++++
2 files changed, 520 insertions(+)
create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index 808dac1d9e..4d36a16314 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -6,6 +6,12 @@ This is a non-normative implementation tracker for game authoring, publishing, a
## Current Status
+### Canonical Version identity storage proof
+
+The restored Version identity native owner test preserves the original retained Version fields and row version through the V35.1 identity migration and later default migrations, leaves its canonical identity unmapped and refuses a later identity backfill. Fresh Version creation and update retain the exact persisted Game provenance, including a Game retained through V29. Wrong-tenant, missing, null and nil canonical lookups preserve Version and Game row versions; database guards reject identity replacement, mismatched source, nil identity and canonical truncation, while the explicitly unmapped retained Version remains deletable.
+
+All six native cases freshly pass with zero failures, errors or skips against the canonical PostgreSQL image and owning filesystem migrations. Canonical formatting, style, Integration Checkstyle and SpotBugs pass; passive capture identifies the one run-owned PostgreSQL container and independently confirms its absence after completion. This proves owner-local identity and historical retention mechanics with controlled setup. It does not establish creator or issuer authority, currentness, publication enablement, an immutable production release, activation or a genuine Gameplay handoff. No production, installed migration or registration changes are included.
+
### Selected-full owner publication preparation
The source candidate prepares complete selected-owner publication consumption under the [canonical selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile). It reuses the actual parent World closure producer, adds its full-profile consumer mapping, and composes the selected Game Design digest read/collector with independently retained Entity, Automation and Game Logic receipts. The Game Logic adapter reads the exact retained terminal, selected source and manifest through the existing owner repository and returns both manifest and ability projections; its default Spring composition remains denied. Private selected writer mechanics use the exact canonical selection/request binding and selected gate. Public Game Design fresh/PENDING publication remains denied. Existing Game Design V1020 storage is reused; no Game Design migration is added.
diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java
new file mode 100644
index 0000000000..7d64feaf52
--- /dev/null
+++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java
@@ -0,0 +1,514 @@
+package integration.net.firedevops.firemud.gamedesign.repository;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.gamedesign.entity.Game;
+import net.firedevops.firemud.gamedesign.entity.Version;
+import net.firedevops.firemud.gamedesign.repository.GameRepository;
+import net.firedevops.firemud.gamedesign.repository.VersionRepository;
+import net.firedevops.firemud.test.TestContainerImages;
+import org.flywaydb.core.Flyway;
+import org.flywaydb.core.api.MigrationVersion;
+import org.jooq.DSLContext;
+import org.jooq.Field;
+import org.jooq.SQLDialect;
+import org.jooq.Table;
+import org.jooq.exception.DataAccessException;
+import org.jooq.impl.DSL;
+import org.junit.jupiter.api.Test;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
+import org.springframework.transaction.support.TransactionTemplate;
+import org.testcontainers.containers.PostgreSQLContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+@Testcontainers(disabledWithoutDocker = true)
+class VersionCanonicalIdentityIntegrationTest {
+ private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service";
+ private static final MigrationVersion V35 = MigrationVersion.fromVersion("35");
+ private static final Table> VERSION = DSL.table(DSL.name("version"));
+ private static final Field ID = DSL.field(DSL.name("id"), Long.class);
+ private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class);
+ private static final Field VERSION_NUMBER =
+ DSL.field(DSL.name("version_number"), Integer.class);
+ private static final Field VERSION_STATE =
+ DSL.field(DSL.name("version_state"), String.class);
+ private static final Field VERSION_STATE_EPOCH =
+ DSL.field(DSL.name("version_state_epoch"), Long.class);
+ private static final Field SCRIPT_PATCH_VERSION =
+ DSL.field(DSL.name("script_patch_version"), String.class);
+ private static final Field BASE_VERSION_ID =
+ DSL.field(DSL.name("base_version_id"), Long.class);
+ private static final Field IS_SCRIPT_ONLY =
+ DSL.field(DSL.name("is_script_only"), Boolean.class);
+ private static final Field NOTES = DSL.field(DSL.name("notes"), String.class);
+ private static final Field CREATED_AT =
+ DSL.field(DSL.name("created_at"), java.sql.Timestamp.class);
+ private static final Field UPDATED_AT =
+ DSL.field(DSL.name("updated_at"), java.sql.Timestamp.class);
+ private static final Field CANONICAL_VERSION_ID =
+ DSL.field(DSL.name("canonical_version_id"), UUID.class);
+ private static final Field CANONICAL_TENANT_ID =
+ DSL.field(DSL.name("canonical_tenant_id"), UUID.class);
+ private static final Field IDENTITY_SOURCE_GAME_ROW_ID =
+ DSL.field(DSL.name("identity_source_game_row_id"), Long.class);
+ private static final Field IDENTITY_SOURCE_GAME_TENANT_KEY =
+ DSL.field(DSL.name("identity_source_game_tenant_key"), String.class);
+ private static final Field IDENTITY_SOURCE_PROVENANCE_KIND =
+ DSL.field(DSL.name("identity_source_provenance_kind"), String.class);
+ private static final UUID NIL_UUID = new UUID(0L, 0L);
+
+ @Container
+ static PostgreSQLContainer> postgres =
+ new PostgreSQLContainer<>(TestContainerImages.postgres());
+
+ @Test
+ void v35_1PreservesRetainedVersionHistoryAndLeavesIdentityUnmapped() {
+ Fixture fixture = fixture(V35);
+ Game game = saveGame(fixture, "retained-version-source");
+ Long retainedVersionId = insertRetainedVersion(fixture.dsl(), game.getTenantId());
+ Map retainedFieldsBefore = retainedFields(fixture.dsl(), retainedVersionId);
+ String retainedXminBefore = versionXmin(fixture.dsl(), retainedVersionId);
+
+ migrate(fixture.dataSource(), fixture.schema(), null);
+
+ assertThat(retainedFields(fixture.dsl(), retainedVersionId)).isEqualTo(retainedFieldsBefore);
+ assertThat(versionXmin(fixture.dsl(), retainedVersionId)).isEqualTo(retainedXminBefore);
+ assertThat(
+ fixture
+ .dsl()
+ .select(CANONICAL_VERSION_ID)
+ .from(VERSION)
+ .where(ID.eq(retainedVersionId))
+ .fetchOne(CANONICAL_VERSION_ID))
+ .isNull();
+ assertThat(
+ fixture
+ .dsl()
+ .select(CANONICAL_TENANT_ID)
+ .from(VERSION)
+ .where(ID.eq(retainedVersionId))
+ .fetchOne(CANONICAL_TENANT_ID))
+ .isNull();
+ assertThat(
+ fixture
+ .dsl()
+ .select(IDENTITY_SOURCE_GAME_ROW_ID)
+ .from(VERSION)
+ .where(ID.eq(retainedVersionId))
+ .fetchOne(IDENTITY_SOURCE_GAME_ROW_ID))
+ .isNull();
+ assertThat(
+ fixture
+ .versionRepository()
+ .findByCanonicalTenantIdAndCanonicalVersionId(
+ game.getCanonicalTenantId(), UUID.randomUUID()))
+ .isEmpty();
+
+ assertThatThrownBy(
+ () ->
+ fixture
+ .dsl()
+ .update(VERSION)
+ .set(CANONICAL_VERSION_ID, UUID.randomUUID())
+ .set(CANONICAL_TENANT_ID, game.getCanonicalTenantId())
+ .set(IDENTITY_SOURCE_GAME_ROW_ID, game.getId())
+ .set(IDENTITY_SOURCE_GAME_TENANT_KEY, game.getTenantId())
+ .set(IDENTITY_SOURCE_PROVENANCE_KIND, "NEW_GAME_ROW")
+ .where(ID.eq(retainedVersionId))
+ .execute())
+ .isInstanceOf(DataAccessException.class)
+ .hasMessageContaining("retained Version rows cannot be assigned a canonical identity");
+ }
+
+ @Test
+ void savePersistsAndReadsBackFreshCanonicalIdentityAcrossUpdate() {
+ Fixture fixture = fixture(null);
+ Game game = saveGame(fixture, "fresh-version-source");
+
+ Version inserted =
+ fixture
+ .transactionTemplate()
+ .execute(status -> fixture.versionRepository().save(version(game)));
+ assertThat(inserted).isNotNull();
+ assertThat(inserted.getCanonicalVersionId()).isNotNull().isNotEqualTo(NIL_UUID);
+ assertThat(inserted.getCanonicalTenantId()).isEqualTo(game.getCanonicalTenantId());
+ assertThat(inserted.getIdentitySourceGameRowId()).isEqualTo(game.getId());
+ assertThat(inserted.getIdentitySourceGameTenantKey()).isEqualTo(game.getTenantId());
+ assertThat(inserted.getIdentitySourceProvenanceKind()).isEqualTo("NEW_GAME_ROW");
+
+ Version exactRead =
+ fixture
+ .versionRepository()
+ .findByCanonicalTenantIdAndCanonicalVersionId(
+ game.getCanonicalTenantId(), inserted.getCanonicalVersionId())
+ .orElseThrow();
+ assertIdentityMatches(exactRead, game, inserted.getCanonicalVersionId());
+ assertIdentityMatches(
+ fixture.versionRepository().findById(inserted.getId()).orElseThrow(),
+ game,
+ inserted.getCanonicalVersionId());
+
+ inserted.setNotes("updated without replacing owner identity");
+ Version updated =
+ fixture.transactionTemplate().execute(status -> fixture.versionRepository().save(inserted));
+ assertThat(updated).isNotNull();
+ assertThat(updated.getNotes()).isEqualTo("updated without replacing owner identity");
+ assertIdentityMatches(updated, game, inserted.getCanonicalVersionId());
+ assertIdentityMatches(
+ fixture
+ .versionRepository()
+ .findByCanonicalTenantIdAndCanonicalVersionId(
+ game.getCanonicalTenantId(), inserted.getCanonicalVersionId())
+ .orElseThrow(),
+ game,
+ inserted.getCanonicalVersionId());
+ }
+
+ @Test
+ void newVersionIdentityUsesExactRetainedGameSourceProvenance() {
+ Fixture fixture = fixtureWithRetainedGame();
+ Game retainedGame = fixture.gameRepository().findByTenantId("retained-version-game-source");
+ assertThat(retainedGame).isNotNull();
+
+ Version saved =
+ fixture
+ .transactionTemplate()
+ .execute(status -> fixture.versionRepository().save(version(retainedGame)));
+
+ assertThat(saved).isNotNull();
+ assertThat(saved.getCanonicalVersionId()).isNotNull().isNotEqualTo(NIL_UUID);
+ assertThat(saved.getIdentitySourceProvenanceKind()).isEqualTo("RETAINED_GAME_V29");
+ assertIdentityMatches(
+ fixture
+ .versionRepository()
+ .findByCanonicalTenantIdAndCanonicalVersionId(
+ retainedGame.getCanonicalTenantId(), saved.getCanonicalVersionId())
+ .orElseThrow(),
+ retainedGame,
+ saved.getCanonicalVersionId(),
+ "RETAINED_GAME_V29");
+ }
+
+ @Test
+ void canonicalLookupRejectsWrongTenantMissingAndNilIdsWithoutMutation() {
+ Fixture fixture = fixture(null);
+ Game owner = saveGame(fixture, "lookup-version-owner");
+ Game other = saveGame(fixture, "lookup-version-other");
+ Version saved =
+ fixture
+ .transactionTemplate()
+ .execute(status -> fixture.versionRepository().save(version(owner)));
+ assertThat(saved).isNotNull();
+ String versionXminBefore = versionXmin(fixture.dsl(), saved.getId());
+ String ownerXminBefore = gameXmin(fixture.dsl(), owner.getId());
+ String otherXminBefore = gameXmin(fixture.dsl(), other.getId());
+
+ assertThat(
+ fixture
+ .versionRepository()
+ .findByCanonicalTenantIdAndCanonicalVersionId(
+ other.getCanonicalTenantId(), saved.getCanonicalVersionId()))
+ .isEmpty();
+ assertThat(
+ fixture
+ .versionRepository()
+ .findByCanonicalTenantIdAndCanonicalVersionId(
+ owner.getCanonicalTenantId(), UUID.randomUUID()))
+ .isEmpty();
+ assertThat(
+ fixture
+ .versionRepository()
+ .findByCanonicalTenantIdAndCanonicalVersionId(owner.getCanonicalTenantId(), null))
+ .isEmpty();
+ assertThat(
+ fixture
+ .versionRepository()
+ .findByCanonicalTenantIdAndCanonicalVersionId(null, saved.getCanonicalVersionId()))
+ .isEmpty();
+ assertThat(
+ fixture
+ .versionRepository()
+ .findByCanonicalTenantIdAndCanonicalVersionId(
+ NIL_UUID, saved.getCanonicalVersionId()))
+ .isEmpty();
+ assertThat(
+ fixture
+ .versionRepository()
+ .findByCanonicalTenantIdAndCanonicalVersionId(
+ owner.getCanonicalTenantId(), NIL_UUID))
+ .isEmpty();
+ assertIdentityMatches(
+ fixture
+ .versionRepository()
+ .findByCanonicalTenantIdAndCanonicalVersionId(
+ owner.getCanonicalTenantId(), saved.getCanonicalVersionId())
+ .orElseThrow(),
+ owner,
+ saved.getCanonicalVersionId());
+
+ assertThat(versionXmin(fixture.dsl(), saved.getId())).isEqualTo(versionXminBefore);
+ assertThat(gameXmin(fixture.dsl(), owner.getId())).isEqualTo(ownerXminBefore);
+ assertThat(gameXmin(fixture.dsl(), other.getId())).isEqualTo(otherXminBefore);
+ }
+
+ @Test
+ void databaseRejectsIdentityMutationNilIdentityAndMismatchedSource() {
+ Fixture fixture = fixture(null);
+ Game owner = saveGame(fixture, "mutation-version-owner");
+ Game other = saveGame(fixture, "mutation-version-other");
+ Version saved =
+ fixture
+ .transactionTemplate()
+ .execute(status -> fixture.versionRepository().save(version(owner)));
+ assertThat(saved).isNotNull();
+
+ assertThatThrownBy(
+ () ->
+ fixture
+ .dsl()
+ .update(VERSION)
+ .set(CANONICAL_VERSION_ID, UUID.randomUUID())
+ .where(ID.eq(saved.getId()))
+ .execute())
+ .isInstanceOf(DataAccessException.class)
+ .hasMessageContaining("canonical Version identity and its tenant source are immutable");
+ assertThatThrownBy(
+ () -> fixture.dsl().deleteFrom(VERSION).where(ID.eq(saved.getId())).execute())
+ .isInstanceOf(DataAccessException.class)
+ .hasMessageContaining("canonical Version identity is immutable");
+
+ assertThatThrownBy(
+ () ->
+ fixture
+ .dsl()
+ .execute(
+ "INSERT INTO version (tenant_id, version_number, version_state, "
+ + "version_state_epoch, canonical_version_id, canonical_tenant_id, "
+ + "identity_source_game_row_id, identity_source_game_tenant_key, "
+ + "identity_source_provenance_kind) "
+ + "VALUES (?, 2, 'DRAFT', 1, ?, ?, ?, ?, ?)",
+ owner.getTenantId(),
+ NIL_UUID,
+ owner.getCanonicalTenantId(),
+ owner.getId(),
+ owner.getTenantId(),
+ "NEW_GAME_ROW"))
+ .isInstanceOf(DataAccessException.class);
+
+ assertThatThrownBy(
+ () ->
+ fixture
+ .dsl()
+ .execute(
+ "INSERT INTO version (tenant_id, version_number, version_state, "
+ + "version_state_epoch, canonical_version_id, canonical_tenant_id, "
+ + "identity_source_game_row_id, identity_source_game_tenant_key, "
+ + "identity_source_provenance_kind) "
+ + "VALUES (?, 3, 'DRAFT', 1, ?, ?, ?, ?, ?)",
+ owner.getTenantId(),
+ UUID.randomUUID(),
+ owner.getCanonicalTenantId(),
+ other.getId(),
+ other.getTenantId(),
+ "NEW_GAME_ROW"))
+ .isInstanceOf(DataAccessException.class)
+ .hasMessageContaining(
+ "canonical Version identity source does not match its exact game row");
+
+ Version wrongTenantAlias = version(owner);
+ wrongTenantAlias.setTenantId(owner.getCanonicalTenantId().toString());
+ assertThatThrownBy(
+ () ->
+ fixture
+ .transactionTemplate()
+ .execute(status -> fixture.versionRepository().save(wrongTenantAlias)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("no exact Game Design source row");
+ }
+
+ @Test
+ void canonicalIdentityRejectsTruncateWhileUnmappedRetainedVersionRemainsDeletable() {
+ Fixture mappedFixture = fixture(null);
+ Game mappedGame = saveGame(mappedFixture, "truncate-version-owner");
+ Version mapped =
+ mappedFixture
+ .transactionTemplate()
+ .execute(status -> mappedFixture.versionRepository().save(version(mappedGame)));
+ assertThat(mapped).isNotNull();
+
+ assertThatThrownBy(() -> mappedFixture.dsl().execute("TRUNCATE TABLE version CASCADE"))
+ .isInstanceOf(DataAccessException.class)
+ .hasMessageContaining("canonical Version identities cannot be truncated");
+
+ Fixture retainedFixture = fixture(V35);
+ Game retainedGame = saveGame(retainedFixture, "delete-retained-version-owner");
+ Long retainedVersionId =
+ insertRetainedVersion(retainedFixture.dsl(), retainedGame.getTenantId());
+ migrate(retainedFixture.dataSource(), retainedFixture.schema(), null);
+ assertThat(retainedFixture.dsl().deleteFrom(VERSION).where(ID.eq(retainedVersionId)).execute())
+ .isEqualTo(1);
+ }
+
+ private Fixture fixture(MigrationVersion target) {
+ String schema = "game_design_version_identity_" + UUID.randomUUID().toString().replace("-", "");
+ DriverManagerDataSource dataSource = dataSource(schema);
+ migrate(dataSource, schema, target);
+ DSLContext dsl =
+ DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES);
+ DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
+ TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
+ transactionTemplate.setIsolationLevel(
+ org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED);
+ GameRepository gameRepository = new GameRepository(dsl);
+ VersionRepository versionRepository = new VersionRepository(dsl);
+ return new Fixture(
+ schema, dataSource, dsl, gameRepository, versionRepository, transactionTemplate);
+ }
+
+ private Fixture fixtureWithRetainedGame() {
+ String schema = "gd_retained_version_identity_" + UUID.randomUUID().toString().replace("-", "");
+ DriverManagerDataSource dataSource = dataSource(schema);
+ migrate(dataSource, schema, MigrationVersion.fromVersion("28"));
+ DSLContext legacyDsl =
+ DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES);
+ legacyDsl.execute(
+ "INSERT INTO game (tenant_id, name, description) VALUES (?, ?, ?)",
+ "retained-version-game-source",
+ "Retained Version Source",
+ "Source row predating canonical tenant identity");
+ migrate(dataSource, schema, null);
+ return fixtureFromMigratedSchema(schema, dataSource);
+ }
+
+ private Fixture fixtureFromMigratedSchema(String schema, DriverManagerDataSource dataSource) {
+ DSLContext dsl =
+ DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES);
+ DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
+ TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
+ transactionTemplate.setIsolationLevel(
+ org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED);
+ GameRepository gameRepository = new GameRepository(dsl);
+ VersionRepository versionRepository = new VersionRepository(dsl);
+ return new Fixture(
+ schema, dataSource, dsl, gameRepository, versionRepository, transactionTemplate);
+ }
+
+ private DriverManagerDataSource dataSource(String schema) {
+ DriverManagerDataSource dataSource = new DriverManagerDataSource();
+ dataSource.setUrl(postgres.getJdbcUrl());
+ dataSource.setUsername(postgres.getUsername());
+ dataSource.setPassword(postgres.getPassword());
+ dataSource.setSchema(schema);
+ return dataSource;
+ }
+
+ private void migrate(DriverManagerDataSource dataSource, String schema, MigrationVersion target) {
+ var configuration =
+ Flyway.configure()
+ .dataSource(dataSource)
+ .schemas(schema)
+ .defaultSchema(schema)
+ .table(FLYWAY_TABLE)
+ .placeholders(Map.of("serviceSchema", schema))
+ .locations(
+ "filesystem:"
+ + java.nio.file.Path.of("src/main/resources/db/migration")
+ .toAbsolutePath()
+ .normalize());
+ if (target != null) {
+ configuration.target(target);
+ }
+ configuration.load().migrate();
+ }
+
+ private Game saveGame(Fixture fixture, String tenantKey) {
+ Game game = new Game();
+ game.setTenantId(tenantKey);
+ game.setName("Version Identity Owner");
+ game.setDescription("Source row for canonical Version identity");
+ return fixture.transactionTemplate().execute(status -> fixture.gameRepository().save(game));
+ }
+
+ private Long insertRetainedVersion(DSLContext dsl, String tenantId) {
+ return dsl.resultQuery(
+ "INSERT INTO version (tenant_id, version_number, version_state, version_state_epoch, "
+ + "script_patch_version, base_version_id, is_script_only, notes) "
+ + "VALUES (?, 4, 'FAILED', 3, NULL, NULL, FALSE, 'retained history') RETURNING id",
+ tenantId)
+ .fetchOne(0, Long.class);
+ }
+
+ private Map retainedFields(DSLContext dsl, Long versionId) {
+ return dsl.select(
+ ID,
+ TENANT_ID,
+ VERSION_NUMBER,
+ VERSION_STATE,
+ VERSION_STATE_EPOCH,
+ SCRIPT_PATCH_VERSION,
+ BASE_VERSION_ID,
+ IS_SCRIPT_ONLY,
+ NOTES,
+ CREATED_AT,
+ UPDATED_AT)
+ .from(VERSION)
+ .where(ID.eq(versionId))
+ .fetchSingle()
+ .intoMap();
+ }
+
+ private String versionXmin(DSLContext dsl, Long versionId) {
+ var row =
+ Objects.requireNonNull(
+ dsl.fetchOne("SELECT xmin::text AS xmin FROM version WHERE id = ?", versionId),
+ "Version xmin query returned no row");
+ return Objects.requireNonNull(
+ row.get("xmin", String.class), "Version xmin readback returned null");
+ }
+
+ private String gameXmin(DSLContext dsl, Long gameId) {
+ var row =
+ Objects.requireNonNull(
+ dsl.fetchOne("SELECT xmin::text AS xmin FROM game WHERE id = ?", gameId),
+ "Game xmin query returned no row");
+ return Objects.requireNonNull(
+ row.get("xmin", String.class), "Game xmin readback returned null");
+ }
+
+ private Version version(Game game) {
+ Version version = new Version();
+ version.setTenantId(game.getTenantId());
+ version.setVersionNumber(1);
+ version.setNotes("fresh version");
+ return version;
+ }
+
+ private void assertIdentityMatches(Version version, Game game, UUID canonicalVersionId) {
+ assertIdentityMatches(version, game, canonicalVersionId, "NEW_GAME_ROW");
+ }
+
+ private void assertIdentityMatches(
+ Version version, Game game, UUID canonicalVersionId, String provenanceKind) {
+ assertThat(version.getTenantId()).isEqualTo(game.getTenantId());
+ assertThat(version.getCanonicalVersionId()).isEqualTo(canonicalVersionId);
+ assertThat(version.getCanonicalTenantId()).isEqualTo(game.getCanonicalTenantId());
+ assertThat(version.getIdentitySourceGameRowId()).isEqualTo(game.getId());
+ assertThat(version.getIdentitySourceGameTenantKey()).isEqualTo(game.getTenantId());
+ assertThat(version.getIdentitySourceProvenanceKind()).isEqualTo(provenanceKind);
+ }
+
+ private record Fixture(
+ String schema,
+ DriverManagerDataSource dataSource,
+ DSLContext dsl,
+ GameRepository gameRepository,
+ VersionRepository versionRepository,
+ TransactionTemplate transactionTemplate) {}
+}
From d80c467654425ecd3d4167c741aea0a6b56eceef Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 18:18:06 +1300
Subject: [PATCH 16/55] test: preserve publish attempt CAS and terminal rows
---
...ame-authoring-publishing-and-activation.md | 6 +
...emptServiceTransactionIntegrationTest.java | 113 ++++++++++++++++++
2 files changed, 119 insertions(+)
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index 4d36a16314..f785f1dec3 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -6,6 +6,12 @@ This is a non-normative implementation tracker for game authoring, publishing, a
## Current Status
+### Publish-attempt revision and terminal retention proof
+
+The restored publish-attempt native regression reads two independent copies of a pending attempt, advances the winning revision from one to two and refuses the stale writer with the current CAS conflict code. A legal failure transition advances the revision to three; a later terminal rewrite is refused. Both refusals preserve the complete persisted attempt row and PostgreSQL row version. The existing transaction-boundary case separately confirms an actual writable Read Committed owner transaction.
+
+Both focused native cases freshly pass with zero failures, errors or skips. Canonical formatting, style, Integration Checkstyle and SpotBugs pass; passive capture identifies the one run-owned PostgreSQL container and independently confirms its absence after completion. This proves local repository revision and terminal guards. It does not execute the held publication finalizer or enable legacy digest backfill, public publication, creator or issuer authority, currentness, activation or a genuine Gameplay handoff. Other publication transaction cases retain their preceding attribution; no production, installed migration or registration changes are included.
+
### Canonical Version identity storage proof
The restored Version identity native owner test preserves the original retained Version fields and row version through the V35.1 identity migration and later default migrations, leaves its canonical identity unmapped and refuses a later identity backfill. Fresh Version creation and update retain the exact persisted Game provenance, including a Game retained through V29. Wrong-tenant, missing, null and nil canonical lookups preserve Version and Game row versions; database guards reject identity replacement, mismatched source, nil identity and canonical truncation, while the explicitly unmapped retained Version remains deletable.
diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java
index b6e370c341..34409aa394 100644
--- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java
+++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java
@@ -133,6 +133,119 @@ static void configure(DynamicPropertyRegistry registry) {
@MockitoSpyBean private RecordedParticipantDigestService recordedParticipantDigestService;
@MockitoSpyBean private VersionAssetArtifactService versionAssetArtifactService;
+ @Test
+ void publishAttemptSaveUsesRevisionCasAndRejectsStaleAndTerminalUpdates() {
+ String tenantId = isolatedTenantId();
+ Game game = new Game();
+ game.setTenantId(tenantId);
+ game.setName("publish-attempt-revision-proof-game");
+ gameRepository.save(game);
+
+ Version version = new Version();
+ version.setTenantId(tenantId);
+ version.setVersionNumber(1);
+ version.setVersionState(VersionLifecycleState.DRAFT);
+ version.setVersionStateEpoch(1L);
+ Version savedVersion = versionRepository.save(version);
+
+ PublishAttempt attempt = new PublishAttempt();
+ attempt.setTenantId(tenantId);
+ attempt.setPublishWorkflowId("publish-attempt-revision-cas-integration-test");
+ attempt.setPublishType(PublishType.FULL_VERSION);
+ attempt.setVersionId(savedVersion.getId());
+ attempt.setVersionNumber(savedVersion.getVersionNumber());
+ PublishAttempt inserted = publishAttemptRepository.save(attempt);
+ assertThat(inserted).isNotNull();
+ assertThat(inserted.getId()).isNotNull();
+ assertThat(inserted.getRevision()).isEqualTo(1L);
+ assertThat(inserted.getTenantId()).isEqualTo(tenantId);
+ assertThat(inserted.getPublishWorkflowId()).isEqualTo(attempt.getPublishWorkflowId());
+ assertThat(inserted.getVersionId()).isEqualTo(savedVersion.getId());
+ assertThat(inserted.getStatus()).isEqualTo(PublishAttemptStatus.PENDING);
+ PublishAttempt insertedReadback =
+ publishAttemptRepository
+ .findByPublishWorkflowId(attempt.getPublishWorkflowId())
+ .orElseThrow();
+ assertThat(insertedReadback.getId()).isEqualTo(inserted.getId());
+ assertThat(insertedReadback.getRevision()).isEqualTo(1L);
+ assertThat(insertedReadback.getTenantId()).isEqualTo(tenantId);
+ assertThat(insertedReadback.getVersionId()).isEqualTo(savedVersion.getId());
+ assertThat(insertedReadback.getStatus()).isEqualTo(PublishAttemptStatus.PENDING);
+
+ PublishAttempt firstWriter =
+ publishAttemptRepository
+ .findByPublishWorkflowId(attempt.getPublishWorkflowId())
+ .orElseThrow();
+ PublishAttempt staleWriter =
+ publishAttemptRepository
+ .findByPublishWorkflowId(attempt.getPublishWorkflowId())
+ .orElseThrow();
+ firstWriter.setFailureMessage("first revision writer");
+ firstWriter = publishAttemptRepository.save(firstWriter);
+ assertThat(firstWriter.getId()).isEqualTo(inserted.getId());
+ assertThat(firstWriter.getRevision()).isEqualTo(2L);
+ assertThat(firstWriter.getStatus()).isEqualTo(PublishAttemptStatus.PENDING);
+ assertThat(firstWriter.getFailureMessage()).isEqualTo("first revision writer");
+
+ var beforeStaleWrite =
+ dsl.fetchSingle(
+ "SELECT *, xmin::text AS xmin FROM publish_attempt WHERE id = ?", inserted.getId())
+ .intoMap();
+ staleWriter.setFailureMessage("stale revision writer");
+ assertThatThrownBy(() -> publishAttemptRepository.save(staleWriter))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("PUBLISH_ATTEMPT_CAS_CONFLICT");
+ assertThat(
+ dsl.fetchSingle(
+ "SELECT *, xmin::text AS xmin FROM publish_attempt WHERE id = ?",
+ inserted.getId())
+ .intoMap())
+ .isEqualTo(beforeStaleWrite);
+ PublishAttempt afterStaleWrite =
+ publishAttemptRepository
+ .findByPublishWorkflowId(attempt.getPublishWorkflowId())
+ .orElseThrow();
+ assertThat(afterStaleWrite.getId()).isEqualTo(inserted.getId());
+ assertThat(afterStaleWrite.getRevision()).isEqualTo(2L);
+ assertThat(afterStaleWrite.getStatus()).isEqualTo(PublishAttemptStatus.PENDING);
+ assertThat(afterStaleWrite.getFailureMessage()).isEqualTo("first revision writer");
+ assertThat(afterStaleWrite.getFailureCode()).isNull();
+ assertThat(afterStaleWrite.getCompletedAt()).isNull();
+
+ afterStaleWrite.setStatus(PublishAttemptStatus.FAILED);
+ afterStaleWrite.setFailureCode("terminal-revision-proof");
+ afterStaleWrite.setCompletedAt(LocalDateTime.now());
+ PublishAttempt terminal = publishAttemptRepository.save(afterStaleWrite);
+ assertThat(terminal.getId()).isEqualTo(inserted.getId());
+ assertThat(terminal.getRevision()).isEqualTo(3L);
+ assertThat(terminal.getStatus()).isEqualTo(PublishAttemptStatus.FAILED);
+ assertThat(terminal.getFailureMessage()).isEqualTo("first revision writer");
+ assertThat(terminal.getFailureCode()).isEqualTo("terminal-revision-proof");
+ var beforeTerminalWrite =
+ dsl.fetchSingle(
+ "SELECT *, xmin::text AS xmin FROM publish_attempt WHERE id = ?", terminal.getId())
+ .intoMap();
+ terminal.setFailureMessage("terminal rows cannot be rewritten");
+ assertThatThrownBy(() -> publishAttemptRepository.save(terminal))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("PUBLISH_ATTEMPT_CAS_CONFLICT");
+ assertThat(
+ dsl.fetchSingle(
+ "SELECT *, xmin::text AS xmin FROM publish_attempt WHERE id = ?",
+ terminal.getId())
+ .intoMap())
+ .isEqualTo(beforeTerminalWrite);
+ PublishAttempt afterTerminalWrite =
+ publishAttemptRepository
+ .findByPublishWorkflowId(attempt.getPublishWorkflowId())
+ .orElseThrow();
+ assertThat(afterTerminalWrite.getId()).isEqualTo(inserted.getId());
+ assertThat(afterTerminalWrite.getRevision()).isEqualTo(3L);
+ assertThat(afterTerminalWrite.getStatus()).isEqualTo(PublishAttemptStatus.FAILED);
+ assertThat(afterTerminalWrite.getFailureMessage()).isEqualTo("first revision writer");
+ assertThat(afterTerminalWrite.getFailureCode()).isEqualTo("terminal-revision-proof");
+ }
+
@Test
void fullVersionSealTransactionUsesExplicitReadCommittedIsolation() {
AtomicReference isolation = new AtomicReference<>();
From 2d1790f34f1d8e4808537ff5de250306c01316c3 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 18:50:50 +1300
Subject: [PATCH 17/55] test: qualify gameplay source catalog and legacy
refusals
---
...ame-authoring-publishing-and-activation.md | 6 +
...urceRepositoryPostgresIntegrationTest.java | 326 +++++++++++++++++-
2 files changed, 315 insertions(+), 17 deletions(-)
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index 8d1b1b5cd1..b1937e9de5 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -6,6 +6,12 @@ This is a non-normative implementation tracker for game authoring, publishing, a
## Current Status
+### Gameplay source catalog and legacy handoff proof
+
+The existing Game Design gameplay source PostgreSQL owner test now retains a nonempty action, ability, effect, resource and admission-tag catalog beside an ordinary asset in one owner outcome. Exact retry and independent repository reads preserve the original source bytes. A disjoint asset change inherits the gameplay epoch and original binding; explicit ability and action deletion advances the gameplay epoch while preserving the prior snapshot. Additional cases deny legacy effective commands and generic gameplay-rule history before or after the typed snapshot, including an explicitly emptied rule inventory. Generic history under a different private tenant or Version does not contaminate the exact selected source.
+
+All eleven owning native invocations freshly pass with zero failures, errors or skips. Canonical formatting, Integration Checkstyle and SpotBugs pass; style checks remain up to date against the formatted source. Passive capture identifies one run-owned PostgreSQL container and independently confirms its absence after completion. The donor's earlier absent-command deletion fixture failure and the subsequent boxing-only static failure are retained separately from the passing run. This is controlled current-default storage and handoff-refusal proof; it does not establish Game Logic intake, an authenticated creator or issuer, currentness, publication enablement, a genuine immutable release, activation or a Gameplay handoff. No production, migration or registration changes are included.
+
### Publish-attempt revision and terminal retention proof
The restored publish-attempt native regression reads two independent copies of a pending attempt, advances the winning revision from one to two and refuses the stale writer with the current CAS conflict code. A legal failure transition advances the revision to three; a later terminal rewrite is refused. Both refusals preserve the complete persisted attempt row and PostgreSQL row version. The existing transaction-boundary case separately confirms an actual writable Read Committed owner transaction.
diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepositoryPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepositoryPostgresIntegrationTest.java
index b34a1b71cc..ca1ca3488d 100644
--- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepositoryPostgresIntegrationTest.java
+++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepositoryPostgresIntegrationTest.java
@@ -10,6 +10,8 @@
import net.firedevops.firemud.common.authoring.DraftCommitBinding;
import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof;
+import net.firedevops.firemud.common.gamedesign.AssetSource;
+import net.firedevops.firemud.common.gamedesign.CommandSource;
import net.firedevops.firemud.common.gamedesign.GameplayRuleSource;
import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest;
import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family;
@@ -17,10 +19,12 @@
import net.firedevops.firemud.gamedesign.draft.GameDesignReviewedBaseRepository;
import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup;
import net.firedevops.firemud.gamedesign.entity.Game;
+import net.firedevops.firemud.gamedesign.entity.GameAsset;
import net.firedevops.firemud.gamedesign.entity.Version;
import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository;
import net.firedevops.firemud.gamedesign.publication.GameplayRuleSnapshot;
import net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository;
+import net.firedevops.firemud.gamedesign.repository.GameAssetRepository;
import net.firedevops.firemud.gamedesign.repository.GameRepository;
import net.firedevops.firemud.gamedesign.repository.VersionRepository;
import net.firedevops.firemud.test.TestContainerImages;
@@ -29,6 +33,8 @@
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
@@ -139,6 +145,263 @@ void rolledBackGameplayWriteLeavesFreshGenesisAndNoStagedOrVisibleHistory() {
assertThat(fixture.sql().fetchCount(DSL.table("game_design_gameplay_rule_revision"))).isZero();
}
+ @Test
+ void nonemptyReferencedGameplayCatalogSharesAssetOutcomeAndRetainsInheritedSources() {
+ var fixture = fixture();
+ var asset =
+ fixture
+ .write()
+ .execute(
+ ignored -> {
+ var value = new GameAsset();
+ value.setTenantId(fixture.target().gameDesignVersionTenantKey());
+ value.setFileName("catalog-resource.png");
+ value.setContentType("image/png");
+ value.setData(
+ "actual catalog asset bytes"
+ .getBytes(java.nio.charset.StandardCharsets.UTF_8));
+ return new GameAssetRepository(fixture.sql()).save(value);
+ });
+ var payloads = new java.util.ArrayList<>(gameplayPayloads());
+ payloads.add(
+ AssetSource.upsertPayload(
+ asset.getId().toString(), asset.getFileName(), AssetSource.Requiredness.REQUIRED));
+ var binding = fixture.binding("0", fixture.genesisBase(), payloads.toArray(String[]::new));
+ fixture.stage(binding);
+ fixture.synchronize(binding);
+ var owner = new GameplayRuleSourceRepository(fixture.sql());
+ var snapshot = owner.requireCompleteForGameLogic(fixture.target(), binding.commitId());
+ assertThat(snapshot.manifest().families()).hasSize(Family.values().length);
+ assertThat(snapshot.manifest().families().get(Family.ACTIONS)).hasSize(1);
+ assertThat(snapshot.manifest().families().get(Family.ABILITIES)).hasSize(1);
+ assertThat(snapshot.entries())
+ .allSatisfy(entry -> assertThat(entry.sourceBinding()).isEqualTo(binding));
+ var outcome = fixture.write().execute(ignored -> fixture.sources().apply(binding));
+ assertThat(outcome.asset()).isPresent();
+ assertThat(outcome.gameplay().orElseThrow().snapshot().canonicalBytes())
+ .containsExactly(snapshot.canonicalBytes());
+ var independentlyRead =
+ new GameplayRuleSourceRepository(fixture.sql())
+ .requireCompleteForGameLogic(fixture.target(), binding.commitId());
+ assertThat(independentlyRead.canonicalBytes()).containsExactly(snapshot.canonicalBytes());
+ var disjoint =
+ fixture.binding(
+ "1", binding.commitId().toString(), AssetSource.deletePayload(asset.getFileName()));
+ fixture.stage(disjoint);
+ fixture.synchronize(disjoint);
+ var inherited = owner.requireCompleteForGameLogic(fixture.target(), disjoint.commitId());
+ assertThat(inherited.sourceEpoch()).isEqualTo("1");
+ assertThat(inherited.inheritedCommitId()).isEqualTo(binding.commitId());
+ assertThat(inherited.entries())
+ .allSatisfy(entry -> assertThat(entry.sourceBinding()).isEqualTo(binding));
+ assertThat(inherited.manifest().canonicalBytes())
+ .containsExactly(snapshot.manifest().canonicalBytes());
+ var deletion =
+ fixture.binding(
+ "1",
+ disjoint.commitId().toString(),
+ GameplayRuleSource.deletePayload(Family.ABILITIES, "focusAbility"),
+ GameplayRuleSource.deletePayload(Family.ACTIONS, "focusAction"));
+ fixture.stage(deletion);
+ fixture.synchronize(deletion);
+ var deleted = owner.requireCompleteForGameLogic(fixture.target(), deletion.commitId());
+ assertThat(deleted.sourceEpoch()).isEqualTo("2");
+ assertThat(deleted.manifest().families().get(Family.ACTIONS)).isEmpty();
+ assertThat(deleted.manifest().families().get(Family.ABILITIES)).isEmpty();
+ assertThat(
+ owner.readSnapshot(fixture.target(), binding.commitId()).orElseThrow().canonicalBytes())
+ .containsExactly(snapshot.canonicalBytes());
+ }
+
+ @Test
+ void gameplayHandoffDeniesUnqualifiedLegacyEffectiveCommands() {
+ var fixture = fixture();
+ var command =
+ "{\"schemaVersion\":1,\"commandId\":\"legacy\",\"semanticOwner\":\"GAME_LOGIC\","
+ + "\"executionDiscipline\":\"DURABLE_GAMEPLAY\",\"stageRequirement\":\"GAMEPLAY\","
+ + "\"promptPolicy\":\"WHEN_GAMEPLAY\",\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true,"
+ + "\"aliases\":[],\"actionTags\":[],\"effects\":[]}";
+ var binding = fixture.binding("0", fixture.genesisBase(), CommandSource.upsertPayload(command));
+ fixture.stage(binding);
+ fixture.synchronize(binding);
+ assertThat(
+ new GameplayRuleSourceRepository(fixture.sql())
+ .readSnapshot(binding.target(), binding.commitId()))
+ .isPresent();
+ assertThatThrownBy(
+ () ->
+ new GameplayRuleSourceRepository(fixture.sql())
+ .requireCompleteForGameLogic(binding.target(), binding.commitId()))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("GAMEPLAY_RULE_LEGACY_COMMAND_SOURCE_NOT_CONVERGED");
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void gameplayHandoffDeniesGenericRuleEvenWhenTypedRevisionMatches(boolean legacyBeforeSnapshot) {
+ var fixture = fixture();
+ var binding =
+ fixture.binding("0", fixture.genesisBase(), gameplayPayloads().toArray(String[]::new));
+ var revision = binding.revisions().getFirst();
+ if (!legacyBeforeSnapshot) {
+ fixture.stage(binding);
+ fixture.synchronize(binding);
+ }
+ fixture
+ .sql()
+ .execute(
+ "INSERT INTO revision (tenant_id, version_id, author_account_id, revision_kind, logical_revision_id, data) "
+ + "VALUES (?, ?, 1, 'GAMEPLAY_RULE', ?, CAST(? AS JSONB))",
+ fixture.target().gameDesignVersionTenantKey(),
+ fixture.target().gameDesignVersionRowId(),
+ revision.revisionId().toString(),
+ revision.payload());
+ var retainedRows = fixture.sql().fetch("SELECT * FROM revision ORDER BY id");
+ if (legacyBeforeSnapshot) {
+ fixture.stage(binding);
+ fixture.synchronize(binding);
+ }
+ var repository = new GameplayRuleSourceRepository(fixture.sql());
+ var snapshot = repository.readSnapshot(binding.target(), binding.commitId()).orElseThrow();
+ assertThat(snapshot.entries()).isNotEmpty();
+
+ assertThatThrownBy(
+ () -> repository.requireCompleteForGameLogic(binding.target(), binding.commitId()))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("GAMEPLAY_RULE_GENERIC_SOURCE_NOT_CONVERGED");
+ assertThatThrownBy(
+ () ->
+ new GameplayRuleSourceRepository(fixture.sql())
+ .requireCompleteForGameLogic(binding.target(), binding.commitId()))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("GAMEPLAY_RULE_GENERIC_SOURCE_NOT_CONVERGED");
+ assertThat(repository.readSnapshot(binding.target(), binding.commitId()).orElseThrow())
+ .isEqualTo(snapshot);
+ assertThat(fixture.sql().fetch("SELECT * FROM revision ORDER BY id")).isEqualTo(retainedRows);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void gameplayHandoffGenericRuleGuardUsesExactPrivateTenantAndVersion(boolean differentTenant) {
+ var fixture = fixture();
+ Version otherVersion =
+ fixture
+ .write()
+ .execute(
+ ignored -> {
+ var value = new Version();
+ value.setTenantId(fixture.target().gameDesignVersionTenantKey());
+ value.setVersionNumber(2);
+ return new VersionRepository(fixture.sql()).save(value);
+ });
+ String foreignTenant =
+ fixture
+ .write()
+ .execute(
+ ignored -> {
+ var value = new Game();
+ value.setTenantId("foreign-" + UUID.randomUUID().toString().substring(0, 8));
+ value.setName("Controlled foreign legacy history scope");
+ return new GameRepository(fixture.sql()).save(value).getTenantId();
+ });
+ var binding =
+ fixture.binding("0", fixture.genesisBase(), gameplayPayloads().toArray(String[]::new));
+ fixture.stage(binding);
+ fixture.synchronize(binding);
+ var repository = new GameplayRuleSourceRepository(fixture.sql());
+ var snapshot = repository.requireCompleteForGameLogic(binding.target(), binding.commitId());
+ // Generic history has no composite owner FK; scope both private keys even for retained rows.
+ fixture
+ .sql()
+ .execute(
+ "INSERT INTO revision (tenant_id, version_id, author_account_id, revision_kind, data) "
+ + "VALUES (?, ?, 1, 'GAMEPLAY_RULE', '{}'::JSONB)",
+ differentTenant ? foreignTenant : fixture.target().gameDesignVersionTenantKey(),
+ differentTenant
+ ? Long.valueOf(fixture.target().gameDesignVersionRowId())
+ : otherVersion.getId());
+ var retainedRows = fixture.sql().fetch("SELECT * FROM revision ORDER BY id");
+
+ assertThat(repository.requireCompleteForGameLogic(binding.target(), binding.commitId()))
+ .isEqualTo(snapshot);
+ assertThat(fixture.sql().fetch("SELECT * FROM revision ORDER BY id")).isEqualTo(retainedRows);
+ }
+
+ @Test
+ void gameplayHandoffCannotClaimEmptyWhileGenericRuleHistoryExists() {
+ var fixture = fixture();
+ var first = fixture.binding("0", fixture.genesisBase(), upsert("10"));
+ fixture.stage(first);
+ fixture.synchronize(first);
+ var binding =
+ fixture.binding(
+ "1",
+ first.commitId().toString(),
+ GameplayRuleSource.deletePayload(Family.STATS, "strength"));
+ fixture.stage(binding);
+ fixture.synchronize(binding);
+ var repository = new GameplayRuleSourceRepository(fixture.sql());
+ assertThat(
+ repository.requireCompleteForGameLogic(binding.target(), binding.commitId()).entries())
+ .isEmpty();
+ fixture
+ .sql()
+ .execute(
+ "INSERT INTO revision (tenant_id, version_id, author_account_id, revision_kind, data) "
+ + "VALUES (?, ?, 1, 'GAMEPLAY_RULE', '{}'::JSONB)",
+ fixture.target().gameDesignVersionTenantKey(),
+ fixture.target().gameDesignVersionRowId());
+ var retainedRows = fixture.sql().fetch("SELECT * FROM revision ORDER BY id");
+
+ assertThatThrownBy(
+ () -> repository.requireCompleteForGameLogic(binding.target(), binding.commitId()))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("GAMEPLAY_RULE_GENERIC_SOURCE_NOT_CONVERGED");
+ assertThat(fixture.sql().fetch("SELECT * FROM revision ORDER BY id")).isEqualTo(retainedRows);
+ }
+
+ private List gameplayPayloads() {
+ var action =
+ new GameplayRuleManifest.Action(
+ "focusAction",
+ "Focus",
+ List.of("canFocus"),
+ List.of(),
+ List.of(
+ new GameplayRuleManifest.Cost(
+ "energy",
+ java.math.BigDecimal.ONE,
+ GameplayRuleManifest.CommitPolicy.ON_EXECUTION)),
+ List.of(
+ new GameplayRuleManifest.Cooldown(
+ "focusCooldown", 3L, GameplayRuleManifest.CommitPolicy.ON_EFFECT_SUCCESS)),
+ List.of(new GameplayRuleManifest.EffectBinding("restore", "SOURCE")),
+ List.of());
+ List definitions =
+ List.of(
+ new GameplayRuleManifest.AdmissionTag("canFocus"),
+ new GameplayRuleManifest.Resource(
+ "energy",
+ java.math.BigDecimal.TEN,
+ java.math.BigDecimal.ZERO,
+ java.math.BigDecimal.TEN,
+ java.math.BigDecimal.valueOf(100),
+ GameplayRuleManifest.Visibility.PUBLIC,
+ List.of()),
+ new GameplayRuleManifest.Effect(
+ "restore",
+ GameplayRuleManifest.Lifecycle.INSTANT,
+ GameplayRuleManifest.EffectOperation.ADJUST_RESOURCE,
+ "energy",
+ null,
+ java.math.BigDecimal.ONE,
+ null,
+ null),
+ action,
+ new GameplayRuleManifest.Ability("focusAbility", "Focus ability", "focusAction"));
+ return definitions.stream().map(GameplayRuleSource::upsertPayload).toList();
+ }
+
private static String upsert(String value) {
return upsert("strength", value);
}
@@ -167,7 +430,11 @@ private static Fixture fixture() {
.schemas(schema)
.defaultSchema(schema)
.placeholders(java.util.Map.of("serviceSchema", schema))
- .locations("classpath:db/migration")
+ .locations(
+ "filesystem:"
+ + java.nio.file.Path.of("src/main/resources/db/migration")
+ .toAbsolutePath()
+ .normalize())
.load()
.migrate();
var write = new TransactionTemplate(new DataSourceTransactionManager(data));
@@ -211,23 +478,48 @@ String genesisBase() {
return "genesis:" + sources.readGenesis(target).orElseThrow().policy().receiptId();
}
- DraftCommitBinding binding(String epoch, String base, String payload) {
+ DraftCommitBinding binding(String epoch, String base, String... payloads) {
+ var revisions = new java.util.ArrayList();
+ for (int index = 0; index < payloads.length; index++) {
+ revisions.add(
+ new DraftCommitBinding.RevisionPayload(
+ Integer.toString(index),
+ UUID.randomUUID(),
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ payloads[index]));
+ }
+ var units = new java.util.ArrayList();
+ for (String scope :
+ List.of(GameplayRuleSource.SCOPE, CommandSource.SCOPE, AssetSource.SCOPE)) {
+ String kind =
+ scope.equals(GameplayRuleSource.SCOPE)
+ ? "GAMEPLAY_RULE"
+ : scope.equals(CommandSource.SCOPE) ? "COMMAND_DEFINITION" : "ASSET_REFERENCE";
+ if (java.util.Arrays.stream(payloads).noneMatch(payload -> payload.contains(kind)))
+ continue;
+ String sourceEpoch = epoch;
+ if (!scope.equals(GameplayRuleSource.SCOPE)) {
+ String table =
+ scope.equals(CommandSource.SCOPE)
+ ? "game_design_command_source_head"
+ : "game_design_asset_source_head";
+ sourceEpoch =
+ sql.fetchSingle(
+ "SELECT source_epoch FROM " + table + " WHERE canonical_version_id = ?",
+ target.canonicalVersionId())
+ .get(0, String.class);
+ }
+ units.add(
+ new DraftCommitBinding.AffectedUnit(
+ Owner.GAME_DESIGN_CONTROL_PLANE,
+ scope,
+ target.canonicalVersionId().toString(),
+ scope,
+ "effective",
+ sourceEpoch));
+ }
return DraftCommitBinding.create(
- target,
- UUID.randomUUID(),
- UUID.randomUUID(),
- base,
- List.of(
- new DraftCommitBinding.RevisionPayload(
- "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, payload)),
- List.of(
- new DraftCommitBinding.AffectedUnit(
- Owner.GAME_DESIGN_CONTROL_PLANE,
- GameplayRuleSource.SCOPE,
- target.canonicalVersionId().toString(),
- GameplayRuleSource.SCOPE,
- GameplayRuleSource.SCOPE_ID,
- epoch)));
+ target, UUID.randomUUID(), UUID.randomUUID(), base, revisions, units);
}
void stage(DraftCommitBinding binding) {
From 4e441fc0962c8d5babe7b477e4529a49c63896fa Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 20:34:34 +1300
Subject: [PATCH 18/55] test: align selected publication transaction fixtures
with owning collector
---
...emptServiceTransactionIntegrationTest.java | 45 ++++++++++++++++---
1 file changed, 39 insertions(+), 6 deletions(-)
diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java
index 34409aa394..4343cf907c 100644
--- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java
+++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java
@@ -671,9 +671,20 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() {
AtomicInteger artifactReadbackCount = new AtomicInteger();
Mockito.when(
- publishGateService.collectFullVersionParticipantDigests(
+ publishGateService.collectSelectedFullVersionParticipantDigests(
Mockito.any(VersionDto.class),
- Mockito.eq(publishRequestId),
+ Mockito.eq(
+ PublicationDigestRequestBinding.full(
+ fixture
+ .operation()
+ .account()
+ .input()
+ .selection()
+ .intent()
+ .canonicalTenantId()
+ .toString(),
+ String.valueOf(fixture.version().getId()),
+ publishRequestId)),
Mockito.eq(publishWorkflowId)))
.thenAnswer(
invocation -> {
@@ -795,9 +806,20 @@ void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidate
AtomicBoolean finalizationFailureInjected = new AtomicBoolean();
Mockito.when(
- publishGateService.collectFullVersionParticipantDigests(
+ publishGateService.collectSelectedFullVersionParticipantDigests(
Mockito.any(VersionDto.class),
- Mockito.eq(publishRequestId),
+ Mockito.eq(
+ PublicationDigestRequestBinding.full(
+ fixture
+ .operation()
+ .account()
+ .input()
+ .selection()
+ .intent()
+ .canonicalTenantId()
+ .toString(),
+ String.valueOf(fixture.version().getId()),
+ publishRequestId)),
Mockito.eq(publishWorkflowId)))
.thenAnswer(
invocation -> {
@@ -964,9 +986,20 @@ void privateMechanicsCommitsGdsOwnerButRemainsPendingWithoutWorldProducer() {
AtomicReference controlPlaneDigestFailure = captureControlPlaneDigestFailure();
Mockito.when(
- publishGateService.collectFullVersionParticipantDigests(
+ publishGateService.collectSelectedFullVersionParticipantDigests(
Mockito.any(VersionDto.class),
- Mockito.eq(publishRequestId),
+ Mockito.eq(
+ PublicationDigestRequestBinding.full(
+ fixture
+ .operation()
+ .account()
+ .input()
+ .selection()
+ .intent()
+ .canonicalTenantId()
+ .toString(),
+ String.valueOf(fixture.version().getId()),
+ publishRequestId)),
Mockito.eq(publishWorkflowId)))
.thenAnswer(
invocation -> {
From 532552a9995fdc360ac18b2fef5cf5fc353b9c7f Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 20:40:41 +1300
Subject: [PATCH 19/55] test: match publication bindings by complete canonical
preimage
---
...emptServiceTransactionIntegrationTest.java | 90 +++++++++++--------
1 file changed, 54 insertions(+), 36 deletions(-)
diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java
index 4343cf907c..f2ddf0a9c8 100644
--- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java
+++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java
@@ -666,6 +666,18 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() {
String publishRequestId =
fixture.operation().account().input().selection().intent().publishRequestId();
String publishWorkflowId = fixture.operation().workflowId();
+ PublicationDigestRequestBinding expectedDigestBinding =
+ PublicationDigestRequestBinding.full(
+ fixture
+ .operation()
+ .account()
+ .input()
+ .selection()
+ .intent()
+ .canonicalTenantId()
+ .toString(),
+ String.valueOf(fixture.version().getId()),
+ publishRequestId);
ExportedAssetManifest candidate = recordFixtureCandidate(fixture);
AtomicReference recordedDigestFailure = new AtomicReference<>();
AtomicInteger artifactReadbackCount = new AtomicInteger();
@@ -673,18 +685,12 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() {
Mockito.when(
publishGateService.collectSelectedFullVersionParticipantDigests(
Mockito.any(VersionDto.class),
- Mockito.eq(
- PublicationDigestRequestBinding.full(
- fixture
- .operation()
- .account()
- .input()
- .selection()
- .intent()
- .canonicalTenantId()
- .toString(),
- String.valueOf(fixture.version().getId()),
- publishRequestId)),
+ Mockito.argThat(
+ actualBinding ->
+ actualBinding != null
+ && expectedDigestBinding
+ .canonicalPreimageHex()
+ .equals(actualBinding.canonicalPreimageHex())),
Mockito.eq(publishWorkflowId)))
.thenAnswer(
invocation -> {
@@ -791,6 +797,18 @@ void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidate
String publishRequestId =
fixture.operation().account().input().selection().intent().publishRequestId();
String publishWorkflowId = fixture.operation().workflowId();
+ PublicationDigestRequestBinding expectedDigestBinding =
+ PublicationDigestRequestBinding.full(
+ fixture
+ .operation()
+ .account()
+ .input()
+ .selection()
+ .intent()
+ .canonicalTenantId()
+ .toString(),
+ String.valueOf(fixture.version().getId()),
+ publishRequestId);
Version sourceVersion =
versionRepository.findByTenantIdAndVersionNumber(tenantId, 1).orElseThrow();
long sourceVersionId = sourceVersion.getId();
@@ -808,18 +826,12 @@ void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidate
Mockito.when(
publishGateService.collectSelectedFullVersionParticipantDigests(
Mockito.any(VersionDto.class),
- Mockito.eq(
- PublicationDigestRequestBinding.full(
- fixture
- .operation()
- .account()
- .input()
- .selection()
- .intent()
- .canonicalTenantId()
- .toString(),
- String.valueOf(fixture.version().getId()),
- publishRequestId)),
+ Mockito.argThat(
+ actualBinding ->
+ actualBinding != null
+ && expectedDigestBinding
+ .canonicalPreimageHex()
+ .equals(actualBinding.canonicalPreimageHex())),
Mockito.eq(publishWorkflowId)))
.thenAnswer(
invocation -> {
@@ -983,23 +995,29 @@ void privateMechanicsCommitsGdsOwnerButRemainsPendingWithoutWorldProducer() {
String publishRequestId =
fixture.operation().account().input().selection().intent().publishRequestId();
String publishWorkflowId = fixture.operation().workflowId();
+ PublicationDigestRequestBinding expectedDigestBinding =
+ PublicationDigestRequestBinding.full(
+ fixture
+ .operation()
+ .account()
+ .input()
+ .selection()
+ .intent()
+ .canonicalTenantId()
+ .toString(),
+ String.valueOf(fixture.version().getId()),
+ publishRequestId);
AtomicReference controlPlaneDigestFailure = captureControlPlaneDigestFailure();
Mockito.when(
publishGateService.collectSelectedFullVersionParticipantDigests(
Mockito.any(VersionDto.class),
- Mockito.eq(
- PublicationDigestRequestBinding.full(
- fixture
- .operation()
- .account()
- .input()
- .selection()
- .intent()
- .canonicalTenantId()
- .toString(),
- String.valueOf(fixture.version().getId()),
- publishRequestId)),
+ Mockito.argThat(
+ actualBinding ->
+ actualBinding != null
+ && expectedDigestBinding
+ .canonicalPreimageHex()
+ .equals(actualBinding.canonicalPreimageHex())),
Mockito.eq(publishWorkflowId)))
.thenAnswer(
invocation -> {
From 4265a81f008d0dbd343cd9adf6413bd3ac5c8904 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 20:48:52 +1300
Subject: [PATCH 20/55] test: carry existing selected-full fixture repair to
publication owner
---
.../draft/IsolatedPublicationOwnerSetup.java | 51 ++++++++++++++--
.../IsolatedPublicationOperationFixtures.java | 39 +++++++++++--
.../impl/PublishedWorldSelectorFixtures.java | 20 ++++++-
...emptServiceTransactionIntegrationTest.java | 58 +++++++++++--------
4 files changed, 133 insertions(+), 35 deletions(-)
diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java
index b135d2b0bd..f564110d45 100644
--- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java
+++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java
@@ -137,6 +137,24 @@ public static GameDesignPublicationOperation retainFrozenSourceBacked(
return operation;
}
+ /**
+ * Isolated GDS transaction fixture with a fresh stipulated selected-full World schema-4 input.
+ * The World evidence remains stipulated and is not native producer or freeze proof.
+ */
+ public static GameDesignPublicationOperation retainFrozenSourceBackedSelectedFull(
+ DSLContext dsl,
+ DraftCommitBinding.TargetProof target,
+ long draftEpoch,
+ String notes,
+ List ordinaryAssets)
+ throws Exception {
+ String authoredPolicyCommit = retainPublicProductionPolicy(dsl, target, ordinaryAssets);
+ GameDesignPublicationOperation operation =
+ retain(dsl, target, draftEpoch, notes, true, authoredPolicyCommit, false, true);
+ new GameDesignPublicationOperationRepository(dsl).reserveSourceBacked(operation);
+ return operation;
+ }
+
/** Fixture input from an actual same-tenant game_assets row, not publication authority. */
public record OrdinaryAsset(long assetRowId, String usageKey) {
public OrdinaryAsset {
@@ -176,6 +194,20 @@ private static GameDesignPublicationOperation retain(
String sourceBaseReference,
boolean historicalV1)
throws Exception {
+ return retain(
+ dsl, target, draftEpoch, notes, captureSources, sourceBaseReference, historicalV1, false);
+ }
+
+ private static GameDesignPublicationOperation retain(
+ DSLContext dsl,
+ DraftCommitBinding.TargetProof target,
+ long draftEpoch,
+ String notes,
+ boolean captureSources,
+ String sourceBaseReference,
+ boolean historicalV1,
+ boolean selectedFullWorld)
+ throws Exception {
var sources = new GameDesignSourceRepository(dsl);
var reviewed = new GameDesignReviewedBaseRepository(dsl);
var evidence =
@@ -189,10 +221,14 @@ private static GameDesignPublicationOperation retain(
: sourceBaseReference))
: null;
var seed =
- captureSources
- ? IsolatedPublicationOperationFixtures.fresh(
+ selectedFullWorld
+ ? IsolatedPublicationOperationFixtures.freshSelectedFull(
target, evidence.reference().canonicalValue())
- : IsolatedPublicationOperationFixtures.fresh(target);
+ : captureSources
+ ? IsolatedPublicationOperationFixtures.fresh(
+ target, evidence.reference().canonicalValue())
+ : IsolatedPublicationOperationFixtures.fresh(target);
+ var seedWorld = seed.world();
var draft = seed.account().input().selection().selectedCommit();
var coordinator = new DraftCommitCoordinatorRepository(dsl);
// The original Draft Account/World result is stipulated upstream fixture evidence, not a new
@@ -222,7 +258,7 @@ private static GameDesignPublicationOperation retain(
draft.commitId(),
draft.digest(),
"ISOLATED-world-applied",
- seed.world().appliedResultBytes(),
+ seedWorld.appliedResultBytes(),
epochs);
coordinator.markOwnerInProgress(draft, DraftCommitBinding.Owner.WORLD_MANAGEMENT);
coordinator.recordOwnerOutcome(draft, outcome);
@@ -253,8 +289,11 @@ private static GameDesignPublicationOperation retain(
var operation =
historicalV1
? IsolatedPublicationOperationFixtures.historicalV1ForSelection(
- selectedBinding, seed.world())
- : IsolatedPublicationOperationFixtures.forSelection(selectedBinding, seed.world());
+ selectedBinding, seedWorld)
+ : selectedFullWorld
+ ? IsolatedPublicationOperationFixtures.forSelectedFullSelection(
+ selectedBinding, seedWorld)
+ : IsolatedPublicationOperationFixtures.forSelection(selectedBinding, seedWorld);
var attempt = new PublishAttempt();
attempt.setTenantId(target.gameDesignVersionTenantKey());
attempt.setPublishWorkflowId(operation.workflowId());
diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java
index 0554126103..98a856ff30 100644
--- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java
+++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java
@@ -10,6 +10,7 @@
import java.util.UUID;
import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding;
import net.firedevops.firemud.common.authoring.DraftCommitBinding;
+import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence;
import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding;
import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding;
@@ -39,9 +40,26 @@ public static GameDesignPublicationOperation fresh(
return fresh(target, PublishedWorldSelectorFixtures.evidence(target, baseReference));
}
+ /** Fresh stipulated selected-full fixture; schema 4 is constructed before operation retention. */
+ public static GameDesignPublicationOperation freshSelectedFull(
+ DraftCommitBinding.TargetProof target, String baseReference) throws Exception {
+ return fresh(
+ target,
+ PublishedWorldSelectorFixtures.selectedFullSeed(target, baseReference),
+ AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
+ }
+
private static GameDesignPublicationOperation fresh(
DraftCommitBinding.TargetProof target, WorldPublishedStartLocationEvidence seed)
throws Exception {
+ return fresh(target, seed, 3);
+ }
+
+ private static GameDesignPublicationOperation fresh(
+ DraftCommitBinding.TargetProof target,
+ WorldPublishedStartLocationEvidence seed,
+ int worldDigestSchemaVersion)
+ throws Exception {
var originalDraftAccount =
DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes());
var draft =
@@ -110,12 +128,22 @@ private static GameDesignPublicationOperation fresh(
draft.digest(),
vector,
OffsetDateTime.parse("2026-10-07T00:00:00Z")));
- return forSelection(selected, seed);
+ return selection(selected, seed, false, worldDigestSchemaVersion);
}
public static GameDesignPublicationOperation forSelection(
AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed) {
- return selection(selected, seed, false);
+ return selection(selected, seed, false, 3);
+ }
+
+ /** Builds a fresh selected-full operation without reinterpreting retained schema-3 history. */
+ public static GameDesignPublicationOperation forSelectedFullSelection(
+ AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed) {
+ return selection(
+ selected,
+ seed,
+ false,
+ AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
}
/**
@@ -124,13 +152,14 @@ public static GameDesignPublicationOperation forSelection(
*/
public static GameDesignPublicationOperation historicalV1ForSelection(
AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed) {
- return selection(selected, seed, true);
+ return selection(selected, seed, true, 3);
}
private static GameDesignPublicationOperation selection(
AuthoredDraftPublishSelectionBinding selected,
WorldPublishedStartLocationEvidence seed,
- boolean historicalV1) {
+ boolean historicalV1,
+ int worldDigestSchemaVersion) {
var originalDraftAccount =
DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes());
var target = selected.target();
@@ -181,7 +210,7 @@ private static GameDesignPublicationOperation selection(
intent.publishRequestId()),
draft.commitId().toString(),
seed.request().contentDigest(),
- 3,
+ worldDigestSchemaVersion,
seed.request().worldAffectedTuples()),
seed.selectorReceiptBytes(),
seed.originalAccountBindingBytes(),
diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java
index 277640b137..84c1cd3b26 100644
--- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java
+++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java
@@ -43,6 +43,19 @@ public static WorldPublishedStartLocationEvidence evidence(TargetProof target) t
return new PublishedWorldSelectorFixtures(target).build();
}
+ /**
+ * Stipulated fresh selected-full World input; schema 4 is present from its first construction.
+ * This fixture does not claim that a live World producer computed or authorized the evidence.
+ */
+ public static WorldPublishedStartLocationEvidence selectedFullSeed(
+ TargetProof target, String baseReference) throws Exception {
+ net.firedevops.firemud.common.authoring.DraftBaseReference.parse(baseReference);
+ var fixture = new PublishedWorldSelectorFixtures(target, baseReference);
+ return fixture.build(
+ fixture.freshGraphBinding(),
+ AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
+ }
+
public static WorldPublishedStartLocationEvidence evidence(
TargetProof target, String baseReference) throws Exception {
net.firedevops.firemud.common.authoring.DraftBaseReference.parse(baseReference);
@@ -117,6 +130,11 @@ private WorldPublishedStartLocationEvidence build() throws Exception {
}
private WorldPublishedStartLocationEvidence build(DraftCommitBinding draft) throws Exception {
+ return build(draft, 3);
+ }
+
+ private WorldPublishedStartLocationEvidence build(
+ DraftCommitBinding draft, int attestationSchemaVersion) throws Exception {
var terminal = WorldDraftTerminalReadEvidence.Request.create("test", accountBinding(draft));
var result = committedReadback(terminal, true);
var applied = JSON.readTree(result.result());
@@ -152,7 +170,7 @@ private WorldPublishedStartLocationEvidence build(DraftCommitBinding draft) thro
"publish-workflow",
draft.commitId().toString(),
"b".repeat(64),
- 3,
+ attestationSchemaVersion,
tuples);
return new WorldPublishedStartLocationEvidence(
request,
diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java
index f2ddf0a9c8..e31f1ea2a5 100644
--- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java
+++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java
@@ -662,11 +662,11 @@ void scriptPatchFinalizationFailureRollsBackToRetainedDraftAndMarksAttemptFailed
void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() {
String tenantId = isolatedTenantId();
SelectedPublicationFixture fixture =
- selectedPublicationFixture(tenantId, "pending-readback-proof-game", false);
+ selectedFullPublicationFixture(tenantId, "pending-readback-proof-game", false);
String publishRequestId =
fixture.operation().account().input().selection().intent().publishRequestId();
String publishWorkflowId = fixture.operation().workflowId();
- PublicationDigestRequestBinding expectedDigestBinding =
+ PublicationDigestRequestBinding expectedBinding =
PublicationDigestRequestBinding.full(
fixture
.operation()
@@ -686,11 +686,15 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() {
publishGateService.collectSelectedFullVersionParticipantDigests(
Mockito.any(VersionDto.class),
Mockito.argThat(
- actualBinding ->
- actualBinding != null
- && expectedDigestBinding
+ binding ->
+ binding != null
+ && binding
.canonicalPreimageHex()
- .equals(actualBinding.canonicalPreimageHex())),
+ .equals(expectedBinding.canonicalPreimageHex())
+ && binding.requestDigest().equals(expectedBinding.requestDigest())
+ && binding
+ .derivedWorkflowIdentity()
+ .equals(expectedBinding.derivedWorkflowIdentity())),
Mockito.eq(publishWorkflowId)))
.thenAnswer(
invocation -> {
@@ -698,7 +702,7 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() {
return PublishedWorldSelectorFixtures.participants(
selectedVersion.id(),
fixture.operation().world(),
- AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION);
+ AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
});
Mockito.doAnswer(
invocation -> {
@@ -793,11 +797,11 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() {
void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidateAndRemap() {
String tenantId = isolatedTenantId();
SelectedPublicationFixture fixture =
- selectedPublicationFixture(tenantId, "failed-remap-proof-game", true);
+ selectedFullPublicationFixture(tenantId, "failed-remap-proof-game", true);
String publishRequestId =
fixture.operation().account().input().selection().intent().publishRequestId();
String publishWorkflowId = fixture.operation().workflowId();
- PublicationDigestRequestBinding expectedDigestBinding =
+ PublicationDigestRequestBinding expectedBinding =
PublicationDigestRequestBinding.full(
fixture
.operation()
@@ -827,11 +831,15 @@ void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidate
publishGateService.collectSelectedFullVersionParticipantDigests(
Mockito.any(VersionDto.class),
Mockito.argThat(
- actualBinding ->
- actualBinding != null
- && expectedDigestBinding
+ binding ->
+ binding != null
+ && binding
.canonicalPreimageHex()
- .equals(actualBinding.canonicalPreimageHex())),
+ .equals(expectedBinding.canonicalPreimageHex())
+ && binding.requestDigest().equals(expectedBinding.requestDigest())
+ && binding
+ .derivedWorkflowIdentity()
+ .equals(expectedBinding.derivedWorkflowIdentity())),
Mockito.eq(publishWorkflowId)))
.thenAnswer(
invocation -> {
@@ -841,7 +849,7 @@ void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidate
return PublishedWorldSelectorFixtures.participants(
candidate.id(),
fixture.operation().world(),
- AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION);
+ AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
});
Mockito.doAnswer(
invocation -> {
@@ -991,11 +999,11 @@ void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidate
void privateMechanicsCommitsGdsOwnerButRemainsPendingWithoutWorldProducer() {
String tenantId = "9002";
SelectedPublicationFixture fixture =
- selectedPublicationFixture(tenantId, "successful-transaction-proof-game", false);
+ selectedFullPublicationFixture(tenantId, "successful-transaction-proof-game", false);
String publishRequestId =
fixture.operation().account().input().selection().intent().publishRequestId();
String publishWorkflowId = fixture.operation().workflowId();
- PublicationDigestRequestBinding expectedDigestBinding =
+ PublicationDigestRequestBinding expectedBinding =
PublicationDigestRequestBinding.full(
fixture
.operation()
@@ -1013,11 +1021,15 @@ void privateMechanicsCommitsGdsOwnerButRemainsPendingWithoutWorldProducer() {
publishGateService.collectSelectedFullVersionParticipantDigests(
Mockito.any(VersionDto.class),
Mockito.argThat(
- actualBinding ->
- actualBinding != null
- && expectedDigestBinding
+ binding ->
+ binding != null
+ && binding
.canonicalPreimageHex()
- .equals(actualBinding.canonicalPreimageHex())),
+ .equals(expectedBinding.canonicalPreimageHex())
+ && binding.requestDigest().equals(expectedBinding.requestDigest())
+ && binding
+ .derivedWorkflowIdentity()
+ .equals(expectedBinding.derivedWorkflowIdentity())),
Mockito.eq(publishWorkflowId)))
.thenAnswer(
invocation -> {
@@ -1025,7 +1037,7 @@ void privateMechanicsCommitsGdsOwnerButRemainsPendingWithoutWorldProducer() {
return PublishedWorldSelectorFixtures.participants(
version.id(),
fixture.operation().world(),
- AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION);
+ AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION);
});
Mockito.when(assetExportService.exportAssets(tenantId, fixture.version().getVersionNumber()))
.thenAnswer(invocation -> recordFixtureCandidate(fixture));
@@ -1138,7 +1150,7 @@ void publicFreshAndPendingFullVersionPublicationAreDeniedBeforeMutation() {
}
/** Fixture-only Account/World inputs; this exercises GD's actual selected owner transaction. */
- private SelectedPublicationFixture selectedPublicationFixture(
+ private SelectedPublicationFixture selectedFullPublicationFixture(
String tenantId, String gameName, boolean includePublishedSource) {
TransactionTemplate sourceTransaction = new TransactionTemplate(transactionManager);
sourceTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
@@ -1183,7 +1195,7 @@ private SelectedPublicationFixture selectedPublicationFixture(
GameAsset persistedAsset = gameAssetRepository.save(asset);
try {
GameDesignPublicationOperation operation =
- IsolatedPublicationOwnerSetup.retainFrozenSourceBacked(
+ IsolatedPublicationOwnerSetup.retainFrozenSourceBackedSelectedFull(
dsl,
target,
persisted.getVersionStateEpoch(),
From be8f4edce1b0f85e31f3a8cfcc8af5befab64bc5 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 21:10:14 +1300
Subject: [PATCH 21/55] docs: record successor fixture repair reuse lesson
---
design/project-management/ai-observations.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md
index 860314c204..992bf21707 100644
--- a/design/project-management/ai-observations.md
+++ b/design/project-management/ai-observations.md
@@ -143,3 +143,5 @@ Entry format:
- Reconsideration trigger: a subsequent canonical attempt completes with terminal capture, or bounded process evidence identifies why the previous owner ended.
- `2026-10-16`: Qualify tenant mutation predicates before relying on filtered readback or later owner guards. The template repository's global-ID update could rewrite a retained row's tenant before returning it under the supplied tenant; a tenant-filtered readback did not protect the original row. Test controlled pre-phase rows as well as later guarded owners: the native counterexample changed the complete row and `xmin`, while the restored exact tenant predicate preserves both owner rows and their versions. Keep the create-only ID refusal before mapper/repository access, and separate this owner-local SQL proof from authenticated creator or hosted-content readiness.
+
+- `2026-10-16`: Check existing successor repairs before reworking a failed fixture. While fixing the three #3251 publication transaction failures, two focused local gates failed before the worker noticed that the already-reconciled #2967 tree contained the complete selected-full schema-4 fixture repair. The first attempts corrected stale collector stubs but missed the dependent fixture profile. Compare the bounded failing test and its called helpers against known receiving successors before changing or rerunning it; reuse the complete canonical repair without removing assertions. The exact four-path backport at `4265a81f008d0dbd343cd9adf6413bd3ac5c8904` then passed66 unit and10 native cases. The failed attempts retain their original outcomes; this lesson does not establish a general infrastructure cause.
From 21fc70826a19530603b674170cdfe2ed6bed8573 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 23:50:42 +1300
Subject: [PATCH 22/55] Author selected publication command through canonical
gameplay rules
---
...ctedDraftPublicationDigestReadService.java | 3 +-
...nerPublicationPostgresIntegrationTest.java | 60 +++++++++++++------
2 files changed, 42 insertions(+), 21 deletions(-)
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java
index 3b96665eaa..d8826bb96a 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java
@@ -248,8 +248,7 @@ private static void requireFrozenSources(
GameplayRuleSnapshot gameplay =
synchronizedSources
.gameplayEvidence()
- .orElseThrow(
- () -> new IllegalStateException("Selected gameplay source unavailable"));
+ .orElseThrow(() -> new IllegalStateException("Selected gameplay source unavailable"));
if (!selected.equals(synchronizedSources.command().binding())
|| !selected.equals(synchronizedSources.policy().binding())
|| !selected.equals(synchronizedSources.asset().binding())
diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
index 2f2d3ca395..113eee2e0f 100644
--- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
+++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
@@ -41,7 +41,6 @@
import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof;
import net.firedevops.firemud.common.config.ServiceEndpointsProperties;
import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt;
-import net.firedevops.firemud.common.gamedesign.CommandSource;
import net.firedevops.firemud.common.gamedesign.GameplayRuleSource;
import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence;
import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation;
@@ -290,7 +289,15 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema
new GameDesignSourceRepository(gds.dsl())
.readSynchronized(draft.target(), commit.commitId())
.orElseThrow();
+ assertThat(synchronizedSources.command().definitions()).isEmpty();
var gameplaySnapshot = synchronizedSources.gameplayEvidence().orElseThrow();
+ assertThat(
+ gameplaySnapshot
+ .manifest()
+ .families()
+ .get(GameplayRuleManifest.Family.COMMANDS))
+ .extracting(GameplayRuleManifest.Definition::key)
+ .containsExactly("LOOK");
var gameplaySource = new GameplayRuleSelectedSource(gameplaySnapshot.canonicalJson());
var glAuthorization =
new GameLogicIntakeAuthorizationBinding(
@@ -796,41 +803,56 @@ private static DraftCommitBinding selectedCommit(Store gds, TargetProof target)
var revisions = new ArrayList();
var units = new ArrayList();
- String commandJson =
- "{\"schemaVersion\":1,\"commandId\":\"LOOK\",\"semanticOwner\":\"WORLD\","
- + "\"executionDiscipline\":\"DURABLE_GAMEPLAY\",\"stageRequirement\":\"GAMEPLAY\","
- + "\"promptPolicy\":\"NEVER\",\"actionCategory\":\"GAMEPLAY\","
- + "\"historyRecordable\":true,\"aliases\":[],\"actionTags\":[\"WORLD_BROWSE\"],"
- + "\"effects\":[]}";
+ var selectedWorldAction =
+ new GameplayRuleManifest.Action(
+ "selected-world-look",
+ "Look",
+ List.of("selected-world-admission"),
+ List.of(),
+ List.of(),
+ List.of(),
+ List.of(),
+ List.of());
+ var selectedWorldCommand =
+ new GameplayRuleManifest.Command(
+ "LOOK",
+ "selected-world-look",
+ "WORLD",
+ GameplayRuleManifest.ExecutionDiscipline.DURABLE_GAMEPLAY,
+ GameplayRuleManifest.Stage.GAMEPLAY,
+ GameplayRuleManifest.PromptPolicy.NEVER,
+ GameplayRuleManifest.ActionCategory.GAMEPLAY,
+ true,
+ List.of(),
+ List.of(GameplayRuleManifest.ActionTag.WORLD_BROWSE),
+ List.of("selected-world-admission"));
revisions.add(
new RevisionPayload(
"0",
UUID.randomUUID(),
Owner.GAME_DESIGN_CONTROL_PLANE,
- CommandSource.upsertPayload(commandJson)));
+ GameplayRuleSource.upsertPayload(selectedWorldAction)));
units.add(
new AffectedUnit(
Owner.GAME_DESIGN_CONTROL_PLANE,
- CommandSource.SCOPE,
+ GameplayRuleSource.SCOPE,
target.canonicalVersionId().toString(),
- CommandSource.SCOPE,
- CommandSource.SCOPE_ID,
+ GameplayRuleSource.SCOPE,
+ GameplayRuleSource.SCOPE_ID,
"0"));
revisions.add(
new RevisionPayload(
"1",
UUID.randomUUID(),
Owner.GAME_DESIGN_CONTROL_PLANE,
+ GameplayRuleSource.upsertPayload(selectedWorldCommand)));
+ revisions.add(
+ new RevisionPayload(
+ "2",
+ UUID.randomUUID(),
+ Owner.GAME_DESIGN_CONTROL_PLANE,
GameplayRuleSource.upsertPayload(
new GameplayRuleManifest.AdmissionTag("selected-world-admission"))));
- units.add(
- new AffectedUnit(
- Owner.GAME_DESIGN_CONTROL_PLANE,
- GameplayRuleSource.SCOPE,
- target.canonicalVersionId().toString(),
- GameplayRuleSource.SCOPE,
- "effective",
- "0"));
String policyPayload =
"{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"selected-public-realm\",\"policy\":{"
+ "\"schemaVersion\":1,\"worldSlug\":\"controlled-selected-world\",\"worldDisplayName\":\"World\","
From d4fe3bac4a6d5d35dfb76b79b54a1a6c2f1f7b55 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Fri, 16 Oct 2026 23:54:16 +1300
Subject: [PATCH 23/55] Format qualified canonical gameplay publication fixture
---
...SelectedFullOwnerPublicationPostgresIntegrationTest.java | 6 +-----
1 file changed, 1 insertion(+), 5 deletions(-)
diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
index 113eee2e0f..f50e80d7a4 100644
--- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
+++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
@@ -291,11 +291,7 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema
.orElseThrow();
assertThat(synchronizedSources.command().definitions()).isEmpty();
var gameplaySnapshot = synchronizedSources.gameplayEvidence().orElseThrow();
- assertThat(
- gameplaySnapshot
- .manifest()
- .families()
- .get(GameplayRuleManifest.Family.COMMANDS))
+ assertThat(gameplaySnapshot.manifest().families().get(GameplayRuleManifest.Family.COMMANDS))
.extracting(GameplayRuleManifest.Definition::key)
.containsExactly("LOOK");
var gameplaySource = new GameplayRuleSelectedSource(gameplaySnapshot.canonicalJson());
From 8180b64d34a95f45084b75a1b2e981d9da7397d7 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Sat, 17 Oct 2026 04:57:51 +1300
Subject: [PATCH 24/55] docs: restore selected Game Logic intake API contract
---
.../microservices/game-logic-service/api-contracts.md | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/design/architecture/microservices/game-logic-service/api-contracts.md b/design/architecture/microservices/game-logic-service/api-contracts.md
index d2f24a2288..44efc9a0d8 100644
--- a/design/architecture/microservices/game-logic-service/api-contracts.md
+++ b/design/architecture/microservices/game-logic-service/api-contracts.md
@@ -53,6 +53,16 @@ Expected response:
## gRPC
+### Selected-source intake command
+
+The standalone [`RetainGameplayRuleIntake`](../../../../protos/game-logic/v1/gameplay_rule_intake_service.proto) method admits only the exact verified same-namespace Game Design workload, authenticated before decoding. Its versioned request carries independent transport correlation and the complete original Account intake authorization bytes/digest; the closed response echoes the exact binding and original immutable terminal. The intake owner rejects the canonical original Draft and Game Logic intake-authorization credential contexts; player or operator context supplies no intake mutation authority. A service identity alone does not authorize retention: the exact Account HELD operation and synchronized Game Design source remain mandatory under the [selected-input owner contract](runtime-and-data.md#draft-digest-contract). The adapter is unregistered and grants no publication, activation or runtime permission.
+
+### Selected-source terminal read
+
+The separate, unregistered [`ReadGameplayRuleIntakeTerminal`](../../../../protos/game-logic/v1/gameplay_rule_intake_terminal_service.proto) method accepts only verified same-namespace Account callers, authenticating before decoding source evidence. Its versioned request binds the namespace, fresh read correlation and exact original Account intake authorization bytes/digest. Its closed response echoes that tuple and returns either the original canonical terminal and digest or explicit absence; absence is not an abort. The read is allowlisted to Account and performs no source creation, retention, abort, settlement, or admission. The [Account owner contract](../account-service/api-contracts.md#grpc-apis) defines held-order fencing and exact settlement authority; the [runtime/data owner](runtime-and-data.md#draft-digest-contract) defines intake and definitive-abort semantics. The [selected intake tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) and [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records unregistered transport, bounded-message and physical proof gates.
+
+### Gameplay methods
+
- `Ping(PingRequest) returns (PingResponse)` is the basic connectivity check defined in [`game_logic_service.proto`](../../../../protos/game-logic/v1/game_logic_service.proto).
- `ExecuteCommand(ExecuteCommandRequest) returns (ExecuteCommandResponse)` evaluates a parsed gameplay command and returns the outcome.
- `SendCommunication` is the target gameplay communication contract: it inherits the complete validated `PlayerExecutionContext` from Game Session, classifies a world/gameplay communication type, resolves topology/perception/capability/effect facts, and forwards one bounded plan with stable identity, authorized candidate views, and owner handoffs. The current Game Logic adapter first requires `account_id` to be present, positive, and numeric; malformed, missing, or non-positive account identity returns `INVALID_ARGUMENT` before Entity Management or Social calls. It then projects the flat request to Social & Groups as `tenant_id`, that validated account identity as `sender_id`, mapped communication `type`, normalized text as `content`, the resolved recipient when applicable, and `effect_id`; it never falls back to `character_id` for sender authority. It does not forward `session_id`, room context, target kind/name, or legacy `session_attestation` unchanged. Game Logic owns validating the incoming request fields against the target context, but focused tenant/session/character/target mismatch and projection proof remains an implementation gap. Until that target context is propagated, the live request remains the flat field set documented under [Player execution context](#player-execution-context), including legacy `session_attestation`; those request fields are data to validate against the target context, never caller authority. Account messaging, ordinary group/channel communication, browser social actions, and ordinary account/social mail are Social-owned classes and may use an authenticated in-game adapter without becoming Game Logic actions or exposing private content to tenant-authored scripts. Deliberately world-specific mail is a gameplay communication class under [ADR 0147](../../decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md); [ADR 0148](../../decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md) remains the value and attachment authority. See active ADR 0147, mapped from reviewed archive record `archive-ADR-0134`.
From 3abddf3bb4187583b7170189adf6d4baf3a176c7 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Sat, 17 Oct 2026 21:08:28 +1300
Subject: [PATCH 25/55] docs(publication): align selected owner digest
contracts
---
.../automation-scripting-service/api-contracts.md | 10 ++++++++--
.../entity-management-service/api-contracts.md | 10 +++++++++-
2 files changed, 17 insertions(+), 3 deletions(-)
diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md
index 6c560f05ef..d080f2b93d 100644
--- a/design/architecture/microservices/automation-scripting-service/api-contracts.md
+++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md
@@ -274,10 +274,16 @@ This service is a required digest participant for full publishes and script-patc
Publish gating must fail closed when the service cannot attest a digest under its documented manifest for the reported `digestSchemaVersion`.
+**Current selected-empty status:** An unregistered owner-local reader now provides a bounded selected-empty full-version primitive over Automation's immutable validated fresh-empty receipt. Its native receiver applies the existing exact `PublicationReadGuard` and validates the complete publication request binding before lookup. The existing registered full-version reader remains unchanged; this primitive does not make Automation publication readiness or runtime registration complete. It accepts only a receipt created by the fresh `retainFresh` path with all three declared script, event-binding, and patch-base-binding families explicitly empty. Nonempty or historical participant evidence outside this exact fresh-empty path is unsupported and denied; old participant evidence is not silently rewritten or reinterpreted. This selected-empty full-version semantic path uses `digestSchemaVersion=6`; the existing script-patch digest remains schema 5 with its existing behavior.
+
+The selected-empty reader resolves by configured namespace, canonical tenant UUID, and the numeric Game Design Version row in the incoming full-version request. It scans only that namespace/tenant association prefix, fully validates each receipt, and requires exactly one association whose retained original selected-target proof matches the tenant, canonical Version UUID, and numeric Game Design Version row. The retained proof supplies the canonical Version UUID; the caller does not invent or submit it, and no mapping migration is introduced. Missing, ambiguous, corrupt, or mismatched evidence fails closed. Private Automation numeric keys, receipt digests/bytes, request/operation/authorization provenance, World read evidence, and timestamps are not publication identity or digest input. Its SHA-256 content preimage uses ADR 0047 byte-length framing over these ordered segments: the owner-specific domain `automation-selected-empty-publication-digest/v1`, schema `6`, canonical tenant UUID, numeric Game Design Version row, canonical Version UUID retained in the selected-target proof, and the exact canonical Automation inventory declaration. `appliedCommitId` is the original selected commit UUID retained in the receipt. This subset is not a claim that nonempty full-version script graphs or bindings are covered, and schema-6 participant evidence is not created by rewriting old evidence.
+
+The selected-empty service also requires the complete incoming publication request, derived workflow and digest to match its original retained World freeze and exact selected commit/acknowledgement. This schema-6 participant is admitted only through the [canonical selected-full profile](../game-design-service/version-control.md#selected-full-publication-profile) with independent retained recipient validation; it supplies no activation or publication authority on its own.
+
### Game Design owner-to-owner digest authorization
For publication-gate calls, `GetDraftDesignDigest` is not an admin or user operation. The target receiver authorization is a method-level allowlist for the authenticated Game Design workload identity, under the shared [Security Architecture](../../system-architecture-security.md) and [Authentication & Authorization](../../system-architecture-authentication.md) owner rules. The call must carry and validate the exact `{tenantId, scope}` (`versionId` or `scriptPatchVersion`) together with the stable caller `publishRequestId`, derived workflow identity, and canonical `requestDigest`; omitted or changed binding fails closed. This context is authorization and replay evidence, not a digest input. Other internal workloads are denied, and no user/admin JWT is accepted as a substitute. Game Design's Temporal activities must never forward the initiating human operator JWT; operator authority terminates at workflow admission.
-**Current status:** `GetDraftDesignDigest` now invokes `PublicationReadGuard` for the exact Automation publication-read method. The guard requires the authenticated Game Design workload peer in the trusted namespace and a role-free internal JWT; the JWT `serviceName` claim is not treated as workload identity, and user/admin JWT substitution or a different peer is denied. The request proto carries tenant, typed scope, the patch `baseVersionId` when applicable, stable `publishRequestId`, derived workflow identity, and canonical `requestDigest`; the handler validates that complete binding before reading content and exact-compares the returned tenant and scope. Focused unit proof covers the allowlisted peer, missing/wrong peer, JWT-only/user/admin substitution, and changed request digest. This closes the former empty-role/admin-guard authorization failure, but does not claim live mounted-certificate or real Temporal-activity proof. The schema-5 script-patch content digest includes the retained base version. Remaining content/proof gaps are explicit: the full-version digest input is still tenant-wide rather than version-mapped, and multi-version/cross-tenant owner proof is still required. See the [Game Design publication/Temporal contract](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) for the coordinator-side boundary.
+**Current status:** `GetDraftDesignDigest` now invokes `PublicationReadGuard` for the exact Automation publication-read method. The guard requires the authenticated exact Game Design workload mTLS peer in the configured trusted namespace and denies account, global-role, or scoped-role context. It does not add an end-user JWT requirement; a role-free internal identity is neither workload authorization nor an independent denial condition when the exact peer is present. The request proto carries tenant, typed scope, the patch `baseVersionId` when applicable, stable `publishRequestId`, derived workflow identity, and canonical `requestDigest`; the handler validates that complete binding before reading content and exact-compares the returned tenant and scope. Focused unit proof covers the allowlisted peer without end-user context, missing/wrong peer, account/global/scoped-role context denial, and changed request digest. This does not claim live mounted-certificate or real Temporal-activity proof. The existing script-patch content digest remains schema 5 and includes the retained base version; the selected-empty schema-6 primitive is unregistered and does not replace the live full-version reader, whose input remains tenant-wide. Multi-version/cross-tenant owner proof is still required. See the [Game Design publication/Temporal contract](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) for the coordinator-side boundary.
-The same owner-to-owner authorization now covers the WMS, Entity, Game Logic, and Automation participant reads: each handler applies the shared exact-method `PublicationReadGuard`, validates the complete typed request binding, and checks the returned tenant/scope before exposing its digest. The shared negative proof covers missing or wrong peer identity and JWT-only/user/admin substitution; live mounted-certificate, real Temporal-activity, and multi-version/cross-tenant proof remain separate gaps. Content manifests remain owner-local: Automation's patch digest now binds the retained base version, while its full-version mapping remains tenant-wide, so the authorization boundary must not be read as complete digest correctness. The shared target and proof requirements are maintained in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity), not redefined here.
+The same owner-to-owner authorization now covers the WMS, Entity, Game Logic, and Automation participant reads: each handler applies the shared exact-method `PublicationReadGuard`, validates the complete typed request binding, and checks the returned tenant/scope before exposing its digest. The guard requires the exact authenticated Game Design workload mTLS peer and denies account or role-bearing context; role-free internal identity alone is not authorization or a substitute for that peer. Live mounted-certificate, real Temporal-activity, and multi-version/cross-tenant proof remain separate gaps. Content manifests remain owner-local: Automation's patch digest now binds the retained base version, while its existing live full-version mapping remains tenant-wide, so the authorization boundary must not be read as complete digest correctness. The shared target and proof requirements are maintained in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity), not redefined here.
diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md
index 40efc3b992..afb85df57c 100644
--- a/design/architecture/microservices/entity-management-service/api-contracts.md
+++ b/design/architecture/microservices/entity-management-service/api-contracts.md
@@ -93,12 +93,20 @@ Entity Management must also expose a read-only design-time synchronization surfa
- `GetDraftDesignDigest(GetDraftDesignDigestRequest)` uses request shape `{tenantId, scope: oneof {versionId, scriptPatchVersion}}`. Entity Management supports `versionId` scope only and returns `UNSUPPORTED_SCOPE` otherwise.
- Response returns `{tenantId, scope, appliedCommitId, contentDigest, digestSchemaVersion}` as described in [`world-editing-tools.md`](../game-design-service/world-editing-tools.md).
-- Current drift: the digest handler has no owner/method authorization or exact Game Design publication binding beyond shared bearer parsing. The target workload, tenant/scope/request/workflow/digest context and denial proof are canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity).
+- Current boundary: `GetDraftDesignDigest` requires a configured trusted namespace and the exact authenticated Game Design workload peer through `PublicationReadGuard`, and denies authenticated account or role-bearing caller context. A role-free internal identity is not workload authorization or an additional JWT requirement. The handler validates the complete typed publication request binding and exact returned tenant/scope. Its registered reader still supplies synthetic `appliedCommitId = "version:"`; that projection is not selected-commit evidence. The target binding and proof requirements remain canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity).
## Digest Input Manifest
Entity Management is a required publish-gate participant and must maintain a stable digest manifest for `GetDraftDesignDigest(versionId)`:
+**Current selected-empty status:** An unregistered owner-local reader now provides a bounded selected-empty full-version primitive over Entity's immutable validated fresh-empty receipt. Its native receiver applies the existing exact `PublicationReadGuard` and validates the complete publication request binding before lookup. The existing registered digest reader remains unchanged; this primitive does not make Entity publication readiness or runtime registration complete. It accepts only a receipt created by the fresh `retainFresh` path with the complete 23-family census explicitly empty, including `equipmentApplicability=NOT_APPLICABLE` and every declared family empty. Nonempty or historical participant evidence outside this exact fresh-empty path is unsupported and denied; old participant evidence is not silently rewritten or reinterpreted.
+
+The selected-empty reader resolves by configured namespace, canonical tenant UUID, and the numeric Game Design Version row in the incoming full-version request. It scans only that namespace/tenant association prefix, fully validates each receipt, and requires exactly one association whose retained original selected-target proof matches the tenant, canonical Version UUID, and numeric Game Design Version row. The retained proof supplies the canonical Version UUID; the caller does not invent or submit it, and no mapping migration is introduced. Missing, ambiguous, corrupt, or mismatched evidence fails closed. Private Entity numeric keys, receipt digests/bytes, request/operation/authorization provenance, World read evidence, and timestamps are not publication identity or digest input.
+
+For this selected-empty subset, `digestSchemaVersion=3`; the SHA-256 content preimage uses ADR 0047 byte-length framing over these ordered segments: the owner-specific domain `entity-selected-empty-publication-digest/v1`, schema `3`, canonical tenant UUID, numeric Game Design Version row, canonical Version UUID retained in the selected-target proof, and the exact canonical Entity inventory declaration. `appliedCommitId` is the original selected commit UUID retained in the receipt. The new semantic preimage requires a new schema under the digest migration rule; retained schema-2 participant evidence keeps its original meaning and bytes. This is a separately versioned, bounded semantic digest, not a receipt digest and not a claim that all nonempty Entity template families are covered. Only the new selected full-release profile may accept schema 3 after its compatible recorded owner evidence and exact readback pass; existing participant evidence is not upgraded in place.
+
+The selected-empty service additionally compares the incoming publication request, derived workflow and request digest with the original retained World freeze, its exact selected commit and acknowledgement. A later read correlation or latest owner state cannot substitute for that publication operation. Its schema-3 digest participates only in the [selected-full publication profile](../game-design-service/version-control.md#selected-full-publication-profile), where Game Design independently validates retained recipient evidence. Controlled receipt fixtures, local content integrity and a successful standalone read do not establish genuine Account authority, an authored producer, continuous currentness or permission to publish.
+
Implementation Notes:
- The current implementation hashes the version-scoped entity-definition rows for the requested `(tenantId, versionId)` and returns synthetic `appliedCommitId = "version:"` until the later applied-revision ledger lands.
From 46a0fb3731a6368b55d5c69a99b522299e5ac704 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Sun, 18 Oct 2026 05:53:31 +1300
Subject: [PATCH 26/55] docs: align selected-full owner qualification with
retained proof
---
.../microservices/game-design-service/version-control.md | 4 ++--
.../game-authoring-publishing-and-activation.md | 2 +-
2 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md
index 5a0a7ae955..abd6ff221f 100644
--- a/design/architecture/microservices/game-design-service/version-control.md
+++ b/design/architecture/microservices/game-design-service/version-control.md
@@ -6,11 +6,11 @@ Game Design is the canonical authored-history, publication-coordination, release
## Implementation Status
-The selected-full owner closure is prepared as unqualified source: exact selected digest collection and retained Game Logic reads feed the existing guarded release storage, while public fresh/PENDING publication remains denied. All new owner components remain standalone and unregistered, and the default Game Logic Spring composition remains denied. No fresh schema-4 writer/readback or native cross-owner passing result is claimed; current scope and qualification limits are recorded in the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation).
+R45 qualifies the controlled five-store selected-full owner composition, including schema-4 bundle write, independent readback and exact retry; detailed proof attribution and limits are recorded in the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation). Account authorization and source/provenance, creator, issuer, environment, asset metadata and PKI inputs remain controlled. Owner components remain standalone and unregistered, public fresh/PENDING publication remains denied, and the default Game Logic Spring composition remains denied. This does not establish genuine creator, issuer, environment, release or continuous-protection authority, activation, actor placement or operational delivery.
The recipient-intake preparation adds an unregistered Account-authenticated read of all six selected source families. Its required branding source owner uses existing V1007 storage, and command snapshot parsing converges on the shared typed contract while retaining owner-local capture context. No retained source is inferred or upgraded to complete. Qualification and selected-owner producer dependencies remain in the [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation).
-The shared strict selected-full attestation and terminal codecs, read-only World lifecycle support for schema 4 and a class-only guarded World evidence fixture are source-prepared and unqualified in this read stage. The actual Game Design writer/storage integration, fixture factory execution and five-store owner composition remain in the full selected-owner successor; this preparation supplies no fresh publication authority. Public fresh/PENDING publication remains denied and no activation or component registration is enabled. Current execution attribution and remaining qualification are recorded in the [selected-template tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-template-publication-and-original-launch-reads).
+The shared strict selected-full codecs, read-only World lifecycle support for schema 4 and class-only guarded World evidence fixture are exercised in the R45 owner composition. Its detailed qualification and controlled-input limits are recorded in the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation); the separate [selected-template tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-template-publication-and-original-launch-reads) retains that slice's own scope and proof status. This owner composition grants no genuine creator, issuer, environment, release or continuous-protection authority, and enables no registration or activation.
Standalone Template source/reference owners, selected-publication reservation and the exact original StartSession template read are prepared over existing guarded storage. They remain unregistered; qualified owner-local storage does not supply genuine Account, World or immutable-release authority. Current source, proof and retention limitations belong to [the authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-template-publication-and-original-launch-reads).
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index 28d00743e4..4650294589 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -114,7 +114,7 @@ The receiving full Game Design gate at `3ad94e6c595dffbb2ca0c01c677512832574e706
The prior `a35e155da930714ded1c8ff93d097d9ce2df00b6` attempt failed compiling the native fixture and receives no native proof credit. On source `aa3aa977a5f3d13cdc33b99636e8bd7a9ff33f87`, `StartSessionLaunchDescriptorProducer` and `AuthoredInitialActorCoreReadService` use one shared `SelectedGameplayRuleSourceJoin` predicate for operation, selected-binding and canonical-byte equality across the frozen Gameplay capture, selected source snapshot and retained Game Logic receipt, implementing the [canonical selected-source contract](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations). The corrected focused retry freshly passed all seven cases in `SelectedDraftGameLogicReceiptPostgresIntegrationTest`, including equal-byte acceptance and same-binding unequal-byte refusal after current owner capture and immutable receipt readback; the operation remained `PENDING`, with controlled Account and Game Logic inputs. Integration Checkstyle, SpotBugs and Spotless checks also passed. This qualifies the shared production predicate at the owner boundary, not a public StartSession lifecycle journey, runtime registration, current upstream authority or closure of a genuine Gameplay handoff.
-This read-stage preparation also carries the strict shared attestation and terminal codecs, read-only World lifecycle support for the [canonical selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile), and a class-only guarded World fixture. The eight prepared code paths comprise the two shared models and their focused proofs, the World lifecycle reader and its unit proof, the guarded native fixture and its class-only build export. These postimages are source-prepared and unqualified; no factory execution or passing fresh writer/readback is claimed. Actual Game Design writer/storage integration and five-store proof remain in the full selected-owner successor. Public fresh/PENDING publication remains default-denied; no registration, activation or genuine creator, issuer, environment, release or continuous-protection authority is granted. All four genuine Gameplay handoffs remain open and broader Unit 1B remains paused.
+The read-stage preparation's strict shared attestation and terminal codecs, read-only World lifecycle support for the [canonical selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile), and class-only guarded World fixture are exercised by the R45 five-store owner composition described above. This linked qualification covers the controlled owner composition only: public fresh/PENDING publication remains default-denied, no component registration or activation is enabled, and no genuine creator, issuer, environment, release or continuous-protection authority is established. All four genuine Gameplay handoffs remain open and broader Unit 1B remains paused.
Qualification remains partial. R21's focused gate freshly passes all 12 Game Design Template configuration cases with zero skips; the three Game Session authored-core cases retain their R20 pass and also pass in R21's fresh unfiltered native execution. Game Session proves the actual V37/V38 immutable pins, exact original live owner selectors, constructor and repository denials, foreign-key and cascading-truncate refusal, unchanged owner/launch/pin row bytes and versions, live-read expiry and V1013 retention/upgrade. Game Design now proves first publication reservation, concurrent winning read correlation, exact replay, association-conflict denial and original Template provenance using a real visible public-production `REALM_ENTRY_POLICY` mutation before its complete World-only successor. Upstream Account and World inputs remain stipulated component evidence; these tests do not establish genuine authority.
From a7d85691ab4d9591b80dfac66c4a63aa597baa02 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Sun, 18 Oct 2026 06:11:36 +1300
Subject: [PATCH 27/55] docs: retain scoped selected-full proof and
endpoint-refusal outcome
---
design/project-management/ai-observations.md | 6 ++++++
.../game-authoring-publishing-and-activation.md | 2 ++
2 files changed, 8 insertions(+)
diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md
index 4770f59b0c..2b3e1419aa 100644
--- a/design/project-management/ai-observations.md
+++ b/design/project-management/ai-observations.md
@@ -198,3 +198,9 @@ Entry format:
- Observation: the current allocation status and review-record history exposed the budget, null checkpoint and taper explanation, but no allocation decision timestamp or original grant rationale. Verifying the controlling allowance required a complete queue readback; no head-change counter reset was established.
- Expected pattern: expose the controlling grant decision, timestamp, actor, original reason and baseline beside its additional-result count through an existing read-only controller command, so a worker can distinguish lifetime history from the current allowance without guessing. This is a tooling suggestion; existing counting and authorization rules stay unchanged.
- Reconsideration trigger: when an existing read-only controller command exposes the controlling grant decision, timestamp, rationale and baseline beside the remaining allowance, verify it against separate lifetime and current allowances and revisit the manual queue readback.
+
+- `2026-10-18`: Follow up the PostgreSQL endpoint refusal with one scoped reproduction
+ - Context: the new Automation Flyway test-time refusal met the reconsideration trigger in the `2026-10-13` PostgreSQL endpoint-diagnosis observation.
+ - Observation: one focused five-store reproduction passed with zero failures, errors or skips and no endpoint refusal. All five exact containers were observed running with host-port bindings and absent after the Gradle child ended. Six inspect errors and 20 unparsed records arose only after the case completed during sequential teardown, so continuous ownership through cleanup is not established.
+ - Outcome: the preceding Automation Flyway refusal remains failed evidence with unknown cause; the passing reproduction does not explain it. No speculative host or readiness change is selected.
+ - Reconsideration trigger: a later physical test-time endpoint refusal, or separately retained evidence that identifies the refused endpoint's failure mechanism.
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index 4650294589..e660a8a9d1 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -36,6 +36,8 @@ R38 freshly passes 178 Common Security units and 23 native PostgreSQL cases: Ent
Upstream Account authorization, source/provenance inputs, creator, issuer, environment and PKI remain explicitly controlled where used. Empty asset manifest metadata and the candidate delivery origin are controlled; no object-store write or public delivery is proved. These standalone unregistered owner components do not establish genuine authority, current or continuous protection, runtime activation, actor placement or operational delivery. Historical release bytes retain their original scoped read/retry meaning. All four genuine Gameplay handoffs remain open and broader Unit 1B/corpus stays paused.
+Gameplay receiving revision `46a0fb3731a6368b55d5c69a99b522299e5ac704` freshly passes the existing `SelectedFullOwnerPublicationPostgresIntegrationTest`: one five-store physical case, zero failures, errors or skips. `linkCheck` and `lintMarkdown` also pass in that invocation. The preceding focused attempt failed during the Automation Flyway store at `localhost:59128`; the scoped passive reproduction passed without a refusal and does not establish the earlier cause. It observed all five run-owned containers running with host-port bindings and absent at child completion, but six inspect errors and 20 unparsed records occurred after case completion during sequential teardown, so continuous ownership through cleanup is not claimed. The previously recorded R45 686 Game Design unit and R38 owner-suite attributions were not rerun. Account authorization and source/provenance, creator, issuer, environment, asset metadata and PKI inputs remain controlled; the owner components remain standalone and unregistered, public fresh/PENDING publication remains denied, and this result establishes no genuine authority, activation or Unit 1B release.
+
### Selected-full release service refusal proof
The existing release-bundle service test independently substitutes each of the five participant digest schemas and verifies that the service refuses the mixed vector before saving a release. The current full `4/3/1/6/2` positive, immutable selected retry, source-capture and command validation cases remain intact; historical schema-3 consumer support is not widened.
From 8007dacd7a38e95bbd46eceabbf456550d0f9453 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Sun, 18 Oct 2026 06:30:21 +1300
Subject: [PATCH 28/55] docs: state the reusable endpoint diagnosis pattern
---
design/project-management/ai-observations.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md
index e083c24fe1..aa7b308605 100644
--- a/design/project-management/ai-observations.md
+++ b/design/project-management/ai-observations.md
@@ -206,5 +206,6 @@ Entry format:
- `2026-10-18`: Follow up the PostgreSQL endpoint refusal with one scoped reproduction
- Context: the new Automation Flyway test-time refusal met the reconsideration trigger in the `2026-10-13` PostgreSQL endpoint-diagnosis observation.
- Observation: one focused five-store reproduction passed with zero failures, errors or skips and no endpoint refusal. All five exact containers were observed running with host-port bindings and absent after the Gradle child ended. Six inspect errors and 20 unparsed records arose only after the case completed during sequential teardown, so continuous ownership through cleanup is not established.
+ - Expected pattern: retain the original failed test evidence and capture only exact run-owned container states and ports before teardown when a new refusal justifies focused reproduction; keep a successful reproduction distinct from an explained cause.
- Outcome: the preceding Automation Flyway refusal remains failed evidence with unknown cause; the passing reproduction does not explain it. No speculative host or readiness change is selected.
- Reconsideration trigger: a later physical test-time endpoint refusal, or separately retained evidence that identifies the refused endpoint's failure mechanism.
From 55aa8808375bd55ce80b21a74a6a9e8a84e19bf3 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Sun, 18 Oct 2026 07:58:11 +1300
Subject: [PATCH 29/55] Record stale PR metadata attribution friction in
canonical LOC helper
---
design/project-management/ai-observations.md | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md
index 0c0a64ed05..4230916154 100644
--- a/design/project-management/ai-observations.md
+++ b/design/project-management/ai-observations.md
@@ -210,3 +210,8 @@ Entry format:
- Expected pattern: retain the original failed test evidence and capture only exact run-owned container states and ports before teardown when a new refusal justifies focused reproduction; keep a successful reproduction distinct from an explained cause.
- Outcome: the preceding Automation Flyway refusal remains failed evidence with unknown cause; the passing reproduction does not explain it. No speculative host or readiness change is selected.
- Reconsideration trigger: a later physical test-time endpoint refusal, or separately retained evidence that identifies the refused endpoint's failure mechanism.
+
+- `2026-10-18`: Verify LOC report identity after a PR fast-forward
+ - Context: `cloc-report.py pr 3248` ran immediately after the existing branch advanced from `6c3eed5d651b` to `eb40332cdb9f`.
+ - Observation: GitHub still returned the preceding PR head/base payload, so the canonical helper completed successfully with LOC metadata for the old candidate. The worker caught the mismatch before editing the body and regenerated after payload convergence; no stale report was published. The tool-level consistency guard remains an improvement reported to Overseer.
+ - Expected pattern: compare generated head/base metadata with verified current remote refs before publication; a mismatch must refresh or fail closed. A successful LOC command alone does not prove current candidate attribution.
From df0df124886e1af01d92188810b764930b0098de Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Sun, 18 Oct 2026 22:42:31 +1300
Subject: [PATCH 30/55] Recover expired preliminary source reservations under
Account locks
---
...wnerIntakeSourceReservationRepository.java | 97 +++++++
...edOwnerIntakeSourceReservationService.java | 39 +++
...eAuthorizationPostgresIntegrationTest.java | 243 ++++++++++++++++++
...nerIntakeSourceReservationServiceTest.java | 68 +++++
.../AccountControlUiOriginalOrderFixture.java | 34 ++-
5 files changed, 480 insertions(+), 1 deletion(-)
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java
index ec50e5e71b..8f803ebb54 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java
@@ -21,6 +21,7 @@
import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence;
import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence;
import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.springframework.transaction.support.TransactionSynchronizationManager;
@@ -30,6 +31,8 @@
* Automation {@code COMMITTED_EMPTY} terminal settlement.
*/
public final class AccountSelectedOwnerIntakeSourceReservationRepository {
+ public static final int MAX_EXPIRED_PRELIMINARY_RECOVERY_BATCH_SIZE = 128;
+
private static final String RESERVATIONS =
"account_selected_owner_intake_source_read_reservations";
private static final String SOURCES = "account_selected_owner_intake_source_read_sources";
@@ -208,6 +211,100 @@ Recovery abortSourceRead(SelectedOwnerIntakeSourceReadScope scope) {
return new Recovery(scope, State.ABORTED);
}
+ /**
+ * Finds a bounded page of exact, expired, unfinalized reservations for one Account namespace.
+ * The scope and complete retained source vector are validated before a candidate is returned.
+ */
+ List findExpiredPreliminarySourceReadScopes(
+ int limit, String namespace) {
+ requireTransaction();
+ requireRecoveryLimit(limit);
+ if (!GrpcPeerIdentity.isValidNamespace(namespace)) {
+ throw new IllegalArgumentException("Canonical Account workload namespace required");
+ }
+
+ List rows =
+ dsl.fetch(
+ "SELECT reservation.* FROM "
+ + RESERVATIONS
+ + " reservation JOIN account_control_ui_issuance_operations issuer"
+ + " ON issuer.operation_id = reservation.issuance_operation_id"
+ + " CROSS JOIN LATERAL account_publication_authorization_read_frame("
+ + "reservation.scope_bytes, 1) schema_part"
+ + " CROSS JOIN LATERAL account_publication_authorization_read_frame("
+ + "reservation.scope_bytes, schema_part.next_position) owner_part"
+ + " CROSS JOIN LATERAL account_publication_authorization_read_frame("
+ + "reservation.scope_bytes, owner_part.next_position) namespace_part"
+ + " LEFT JOIN "
+ + AUTHORIZATIONS
+ + " authorization ON authorization.operation_id = reservation.operation_id"
+ + " LEFT JOIN "
+ + ABORTS
+ + " aborted ON aborted.operation_id = reservation.operation_id"
+ + " WHERE convert_from(namespace_part.frame_value, 'UTF8') = ?"
+ + " AND issuer.status = 'COMMITTED'"
+ + " AND extract(epoch FROM clock_timestamp()) >= issuer.expires_at_epoch_second"
+ + " AND authorization.operation_id IS NULL"
+ + " AND aborted.operation_id IS NULL"
+ + " ORDER BY issuer.expires_at_epoch_second, reservation.operation_id"
+ + " LIMIT ?",
+ namespace,
+ limit);
+ List scopes = new ArrayList<>(rows.size());
+ for (Record row : rows) {
+ var scope =
+ SelectedOwnerIntakeSourceReadScope.fromStored(
+ row.get("scope_bytes", byte[].class));
+ if (!namespace.equals(scope.targetNamespace())) {
+ throw new IllegalArgumentException("Expired reservation belongs to another namespace");
+ }
+ requireReservation(row, scope);
+ scopes.add(scope);
+ }
+ return List.copyOf(scopes);
+ }
+
+ /**
+ * Aborts one expired preliminary reservation after taking the canonical source and reservation
+ * locks. A concurrent finalization or a candidate that is no longer eligible is skipped.
+ */
+ boolean abortExpiredPreliminarySourceRead(
+ SelectedOwnerIntakeSourceReadScope scope, String namespace) {
+ requireTransaction();
+ Objects.requireNonNull(scope, "scope");
+ if (!GrpcPeerIdentity.isValidNamespace(namespace)
+ || !namespace.equals(scope.targetNamespace())) {
+ throw new IllegalArgumentException("Exact Account workload namespace required");
+ }
+ requireOwner(scope.owner());
+
+ lockReservedSources(scope);
+ Record row = reservation(scope);
+ requireReservation(row, scope);
+ if (aborted(scope) || authorization(scope.operationId()) != null) return false;
+
+ UUID issuanceOperationId = row.get("issuance_operation_id", UUID.class);
+ if (dsl.fetchOne(
+ "SELECT operation_id FROM account_control_ui_issuance_operations"
+ + " WHERE operation_id = ? AND status = 'COMMITTED'"
+ + " AND extract(epoch FROM clock_timestamp()) >= expires_at_epoch_second",
+ issuanceOperationId)
+ == null) {
+ return false;
+ }
+
+ dsl.execute("INSERT INTO " + ABORTS + " (operation_id) VALUES (?)", scope.operationId());
+ return true;
+ }
+
+ private static void requireRecoveryLimit(int limit) {
+ if (limit <= 0 || limit > MAX_EXPIRED_PRELIMINARY_RECOVERY_BATCH_SIZE) {
+ throw new IllegalArgumentException(
+ "Expired preliminary recovery batch must be between 1 and "
+ + MAX_EXPIRED_PRELIMINARY_RECOVERY_BATCH_SIZE);
+ }
+ }
+
SelectedOwnerIntakeAuthorizationBinding finalizeSourceRead(
SelectedOwnerIntakeSourceReadScope scope,
SelectedOwnerIntakeSourceContent content,
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java
index 571ae7e553..0cc293755d 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java
@@ -137,6 +137,45 @@ public AccountSelectedOwnerIntakeSourceReservationRepository.Recovery abortSourc
return abortSourceRead(scope);
}
+ /**
+ * Performs one bounded Account-internal reconciliation page before any receiver is registered.
+ * It is not a transport or scheduled job: the caller owns invocation and readiness policy.
+ * Each candidate is rechecked and, if still eligible, durably aborted in its own independent
+ * READ_COMMITTED owner transaction. Finalized and concurrently changed candidates are skipped.
+ *
+ * @return abort rows committed by this page; this is not a global completion signal
+ */
+ public int recoverExpiredPreliminarySourceReads(int maximumCandidates) {
+ if (maximumCandidates <= 0) {
+ throw new IllegalArgumentException(
+ "Expired preliminary recovery batch must be positive");
+ }
+ requireNoAmbientTransaction();
+ int boundedCandidates =
+ Math.min(
+ maximumCandidates,
+ AccountSelectedOwnerIntakeSourceReservationRepository
+ .MAX_EXPIRED_PRELIMINARY_RECOVERY_BATCH_SIZE);
+
+ var candidates =
+ Objects.requireNonNull(
+ ownerTransaction.execute(
+ ignored ->
+ repository.findExpiredPreliminarySourceReadScopes(
+ boundedCandidates, namespace)),
+ "Expired source-read candidate lookup returned no result");
+ int aborted = 0;
+ for (SelectedOwnerIntakeSourceReadScope scope : candidates) {
+ if (Objects.requireNonNull(
+ ownerTransaction.execute(
+ ignored -> repository.abortExpiredPreliminarySourceRead(scope, namespace)),
+ "Expired source-read recovery returned no result")) {
+ aborted++;
+ }
+ }
+ return aborted;
+ }
+
private Optional findScope(
String originalCompactJwt, UUID intakeRequestId, Owner owner, DraftCommitBinding selected) {
requireGameDesignPeer();
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
index 20920fbed8..a2d0762aa7 100644
--- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
@@ -8,6 +8,7 @@
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.Clock;
+import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.Comparator;
@@ -309,6 +310,190 @@ void finalizesBothOwnersExactlyAndKeepsTheirFullSourceVectorsPending() throws Ex
}
}
+ @Test
+ void expiredRecoveryUsesDatabaseCutoffAndPreservesFinalizedOwnerUntilExactSettlement()
+ throws Exception {
+ try (var fixture =
+ new AccountControlUiOriginalOrderFixture(
+ postgres.getJdbcUrl(),
+ postgres.getUsername(),
+ postgres.getPassword(),
+ redis.getHost(),
+ redis.getMappedPort(6379),
+ temporary,
+ UUID.randomUUID(),
+ Clock.systemUTC(),
+ null,
+ Clock.offset(Clock.systemUTC(), Duration.ofSeconds(-290)))) {
+ var issued = fixture.issueCreator();
+ var f = issued.sources();
+ var selected = selectedForSettlement(f.tenant);
+ settleOriginal(issued, selected);
+ var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl);
+ var reservations =
+ new AccountSelectedOwnerIntakeSourceReservationService(
+ issued.actors(), f.fences, repository, f.manager, "test");
+ var preliminary =
+ asGameDesign(
+ () ->
+ reservations.reserveSourceRead(
+ issued.compact(),
+ UUID.randomUUID(),
+ Owner.AUTOMATION_SCRIPTING,
+ selected,
+ issued.environment()));
+ var finalizingScope =
+ asGameDesign(
+ () ->
+ reservations.reserveSourceRead(
+ issued.compact(),
+ UUID.randomUUID(),
+ Owner.ENTITY_MANAGEMENT,
+ selected,
+ issued.environment()));
+ var alreadyFinalized =
+ finalizeEntityBinding(issued, reservations, repository, selected, "recovery-committed");
+ UUID issuanceOperationId =
+ f.dsl
+ .fetchSingle(
+ "SELECT issuance_operation_id FROM account_selected_owner_intake_source_read_reservations"
+ + " WHERE operation_id = ?",
+ preliminary.operationId())
+ .get("issuance_operation_id", UUID.class);
+
+ assertThat(issuerExpiryReached(f.dsl, issuanceOperationId)).isFalse();
+ assertThat(reservations.recoverExpiredPreliminarySourceReads(128)).isZero();
+ assertThat(f.tx(() -> repository.recoverSourceRead(preliminary).state()))
+ .isEqualTo(State.RESERVED);
+ assertThat(sourceReadPending(f.dsl, preliminary.operationId())).isTrue();
+ var finalizationContent = content(finalizingScope, "recovery-race-finalized");
+ var authorizationInserted = new CountDownLatch(1);
+ var allowFinalizationCommit = new CountDownLatch(1);
+ var recoveryStarted = new CountDownLatch(1);
+ var finalizationBackendPid = new AtomicInteger();
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ var finalizing =
+ executor.submit(
+ () ->
+ asGameDesign(
+ () ->
+ issued
+ .actors()
+ .withCurrent(
+ issued.compact(),
+ f.tenant,
+ issued.environment(),
+ current -> {
+ var binding =
+ repository.finalizeSourceRead(
+ finalizingScope,
+ finalizationContent,
+ current,
+ () ->
+ f.fences.requireSelectedOwnerIntakeAdmission(
+ current.source().sources(), selected));
+ finalizationBackendPid.set(
+ f.dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class));
+ authorizationInserted.countDown();
+ awaitFinalizationCommit(allowFinalizationCommit);
+ return binding;
+ })));
+ assertThat(authorizationInserted.await(10, TimeUnit.SECONDS)).isTrue();
+ assertThat(issuerExpiryReached(f.dsl, issuanceOperationId)).isFalse();
+
+ awaitIssuerExpiry(f.dsl, issuanceOperationId);
+ var recovering =
+ executor.submit(
+ () -> {
+ recoveryStarted.countDown();
+ return reservations.recoverExpiredPreliminarySourceReads(128);
+ });
+ assertThat(recoveryStarted.await(10, TimeUnit.SECONDS)).isTrue();
+ awaitRecoverySourceLockWait(f.dsl, finalizationBackendPid.get());
+ assertThat(recovering.isDone()).isFalse();
+
+ allowFinalizationCommit.countDown();
+ Throwable finalizationFailure = null;
+ try {
+ finalizing.get(10, TimeUnit.SECONDS);
+ } catch (java.util.concurrent.ExecutionException expected) {
+ finalizationFailure = expected;
+ }
+ assertThat(finalizationFailure).isNotNull();
+ Throwable rootCause = finalizationFailure;
+ while (rootCause.getCause() != null) rootCause = rootCause.getCause();
+ assertThat(rootCause.getMessage())
+ .contains("Finalized authorization requires exact current committed creator evidence");
+ assertThat(recovering.get(10, TimeUnit.SECONDS)).isEqualTo(2);
+ } finally {
+ allowFinalizationCommit.countDown();
+ executor.shutdownNow();
+ assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue();
+ }
+
+ assertThat(reservations.recoverExpiredPreliminarySourceReads(128)).isZero();
+ assertThat(f.tx(() -> repository.recoverSourceRead(preliminary).state()))
+ .isEqualTo(State.ABORTED);
+ assertThat(f.tx(() -> repository.recoverSourceRead(finalizingScope).state()))
+ .isEqualTo(State.ABORTED);
+ assertThat(sourceReadPending(f.dsl, preliminary.operationId())).isFalse();
+ assertThat(sourceReadPending(f.dsl, finalizingScope.operationId())).isFalse();
+ assertThat(
+ f.dsl
+ .fetchSingle(
+ "SELECT scope_bytes FROM account_selected_owner_intake_source_read_reservations"
+ + " WHERE operation_id = ?",
+ preliminary.operationId())
+ .get("scope_bytes", byte[].class))
+ .isEqualTo(preliminary.canonicalBytes());
+ assertThat(
+ f.dsl
+ .fetchSingle(
+ "SELECT count(*) FROM account_selected_owner_intake_source_read_aborts"
+ + " WHERE operation_id = ?",
+ preliminary.operationId())
+ .get(0, Long.class))
+ .isEqualTo(1L);
+ assertThat(
+ f.dsl
+ .fetchSingle(
+ "SELECT count(*) FROM account_selected_owner_intake_source_read_aborts"
+ + " WHERE operation_id = ?",
+ finalizingScope.operationId())
+ .get(0, Long.class))
+ .isEqualTo(1L);
+
+ var committedScope = alreadyFinalized.content().scope();
+ assertThat(f.tx(() -> repository.recoverSourceRead(committedScope).state()))
+ .isEqualTo(State.FINALIZED);
+ assertThat(sourceReadPending(f.dsl, alreadyFinalized.operationId())).isTrue();
+ assertThat(
+ f.dsl
+ .fetchSingle(
+ "SELECT binding_bytes FROM account_selected_owner_intake_authorizations"
+ + " WHERE operation_id = ?",
+ alreadyFinalized.operationId())
+ .get("binding_bytes", byte[].class))
+ .isEqualTo(alreadyFinalized.canonicalBytes());
+ var terminal = entityTerminalEvidence(alreadyFinalized, 9851, 9852);
+ var settlement = f.tx(() -> repository.settleEntityCommittedEmpty(terminal));
+ assertThat(
+ f.tx(
+ () ->
+ repository
+ .findSettlement(alreadyFinalized)
+ .orElseThrow()
+ .canonicalBytes()))
+ .isEqualTo(settlement.canonicalBytes());
+ assertThat(
+ f.tx(
+ () -> repository.settleEntityCommittedEmpty(terminal).canonicalBytes()))
+ .isEqualTo(settlement.canonicalBytes());
+ assertThat(sourceReadPending(f.dsl, alreadyFinalized.operationId())).isFalse();
+ }
+ }
+
@Test
void commitsExactAutomationEmptySettlementAndReleasesOnlyThatOperation() throws Exception {
try (var fixture =
@@ -2218,6 +2403,64 @@ private static void awaitLatch(CountDownLatch latch) {
}
}
+ private static boolean sourceReadPending(DSLContext dsl, UUID operationId) {
+ return dsl
+ .fetchSingle(
+ "SELECT account_selected_owner_intake_source_read_is_pending(?)", operationId)
+ .get(0, Boolean.class);
+ }
+
+ private static boolean issuerExpiryReached(DSLContext dsl, UUID issuanceOperationId) {
+ return dsl
+ .fetchSingle(
+ "SELECT extract(epoch FROM clock_timestamp()) >= expires_at_epoch_second"
+ + " FROM account_control_ui_issuance_operations WHERE operation_id = ?",
+ issuanceOperationId)
+ .get(0, Boolean.class);
+ }
+
+ private static void awaitIssuerExpiry(DSLContext dsl, UUID issuanceOperationId)
+ throws InterruptedException {
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
+ do {
+ if (issuerExpiryReached(dsl, issuanceOperationId)) return;
+ Thread.sleep(10);
+ } while (System.nanoTime() < deadline);
+ throw new AssertionError("Original Account issuance did not reach its immutable DB expiry");
+ }
+
+ private static void awaitRecoverySourceLockWait(DSLContext dsl, int finalizationBackendPid)
+ throws InterruptedException {
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
+ do {
+ if (Boolean.TRUE.equals(
+ dsl.fetchSingle(
+ "SELECT EXISTS (SELECT 1 FROM pg_stat_activity"
+ + " WHERE pid <> pg_backend_pid() AND datname = current_database()"
+ + " AND wait_event_type = 'Lock'"
+ + " AND ? = ANY(pg_blocking_pids(pid))"
+ + " AND query LIKE '%account_draft_authorization_source_locks%'"
+ + " AND query LIKE '%FOR UPDATE%')",
+ finalizationBackendPid)
+ .get(0, Boolean.class))) {
+ return;
+ }
+ Thread.sleep(10);
+ } while (System.nanoTime() < deadline);
+ throw new AssertionError("Expired recovery did not wait on finalization-held source locks");
+ }
+
+ private static void awaitFinalizationCommit(CountDownLatch latch) {
+ try {
+ if (!latch.await(30, TimeUnit.SECONDS)) {
+ throw new IllegalStateException("Finalization commit was not released");
+ }
+ } catch (InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException("Interrupted finalization lock race", interrupted);
+ }
+ }
+
private static void awaitSourceLockWait(DSLContext dsl, int writerBackendPid)
throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java
index 105b642c97..e9094b951a 100644
--- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java
@@ -284,6 +284,74 @@ void originalCreatorRecoveryUsesAnIndependentReadCommittedTransaction() {
verify(repository).recoverSourceRead(scope);
}
+ @Test
+ void expiredPreliminaryRecoveryBoundsWorkAndUsesOneOwnerTransactionPerCandidate() {
+ var selected = selected();
+ var first =
+ new SelectedOwnerIntakeSourceReadScope(
+ DraftCommitBinding.Owner.ENTITY_MANAGEMENT,
+ "test",
+ UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"),
+ UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"),
+ selected.requestId(),
+ UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"),
+ selected);
+ var second =
+ new SelectedOwnerIntakeSourceReadScope(
+ DraftCommitBinding.Owner.AUTOMATION_SCRIPTING,
+ "test",
+ UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"),
+ UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"),
+ selected.requestId(),
+ UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"),
+ selected);
+ when(transactions.getTransaction(any(TransactionDefinition.class)))
+ .thenReturn(
+ new SimpleTransactionStatus(),
+ new SimpleTransactionStatus(),
+ new SimpleTransactionStatus());
+ when(repository.findExpiredPreliminarySourceReadScopes(128, "test"))
+ .thenReturn(List.of(first, second));
+ when(repository.abortExpiredPreliminarySourceRead(first, "test")).thenReturn(true);
+ when(repository.abortExpiredPreliminarySourceRead(second, "test")).thenReturn(false);
+
+ assertThat(service.recoverExpiredPreliminarySourceReads(129)).isEqualTo(1);
+
+ var definitions = org.mockito.ArgumentCaptor.forClass(TransactionDefinition.class);
+ verify(transactions, org.mockito.Mockito.times(3)).getTransaction(definitions.capture());
+ assertThat(definitions.getAllValues())
+ .allSatisfy(
+ definition -> {
+ assertThat(definition.getPropagationBehavior())
+ .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
+ assertThat(definition.getIsolationLevel())
+ .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED);
+ assertThat(definition.isReadOnly()).isFalse();
+ });
+ verify(repository).findExpiredPreliminarySourceReadScopes(128, "test");
+ verify(repository).abortExpiredPreliminarySourceRead(first, "test");
+ verify(repository).abortExpiredPreliminarySourceRead(second, "test");
+ verifyNoInteractions(actors, fences);
+ }
+
+ @Test
+ void expiredPreliminaryRecoveryRejectsNonpositivePagesBeforeOpeningTransactions() {
+ assertThatThrownBy(() -> service.recoverExpiredPreliminarySourceReads(0))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> service.recoverExpiredPreliminarySourceReads(-1))
+ .isInstanceOf(IllegalArgumentException.class);
+ verifyNoInteractions(actors, fences, repository, transactions);
+ }
+
+ @Test
+ void expiredPreliminaryRecoveryRejectsAmbientTransactionsBeforeOwnerAccess() {
+ TransactionSynchronizationManager.setActualTransactionActive(true);
+ assertThatThrownBy(() -> service.recoverExpiredPreliminarySourceReads(1))
+ .isInstanceOf(io.grpc.StatusRuntimeException.class)
+ .hasMessageContaining("independent transaction");
+ verifyNoInteractions(actors, fences, repository, transactions);
+ }
+
private static AccountControlUiAuthority.Snapshot snapshot(
List sources) {
var snapshot = mock(AccountControlUiAuthority.Snapshot.class);
diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java
index a9bdc9d9ff..ecb34004d9 100644
--- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java
+++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java
@@ -13,6 +13,7 @@
import java.util.Base64;
import java.util.Collection;
import java.util.List;
+import java.util.Objects;
import java.util.UUID;
import net.firedevops.firemud.accountservice.authordraft.AccountDraftTerminalReconciliationService;
import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement;
@@ -109,7 +110,38 @@ public AccountControlUiOriginalOrderFixture(
Clock actorClock,
String migrationTarget)
throws Exception {
+ this(
+ jdbcUrl,
+ username,
+ password,
+ redisHost,
+ redisPort,
+ temporary,
+ gameDesignTenant,
+ actorClock,
+ migrationTarget,
+ Clock.systemUTC());
+ }
+
+ /**
+ * Test-only owner fixture with a separately injectable issuance clock; actor validation remains
+ * on its independently supplied clock.
+ */
+ public AccountControlUiOriginalOrderFixture(
+ String jdbcUrl,
+ String username,
+ String password,
+ String redisHost,
+ int redisPort,
+ Path temporary,
+ UUID gameDesignTenant,
+ Clock actorClock,
+ String migrationTarget,
+ Clock serviceClock)
+ throws Exception {
this.temporary = temporary;
+ Objects.requireNonNull(actorClock, "actorClock");
+ Objects.requireNonNull(serviceClock, "serviceClock");
f =
new AccountControlUiOwnerSourcesFixture(
jdbcUrl, username, password, temporary, false, gameDesignTenant, migrationTarget);
@@ -199,7 +231,7 @@ public AccountControlUiOriginalOrderFixture(
coordination,
actors,
f.manager,
- Clock.systemUTC(),
+ serviceClock,
300_000L,
AccountControlUiOwnerSourcesFixture.CALLER);
}
From cda9f4b0bb33265edaf3f0b32c348984472b1d14 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Sun, 18 Oct 2026 22:50:58 +1300
Subject: [PATCH 31/55] Align recovery fixture signer evidence with original
issuance clock
---
...wnerIntakeSourceReservationRepository.java | 7 +++----
...edOwnerIntakeSourceReservationService.java | 15 +++++++-------
...eAuthorizationPostgresIntegrationTest.java | 20 +++++++------------
.../AccountControlUiOriginalOrderFixture.java | 2 +-
.../AccountControlUiSignerFixture.java | 14 ++++++++++---
5 files changed, 29 insertions(+), 29 deletions(-)
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java
index 8f803ebb54..aa8cffa7f7 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java
@@ -212,8 +212,8 @@ Recovery abortSourceRead(SelectedOwnerIntakeSourceReadScope scope) {
}
/**
- * Finds a bounded page of exact, expired, unfinalized reservations for one Account namespace.
- * The scope and complete retained source vector are validated before a candidate is returned.
+ * Finds a bounded page of exact, expired, unfinalized reservations for one Account namespace. The
+ * scope and complete retained source vector are validated before a candidate is returned.
*/
List findExpiredPreliminarySourceReadScopes(
int limit, String namespace) {
@@ -253,8 +253,7 @@ List findExpiredPreliminarySourceReadScopes(
List scopes = new ArrayList<>(rows.size());
for (Record row : rows) {
var scope =
- SelectedOwnerIntakeSourceReadScope.fromStored(
- row.get("scope_bytes", byte[].class));
+ SelectedOwnerIntakeSourceReadScope.fromStored(row.get("scope_bytes", byte[].class));
if (!namespace.equals(scope.targetNamespace())) {
throw new IllegalArgumentException("Expired reservation belongs to another namespace");
}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java
index 0cc293755d..75761abd36 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java
@@ -138,17 +138,16 @@ public AccountSelectedOwnerIntakeSourceReservationRepository.Recovery abortSourc
}
/**
- * Performs one bounded Account-internal reconciliation page before any receiver is registered.
- * It is not a transport or scheduled job: the caller owns invocation and readiness policy.
- * Each candidate is rechecked and, if still eligible, durably aborted in its own independent
+ * Performs one bounded Account-internal reconciliation page before any receiver is registered. It
+ * is not a transport or scheduled job: the caller owns invocation and readiness policy. Each
+ * candidate is rechecked and, if still eligible, durably aborted in its own independent
* READ_COMMITTED owner transaction. Finalized and concurrently changed candidates are skipped.
*
* @return abort rows committed by this page; this is not a global completion signal
*/
public int recoverExpiredPreliminarySourceReads(int maximumCandidates) {
if (maximumCandidates <= 0) {
- throw new IllegalArgumentException(
- "Expired preliminary recovery batch must be positive");
+ throw new IllegalArgumentException("Expired preliminary recovery batch must be positive");
}
requireNoAmbientTransaction();
int boundedCandidates =
@@ -167,9 +166,9 @@ public int recoverExpiredPreliminarySourceReads(int maximumCandidates) {
int aborted = 0;
for (SelectedOwnerIntakeSourceReadScope scope : candidates) {
if (Objects.requireNonNull(
- ownerTransaction.execute(
- ignored -> repository.abortExpiredPreliminarySourceRead(scope, namespace)),
- "Expired source-read recovery returned no result")) {
+ ownerTransaction.execute(
+ ignored -> repository.abortExpiredPreliminarySourceRead(scope, namespace)),
+ "Expired source-read recovery returned no result")) {
aborted++;
}
}
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
index a2d0762aa7..b595def889 100644
--- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
@@ -394,7 +394,9 @@ void expiredRecoveryUsesDatabaseCutoffAndPreservesFinalizedOwnerUntilExactSettle
f.fences.requireSelectedOwnerIntakeAdmission(
current.source().sources(), selected));
finalizationBackendPid.set(
- f.dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class));
+ f.dsl
+ .fetchSingle("SELECT pg_backend_pid()")
+ .get(0, Integer.class));
authorizationInserted.countDown();
awaitFinalizationCommit(allowFinalizationCommit);
return binding;
@@ -480,15 +482,9 @@ void expiredRecoveryUsesDatabaseCutoffAndPreservesFinalizedOwnerUntilExactSettle
var settlement = f.tx(() -> repository.settleEntityCommittedEmpty(terminal));
assertThat(
f.tx(
- () ->
- repository
- .findSettlement(alreadyFinalized)
- .orElseThrow()
- .canonicalBytes()))
+ () -> repository.findSettlement(alreadyFinalized).orElseThrow().canonicalBytes()))
.isEqualTo(settlement.canonicalBytes());
- assertThat(
- f.tx(
- () -> repository.settleEntityCommittedEmpty(terminal).canonicalBytes()))
+ assertThat(f.tx(() -> repository.settleEntityCommittedEmpty(terminal).canonicalBytes()))
.isEqualTo(settlement.canonicalBytes());
assertThat(sourceReadPending(f.dsl, alreadyFinalized.operationId())).isFalse();
}
@@ -2404,15 +2400,13 @@ private static void awaitLatch(CountDownLatch latch) {
}
private static boolean sourceReadPending(DSLContext dsl, UUID operationId) {
- return dsl
- .fetchSingle(
+ return dsl.fetchSingle(
"SELECT account_selected_owner_intake_source_read_is_pending(?)", operationId)
.get(0, Boolean.class);
}
private static boolean issuerExpiryReached(DSLContext dsl, UUID issuanceOperationId) {
- return dsl
- .fetchSingle(
+ return dsl.fetchSingle(
"SELECT extract(epoch FROM clock_timestamp()) >= expires_at_epoch_second"
+ " FROM account_control_ui_issuance_operations WHERE operation_id = ?",
issuanceOperationId)
diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java
index ecb34004d9..e0ce00232d 100644
--- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java
+++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java
@@ -145,7 +145,7 @@ public AccountControlUiOriginalOrderFixture(
f =
new AccountControlUiOwnerSourcesFixture(
jdbcUrl, username, password, temporary, false, gameDesignTenant, migrationTarget);
- var lifecycle = new AccountControlUiSignerFixture(f, temporary);
+ var lifecycle = new AccountControlUiSignerFixture(f, temporary, serviceClock);
lifecycle.commit();
var originalSigner = f.tx(lifecycle.signer::captureCurrent);
assertThat(f.tx(() -> lifecycle.signer.requireOriginal(originalSigner.receipt())).receipt())
diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java
index d296be3853..d4f75eb1e3 100644
--- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java
+++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java
@@ -24,6 +24,7 @@
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
@@ -113,10 +114,17 @@ final class AccountControlUiSignerFixture {
final AccountJwtSignerBootstrapCoordinator coordinator;
final AccountJwtSignerMaterializationService materializer;
final AccountControlUiSignerOwner signer;
+ private final Clock clock;
AccountControlUiSignerFixture(AccountControlUiOwnerSourcesFixture fixture, Path root)
throws Exception {
+ this(fixture, root, Clock.systemUTC());
+ }
+
+ AccountControlUiSignerFixture(
+ AccountControlUiOwnerSourcesFixture fixture, Path root, Clock clock) throws Exception {
f = fixture;
+ this.clock = Objects.requireNonNull(clock, "clock");
privateRoot = Files.createDirectories(root.resolve("private"));
publicRoot = Files.createDirectories(root.resolve("public"));
desired = new AccountJwtSignerDesiredStateRepository(f.dsl);
@@ -344,7 +352,7 @@ void commit() throws Exception {
new AccountJwtReadinessProbeService(
readiness,
f.transactions,
- Clock.systemUTC(),
+ clock,
privateRoot,
Path.of("pending.key"),
publicRoot,
@@ -480,8 +488,8 @@ public void onCompleted() {
private record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {}
- private static Instant now() {
- return Instant.ofEpochSecond(Instant.now().getEpochSecond());
+ private Instant now() {
+ return Instant.ofEpochSecond(clock.instant().getEpochSecond());
}
private static TrustFence trust() {
From 96e3e56c5976a560e9f0567d912bfc3e608242f4 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Sun, 18 Oct 2026 22:54:18 +1300
Subject: [PATCH 32/55] Use the original issuance clock for fixture recovery
envelope custody
---
.../service/session/AccountControlUiOriginalOrderFixture.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java
index e0ce00232d..d7f60deb97 100644
--- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java
+++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java
@@ -227,7 +227,7 @@ public AccountControlUiOriginalOrderFixture(
f.fences,
lifecycle.signer,
new AccountControlUiResponseCryptography(
- new AccountControlUiKeyring(temporary.resolve("custody")), Clock.systemUTC()),
+ new AccountControlUiKeyring(temporary.resolve("custody")), serviceClock),
coordination,
actors,
f.manager,
From 7ff2e65bc7fd1bd7d97f9a7034dfd65a39f8f381 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Sun, 18 Oct 2026 22:56:00 +1300
Subject: [PATCH 33/55] Use a PostgreSQL-safe alias for finalized reservation
lookup
---
...AccountSelectedOwnerIntakeSourceReservationRepository.java | 4 ++--
.../service/session/AccountControlUiSignerFixture.java | 4 ++--
2 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java
index aa8cffa7f7..595b4b8fa3 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java
@@ -237,14 +237,14 @@ List findExpiredPreliminarySourceReadScopes(
+ "reservation.scope_bytes, owner_part.next_position) namespace_part"
+ " LEFT JOIN "
+ AUTHORIZATIONS
- + " authorization ON authorization.operation_id = reservation.operation_id"
+ + " finalized_reservation ON finalized_reservation.operation_id = reservation.operation_id"
+ " LEFT JOIN "
+ ABORTS
+ " aborted ON aborted.operation_id = reservation.operation_id"
+ " WHERE convert_from(namespace_part.frame_value, 'UTF8') = ?"
+ " AND issuer.status = 'COMMITTED'"
+ " AND extract(epoch FROM clock_timestamp()) >= issuer.expires_at_epoch_second"
- + " AND authorization.operation_id IS NULL"
+ + " AND finalized_reservation.operation_id IS NULL"
+ " AND aborted.operation_id IS NULL"
+ " ORDER BY issuer.expires_at_epoch_second, reservation.operation_id"
+ " LIMIT ?",
diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java
index d4f75eb1e3..b0961a0ca1 100644
--- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java
+++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java
@@ -121,8 +121,8 @@ final class AccountControlUiSignerFixture {
this(fixture, root, Clock.systemUTC());
}
- AccountControlUiSignerFixture(
- AccountControlUiOwnerSourcesFixture fixture, Path root, Clock clock) throws Exception {
+ AccountControlUiSignerFixture(AccountControlUiOwnerSourcesFixture fixture, Path root, Clock clock)
+ throws Exception {
f = fixture;
this.clock = Objects.requireNonNull(clock, "clock");
privateRoot = Files.createDirectories(root.resolve("private"));
From 6984e0ace8a8cde5842b9a6394bdabc1cfd895c2 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Sun, 18 Oct 2026 23:00:09 +1300
Subject: [PATCH 34/55] Record bounded preliminary recovery proof and runtime
gaps
---
.../implementation-tracking/player-access-and-session.md | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md
index 47745115e5..65af32f94f 100644
--- a/design/project-management/implementation-tracking/player-access-and-session.md
+++ b/design/project-management/implementation-tracking/player-access-and-session.md
@@ -10,7 +10,9 @@ This is a non-normative implementation tracker for player access and session. Ca
This preparation is owned by [AA-1.3](#capability-status), which remains `partial` / `drift-found`. Its production and focused proof anchors are recorded in that row.
-Preliminary source reservations remain held until exact explicit abort, including after the creator credential expires; expiry or a lost Game Design response does not establish safe settlement. Exact original recovery and abort remain available after credential expiry, but an abandoned reservation has no Account-owned autonomous recovery path here. Before registering these owners, the selected-recipient finalization and terminal-settlement stage (#3251) must prove Account-owned recovery for abandoned preliminary reservations and exact terminal release for finalized owners. Preserve the complete source fence until sufficient owner evidence exists; do not release it through a guessed timeout. This is an activation blocker, with reconsideration at that lifecycle stage; current source preparation remains unregistered.
+Preliminary source reservations remain held until exact explicit abort or the prepared Account-owned expired-preliminary recovery operation commits that same immutable abort. The internal recovery entry accepts a bounded page of at most 128 candidates from its configured namespace, selects only original COMMITTED issuances past their actual PostgreSQL expiry, and revalidates exact retained scope and issuer evidence under the canonical source-lock then reservation-lock order. Each candidate commits independently; the returned count is not global completion or readiness. Finalized owners are excluded and remain protected until exact authenticated terminal settlement. Lost responses, unknown state or a guessed timeout do not authorize release. The operation has no transport registration, scheduler or invocation policy; those remain activation prerequisites.
+
+The focused recovery preparation passes eight unit cases at `cda9f4b0bb33265edaf3f0b32c348984472b1d14` and the one new physical PostgreSQL expiry/race case at `7ff2e65bc7fd1bd7d97f9a7034dfd65a39f8f381`, with zero failures, errors or skips in those separate scopes. Eight other native authorization/settlement cases passed in the earlier nine-case run, whose aggregate remains failed; this is not a new passing nine-case aggregate. Affected static and formatting checks pass after the fixture clock and query-alias corrections. The new case observes the real database cutoff and actual source-lock blocking: an in-flight finalization cannot commit after original expiry, abandoned preliminary reservations abort once, and an already committed finalization remains pending until exact Entity terminal settlement. Signer, issuer, source and terminal inputs remain controlled fixtures; no genuine authority, autonomous runtime recovery or activation is established. Prior failed selector, fixture and SQL attempts retain their original evidence.
R31 freshly passes all eight Account final-authorization, exact Entity/Automation terminal-storage and retained-upgrade cases with zero skips. Account's 1,500 unit cases pass with four existing skips, Common's 811 units pass with zero skips, and World's 593 units retain the unchanged R30 pass. A real Java writer-exclusion omission exposed by R30 is corrected: the shared settlement check now includes the existing pending selected-owner reservation predicate, matching the retained SQL guard. The shared synthetic terminal codec fixture is carried at its first consumer. R35 freshly passes the successor disclosure composition at the actual V1008–V1010 repository frontier, including physical source-writer exclusion until exact reservation abort; its static, formatting and documentation checks pass. The earlier V1007-only source proof retains separate R33 attribution. Full-native PostgreSQL/Redis limits remain; controlled source, terminal and PKI inputs establish no genuine authority.
From 1b8c912229c841a5df7304975892319ddcb1b827 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Mon, 19 Oct 2026 00:08:47 +1300
Subject: [PATCH 35/55] docs(account): preserve receiving owner qualification
status
---
.../microservices/account-service/runtime-and-data.md | 2 +-
.../implementation-tracking/player-access-and-session.md | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md
index 7a3272721b..20cc55a161 100644
--- a/design/architecture/microservices/account-service/runtime-and-data.md
+++ b/design/architecture/microservices/account-service/runtime-and-data.md
@@ -354,4 +354,4 @@ Forward [V1004.2](../../../../services/account-service/src/main/resources/db/mig
Forward [V1004.3](../../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql) requires all four Base64 carriers in the Account activation request to match the canonical encoding of their decoded tuple, projection, launch-read, and PREPARING bytes before protection acquisition. This prevents accepted whitespace spellings from being retained in an immutable request that later settlement must compare. It changes only the existing acquisition guard and does not backfill rows, authenticate World, or activate the source path. Current proof and limits are recorded in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage).
-V1003 preserves canonical predecessor SQL and retained owner rows; it never backfills protection, adopts missing historical evidence, fabricates owner proof or registers runtime authority. Its scoped PostgreSQL fixtures explicitly stipulate upstream capture/redemption/World rows with upstream producer triggers disabled while leaving the protection and source-writer guards under test enabled. Such execution establishes storage integrity, exclusion and retained-history behavior only. Genuine current-owner acquisition, authenticated terminal reads/settlement, continuously protected admission and activation remain unproved. Forward [Account V1007](../../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql) now provides preliminary selected-owner reservation and source-writer storage; finalized owner authorization and recovery, exact terminal settlement, full qualification and registration remain unproved.
+V1003 preserves canonical predecessor SQL and retained owner rows; it never backfills protection, adopts missing historical evidence, fabricates owner proof or registers runtime authority. Its scoped PostgreSQL fixtures explicitly stipulate upstream capture/redemption/World rows with upstream producer triggers disabled while leaving the protection and source-writer guards under test enabled. Such execution establishes storage integrity, exclusion and retained-history behavior only. Genuine current-owner acquisition, authenticated terminal reads/settlement, continuously protected admission and activation remain unproved. Forward [Account V1007](../../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql) now provides preliminary selected-owner reservation and source-writer storage; the receiving finalized-authorization, exact-settlement and bounded recovery owners are source-prepared, with focused proof and remaining qualification and registration gaps recorded in the [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation).
diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md
index 0aec41e552..7af8c72fc8 100644
--- a/design/project-management/implementation-tracking/player-access-and-session.md
+++ b/design/project-management/implementation-tracking/player-access-and-session.md
@@ -70,7 +70,7 @@ Focused proof is split by unchanged source attribution: twelve shared validator
### Original StartSession source-protection storage
-The bounded V1003 receiving cut, hardened by forward V1004, adds passive Account admission and activation protection storage and immutable terminal-settlement integrity, while preserving every canonical parent migration and original owner evidence. Its existing source-writer hooks retain World participation and other published owner guards. Forward [Account V1007 preliminary selected-owner reservation storage and source-writer hooks](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql) are now received for Entity and Automation participation. Finalized owner authorization and recovery, exact terminal settlement, full qualification, and registration remain separate unfinished dependencies. AA-1.3 stays `partial` / `drift-found`; all genuine Gameplay handoffs remain open and broader Unit 1B remains paused.
+The bounded V1003 receiving cut, hardened by forward V1004, adds passive Account admission and activation protection storage and immutable terminal-settlement integrity, while preserving every canonical parent migration and original owner evidence. Its existing source-writer hooks retain World participation and other published owner guards. Forward [Account V1007 preliminary selected-owner reservation storage and source-writer hooks](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql) are now received for Entity and Automation participation. The receiving finalized-authorization, exact-settlement and bounded recovery owners are now source-prepared; their focused proof and remaining qualification and registration gaps are recorded in [Selected recipient source intake preparation](#selected-recipient-source-intake-preparation). AA-1.3 stays `partial` / `drift-found`; all genuine Gameplay handoffs remain open and broader Unit 1B remains paused.
The pre-review preparation on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca159c40c` passed all 15 focused Account PostgreSQL cases with zero failures/errors/skips: 13 admission and two activation cases, including the default-location fresh 113-artifact manifest and unchanged actual 112-artifact parent upgrade. jOOQ generation, compilation, formatting, Checkstyle, integration SpotBugs and documentation checks pass. The broader local 236-case Account integration run had two unavailable endpoint fixtures and remains a failed local gate; identical Account/Common/proto/build inputs at published `a1a6d13f0f4953261e1fdd7154f50f83e17be84e` pass the own Account source-CI artifact 11822625688 with 240 integration cases (zero failures, errors or skips) and 1,295 unit cases (zero failures or errors, four existing filesystem skips). Fresh rebuilt images also pass both unchanged legacy LOGIN/PLAY/LOOK transport baselines. These results qualify the bounded protection storage and existing behavior only. Those pre-review results did not exercise the activation acquisition guards. The corrected [admission storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java) and [activation storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) stipulate upstream data while leaving the protection/source-writer guards enabled; they establish no genuine owner production, authenticated terminal settlement, continuous canonical admission, actor placement or region delivery. Canonical obligations remain in [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), with local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#original-startsession-source-protection-storage).
From 89b0f39227e77c4f05b8e35558ef70f49c8495a0 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Mon, 19 Oct 2026 09:48:57 +1300
Subject: [PATCH 36/55] fix: recover revoked preliminary reservations and
preserve publication failure semantics
---
design/project-management/ai-observations.md | 2 +-
...wnerIntakeSourceReservationRepository.java | 31 +++-
...edOwnerIntakeSourceReservationService.java | 25 ++-
...eAuthorizationPostgresIntegrationTest.java | 158 +++++++++++++++++-
...IntakeSourceReservationRepositoryTest.java | 55 ++++++
...nerIntakeSourceReservationServiceTest.java | 65 +++++++
...ctedDraftPublicationDigestReadService.java | 10 +-
...nerPublicationPostgresIntegrationTest.java | 12 +-
...rsionCanonicalIdentityIntegrationTest.java | 3 +-
.../publication/GameLogicClientTest.java | 21 +++
.../SelectedDraftControlPlaneDigestTest.java | 18 +-
...DraftPublicationDigestReadServiceTest.java | 44 +++++
.../impl/PublishGateServiceImplTest.java | 3 +-
.../service/impl/GameLogicGrpcService.java | 23 +--
.../impl/GameLogicGrpcServiceTest.java | 50 ++++++
15 files changed, 465 insertions(+), 55 deletions(-)
diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md
index f8abdd81c4..14fe667932 100644
--- a/design/project-management/ai-observations.md
+++ b/design/project-management/ai-observations.md
@@ -145,7 +145,7 @@ Entry format:
- Observation: The global-ID update rewrote a retained row's tenant before returning it under the supplied tenant; tenant-filtered readback did not protect the original row. The native counterexample changed the complete row and `xmin`, while the restored exact tenant predicate preserves both owner rows and their versions.
- Expected pattern: Test controlled pre-phase rows as well as later guarded owners. Keep the create-only ID refusal before mapper/repository access, and separate this owner-local SQL proof from authenticated creator or hosted-content readiness.
-- `2026-10-16`: Check existing successor repairs before reworking a failed fixture. While fixing the three #3251 publication transaction failures, two focused local gates failed before the worker noticed that the already-reconciled #2967 tree contained the complete selected-full schema-4 fixture repair. The first attempts corrected stale collector stubs but missed the dependent fixture profile. Compare the bounded failing test and its called helpers against known receiving successors before changing or rerunning it; reuse the complete canonical repair without removing assertions. The exact four-path backport at `4265a81f008d0dbd343cd9adf6413bd3ac5c8904` then passed66 unit and10 native cases. The failed attempts retain their original outcomes; this lesson does not establish a general infrastructure cause.
+- `2026-10-16`: Check existing successor repairs before reworking a failed fixture. While fixing the three #3251 publication transaction failures, two focused local gates failed before the worker noticed that the already-reconciled #2967 tree contained the complete selected-full schema-4 fixture repair. The first attempts corrected stale collector stubs but missed the dependent fixture profile. Compare the bounded failing test and its called helpers against known receiving successors before changing or rerunning it; reuse the complete canonical repair without removing assertions. The exact four-path backport at `4265a81f008d0dbd343cd9adf6413bd3ac5c8904` then passed 66 unit and 10 native cases. The failed attempts retain their original outcomes; this lesson does not establish a general infrastructure cause.
- `2026-10-16`: Derive focused Gradle selectors from declared Java packages
- Context: a Gameplay capture proof supplied `integration.net...` as the selector, and Gradle executed no tests before failing discovery.
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java
index b58c269153..3d2139ca0f 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java
@@ -25,6 +25,8 @@
import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
import org.jooq.DSLContext;
import org.jooq.Record;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
@@ -34,6 +36,9 @@
public final class AccountSelectedOwnerIntakeSourceReservationRepository {
public static final int MAX_EXPIRED_PRELIMINARY_RECOVERY_BATCH_SIZE = 128;
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(AccountSelectedOwnerIntakeSourceReservationRepository.class);
+
private static final String RESERVATIONS =
"account_selected_owner_intake_source_read_reservations";
private static final String SOURCES = "account_selected_owner_intake_source_read_sources";
@@ -243,7 +248,7 @@ List findExpiredPreliminarySourceReadScopes(
+ ABORTS
+ " aborted ON aborted.operation_id = reservation.operation_id"
+ " WHERE convert_from(namespace_part.frame_value, 'UTF8') = ?"
- + " AND issuer.status = 'COMMITTED'"
+ + " AND issuer.status IN ('COMMITTED', 'REVOKING', 'REVOKED')"
+ " AND extract(epoch FROM clock_timestamp()) >= issuer.expires_at_epoch_second"
+ " AND finalized_reservation.operation_id IS NULL"
+ " AND aborted.operation_id IS NULL"
@@ -252,14 +257,24 @@ List findExpiredPreliminarySourceReadScopes(
namespace,
limit);
List scopes = new ArrayList<>(rows.size());
+ int rowNumber = 0;
for (Record row : rows) {
- var scope =
- SelectedOwnerIntakeSourceReadScope.fromStored(row.get("scope_bytes", byte[].class));
- if (!namespace.equals(scope.targetNamespace())) {
- throw new IllegalArgumentException("Expired reservation belongs to another namespace");
+ rowNumber++;
+ try {
+ var scope =
+ SelectedOwnerIntakeSourceReadScope.fromStored(row.get("scope_bytes", byte[].class));
+ if (!namespace.equals(scope.targetNamespace())) {
+ throw new IllegalArgumentException("Expired reservation belongs to another namespace");
+ }
+ requireReservation(row, scope);
+ scopes.add(scope);
+ } catch (IllegalArgumentException | IllegalStateException invalidRow) {
+ LOGGER.warn(
+ "Skipped invalid expired preliminary source-read row {}/{} (failureType={})",
+ rowNumber,
+ rows.size(),
+ invalidRow.getClass().getSimpleName());
}
- requireReservation(row, scope);
- scopes.add(scope);
}
return List.copyOf(scopes);
}
@@ -286,7 +301,7 @@ boolean abortExpiredPreliminarySourceRead(
UUID issuanceOperationId = row.get("issuance_operation_id", UUID.class);
if (dsl.fetchOne(
"SELECT operation_id FROM account_control_ui_issuance_operations"
- + " WHERE operation_id = ? AND status = 'COMMITTED'"
+ + " WHERE operation_id = ? AND status IN ('COMMITTED', 'REVOKING', 'REVOKED')"
+ " AND extract(epoch FROM clock_timestamp()) >= expires_at_epoch_second",
issuanceOperationId)
== null) {
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java
index 75761abd36..69664285ef 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java
@@ -13,6 +13,8 @@
import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner;
import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
import net.firedevops.firemud.common.security.SessionContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionSynchronizationManager;
@@ -20,6 +22,9 @@
/** Unregistered preliminary source-read producer; it grants no owner retention authority. */
public final class AccountSelectedOwnerIntakeSourceReservationService {
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(AccountSelectedOwnerIntakeSourceReservationService.class);
+
private final AccountControlUiActorService actors;
private final DraftAuthorizationFenceRepository fences;
private final AccountSelectedOwnerIntakeSourceReservationRepository repository;
@@ -164,12 +169,22 @@ public int recoverExpiredPreliminarySourceReads(int maximumCandidates) {
boundedCandidates, namespace)),
"Expired source-read candidate lookup returned no result");
int aborted = 0;
+ int candidateNumber = 0;
for (SelectedOwnerIntakeSourceReadScope scope : candidates) {
- if (Objects.requireNonNull(
- ownerTransaction.execute(
- ignored -> repository.abortExpiredPreliminarySourceRead(scope, namespace)),
- "Expired source-read recovery returned no result")) {
- aborted++;
+ candidateNumber++;
+ try {
+ if (Objects.requireNonNull(
+ ownerTransaction.execute(
+ ignored -> repository.abortExpiredPreliminarySourceRead(scope, namespace)),
+ "Expired source-read recovery returned no result")) {
+ aborted++;
+ }
+ } catch (RuntimeException candidateFailure) {
+ LOGGER.warn(
+ "Skipped failed expired preliminary source-read candidate {}/{} (failureType={})",
+ candidateNumber,
+ candidates.size(),
+ candidateFailure.getClass().getSimpleName());
}
}
return aborted;
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
index b595def889..cc36159ced 100644
--- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
@@ -9,7 +9,9 @@
import java.nio.file.Path;
import java.time.Clock;
import java.time.Duration;
+import java.time.Instant;
import java.time.OffsetDateTime;
+import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
@@ -22,6 +24,7 @@
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority;
import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository;
import net.firedevops.firemud.accountservice.service.session.AccountSelectedOwnerIntakeSourceReservationRepository.State;
@@ -84,6 +87,8 @@
import org.jooq.DSLContext;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.Network;
import org.testcontainers.containers.PostgreSQLContainer;
@@ -324,7 +329,7 @@ void expiredRecoveryUsesDatabaseCutoffAndPreservesFinalizedOwnerUntilExactSettle
UUID.randomUUID(),
Clock.systemUTC(),
null,
- Clock.offset(Clock.systemUTC(), Duration.ofSeconds(-290)))) {
+ Clock.offset(Clock.systemUTC(), Duration.ofSeconds(-270)))) {
var issued = fixture.issueCreator();
var f = issued.sources();
var selected = selectedForSettlement(f.tenant);
@@ -490,6 +495,126 @@ void expiredRecoveryUsesDatabaseCutoffAndPreservesFinalizedOwnerUntilExactSettle
}
}
+ @ParameterizedTest
+ @ValueSource(strings = {"REVOKING", "REVOKED"})
+ void expiredPreliminaryRecoveryAcceptsRetainedExpiredIssuersAndKeepsFinalAuthorization(
+ String issuerStatus) throws Exception {
+ var serviceClock = new MutableOffsetClock(Clock.systemUTC(), -270L);
+ try (var fixture =
+ new AccountControlUiOriginalOrderFixture(
+ postgres.getJdbcUrl(),
+ postgres.getUsername(),
+ postgres.getPassword(),
+ redis.getHost(),
+ redis.getMappedPort(6379),
+ temporary,
+ UUID.randomUUID(),
+ Clock.systemUTC(),
+ null,
+ serviceClock)) {
+ var issued = fixture.issueCreator();
+ var f = issued.sources();
+ var selected = selectedForSettlement(f.tenant);
+ settleOriginal(issued, selected);
+ var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl);
+ var reservations =
+ new AccountSelectedOwnerIntakeSourceReservationService(
+ issued.actors(), f.fences, repository, f.manager, "test");
+ var preliminary =
+ asGameDesign(
+ () ->
+ reservations.reserveSourceRead(
+ issued.compact(),
+ UUID.randomUUID(),
+ Owner.AUTOMATION_SCRIPTING,
+ selected,
+ issued.environment()));
+ var finalized =
+ finalizeEntityBinding(issued, reservations, repository, selected, issuerStatus);
+ var finalizedScope = finalized.content().scope();
+ UUID issuanceOperationId =
+ f.dsl
+ .fetchSingle(
+ "SELECT issuance_operation_id FROM account_selected_owner_intake_source_read_reservations"
+ + " WHERE operation_id = ?",
+ preliminary.operationId())
+ .get("issuance_operation_id", UUID.class);
+
+ assertThat(issuerExpiryReached(f.dsl, issuanceOperationId)).isFalse();
+ awaitIssuerExpiry(f.dsl, issuanceOperationId);
+ var issuanceRepository = new AccountControlUiIssuanceRepository(f.dsl);
+ if ("REVOKING".equals(issuerStatus)) {
+ var original =
+ f.tx(
+ () ->
+ issuanceRepository.findToken(
+ AccountControlUiIssuanceRepository.hash(
+ issued.compact().getBytes(StandardCharsets.US_ASCII))));
+ assertThat(original).isNotNull();
+ var revoking = f.tx(() -> issuanceRepository.beginRecoveryFailure(original));
+ assertThat(revoking.status).isEqualTo("REVOKING");
+ } else {
+ serviceClock.advance(Duration.ofSeconds(31));
+ assertThatThrownBy(fixture::issueCreator).isInstanceOf(IllegalStateException.class);
+ }
+ assertThat(
+ f.dsl
+ .fetchSingle(
+ "SELECT status FROM account_control_ui_issuance_operations WHERE operation_id = ?",
+ issuanceOperationId)
+ .get("status", String.class))
+ .isEqualTo(issuerStatus);
+
+ assertThat(reservations.recoverExpiredPreliminarySourceReads(128)).isEqualTo(1);
+
+ assertThat(f.tx(() -> repository.recoverSourceRead(preliminary).state()))
+ .isEqualTo(State.ABORTED);
+ assertThat(f.tx(() -> repository.recoverSourceRead(finalizedScope).state()))
+ .isEqualTo(State.FINALIZED);
+ assertThat(sourceReadPending(f.dsl, preliminary.operationId())).isFalse();
+ assertThat(sourceReadPending(f.dsl, finalizedScope.operationId())).isTrue();
+ assertThat(
+ f.dsl
+ .fetchSingle(
+ "SELECT scope_bytes FROM account_selected_owner_intake_source_read_reservations"
+ + " WHERE operation_id = ?",
+ preliminary.operationId())
+ .get("scope_bytes", byte[].class))
+ .isEqualTo(preliminary.canonicalBytes());
+ assertThat(
+ f.dsl
+ .fetchSingle(
+ "SELECT binding_bytes FROM account_selected_owner_intake_authorizations"
+ + " WHERE operation_id = ?",
+ finalizedScope.operationId())
+ .get("binding_bytes", byte[].class))
+ .isEqualTo(finalized.canonicalBytes());
+ assertThat(
+ f.dsl
+ .fetchSingle(
+ "SELECT count(*) FROM account_selected_owner_intake_source_read_aborts"
+ + " WHERE operation_id = ?",
+ preliminary.operationId())
+ .get(0, Long.class))
+ .isEqualTo(1L);
+ assertThat(
+ f.dsl
+ .fetchSingle(
+ "SELECT count(*) FROM account_selected_owner_intake_source_read_aborts"
+ + " WHERE operation_id = ?",
+ finalizedScope.operationId())
+ .get(0, Long.class))
+ .isZero();
+
+ var sourceChange =
+ new DraftAuthorizationFenceRepository.SourceChange(
+ UUID.randomUUID(), finalized.sources(), new byte[] {2});
+ assertThat(f.tx(() -> f.fences.requestSourceChange(sourceChange))).isFalse();
+ assertThat(f.tx(() -> f.fences.sourceMutationPermitted(sourceChange))).isFalse();
+ assertThat(reservations.recoverExpiredPreliminarySourceReads(128)).isZero();
+ }
+ }
+
@Test
void commitsExactAutomationEmptySettlementAndReleasesOnlyThatOperation() throws Exception {
try (var fixture =
@@ -2405,6 +2530,35 @@ private static boolean sourceReadPending(DSLContext dsl, UUID operationId) {
.get(0, Boolean.class);
}
+ private static final class MutableOffsetClock extends Clock {
+ private final Clock base;
+ private final AtomicLong offsetSeconds;
+
+ MutableOffsetClock(Clock base, long offsetSeconds) {
+ this.base = base;
+ this.offsetSeconds = new AtomicLong(offsetSeconds);
+ }
+
+ @Override
+ public ZoneId getZone() {
+ return base.getZone();
+ }
+
+ @Override
+ public Clock withZone(ZoneId zone) {
+ return new MutableOffsetClock(base.withZone(zone), offsetSeconds.get());
+ }
+
+ @Override
+ public Instant instant() {
+ return base.instant().plusSeconds(offsetSeconds.get());
+ }
+
+ void advance(Duration duration) {
+ offsetSeconds.addAndGet(duration.getSeconds());
+ }
+ }
+
private static boolean issuerExpiryReached(DSLContext dsl, UUID issuanceOperationId) {
return dsl.fetchSingle(
"SELECT extract(epoch FROM clock_timestamp()) >= expires_at_epoch_second"
@@ -2415,7 +2569,7 @@ private static boolean issuerExpiryReached(DSLContext dsl, UUID issuanceOperatio
private static void awaitIssuerExpiry(DSLContext dsl, UUID issuanceOperationId)
throws InterruptedException {
- long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(45);
do {
if (issuerExpiryReached(dsl, issuanceOperationId)) return;
Thread.sleep(10);
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java
index 194de5fc55..b12dd3fa07 100644
--- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java
@@ -1,14 +1,30 @@
package net.firedevops.firemud.accountservice.service.session;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+import java.util.List;
import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.jooq.Result;
+import org.jooq.exception.DataAccessException;
+import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
/** Synthetic transaction-bound repository boundary tests; no PostgreSQL proof is claimed. */
class AccountSelectedOwnerIntakeSourceReservationRepositoryTest {
+ @AfterEach
+ void clearTransactionState() {
+ TransactionSynchronizationManager.clear();
+ }
+
@Test
void everyReservationRecoveryAbortAndCurrentnessReadRequiresAnOwnerTransaction() {
var dsl = mock(DSLContext.class);
@@ -48,4 +64,43 @@ void everyReservationRecoveryAbortAndCurrentnessReadRequiresAnOwnerTransaction()
verifyNoInteractions(dsl);
}
+
+ @Test
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ void expiredRecoverySkipsInvalidRowsAndStillDecodesLaterRows() {
+ var dsl = mock(DSLContext.class);
+ var first = mock(Record.class);
+ var later = mock(Record.class);
+ when(first.get("scope_bytes", byte[].class)).thenReturn(new byte[0]);
+ when(later.get("scope_bytes", byte[].class))
+ .thenThrow(new IllegalStateException("synthetic row failure"));
+ Result rows = mock(Result.class);
+ when(rows.size()).thenReturn(2);
+ when(rows.iterator()).thenReturn(List.of(first, later).iterator());
+ when(dsl.fetch(anyString(), any(Object[].class))).thenReturn(rows);
+ TransactionSynchronizationManager.setActualTransactionActive(true);
+
+ var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(dsl);
+
+ assertThat(repository.findExpiredPreliminarySourceReadScopes(2, "test")).isEmpty();
+
+ verify(first).get("scope_bytes", byte[].class);
+ verify(later).get("scope_bytes", byte[].class);
+ }
+
+ @Test
+ void expiredRecoveryPropagatesLookupFailuresForTheWholeOwnerTransaction() {
+ var dsl = mock(DSLContext.class);
+ when(dsl.fetch(anyString(), any(Object[].class)))
+ .thenThrow(
+ new DataAccessException("synthetic lookup failure") {
+ private static final long serialVersionUID = 1L;
+ });
+ TransactionSynchronizationManager.setActualTransactionActive(true);
+
+ var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(dsl);
+
+ assertThatThrownBy(() -> repository.findExpiredPreliminarySourceReadScopes(2, "test"))
+ .isInstanceOf(DataAccessException.class);
+ }
}
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java
index e9094b951a..078813aad5 100644
--- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java
@@ -7,6 +7,7 @@
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -334,6 +335,58 @@ void expiredPreliminaryRecoveryBoundsWorkAndUsesOneOwnerTransactionPerCandidate(
verifyNoInteractions(actors, fences);
}
+ @Test
+ void expiredPreliminaryRecoveryContinuesAfterFirstAndLaterCandidateFailures() {
+ var selected = selected();
+ var first = recoveryScope(selected, "11111111-1111-4111-8111-111111111111");
+ var successful = recoveryScope(selected, "22222222-2222-4222-8222-222222222222");
+ var later = recoveryScope(selected, "33333333-3333-4333-8333-333333333333");
+ when(transactions.getTransaction(any(TransactionDefinition.class)))
+ .thenReturn(
+ new SimpleTransactionStatus(),
+ new SimpleTransactionStatus(),
+ new SimpleTransactionStatus(),
+ new SimpleTransactionStatus());
+ when(repository.findExpiredPreliminarySourceReadScopes(3, "test"))
+ .thenReturn(List.of(first, successful, later));
+ when(repository.abortExpiredPreliminarySourceRead(first, "test"))
+ .thenThrow(new IllegalStateException("synthetic source payload must not be logged"));
+ when(repository.abortExpiredPreliminarySourceRead(successful, "test")).thenReturn(true);
+ when(repository.abortExpiredPreliminarySourceRead(later, "test"))
+ .thenThrow(new IllegalArgumentException("synthetic credential must not be logged"));
+
+ assertThat(service.recoverExpiredPreliminarySourceReads(3)).isEqualTo(1);
+
+ verify(repository).abortExpiredPreliminarySourceRead(first, "test");
+ verify(repository).abortExpiredPreliminarySourceRead(successful, "test");
+ verify(repository).abortExpiredPreliminarySourceRead(later, "test");
+ verify(transactions, times(4)).getTransaction(any(TransactionDefinition.class));
+ }
+
+ @Test
+ void expiredPreliminaryRecoveryContinuesAndReturnsZeroWhenEveryCandidateFails() {
+ var selected = selected();
+ var first = recoveryScope(selected, "44444444-4444-4444-8444-444444444444");
+ var second = recoveryScope(selected, "55555555-5555-4555-8555-555555555555");
+ when(transactions.getTransaction(any(TransactionDefinition.class)))
+ .thenReturn(
+ new SimpleTransactionStatus(),
+ new SimpleTransactionStatus(),
+ new SimpleTransactionStatus());
+ when(repository.findExpiredPreliminarySourceReadScopes(2, "test"))
+ .thenReturn(List.of(first, second));
+ when(repository.abortExpiredPreliminarySourceRead(first, "test"))
+ .thenThrow(new IllegalStateException("synthetic failure"));
+ when(repository.abortExpiredPreliminarySourceRead(second, "test"))
+ .thenThrow(new IllegalStateException("synthetic failure"));
+
+ assertThat(service.recoverExpiredPreliminarySourceReads(2)).isZero();
+
+ verify(repository).abortExpiredPreliminarySourceRead(first, "test");
+ verify(repository).abortExpiredPreliminarySourceRead(second, "test");
+ verify(transactions, times(3)).getTransaction(any(TransactionDefinition.class));
+ }
+
@Test
void expiredPreliminaryRecoveryRejectsNonpositivePagesBeforeOpeningTransactions() {
assertThatThrownBy(() -> service.recoverExpiredPreliminarySourceReads(0))
@@ -362,6 +415,18 @@ private static AccountControlUiAuthority.Snapshot snapshot(
return snapshot;
}
+ private static SelectedOwnerIntakeSourceReadScope recoveryScope(
+ DraftCommitBinding selected, String operationId) {
+ return new SelectedOwnerIntakeSourceReadScope(
+ DraftCommitBinding.Owner.ENTITY_MANAGEMENT,
+ "test",
+ UUID.fromString(operationId),
+ UUID.randomUUID(),
+ selected.requestId(),
+ UUID.randomUUID(),
+ selected);
+ }
+
private static AccountControlUiIssuanceRepository.Stored stored(UUID actorId, UUID tenantId) {
Record row = mock(Record.class);
var operation = UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd");
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java
index d8826bb96a..532d8f5732 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java
@@ -15,8 +15,12 @@
import net.firedevops.firemud.gamedesign.model.PublishParticipantKey;
import org.jooq.DSLContext;
import org.jooq.exception.DataAccessException;
+import org.springframework.dao.DataAccessResourceFailureException;
+import org.springframework.dao.TransientDataAccessException;
+import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.TransactionSystemException;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionTemplate;
@@ -73,7 +77,11 @@ public ReadResult read(
"Selected publication digest snapshot returned no result");
} catch (StatusRuntimeException failure) {
throw failure;
- } catch (DataAccessException unavailable) {
+ } catch (DataAccessException
+ | TransientDataAccessException
+ | DataAccessResourceFailureException
+ | CannotCreateTransactionException
+ | TransactionSystemException unavailable) {
throw Status.UNAVAILABLE
.withDescription("Selected publication source readback unavailable")
.withCause(unavailable)
diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
index f50e80d7a4..15501975fb 100644
--- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
+++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
@@ -71,6 +71,7 @@
import net.firedevops.firemud.gamedesign.dto.VersionDto;
import net.firedevops.firemud.gamedesign.entity.Game;
import net.firedevops.firemud.gamedesign.entity.Version;
+import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode;
import net.firedevops.firemud.gamedesign.model.VersionLifecycleState;
import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository;
import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt;
@@ -82,6 +83,7 @@
import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository;
import net.firedevops.firemud.gamedesign.repository.VersionRepository;
import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest;
+import net.firedevops.firemud.gamedesign.service.PublishGateFailureException;
import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService;
import net.firedevops.firemud.gamedesign.service.impl.PublishGateServiceImpl;
import net.firedevops.firemud.gamedesign.service.impl.PublishedReleaseBundleServiceImpl;
@@ -486,9 +488,12 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema
validAutomation.abilitySchemaDigest(),
validAutomation.errorCode(),
validAutomation.errorMessage()));
- gate.assertSelectedGatePassed(versionDto, participantDigests);
assertThatThrownBy(() -> gate.assertSelectedGatePassed(versionDto, altered))
- .isInstanceOf(RuntimeException.class);
+ .isInstanceOf(PublishGateFailureException.class)
+ .satisfies(
+ failure ->
+ assertThat(((PublishGateFailureException) failure).failureCode())
+ .isEqualTo(PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA));
var releaseService =
new PublishedReleaseBundleServiceImpl(
@@ -565,7 +570,8 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema
"controlled-generation-input",
altered,
worldOwners.startLocationEvidence())))
- .isInstanceOf(RuntimeException.class);
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Selected-full release requires the exact 4/3/1/6/2");
assertThat(
gds.dsl()
.fetchSingle(
diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java
index 7d64feaf52..2000df083d 100644
--- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java
+++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java
@@ -300,7 +300,8 @@ void databaseRejectsIdentityMutationNilIdentityAndMismatchedSource() {
owner.getId(),
owner.getTenantId(),
"NEW_GAME_ROW"))
- .isInstanceOf(DataAccessException.class);
+ .isInstanceOf(DataAccessException.class)
+ .hasMessageContaining("chk_version_canonical_identity_shape");
assertThatThrownBy(
() ->
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java
index eb7e95bca3..99b580bcaa 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java
@@ -10,6 +10,8 @@
import static org.mockito.Mockito.when;
import io.grpc.ClientInterceptor;
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -115,6 +117,25 @@ void rejectsAValidButDifferentTerminalFromTheImmutableReceipt(@TempDir Path tlsD
assertThat(result.abilitySchemaDigest()).isNull();
}
+ @Test
+ void propagatesUnavailableTransportFailureForRetry(@TempDir Path tlsDirectory)
+ throws IOException {
+ var receipt = SelectedDraftGameLogicReceiptTest.fixture();
+ var publication = publicationBinding(receipt);
+ var clientAndStub = client(tlsDirectory);
+ when(clientAndStub.stub().getDraftDesignDigest(any(GetDraftDesignDigestRequest.class)))
+ .thenThrow(Status.UNAVAILABLE.withDescription("readback unavailable").asRuntimeException());
+
+ assertThatThrownBy(
+ () -> clientAndStub.client().getDraftDesignDigestForVersion(publication, receipt))
+ .isInstanceOf(StatusRuntimeException.class)
+ .satisfies(
+ failure ->
+ assertThat(Status.fromThrowable(failure).getCode())
+ .isEqualTo(Status.Code.UNAVAILABLE));
+ verify(clientAndStub.stub()).getDraftDesignDigest(any(GetDraftDesignDigestRequest.class));
+ }
+
@Test
void rejectsMalformedManifestDigestFromPublicationResponse(@TempDir Path tlsDirectory)
throws IOException {
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
index 2802b62262..b185f8e61f 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java
@@ -8,35 +8,19 @@
import java.util.UUID;
import net.firedevops.firemud.common.authoring.DraftCommitBinding;
import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof;
-import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
import org.junit.jupiter.api.Test;
/** Structural digest vectors only; synthetic source rows do not prove physical owner provenance. */
class SelectedDraftControlPlaneDigestTest {
@Test
- void exactSixFamilyPreimageIsDeterministicAndDoesNotIncludePublicationRequestIdentity()
- throws Exception {
+ void exactSixFamilyPreimageIsDeterministic() throws Exception {
var selected = selectedBinding();
var sources = sources(selected);
- var firstRequest =
- PublicationDigestRequestBinding.full(
- selected.target().canonicalTenantId().toString(),
- Long.toString(selected.target().gameDesignVersionRowId()),
- "publish-one");
- var retryRequest =
- PublicationDigestRequestBinding.full(
- selected.target().canonicalTenantId().toString(),
- Long.toString(selected.target().gameDesignVersionRowId()),
- "publish-two");
-
var first = SelectedDraftControlPlaneDigest.compute(selected, sources);
var replay = SelectedDraftControlPlaneDigest.compute(selected, sources);
- var otherRequest = SelectedDraftControlPlaneDigest.compute(selected, sources);
assertThat(first).isEqualTo(replay);
- assertThat(first).isEqualTo(otherRequest);
- assertThat(firstRequest.requestDigest()).isNotEqualTo(retryRequest.requestDigest());
assertThat(first.digestSchemaVersion()).isEqualTo(2);
assertThat(first.tenantId()).isEqualTo(selected.target().canonicalTenantId().toString());
assertThat(first.scopeValue())
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
index 341cf55738..fad0b8c792 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java
@@ -22,9 +22,11 @@
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
+import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
+import org.springframework.transaction.TransactionSystemException;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/** Structural owner-read proof; mocks do not establish physical PostgreSQL source provenance. */
@@ -180,6 +182,34 @@ void missingOperationOrRetainedSelectionFailsBeforeSourceReads() throws Exceptio
verify(owner, never()).readSourceCapture(any());
}
+ @Test
+ void transactionAcquisitionFailureIsSanitizedAsUnavailable() throws Exception {
+ var fixture = fixture();
+ var request = request(fixture.operation());
+ when(transactions.getTransaction(any()))
+ .thenThrow(new CannotCreateTransactionException("database-secret"));
+ var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE);
+
+ assertSanitizedUnavailable(service, request);
+ verifyNoInteractions(owner);
+ }
+
+ @Test
+ void transactionRollbackFailureIsSanitizedAsUnavailable() throws Exception {
+ var fixture = fixture();
+ var request = request(fixture.operation());
+ when(transactions.getTransaction(any())).thenReturn(transactionStatus);
+ org.mockito.Mockito.doThrow(new TransactionSystemException("rollback-database-secret"))
+ .when(transactions)
+ .rollback(transactionStatus);
+ org.mockito.Mockito.doThrow(new IllegalStateException("selection-secret"))
+ .when(owner)
+ .read(request.derivedWorkflowIdentity());
+ var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE);
+
+ assertSanitizedUnavailable(service, request);
+ }
+
@Test
void missingSourceFamiliesAndFrozenSnapshotMismatchCannotProveAnEmptyOrDifferentSource()
throws Exception {
@@ -414,6 +444,20 @@ private static void assertCode(Status.Code expected, Runnable action) {
failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected));
}
+ private void assertSanitizedUnavailable(
+ SelectedDraftPublicationDigestReadService service, PublicationDigestRequestBinding request) {
+ assertThatThrownBy(() -> service.read(NAMESPACE, request))
+ .isInstanceOf(StatusRuntimeException.class)
+ .satisfies(
+ failure -> {
+ var status = ((StatusRuntimeException) failure).getStatus();
+ assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE);
+ assertThat(status.getDescription())
+ .isEqualTo("Selected publication source readback unavailable")
+ .doesNotContain("secret");
+ });
+ }
+
private record Fixture(
GameDesignPublicationOperation operation,
DraftCommitBinding binding,
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java
index e64e9f6b04..4c613b1c4a 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java
@@ -253,7 +253,8 @@ void selectedReceiptStorageInterruptionRemainsRetryable() {
assertEquals("UNAVAILABLE", digests.get(2).errorCode());
PublishGateFailureException thrown =
assertThrows(
- PublishGateFailureException.class, () -> service.assertGatePassed(version, digests));
+ PublishGateFailureException.class,
+ () -> service.assertSelectedGatePassed(version, digests));
assertTrue(PublicationFailureClassifier.isRetryableParticipantDependencyFailure(thrown));
}
diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java
index 0a934af274..7c3cb358c0 100644
--- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java
+++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java
@@ -70,6 +70,8 @@
@GrpcService
public class GameLogicGrpcService extends GameLogicServiceGrpc.GameLogicServiceImplBase {
private static final Logger logger = LoggerFactory.getLogger(GameLogicGrpcService.class);
+ private static final String PUBLICATION_READ_FAILURE_DESCRIPTION =
+ "Exact retained publication source read failed";
private final PingService pingService;
private final CommandService commandService;
private final LookAggregationService lookAggregationService;
@@ -211,22 +213,11 @@ public void getDraftDesignDigest(
.build());
responseObserver.onCompleted();
} catch (StatusRuntimeException ex) {
- Status status = ex.getStatus();
- String description =
- status.getDescription() == null
- ? "Exact retained publication source read was denied"
- : status.getDescription();
- responseObserver.onNext(
- GetDraftDesignDigestResponse.newBuilder()
- .setError(
- GrpcAppErrors.error(
- meterRegistry,
- logger,
- "GetDraftDesignDigest",
- status.getCode().name(),
- description))
- .build());
- responseObserver.onCompleted();
+ Status status = Status.fromThrowable(ex);
+ responseObserver.onError(
+ Status.fromCode(status.getCode())
+ .withDescription(PUBLICATION_READ_FAILURE_DESCRIPTION)
+ .asRuntimeException());
} catch (Exception ex) {
responseObserver.onNext(
GetDraftDesignDigestResponse.newBuilder()
diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java
index 1c81951446..55120e296b 100644
--- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java
+++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java
@@ -1,5 +1,6 @@
package net.firedevops.firemud.gamelogic.service.impl;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -539,6 +540,55 @@ void getDraftDesignDigestMapsUnexpectedUnsupportedOperationToInternalError() {
assertEquals("Internal error", response.get().getError().getMessage());
}
+ @Test
+ void getDraftDesignDigestReturnsSanitizedTransportStatusesWhenSourceReadFails() {
+ GameLogicDraftDesignDigestService digestService = mockDigestService();
+ SessionContext.setContext(
+ null, List.of(), Map.of(), true, "game-design-service", "test-instance");
+ GameLogicGrpcService service = newDigestService(digestService);
+ for (Status.Code code : List.of(Status.Code.FAILED_PRECONDITION, Status.Code.UNAVAILABLE)) {
+ Mockito.reset(digestService);
+ Mockito.when(
+ digestService.getDraftDesignDigest(any(GameLogicPublicationSourceReadBinding.class)))
+ .thenThrow(
+ Status.fromCode(code)
+ .withDescription("database-password-secret")
+ .asRuntimeException());
+ AtomicReference failure = new AtomicReference<>();
+
+ runAsGameDesign(
+ () ->
+ service.getDraftDesignDigest(
+ fullDigestRequest(TEST_TENANT.toString(), "7"),
+ new StreamObserver<>() {
+ @Override
+ public void onNext(GetDraftDesignDigestResponse value) {
+ fail("expected a transport failure, got response: " + value);
+ }
+
+ @Override
+ public void onError(Throwable t) {
+ failure.set(t);
+ }
+
+ @Override
+ public void onCompleted() {
+ fail("transport failure must not complete successfully");
+ }
+ }));
+
+ assertThat(failure.get()).isInstanceOf(StatusRuntimeException.class);
+ var statusFailure = (StatusRuntimeException) failure.get();
+ assertThat(statusFailure.getStatus().getCode()).isEqualTo(code);
+ assertThat(statusFailure.getStatus().getDescription())
+ .isEqualTo("Exact retained publication source read failed")
+ .hasSizeLessThan(128)
+ .doesNotContain("secret", "database");
+ assertThat(statusFailure.getCause()).isNull();
+ assertThat(statusFailure.getTrailers()).isNull();
+ }
+ }
+
@Test
void getDraftDesignDigestRejectsMissingPeerIdentityForInternalCaller() {
GameLogicDraftDesignDigestService digestService = mockDigestService();
From 3b9e7a9a9abb97d6180d362f3e5463c1128e8c92 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Mon, 19 Oct 2026 09:52:01 +1300
Subject: [PATCH 37/55] test: assert transport status for retained Game Logic
binding conflicts
---
.../impl/GameLogicGrpcServiceTest.java | 70 +++++++++++--------
1 file changed, 39 insertions(+), 31 deletions(-)
diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java
index 55120e296b..1682a8db7b 100644
--- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java
+++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java
@@ -508,16 +508,12 @@ void getDraftDesignDigestDeniesSourceBindingThatDiffersFromRetainedOperation() {
SessionContext.setContext(
null, List.of(), Map.of(), true, "game-design-service", "test-instance");
- AtomicReference responseReference = new AtomicReference<>();
+ AtomicReference failureReference = new AtomicReference<>();
runAsGameDesign(
- () -> responseReference.set(invokeDigest(service, fullDigestRequest(changedBinding))));
- GetDraftDesignDigestResponse response = responseReference.get();
+ () ->
+ failureReference.set(invokeDigestFailure(service, fullDigestRequest(changedBinding))));
- assertEquals("ALREADY_EXISTS", response.getError().getCode());
- assertEquals("", response.getContentDigest());
- assertEquals("", response.getAbilitySchemaDigest());
- assertEquals(0, response.getDigestSchemaVersion());
- assertEquals(ByteString.EMPTY, response.getRetainedIntakeTerminal());
+ assertThat(failureReference.get().getStatus().getCode()).isEqualTo(Status.Code.ALREADY_EXISTS);
Mockito.verify(repository).findTerminal(authorization.operationId());
}
@@ -554,31 +550,13 @@ void getDraftDesignDigestReturnsSanitizedTransportStatusesWhenSourceReadFails()
Status.fromCode(code)
.withDescription("database-password-secret")
.asRuntimeException());
- AtomicReference failure = new AtomicReference<>();
-
+ AtomicReference failure = new AtomicReference<>();
runAsGameDesign(
() ->
- service.getDraftDesignDigest(
- fullDigestRequest(TEST_TENANT.toString(), "7"),
- new StreamObserver<>() {
- @Override
- public void onNext(GetDraftDesignDigestResponse value) {
- fail("expected a transport failure, got response: " + value);
- }
-
- @Override
- public void onError(Throwable t) {
- failure.set(t);
- }
-
- @Override
- public void onCompleted() {
- fail("transport failure must not complete successfully");
- }
- }));
-
- assertThat(failure.get()).isInstanceOf(StatusRuntimeException.class);
- var statusFailure = (StatusRuntimeException) failure.get();
+ failure.set(
+ invokeDigestFailure(service, fullDigestRequest(TEST_TENANT.toString(), "7"))));
+
+ var statusFailure = failure.get();
assertThat(statusFailure.getStatus().getCode()).isEqualTo(code);
assertThat(statusFailure.getStatus().getDescription())
.isEqualTo("Exact retained publication source read failed")
@@ -728,6 +706,36 @@ public void onCompleted() {}
return response;
}
+ private StatusRuntimeException invokeDigestFailure(
+ GameLogicGrpcService service, GetDraftDesignDigestRequest request) {
+ AtomicReference failure = new AtomicReference<>();
+ service.getDraftDesignDigest(
+ request,
+ new StreamObserver<>() {
+ @Override
+ public void onNext(GetDraftDesignDigestResponse value) {
+ fail("expected a transport failure, got response: " + value);
+ }
+
+ @Override
+ public void onError(Throwable t) {
+ failure.set(t);
+ }
+
+ @Override
+ public void onCompleted() {
+ fail("transport failure must not complete successfully");
+ }
+ });
+ if (failure.get() == null) {
+ throw new AssertionError("getDraftDesignDigest completed without a transport failure");
+ }
+ if (!(failure.get() instanceof StatusRuntimeException statusFailure)) {
+ throw new AssertionError("getDraftDesignDigest returned a non-status failure", failure.get());
+ }
+ return statusFailure;
+ }
+
private static void withPeer(GrpcPeerIdentity peer, Runnable action) {
Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer);
Context previous = context.attach();
From cd1cb47b421ffe0df923e67b47916d6360ea9d9d Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Mon, 19 Oct 2026 10:16:57 +1300
Subject: [PATCH 38/55] docs: align preliminary recovery status tracking
---
.../implementation-tracking/player-access-and-session.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md
index 2517e278f5..7922ea39f0 100644
--- a/design/project-management/implementation-tracking/player-access-and-session.md
+++ b/design/project-management/implementation-tracking/player-access-and-session.md
@@ -10,7 +10,7 @@ This is a non-normative implementation tracker for player access and session. Ca
This preparation is owned by [AA-1.3](#capability-status), which remains `partial` / `drift-found`. Its production and focused proof anchors are recorded in that row.
-Preliminary source reservations remain held until exact explicit abort or the prepared Account-owned expired-preliminary recovery operation commits that same immutable abort. The internal recovery entry accepts a bounded page of at most 128 candidates from its configured namespace, selects only original COMMITTED issuances past their actual PostgreSQL expiry, and revalidates exact retained scope and issuer evidence under the canonical source-lock then reservation-lock order. Each candidate commits independently; the returned count is not global completion or readiness. Finalized owners are excluded and remain protected until exact authenticated terminal settlement. Lost responses, unknown state or a guessed timeout do not authorize release. The operation has no transport registration, scheduler or invocation policy; those remain activation prerequisites.
+Preliminary source reservations remain held until exact explicit abort or the prepared Account-owned expired-preliminary recovery operation commits that same immutable abort. The internal recovery entry accepts a bounded page of at most 128 candidates from its configured namespace, selects only original COMMITTED, REVOKING, or REVOKED issuances past their actual PostgreSQL expiry, and revalidates exact retained scope and issuer evidence under the canonical source-lock then reservation-lock order. Each candidate commits independently, and a candidate failure does not roll back other candidates; the returned count is not global completion or readiness. Finalized owners are excluded and remain protected until exact authenticated terminal settlement. Lost responses, unknown state or a guessed timeout do not authorize release. The operation has no transport registration, scheduler or invocation policy; those remain activation prerequisites.
The focused recovery preparation passes eight unit cases at `cda9f4b0bb33265edaf3f0b32c348984472b1d14` and the one new physical PostgreSQL expiry/race case at `7ff2e65bc7fd1bd7d97f9a7034dfd65a39f8f381`, with zero failures, errors or skips in those separate scopes. Eight other native authorization/settlement cases passed in the earlier nine-case run, whose aggregate remains failed; this is not a new passing nine-case aggregate. Affected static and formatting checks pass after the fixture clock and query-alias corrections. The new case observes the real database cutoff and actual source-lock blocking: an in-flight finalization cannot commit after original expiry, abandoned preliminary reservations abort once, and an already committed finalization remains pending until exact Entity terminal settlement. Signer, issuer, source and terminal inputs remain controlled fixtures; no genuine authority, autonomous runtime recovery or activation is established. Prior failed selector, fixture and SQL attempts retain their original evidence.
From 83cdcd4243464252ba592191eec2b2e7e351eaf3 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Mon, 19 Oct 2026 11:56:59 +1300
Subject: [PATCH 39/55] test: assert sanitized Game Logic source-read transport
refusals
---
...tionDigestReadPostgresIntegrationTest.java | 55 ++++++++++++++++---
1 file changed, 48 insertions(+), 7 deletions(-)
diff --git a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java
index def0bf73a4..831feb639c 100644
--- a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java
+++ b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java
@@ -8,6 +8,8 @@
import static org.mockito.Mockito.when;
import io.grpc.Context;
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.util.List;
@@ -127,10 +129,10 @@ void actualRetainedOwnerFlowsThroughDigestServiceAndReceiverWithExactReplayAndRe
authorization.fenceId(),
authorization.intakeRequestId(),
authorization.source());
- assertError(
+ assertTransportError(
receiver,
GameLogicPublicationSourceReadGrpcCodec.toRequest(publicationBinding(missing)),
- "FAILED_PRECONDITION");
+ Status.Code.FAILED_PRECONDITION);
var changed =
copyAuthorization(
authorization,
@@ -138,10 +140,10 @@ void actualRetainedOwnerFlowsThroughDigestServiceAndReceiverWithExactReplayAndRe
UUID.randomUUID(),
authorization.intakeRequestId(),
authorization.source());
- assertError(
+ assertTransportError(
receiver,
GameLogicPublicationSourceReadGrpcCodec.toRequest(publicationBinding(changed)),
- "ALREADY_EXISTS");
+ Status.Code.ALREADY_EXISTS);
assertError(
receiver,
request.toBuilder().clearSourceReadBinding().clearSourceReadBindingDigest().build(),
@@ -164,7 +166,7 @@ void actualRetainedOwnerFlowsThroughDigestServiceAndReceiverWithExactReplayAndRe
SessionContext.clear();
TransactionSynchronizationManager.setActualTransactionActive(true);
try {
- assertError(receiver, request, "FAILED_PRECONDITION");
+ assertTransportError(receiver, request, Status.Code.FAILED_PRECONDITION);
} finally {
TransactionSynchronizationManager.setActualTransactionActive(false);
}
@@ -190,10 +192,10 @@ void actualRetainedOwnerFlowsThroughDigestServiceAndReceiverWithExactReplayAndRe
verify(abortAccountReader).read(any());
verify(unusedAbortSourceReader, never()).read(any());
String aborted = row(f, abortedAuthorization.operationId());
- assertError(
+ assertTransportError(
receiver,
GameLogicPublicationSourceReadGrpcCodec.toRequest(publicationBinding(abortedAuthorization)),
- "FAILED_PRECONDITION");
+ Status.Code.FAILED_PRECONDITION);
assertThat(row(f, abortedAuthorization.operationId())).isEqualTo(aborted);
assertThat(row(f, authorization.operationId())).isEqualTo(retained);
}
@@ -246,6 +248,45 @@ private static void assertError(
assertThat(response.getAbilitySchemaDigest()).isEmpty();
}
+ private static void assertTransportError(
+ GameLogicGrpcService receiver, GetDraftDesignDigestRequest request, Status.Code code)
+ throws Exception {
+ var failure = new AtomicReference();
+ var response = new AtomicReference();
+ var completed = new AtomicReference<>(false);
+ asGameDesign(
+ () -> {
+ receiver.getDraftDesignDigest(
+ request,
+ new StreamObserver<>() {
+ @Override
+ public void onNext(GetDraftDesignDigestResponse value) {
+ response.set(value);
+ }
+
+ @Override
+ public void onError(Throwable value) {
+ failure.set(value);
+ }
+
+ @Override
+ public void onCompleted() {
+ completed.set(true);
+ }
+ });
+ return null;
+ });
+ assertThat(failure.get()).isInstanceOf(StatusRuntimeException.class);
+ var statusFailure = (StatusRuntimeException) failure.get();
+ assertThat(statusFailure.getStatus().getCode()).isEqualTo(code);
+ assertThat(statusFailure.getStatus().getDescription())
+ .isEqualTo("Exact retained publication source read failed");
+ assertThat(statusFailure.getCause()).isNull();
+ assertThat(statusFailure.getTrailers()).isNull();
+ assertThat(response.get()).isNull();
+ assertThat(completed.get()).isFalse();
+ }
+
private static String row(Fixture f, UUID operation) {
return f.dsl()
.fetchSingle(
From f9e1758af8fae53d056da9058e78f50dad1e540e Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Mon, 19 Oct 2026 21:55:47 +1300
Subject: [PATCH 40/55] fix: preserve publication retries and advance expired
recovery pages
---
.../account-service/runtime-and-data.md | 2 +-
.../game-logic-service/api-contracts.md | 4 +-
...wnerIntakeSourceReservationRepository.java | 51 +++-
...edOwnerIntakeSourceReservationService.java | 28 +-
...eAuthorizationPostgresIntegrationTest.java | 104 +++++++-
...IntakeSourceReservationRepositoryTest.java | 19 +-
...nerIntakeSourceReservationServiceTest.java | 101 +++++++-
.../service/impl/PublishGateServiceImpl.java | 15 +-
.../VersionPublishCommandServiceImpl.java | 4 +-
.../impl/PublishedWorldSelectorFixtures.java | 26 ++
...ionTemplateAssociationReadServiceTest.java | 9 -
.../CompleteLaunchBindingServiceImplTest.java | 22 +-
.../impl/PublishGateServiceImplTest.java | 13 +-
.../PublishedReleaseBundleContractTest.java | 22 +-
...PublishedReleaseBundleServiceImplTest.java | 22 +-
.../VersionPublishCommandServiceImplTest.java | 242 ++++++++++++++++--
.../service/impl/GameLogicGrpcService.java | 2 +
.../impl/GameLogicGrpcServiceTest.java | 22 +-
18 files changed, 565 insertions(+), 143 deletions(-)
diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md
index 44a5f47a12..11898fa62b 100644
--- a/design/architecture/microservices/account-service/runtime-and-data.md
+++ b/design/architecture/microservices/account-service/runtime-and-data.md
@@ -8,7 +8,7 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn
## Implementation Status
-The selected-recipient intake source prepares distinct Entity/Automation source reservations and finalized authorizations, retained source-writer exclusion, and exact terminal settlement. Prepared final authorization and terminal migrations V1008–V1010 follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002, while preserving prior protection/disposal guards. These components remain unregistered and unqualified; the [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation) owns current proof, qualification limits and remaining dependencies.
+The selected-recipient intake source prepares distinct Entity/Automation source reservations and finalized authorizations, retained source-writer exclusion, and exact terminal settlement. Expired preliminary recovery pages use a caller-held `(expiry epoch second, operation UUID)` keyset cursor that advances across every examined row, including invalid rows and candidates whose abort does not commit; a caller continues while a cursor is returned and starts a fresh sweep only after an empty page. Prepared final authorization and terminal migrations V1008–V1010 follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002, while preserving prior protection/disposal guards. These components remain unregistered and unqualified; the [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation) owns current proof, qualification limits and remaining dependencies.
The additive [V1003 source-protection storage](../../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql) provides passive original StartSession admission and activation protection relations and source-writer exclusions. It adds no registered producer or transport. Qualification and remaining composition gates are recorded in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage).
diff --git a/design/architecture/microservices/game-logic-service/api-contracts.md b/design/architecture/microservices/game-logic-service/api-contracts.md
index 44efc9a0d8..c96a5e8f3b 100644
--- a/design/architecture/microservices/game-logic-service/api-contracts.md
+++ b/design/architecture/microservices/game-logic-service/api-contracts.md
@@ -59,7 +59,9 @@ The standalone [`RetainGameplayRuleIntake`](../../../../protos/game-logic/v1/gam
### Selected-source terminal read
-The separate, unregistered [`ReadGameplayRuleIntakeTerminal`](../../../../protos/game-logic/v1/gameplay_rule_intake_terminal_service.proto) method accepts only verified same-namespace Account callers, authenticating before decoding source evidence. Its versioned request binds the namespace, fresh read correlation and exact original Account intake authorization bytes/digest. Its closed response echoes that tuple and returns either the original canonical terminal and digest or explicit absence; absence is not an abort. The read is allowlisted to Account and performs no source creation, retention, abort, settlement, or admission. The [Account owner contract](../account-service/api-contracts.md#grpc-apis) defines held-order fencing and exact settlement authority; the [runtime/data owner](runtime-and-data.md#draft-digest-contract) defines intake and definitive-abort semantics. The [selected intake tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) and [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records unregistered transport, bounded-message and physical proof gates.
+The separate, unregistered [`ReadGameplayRuleIntakeTerminal`](../../../../protos/game-logic/v1/gameplay_rule_intake_terminal_service.proto) method accepts only verified same-namespace Account callers, authenticating before decoding source evidence. Its versioned request binds the namespace, fresh read correlation and exact original Account intake authorization bytes/digest. Its closed response echoes that tuple and returns either the original canonical terminal and digest or explicit absence; absence is not an abort. The read is allowlisted to Account and performs no source creation, retention, abort, settlement, or admission. The [Account owner contract](../account-service/api-contracts.md#grpc-apis) defines held-order fencing and exact settlement authority; the [runtime/data owner](runtime-and-data.md#draft-digest-contract) defines intake and definitive-abort semantics. The [selected intake tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) and [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) record unregistered transport, bounded-message and physical proof gates.
+
+The selected-full `GetDraftDesignDigest` adapter reads the exact retained source bound to the original Account-finalized receipt. A source-read failure that prevents producing that result uses a non-OK transport status under the [canonical classification](../../system-architecture-grpc.md#outcome-and-transport-classification), with a bounded generic description and no forwarded cause or trailers. Missing retained evidence uses `FAILED_PRECONDITION`; a conflicting retained binding uses `ALREADY_EXISTS`. Game Design preserves the original selection and retries only explicit transient dependency failures such as `UNAVAILABLE` and `DEADLINE_EXCEEDED`; those semantic precondition and binding failures do not become transient retries. The adapter records the bounded status code in `grpc.app_error` and its server diagnostic without logging arbitrary upstream descriptions. This standalone path remains unregistered.
### Gameplay methods
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java
index 3d2139ca0f..c81b8955e9 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java
@@ -59,6 +59,26 @@ public enum State {
ABORTED
}
+ /** Keyset position for continuing one caller-owned expired-reservation sweep. */
+ public record RecoveryCursor(long expiresAtEpochSecond, UUID operationId) {
+ public RecoveryCursor {
+ DraftAuthorizationFenceBinding.requireUuid(operationId);
+ }
+ }
+
+ /** Valid scopes decoded from one raw page, with its continuation based on the last raw row. */
+ record ExpiredPreliminarySourceReadPage(
+ List scopes,
+ int examinedCount,
+ RecoveryCursor nextCursor) {
+ ExpiredPreliminarySourceReadPage {
+ scopes = List.copyOf(scopes);
+ if (examinedCount < 0 || scopes.size() > examinedCount) {
+ throw new IllegalArgumentException("Invalid expired preliminary recovery page");
+ }
+ }
+ }
+
/** Historical evidence only. RESERVED does not imply a live source-read permission. */
public record Recovery(SelectedOwnerIntakeSourceReadScope scope, State state) {
public Recovery {
@@ -217,21 +237,27 @@ Recovery abortSourceRead(SelectedOwnerIntakeSourceReadScope scope) {
return new Recovery(scope, State.ABORTED);
}
- /**
- * Finds a bounded page of exact, expired, unfinalized reservations for one Account namespace. The
- * scope and complete retained source vector are validated before a candidate is returned.
- */
- List findExpiredPreliminarySourceReadScopes(
- int limit, String namespace) {
+ /** Finds one bounded, keyset-paged batch of exact expired reservations for one namespace. */
+ ExpiredPreliminarySourceReadPage findExpiredPreliminarySourceReadScopes(
+ int limit, String namespace, RecoveryCursor after) {
requireTransaction();
requireRecoveryLimit(limit);
if (!GrpcPeerIdentity.isValidNamespace(namespace)) {
throw new IllegalArgumentException("Canonical Account workload namespace required");
}
+ String continuation =
+ after == null
+ ? ""
+ : " AND (issuer.expires_at_epoch_second, reservation.operation_id) > (?, ?)";
+ Object[] parameters =
+ after == null
+ ? new Object[] {namespace, limit}
+ : new Object[] {namespace, after.expiresAtEpochSecond(), after.operationId(), limit};
List rows =
dsl.fetch(
- "SELECT reservation.* FROM "
+ "SELECT reservation.*, issuer.expires_at_epoch_second AS recovery_expires_at_epoch_second, "
+ + "reservation.operation_id AS recovery_operation_id FROM "
+ RESERVATIONS
+ " reservation JOIN account_control_ui_issuance_operations issuer"
+ " ON issuer.operation_id = reservation.issuance_operation_id"
@@ -252,14 +278,19 @@ List findExpiredPreliminarySourceReadScopes(
+ " AND extract(epoch FROM clock_timestamp()) >= issuer.expires_at_epoch_second"
+ " AND finalized_reservation.operation_id IS NULL"
+ " AND aborted.operation_id IS NULL"
+ + continuation
+ " ORDER BY issuer.expires_at_epoch_second, reservation.operation_id"
+ " LIMIT ?",
- namespace,
- limit);
+ parameters);
List scopes = new ArrayList<>(rows.size());
+ RecoveryCursor nextCursor = null;
int rowNumber = 0;
for (Record row : rows) {
rowNumber++;
+ nextCursor =
+ new RecoveryCursor(
+ row.get("recovery_expires_at_epoch_second", Long.class),
+ row.get("recovery_operation_id", UUID.class));
try {
var scope =
SelectedOwnerIntakeSourceReadScope.fromStored(row.get("scope_bytes", byte[].class));
@@ -276,7 +307,7 @@ List findExpiredPreliminarySourceReadScopes(
invalidRow.getClass().getSimpleName());
}
}
- return List.copyOf(scopes);
+ return new ExpiredPreliminarySourceReadPage(scopes, rows.size(), nextCursor);
}
/**
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java
index 69664285ef..9af79b25db 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java
@@ -31,6 +31,18 @@ public final class AccountSelectedOwnerIntakeSourceReservationService {
private final String namespace;
private final TransactionTemplate ownerTransaction;
+ /** Outcome of one bounded recovery page; zero aborts does not mean the sweep is complete. */
+ public record RecoveryPage(
+ int abortedCount,
+ int examinedCount,
+ AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor nextCursor) {
+ public RecoveryPage {
+ if (abortedCount < 0 || examinedCount < 0 || abortedCount > examinedCount) {
+ throw new IllegalArgumentException("Invalid expired preliminary recovery result");
+ }
+ }
+ }
+
public AccountSelectedOwnerIntakeSourceReservationService(
AccountControlUiActorService actors,
DraftAuthorizationFenceRepository fences,
@@ -148,9 +160,11 @@ public AccountSelectedOwnerIntakeSourceReservationRepository.Recovery abortSourc
* candidate is rechecked and, if still eligible, durably aborted in its own independent
* READ_COMMITTED owner transaction. Finalized and concurrently changed candidates are skipped.
*
- * @return abort rows committed by this page; this is not a global completion signal
+ * @return counts and caller-owned continuation; a zero abort count is not global completion
*/
- public int recoverExpiredPreliminarySourceReads(int maximumCandidates) {
+ public RecoveryPage recoverExpiredPreliminarySourceReads(
+ int maximumCandidates,
+ AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor after) {
if (maximumCandidates <= 0) {
throw new IllegalArgumentException("Expired preliminary recovery batch must be positive");
}
@@ -161,16 +175,16 @@ public int recoverExpiredPreliminarySourceReads(int maximumCandidates) {
AccountSelectedOwnerIntakeSourceReservationRepository
.MAX_EXPIRED_PRELIMINARY_RECOVERY_BATCH_SIZE);
- var candidates =
+ var page =
Objects.requireNonNull(
ownerTransaction.execute(
ignored ->
repository.findExpiredPreliminarySourceReadScopes(
- boundedCandidates, namespace)),
+ boundedCandidates, namespace, after)),
"Expired source-read candidate lookup returned no result");
int aborted = 0;
int candidateNumber = 0;
- for (SelectedOwnerIntakeSourceReadScope scope : candidates) {
+ for (SelectedOwnerIntakeSourceReadScope scope : page.scopes()) {
candidateNumber++;
try {
if (Objects.requireNonNull(
@@ -183,11 +197,11 @@ public int recoverExpiredPreliminarySourceReads(int maximumCandidates) {
LOGGER.warn(
"Skipped failed expired preliminary source-read candidate {}/{} (failureType={})",
candidateNumber,
- candidates.size(),
+ page.scopes().size(),
candidateFailure.getClass().getSimpleName());
}
}
- return aborted;
+ return new RecoveryPage(aborted, page.examinedCount(), page.nextCursor());
}
private Optional findScope(
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
index cc36159ced..8fe433c0f0 100644
--- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
@@ -367,7 +367,8 @@ void expiredRecoveryUsesDatabaseCutoffAndPreservesFinalizedOwnerUntilExactSettle
.get("issuance_operation_id", UUID.class);
assertThat(issuerExpiryReached(f.dsl, issuanceOperationId)).isFalse();
- assertThat(reservations.recoverExpiredPreliminarySourceReads(128)).isZero();
+ assertThat(reservations.recoverExpiredPreliminarySourceReads(128, null).abortedCount())
+ .isZero();
assertThat(f.tx(() -> repository.recoverSourceRead(preliminary).state()))
.isEqualTo(State.RESERVED);
assertThat(sourceReadPending(f.dsl, preliminary.operationId())).isTrue();
@@ -414,7 +415,9 @@ void expiredRecoveryUsesDatabaseCutoffAndPreservesFinalizedOwnerUntilExactSettle
executor.submit(
() -> {
recoveryStarted.countDown();
- return reservations.recoverExpiredPreliminarySourceReads(128);
+ return reservations
+ .recoverExpiredPreliminarySourceReads(128, null)
+ .abortedCount();
});
assertThat(recoveryStarted.await(10, TimeUnit.SECONDS)).isTrue();
awaitRecoverySourceLockWait(f.dsl, finalizationBackendPid.get());
@@ -439,7 +442,8 @@ void expiredRecoveryUsesDatabaseCutoffAndPreservesFinalizedOwnerUntilExactSettle
assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue();
}
- assertThat(reservations.recoverExpiredPreliminarySourceReads(128)).isZero();
+ assertThat(reservations.recoverExpiredPreliminarySourceReads(128, null).abortedCount())
+ .isZero();
assertThat(f.tx(() -> repository.recoverSourceRead(preliminary).state()))
.isEqualTo(State.ABORTED);
assertThat(f.tx(() -> repository.recoverSourceRead(finalizingScope).state()))
@@ -495,6 +499,86 @@ void expiredRecoveryUsesDatabaseCutoffAndPreservesFinalizedOwnerUntilExactSettle
}
}
+ @Test
+ void expiredPreliminaryRecoveryContinuesAcrossSameExpiryRowsByKeyset() throws Exception {
+ var serviceClock = new MutableOffsetClock(Clock.systemUTC(), -270L);
+ try (var fixture =
+ new AccountControlUiOriginalOrderFixture(
+ postgres.getJdbcUrl(),
+ postgres.getUsername(),
+ postgres.getPassword(),
+ redis.getHost(),
+ redis.getMappedPort(6379),
+ temporary,
+ UUID.randomUUID(),
+ Clock.systemUTC(),
+ null,
+ serviceClock)) {
+ var issued = fixture.issueCreator();
+ var f = issued.sources();
+ var selected = selectedForSettlement(f.tenant);
+ settleOriginal(issued, selected);
+ var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl);
+ var reservations =
+ new AccountSelectedOwnerIntakeSourceReservationService(
+ issued.actors(), f.fences, repository, f.manager, "test");
+ var firstScope =
+ asGameDesign(
+ () ->
+ reservations.reserveSourceRead(
+ issued.compact(),
+ UUID.randomUUID(),
+ Owner.ENTITY_MANAGEMENT,
+ selected,
+ issued.environment()));
+ var secondScope =
+ asGameDesign(
+ () ->
+ reservations.reserveSourceRead(
+ issued.compact(),
+ UUID.randomUUID(),
+ Owner.AUTOMATION_SCRIPTING,
+ selected,
+ issued.environment()));
+ UUID issuanceOperationId =
+ f.dsl
+ .fetchSingle(
+ "SELECT issuance_operation_id FROM account_selected_owner_intake_source_read_reservations"
+ + " WHERE operation_id = ?",
+ firstScope.operationId())
+ .get("issuance_operation_id", UUID.class);
+
+ awaitIssuerExpiry(f.dsl, issuanceOperationId);
+
+ var firstPage = reservations.recoverExpiredPreliminarySourceReads(1, null);
+ assertThat(firstPage.examinedCount()).isEqualTo(1);
+ assertThat(firstPage.abortedCount()).isEqualTo(1);
+ assertThat(firstPage.nextCursor()).isNotNull();
+ assertThat(firstPage.nextCursor().expiresAtEpochSecond())
+ .isEqualTo(issuerExpiryEpochSecond(f.dsl, issuanceOperationId));
+
+ var secondPage = reservations.recoverExpiredPreliminarySourceReads(1, firstPage.nextCursor());
+ assertThat(secondPage.examinedCount()).isEqualTo(1);
+ assertThat(secondPage.abortedCount()).isEqualTo(1);
+ assertThat(secondPage.nextCursor()).isNotNull();
+ assertThat(secondPage.nextCursor().expiresAtEpochSecond())
+ .isEqualTo(firstPage.nextCursor().expiresAtEpochSecond());
+ assertThat(secondPage.nextCursor().operationId())
+ .isNotEqualTo(firstPage.nextCursor().operationId());
+
+ var emptyPage = reservations.recoverExpiredPreliminarySourceReads(1, secondPage.nextCursor());
+ assertThat(emptyPage.examinedCount()).isZero();
+ assertThat(emptyPage.abortedCount()).isZero();
+ assertThat(emptyPage.nextCursor()).isNull();
+ assertThat(f.tx(() -> repository.recoverSourceRead(firstScope).state()))
+ .isEqualTo(State.ABORTED);
+ assertThat(f.tx(() -> repository.recoverSourceRead(secondScope).state()))
+ .isEqualTo(State.ABORTED);
+ assertThat(sourceReadPending(f.dsl, firstScope.operationId())).isFalse();
+ assertThat(sourceReadPending(f.dsl, secondScope.operationId())).isFalse();
+ }
+ }
+
@ParameterizedTest
@ValueSource(strings = {"REVOKING", "REVOKED"})
void expiredPreliminaryRecoveryAcceptsRetainedExpiredIssuersAndKeepsFinalAuthorization(
@@ -565,7 +649,8 @@ void expiredPreliminaryRecoveryAcceptsRetainedExpiredIssuersAndKeepsFinalAuthori
.get("status", String.class))
.isEqualTo(issuerStatus);
- assertThat(reservations.recoverExpiredPreliminarySourceReads(128)).isEqualTo(1);
+ assertThat(reservations.recoverExpiredPreliminarySourceReads(128, null).abortedCount())
+ .isEqualTo(1);
assertThat(f.tx(() -> repository.recoverSourceRead(preliminary).state()))
.isEqualTo(State.ABORTED);
@@ -611,7 +696,8 @@ void expiredPreliminaryRecoveryAcceptsRetainedExpiredIssuersAndKeepsFinalAuthori
UUID.randomUUID(), finalized.sources(), new byte[] {2});
assertThat(f.tx(() -> f.fences.requestSourceChange(sourceChange))).isFalse();
assertThat(f.tx(() -> f.fences.sourceMutationPermitted(sourceChange))).isFalse();
- assertThat(reservations.recoverExpiredPreliminarySourceReads(128)).isZero();
+ assertThat(reservations.recoverExpiredPreliminarySourceReads(128, null).abortedCount())
+ .isZero();
}
}
@@ -2567,6 +2653,14 @@ private static boolean issuerExpiryReached(DSLContext dsl, UUID issuanceOperatio
.get(0, Boolean.class);
}
+ private static long issuerExpiryEpochSecond(DSLContext dsl, UUID issuanceOperationId) {
+ return dsl.fetchSingle(
+ "SELECT expires_at_epoch_second FROM account_control_ui_issuance_operations "
+ + "WHERE operation_id = ?",
+ issuanceOperationId)
+ .get("expires_at_epoch_second", Long.class);
+ }
+
private static void awaitIssuerExpiry(DSLContext dsl, UUID issuanceOperationId)
throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(45);
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java
index b12dd3fa07..7f0a57bcf8 100644
--- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java
@@ -67,13 +67,19 @@ void everyReservationRecoveryAbortAndCurrentnessReadRequiresAnOwnerTransaction()
@Test
@SuppressWarnings({"rawtypes", "unchecked"})
- void expiredRecoverySkipsInvalidRowsAndStillDecodesLaterRows() {
+ void expiredRecoveryAttemptsInvalidRowsAndAdvancesCursorPastThem() {
var dsl = mock(DSLContext.class);
var first = mock(Record.class);
var later = mock(Record.class);
when(first.get("scope_bytes", byte[].class)).thenReturn(new byte[0]);
when(later.get("scope_bytes", byte[].class))
.thenThrow(new IllegalStateException("synthetic row failure"));
+ when(first.get("recovery_expires_at_epoch_second", Long.class)).thenReturn(10L);
+ when(later.get("recovery_expires_at_epoch_second", Long.class)).thenReturn(20L);
+ when(first.get("recovery_operation_id", java.util.UUID.class))
+ .thenReturn(java.util.UUID.fromString("11111111-1111-4111-8111-111111111111"));
+ when(later.get("recovery_operation_id", java.util.UUID.class))
+ .thenReturn(java.util.UUID.fromString("22222222-2222-4222-8222-222222222222"));
Result rows = mock(Result.class);
when(rows.size()).thenReturn(2);
when(rows.iterator()).thenReturn(List.of(first, later).iterator());
@@ -82,7 +88,14 @@ void expiredRecoverySkipsInvalidRowsAndStillDecodesLaterRows() {
var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(dsl);
- assertThat(repository.findExpiredPreliminarySourceReadScopes(2, "test")).isEmpty();
+ var page = repository.findExpiredPreliminarySourceReadScopes(2, "test", null);
+
+ assertThat(page.scopes()).isEmpty();
+ assertThat(page.examinedCount()).isEqualTo(2);
+ assertThat(page.nextCursor())
+ .isEqualTo(
+ new AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor(
+ 20L, java.util.UUID.fromString("22222222-2222-4222-8222-222222222222")));
verify(first).get("scope_bytes", byte[].class);
verify(later).get("scope_bytes", byte[].class);
@@ -100,7 +113,7 @@ void expiredRecoveryPropagatesLookupFailuresForTheWholeOwnerTransaction() {
var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(dsl);
- assertThatThrownBy(() -> repository.findExpiredPreliminarySourceReadScopes(2, "test"))
+ assertThatThrownBy(() -> repository.findExpiredPreliminarySourceReadScopes(2, "test", null))
.isInstanceOf(DataAccessException.class);
}
}
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java
index 078813aad5..44b476c82c 100644
--- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java
@@ -311,12 +311,24 @@ void expiredPreliminaryRecoveryBoundsWorkAndUsesOneOwnerTransactionPerCandidate(
new SimpleTransactionStatus(),
new SimpleTransactionStatus(),
new SimpleTransactionStatus());
- when(repository.findExpiredPreliminarySourceReadScopes(128, "test"))
- .thenReturn(List.of(first, second));
+ when(repository.findExpiredPreliminarySourceReadScopes(128, "test", null))
+ .thenReturn(
+ new AccountSelectedOwnerIntakeSourceReservationRepository
+ .ExpiredPreliminarySourceReadPage(
+ List.of(first, second),
+ 2,
+ new AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor(
+ 10L, second.operationId())));
when(repository.abortExpiredPreliminarySourceRead(first, "test")).thenReturn(true);
when(repository.abortExpiredPreliminarySourceRead(second, "test")).thenReturn(false);
- assertThat(service.recoverExpiredPreliminarySourceReads(129)).isEqualTo(1);
+ var result = service.recoverExpiredPreliminarySourceReads(129, null);
+ assertThat(result.abortedCount()).isEqualTo(1);
+ assertThat(result.examinedCount()).isEqualTo(2);
+ assertThat(result.nextCursor())
+ .isEqualTo(
+ new AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor(
+ 10L, second.operationId()));
var definitions = org.mockito.ArgumentCaptor.forClass(TransactionDefinition.class);
verify(transactions, org.mockito.Mockito.times(3)).getTransaction(definitions.capture());
@@ -329,12 +341,63 @@ void expiredPreliminaryRecoveryBoundsWorkAndUsesOneOwnerTransactionPerCandidate(
.isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED);
assertThat(definition.isReadOnly()).isFalse();
});
- verify(repository).findExpiredPreliminarySourceReadScopes(128, "test");
+ verify(repository).findExpiredPreliminarySourceReadScopes(128, "test", null);
verify(repository).abortExpiredPreliminarySourceRead(first, "test");
verify(repository).abortExpiredPreliminarySourceRead(second, "test");
verifyNoInteractions(actors, fences);
}
+ @Test
+ void expiredPreliminaryRecoveryCarriesCursorAcrossSkippedAndSuccessfulPages() {
+ var selected = selected();
+ var later = recoveryScope(selected, "22222222-2222-4222-8222-222222222222");
+ var firstCursor =
+ new AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor(
+ -17L, UUID.fromString("11111111-1111-4111-8111-111111111111"));
+ var secondCursor =
+ new AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor(
+ -17L, UUID.fromString("33333333-3333-4333-8333-333333333333"));
+ when(transactions.getTransaction(any(TransactionDefinition.class)))
+ .thenReturn(
+ new SimpleTransactionStatus(),
+ new SimpleTransactionStatus(),
+ new SimpleTransactionStatus());
+ when(repository.findExpiredPreliminarySourceReadScopes(1, "test", null))
+ .thenReturn(
+ new AccountSelectedOwnerIntakeSourceReservationRepository
+ .ExpiredPreliminarySourceReadPage(List.of(), 1, firstCursor));
+ when(repository.findExpiredPreliminarySourceReadScopes(1, "test", firstCursor))
+ .thenReturn(
+ new AccountSelectedOwnerIntakeSourceReservationRepository
+ .ExpiredPreliminarySourceReadPage(List.of(later), 1, secondCursor));
+ when(repository.abortExpiredPreliminarySourceRead(later, "test")).thenReturn(true);
+
+ var firstPage = service.recoverExpiredPreliminarySourceReads(1, null);
+ assertThat(firstPage.abortedCount()).isZero();
+ assertThat(firstPage.examinedCount()).isEqualTo(1);
+ assertThat(firstPage.nextCursor()).isEqualTo(firstCursor);
+
+ var secondPage = service.recoverExpiredPreliminarySourceReads(1, firstPage.nextCursor());
+ assertThat(secondPage.abortedCount()).isEqualTo(1);
+ assertThat(secondPage.examinedCount()).isEqualTo(1);
+ assertThat(secondPage.nextCursor()).isEqualTo(secondCursor);
+
+ verify(repository).findExpiredPreliminarySourceReadScopes(1, "test", null);
+ verify(repository).findExpiredPreliminarySourceReadScopes(1, "test", firstCursor);
+ verify(repository).abortExpiredPreliminarySourceRead(later, "test");
+ var definitions = org.mockito.ArgumentCaptor.forClass(TransactionDefinition.class);
+ verify(transactions, times(3)).getTransaction(definitions.capture());
+ assertThat(definitions.getAllValues())
+ .allSatisfy(
+ definition -> {
+ assertThat(definition.getPropagationBehavior())
+ .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
+ assertThat(definition.getIsolationLevel())
+ .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED);
+ assertThat(definition.isReadOnly()).isFalse();
+ });
+ }
+
@Test
void expiredPreliminaryRecoveryContinuesAfterFirstAndLaterCandidateFailures() {
var selected = selected();
@@ -347,15 +410,21 @@ void expiredPreliminaryRecoveryContinuesAfterFirstAndLaterCandidateFailures() {
new SimpleTransactionStatus(),
new SimpleTransactionStatus(),
new SimpleTransactionStatus());
- when(repository.findExpiredPreliminarySourceReadScopes(3, "test"))
- .thenReturn(List.of(first, successful, later));
+ when(repository.findExpiredPreliminarySourceReadScopes(3, "test", null))
+ .thenReturn(
+ new AccountSelectedOwnerIntakeSourceReservationRepository
+ .ExpiredPreliminarySourceReadPage(
+ List.of(first, successful, later),
+ 3,
+ new AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor(
+ 10L, later.operationId())));
when(repository.abortExpiredPreliminarySourceRead(first, "test"))
.thenThrow(new IllegalStateException("synthetic source payload must not be logged"));
when(repository.abortExpiredPreliminarySourceRead(successful, "test")).thenReturn(true);
when(repository.abortExpiredPreliminarySourceRead(later, "test"))
.thenThrow(new IllegalArgumentException("synthetic credential must not be logged"));
- assertThat(service.recoverExpiredPreliminarySourceReads(3)).isEqualTo(1);
+ assertThat(service.recoverExpiredPreliminarySourceReads(3, null).abortedCount()).isEqualTo(1);
verify(repository).abortExpiredPreliminarySourceRead(first, "test");
verify(repository).abortExpiredPreliminarySourceRead(successful, "test");
@@ -373,14 +442,20 @@ void expiredPreliminaryRecoveryContinuesAndReturnsZeroWhenEveryCandidateFails()
new SimpleTransactionStatus(),
new SimpleTransactionStatus(),
new SimpleTransactionStatus());
- when(repository.findExpiredPreliminarySourceReadScopes(2, "test"))
- .thenReturn(List.of(first, second));
+ when(repository.findExpiredPreliminarySourceReadScopes(2, "test", null))
+ .thenReturn(
+ new AccountSelectedOwnerIntakeSourceReservationRepository
+ .ExpiredPreliminarySourceReadPage(
+ List.of(first, second),
+ 2,
+ new AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor(
+ 10L, second.operationId())));
when(repository.abortExpiredPreliminarySourceRead(first, "test"))
.thenThrow(new IllegalStateException("synthetic failure"));
when(repository.abortExpiredPreliminarySourceRead(second, "test"))
.thenThrow(new IllegalStateException("synthetic failure"));
- assertThat(service.recoverExpiredPreliminarySourceReads(2)).isZero();
+ assertThat(service.recoverExpiredPreliminarySourceReads(2, null).abortedCount()).isZero();
verify(repository).abortExpiredPreliminarySourceRead(first, "test");
verify(repository).abortExpiredPreliminarySourceRead(second, "test");
@@ -389,9 +464,9 @@ void expiredPreliminaryRecoveryContinuesAndReturnsZeroWhenEveryCandidateFails()
@Test
void expiredPreliminaryRecoveryRejectsNonpositivePagesBeforeOpeningTransactions() {
- assertThatThrownBy(() -> service.recoverExpiredPreliminarySourceReads(0))
+ assertThatThrownBy(() -> service.recoverExpiredPreliminarySourceReads(0, null))
.isInstanceOf(IllegalArgumentException.class);
- assertThatThrownBy(() -> service.recoverExpiredPreliminarySourceReads(-1))
+ assertThatThrownBy(() -> service.recoverExpiredPreliminarySourceReads(-1, null))
.isInstanceOf(IllegalArgumentException.class);
verifyNoInteractions(actors, fences, repository, transactions);
}
@@ -399,7 +474,7 @@ void expiredPreliminaryRecoveryRejectsNonpositivePagesBeforeOpeningTransactions(
@Test
void expiredPreliminaryRecoveryRejectsAmbientTransactionsBeforeOwnerAccess() {
TransactionSynchronizationManager.setActualTransactionActive(true);
- assertThatThrownBy(() -> service.recoverExpiredPreliminarySourceReads(1))
+ assertThatThrownBy(() -> service.recoverExpiredPreliminarySourceReads(1, null))
.isInstanceOf(io.grpc.StatusRuntimeException.class)
.hasMessageContaining("independent transaction");
verifyNoInteractions(actors, fences, repository, transactions);
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java
index 9741f63ff2..c71c68bf03 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java
@@ -253,6 +253,7 @@ public void assertSelectedGatePassed(
if (version.scriptOnly()) {
throw new IllegalArgumentException("Selected publication requires a full version");
}
+ assertParticipantSetAndSucceeded(version, participantDigests);
List worldDigests =
participantDigests == null
? List.of()
@@ -273,13 +274,19 @@ public void assertSelectedGatePassed(
PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA,
"publish gate failed: unsupported selected World digest schema");
};
- assertGatePassed(version, participantDigests, selectedAttestationSchema);
+ assertParticipantEvidence(version, participantDigests, selectedAttestationSchema);
}
private void assertGatePassed(
VersionDto version,
List participantDigests,
Integer selectedAttestationSchema) {
+ assertParticipantSetAndSucceeded(version, participantDigests);
+ assertParticipantEvidence(version, participantDigests, selectedAttestationSchema);
+ }
+
+ private void assertParticipantSetAndSucceeded(
+ VersionDto version, List participantDigests) {
List expectedParticipants =
version.scriptOnly() ? SCRIPT_PATCH_PARTICIPANTS : FULL_VERSION_PARTICIPANTS;
List expectedParticipantKeyList =
@@ -316,6 +323,12 @@ private void assertGatePassed(
+ (failed.errorMessage() == null ? failed.errorCode() : failed.errorMessage()),
failed.errorCode());
}
+ }
+
+ private void assertParticipantEvidence(
+ VersionDto version,
+ List participantDigests,
+ Integer selectedAttestationSchema) {
String expectedScope =
version.scriptOnly() ? version.scriptPatchVersion() : String.valueOf(version.id());
Long expectedBaseVersionId = version.scriptOnly() ? version.baseVersionId() : null;
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java
index 73af3c7ec3..d2240ce0de 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java
@@ -283,12 +283,12 @@ private PublishWorkflowSnapshot reconcileSelectedPublicationMechanicsLocal(
return failDefinitively(request, attempt, version, null, ex);
}
try {
+ publishGateService.assertSelectedGatePassed(dto, participantDigests);
assertSelectedCommit(request, participantDigests);
PublishedReleaseBundleContract.requireFreshSelectedFullParticipantVector(
dto.id(),
requireSelectedIntent(request).selectedCommit().commitId().toString(),
participantDigests);
- publishGateService.assertSelectedGatePassed(dto, participantDigests);
} catch (RuntimeException ex) {
if (PublicationFailureClassifier.isRetryableParticipantDependencyFailure(ex)) {
throw pendingReconciliation(
@@ -510,12 +510,12 @@ private PublishWorkflowSnapshot finalizeFullVersion(
VersionDto dto = versionMapper.toDto(version);
requireSelectedDraftEpoch(request, version);
+ publishGateService.assertSelectedGatePassed(dto, participantDigests);
assertSelectedCommit(request, participantDigests);
PublishedReleaseBundleContract.requireFreshSelectedFullParticipantVector(
dto.id(),
requireSelectedIntent(request).selectedCommit().commitId().toString(),
participantDigests);
- publishGateService.assertSelectedGatePassed(dto, participantDigests);
publishAttemptService.recordFullVersionParticipantDigests(
request.publishWorkflowId(), participantDigests);
VersionAssetArtifactStateDto exportedState =
diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java
index 84c1cd3b26..e6326497ff 100644
--- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java
+++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java
@@ -39,6 +39,32 @@ private PublishedWorldSelectorFixtures(TargetProof target, String baseReference)
this.VERSION_ID = target.canonicalVersionId();
}
+ /** Rebuilds only the schema field of stipulated test evidence for contract boundary checks. */
+ public static WorldPublishedStartLocationEvidence withDigestSchemaVersion(
+ WorldPublishedStartLocationEvidence base, int digestSchemaVersion) {
+ var original = base.request();
+ var request =
+ new WorldPublishedStartLocationEvidence.Request(
+ original.targetNamespace(),
+ original.canonicalTenantId(),
+ original.canonicalVersionId(),
+ original.intakeRequestId(),
+ original.publicationFence(),
+ original.publicationRequestId(),
+ original.requestDigest(),
+ original.versionStateEpoch(),
+ original.publishWorkflowId(),
+ original.appliedCommitId(),
+ original.contentDigest(),
+ digestSchemaVersion,
+ original.worldAffectedTuples());
+ return new WorldPublishedStartLocationEvidence(
+ request,
+ base.selectorReceiptBytes(),
+ base.originalAccountBindingBytes(),
+ base.appliedResultBytes());
+ }
+
public static WorldPublishedStartLocationEvidence evidence(TargetProof target) throws Exception {
return new PublishedWorldSelectorFixtures(target).build();
}
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java
index ab8577ba20..61d379ea32 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java
@@ -51,15 +51,6 @@ class StartSessionTemplateAssociationReadServiceTest {
private final DSLContext dsl = mock(DSLContext.class);
private final PublishedReleaseBundleService releases = mock(PublishedReleaseBundleService.class);
- @Test
- void configuredReleaseSelectionRetainsV2AndAcceptsOnlyFullV4() {
- assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v2")).isTrue();
- assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v4")).isTrue();
- assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v1")).isFalse();
- assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v3")).isFalse();
- assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema(null)).isFalse();
- }
-
@Test
void independentlyChecksExactAccountAttemptBeforeOpeningAnyLocalSnapshot() {
var tuple = postTuple("account-before-local-snapshot");
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java
index 83970e9071..d296297cae 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java
@@ -1038,27 +1038,7 @@ private WorldPublishedStartLocationEvidence selectorEvidence() throws Exception
private WorldPublishedStartLocationEvidence selectorEvidence(int digestSchemaVersion)
throws Exception {
var base = selectorEvidence();
- var original = base.request();
- var request =
- new WorldPublishedStartLocationEvidence.Request(
- original.targetNamespace(),
- original.canonicalTenantId(),
- original.canonicalVersionId(),
- original.intakeRequestId(),
- original.publicationFence(),
- original.publicationRequestId(),
- original.requestDigest(),
- original.versionStateEpoch(),
- original.publishWorkflowId(),
- original.appliedCommitId(),
- original.contentDigest(),
- digestSchemaVersion,
- original.worldAffectedTuples());
- return new WorldPublishedStartLocationEvidence(
- request,
- base.selectorReceiptBytes(),
- base.originalAccountBindingBytes(),
- base.appliedResultBytes());
+ return PublishedWorldSelectorFixtures.withDigestSchemaVersion(base, digestSchemaVersion);
}
private PublishedReleaseBundleDto selectorBundle(
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java
index 4c613b1c4a..fe5f28315d 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java
@@ -2,6 +2,7 @@
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -648,9 +649,15 @@ void unavailableSelectedReaderFailsBothOwnersWithoutLegacyFallback() {
assertEquals(5, digests.size());
assertEquals("UNAVAILABLE", digests.getFirst().errorCode());
assertEquals("UNAVAILABLE", digests.get(4).errorCode());
- assertThrows(
- PublishGateFailureException.class,
- () -> service.assertSelectedGatePassed(version, digests));
+ assertNull(digests.getFirst().appliedCommitId());
+ assertNull(digests.getFirst().digestSchemaVersion());
+ PublishGateFailureException failure =
+ assertThrows(
+ PublishGateFailureException.class,
+ () -> service.assertSelectedGatePassed(version, digests));
+ assertEquals(PublishGateFailureCode.PARTICIPANT_UNAVAILABLE, failure.failureCode());
+ assertEquals("UNAVAILABLE", failure.participantFailureCode());
+ assertTrue(PublicationFailureClassifier.isRetryableParticipantDependencyFailure(failure));
org.mockito.Mockito.verifyNoInteractions(worldManagementClient, controlPlaneDigestService);
verify(gameLogicClient).getDraftDesignDigestForVersion(binding, receipt);
}
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java
index a05b606e34..b60168aad9 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java
@@ -339,27 +339,7 @@ private static WorldPublishedStartLocationEvidence selectorEvidence() throws Exc
private static WorldPublishedStartLocationEvidence selectorEvidence(int digestSchemaVersion)
throws Exception {
var base = selectorEvidence();
- var original = base.request();
- var request =
- new WorldPublishedStartLocationEvidence.Request(
- original.targetNamespace(),
- original.canonicalTenantId(),
- original.canonicalVersionId(),
- original.intakeRequestId(),
- original.publicationFence(),
- original.publicationRequestId(),
- original.requestDigest(),
- original.versionStateEpoch(),
- original.publishWorkflowId(),
- original.appliedCommitId(),
- original.contentDigest(),
- digestSchemaVersion,
- original.worldAffectedTuples());
- return new WorldPublishedStartLocationEvidence(
- request,
- base.selectorReceiptBytes(),
- base.originalAccountBindingBytes(),
- base.appliedResultBytes());
+ return PublishedWorldSelectorFixtures.withDigestSchemaVersion(base, digestSchemaVersion);
}
private static List selectorParticipants(
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
index be1631932c..7d23db3d44 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
@@ -346,27 +346,7 @@ private WorldPublishedStartLocationEvidence selectorEvidence(int digestSchemaVer
42L,
"tenant-1",
"NEW_GAME_ROW"));
- var original = base.request();
- var request =
- new WorldPublishedStartLocationEvidence.Request(
- original.targetNamespace(),
- original.canonicalTenantId(),
- original.canonicalVersionId(),
- original.intakeRequestId(),
- original.publicationFence(),
- original.publicationRequestId(),
- original.requestDigest(),
- original.versionStateEpoch(),
- original.publishWorkflowId(),
- original.appliedCommitId(),
- original.contentDigest(),
- digestSchemaVersion,
- original.worldAffectedTuples());
- return new WorldPublishedStartLocationEvidence(
- request,
- base.selectorReceiptBytes(),
- base.originalAccountBindingBytes(),
- base.appliedResultBytes());
+ return PublishedWorldSelectorFixtures.withDigestSchemaVersion(base, digestSchemaVersion);
}
private VersionDto selectorVersion() {
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java
index 79dfe15ef7..8ce625b7d7 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java
@@ -1,6 +1,7 @@
package net.firedevops.firemud.gamedesign.service.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -28,6 +29,10 @@
import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence;
import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence;
+import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient;
+import net.firedevops.firemud.gamedesign.client.EntityManagementClient;
+import net.firedevops.firemud.gamedesign.client.GameLogicClient;
+import net.firedevops.firemud.gamedesign.client.WorldManagementClient;
import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection;
import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent;
import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository;
@@ -48,6 +53,9 @@
import net.firedevops.firemud.gamedesign.model.PublishType;
import net.firedevops.firemud.gamedesign.model.VersionLifecycleState;
import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures;
+import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt;
+import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository;
+import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationDigestReadService;
import net.firedevops.firemud.gamedesign.repository.GameRepository;
import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository;
import net.firedevops.firemud.gamedesign.repository.VersionRepository;
@@ -55,6 +63,7 @@
import net.firedevops.firemud.gamedesign.service.AssetExportService;
import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService;
import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest;
+import net.firedevops.firemud.gamedesign.service.PublicationFailureClassifier;
import net.firedevops.firemud.gamedesign.service.PublishAttemptService;
import net.firedevops.firemud.gamedesign.service.PublishGateFailureException;
import net.firedevops.firemud.gamedesign.service.PublishGateService;
@@ -153,21 +162,25 @@ void setup() {
.when(publishAttemptService)
.executeFullVersionTransaction(any());
VersionMapper mapper = Mappers.getMapper(VersionMapper.class);
- service =
- new VersionPublishCommandServiceImpl(
- versionRepository,
- gameRepository,
- publishAttemptRepository,
- mapper,
- assetExportService,
- publishAttemptService,
- publishGateService,
- controlPlaneDigestService,
- versionAssetArtifactService,
- publishedReleaseBundleService,
- recordedParticipantDigestService,
- authoredSelections,
- worldProducerProvider);
+ service = commandService(mapper, publishGateService);
+ }
+
+ private VersionPublishCommandServiceImpl commandService(
+ VersionMapper mapper, PublishGateService gateService) {
+ return new VersionPublishCommandServiceImpl(
+ versionRepository,
+ gameRepository,
+ publishAttemptRepository,
+ mapper,
+ assetExportService,
+ publishAttemptService,
+ gateService,
+ controlPlaneDigestService,
+ versionAssetArtifactService,
+ publishedReleaseBundleService,
+ recordedParticipantDigestService,
+ authoredSelections,
+ worldProducerProvider);
}
@Test
@@ -921,6 +934,176 @@ void transientParticipantReadLeavesSelectedFullAttemptPending(Status.Code status
verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class));
}
+ @ParameterizedTest
+ @EnumSource(TransientCollectorFailure.class)
+ void transientSelectedCollectorObservationsLeaveAttemptPending(
+ TransientCollectorFailure transientFailure) {
+ SelectedPublishFixture fixture = selectedPublishFixture(1);
+ var worldClient = org.mockito.Mockito.mock(WorldManagementClient.class);
+ var entityClient = org.mockito.Mockito.mock(EntityManagementClient.class);
+ var gameLogicClient = org.mockito.Mockito.mock(GameLogicClient.class);
+ var automationClient = org.mockito.Mockito.mock(AutomationScriptingClient.class);
+ var selectedReceiptRepository =
+ org.mockito.Mockito.mock(SelectedDraftGameLogicReceiptRepository.class);
+ var selectedDigestReader =
+ org.mockito.Mockito.mock(SelectedDraftPublicationDigestReadService.class);
+ var binding =
+ PublicationDigestRequestBinding.full(
+ fixture.request().intent().canonicalTenantId().toString(),
+ String.valueOf(fixture.version().getId()),
+ fixture.request().publishRequestId());
+ org.mockito.ArgumentMatcher exactBinding =
+ candidate ->
+ candidate != null
+ && java.util.Arrays.equals(
+ binding.canonicalPreimage(), candidate.canonicalPreimage());
+ var selectedCommit = fixture.reservation().selection().selectedCommit().commitId().toString();
+ if (transientFailure == TransientCollectorFailure.SELECTED_SNAPSHOT_UNAVAILABLE) {
+ when(selectedDigestReader.read(
+ org.mockito.ArgumentMatchers.eq("test"),
+ org.mockito.ArgumentMatchers.argThat(exactBinding)))
+ .thenThrow(Status.UNAVAILABLE.asRuntimeException());
+ } else {
+ when(selectedDigestReader.read(
+ org.mockito.ArgumentMatchers.eq("test"),
+ org.mockito.ArgumentMatchers.argThat(exactBinding)))
+ .thenReturn(
+ new SelectedDraftPublicationDigestReadService.ReadResult(
+ binding,
+ binding.requestDigest(),
+ new DesignControlPlaneDigestDto(
+ binding.tenantId(), "10", selectedCommit, "c".repeat(64), 2),
+ new PublishParticipantDigestDto(
+ "WORLD_MANAGEMENT",
+ "10",
+ null,
+ selectedCommit,
+ "d".repeat(64),
+ 4,
+ null,
+ null,
+ null)));
+ }
+ when(entityClient.getDraftDesignDigestForVersion(
+ org.mockito.ArgumentMatchers.argThat(exactBinding)))
+ .thenReturn(
+ new PublishParticipantDigestDto(
+ "ENTITY_MANAGEMENT",
+ "10",
+ null,
+ selectedCommit,
+ "a".repeat(64),
+ 3,
+ null,
+ null,
+ null));
+ when(automationClient.getDraftDesignDigestForVersion(
+ org.mockito.ArgumentMatchers.argThat(exactBinding)))
+ .thenReturn(
+ new PublishParticipantDigestDto(
+ "AUTOMATION_SCRIPTING",
+ "10",
+ null,
+ selectedCommit,
+ "b".repeat(64),
+ 6,
+ null,
+ null,
+ null));
+ if (transientFailure == TransientCollectorFailure.GAME_LOGIC_RECEIPT_MISSING) {
+ when(selectedReceiptRepository.readForPublication(
+ org.mockito.ArgumentMatchers.argThat(exactBinding)))
+ .thenReturn(Optional.empty());
+ } else if (transientFailure
+ == TransientCollectorFailure.GAME_LOGIC_RECEIPT_STORAGE_UNAVAILABLE) {
+ when(selectedReceiptRepository.readForPublication(
+ org.mockito.ArgumentMatchers.argThat(exactBinding)))
+ .thenThrow(new org.jooq.exception.DataAccessException("database unavailable"));
+ } else {
+ var selectedReceipt = org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class);
+ when(selectedReceiptRepository.readForPublication(
+ org.mockito.ArgumentMatchers.argThat(exactBinding)))
+ .thenReturn(Optional.of(selectedReceipt));
+ when(gameLogicClient.getDraftDesignDigestForVersion(
+ org.mockito.ArgumentMatchers.argThat(exactBinding), same(selectedReceipt)))
+ .thenReturn(
+ new PublishParticipantDigestDto(
+ "GAME_LOGIC",
+ "10",
+ null,
+ selectedCommit,
+ "e".repeat(64),
+ 1,
+ "sha256:" + "f".repeat(64),
+ null,
+ null));
+ }
+ PublishGateServiceImpl realGateService =
+ new PublishGateServiceImpl(
+ controlPlaneDigestService,
+ worldClient,
+ entityClient,
+ gameLogicClient,
+ automationClient,
+ selectedReceiptRepository,
+ selectedDigestReader,
+ "test");
+ VersionMapper mapper = Mappers.getMapper(VersionMapper.class);
+ service = commandService(mapper, realGateService);
+
+ VersionDto versionDto = mapper.toDto(fixture.version());
+ List observed =
+ realGateService.collectSelectedFullVersionParticipantDigests(
+ versionDto, binding, fixture.request().publishWorkflowId());
+ if (transientFailure == TransientCollectorFailure.SELECTED_SNAPSHOT_UNAVAILABLE) {
+ assertEquals("UNAVAILABLE", observed.getFirst().errorCode());
+ assertNull(observed.getFirst().appliedCommitId());
+ assertNull(observed.getFirst().digestSchemaVersion());
+ assertEquals("UNAVAILABLE", observed.getLast().errorCode());
+ assertNull(observed.getLast().appliedCommitId());
+ assertNull(observed.getLast().digestSchemaVersion());
+ assertTrue(observed.get(2).succeeded());
+ } else {
+ assertTrue(observed.getFirst().succeeded());
+ assertEquals(selectedCommit, observed.getFirst().appliedCommitId());
+ assertEquals(4, observed.getFirst().digestSchemaVersion());
+ assertTrue(observed.getLast().succeeded());
+ assertEquals(selectedCommit, observed.getLast().appliedCommitId());
+ assertEquals(2, observed.getLast().digestSchemaVersion());
+ assertEquals(
+ transientFailure == TransientCollectorFailure.GAME_LOGIC_RECEIPT_MISSING
+ ? "PARTICIPANT_UNAVAILABLE"
+ : "UNAVAILABLE",
+ observed.get(2).errorCode());
+ assertNull(observed.get(2).appliedCommitId());
+ assertNull(observed.get(2).digestSchemaVersion());
+ }
+ PublishGateFailureException gateFailure =
+ assertThrows(
+ PublishGateFailureException.class,
+ () -> realGateService.assertSelectedGatePassed(versionDto, observed));
+ assertTrue(PublicationFailureClassifier.isRetryableParticipantDependencyFailure(gateFailure));
+
+ VersionPublishCommandServiceImpl.PendingReconciliationException thrown =
+ assertThrows(
+ VersionPublishCommandServiceImpl.PendingReconciliationException.class,
+ () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request()));
+
+ assertTrue(thrown.getMessage().contains("temporarily unavailable"));
+ assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus());
+ org.mockito.Mockito.verify(selectedDigestReader, org.mockito.Mockito.times(2))
+ .read(
+ org.mockito.ArgumentMatchers.eq("test"),
+ org.mockito.ArgumentMatchers.argThat(exactBinding));
+ verify(publishAttemptService, never())
+ .markFullVersionFailed(any(String.class), any(String.class), any(String.class));
+ verify(publishAttemptRepository, never())
+ .sealPublication(any(PublishAttempt.class), org.mockito.ArgumentMatchers.anyBoolean());
+ verify(versionAssetArtifactService, never())
+ .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class));
+ verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class));
+ }
+
@Test
void uncertainAssetExportRemainsPendingForExactRetry() {
SelectedPublishFixture fixture = selectedPublishFixture(1);
@@ -2129,7 +2312,7 @@ void privateMechanicsGateRejectionDoesNotRecordDigestsOrExportAssets() {
}
@Test
- void freshSelectedPublishRejectsLegacyOwnerVectorBeforeGateOrAssetEffects() throws Exception {
+ void freshSelectedPublishRejectsLegacyOwnerVectorBeforeAssetEffects() throws Exception {
SelectedPublishFixture fixture = selectedPublishFixture(1);
var fullVector = participantDigests();
var legacySchemas = List.of(3, 2, 1, 5, 2);
@@ -2158,8 +2341,13 @@ void freshSelectedPublishRejectsLegacyOwnerVectorBeforeGateOrAssetEffects() thro
reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request());
assertEquals("FAILED", snapshot.status());
- verify(publishGateService, never())
- .assertSelectedGatePassed(any(VersionDto.class), any(List.class));
+ assertEquals("PUBLISH_FAILED", snapshot.failureCode());
+ assertEquals(
+ "Selected-full release requires the exact 4/3/1/6/2 successful participant vector",
+ snapshot.failureMessage());
+ verify(publishGateService)
+ .assertSelectedGatePassed(
+ any(VersionDto.class), org.mockito.ArgumentMatchers.eq(legacyVector));
verify(versionAssetArtifactService, never())
.stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class));
verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class));
@@ -2169,8 +2357,8 @@ void freshSelectedPublishRejectsLegacyOwnerVectorBeforeGateOrAssetEffects() thro
@ValueSource(ints = {0, 1, 2, 3, 4})
void freshSelectedPublishRefusesEachNoncanonicalParticipantSchemaBeforeEffects(int index)
throws Exception {
- // These unit carriers are controlled; the actual contract validator must reject every
- // downgrade.
+ // These controlled unit carriers increment each participant schema, but none is the canonical
+ // selected-full schema.
SelectedPublishFixture fixture = selectedPublishFixture(1);
var vector = new java.util.ArrayList<>(participantDigests());
var original = vector.get(index);
@@ -2193,8 +2381,12 @@ void freshSelectedPublishRefusesEachNoncanonicalParticipantSchemaBeforeEffects(i
var result = reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request());
assertEquals("FAILED", result.status());
- verify(publishGateService, never())
- .assertSelectedGatePassed(any(VersionDto.class), any(List.class));
+ assertEquals("PUBLISH_FAILED", result.failureCode());
+ assertEquals(
+ "Selected-full release requires the exact 4/3/1/6/2 successful participant vector",
+ result.failureMessage());
+ verify(publishGateService)
+ .assertSelectedGatePassed(any(VersionDto.class), org.mockito.ArgumentMatchers.eq(vector));
verify(publishGateService, never()).assertGatePassed(any(VersionDto.class), any(List.class));
verify(versionAssetArtifactService, never())
.stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class));
@@ -3031,6 +3223,12 @@ private List participantDigests() {
null));
}
+ private enum TransientCollectorFailure {
+ SELECTED_SNAPSHOT_UNAVAILABLE,
+ GAME_LOGIC_RECEIPT_MISSING,
+ GAME_LOGIC_RECEIPT_STORAGE_UNAVAILABLE
+ }
+
private record SelectedPublishFixture(
SelectionSnapshot reservation,
PublishWorkflowRequest request,
diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java
index 7c3cb358c0..3edb3234d1 100644
--- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java
+++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java
@@ -214,6 +214,8 @@ public void getDraftDesignDigest(
responseObserver.onCompleted();
} catch (StatusRuntimeException ex) {
Status status = Status.fromThrowable(ex);
+ logger.warn("GetDraftDesignDigest retained source read failed: code={}", status.getCode());
+ meterRegistry.counter("grpc.app_error", "code", status.getCode().name()).increment();
responseObserver.onError(
Status.fromCode(status.getCode())
.withDescription(PUBLICATION_READ_FAILURE_DESCRIPTION)
diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java
index 1682a8db7b..3b1043f54d 100644
--- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java
+++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java
@@ -541,8 +541,15 @@ void getDraftDesignDigestReturnsSanitizedTransportStatusesWhenSourceReadFails()
GameLogicDraftDesignDigestService digestService = mockDigestService();
SessionContext.setContext(
null, List.of(), Map.of(), true, "game-design-service", "test-instance");
- GameLogicGrpcService service = newDigestService(digestService);
- for (Status.Code code : List.of(Status.Code.FAILED_PRECONDITION, Status.Code.UNAVAILABLE)) {
+ var meters = new SimpleMeterRegistry();
+ GameLogicGrpcService service = newDigestService(digestService, TEST_NAMESPACE, meters);
+ for (Status.Code code :
+ List.of(
+ Status.Code.FAILED_PRECONDITION,
+ Status.Code.UNAVAILABLE,
+ Status.Code.ALREADY_EXISTS,
+ Status.Code.INTERNAL,
+ Status.Code.UNKNOWN)) {
Mockito.reset(digestService);
Mockito.when(
digestService.getDraftDesignDigest(any(GameLogicPublicationSourceReadBinding.class)))
@@ -564,6 +571,8 @@ void getDraftDesignDigestReturnsSanitizedTransportStatusesWhenSourceReadFails()
.doesNotContain("secret", "database");
assertThat(statusFailure.getCause()).isNull();
assertThat(statusFailure.getTrailers()).isNull();
+ assertThat(meters.get("grpc.app_error").tag("code", code.name()).counter().count())
+ .isEqualTo(1.0);
}
}
@@ -642,6 +651,13 @@ private GameLogicGrpcService newDigestService(GameLogicDraftDesignDigestService
private GameLogicGrpcService newDigestService(
GameLogicDraftDesignDigestService digestService, String workloadNamespace) {
+ return newDigestService(digestService, workloadNamespace, new SimpleMeterRegistry());
+ }
+
+ private GameLogicGrpcService newDigestService(
+ GameLogicDraftDesignDigestService digestService,
+ String workloadNamespace,
+ SimpleMeterRegistry meters) {
return new GameLogicGrpcService(
new PingServiceImpl(),
new CommandServiceImpl(
@@ -653,7 +669,7 @@ private GameLogicGrpcService newDigestService(
Mockito.mock(ItemRuntimeService.class),
digestService,
mockAttestationService(),
- new SimpleMeterRegistry(),
+ meters,
workloadNamespace);
}
From 2bfc318d3fd5449f5e72a31de6b0204c80148adb Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Mon, 19 Oct 2026 22:29:15 +1300
Subject: [PATCH 41/55] Preserve retryable publication reads and reject corrupt
selections
---
.../game-logic-service/api-contracts.md | 2 +-
.../gamedesign/client/GameLogicClient.java | 11 ++-
...lectedDraftPublicationReadGrpcService.java | 13 ++-
...edDraftPublicationReadGrpcServiceTest.java | 49 +++++++++--
.../publication/GameLogicClientTest.java | 81 +++++++++++--------
5 files changed, 114 insertions(+), 42 deletions(-)
diff --git a/design/architecture/microservices/game-logic-service/api-contracts.md b/design/architecture/microservices/game-logic-service/api-contracts.md
index c96a5e8f3b..7d796d48a0 100644
--- a/design/architecture/microservices/game-logic-service/api-contracts.md
+++ b/design/architecture/microservices/game-logic-service/api-contracts.md
@@ -6,7 +6,7 @@ This document defines the Game Logic Service REST and gRPC surfaces, exposure cl
- The current Game Logic adapters still return `shared.v1.ErrorDetail` for many failures and record `grpc.app_error`; that is implementation drift and a migration/proof gap, not a second contract.
- Causal-read status is target-only: the complete `CausalReadFence` and participant-proof enforcement described below are not current behavior. The live `ResolveLook` request/proto and World/Entity adapters remain floor-free, so protobuf propagation, adapter evidence, and focused causal-floor proof are implementation gaps.
-- The prepared publish-gate adapter can read the exact retained owner terminal, selected source and manifest through `GameLogicPublicationSourceReadService`, preserving the original authorization and both manifest/ability digests. The default Spring composition and the no-receipt lookup remain denied; the standalone adapter and focused proof are unqualified and establish no genuine upstream authority or publication enablement. The canonical selected contract is owned by [Game Design Version Control](../game-design-service/version-control.md#selected-full-publication-profile), with source and composition limits in the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation).
+- The prepared publish-gate adapter can read the exact retained owner terminal, selected source and manifest through `GameLogicPublicationSourceReadService`, preserving the original authorization and both manifest/ability digests. R45 exercises this standalone adapter in the controlled selected-full owner composition; the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation) records its exact proof attribution and controlled-input limits. The default Spring composition and the no-receipt lookup remain denied, and this proof establishes no genuine upstream authority or publication enablement. The canonical selected contract is owned by [Game Design Version Control](../game-design-service/version-control.md#selected-full-publication-profile).
### Player execution context
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java
index 040bb66cc3..c4346e5a06 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java
@@ -99,8 +99,17 @@ public PublishParticipantDigestDto getDraftDesignDigestForVersion(
GameLogicPublicationSourceReadBinding expectedBinding =
new GameLogicPublicationSourceReadBinding(binding, receipt.authorization());
var request = GameLogicPublicationSourceReadGrpcCodec.toRequest(expectedBinding);
+ GameLogicServiceGrpc.GameLogicServiceBlockingStub publicationReadStub;
+ try {
+ publicationReadStub = requirePublicationReadStub();
+ } catch (IllegalStateException unavailableConfiguration) {
+ return failure(
+ versionId,
+ "PARTICIPANT_UNAVAILABLE",
+ "Game Logic publication source read is not configured");
+ }
var response =
- requirePublicationReadStub()
+ publicationReadStub
.withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS)
.getDraftDesignDigest(request);
if (response.hasError() && !response.getError().getCode().isBlank()) {
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java
index ab1a45a9c8..6d5b803a96 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java
@@ -12,6 +12,9 @@
import net.firedevops.firemud.gamedesign.v1.GameDesignSelectedDraftPublicationReadServiceGrpc;
import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationRequest;
import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationResponse;
+import org.jooq.exception.DataAccessException;
+import org.springframework.dao.DataAccessResourceFailureException;
+import org.springframework.dao.TransientDataAccessException;
/**
* Standalone, unregistered immutable selection owner read. Does not inspect mutable Version state
@@ -84,12 +87,20 @@ public void readSelectedDraftPublication(
.withDescription("Selected Draft publication read denied or unavailable")
.asRuntimeException());
return;
- } catch (RuntimeException unavailable) {
+ } catch (DataAccessException
+ | TransientDataAccessException
+ | DataAccessResourceFailureException unavailable) {
observer.onError(
Status.UNAVAILABLE
.withDescription("Game Design selection storage unavailable")
.asRuntimeException());
return;
+ } catch (RuntimeException invalid) {
+ observer.onError(
+ Status.FAILED_PRECONDITION
+ .withDescription("Retained selected Draft publication evidence is invalid")
+ .asRuntimeException());
+ return;
}
observer.onNext(response);
observer.onCompleted();
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java
index f80e35ae13..c2703bb723 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java
@@ -10,6 +10,7 @@
import com.google.protobuf.UnknownFieldSet;
import io.grpc.Context;
import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import java.time.OffsetDateTime;
import java.util.List;
@@ -173,17 +174,35 @@ void changedStoredSelectionFailsWithoutPartialBytes() {
}
@Test
- void corruptOrUnavailableStorageReturnsNoEvidence() {
+ void corruptRetainedSelectionIsDeniedAsNonRetryableWithoutLeakingEvidence() {
for (RuntimeException failure :
List.of(
new IllegalStateException("corrupt retained selection"),
- new org.jooq.exception.DataAccessException("storage unavailable"))) {
+ new IllegalArgumentException("invalid retained selection"))) {
var repository = mock(AuthoredDraftPublishSelectionRepository.class);
when(repository.read(any(), any(), any())).thenThrow(failure);
var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE);
- assertFailure(
- invokeAs(service, wireRequest(), peer("account-service", NAMESPACE)),
- Status.Code.UNAVAILABLE);
+ var result = invokeAs(service, wireRequest(), peer("account-service", NAMESPACE));
+ assertFailure(result, Status.Code.FAILED_PRECONDITION);
+ assertSanitizedFailure(result, "Retained selected Draft publication evidence is invalid");
+ }
+ }
+
+ @Test
+ void typedStorageFailuresAreUnavailableWithoutReturningEvidence() {
+ for (RuntimeException failure :
+ List.of(
+ new org.jooq.exception.DataAccessException("storage unavailable"),
+ new org.springframework.dao.TransientDataAccessResourceException(
+ "temporary storage failure"),
+ new org.springframework.dao.DataAccessResourceFailureException(
+ "storage resource unavailable"))) {
+ var repository = mock(AuthoredDraftPublishSelectionRepository.class);
+ when(repository.read(any(), any(), any())).thenThrow(failure);
+ var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE);
+ var result = invokeAs(service, wireRequest(), peer("account-service", NAMESPACE));
+ assertFailure(result, Status.Code.UNAVAILABLE);
+ assertSanitizedFailure(result, "Game Design selection storage unavailable");
}
}
@@ -205,6 +224,13 @@ private static void assertFailure(Collector collector, Status.Code expected) {
assertThat(collector.completed).isFalse();
}
+ private static void assertSanitizedFailure(Collector collector, String description) {
+ assertThat(collector.failureIsStatusRuntimeException).isTrue();
+ assertThat(collector.failureDescription).isEqualTo(description);
+ assertThat(collector.failureHasCause).isFalse();
+ assertThat(collector.failureHasTrailers).isFalse();
+ }
+
private static Collector invokeAs(
GameDesignSelectedDraftPublicationReadGrpcService service,
ReadSelectedDraftPublicationRequest request,
@@ -282,6 +308,10 @@ private static final class Collector
implements StreamObserver {
private ReadSelectedDraftPublicationResponse value;
private Status.Code errorCode;
+ private String failureDescription;
+ private boolean failureIsStatusRuntimeException;
+ private boolean failureHasCause;
+ private boolean failureHasTrailers;
private boolean completed;
@Override
@@ -291,7 +321,14 @@ public void onNext(ReadSelectedDraftPublicationResponse response) {
@Override
public void onError(Throwable failure) {
- errorCode = Status.fromThrowable(failure).getCode();
+ var status = Status.fromThrowable(failure);
+ errorCode = status.getCode();
+ failureDescription = status.getDescription();
+ failureHasCause = failure.getCause() != null;
+ if (failure instanceof StatusRuntimeException statusFailure) {
+ failureIsStatusRuntimeException = true;
+ failureHasTrailers = statusFailure.getTrailers() != null;
+ }
}
@Override
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java
index 99b580bcaa..bc5dab2a20 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java
@@ -27,6 +27,7 @@
import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding;
import net.firedevops.firemud.gamedesign.client.GameLogicClient;
+import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto;
import net.firedevops.firemud.gamelogic.v1.GameLogicServiceGrpc;
import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestRequest;
import org.junit.jupiter.api.Test;
@@ -225,69 +226,74 @@ void rejectsPublicationRequestThatDoesNotMatchTheReceiptSelection(@TempDir Path
}
@Test
- void missingWorkloadNamespaceDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException {
+ void missingWorkloadNamespaceReturnsUnavailableBeforeRpc(@TempDir Path tlsDirectory)
+ throws IOException {
var receipt = SelectedDraftGameLogicReceiptTest.fixture();
var clientAndStub = client(tlsDirectory);
ReflectionTestUtils.setField(clientAndStub.client(), "workloadNamespace", "");
- assertThatThrownBy(
- () ->
- clientAndStub
- .client()
- .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt))
- .isInstanceOf(IllegalStateException.class)
- .hasMessageContaining("configured workload namespace");
+ var result =
+ clientAndStub.client().getDraftDesignDigestForVersion(publicationBinding(receipt), receipt);
+
+ assertConfigurationUnavailable(result);
verifyNoInteractions(clientAndStub.stub());
}
@Test
- void invalidWorkloadNamespaceDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException {
+ void invalidWorkloadNamespaceReturnsUnavailableBeforeRpc(@TempDir Path tlsDirectory)
+ throws IOException {
var receipt = SelectedDraftGameLogicReceiptTest.fixture();
var clientAndStub = client(tlsDirectory);
ReflectionTestUtils.setField(clientAndStub.client(), "workloadNamespace", "Not_A_Namespace");
- assertThatThrownBy(
- () ->
- clientAndStub
- .client()
- .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt))
- .isInstanceOf(IllegalStateException.class)
- .hasMessageContaining("configured workload namespace");
+ var result =
+ clientAndStub.client().getDraftDesignDigestForVersion(publicationBinding(receipt), receipt);
+
+ assertConfigurationUnavailable(result);
verifyNoInteractions(clientAndStub.stub());
}
@Test
- void plaintextTlsConfigurationDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException {
+ void plaintextTlsConfigurationReturnsUnavailableBeforeRpc(@TempDir Path tlsDirectory)
+ throws IOException {
var receipt = SelectedDraftGameLogicReceiptTest.fixture();
var tls = new CommonGrpcClientProperties();
tls.setPlaintext(true);
var clientAndStub = client(tlsDirectory, tls);
- assertThatThrownBy(
- () ->
- clientAndStub
- .client()
- .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt))
- .isInstanceOf(IllegalStateException.class)
- .hasMessageContaining("file-backed workload mTLS");
+ var result =
+ clientAndStub.client().getDraftDesignDigestForVersion(publicationBinding(receipt), receipt);
+
+ assertConfigurationUnavailable(result);
verifyNoInteractions(clientAndStub.stub());
}
@Test
- void unreadableTlsMaterialDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException {
+ void unreadableTlsMaterialReturnsUnavailableBeforeRpc(@TempDir Path tlsDirectory)
+ throws IOException {
var receipt = SelectedDraftGameLogicReceiptTest.fixture();
var tls = fileBackedTls(tlsDirectory);
tls.setCaCert(tlsDirectory.resolve("missing-ca.crt").toString());
var clientAndStub = client(tlsDirectory, tls);
- assertThatThrownBy(
- () ->
- clientAndStub
- .client()
- .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt))
- .isInstanceOf(IllegalStateException.class)
- .hasMessageContaining("CA certificate")
- .hasMessageContaining("readable file");
+ var result =
+ clientAndStub.client().getDraftDesignDigestForVersion(publicationBinding(receipt), receipt);
+
+ assertConfigurationUnavailable(result);
+ verifyNoInteractions(clientAndStub.stub());
+ }
+
+ @Test
+ void uninitializedClientReturnsUnavailableBeforeRpc(@TempDir Path tlsDirectory)
+ throws IOException {
+ var receipt = SelectedDraftGameLogicReceiptTest.fixture();
+ var clientAndStub = client(tlsDirectory);
+ ReflectionTestUtils.setField(clientAndStub.client(), "stub", null);
+
+ var result =
+ clientAndStub.client().getDraftDesignDigestForVersion(publicationBinding(receipt), receipt);
+
+ assertConfigurationUnavailable(result);
verifyNoInteractions(clientAndStub.stub());
}
@@ -341,6 +347,15 @@ private static ClientAndStub client(Path tlsDirectory) throws IOException {
return client(tlsDirectory, fileBackedTls(tlsDirectory));
}
+ private static void assertConfigurationUnavailable(PublishParticipantDigestDto result) {
+ assertThat(result.succeeded()).isFalse();
+ assertThat(result.errorCode()).isEqualTo("PARTICIPANT_UNAVAILABLE");
+ assertThat(result.errorMessage())
+ .isEqualTo("Game Logic publication source read is not configured");
+ assertThat(result.contentDigest()).isNull();
+ assertThat(result.abilitySchemaDigest()).isNull();
+ }
+
private static ClientAndStub client(Path tlsDirectory, CommonGrpcClientProperties tls) {
var client =
new GameLogicClient(
From 0d41d7041191b3508f78b88c209a033e24b59a94 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Mon, 19 Oct 2026 22:50:58 +1300
Subject: [PATCH 42/55] Stabilize recovery race proof and unify selected
release schema checks
---
.../player-access-and-session.md | 4 ++--
...IntakeAuthorizationPostgresIntegrationTest.java | 2 +-
.../gamedesign/dto/PublishedReleaseBundleDto.java | 7 +++++--
.../StartSessionLaunchDescriptorProducer.java | 7 ++-----
...StartSessionTemplateAssociationReadService.java | 2 +-
.../PublishedReleaseBundleRepository.java | 13 +++++++------
.../impl/CompleteLaunchBindingServiceImpl.java | 4 +---
.../impl/PublishedReleaseBundleContract.java | 6 ++----
.../impl/VersionPublishCommandServiceImpl.java | 14 ++++----------
.../StartSessionLaunchDescriptorProducerTest.java | 10 +++++-----
10 files changed, 30 insertions(+), 39 deletions(-)
diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md
index 7922ea39f0..941ff14b3e 100644
--- a/design/project-management/implementation-tracking/player-access-and-session.md
+++ b/design/project-management/implementation-tracking/player-access-and-session.md
@@ -10,9 +10,9 @@ This is a non-normative implementation tracker for player access and session. Ca
This preparation is owned by [AA-1.3](#capability-status), which remains `partial` / `drift-found`. Its production and focused proof anchors are recorded in that row.
-Preliminary source reservations remain held until exact explicit abort or the prepared Account-owned expired-preliminary recovery operation commits that same immutable abort. The internal recovery entry accepts a bounded page of at most 128 candidates from its configured namespace, selects only original COMMITTED, REVOKING, or REVOKED issuances past their actual PostgreSQL expiry, and revalidates exact retained scope and issuer evidence under the canonical source-lock then reservation-lock order. Each candidate commits independently, and a candidate failure does not roll back other candidates; the returned count is not global completion or readiness. Finalized owners are excluded and remain protected until exact authenticated terminal settlement. Lost responses, unknown state or a guessed timeout do not authorize release. The operation has no transport registration, scheduler or invocation policy; those remain activation prerequisites.
+Preliminary source reservations remain held until exact explicit abort or the prepared Account-owned expired-preliminary recovery operation commits that same immutable abort. The internal recovery entry accepts a bounded page of at most 128 candidates from its configured namespace, selects only original COMMITTED, REVOKING, or REVOKED issuances past their actual PostgreSQL expiry, and revalidates exact retained scope and issuer evidence under the canonical source-lock then reservation-lock order. Each candidate commits independently, and a candidate failure does not roll back other candidates; returned page counts and cursor do not establish global completion or readiness. Finalized owners are excluded and remain protected until exact authenticated terminal settlement. Lost responses, unknown state or a guessed timeout do not authorize release. The operation has no transport registration, scheduler or invocation policy; those remain activation prerequisites.
-The focused recovery preparation passes eight unit cases at `cda9f4b0bb33265edaf3f0b32c348984472b1d14` and the one new physical PostgreSQL expiry/race case at `7ff2e65bc7fd1bd7d97f9a7034dfd65a39f8f381`, with zero failures, errors or skips in those separate scopes. Eight other native authorization/settlement cases passed in the earlier nine-case run, whose aggregate remains failed; this is not a new passing nine-case aggregate. Affected static and formatting checks pass after the fixture clock and query-alias corrections. The new case observes the real database cutoff and actual source-lock blocking: an in-flight finalization cannot commit after original expiry, abandoned preliminary reservations abort once, and an already committed finalization remains pending until exact Entity terminal settlement. Signer, issuer, source and terminal inputs remain controlled fixtures; no genuine authority, autonomous runtime recovery or activation is established. Prior failed selector, fixture and SQL attempts retain their original evidence.
+The focused recovery preparation passes eight unit cases at `cda9f4b0bb33265edaf3f0b32c348984472b1d14` and the one new physical PostgreSQL expiry/race case at `7ff2e65bc7fd1bd7d97f9a7034dfd65a39f8f381`, with zero failures, errors or skips in those separate scopes. Eight other native authorization/settlement cases passed in the earlier nine-case run, whose aggregate remains failed; this is not a new passing nine-case aggregate. A later saved native Account XML reports all 12 PostgreSQL invocations passing, including the same-expiry keyset case and the two parameterized retained-expired-issuer invocations (`REVOKING` and `REVOKED`). In that saved attempt, the two focused Account unit suites also pass all 13 cases (10 service and 3 repository). These are Account-suite attributions only: the 240.326-second Gradle attempt failed three Game Design mock tests, so no aggregate pass is claimed. Its Account source is tied to published `f9e1758af8fae53d056da9058e78f50dad1e540e` and remained unchanged through the pre-edit `2bfc318d3fd5449f5e72a31de6b0204c80148adb`; that saved proof has its own source attribution. The timeout-adjusted fixture now freshly passes all 12 PostgreSQL invocations, including the expiry/lock race, keyset continuation and both retained-issuer parameters, with zero failures, errors or skips (195.012-second Account suite on 19 October NZDT). Its enclosing 221.616-second attempt failed Game Design compilation, so it establishes no passing aggregate. All three exact logged test containers were independently absent afterward. Affected static and formatting checks pass after the fixture clock and query-alias corrections. The original expiry/race case observes the real database cutoff and actual source-lock blocking: an in-flight finalization cannot commit after original expiry, abandoned preliminary reservations abort once, and an already committed finalization remains pending until exact Entity terminal settlement. Signer, issuer, source and terminal inputs remain controlled fixtures; no genuine authority, autonomous runtime recovery or activation is established. Prior failed selector, fixture and SQL attempts retain their original evidence.
R31 freshly passes all eight Account final-authorization, exact Entity/Automation terminal-storage and retained-upgrade cases with zero skips. Account's 1,500 unit cases pass with four existing skips, Common's 811 units pass with zero skips, and World's 593 units retain the unchanged R30 pass. A real Java writer-exclusion omission exposed by R30 is corrected: the shared settlement check now includes the existing pending selected-owner reservation predicate, matching the retained SQL guard. The shared synthetic terminal codec fixture is carried at its first consumer. R35 freshly passes the successor disclosure composition at the actual V1008–V1010 repository frontier, including physical source-writer exclusion until exact reservation abort; its static, formatting and documentation checks pass. The earlier V1007-only source proof retains separate R28 attribution. Full-native PostgreSQL/Redis limits remain; controlled source, terminal and PKI inputs establish no genuine authority.
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
index 8fe433c0f0..72d173c523 100644
--- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
@@ -2694,7 +2694,7 @@ private static void awaitRecoverySourceLockWait(DSLContext dsl, int finalization
private static void awaitFinalizationCommit(CountDownLatch latch) {
try {
- if (!latch.await(30, TimeUnit.SECONDS)) {
+ if (!latch.await(90, TimeUnit.SECONDS)) {
throw new IllegalStateException("Finalization commit was not released");
}
} catch (InterruptedException interrupted) {
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java
index e3d108989f..fc8ca116e7 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java
@@ -37,14 +37,17 @@ public record PublishedReleaseBundleDto(
"Manifest schema and artifact proof must be present together");
}
artifactDigests = artifactDigests == null ? null : List.copyOf(artifactDigests);
- boolean selectedRelease =
- "v2".equals(attestationSchemaVersion) || "v4".equals(attestationSchemaVersion);
+ boolean selectedRelease = isSelectedAttestationSchema(attestationSchemaVersion);
if (selectedRelease != (worldPublishedStartLocationEvidence != null)) {
throw new IllegalArgumentException(
"Selector evidence requires bundle v2 or v4 and is mandatory for both");
}
}
+ public static boolean isSelectedAttestationSchema(String schemaVersion) {
+ return "v2".equals(schemaVersion) || "v4".equals(schemaVersion);
+ }
+
/** Original retained bundle construction shape; cannot construct a selector-bearing v2 bundle. */
public PublishedReleaseBundleDto(
Long id,
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java
index 3a2ba8e3a6..35c8cc11d8 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java
@@ -561,7 +561,8 @@ private void requireReleaseMatches(
|| !Objects.equals(release.canonicalTenantId(), exact.association().canonicalTenantId())
|| !Objects.equals(release.canonicalVersionId(), exact.association().canonicalVersionId())
|| !Objects.equals(release.publishWorkflowId(), exact.association().publishWorkflowId())
- || !isSelectedReleaseBundleSchema(release.attestationSchemaVersion())
+ || !PublishedReleaseBundleDto.isSelectedAttestationSchema(
+ release.attestationSchemaVersion())
|| !Objects.equals(
release.worldPublishedStartLocationEvidence(),
exact.worldPublishedStartLocationEvidence())
@@ -588,10 +589,6 @@ private void requireReleaseMatches(
}
}
- static boolean isSelectedReleaseBundleSchema(String schemaVersion) {
- return "v2".equals(schemaVersion) || "v4".equals(schemaVersion);
- }
-
private void lockAndReloadSelectedVersion(
Version version, UUID canonicalTenantId, UUID canonicalVersionId) {
Record row =
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java
index 1d7054b080..5ce6182007 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java
@@ -260,7 +260,7 @@ private Result readSnapshot(Request request, StartSessionPostAuthorizationExecut
.asRuntimeException());
if (!canonicalTenantId.equals(configuredRelease.canonicalTenantId())
|| !canonicalVersionId.equals(configuredRelease.canonicalVersionId())
- || !StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema(
+ || !PublishedReleaseBundleDto.isSelectedAttestationSchema(
configuredRelease.attestationSchemaVersion())) {
throw new IllegalStateException("START_SESSION_CONFIGURED_RELEASE_IDENTITY_CONFLICT");
}
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java
index 437fd8101e..d450711f7f 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java
@@ -11,6 +11,7 @@
import java.util.UUID;
import net.firedevops.firemud.common.gamedesign.CommandSource;
import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence;
+import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto;
import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle;
import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation;
import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository;
@@ -182,14 +183,14 @@ private PublishedReleaseBundle insertNewBundle(
rejectCallerIdentitySubstitution(bundle, source);
verifySelectorSource(bundle, source);
if (!"v1".equals(bundle.getAttestationSchemaVersion())
- && !"v2".equals(bundle.getAttestationSchemaVersion())
- && !"v4".equals(bundle.getAttestationSchemaVersion())) {
+ && !PublishedReleaseBundleDto.isSelectedAttestationSchema(
+ bundle.getAttestationSchemaVersion())) {
throw new IllegalArgumentException(
"Unsupported published release bundle attestation schema "
+ bundle.getAttestationSchemaVersion());
}
- if ("v2".equals(bundle.getAttestationSchemaVersion())
- || "v4".equals(bundle.getAttestationSchemaVersion())) {
+ if (PublishedReleaseBundleDto.isSelectedAttestationSchema(
+ bundle.getAttestationSchemaVersion())) {
PublishedReleaseBundle existing =
tx.selectFrom(TABLE_REF)
.where(TENANT_ID.eq(bundle.getTenantId()).and(VERSION_ID.eq(bundle.getVersionId())))
@@ -365,8 +366,8 @@ private PublishedReleaseBundle toEntity(Record record) {
private static void verifySelectorSource(PublishedReleaseBundle bundle, CanonicalSource source) {
String bytes = bundle.getWorldPublishedStartLocationEvidenceJson();
- if (!"v2".equals(bundle.getAttestationSchemaVersion())
- && !"v4".equals(bundle.getAttestationSchemaVersion())) {
+ if (!PublishedReleaseBundleDto.isSelectedAttestationSchema(
+ bundle.getAttestationSchemaVersion())) {
if (bytes != null) {
throw new IllegalArgumentException(
"Selector evidence is forbidden on historical release schemas");
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java
index 6e6e708175..261d04ae77 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java
@@ -297,9 +297,7 @@ private void requireExactBundleBinding(
|| !Objects.equals(snapshotCanonicalVersionId, bundle.canonicalVersionId())
|| !("v1".equals(bundle.attestationSchemaVersion())
&& bundle.worldPublishedStartLocationEvidence() == null
- || "v2".equals(bundle.attestationSchemaVersion())
- && bundle.worldPublishedStartLocationEvidence() != null
- || PublishedReleaseBundleContract.SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(
+ || PublishedReleaseBundleDto.isSelectedAttestationSchema(
bundle.attestationSchemaVersion())
&& bundle.worldPublishedStartLocationEvidence() != null)
|| !Objects.equals(bundle.id(), descriptor.releaseBundleId())
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java
index e17e9956de..22f925c203 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java
@@ -238,8 +238,7 @@ static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto bundle) {
* Descriptor resolution only; descriptor/v1 remains separate from the complete release carrier.
*/
static void requireSupportedSchemaForLaunchDescriptor(PublishedReleaseBundleDto bundle) {
- if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())
- || SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) {
+ if (PublishedReleaseBundleDto.isSelectedAttestationSchema(bundle.attestationSchemaVersion())) {
requireSupportedSchemaForLaunch(bundle);
return;
}
@@ -248,8 +247,7 @@ static void requireSupportedSchemaForLaunchDescriptor(PublishedReleaseBundleDto
static void requireExactRepairMatch(
PublishedReleaseBundleDto bundle, ExportedAssetManifest exportedManifest) {
- if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())
- || SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) {
+ if (PublishedReleaseBundleDto.isSelectedAttestationSchema(bundle.attestationSchemaVersion())) {
requireSupportedSchemaForPublicationRead(bundle);
} else {
requireSupportedSchemaForRead(bundle);
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java
index d2240ce0de..fe5dfbb52d 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java
@@ -659,7 +659,8 @@ private void assertCommittedBundleEvidence(
VersionDto versionDto = versionMapper.toDto(readback.version());
PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(readback.bundle());
assertSelectedCommit(request, readback.bundle().participantDigests());
- if (isSelectedReleaseBundle(readback.bundle())) {
+ if (PublishedReleaseBundleDto.isSelectedAttestationSchema(
+ readback.bundle().attestationSchemaVersion())) {
publishGateService.assertSelectedGatePassed(
versionDto, readback.bundle().participantDigests());
} else {
@@ -951,7 +952,7 @@ private void requireExactBundleEvidence(
if (!Objects.equals(version.getTenantId(), bundle.tenantId())
|| version.getVersionNumber() != bundle.versionNumber()
|| version.isScriptOnly()
- || (isSelectedReleaseBundle(bundle)
+ || (PublishedReleaseBundleDto.isSelectedAttestationSchema(bundle.attestationSchemaVersion())
&& (!Objects.equals(version.getCanonicalTenantId(), bundle.canonicalTenantId())
|| !Objects.equals(
version.getCanonicalVersionId(), bundle.canonicalVersionId())))) {
@@ -969,19 +970,12 @@ private void requireExactCommittedBundleIdentity(
|| bundle.scriptPatchVersion() != null) {
throw new IllegalStateException("PUBLISH_ATTEMPT_BUNDLE_SCOPE_MISMATCH");
}
- if (isSelectedReleaseBundle(bundle)) {
+ if (PublishedReleaseBundleDto.isSelectedAttestationSchema(bundle.attestationSchemaVersion())) {
PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(bundle);
requireExactSelectedWorldEvidence(request, bundle);
}
}
- private boolean isSelectedReleaseBundle(PublishedReleaseBundleDto bundle) {
- return PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(
- bundle.attestationSchemaVersion())
- || PublishedReleaseBundleContract.SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(
- bundle.attestationSchemaVersion());
- }
-
private void requireExactSelectedWorldEvidence(
PublishWorkflowRequest request, PublishedReleaseBundleDto bundle) {
// The stored owner payload is historical readback. It does not reconstruct a missing current
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java
index 2428fddb7d..8304f5ca9e 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java
@@ -69,11 +69,11 @@ class StartSessionLaunchDescriptorProducerTest {
@Test
void selectedReleaseMatchingRetainsV2AndAcceptsOnlyFullV4() {
- assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v2")).isTrue();
- assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v4")).isTrue();
- assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v1")).isFalse();
- assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema("v3")).isFalse();
- assertThat(StartSessionLaunchDescriptorProducer.isSelectedReleaseBundleSchema(null)).isFalse();
+ assertThat(PublishedReleaseBundleDto.isSelectedAttestationSchema("v2")).isTrue();
+ assertThat(PublishedReleaseBundleDto.isSelectedAttestationSchema("v4")).isTrue();
+ assertThat(PublishedReleaseBundleDto.isSelectedAttestationSchema("v1")).isFalse();
+ assertThat(PublishedReleaseBundleDto.isSelectedAttestationSchema("v3")).isFalse();
+ assertThat(PublishedReleaseBundleDto.isSelectedAttestationSchema(null)).isFalse();
}
@Test
From 857360e2257d1a0e930d0b3239fd1a786da08592 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Mon, 19 Oct 2026 23:24:25 +1300
Subject: [PATCH 43/55] Isolate selected-full World digest refusal in bundle
test
---
.../service/impl/PublishedReleaseBundleServiceImplTest.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
index 7d23db3d44..8c163a4ee1 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java
@@ -205,7 +205,7 @@ void selectedFullV4RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChanged
null,
world.appliedCommitId(),
"e".repeat(64),
- 3,
+ world.digestSchemaVersion(),
null,
null,
null));
From 7f46a25139867e3bb76ced8a0878c25d4f973efd Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Mon, 19 Oct 2026 23:40:43 +1300
Subject: [PATCH 44/55] Record retained-history recovery query qualification
gap
---
.../implementation-tracking/player-access-and-session.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md
index 941ff14b3e..0e80e3787f 100644
--- a/design/project-management/implementation-tracking/player-access-and-session.md
+++ b/design/project-management/implementation-tracking/player-access-and-session.md
@@ -12,6 +12,8 @@ This preparation is owned by [AA-1.3](#capability-status), which remains `partia
Preliminary source reservations remain held until exact explicit abort or the prepared Account-owned expired-preliminary recovery operation commits that same immutable abort. The internal recovery entry accepts a bounded page of at most 128 candidates from its configured namespace, selects only original COMMITTED, REVOKING, or REVOKED issuances past their actual PostgreSQL expiry, and revalidates exact retained scope and issuer evidence under the canonical source-lock then reservation-lock order. Each candidate commits independently, and a candidate failure does not roll back other candidates; returned page counts and cursor do not establish global completion or readiness. Finalized owners are excluded and remain protected until exact authenticated terminal settlement. Lost responses, unknown state or a guessed timeout do not authorize release. The operation has no transport registration, scheduler or invocation policy; those remain activation prerequisites.
+The query's 128-row limit bounds the returned raw candidate page, but does not establish bounded scan, decode or sort work as retained history grows: it decodes namespace from stored scope frames and joins retained issuer expiry data before ordering across the join. No EXPLAIN, scaled benchmark or index-backed cost proof was run, so retained-history operational cost and query-plan qualification remain open. Reconsider that qualification when this currently unregistered recovery operation receives authorized scheduling or production invocation. Account retention and runtime/data architecture own any future design; no SQL, schema, index, retention or invocation-policy change is recorded here.
+
The focused recovery preparation passes eight unit cases at `cda9f4b0bb33265edaf3f0b32c348984472b1d14` and the one new physical PostgreSQL expiry/race case at `7ff2e65bc7fd1bd7d97f9a7034dfd65a39f8f381`, with zero failures, errors or skips in those separate scopes. Eight other native authorization/settlement cases passed in the earlier nine-case run, whose aggregate remains failed; this is not a new passing nine-case aggregate. A later saved native Account XML reports all 12 PostgreSQL invocations passing, including the same-expiry keyset case and the two parameterized retained-expired-issuer invocations (`REVOKING` and `REVOKED`). In that saved attempt, the two focused Account unit suites also pass all 13 cases (10 service and 3 repository). These are Account-suite attributions only: the 240.326-second Gradle attempt failed three Game Design mock tests, so no aggregate pass is claimed. Its Account source is tied to published `f9e1758af8fae53d056da9058e78f50dad1e540e` and remained unchanged through the pre-edit `2bfc318d3fd5449f5e72a31de6b0204c80148adb`; that saved proof has its own source attribution. The timeout-adjusted fixture now freshly passes all 12 PostgreSQL invocations, including the expiry/lock race, keyset continuation and both retained-issuer parameters, with zero failures, errors or skips (195.012-second Account suite on 19 October NZDT). Its enclosing 221.616-second attempt failed Game Design compilation, so it establishes no passing aggregate. All three exact logged test containers were independently absent afterward. Affected static and formatting checks pass after the fixture clock and query-alias corrections. The original expiry/race case observes the real database cutoff and actual source-lock blocking: an in-flight finalization cannot commit after original expiry, abandoned preliminary reservations abort once, and an already committed finalization remains pending until exact Entity terminal settlement. Signer, issuer, source and terminal inputs remain controlled fixtures; no genuine authority, autonomous runtime recovery or activation is established. Prior failed selector, fixture and SQL attempts retain their original evidence.
R31 freshly passes all eight Account final-authorization, exact Entity/Automation terminal-storage and retained-upgrade cases with zero skips. Account's 1,500 unit cases pass with four existing skips, Common's 811 units pass with zero skips, and World's 593 units retain the unchanged R30 pass. A real Java writer-exclusion omission exposed by R30 is corrected: the shared settlement check now includes the existing pending selected-owner reservation predicate, matching the retained SQL guard. The shared synthetic terminal codec fixture is carried at its first consumer. R35 freshly passes the successor disclosure composition at the actual V1008–V1010 repository frontier, including physical source-writer exclusion until exact reservation abort; its static, formatting and documentation checks pass. The earlier V1007-only source proof retains separate R28 attribution. Full-native PostgreSQL/Redis limits remain; controlled source, terminal and PKI inputs establish no genuine authority.
From 3c2ae336010a3de2a66e5a401db5f3a8474ef3de Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Mon, 19 Oct 2026 23:54:51 +1300
Subject: [PATCH 45/55] Qualify retained publication replay with real gate
assertions
---
.../VersionPublishCommandServiceImplTest.java | 62 ++++++++++++++++++-
1 file changed, 61 insertions(+), 1 deletion(-)
diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java
index 8ce625b7d7..456a02f454 100644
--- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java
+++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java
@@ -428,6 +428,7 @@ void succeededReplayUsesStoredBundleAfterLifecycleDriftWithoutWritesOrGates() {
void selectedSucceededReplayRevalidatesExactTerminalEvidenceWithoutWriting(
VersionLifecycleState lifecycleState) throws Exception {
SelectedSucceededReplayFixture fixture = selectedSucceededReplayFixture(lifecycleState);
+ delegateGateAssertionsToRealGate();
PublishWorkflowSnapshot snapshot = service.reconcileFullVersionPublish(fixture.request());
@@ -1573,13 +1574,14 @@ private void assertSelectedStagedArtifactRemainsPartial(
@Test
void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() {
SelectedPublishFixture fixture = selectedPublishFixture(1);
+ delegateGateAssertionsToRealGate();
PublishWorkflowRequest request = fixture.request();
String workflowId = request.publishWorkflowId();
PublishAttempt attempt = fixture.attempt();
Version version = fixture.version();
version.setVersionState(VersionLifecycleState.PUBLISHED);
version.setVersionStateEpoch(2L);
- List participantDigests = participantDigests();
+ List participantDigests = legacyParticipantDigests();
PublishedReleaseBundleDto bundle =
publishedReleaseBundleDto(
1L,
@@ -2465,6 +2467,7 @@ void privateMechanicsPreservesSharedAssetsWhenAttestationWriteIsUncertain() {
@Test
void privateMechanicsReconcilesPendingAttemptThroughCurrentGates() throws Exception {
SelectedPublishFixture fixture = selectedPublishFixture(1);
+ delegateGateAssertionsToRealGate();
SelectionSnapshot seedReservation = fixture.reservation();
AuthoredDraftPublishSelection seedSelection = seedReservation.selection();
DraftCommitBinding seedCommit = seedSelection.selectedCommit();
@@ -3223,6 +3226,63 @@ private List participantDigests() {
null));
}
+ private List legacyParticipantDigests() {
+ String appliedCommitId = selectedIntent().selectedCommitId().toString();
+ return List.of(
+ new PublishParticipantDigestDto(
+ "WORLD_MANAGEMENT", "10", null, appliedCommitId, "a".repeat(64), 3, null, null, null),
+ new PublishParticipantDigestDto(
+ "ENTITY_MANAGEMENT", "10", null, appliedCommitId, "b".repeat(64), 1, null, null, null),
+ new PublishParticipantDigestDto(
+ "GAME_LOGIC", "10", null, appliedCommitId, "c".repeat(64), 1, null, null, null),
+ new PublishParticipantDigestDto(
+ "AUTOMATION_SCRIPTING",
+ "10",
+ null,
+ appliedCommitId,
+ "e".repeat(64),
+ 5,
+ null,
+ null,
+ null),
+ new PublishParticipantDigestDto(
+ "GAME_DESIGN_CONTROL_PLANE",
+ "10",
+ null,
+ appliedCommitId,
+ "f".repeat(64),
+ 1,
+ null,
+ null,
+ null));
+ }
+
+ private void delegateGateAssertionsToRealGate() {
+ PublishGateServiceImpl realGate =
+ new PublishGateServiceImpl(
+ controlPlaneDigestService,
+ org.mockito.Mockito.mock(WorldManagementClient.class),
+ org.mockito.Mockito.mock(EntityManagementClient.class),
+ org.mockito.Mockito.mock(GameLogicClient.class),
+ org.mockito.Mockito.mock(AutomationScriptingClient.class),
+ org.mockito.Mockito.mock(SelectedDraftGameLogicReceiptRepository.class));
+ org.mockito.Mockito.doAnswer(
+ invocation -> {
+ realGate.assertSelectedGatePassed(
+ invocation.getArgument(0), invocation.getArgument(1));
+ return null;
+ })
+ .when(publishGateService)
+ .assertSelectedGatePassed(any(VersionDto.class), any(List.class));
+ org.mockito.Mockito.doAnswer(
+ invocation -> {
+ realGate.assertGatePassed(invocation.getArgument(0), invocation.getArgument(1));
+ return null;
+ })
+ .when(publishGateService)
+ .assertGatePassed(any(VersionDto.class), any(List.class));
+ }
+
private enum TransientCollectorFailure {
SELECTED_SNAPSHOT_UNAVAILABLE,
GAME_LOGIC_RECEIPT_MISSING,
From a575d7584ebbe10f0472facaa8f9ea1f8036dff9 Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Tue, 20 Oct 2026 06:23:18 +1300
Subject: [PATCH 46/55] Fix selected publication receipt recovery and proof
cleanup
---
design/project-management/ai-observations.md | 12 +-
...ame-authoring-publishing-and-activation.md | 4 +-
.../service/impl/PublishGateServiceImpl.java | 3 +-
...nerPublicationPostgresIntegrationTest.java | 168 +++++++++++++++++-
.../impl/PublishGateServiceImplTest.java | 21 +++
5 files changed, 196 insertions(+), 12 deletions(-)
diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md
index 2c4b27d984..8481591537 100644
--- a/design/project-management/ai-observations.md
+++ b/design/project-management/ai-observations.md
@@ -145,7 +145,11 @@ Entry format:
- Observation: The global-ID update rewrote a retained row's tenant before returning it under the supplied tenant; tenant-filtered readback did not protect the original row. The native counterexample changed the complete row and `xmin`, while the restored exact tenant predicate preserves both owner rows and their versions.
- Expected pattern: Test controlled pre-phase rows as well as later guarded owners. Keep the create-only ID refusal before mapper/repository access, and separate this owner-local SQL proof from authenticated creator or hosted-content readiness.
-- `2026-10-16`: Check existing successor repairs before reworking a failed fixture. While fixing the three #3251 publication transaction failures, two focused local gates failed before the worker noticed that the already-reconciled #2967 tree contained the complete selected-full schema-4 fixture repair. The first attempts corrected stale collector stubs but missed the dependent fixture profile. Compare the bounded failing test and its called helpers against known receiving successors before changing or rerunning it; reuse the complete canonical repair without removing assertions. The exact four-path backport at `4265a81f008d0dbd343cd9adf6413bd3ac5c8904` then passed 66 unit and 10 native cases. The failed attempts retain their original outcomes; this lesson does not establish a general infrastructure cause.
+- `2026-10-16`: Check existing successor repairs before reworking a failed fixture.
+ - Context: While fixing the three #3251 publication transaction failures, two focused local gates failed before the worker noticed that the already-reconciled #2967 tree contained the complete selected-full schema-4 fixture repair.
+ - Observation: The first attempts corrected stale collector stubs but missed the dependent fixture profile.
+ - Expected pattern: Compare the bounded failing test and its called helpers against known receiving successors before changing or rerunning it; reuse the complete canonical repair without removing assertions.
+ - Outcome: The exact four-path backport at `4265a81f008d0dbd343cd9adf6413bd3ac5c8904` then passed 66 unit and 10 native cases. The failed attempts retain their original outcomes; this lesson does not establish a general infrastructure cause.
- `2026-10-16`: Derive focused Gradle selectors from declared Java packages
- Context: a Gameplay capture proof supplied `integration.net...` as the selector, and Gradle executed no tests before failing discovery.
@@ -255,7 +259,11 @@ Entry format:
- Expected pattern: Preserve the immutable capture and original attempt identity, report the recording gap, and use an explicitly bounded canonical recovery before adjudication and finalization. Do not rerun a completed review, invent credit, or use an unrelated schema migration to repair its record.
- Status and reconsideration: Overseer owns bounded recovery in #3271; no live recovery or migration is authorized yet. The exact persistence cause remains unconfirmed. Revisit after that maintenance change is qualified and promoted and the original capture is recovered through its exact native command.
-- 2026-10-15: Selected-full digest fixture R41/R42 produced different fixed-golden values from otherwise unchanged source. The fixture serialized `Map.of` payloads into strings inside a canonical binding; outer canonicalization preserves string contents and therefore does not normalize the inner map order. Restored explicit RFC 8785 normalization of each fixture payload before binding creation. Updating a golden from one failing run alone did not establish a stable vector; retain equality/mutation checks and verify the normalized vector before claiming deterministic proof. No production digest or retained bytes were changed. R44 and the fresh R45 JVM agree on the normalized vector; all 686 GDS unit cases pass in R45.
+- `2026-10-15`: Normalize nested fixture payloads before computing a digest golden
+ - Context: Selected-full digest fixture R41/R42 produced different fixed-golden values from otherwise unchanged source.
+ - Observation: The fixture serialized `Map.of` payloads into strings inside a canonical binding; outer canonicalization preserves string contents and therefore does not normalize the inner map order.
+ - Expected pattern: Restored explicit RFC 8785 normalization of each fixture payload before binding creation. Updating a golden from one failing run alone did not establish a stable vector; retain equality/mutation checks and verify the normalized vector before claiming deterministic proof.
+ - Outcome: No production digest or retained bytes were changed. R44 and the fresh R45 JVM agree on the normalized vector; all 686 GDS unit cases pass in R45.
- `2026-10-19`: Independent maintenance temporarily becomes the product queue's parent
- Context: Controller recovery maintenance PR #3271 was inserted before the existing product front to obtain the next admissible shared review slot.
diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
index 098af02e10..2ef63357ff 100644
--- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
+++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md
@@ -8,7 +8,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a
### Selected Entity and Automation intake prerequisite
-The Entity and Automation owner-local empty selected-source intake commands, terminal and digest primitives, shared codecs and security clients remain source-prepared, standalone, unregistered and default-denied. Exact namespace, workload, current Account and World binding guards remain part of the owner boundary. This work grants no fresh public publication, finalizer registration, continuous protection, genuine issuer or creator authority, admission or activation. Selected-full Game Design and Game Logic publication composition and five-store proof remain downstream in the existing 3251 closure. Canonical behavior remains in the [Entity contract](../../architecture/microservices/entity-management-service/api-contracts.md), [Automation contract](../../architecture/microservices/automation-scripting-service/api-contracts.md) and [Game Design selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile).
+The Entity and Automation owner-local empty selected-source intake commands, terminal and digest primitives, shared codecs and security clients remain source-prepared, standalone, unregistered and default-denied. Exact namespace, workload, current Account and World binding guards remain part of the owner boundary. This work grants no fresh public publication, finalizer registration, continuous protection, genuine issuer or creator authority, admission or activation. Controlled selected-full Game Design and Game Logic publication composition and its five-store proof are recorded in [Selected-full owner publication preparation](#selected-full-owner-publication-preparation), with their source attribution and authority limits. Canonical behavior remains in the [Entity contract](../../architecture/microservices/entity-management-service/api-contracts.md), [Automation contract](../../architecture/microservices/automation-scripting-service/api-contracts.md) and [Game Design selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile).
At source `f9e3f879d137b9a6fa54085e9c0b797586636a00`, the focused gate passed 1,105 cases across 224 suites (Gradle reported 4m 22s): 915 Common, 184 Common Security, five `EntityRetainedAuthoredActorCoreSourceService` cases, and one physical `AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest` case. There were zero failures, errors or skips. Common and Common Security full checks passed, along with affected style and documentation checks. This qualifies only these recorded scopes; it is not a fresh whole-service Entity or Automation rerun. The shared selected-source digest helper was introduced at `fdcc676597d33a154c92967baf33ad540387ddf8`, after this `f9e3f879d137b9a6fa54085e9c0b797586636a00` source checkpoint; its later current-source executions are attributed below, not to this gate.
@@ -308,7 +308,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora
| `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and the owner-local typed generation mutation algorithm; registered typed generation ingress, LLM-assisted authoring, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and owner-local typed generation mutation tests exist, but registered typed generation ingress, destructive plan protocol, staging bounds, and large-grid proof remain incomplete. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. |
| `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, design-time script-patch publication, and bounded local activation-preflight/control-plane seams; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. |
| `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `proven` only for controlled-input ordinary asset-source creation and synchronized projection, with focused proof in `GameDesignSourcePostgresIntegrationTest` and `VersionAssetExportSnapshotIntegrationTest`; production authoring ingress and the full publication workflow, durable object-store proof, purge, and runtime delivery remain absent or unproved. Earlier frozen-origin, snapshot-integrity, candidate export/readback, and release-v2 selector migration proof retains its exact historical attribution below. | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [VersionAssetExportCandidateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java); [VersionAssetPublicationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [PublishedReleaseBundleContract.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql); [V35.2 canonical release version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V37 mapping and export snapshot](../../../services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql); [V38 published asset digest evidence](../../../services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql); [V49 published-world selector evidence](../../../services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql); [V49.1 selected-world release participant schema](../../../services/game-design-service/src/main/resources/db/migration/V49.1__selected_world_release_participant_schema.sql); [V50 frozen candidate origin](../../../services/game-design-service/src/main/resources/db/migration/V50__freeze_asset_export_candidate_public_origin.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [AssetSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java); [GameDesignSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java); [V1003 ordinary asset source](../../../services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql); [V1024 asset-bound reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.sql) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetExportCandidateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [PublishedReleaseBundleContractTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [PublishedWorldSelectorSchemaMigrationIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [VersionAssetExportSnapshotIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the current source includes Draft `version_asset` mappings, a durable version-scoped export snapshot with independent readback, candidate export/readback, and immutable v1 bundle storage with canonical identity, opaque reference, manifest-schema metadata, and artifact digests. Release-v2 selector binding is enforced by `PublishedReleaseBundleContract.requireSelectorBinding`; current pinned-source physical proof covers V49 and V49.1, the frozen V50 candidate origin, and database-computed snapshot hash/length verification. Normal export consumes the frozen snapshot and records candidate manifest/artifact digest evidence before object writes; published repair independently reads the immutable candidate and checks it against the exact release bundle before object writes. Production authoring ingress remains absent, so public and registered Temporal full-version ingress fails closed before mutation. Complete Draft quota admission, unbounded whole-selection hash work, durable object-store candidate isolation, integrated lifecycle migration closure, global publication/purge fencing, destructive lifecycle safety, complete creator UX, approved external delivery, and runtime launch readiness remain incomplete or unproved. Ordinary asset-source creation and synchronized projection are owned by `AssetSourceRepository` and `GameDesignSourceRepository`; direct `associateDraftAsset` fails closed. Migration V1003 establishes ordinary asset source storage and V1024 binds reviewed-base evidence to its asset. |
-| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` for focused immutable-source unit/static boundaries and the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. Historical published source proof checkpoint `9bf78e22f742c3830821c920e70570eb1bc03e2b`: Validation `38354137185` (source job `115153084495`) physically executed 473 unit and 109 physical PostgreSQL cases with zero skips. The local primary log `gameplay3120-cli4-full-gds-proof.log` covers 05:45:24–05:49:53; after the nullable-query assertion fixes, `gameplay3120-cli4-final-affected-proof.log` records 27 affected physical PostgreSQL cases with zero skips at 05:52–05:54. Formatting/fullCheck, Checkstyle, and all three SpotBugs tasks passed on those matching postimages. The combined local proof described above covers the V50.15 owner-list guard and exact publication-terminal denial assertions; current-head source Validation `38361682862` (job `115177242916`) independently confirms all 476 unit and 114 physical PostgreSQL cases pass without skips on published `3e8126217206419bc379497988884739a8e1fda0`. This checkpoint does not claim new-head CI, packaged-runtime, full-workflow, or runtime-activation completion. The bounded Entity/Automation selected-source intake and terminal-read slice has focused source/storage/transport proof at `f9e3f879d137b9a6fa54085e9c0b797586636a00`. The shared selected-source digest helper was introduced at `fdcc676597d33a154c92967baf33ad540387ddf8`; it is absent at `f9e3f879d137b9a6fa54085e9c0b797586636a00` and present at the later `a5d501ca95f30a6dd86fc7a24290d443fb75fba4` Entity checkpoint. The current-source Entity execution at `17c82ab6462868a2f66dfe8a3cbc737bdd013383` passed 44 cases across seven suites in 67.986 seconds with zero failures, errors, or skips. Its 11-case physical PostgreSQL `EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest` included `selectedEmptyPublicationReaderResolvesOnlyTheValidatedReceiptForTenantAndGameDesignRow`; that test calls the Entity digest reader and compares the returned digest with an independently framed expected value. This was a focused gate, not a fresh whole-service Entity run. Separately, the exact-source Automation gate at `f2d3142214654736c224cb02f817d33f751b744d` passed 33 cases across eight suites in 75.453 seconds with zero failures, errors, or skips: 20 unit cases, nine physical PostgreSQL repository cases, three mocked service-integration cases, and one actual terminal-read mTLS/PostgreSQL case. The six-case physical PostgreSQL `AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest` included `selectedEmptyPublicationReaderUsesTheRetainedTargetProofAndReturnsSchemaSixDigest`. The earlier Entity attribution at `a5d501ca95f30a6dd86fc7a24290d443fb75fba4` remains a separate historical checkpoint and is not part of the Automation aggregate. The Entity digest receiver unit result belongs to initial `e2c38ec63dc3664877ee0f7c8fb62ef6574777ce`: 917 Common, 187 Common Security, and 23 Entity unit cases passed on unchanged postimages, but that aggregate failed at test compilation. The receiver result does not establish a fresh whole-service aggregate. The slice remains standalone and unregistered; this proof does not establish complete owner publication, registration, or runtime activation. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [Entity selected-source contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Automation selected-source contracts](../../architecture/microservices/automation-scripting-service/api-contracts.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) ; [CommandSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java); [RealmPolicySourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java); [RealmPolicyPublicationGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java); [GameDesignPublicationOperationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java); [GameDesignReviewedBaseRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java); [V50.1 Draft coordination](../../../services/game-design-service/src/main/resources/db/migration/V50.1__durable_draft_commit_coordination.sql); [V50.2 authored selection](../../../services/game-design-service/src/main/resources/db/migration/V50.2__authored_draft_publish_selection.sql); [V50.6 terminal seal](../../../services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql); [V50.8 realm-policy source](../../../services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql); [V50.9 policy publication evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql); [V50.10 command source](../../../services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql); [V50.11 reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql); [V50.12 policy head transitions](../../../services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql); [V50.13 stable publication release-row receipt evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.13__stable_publication_release_row_evidence.sql); [V50.14 Draft visibility and realm-policy source-head guards](../../../services/game-design-service/src/main/resources/db/migration/V50.14__draft_visibility_and_realm_policy_source_insert_guards.sql) ; [V50.15 required-owner binding guards](../../../services/game-design-service/src/main/resources/db/migration/V50.15__draft_commit_required_owner_guards.sql); [V50.16 reviewed source-application guards](../../../services/game-design-service/src/main/resources/db/migration/V50.16__reviewed_source_application_guards.sql); [AssetSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java); [GameDesignSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java); [V1003 ordinary asset source](../../../services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql); [V1024 asset-bound reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.sql); [EntityEmptySelectedSourceIntakeService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java); [EntityEmptySelectedSourceIntakeTerminalReadService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java); [EntitySelectedEmptyPublicationDigestService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java); [AutomationEmptySelectedSourceIntakeService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java); [AutomationEmptySelectedSourceIntakeTerminalReadService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java); [AutomationSelectedEmptyPublicationDigestService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) ; [RealmPolicyPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java); [RealmPolicySourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [CommandSourceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java); [RealmPolicyPublicationGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java); [VersionAssetExportSnapshotIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java); [EntityRetainedAuthoredActorCoreSourceServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceServiceTest.java); [AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java](../../../services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java); [EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java); [AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java); [EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java); [AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java](../../../services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial immutable command/realm-policy source, reviewed-base and terminal-seal capability with focused unit/static proof; Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Participant tokens remain synthetic; World emits digest schema 3, and the full-Version gate requires schema 3. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. |
+| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` for focused immutable-source unit/static boundaries and the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; controlled five-store selected-full qualification commits the v4 bundle with the exact 4/3/1/6/2 participant vector and proves immutable readback/retry, as recorded above; public fresh/PENDING full-version publication and legacy bundle creation remain refused; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. Historical published source proof checkpoint `9bf78e22f742c3830821c920e70570eb1bc03e2b`: Validation `38354137185` (source job `115153084495`) physically executed 473 unit and 109 physical PostgreSQL cases with zero skips. The local primary log `gameplay3120-cli4-full-gds-proof.log` covers 05:45:24–05:49:53; after the nullable-query assertion fixes, `gameplay3120-cli4-final-affected-proof.log` records 27 affected physical PostgreSQL cases with zero skips at 05:52–05:54. Formatting/fullCheck, Checkstyle, and all three SpotBugs tasks passed on those matching postimages. The combined local proof described above covers the V50.15 owner-list guard and exact publication-terminal denial assertions; current-head source Validation `38361682862` (job `115177242916`) independently confirms all 476 unit and 114 physical PostgreSQL cases pass without skips on published `3e8126217206419bc379497988884739a8e1fda0`. This checkpoint does not claim new-head CI, packaged-runtime, full-workflow, or runtime-activation completion. The bounded Entity/Automation selected-source intake and terminal-read slice has focused source/storage/transport proof at `f9e3f879d137b9a6fa54085e9c0b797586636a00`. The shared selected-source digest helper was introduced at `fdcc676597d33a154c92967baf33ad540387ddf8`; it is absent at `f9e3f879d137b9a6fa54085e9c0b797586636a00` and present at the later `a5d501ca95f30a6dd86fc7a24290d443fb75fba4` Entity checkpoint. The current-source Entity execution at `17c82ab6462868a2f66dfe8a3cbc737bdd013383` passed 44 cases across seven suites in 67.986 seconds with zero failures, errors, or skips. Its 11-case physical PostgreSQL `EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest` included `selectedEmptyPublicationReaderResolvesOnlyTheValidatedReceiptForTenantAndGameDesignRow`; that test calls the Entity digest reader and compares the returned digest with an independently framed expected value. This was a focused gate, not a fresh whole-service Entity run. Separately, the exact-source Automation gate at `f2d3142214654736c224cb02f817d33f751b744d` passed 33 cases across eight suites in 75.453 seconds with zero failures, errors, or skips: 20 unit cases, nine physical PostgreSQL repository cases, three mocked service-integration cases, and one actual terminal-read mTLS/PostgreSQL case. The six-case physical PostgreSQL `AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest` included `selectedEmptyPublicationReaderUsesTheRetainedTargetProofAndReturnsSchemaSixDigest`. The earlier Entity attribution at `a5d501ca95f30a6dd86fc7a24290d443fb75fba4` remains a separate historical checkpoint and is not part of the Automation aggregate. The Entity digest receiver unit result belongs to initial `e2c38ec63dc3664877ee0f7c8fb62ef6574777ce`: 917 Common, 187 Common Security, and 23 Entity unit cases passed on unchanged postimages, but that aggregate failed at test compilation. The receiver result does not establish a fresh whole-service aggregate. The slice remains standalone and unregistered; this proof does not establish complete owner publication, registration, or runtime activation. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [Entity selected-source contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Automation selected-source contracts](../../architecture/microservices/automation-scripting-service/api-contracts.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) ; [CommandSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java); [RealmPolicySourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java); [RealmPolicyPublicationGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java); [GameDesignPublicationOperationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java); [GameDesignReviewedBaseRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java); [V50.1 Draft coordination](../../../services/game-design-service/src/main/resources/db/migration/V50.1__durable_draft_commit_coordination.sql); [V50.2 authored selection](../../../services/game-design-service/src/main/resources/db/migration/V50.2__authored_draft_publish_selection.sql); [V50.6 terminal seal](../../../services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql); [V50.8 realm-policy source](../../../services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql); [V50.9 policy publication evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql); [V50.10 command source](../../../services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql); [V50.11 reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql); [V50.12 policy head transitions](../../../services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql); [V50.13 stable publication release-row receipt evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.13__stable_publication_release_row_evidence.sql); [V50.14 Draft visibility and realm-policy source-head guards](../../../services/game-design-service/src/main/resources/db/migration/V50.14__draft_visibility_and_realm_policy_source_insert_guards.sql) ; [V50.15 required-owner binding guards](../../../services/game-design-service/src/main/resources/db/migration/V50.15__draft_commit_required_owner_guards.sql); [V50.16 reviewed source-application guards](../../../services/game-design-service/src/main/resources/db/migration/V50.16__reviewed_source_application_guards.sql); [AssetSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java); [GameDesignSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java); [V1003 ordinary asset source](../../../services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql); [V1024 asset-bound reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.sql); [EntityEmptySelectedSourceIntakeService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java); [EntityEmptySelectedSourceIntakeTerminalReadService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java); [EntitySelectedEmptyPublicationDigestService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java); [AutomationEmptySelectedSourceIntakeService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java); [AutomationEmptySelectedSourceIntakeTerminalReadService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java); [AutomationSelectedEmptyPublicationDigestService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java); [PublishedReleaseBundleContract.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) ; [RealmPolicyPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java); [RealmPolicySourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [CommandSourceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java); [RealmPolicyPublicationGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java); [VersionAssetExportSnapshotIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java); [EntityRetainedAuthoredActorCoreSourceServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceServiceTest.java); [AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java](../../../services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java); [EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java); [AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java); [EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java); [AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java](../../../services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java); [SelectedFullOwnerPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java); [PublishedReleaseBundleContractTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial immutable command/realm-policy source, reviewed-base and terminal-seal capability with focused unit/static proof; Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Controlled selected-full qualification uses World digest schema 4 and a v4 bundle; exact retained v2/World-3 history remains readable. The owner components remain standalone and unregistered, with controlled authority inputs; public fresh/PENDING publication remains denied. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. |
| `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. |
| `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. |
| `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. |
diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java
index c71c68bf03..715300a695 100644
--- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java
+++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java
@@ -30,6 +30,7 @@
import org.jooq.DSLContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
+import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
@@ -406,7 +407,7 @@ private PublishParticipantDigestDto observeSelectedGameLogicParticipant(
Optional receipt;
try {
receipt = selectedGameLogicReceiptRepository.readForPublication(binding);
- } catch (org.jooq.exception.DataAccessException unavailable) {
+ } catch (org.jooq.exception.DataAccessException | DataAccessException unavailable) {
return failedObservation(
PublishParticipantKey.GAME_LOGIC,
binding.versionId(),
diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
index 15501975fb..d8689ca770 100644
--- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
+++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java
@@ -2,6 +2,12 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assertions.catchThrowable;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
import com.google.protobuf.util.JsonFormat;
import io.grpc.Server;
@@ -377,6 +383,7 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema
Server entityServer = null;
Server automationServer = null;
Server gameLogicServer = null;
+ Throwable bodyFailure = null;
try {
entityServer =
ownerServer(
@@ -665,10 +672,111 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema
assertThat(replay).isEqualTo(written);
assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow);
}
+ } catch (Exception failure) {
+ bodyFailure = failure;
+ throw failure;
+ } catch (Error failure) {
+ bodyFailure = failure;
+ throw failure;
} finally {
- stop(entityServer);
- stop(automationServer);
- stop(gameLogicServer);
+ stopServers(bodyFailure, entityServer, automationServer, gameLogicServer);
+ }
+ }
+
+ @Test
+ void ownerServerCleanupAttemptsEveryServerAndSuppressesFailuresOnBodyFailure()
+ throws InterruptedException {
+ Server entityServer = mock(Server.class);
+ Server automationServer = mock(Server.class);
+ Server gameLogicServer = mock(Server.class);
+ RuntimeException bodyFailure = new IllegalStateException("publication body failed");
+ RuntimeException shutdownFailure = new IllegalStateException("entity shutdown failed");
+ RuntimeException waitFailure = new IllegalStateException("automation wait failed");
+ doThrow(shutdownFailure).when(entityServer).shutdownNow();
+ when(entityServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true);
+ when(automationServer.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(waitFailure);
+ when(gameLogicServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(false);
+
+ Throwable thrown =
+ catchThrowable(
+ () -> {
+ Throwable primaryFailure = null;
+ try {
+ throw bodyFailure;
+ } catch (RuntimeException failure) {
+ primaryFailure = failure;
+ throw failure;
+ } finally {
+ stopServers(primaryFailure, entityServer, automationServer, gameLogicServer);
+ }
+ });
+
+ assertThat(thrown).isSameAs(bodyFailure);
+ assertThat(bodyFailure.getSuppressed()).hasSize(3);
+ assertThat(bodyFailure.getSuppressed()[0].getCause()).isSameAs(shutdownFailure);
+ assertThat(bodyFailure.getSuppressed()[1].getCause()).isSameAs(waitFailure);
+ assertThat(bodyFailure.getSuppressed()[2].getMessage())
+ .contains("game logic owner server did not terminate");
+ var order = inOrder(entityServer, automationServer, gameLogicServer);
+ order.verify(entityServer).shutdownNow();
+ order.verify(automationServer).shutdownNow();
+ order.verify(gameLogicServer).shutdownNow();
+ order.verify(entityServer).awaitTermination(5, TimeUnit.SECONDS);
+ order.verify(automationServer).awaitTermination(5, TimeUnit.SECONDS);
+ order.verify(gameLogicServer).awaitTermination(5, TimeUnit.SECONDS);
+ }
+
+ @Test
+ void ownerServerCleanupFailureFailsWhenPublicationBodySucceeded() throws InterruptedException {
+ Server entityServer = mock(Server.class);
+ Server automationServer = mock(Server.class);
+ Server gameLogicServer = mock(Server.class);
+ RuntimeException waitFailure = new IllegalStateException("entity wait failed");
+ when(entityServer.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(waitFailure);
+ when(automationServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true);
+ when(gameLogicServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true);
+
+ assertThatThrownBy(() -> stopServers(null, entityServer, automationServer, gameLogicServer))
+ .isInstanceOf(AssertionError.class)
+ .satisfies(
+ failure -> {
+ assertThat(failure.getSuppressed()).hasSize(1);
+ assertThat(failure.getSuppressed()[0].getCause()).isSameAs(waitFailure);
+ });
+
+ verify(entityServer).shutdownNow();
+ verify(automationServer).shutdownNow();
+ verify(gameLogicServer).shutdownNow();
+ verify(entityServer).awaitTermination(5, TimeUnit.SECONDS);
+ verify(automationServer).awaitTermination(5, TimeUnit.SECONDS);
+ verify(gameLogicServer).awaitTermination(5, TimeUnit.SECONDS);
+ }
+
+ @Test
+ void ownerServerCleanupRestoresInterruptAfterAttemptingAllTerminationWaits()
+ throws InterruptedException {
+ Server entityServer = mock(Server.class);
+ Server automationServer = mock(Server.class);
+ Server gameLogicServer = mock(Server.class);
+ InterruptedException interruption = new InterruptedException("entity wait interrupted");
+ when(entityServer.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(interruption);
+ when(automationServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true);
+ when(gameLogicServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true);
+
+ try {
+ assertThatThrownBy(() -> stopServers(null, entityServer, automationServer, gameLogicServer))
+ .isInstanceOf(AssertionError.class)
+ .satisfies(
+ failure -> {
+ assertThat(failure.getSuppressed()).hasSize(1);
+ assertThat(failure.getSuppressed()[0].getCause()).isSameAs(interruption);
+ });
+ assertThat(Thread.currentThread().isInterrupted()).isTrue();
+ verify(entityServer).awaitTermination(5, TimeUnit.SECONDS);
+ verify(automationServer).awaitTermination(5, TimeUnit.SECONDS);
+ verify(gameLogicServer).awaitTermination(5, TimeUnit.SECONDS);
+ } finally {
+ Thread.interrupted();
}
}
@@ -1135,10 +1243,56 @@ private static Server ownerServer(ProofPki pki, String service, io.grpc.Bindable
.start();
}
- private static void stop(Server server) throws InterruptedException {
- if (server == null) return;
- server.shutdownNow();
- assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue();
+ private static void stopServers(
+ Throwable bodyFailure, Server entityServer, Server automationServer, Server gameLogicServer) {
+ Server[] servers = {entityServer, automationServer, gameLogicServer};
+ String[] serverNames = {"entity", "automation", "game logic"};
+ List